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