smart-http: Really never use Expect: 100-continue
[git/mingw.git] / diff.c
bloba2d8c7f9a7a3bbfca889dedfbda8d6f351fbf016
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "quote.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "delta.h"
9 #include "xdiff-interface.h"
10 #include "color.h"
11 #include "attr.h"
12 #include "run-command.h"
13 #include "utf8.h"
14 #include "userdiff.h"
15 #include "sigchain.h"
16 #include "submodule.h"
17 #include "ll-merge.h"
19 #ifdef NO_FAST_WORKING_DIRECTORY
20 #define FAST_WORKING_DIRECTORY 0
21 #else
22 #define FAST_WORKING_DIRECTORY 1
23 #endif
25 static int diff_detect_rename_default;
26 static int diff_rename_limit_default = 200;
27 static int diff_suppress_blank_empty;
28 int diff_use_color_default = -1;
29 static const char *diff_word_regex_cfg;
30 static const char *external_diff_cmd_cfg;
31 int diff_auto_refresh_index = 1;
32 static int diff_mnemonic_prefix;
34 static char diff_colors[][COLOR_MAXLEN] = {
35 GIT_COLOR_RESET,
36 GIT_COLOR_NORMAL, /* PLAIN */
37 GIT_COLOR_BOLD, /* METAINFO */
38 GIT_COLOR_CYAN, /* FRAGINFO */
39 GIT_COLOR_RED, /* OLD */
40 GIT_COLOR_GREEN, /* NEW */
41 GIT_COLOR_YELLOW, /* COMMIT */
42 GIT_COLOR_BG_RED, /* WHITESPACE */
43 GIT_COLOR_NORMAL, /* FUNCINFO */
46 static void diff_filespec_load_driver(struct diff_filespec *one);
47 static char *run_textconv(const char *, struct diff_filespec *, size_t *);
49 static int parse_diff_color_slot(const char *var, int ofs)
51 if (!strcasecmp(var+ofs, "plain"))
52 return DIFF_PLAIN;
53 if (!strcasecmp(var+ofs, "meta"))
54 return DIFF_METAINFO;
55 if (!strcasecmp(var+ofs, "frag"))
56 return DIFF_FRAGINFO;
57 if (!strcasecmp(var+ofs, "old"))
58 return DIFF_FILE_OLD;
59 if (!strcasecmp(var+ofs, "new"))
60 return DIFF_FILE_NEW;
61 if (!strcasecmp(var+ofs, "commit"))
62 return DIFF_COMMIT;
63 if (!strcasecmp(var+ofs, "whitespace"))
64 return DIFF_WHITESPACE;
65 if (!strcasecmp(var+ofs, "func"))
66 return DIFF_FUNCINFO;
67 return -1;
70 static int git_config_rename(const char *var, const char *value)
72 if (!value)
73 return DIFF_DETECT_RENAME;
74 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
75 return DIFF_DETECT_COPY;
76 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
80 * These are to give UI layer defaults.
81 * The core-level commands such as git-diff-files should
82 * never be affected by the setting of diff.renames
83 * the user happens to have in the configuration file.
85 int git_diff_ui_config(const char *var, const char *value, void *cb)
87 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
88 diff_use_color_default = git_config_colorbool(var, value, -1);
89 return 0;
91 if (!strcmp(var, "diff.renames")) {
92 diff_detect_rename_default = git_config_rename(var, value);
93 return 0;
95 if (!strcmp(var, "diff.autorefreshindex")) {
96 diff_auto_refresh_index = git_config_bool(var, value);
97 return 0;
99 if (!strcmp(var, "diff.mnemonicprefix")) {
100 diff_mnemonic_prefix = git_config_bool(var, value);
101 return 0;
103 if (!strcmp(var, "diff.external"))
104 return git_config_string(&external_diff_cmd_cfg, var, value);
105 if (!strcmp(var, "diff.wordregex"))
106 return git_config_string(&diff_word_regex_cfg, var, value);
108 return git_diff_basic_config(var, value, cb);
111 int git_diff_basic_config(const char *var, const char *value, void *cb)
113 if (!strcmp(var, "diff.renamelimit")) {
114 diff_rename_limit_default = git_config_int(var, value);
115 return 0;
118 switch (userdiff_config(var, value)) {
119 case 0: break;
120 case -1: return -1;
121 default: return 0;
124 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
125 int slot = parse_diff_color_slot(var, 11);
126 if (slot < 0)
127 return 0;
128 if (!value)
129 return config_error_nonbool(var);
130 color_parse(value, var, diff_colors[slot]);
131 return 0;
134 /* like GNU diff's --suppress-blank-empty option */
135 if (!strcmp(var, "diff.suppressblankempty") ||
136 /* for backwards compatibility */
137 !strcmp(var, "diff.suppress-blank-empty")) {
138 diff_suppress_blank_empty = git_config_bool(var, value);
139 return 0;
142 return git_color_default_config(var, value, cb);
145 static char *quote_two(const char *one, const char *two)
147 int need_one = quote_c_style(one, NULL, NULL, 1);
148 int need_two = quote_c_style(two, NULL, NULL, 1);
149 struct strbuf res = STRBUF_INIT;
151 if (need_one + need_two) {
152 strbuf_addch(&res, '"');
153 quote_c_style(one, &res, NULL, 1);
154 quote_c_style(two, &res, NULL, 1);
155 strbuf_addch(&res, '"');
156 } else {
157 strbuf_addstr(&res, one);
158 strbuf_addstr(&res, two);
160 return strbuf_detach(&res, NULL);
163 static const char *external_diff(void)
165 static const char *external_diff_cmd = NULL;
166 static int done_preparing = 0;
168 if (done_preparing)
169 return external_diff_cmd;
170 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
171 if (!external_diff_cmd)
172 external_diff_cmd = external_diff_cmd_cfg;
173 done_preparing = 1;
174 return external_diff_cmd;
177 static struct diff_tempfile {
178 const char *name; /* filename external diff should read from */
179 char hex[41];
180 char mode[10];
181 char tmp_path[PATH_MAX];
182 } diff_temp[2];
184 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
186 struct emit_callback {
187 int color_diff;
188 unsigned ws_rule;
189 int blank_at_eof_in_preimage;
190 int blank_at_eof_in_postimage;
191 int lno_in_preimage;
192 int lno_in_postimage;
193 sane_truncate_fn truncate;
194 const char **label_path;
195 struct diff_words_data *diff_words;
196 int *found_changesp;
197 FILE *file;
198 struct strbuf *header;
201 static int count_lines(const char *data, int size)
203 int count, ch, completely_empty = 1, nl_just_seen = 0;
204 count = 0;
205 while (0 < size--) {
206 ch = *data++;
207 if (ch == '\n') {
208 count++;
209 nl_just_seen = 1;
210 completely_empty = 0;
212 else {
213 nl_just_seen = 0;
214 completely_empty = 0;
217 if (completely_empty)
218 return 0;
219 if (!nl_just_seen)
220 count++; /* no trailing newline */
221 return count;
224 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
226 if (!DIFF_FILE_VALID(one)) {
227 mf->ptr = (char *)""; /* does not matter */
228 mf->size = 0;
229 return 0;
231 else if (diff_populate_filespec(one, 0))
232 return -1;
234 mf->ptr = one->data;
235 mf->size = one->size;
236 return 0;
239 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
241 char *ptr = mf->ptr;
242 long size = mf->size;
243 int cnt = 0;
245 if (!size)
246 return cnt;
247 ptr += size - 1; /* pointing at the very end */
248 if (*ptr != '\n')
249 ; /* incomplete line */
250 else
251 ptr--; /* skip the last LF */
252 while (mf->ptr < ptr) {
253 char *prev_eol;
254 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
255 if (*prev_eol == '\n')
256 break;
257 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
258 break;
259 cnt++;
260 ptr = prev_eol - 1;
262 return cnt;
265 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
266 struct emit_callback *ecbdata)
268 int l1, l2, at;
269 unsigned ws_rule = ecbdata->ws_rule;
270 l1 = count_trailing_blank(mf1, ws_rule);
271 l2 = count_trailing_blank(mf2, ws_rule);
272 if (l2 <= l1) {
273 ecbdata->blank_at_eof_in_preimage = 0;
274 ecbdata->blank_at_eof_in_postimage = 0;
275 return;
277 at = count_lines(mf1->ptr, mf1->size);
278 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
280 at = count_lines(mf2->ptr, mf2->size);
281 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
284 static void emit_line_0(FILE *file, const char *set, const char *reset,
285 int first, const char *line, int len)
287 int has_trailing_newline, has_trailing_carriage_return;
288 int nofirst;
290 if (len == 0) {
291 has_trailing_newline = (first == '\n');
292 has_trailing_carriage_return = (!has_trailing_newline &&
293 (first == '\r'));
294 nofirst = has_trailing_newline || has_trailing_carriage_return;
295 } else {
296 has_trailing_newline = (len > 0 && line[len-1] == '\n');
297 if (has_trailing_newline)
298 len--;
299 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
300 if (has_trailing_carriage_return)
301 len--;
302 nofirst = 0;
305 if (len || !nofirst) {
306 fputs(set, file);
307 if (!nofirst)
308 fputc(first, file);
309 fwrite(line, len, 1, file);
310 fputs(reset, file);
312 if (has_trailing_carriage_return)
313 fputc('\r', file);
314 if (has_trailing_newline)
315 fputc('\n', file);
318 static void emit_line(FILE *file, const char *set, const char *reset,
319 const char *line, int len)
321 emit_line_0(file, set, reset, line[0], line+1, len-1);
324 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
326 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
327 ecbdata->blank_at_eof_in_preimage &&
328 ecbdata->blank_at_eof_in_postimage &&
329 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
330 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
331 return 0;
332 return ws_blank_line(line, len, ecbdata->ws_rule);
335 static void emit_add_line(const char *reset,
336 struct emit_callback *ecbdata,
337 const char *line, int len)
339 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
340 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
342 if (!*ws)
343 emit_line_0(ecbdata->file, set, reset, '+', line, len);
344 else if (new_blank_line_at_eof(ecbdata, line, len))
345 /* Blank line at EOF - paint '+' as well */
346 emit_line_0(ecbdata->file, ws, reset, '+', line, len);
347 else {
348 /* Emit just the prefix, then the rest. */
349 emit_line_0(ecbdata->file, set, reset, '+', "", 0);
350 ws_check_emit(line, len, ecbdata->ws_rule,
351 ecbdata->file, set, reset, ws);
355 static void emit_hunk_header(struct emit_callback *ecbdata,
356 const char *line, int len)
358 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
359 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
360 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
361 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
362 static const char atat[2] = { '@', '@' };
363 const char *cp, *ep;
366 * As a hunk header must begin with "@@ -<old>, +<new> @@",
367 * it always is at least 10 bytes long.
369 if (len < 10 ||
370 memcmp(line, atat, 2) ||
371 !(ep = memmem(line + 2, len - 2, atat, 2))) {
372 emit_line(ecbdata->file, plain, reset, line, len);
373 return;
375 ep += 2; /* skip over @@ */
377 /* The hunk header in fraginfo color */
378 emit_line(ecbdata->file, frag, reset, line, ep - line);
380 /* blank before the func header */
381 for (cp = ep; ep - line < len; ep++)
382 if (*ep != ' ' && *ep != '\t')
383 break;
384 if (ep != cp)
385 emit_line(ecbdata->file, plain, reset, cp, ep - cp);
387 if (ep < line + len)
388 emit_line(ecbdata->file, func, reset, ep, line + len - ep);
391 static struct diff_tempfile *claim_diff_tempfile(void) {
392 int i;
393 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
394 if (!diff_temp[i].name)
395 return diff_temp + i;
396 die("BUG: diff is failing to clean up its tempfiles");
399 static int remove_tempfile_installed;
401 static void remove_tempfile(void)
403 int i;
404 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
405 if (diff_temp[i].name == diff_temp[i].tmp_path)
406 unlink_or_warn(diff_temp[i].name);
407 diff_temp[i].name = NULL;
411 static void remove_tempfile_on_signal(int signo)
413 remove_tempfile();
414 sigchain_pop(signo);
415 raise(signo);
418 static void print_line_count(FILE *file, int count)
420 switch (count) {
421 case 0:
422 fprintf(file, "0,0");
423 break;
424 case 1:
425 fprintf(file, "1");
426 break;
427 default:
428 fprintf(file, "1,%d", count);
429 break;
433 static void emit_rewrite_lines(struct emit_callback *ecb,
434 int prefix, const char *data, int size)
436 const char *endp = NULL;
437 static const char *nneof = " No newline at end of file\n";
438 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
439 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
441 while (0 < size) {
442 int len;
444 endp = memchr(data, '\n', size);
445 len = endp ? (endp - data + 1) : size;
446 if (prefix != '+') {
447 ecb->lno_in_preimage++;
448 emit_line_0(ecb->file, old, reset, '-',
449 data, len);
450 } else {
451 ecb->lno_in_postimage++;
452 emit_add_line(reset, ecb, data, len);
454 size -= len;
455 data += len;
457 if (!endp) {
458 const char *plain = diff_get_color(ecb->color_diff,
459 DIFF_PLAIN);
460 emit_line_0(ecb->file, plain, reset, '\\',
461 nneof, strlen(nneof));
465 static void emit_rewrite_diff(const char *name_a,
466 const char *name_b,
467 struct diff_filespec *one,
468 struct diff_filespec *two,
469 const char *textconv_one,
470 const char *textconv_two,
471 struct diff_options *o)
473 int lc_a, lc_b;
474 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
475 const char *name_a_tab, *name_b_tab;
476 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
477 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
478 const char *reset = diff_get_color(color_diff, DIFF_RESET);
479 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
480 const char *a_prefix, *b_prefix;
481 const char *data_one, *data_two;
482 size_t size_one, size_two;
483 struct emit_callback ecbdata;
485 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
486 a_prefix = o->b_prefix;
487 b_prefix = o->a_prefix;
488 } else {
489 a_prefix = o->a_prefix;
490 b_prefix = o->b_prefix;
493 name_a += (*name_a == '/');
494 name_b += (*name_b == '/');
495 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
496 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
498 strbuf_reset(&a_name);
499 strbuf_reset(&b_name);
500 quote_two_c_style(&a_name, a_prefix, name_a, 0);
501 quote_two_c_style(&b_name, b_prefix, name_b, 0);
503 diff_populate_filespec(one, 0);
504 diff_populate_filespec(two, 0);
505 if (textconv_one) {
506 data_one = run_textconv(textconv_one, one, &size_one);
507 if (!data_one)
508 die("unable to read files to diff");
510 else {
511 data_one = one->data;
512 size_one = one->size;
514 if (textconv_two) {
515 data_two = run_textconv(textconv_two, two, &size_two);
516 if (!data_two)
517 die("unable to read files to diff");
519 else {
520 data_two = two->data;
521 size_two = two->size;
524 memset(&ecbdata, 0, sizeof(ecbdata));
525 ecbdata.color_diff = color_diff;
526 ecbdata.found_changesp = &o->found_changes;
527 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
528 ecbdata.file = o->file;
529 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
530 mmfile_t mf1, mf2;
531 mf1.ptr = (char *)data_one;
532 mf2.ptr = (char *)data_two;
533 mf1.size = size_one;
534 mf2.size = size_two;
535 check_blank_at_eof(&mf1, &mf2, &ecbdata);
537 ecbdata.lno_in_preimage = 1;
538 ecbdata.lno_in_postimage = 1;
540 lc_a = count_lines(data_one, size_one);
541 lc_b = count_lines(data_two, size_two);
542 fprintf(o->file,
543 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
544 metainfo, a_name.buf, name_a_tab, reset,
545 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
546 print_line_count(o->file, lc_a);
547 fprintf(o->file, " +");
548 print_line_count(o->file, lc_b);
549 fprintf(o->file, " @@%s\n", reset);
550 if (lc_a)
551 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
552 if (lc_b)
553 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
556 struct diff_words_buffer {
557 mmfile_t text;
558 long alloc;
559 struct diff_words_orig {
560 const char *begin, *end;
561 } *orig;
562 int orig_nr, orig_alloc;
565 static void diff_words_append(char *line, unsigned long len,
566 struct diff_words_buffer *buffer)
568 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
569 line++;
570 len--;
571 memcpy(buffer->text.ptr + buffer->text.size, line, len);
572 buffer->text.size += len;
573 buffer->text.ptr[buffer->text.size] = '\0';
576 struct diff_words_data {
577 struct diff_words_buffer minus, plus;
578 const char *current_plus;
579 FILE *file;
580 regex_t *word_regex;
583 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
585 struct diff_words_data *diff_words = priv;
586 int minus_first, minus_len, plus_first, plus_len;
587 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
589 if (line[0] != '@' || parse_hunk_header(line, len,
590 &minus_first, &minus_len, &plus_first, &plus_len))
591 return;
593 /* POSIX requires that first be decremented by one if len == 0... */
594 if (minus_len) {
595 minus_begin = diff_words->minus.orig[minus_first].begin;
596 minus_end =
597 diff_words->minus.orig[minus_first + minus_len - 1].end;
598 } else
599 minus_begin = minus_end =
600 diff_words->minus.orig[minus_first].end;
602 if (plus_len) {
603 plus_begin = diff_words->plus.orig[plus_first].begin;
604 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
605 } else
606 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
608 if (diff_words->current_plus != plus_begin)
609 fwrite(diff_words->current_plus,
610 plus_begin - diff_words->current_plus, 1,
611 diff_words->file);
612 if (minus_begin != minus_end)
613 color_fwrite_lines(diff_words->file,
614 diff_get_color(1, DIFF_FILE_OLD),
615 minus_end - minus_begin, minus_begin);
616 if (plus_begin != plus_end)
617 color_fwrite_lines(diff_words->file,
618 diff_get_color(1, DIFF_FILE_NEW),
619 plus_end - plus_begin, plus_begin);
621 diff_words->current_plus = plus_end;
624 /* This function starts looking at *begin, and returns 0 iff a word was found. */
625 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
626 int *begin, int *end)
628 if (word_regex && *begin < buffer->size) {
629 regmatch_t match[1];
630 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
631 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
632 '\n', match[0].rm_eo - match[0].rm_so);
633 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
634 *begin += match[0].rm_so;
635 return *begin >= *end;
637 return -1;
640 /* find the next word */
641 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
642 (*begin)++;
643 if (*begin >= buffer->size)
644 return -1;
646 /* find the end of the word */
647 *end = *begin + 1;
648 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
649 (*end)++;
651 return 0;
655 * This function splits the words in buffer->text, stores the list with
656 * newline separator into out, and saves the offsets of the original words
657 * in buffer->orig.
659 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
660 regex_t *word_regex)
662 int i, j;
663 long alloc = 0;
665 out->size = 0;
666 out->ptr = NULL;
668 /* fake an empty "0th" word */
669 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
670 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
671 buffer->orig_nr = 1;
673 for (i = 0; i < buffer->text.size; i++) {
674 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
675 return;
677 /* store original boundaries */
678 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
679 buffer->orig_alloc);
680 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
681 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
682 buffer->orig_nr++;
684 /* store one word */
685 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
686 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
687 out->ptr[out->size + j - i] = '\n';
688 out->size += j - i + 1;
690 i = j - 1;
694 /* this executes the word diff on the accumulated buffers */
695 static void diff_words_show(struct diff_words_data *diff_words)
697 xpparam_t xpp;
698 xdemitconf_t xecfg;
699 mmfile_t minus, plus;
701 /* special case: only removal */
702 if (!diff_words->plus.text.size) {
703 color_fwrite_lines(diff_words->file,
704 diff_get_color(1, DIFF_FILE_OLD),
705 diff_words->minus.text.size, diff_words->minus.text.ptr);
706 diff_words->minus.text.size = 0;
707 return;
710 diff_words->current_plus = diff_words->plus.text.ptr;
712 memset(&xpp, 0, sizeof(xpp));
713 memset(&xecfg, 0, sizeof(xecfg));
714 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
715 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
716 xpp.flags = XDF_NEED_MINIMAL;
717 /* as only the hunk header will be parsed, we need a 0-context */
718 xecfg.ctxlen = 0;
719 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
720 &xpp, &xecfg);
721 free(minus.ptr);
722 free(plus.ptr);
723 if (diff_words->current_plus != diff_words->plus.text.ptr +
724 diff_words->plus.text.size)
725 fwrite(diff_words->current_plus,
726 diff_words->plus.text.ptr + diff_words->plus.text.size
727 - diff_words->current_plus, 1,
728 diff_words->file);
729 diff_words->minus.text.size = diff_words->plus.text.size = 0;
732 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
733 static void diff_words_flush(struct emit_callback *ecbdata)
735 if (ecbdata->diff_words->minus.text.size ||
736 ecbdata->diff_words->plus.text.size)
737 diff_words_show(ecbdata->diff_words);
740 static void free_diff_words_data(struct emit_callback *ecbdata)
742 if (ecbdata->diff_words) {
743 diff_words_flush(ecbdata);
744 free (ecbdata->diff_words->minus.text.ptr);
745 free (ecbdata->diff_words->minus.orig);
746 free (ecbdata->diff_words->plus.text.ptr);
747 free (ecbdata->diff_words->plus.orig);
748 free(ecbdata->diff_words->word_regex);
749 free(ecbdata->diff_words);
750 ecbdata->diff_words = NULL;
754 const char *diff_get_color(int diff_use_color, enum color_diff ix)
756 if (diff_use_color)
757 return diff_colors[ix];
758 return "";
761 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
763 const char *cp;
764 unsigned long allot;
765 size_t l = len;
767 if (ecb->truncate)
768 return ecb->truncate(line, len);
769 cp = line;
770 allot = l;
771 while (0 < l) {
772 (void) utf8_width(&cp, &l);
773 if (!cp)
774 break; /* truncated in the middle? */
776 return allot - l;
779 static void find_lno(const char *line, struct emit_callback *ecbdata)
781 const char *p;
782 ecbdata->lno_in_preimage = 0;
783 ecbdata->lno_in_postimage = 0;
784 p = strchr(line, '-');
785 if (!p)
786 return; /* cannot happen */
787 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
788 p = strchr(p, '+');
789 if (!p)
790 return; /* cannot happen */
791 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
794 static void fn_out_consume(void *priv, char *line, unsigned long len)
796 struct emit_callback *ecbdata = priv;
797 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
798 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
799 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
801 if (ecbdata->header) {
802 fprintf(ecbdata->file, "%s", ecbdata->header->buf);
803 strbuf_reset(ecbdata->header);
804 ecbdata->header = NULL;
806 *(ecbdata->found_changesp) = 1;
808 if (ecbdata->label_path[0]) {
809 const char *name_a_tab, *name_b_tab;
811 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
812 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
814 fprintf(ecbdata->file, "%s--- %s%s%s\n",
815 meta, ecbdata->label_path[0], reset, name_a_tab);
816 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
817 meta, ecbdata->label_path[1], reset, name_b_tab);
818 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
821 if (diff_suppress_blank_empty
822 && len == 2 && line[0] == ' ' && line[1] == '\n') {
823 line[0] = '\n';
824 len = 1;
827 if (line[0] == '@') {
828 if (ecbdata->diff_words)
829 diff_words_flush(ecbdata);
830 len = sane_truncate_line(ecbdata, line, len);
831 find_lno(line, ecbdata);
832 emit_hunk_header(ecbdata, line, len);
833 if (line[len-1] != '\n')
834 putc('\n', ecbdata->file);
835 return;
838 if (len < 1) {
839 emit_line(ecbdata->file, reset, reset, line, len);
840 return;
843 if (ecbdata->diff_words) {
844 if (line[0] == '-') {
845 diff_words_append(line, len,
846 &ecbdata->diff_words->minus);
847 return;
848 } else if (line[0] == '+') {
849 diff_words_append(line, len,
850 &ecbdata->diff_words->plus);
851 return;
853 diff_words_flush(ecbdata);
854 line++;
855 len--;
856 emit_line(ecbdata->file, plain, reset, line, len);
857 return;
860 if (line[0] != '+') {
861 const char *color =
862 diff_get_color(ecbdata->color_diff,
863 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
864 ecbdata->lno_in_preimage++;
865 if (line[0] == ' ')
866 ecbdata->lno_in_postimage++;
867 emit_line(ecbdata->file, color, reset, line, len);
868 } else {
869 ecbdata->lno_in_postimage++;
870 emit_add_line(reset, ecbdata, line + 1, len - 1);
874 static char *pprint_rename(const char *a, const char *b)
876 const char *old = a;
877 const char *new = b;
878 struct strbuf name = STRBUF_INIT;
879 int pfx_length, sfx_length;
880 int len_a = strlen(a);
881 int len_b = strlen(b);
882 int a_midlen, b_midlen;
883 int qlen_a = quote_c_style(a, NULL, NULL, 0);
884 int qlen_b = quote_c_style(b, NULL, NULL, 0);
886 if (qlen_a || qlen_b) {
887 quote_c_style(a, &name, NULL, 0);
888 strbuf_addstr(&name, " => ");
889 quote_c_style(b, &name, NULL, 0);
890 return strbuf_detach(&name, NULL);
893 /* Find common prefix */
894 pfx_length = 0;
895 while (*old && *new && *old == *new) {
896 if (*old == '/')
897 pfx_length = old - a + 1;
898 old++;
899 new++;
902 /* Find common suffix */
903 old = a + len_a;
904 new = b + len_b;
905 sfx_length = 0;
906 while (a <= old && b <= new && *old == *new) {
907 if (*old == '/')
908 sfx_length = len_a - (old - a);
909 old--;
910 new--;
914 * pfx{mid-a => mid-b}sfx
915 * {pfx-a => pfx-b}sfx
916 * pfx{sfx-a => sfx-b}
917 * name-a => name-b
919 a_midlen = len_a - pfx_length - sfx_length;
920 b_midlen = len_b - pfx_length - sfx_length;
921 if (a_midlen < 0)
922 a_midlen = 0;
923 if (b_midlen < 0)
924 b_midlen = 0;
926 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
927 if (pfx_length + sfx_length) {
928 strbuf_add(&name, a, pfx_length);
929 strbuf_addch(&name, '{');
931 strbuf_add(&name, a + pfx_length, a_midlen);
932 strbuf_addstr(&name, " => ");
933 strbuf_add(&name, b + pfx_length, b_midlen);
934 if (pfx_length + sfx_length) {
935 strbuf_addch(&name, '}');
936 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
938 return strbuf_detach(&name, NULL);
941 struct diffstat_t {
942 int nr;
943 int alloc;
944 struct diffstat_file {
945 char *from_name;
946 char *name;
947 char *print_name;
948 unsigned is_unmerged:1;
949 unsigned is_binary:1;
950 unsigned is_renamed:1;
951 uintmax_t added, deleted;
952 } **files;
955 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
956 const char *name_a,
957 const char *name_b)
959 struct diffstat_file *x;
960 x = xcalloc(sizeof (*x), 1);
961 if (diffstat->nr == diffstat->alloc) {
962 diffstat->alloc = alloc_nr(diffstat->alloc);
963 diffstat->files = xrealloc(diffstat->files,
964 diffstat->alloc * sizeof(x));
966 diffstat->files[diffstat->nr++] = x;
967 if (name_b) {
968 x->from_name = xstrdup(name_a);
969 x->name = xstrdup(name_b);
970 x->is_renamed = 1;
972 else {
973 x->from_name = NULL;
974 x->name = xstrdup(name_a);
976 return x;
979 static void diffstat_consume(void *priv, char *line, unsigned long len)
981 struct diffstat_t *diffstat = priv;
982 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
984 if (line[0] == '+')
985 x->added++;
986 else if (line[0] == '-')
987 x->deleted++;
990 const char mime_boundary_leader[] = "------------";
992 static int scale_linear(int it, int width, int max_change)
995 * make sure that at least one '-' is printed if there were deletions,
996 * and likewise for '+'.
998 if (max_change < 2)
999 return it;
1000 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
1003 static void show_name(FILE *file,
1004 const char *prefix, const char *name, int len)
1006 fprintf(file, " %s%-*s |", prefix, len, name);
1009 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1011 if (cnt <= 0)
1012 return;
1013 fprintf(file, "%s", set);
1014 while (cnt--)
1015 putc(ch, file);
1016 fprintf(file, "%s", reset);
1019 static void fill_print_name(struct diffstat_file *file)
1021 char *pname;
1023 if (file->print_name)
1024 return;
1026 if (!file->is_renamed) {
1027 struct strbuf buf = STRBUF_INIT;
1028 if (quote_c_style(file->name, &buf, NULL, 0)) {
1029 pname = strbuf_detach(&buf, NULL);
1030 } else {
1031 pname = file->name;
1032 strbuf_release(&buf);
1034 } else {
1035 pname = pprint_rename(file->from_name, file->name);
1037 file->print_name = pname;
1040 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1042 int i, len, add, del, adds = 0, dels = 0;
1043 uintmax_t max_change = 0, max_len = 0;
1044 int total_files = data->nr;
1045 int width, name_width;
1046 const char *reset, *set, *add_c, *del_c;
1048 if (data->nr == 0)
1049 return;
1051 width = options->stat_width ? options->stat_width : 80;
1052 name_width = options->stat_name_width ? options->stat_name_width : 50;
1054 /* Sanity: give at least 5 columns to the graph,
1055 * but leave at least 10 columns for the name.
1057 if (width < 25)
1058 width = 25;
1059 if (name_width < 10)
1060 name_width = 10;
1061 else if (width < name_width + 15)
1062 name_width = width - 15;
1064 /* Find the longest filename and max number of changes */
1065 reset = diff_get_color_opt(options, DIFF_RESET);
1066 set = diff_get_color_opt(options, DIFF_PLAIN);
1067 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1068 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1070 for (i = 0; i < data->nr; i++) {
1071 struct diffstat_file *file = data->files[i];
1072 uintmax_t change = file->added + file->deleted;
1073 fill_print_name(file);
1074 len = strlen(file->print_name);
1075 if (max_len < len)
1076 max_len = len;
1078 if (file->is_binary || file->is_unmerged)
1079 continue;
1080 if (max_change < change)
1081 max_change = change;
1084 /* Compute the width of the graph part;
1085 * 10 is for one blank at the beginning of the line plus
1086 * " | count " between the name and the graph.
1088 * From here on, name_width is the width of the name area,
1089 * and width is the width of the graph area.
1091 name_width = (name_width < max_len) ? name_width : max_len;
1092 if (width < (name_width + 10) + max_change)
1093 width = width - (name_width + 10);
1094 else
1095 width = max_change;
1097 for (i = 0; i < data->nr; i++) {
1098 const char *prefix = "";
1099 char *name = data->files[i]->print_name;
1100 uintmax_t added = data->files[i]->added;
1101 uintmax_t deleted = data->files[i]->deleted;
1102 int name_len;
1105 * "scale" the filename
1107 len = name_width;
1108 name_len = strlen(name);
1109 if (name_width < name_len) {
1110 char *slash;
1111 prefix = "...";
1112 len -= 3;
1113 name += name_len - len;
1114 slash = strchr(name, '/');
1115 if (slash)
1116 name = slash;
1119 if (data->files[i]->is_binary) {
1120 show_name(options->file, prefix, name, len);
1121 fprintf(options->file, " Bin ");
1122 fprintf(options->file, "%s%"PRIuMAX"%s",
1123 del_c, deleted, reset);
1124 fprintf(options->file, " -> ");
1125 fprintf(options->file, "%s%"PRIuMAX"%s",
1126 add_c, added, reset);
1127 fprintf(options->file, " bytes");
1128 fprintf(options->file, "\n");
1129 continue;
1131 else if (data->files[i]->is_unmerged) {
1132 show_name(options->file, prefix, name, len);
1133 fprintf(options->file, " Unmerged\n");
1134 continue;
1136 else if (!data->files[i]->is_renamed &&
1137 (added + deleted == 0)) {
1138 total_files--;
1139 continue;
1143 * scale the add/delete
1145 add = added;
1146 del = deleted;
1147 adds += add;
1148 dels += del;
1150 if (width <= max_change) {
1151 add = scale_linear(add, width, max_change);
1152 del = scale_linear(del, width, max_change);
1154 show_name(options->file, prefix, name, len);
1155 fprintf(options->file, "%5"PRIuMAX"%s", added + deleted,
1156 added + deleted ? " " : "");
1157 show_graph(options->file, '+', add, add_c, reset);
1158 show_graph(options->file, '-', del, del_c, reset);
1159 fprintf(options->file, "\n");
1161 fprintf(options->file,
1162 " %d files changed, %d insertions(+), %d deletions(-)\n",
1163 total_files, adds, dels);
1166 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1168 int i, adds = 0, dels = 0, total_files = data->nr;
1170 if (data->nr == 0)
1171 return;
1173 for (i = 0; i < data->nr; i++) {
1174 if (!data->files[i]->is_binary &&
1175 !data->files[i]->is_unmerged) {
1176 int added = data->files[i]->added;
1177 int deleted= data->files[i]->deleted;
1178 if (!data->files[i]->is_renamed &&
1179 (added + deleted == 0)) {
1180 total_files--;
1181 } else {
1182 adds += added;
1183 dels += deleted;
1187 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1188 total_files, adds, dels);
1191 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1193 int i;
1195 if (data->nr == 0)
1196 return;
1198 for (i = 0; i < data->nr; i++) {
1199 struct diffstat_file *file = data->files[i];
1201 if (file->is_binary)
1202 fprintf(options->file, "-\t-\t");
1203 else
1204 fprintf(options->file,
1205 "%"PRIuMAX"\t%"PRIuMAX"\t",
1206 file->added, file->deleted);
1207 if (options->line_termination) {
1208 fill_print_name(file);
1209 if (!file->is_renamed)
1210 write_name_quoted(file->name, options->file,
1211 options->line_termination);
1212 else {
1213 fputs(file->print_name, options->file);
1214 putc(options->line_termination, options->file);
1216 } else {
1217 if (file->is_renamed) {
1218 putc('\0', options->file);
1219 write_name_quoted(file->from_name, options->file, '\0');
1221 write_name_quoted(file->name, options->file, '\0');
1226 struct dirstat_file {
1227 const char *name;
1228 unsigned long changed;
1231 struct dirstat_dir {
1232 struct dirstat_file *files;
1233 int alloc, nr, percent, cumulative;
1236 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1238 unsigned long this_dir = 0;
1239 unsigned int sources = 0;
1241 while (dir->nr) {
1242 struct dirstat_file *f = dir->files;
1243 int namelen = strlen(f->name);
1244 unsigned long this;
1245 char *slash;
1247 if (namelen < baselen)
1248 break;
1249 if (memcmp(f->name, base, baselen))
1250 break;
1251 slash = strchr(f->name + baselen, '/');
1252 if (slash) {
1253 int newbaselen = slash + 1 - f->name;
1254 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1255 sources++;
1256 } else {
1257 this = f->changed;
1258 dir->files++;
1259 dir->nr--;
1260 sources += 2;
1262 this_dir += this;
1266 * We don't report dirstat's for
1267 * - the top level
1268 * - or cases where everything came from a single directory
1269 * under this directory (sources == 1).
1271 if (baselen && sources != 1) {
1272 int permille = this_dir * 1000 / changed;
1273 if (permille) {
1274 int percent = permille / 10;
1275 if (percent >= dir->percent) {
1276 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1277 if (!dir->cumulative)
1278 return 0;
1282 return this_dir;
1285 static int dirstat_compare(const void *_a, const void *_b)
1287 const struct dirstat_file *a = _a;
1288 const struct dirstat_file *b = _b;
1289 return strcmp(a->name, b->name);
1292 static void show_dirstat(struct diff_options *options)
1294 int i;
1295 unsigned long changed;
1296 struct dirstat_dir dir;
1297 struct diff_queue_struct *q = &diff_queued_diff;
1299 dir.files = NULL;
1300 dir.alloc = 0;
1301 dir.nr = 0;
1302 dir.percent = options->dirstat_percent;
1303 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1305 changed = 0;
1306 for (i = 0; i < q->nr; i++) {
1307 struct diff_filepair *p = q->queue[i];
1308 const char *name;
1309 unsigned long copied, added, damage;
1311 name = p->one->path ? p->one->path : p->two->path;
1313 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1314 diff_populate_filespec(p->one, 0);
1315 diff_populate_filespec(p->two, 0);
1316 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1317 &copied, &added);
1318 diff_free_filespec_data(p->one);
1319 diff_free_filespec_data(p->two);
1320 } else if (DIFF_FILE_VALID(p->one)) {
1321 diff_populate_filespec(p->one, 1);
1322 copied = added = 0;
1323 diff_free_filespec_data(p->one);
1324 } else if (DIFF_FILE_VALID(p->two)) {
1325 diff_populate_filespec(p->two, 1);
1326 copied = 0;
1327 added = p->two->size;
1328 diff_free_filespec_data(p->two);
1329 } else
1330 continue;
1333 * Original minus copied is the removed material,
1334 * added is the new material. They are both damages
1335 * made to the preimage. In --dirstat-by-file mode, count
1336 * damaged files, not damaged lines. This is done by
1337 * counting only a single damaged line per file.
1339 damage = (p->one->size - copied) + added;
1340 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1341 damage = 1;
1343 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1344 dir.files[dir.nr].name = name;
1345 dir.files[dir.nr].changed = damage;
1346 changed += damage;
1347 dir.nr++;
1350 /* This can happen even with many files, if everything was renames */
1351 if (!changed)
1352 return;
1354 /* Show all directories with more than x% of the changes */
1355 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1356 gather_dirstat(options->file, &dir, changed, "", 0);
1359 static void free_diffstat_info(struct diffstat_t *diffstat)
1361 int i;
1362 for (i = 0; i < diffstat->nr; i++) {
1363 struct diffstat_file *f = diffstat->files[i];
1364 if (f->name != f->print_name)
1365 free(f->print_name);
1366 free(f->name);
1367 free(f->from_name);
1368 free(f);
1370 free(diffstat->files);
1373 struct checkdiff_t {
1374 const char *filename;
1375 int lineno;
1376 int conflict_marker_size;
1377 struct diff_options *o;
1378 unsigned ws_rule;
1379 unsigned status;
1382 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
1384 char firstchar;
1385 int cnt;
1387 if (len < marker_size + 1)
1388 return 0;
1389 firstchar = line[0];
1390 switch (firstchar) {
1391 case '=': case '>': case '<': case '|':
1392 break;
1393 default:
1394 return 0;
1396 for (cnt = 1; cnt < marker_size; cnt++)
1397 if (line[cnt] != firstchar)
1398 return 0;
1399 /* line[1] thru line[marker_size-1] are same as firstchar */
1400 if (len < marker_size + 1 || !isspace(line[marker_size]))
1401 return 0;
1402 return 1;
1405 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1407 struct checkdiff_t *data = priv;
1408 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1409 int marker_size = data->conflict_marker_size;
1410 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1411 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1412 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1413 char *err;
1415 if (line[0] == '+') {
1416 unsigned bad;
1417 data->lineno++;
1418 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
1419 data->status |= 1;
1420 fprintf(data->o->file,
1421 "%s:%d: leftover conflict marker\n",
1422 data->filename, data->lineno);
1424 bad = ws_check(line + 1, len - 1, data->ws_rule);
1425 if (!bad)
1426 return;
1427 data->status |= bad;
1428 err = whitespace_error_string(bad);
1429 fprintf(data->o->file, "%s:%d: %s.\n",
1430 data->filename, data->lineno, err);
1431 free(err);
1432 emit_line(data->o->file, set, reset, line, 1);
1433 ws_check_emit(line + 1, len - 1, data->ws_rule,
1434 data->o->file, set, reset, ws);
1435 } else if (line[0] == ' ') {
1436 data->lineno++;
1437 } else if (line[0] == '@') {
1438 char *plus = strchr(line, '+');
1439 if (plus)
1440 data->lineno = strtol(plus, NULL, 10) - 1;
1441 else
1442 die("invalid diff");
1446 static unsigned char *deflate_it(char *data,
1447 unsigned long size,
1448 unsigned long *result_size)
1450 int bound;
1451 unsigned char *deflated;
1452 z_stream stream;
1454 memset(&stream, 0, sizeof(stream));
1455 deflateInit(&stream, zlib_compression_level);
1456 bound = deflateBound(&stream, size);
1457 deflated = xmalloc(bound);
1458 stream.next_out = deflated;
1459 stream.avail_out = bound;
1461 stream.next_in = (unsigned char *)data;
1462 stream.avail_in = size;
1463 while (deflate(&stream, Z_FINISH) == Z_OK)
1464 ; /* nothing */
1465 deflateEnd(&stream);
1466 *result_size = stream.total_out;
1467 return deflated;
1470 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1472 void *cp;
1473 void *delta;
1474 void *deflated;
1475 void *data;
1476 unsigned long orig_size;
1477 unsigned long delta_size;
1478 unsigned long deflate_size;
1479 unsigned long data_size;
1481 /* We could do deflated delta, or we could do just deflated two,
1482 * whichever is smaller.
1484 delta = NULL;
1485 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1486 if (one->size && two->size) {
1487 delta = diff_delta(one->ptr, one->size,
1488 two->ptr, two->size,
1489 &delta_size, deflate_size);
1490 if (delta) {
1491 void *to_free = delta;
1492 orig_size = delta_size;
1493 delta = deflate_it(delta, delta_size, &delta_size);
1494 free(to_free);
1498 if (delta && delta_size < deflate_size) {
1499 fprintf(file, "delta %lu\n", orig_size);
1500 free(deflated);
1501 data = delta;
1502 data_size = delta_size;
1504 else {
1505 fprintf(file, "literal %lu\n", two->size);
1506 free(delta);
1507 data = deflated;
1508 data_size = deflate_size;
1511 /* emit data encoded in base85 */
1512 cp = data;
1513 while (data_size) {
1514 int bytes = (52 < data_size) ? 52 : data_size;
1515 char line[70];
1516 data_size -= bytes;
1517 if (bytes <= 26)
1518 line[0] = bytes + 'A' - 1;
1519 else
1520 line[0] = bytes - 26 + 'a' - 1;
1521 encode_85(line + 1, cp, bytes);
1522 cp = (char *) cp + bytes;
1523 fputs(line, file);
1524 fputc('\n', file);
1526 fprintf(file, "\n");
1527 free(data);
1530 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1532 fprintf(file, "GIT binary patch\n");
1533 emit_binary_diff_body(file, one, two);
1534 emit_binary_diff_body(file, two, one);
1537 static void diff_filespec_load_driver(struct diff_filespec *one)
1539 if (!one->driver)
1540 one->driver = userdiff_find_by_path(one->path);
1541 if (!one->driver)
1542 one->driver = userdiff_find_by_name("default");
1545 int diff_filespec_is_binary(struct diff_filespec *one)
1547 if (one->is_binary == -1) {
1548 diff_filespec_load_driver(one);
1549 if (one->driver->binary != -1)
1550 one->is_binary = one->driver->binary;
1551 else {
1552 if (!one->data && DIFF_FILE_VALID(one))
1553 diff_populate_filespec(one, 0);
1554 if (one->data)
1555 one->is_binary = buffer_is_binary(one->data,
1556 one->size);
1557 if (one->is_binary == -1)
1558 one->is_binary = 0;
1561 return one->is_binary;
1564 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1566 diff_filespec_load_driver(one);
1567 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1570 static const char *userdiff_word_regex(struct diff_filespec *one)
1572 diff_filespec_load_driver(one);
1573 return one->driver->word_regex;
1576 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1578 if (!options->a_prefix)
1579 options->a_prefix = a;
1580 if (!options->b_prefix)
1581 options->b_prefix = b;
1584 static const char *get_textconv(struct diff_filespec *one)
1586 if (!DIFF_FILE_VALID(one))
1587 return NULL;
1588 if (!S_ISREG(one->mode))
1589 return NULL;
1590 diff_filespec_load_driver(one);
1591 return one->driver->textconv;
1594 static void builtin_diff(const char *name_a,
1595 const char *name_b,
1596 struct diff_filespec *one,
1597 struct diff_filespec *two,
1598 const char *xfrm_msg,
1599 struct diff_options *o,
1600 int complete_rewrite)
1602 mmfile_t mf1, mf2;
1603 const char *lbl[2];
1604 char *a_one, *b_two;
1605 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1606 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1607 const char *a_prefix, *b_prefix;
1608 const char *textconv_one = NULL, *textconv_two = NULL;
1609 struct strbuf header = STRBUF_INIT;
1611 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
1612 (!one->mode || S_ISGITLINK(one->mode)) &&
1613 (!two->mode || S_ISGITLINK(two->mode))) {
1614 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1615 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1616 show_submodule_summary(o->file, one ? one->path : two->path,
1617 one->sha1, two->sha1, two->dirty_submodule,
1618 del, add, reset);
1619 return;
1622 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1623 textconv_one = get_textconv(one);
1624 textconv_two = get_textconv(two);
1627 diff_set_mnemonic_prefix(o, "a/", "b/");
1628 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1629 a_prefix = o->b_prefix;
1630 b_prefix = o->a_prefix;
1631 } else {
1632 a_prefix = o->a_prefix;
1633 b_prefix = o->b_prefix;
1636 /* Never use a non-valid filename anywhere if at all possible */
1637 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1638 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1640 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1641 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1642 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1643 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1644 strbuf_addf(&header, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1645 if (lbl[0][0] == '/') {
1646 /* /dev/null */
1647 strbuf_addf(&header, "%snew file mode %06o%s\n", set, two->mode, reset);
1648 if (xfrm_msg && xfrm_msg[0])
1649 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1651 else if (lbl[1][0] == '/') {
1652 strbuf_addf(&header, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1653 if (xfrm_msg && xfrm_msg[0])
1654 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1656 else {
1657 if (one->mode != two->mode) {
1658 strbuf_addf(&header, "%sold mode %06o%s\n", set, one->mode, reset);
1659 strbuf_addf(&header, "%snew mode %06o%s\n", set, two->mode, reset);
1661 if (xfrm_msg && xfrm_msg[0])
1662 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1665 * we do not run diff between different kind
1666 * of objects.
1668 if ((one->mode ^ two->mode) & S_IFMT)
1669 goto free_ab_and_return;
1670 if (complete_rewrite &&
1671 (textconv_one || !diff_filespec_is_binary(one)) &&
1672 (textconv_two || !diff_filespec_is_binary(two))) {
1673 fprintf(o->file, "%s", header.buf);
1674 strbuf_reset(&header);
1675 emit_rewrite_diff(name_a, name_b, one, two,
1676 textconv_one, textconv_two, o);
1677 o->found_changes = 1;
1678 goto free_ab_and_return;
1682 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1683 die("unable to read files to diff");
1685 if (!DIFF_OPT_TST(o, TEXT) &&
1686 ( (diff_filespec_is_binary(one) && !textconv_one) ||
1687 (diff_filespec_is_binary(two) && !textconv_two) )) {
1688 /* Quite common confusing case */
1689 if (mf1.size == mf2.size &&
1690 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1691 goto free_ab_and_return;
1692 fprintf(o->file, "%s", header.buf);
1693 strbuf_reset(&header);
1694 if (DIFF_OPT_TST(o, BINARY))
1695 emit_binary_diff(o->file, &mf1, &mf2);
1696 else
1697 fprintf(o->file, "Binary files %s and %s differ\n",
1698 lbl[0], lbl[1]);
1699 o->found_changes = 1;
1701 else {
1702 /* Crazy xdl interfaces.. */
1703 const char *diffopts = getenv("GIT_DIFF_OPTS");
1704 xpparam_t xpp;
1705 xdemitconf_t xecfg;
1706 struct emit_callback ecbdata;
1707 const struct userdiff_funcname *pe;
1709 if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS)) {
1710 fprintf(o->file, "%s", header.buf);
1711 strbuf_reset(&header);
1714 if (textconv_one) {
1715 size_t size;
1716 mf1.ptr = run_textconv(textconv_one, one, &size);
1717 if (!mf1.ptr)
1718 die("unable to read files to diff");
1719 mf1.size = size;
1721 if (textconv_two) {
1722 size_t size;
1723 mf2.ptr = run_textconv(textconv_two, two, &size);
1724 if (!mf2.ptr)
1725 die("unable to read files to diff");
1726 mf2.size = size;
1729 pe = diff_funcname_pattern(one);
1730 if (!pe)
1731 pe = diff_funcname_pattern(two);
1733 memset(&xpp, 0, sizeof(xpp));
1734 memset(&xecfg, 0, sizeof(xecfg));
1735 memset(&ecbdata, 0, sizeof(ecbdata));
1736 ecbdata.label_path = lbl;
1737 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1738 ecbdata.found_changesp = &o->found_changes;
1739 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1740 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1741 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1742 ecbdata.file = o->file;
1743 ecbdata.header = header.len ? &header : NULL;
1744 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1745 xecfg.ctxlen = o->context;
1746 xecfg.interhunkctxlen = o->interhunkcontext;
1747 xecfg.flags = XDL_EMIT_FUNCNAMES;
1748 if (pe)
1749 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1750 if (!diffopts)
1752 else if (!prefixcmp(diffopts, "--unified="))
1753 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1754 else if (!prefixcmp(diffopts, "-u"))
1755 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1756 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1757 ecbdata.diff_words =
1758 xcalloc(1, sizeof(struct diff_words_data));
1759 ecbdata.diff_words->file = o->file;
1760 if (!o->word_regex)
1761 o->word_regex = userdiff_word_regex(one);
1762 if (!o->word_regex)
1763 o->word_regex = userdiff_word_regex(two);
1764 if (!o->word_regex)
1765 o->word_regex = diff_word_regex_cfg;
1766 if (o->word_regex) {
1767 ecbdata.diff_words->word_regex = (regex_t *)
1768 xmalloc(sizeof(regex_t));
1769 if (regcomp(ecbdata.diff_words->word_regex,
1770 o->word_regex,
1771 REG_EXTENDED | REG_NEWLINE))
1772 die ("Invalid regular expression: %s",
1773 o->word_regex);
1776 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1777 &xpp, &xecfg);
1778 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1779 free_diff_words_data(&ecbdata);
1780 if (textconv_one)
1781 free(mf1.ptr);
1782 if (textconv_two)
1783 free(mf2.ptr);
1784 xdiff_clear_find_func(&xecfg);
1787 free_ab_and_return:
1788 strbuf_release(&header);
1789 diff_free_filespec_data(one);
1790 diff_free_filespec_data(two);
1791 free(a_one);
1792 free(b_two);
1793 return;
1796 static void builtin_diffstat(const char *name_a, const char *name_b,
1797 struct diff_filespec *one,
1798 struct diff_filespec *two,
1799 struct diffstat_t *diffstat,
1800 struct diff_options *o,
1801 int complete_rewrite)
1803 mmfile_t mf1, mf2;
1804 struct diffstat_file *data;
1806 data = diffstat_add(diffstat, name_a, name_b);
1808 if (!one || !two) {
1809 data->is_unmerged = 1;
1810 return;
1812 if (complete_rewrite) {
1813 diff_populate_filespec(one, 0);
1814 diff_populate_filespec(two, 0);
1815 data->deleted = count_lines(one->data, one->size);
1816 data->added = count_lines(two->data, two->size);
1817 goto free_and_return;
1819 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1820 die("unable to read files to diff");
1822 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1823 data->is_binary = 1;
1824 data->added = mf2.size;
1825 data->deleted = mf1.size;
1826 } else {
1827 /* Crazy xdl interfaces.. */
1828 xpparam_t xpp;
1829 xdemitconf_t xecfg;
1831 memset(&xpp, 0, sizeof(xpp));
1832 memset(&xecfg, 0, sizeof(xecfg));
1833 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1834 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1835 &xpp, &xecfg);
1838 free_and_return:
1839 diff_free_filespec_data(one);
1840 diff_free_filespec_data(two);
1843 static void builtin_checkdiff(const char *name_a, const char *name_b,
1844 const char *attr_path,
1845 struct diff_filespec *one,
1846 struct diff_filespec *two,
1847 struct diff_options *o)
1849 mmfile_t mf1, mf2;
1850 struct checkdiff_t data;
1852 if (!two)
1853 return;
1855 memset(&data, 0, sizeof(data));
1856 data.filename = name_b ? name_b : name_a;
1857 data.lineno = 0;
1858 data.o = o;
1859 data.ws_rule = whitespace_rule(attr_path);
1860 data.conflict_marker_size = ll_merge_marker_size(attr_path);
1862 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1863 die("unable to read files to diff");
1866 * All the other codepaths check both sides, but not checking
1867 * the "old" side here is deliberate. We are checking the newly
1868 * introduced changes, and as long as the "new" side is text, we
1869 * can and should check what it introduces.
1871 if (diff_filespec_is_binary(two))
1872 goto free_and_return;
1873 else {
1874 /* Crazy xdl interfaces.. */
1875 xpparam_t xpp;
1876 xdemitconf_t xecfg;
1878 memset(&xpp, 0, sizeof(xpp));
1879 memset(&xecfg, 0, sizeof(xecfg));
1880 xecfg.ctxlen = 1; /* at least one context line */
1881 xpp.flags = XDF_NEED_MINIMAL;
1882 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1883 &xpp, &xecfg);
1885 if (data.ws_rule & WS_BLANK_AT_EOF) {
1886 struct emit_callback ecbdata;
1887 int blank_at_eof;
1889 ecbdata.ws_rule = data.ws_rule;
1890 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1891 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
1893 if (blank_at_eof) {
1894 static char *err;
1895 if (!err)
1896 err = whitespace_error_string(WS_BLANK_AT_EOF);
1897 fprintf(o->file, "%s:%d: %s.\n",
1898 data.filename, blank_at_eof, err);
1899 data.status = 1; /* report errors */
1903 free_and_return:
1904 diff_free_filespec_data(one);
1905 diff_free_filespec_data(two);
1906 if (data.status)
1907 DIFF_OPT_SET(o, CHECK_FAILED);
1910 struct diff_filespec *alloc_filespec(const char *path)
1912 int namelen = strlen(path);
1913 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1915 memset(spec, 0, sizeof(*spec));
1916 spec->path = (char *)(spec + 1);
1917 memcpy(spec->path, path, namelen+1);
1918 spec->count = 1;
1919 spec->is_binary = -1;
1920 return spec;
1923 void free_filespec(struct diff_filespec *spec)
1925 if (!--spec->count) {
1926 diff_free_filespec_data(spec);
1927 free(spec);
1931 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1932 unsigned short mode)
1934 if (mode) {
1935 spec->mode = canon_mode(mode);
1936 hashcpy(spec->sha1, sha1);
1937 spec->sha1_valid = !is_null_sha1(sha1);
1942 * Given a name and sha1 pair, if the index tells us the file in
1943 * the work tree has that object contents, return true, so that
1944 * prepare_temp_file() does not have to inflate and extract.
1946 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1948 struct cache_entry *ce;
1949 struct stat st;
1950 int pos, len;
1953 * We do not read the cache ourselves here, because the
1954 * benchmark with my previous version that always reads cache
1955 * shows that it makes things worse for diff-tree comparing
1956 * two linux-2.6 kernel trees in an already checked out work
1957 * tree. This is because most diff-tree comparisons deal with
1958 * only a small number of files, while reading the cache is
1959 * expensive for a large project, and its cost outweighs the
1960 * savings we get by not inflating the object to a temporary
1961 * file. Practically, this code only helps when we are used
1962 * by diff-cache --cached, which does read the cache before
1963 * calling us.
1965 if (!active_cache)
1966 return 0;
1968 /* We want to avoid the working directory if our caller
1969 * doesn't need the data in a normal file, this system
1970 * is rather slow with its stat/open/mmap/close syscalls,
1971 * and the object is contained in a pack file. The pack
1972 * is probably already open and will be faster to obtain
1973 * the data through than the working directory. Loose
1974 * objects however would tend to be slower as they need
1975 * to be individually opened and inflated.
1977 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1978 return 0;
1980 len = strlen(name);
1981 pos = cache_name_pos(name, len);
1982 if (pos < 0)
1983 return 0;
1984 ce = active_cache[pos];
1987 * This is not the sha1 we are looking for, or
1988 * unreusable because it is not a regular file.
1990 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1991 return 0;
1994 * If ce is marked as "assume unchanged", there is no
1995 * guarantee that work tree matches what we are looking for.
1997 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
1998 return 0;
2001 * If ce matches the file in the work tree, we can reuse it.
2003 if (ce_uptodate(ce) ||
2004 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2005 return 1;
2007 return 0;
2010 static int populate_from_stdin(struct diff_filespec *s)
2012 struct strbuf buf = STRBUF_INIT;
2013 size_t size = 0;
2015 if (strbuf_read(&buf, 0, 0) < 0)
2016 return error("error while reading from stdin %s",
2017 strerror(errno));
2019 s->should_munmap = 0;
2020 s->data = strbuf_detach(&buf, &size);
2021 s->size = size;
2022 s->should_free = 1;
2023 return 0;
2026 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2028 int len;
2029 char *data = xmalloc(100), *dirty = "";
2031 /* Are we looking at the work tree? */
2032 if (!s->sha1_valid && s->dirty_submodule)
2033 dirty = "-dirty";
2035 len = snprintf(data, 100,
2036 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2037 s->data = data;
2038 s->size = len;
2039 s->should_free = 1;
2040 if (size_only) {
2041 s->data = NULL;
2042 free(data);
2044 return 0;
2048 * While doing rename detection and pickaxe operation, we may need to
2049 * grab the data for the blob (or file) for our own in-core comparison.
2050 * diff_filespec has data and size fields for this purpose.
2052 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2054 int err = 0;
2055 if (!DIFF_FILE_VALID(s))
2056 die("internal error: asking to populate invalid file.");
2057 if (S_ISDIR(s->mode))
2058 return -1;
2060 if (s->data)
2061 return 0;
2063 if (size_only && 0 < s->size)
2064 return 0;
2066 if (S_ISGITLINK(s->mode))
2067 return diff_populate_gitlink(s, size_only);
2069 if (!s->sha1_valid ||
2070 reuse_worktree_file(s->path, s->sha1, 0)) {
2071 struct strbuf buf = STRBUF_INIT;
2072 struct stat st;
2073 int fd;
2075 if (!strcmp(s->path, "-"))
2076 return populate_from_stdin(s);
2078 if (lstat(s->path, &st) < 0) {
2079 if (errno == ENOENT) {
2080 err_empty:
2081 err = -1;
2082 empty:
2083 s->data = (char *)"";
2084 s->size = 0;
2085 return err;
2088 s->size = xsize_t(st.st_size);
2089 if (!s->size)
2090 goto empty;
2091 if (S_ISLNK(st.st_mode)) {
2092 struct strbuf sb = STRBUF_INIT;
2094 if (strbuf_readlink(&sb, s->path, s->size))
2095 goto err_empty;
2096 s->size = sb.len;
2097 s->data = strbuf_detach(&sb, NULL);
2098 s->should_free = 1;
2099 return 0;
2101 if (size_only)
2102 return 0;
2103 fd = open(s->path, O_RDONLY);
2104 if (fd < 0)
2105 goto err_empty;
2106 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2107 close(fd);
2108 s->should_munmap = 1;
2111 * Convert from working tree format to canonical git format
2113 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2114 size_t size = 0;
2115 munmap(s->data, s->size);
2116 s->should_munmap = 0;
2117 s->data = strbuf_detach(&buf, &size);
2118 s->size = size;
2119 s->should_free = 1;
2122 else {
2123 enum object_type type;
2124 if (size_only)
2125 type = sha1_object_info(s->sha1, &s->size);
2126 else {
2127 s->data = read_sha1_file(s->sha1, &type, &s->size);
2128 s->should_free = 1;
2131 return 0;
2134 void diff_free_filespec_blob(struct diff_filespec *s)
2136 if (s->should_free)
2137 free(s->data);
2138 else if (s->should_munmap)
2139 munmap(s->data, s->size);
2141 if (s->should_free || s->should_munmap) {
2142 s->should_free = s->should_munmap = 0;
2143 s->data = NULL;
2147 void diff_free_filespec_data(struct diff_filespec *s)
2149 diff_free_filespec_blob(s);
2150 free(s->cnt_data);
2151 s->cnt_data = NULL;
2154 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2155 void *blob,
2156 unsigned long size,
2157 const unsigned char *sha1,
2158 int mode)
2160 int fd;
2161 struct strbuf buf = STRBUF_INIT;
2162 struct strbuf template = STRBUF_INIT;
2163 char *path_dup = xstrdup(path);
2164 const char *base = basename(path_dup);
2166 /* Generate "XXXXXX_basename.ext" */
2167 strbuf_addstr(&template, "XXXXXX_");
2168 strbuf_addstr(&template, base);
2170 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2171 strlen(base) + 1);
2172 if (fd < 0)
2173 die_errno("unable to create temp-file");
2174 if (convert_to_working_tree(path,
2175 (const char *)blob, (size_t)size, &buf)) {
2176 blob = buf.buf;
2177 size = buf.len;
2179 if (write_in_full(fd, blob, size) != size)
2180 die_errno("unable to write temp-file");
2181 close(fd);
2182 temp->name = temp->tmp_path;
2183 strcpy(temp->hex, sha1_to_hex(sha1));
2184 temp->hex[40] = 0;
2185 sprintf(temp->mode, "%06o", mode);
2186 strbuf_release(&buf);
2187 strbuf_release(&template);
2188 free(path_dup);
2191 static struct diff_tempfile *prepare_temp_file(const char *name,
2192 struct diff_filespec *one)
2194 struct diff_tempfile *temp = claim_diff_tempfile();
2196 if (!DIFF_FILE_VALID(one)) {
2197 not_a_valid_file:
2198 /* A '-' entry produces this for file-2, and
2199 * a '+' entry produces this for file-1.
2201 temp->name = "/dev/null";
2202 strcpy(temp->hex, ".");
2203 strcpy(temp->mode, ".");
2204 return temp;
2207 if (!remove_tempfile_installed) {
2208 atexit(remove_tempfile);
2209 sigchain_push_common(remove_tempfile_on_signal);
2210 remove_tempfile_installed = 1;
2213 if (!one->sha1_valid ||
2214 reuse_worktree_file(name, one->sha1, 1)) {
2215 struct stat st;
2216 if (lstat(name, &st) < 0) {
2217 if (errno == ENOENT)
2218 goto not_a_valid_file;
2219 die_errno("stat(%s)", name);
2221 if (S_ISLNK(st.st_mode)) {
2222 struct strbuf sb = STRBUF_INIT;
2223 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2224 die_errno("readlink(%s)", name);
2225 prep_temp_blob(name, temp, sb.buf, sb.len,
2226 (one->sha1_valid ?
2227 one->sha1 : null_sha1),
2228 (one->sha1_valid ?
2229 one->mode : S_IFLNK));
2230 strbuf_release(&sb);
2232 else {
2233 /* we can borrow from the file in the work tree */
2234 temp->name = name;
2235 if (!one->sha1_valid)
2236 strcpy(temp->hex, sha1_to_hex(null_sha1));
2237 else
2238 strcpy(temp->hex, sha1_to_hex(one->sha1));
2239 /* Even though we may sometimes borrow the
2240 * contents from the work tree, we always want
2241 * one->mode. mode is trustworthy even when
2242 * !(one->sha1_valid), as long as
2243 * DIFF_FILE_VALID(one).
2245 sprintf(temp->mode, "%06o", one->mode);
2247 return temp;
2249 else {
2250 if (diff_populate_filespec(one, 0))
2251 die("cannot read data blob for %s", one->path);
2252 prep_temp_blob(name, temp, one->data, one->size,
2253 one->sha1, one->mode);
2255 return temp;
2258 /* An external diff command takes:
2260 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2261 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2264 static void run_external_diff(const char *pgm,
2265 const char *name,
2266 const char *other,
2267 struct diff_filespec *one,
2268 struct diff_filespec *two,
2269 const char *xfrm_msg,
2270 int complete_rewrite)
2272 const char *spawn_arg[10];
2273 int retval;
2274 const char **arg = &spawn_arg[0];
2276 if (one && two) {
2277 struct diff_tempfile *temp_one, *temp_two;
2278 const char *othername = (other ? other : name);
2279 temp_one = prepare_temp_file(name, one);
2280 temp_two = prepare_temp_file(othername, two);
2281 *arg++ = pgm;
2282 *arg++ = name;
2283 *arg++ = temp_one->name;
2284 *arg++ = temp_one->hex;
2285 *arg++ = temp_one->mode;
2286 *arg++ = temp_two->name;
2287 *arg++ = temp_two->hex;
2288 *arg++ = temp_two->mode;
2289 if (other) {
2290 *arg++ = other;
2291 *arg++ = xfrm_msg;
2293 } else {
2294 *arg++ = pgm;
2295 *arg++ = name;
2297 *arg = NULL;
2298 fflush(NULL);
2299 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2300 remove_tempfile();
2301 if (retval) {
2302 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2303 exit(1);
2307 static int similarity_index(struct diff_filepair *p)
2309 return p->score * 100 / MAX_SCORE;
2312 static void fill_metainfo(struct strbuf *msg,
2313 const char *name,
2314 const char *other,
2315 struct diff_filespec *one,
2316 struct diff_filespec *two,
2317 struct diff_options *o,
2318 struct diff_filepair *p)
2320 strbuf_init(msg, PATH_MAX * 2 + 300);
2321 switch (p->status) {
2322 case DIFF_STATUS_COPIED:
2323 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2324 strbuf_addstr(msg, "\ncopy from ");
2325 quote_c_style(name, msg, NULL, 0);
2326 strbuf_addstr(msg, "\ncopy to ");
2327 quote_c_style(other, msg, NULL, 0);
2328 strbuf_addch(msg, '\n');
2329 break;
2330 case DIFF_STATUS_RENAMED:
2331 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2332 strbuf_addstr(msg, "\nrename from ");
2333 quote_c_style(name, msg, NULL, 0);
2334 strbuf_addstr(msg, "\nrename to ");
2335 quote_c_style(other, msg, NULL, 0);
2336 strbuf_addch(msg, '\n');
2337 break;
2338 case DIFF_STATUS_MODIFIED:
2339 if (p->score) {
2340 strbuf_addf(msg, "dissimilarity index %d%%\n",
2341 similarity_index(p));
2342 break;
2344 /* fallthru */
2345 default:
2346 /* nothing */
2349 if (one && two && hashcmp(one->sha1, two->sha1)) {
2350 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2352 if (DIFF_OPT_TST(o, BINARY)) {
2353 mmfile_t mf;
2354 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2355 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2356 abbrev = 40;
2358 strbuf_addf(msg, "index %.*s..%.*s",
2359 abbrev, sha1_to_hex(one->sha1),
2360 abbrev, sha1_to_hex(two->sha1));
2361 if (one->mode == two->mode)
2362 strbuf_addf(msg, " %06o", one->mode);
2363 strbuf_addch(msg, '\n');
2365 if (msg->len)
2366 strbuf_setlen(msg, msg->len - 1);
2369 static void run_diff_cmd(const char *pgm,
2370 const char *name,
2371 const char *other,
2372 const char *attr_path,
2373 struct diff_filespec *one,
2374 struct diff_filespec *two,
2375 struct strbuf *msg,
2376 struct diff_options *o,
2377 struct diff_filepair *p)
2379 const char *xfrm_msg = NULL;
2380 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2382 if (msg) {
2383 fill_metainfo(msg, name, other, one, two, o, p);
2384 xfrm_msg = msg->len ? msg->buf : NULL;
2387 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2388 pgm = NULL;
2389 else {
2390 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2391 if (drv && drv->external)
2392 pgm = drv->external;
2395 if (pgm) {
2396 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2397 complete_rewrite);
2398 return;
2400 if (one && two)
2401 builtin_diff(name, other ? other : name,
2402 one, two, xfrm_msg, o, complete_rewrite);
2403 else
2404 fprintf(o->file, "* Unmerged path %s\n", name);
2407 static void diff_fill_sha1_info(struct diff_filespec *one)
2409 if (DIFF_FILE_VALID(one)) {
2410 if (!one->sha1_valid) {
2411 struct stat st;
2412 if (!strcmp(one->path, "-")) {
2413 hashcpy(one->sha1, null_sha1);
2414 return;
2416 if (lstat(one->path, &st) < 0)
2417 die_errno("stat '%s'", one->path);
2418 if (index_path(one->sha1, one->path, &st, 0))
2419 die("cannot hash %s", one->path);
2422 else
2423 hashclr(one->sha1);
2426 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2428 /* Strip the prefix but do not molest /dev/null and absolute paths */
2429 if (*namep && **namep != '/')
2430 *namep += prefix_length;
2431 if (*otherp && **otherp != '/')
2432 *otherp += prefix_length;
2435 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2437 const char *pgm = external_diff();
2438 struct strbuf msg;
2439 struct diff_filespec *one = p->one;
2440 struct diff_filespec *two = p->two;
2441 const char *name;
2442 const char *other;
2443 const char *attr_path;
2445 name = p->one->path;
2446 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2447 attr_path = name;
2448 if (o->prefix_length)
2449 strip_prefix(o->prefix_length, &name, &other);
2451 if (DIFF_PAIR_UNMERGED(p)) {
2452 run_diff_cmd(pgm, name, NULL, attr_path,
2453 NULL, NULL, NULL, o, p);
2454 return;
2457 diff_fill_sha1_info(one);
2458 diff_fill_sha1_info(two);
2460 if (!pgm &&
2461 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2462 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2464 * a filepair that changes between file and symlink
2465 * needs to be split into deletion and creation.
2467 struct diff_filespec *null = alloc_filespec(two->path);
2468 run_diff_cmd(NULL, name, other, attr_path,
2469 one, null, &msg, o, p);
2470 free(null);
2471 strbuf_release(&msg);
2473 null = alloc_filespec(one->path);
2474 run_diff_cmd(NULL, name, other, attr_path,
2475 null, two, &msg, o, p);
2476 free(null);
2478 else
2479 run_diff_cmd(pgm, name, other, attr_path,
2480 one, two, &msg, o, p);
2482 strbuf_release(&msg);
2485 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2486 struct diffstat_t *diffstat)
2488 const char *name;
2489 const char *other;
2490 int complete_rewrite = 0;
2492 if (DIFF_PAIR_UNMERGED(p)) {
2493 /* unmerged */
2494 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2495 return;
2498 name = p->one->path;
2499 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2501 if (o->prefix_length)
2502 strip_prefix(o->prefix_length, &name, &other);
2504 diff_fill_sha1_info(p->one);
2505 diff_fill_sha1_info(p->two);
2507 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2508 complete_rewrite = 1;
2509 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2512 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2514 const char *name;
2515 const char *other;
2516 const char *attr_path;
2518 if (DIFF_PAIR_UNMERGED(p)) {
2519 /* unmerged */
2520 return;
2523 name = p->one->path;
2524 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2525 attr_path = other ? other : name;
2527 if (o->prefix_length)
2528 strip_prefix(o->prefix_length, &name, &other);
2530 diff_fill_sha1_info(p->one);
2531 diff_fill_sha1_info(p->two);
2533 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2536 void diff_setup(struct diff_options *options)
2538 memset(options, 0, sizeof(*options));
2540 options->file = stdout;
2542 options->line_termination = '\n';
2543 options->break_opt = -1;
2544 options->rename_limit = -1;
2545 options->dirstat_percent = 3;
2546 options->context = 3;
2548 options->change = diff_change;
2549 options->add_remove = diff_addremove;
2550 if (diff_use_color_default > 0)
2551 DIFF_OPT_SET(options, COLOR_DIFF);
2552 options->detect_rename = diff_detect_rename_default;
2554 if (!diff_mnemonic_prefix) {
2555 options->a_prefix = "a/";
2556 options->b_prefix = "b/";
2560 int diff_setup_done(struct diff_options *options)
2562 int count = 0;
2564 if (options->output_format & DIFF_FORMAT_NAME)
2565 count++;
2566 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2567 count++;
2568 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2569 count++;
2570 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2571 count++;
2572 if (count > 1)
2573 die("--name-only, --name-status, --check and -s are mutually exclusive");
2576 * Most of the time we can say "there are changes"
2577 * only by checking if there are changed paths, but
2578 * --ignore-whitespace* options force us to look
2579 * inside contents.
2582 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2583 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2584 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2585 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2586 else
2587 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2589 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2590 options->detect_rename = DIFF_DETECT_COPY;
2592 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2593 options->prefix = NULL;
2594 if (options->prefix)
2595 options->prefix_length = strlen(options->prefix);
2596 else
2597 options->prefix_length = 0;
2599 if (options->output_format & (DIFF_FORMAT_NAME |
2600 DIFF_FORMAT_NAME_STATUS |
2601 DIFF_FORMAT_CHECKDIFF |
2602 DIFF_FORMAT_NO_OUTPUT))
2603 options->output_format &= ~(DIFF_FORMAT_RAW |
2604 DIFF_FORMAT_NUMSTAT |
2605 DIFF_FORMAT_DIFFSTAT |
2606 DIFF_FORMAT_SHORTSTAT |
2607 DIFF_FORMAT_DIRSTAT |
2608 DIFF_FORMAT_SUMMARY |
2609 DIFF_FORMAT_PATCH);
2612 * These cases always need recursive; we do not drop caller-supplied
2613 * recursive bits for other formats here.
2615 if (options->output_format & (DIFF_FORMAT_PATCH |
2616 DIFF_FORMAT_NUMSTAT |
2617 DIFF_FORMAT_DIFFSTAT |
2618 DIFF_FORMAT_SHORTSTAT |
2619 DIFF_FORMAT_DIRSTAT |
2620 DIFF_FORMAT_SUMMARY |
2621 DIFF_FORMAT_CHECKDIFF))
2622 DIFF_OPT_SET(options, RECURSIVE);
2624 * Also pickaxe would not work very well if you do not say recursive
2626 if (options->pickaxe)
2627 DIFF_OPT_SET(options, RECURSIVE);
2629 if (options->detect_rename && options->rename_limit < 0)
2630 options->rename_limit = diff_rename_limit_default;
2631 if (options->setup & DIFF_SETUP_USE_CACHE) {
2632 if (!active_cache)
2633 /* read-cache does not die even when it fails
2634 * so it is safe for us to do this here. Also
2635 * it does not smudge active_cache or active_nr
2636 * when it fails, so we do not have to worry about
2637 * cleaning it up ourselves either.
2639 read_cache();
2641 if (options->abbrev <= 0 || 40 < options->abbrev)
2642 options->abbrev = 40; /* full */
2645 * It does not make sense to show the first hit we happened
2646 * to have found. It does not make sense not to return with
2647 * exit code in such a case either.
2649 if (DIFF_OPT_TST(options, QUICK)) {
2650 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2651 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2654 return 0;
2657 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2659 char c, *eq;
2660 int len;
2662 if (*arg != '-')
2663 return 0;
2664 c = *++arg;
2665 if (!c)
2666 return 0;
2667 if (c == arg_short) {
2668 c = *++arg;
2669 if (!c)
2670 return 1;
2671 if (val && isdigit(c)) {
2672 char *end;
2673 int n = strtoul(arg, &end, 10);
2674 if (*end)
2675 return 0;
2676 *val = n;
2677 return 1;
2679 return 0;
2681 if (c != '-')
2682 return 0;
2683 arg++;
2684 eq = strchr(arg, '=');
2685 if (eq)
2686 len = eq - arg;
2687 else
2688 len = strlen(arg);
2689 if (!len || strncmp(arg, arg_long, len))
2690 return 0;
2691 if (eq) {
2692 int n;
2693 char *end;
2694 if (!isdigit(*++eq))
2695 return 0;
2696 n = strtoul(eq, &end, 10);
2697 if (*end)
2698 return 0;
2699 *val = n;
2701 return 1;
2704 static int diff_scoreopt_parse(const char *opt);
2706 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2708 const char *arg = av[0];
2710 /* Output format options */
2711 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2712 options->output_format |= DIFF_FORMAT_PATCH;
2713 else if (opt_arg(arg, 'U', "unified", &options->context))
2714 options->output_format |= DIFF_FORMAT_PATCH;
2715 else if (!strcmp(arg, "--raw"))
2716 options->output_format |= DIFF_FORMAT_RAW;
2717 else if (!strcmp(arg, "--patch-with-raw"))
2718 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2719 else if (!strcmp(arg, "--numstat"))
2720 options->output_format |= DIFF_FORMAT_NUMSTAT;
2721 else if (!strcmp(arg, "--shortstat"))
2722 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2723 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2724 options->output_format |= DIFF_FORMAT_DIRSTAT;
2725 else if (!strcmp(arg, "--cumulative")) {
2726 options->output_format |= DIFF_FORMAT_DIRSTAT;
2727 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2728 } else if (opt_arg(arg, 0, "dirstat-by-file",
2729 &options->dirstat_percent)) {
2730 options->output_format |= DIFF_FORMAT_DIRSTAT;
2731 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2733 else if (!strcmp(arg, "--check"))
2734 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2735 else if (!strcmp(arg, "--summary"))
2736 options->output_format |= DIFF_FORMAT_SUMMARY;
2737 else if (!strcmp(arg, "--patch-with-stat"))
2738 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2739 else if (!strcmp(arg, "--name-only"))
2740 options->output_format |= DIFF_FORMAT_NAME;
2741 else if (!strcmp(arg, "--name-status"))
2742 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2743 else if (!strcmp(arg, "-s"))
2744 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2745 else if (!prefixcmp(arg, "--stat")) {
2746 char *end;
2747 int width = options->stat_width;
2748 int name_width = options->stat_name_width;
2749 arg += 6;
2750 end = (char *)arg;
2752 switch (*arg) {
2753 case '-':
2754 if (!prefixcmp(arg, "-width="))
2755 width = strtoul(arg + 7, &end, 10);
2756 else if (!prefixcmp(arg, "-name-width="))
2757 name_width = strtoul(arg + 12, &end, 10);
2758 break;
2759 case '=':
2760 width = strtoul(arg+1, &end, 10);
2761 if (*end == ',')
2762 name_width = strtoul(end+1, &end, 10);
2765 /* Important! This checks all the error cases! */
2766 if (*end)
2767 return 0;
2768 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2769 options->stat_name_width = name_width;
2770 options->stat_width = width;
2773 /* renames options */
2774 else if (!prefixcmp(arg, "-B")) {
2775 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2776 return -1;
2778 else if (!prefixcmp(arg, "-M")) {
2779 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2780 return -1;
2781 options->detect_rename = DIFF_DETECT_RENAME;
2783 else if (!prefixcmp(arg, "-C")) {
2784 if (options->detect_rename == DIFF_DETECT_COPY)
2785 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2786 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2787 return -1;
2788 options->detect_rename = DIFF_DETECT_COPY;
2790 else if (!strcmp(arg, "--no-renames"))
2791 options->detect_rename = 0;
2792 else if (!strcmp(arg, "--relative"))
2793 DIFF_OPT_SET(options, RELATIVE_NAME);
2794 else if (!prefixcmp(arg, "--relative=")) {
2795 DIFF_OPT_SET(options, RELATIVE_NAME);
2796 options->prefix = arg + 11;
2799 /* xdiff options */
2800 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2801 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2802 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2803 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2804 else if (!strcmp(arg, "--ignore-space-at-eol"))
2805 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2806 else if (!strcmp(arg, "--patience"))
2807 DIFF_XDL_SET(options, PATIENCE_DIFF);
2809 /* flags options */
2810 else if (!strcmp(arg, "--binary")) {
2811 options->output_format |= DIFF_FORMAT_PATCH;
2812 DIFF_OPT_SET(options, BINARY);
2814 else if (!strcmp(arg, "--full-index"))
2815 DIFF_OPT_SET(options, FULL_INDEX);
2816 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2817 DIFF_OPT_SET(options, TEXT);
2818 else if (!strcmp(arg, "-R"))
2819 DIFF_OPT_SET(options, REVERSE_DIFF);
2820 else if (!strcmp(arg, "--find-copies-harder"))
2821 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2822 else if (!strcmp(arg, "--follow"))
2823 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2824 else if (!strcmp(arg, "--color"))
2825 DIFF_OPT_SET(options, COLOR_DIFF);
2826 else if (!strcmp(arg, "--no-color"))
2827 DIFF_OPT_CLR(options, COLOR_DIFF);
2828 else if (!strcmp(arg, "--color-words")) {
2829 DIFF_OPT_SET(options, COLOR_DIFF);
2830 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2832 else if (!prefixcmp(arg, "--color-words=")) {
2833 DIFF_OPT_SET(options, COLOR_DIFF);
2834 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2835 options->word_regex = arg + 14;
2837 else if (!strcmp(arg, "--exit-code"))
2838 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2839 else if (!strcmp(arg, "--quiet"))
2840 DIFF_OPT_SET(options, QUICK);
2841 else if (!strcmp(arg, "--ext-diff"))
2842 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2843 else if (!strcmp(arg, "--no-ext-diff"))
2844 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2845 else if (!strcmp(arg, "--textconv"))
2846 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2847 else if (!strcmp(arg, "--no-textconv"))
2848 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2849 else if (!strcmp(arg, "--ignore-submodules"))
2850 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2851 else if (!strcmp(arg, "--submodule"))
2852 DIFF_OPT_SET(options, SUBMODULE_LOG);
2853 else if (!prefixcmp(arg, "--submodule=")) {
2854 if (!strcmp(arg + 12, "log"))
2855 DIFF_OPT_SET(options, SUBMODULE_LOG);
2858 /* misc options */
2859 else if (!strcmp(arg, "-z"))
2860 options->line_termination = 0;
2861 else if (!prefixcmp(arg, "-l"))
2862 options->rename_limit = strtoul(arg+2, NULL, 10);
2863 else if (!prefixcmp(arg, "-S"))
2864 options->pickaxe = arg + 2;
2865 else if (!strcmp(arg, "--pickaxe-all"))
2866 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2867 else if (!strcmp(arg, "--pickaxe-regex"))
2868 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2869 else if (!prefixcmp(arg, "-O"))
2870 options->orderfile = arg + 2;
2871 else if (!prefixcmp(arg, "--diff-filter="))
2872 options->filter = arg + 14;
2873 else if (!strcmp(arg, "--abbrev"))
2874 options->abbrev = DEFAULT_ABBREV;
2875 else if (!prefixcmp(arg, "--abbrev=")) {
2876 options->abbrev = strtoul(arg + 9, NULL, 10);
2877 if (options->abbrev < MINIMUM_ABBREV)
2878 options->abbrev = MINIMUM_ABBREV;
2879 else if (40 < options->abbrev)
2880 options->abbrev = 40;
2882 else if (!prefixcmp(arg, "--src-prefix="))
2883 options->a_prefix = arg + 13;
2884 else if (!prefixcmp(arg, "--dst-prefix="))
2885 options->b_prefix = arg + 13;
2886 else if (!strcmp(arg, "--no-prefix"))
2887 options->a_prefix = options->b_prefix = "";
2888 else if (opt_arg(arg, '\0', "inter-hunk-context",
2889 &options->interhunkcontext))
2891 else if (!prefixcmp(arg, "--output=")) {
2892 options->file = fopen(arg + strlen("--output="), "w");
2893 if (!options->file)
2894 die_errno("Could not open '%s'", arg + strlen("--output="));
2895 options->close_file = 1;
2896 } else
2897 return 0;
2898 return 1;
2901 static int parse_num(const char **cp_p)
2903 unsigned long num, scale;
2904 int ch, dot;
2905 const char *cp = *cp_p;
2907 num = 0;
2908 scale = 1;
2909 dot = 0;
2910 for (;;) {
2911 ch = *cp;
2912 if ( !dot && ch == '.' ) {
2913 scale = 1;
2914 dot = 1;
2915 } else if ( ch == '%' ) {
2916 scale = dot ? scale*100 : 100;
2917 cp++; /* % is always at the end */
2918 break;
2919 } else if ( ch >= '0' && ch <= '9' ) {
2920 if ( scale < 100000 ) {
2921 scale *= 10;
2922 num = (num*10) + (ch-'0');
2924 } else {
2925 break;
2927 cp++;
2929 *cp_p = cp;
2931 /* user says num divided by scale and we say internally that
2932 * is MAX_SCORE * num / scale.
2934 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2937 static int diff_scoreopt_parse(const char *opt)
2939 int opt1, opt2, cmd;
2941 if (*opt++ != '-')
2942 return -1;
2943 cmd = *opt++;
2944 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2945 return -1; /* that is not a -M, -C nor -B option */
2947 opt1 = parse_num(&opt);
2948 if (cmd != 'B')
2949 opt2 = 0;
2950 else {
2951 if (*opt == 0)
2952 opt2 = 0;
2953 else if (*opt != '/')
2954 return -1; /* we expect -B80/99 or -B80 */
2955 else {
2956 opt++;
2957 opt2 = parse_num(&opt);
2960 if (*opt != 0)
2961 return -1;
2962 return opt1 | (opt2 << 16);
2965 struct diff_queue_struct diff_queued_diff;
2967 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2969 if (queue->alloc <= queue->nr) {
2970 queue->alloc = alloc_nr(queue->alloc);
2971 queue->queue = xrealloc(queue->queue,
2972 sizeof(dp) * queue->alloc);
2974 queue->queue[queue->nr++] = dp;
2977 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2978 struct diff_filespec *one,
2979 struct diff_filespec *two)
2981 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2982 dp->one = one;
2983 dp->two = two;
2984 if (queue)
2985 diff_q(queue, dp);
2986 return dp;
2989 void diff_free_filepair(struct diff_filepair *p)
2991 free_filespec(p->one);
2992 free_filespec(p->two);
2993 free(p);
2996 /* This is different from find_unique_abbrev() in that
2997 * it stuffs the result with dots for alignment.
2999 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3001 int abblen;
3002 const char *abbrev;
3003 if (len == 40)
3004 return sha1_to_hex(sha1);
3006 abbrev = find_unique_abbrev(sha1, len);
3007 abblen = strlen(abbrev);
3008 if (abblen < 37) {
3009 static char hex[41];
3010 if (len < abblen && abblen <= len + 2)
3011 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3012 else
3013 sprintf(hex, "%s...", abbrev);
3014 return hex;
3016 return sha1_to_hex(sha1);
3019 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3021 int line_termination = opt->line_termination;
3022 int inter_name_termination = line_termination ? '\t' : '\0';
3024 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3025 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3026 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3027 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3029 if (p->score) {
3030 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3031 inter_name_termination);
3032 } else {
3033 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3036 if (p->status == DIFF_STATUS_COPIED ||
3037 p->status == DIFF_STATUS_RENAMED) {
3038 const char *name_a, *name_b;
3039 name_a = p->one->path;
3040 name_b = p->two->path;
3041 strip_prefix(opt->prefix_length, &name_a, &name_b);
3042 write_name_quoted(name_a, opt->file, inter_name_termination);
3043 write_name_quoted(name_b, opt->file, line_termination);
3044 } else {
3045 const char *name_a, *name_b;
3046 name_a = p->one->mode ? p->one->path : p->two->path;
3047 name_b = NULL;
3048 strip_prefix(opt->prefix_length, &name_a, &name_b);
3049 write_name_quoted(name_a, opt->file, line_termination);
3053 int diff_unmodified_pair(struct diff_filepair *p)
3055 /* This function is written stricter than necessary to support
3056 * the currently implemented transformers, but the idea is to
3057 * let transformers to produce diff_filepairs any way they want,
3058 * and filter and clean them up here before producing the output.
3060 struct diff_filespec *one = p->one, *two = p->two;
3062 if (DIFF_PAIR_UNMERGED(p))
3063 return 0; /* unmerged is interesting */
3065 /* deletion, addition, mode or type change
3066 * and rename are all interesting.
3068 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3069 DIFF_PAIR_MODE_CHANGED(p) ||
3070 strcmp(one->path, two->path))
3071 return 0;
3073 /* both are valid and point at the same path. that is, we are
3074 * dealing with a change.
3076 if (one->sha1_valid && two->sha1_valid &&
3077 !hashcmp(one->sha1, two->sha1))
3078 return 1; /* no change */
3079 if (!one->sha1_valid && !two->sha1_valid)
3080 return 1; /* both look at the same file on the filesystem. */
3081 return 0;
3084 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3086 if (diff_unmodified_pair(p))
3087 return;
3089 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3090 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3091 return; /* no tree diffs in patch format */
3093 run_diff(p, o);
3096 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3097 struct diffstat_t *diffstat)
3099 if (diff_unmodified_pair(p))
3100 return;
3102 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3103 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3104 return; /* no tree diffs in patch format */
3106 run_diffstat(p, o, diffstat);
3109 static void diff_flush_checkdiff(struct diff_filepair *p,
3110 struct diff_options *o)
3112 if (diff_unmodified_pair(p))
3113 return;
3115 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3116 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3117 return; /* no tree diffs in patch format */
3119 run_checkdiff(p, o);
3122 int diff_queue_is_empty(void)
3124 struct diff_queue_struct *q = &diff_queued_diff;
3125 int i;
3126 for (i = 0; i < q->nr; i++)
3127 if (!diff_unmodified_pair(q->queue[i]))
3128 return 0;
3129 return 1;
3132 #if DIFF_DEBUG
3133 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3135 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3136 x, one ? one : "",
3137 s->path,
3138 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3139 s->mode,
3140 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3141 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3142 x, one ? one : "",
3143 s->size, s->xfrm_flags);
3146 void diff_debug_filepair(const struct diff_filepair *p, int i)
3148 diff_debug_filespec(p->one, i, "one");
3149 diff_debug_filespec(p->two, i, "two");
3150 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3151 p->score, p->status ? p->status : '?',
3152 p->one->rename_used, p->broken_pair);
3155 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3157 int i;
3158 if (msg)
3159 fprintf(stderr, "%s\n", msg);
3160 fprintf(stderr, "q->nr = %d\n", q->nr);
3161 for (i = 0; i < q->nr; i++) {
3162 struct diff_filepair *p = q->queue[i];
3163 diff_debug_filepair(p, i);
3166 #endif
3168 static void diff_resolve_rename_copy(void)
3170 int i;
3171 struct diff_filepair *p;
3172 struct diff_queue_struct *q = &diff_queued_diff;
3174 diff_debug_queue("resolve-rename-copy", q);
3176 for (i = 0; i < q->nr; i++) {
3177 p = q->queue[i];
3178 p->status = 0; /* undecided */
3179 if (DIFF_PAIR_UNMERGED(p))
3180 p->status = DIFF_STATUS_UNMERGED;
3181 else if (!DIFF_FILE_VALID(p->one))
3182 p->status = DIFF_STATUS_ADDED;
3183 else if (!DIFF_FILE_VALID(p->two))
3184 p->status = DIFF_STATUS_DELETED;
3185 else if (DIFF_PAIR_TYPE_CHANGED(p))
3186 p->status = DIFF_STATUS_TYPE_CHANGED;
3188 /* from this point on, we are dealing with a pair
3189 * whose both sides are valid and of the same type, i.e.
3190 * either in-place edit or rename/copy edit.
3192 else if (DIFF_PAIR_RENAME(p)) {
3194 * A rename might have re-connected a broken
3195 * pair up, causing the pathnames to be the
3196 * same again. If so, that's not a rename at
3197 * all, just a modification..
3199 * Otherwise, see if this source was used for
3200 * multiple renames, in which case we decrement
3201 * the count, and call it a copy.
3203 if (!strcmp(p->one->path, p->two->path))
3204 p->status = DIFF_STATUS_MODIFIED;
3205 else if (--p->one->rename_used > 0)
3206 p->status = DIFF_STATUS_COPIED;
3207 else
3208 p->status = DIFF_STATUS_RENAMED;
3210 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3211 p->one->mode != p->two->mode ||
3212 is_null_sha1(p->one->sha1))
3213 p->status = DIFF_STATUS_MODIFIED;
3214 else {
3215 /* This is a "no-change" entry and should not
3216 * happen anymore, but prepare for broken callers.
3218 error("feeding unmodified %s to diffcore",
3219 p->one->path);
3220 p->status = DIFF_STATUS_UNKNOWN;
3223 diff_debug_queue("resolve-rename-copy done", q);
3226 static int check_pair_status(struct diff_filepair *p)
3228 switch (p->status) {
3229 case DIFF_STATUS_UNKNOWN:
3230 return 0;
3231 case 0:
3232 die("internal error in diff-resolve-rename-copy");
3233 default:
3234 return 1;
3238 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3240 int fmt = opt->output_format;
3242 if (fmt & DIFF_FORMAT_CHECKDIFF)
3243 diff_flush_checkdiff(p, opt);
3244 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3245 diff_flush_raw(p, opt);
3246 else if (fmt & DIFF_FORMAT_NAME) {
3247 const char *name_a, *name_b;
3248 name_a = p->two->path;
3249 name_b = NULL;
3250 strip_prefix(opt->prefix_length, &name_a, &name_b);
3251 write_name_quoted(name_a, opt->file, opt->line_termination);
3255 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3257 if (fs->mode)
3258 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3259 else
3260 fprintf(file, " %s ", newdelete);
3261 write_name_quoted(fs->path, file, '\n');
3265 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3267 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3268 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3269 show_name ? ' ' : '\n');
3270 if (show_name) {
3271 write_name_quoted(p->two->path, file, '\n');
3276 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3278 char *names = pprint_rename(p->one->path, p->two->path);
3280 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3281 free(names);
3282 show_mode_change(file, p, 0);
3285 static void diff_summary(FILE *file, struct diff_filepair *p)
3287 switch(p->status) {
3288 case DIFF_STATUS_DELETED:
3289 show_file_mode_name(file, "delete", p->one);
3290 break;
3291 case DIFF_STATUS_ADDED:
3292 show_file_mode_name(file, "create", p->two);
3293 break;
3294 case DIFF_STATUS_COPIED:
3295 show_rename_copy(file, "copy", p);
3296 break;
3297 case DIFF_STATUS_RENAMED:
3298 show_rename_copy(file, "rename", p);
3299 break;
3300 default:
3301 if (p->score) {
3302 fputs(" rewrite ", file);
3303 write_name_quoted(p->two->path, file, ' ');
3304 fprintf(file, "(%d%%)\n", similarity_index(p));
3306 show_mode_change(file, p, !p->score);
3307 break;
3311 struct patch_id_t {
3312 git_SHA_CTX *ctx;
3313 int patchlen;
3316 static int remove_space(char *line, int len)
3318 int i;
3319 char *dst = line;
3320 unsigned char c;
3322 for (i = 0; i < len; i++)
3323 if (!isspace((c = line[i])))
3324 *dst++ = c;
3326 return dst - line;
3329 static void patch_id_consume(void *priv, char *line, unsigned long len)
3331 struct patch_id_t *data = priv;
3332 int new_len;
3334 /* Ignore line numbers when computing the SHA1 of the patch */
3335 if (!prefixcmp(line, "@@ -"))
3336 return;
3338 new_len = remove_space(line, len);
3340 git_SHA1_Update(data->ctx, line, new_len);
3341 data->patchlen += new_len;
3344 /* returns 0 upon success, and writes result into sha1 */
3345 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3347 struct diff_queue_struct *q = &diff_queued_diff;
3348 int i;
3349 git_SHA_CTX ctx;
3350 struct patch_id_t data;
3351 char buffer[PATH_MAX * 4 + 20];
3353 git_SHA1_Init(&ctx);
3354 memset(&data, 0, sizeof(struct patch_id_t));
3355 data.ctx = &ctx;
3357 for (i = 0; i < q->nr; i++) {
3358 xpparam_t xpp;
3359 xdemitconf_t xecfg;
3360 mmfile_t mf1, mf2;
3361 struct diff_filepair *p = q->queue[i];
3362 int len1, len2;
3364 memset(&xpp, 0, sizeof(xpp));
3365 memset(&xecfg, 0, sizeof(xecfg));
3366 if (p->status == 0)
3367 return error("internal diff status error");
3368 if (p->status == DIFF_STATUS_UNKNOWN)
3369 continue;
3370 if (diff_unmodified_pair(p))
3371 continue;
3372 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3373 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3374 continue;
3375 if (DIFF_PAIR_UNMERGED(p))
3376 continue;
3378 diff_fill_sha1_info(p->one);
3379 diff_fill_sha1_info(p->two);
3380 if (fill_mmfile(&mf1, p->one) < 0 ||
3381 fill_mmfile(&mf2, p->two) < 0)
3382 return error("unable to read files to diff");
3384 len1 = remove_space(p->one->path, strlen(p->one->path));
3385 len2 = remove_space(p->two->path, strlen(p->two->path));
3386 if (p->one->mode == 0)
3387 len1 = snprintf(buffer, sizeof(buffer),
3388 "diff--gita/%.*sb/%.*s"
3389 "newfilemode%06o"
3390 "---/dev/null"
3391 "+++b/%.*s",
3392 len1, p->one->path,
3393 len2, p->two->path,
3394 p->two->mode,
3395 len2, p->two->path);
3396 else if (p->two->mode == 0)
3397 len1 = snprintf(buffer, sizeof(buffer),
3398 "diff--gita/%.*sb/%.*s"
3399 "deletedfilemode%06o"
3400 "---a/%.*s"
3401 "+++/dev/null",
3402 len1, p->one->path,
3403 len2, p->two->path,
3404 p->one->mode,
3405 len1, p->one->path);
3406 else
3407 len1 = snprintf(buffer, sizeof(buffer),
3408 "diff--gita/%.*sb/%.*s"
3409 "---a/%.*s"
3410 "+++b/%.*s",
3411 len1, p->one->path,
3412 len2, p->two->path,
3413 len1, p->one->path,
3414 len2, p->two->path);
3415 git_SHA1_Update(&ctx, buffer, len1);
3417 xpp.flags = XDF_NEED_MINIMAL;
3418 xecfg.ctxlen = 3;
3419 xecfg.flags = XDL_EMIT_FUNCNAMES;
3420 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3421 &xpp, &xecfg);
3424 git_SHA1_Final(sha1, &ctx);
3425 return 0;
3428 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3430 struct diff_queue_struct *q = &diff_queued_diff;
3431 int i;
3432 int result = diff_get_patch_id(options, sha1);
3434 for (i = 0; i < q->nr; i++)
3435 diff_free_filepair(q->queue[i]);
3437 free(q->queue);
3438 q->queue = NULL;
3439 q->nr = q->alloc = 0;
3441 return result;
3444 static int is_summary_empty(const struct diff_queue_struct *q)
3446 int i;
3448 for (i = 0; i < q->nr; i++) {
3449 const struct diff_filepair *p = q->queue[i];
3451 switch (p->status) {
3452 case DIFF_STATUS_DELETED:
3453 case DIFF_STATUS_ADDED:
3454 case DIFF_STATUS_COPIED:
3455 case DIFF_STATUS_RENAMED:
3456 return 0;
3457 default:
3458 if (p->score)
3459 return 0;
3460 if (p->one->mode && p->two->mode &&
3461 p->one->mode != p->two->mode)
3462 return 0;
3463 break;
3466 return 1;
3469 void diff_flush(struct diff_options *options)
3471 struct diff_queue_struct *q = &diff_queued_diff;
3472 int i, output_format = options->output_format;
3473 int separator = 0;
3476 * Order: raw, stat, summary, patch
3477 * or: name/name-status/checkdiff (other bits clear)
3479 if (!q->nr)
3480 goto free_queue;
3482 if (output_format & (DIFF_FORMAT_RAW |
3483 DIFF_FORMAT_NAME |
3484 DIFF_FORMAT_NAME_STATUS |
3485 DIFF_FORMAT_CHECKDIFF)) {
3486 for (i = 0; i < q->nr; i++) {
3487 struct diff_filepair *p = q->queue[i];
3488 if (check_pair_status(p))
3489 flush_one_pair(p, options);
3491 separator++;
3494 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3495 struct diffstat_t diffstat;
3497 memset(&diffstat, 0, sizeof(struct diffstat_t));
3498 for (i = 0; i < q->nr; i++) {
3499 struct diff_filepair *p = q->queue[i];
3500 if (check_pair_status(p))
3501 diff_flush_stat(p, options, &diffstat);
3503 if (output_format & DIFF_FORMAT_NUMSTAT)
3504 show_numstat(&diffstat, options);
3505 if (output_format & DIFF_FORMAT_DIFFSTAT)
3506 show_stats(&diffstat, options);
3507 if (output_format & DIFF_FORMAT_SHORTSTAT)
3508 show_shortstats(&diffstat, options);
3509 free_diffstat_info(&diffstat);
3510 separator++;
3512 if (output_format & DIFF_FORMAT_DIRSTAT)
3513 show_dirstat(options);
3515 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3516 for (i = 0; i < q->nr; i++)
3517 diff_summary(options->file, q->queue[i]);
3518 separator++;
3521 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
3522 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
3523 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3525 * run diff_flush_patch for the exit status. setting
3526 * options->file to /dev/null should be safe, becaue we
3527 * aren't supposed to produce any output anyway.
3529 if (options->close_file)
3530 fclose(options->file);
3531 options->file = fopen("/dev/null", "w");
3532 if (!options->file)
3533 die_errno("Could not open /dev/null");
3534 options->close_file = 1;
3535 for (i = 0; i < q->nr; i++) {
3536 struct diff_filepair *p = q->queue[i];
3537 if (check_pair_status(p))
3538 diff_flush_patch(p, options);
3539 if (options->found_changes)
3540 break;
3544 if (output_format & DIFF_FORMAT_PATCH) {
3545 if (separator) {
3546 putc(options->line_termination, options->file);
3547 if (options->stat_sep) {
3548 /* attach patch instead of inline */
3549 fputs(options->stat_sep, options->file);
3553 for (i = 0; i < q->nr; i++) {
3554 struct diff_filepair *p = q->queue[i];
3555 if (check_pair_status(p))
3556 diff_flush_patch(p, options);
3560 if (output_format & DIFF_FORMAT_CALLBACK)
3561 options->format_callback(q, options, options->format_callback_data);
3563 for (i = 0; i < q->nr; i++)
3564 diff_free_filepair(q->queue[i]);
3565 free_queue:
3566 free(q->queue);
3567 q->queue = NULL;
3568 q->nr = q->alloc = 0;
3569 if (options->close_file)
3570 fclose(options->file);
3573 * Report the content-level differences with HAS_CHANGES;
3574 * diff_addremove/diff_change does not set the bit when
3575 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3577 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3578 if (options->found_changes)
3579 DIFF_OPT_SET(options, HAS_CHANGES);
3580 else
3581 DIFF_OPT_CLR(options, HAS_CHANGES);
3585 static void diffcore_apply_filter(const char *filter)
3587 int i;
3588 struct diff_queue_struct *q = &diff_queued_diff;
3589 struct diff_queue_struct outq;
3590 outq.queue = NULL;
3591 outq.nr = outq.alloc = 0;
3593 if (!filter)
3594 return;
3596 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3597 int found;
3598 for (i = found = 0; !found && i < q->nr; i++) {
3599 struct diff_filepair *p = q->queue[i];
3600 if (((p->status == DIFF_STATUS_MODIFIED) &&
3601 ((p->score &&
3602 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3603 (!p->score &&
3604 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3605 ((p->status != DIFF_STATUS_MODIFIED) &&
3606 strchr(filter, p->status)))
3607 found++;
3609 if (found)
3610 return;
3612 /* otherwise we will clear the whole queue
3613 * by copying the empty outq at the end of this
3614 * function, but first clear the current entries
3615 * in the queue.
3617 for (i = 0; i < q->nr; i++)
3618 diff_free_filepair(q->queue[i]);
3620 else {
3621 /* Only the matching ones */
3622 for (i = 0; i < q->nr; i++) {
3623 struct diff_filepair *p = q->queue[i];
3625 if (((p->status == DIFF_STATUS_MODIFIED) &&
3626 ((p->score &&
3627 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3628 (!p->score &&
3629 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3630 ((p->status != DIFF_STATUS_MODIFIED) &&
3631 strchr(filter, p->status)))
3632 diff_q(&outq, p);
3633 else
3634 diff_free_filepair(p);
3637 free(q->queue);
3638 *q = outq;
3641 /* Check whether two filespecs with the same mode and size are identical */
3642 static int diff_filespec_is_identical(struct diff_filespec *one,
3643 struct diff_filespec *two)
3645 if (S_ISGITLINK(one->mode))
3646 return 0;
3647 if (diff_populate_filespec(one, 0))
3648 return 0;
3649 if (diff_populate_filespec(two, 0))
3650 return 0;
3651 return !memcmp(one->data, two->data, one->size);
3654 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3656 int i;
3657 struct diff_queue_struct *q = &diff_queued_diff;
3658 struct diff_queue_struct outq;
3659 outq.queue = NULL;
3660 outq.nr = outq.alloc = 0;
3662 for (i = 0; i < q->nr; i++) {
3663 struct diff_filepair *p = q->queue[i];
3666 * 1. Entries that come from stat info dirtiness
3667 * always have both sides (iow, not create/delete),
3668 * one side of the object name is unknown, with
3669 * the same mode and size. Keep the ones that
3670 * do not match these criteria. They have real
3671 * differences.
3673 * 2. At this point, the file is known to be modified,
3674 * with the same mode and size, and the object
3675 * name of one side is unknown. Need to inspect
3676 * the identical contents.
3678 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3679 !DIFF_FILE_VALID(p->two) ||
3680 (p->one->sha1_valid && p->two->sha1_valid) ||
3681 (p->one->mode != p->two->mode) ||
3682 diff_populate_filespec(p->one, 1) ||
3683 diff_populate_filespec(p->two, 1) ||
3684 (p->one->size != p->two->size) ||
3685 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3686 diff_q(&outq, p);
3687 else {
3689 * The caller can subtract 1 from skip_stat_unmatch
3690 * to determine how many paths were dirty only
3691 * due to stat info mismatch.
3693 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3694 diffopt->skip_stat_unmatch++;
3695 diff_free_filepair(p);
3698 free(q->queue);
3699 *q = outq;
3702 static int diffnamecmp(const void *a_, const void *b_)
3704 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
3705 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
3706 const char *name_a, *name_b;
3708 name_a = a->one ? a->one->path : a->two->path;
3709 name_b = b->one ? b->one->path : b->two->path;
3710 return strcmp(name_a, name_b);
3713 void diffcore_fix_diff_index(struct diff_options *options)
3715 struct diff_queue_struct *q = &diff_queued_diff;
3716 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
3719 void diffcore_std(struct diff_options *options)
3721 if (options->skip_stat_unmatch)
3722 diffcore_skip_stat_unmatch(options);
3723 if (options->break_opt != -1)
3724 diffcore_break(options->break_opt);
3725 if (options->detect_rename)
3726 diffcore_rename(options);
3727 if (options->break_opt != -1)
3728 diffcore_merge_broken();
3729 if (options->pickaxe)
3730 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3731 if (options->orderfile)
3732 diffcore_order(options->orderfile);
3733 diff_resolve_rename_copy();
3734 diffcore_apply_filter(options->filter);
3736 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3737 DIFF_OPT_SET(options, HAS_CHANGES);
3738 else
3739 DIFF_OPT_CLR(options, HAS_CHANGES);
3742 int diff_result_code(struct diff_options *opt, int status)
3744 int result = 0;
3745 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3746 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3747 return status;
3748 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3749 DIFF_OPT_TST(opt, HAS_CHANGES))
3750 result |= 01;
3751 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3752 DIFF_OPT_TST(opt, CHECK_FAILED))
3753 result |= 02;
3754 return result;
3757 void diff_addremove(struct diff_options *options,
3758 int addremove, unsigned mode,
3759 const unsigned char *sha1,
3760 const char *concatpath, unsigned dirty_submodule)
3762 struct diff_filespec *one, *two;
3764 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3765 return;
3767 /* This may look odd, but it is a preparation for
3768 * feeding "there are unchanged files which should
3769 * not produce diffs, but when you are doing copy
3770 * detection you would need them, so here they are"
3771 * entries to the diff-core. They will be prefixed
3772 * with something like '=' or '*' (I haven't decided
3773 * which but should not make any difference).
3774 * Feeding the same new and old to diff_change()
3775 * also has the same effect.
3776 * Before the final output happens, they are pruned after
3777 * merged into rename/copy pairs as appropriate.
3779 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3780 addremove = (addremove == '+' ? '-' :
3781 addremove == '-' ? '+' : addremove);
3783 if (options->prefix &&
3784 strncmp(concatpath, options->prefix, options->prefix_length))
3785 return;
3787 one = alloc_filespec(concatpath);
3788 two = alloc_filespec(concatpath);
3790 if (addremove != '+')
3791 fill_filespec(one, sha1, mode);
3792 if (addremove != '-') {
3793 fill_filespec(two, sha1, mode);
3794 two->dirty_submodule = dirty_submodule;
3797 diff_queue(&diff_queued_diff, one, two);
3798 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3799 DIFF_OPT_SET(options, HAS_CHANGES);
3802 void diff_change(struct diff_options *options,
3803 unsigned old_mode, unsigned new_mode,
3804 const unsigned char *old_sha1,
3805 const unsigned char *new_sha1,
3806 const char *concatpath,
3807 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
3809 struct diff_filespec *one, *two;
3811 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3812 && S_ISGITLINK(new_mode))
3813 return;
3815 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3816 unsigned tmp;
3817 const unsigned char *tmp_c;
3818 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3819 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3820 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
3821 new_dirty_submodule = tmp;
3824 if (options->prefix &&
3825 strncmp(concatpath, options->prefix, options->prefix_length))
3826 return;
3828 one = alloc_filespec(concatpath);
3829 two = alloc_filespec(concatpath);
3830 fill_filespec(one, old_sha1, old_mode);
3831 fill_filespec(two, new_sha1, new_mode);
3832 one->dirty_submodule = old_dirty_submodule;
3833 two->dirty_submodule = new_dirty_submodule;
3835 diff_queue(&diff_queued_diff, one, two);
3836 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3837 DIFF_OPT_SET(options, HAS_CHANGES);
3840 void diff_unmerge(struct diff_options *options,
3841 const char *path,
3842 unsigned mode, const unsigned char *sha1)
3844 struct diff_filespec *one, *two;
3846 if (options->prefix &&
3847 strncmp(path, options->prefix, options->prefix_length))
3848 return;
3850 one = alloc_filespec(path);
3851 two = alloc_filespec(path);
3852 fill_filespec(one, sha1, mode);
3853 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3856 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3857 size_t *outsize)
3859 struct diff_tempfile *temp;
3860 const char *argv[3];
3861 const char **arg = argv;
3862 struct child_process child;
3863 struct strbuf buf = STRBUF_INIT;
3864 int err = 0;
3866 temp = prepare_temp_file(spec->path, spec);
3867 *arg++ = pgm;
3868 *arg++ = temp->name;
3869 *arg = NULL;
3871 memset(&child, 0, sizeof(child));
3872 child.use_shell = 1;
3873 child.argv = argv;
3874 child.out = -1;
3875 if (start_command(&child)) {
3876 remove_tempfile();
3877 return NULL;
3880 if (strbuf_read(&buf, child.out, 0) < 0)
3881 err = error("error reading from textconv command '%s'", pgm);
3882 close(child.out);
3884 if (finish_command(&child) || err) {
3885 strbuf_release(&buf);
3886 remove_tempfile();
3887 return NULL;
3889 remove_tempfile();
3891 return strbuf_detach(&buf, outsize);