start_command: close cmd->err descriptor when fork/spawn fails
[git/mingw/4msysgit.git] / diff.c
blob7effdac86171c7dff3fb01ebb8f6665db2f0ce5a
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "quote.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "delta.h"
9 #include "xdiff-interface.h"
10 #include "color.h"
11 #include "attr.h"
12 #include "run-command.h"
13 #include "utf8.h"
14 #include "userdiff.h"
15 #include "sigchain.h"
16 #include "submodule.h"
17 #include "ll-merge.h"
19 #ifdef NO_FAST_WORKING_DIRECTORY
20 #define FAST_WORKING_DIRECTORY 0
21 #else
22 #define FAST_WORKING_DIRECTORY 1
23 #endif
25 static int diff_detect_rename_default;
26 static int diff_rename_limit_default = 200;
27 static int diff_suppress_blank_empty;
28 int diff_use_color_default = -1;
29 static const char *diff_word_regex_cfg;
30 static const char *external_diff_cmd_cfg;
31 int diff_auto_refresh_index = 1;
32 static int diff_mnemonic_prefix;
34 static char diff_colors[][COLOR_MAXLEN] = {
35 GIT_COLOR_RESET,
36 GIT_COLOR_NORMAL, /* PLAIN */
37 GIT_COLOR_BOLD, /* METAINFO */
38 GIT_COLOR_CYAN, /* FRAGINFO */
39 GIT_COLOR_RED, /* OLD */
40 GIT_COLOR_GREEN, /* NEW */
41 GIT_COLOR_YELLOW, /* COMMIT */
42 GIT_COLOR_BG_RED, /* WHITESPACE */
43 GIT_COLOR_NORMAL, /* FUNCINFO */
46 static void diff_filespec_load_driver(struct diff_filespec *one);
47 static size_t fill_textconv(struct userdiff_driver *driver,
48 struct diff_filespec *df, char **outbuf);
50 static int parse_diff_color_slot(const char *var, int ofs)
52 if (!strcasecmp(var+ofs, "plain"))
53 return DIFF_PLAIN;
54 if (!strcasecmp(var+ofs, "meta"))
55 return DIFF_METAINFO;
56 if (!strcasecmp(var+ofs, "frag"))
57 return DIFF_FRAGINFO;
58 if (!strcasecmp(var+ofs, "old"))
59 return DIFF_FILE_OLD;
60 if (!strcasecmp(var+ofs, "new"))
61 return DIFF_FILE_NEW;
62 if (!strcasecmp(var+ofs, "commit"))
63 return DIFF_COMMIT;
64 if (!strcasecmp(var+ofs, "whitespace"))
65 return DIFF_WHITESPACE;
66 if (!strcasecmp(var+ofs, "func"))
67 return DIFF_FUNCINFO;
68 return -1;
71 static int git_config_rename(const char *var, const char *value)
73 if (!value)
74 return DIFF_DETECT_RENAME;
75 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
76 return DIFF_DETECT_COPY;
77 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
81 * These are to give UI layer defaults.
82 * The core-level commands such as git-diff-files should
83 * never be affected by the setting of diff.renames
84 * the user happens to have in the configuration file.
86 int git_diff_ui_config(const char *var, const char *value, void *cb)
88 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
89 diff_use_color_default = git_config_colorbool(var, value, -1);
90 return 0;
92 if (!strcmp(var, "diff.renames")) {
93 diff_detect_rename_default = git_config_rename(var, value);
94 return 0;
96 if (!strcmp(var, "diff.autorefreshindex")) {
97 diff_auto_refresh_index = git_config_bool(var, value);
98 return 0;
100 if (!strcmp(var, "diff.mnemonicprefix")) {
101 diff_mnemonic_prefix = git_config_bool(var, value);
102 return 0;
104 if (!strcmp(var, "diff.external"))
105 return git_config_string(&external_diff_cmd_cfg, var, value);
106 if (!strcmp(var, "diff.wordregex"))
107 return git_config_string(&diff_word_regex_cfg, var, value);
109 return git_diff_basic_config(var, value, cb);
112 int git_diff_basic_config(const char *var, const char *value, void *cb)
114 if (!strcmp(var, "diff.renamelimit")) {
115 diff_rename_limit_default = git_config_int(var, value);
116 return 0;
119 switch (userdiff_config(var, value)) {
120 case 0: break;
121 case -1: return -1;
122 default: return 0;
125 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
126 int slot = parse_diff_color_slot(var, 11);
127 if (slot < 0)
128 return 0;
129 if (!value)
130 return config_error_nonbool(var);
131 color_parse(value, var, diff_colors[slot]);
132 return 0;
135 /* like GNU diff's --suppress-blank-empty option */
136 if (!strcmp(var, "diff.suppressblankempty") ||
137 /* for backwards compatibility */
138 !strcmp(var, "diff.suppress-blank-empty")) {
139 diff_suppress_blank_empty = git_config_bool(var, value);
140 return 0;
143 return git_color_default_config(var, value, cb);
146 static char *quote_two(const char *one, const char *two)
148 int need_one = quote_c_style(one, NULL, NULL, 1);
149 int need_two = quote_c_style(two, NULL, NULL, 1);
150 struct strbuf res = STRBUF_INIT;
152 if (need_one + need_two) {
153 strbuf_addch(&res, '"');
154 quote_c_style(one, &res, NULL, 1);
155 quote_c_style(two, &res, NULL, 1);
156 strbuf_addch(&res, '"');
157 } else {
158 strbuf_addstr(&res, one);
159 strbuf_addstr(&res, two);
161 return strbuf_detach(&res, NULL);
164 static const char *external_diff(void)
166 static const char *external_diff_cmd = NULL;
167 static int done_preparing = 0;
169 if (done_preparing)
170 return external_diff_cmd;
171 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
172 if (!external_diff_cmd)
173 external_diff_cmd = external_diff_cmd_cfg;
174 done_preparing = 1;
175 return external_diff_cmd;
178 static struct diff_tempfile {
179 const char *name; /* filename external diff should read from */
180 char hex[41];
181 char mode[10];
182 char tmp_path[PATH_MAX];
183 } diff_temp[2];
185 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
187 struct emit_callback {
188 int color_diff;
189 unsigned ws_rule;
190 int blank_at_eof_in_preimage;
191 int blank_at_eof_in_postimage;
192 int lno_in_preimage;
193 int lno_in_postimage;
194 sane_truncate_fn truncate;
195 const char **label_path;
196 struct diff_words_data *diff_words;
197 int *found_changesp;
198 FILE *file;
199 struct strbuf *header;
202 static int count_lines(const char *data, int size)
204 int count, ch, completely_empty = 1, nl_just_seen = 0;
205 count = 0;
206 while (0 < size--) {
207 ch = *data++;
208 if (ch == '\n') {
209 count++;
210 nl_just_seen = 1;
211 completely_empty = 0;
213 else {
214 nl_just_seen = 0;
215 completely_empty = 0;
218 if (completely_empty)
219 return 0;
220 if (!nl_just_seen)
221 count++; /* no trailing newline */
222 return count;
225 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
227 if (!DIFF_FILE_VALID(one)) {
228 mf->ptr = (char *)""; /* does not matter */
229 mf->size = 0;
230 return 0;
232 else if (diff_populate_filespec(one, 0))
233 return -1;
235 mf->ptr = one->data;
236 mf->size = one->size;
237 return 0;
240 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
242 char *ptr = mf->ptr;
243 long size = mf->size;
244 int cnt = 0;
246 if (!size)
247 return cnt;
248 ptr += size - 1; /* pointing at the very end */
249 if (*ptr != '\n')
250 ; /* incomplete line */
251 else
252 ptr--; /* skip the last LF */
253 while (mf->ptr < ptr) {
254 char *prev_eol;
255 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
256 if (*prev_eol == '\n')
257 break;
258 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
259 break;
260 cnt++;
261 ptr = prev_eol - 1;
263 return cnt;
266 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
267 struct emit_callback *ecbdata)
269 int l1, l2, at;
270 unsigned ws_rule = ecbdata->ws_rule;
271 l1 = count_trailing_blank(mf1, ws_rule);
272 l2 = count_trailing_blank(mf2, ws_rule);
273 if (l2 <= l1) {
274 ecbdata->blank_at_eof_in_preimage = 0;
275 ecbdata->blank_at_eof_in_postimage = 0;
276 return;
278 at = count_lines(mf1->ptr, mf1->size);
279 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
281 at = count_lines(mf2->ptr, mf2->size);
282 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
285 static void emit_line_0(FILE *file, const char *set, const char *reset,
286 int first, const char *line, int len)
288 int has_trailing_newline, has_trailing_carriage_return;
289 int nofirst;
291 if (len == 0) {
292 has_trailing_newline = (first == '\n');
293 has_trailing_carriage_return = (!has_trailing_newline &&
294 (first == '\r'));
295 nofirst = has_trailing_newline || has_trailing_carriage_return;
296 } else {
297 has_trailing_newline = (len > 0 && line[len-1] == '\n');
298 if (has_trailing_newline)
299 len--;
300 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
301 if (has_trailing_carriage_return)
302 len--;
303 nofirst = 0;
306 if (len || !nofirst) {
307 fputs(set, file);
308 if (!nofirst)
309 fputc(first, file);
310 fwrite(line, len, 1, file);
311 fputs(reset, file);
313 if (has_trailing_carriage_return)
314 fputc('\r', file);
315 if (has_trailing_newline)
316 fputc('\n', file);
319 static void emit_line(FILE *file, const char *set, const char *reset,
320 const char *line, int len)
322 emit_line_0(file, set, reset, line[0], line+1, len-1);
325 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
327 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
328 ecbdata->blank_at_eof_in_preimage &&
329 ecbdata->blank_at_eof_in_postimage &&
330 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
331 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
332 return 0;
333 return ws_blank_line(line, len, ecbdata->ws_rule);
336 static void emit_add_line(const char *reset,
337 struct emit_callback *ecbdata,
338 const char *line, int len)
340 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
341 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
343 if (!*ws)
344 emit_line_0(ecbdata->file, set, reset, '+', line, len);
345 else if (new_blank_line_at_eof(ecbdata, line, len))
346 /* Blank line at EOF - paint '+' as well */
347 emit_line_0(ecbdata->file, ws, reset, '+', line, len);
348 else {
349 /* Emit just the prefix, then the rest. */
350 emit_line_0(ecbdata->file, set, reset, '+', "", 0);
351 ws_check_emit(line, len, ecbdata->ws_rule,
352 ecbdata->file, set, reset, ws);
356 static void emit_hunk_header(struct emit_callback *ecbdata,
357 const char *line, int len)
359 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
360 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
361 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
362 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
363 static const char atat[2] = { '@', '@' };
364 const char *cp, *ep;
367 * As a hunk header must begin with "@@ -<old>, +<new> @@",
368 * it always is at least 10 bytes long.
370 if (len < 10 ||
371 memcmp(line, atat, 2) ||
372 !(ep = memmem(line + 2, len - 2, atat, 2))) {
373 emit_line(ecbdata->file, plain, reset, line, len);
374 return;
376 ep += 2; /* skip over @@ */
378 /* The hunk header in fraginfo color */
379 emit_line(ecbdata->file, frag, reset, line, ep - line);
381 /* blank before the func header */
382 for (cp = ep; ep - line < len; ep++)
383 if (*ep != ' ' && *ep != '\t')
384 break;
385 if (ep != cp)
386 emit_line(ecbdata->file, plain, reset, cp, ep - cp);
388 if (ep < line + len)
389 emit_line(ecbdata->file, func, reset, ep, line + len - ep);
392 static struct diff_tempfile *claim_diff_tempfile(void) {
393 int i;
394 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
395 if (!diff_temp[i].name)
396 return diff_temp + i;
397 die("BUG: diff is failing to clean up its tempfiles");
400 static int remove_tempfile_installed;
402 static void remove_tempfile(void)
404 int i;
405 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
406 if (diff_temp[i].name == diff_temp[i].tmp_path)
407 unlink_or_warn(diff_temp[i].name);
408 diff_temp[i].name = NULL;
412 static void remove_tempfile_on_signal(int signo)
414 remove_tempfile();
415 sigchain_pop(signo);
416 raise(signo);
419 static void print_line_count(FILE *file, int count)
421 switch (count) {
422 case 0:
423 fprintf(file, "0,0");
424 break;
425 case 1:
426 fprintf(file, "1");
427 break;
428 default:
429 fprintf(file, "1,%d", count);
430 break;
434 static void emit_rewrite_lines(struct emit_callback *ecb,
435 int prefix, const char *data, int size)
437 const char *endp = NULL;
438 static const char *nneof = " No newline at end of file\n";
439 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
440 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
442 while (0 < size) {
443 int len;
445 endp = memchr(data, '\n', size);
446 len = endp ? (endp - data + 1) : size;
447 if (prefix != '+') {
448 ecb->lno_in_preimage++;
449 emit_line_0(ecb->file, old, reset, '-',
450 data, len);
451 } else {
452 ecb->lno_in_postimage++;
453 emit_add_line(reset, ecb, data, len);
455 size -= len;
456 data += len;
458 if (!endp) {
459 const char *plain = diff_get_color(ecb->color_diff,
460 DIFF_PLAIN);
461 emit_line_0(ecb->file, plain, reset, '\\',
462 nneof, strlen(nneof));
466 static void emit_rewrite_diff(const char *name_a,
467 const char *name_b,
468 struct diff_filespec *one,
469 struct diff_filespec *two,
470 struct userdiff_driver *textconv_one,
471 struct userdiff_driver *textconv_two,
472 struct diff_options *o)
474 int lc_a, lc_b;
475 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
476 const char *name_a_tab, *name_b_tab;
477 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
478 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
479 const char *reset = diff_get_color(color_diff, DIFF_RESET);
480 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
481 const char *a_prefix, *b_prefix;
482 char *data_one, *data_two;
483 size_t size_one, size_two;
484 struct emit_callback ecbdata;
486 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
487 a_prefix = o->b_prefix;
488 b_prefix = o->a_prefix;
489 } else {
490 a_prefix = o->a_prefix;
491 b_prefix = o->b_prefix;
494 name_a += (*name_a == '/');
495 name_b += (*name_b == '/');
496 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
497 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
499 strbuf_reset(&a_name);
500 strbuf_reset(&b_name);
501 quote_two_c_style(&a_name, a_prefix, name_a, 0);
502 quote_two_c_style(&b_name, b_prefix, name_b, 0);
504 size_one = fill_textconv(textconv_one, one, &data_one);
505 size_two = fill_textconv(textconv_two, two, &data_two);
507 memset(&ecbdata, 0, sizeof(ecbdata));
508 ecbdata.color_diff = color_diff;
509 ecbdata.found_changesp = &o->found_changes;
510 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
511 ecbdata.file = o->file;
512 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
513 mmfile_t mf1, mf2;
514 mf1.ptr = (char *)data_one;
515 mf2.ptr = (char *)data_two;
516 mf1.size = size_one;
517 mf2.size = size_two;
518 check_blank_at_eof(&mf1, &mf2, &ecbdata);
520 ecbdata.lno_in_preimage = 1;
521 ecbdata.lno_in_postimage = 1;
523 lc_a = count_lines(data_one, size_one);
524 lc_b = count_lines(data_two, size_two);
525 fprintf(o->file,
526 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
527 metainfo, a_name.buf, name_a_tab, reset,
528 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
529 print_line_count(o->file, lc_a);
530 fprintf(o->file, " +");
531 print_line_count(o->file, lc_b);
532 fprintf(o->file, " @@%s\n", reset);
533 if (lc_a)
534 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
535 if (lc_b)
536 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
537 if (textconv_one)
538 free((char *)data_one);
539 if (textconv_two)
540 free((char *)data_two);
543 struct diff_words_buffer {
544 mmfile_t text;
545 long alloc;
546 struct diff_words_orig {
547 const char *begin, *end;
548 } *orig;
549 int orig_nr, orig_alloc;
552 static void diff_words_append(char *line, unsigned long len,
553 struct diff_words_buffer *buffer)
555 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
556 line++;
557 len--;
558 memcpy(buffer->text.ptr + buffer->text.size, line, len);
559 buffer->text.size += len;
560 buffer->text.ptr[buffer->text.size] = '\0';
563 struct diff_words_data {
564 struct diff_words_buffer minus, plus;
565 const char *current_plus;
566 FILE *file;
567 regex_t *word_regex;
570 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
572 struct diff_words_data *diff_words = priv;
573 int minus_first, minus_len, plus_first, plus_len;
574 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
576 if (line[0] != '@' || parse_hunk_header(line, len,
577 &minus_first, &minus_len, &plus_first, &plus_len))
578 return;
580 /* POSIX requires that first be decremented by one if len == 0... */
581 if (minus_len) {
582 minus_begin = diff_words->minus.orig[minus_first].begin;
583 minus_end =
584 diff_words->minus.orig[minus_first + minus_len - 1].end;
585 } else
586 minus_begin = minus_end =
587 diff_words->minus.orig[minus_first].end;
589 if (plus_len) {
590 plus_begin = diff_words->plus.orig[plus_first].begin;
591 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
592 } else
593 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
595 if (diff_words->current_plus != plus_begin)
596 fwrite(diff_words->current_plus,
597 plus_begin - diff_words->current_plus, 1,
598 diff_words->file);
599 if (minus_begin != minus_end)
600 color_fwrite_lines(diff_words->file,
601 diff_get_color(1, DIFF_FILE_OLD),
602 minus_end - minus_begin, minus_begin);
603 if (plus_begin != plus_end)
604 color_fwrite_lines(diff_words->file,
605 diff_get_color(1, DIFF_FILE_NEW),
606 plus_end - plus_begin, plus_begin);
608 diff_words->current_plus = plus_end;
611 /* This function starts looking at *begin, and returns 0 iff a word was found. */
612 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
613 int *begin, int *end)
615 if (word_regex && *begin < buffer->size) {
616 regmatch_t match[1];
617 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
618 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
619 '\n', match[0].rm_eo - match[0].rm_so);
620 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
621 *begin += match[0].rm_so;
622 return *begin >= *end;
624 return -1;
627 /* find the next word */
628 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
629 (*begin)++;
630 if (*begin >= buffer->size)
631 return -1;
633 /* find the end of the word */
634 *end = *begin + 1;
635 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
636 (*end)++;
638 return 0;
642 * This function splits the words in buffer->text, stores the list with
643 * newline separator into out, and saves the offsets of the original words
644 * in buffer->orig.
646 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
647 regex_t *word_regex)
649 int i, j;
650 long alloc = 0;
652 out->size = 0;
653 out->ptr = NULL;
655 /* fake an empty "0th" word */
656 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
657 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
658 buffer->orig_nr = 1;
660 for (i = 0; i < buffer->text.size; i++) {
661 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
662 return;
664 /* store original boundaries */
665 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
666 buffer->orig_alloc);
667 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
668 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
669 buffer->orig_nr++;
671 /* store one word */
672 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
673 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
674 out->ptr[out->size + j - i] = '\n';
675 out->size += j - i + 1;
677 i = j - 1;
681 /* this executes the word diff on the accumulated buffers */
682 static void diff_words_show(struct diff_words_data *diff_words)
684 xpparam_t xpp;
685 xdemitconf_t xecfg;
686 xdemitcb_t ecb;
687 mmfile_t minus, plus;
689 /* special case: only removal */
690 if (!diff_words->plus.text.size) {
691 color_fwrite_lines(diff_words->file,
692 diff_get_color(1, DIFF_FILE_OLD),
693 diff_words->minus.text.size, diff_words->minus.text.ptr);
694 diff_words->minus.text.size = 0;
695 return;
698 diff_words->current_plus = diff_words->plus.text.ptr;
700 memset(&xpp, 0, sizeof(xpp));
701 memset(&xecfg, 0, sizeof(xecfg));
702 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
703 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
704 xpp.flags = XDF_NEED_MINIMAL;
705 /* as only the hunk header will be parsed, we need a 0-context */
706 xecfg.ctxlen = 0;
707 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
708 &xpp, &xecfg, &ecb);
709 free(minus.ptr);
710 free(plus.ptr);
711 if (diff_words->current_plus != diff_words->plus.text.ptr +
712 diff_words->plus.text.size)
713 fwrite(diff_words->current_plus,
714 diff_words->plus.text.ptr + diff_words->plus.text.size
715 - diff_words->current_plus, 1,
716 diff_words->file);
717 diff_words->minus.text.size = diff_words->plus.text.size = 0;
720 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
721 static void diff_words_flush(struct emit_callback *ecbdata)
723 if (ecbdata->diff_words->minus.text.size ||
724 ecbdata->diff_words->plus.text.size)
725 diff_words_show(ecbdata->diff_words);
728 static void free_diff_words_data(struct emit_callback *ecbdata)
730 if (ecbdata->diff_words) {
731 diff_words_flush(ecbdata);
732 free (ecbdata->diff_words->minus.text.ptr);
733 free (ecbdata->diff_words->minus.orig);
734 free (ecbdata->diff_words->plus.text.ptr);
735 free (ecbdata->diff_words->plus.orig);
736 free(ecbdata->diff_words->word_regex);
737 free(ecbdata->diff_words);
738 ecbdata->diff_words = NULL;
742 const char *diff_get_color(int diff_use_color, enum color_diff ix)
744 if (diff_use_color)
745 return diff_colors[ix];
746 return "";
749 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
751 const char *cp;
752 unsigned long allot;
753 size_t l = len;
755 if (ecb->truncate)
756 return ecb->truncate(line, len);
757 cp = line;
758 allot = l;
759 while (0 < l) {
760 (void) utf8_width(&cp, &l);
761 if (!cp)
762 break; /* truncated in the middle? */
764 return allot - l;
767 static void find_lno(const char *line, struct emit_callback *ecbdata)
769 const char *p;
770 ecbdata->lno_in_preimage = 0;
771 ecbdata->lno_in_postimage = 0;
772 p = strchr(line, '-');
773 if (!p)
774 return; /* cannot happen */
775 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
776 p = strchr(p, '+');
777 if (!p)
778 return; /* cannot happen */
779 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
782 static void fn_out_consume(void *priv, char *line, unsigned long len)
784 struct emit_callback *ecbdata = priv;
785 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
786 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
787 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
789 if (ecbdata->header) {
790 fprintf(ecbdata->file, "%s", ecbdata->header->buf);
791 strbuf_reset(ecbdata->header);
792 ecbdata->header = NULL;
794 *(ecbdata->found_changesp) = 1;
796 if (ecbdata->label_path[0]) {
797 const char *name_a_tab, *name_b_tab;
799 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
800 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
802 fprintf(ecbdata->file, "%s--- %s%s%s\n",
803 meta, ecbdata->label_path[0], reset, name_a_tab);
804 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
805 meta, ecbdata->label_path[1], reset, name_b_tab);
806 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
809 if (diff_suppress_blank_empty
810 && len == 2 && line[0] == ' ' && line[1] == '\n') {
811 line[0] = '\n';
812 len = 1;
815 if (line[0] == '@') {
816 if (ecbdata->diff_words)
817 diff_words_flush(ecbdata);
818 len = sane_truncate_line(ecbdata, line, len);
819 find_lno(line, ecbdata);
820 emit_hunk_header(ecbdata, line, len);
821 if (line[len-1] != '\n')
822 putc('\n', ecbdata->file);
823 return;
826 if (len < 1) {
827 emit_line(ecbdata->file, reset, reset, line, len);
828 return;
831 if (ecbdata->diff_words) {
832 if (line[0] == '-') {
833 diff_words_append(line, len,
834 &ecbdata->diff_words->minus);
835 return;
836 } else if (line[0] == '+') {
837 diff_words_append(line, len,
838 &ecbdata->diff_words->plus);
839 return;
841 diff_words_flush(ecbdata);
842 line++;
843 len--;
844 emit_line(ecbdata->file, plain, reset, line, len);
845 return;
848 if (line[0] != '+') {
849 const char *color =
850 diff_get_color(ecbdata->color_diff,
851 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
852 ecbdata->lno_in_preimage++;
853 if (line[0] == ' ')
854 ecbdata->lno_in_postimage++;
855 emit_line(ecbdata->file, color, reset, line, len);
856 } else {
857 ecbdata->lno_in_postimage++;
858 emit_add_line(reset, ecbdata, line + 1, len - 1);
862 static char *pprint_rename(const char *a, const char *b)
864 const char *old = a;
865 const char *new = b;
866 struct strbuf name = STRBUF_INIT;
867 int pfx_length, sfx_length;
868 int len_a = strlen(a);
869 int len_b = strlen(b);
870 int a_midlen, b_midlen;
871 int qlen_a = quote_c_style(a, NULL, NULL, 0);
872 int qlen_b = quote_c_style(b, NULL, NULL, 0);
874 if (qlen_a || qlen_b) {
875 quote_c_style(a, &name, NULL, 0);
876 strbuf_addstr(&name, " => ");
877 quote_c_style(b, &name, NULL, 0);
878 return strbuf_detach(&name, NULL);
881 /* Find common prefix */
882 pfx_length = 0;
883 while (*old && *new && *old == *new) {
884 if (*old == '/')
885 pfx_length = old - a + 1;
886 old++;
887 new++;
890 /* Find common suffix */
891 old = a + len_a;
892 new = b + len_b;
893 sfx_length = 0;
894 while (a <= old && b <= new && *old == *new) {
895 if (*old == '/')
896 sfx_length = len_a - (old - a);
897 old--;
898 new--;
902 * pfx{mid-a => mid-b}sfx
903 * {pfx-a => pfx-b}sfx
904 * pfx{sfx-a => sfx-b}
905 * name-a => name-b
907 a_midlen = len_a - pfx_length - sfx_length;
908 b_midlen = len_b - pfx_length - sfx_length;
909 if (a_midlen < 0)
910 a_midlen = 0;
911 if (b_midlen < 0)
912 b_midlen = 0;
914 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
915 if (pfx_length + sfx_length) {
916 strbuf_add(&name, a, pfx_length);
917 strbuf_addch(&name, '{');
919 strbuf_add(&name, a + pfx_length, a_midlen);
920 strbuf_addstr(&name, " => ");
921 strbuf_add(&name, b + pfx_length, b_midlen);
922 if (pfx_length + sfx_length) {
923 strbuf_addch(&name, '}');
924 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
926 return strbuf_detach(&name, NULL);
929 struct diffstat_t {
930 int nr;
931 int alloc;
932 struct diffstat_file {
933 char *from_name;
934 char *name;
935 char *print_name;
936 unsigned is_unmerged:1;
937 unsigned is_binary:1;
938 unsigned is_renamed:1;
939 unsigned int added, deleted;
940 } **files;
943 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
944 const char *name_a,
945 const char *name_b)
947 struct diffstat_file *x;
948 x = xcalloc(sizeof (*x), 1);
949 if (diffstat->nr == diffstat->alloc) {
950 diffstat->alloc = alloc_nr(diffstat->alloc);
951 diffstat->files = xrealloc(diffstat->files,
952 diffstat->alloc * sizeof(x));
954 diffstat->files[diffstat->nr++] = x;
955 if (name_b) {
956 x->from_name = xstrdup(name_a);
957 x->name = xstrdup(name_b);
958 x->is_renamed = 1;
960 else {
961 x->from_name = NULL;
962 x->name = xstrdup(name_a);
964 return x;
967 static void diffstat_consume(void *priv, char *line, unsigned long len)
969 struct diffstat_t *diffstat = priv;
970 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
972 if (line[0] == '+')
973 x->added++;
974 else if (line[0] == '-')
975 x->deleted++;
978 const char mime_boundary_leader[] = "------------";
980 static int scale_linear(int it, int width, int max_change)
983 * make sure that at least one '-' is printed if there were deletions,
984 * and likewise for '+'.
986 if (max_change < 2)
987 return it;
988 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
991 static void show_name(FILE *file,
992 const char *prefix, const char *name, int len)
994 fprintf(file, " %s%-*s |", prefix, len, name);
997 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
999 if (cnt <= 0)
1000 return;
1001 fprintf(file, "%s", set);
1002 while (cnt--)
1003 putc(ch, file);
1004 fprintf(file, "%s", reset);
1007 static void fill_print_name(struct diffstat_file *file)
1009 char *pname;
1011 if (file->print_name)
1012 return;
1014 if (!file->is_renamed) {
1015 struct strbuf buf = STRBUF_INIT;
1016 if (quote_c_style(file->name, &buf, NULL, 0)) {
1017 pname = strbuf_detach(&buf, NULL);
1018 } else {
1019 pname = file->name;
1020 strbuf_release(&buf);
1022 } else {
1023 pname = pprint_rename(file->from_name, file->name);
1025 file->print_name = pname;
1028 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1030 int i, len, add, del, adds = 0, dels = 0;
1031 int max_change = 0, max_len = 0;
1032 int total_files = data->nr;
1033 int width, name_width;
1034 const char *reset, *set, *add_c, *del_c;
1036 if (data->nr == 0)
1037 return;
1039 width = options->stat_width ? options->stat_width : 80;
1040 name_width = options->stat_name_width ? options->stat_name_width : 50;
1042 /* Sanity: give at least 5 columns to the graph,
1043 * but leave at least 10 columns for the name.
1045 if (width < 25)
1046 width = 25;
1047 if (name_width < 10)
1048 name_width = 10;
1049 else if (width < name_width + 15)
1050 name_width = width - 15;
1052 /* Find the longest filename and max number of changes */
1053 reset = diff_get_color_opt(options, DIFF_RESET);
1054 set = diff_get_color_opt(options, DIFF_PLAIN);
1055 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1056 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1058 for (i = 0; i < data->nr; i++) {
1059 struct diffstat_file *file = data->files[i];
1060 int change = file->added + file->deleted;
1061 fill_print_name(file);
1062 len = strlen(file->print_name);
1063 if (max_len < len)
1064 max_len = len;
1066 if (file->is_binary || file->is_unmerged)
1067 continue;
1068 if (max_change < change)
1069 max_change = change;
1072 /* Compute the width of the graph part;
1073 * 10 is for one blank at the beginning of the line plus
1074 * " | count " between the name and the graph.
1076 * From here on, name_width is the width of the name area,
1077 * and width is the width of the graph area.
1079 name_width = (name_width < max_len) ? name_width : max_len;
1080 if (width < (name_width + 10) + max_change)
1081 width = width - (name_width + 10);
1082 else
1083 width = max_change;
1085 for (i = 0; i < data->nr; i++) {
1086 const char *prefix = "";
1087 char *name = data->files[i]->print_name;
1088 int added = data->files[i]->added;
1089 int deleted = data->files[i]->deleted;
1090 int name_len;
1093 * "scale" the filename
1095 len = name_width;
1096 name_len = strlen(name);
1097 if (name_width < name_len) {
1098 char *slash;
1099 prefix = "...";
1100 len -= 3;
1101 name += name_len - len;
1102 slash = strchr(name, '/');
1103 if (slash)
1104 name = slash;
1107 if (data->files[i]->is_binary) {
1108 show_name(options->file, prefix, name, len);
1109 fprintf(options->file, " Bin ");
1110 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
1111 fprintf(options->file, " -> ");
1112 fprintf(options->file, "%s%d%s", add_c, added, reset);
1113 fprintf(options->file, " bytes");
1114 fprintf(options->file, "\n");
1115 continue;
1117 else if (data->files[i]->is_unmerged) {
1118 show_name(options->file, prefix, name, len);
1119 fprintf(options->file, " Unmerged\n");
1120 continue;
1122 else if (!data->files[i]->is_renamed &&
1123 (added + deleted == 0)) {
1124 total_files--;
1125 continue;
1129 * scale the add/delete
1131 add = added;
1132 del = deleted;
1133 adds += add;
1134 dels += del;
1136 if (width <= max_change) {
1137 add = scale_linear(add, width, max_change);
1138 del = scale_linear(del, width, max_change);
1140 show_name(options->file, prefix, name, len);
1141 fprintf(options->file, "%5d%s", added + deleted,
1142 added + deleted ? " " : "");
1143 show_graph(options->file, '+', add, add_c, reset);
1144 show_graph(options->file, '-', del, del_c, reset);
1145 fprintf(options->file, "\n");
1147 fprintf(options->file,
1148 " %d files changed, %d insertions(+), %d deletions(-)\n",
1149 total_files, adds, dels);
1152 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1154 int i, adds = 0, dels = 0, total_files = data->nr;
1156 if (data->nr == 0)
1157 return;
1159 for (i = 0; i < data->nr; i++) {
1160 if (!data->files[i]->is_binary &&
1161 !data->files[i]->is_unmerged) {
1162 int added = data->files[i]->added;
1163 int deleted= data->files[i]->deleted;
1164 if (!data->files[i]->is_renamed &&
1165 (added + deleted == 0)) {
1166 total_files--;
1167 } else {
1168 adds += added;
1169 dels += deleted;
1173 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1174 total_files, adds, dels);
1177 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1179 int i;
1181 if (data->nr == 0)
1182 return;
1184 for (i = 0; i < data->nr; i++) {
1185 struct diffstat_file *file = data->files[i];
1187 if (file->is_binary)
1188 fprintf(options->file, "-\t-\t");
1189 else
1190 fprintf(options->file,
1191 "%d\t%d\t", file->added, file->deleted);
1192 if (options->line_termination) {
1193 fill_print_name(file);
1194 if (!file->is_renamed)
1195 write_name_quoted(file->name, options->file,
1196 options->line_termination);
1197 else {
1198 fputs(file->print_name, options->file);
1199 putc(options->line_termination, options->file);
1201 } else {
1202 if (file->is_renamed) {
1203 putc('\0', options->file);
1204 write_name_quoted(file->from_name, options->file, '\0');
1206 write_name_quoted(file->name, options->file, '\0');
1211 struct dirstat_file {
1212 const char *name;
1213 unsigned long changed;
1216 struct dirstat_dir {
1217 struct dirstat_file *files;
1218 int alloc, nr, percent, cumulative;
1221 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1223 unsigned long this_dir = 0;
1224 unsigned int sources = 0;
1226 while (dir->nr) {
1227 struct dirstat_file *f = dir->files;
1228 int namelen = strlen(f->name);
1229 unsigned long this;
1230 char *slash;
1232 if (namelen < baselen)
1233 break;
1234 if (memcmp(f->name, base, baselen))
1235 break;
1236 slash = strchr(f->name + baselen, '/');
1237 if (slash) {
1238 int newbaselen = slash + 1 - f->name;
1239 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1240 sources++;
1241 } else {
1242 this = f->changed;
1243 dir->files++;
1244 dir->nr--;
1245 sources += 2;
1247 this_dir += this;
1251 * We don't report dirstat's for
1252 * - the top level
1253 * - or cases where everything came from a single directory
1254 * under this directory (sources == 1).
1256 if (baselen && sources != 1) {
1257 int permille = this_dir * 1000 / changed;
1258 if (permille) {
1259 int percent = permille / 10;
1260 if (percent >= dir->percent) {
1261 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1262 if (!dir->cumulative)
1263 return 0;
1267 return this_dir;
1270 static int dirstat_compare(const void *_a, const void *_b)
1272 const struct dirstat_file *a = _a;
1273 const struct dirstat_file *b = _b;
1274 return strcmp(a->name, b->name);
1277 static void show_dirstat(struct diff_options *options)
1279 int i;
1280 unsigned long changed;
1281 struct dirstat_dir dir;
1282 struct diff_queue_struct *q = &diff_queued_diff;
1284 dir.files = NULL;
1285 dir.alloc = 0;
1286 dir.nr = 0;
1287 dir.percent = options->dirstat_percent;
1288 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1290 changed = 0;
1291 for (i = 0; i < q->nr; i++) {
1292 struct diff_filepair *p = q->queue[i];
1293 const char *name;
1294 unsigned long copied, added, damage;
1296 name = p->one->path ? p->one->path : p->two->path;
1298 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1299 diff_populate_filespec(p->one, 0);
1300 diff_populate_filespec(p->two, 0);
1301 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1302 &copied, &added);
1303 diff_free_filespec_data(p->one);
1304 diff_free_filespec_data(p->two);
1305 } else if (DIFF_FILE_VALID(p->one)) {
1306 diff_populate_filespec(p->one, 1);
1307 copied = added = 0;
1308 diff_free_filespec_data(p->one);
1309 } else if (DIFF_FILE_VALID(p->two)) {
1310 diff_populate_filespec(p->two, 1);
1311 copied = 0;
1312 added = p->two->size;
1313 diff_free_filespec_data(p->two);
1314 } else
1315 continue;
1318 * Original minus copied is the removed material,
1319 * added is the new material. They are both damages
1320 * made to the preimage. In --dirstat-by-file mode, count
1321 * damaged files, not damaged lines. This is done by
1322 * counting only a single damaged line per file.
1324 damage = (p->one->size - copied) + added;
1325 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1326 damage = 1;
1328 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1329 dir.files[dir.nr].name = name;
1330 dir.files[dir.nr].changed = damage;
1331 changed += damage;
1332 dir.nr++;
1335 /* This can happen even with many files, if everything was renames */
1336 if (!changed)
1337 return;
1339 /* Show all directories with more than x% of the changes */
1340 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1341 gather_dirstat(options->file, &dir, changed, "", 0);
1344 static void free_diffstat_info(struct diffstat_t *diffstat)
1346 int i;
1347 for (i = 0; i < diffstat->nr; i++) {
1348 struct diffstat_file *f = diffstat->files[i];
1349 if (f->name != f->print_name)
1350 free(f->print_name);
1351 free(f->name);
1352 free(f->from_name);
1353 free(f);
1355 free(diffstat->files);
1358 struct checkdiff_t {
1359 const char *filename;
1360 int lineno;
1361 int conflict_marker_size;
1362 struct diff_options *o;
1363 unsigned ws_rule;
1364 unsigned status;
1367 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
1369 char firstchar;
1370 int cnt;
1372 if (len < marker_size + 1)
1373 return 0;
1374 firstchar = line[0];
1375 switch (firstchar) {
1376 case '=': case '>': case '<': case '|':
1377 break;
1378 default:
1379 return 0;
1381 for (cnt = 1; cnt < marker_size; cnt++)
1382 if (line[cnt] != firstchar)
1383 return 0;
1384 /* line[1] thru line[marker_size-1] are same as firstchar */
1385 if (len < marker_size + 1 || !isspace(line[marker_size]))
1386 return 0;
1387 return 1;
1390 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1392 struct checkdiff_t *data = priv;
1393 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1394 int marker_size = data->conflict_marker_size;
1395 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1396 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1397 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1398 char *err;
1400 if (line[0] == '+') {
1401 unsigned bad;
1402 data->lineno++;
1403 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
1404 data->status |= 1;
1405 fprintf(data->o->file,
1406 "%s:%d: leftover conflict marker\n",
1407 data->filename, data->lineno);
1409 bad = ws_check(line + 1, len - 1, data->ws_rule);
1410 if (!bad)
1411 return;
1412 data->status |= bad;
1413 err = whitespace_error_string(bad);
1414 fprintf(data->o->file, "%s:%d: %s.\n",
1415 data->filename, data->lineno, err);
1416 free(err);
1417 emit_line(data->o->file, set, reset, line, 1);
1418 ws_check_emit(line + 1, len - 1, data->ws_rule,
1419 data->o->file, set, reset, ws);
1420 } else if (line[0] == ' ') {
1421 data->lineno++;
1422 } else if (line[0] == '@') {
1423 char *plus = strchr(line, '+');
1424 if (plus)
1425 data->lineno = strtol(plus, NULL, 10) - 1;
1426 else
1427 die("invalid diff");
1431 static unsigned char *deflate_it(char *data,
1432 unsigned long size,
1433 unsigned long *result_size)
1435 int bound;
1436 unsigned char *deflated;
1437 z_stream stream;
1439 memset(&stream, 0, sizeof(stream));
1440 deflateInit(&stream, zlib_compression_level);
1441 bound = deflateBound(&stream, size);
1442 deflated = xmalloc(bound);
1443 stream.next_out = deflated;
1444 stream.avail_out = bound;
1446 stream.next_in = (unsigned char *)data;
1447 stream.avail_in = size;
1448 while (deflate(&stream, Z_FINISH) == Z_OK)
1449 ; /* nothing */
1450 deflateEnd(&stream);
1451 *result_size = stream.total_out;
1452 return deflated;
1455 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1457 void *cp;
1458 void *delta;
1459 void *deflated;
1460 void *data;
1461 unsigned long orig_size;
1462 unsigned long delta_size;
1463 unsigned long deflate_size;
1464 unsigned long data_size;
1466 /* We could do deflated delta, or we could do just deflated two,
1467 * whichever is smaller.
1469 delta = NULL;
1470 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1471 if (one->size && two->size) {
1472 delta = diff_delta(one->ptr, one->size,
1473 two->ptr, two->size,
1474 &delta_size, deflate_size);
1475 if (delta) {
1476 void *to_free = delta;
1477 orig_size = delta_size;
1478 delta = deflate_it(delta, delta_size, &delta_size);
1479 free(to_free);
1483 if (delta && delta_size < deflate_size) {
1484 fprintf(file, "delta %lu\n", orig_size);
1485 free(deflated);
1486 data = delta;
1487 data_size = delta_size;
1489 else {
1490 fprintf(file, "literal %lu\n", two->size);
1491 free(delta);
1492 data = deflated;
1493 data_size = deflate_size;
1496 /* emit data encoded in base85 */
1497 cp = data;
1498 while (data_size) {
1499 int bytes = (52 < data_size) ? 52 : data_size;
1500 char line[70];
1501 data_size -= bytes;
1502 if (bytes <= 26)
1503 line[0] = bytes + 'A' - 1;
1504 else
1505 line[0] = bytes - 26 + 'a' - 1;
1506 encode_85(line + 1, cp, bytes);
1507 cp = (char *) cp + bytes;
1508 fputs(line, file);
1509 fputc('\n', file);
1511 fprintf(file, "\n");
1512 free(data);
1515 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1517 fprintf(file, "GIT binary patch\n");
1518 emit_binary_diff_body(file, one, two);
1519 emit_binary_diff_body(file, two, one);
1522 static void diff_filespec_load_driver(struct diff_filespec *one)
1524 if (!one->driver)
1525 one->driver = userdiff_find_by_path(one->path);
1526 if (!one->driver)
1527 one->driver = userdiff_find_by_name("default");
1530 int diff_filespec_is_binary(struct diff_filespec *one)
1532 if (one->is_binary == -1) {
1533 diff_filespec_load_driver(one);
1534 if (one->driver->binary != -1)
1535 one->is_binary = one->driver->binary;
1536 else {
1537 if (!one->data && DIFF_FILE_VALID(one))
1538 diff_populate_filespec(one, 0);
1539 if (one->data)
1540 one->is_binary = buffer_is_binary(one->data,
1541 one->size);
1542 if (one->is_binary == -1)
1543 one->is_binary = 0;
1546 return one->is_binary;
1549 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1551 diff_filespec_load_driver(one);
1552 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1555 static const char *userdiff_word_regex(struct diff_filespec *one)
1557 diff_filespec_load_driver(one);
1558 return one->driver->word_regex;
1561 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1563 if (!options->a_prefix)
1564 options->a_prefix = a;
1565 if (!options->b_prefix)
1566 options->b_prefix = b;
1569 static struct userdiff_driver *get_textconv(struct diff_filespec *one)
1571 if (!DIFF_FILE_VALID(one))
1572 return NULL;
1573 if (!S_ISREG(one->mode))
1574 return NULL;
1575 diff_filespec_load_driver(one);
1576 if (!one->driver->textconv)
1577 return NULL;
1579 if (one->driver->textconv_want_cache && !one->driver->textconv_cache) {
1580 struct notes_cache *c = xmalloc(sizeof(*c));
1581 struct strbuf name = STRBUF_INIT;
1583 strbuf_addf(&name, "textconv/%s", one->driver->name);
1584 notes_cache_init(c, name.buf, one->driver->textconv);
1585 one->driver->textconv_cache = c;
1588 return one->driver;
1591 static void builtin_diff(const char *name_a,
1592 const char *name_b,
1593 struct diff_filespec *one,
1594 struct diff_filespec *two,
1595 const char *xfrm_msg,
1596 struct diff_options *o,
1597 int complete_rewrite)
1599 mmfile_t mf1, mf2;
1600 const char *lbl[2];
1601 char *a_one, *b_two;
1602 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1603 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1604 const char *a_prefix, *b_prefix;
1605 struct userdiff_driver *textconv_one = NULL;
1606 struct userdiff_driver *textconv_two = NULL;
1607 struct strbuf header = STRBUF_INIT;
1609 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
1610 (!one->mode || S_ISGITLINK(one->mode)) &&
1611 (!two->mode || S_ISGITLINK(two->mode))) {
1612 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1613 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1614 show_submodule_summary(o->file, one ? one->path : two->path,
1615 one->sha1, two->sha1, two->dirty_submodule,
1616 del, add, reset);
1617 return;
1620 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1621 textconv_one = get_textconv(one);
1622 textconv_two = get_textconv(two);
1625 diff_set_mnemonic_prefix(o, "a/", "b/");
1626 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1627 a_prefix = o->b_prefix;
1628 b_prefix = o->a_prefix;
1629 } else {
1630 a_prefix = o->a_prefix;
1631 b_prefix = o->b_prefix;
1634 /* Never use a non-valid filename anywhere if at all possible */
1635 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1636 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1638 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1639 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1640 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1641 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1642 strbuf_addf(&header, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1643 if (lbl[0][0] == '/') {
1644 /* /dev/null */
1645 strbuf_addf(&header, "%snew file mode %06o%s\n", set, two->mode, reset);
1646 if (xfrm_msg && xfrm_msg[0])
1647 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1649 else if (lbl[1][0] == '/') {
1650 strbuf_addf(&header, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1651 if (xfrm_msg && xfrm_msg[0])
1652 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1654 else {
1655 if (one->mode != two->mode) {
1656 strbuf_addf(&header, "%sold mode %06o%s\n", set, one->mode, reset);
1657 strbuf_addf(&header, "%snew mode %06o%s\n", set, two->mode, reset);
1659 if (xfrm_msg && xfrm_msg[0])
1660 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1663 * we do not run diff between different kind
1664 * of objects.
1666 if ((one->mode ^ two->mode) & S_IFMT)
1667 goto free_ab_and_return;
1668 if (complete_rewrite &&
1669 (textconv_one || !diff_filespec_is_binary(one)) &&
1670 (textconv_two || !diff_filespec_is_binary(two))) {
1671 fprintf(o->file, "%s", header.buf);
1672 strbuf_reset(&header);
1673 emit_rewrite_diff(name_a, name_b, one, two,
1674 textconv_one, textconv_two, o);
1675 o->found_changes = 1;
1676 goto free_ab_and_return;
1680 if (!DIFF_OPT_TST(o, TEXT) &&
1681 ( (!textconv_one && diff_filespec_is_binary(one)) ||
1682 (!textconv_two && diff_filespec_is_binary(two)) )) {
1683 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1684 die("unable to read files to diff");
1685 /* Quite common confusing case */
1686 if (mf1.size == mf2.size &&
1687 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1688 goto free_ab_and_return;
1689 fprintf(o->file, "%s", header.buf);
1690 strbuf_reset(&header);
1691 if (DIFF_OPT_TST(o, BINARY))
1692 emit_binary_diff(o->file, &mf1, &mf2);
1693 else
1694 fprintf(o->file, "Binary files %s and %s differ\n",
1695 lbl[0], lbl[1]);
1696 o->found_changes = 1;
1698 else {
1699 /* Crazy xdl interfaces.. */
1700 const char *diffopts = getenv("GIT_DIFF_OPTS");
1701 xpparam_t xpp;
1702 xdemitconf_t xecfg;
1703 xdemitcb_t ecb;
1704 struct emit_callback ecbdata;
1705 const struct userdiff_funcname *pe;
1707 if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS)) {
1708 fprintf(o->file, "%s", header.buf);
1709 strbuf_reset(&header);
1712 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
1713 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
1715 pe = diff_funcname_pattern(one);
1716 if (!pe)
1717 pe = diff_funcname_pattern(two);
1719 memset(&xpp, 0, sizeof(xpp));
1720 memset(&xecfg, 0, sizeof(xecfg));
1721 memset(&ecbdata, 0, sizeof(ecbdata));
1722 ecbdata.label_path = lbl;
1723 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1724 ecbdata.found_changesp = &o->found_changes;
1725 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1726 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1727 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1728 ecbdata.file = o->file;
1729 ecbdata.header = header.len ? &header : NULL;
1730 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1731 xecfg.ctxlen = o->context;
1732 xecfg.interhunkctxlen = o->interhunkcontext;
1733 xecfg.flags = XDL_EMIT_FUNCNAMES;
1734 if (pe)
1735 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1736 if (!diffopts)
1738 else if (!prefixcmp(diffopts, "--unified="))
1739 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1740 else if (!prefixcmp(diffopts, "-u"))
1741 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1742 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1743 ecbdata.diff_words =
1744 xcalloc(1, sizeof(struct diff_words_data));
1745 ecbdata.diff_words->file = o->file;
1746 if (!o->word_regex)
1747 o->word_regex = userdiff_word_regex(one);
1748 if (!o->word_regex)
1749 o->word_regex = userdiff_word_regex(two);
1750 if (!o->word_regex)
1751 o->word_regex = diff_word_regex_cfg;
1752 if (o->word_regex) {
1753 ecbdata.diff_words->word_regex = (regex_t *)
1754 xmalloc(sizeof(regex_t));
1755 if (regcomp(ecbdata.diff_words->word_regex,
1756 o->word_regex,
1757 REG_EXTENDED | REG_NEWLINE))
1758 die ("Invalid regular expression: %s",
1759 o->word_regex);
1762 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1763 &xpp, &xecfg, &ecb);
1764 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1765 free_diff_words_data(&ecbdata);
1766 if (textconv_one)
1767 free(mf1.ptr);
1768 if (textconv_two)
1769 free(mf2.ptr);
1770 xdiff_clear_find_func(&xecfg);
1773 free_ab_and_return:
1774 strbuf_release(&header);
1775 diff_free_filespec_data(one);
1776 diff_free_filespec_data(two);
1777 free(a_one);
1778 free(b_two);
1779 return;
1782 static void builtin_diffstat(const char *name_a, const char *name_b,
1783 struct diff_filespec *one,
1784 struct diff_filespec *two,
1785 struct diffstat_t *diffstat,
1786 struct diff_options *o,
1787 int complete_rewrite)
1789 mmfile_t mf1, mf2;
1790 struct diffstat_file *data;
1792 data = diffstat_add(diffstat, name_a, name_b);
1794 if (!one || !two) {
1795 data->is_unmerged = 1;
1796 return;
1798 if (complete_rewrite) {
1799 diff_populate_filespec(one, 0);
1800 diff_populate_filespec(two, 0);
1801 data->deleted = count_lines(one->data, one->size);
1802 data->added = count_lines(two->data, two->size);
1803 goto free_and_return;
1805 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1806 die("unable to read files to diff");
1808 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1809 data->is_binary = 1;
1810 data->added = mf2.size;
1811 data->deleted = mf1.size;
1812 } else {
1813 /* Crazy xdl interfaces.. */
1814 xpparam_t xpp;
1815 xdemitconf_t xecfg;
1816 xdemitcb_t ecb;
1818 memset(&xpp, 0, sizeof(xpp));
1819 memset(&xecfg, 0, sizeof(xecfg));
1820 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1821 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1822 &xpp, &xecfg, &ecb);
1825 free_and_return:
1826 diff_free_filespec_data(one);
1827 diff_free_filespec_data(two);
1830 static void builtin_checkdiff(const char *name_a, const char *name_b,
1831 const char *attr_path,
1832 struct diff_filespec *one,
1833 struct diff_filespec *two,
1834 struct diff_options *o)
1836 mmfile_t mf1, mf2;
1837 struct checkdiff_t data;
1839 if (!two)
1840 return;
1842 memset(&data, 0, sizeof(data));
1843 data.filename = name_b ? name_b : name_a;
1844 data.lineno = 0;
1845 data.o = o;
1846 data.ws_rule = whitespace_rule(attr_path);
1847 data.conflict_marker_size = ll_merge_marker_size(attr_path);
1849 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1850 die("unable to read files to diff");
1853 * All the other codepaths check both sides, but not checking
1854 * the "old" side here is deliberate. We are checking the newly
1855 * introduced changes, and as long as the "new" side is text, we
1856 * can and should check what it introduces.
1858 if (diff_filespec_is_binary(two))
1859 goto free_and_return;
1860 else {
1861 /* Crazy xdl interfaces.. */
1862 xpparam_t xpp;
1863 xdemitconf_t xecfg;
1864 xdemitcb_t ecb;
1866 memset(&xpp, 0, sizeof(xpp));
1867 memset(&xecfg, 0, sizeof(xecfg));
1868 xecfg.ctxlen = 1; /* at least one context line */
1869 xpp.flags = XDF_NEED_MINIMAL;
1870 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1871 &xpp, &xecfg, &ecb);
1873 if (data.ws_rule & WS_BLANK_AT_EOF) {
1874 struct emit_callback ecbdata;
1875 int blank_at_eof;
1877 ecbdata.ws_rule = data.ws_rule;
1878 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1879 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
1881 if (blank_at_eof) {
1882 static char *err;
1883 if (!err)
1884 err = whitespace_error_string(WS_BLANK_AT_EOF);
1885 fprintf(o->file, "%s:%d: %s.\n",
1886 data.filename, blank_at_eof, err);
1887 data.status = 1; /* report errors */
1891 free_and_return:
1892 diff_free_filespec_data(one);
1893 diff_free_filespec_data(two);
1894 if (data.status)
1895 DIFF_OPT_SET(o, CHECK_FAILED);
1898 struct diff_filespec *alloc_filespec(const char *path)
1900 int namelen = strlen(path);
1901 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1903 memset(spec, 0, sizeof(*spec));
1904 spec->path = (char *)(spec + 1);
1905 memcpy(spec->path, path, namelen+1);
1906 spec->count = 1;
1907 spec->is_binary = -1;
1908 return spec;
1911 void free_filespec(struct diff_filespec *spec)
1913 if (!--spec->count) {
1914 diff_free_filespec_data(spec);
1915 free(spec);
1919 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1920 unsigned short mode)
1922 if (mode) {
1923 spec->mode = canon_mode(mode);
1924 hashcpy(spec->sha1, sha1);
1925 spec->sha1_valid = !is_null_sha1(sha1);
1930 * Given a name and sha1 pair, if the index tells us the file in
1931 * the work tree has that object contents, return true, so that
1932 * prepare_temp_file() does not have to inflate and extract.
1934 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1936 struct cache_entry *ce;
1937 struct stat st;
1938 int pos, len;
1941 * We do not read the cache ourselves here, because the
1942 * benchmark with my previous version that always reads cache
1943 * shows that it makes things worse for diff-tree comparing
1944 * two linux-2.6 kernel trees in an already checked out work
1945 * tree. This is because most diff-tree comparisons deal with
1946 * only a small number of files, while reading the cache is
1947 * expensive for a large project, and its cost outweighs the
1948 * savings we get by not inflating the object to a temporary
1949 * file. Practically, this code only helps when we are used
1950 * by diff-cache --cached, which does read the cache before
1951 * calling us.
1953 if (!active_cache)
1954 return 0;
1956 /* We want to avoid the working directory if our caller
1957 * doesn't need the data in a normal file, this system
1958 * is rather slow with its stat/open/mmap/close syscalls,
1959 * and the object is contained in a pack file. The pack
1960 * is probably already open and will be faster to obtain
1961 * the data through than the working directory. Loose
1962 * objects however would tend to be slower as they need
1963 * to be individually opened and inflated.
1965 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1966 return 0;
1968 len = strlen(name);
1969 pos = cache_name_pos(name, len);
1970 if (pos < 0)
1971 return 0;
1972 ce = active_cache[pos];
1975 * This is not the sha1 we are looking for, or
1976 * unreusable because it is not a regular file.
1978 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1979 return 0;
1982 * If ce is marked as "assume unchanged", there is no
1983 * guarantee that work tree matches what we are looking for.
1985 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
1986 return 0;
1989 * If ce matches the file in the work tree, we can reuse it.
1991 if (ce_uptodate(ce) ||
1992 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1993 return 1;
1995 return 0;
1998 static int populate_from_stdin(struct diff_filespec *s)
2000 struct strbuf buf = STRBUF_INIT;
2001 size_t size = 0;
2003 if (strbuf_read(&buf, 0, 0) < 0)
2004 return error("error while reading from stdin %s",
2005 strerror(errno));
2007 s->should_munmap = 0;
2008 s->data = strbuf_detach(&buf, &size);
2009 s->size = size;
2010 s->should_free = 1;
2011 return 0;
2014 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2016 int len;
2017 char *data = xmalloc(100), *dirty = "";
2019 /* Are we looking at the work tree? */
2020 if (s->dirty_submodule)
2021 dirty = "-dirty";
2023 len = snprintf(data, 100,
2024 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2025 s->data = data;
2026 s->size = len;
2027 s->should_free = 1;
2028 if (size_only) {
2029 s->data = NULL;
2030 free(data);
2032 return 0;
2036 * While doing rename detection and pickaxe operation, we may need to
2037 * grab the data for the blob (or file) for our own in-core comparison.
2038 * diff_filespec has data and size fields for this purpose.
2040 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2042 int err = 0;
2043 if (!DIFF_FILE_VALID(s))
2044 die("internal error: asking to populate invalid file.");
2045 if (S_ISDIR(s->mode))
2046 return -1;
2048 if (s->data)
2049 return 0;
2051 if (size_only && 0 < s->size)
2052 return 0;
2054 if (S_ISGITLINK(s->mode))
2055 return diff_populate_gitlink(s, size_only);
2057 if (!s->sha1_valid ||
2058 reuse_worktree_file(s->path, s->sha1, 0)) {
2059 struct strbuf buf = STRBUF_INIT;
2060 struct stat st;
2061 int fd;
2063 if (!strcmp(s->path, "-"))
2064 return populate_from_stdin(s);
2066 if (lstat(s->path, &st) < 0) {
2067 if (errno == ENOENT) {
2068 err_empty:
2069 err = -1;
2070 empty:
2071 s->data = (char *)"";
2072 s->size = 0;
2073 return err;
2076 s->size = xsize_t(st.st_size);
2077 if (!s->size)
2078 goto empty;
2079 if (S_ISLNK(st.st_mode)) {
2080 struct strbuf sb = STRBUF_INIT;
2082 if (strbuf_readlink(&sb, s->path, s->size))
2083 goto err_empty;
2084 s->size = sb.len;
2085 s->data = strbuf_detach(&sb, NULL);
2086 s->should_free = 1;
2087 return 0;
2089 if (size_only)
2090 return 0;
2091 fd = open(s->path, O_RDONLY);
2092 if (fd < 0)
2093 goto err_empty;
2094 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2095 close(fd);
2096 s->should_munmap = 1;
2099 * Convert from working tree format to canonical git format
2101 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2102 size_t size = 0;
2103 munmap(s->data, s->size);
2104 s->should_munmap = 0;
2105 s->data = strbuf_detach(&buf, &size);
2106 s->size = size;
2107 s->should_free = 1;
2110 else {
2111 enum object_type type;
2112 if (size_only)
2113 type = sha1_object_info(s->sha1, &s->size);
2114 else {
2115 s->data = read_sha1_file(s->sha1, &type, &s->size);
2116 s->should_free = 1;
2119 return 0;
2122 void diff_free_filespec_blob(struct diff_filespec *s)
2124 if (s->should_free)
2125 free(s->data);
2126 else if (s->should_munmap)
2127 munmap(s->data, s->size);
2129 if (s->should_free || s->should_munmap) {
2130 s->should_free = s->should_munmap = 0;
2131 s->data = NULL;
2135 void diff_free_filespec_data(struct diff_filespec *s)
2137 diff_free_filespec_blob(s);
2138 free(s->cnt_data);
2139 s->cnt_data = NULL;
2142 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2143 void *blob,
2144 unsigned long size,
2145 const unsigned char *sha1,
2146 int mode)
2148 int fd;
2149 struct strbuf buf = STRBUF_INIT;
2150 struct strbuf template = STRBUF_INIT;
2151 char *path_dup = xstrdup(path);
2152 const char *base = basename(path_dup);
2154 /* Generate "XXXXXX_basename.ext" */
2155 strbuf_addstr(&template, "XXXXXX_");
2156 strbuf_addstr(&template, base);
2158 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2159 strlen(base) + 1);
2160 if (fd < 0)
2161 die_errno("unable to create temp-file");
2162 if (convert_to_working_tree(path,
2163 (const char *)blob, (size_t)size, &buf)) {
2164 blob = buf.buf;
2165 size = buf.len;
2167 if (write_in_full(fd, blob, size) != size)
2168 die_errno("unable to write temp-file");
2169 close(fd);
2170 temp->name = temp->tmp_path;
2171 strcpy(temp->hex, sha1_to_hex(sha1));
2172 temp->hex[40] = 0;
2173 sprintf(temp->mode, "%06o", mode);
2174 strbuf_release(&buf);
2175 strbuf_release(&template);
2176 free(path_dup);
2179 static struct diff_tempfile *prepare_temp_file(const char *name,
2180 struct diff_filespec *one)
2182 struct diff_tempfile *temp = claim_diff_tempfile();
2184 if (!DIFF_FILE_VALID(one)) {
2185 not_a_valid_file:
2186 /* A '-' entry produces this for file-2, and
2187 * a '+' entry produces this for file-1.
2189 temp->name = "/dev/null";
2190 strcpy(temp->hex, ".");
2191 strcpy(temp->mode, ".");
2192 return temp;
2195 if (!remove_tempfile_installed) {
2196 atexit(remove_tempfile);
2197 sigchain_push_common(remove_tempfile_on_signal);
2198 remove_tempfile_installed = 1;
2201 if (!one->sha1_valid ||
2202 reuse_worktree_file(name, one->sha1, 1)) {
2203 struct stat st;
2204 if (lstat(name, &st) < 0) {
2205 if (errno == ENOENT)
2206 goto not_a_valid_file;
2207 die_errno("stat(%s)", name);
2209 if (S_ISLNK(st.st_mode)) {
2210 struct strbuf sb = STRBUF_INIT;
2211 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2212 die_errno("readlink(%s)", name);
2213 prep_temp_blob(name, temp, sb.buf, sb.len,
2214 (one->sha1_valid ?
2215 one->sha1 : null_sha1),
2216 (one->sha1_valid ?
2217 one->mode : S_IFLNK));
2218 strbuf_release(&sb);
2220 else {
2221 /* we can borrow from the file in the work tree */
2222 temp->name = name;
2223 if (!one->sha1_valid)
2224 strcpy(temp->hex, sha1_to_hex(null_sha1));
2225 else
2226 strcpy(temp->hex, sha1_to_hex(one->sha1));
2227 /* Even though we may sometimes borrow the
2228 * contents from the work tree, we always want
2229 * one->mode. mode is trustworthy even when
2230 * !(one->sha1_valid), as long as
2231 * DIFF_FILE_VALID(one).
2233 sprintf(temp->mode, "%06o", one->mode);
2235 return temp;
2237 else {
2238 if (diff_populate_filespec(one, 0))
2239 die("cannot read data blob for %s", one->path);
2240 prep_temp_blob(name, temp, one->data, one->size,
2241 one->sha1, one->mode);
2243 return temp;
2246 /* An external diff command takes:
2248 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2249 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2252 static void run_external_diff(const char *pgm,
2253 const char *name,
2254 const char *other,
2255 struct diff_filespec *one,
2256 struct diff_filespec *two,
2257 const char *xfrm_msg,
2258 int complete_rewrite)
2260 const char *spawn_arg[10];
2261 int retval;
2262 const char **arg = &spawn_arg[0];
2264 if (one && two) {
2265 struct diff_tempfile *temp_one, *temp_two;
2266 const char *othername = (other ? other : name);
2267 temp_one = prepare_temp_file(name, one);
2268 temp_two = prepare_temp_file(othername, two);
2269 *arg++ = pgm;
2270 *arg++ = name;
2271 *arg++ = temp_one->name;
2272 *arg++ = temp_one->hex;
2273 *arg++ = temp_one->mode;
2274 *arg++ = temp_two->name;
2275 *arg++ = temp_two->hex;
2276 *arg++ = temp_two->mode;
2277 if (other) {
2278 *arg++ = other;
2279 *arg++ = xfrm_msg;
2281 } else {
2282 *arg++ = pgm;
2283 *arg++ = name;
2285 *arg = NULL;
2286 fflush(NULL);
2287 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2288 remove_tempfile();
2289 if (retval) {
2290 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2291 exit(1);
2295 static int similarity_index(struct diff_filepair *p)
2297 return p->score * 100 / MAX_SCORE;
2300 static void fill_metainfo(struct strbuf *msg,
2301 const char *name,
2302 const char *other,
2303 struct diff_filespec *one,
2304 struct diff_filespec *two,
2305 struct diff_options *o,
2306 struct diff_filepair *p)
2308 strbuf_init(msg, PATH_MAX * 2 + 300);
2309 switch (p->status) {
2310 case DIFF_STATUS_COPIED:
2311 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2312 strbuf_addstr(msg, "\ncopy from ");
2313 quote_c_style(name, msg, NULL, 0);
2314 strbuf_addstr(msg, "\ncopy to ");
2315 quote_c_style(other, msg, NULL, 0);
2316 strbuf_addch(msg, '\n');
2317 break;
2318 case DIFF_STATUS_RENAMED:
2319 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2320 strbuf_addstr(msg, "\nrename from ");
2321 quote_c_style(name, msg, NULL, 0);
2322 strbuf_addstr(msg, "\nrename to ");
2323 quote_c_style(other, msg, NULL, 0);
2324 strbuf_addch(msg, '\n');
2325 break;
2326 case DIFF_STATUS_MODIFIED:
2327 if (p->score) {
2328 strbuf_addf(msg, "dissimilarity index %d%%\n",
2329 similarity_index(p));
2330 break;
2332 /* fallthru */
2333 default:
2334 /* nothing */
2337 if (one && two && hashcmp(one->sha1, two->sha1)) {
2338 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2340 if (DIFF_OPT_TST(o, BINARY)) {
2341 mmfile_t mf;
2342 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2343 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2344 abbrev = 40;
2346 strbuf_addf(msg, "index %.*s..%.*s",
2347 abbrev, sha1_to_hex(one->sha1),
2348 abbrev, sha1_to_hex(two->sha1));
2349 if (one->mode == two->mode)
2350 strbuf_addf(msg, " %06o", one->mode);
2351 strbuf_addch(msg, '\n');
2353 if (msg->len)
2354 strbuf_setlen(msg, msg->len - 1);
2357 static void run_diff_cmd(const char *pgm,
2358 const char *name,
2359 const char *other,
2360 const char *attr_path,
2361 struct diff_filespec *one,
2362 struct diff_filespec *two,
2363 struct strbuf *msg,
2364 struct diff_options *o,
2365 struct diff_filepair *p)
2367 const char *xfrm_msg = NULL;
2368 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2370 if (msg) {
2371 fill_metainfo(msg, name, other, one, two, o, p);
2372 xfrm_msg = msg->len ? msg->buf : NULL;
2375 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2376 pgm = NULL;
2377 else {
2378 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2379 if (drv && drv->external)
2380 pgm = drv->external;
2383 if (pgm) {
2384 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2385 complete_rewrite);
2386 return;
2388 if (one && two)
2389 builtin_diff(name, other ? other : name,
2390 one, two, xfrm_msg, o, complete_rewrite);
2391 else
2392 fprintf(o->file, "* Unmerged path %s\n", name);
2395 static void diff_fill_sha1_info(struct diff_filespec *one)
2397 if (DIFF_FILE_VALID(one)) {
2398 if (!one->sha1_valid) {
2399 struct stat st;
2400 if (!strcmp(one->path, "-")) {
2401 hashcpy(one->sha1, null_sha1);
2402 return;
2404 if (lstat(one->path, &st) < 0)
2405 die_errno("stat '%s'", one->path);
2406 if (index_path(one->sha1, one->path, &st, 0))
2407 die("cannot hash %s", one->path);
2410 else
2411 hashclr(one->sha1);
2414 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2416 /* Strip the prefix but do not molest /dev/null and absolute paths */
2417 if (*namep && **namep != '/')
2418 *namep += prefix_length;
2419 if (*otherp && **otherp != '/')
2420 *otherp += prefix_length;
2423 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2425 const char *pgm = external_diff();
2426 struct strbuf msg;
2427 struct diff_filespec *one = p->one;
2428 struct diff_filespec *two = p->two;
2429 const char *name;
2430 const char *other;
2431 const char *attr_path;
2433 name = p->one->path;
2434 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2435 attr_path = name;
2436 if (o->prefix_length)
2437 strip_prefix(o->prefix_length, &name, &other);
2439 if (DIFF_PAIR_UNMERGED(p)) {
2440 run_diff_cmd(pgm, name, NULL, attr_path,
2441 NULL, NULL, NULL, o, p);
2442 return;
2445 diff_fill_sha1_info(one);
2446 diff_fill_sha1_info(two);
2448 if (!pgm &&
2449 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2450 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2452 * a filepair that changes between file and symlink
2453 * needs to be split into deletion and creation.
2455 struct diff_filespec *null = alloc_filespec(two->path);
2456 run_diff_cmd(NULL, name, other, attr_path,
2457 one, null, &msg, o, p);
2458 free(null);
2459 strbuf_release(&msg);
2461 null = alloc_filespec(one->path);
2462 run_diff_cmd(NULL, name, other, attr_path,
2463 null, two, &msg, o, p);
2464 free(null);
2466 else
2467 run_diff_cmd(pgm, name, other, attr_path,
2468 one, two, &msg, o, p);
2470 strbuf_release(&msg);
2473 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2474 struct diffstat_t *diffstat)
2476 const char *name;
2477 const char *other;
2478 int complete_rewrite = 0;
2480 if (DIFF_PAIR_UNMERGED(p)) {
2481 /* unmerged */
2482 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2483 return;
2486 name = p->one->path;
2487 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2489 if (o->prefix_length)
2490 strip_prefix(o->prefix_length, &name, &other);
2492 diff_fill_sha1_info(p->one);
2493 diff_fill_sha1_info(p->two);
2495 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2496 complete_rewrite = 1;
2497 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2500 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2502 const char *name;
2503 const char *other;
2504 const char *attr_path;
2506 if (DIFF_PAIR_UNMERGED(p)) {
2507 /* unmerged */
2508 return;
2511 name = p->one->path;
2512 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2513 attr_path = other ? other : name;
2515 if (o->prefix_length)
2516 strip_prefix(o->prefix_length, &name, &other);
2518 diff_fill_sha1_info(p->one);
2519 diff_fill_sha1_info(p->two);
2521 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2524 void diff_setup(struct diff_options *options)
2526 memset(options, 0, sizeof(*options));
2528 options->file = stdout;
2530 options->line_termination = '\n';
2531 options->break_opt = -1;
2532 options->rename_limit = -1;
2533 options->dirstat_percent = 3;
2534 options->context = 3;
2536 options->change = diff_change;
2537 options->add_remove = diff_addremove;
2538 if (diff_use_color_default > 0)
2539 DIFF_OPT_SET(options, COLOR_DIFF);
2540 options->detect_rename = diff_detect_rename_default;
2542 if (!diff_mnemonic_prefix) {
2543 options->a_prefix = "a/";
2544 options->b_prefix = "b/";
2548 int diff_setup_done(struct diff_options *options)
2550 int count = 0;
2552 if (options->output_format & DIFF_FORMAT_NAME)
2553 count++;
2554 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2555 count++;
2556 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2557 count++;
2558 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2559 count++;
2560 if (count > 1)
2561 die("--name-only, --name-status, --check and -s are mutually exclusive");
2564 * Most of the time we can say "there are changes"
2565 * only by checking if there are changed paths, but
2566 * --ignore-whitespace* options force us to look
2567 * inside contents.
2570 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2571 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2572 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2573 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2574 else
2575 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2577 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2578 options->detect_rename = DIFF_DETECT_COPY;
2580 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2581 options->prefix = NULL;
2582 if (options->prefix)
2583 options->prefix_length = strlen(options->prefix);
2584 else
2585 options->prefix_length = 0;
2587 if (options->output_format & (DIFF_FORMAT_NAME |
2588 DIFF_FORMAT_NAME_STATUS |
2589 DIFF_FORMAT_CHECKDIFF |
2590 DIFF_FORMAT_NO_OUTPUT))
2591 options->output_format &= ~(DIFF_FORMAT_RAW |
2592 DIFF_FORMAT_NUMSTAT |
2593 DIFF_FORMAT_DIFFSTAT |
2594 DIFF_FORMAT_SHORTSTAT |
2595 DIFF_FORMAT_DIRSTAT |
2596 DIFF_FORMAT_SUMMARY |
2597 DIFF_FORMAT_PATCH);
2600 * These cases always need recursive; we do not drop caller-supplied
2601 * recursive bits for other formats here.
2603 if (options->output_format & (DIFF_FORMAT_PATCH |
2604 DIFF_FORMAT_NUMSTAT |
2605 DIFF_FORMAT_DIFFSTAT |
2606 DIFF_FORMAT_SHORTSTAT |
2607 DIFF_FORMAT_DIRSTAT |
2608 DIFF_FORMAT_SUMMARY |
2609 DIFF_FORMAT_CHECKDIFF))
2610 DIFF_OPT_SET(options, RECURSIVE);
2612 * Also pickaxe would not work very well if you do not say recursive
2614 if (options->pickaxe)
2615 DIFF_OPT_SET(options, RECURSIVE);
2617 * When patches are generated, submodules diffed against the work tree
2618 * must be checked for dirtiness too so it can be shown in the output
2620 if (options->output_format & DIFF_FORMAT_PATCH)
2621 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
2623 if (options->detect_rename && options->rename_limit < 0)
2624 options->rename_limit = diff_rename_limit_default;
2625 if (options->setup & DIFF_SETUP_USE_CACHE) {
2626 if (!active_cache)
2627 /* read-cache does not die even when it fails
2628 * so it is safe for us to do this here. Also
2629 * it does not smudge active_cache or active_nr
2630 * when it fails, so we do not have to worry about
2631 * cleaning it up ourselves either.
2633 read_cache();
2635 if (options->abbrev <= 0 || 40 < options->abbrev)
2636 options->abbrev = 40; /* full */
2639 * It does not make sense to show the first hit we happened
2640 * to have found. It does not make sense not to return with
2641 * exit code in such a case either.
2643 if (DIFF_OPT_TST(options, QUICK)) {
2644 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2645 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2648 return 0;
2651 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2653 char c, *eq;
2654 int len;
2656 if (*arg != '-')
2657 return 0;
2658 c = *++arg;
2659 if (!c)
2660 return 0;
2661 if (c == arg_short) {
2662 c = *++arg;
2663 if (!c)
2664 return 1;
2665 if (val && isdigit(c)) {
2666 char *end;
2667 int n = strtoul(arg, &end, 10);
2668 if (*end)
2669 return 0;
2670 *val = n;
2671 return 1;
2673 return 0;
2675 if (c != '-')
2676 return 0;
2677 arg++;
2678 eq = strchr(arg, '=');
2679 if (eq)
2680 len = eq - arg;
2681 else
2682 len = strlen(arg);
2683 if (!len || strncmp(arg, arg_long, len))
2684 return 0;
2685 if (eq) {
2686 int n;
2687 char *end;
2688 if (!isdigit(*++eq))
2689 return 0;
2690 n = strtoul(eq, &end, 10);
2691 if (*end)
2692 return 0;
2693 *val = n;
2695 return 1;
2698 static int diff_scoreopt_parse(const char *opt);
2700 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2702 const char *arg = av[0];
2704 /* Output format options */
2705 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2706 options->output_format |= DIFF_FORMAT_PATCH;
2707 else if (opt_arg(arg, 'U', "unified", &options->context))
2708 options->output_format |= DIFF_FORMAT_PATCH;
2709 else if (!strcmp(arg, "--raw"))
2710 options->output_format |= DIFF_FORMAT_RAW;
2711 else if (!strcmp(arg, "--patch-with-raw"))
2712 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2713 else if (!strcmp(arg, "--numstat"))
2714 options->output_format |= DIFF_FORMAT_NUMSTAT;
2715 else if (!strcmp(arg, "--shortstat"))
2716 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2717 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2718 options->output_format |= DIFF_FORMAT_DIRSTAT;
2719 else if (!strcmp(arg, "--cumulative")) {
2720 options->output_format |= DIFF_FORMAT_DIRSTAT;
2721 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2722 } else if (opt_arg(arg, 0, "dirstat-by-file",
2723 &options->dirstat_percent)) {
2724 options->output_format |= DIFF_FORMAT_DIRSTAT;
2725 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2727 else if (!strcmp(arg, "--check"))
2728 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2729 else if (!strcmp(arg, "--summary"))
2730 options->output_format |= DIFF_FORMAT_SUMMARY;
2731 else if (!strcmp(arg, "--patch-with-stat"))
2732 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2733 else if (!strcmp(arg, "--name-only"))
2734 options->output_format |= DIFF_FORMAT_NAME;
2735 else if (!strcmp(arg, "--name-status"))
2736 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2737 else if (!strcmp(arg, "-s"))
2738 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2739 else if (!prefixcmp(arg, "--stat")) {
2740 char *end;
2741 int width = options->stat_width;
2742 int name_width = options->stat_name_width;
2743 arg += 6;
2744 end = (char *)arg;
2746 switch (*arg) {
2747 case '-':
2748 if (!prefixcmp(arg, "-width="))
2749 width = strtoul(arg + 7, &end, 10);
2750 else if (!prefixcmp(arg, "-name-width="))
2751 name_width = strtoul(arg + 12, &end, 10);
2752 break;
2753 case '=':
2754 width = strtoul(arg+1, &end, 10);
2755 if (*end == ',')
2756 name_width = strtoul(end+1, &end, 10);
2759 /* Important! This checks all the error cases! */
2760 if (*end)
2761 return 0;
2762 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2763 options->stat_name_width = name_width;
2764 options->stat_width = width;
2767 /* renames options */
2768 else if (!prefixcmp(arg, "-B")) {
2769 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2770 return -1;
2772 else if (!prefixcmp(arg, "-M")) {
2773 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2774 return -1;
2775 options->detect_rename = DIFF_DETECT_RENAME;
2777 else if (!prefixcmp(arg, "-C")) {
2778 if (options->detect_rename == DIFF_DETECT_COPY)
2779 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2780 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2781 return -1;
2782 options->detect_rename = DIFF_DETECT_COPY;
2784 else if (!strcmp(arg, "--no-renames"))
2785 options->detect_rename = 0;
2786 else if (!strcmp(arg, "--relative"))
2787 DIFF_OPT_SET(options, RELATIVE_NAME);
2788 else if (!prefixcmp(arg, "--relative=")) {
2789 DIFF_OPT_SET(options, RELATIVE_NAME);
2790 options->prefix = arg + 11;
2793 /* xdiff options */
2794 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2795 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2796 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2797 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2798 else if (!strcmp(arg, "--ignore-space-at-eol"))
2799 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2800 else if (!strcmp(arg, "--patience"))
2801 DIFF_XDL_SET(options, PATIENCE_DIFF);
2803 /* flags options */
2804 else if (!strcmp(arg, "--binary")) {
2805 options->output_format |= DIFF_FORMAT_PATCH;
2806 DIFF_OPT_SET(options, BINARY);
2808 else if (!strcmp(arg, "--full-index"))
2809 DIFF_OPT_SET(options, FULL_INDEX);
2810 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2811 DIFF_OPT_SET(options, TEXT);
2812 else if (!strcmp(arg, "-R"))
2813 DIFF_OPT_SET(options, REVERSE_DIFF);
2814 else if (!strcmp(arg, "--find-copies-harder"))
2815 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2816 else if (!strcmp(arg, "--follow"))
2817 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2818 else if (!strcmp(arg, "--color"))
2819 DIFF_OPT_SET(options, COLOR_DIFF);
2820 else if (!prefixcmp(arg, "--color=")) {
2821 int value = git_config_colorbool(NULL, arg+8, -1);
2822 if (value == 0)
2823 DIFF_OPT_CLR(options, COLOR_DIFF);
2824 else if (value > 0)
2825 DIFF_OPT_SET(options, COLOR_DIFF);
2826 else
2827 return error("option `color' expects \"always\", \"auto\", or \"never\"");
2829 else if (!strcmp(arg, "--no-color"))
2830 DIFF_OPT_CLR(options, COLOR_DIFF);
2831 else if (!strcmp(arg, "--color-words")) {
2832 DIFF_OPT_SET(options, COLOR_DIFF);
2833 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2835 else if (!prefixcmp(arg, "--color-words=")) {
2836 DIFF_OPT_SET(options, COLOR_DIFF);
2837 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2838 options->word_regex = arg + 14;
2840 else if (!strcmp(arg, "--exit-code"))
2841 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2842 else if (!strcmp(arg, "--quiet"))
2843 DIFF_OPT_SET(options, QUICK);
2844 else if (!strcmp(arg, "--ext-diff"))
2845 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2846 else if (!strcmp(arg, "--no-ext-diff"))
2847 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2848 else if (!strcmp(arg, "--textconv"))
2849 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2850 else if (!strcmp(arg, "--no-textconv"))
2851 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2852 else if (!strcmp(arg, "--ignore-submodules"))
2853 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2854 else if (!strcmp(arg, "--submodule"))
2855 DIFF_OPT_SET(options, SUBMODULE_LOG);
2856 else if (!prefixcmp(arg, "--submodule=")) {
2857 if (!strcmp(arg + 12, "log"))
2858 DIFF_OPT_SET(options, SUBMODULE_LOG);
2861 /* misc options */
2862 else if (!strcmp(arg, "-z"))
2863 options->line_termination = 0;
2864 else if (!prefixcmp(arg, "-l"))
2865 options->rename_limit = strtoul(arg+2, NULL, 10);
2866 else if (!prefixcmp(arg, "-S"))
2867 options->pickaxe = arg + 2;
2868 else if (!strcmp(arg, "--pickaxe-all"))
2869 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2870 else if (!strcmp(arg, "--pickaxe-regex"))
2871 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2872 else if (!prefixcmp(arg, "-O"))
2873 options->orderfile = arg + 2;
2874 else if (!prefixcmp(arg, "--diff-filter="))
2875 options->filter = arg + 14;
2876 else if (!strcmp(arg, "--abbrev"))
2877 options->abbrev = DEFAULT_ABBREV;
2878 else if (!prefixcmp(arg, "--abbrev=")) {
2879 options->abbrev = strtoul(arg + 9, NULL, 10);
2880 if (options->abbrev < MINIMUM_ABBREV)
2881 options->abbrev = MINIMUM_ABBREV;
2882 else if (40 < options->abbrev)
2883 options->abbrev = 40;
2885 else if (!prefixcmp(arg, "--src-prefix="))
2886 options->a_prefix = arg + 13;
2887 else if (!prefixcmp(arg, "--dst-prefix="))
2888 options->b_prefix = arg + 13;
2889 else if (!strcmp(arg, "--no-prefix"))
2890 options->a_prefix = options->b_prefix = "";
2891 else if (opt_arg(arg, '\0', "inter-hunk-context",
2892 &options->interhunkcontext))
2894 else if (!prefixcmp(arg, "--output=")) {
2895 options->file = fopen(arg + strlen("--output="), "w");
2896 if (!options->file)
2897 die_errno("Could not open '%s'", arg + strlen("--output="));
2898 options->close_file = 1;
2899 } else
2900 return 0;
2901 return 1;
2904 static int parse_num(const char **cp_p)
2906 unsigned long num, scale;
2907 int ch, dot;
2908 const char *cp = *cp_p;
2910 num = 0;
2911 scale = 1;
2912 dot = 0;
2913 for (;;) {
2914 ch = *cp;
2915 if ( !dot && ch == '.' ) {
2916 scale = 1;
2917 dot = 1;
2918 } else if ( ch == '%' ) {
2919 scale = dot ? scale*100 : 100;
2920 cp++; /* % is always at the end */
2921 break;
2922 } else if ( ch >= '0' && ch <= '9' ) {
2923 if ( scale < 100000 ) {
2924 scale *= 10;
2925 num = (num*10) + (ch-'0');
2927 } else {
2928 break;
2930 cp++;
2932 *cp_p = cp;
2934 /* user says num divided by scale and we say internally that
2935 * is MAX_SCORE * num / scale.
2937 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2940 static int diff_scoreopt_parse(const char *opt)
2942 int opt1, opt2, cmd;
2944 if (*opt++ != '-')
2945 return -1;
2946 cmd = *opt++;
2947 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2948 return -1; /* that is not a -M, -C nor -B option */
2950 opt1 = parse_num(&opt);
2951 if (cmd != 'B')
2952 opt2 = 0;
2953 else {
2954 if (*opt == 0)
2955 opt2 = 0;
2956 else if (*opt != '/')
2957 return -1; /* we expect -B80/99 or -B80 */
2958 else {
2959 opt++;
2960 opt2 = parse_num(&opt);
2963 if (*opt != 0)
2964 return -1;
2965 return opt1 | (opt2 << 16);
2968 struct diff_queue_struct diff_queued_diff;
2970 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2972 if (queue->alloc <= queue->nr) {
2973 queue->alloc = alloc_nr(queue->alloc);
2974 queue->queue = xrealloc(queue->queue,
2975 sizeof(dp) * queue->alloc);
2977 queue->queue[queue->nr++] = dp;
2980 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2981 struct diff_filespec *one,
2982 struct diff_filespec *two)
2984 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2985 dp->one = one;
2986 dp->two = two;
2987 if (queue)
2988 diff_q(queue, dp);
2989 return dp;
2992 void diff_free_filepair(struct diff_filepair *p)
2994 free_filespec(p->one);
2995 free_filespec(p->two);
2996 free(p);
2999 /* This is different from find_unique_abbrev() in that
3000 * it stuffs the result with dots for alignment.
3002 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3004 int abblen;
3005 const char *abbrev;
3006 if (len == 40)
3007 return sha1_to_hex(sha1);
3009 abbrev = find_unique_abbrev(sha1, len);
3010 abblen = strlen(abbrev);
3011 if (abblen < 37) {
3012 static char hex[41];
3013 if (len < abblen && abblen <= len + 2)
3014 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3015 else
3016 sprintf(hex, "%s...", abbrev);
3017 return hex;
3019 return sha1_to_hex(sha1);
3022 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3024 int line_termination = opt->line_termination;
3025 int inter_name_termination = line_termination ? '\t' : '\0';
3027 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3028 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3029 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3030 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3032 if (p->score) {
3033 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3034 inter_name_termination);
3035 } else {
3036 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3039 if (p->status == DIFF_STATUS_COPIED ||
3040 p->status == DIFF_STATUS_RENAMED) {
3041 const char *name_a, *name_b;
3042 name_a = p->one->path;
3043 name_b = p->two->path;
3044 strip_prefix(opt->prefix_length, &name_a, &name_b);
3045 write_name_quoted(name_a, opt->file, inter_name_termination);
3046 write_name_quoted(name_b, opt->file, line_termination);
3047 } else {
3048 const char *name_a, *name_b;
3049 name_a = p->one->mode ? p->one->path : p->two->path;
3050 name_b = NULL;
3051 strip_prefix(opt->prefix_length, &name_a, &name_b);
3052 write_name_quoted(name_a, opt->file, line_termination);
3056 int diff_unmodified_pair(struct diff_filepair *p)
3058 /* This function is written stricter than necessary to support
3059 * the currently implemented transformers, but the idea is to
3060 * let transformers to produce diff_filepairs any way they want,
3061 * and filter and clean them up here before producing the output.
3063 struct diff_filespec *one = p->one, *two = p->two;
3065 if (DIFF_PAIR_UNMERGED(p))
3066 return 0; /* unmerged is interesting */
3068 /* deletion, addition, mode or type change
3069 * and rename are all interesting.
3071 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3072 DIFF_PAIR_MODE_CHANGED(p) ||
3073 strcmp(one->path, two->path))
3074 return 0;
3076 /* both are valid and point at the same path. that is, we are
3077 * dealing with a change.
3079 if (one->sha1_valid && two->sha1_valid &&
3080 !hashcmp(one->sha1, two->sha1) &&
3081 !one->dirty_submodule && !two->dirty_submodule)
3082 return 1; /* no change */
3083 if (!one->sha1_valid && !two->sha1_valid)
3084 return 1; /* both look at the same file on the filesystem. */
3085 return 0;
3088 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3090 if (diff_unmodified_pair(p))
3091 return;
3093 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3094 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3095 return; /* no tree diffs in patch format */
3097 run_diff(p, o);
3100 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3101 struct diffstat_t *diffstat)
3103 if (diff_unmodified_pair(p))
3104 return;
3106 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3107 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3108 return; /* no tree diffs in patch format */
3110 run_diffstat(p, o, diffstat);
3113 static void diff_flush_checkdiff(struct diff_filepair *p,
3114 struct diff_options *o)
3116 if (diff_unmodified_pair(p))
3117 return;
3119 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3120 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3121 return; /* no tree diffs in patch format */
3123 run_checkdiff(p, o);
3126 int diff_queue_is_empty(void)
3128 struct diff_queue_struct *q = &diff_queued_diff;
3129 int i;
3130 for (i = 0; i < q->nr; i++)
3131 if (!diff_unmodified_pair(q->queue[i]))
3132 return 0;
3133 return 1;
3136 #if DIFF_DEBUG
3137 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3139 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3140 x, one ? one : "",
3141 s->path,
3142 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3143 s->mode,
3144 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3145 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3146 x, one ? one : "",
3147 s->size, s->xfrm_flags);
3150 void diff_debug_filepair(const struct diff_filepair *p, int i)
3152 diff_debug_filespec(p->one, i, "one");
3153 diff_debug_filespec(p->two, i, "two");
3154 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3155 p->score, p->status ? p->status : '?',
3156 p->one->rename_used, p->broken_pair);
3159 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3161 int i;
3162 if (msg)
3163 fprintf(stderr, "%s\n", msg);
3164 fprintf(stderr, "q->nr = %d\n", q->nr);
3165 for (i = 0; i < q->nr; i++) {
3166 struct diff_filepair *p = q->queue[i];
3167 diff_debug_filepair(p, i);
3170 #endif
3172 static void diff_resolve_rename_copy(void)
3174 int i;
3175 struct diff_filepair *p;
3176 struct diff_queue_struct *q = &diff_queued_diff;
3178 diff_debug_queue("resolve-rename-copy", q);
3180 for (i = 0; i < q->nr; i++) {
3181 p = q->queue[i];
3182 p->status = 0; /* undecided */
3183 if (DIFF_PAIR_UNMERGED(p))
3184 p->status = DIFF_STATUS_UNMERGED;
3185 else if (!DIFF_FILE_VALID(p->one))
3186 p->status = DIFF_STATUS_ADDED;
3187 else if (!DIFF_FILE_VALID(p->two))
3188 p->status = DIFF_STATUS_DELETED;
3189 else if (DIFF_PAIR_TYPE_CHANGED(p))
3190 p->status = DIFF_STATUS_TYPE_CHANGED;
3192 /* from this point on, we are dealing with a pair
3193 * whose both sides are valid and of the same type, i.e.
3194 * either in-place edit or rename/copy edit.
3196 else if (DIFF_PAIR_RENAME(p)) {
3198 * A rename might have re-connected a broken
3199 * pair up, causing the pathnames to be the
3200 * same again. If so, that's not a rename at
3201 * all, just a modification..
3203 * Otherwise, see if this source was used for
3204 * multiple renames, in which case we decrement
3205 * the count, and call it a copy.
3207 if (!strcmp(p->one->path, p->two->path))
3208 p->status = DIFF_STATUS_MODIFIED;
3209 else if (--p->one->rename_used > 0)
3210 p->status = DIFF_STATUS_COPIED;
3211 else
3212 p->status = DIFF_STATUS_RENAMED;
3214 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3215 p->one->mode != p->two->mode ||
3216 p->one->dirty_submodule ||
3217 p->two->dirty_submodule ||
3218 is_null_sha1(p->one->sha1))
3219 p->status = DIFF_STATUS_MODIFIED;
3220 else {
3221 /* This is a "no-change" entry and should not
3222 * happen anymore, but prepare for broken callers.
3224 error("feeding unmodified %s to diffcore",
3225 p->one->path);
3226 p->status = DIFF_STATUS_UNKNOWN;
3229 diff_debug_queue("resolve-rename-copy done", q);
3232 static int check_pair_status(struct diff_filepair *p)
3234 switch (p->status) {
3235 case DIFF_STATUS_UNKNOWN:
3236 return 0;
3237 case 0:
3238 die("internal error in diff-resolve-rename-copy");
3239 default:
3240 return 1;
3244 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3246 int fmt = opt->output_format;
3248 if (fmt & DIFF_FORMAT_CHECKDIFF)
3249 diff_flush_checkdiff(p, opt);
3250 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3251 diff_flush_raw(p, opt);
3252 else if (fmt & DIFF_FORMAT_NAME) {
3253 const char *name_a, *name_b;
3254 name_a = p->two->path;
3255 name_b = NULL;
3256 strip_prefix(opt->prefix_length, &name_a, &name_b);
3257 write_name_quoted(name_a, opt->file, opt->line_termination);
3261 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3263 if (fs->mode)
3264 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3265 else
3266 fprintf(file, " %s ", newdelete);
3267 write_name_quoted(fs->path, file, '\n');
3271 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3273 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3274 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3275 show_name ? ' ' : '\n');
3276 if (show_name) {
3277 write_name_quoted(p->two->path, file, '\n');
3282 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3284 char *names = pprint_rename(p->one->path, p->two->path);
3286 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3287 free(names);
3288 show_mode_change(file, p, 0);
3291 static void diff_summary(FILE *file, struct diff_filepair *p)
3293 switch(p->status) {
3294 case DIFF_STATUS_DELETED:
3295 show_file_mode_name(file, "delete", p->one);
3296 break;
3297 case DIFF_STATUS_ADDED:
3298 show_file_mode_name(file, "create", p->two);
3299 break;
3300 case DIFF_STATUS_COPIED:
3301 show_rename_copy(file, "copy", p);
3302 break;
3303 case DIFF_STATUS_RENAMED:
3304 show_rename_copy(file, "rename", p);
3305 break;
3306 default:
3307 if (p->score) {
3308 fputs(" rewrite ", file);
3309 write_name_quoted(p->two->path, file, ' ');
3310 fprintf(file, "(%d%%)\n", similarity_index(p));
3312 show_mode_change(file, p, !p->score);
3313 break;
3317 struct patch_id_t {
3318 git_SHA_CTX *ctx;
3319 int patchlen;
3322 static int remove_space(char *line, int len)
3324 int i;
3325 char *dst = line;
3326 unsigned char c;
3328 for (i = 0; i < len; i++)
3329 if (!isspace((c = line[i])))
3330 *dst++ = c;
3332 return dst - line;
3335 static void patch_id_consume(void *priv, char *line, unsigned long len)
3337 struct patch_id_t *data = priv;
3338 int new_len;
3340 /* Ignore line numbers when computing the SHA1 of the patch */
3341 if (!prefixcmp(line, "@@ -"))
3342 return;
3344 new_len = remove_space(line, len);
3346 git_SHA1_Update(data->ctx, line, new_len);
3347 data->patchlen += new_len;
3350 /* returns 0 upon success, and writes result into sha1 */
3351 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3353 struct diff_queue_struct *q = &diff_queued_diff;
3354 int i;
3355 git_SHA_CTX ctx;
3356 struct patch_id_t data;
3357 char buffer[PATH_MAX * 4 + 20];
3359 git_SHA1_Init(&ctx);
3360 memset(&data, 0, sizeof(struct patch_id_t));
3361 data.ctx = &ctx;
3363 for (i = 0; i < q->nr; i++) {
3364 xpparam_t xpp;
3365 xdemitconf_t xecfg;
3366 xdemitcb_t ecb;
3367 mmfile_t mf1, mf2;
3368 struct diff_filepair *p = q->queue[i];
3369 int len1, len2;
3371 memset(&xpp, 0, sizeof(xpp));
3372 memset(&xecfg, 0, sizeof(xecfg));
3373 if (p->status == 0)
3374 return error("internal diff status error");
3375 if (p->status == DIFF_STATUS_UNKNOWN)
3376 continue;
3377 if (diff_unmodified_pair(p))
3378 continue;
3379 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3380 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3381 continue;
3382 if (DIFF_PAIR_UNMERGED(p))
3383 continue;
3385 diff_fill_sha1_info(p->one);
3386 diff_fill_sha1_info(p->two);
3387 if (fill_mmfile(&mf1, p->one) < 0 ||
3388 fill_mmfile(&mf2, p->two) < 0)
3389 return error("unable to read files to diff");
3391 len1 = remove_space(p->one->path, strlen(p->one->path));
3392 len2 = remove_space(p->two->path, strlen(p->two->path));
3393 if (p->one->mode == 0)
3394 len1 = snprintf(buffer, sizeof(buffer),
3395 "diff--gita/%.*sb/%.*s"
3396 "newfilemode%06o"
3397 "---/dev/null"
3398 "+++b/%.*s",
3399 len1, p->one->path,
3400 len2, p->two->path,
3401 p->two->mode,
3402 len2, p->two->path);
3403 else if (p->two->mode == 0)
3404 len1 = snprintf(buffer, sizeof(buffer),
3405 "diff--gita/%.*sb/%.*s"
3406 "deletedfilemode%06o"
3407 "---a/%.*s"
3408 "+++/dev/null",
3409 len1, p->one->path,
3410 len2, p->two->path,
3411 p->one->mode,
3412 len1, p->one->path);
3413 else
3414 len1 = snprintf(buffer, sizeof(buffer),
3415 "diff--gita/%.*sb/%.*s"
3416 "---a/%.*s"
3417 "+++b/%.*s",
3418 len1, p->one->path,
3419 len2, p->two->path,
3420 len1, p->one->path,
3421 len2, p->two->path);
3422 git_SHA1_Update(&ctx, buffer, len1);
3424 xpp.flags = XDF_NEED_MINIMAL;
3425 xecfg.ctxlen = 3;
3426 xecfg.flags = XDL_EMIT_FUNCNAMES;
3427 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3428 &xpp, &xecfg, &ecb);
3431 git_SHA1_Final(sha1, &ctx);
3432 return 0;
3435 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3437 struct diff_queue_struct *q = &diff_queued_diff;
3438 int i;
3439 int result = diff_get_patch_id(options, sha1);
3441 for (i = 0; i < q->nr; i++)
3442 diff_free_filepair(q->queue[i]);
3444 free(q->queue);
3445 q->queue = NULL;
3446 q->nr = q->alloc = 0;
3448 return result;
3451 static int is_summary_empty(const struct diff_queue_struct *q)
3453 int i;
3455 for (i = 0; i < q->nr; i++) {
3456 const struct diff_filepair *p = q->queue[i];
3458 switch (p->status) {
3459 case DIFF_STATUS_DELETED:
3460 case DIFF_STATUS_ADDED:
3461 case DIFF_STATUS_COPIED:
3462 case DIFF_STATUS_RENAMED:
3463 return 0;
3464 default:
3465 if (p->score)
3466 return 0;
3467 if (p->one->mode && p->two->mode &&
3468 p->one->mode != p->two->mode)
3469 return 0;
3470 break;
3473 return 1;
3476 void diff_flush(struct diff_options *options)
3478 struct diff_queue_struct *q = &diff_queued_diff;
3479 int i, output_format = options->output_format;
3480 int separator = 0;
3483 * Order: raw, stat, summary, patch
3484 * or: name/name-status/checkdiff (other bits clear)
3486 if (!q->nr)
3487 goto free_queue;
3489 if (output_format & (DIFF_FORMAT_RAW |
3490 DIFF_FORMAT_NAME |
3491 DIFF_FORMAT_NAME_STATUS |
3492 DIFF_FORMAT_CHECKDIFF)) {
3493 for (i = 0; i < q->nr; i++) {
3494 struct diff_filepair *p = q->queue[i];
3495 if (check_pair_status(p))
3496 flush_one_pair(p, options);
3498 separator++;
3501 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3502 struct diffstat_t diffstat;
3504 memset(&diffstat, 0, sizeof(struct diffstat_t));
3505 for (i = 0; i < q->nr; i++) {
3506 struct diff_filepair *p = q->queue[i];
3507 if (check_pair_status(p))
3508 diff_flush_stat(p, options, &diffstat);
3510 if (output_format & DIFF_FORMAT_NUMSTAT)
3511 show_numstat(&diffstat, options);
3512 if (output_format & DIFF_FORMAT_DIFFSTAT)
3513 show_stats(&diffstat, options);
3514 if (output_format & DIFF_FORMAT_SHORTSTAT)
3515 show_shortstats(&diffstat, options);
3516 free_diffstat_info(&diffstat);
3517 separator++;
3519 if (output_format & DIFF_FORMAT_DIRSTAT)
3520 show_dirstat(options);
3522 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3523 for (i = 0; i < q->nr; i++)
3524 diff_summary(options->file, q->queue[i]);
3525 separator++;
3528 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
3529 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
3530 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3532 * run diff_flush_patch for the exit status. setting
3533 * options->file to /dev/null should be safe, becaue we
3534 * aren't supposed to produce any output anyway.
3536 if (options->close_file)
3537 fclose(options->file);
3538 options->file = fopen("/dev/null", "w");
3539 if (!options->file)
3540 die_errno("Could not open /dev/null");
3541 options->close_file = 1;
3542 for (i = 0; i < q->nr; i++) {
3543 struct diff_filepair *p = q->queue[i];
3544 if (check_pair_status(p))
3545 diff_flush_patch(p, options);
3546 if (options->found_changes)
3547 break;
3551 if (output_format & DIFF_FORMAT_PATCH) {
3552 if (separator) {
3553 putc(options->line_termination, options->file);
3554 if (options->stat_sep) {
3555 /* attach patch instead of inline */
3556 fputs(options->stat_sep, options->file);
3560 for (i = 0; i < q->nr; i++) {
3561 struct diff_filepair *p = q->queue[i];
3562 if (check_pair_status(p))
3563 diff_flush_patch(p, options);
3567 if (output_format & DIFF_FORMAT_CALLBACK)
3568 options->format_callback(q, options, options->format_callback_data);
3570 for (i = 0; i < q->nr; i++)
3571 diff_free_filepair(q->queue[i]);
3572 free_queue:
3573 free(q->queue);
3574 q->queue = NULL;
3575 q->nr = q->alloc = 0;
3576 if (options->close_file)
3577 fclose(options->file);
3580 * Report the content-level differences with HAS_CHANGES;
3581 * diff_addremove/diff_change does not set the bit when
3582 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3584 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3585 if (options->found_changes)
3586 DIFF_OPT_SET(options, HAS_CHANGES);
3587 else
3588 DIFF_OPT_CLR(options, HAS_CHANGES);
3592 static void diffcore_apply_filter(const char *filter)
3594 int i;
3595 struct diff_queue_struct *q = &diff_queued_diff;
3596 struct diff_queue_struct outq;
3597 outq.queue = NULL;
3598 outq.nr = outq.alloc = 0;
3600 if (!filter)
3601 return;
3603 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3604 int found;
3605 for (i = found = 0; !found && i < q->nr; i++) {
3606 struct diff_filepair *p = q->queue[i];
3607 if (((p->status == DIFF_STATUS_MODIFIED) &&
3608 ((p->score &&
3609 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3610 (!p->score &&
3611 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3612 ((p->status != DIFF_STATUS_MODIFIED) &&
3613 strchr(filter, p->status)))
3614 found++;
3616 if (found)
3617 return;
3619 /* otherwise we will clear the whole queue
3620 * by copying the empty outq at the end of this
3621 * function, but first clear the current entries
3622 * in the queue.
3624 for (i = 0; i < q->nr; i++)
3625 diff_free_filepair(q->queue[i]);
3627 else {
3628 /* Only the matching ones */
3629 for (i = 0; i < q->nr; i++) {
3630 struct diff_filepair *p = q->queue[i];
3632 if (((p->status == DIFF_STATUS_MODIFIED) &&
3633 ((p->score &&
3634 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3635 (!p->score &&
3636 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3637 ((p->status != DIFF_STATUS_MODIFIED) &&
3638 strchr(filter, p->status)))
3639 diff_q(&outq, p);
3640 else
3641 diff_free_filepair(p);
3644 free(q->queue);
3645 *q = outq;
3648 /* Check whether two filespecs with the same mode and size are identical */
3649 static int diff_filespec_is_identical(struct diff_filespec *one,
3650 struct diff_filespec *two)
3652 if (S_ISGITLINK(one->mode))
3653 return 0;
3654 if (diff_populate_filespec(one, 0))
3655 return 0;
3656 if (diff_populate_filespec(two, 0))
3657 return 0;
3658 return !memcmp(one->data, two->data, one->size);
3661 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3663 int i;
3664 struct diff_queue_struct *q = &diff_queued_diff;
3665 struct diff_queue_struct outq;
3666 outq.queue = NULL;
3667 outq.nr = outq.alloc = 0;
3669 for (i = 0; i < q->nr; i++) {
3670 struct diff_filepair *p = q->queue[i];
3673 * 1. Entries that come from stat info dirtiness
3674 * always have both sides (iow, not create/delete),
3675 * one side of the object name is unknown, with
3676 * the same mode and size. Keep the ones that
3677 * do not match these criteria. They have real
3678 * differences.
3680 * 2. At this point, the file is known to be modified,
3681 * with the same mode and size, and the object
3682 * name of one side is unknown. Need to inspect
3683 * the identical contents.
3685 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3686 !DIFF_FILE_VALID(p->two) ||
3687 (p->one->sha1_valid && p->two->sha1_valid) ||
3688 (p->one->mode != p->two->mode) ||
3689 diff_populate_filespec(p->one, 1) ||
3690 diff_populate_filespec(p->two, 1) ||
3691 (p->one->size != p->two->size) ||
3692 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3693 diff_q(&outq, p);
3694 else {
3696 * The caller can subtract 1 from skip_stat_unmatch
3697 * to determine how many paths were dirty only
3698 * due to stat info mismatch.
3700 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3701 diffopt->skip_stat_unmatch++;
3702 diff_free_filepair(p);
3705 free(q->queue);
3706 *q = outq;
3709 static int diffnamecmp(const void *a_, const void *b_)
3711 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
3712 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
3713 const char *name_a, *name_b;
3715 name_a = a->one ? a->one->path : a->two->path;
3716 name_b = b->one ? b->one->path : b->two->path;
3717 return strcmp(name_a, name_b);
3720 void diffcore_fix_diff_index(struct diff_options *options)
3722 struct diff_queue_struct *q = &diff_queued_diff;
3723 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
3726 void diffcore_std(struct diff_options *options)
3728 if (options->skip_stat_unmatch)
3729 diffcore_skip_stat_unmatch(options);
3730 if (options->break_opt != -1)
3731 diffcore_break(options->break_opt);
3732 if (options->detect_rename)
3733 diffcore_rename(options);
3734 if (options->break_opt != -1)
3735 diffcore_merge_broken();
3736 if (options->pickaxe)
3737 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3738 if (options->orderfile)
3739 diffcore_order(options->orderfile);
3740 diff_resolve_rename_copy();
3741 diffcore_apply_filter(options->filter);
3743 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3744 DIFF_OPT_SET(options, HAS_CHANGES);
3745 else
3746 DIFF_OPT_CLR(options, HAS_CHANGES);
3749 int diff_result_code(struct diff_options *opt, int status)
3751 int result = 0;
3752 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3753 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3754 return status;
3755 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3756 DIFF_OPT_TST(opt, HAS_CHANGES))
3757 result |= 01;
3758 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3759 DIFF_OPT_TST(opt, CHECK_FAILED))
3760 result |= 02;
3761 return result;
3764 void diff_addremove(struct diff_options *options,
3765 int addremove, unsigned mode,
3766 const unsigned char *sha1,
3767 const char *concatpath, unsigned dirty_submodule)
3769 struct diff_filespec *one, *two;
3771 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3772 return;
3774 /* This may look odd, but it is a preparation for
3775 * feeding "there are unchanged files which should
3776 * not produce diffs, but when you are doing copy
3777 * detection you would need them, so here they are"
3778 * entries to the diff-core. They will be prefixed
3779 * with something like '=' or '*' (I haven't decided
3780 * which but should not make any difference).
3781 * Feeding the same new and old to diff_change()
3782 * also has the same effect.
3783 * Before the final output happens, they are pruned after
3784 * merged into rename/copy pairs as appropriate.
3786 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3787 addremove = (addremove == '+' ? '-' :
3788 addremove == '-' ? '+' : addremove);
3790 if (options->prefix &&
3791 strncmp(concatpath, options->prefix, options->prefix_length))
3792 return;
3794 one = alloc_filespec(concatpath);
3795 two = alloc_filespec(concatpath);
3797 if (addremove != '+')
3798 fill_filespec(one, sha1, mode);
3799 if (addremove != '-') {
3800 fill_filespec(two, sha1, mode);
3801 two->dirty_submodule = dirty_submodule;
3804 diff_queue(&diff_queued_diff, one, two);
3805 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3806 DIFF_OPT_SET(options, HAS_CHANGES);
3809 void diff_change(struct diff_options *options,
3810 unsigned old_mode, unsigned new_mode,
3811 const unsigned char *old_sha1,
3812 const unsigned char *new_sha1,
3813 const char *concatpath,
3814 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
3816 struct diff_filespec *one, *two;
3818 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3819 && S_ISGITLINK(new_mode))
3820 return;
3822 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3823 unsigned tmp;
3824 const unsigned char *tmp_c;
3825 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3826 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3827 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
3828 new_dirty_submodule = tmp;
3831 if (options->prefix &&
3832 strncmp(concatpath, options->prefix, options->prefix_length))
3833 return;
3835 one = alloc_filespec(concatpath);
3836 two = alloc_filespec(concatpath);
3837 fill_filespec(one, old_sha1, old_mode);
3838 fill_filespec(two, new_sha1, new_mode);
3839 one->dirty_submodule = old_dirty_submodule;
3840 two->dirty_submodule = new_dirty_submodule;
3842 diff_queue(&diff_queued_diff, one, two);
3843 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3844 DIFF_OPT_SET(options, HAS_CHANGES);
3847 void diff_unmerge(struct diff_options *options,
3848 const char *path,
3849 unsigned mode, const unsigned char *sha1)
3851 struct diff_filespec *one, *two;
3853 if (options->prefix &&
3854 strncmp(path, options->prefix, options->prefix_length))
3855 return;
3857 one = alloc_filespec(path);
3858 two = alloc_filespec(path);
3859 fill_filespec(one, sha1, mode);
3860 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3863 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3864 size_t *outsize)
3866 struct diff_tempfile *temp;
3867 const char *argv[3];
3868 const char **arg = argv;
3869 struct child_process child;
3870 struct strbuf buf = STRBUF_INIT;
3871 int err = 0;
3873 temp = prepare_temp_file(spec->path, spec);
3874 *arg++ = pgm;
3875 *arg++ = temp->name;
3876 *arg = NULL;
3878 memset(&child, 0, sizeof(child));
3879 child.use_shell = 1;
3880 child.argv = argv;
3881 child.out = -1;
3882 if (start_command(&child)) {
3883 remove_tempfile();
3884 return NULL;
3887 if (strbuf_read(&buf, child.out, 0) < 0)
3888 err = error("error reading from textconv command '%s'", pgm);
3889 close(child.out);
3891 if (finish_command(&child) || err) {
3892 strbuf_release(&buf);
3893 remove_tempfile();
3894 return NULL;
3896 remove_tempfile();
3898 return strbuf_detach(&buf, outsize);
3901 static size_t fill_textconv(struct userdiff_driver *driver,
3902 struct diff_filespec *df,
3903 char **outbuf)
3905 size_t size;
3907 if (!driver || !driver->textconv) {
3908 if (!DIFF_FILE_VALID(df)) {
3909 *outbuf = "";
3910 return 0;
3912 if (diff_populate_filespec(df, 0))
3913 die("unable to read files to diff");
3914 *outbuf = df->data;
3915 return df->size;
3918 if (driver->textconv_cache) {
3919 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
3920 &size);
3921 if (*outbuf)
3922 return size;
3925 *outbuf = run_textconv(driver->textconv, df, &size);
3926 if (!*outbuf)
3927 die("unable to read files to diff");
3929 if (driver->textconv_cache) {
3930 /* ignore errors, as we might be in a readonly repository */
3931 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
3932 size);
3934 * we could save up changes and flush them all at the end,
3935 * but we would need an extra call after all diffing is done.
3936 * Since generating a cache entry is the slow path anyway,
3937 * this extra overhead probably isn't a big deal.
3939 notes_cache_write(driver->textconv_cache);
3942 return size;