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