Merge branch 'jk/am-skip-hint'
[git.git] / diff.c
blobb53b6ec8e2ced8c94c0353dddf07ca5c1dd79978
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;
33 static int diff_no_prefix;
35 static char diff_colors[][COLOR_MAXLEN] = {
36 GIT_COLOR_RESET,
37 GIT_COLOR_NORMAL, /* PLAIN */
38 GIT_COLOR_BOLD, /* METAINFO */
39 GIT_COLOR_CYAN, /* FRAGINFO */
40 GIT_COLOR_RED, /* OLD */
41 GIT_COLOR_GREEN, /* NEW */
42 GIT_COLOR_YELLOW, /* COMMIT */
43 GIT_COLOR_BG_RED, /* WHITESPACE */
44 GIT_COLOR_NORMAL, /* FUNCINFO */
47 static void diff_filespec_load_driver(struct diff_filespec *one);
48 static size_t fill_textconv(struct userdiff_driver *driver,
49 struct diff_filespec *df, char **outbuf);
51 static int parse_diff_color_slot(const char *var, int ofs)
53 if (!strcasecmp(var+ofs, "plain"))
54 return DIFF_PLAIN;
55 if (!strcasecmp(var+ofs, "meta"))
56 return DIFF_METAINFO;
57 if (!strcasecmp(var+ofs, "frag"))
58 return DIFF_FRAGINFO;
59 if (!strcasecmp(var+ofs, "old"))
60 return DIFF_FILE_OLD;
61 if (!strcasecmp(var+ofs, "new"))
62 return DIFF_FILE_NEW;
63 if (!strcasecmp(var+ofs, "commit"))
64 return DIFF_COMMIT;
65 if (!strcasecmp(var+ofs, "whitespace"))
66 return DIFF_WHITESPACE;
67 if (!strcasecmp(var+ofs, "func"))
68 return DIFF_FUNCINFO;
69 return -1;
72 static int git_config_rename(const char *var, const char *value)
74 if (!value)
75 return DIFF_DETECT_RENAME;
76 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
77 return DIFF_DETECT_COPY;
78 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
82 * These are to give UI layer defaults.
83 * The core-level commands such as git-diff-files should
84 * never be affected by the setting of diff.renames
85 * the user happens to have in the configuration file.
87 int git_diff_ui_config(const char *var, const char *value, void *cb)
89 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
90 diff_use_color_default = git_config_colorbool(var, value, -1);
91 return 0;
93 if (!strcmp(var, "diff.renames")) {
94 diff_detect_rename_default = git_config_rename(var, value);
95 return 0;
97 if (!strcmp(var, "diff.autorefreshindex")) {
98 diff_auto_refresh_index = git_config_bool(var, value);
99 return 0;
101 if (!strcmp(var, "diff.mnemonicprefix")) {
102 diff_mnemonic_prefix = git_config_bool(var, value);
103 return 0;
105 if (!strcmp(var, "diff.noprefix")) {
106 diff_no_prefix = git_config_bool(var, value);
107 return 0;
109 if (!strcmp(var, "diff.external"))
110 return git_config_string(&external_diff_cmd_cfg, var, value);
111 if (!strcmp(var, "diff.wordregex"))
112 return git_config_string(&diff_word_regex_cfg, var, value);
114 return git_diff_basic_config(var, value, cb);
117 int git_diff_basic_config(const char *var, const char *value, void *cb)
119 if (!strcmp(var, "diff.renamelimit")) {
120 diff_rename_limit_default = git_config_int(var, value);
121 return 0;
124 switch (userdiff_config(var, value)) {
125 case 0: break;
126 case -1: return -1;
127 default: return 0;
130 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
131 int slot = parse_diff_color_slot(var, 11);
132 if (slot < 0)
133 return 0;
134 if (!value)
135 return config_error_nonbool(var);
136 color_parse(value, var, diff_colors[slot]);
137 return 0;
140 /* like GNU diff's --suppress-blank-empty option */
141 if (!strcmp(var, "diff.suppressblankempty") ||
142 /* for backwards compatibility */
143 !strcmp(var, "diff.suppress-blank-empty")) {
144 diff_suppress_blank_empty = git_config_bool(var, value);
145 return 0;
148 return git_color_default_config(var, value, cb);
151 static char *quote_two(const char *one, const char *two)
153 int need_one = quote_c_style(one, NULL, NULL, 1);
154 int need_two = quote_c_style(two, NULL, NULL, 1);
155 struct strbuf res = STRBUF_INIT;
157 if (need_one + need_two) {
158 strbuf_addch(&res, '"');
159 quote_c_style(one, &res, NULL, 1);
160 quote_c_style(two, &res, NULL, 1);
161 strbuf_addch(&res, '"');
162 } else {
163 strbuf_addstr(&res, one);
164 strbuf_addstr(&res, two);
166 return strbuf_detach(&res, NULL);
169 static const char *external_diff(void)
171 static const char *external_diff_cmd = NULL;
172 static int done_preparing = 0;
174 if (done_preparing)
175 return external_diff_cmd;
176 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
177 if (!external_diff_cmd)
178 external_diff_cmd = external_diff_cmd_cfg;
179 done_preparing = 1;
180 return external_diff_cmd;
183 static struct diff_tempfile {
184 const char *name; /* filename external diff should read from */
185 char hex[41];
186 char mode[10];
187 char tmp_path[PATH_MAX];
188 } diff_temp[2];
190 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
192 struct emit_callback {
193 int color_diff;
194 unsigned ws_rule;
195 int blank_at_eof_in_preimage;
196 int blank_at_eof_in_postimage;
197 int lno_in_preimage;
198 int lno_in_postimage;
199 sane_truncate_fn truncate;
200 const char **label_path;
201 struct diff_words_data *diff_words;
202 int *found_changesp;
203 FILE *file;
204 struct strbuf *header;
207 static int count_lines(const char *data, int size)
209 int count, ch, completely_empty = 1, nl_just_seen = 0;
210 count = 0;
211 while (0 < size--) {
212 ch = *data++;
213 if (ch == '\n') {
214 count++;
215 nl_just_seen = 1;
216 completely_empty = 0;
218 else {
219 nl_just_seen = 0;
220 completely_empty = 0;
223 if (completely_empty)
224 return 0;
225 if (!nl_just_seen)
226 count++; /* no trailing newline */
227 return count;
230 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
232 if (!DIFF_FILE_VALID(one)) {
233 mf->ptr = (char *)""; /* does not matter */
234 mf->size = 0;
235 return 0;
237 else if (diff_populate_filespec(one, 0))
238 return -1;
240 mf->ptr = one->data;
241 mf->size = one->size;
242 return 0;
245 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
247 char *ptr = mf->ptr;
248 long size = mf->size;
249 int cnt = 0;
251 if (!size)
252 return cnt;
253 ptr += size - 1; /* pointing at the very end */
254 if (*ptr != '\n')
255 ; /* incomplete line */
256 else
257 ptr--; /* skip the last LF */
258 while (mf->ptr < ptr) {
259 char *prev_eol;
260 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
261 if (*prev_eol == '\n')
262 break;
263 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
264 break;
265 cnt++;
266 ptr = prev_eol - 1;
268 return cnt;
271 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
272 struct emit_callback *ecbdata)
274 int l1, l2, at;
275 unsigned ws_rule = ecbdata->ws_rule;
276 l1 = count_trailing_blank(mf1, ws_rule);
277 l2 = count_trailing_blank(mf2, ws_rule);
278 if (l2 <= l1) {
279 ecbdata->blank_at_eof_in_preimage = 0;
280 ecbdata->blank_at_eof_in_postimage = 0;
281 return;
283 at = count_lines(mf1->ptr, mf1->size);
284 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
286 at = count_lines(mf2->ptr, mf2->size);
287 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
290 static void emit_line_0(FILE *file, const char *set, const char *reset,
291 int first, const char *line, int len)
293 int has_trailing_newline, has_trailing_carriage_return;
294 int nofirst;
296 if (len == 0) {
297 has_trailing_newline = (first == '\n');
298 has_trailing_carriage_return = (!has_trailing_newline &&
299 (first == '\r'));
300 nofirst = has_trailing_newline || has_trailing_carriage_return;
301 } else {
302 has_trailing_newline = (len > 0 && line[len-1] == '\n');
303 if (has_trailing_newline)
304 len--;
305 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
306 if (has_trailing_carriage_return)
307 len--;
308 nofirst = 0;
311 if (len || !nofirst) {
312 fputs(set, file);
313 if (!nofirst)
314 fputc(first, file);
315 fwrite(line, len, 1, file);
316 fputs(reset, file);
318 if (has_trailing_carriage_return)
319 fputc('\r', file);
320 if (has_trailing_newline)
321 fputc('\n', file);
324 static void emit_line(FILE *file, const char *set, const char *reset,
325 const char *line, int len)
327 emit_line_0(file, set, reset, line[0], line+1, len-1);
330 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
332 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
333 ecbdata->blank_at_eof_in_preimage &&
334 ecbdata->blank_at_eof_in_postimage &&
335 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
336 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
337 return 0;
338 return ws_blank_line(line, len, ecbdata->ws_rule);
341 static void emit_add_line(const char *reset,
342 struct emit_callback *ecbdata,
343 const char *line, int len)
345 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
346 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
348 if (!*ws)
349 emit_line_0(ecbdata->file, set, reset, '+', line, len);
350 else if (new_blank_line_at_eof(ecbdata, line, len))
351 /* Blank line at EOF - paint '+' as well */
352 emit_line_0(ecbdata->file, ws, reset, '+', line, len);
353 else {
354 /* Emit just the prefix, then the rest. */
355 emit_line_0(ecbdata->file, set, reset, '+', "", 0);
356 ws_check_emit(line, len, ecbdata->ws_rule,
357 ecbdata->file, set, reset, ws);
361 static void emit_hunk_header(struct emit_callback *ecbdata,
362 const char *line, int len)
364 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
365 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
366 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
367 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
368 static const char atat[2] = { '@', '@' };
369 const char *cp, *ep;
372 * As a hunk header must begin with "@@ -<old>, +<new> @@",
373 * it always is at least 10 bytes long.
375 if (len < 10 ||
376 memcmp(line, atat, 2) ||
377 !(ep = memmem(line + 2, len - 2, atat, 2))) {
378 emit_line(ecbdata->file, plain, reset, line, len);
379 return;
381 ep += 2; /* skip over @@ */
383 /* The hunk header in fraginfo color */
384 emit_line(ecbdata->file, frag, reset, line, ep - line);
386 /* blank before the func header */
387 for (cp = ep; ep - line < len; ep++)
388 if (*ep != ' ' && *ep != '\t')
389 break;
390 if (ep != cp)
391 emit_line(ecbdata->file, plain, reset, cp, ep - cp);
393 if (ep < line + len)
394 emit_line(ecbdata->file, func, reset, ep, line + len - ep);
397 static struct diff_tempfile *claim_diff_tempfile(void) {
398 int i;
399 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
400 if (!diff_temp[i].name)
401 return diff_temp + i;
402 die("BUG: diff is failing to clean up its tempfiles");
405 static int remove_tempfile_installed;
407 static void remove_tempfile(void)
409 int i;
410 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
411 if (diff_temp[i].name == diff_temp[i].tmp_path)
412 unlink_or_warn(diff_temp[i].name);
413 diff_temp[i].name = NULL;
417 static void remove_tempfile_on_signal(int signo)
419 remove_tempfile();
420 sigchain_pop(signo);
421 raise(signo);
424 static void print_line_count(FILE *file, int count)
426 switch (count) {
427 case 0:
428 fprintf(file, "0,0");
429 break;
430 case 1:
431 fprintf(file, "1");
432 break;
433 default:
434 fprintf(file, "1,%d", count);
435 break;
439 static void emit_rewrite_lines(struct emit_callback *ecb,
440 int prefix, const char *data, int size)
442 const char *endp = NULL;
443 static const char *nneof = " No newline at end of file\n";
444 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
445 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
447 while (0 < size) {
448 int len;
450 endp = memchr(data, '\n', size);
451 len = endp ? (endp - data + 1) : size;
452 if (prefix != '+') {
453 ecb->lno_in_preimage++;
454 emit_line_0(ecb->file, old, reset, '-',
455 data, len);
456 } else {
457 ecb->lno_in_postimage++;
458 emit_add_line(reset, ecb, data, len);
460 size -= len;
461 data += len;
463 if (!endp) {
464 const char *plain = diff_get_color(ecb->color_diff,
465 DIFF_PLAIN);
466 emit_line_0(ecb->file, plain, reset, '\\',
467 nneof, strlen(nneof));
471 static void emit_rewrite_diff(const char *name_a,
472 const char *name_b,
473 struct diff_filespec *one,
474 struct diff_filespec *two,
475 struct userdiff_driver *textconv_one,
476 struct userdiff_driver *textconv_two,
477 struct diff_options *o)
479 int lc_a, lc_b;
480 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
481 const char *name_a_tab, *name_b_tab;
482 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
483 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
484 const char *reset = diff_get_color(color_diff, DIFF_RESET);
485 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
486 const char *a_prefix, *b_prefix;
487 char *data_one, *data_two;
488 size_t size_one, size_two;
489 struct emit_callback ecbdata;
491 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
492 a_prefix = o->b_prefix;
493 b_prefix = o->a_prefix;
494 } else {
495 a_prefix = o->a_prefix;
496 b_prefix = o->b_prefix;
499 name_a += (*name_a == '/');
500 name_b += (*name_b == '/');
501 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
502 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
504 strbuf_reset(&a_name);
505 strbuf_reset(&b_name);
506 quote_two_c_style(&a_name, a_prefix, name_a, 0);
507 quote_two_c_style(&b_name, b_prefix, name_b, 0);
509 size_one = fill_textconv(textconv_one, one, &data_one);
510 size_two = fill_textconv(textconv_two, two, &data_two);
512 memset(&ecbdata, 0, sizeof(ecbdata));
513 ecbdata.color_diff = color_diff;
514 ecbdata.found_changesp = &o->found_changes;
515 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
516 ecbdata.file = o->file;
517 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
518 mmfile_t mf1, mf2;
519 mf1.ptr = (char *)data_one;
520 mf2.ptr = (char *)data_two;
521 mf1.size = size_one;
522 mf2.size = size_two;
523 check_blank_at_eof(&mf1, &mf2, &ecbdata);
525 ecbdata.lno_in_preimage = 1;
526 ecbdata.lno_in_postimage = 1;
528 lc_a = count_lines(data_one, size_one);
529 lc_b = count_lines(data_two, size_two);
530 fprintf(o->file,
531 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
532 metainfo, a_name.buf, name_a_tab, reset,
533 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
534 print_line_count(o->file, lc_a);
535 fprintf(o->file, " +");
536 print_line_count(o->file, lc_b);
537 fprintf(o->file, " @@%s\n", reset);
538 if (lc_a)
539 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
540 if (lc_b)
541 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
542 if (textconv_one)
543 free((char *)data_one);
544 if (textconv_two)
545 free((char *)data_two);
548 struct diff_words_buffer {
549 mmfile_t text;
550 long alloc;
551 struct diff_words_orig {
552 const char *begin, *end;
553 } *orig;
554 int orig_nr, orig_alloc;
557 static void diff_words_append(char *line, unsigned long len,
558 struct diff_words_buffer *buffer)
560 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
561 line++;
562 len--;
563 memcpy(buffer->text.ptr + buffer->text.size, line, len);
564 buffer->text.size += len;
565 buffer->text.ptr[buffer->text.size] = '\0';
568 struct diff_words_style_elem
570 const char *prefix;
571 const char *suffix;
572 const char *color; /* NULL; filled in by the setup code if
573 * color is enabled */
576 struct diff_words_style
578 enum diff_words_type type;
579 struct diff_words_style_elem new, old, ctx;
580 const char *newline;
583 struct diff_words_style diff_words_styles[] = {
584 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
585 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
586 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
589 struct diff_words_data {
590 struct diff_words_buffer minus, plus;
591 const char *current_plus;
592 FILE *file;
593 regex_t *word_regex;
594 enum diff_words_type type;
595 struct diff_words_style *style;
598 static int fn_out_diff_words_write_helper(FILE *fp,
599 struct diff_words_style_elem *st_el,
600 const char *newline,
601 size_t count, const char *buf)
603 while (count) {
604 char *p = memchr(buf, '\n', count);
605 if (p != buf) {
606 if (st_el->color && fputs(st_el->color, fp) < 0)
607 return -1;
608 if (fputs(st_el->prefix, fp) < 0 ||
609 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
610 fputs(st_el->suffix, fp) < 0)
611 return -1;
612 if (st_el->color && *st_el->color
613 && fputs(GIT_COLOR_RESET, fp) < 0)
614 return -1;
616 if (!p)
617 return 0;
618 if (fputs(newline, fp) < 0)
619 return -1;
620 count -= p + 1 - buf;
621 buf = p + 1;
623 return 0;
626 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
628 struct diff_words_data *diff_words = priv;
629 struct diff_words_style *style = diff_words->style;
630 int minus_first, minus_len, plus_first, plus_len;
631 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
633 if (line[0] != '@' || parse_hunk_header(line, len,
634 &minus_first, &minus_len, &plus_first, &plus_len))
635 return;
637 /* POSIX requires that first be decremented by one if len == 0... */
638 if (minus_len) {
639 minus_begin = diff_words->minus.orig[minus_first].begin;
640 minus_end =
641 diff_words->minus.orig[minus_first + minus_len - 1].end;
642 } else
643 minus_begin = minus_end =
644 diff_words->minus.orig[minus_first].end;
646 if (plus_len) {
647 plus_begin = diff_words->plus.orig[plus_first].begin;
648 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
649 } else
650 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
652 if (diff_words->current_plus != plus_begin)
653 fn_out_diff_words_write_helper(diff_words->file,
654 &style->ctx, style->newline,
655 plus_begin - diff_words->current_plus,
656 diff_words->current_plus);
657 if (minus_begin != minus_end)
658 fn_out_diff_words_write_helper(diff_words->file,
659 &style->old, style->newline,
660 minus_end - minus_begin, minus_begin);
661 if (plus_begin != plus_end)
662 fn_out_diff_words_write_helper(diff_words->file,
663 &style->new, style->newline,
664 plus_end - plus_begin, plus_begin);
666 diff_words->current_plus = plus_end;
669 /* This function starts looking at *begin, and returns 0 iff a word was found. */
670 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
671 int *begin, int *end)
673 if (word_regex && *begin < buffer->size) {
674 regmatch_t match[1];
675 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
676 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
677 '\n', match[0].rm_eo - match[0].rm_so);
678 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
679 *begin += match[0].rm_so;
680 return *begin >= *end;
682 return -1;
685 /* find the next word */
686 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
687 (*begin)++;
688 if (*begin >= buffer->size)
689 return -1;
691 /* find the end of the word */
692 *end = *begin + 1;
693 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
694 (*end)++;
696 return 0;
700 * This function splits the words in buffer->text, stores the list with
701 * newline separator into out, and saves the offsets of the original words
702 * in buffer->orig.
704 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
705 regex_t *word_regex)
707 int i, j;
708 long alloc = 0;
710 out->size = 0;
711 out->ptr = NULL;
713 /* fake an empty "0th" word */
714 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
715 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
716 buffer->orig_nr = 1;
718 for (i = 0; i < buffer->text.size; i++) {
719 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
720 return;
722 /* store original boundaries */
723 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
724 buffer->orig_alloc);
725 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
726 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
727 buffer->orig_nr++;
729 /* store one word */
730 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
731 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
732 out->ptr[out->size + j - i] = '\n';
733 out->size += j - i + 1;
735 i = j - 1;
739 /* this executes the word diff on the accumulated buffers */
740 static void diff_words_show(struct diff_words_data *diff_words)
742 xpparam_t xpp;
743 xdemitconf_t xecfg;
744 mmfile_t minus, plus;
745 struct diff_words_style *style = diff_words->style;
747 /* special case: only removal */
748 if (!diff_words->plus.text.size) {
749 fn_out_diff_words_write_helper(diff_words->file,
750 &style->old, style->newline,
751 diff_words->minus.text.size, diff_words->minus.text.ptr);
752 diff_words->minus.text.size = 0;
753 return;
756 diff_words->current_plus = diff_words->plus.text.ptr;
758 memset(&xpp, 0, sizeof(xpp));
759 memset(&xecfg, 0, sizeof(xecfg));
760 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
761 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
762 xpp.flags = 0;
763 /* as only the hunk header will be parsed, we need a 0-context */
764 xecfg.ctxlen = 0;
765 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
766 &xpp, &xecfg);
767 free(minus.ptr);
768 free(plus.ptr);
769 if (diff_words->current_plus != diff_words->plus.text.ptr +
770 diff_words->plus.text.size)
771 fn_out_diff_words_write_helper(diff_words->file,
772 &style->ctx, style->newline,
773 diff_words->plus.text.ptr + diff_words->plus.text.size
774 - diff_words->current_plus, diff_words->current_plus);
775 diff_words->minus.text.size = diff_words->plus.text.size = 0;
778 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
779 static void diff_words_flush(struct emit_callback *ecbdata)
781 if (ecbdata->diff_words->minus.text.size ||
782 ecbdata->diff_words->plus.text.size)
783 diff_words_show(ecbdata->diff_words);
786 static void free_diff_words_data(struct emit_callback *ecbdata)
788 if (ecbdata->diff_words) {
789 diff_words_flush(ecbdata);
790 free (ecbdata->diff_words->minus.text.ptr);
791 free (ecbdata->diff_words->minus.orig);
792 free (ecbdata->diff_words->plus.text.ptr);
793 free (ecbdata->diff_words->plus.orig);
794 free(ecbdata->diff_words->word_regex);
795 free(ecbdata->diff_words);
796 ecbdata->diff_words = NULL;
800 const char *diff_get_color(int diff_use_color, enum color_diff ix)
802 if (diff_use_color)
803 return diff_colors[ix];
804 return "";
807 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
809 const char *cp;
810 unsigned long allot;
811 size_t l = len;
813 if (ecb->truncate)
814 return ecb->truncate(line, len);
815 cp = line;
816 allot = l;
817 while (0 < l) {
818 (void) utf8_width(&cp, &l);
819 if (!cp)
820 break; /* truncated in the middle? */
822 return allot - l;
825 static void find_lno(const char *line, struct emit_callback *ecbdata)
827 const char *p;
828 ecbdata->lno_in_preimage = 0;
829 ecbdata->lno_in_postimage = 0;
830 p = strchr(line, '-');
831 if (!p)
832 return; /* cannot happen */
833 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
834 p = strchr(p, '+');
835 if (!p)
836 return; /* cannot happen */
837 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
840 static void fn_out_consume(void *priv, char *line, unsigned long len)
842 struct emit_callback *ecbdata = priv;
843 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
844 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
845 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
847 if (ecbdata->header) {
848 fprintf(ecbdata->file, "%s", ecbdata->header->buf);
849 strbuf_reset(ecbdata->header);
850 ecbdata->header = NULL;
852 *(ecbdata->found_changesp) = 1;
854 if (ecbdata->label_path[0]) {
855 const char *name_a_tab, *name_b_tab;
857 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
858 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
860 fprintf(ecbdata->file, "%s--- %s%s%s\n",
861 meta, ecbdata->label_path[0], reset, name_a_tab);
862 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
863 meta, ecbdata->label_path[1], reset, name_b_tab);
864 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
867 if (diff_suppress_blank_empty
868 && len == 2 && line[0] == ' ' && line[1] == '\n') {
869 line[0] = '\n';
870 len = 1;
873 if (line[0] == '@') {
874 if (ecbdata->diff_words)
875 diff_words_flush(ecbdata);
876 len = sane_truncate_line(ecbdata, line, len);
877 find_lno(line, ecbdata);
878 emit_hunk_header(ecbdata, line, len);
879 if (line[len-1] != '\n')
880 putc('\n', ecbdata->file);
881 return;
884 if (len < 1) {
885 emit_line(ecbdata->file, reset, reset, line, len);
886 if (ecbdata->diff_words
887 && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
888 fputs("~\n", ecbdata->file);
889 return;
892 if (ecbdata->diff_words) {
893 if (line[0] == '-') {
894 diff_words_append(line, len,
895 &ecbdata->diff_words->minus);
896 return;
897 } else if (line[0] == '+') {
898 diff_words_append(line, len,
899 &ecbdata->diff_words->plus);
900 return;
902 diff_words_flush(ecbdata);
903 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
904 emit_line(ecbdata->file, plain, reset, line, len);
905 fputs("~\n", ecbdata->file);
906 } else {
907 /* don't print the prefix character */
908 emit_line(ecbdata->file, plain, reset, line+1, len-1);
910 return;
913 if (line[0] != '+') {
914 const char *color =
915 diff_get_color(ecbdata->color_diff,
916 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
917 ecbdata->lno_in_preimage++;
918 if (line[0] == ' ')
919 ecbdata->lno_in_postimage++;
920 emit_line(ecbdata->file, color, reset, line, len);
921 } else {
922 ecbdata->lno_in_postimage++;
923 emit_add_line(reset, ecbdata, line + 1, len - 1);
927 static char *pprint_rename(const char *a, const char *b)
929 const char *old = a;
930 const char *new = b;
931 struct strbuf name = STRBUF_INIT;
932 int pfx_length, sfx_length;
933 int len_a = strlen(a);
934 int len_b = strlen(b);
935 int a_midlen, b_midlen;
936 int qlen_a = quote_c_style(a, NULL, NULL, 0);
937 int qlen_b = quote_c_style(b, NULL, NULL, 0);
939 if (qlen_a || qlen_b) {
940 quote_c_style(a, &name, NULL, 0);
941 strbuf_addstr(&name, " => ");
942 quote_c_style(b, &name, NULL, 0);
943 return strbuf_detach(&name, NULL);
946 /* Find common prefix */
947 pfx_length = 0;
948 while (*old && *new && *old == *new) {
949 if (*old == '/')
950 pfx_length = old - a + 1;
951 old++;
952 new++;
955 /* Find common suffix */
956 old = a + len_a;
957 new = b + len_b;
958 sfx_length = 0;
959 while (a <= old && b <= new && *old == *new) {
960 if (*old == '/')
961 sfx_length = len_a - (old - a);
962 old--;
963 new--;
967 * pfx{mid-a => mid-b}sfx
968 * {pfx-a => pfx-b}sfx
969 * pfx{sfx-a => sfx-b}
970 * name-a => name-b
972 a_midlen = len_a - pfx_length - sfx_length;
973 b_midlen = len_b - pfx_length - sfx_length;
974 if (a_midlen < 0)
975 a_midlen = 0;
976 if (b_midlen < 0)
977 b_midlen = 0;
979 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
980 if (pfx_length + sfx_length) {
981 strbuf_add(&name, a, pfx_length);
982 strbuf_addch(&name, '{');
984 strbuf_add(&name, a + pfx_length, a_midlen);
985 strbuf_addstr(&name, " => ");
986 strbuf_add(&name, b + pfx_length, b_midlen);
987 if (pfx_length + sfx_length) {
988 strbuf_addch(&name, '}');
989 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
991 return strbuf_detach(&name, NULL);
994 struct diffstat_t {
995 int nr;
996 int alloc;
997 struct diffstat_file {
998 char *from_name;
999 char *name;
1000 char *print_name;
1001 unsigned is_unmerged:1;
1002 unsigned is_binary:1;
1003 unsigned is_renamed:1;
1004 uintmax_t added, deleted;
1005 } **files;
1008 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1009 const char *name_a,
1010 const char *name_b)
1012 struct diffstat_file *x;
1013 x = xcalloc(sizeof (*x), 1);
1014 if (diffstat->nr == diffstat->alloc) {
1015 diffstat->alloc = alloc_nr(diffstat->alloc);
1016 diffstat->files = xrealloc(diffstat->files,
1017 diffstat->alloc * sizeof(x));
1019 diffstat->files[diffstat->nr++] = x;
1020 if (name_b) {
1021 x->from_name = xstrdup(name_a);
1022 x->name = xstrdup(name_b);
1023 x->is_renamed = 1;
1025 else {
1026 x->from_name = NULL;
1027 x->name = xstrdup(name_a);
1029 return x;
1032 static void diffstat_consume(void *priv, char *line, unsigned long len)
1034 struct diffstat_t *diffstat = priv;
1035 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1037 if (line[0] == '+')
1038 x->added++;
1039 else if (line[0] == '-')
1040 x->deleted++;
1043 const char mime_boundary_leader[] = "------------";
1045 static int scale_linear(int it, int width, int max_change)
1048 * make sure that at least one '-' is printed if there were deletions,
1049 * and likewise for '+'.
1051 if (max_change < 2)
1052 return it;
1053 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
1056 static void show_name(FILE *file,
1057 const char *prefix, const char *name, int len)
1059 fprintf(file, " %s%-*s |", prefix, len, name);
1062 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1064 if (cnt <= 0)
1065 return;
1066 fprintf(file, "%s", set);
1067 while (cnt--)
1068 putc(ch, file);
1069 fprintf(file, "%s", reset);
1072 static void fill_print_name(struct diffstat_file *file)
1074 char *pname;
1076 if (file->print_name)
1077 return;
1079 if (!file->is_renamed) {
1080 struct strbuf buf = STRBUF_INIT;
1081 if (quote_c_style(file->name, &buf, NULL, 0)) {
1082 pname = strbuf_detach(&buf, NULL);
1083 } else {
1084 pname = file->name;
1085 strbuf_release(&buf);
1087 } else {
1088 pname = pprint_rename(file->from_name, file->name);
1090 file->print_name = pname;
1093 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1095 int i, len, add, del, adds = 0, dels = 0;
1096 uintmax_t max_change = 0, max_len = 0;
1097 int total_files = data->nr;
1098 int width, name_width;
1099 const char *reset, *set, *add_c, *del_c;
1101 if (data->nr == 0)
1102 return;
1104 width = options->stat_width ? options->stat_width : 80;
1105 name_width = options->stat_name_width ? options->stat_name_width : 50;
1107 /* Sanity: give at least 5 columns to the graph,
1108 * but leave at least 10 columns for the name.
1110 if (width < 25)
1111 width = 25;
1112 if (name_width < 10)
1113 name_width = 10;
1114 else if (width < name_width + 15)
1115 name_width = width - 15;
1117 /* Find the longest filename and max number of changes */
1118 reset = diff_get_color_opt(options, DIFF_RESET);
1119 set = diff_get_color_opt(options, DIFF_PLAIN);
1120 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1121 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1123 for (i = 0; i < data->nr; i++) {
1124 struct diffstat_file *file = data->files[i];
1125 uintmax_t change = file->added + file->deleted;
1126 fill_print_name(file);
1127 len = strlen(file->print_name);
1128 if (max_len < len)
1129 max_len = len;
1131 if (file->is_binary || file->is_unmerged)
1132 continue;
1133 if (max_change < change)
1134 max_change = change;
1137 /* Compute the width of the graph part;
1138 * 10 is for one blank at the beginning of the line plus
1139 * " | count " between the name and the graph.
1141 * From here on, name_width is the width of the name area,
1142 * and width is the width of the graph area.
1144 name_width = (name_width < max_len) ? name_width : max_len;
1145 if (width < (name_width + 10) + max_change)
1146 width = width - (name_width + 10);
1147 else
1148 width = max_change;
1150 for (i = 0; i < data->nr; i++) {
1151 const char *prefix = "";
1152 char *name = data->files[i]->print_name;
1153 uintmax_t added = data->files[i]->added;
1154 uintmax_t deleted = data->files[i]->deleted;
1155 int name_len;
1158 * "scale" the filename
1160 len = name_width;
1161 name_len = strlen(name);
1162 if (name_width < name_len) {
1163 char *slash;
1164 prefix = "...";
1165 len -= 3;
1166 name += name_len - len;
1167 slash = strchr(name, '/');
1168 if (slash)
1169 name = slash;
1172 if (data->files[i]->is_binary) {
1173 show_name(options->file, prefix, name, len);
1174 fprintf(options->file, " Bin ");
1175 fprintf(options->file, "%s%"PRIuMAX"%s",
1176 del_c, deleted, reset);
1177 fprintf(options->file, " -> ");
1178 fprintf(options->file, "%s%"PRIuMAX"%s",
1179 add_c, added, reset);
1180 fprintf(options->file, " bytes");
1181 fprintf(options->file, "\n");
1182 continue;
1184 else if (data->files[i]->is_unmerged) {
1185 show_name(options->file, prefix, name, len);
1186 fprintf(options->file, " Unmerged\n");
1187 continue;
1189 else if (!data->files[i]->is_renamed &&
1190 (added + deleted == 0)) {
1191 total_files--;
1192 continue;
1196 * scale the add/delete
1198 add = added;
1199 del = deleted;
1200 adds += add;
1201 dels += del;
1203 if (width <= max_change) {
1204 add = scale_linear(add, width, max_change);
1205 del = scale_linear(del, width, max_change);
1207 show_name(options->file, prefix, name, len);
1208 fprintf(options->file, "%5"PRIuMAX"%s", added + deleted,
1209 added + deleted ? " " : "");
1210 show_graph(options->file, '+', add, add_c, reset);
1211 show_graph(options->file, '-', del, del_c, reset);
1212 fprintf(options->file, "\n");
1214 fprintf(options->file,
1215 " %d files changed, %d insertions(+), %d deletions(-)\n",
1216 total_files, adds, dels);
1219 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1221 int i, adds = 0, dels = 0, total_files = data->nr;
1223 if (data->nr == 0)
1224 return;
1226 for (i = 0; i < data->nr; i++) {
1227 if (!data->files[i]->is_binary &&
1228 !data->files[i]->is_unmerged) {
1229 int added = data->files[i]->added;
1230 int deleted= data->files[i]->deleted;
1231 if (!data->files[i]->is_renamed &&
1232 (added + deleted == 0)) {
1233 total_files--;
1234 } else {
1235 adds += added;
1236 dels += deleted;
1240 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1241 total_files, adds, dels);
1244 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1246 int i;
1248 if (data->nr == 0)
1249 return;
1251 for (i = 0; i < data->nr; i++) {
1252 struct diffstat_file *file = data->files[i];
1254 if (file->is_binary)
1255 fprintf(options->file, "-\t-\t");
1256 else
1257 fprintf(options->file,
1258 "%"PRIuMAX"\t%"PRIuMAX"\t",
1259 file->added, file->deleted);
1260 if (options->line_termination) {
1261 fill_print_name(file);
1262 if (!file->is_renamed)
1263 write_name_quoted(file->name, options->file,
1264 options->line_termination);
1265 else {
1266 fputs(file->print_name, options->file);
1267 putc(options->line_termination, options->file);
1269 } else {
1270 if (file->is_renamed) {
1271 putc('\0', options->file);
1272 write_name_quoted(file->from_name, options->file, '\0');
1274 write_name_quoted(file->name, options->file, '\0');
1279 struct dirstat_file {
1280 const char *name;
1281 unsigned long changed;
1284 struct dirstat_dir {
1285 struct dirstat_file *files;
1286 int alloc, nr, percent, cumulative;
1289 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1291 unsigned long this_dir = 0;
1292 unsigned int sources = 0;
1294 while (dir->nr) {
1295 struct dirstat_file *f = dir->files;
1296 int namelen = strlen(f->name);
1297 unsigned long this;
1298 char *slash;
1300 if (namelen < baselen)
1301 break;
1302 if (memcmp(f->name, base, baselen))
1303 break;
1304 slash = strchr(f->name + baselen, '/');
1305 if (slash) {
1306 int newbaselen = slash + 1 - f->name;
1307 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1308 sources++;
1309 } else {
1310 this = f->changed;
1311 dir->files++;
1312 dir->nr--;
1313 sources += 2;
1315 this_dir += this;
1319 * We don't report dirstat's for
1320 * - the top level
1321 * - or cases where everything came from a single directory
1322 * under this directory (sources == 1).
1324 if (baselen && sources != 1) {
1325 int permille = this_dir * 1000 / changed;
1326 if (permille) {
1327 int percent = permille / 10;
1328 if (percent >= dir->percent) {
1329 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1330 if (!dir->cumulative)
1331 return 0;
1335 return this_dir;
1338 static int dirstat_compare(const void *_a, const void *_b)
1340 const struct dirstat_file *a = _a;
1341 const struct dirstat_file *b = _b;
1342 return strcmp(a->name, b->name);
1345 static void show_dirstat(struct diff_options *options)
1347 int i;
1348 unsigned long changed;
1349 struct dirstat_dir dir;
1350 struct diff_queue_struct *q = &diff_queued_diff;
1352 dir.files = NULL;
1353 dir.alloc = 0;
1354 dir.nr = 0;
1355 dir.percent = options->dirstat_percent;
1356 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1358 changed = 0;
1359 for (i = 0; i < q->nr; i++) {
1360 struct diff_filepair *p = q->queue[i];
1361 const char *name;
1362 unsigned long copied, added, damage;
1364 name = p->one->path ? p->one->path : p->two->path;
1366 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1367 diff_populate_filespec(p->one, 0);
1368 diff_populate_filespec(p->two, 0);
1369 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1370 &copied, &added);
1371 diff_free_filespec_data(p->one);
1372 diff_free_filespec_data(p->two);
1373 } else if (DIFF_FILE_VALID(p->one)) {
1374 diff_populate_filespec(p->one, 1);
1375 copied = added = 0;
1376 diff_free_filespec_data(p->one);
1377 } else if (DIFF_FILE_VALID(p->two)) {
1378 diff_populate_filespec(p->two, 1);
1379 copied = 0;
1380 added = p->two->size;
1381 diff_free_filespec_data(p->two);
1382 } else
1383 continue;
1386 * Original minus copied is the removed material,
1387 * added is the new material. They are both damages
1388 * made to the preimage. In --dirstat-by-file mode, count
1389 * damaged files, not damaged lines. This is done by
1390 * counting only a single damaged line per file.
1392 damage = (p->one->size - copied) + added;
1393 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1394 damage = 1;
1396 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1397 dir.files[dir.nr].name = name;
1398 dir.files[dir.nr].changed = damage;
1399 changed += damage;
1400 dir.nr++;
1403 /* This can happen even with many files, if everything was renames */
1404 if (!changed)
1405 return;
1407 /* Show all directories with more than x% of the changes */
1408 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1409 gather_dirstat(options->file, &dir, changed, "", 0);
1412 static void free_diffstat_info(struct diffstat_t *diffstat)
1414 int i;
1415 for (i = 0; i < diffstat->nr; i++) {
1416 struct diffstat_file *f = diffstat->files[i];
1417 if (f->name != f->print_name)
1418 free(f->print_name);
1419 free(f->name);
1420 free(f->from_name);
1421 free(f);
1423 free(diffstat->files);
1426 struct checkdiff_t {
1427 const char *filename;
1428 int lineno;
1429 int conflict_marker_size;
1430 struct diff_options *o;
1431 unsigned ws_rule;
1432 unsigned status;
1435 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
1437 char firstchar;
1438 int cnt;
1440 if (len < marker_size + 1)
1441 return 0;
1442 firstchar = line[0];
1443 switch (firstchar) {
1444 case '=': case '>': case '<': case '|':
1445 break;
1446 default:
1447 return 0;
1449 for (cnt = 1; cnt < marker_size; cnt++)
1450 if (line[cnt] != firstchar)
1451 return 0;
1452 /* line[1] thru line[marker_size-1] are same as firstchar */
1453 if (len < marker_size + 1 || !isspace(line[marker_size]))
1454 return 0;
1455 return 1;
1458 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1460 struct checkdiff_t *data = priv;
1461 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1462 int marker_size = data->conflict_marker_size;
1463 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1464 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1465 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1466 char *err;
1468 if (line[0] == '+') {
1469 unsigned bad;
1470 data->lineno++;
1471 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
1472 data->status |= 1;
1473 fprintf(data->o->file,
1474 "%s:%d: leftover conflict marker\n",
1475 data->filename, data->lineno);
1477 bad = ws_check(line + 1, len - 1, data->ws_rule);
1478 if (!bad)
1479 return;
1480 data->status |= bad;
1481 err = whitespace_error_string(bad);
1482 fprintf(data->o->file, "%s:%d: %s.\n",
1483 data->filename, data->lineno, err);
1484 free(err);
1485 emit_line(data->o->file, set, reset, line, 1);
1486 ws_check_emit(line + 1, len - 1, data->ws_rule,
1487 data->o->file, set, reset, ws);
1488 } else if (line[0] == ' ') {
1489 data->lineno++;
1490 } else if (line[0] == '@') {
1491 char *plus = strchr(line, '+');
1492 if (plus)
1493 data->lineno = strtol(plus, NULL, 10) - 1;
1494 else
1495 die("invalid diff");
1499 static unsigned char *deflate_it(char *data,
1500 unsigned long size,
1501 unsigned long *result_size)
1503 int bound;
1504 unsigned char *deflated;
1505 z_stream stream;
1507 memset(&stream, 0, sizeof(stream));
1508 deflateInit(&stream, zlib_compression_level);
1509 bound = deflateBound(&stream, size);
1510 deflated = xmalloc(bound);
1511 stream.next_out = deflated;
1512 stream.avail_out = bound;
1514 stream.next_in = (unsigned char *)data;
1515 stream.avail_in = size;
1516 while (deflate(&stream, Z_FINISH) == Z_OK)
1517 ; /* nothing */
1518 deflateEnd(&stream);
1519 *result_size = stream.total_out;
1520 return deflated;
1523 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1525 void *cp;
1526 void *delta;
1527 void *deflated;
1528 void *data;
1529 unsigned long orig_size;
1530 unsigned long delta_size;
1531 unsigned long deflate_size;
1532 unsigned long data_size;
1534 /* We could do deflated delta, or we could do just deflated two,
1535 * whichever is smaller.
1537 delta = NULL;
1538 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1539 if (one->size && two->size) {
1540 delta = diff_delta(one->ptr, one->size,
1541 two->ptr, two->size,
1542 &delta_size, deflate_size);
1543 if (delta) {
1544 void *to_free = delta;
1545 orig_size = delta_size;
1546 delta = deflate_it(delta, delta_size, &delta_size);
1547 free(to_free);
1551 if (delta && delta_size < deflate_size) {
1552 fprintf(file, "delta %lu\n", orig_size);
1553 free(deflated);
1554 data = delta;
1555 data_size = delta_size;
1557 else {
1558 fprintf(file, "literal %lu\n", two->size);
1559 free(delta);
1560 data = deflated;
1561 data_size = deflate_size;
1564 /* emit data encoded in base85 */
1565 cp = data;
1566 while (data_size) {
1567 int bytes = (52 < data_size) ? 52 : data_size;
1568 char line[70];
1569 data_size -= bytes;
1570 if (bytes <= 26)
1571 line[0] = bytes + 'A' - 1;
1572 else
1573 line[0] = bytes - 26 + 'a' - 1;
1574 encode_85(line + 1, cp, bytes);
1575 cp = (char *) cp + bytes;
1576 fputs(line, file);
1577 fputc('\n', file);
1579 fprintf(file, "\n");
1580 free(data);
1583 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1585 fprintf(file, "GIT binary patch\n");
1586 emit_binary_diff_body(file, one, two);
1587 emit_binary_diff_body(file, two, one);
1590 static void diff_filespec_load_driver(struct diff_filespec *one)
1592 if (!one->driver)
1593 one->driver = userdiff_find_by_path(one->path);
1594 if (!one->driver)
1595 one->driver = userdiff_find_by_name("default");
1598 int diff_filespec_is_binary(struct diff_filespec *one)
1600 if (one->is_binary == -1) {
1601 diff_filespec_load_driver(one);
1602 if (one->driver->binary != -1)
1603 one->is_binary = one->driver->binary;
1604 else {
1605 if (!one->data && DIFF_FILE_VALID(one))
1606 diff_populate_filespec(one, 0);
1607 if (one->data)
1608 one->is_binary = buffer_is_binary(one->data,
1609 one->size);
1610 if (one->is_binary == -1)
1611 one->is_binary = 0;
1614 return one->is_binary;
1617 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1619 diff_filespec_load_driver(one);
1620 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1623 static const char *userdiff_word_regex(struct diff_filespec *one)
1625 diff_filespec_load_driver(one);
1626 return one->driver->word_regex;
1629 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1631 if (!options->a_prefix)
1632 options->a_prefix = a;
1633 if (!options->b_prefix)
1634 options->b_prefix = b;
1637 static struct userdiff_driver *get_textconv(struct diff_filespec *one)
1639 if (!DIFF_FILE_VALID(one))
1640 return NULL;
1641 if (!S_ISREG(one->mode))
1642 return NULL;
1643 diff_filespec_load_driver(one);
1644 if (!one->driver->textconv)
1645 return NULL;
1647 if (one->driver->textconv_want_cache && !one->driver->textconv_cache) {
1648 struct notes_cache *c = xmalloc(sizeof(*c));
1649 struct strbuf name = STRBUF_INIT;
1651 strbuf_addf(&name, "textconv/%s", one->driver->name);
1652 notes_cache_init(c, name.buf, one->driver->textconv);
1653 one->driver->textconv_cache = c;
1656 return one->driver;
1659 static void builtin_diff(const char *name_a,
1660 const char *name_b,
1661 struct diff_filespec *one,
1662 struct diff_filespec *two,
1663 const char *xfrm_msg,
1664 struct diff_options *o,
1665 int complete_rewrite)
1667 mmfile_t mf1, mf2;
1668 const char *lbl[2];
1669 char *a_one, *b_two;
1670 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1671 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1672 const char *a_prefix, *b_prefix;
1673 struct userdiff_driver *textconv_one = NULL;
1674 struct userdiff_driver *textconv_two = NULL;
1675 struct strbuf header = STRBUF_INIT;
1677 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
1678 (!one->mode || S_ISGITLINK(one->mode)) &&
1679 (!two->mode || S_ISGITLINK(two->mode))) {
1680 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1681 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1682 show_submodule_summary(o->file, one ? one->path : two->path,
1683 one->sha1, two->sha1, two->dirty_submodule,
1684 del, add, reset);
1685 return;
1688 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1689 textconv_one = get_textconv(one);
1690 textconv_two = get_textconv(two);
1693 diff_set_mnemonic_prefix(o, "a/", "b/");
1694 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1695 a_prefix = o->b_prefix;
1696 b_prefix = o->a_prefix;
1697 } else {
1698 a_prefix = o->a_prefix;
1699 b_prefix = o->b_prefix;
1702 /* Never use a non-valid filename anywhere if at all possible */
1703 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1704 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1706 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1707 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1708 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1709 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1710 strbuf_addf(&header, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1711 if (lbl[0][0] == '/') {
1712 /* /dev/null */
1713 strbuf_addf(&header, "%snew file mode %06o%s\n", set, two->mode, reset);
1714 if (xfrm_msg)
1715 strbuf_addstr(&header, xfrm_msg);
1717 else if (lbl[1][0] == '/') {
1718 strbuf_addf(&header, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1719 if (xfrm_msg)
1720 strbuf_addstr(&header, xfrm_msg);
1722 else {
1723 if (one->mode != two->mode) {
1724 strbuf_addf(&header, "%sold mode %06o%s\n", set, one->mode, reset);
1725 strbuf_addf(&header, "%snew mode %06o%s\n", set, two->mode, reset);
1727 if (xfrm_msg)
1728 strbuf_addstr(&header, xfrm_msg);
1731 * we do not run diff between different kind
1732 * of objects.
1734 if ((one->mode ^ two->mode) & S_IFMT)
1735 goto free_ab_and_return;
1736 if (complete_rewrite &&
1737 (textconv_one || !diff_filespec_is_binary(one)) &&
1738 (textconv_two || !diff_filespec_is_binary(two))) {
1739 fprintf(o->file, "%s", header.buf);
1740 strbuf_reset(&header);
1741 emit_rewrite_diff(name_a, name_b, one, two,
1742 textconv_one, textconv_two, o);
1743 o->found_changes = 1;
1744 goto free_ab_and_return;
1748 if (!DIFF_OPT_TST(o, TEXT) &&
1749 ( (!textconv_one && diff_filespec_is_binary(one)) ||
1750 (!textconv_two && diff_filespec_is_binary(two)) )) {
1751 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1752 die("unable to read files to diff");
1753 /* Quite common confusing case */
1754 if (mf1.size == mf2.size &&
1755 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1756 goto free_ab_and_return;
1757 fprintf(o->file, "%s", header.buf);
1758 strbuf_reset(&header);
1759 if (DIFF_OPT_TST(o, BINARY))
1760 emit_binary_diff(o->file, &mf1, &mf2);
1761 else
1762 fprintf(o->file, "Binary files %s and %s differ\n",
1763 lbl[0], lbl[1]);
1764 o->found_changes = 1;
1766 else {
1767 /* Crazy xdl interfaces.. */
1768 const char *diffopts = getenv("GIT_DIFF_OPTS");
1769 xpparam_t xpp;
1770 xdemitconf_t xecfg;
1771 struct emit_callback ecbdata;
1772 const struct userdiff_funcname *pe;
1774 if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS)) {
1775 fprintf(o->file, "%s", header.buf);
1776 strbuf_reset(&header);
1779 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
1780 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
1782 pe = diff_funcname_pattern(one);
1783 if (!pe)
1784 pe = diff_funcname_pattern(two);
1786 memset(&xpp, 0, sizeof(xpp));
1787 memset(&xecfg, 0, sizeof(xecfg));
1788 memset(&ecbdata, 0, sizeof(ecbdata));
1789 ecbdata.label_path = lbl;
1790 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1791 ecbdata.found_changesp = &o->found_changes;
1792 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1793 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1794 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1795 ecbdata.file = o->file;
1796 ecbdata.header = header.len ? &header : NULL;
1797 xpp.flags = o->xdl_opts;
1798 xecfg.ctxlen = o->context;
1799 xecfg.interhunkctxlen = o->interhunkcontext;
1800 xecfg.flags = XDL_EMIT_FUNCNAMES;
1801 if (pe)
1802 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1803 if (!diffopts)
1805 else if (!prefixcmp(diffopts, "--unified="))
1806 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1807 else if (!prefixcmp(diffopts, "-u"))
1808 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1809 if (o->word_diff) {
1810 int i;
1812 ecbdata.diff_words =
1813 xcalloc(1, sizeof(struct diff_words_data));
1814 ecbdata.diff_words->file = o->file;
1815 ecbdata.diff_words->type = o->word_diff;
1816 if (!o->word_regex)
1817 o->word_regex = userdiff_word_regex(one);
1818 if (!o->word_regex)
1819 o->word_regex = userdiff_word_regex(two);
1820 if (!o->word_regex)
1821 o->word_regex = diff_word_regex_cfg;
1822 if (o->word_regex) {
1823 ecbdata.diff_words->word_regex = (regex_t *)
1824 xmalloc(sizeof(regex_t));
1825 if (regcomp(ecbdata.diff_words->word_regex,
1826 o->word_regex,
1827 REG_EXTENDED | REG_NEWLINE))
1828 die ("Invalid regular expression: %s",
1829 o->word_regex);
1831 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1832 if (o->word_diff == diff_words_styles[i].type) {
1833 ecbdata.diff_words->style =
1834 &diff_words_styles[i];
1835 break;
1838 if (DIFF_OPT_TST(o, COLOR_DIFF)) {
1839 struct diff_words_style *st = ecbdata.diff_words->style;
1840 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1841 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1842 st->ctx.color = diff_get_color_opt(o, DIFF_PLAIN);
1845 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1846 &xpp, &xecfg);
1847 if (o->word_diff)
1848 free_diff_words_data(&ecbdata);
1849 if (textconv_one)
1850 free(mf1.ptr);
1851 if (textconv_two)
1852 free(mf2.ptr);
1853 xdiff_clear_find_func(&xecfg);
1856 free_ab_and_return:
1857 strbuf_release(&header);
1858 diff_free_filespec_data(one);
1859 diff_free_filespec_data(two);
1860 free(a_one);
1861 free(b_two);
1862 return;
1865 static void builtin_diffstat(const char *name_a, const char *name_b,
1866 struct diff_filespec *one,
1867 struct diff_filespec *two,
1868 struct diffstat_t *diffstat,
1869 struct diff_options *o,
1870 int complete_rewrite)
1872 mmfile_t mf1, mf2;
1873 struct diffstat_file *data;
1875 data = diffstat_add(diffstat, name_a, name_b);
1877 if (!one || !two) {
1878 data->is_unmerged = 1;
1879 return;
1881 if (complete_rewrite) {
1882 diff_populate_filespec(one, 0);
1883 diff_populate_filespec(two, 0);
1884 data->deleted = count_lines(one->data, one->size);
1885 data->added = count_lines(two->data, two->size);
1886 goto free_and_return;
1888 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1889 die("unable to read files to diff");
1891 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1892 data->is_binary = 1;
1893 data->added = mf2.size;
1894 data->deleted = mf1.size;
1895 } else {
1896 /* Crazy xdl interfaces.. */
1897 xpparam_t xpp;
1898 xdemitconf_t xecfg;
1900 memset(&xpp, 0, sizeof(xpp));
1901 memset(&xecfg, 0, sizeof(xecfg));
1902 xpp.flags = o->xdl_opts;
1903 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1904 &xpp, &xecfg);
1907 free_and_return:
1908 diff_free_filespec_data(one);
1909 diff_free_filespec_data(two);
1912 static void builtin_checkdiff(const char *name_a, const char *name_b,
1913 const char *attr_path,
1914 struct diff_filespec *one,
1915 struct diff_filespec *two,
1916 struct diff_options *o)
1918 mmfile_t mf1, mf2;
1919 struct checkdiff_t data;
1921 if (!two)
1922 return;
1924 memset(&data, 0, sizeof(data));
1925 data.filename = name_b ? name_b : name_a;
1926 data.lineno = 0;
1927 data.o = o;
1928 data.ws_rule = whitespace_rule(attr_path);
1929 data.conflict_marker_size = ll_merge_marker_size(attr_path);
1931 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1932 die("unable to read files to diff");
1935 * All the other codepaths check both sides, but not checking
1936 * the "old" side here is deliberate. We are checking the newly
1937 * introduced changes, and as long as the "new" side is text, we
1938 * can and should check what it introduces.
1940 if (diff_filespec_is_binary(two))
1941 goto free_and_return;
1942 else {
1943 /* Crazy xdl interfaces.. */
1944 xpparam_t xpp;
1945 xdemitconf_t xecfg;
1947 memset(&xpp, 0, sizeof(xpp));
1948 memset(&xecfg, 0, sizeof(xecfg));
1949 xecfg.ctxlen = 1; /* at least one context line */
1950 xpp.flags = 0;
1951 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1952 &xpp, &xecfg);
1954 if (data.ws_rule & WS_BLANK_AT_EOF) {
1955 struct emit_callback ecbdata;
1956 int blank_at_eof;
1958 ecbdata.ws_rule = data.ws_rule;
1959 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1960 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
1962 if (blank_at_eof) {
1963 static char *err;
1964 if (!err)
1965 err = whitespace_error_string(WS_BLANK_AT_EOF);
1966 fprintf(o->file, "%s:%d: %s.\n",
1967 data.filename, blank_at_eof, err);
1968 data.status = 1; /* report errors */
1972 free_and_return:
1973 diff_free_filespec_data(one);
1974 diff_free_filespec_data(two);
1975 if (data.status)
1976 DIFF_OPT_SET(o, CHECK_FAILED);
1979 struct diff_filespec *alloc_filespec(const char *path)
1981 int namelen = strlen(path);
1982 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1984 memset(spec, 0, sizeof(*spec));
1985 spec->path = (char *)(spec + 1);
1986 memcpy(spec->path, path, namelen+1);
1987 spec->count = 1;
1988 spec->is_binary = -1;
1989 return spec;
1992 void free_filespec(struct diff_filespec *spec)
1994 if (!--spec->count) {
1995 diff_free_filespec_data(spec);
1996 free(spec);
2000 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
2001 unsigned short mode)
2003 if (mode) {
2004 spec->mode = canon_mode(mode);
2005 hashcpy(spec->sha1, sha1);
2006 spec->sha1_valid = !is_null_sha1(sha1);
2011 * Given a name and sha1 pair, if the index tells us the file in
2012 * the work tree has that object contents, return true, so that
2013 * prepare_temp_file() does not have to inflate and extract.
2015 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2017 struct cache_entry *ce;
2018 struct stat st;
2019 int pos, len;
2022 * We do not read the cache ourselves here, because the
2023 * benchmark with my previous version that always reads cache
2024 * shows that it makes things worse for diff-tree comparing
2025 * two linux-2.6 kernel trees in an already checked out work
2026 * tree. This is because most diff-tree comparisons deal with
2027 * only a small number of files, while reading the cache is
2028 * expensive for a large project, and its cost outweighs the
2029 * savings we get by not inflating the object to a temporary
2030 * file. Practically, this code only helps when we are used
2031 * by diff-cache --cached, which does read the cache before
2032 * calling us.
2034 if (!active_cache)
2035 return 0;
2037 /* We want to avoid the working directory if our caller
2038 * doesn't need the data in a normal file, this system
2039 * is rather slow with its stat/open/mmap/close syscalls,
2040 * and the object is contained in a pack file. The pack
2041 * is probably already open and will be faster to obtain
2042 * the data through than the working directory. Loose
2043 * objects however would tend to be slower as they need
2044 * to be individually opened and inflated.
2046 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2047 return 0;
2049 len = strlen(name);
2050 pos = cache_name_pos(name, len);
2051 if (pos < 0)
2052 return 0;
2053 ce = active_cache[pos];
2056 * This is not the sha1 we are looking for, or
2057 * unreusable because it is not a regular file.
2059 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
2060 return 0;
2063 * If ce is marked as "assume unchanged", there is no
2064 * guarantee that work tree matches what we are looking for.
2066 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2067 return 0;
2070 * If ce matches the file in the work tree, we can reuse it.
2072 if (ce_uptodate(ce) ||
2073 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2074 return 1;
2076 return 0;
2079 static int populate_from_stdin(struct diff_filespec *s)
2081 struct strbuf buf = STRBUF_INIT;
2082 size_t size = 0;
2084 if (strbuf_read(&buf, 0, 0) < 0)
2085 return error("error while reading from stdin %s",
2086 strerror(errno));
2088 s->should_munmap = 0;
2089 s->data = strbuf_detach(&buf, &size);
2090 s->size = size;
2091 s->should_free = 1;
2092 return 0;
2095 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2097 int len;
2098 char *data = xmalloc(100), *dirty = "";
2100 /* Are we looking at the work tree? */
2101 if (s->dirty_submodule)
2102 dirty = "-dirty";
2104 len = snprintf(data, 100,
2105 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2106 s->data = data;
2107 s->size = len;
2108 s->should_free = 1;
2109 if (size_only) {
2110 s->data = NULL;
2111 free(data);
2113 return 0;
2117 * While doing rename detection and pickaxe operation, we may need to
2118 * grab the data for the blob (or file) for our own in-core comparison.
2119 * diff_filespec has data and size fields for this purpose.
2121 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2123 int err = 0;
2124 if (!DIFF_FILE_VALID(s))
2125 die("internal error: asking to populate invalid file.");
2126 if (S_ISDIR(s->mode))
2127 return -1;
2129 if (s->data)
2130 return 0;
2132 if (size_only && 0 < s->size)
2133 return 0;
2135 if (S_ISGITLINK(s->mode))
2136 return diff_populate_gitlink(s, size_only);
2138 if (!s->sha1_valid ||
2139 reuse_worktree_file(s->path, s->sha1, 0)) {
2140 struct strbuf buf = STRBUF_INIT;
2141 struct stat st;
2142 int fd;
2144 if (!strcmp(s->path, "-"))
2145 return populate_from_stdin(s);
2147 if (lstat(s->path, &st) < 0) {
2148 if (errno == ENOENT) {
2149 err_empty:
2150 err = -1;
2151 empty:
2152 s->data = (char *)"";
2153 s->size = 0;
2154 return err;
2157 s->size = xsize_t(st.st_size);
2158 if (!s->size)
2159 goto empty;
2160 if (S_ISLNK(st.st_mode)) {
2161 struct strbuf sb = STRBUF_INIT;
2163 if (strbuf_readlink(&sb, s->path, s->size))
2164 goto err_empty;
2165 s->size = sb.len;
2166 s->data = strbuf_detach(&sb, NULL);
2167 s->should_free = 1;
2168 return 0;
2170 if (size_only)
2171 return 0;
2172 fd = open(s->path, O_RDONLY);
2173 if (fd < 0)
2174 goto err_empty;
2175 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2176 close(fd);
2177 s->should_munmap = 1;
2180 * Convert from working tree format to canonical git format
2182 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2183 size_t size = 0;
2184 munmap(s->data, s->size);
2185 s->should_munmap = 0;
2186 s->data = strbuf_detach(&buf, &size);
2187 s->size = size;
2188 s->should_free = 1;
2191 else {
2192 enum object_type type;
2193 if (size_only)
2194 type = sha1_object_info(s->sha1, &s->size);
2195 else {
2196 s->data = read_sha1_file(s->sha1, &type, &s->size);
2197 s->should_free = 1;
2200 return 0;
2203 void diff_free_filespec_blob(struct diff_filespec *s)
2205 if (s->should_free)
2206 free(s->data);
2207 else if (s->should_munmap)
2208 munmap(s->data, s->size);
2210 if (s->should_free || s->should_munmap) {
2211 s->should_free = s->should_munmap = 0;
2212 s->data = NULL;
2216 void diff_free_filespec_data(struct diff_filespec *s)
2218 diff_free_filespec_blob(s);
2219 free(s->cnt_data);
2220 s->cnt_data = NULL;
2223 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2224 void *blob,
2225 unsigned long size,
2226 const unsigned char *sha1,
2227 int mode)
2229 int fd;
2230 struct strbuf buf = STRBUF_INIT;
2231 struct strbuf template = STRBUF_INIT;
2232 char *path_dup = xstrdup(path);
2233 const char *base = basename(path_dup);
2235 /* Generate "XXXXXX_basename.ext" */
2236 strbuf_addstr(&template, "XXXXXX_");
2237 strbuf_addstr(&template, base);
2239 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2240 strlen(base) + 1);
2241 if (fd < 0)
2242 die_errno("unable to create temp-file");
2243 if (convert_to_working_tree(path,
2244 (const char *)blob, (size_t)size, &buf)) {
2245 blob = buf.buf;
2246 size = buf.len;
2248 if (write_in_full(fd, blob, size) != size)
2249 die_errno("unable to write temp-file");
2250 close(fd);
2251 temp->name = temp->tmp_path;
2252 strcpy(temp->hex, sha1_to_hex(sha1));
2253 temp->hex[40] = 0;
2254 sprintf(temp->mode, "%06o", mode);
2255 strbuf_release(&buf);
2256 strbuf_release(&template);
2257 free(path_dup);
2260 static struct diff_tempfile *prepare_temp_file(const char *name,
2261 struct diff_filespec *one)
2263 struct diff_tempfile *temp = claim_diff_tempfile();
2265 if (!DIFF_FILE_VALID(one)) {
2266 not_a_valid_file:
2267 /* A '-' entry produces this for file-2, and
2268 * a '+' entry produces this for file-1.
2270 temp->name = "/dev/null";
2271 strcpy(temp->hex, ".");
2272 strcpy(temp->mode, ".");
2273 return temp;
2276 if (!remove_tempfile_installed) {
2277 atexit(remove_tempfile);
2278 sigchain_push_common(remove_tempfile_on_signal);
2279 remove_tempfile_installed = 1;
2282 if (!one->sha1_valid ||
2283 reuse_worktree_file(name, one->sha1, 1)) {
2284 struct stat st;
2285 if (lstat(name, &st) < 0) {
2286 if (errno == ENOENT)
2287 goto not_a_valid_file;
2288 die_errno("stat(%s)", name);
2290 if (S_ISLNK(st.st_mode)) {
2291 struct strbuf sb = STRBUF_INIT;
2292 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2293 die_errno("readlink(%s)", name);
2294 prep_temp_blob(name, temp, sb.buf, sb.len,
2295 (one->sha1_valid ?
2296 one->sha1 : null_sha1),
2297 (one->sha1_valid ?
2298 one->mode : S_IFLNK));
2299 strbuf_release(&sb);
2301 else {
2302 /* we can borrow from the file in the work tree */
2303 temp->name = name;
2304 if (!one->sha1_valid)
2305 strcpy(temp->hex, sha1_to_hex(null_sha1));
2306 else
2307 strcpy(temp->hex, sha1_to_hex(one->sha1));
2308 /* Even though we may sometimes borrow the
2309 * contents from the work tree, we always want
2310 * one->mode. mode is trustworthy even when
2311 * !(one->sha1_valid), as long as
2312 * DIFF_FILE_VALID(one).
2314 sprintf(temp->mode, "%06o", one->mode);
2316 return temp;
2318 else {
2319 if (diff_populate_filespec(one, 0))
2320 die("cannot read data blob for %s", one->path);
2321 prep_temp_blob(name, temp, one->data, one->size,
2322 one->sha1, one->mode);
2324 return temp;
2327 /* An external diff command takes:
2329 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2330 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2333 static void run_external_diff(const char *pgm,
2334 const char *name,
2335 const char *other,
2336 struct diff_filespec *one,
2337 struct diff_filespec *two,
2338 const char *xfrm_msg,
2339 int complete_rewrite)
2341 const char *spawn_arg[10];
2342 int retval;
2343 const char **arg = &spawn_arg[0];
2345 if (one && two) {
2346 struct diff_tempfile *temp_one, *temp_two;
2347 const char *othername = (other ? other : name);
2348 temp_one = prepare_temp_file(name, one);
2349 temp_two = prepare_temp_file(othername, two);
2350 *arg++ = pgm;
2351 *arg++ = name;
2352 *arg++ = temp_one->name;
2353 *arg++ = temp_one->hex;
2354 *arg++ = temp_one->mode;
2355 *arg++ = temp_two->name;
2356 *arg++ = temp_two->hex;
2357 *arg++ = temp_two->mode;
2358 if (other) {
2359 *arg++ = other;
2360 *arg++ = xfrm_msg;
2362 } else {
2363 *arg++ = pgm;
2364 *arg++ = name;
2366 *arg = NULL;
2367 fflush(NULL);
2368 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2369 remove_tempfile();
2370 if (retval) {
2371 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2372 exit(1);
2376 static int similarity_index(struct diff_filepair *p)
2378 return p->score * 100 / MAX_SCORE;
2381 static void fill_metainfo(struct strbuf *msg,
2382 const char *name,
2383 const char *other,
2384 struct diff_filespec *one,
2385 struct diff_filespec *two,
2386 struct diff_options *o,
2387 struct diff_filepair *p,
2388 int use_color)
2390 const char *set = diff_get_color(use_color, DIFF_METAINFO);
2391 const char *reset = diff_get_color(use_color, DIFF_RESET);
2393 strbuf_init(msg, PATH_MAX * 2 + 300);
2394 switch (p->status) {
2395 case DIFF_STATUS_COPIED:
2396 strbuf_addf(msg, "%ssimilarity index %d%%",
2397 set, similarity_index(p));
2398 strbuf_addf(msg, "%s\n%scopy from ", reset, set);
2399 quote_c_style(name, msg, NULL, 0);
2400 strbuf_addf(msg, "%s\n%scopy to ", reset, set);
2401 quote_c_style(other, msg, NULL, 0);
2402 strbuf_addf(msg, "%s\n", reset);
2403 break;
2404 case DIFF_STATUS_RENAMED:
2405 strbuf_addf(msg, "%ssimilarity index %d%%",
2406 set, similarity_index(p));
2407 strbuf_addf(msg, "%s\n%srename from ", reset, set);
2408 quote_c_style(name, msg, NULL, 0);
2409 strbuf_addf(msg, "%s\n%srename to ", reset, set);
2410 quote_c_style(other, msg, NULL, 0);
2411 strbuf_addf(msg, "%s\n", reset);
2412 break;
2413 case DIFF_STATUS_MODIFIED:
2414 if (p->score) {
2415 strbuf_addf(msg, "%sdissimilarity index %d%%%s\n",
2416 set, similarity_index(p), reset);
2417 break;
2419 /* fallthru */
2420 default:
2421 /* nothing */
2424 if (one && two && hashcmp(one->sha1, two->sha1)) {
2425 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2427 if (DIFF_OPT_TST(o, BINARY)) {
2428 mmfile_t mf;
2429 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2430 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2431 abbrev = 40;
2433 strbuf_addf(msg, "%sindex %s..", set,
2434 find_unique_abbrev(one->sha1, abbrev));
2435 strbuf_addstr(msg, find_unique_abbrev(two->sha1, abbrev));
2436 if (one->mode == two->mode)
2437 strbuf_addf(msg, " %06o", one->mode);
2438 strbuf_addf(msg, "%s\n", reset);
2442 static void run_diff_cmd(const char *pgm,
2443 const char *name,
2444 const char *other,
2445 const char *attr_path,
2446 struct diff_filespec *one,
2447 struct diff_filespec *two,
2448 struct strbuf *msg,
2449 struct diff_options *o,
2450 struct diff_filepair *p)
2452 const char *xfrm_msg = NULL;
2453 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2455 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2456 pgm = NULL;
2457 else {
2458 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2459 if (drv && drv->external)
2460 pgm = drv->external;
2463 if (msg) {
2465 * don't use colors when the header is intended for an
2466 * external diff driver
2468 fill_metainfo(msg, name, other, one, two, o, p,
2469 DIFF_OPT_TST(o, COLOR_DIFF) && !pgm);
2470 xfrm_msg = msg->len ? msg->buf : NULL;
2473 if (pgm) {
2474 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2475 complete_rewrite);
2476 return;
2478 if (one && two)
2479 builtin_diff(name, other ? other : name,
2480 one, two, xfrm_msg, o, complete_rewrite);
2481 else
2482 fprintf(o->file, "* Unmerged path %s\n", name);
2485 static void diff_fill_sha1_info(struct diff_filespec *one)
2487 if (DIFF_FILE_VALID(one)) {
2488 if (!one->sha1_valid) {
2489 struct stat st;
2490 if (!strcmp(one->path, "-")) {
2491 hashcpy(one->sha1, null_sha1);
2492 return;
2494 if (lstat(one->path, &st) < 0)
2495 die_errno("stat '%s'", one->path);
2496 if (index_path(one->sha1, one->path, &st, 0))
2497 die("cannot hash %s", one->path);
2500 else
2501 hashclr(one->sha1);
2504 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2506 /* Strip the prefix but do not molest /dev/null and absolute paths */
2507 if (*namep && **namep != '/')
2508 *namep += prefix_length;
2509 if (*otherp && **otherp != '/')
2510 *otherp += prefix_length;
2513 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2515 const char *pgm = external_diff();
2516 struct strbuf msg;
2517 struct diff_filespec *one = p->one;
2518 struct diff_filespec *two = p->two;
2519 const char *name;
2520 const char *other;
2521 const char *attr_path;
2523 name = p->one->path;
2524 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2525 attr_path = name;
2526 if (o->prefix_length)
2527 strip_prefix(o->prefix_length, &name, &other);
2529 if (DIFF_PAIR_UNMERGED(p)) {
2530 run_diff_cmd(pgm, name, NULL, attr_path,
2531 NULL, NULL, NULL, o, p);
2532 return;
2535 diff_fill_sha1_info(one);
2536 diff_fill_sha1_info(two);
2538 if (!pgm &&
2539 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2540 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2542 * a filepair that changes between file and symlink
2543 * needs to be split into deletion and creation.
2545 struct diff_filespec *null = alloc_filespec(two->path);
2546 run_diff_cmd(NULL, name, other, attr_path,
2547 one, null, &msg, o, p);
2548 free(null);
2549 strbuf_release(&msg);
2551 null = alloc_filespec(one->path);
2552 run_diff_cmd(NULL, name, other, attr_path,
2553 null, two, &msg, o, p);
2554 free(null);
2556 else
2557 run_diff_cmd(pgm, name, other, attr_path,
2558 one, two, &msg, o, p);
2560 strbuf_release(&msg);
2563 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2564 struct diffstat_t *diffstat)
2566 const char *name;
2567 const char *other;
2568 int complete_rewrite = 0;
2570 if (DIFF_PAIR_UNMERGED(p)) {
2571 /* unmerged */
2572 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2573 return;
2576 name = p->one->path;
2577 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2579 if (o->prefix_length)
2580 strip_prefix(o->prefix_length, &name, &other);
2582 diff_fill_sha1_info(p->one);
2583 diff_fill_sha1_info(p->two);
2585 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2586 complete_rewrite = 1;
2587 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2590 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2592 const char *name;
2593 const char *other;
2594 const char *attr_path;
2596 if (DIFF_PAIR_UNMERGED(p)) {
2597 /* unmerged */
2598 return;
2601 name = p->one->path;
2602 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2603 attr_path = other ? other : name;
2605 if (o->prefix_length)
2606 strip_prefix(o->prefix_length, &name, &other);
2608 diff_fill_sha1_info(p->one);
2609 diff_fill_sha1_info(p->two);
2611 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2614 void diff_setup(struct diff_options *options)
2616 memset(options, 0, sizeof(*options));
2617 memset(&diff_queued_diff, 0, sizeof(diff_queued_diff));
2619 options->file = stdout;
2621 options->line_termination = '\n';
2622 options->break_opt = -1;
2623 options->rename_limit = -1;
2624 options->dirstat_percent = 3;
2625 options->context = 3;
2627 options->change = diff_change;
2628 options->add_remove = diff_addremove;
2629 if (diff_use_color_default > 0)
2630 DIFF_OPT_SET(options, COLOR_DIFF);
2631 options->detect_rename = diff_detect_rename_default;
2633 if (diff_no_prefix) {
2634 options->a_prefix = options->b_prefix = "";
2635 } else if (!diff_mnemonic_prefix) {
2636 options->a_prefix = "a/";
2637 options->b_prefix = "b/";
2641 int diff_setup_done(struct diff_options *options)
2643 int count = 0;
2645 if (options->output_format & DIFF_FORMAT_NAME)
2646 count++;
2647 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2648 count++;
2649 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2650 count++;
2651 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2652 count++;
2653 if (count > 1)
2654 die("--name-only, --name-status, --check and -s are mutually exclusive");
2657 * Most of the time we can say "there are changes"
2658 * only by checking if there are changed paths, but
2659 * --ignore-whitespace* options force us to look
2660 * inside contents.
2663 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2664 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2665 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2666 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2667 else
2668 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2670 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2671 options->detect_rename = DIFF_DETECT_COPY;
2673 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2674 options->prefix = NULL;
2675 if (options->prefix)
2676 options->prefix_length = strlen(options->prefix);
2677 else
2678 options->prefix_length = 0;
2680 if (options->output_format & (DIFF_FORMAT_NAME |
2681 DIFF_FORMAT_NAME_STATUS |
2682 DIFF_FORMAT_CHECKDIFF |
2683 DIFF_FORMAT_NO_OUTPUT))
2684 options->output_format &= ~(DIFF_FORMAT_RAW |
2685 DIFF_FORMAT_NUMSTAT |
2686 DIFF_FORMAT_DIFFSTAT |
2687 DIFF_FORMAT_SHORTSTAT |
2688 DIFF_FORMAT_DIRSTAT |
2689 DIFF_FORMAT_SUMMARY |
2690 DIFF_FORMAT_PATCH);
2693 * These cases always need recursive; we do not drop caller-supplied
2694 * recursive bits for other formats here.
2696 if (options->output_format & (DIFF_FORMAT_PATCH |
2697 DIFF_FORMAT_NUMSTAT |
2698 DIFF_FORMAT_DIFFSTAT |
2699 DIFF_FORMAT_SHORTSTAT |
2700 DIFF_FORMAT_DIRSTAT |
2701 DIFF_FORMAT_SUMMARY |
2702 DIFF_FORMAT_CHECKDIFF))
2703 DIFF_OPT_SET(options, RECURSIVE);
2705 * Also pickaxe would not work very well if you do not say recursive
2707 if (options->pickaxe)
2708 DIFF_OPT_SET(options, RECURSIVE);
2710 * When patches are generated, submodules diffed against the work tree
2711 * must be checked for dirtiness too so it can be shown in the output
2713 if (options->output_format & DIFF_FORMAT_PATCH)
2714 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
2716 if (options->detect_rename && options->rename_limit < 0)
2717 options->rename_limit = diff_rename_limit_default;
2718 if (options->setup & DIFF_SETUP_USE_CACHE) {
2719 if (!active_cache)
2720 /* read-cache does not die even when it fails
2721 * so it is safe for us to do this here. Also
2722 * it does not smudge active_cache or active_nr
2723 * when it fails, so we do not have to worry about
2724 * cleaning it up ourselves either.
2726 read_cache();
2728 if (options->abbrev <= 0 || 40 < options->abbrev)
2729 options->abbrev = 40; /* full */
2732 * It does not make sense to show the first hit we happened
2733 * to have found. It does not make sense not to return with
2734 * exit code in such a case either.
2736 if (DIFF_OPT_TST(options, QUICK)) {
2737 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2738 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2741 return 0;
2744 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2746 char c, *eq;
2747 int len;
2749 if (*arg != '-')
2750 return 0;
2751 c = *++arg;
2752 if (!c)
2753 return 0;
2754 if (c == arg_short) {
2755 c = *++arg;
2756 if (!c)
2757 return 1;
2758 if (val && isdigit(c)) {
2759 char *end;
2760 int n = strtoul(arg, &end, 10);
2761 if (*end)
2762 return 0;
2763 *val = n;
2764 return 1;
2766 return 0;
2768 if (c != '-')
2769 return 0;
2770 arg++;
2771 eq = strchr(arg, '=');
2772 if (eq)
2773 len = eq - arg;
2774 else
2775 len = strlen(arg);
2776 if (!len || strncmp(arg, arg_long, len))
2777 return 0;
2778 if (eq) {
2779 int n;
2780 char *end;
2781 if (!isdigit(*++eq))
2782 return 0;
2783 n = strtoul(eq, &end, 10);
2784 if (*end)
2785 return 0;
2786 *val = n;
2788 return 1;
2791 static int diff_scoreopt_parse(const char *opt);
2793 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2795 const char *arg = av[0];
2797 /* Output format options */
2798 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch"))
2799 options->output_format |= DIFF_FORMAT_PATCH;
2800 else if (opt_arg(arg, 'U', "unified", &options->context))
2801 options->output_format |= DIFF_FORMAT_PATCH;
2802 else if (!strcmp(arg, "--raw"))
2803 options->output_format |= DIFF_FORMAT_RAW;
2804 else if (!strcmp(arg, "--patch-with-raw"))
2805 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2806 else if (!strcmp(arg, "--numstat"))
2807 options->output_format |= DIFF_FORMAT_NUMSTAT;
2808 else if (!strcmp(arg, "--shortstat"))
2809 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2810 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2811 options->output_format |= DIFF_FORMAT_DIRSTAT;
2812 else if (!strcmp(arg, "--cumulative")) {
2813 options->output_format |= DIFF_FORMAT_DIRSTAT;
2814 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2815 } else if (opt_arg(arg, 0, "dirstat-by-file",
2816 &options->dirstat_percent)) {
2817 options->output_format |= DIFF_FORMAT_DIRSTAT;
2818 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2820 else if (!strcmp(arg, "--check"))
2821 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2822 else if (!strcmp(arg, "--summary"))
2823 options->output_format |= DIFF_FORMAT_SUMMARY;
2824 else if (!strcmp(arg, "--patch-with-stat"))
2825 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2826 else if (!strcmp(arg, "--name-only"))
2827 options->output_format |= DIFF_FORMAT_NAME;
2828 else if (!strcmp(arg, "--name-status"))
2829 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2830 else if (!strcmp(arg, "-s"))
2831 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2832 else if (!prefixcmp(arg, "--stat")) {
2833 char *end;
2834 int width = options->stat_width;
2835 int name_width = options->stat_name_width;
2836 arg += 6;
2837 end = (char *)arg;
2839 switch (*arg) {
2840 case '-':
2841 if (!prefixcmp(arg, "-width="))
2842 width = strtoul(arg + 7, &end, 10);
2843 else if (!prefixcmp(arg, "-name-width="))
2844 name_width = strtoul(arg + 12, &end, 10);
2845 break;
2846 case '=':
2847 width = strtoul(arg+1, &end, 10);
2848 if (*end == ',')
2849 name_width = strtoul(end+1, &end, 10);
2852 /* Important! This checks all the error cases! */
2853 if (*end)
2854 return 0;
2855 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2856 options->stat_name_width = name_width;
2857 options->stat_width = width;
2860 /* renames options */
2861 else if (!prefixcmp(arg, "-B")) {
2862 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2863 return -1;
2865 else if (!prefixcmp(arg, "-M")) {
2866 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2867 return -1;
2868 options->detect_rename = DIFF_DETECT_RENAME;
2870 else if (!prefixcmp(arg, "-C")) {
2871 if (options->detect_rename == DIFF_DETECT_COPY)
2872 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2873 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2874 return -1;
2875 options->detect_rename = DIFF_DETECT_COPY;
2877 else if (!strcmp(arg, "--no-renames"))
2878 options->detect_rename = 0;
2879 else if (!strcmp(arg, "--relative"))
2880 DIFF_OPT_SET(options, RELATIVE_NAME);
2881 else if (!prefixcmp(arg, "--relative=")) {
2882 DIFF_OPT_SET(options, RELATIVE_NAME);
2883 options->prefix = arg + 11;
2886 /* xdiff options */
2887 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2888 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2889 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2890 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2891 else if (!strcmp(arg, "--ignore-space-at-eol"))
2892 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2893 else if (!strcmp(arg, "--patience"))
2894 DIFF_XDL_SET(options, PATIENCE_DIFF);
2896 /* flags options */
2897 else if (!strcmp(arg, "--binary")) {
2898 options->output_format |= DIFF_FORMAT_PATCH;
2899 DIFF_OPT_SET(options, BINARY);
2901 else if (!strcmp(arg, "--full-index"))
2902 DIFF_OPT_SET(options, FULL_INDEX);
2903 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2904 DIFF_OPT_SET(options, TEXT);
2905 else if (!strcmp(arg, "-R"))
2906 DIFF_OPT_SET(options, REVERSE_DIFF);
2907 else if (!strcmp(arg, "--find-copies-harder"))
2908 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2909 else if (!strcmp(arg, "--follow"))
2910 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2911 else if (!strcmp(arg, "--color"))
2912 DIFF_OPT_SET(options, COLOR_DIFF);
2913 else if (!prefixcmp(arg, "--color=")) {
2914 int value = git_config_colorbool(NULL, arg+8, -1);
2915 if (value == 0)
2916 DIFF_OPT_CLR(options, COLOR_DIFF);
2917 else if (value > 0)
2918 DIFF_OPT_SET(options, COLOR_DIFF);
2919 else
2920 return error("option `color' expects \"always\", \"auto\", or \"never\"");
2922 else if (!strcmp(arg, "--no-color"))
2923 DIFF_OPT_CLR(options, COLOR_DIFF);
2924 else if (!strcmp(arg, "--color-words")) {
2925 DIFF_OPT_SET(options, COLOR_DIFF);
2926 options->word_diff = DIFF_WORDS_COLOR;
2928 else if (!prefixcmp(arg, "--color-words=")) {
2929 DIFF_OPT_SET(options, COLOR_DIFF);
2930 options->word_diff = DIFF_WORDS_COLOR;
2931 options->word_regex = arg + 14;
2933 else if (!strcmp(arg, "--word-diff")) {
2934 if (options->word_diff == DIFF_WORDS_NONE)
2935 options->word_diff = DIFF_WORDS_PLAIN;
2937 else if (!prefixcmp(arg, "--word-diff=")) {
2938 const char *type = arg + 12;
2939 if (!strcmp(type, "plain"))
2940 options->word_diff = DIFF_WORDS_PLAIN;
2941 else if (!strcmp(type, "color")) {
2942 DIFF_OPT_SET(options, COLOR_DIFF);
2943 options->word_diff = DIFF_WORDS_COLOR;
2945 else if (!strcmp(type, "porcelain"))
2946 options->word_diff = DIFF_WORDS_PORCELAIN;
2947 else if (!strcmp(type, "none"))
2948 options->word_diff = DIFF_WORDS_NONE;
2949 else
2950 die("bad --word-diff argument: %s", type);
2952 else if (!prefixcmp(arg, "--word-diff-regex=")) {
2953 if (options->word_diff == DIFF_WORDS_NONE)
2954 options->word_diff = DIFF_WORDS_PLAIN;
2955 options->word_regex = arg + 18;
2957 else if (!strcmp(arg, "--exit-code"))
2958 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2959 else if (!strcmp(arg, "--quiet"))
2960 DIFF_OPT_SET(options, QUICK);
2961 else if (!strcmp(arg, "--ext-diff"))
2962 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2963 else if (!strcmp(arg, "--no-ext-diff"))
2964 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2965 else if (!strcmp(arg, "--textconv"))
2966 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2967 else if (!strcmp(arg, "--no-textconv"))
2968 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2969 else if (!strcmp(arg, "--ignore-submodules"))
2970 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2971 else if (!strcmp(arg, "--submodule"))
2972 DIFF_OPT_SET(options, SUBMODULE_LOG);
2973 else if (!prefixcmp(arg, "--submodule=")) {
2974 if (!strcmp(arg + 12, "log"))
2975 DIFF_OPT_SET(options, SUBMODULE_LOG);
2978 /* misc options */
2979 else if (!strcmp(arg, "-z"))
2980 options->line_termination = 0;
2981 else if (!prefixcmp(arg, "-l"))
2982 options->rename_limit = strtoul(arg+2, NULL, 10);
2983 else if (!prefixcmp(arg, "-S"))
2984 options->pickaxe = arg + 2;
2985 else if (!strcmp(arg, "--pickaxe-all"))
2986 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2987 else if (!strcmp(arg, "--pickaxe-regex"))
2988 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2989 else if (!prefixcmp(arg, "-O"))
2990 options->orderfile = arg + 2;
2991 else if (!prefixcmp(arg, "--diff-filter="))
2992 options->filter = arg + 14;
2993 else if (!strcmp(arg, "--abbrev"))
2994 options->abbrev = DEFAULT_ABBREV;
2995 else if (!prefixcmp(arg, "--abbrev=")) {
2996 options->abbrev = strtoul(arg + 9, NULL, 10);
2997 if (options->abbrev < MINIMUM_ABBREV)
2998 options->abbrev = MINIMUM_ABBREV;
2999 else if (40 < options->abbrev)
3000 options->abbrev = 40;
3002 else if (!prefixcmp(arg, "--src-prefix="))
3003 options->a_prefix = arg + 13;
3004 else if (!prefixcmp(arg, "--dst-prefix="))
3005 options->b_prefix = arg + 13;
3006 else if (!strcmp(arg, "--no-prefix"))
3007 options->a_prefix = options->b_prefix = "";
3008 else if (opt_arg(arg, '\0', "inter-hunk-context",
3009 &options->interhunkcontext))
3011 else if (!prefixcmp(arg, "--output=")) {
3012 options->file = fopen(arg + strlen("--output="), "w");
3013 if (!options->file)
3014 die_errno("Could not open '%s'", arg + strlen("--output="));
3015 options->close_file = 1;
3016 } else
3017 return 0;
3018 return 1;
3021 static int parse_num(const char **cp_p)
3023 unsigned long num, scale;
3024 int ch, dot;
3025 const char *cp = *cp_p;
3027 num = 0;
3028 scale = 1;
3029 dot = 0;
3030 for (;;) {
3031 ch = *cp;
3032 if ( !dot && ch == '.' ) {
3033 scale = 1;
3034 dot = 1;
3035 } else if ( ch == '%' ) {
3036 scale = dot ? scale*100 : 100;
3037 cp++; /* % is always at the end */
3038 break;
3039 } else if ( ch >= '0' && ch <= '9' ) {
3040 if ( scale < 100000 ) {
3041 scale *= 10;
3042 num = (num*10) + (ch-'0');
3044 } else {
3045 break;
3047 cp++;
3049 *cp_p = cp;
3051 /* user says num divided by scale and we say internally that
3052 * is MAX_SCORE * num / scale.
3054 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3057 static int diff_scoreopt_parse(const char *opt)
3059 int opt1, opt2, cmd;
3061 if (*opt++ != '-')
3062 return -1;
3063 cmd = *opt++;
3064 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3065 return -1; /* that is not a -M, -C nor -B option */
3067 opt1 = parse_num(&opt);
3068 if (cmd != 'B')
3069 opt2 = 0;
3070 else {
3071 if (*opt == 0)
3072 opt2 = 0;
3073 else if (*opt != '/')
3074 return -1; /* we expect -B80/99 or -B80 */
3075 else {
3076 opt++;
3077 opt2 = parse_num(&opt);
3080 if (*opt != 0)
3081 return -1;
3082 return opt1 | (opt2 << 16);
3085 struct diff_queue_struct diff_queued_diff;
3087 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3089 if (queue->alloc <= queue->nr) {
3090 queue->alloc = alloc_nr(queue->alloc);
3091 queue->queue = xrealloc(queue->queue,
3092 sizeof(dp) * queue->alloc);
3094 queue->queue[queue->nr++] = dp;
3097 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3098 struct diff_filespec *one,
3099 struct diff_filespec *two)
3101 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3102 dp->one = one;
3103 dp->two = two;
3104 if (queue)
3105 diff_q(queue, dp);
3106 return dp;
3109 void diff_free_filepair(struct diff_filepair *p)
3111 free_filespec(p->one);
3112 free_filespec(p->two);
3113 free(p);
3116 /* This is different from find_unique_abbrev() in that
3117 * it stuffs the result with dots for alignment.
3119 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3121 int abblen;
3122 const char *abbrev;
3123 if (len == 40)
3124 return sha1_to_hex(sha1);
3126 abbrev = find_unique_abbrev(sha1, len);
3127 abblen = strlen(abbrev);
3128 if (abblen < 37) {
3129 static char hex[41];
3130 if (len < abblen && abblen <= len + 2)
3131 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3132 else
3133 sprintf(hex, "%s...", abbrev);
3134 return hex;
3136 return sha1_to_hex(sha1);
3139 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3141 int line_termination = opt->line_termination;
3142 int inter_name_termination = line_termination ? '\t' : '\0';
3144 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3145 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3146 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3147 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3149 if (p->score) {
3150 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3151 inter_name_termination);
3152 } else {
3153 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3156 if (p->status == DIFF_STATUS_COPIED ||
3157 p->status == DIFF_STATUS_RENAMED) {
3158 const char *name_a, *name_b;
3159 name_a = p->one->path;
3160 name_b = p->two->path;
3161 strip_prefix(opt->prefix_length, &name_a, &name_b);
3162 write_name_quoted(name_a, opt->file, inter_name_termination);
3163 write_name_quoted(name_b, opt->file, line_termination);
3164 } else {
3165 const char *name_a, *name_b;
3166 name_a = p->one->mode ? p->one->path : p->two->path;
3167 name_b = NULL;
3168 strip_prefix(opt->prefix_length, &name_a, &name_b);
3169 write_name_quoted(name_a, opt->file, line_termination);
3173 int diff_unmodified_pair(struct diff_filepair *p)
3175 /* This function is written stricter than necessary to support
3176 * the currently implemented transformers, but the idea is to
3177 * let transformers to produce diff_filepairs any way they want,
3178 * and filter and clean them up here before producing the output.
3180 struct diff_filespec *one = p->one, *two = p->two;
3182 if (DIFF_PAIR_UNMERGED(p))
3183 return 0; /* unmerged is interesting */
3185 /* deletion, addition, mode or type change
3186 * and rename are all interesting.
3188 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3189 DIFF_PAIR_MODE_CHANGED(p) ||
3190 strcmp(one->path, two->path))
3191 return 0;
3193 /* both are valid and point at the same path. that is, we are
3194 * dealing with a change.
3196 if (one->sha1_valid && two->sha1_valid &&
3197 !hashcmp(one->sha1, two->sha1) &&
3198 !one->dirty_submodule && !two->dirty_submodule)
3199 return 1; /* no change */
3200 if (!one->sha1_valid && !two->sha1_valid)
3201 return 1; /* both look at the same file on the filesystem. */
3202 return 0;
3205 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3207 if (diff_unmodified_pair(p))
3208 return;
3210 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3211 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3212 return; /* no tree diffs in patch format */
3214 run_diff(p, o);
3217 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3218 struct diffstat_t *diffstat)
3220 if (diff_unmodified_pair(p))
3221 return;
3223 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3224 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3225 return; /* no tree diffs in patch format */
3227 run_diffstat(p, o, diffstat);
3230 static void diff_flush_checkdiff(struct diff_filepair *p,
3231 struct diff_options *o)
3233 if (diff_unmodified_pair(p))
3234 return;
3236 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3237 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3238 return; /* no tree diffs in patch format */
3240 run_checkdiff(p, o);
3243 int diff_queue_is_empty(void)
3245 struct diff_queue_struct *q = &diff_queued_diff;
3246 int i;
3247 for (i = 0; i < q->nr; i++)
3248 if (!diff_unmodified_pair(q->queue[i]))
3249 return 0;
3250 return 1;
3253 #if DIFF_DEBUG
3254 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3256 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3257 x, one ? one : "",
3258 s->path,
3259 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3260 s->mode,
3261 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3262 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3263 x, one ? one : "",
3264 s->size, s->xfrm_flags);
3267 void diff_debug_filepair(const struct diff_filepair *p, int i)
3269 diff_debug_filespec(p->one, i, "one");
3270 diff_debug_filespec(p->two, i, "two");
3271 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3272 p->score, p->status ? p->status : '?',
3273 p->one->rename_used, p->broken_pair);
3276 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3278 int i;
3279 if (msg)
3280 fprintf(stderr, "%s\n", msg);
3281 fprintf(stderr, "q->nr = %d\n", q->nr);
3282 for (i = 0; i < q->nr; i++) {
3283 struct diff_filepair *p = q->queue[i];
3284 diff_debug_filepair(p, i);
3287 #endif
3289 static void diff_resolve_rename_copy(void)
3291 int i;
3292 struct diff_filepair *p;
3293 struct diff_queue_struct *q = &diff_queued_diff;
3295 diff_debug_queue("resolve-rename-copy", q);
3297 for (i = 0; i < q->nr; i++) {
3298 p = q->queue[i];
3299 p->status = 0; /* undecided */
3300 if (DIFF_PAIR_UNMERGED(p))
3301 p->status = DIFF_STATUS_UNMERGED;
3302 else if (!DIFF_FILE_VALID(p->one))
3303 p->status = DIFF_STATUS_ADDED;
3304 else if (!DIFF_FILE_VALID(p->two))
3305 p->status = DIFF_STATUS_DELETED;
3306 else if (DIFF_PAIR_TYPE_CHANGED(p))
3307 p->status = DIFF_STATUS_TYPE_CHANGED;
3309 /* from this point on, we are dealing with a pair
3310 * whose both sides are valid and of the same type, i.e.
3311 * either in-place edit or rename/copy edit.
3313 else if (DIFF_PAIR_RENAME(p)) {
3315 * A rename might have re-connected a broken
3316 * pair up, causing the pathnames to be the
3317 * same again. If so, that's not a rename at
3318 * all, just a modification..
3320 * Otherwise, see if this source was used for
3321 * multiple renames, in which case we decrement
3322 * the count, and call it a copy.
3324 if (!strcmp(p->one->path, p->two->path))
3325 p->status = DIFF_STATUS_MODIFIED;
3326 else if (--p->one->rename_used > 0)
3327 p->status = DIFF_STATUS_COPIED;
3328 else
3329 p->status = DIFF_STATUS_RENAMED;
3331 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3332 p->one->mode != p->two->mode ||
3333 p->one->dirty_submodule ||
3334 p->two->dirty_submodule ||
3335 is_null_sha1(p->one->sha1))
3336 p->status = DIFF_STATUS_MODIFIED;
3337 else {
3338 /* This is a "no-change" entry and should not
3339 * happen anymore, but prepare for broken callers.
3341 error("feeding unmodified %s to diffcore",
3342 p->one->path);
3343 p->status = DIFF_STATUS_UNKNOWN;
3346 diff_debug_queue("resolve-rename-copy done", q);
3349 static int check_pair_status(struct diff_filepair *p)
3351 switch (p->status) {
3352 case DIFF_STATUS_UNKNOWN:
3353 return 0;
3354 case 0:
3355 die("internal error in diff-resolve-rename-copy");
3356 default:
3357 return 1;
3361 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3363 int fmt = opt->output_format;
3365 if (fmt & DIFF_FORMAT_CHECKDIFF)
3366 diff_flush_checkdiff(p, opt);
3367 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3368 diff_flush_raw(p, opt);
3369 else if (fmt & DIFF_FORMAT_NAME) {
3370 const char *name_a, *name_b;
3371 name_a = p->two->path;
3372 name_b = NULL;
3373 strip_prefix(opt->prefix_length, &name_a, &name_b);
3374 write_name_quoted(name_a, opt->file, opt->line_termination);
3378 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3380 if (fs->mode)
3381 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3382 else
3383 fprintf(file, " %s ", newdelete);
3384 write_name_quoted(fs->path, file, '\n');
3388 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3390 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3391 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3392 show_name ? ' ' : '\n');
3393 if (show_name) {
3394 write_name_quoted(p->two->path, file, '\n');
3399 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3401 char *names = pprint_rename(p->one->path, p->two->path);
3403 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3404 free(names);
3405 show_mode_change(file, p, 0);
3408 static void diff_summary(FILE *file, struct diff_filepair *p)
3410 switch(p->status) {
3411 case DIFF_STATUS_DELETED:
3412 show_file_mode_name(file, "delete", p->one);
3413 break;
3414 case DIFF_STATUS_ADDED:
3415 show_file_mode_name(file, "create", p->two);
3416 break;
3417 case DIFF_STATUS_COPIED:
3418 show_rename_copy(file, "copy", p);
3419 break;
3420 case DIFF_STATUS_RENAMED:
3421 show_rename_copy(file, "rename", p);
3422 break;
3423 default:
3424 if (p->score) {
3425 fputs(" rewrite ", file);
3426 write_name_quoted(p->two->path, file, ' ');
3427 fprintf(file, "(%d%%)\n", similarity_index(p));
3429 show_mode_change(file, p, !p->score);
3430 break;
3434 struct patch_id_t {
3435 git_SHA_CTX *ctx;
3436 int patchlen;
3439 static int remove_space(char *line, int len)
3441 int i;
3442 char *dst = line;
3443 unsigned char c;
3445 for (i = 0; i < len; i++)
3446 if (!isspace((c = line[i])))
3447 *dst++ = c;
3449 return dst - line;
3452 static void patch_id_consume(void *priv, char *line, unsigned long len)
3454 struct patch_id_t *data = priv;
3455 int new_len;
3457 /* Ignore line numbers when computing the SHA1 of the patch */
3458 if (!prefixcmp(line, "@@ -"))
3459 return;
3461 new_len = remove_space(line, len);
3463 git_SHA1_Update(data->ctx, line, new_len);
3464 data->patchlen += new_len;
3467 /* returns 0 upon success, and writes result into sha1 */
3468 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3470 struct diff_queue_struct *q = &diff_queued_diff;
3471 int i;
3472 git_SHA_CTX ctx;
3473 struct patch_id_t data;
3474 char buffer[PATH_MAX * 4 + 20];
3476 git_SHA1_Init(&ctx);
3477 memset(&data, 0, sizeof(struct patch_id_t));
3478 data.ctx = &ctx;
3480 for (i = 0; i < q->nr; i++) {
3481 xpparam_t xpp;
3482 xdemitconf_t xecfg;
3483 mmfile_t mf1, mf2;
3484 struct diff_filepair *p = q->queue[i];
3485 int len1, len2;
3487 memset(&xpp, 0, sizeof(xpp));
3488 memset(&xecfg, 0, sizeof(xecfg));
3489 if (p->status == 0)
3490 return error("internal diff status error");
3491 if (p->status == DIFF_STATUS_UNKNOWN)
3492 continue;
3493 if (diff_unmodified_pair(p))
3494 continue;
3495 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3496 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3497 continue;
3498 if (DIFF_PAIR_UNMERGED(p))
3499 continue;
3501 diff_fill_sha1_info(p->one);
3502 diff_fill_sha1_info(p->two);
3503 if (fill_mmfile(&mf1, p->one) < 0 ||
3504 fill_mmfile(&mf2, p->two) < 0)
3505 return error("unable to read files to diff");
3507 len1 = remove_space(p->one->path, strlen(p->one->path));
3508 len2 = remove_space(p->two->path, strlen(p->two->path));
3509 if (p->one->mode == 0)
3510 len1 = snprintf(buffer, sizeof(buffer),
3511 "diff--gita/%.*sb/%.*s"
3512 "newfilemode%06o"
3513 "---/dev/null"
3514 "+++b/%.*s",
3515 len1, p->one->path,
3516 len2, p->two->path,
3517 p->two->mode,
3518 len2, p->two->path);
3519 else if (p->two->mode == 0)
3520 len1 = snprintf(buffer, sizeof(buffer),
3521 "diff--gita/%.*sb/%.*s"
3522 "deletedfilemode%06o"
3523 "---a/%.*s"
3524 "+++/dev/null",
3525 len1, p->one->path,
3526 len2, p->two->path,
3527 p->one->mode,
3528 len1, p->one->path);
3529 else
3530 len1 = snprintf(buffer, sizeof(buffer),
3531 "diff--gita/%.*sb/%.*s"
3532 "---a/%.*s"
3533 "+++b/%.*s",
3534 len1, p->one->path,
3535 len2, p->two->path,
3536 len1, p->one->path,
3537 len2, p->two->path);
3538 git_SHA1_Update(&ctx, buffer, len1);
3540 xpp.flags = 0;
3541 xecfg.ctxlen = 3;
3542 xecfg.flags = XDL_EMIT_FUNCNAMES;
3543 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3544 &xpp, &xecfg);
3547 git_SHA1_Final(sha1, &ctx);
3548 return 0;
3551 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3553 struct diff_queue_struct *q = &diff_queued_diff;
3554 int i;
3555 int result = diff_get_patch_id(options, sha1);
3557 for (i = 0; i < q->nr; i++)
3558 diff_free_filepair(q->queue[i]);
3560 free(q->queue);
3561 DIFF_QUEUE_CLEAR(q);
3563 return result;
3566 static int is_summary_empty(const struct diff_queue_struct *q)
3568 int i;
3570 for (i = 0; i < q->nr; i++) {
3571 const struct diff_filepair *p = q->queue[i];
3573 switch (p->status) {
3574 case DIFF_STATUS_DELETED:
3575 case DIFF_STATUS_ADDED:
3576 case DIFF_STATUS_COPIED:
3577 case DIFF_STATUS_RENAMED:
3578 return 0;
3579 default:
3580 if (p->score)
3581 return 0;
3582 if (p->one->mode && p->two->mode &&
3583 p->one->mode != p->two->mode)
3584 return 0;
3585 break;
3588 return 1;
3591 void diff_flush(struct diff_options *options)
3593 struct diff_queue_struct *q = &diff_queued_diff;
3594 int i, output_format = options->output_format;
3595 int separator = 0;
3598 * Order: raw, stat, summary, patch
3599 * or: name/name-status/checkdiff (other bits clear)
3601 if (!q->nr)
3602 goto free_queue;
3604 if (output_format & (DIFF_FORMAT_RAW |
3605 DIFF_FORMAT_NAME |
3606 DIFF_FORMAT_NAME_STATUS |
3607 DIFF_FORMAT_CHECKDIFF)) {
3608 for (i = 0; i < q->nr; i++) {
3609 struct diff_filepair *p = q->queue[i];
3610 if (check_pair_status(p))
3611 flush_one_pair(p, options);
3613 separator++;
3616 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3617 struct diffstat_t diffstat;
3619 memset(&diffstat, 0, sizeof(struct diffstat_t));
3620 for (i = 0; i < q->nr; i++) {
3621 struct diff_filepair *p = q->queue[i];
3622 if (check_pair_status(p))
3623 diff_flush_stat(p, options, &diffstat);
3625 if (output_format & DIFF_FORMAT_NUMSTAT)
3626 show_numstat(&diffstat, options);
3627 if (output_format & DIFF_FORMAT_DIFFSTAT)
3628 show_stats(&diffstat, options);
3629 if (output_format & DIFF_FORMAT_SHORTSTAT)
3630 show_shortstats(&diffstat, options);
3631 free_diffstat_info(&diffstat);
3632 separator++;
3634 if (output_format & DIFF_FORMAT_DIRSTAT)
3635 show_dirstat(options);
3637 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3638 for (i = 0; i < q->nr; i++)
3639 diff_summary(options->file, q->queue[i]);
3640 separator++;
3643 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
3644 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
3645 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3647 * run diff_flush_patch for the exit status. setting
3648 * options->file to /dev/null should be safe, becaue we
3649 * aren't supposed to produce any output anyway.
3651 if (options->close_file)
3652 fclose(options->file);
3653 options->file = fopen("/dev/null", "w");
3654 if (!options->file)
3655 die_errno("Could not open /dev/null");
3656 options->close_file = 1;
3657 for (i = 0; i < q->nr; i++) {
3658 struct diff_filepair *p = q->queue[i];
3659 if (check_pair_status(p))
3660 diff_flush_patch(p, options);
3661 if (options->found_changes)
3662 break;
3666 if (output_format & DIFF_FORMAT_PATCH) {
3667 if (separator) {
3668 putc(options->line_termination, options->file);
3669 if (options->stat_sep) {
3670 /* attach patch instead of inline */
3671 fputs(options->stat_sep, options->file);
3675 for (i = 0; i < q->nr; i++) {
3676 struct diff_filepair *p = q->queue[i];
3677 if (check_pair_status(p))
3678 diff_flush_patch(p, options);
3682 if (output_format & DIFF_FORMAT_CALLBACK)
3683 options->format_callback(q, options, options->format_callback_data);
3685 for (i = 0; i < q->nr; i++)
3686 diff_free_filepair(q->queue[i]);
3687 free_queue:
3688 free(q->queue);
3689 DIFF_QUEUE_CLEAR(q);
3690 if (options->close_file)
3691 fclose(options->file);
3694 * Report the content-level differences with HAS_CHANGES;
3695 * diff_addremove/diff_change does not set the bit when
3696 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3698 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3699 if (options->found_changes)
3700 DIFF_OPT_SET(options, HAS_CHANGES);
3701 else
3702 DIFF_OPT_CLR(options, HAS_CHANGES);
3706 static void diffcore_apply_filter(const char *filter)
3708 int i;
3709 struct diff_queue_struct *q = &diff_queued_diff;
3710 struct diff_queue_struct outq;
3711 DIFF_QUEUE_CLEAR(&outq);
3713 if (!filter)
3714 return;
3716 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3717 int found;
3718 for (i = found = 0; !found && i < q->nr; i++) {
3719 struct diff_filepair *p = q->queue[i];
3720 if (((p->status == DIFF_STATUS_MODIFIED) &&
3721 ((p->score &&
3722 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3723 (!p->score &&
3724 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3725 ((p->status != DIFF_STATUS_MODIFIED) &&
3726 strchr(filter, p->status)))
3727 found++;
3729 if (found)
3730 return;
3732 /* otherwise we will clear the whole queue
3733 * by copying the empty outq at the end of this
3734 * function, but first clear the current entries
3735 * in the queue.
3737 for (i = 0; i < q->nr; i++)
3738 diff_free_filepair(q->queue[i]);
3740 else {
3741 /* Only the matching ones */
3742 for (i = 0; i < q->nr; i++) {
3743 struct diff_filepair *p = q->queue[i];
3745 if (((p->status == DIFF_STATUS_MODIFIED) &&
3746 ((p->score &&
3747 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3748 (!p->score &&
3749 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3750 ((p->status != DIFF_STATUS_MODIFIED) &&
3751 strchr(filter, p->status)))
3752 diff_q(&outq, p);
3753 else
3754 diff_free_filepair(p);
3757 free(q->queue);
3758 *q = outq;
3761 /* Check whether two filespecs with the same mode and size are identical */
3762 static int diff_filespec_is_identical(struct diff_filespec *one,
3763 struct diff_filespec *two)
3765 if (S_ISGITLINK(one->mode))
3766 return 0;
3767 if (diff_populate_filespec(one, 0))
3768 return 0;
3769 if (diff_populate_filespec(two, 0))
3770 return 0;
3771 return !memcmp(one->data, two->data, one->size);
3774 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3776 int i;
3777 struct diff_queue_struct *q = &diff_queued_diff;
3778 struct diff_queue_struct outq;
3779 DIFF_QUEUE_CLEAR(&outq);
3781 for (i = 0; i < q->nr; i++) {
3782 struct diff_filepair *p = q->queue[i];
3785 * 1. Entries that come from stat info dirtiness
3786 * always have both sides (iow, not create/delete),
3787 * one side of the object name is unknown, with
3788 * the same mode and size. Keep the ones that
3789 * do not match these criteria. They have real
3790 * differences.
3792 * 2. At this point, the file is known to be modified,
3793 * with the same mode and size, and the object
3794 * name of one side is unknown. Need to inspect
3795 * the identical contents.
3797 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3798 !DIFF_FILE_VALID(p->two) ||
3799 (p->one->sha1_valid && p->two->sha1_valid) ||
3800 (p->one->mode != p->two->mode) ||
3801 diff_populate_filespec(p->one, 1) ||
3802 diff_populate_filespec(p->two, 1) ||
3803 (p->one->size != p->two->size) ||
3804 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3805 diff_q(&outq, p);
3806 else {
3808 * The caller can subtract 1 from skip_stat_unmatch
3809 * to determine how many paths were dirty only
3810 * due to stat info mismatch.
3812 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3813 diffopt->skip_stat_unmatch++;
3814 diff_free_filepair(p);
3817 free(q->queue);
3818 *q = outq;
3821 static int diffnamecmp(const void *a_, const void *b_)
3823 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
3824 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
3825 const char *name_a, *name_b;
3827 name_a = a->one ? a->one->path : a->two->path;
3828 name_b = b->one ? b->one->path : b->two->path;
3829 return strcmp(name_a, name_b);
3832 void diffcore_fix_diff_index(struct diff_options *options)
3834 struct diff_queue_struct *q = &diff_queued_diff;
3835 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
3838 void diffcore_std(struct diff_options *options)
3840 /* We never run this function more than one time, because the
3841 * rename/copy detection logic can only run once.
3843 if (diff_queued_diff.run)
3844 return;
3846 if (options->skip_stat_unmatch)
3847 diffcore_skip_stat_unmatch(options);
3848 if (options->break_opt != -1)
3849 diffcore_break(options->break_opt);
3850 if (options->detect_rename)
3851 diffcore_rename(options);
3852 if (options->break_opt != -1)
3853 diffcore_merge_broken();
3854 if (options->pickaxe)
3855 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3856 if (options->orderfile)
3857 diffcore_order(options->orderfile);
3858 diff_resolve_rename_copy();
3859 diffcore_apply_filter(options->filter);
3861 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3862 DIFF_OPT_SET(options, HAS_CHANGES);
3863 else
3864 DIFF_OPT_CLR(options, HAS_CHANGES);
3866 diff_queued_diff.run = 1;
3869 int diff_result_code(struct diff_options *opt, int status)
3871 int result = 0;
3872 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3873 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3874 return status;
3875 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3876 DIFF_OPT_TST(opt, HAS_CHANGES))
3877 result |= 01;
3878 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3879 DIFF_OPT_TST(opt, CHECK_FAILED))
3880 result |= 02;
3881 return result;
3884 void diff_addremove(struct diff_options *options,
3885 int addremove, unsigned mode,
3886 const unsigned char *sha1,
3887 const char *concatpath, unsigned dirty_submodule)
3889 struct diff_filespec *one, *two;
3891 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3892 return;
3894 /* This may look odd, but it is a preparation for
3895 * feeding "there are unchanged files which should
3896 * not produce diffs, but when you are doing copy
3897 * detection you would need them, so here they are"
3898 * entries to the diff-core. They will be prefixed
3899 * with something like '=' or '*' (I haven't decided
3900 * which but should not make any difference).
3901 * Feeding the same new and old to diff_change()
3902 * also has the same effect.
3903 * Before the final output happens, they are pruned after
3904 * merged into rename/copy pairs as appropriate.
3906 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3907 addremove = (addremove == '+' ? '-' :
3908 addremove == '-' ? '+' : addremove);
3910 if (options->prefix &&
3911 strncmp(concatpath, options->prefix, options->prefix_length))
3912 return;
3914 one = alloc_filespec(concatpath);
3915 two = alloc_filespec(concatpath);
3917 if (addremove != '+')
3918 fill_filespec(one, sha1, mode);
3919 if (addremove != '-') {
3920 fill_filespec(two, sha1, mode);
3921 two->dirty_submodule = dirty_submodule;
3924 diff_queue(&diff_queued_diff, one, two);
3925 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3926 DIFF_OPT_SET(options, HAS_CHANGES);
3929 void diff_change(struct diff_options *options,
3930 unsigned old_mode, unsigned new_mode,
3931 const unsigned char *old_sha1,
3932 const unsigned char *new_sha1,
3933 const char *concatpath,
3934 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
3936 struct diff_filespec *one, *two;
3938 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3939 && S_ISGITLINK(new_mode))
3940 return;
3942 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3943 unsigned tmp;
3944 const unsigned char *tmp_c;
3945 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3946 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3947 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
3948 new_dirty_submodule = tmp;
3951 if (options->prefix &&
3952 strncmp(concatpath, options->prefix, options->prefix_length))
3953 return;
3955 one = alloc_filespec(concatpath);
3956 two = alloc_filespec(concatpath);
3957 fill_filespec(one, old_sha1, old_mode);
3958 fill_filespec(two, new_sha1, new_mode);
3959 one->dirty_submodule = old_dirty_submodule;
3960 two->dirty_submodule = new_dirty_submodule;
3962 diff_queue(&diff_queued_diff, one, two);
3963 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3964 DIFF_OPT_SET(options, HAS_CHANGES);
3967 void diff_unmerge(struct diff_options *options,
3968 const char *path,
3969 unsigned mode, const unsigned char *sha1)
3971 struct diff_filespec *one, *two;
3973 if (options->prefix &&
3974 strncmp(path, options->prefix, options->prefix_length))
3975 return;
3977 one = alloc_filespec(path);
3978 two = alloc_filespec(path);
3979 fill_filespec(one, sha1, mode);
3980 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3983 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3984 size_t *outsize)
3986 struct diff_tempfile *temp;
3987 const char *argv[3];
3988 const char **arg = argv;
3989 struct child_process child;
3990 struct strbuf buf = STRBUF_INIT;
3991 int err = 0;
3993 temp = prepare_temp_file(spec->path, spec);
3994 *arg++ = pgm;
3995 *arg++ = temp->name;
3996 *arg = NULL;
3998 memset(&child, 0, sizeof(child));
3999 child.use_shell = 1;
4000 child.argv = argv;
4001 child.out = -1;
4002 if (start_command(&child)) {
4003 remove_tempfile();
4004 return NULL;
4007 if (strbuf_read(&buf, child.out, 0) < 0)
4008 err = error("error reading from textconv command '%s'", pgm);
4009 close(child.out);
4011 if (finish_command(&child) || err) {
4012 strbuf_release(&buf);
4013 remove_tempfile();
4014 return NULL;
4016 remove_tempfile();
4018 return strbuf_detach(&buf, outsize);
4021 static size_t fill_textconv(struct userdiff_driver *driver,
4022 struct diff_filespec *df,
4023 char **outbuf)
4025 size_t size;
4027 if (!driver || !driver->textconv) {
4028 if (!DIFF_FILE_VALID(df)) {
4029 *outbuf = "";
4030 return 0;
4032 if (diff_populate_filespec(df, 0))
4033 die("unable to read files to diff");
4034 *outbuf = df->data;
4035 return df->size;
4038 if (driver->textconv_cache) {
4039 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4040 &size);
4041 if (*outbuf)
4042 return size;
4045 *outbuf = run_textconv(driver->textconv, df, &size);
4046 if (!*outbuf)
4047 die("unable to read files to diff");
4049 if (driver->textconv_cache) {
4050 /* ignore errors, as we might be in a readonly repository */
4051 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4052 size);
4054 * we could save up changes and flush them all at the end,
4055 * but we would need an extra call after all diffing is done.
4056 * Since generating a cache entry is the slow path anyway,
4057 * this extra overhead probably isn't a big deal.
4059 notes_cache_write(driver->textconv_cache);
4062 return size;