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