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
13#ifdef NO_FAST_WORKING_DIRECTORY
14#define FAST_WORKING_DIRECTORY 0
15#else
16#define FAST_WORKING_DIRECTORY 1
17#endif
18
19static int diff_detect_rename_default;
20static int diff_rename_limit_default = -1;
21static int diff_use_color_default;
22
23static char diff_colors[][COLOR_MAXLEN] = {
24 "\033[m", /* reset */
25 "", /* PLAIN (normal) */
26 "\033[1m", /* METAINFO (bold) */
27 "\033[36m", /* FRAGINFO (cyan) */
28 "\033[31m", /* OLD (red) */
29 "\033[32m", /* NEW (green) */
30 "\033[33m", /* COMMIT (yellow) */
31 "\033[41m", /* WHITESPACE (red background) */
32};
33
34static int parse_diff_color_slot(const char *var, int ofs)
35{
36 if (!strcasecmp(var+ofs, "plain"))
37 return DIFF_PLAIN;
38 if (!strcasecmp(var+ofs, "meta"))
39 return DIFF_METAINFO;
40 if (!strcasecmp(var+ofs, "frag"))
41 return DIFF_FRAGINFO;
42 if (!strcasecmp(var+ofs, "old"))
43 return DIFF_FILE_OLD;
44 if (!strcasecmp(var+ofs, "new"))
45 return DIFF_FILE_NEW;
46 if (!strcasecmp(var+ofs, "commit"))
47 return DIFF_COMMIT;
48 if (!strcasecmp(var+ofs, "whitespace"))
49 return DIFF_WHITESPACE;
50 die("bad config variable '%s'", var);
51}
52
53static struct ll_diff_driver {
54 const char *name;
55 struct ll_diff_driver *next;
56 char *cmd;
57} *user_diff, **user_diff_tail;
58
59/*
60 * Currently there is only "diff.<drivername>.command" variable;
61 * because there are "diff.color.<slot>" variables, we are parsing
62 * this in a bit convoluted way to allow low level diff driver
63 * called "color".
64 */
65static int parse_lldiff_command(const char *var, const char *ep, const char *value)
66{
67 const char *name;
68 int namelen;
69 struct ll_diff_driver *drv;
70
71 name = var + 5;
72 namelen = ep - name;
73 for (drv = user_diff; drv; drv = drv->next)
74 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
75 break;
76 if (!drv) {
77 char *namebuf;
78 drv = xcalloc(1, sizeof(struct ll_diff_driver));
79 namebuf = xmalloc(namelen + 1);
80 memcpy(namebuf, name, namelen);
81 namebuf[namelen] = 0;
82 drv->name = namebuf;
83 drv->next = NULL;
84 if (!user_diff_tail)
85 user_diff_tail = &user_diff;
86 *user_diff_tail = drv;
87 user_diff_tail = &(drv->next);
88 }
89
90 if (!value)
91 return error("%s: lacks value", var);
92 drv->cmd = strdup(value);
93 return 0;
94}
95
96/*
97 * These are to give UI layer defaults.
98 * The core-level commands such as git-diff-files should
99 * never be affected by the setting of diff.renames
100 * the user happens to have in the configuration file.
101 */
102int git_diff_ui_config(const char *var, const char *value)
103{
104 if (!strcmp(var, "diff.renamelimit")) {
105 diff_rename_limit_default = git_config_int(var, value);
106 return 0;
107 }
108 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
109 diff_use_color_default = git_config_colorbool(var, value);
110 return 0;
111 }
112 if (!strcmp(var, "diff.renames")) {
113 if (!value)
114 diff_detect_rename_default = DIFF_DETECT_RENAME;
115 else if (!strcasecmp(value, "copies") ||
116 !strcasecmp(value, "copy"))
117 diff_detect_rename_default = DIFF_DETECT_COPY;
118 else if (git_config_bool(var,value))
119 diff_detect_rename_default = DIFF_DETECT_RENAME;
120 return 0;
121 }
122 if (!prefixcmp(var, "diff.")) {
123 const char *ep = strrchr(var, '.');
124
125 if (ep != var + 4 && !strcmp(ep, ".command"))
126 return parse_lldiff_command(var, ep, value);
127 }
128 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
129 int slot = parse_diff_color_slot(var, 11);
130 color_parse(value, var, diff_colors[slot]);
131 return 0;
132 }
133
134 return git_default_config(var, value);
135}
136
137static char *quote_one(const char *str)
138{
139 int needlen;
140 char *xp;
141
142 if (!str)
143 return NULL;
144 needlen = quote_c_style(str, NULL, NULL, 0);
145 if (!needlen)
146 return xstrdup(str);
147 xp = xmalloc(needlen + 1);
148 quote_c_style(str, xp, NULL, 0);
149 return xp;
150}
151
152static char *quote_two(const char *one, const char *two)
153{
154 int need_one = quote_c_style(one, NULL, NULL, 1);
155 int need_two = quote_c_style(two, NULL, NULL, 1);
156 char *xp;
157
158 if (need_one + need_two) {
159 if (!need_one) need_one = strlen(one);
160 if (!need_two) need_one = strlen(two);
161
162 xp = xmalloc(need_one + need_two + 3);
163 xp[0] = '"';
164 quote_c_style(one, xp + 1, NULL, 1);
165 quote_c_style(two, xp + need_one + 1, NULL, 1);
166 strcpy(xp + need_one + need_two + 1, "\"");
167 return xp;
168 }
169 need_one = strlen(one);
170 need_two = strlen(two);
171 xp = xmalloc(need_one + need_two + 1);
172 strcpy(xp, one);
173 strcpy(xp + need_one, two);
174 return xp;
175}
176
177static const char *external_diff(void)
178{
179 static const char *external_diff_cmd = NULL;
180 static int done_preparing = 0;
181
182 if (done_preparing)
183 return external_diff_cmd;
184 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
185 done_preparing = 1;
186 return external_diff_cmd;
187}
188
189static struct diff_tempfile {
190 const char *name; /* filename external diff should read from */
191 char hex[41];
192 char mode[10];
193 char tmp_path[PATH_MAX];
194} diff_temp[2];
195
196static int count_lines(const char *data, int size)
197{
198 int count, ch, completely_empty = 1, nl_just_seen = 0;
199 count = 0;
200 while (0 < size--) {
201 ch = *data++;
202 if (ch == '\n') {
203 count++;
204 nl_just_seen = 1;
205 completely_empty = 0;
206 }
207 else {
208 nl_just_seen = 0;
209 completely_empty = 0;
210 }
211 }
212 if (completely_empty)
213 return 0;
214 if (!nl_just_seen)
215 count++; /* no trailing newline */
216 return count;
217}
218
219static void print_line_count(int count)
220{
221 switch (count) {
222 case 0:
223 printf("0,0");
224 break;
225 case 1:
226 printf("1");
227 break;
228 default:
229 printf("1,%d", count);
230 break;
231 }
232}
233
234static void copy_file(int prefix, const char *data, int size,
235 const char *set, const char *reset)
236{
237 int ch, nl_just_seen = 1;
238 while (0 < size--) {
239 ch = *data++;
240 if (nl_just_seen) {
241 fputs(set, stdout);
242 putchar(prefix);
243 }
244 if (ch == '\n') {
245 nl_just_seen = 1;
246 fputs(reset, stdout);
247 } else
248 nl_just_seen = 0;
249 putchar(ch);
250 }
251 if (!nl_just_seen)
252 printf("%s\n\\ No newline at end of file\n", reset);
253}
254
255static void emit_rewrite_diff(const char *name_a,
256 const char *name_b,
257 struct diff_filespec *one,
258 struct diff_filespec *two,
259 int color_diff)
260{
261 int lc_a, lc_b;
262 const char *name_a_tab, *name_b_tab;
263 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
264 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
265 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
266 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
267 const char *reset = diff_get_color(color_diff, DIFF_RESET);
268
269 name_a += (*name_a == '/');
270 name_b += (*name_b == '/');
271 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
272 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
273
274 diff_populate_filespec(one, 0);
275 diff_populate_filespec(two, 0);
276 lc_a = count_lines(one->data, one->size);
277 lc_b = count_lines(two->data, two->size);
278 printf("%s--- a/%s%s%s\n%s+++ b/%s%s%s\n%s@@ -",
279 metainfo, name_a, name_a_tab, reset,
280 metainfo, name_b, name_b_tab, reset, fraginfo);
281 print_line_count(lc_a);
282 printf(" +");
283 print_line_count(lc_b);
284 printf(" @@%s\n", reset);
285 if (lc_a)
286 copy_file('-', one->data, one->size, old, reset);
287 if (lc_b)
288 copy_file('+', two->data, two->size, new, reset);
289}
290
291static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
292{
293 if (!DIFF_FILE_VALID(one)) {
294 mf->ptr = (char *)""; /* does not matter */
295 mf->size = 0;
296 return 0;
297 }
298 else if (diff_populate_filespec(one, 0))
299 return -1;
300 mf->ptr = one->data;
301 mf->size = one->size;
302 return 0;
303}
304
305struct diff_words_buffer {
306 mmfile_t text;
307 long alloc;
308 long current; /* output pointer */
309 int suppressed_newline;
310};
311
312static void diff_words_append(char *line, unsigned long len,
313 struct diff_words_buffer *buffer)
314{
315 if (buffer->text.size + len > buffer->alloc) {
316 buffer->alloc = (buffer->text.size + len) * 3 / 2;
317 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
318 }
319 line++;
320 len--;
321 memcpy(buffer->text.ptr + buffer->text.size, line, len);
322 buffer->text.size += len;
323}
324
325struct diff_words_data {
326 struct xdiff_emit_state xm;
327 struct diff_words_buffer minus, plus;
328};
329
330static void print_word(struct diff_words_buffer *buffer, int len, int color,
331 int suppress_newline)
332{
333 const char *ptr;
334 int eol = 0;
335
336 if (len == 0)
337 return;
338
339 ptr = buffer->text.ptr + buffer->current;
340 buffer->current += len;
341
342 if (ptr[len - 1] == '\n') {
343 eol = 1;
344 len--;
345 }
346
347 fputs(diff_get_color(1, color), stdout);
348 fwrite(ptr, len, 1, stdout);
349 fputs(diff_get_color(1, DIFF_RESET), stdout);
350
351 if (eol) {
352 if (suppress_newline)
353 buffer->suppressed_newline = 1;
354 else
355 putchar('\n');
356 }
357}
358
359static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
360{
361 struct diff_words_data *diff_words = priv;
362
363 if (diff_words->minus.suppressed_newline) {
364 if (line[0] != '+')
365 putchar('\n');
366 diff_words->minus.suppressed_newline = 0;
367 }
368
369 len--;
370 switch (line[0]) {
371 case '-':
372 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
373 break;
374 case '+':
375 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
376 break;
377 case ' ':
378 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
379 diff_words->minus.current += len;
380 break;
381 }
382}
383
384/* this executes the word diff on the accumulated buffers */
385static void diff_words_show(struct diff_words_data *diff_words)
386{
387 xpparam_t xpp;
388 xdemitconf_t xecfg;
389 xdemitcb_t ecb;
390 mmfile_t minus, plus;
391 int i;
392
393 memset(&xecfg, 0, sizeof(xecfg));
394 minus.size = diff_words->minus.text.size;
395 minus.ptr = xmalloc(minus.size);
396 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
397 for (i = 0; i < minus.size; i++)
398 if (isspace(minus.ptr[i]))
399 minus.ptr[i] = '\n';
400 diff_words->minus.current = 0;
401
402 plus.size = diff_words->plus.text.size;
403 plus.ptr = xmalloc(plus.size);
404 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
405 for (i = 0; i < plus.size; i++)
406 if (isspace(plus.ptr[i]))
407 plus.ptr[i] = '\n';
408 diff_words->plus.current = 0;
409
410 xpp.flags = XDF_NEED_MINIMAL;
411 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
412 ecb.outf = xdiff_outf;
413 ecb.priv = diff_words;
414 diff_words->xm.consume = fn_out_diff_words_aux;
415 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
416
417 free(minus.ptr);
418 free(plus.ptr);
419 diff_words->minus.text.size = diff_words->plus.text.size = 0;
420
421 if (diff_words->minus.suppressed_newline) {
422 putchar('\n');
423 diff_words->minus.suppressed_newline = 0;
424 }
425}
426
427struct emit_callback {
428 struct xdiff_emit_state xm;
429 int nparents, color_diff;
430 const char **label_path;
431 struct diff_words_data *diff_words;
432 int *found_changesp;
433};
434
435static void free_diff_words_data(struct emit_callback *ecbdata)
436{
437 if (ecbdata->diff_words) {
438 /* flush buffers */
439 if (ecbdata->diff_words->minus.text.size ||
440 ecbdata->diff_words->plus.text.size)
441 diff_words_show(ecbdata->diff_words);
442
443 if (ecbdata->diff_words->minus.text.ptr)
444 free (ecbdata->diff_words->minus.text.ptr);
445 if (ecbdata->diff_words->plus.text.ptr)
446 free (ecbdata->diff_words->plus.text.ptr);
447 free(ecbdata->diff_words);
448 ecbdata->diff_words = NULL;
449 }
450}
451
452const char *diff_get_color(int diff_use_color, enum color_diff ix)
453{
454 if (diff_use_color)
455 return diff_colors[ix];
456 return "";
457}
458
459static void emit_line(const char *set, const char *reset, const char *line, int len)
460{
461 if (len > 0 && line[len-1] == '\n')
462 len--;
463 fputs(set, stdout);
464 fwrite(line, len, 1, stdout);
465 puts(reset);
466}
467
468static void emit_line_with_ws(int nparents,
469 const char *set, const char *reset, const char *ws,
470 const char *line, int len)
471{
472 int col0 = nparents;
473 int last_tab_in_indent = -1;
474 int last_space_in_indent = -1;
475 int i;
476 int tail = len;
477 int need_highlight_leading_space = 0;
478 /* The line is a newly added line. Does it have funny leading
479 * whitespaces? In indent, SP should never precede a TAB.
480 */
481 for (i = col0; i < len; i++) {
482 if (line[i] == '\t') {
483 last_tab_in_indent = i;
484 if (0 <= last_space_in_indent)
485 need_highlight_leading_space = 1;
486 }
487 else if (line[i] == ' ')
488 last_space_in_indent = i;
489 else
490 break;
491 }
492 fputs(set, stdout);
493 fwrite(line, col0, 1, stdout);
494 fputs(reset, stdout);
495 if (((i == len) || line[i] == '\n') && i != col0) {
496 /* The whole line was indent */
497 emit_line(ws, reset, line + col0, len - col0);
498 return;
499 }
500 i = col0;
501 if (need_highlight_leading_space) {
502 while (i < last_tab_in_indent) {
503 if (line[i] == ' ') {
504 fputs(ws, stdout);
505 putchar(' ');
506 fputs(reset, stdout);
507 }
508 else
509 putchar(line[i]);
510 i++;
511 }
512 }
513 tail = len - 1;
514 if (line[tail] == '\n' && i < tail)
515 tail--;
516 while (i < tail) {
517 if (!isspace(line[tail]))
518 break;
519 tail--;
520 }
521 if ((i < tail && line[tail + 1] != '\n')) {
522 /* This has whitespace between tail+1..len */
523 fputs(set, stdout);
524 fwrite(line + i, tail - i + 1, 1, stdout);
525 fputs(reset, stdout);
526 emit_line(ws, reset, line + tail + 1, len - tail - 1);
527 }
528 else
529 emit_line(set, reset, line + i, len - i);
530}
531
532static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
533{
534 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
535 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
536
537 if (!*ws)
538 emit_line(set, reset, line, len);
539 else
540 emit_line_with_ws(ecbdata->nparents, set, reset, ws,
541 line, len);
542}
543
544static void fn_out_consume(void *priv, char *line, unsigned long len)
545{
546 int i;
547 int color;
548 struct emit_callback *ecbdata = priv;
549 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
550 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
551
552 *(ecbdata->found_changesp) = 1;
553
554 if (ecbdata->label_path[0]) {
555 const char *name_a_tab, *name_b_tab;
556
557 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
558 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
559
560 printf("%s--- %s%s%s\n",
561 set, ecbdata->label_path[0], reset, name_a_tab);
562 printf("%s+++ %s%s%s\n",
563 set, ecbdata->label_path[1], reset, name_b_tab);
564 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
565 }
566
567 /* This is not really necessary for now because
568 * this codepath only deals with two-way diffs.
569 */
570 for (i = 0; i < len && line[i] == '@'; i++)
571 ;
572 if (2 <= i && i < len && line[i] == ' ') {
573 ecbdata->nparents = i - 1;
574 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
575 reset, line, len);
576 return;
577 }
578
579 if (len < ecbdata->nparents) {
580 set = reset;
581 emit_line(reset, reset, line, len);
582 return;
583 }
584
585 color = DIFF_PLAIN;
586 if (ecbdata->diff_words && ecbdata->nparents != 1)
587 /* fall back to normal diff */
588 free_diff_words_data(ecbdata);
589 if (ecbdata->diff_words) {
590 if (line[0] == '-') {
591 diff_words_append(line, len,
592 &ecbdata->diff_words->minus);
593 return;
594 } else if (line[0] == '+') {
595 diff_words_append(line, len,
596 &ecbdata->diff_words->plus);
597 return;
598 }
599 if (ecbdata->diff_words->minus.text.size ||
600 ecbdata->diff_words->plus.text.size)
601 diff_words_show(ecbdata->diff_words);
602 line++;
603 len--;
604 emit_line(set, reset, line, len);
605 return;
606 }
607 for (i = 0; i < ecbdata->nparents && len; i++) {
608 if (line[i] == '-')
609 color = DIFF_FILE_OLD;
610 else if (line[i] == '+')
611 color = DIFF_FILE_NEW;
612 }
613
614 if (color != DIFF_FILE_NEW) {
615 emit_line(diff_get_color(ecbdata->color_diff, color),
616 reset, line, len);
617 return;
618 }
619 emit_add_line(reset, ecbdata, line, len);
620}
621
622static char *pprint_rename(const char *a, const char *b)
623{
624 const char *old = a;
625 const char *new = b;
626 char *name = NULL;
627 int pfx_length, sfx_length;
628 int len_a = strlen(a);
629 int len_b = strlen(b);
630 int qlen_a = quote_c_style(a, NULL, NULL, 0);
631 int qlen_b = quote_c_style(b, NULL, NULL, 0);
632
633 if (qlen_a || qlen_b) {
634 if (qlen_a) len_a = qlen_a;
635 if (qlen_b) len_b = qlen_b;
636 name = xmalloc( len_a + len_b + 5 );
637 if (qlen_a)
638 quote_c_style(a, name, NULL, 0);
639 else
640 memcpy(name, a, len_a);
641 memcpy(name + len_a, " => ", 4);
642 if (qlen_b)
643 quote_c_style(b, name + len_a + 4, NULL, 0);
644 else
645 memcpy(name + len_a + 4, b, len_b + 1);
646 return name;
647 }
648
649 /* Find common prefix */
650 pfx_length = 0;
651 while (*old && *new && *old == *new) {
652 if (*old == '/')
653 pfx_length = old - a + 1;
654 old++;
655 new++;
656 }
657
658 /* Find common suffix */
659 old = a + len_a;
660 new = b + len_b;
661 sfx_length = 0;
662 while (a <= old && b <= new && *old == *new) {
663 if (*old == '/')
664 sfx_length = len_a - (old - a);
665 old--;
666 new--;
667 }
668
669 /*
670 * pfx{mid-a => mid-b}sfx
671 * {pfx-a => pfx-b}sfx
672 * pfx{sfx-a => sfx-b}
673 * name-a => name-b
674 */
675 if (pfx_length + sfx_length) {
676 int a_midlen = len_a - pfx_length - sfx_length;
677 int b_midlen = len_b - pfx_length - sfx_length;
678 if (a_midlen < 0) a_midlen = 0;
679 if (b_midlen < 0) b_midlen = 0;
680
681 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
682 sprintf(name, "%.*s{%.*s => %.*s}%s",
683 pfx_length, a,
684 a_midlen, a + pfx_length,
685 b_midlen, b + pfx_length,
686 a + len_a - sfx_length);
687 }
688 else {
689 name = xmalloc(len_a + len_b + 5);
690 sprintf(name, "%s => %s", a, b);
691 }
692 return name;
693}
694
695struct diffstat_t {
696 struct xdiff_emit_state xm;
697
698 int nr;
699 int alloc;
700 struct diffstat_file {
701 char *name;
702 unsigned is_unmerged:1;
703 unsigned is_binary:1;
704 unsigned is_renamed:1;
705 unsigned int added, deleted;
706 } **files;
707};
708
709static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
710 const char *name_a,
711 const char *name_b)
712{
713 struct diffstat_file *x;
714 x = xcalloc(sizeof (*x), 1);
715 if (diffstat->nr == diffstat->alloc) {
716 diffstat->alloc = alloc_nr(diffstat->alloc);
717 diffstat->files = xrealloc(diffstat->files,
718 diffstat->alloc * sizeof(x));
719 }
720 diffstat->files[diffstat->nr++] = x;
721 if (name_b) {
722 x->name = pprint_rename(name_a, name_b);
723 x->is_renamed = 1;
724 }
725 else
726 x->name = xstrdup(name_a);
727 return x;
728}
729
730static void diffstat_consume(void *priv, char *line, unsigned long len)
731{
732 struct diffstat_t *diffstat = priv;
733 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
734
735 if (line[0] == '+')
736 x->added++;
737 else if (line[0] == '-')
738 x->deleted++;
739}
740
741const char mime_boundary_leader[] = "------------";
742
743static int scale_linear(int it, int width, int max_change)
744{
745 /*
746 * make sure that at least one '-' is printed if there were deletions,
747 * and likewise for '+'.
748 */
749 if (max_change < 2)
750 return it;
751 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
752}
753
754static void show_name(const char *prefix, const char *name, int len,
755 const char *reset, const char *set)
756{
757 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
758}
759
760static void show_graph(char ch, int cnt, const char *set, const char *reset)
761{
762 if (cnt <= 0)
763 return;
764 printf("%s", set);
765 while (cnt--)
766 putchar(ch);
767 printf("%s", reset);
768}
769
770static void show_stats(struct diffstat_t* data, struct diff_options *options)
771{
772 int i, len, add, del, total, adds = 0, dels = 0;
773 int max_change = 0, max_len = 0;
774 int total_files = data->nr;
775 int width, name_width;
776 const char *reset, *set, *add_c, *del_c;
777
778 if (data->nr == 0)
779 return;
780
781 width = options->stat_width ? options->stat_width : 80;
782 name_width = options->stat_name_width ? options->stat_name_width : 50;
783
784 /* Sanity: give at least 5 columns to the graph,
785 * but leave at least 10 columns for the name.
786 */
787 if (width < name_width + 15) {
788 if (name_width <= 25)
789 width = name_width + 15;
790 else
791 name_width = width - 15;
792 }
793
794 /* Find the longest filename and max number of changes */
795 reset = diff_get_color(options->color_diff, DIFF_RESET);
796 set = diff_get_color(options->color_diff, DIFF_PLAIN);
797 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
798 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
799
800 for (i = 0; i < data->nr; i++) {
801 struct diffstat_file *file = data->files[i];
802 int change = file->added + file->deleted;
803
804 if (!file->is_renamed) { /* renames are already quoted by pprint_rename */
805 len = quote_c_style(file->name, NULL, NULL, 0);
806 if (len) {
807 char *qname = xmalloc(len + 1);
808 quote_c_style(file->name, qname, NULL, 0);
809 free(file->name);
810 file->name = qname;
811 }
812 }
813
814 len = strlen(file->name);
815 if (max_len < len)
816 max_len = len;
817
818 if (file->is_binary || file->is_unmerged)
819 continue;
820 if (max_change < change)
821 max_change = change;
822 }
823
824 /* Compute the width of the graph part;
825 * 10 is for one blank at the beginning of the line plus
826 * " | count " between the name and the graph.
827 *
828 * From here on, name_width is the width of the name area,
829 * and width is the width of the graph area.
830 */
831 name_width = (name_width < max_len) ? name_width : max_len;
832 if (width < (name_width + 10) + max_change)
833 width = width - (name_width + 10);
834 else
835 width = max_change;
836
837 for (i = 0; i < data->nr; i++) {
838 const char *prefix = "";
839 char *name = data->files[i]->name;
840 int added = data->files[i]->added;
841 int deleted = data->files[i]->deleted;
842 int name_len;
843
844 /*
845 * "scale" the filename
846 */
847 len = name_width;
848 name_len = strlen(name);
849 if (name_width < name_len) {
850 char *slash;
851 prefix = "...";
852 len -= 3;
853 name += name_len - len;
854 slash = strchr(name, '/');
855 if (slash)
856 name = slash;
857 }
858
859 if (data->files[i]->is_binary) {
860 show_name(prefix, name, len, reset, set);
861 printf(" Bin ");
862 printf("%s%d%s", del_c, deleted, reset);
863 printf(" -> ");
864 printf("%s%d%s", add_c, added, reset);
865 printf(" bytes");
866 printf("\n");
867 goto free_diffstat_file;
868 }
869 else if (data->files[i]->is_unmerged) {
870 show_name(prefix, name, len, reset, set);
871 printf(" Unmerged\n");
872 goto free_diffstat_file;
873 }
874 else if (!data->files[i]->is_renamed &&
875 (added + deleted == 0)) {
876 total_files--;
877 goto free_diffstat_file;
878 }
879
880 /*
881 * scale the add/delete
882 */
883 add = added;
884 del = deleted;
885 total = add + del;
886 adds += add;
887 dels += del;
888
889 if (width <= max_change) {
890 add = scale_linear(add, width, max_change);
891 del = scale_linear(del, width, max_change);
892 total = add + del;
893 }
894 show_name(prefix, name, len, reset, set);
895 printf("%5d ", added + deleted);
896 show_graph('+', add, add_c, reset);
897 show_graph('-', del, del_c, reset);
898 putchar('\n');
899 free_diffstat_file:
900 free(data->files[i]->name);
901 free(data->files[i]);
902 }
903 free(data->files);
904 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
905 set, total_files, adds, dels, reset);
906}
907
908static void show_shortstats(struct diffstat_t* data)
909{
910 int i, adds = 0, dels = 0, total_files = data->nr;
911
912 if (data->nr == 0)
913 return;
914
915 for (i = 0; i < data->nr; i++) {
916 if (!data->files[i]->is_binary &&
917 !data->files[i]->is_unmerged) {
918 int added = data->files[i]->added;
919 int deleted= data->files[i]->deleted;
920 if (!data->files[i]->is_renamed &&
921 (added + deleted == 0)) {
922 total_files--;
923 } else {
924 adds += added;
925 dels += deleted;
926 }
927 }
928 free(data->files[i]->name);
929 free(data->files[i]);
930 }
931 free(data->files);
932
933 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
934 total_files, adds, dels);
935}
936
937static void show_numstat(struct diffstat_t* data, struct diff_options *options)
938{
939 int i;
940
941 for (i = 0; i < data->nr; i++) {
942 struct diffstat_file *file = data->files[i];
943
944 if (file->is_binary)
945 printf("-\t-\t");
946 else
947 printf("%d\t%d\t", file->added, file->deleted);
948 if (options->line_termination && !file->is_renamed &&
949 quote_c_style(file->name, NULL, NULL, 0))
950 quote_c_style(file->name, NULL, stdout, 0);
951 else
952 fputs(file->name, stdout);
953 putchar(options->line_termination);
954 }
955}
956
957struct checkdiff_t {
958 struct xdiff_emit_state xm;
959 const char *filename;
960 int lineno, color_diff;
961};
962
963static void checkdiff_consume(void *priv, char *line, unsigned long len)
964{
965 struct checkdiff_t *data = priv;
966 const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
967 const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
968 const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
969
970 if (line[0] == '+') {
971 int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
972
973 /* check space before tab */
974 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
975 if (line[i] == ' ')
976 spaces++;
977 if (line[i - 1] == '\t' && spaces)
978 space_before_tab = 1;
979
980 /* check white space at line end */
981 if (line[len - 1] == '\n')
982 len--;
983 if (isspace(line[len - 1]))
984 white_space_at_end = 1;
985
986 if (space_before_tab || white_space_at_end) {
987 printf("%s:%d: %s", data->filename, data->lineno, ws);
988 if (space_before_tab) {
989 printf("space before tab");
990 if (white_space_at_end)
991 putchar(',');
992 }
993 if (white_space_at_end)
994 printf("white space at end");
995 printf(":%s ", reset);
996 emit_line_with_ws(1, set, reset, ws, line, len);
997 }
998
999 data->lineno++;
1000 } else if (line[0] == ' ')
1001 data->lineno++;
1002 else if (line[0] == '@') {
1003 char *plus = strchr(line, '+');
1004 if (plus)
1005 data->lineno = strtol(plus, NULL, 10);
1006 else
1007 die("invalid diff");
1008 }
1009}
1010
1011static unsigned char *deflate_it(char *data,
1012 unsigned long size,
1013 unsigned long *result_size)
1014{
1015 int bound;
1016 unsigned char *deflated;
1017 z_stream stream;
1018
1019 memset(&stream, 0, sizeof(stream));
1020 deflateInit(&stream, zlib_compression_level);
1021 bound = deflateBound(&stream, size);
1022 deflated = xmalloc(bound);
1023 stream.next_out = deflated;
1024 stream.avail_out = bound;
1025
1026 stream.next_in = (unsigned char *)data;
1027 stream.avail_in = size;
1028 while (deflate(&stream, Z_FINISH) == Z_OK)
1029 ; /* nothing */
1030 deflateEnd(&stream);
1031 *result_size = stream.total_out;
1032 return deflated;
1033}
1034
1035static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
1036{
1037 void *cp;
1038 void *delta;
1039 void *deflated;
1040 void *data;
1041 unsigned long orig_size;
1042 unsigned long delta_size;
1043 unsigned long deflate_size;
1044 unsigned long data_size;
1045
1046 /* We could do deflated delta, or we could do just deflated two,
1047 * whichever is smaller.
1048 */
1049 delta = NULL;
1050 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1051 if (one->size && two->size) {
1052 delta = diff_delta(one->ptr, one->size,
1053 two->ptr, two->size,
1054 &delta_size, deflate_size);
1055 if (delta) {
1056 void *to_free = delta;
1057 orig_size = delta_size;
1058 delta = deflate_it(delta, delta_size, &delta_size);
1059 free(to_free);
1060 }
1061 }
1062
1063 if (delta && delta_size < deflate_size) {
1064 printf("delta %lu\n", orig_size);
1065 free(deflated);
1066 data = delta;
1067 data_size = delta_size;
1068 }
1069 else {
1070 printf("literal %lu\n", two->size);
1071 free(delta);
1072 data = deflated;
1073 data_size = deflate_size;
1074 }
1075
1076 /* emit data encoded in base85 */
1077 cp = data;
1078 while (data_size) {
1079 int bytes = (52 < data_size) ? 52 : data_size;
1080 char line[70];
1081 data_size -= bytes;
1082 if (bytes <= 26)
1083 line[0] = bytes + 'A' - 1;
1084 else
1085 line[0] = bytes - 26 + 'a' - 1;
1086 encode_85(line + 1, cp, bytes);
1087 cp = (char *) cp + bytes;
1088 puts(line);
1089 }
1090 printf("\n");
1091 free(data);
1092}
1093
1094static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1095{
1096 printf("GIT binary patch\n");
1097 emit_binary_diff_body(one, two);
1098 emit_binary_diff_body(two, one);
1099}
1100
1101static void setup_diff_attr_check(struct git_attr_check *check)
1102{
1103 static struct git_attr *attr_diff;
1104 static struct git_attr *attr_diff_func_name;
1105
1106 if (!attr_diff) {
1107 attr_diff = git_attr("diff", 4);
1108 attr_diff_func_name = git_attr("funcname", 8);
1109 }
1110 check[0].attr = attr_diff;
1111 check[1].attr = attr_diff_func_name;
1112}
1113
1114static void diff_filespec_check_attr(struct diff_filespec *one)
1115{
1116 struct git_attr_check attr_diff_check[2];
1117
1118 if (one->checked_attr)
1119 return;
1120
1121 setup_diff_attr_check(attr_diff_check);
1122 one->is_binary = 0;
1123 one->hunk_header_ident = NULL;
1124
1125 if (!git_checkattr(one->path, ARRAY_SIZE(attr_diff_check), attr_diff_check)) {
1126 const char *value;
1127
1128 /* binaryness */
1129 value = attr_diff_check[0].value;
1130 if (ATTR_TRUE(value))
1131 ;
1132 else if (ATTR_FALSE(value))
1133 one->is_binary = 1;
1134
1135 /* hunk header ident */
1136 value = attr_diff_check[1].value;
1137 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1138 ;
1139 else
1140 one->hunk_header_ident = value;
1141 }
1142
1143 if (!one->data && DIFF_FILE_VALID(one))
1144 diff_populate_filespec(one, 0);
1145
1146 if (one->data)
1147 one->is_binary = buffer_is_binary(one->data, one->size);
1148
1149}
1150
1151int diff_filespec_is_binary(struct diff_filespec *one)
1152{
1153 diff_filespec_check_attr(one);
1154 return one->is_binary;
1155}
1156
1157static struct hunk_header_regexp {
1158 char *name;
1159 char *regexp;
1160 struct hunk_header_regexp *next;
1161} *hunk_header_regexp_list, **hunk_header_regexp_tail;
1162
1163static int hunk_header_config(const char *var, const char *value)
1164{
1165 static const char funcname[] = "funcname.";
1166 struct hunk_header_regexp *hh;
1167
1168 if (prefixcmp(var, funcname))
1169 return 0;
1170 var += strlen(funcname);
1171 for (hh = hunk_header_regexp_list; hh; hh = hh->next)
1172 if (!strcmp(var, hh->name)) {
1173 free(hh->regexp);
1174 hh->regexp = xstrdup(value);
1175 return 0;
1176 }
1177 hh = xcalloc(1, sizeof(*hh));
1178 hh->name = xstrdup(var);
1179 hh->regexp = xstrdup(value);
1180 hh->next = NULL;
1181 *hunk_header_regexp_tail = hh;
1182 return 0;
1183}
1184
1185static const char *hunk_header_regexp(const char *ident)
1186{
1187 struct hunk_header_regexp *hh;
1188
1189 if (!hunk_header_regexp_tail) {
1190 hunk_header_regexp_tail = &hunk_header_regexp_list;
1191 git_config(hunk_header_config);
1192 }
1193 for (hh = hunk_header_regexp_list; hh; hh = hh->next)
1194 if (!strcmp(ident, hh->name))
1195 return hh->regexp;
1196 return NULL;
1197}
1198
1199static const char *diff_hunk_header_regexp(struct diff_filespec *one)
1200{
1201 const char *ident, *regexp;
1202
1203 diff_filespec_check_attr(one);
1204 ident = one->hunk_header_ident;
1205
1206 if (!ident)
1207 /*
1208 * If the config file has "funcname.default" defined, that
1209 * regexp is used; otherwise NULL is returned and xemit uses
1210 * the built-in default.
1211 */
1212 return hunk_header_regexp("default");
1213
1214 /* Look up custom "funcname.$ident" regexp from config. */
1215 regexp = hunk_header_regexp(ident);
1216 if (regexp)
1217 return regexp;
1218
1219 /*
1220 * And define built-in fallback patterns here. Note that
1221 * these can be overriden by the user's config settings.
1222 */
1223 if (!strcmp(ident, "java"))
1224 return "!^[ ]*\\(catch\\|do\\|for\\|if\\|instanceof\\|"
1225 "new\\|return\\|switch\\|throw\\|while\\)\n"
1226 "^[ ]*\\(\\([ ]*"
1227 "[A-Za-z_][A-Za-z_0-9]*\\)\\{2,\\}"
1228 "[ ]*([^;]*$\\)";
1229
1230 return NULL;
1231}
1232
1233static void builtin_diff(const char *name_a,
1234 const char *name_b,
1235 struct diff_filespec *one,
1236 struct diff_filespec *two,
1237 const char *xfrm_msg,
1238 struct diff_options *o,
1239 int complete_rewrite)
1240{
1241 mmfile_t mf1, mf2;
1242 const char *lbl[2];
1243 char *a_one, *b_two;
1244 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1245 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1246
1247 a_one = quote_two("a/", name_a + (*name_a == '/'));
1248 b_two = quote_two("b/", name_b + (*name_b == '/'));
1249 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1250 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1251 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1252 if (lbl[0][0] == '/') {
1253 /* /dev/null */
1254 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1255 if (xfrm_msg && xfrm_msg[0])
1256 printf("%s%s%s\n", set, xfrm_msg, reset);
1257 }
1258 else if (lbl[1][0] == '/') {
1259 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1260 if (xfrm_msg && xfrm_msg[0])
1261 printf("%s%s%s\n", set, xfrm_msg, reset);
1262 }
1263 else {
1264 if (one->mode != two->mode) {
1265 printf("%sold mode %06o%s\n", set, one->mode, reset);
1266 printf("%snew mode %06o%s\n", set, two->mode, reset);
1267 }
1268 if (xfrm_msg && xfrm_msg[0])
1269 printf("%s%s%s\n", set, xfrm_msg, reset);
1270 /*
1271 * we do not run diff between different kind
1272 * of objects.
1273 */
1274 if ((one->mode ^ two->mode) & S_IFMT)
1275 goto free_ab_and_return;
1276 if (complete_rewrite) {
1277 emit_rewrite_diff(name_a, name_b, one, two,
1278 o->color_diff);
1279 o->found_changes = 1;
1280 goto free_ab_and_return;
1281 }
1282 }
1283
1284 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1285 die("unable to read files to diff");
1286
1287 if (!o->text &&
1288 (diff_filespec_is_binary(one) || diff_filespec_is_binary(two))) {
1289 /* Quite common confusing case */
1290 if (mf1.size == mf2.size &&
1291 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1292 goto free_ab_and_return;
1293 if (o->binary)
1294 emit_binary_diff(&mf1, &mf2);
1295 else
1296 printf("Binary files %s and %s differ\n",
1297 lbl[0], lbl[1]);
1298 o->found_changes = 1;
1299 }
1300 else {
1301 /* Crazy xdl interfaces.. */
1302 const char *diffopts = getenv("GIT_DIFF_OPTS");
1303 xpparam_t xpp;
1304 xdemitconf_t xecfg;
1305 xdemitcb_t ecb;
1306 struct emit_callback ecbdata;
1307 const char *hunk_header_regexp;
1308
1309 hunk_header_regexp = diff_hunk_header_regexp(one);
1310 if (!hunk_header_regexp)
1311 hunk_header_regexp = diff_hunk_header_regexp(two);
1312
1313 memset(&xecfg, 0, sizeof(xecfg));
1314 memset(&ecbdata, 0, sizeof(ecbdata));
1315 ecbdata.label_path = lbl;
1316 ecbdata.color_diff = o->color_diff;
1317 ecbdata.found_changesp = &o->found_changes;
1318 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1319 xecfg.ctxlen = o->context;
1320 xecfg.flags = XDL_EMIT_FUNCNAMES;
1321 if (hunk_header_regexp)
1322 xdiff_set_find_func(&xecfg, hunk_header_regexp);
1323 if (!diffopts)
1324 ;
1325 else if (!prefixcmp(diffopts, "--unified="))
1326 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1327 else if (!prefixcmp(diffopts, "-u"))
1328 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1329 ecb.outf = xdiff_outf;
1330 ecb.priv = &ecbdata;
1331 ecbdata.xm.consume = fn_out_consume;
1332 if (o->color_diff_words)
1333 ecbdata.diff_words =
1334 xcalloc(1, sizeof(struct diff_words_data));
1335 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1336 if (o->color_diff_words)
1337 free_diff_words_data(&ecbdata);
1338 }
1339
1340 free_ab_and_return:
1341 diff_free_filespec_data(one);
1342 diff_free_filespec_data(two);
1343 free(a_one);
1344 free(b_two);
1345 return;
1346}
1347
1348static void builtin_diffstat(const char *name_a, const char *name_b,
1349 struct diff_filespec *one,
1350 struct diff_filespec *two,
1351 struct diffstat_t *diffstat,
1352 struct diff_options *o,
1353 int complete_rewrite)
1354{
1355 mmfile_t mf1, mf2;
1356 struct diffstat_file *data;
1357
1358 data = diffstat_add(diffstat, name_a, name_b);
1359
1360 if (!one || !two) {
1361 data->is_unmerged = 1;
1362 return;
1363 }
1364 if (complete_rewrite) {
1365 diff_populate_filespec(one, 0);
1366 diff_populate_filespec(two, 0);
1367 data->deleted = count_lines(one->data, one->size);
1368 data->added = count_lines(two->data, two->size);
1369 goto free_and_return;
1370 }
1371 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1372 die("unable to read files to diff");
1373
1374 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1375 data->is_binary = 1;
1376 data->added = mf2.size;
1377 data->deleted = mf1.size;
1378 } else {
1379 /* Crazy xdl interfaces.. */
1380 xpparam_t xpp;
1381 xdemitconf_t xecfg;
1382 xdemitcb_t ecb;
1383
1384 memset(&xecfg, 0, sizeof(xecfg));
1385 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1386 ecb.outf = xdiff_outf;
1387 ecb.priv = diffstat;
1388 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1389 }
1390
1391 free_and_return:
1392 diff_free_filespec_data(one);
1393 diff_free_filespec_data(two);
1394}
1395
1396static void builtin_checkdiff(const char *name_a, const char *name_b,
1397 struct diff_filespec *one,
1398 struct diff_filespec *two, struct diff_options *o)
1399{
1400 mmfile_t mf1, mf2;
1401 struct checkdiff_t data;
1402
1403 if (!two)
1404 return;
1405
1406 memset(&data, 0, sizeof(data));
1407 data.xm.consume = checkdiff_consume;
1408 data.filename = name_b ? name_b : name_a;
1409 data.lineno = 0;
1410 data.color_diff = o->color_diff;
1411
1412 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1413 die("unable to read files to diff");
1414
1415 if (diff_filespec_is_binary(two))
1416 goto free_and_return;
1417 else {
1418 /* Crazy xdl interfaces.. */
1419 xpparam_t xpp;
1420 xdemitconf_t xecfg;
1421 xdemitcb_t ecb;
1422
1423 memset(&xecfg, 0, sizeof(xecfg));
1424 xpp.flags = XDF_NEED_MINIMAL;
1425 ecb.outf = xdiff_outf;
1426 ecb.priv = &data;
1427 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1428 }
1429 free_and_return:
1430 diff_free_filespec_data(one);
1431 diff_free_filespec_data(two);
1432}
1433
1434struct diff_filespec *alloc_filespec(const char *path)
1435{
1436 int namelen = strlen(path);
1437 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1438
1439 memset(spec, 0, sizeof(*spec));
1440 spec->path = (char *)(spec + 1);
1441 memcpy(spec->path, path, namelen+1);
1442 return spec;
1443}
1444
1445void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1446 unsigned short mode)
1447{
1448 if (mode) {
1449 spec->mode = canon_mode(mode);
1450 hashcpy(spec->sha1, sha1);
1451 spec->sha1_valid = !is_null_sha1(sha1);
1452 }
1453}
1454
1455/*
1456 * Given a name and sha1 pair, if the index tells us the file in
1457 * the work tree has that object contents, return true, so that
1458 * prepare_temp_file() does not have to inflate and extract.
1459 */
1460static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1461{
1462 struct cache_entry *ce;
1463 struct stat st;
1464 int pos, len;
1465
1466 /* We do not read the cache ourselves here, because the
1467 * benchmark with my previous version that always reads cache
1468 * shows that it makes things worse for diff-tree comparing
1469 * two linux-2.6 kernel trees in an already checked out work
1470 * tree. This is because most diff-tree comparisons deal with
1471 * only a small number of files, while reading the cache is
1472 * expensive for a large project, and its cost outweighs the
1473 * savings we get by not inflating the object to a temporary
1474 * file. Practically, this code only helps when we are used
1475 * by diff-cache --cached, which does read the cache before
1476 * calling us.
1477 */
1478 if (!active_cache)
1479 return 0;
1480
1481 /* We want to avoid the working directory if our caller
1482 * doesn't need the data in a normal file, this system
1483 * is rather slow with its stat/open/mmap/close syscalls,
1484 * and the object is contained in a pack file. The pack
1485 * is probably already open and will be faster to obtain
1486 * the data through than the working directory. Loose
1487 * objects however would tend to be slower as they need
1488 * to be individually opened and inflated.
1489 */
1490 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1491 return 0;
1492
1493 len = strlen(name);
1494 pos = cache_name_pos(name, len);
1495 if (pos < 0)
1496 return 0;
1497 ce = active_cache[pos];
1498 if ((lstat(name, &st) < 0) ||
1499 !S_ISREG(st.st_mode) || /* careful! */
1500 ce_match_stat(ce, &st, 0) ||
1501 hashcmp(sha1, ce->sha1))
1502 return 0;
1503 /* we return 1 only when we can stat, it is a regular file,
1504 * stat information matches, and sha1 recorded in the cache
1505 * matches. I.e. we know the file in the work tree really is
1506 * the same as the <name, sha1> pair.
1507 */
1508 return 1;
1509}
1510
1511static int populate_from_stdin(struct diff_filespec *s)
1512{
1513#define INCREMENT 1024
1514 char *buf;
1515 unsigned long size;
1516 ssize_t got;
1517
1518 size = 0;
1519 buf = NULL;
1520 while (1) {
1521 buf = xrealloc(buf, size + INCREMENT);
1522 got = xread(0, buf + size, INCREMENT);
1523 if (!got)
1524 break; /* EOF */
1525 if (got < 0)
1526 return error("error while reading from stdin %s",
1527 strerror(errno));
1528 size += got;
1529 }
1530 s->should_munmap = 0;
1531 s->data = buf;
1532 s->size = size;
1533 s->should_free = 1;
1534 return 0;
1535}
1536
1537static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1538{
1539 int len;
1540 char *data = xmalloc(100);
1541 len = snprintf(data, 100,
1542 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1543 s->data = data;
1544 s->size = len;
1545 s->should_free = 1;
1546 if (size_only) {
1547 s->data = NULL;
1548 free(data);
1549 }
1550 return 0;
1551}
1552
1553/*
1554 * While doing rename detection and pickaxe operation, we may need to
1555 * grab the data for the blob (or file) for our own in-core comparison.
1556 * diff_filespec has data and size fields for this purpose.
1557 */
1558int diff_populate_filespec(struct diff_filespec *s, int size_only)
1559{
1560 int err = 0;
1561 if (!DIFF_FILE_VALID(s))
1562 die("internal error: asking to populate invalid file.");
1563 if (S_ISDIR(s->mode))
1564 return -1;
1565
1566 if (s->data)
1567 return 0;
1568
1569 if (size_only && 0 < s->size)
1570 return 0;
1571
1572 if (S_ISGITLINK(s->mode))
1573 return diff_populate_gitlink(s, size_only);
1574
1575 if (!s->sha1_valid ||
1576 reuse_worktree_file(s->path, s->sha1, 0)) {
1577 struct stat st;
1578 int fd;
1579 char *buf;
1580 unsigned long size;
1581
1582 if (!strcmp(s->path, "-"))
1583 return populate_from_stdin(s);
1584
1585 if (lstat(s->path, &st) < 0) {
1586 if (errno == ENOENT) {
1587 err_empty:
1588 err = -1;
1589 empty:
1590 s->data = (char *)"";
1591 s->size = 0;
1592 return err;
1593 }
1594 }
1595 s->size = xsize_t(st.st_size);
1596 if (!s->size)
1597 goto empty;
1598 if (size_only)
1599 return 0;
1600 if (S_ISLNK(st.st_mode)) {
1601 int ret;
1602 s->data = xmalloc(s->size);
1603 s->should_free = 1;
1604 ret = readlink(s->path, s->data, s->size);
1605 if (ret < 0) {
1606 free(s->data);
1607 goto err_empty;
1608 }
1609 return 0;
1610 }
1611 fd = open(s->path, O_RDONLY);
1612 if (fd < 0)
1613 goto err_empty;
1614 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1615 close(fd);
1616 s->should_munmap = 1;
1617
1618 /*
1619 * Convert from working tree format to canonical git format
1620 */
1621 size = s->size;
1622 buf = convert_to_git(s->path, s->data, &size);
1623 if (buf) {
1624 munmap(s->data, s->size);
1625 s->should_munmap = 0;
1626 s->data = buf;
1627 s->size = size;
1628 s->should_free = 1;
1629 }
1630 }
1631 else {
1632 enum object_type type;
1633 if (size_only)
1634 type = sha1_object_info(s->sha1, &s->size);
1635 else {
1636 s->data = read_sha1_file(s->sha1, &type, &s->size);
1637 s->should_free = 1;
1638 }
1639 }
1640 return 0;
1641}
1642
1643void diff_free_filespec_data(struct diff_filespec *s)
1644{
1645 if (s->should_free)
1646 free(s->data);
1647 else if (s->should_munmap)
1648 munmap(s->data, s->size);
1649
1650 if (s->should_free || s->should_munmap) {
1651 s->should_free = s->should_munmap = 0;
1652 s->data = NULL;
1653 }
1654 free(s->cnt_data);
1655 s->cnt_data = NULL;
1656}
1657
1658static void prep_temp_blob(struct diff_tempfile *temp,
1659 void *blob,
1660 unsigned long size,
1661 const unsigned char *sha1,
1662 int mode)
1663{
1664 int fd;
1665
1666 fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1667 if (fd < 0)
1668 die("unable to create temp-file");
1669 if (write_in_full(fd, blob, size) != size)
1670 die("unable to write temp-file");
1671 close(fd);
1672 temp->name = temp->tmp_path;
1673 strcpy(temp->hex, sha1_to_hex(sha1));
1674 temp->hex[40] = 0;
1675 sprintf(temp->mode, "%06o", mode);
1676}
1677
1678static void prepare_temp_file(const char *name,
1679 struct diff_tempfile *temp,
1680 struct diff_filespec *one)
1681{
1682 if (!DIFF_FILE_VALID(one)) {
1683 not_a_valid_file:
1684 /* A '-' entry produces this for file-2, and
1685 * a '+' entry produces this for file-1.
1686 */
1687 temp->name = "/dev/null";
1688 strcpy(temp->hex, ".");
1689 strcpy(temp->mode, ".");
1690 return;
1691 }
1692
1693 if (!one->sha1_valid ||
1694 reuse_worktree_file(name, one->sha1, 1)) {
1695 struct stat st;
1696 if (lstat(name, &st) < 0) {
1697 if (errno == ENOENT)
1698 goto not_a_valid_file;
1699 die("stat(%s): %s", name, strerror(errno));
1700 }
1701 if (S_ISLNK(st.st_mode)) {
1702 int ret;
1703 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1704 size_t sz = xsize_t(st.st_size);
1705 if (sizeof(buf) <= st.st_size)
1706 die("symlink too long: %s", name);
1707 ret = readlink(name, buf, sz);
1708 if (ret < 0)
1709 die("readlink(%s)", name);
1710 prep_temp_blob(temp, buf, sz,
1711 (one->sha1_valid ?
1712 one->sha1 : null_sha1),
1713 (one->sha1_valid ?
1714 one->mode : S_IFLNK));
1715 }
1716 else {
1717 /* we can borrow from the file in the work tree */
1718 temp->name = name;
1719 if (!one->sha1_valid)
1720 strcpy(temp->hex, sha1_to_hex(null_sha1));
1721 else
1722 strcpy(temp->hex, sha1_to_hex(one->sha1));
1723 /* Even though we may sometimes borrow the
1724 * contents from the work tree, we always want
1725 * one->mode. mode is trustworthy even when
1726 * !(one->sha1_valid), as long as
1727 * DIFF_FILE_VALID(one).
1728 */
1729 sprintf(temp->mode, "%06o", one->mode);
1730 }
1731 return;
1732 }
1733 else {
1734 if (diff_populate_filespec(one, 0))
1735 die("cannot read data blob for %s", one->path);
1736 prep_temp_blob(temp, one->data, one->size,
1737 one->sha1, one->mode);
1738 }
1739}
1740
1741static void remove_tempfile(void)
1742{
1743 int i;
1744
1745 for (i = 0; i < 2; i++)
1746 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1747 unlink(diff_temp[i].name);
1748 diff_temp[i].name = NULL;
1749 }
1750}
1751
1752static void remove_tempfile_on_signal(int signo)
1753{
1754 remove_tempfile();
1755 signal(SIGINT, SIG_DFL);
1756 raise(signo);
1757}
1758
1759static int spawn_prog(const char *pgm, const char **arg)
1760{
1761 pid_t pid;
1762 int status;
1763
1764 fflush(NULL);
1765 pid = fork();
1766 if (pid < 0)
1767 die("unable to fork");
1768 if (!pid) {
1769 execvp(pgm, (char *const*) arg);
1770 exit(255);
1771 }
1772
1773 while (waitpid(pid, &status, 0) < 0) {
1774 if (errno == EINTR)
1775 continue;
1776 return -1;
1777 }
1778
1779 /* Earlier we did not check the exit status because
1780 * diff exits non-zero if files are different, and
1781 * we are not interested in knowing that. It was a
1782 * mistake which made it harder to quit a diff-*
1783 * session that uses the git-apply-patch-script as
1784 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1785 * should also exit non-zero only when it wants to
1786 * abort the entire diff-* session.
1787 */
1788 if (WIFEXITED(status) && !WEXITSTATUS(status))
1789 return 0;
1790 return -1;
1791}
1792
1793/* An external diff command takes:
1794 *
1795 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1796 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1797 *
1798 */
1799static void run_external_diff(const char *pgm,
1800 const char *name,
1801 const char *other,
1802 struct diff_filespec *one,
1803 struct diff_filespec *two,
1804 const char *xfrm_msg,
1805 int complete_rewrite)
1806{
1807 const char *spawn_arg[10];
1808 struct diff_tempfile *temp = diff_temp;
1809 int retval;
1810 static int atexit_asked = 0;
1811 const char *othername;
1812 const char **arg = &spawn_arg[0];
1813
1814 othername = (other? other : name);
1815 if (one && two) {
1816 prepare_temp_file(name, &temp[0], one);
1817 prepare_temp_file(othername, &temp[1], two);
1818 if (! atexit_asked &&
1819 (temp[0].name == temp[0].tmp_path ||
1820 temp[1].name == temp[1].tmp_path)) {
1821 atexit_asked = 1;
1822 atexit(remove_tempfile);
1823 }
1824 signal(SIGINT, remove_tempfile_on_signal);
1825 }
1826
1827 if (one && two) {
1828 *arg++ = pgm;
1829 *arg++ = name;
1830 *arg++ = temp[0].name;
1831 *arg++ = temp[0].hex;
1832 *arg++ = temp[0].mode;
1833 *arg++ = temp[1].name;
1834 *arg++ = temp[1].hex;
1835 *arg++ = temp[1].mode;
1836 if (other) {
1837 *arg++ = other;
1838 *arg++ = xfrm_msg;
1839 }
1840 } else {
1841 *arg++ = pgm;
1842 *arg++ = name;
1843 }
1844 *arg = NULL;
1845 retval = spawn_prog(pgm, spawn_arg);
1846 remove_tempfile();
1847 if (retval) {
1848 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1849 exit(1);
1850 }
1851}
1852
1853static const char *external_diff_attr(const char *name)
1854{
1855 struct git_attr_check attr_diff_check;
1856
1857 setup_diff_attr_check(&attr_diff_check);
1858 if (!git_checkattr(name, 1, &attr_diff_check)) {
1859 const char *value = attr_diff_check.value;
1860 if (!ATTR_TRUE(value) &&
1861 !ATTR_FALSE(value) &&
1862 !ATTR_UNSET(value)) {
1863 struct ll_diff_driver *drv;
1864
1865 if (!user_diff_tail) {
1866 user_diff_tail = &user_diff;
1867 git_config(git_diff_ui_config);
1868 }
1869 for (drv = user_diff; drv; drv = drv->next)
1870 if (!strcmp(drv->name, value))
1871 return drv->cmd;
1872 }
1873 }
1874 return NULL;
1875}
1876
1877static void run_diff_cmd(const char *pgm,
1878 const char *name,
1879 const char *other,
1880 struct diff_filespec *one,
1881 struct diff_filespec *two,
1882 const char *xfrm_msg,
1883 struct diff_options *o,
1884 int complete_rewrite)
1885{
1886 if (!o->allow_external)
1887 pgm = NULL;
1888 else {
1889 const char *cmd = external_diff_attr(name);
1890 if (cmd)
1891 pgm = cmd;
1892 }
1893
1894 if (pgm) {
1895 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1896 complete_rewrite);
1897 return;
1898 }
1899 if (one && two)
1900 builtin_diff(name, other ? other : name,
1901 one, two, xfrm_msg, o, complete_rewrite);
1902 else
1903 printf("* Unmerged path %s\n", name);
1904}
1905
1906static void diff_fill_sha1_info(struct diff_filespec *one)
1907{
1908 if (DIFF_FILE_VALID(one)) {
1909 if (!one->sha1_valid) {
1910 struct stat st;
1911 if (!strcmp(one->path, "-")) {
1912 hashcpy(one->sha1, null_sha1);
1913 return;
1914 }
1915 if (lstat(one->path, &st) < 0)
1916 die("stat %s", one->path);
1917 if (index_path(one->sha1, one->path, &st, 0))
1918 die("cannot hash %s\n", one->path);
1919 }
1920 }
1921 else
1922 hashclr(one->sha1);
1923}
1924
1925static int similarity_index(struct diff_filepair *p)
1926{
1927 return p->score * 100 / MAX_SCORE;
1928}
1929
1930static void run_diff(struct diff_filepair *p, struct diff_options *o)
1931{
1932 const char *pgm = external_diff();
1933 char msg[PATH_MAX*2+300], *xfrm_msg;
1934 struct diff_filespec *one;
1935 struct diff_filespec *two;
1936 const char *name;
1937 const char *other;
1938 char *name_munged, *other_munged;
1939 int complete_rewrite = 0;
1940 int len;
1941
1942 if (DIFF_PAIR_UNMERGED(p)) {
1943 /* unmerged */
1944 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1945 return;
1946 }
1947
1948 name = p->one->path;
1949 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1950 name_munged = quote_one(name);
1951 other_munged = quote_one(other);
1952 one = p->one; two = p->two;
1953
1954 diff_fill_sha1_info(one);
1955 diff_fill_sha1_info(two);
1956
1957 len = 0;
1958 switch (p->status) {
1959 case DIFF_STATUS_COPIED:
1960 len += snprintf(msg + len, sizeof(msg) - len,
1961 "similarity index %d%%\n"
1962 "copy from %s\n"
1963 "copy to %s\n",
1964 similarity_index(p), name_munged, other_munged);
1965 break;
1966 case DIFF_STATUS_RENAMED:
1967 len += snprintf(msg + len, sizeof(msg) - len,
1968 "similarity index %d%%\n"
1969 "rename from %s\n"
1970 "rename to %s\n",
1971 similarity_index(p), name_munged, other_munged);
1972 break;
1973 case DIFF_STATUS_MODIFIED:
1974 if (p->score) {
1975 len += snprintf(msg + len, sizeof(msg) - len,
1976 "dissimilarity index %d%%\n",
1977 similarity_index(p));
1978 complete_rewrite = 1;
1979 break;
1980 }
1981 /* fallthru */
1982 default:
1983 /* nothing */
1984 ;
1985 }
1986
1987 if (hashcmp(one->sha1, two->sha1)) {
1988 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1989
1990 if (o->binary) {
1991 mmfile_t mf;
1992 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
1993 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
1994 abbrev = 40;
1995 }
1996 len += snprintf(msg + len, sizeof(msg) - len,
1997 "index %.*s..%.*s",
1998 abbrev, sha1_to_hex(one->sha1),
1999 abbrev, sha1_to_hex(two->sha1));
2000 if (one->mode == two->mode)
2001 len += snprintf(msg + len, sizeof(msg) - len,
2002 " %06o", one->mode);
2003 len += snprintf(msg + len, sizeof(msg) - len, "\n");
2004 }
2005
2006 if (len)
2007 msg[--len] = 0;
2008 xfrm_msg = len ? msg : NULL;
2009
2010 if (!pgm &&
2011 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2012 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2013 /* a filepair that changes between file and symlink
2014 * needs to be split into deletion and creation.
2015 */
2016 struct diff_filespec *null = alloc_filespec(two->path);
2017 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
2018 free(null);
2019 null = alloc_filespec(one->path);
2020 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
2021 free(null);
2022 }
2023 else
2024 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
2025 complete_rewrite);
2026
2027 free(name_munged);
2028 free(other_munged);
2029}
2030
2031static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2032 struct diffstat_t *diffstat)
2033{
2034 const char *name;
2035 const char *other;
2036 int complete_rewrite = 0;
2037
2038 if (DIFF_PAIR_UNMERGED(p)) {
2039 /* unmerged */
2040 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2041 return;
2042 }
2043
2044 name = p->one->path;
2045 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2046
2047 diff_fill_sha1_info(p->one);
2048 diff_fill_sha1_info(p->two);
2049
2050 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2051 complete_rewrite = 1;
2052 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2053}
2054
2055static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2056{
2057 const char *name;
2058 const char *other;
2059
2060 if (DIFF_PAIR_UNMERGED(p)) {
2061 /* unmerged */
2062 return;
2063 }
2064
2065 name = p->one->path;
2066 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2067
2068 diff_fill_sha1_info(p->one);
2069 diff_fill_sha1_info(p->two);
2070
2071 builtin_checkdiff(name, other, p->one, p->two, o);
2072}
2073
2074void diff_setup(struct diff_options *options)
2075{
2076 memset(options, 0, sizeof(*options));
2077 options->line_termination = '\n';
2078 options->break_opt = -1;
2079 options->rename_limit = -1;
2080 options->context = 3;
2081 options->msg_sep = "";
2082
2083 options->change = diff_change;
2084 options->add_remove = diff_addremove;
2085 options->color_diff = diff_use_color_default;
2086 options->detect_rename = diff_detect_rename_default;
2087}
2088
2089int diff_setup_done(struct diff_options *options)
2090{
2091 int count = 0;
2092
2093 if (options->output_format & DIFF_FORMAT_NAME)
2094 count++;
2095 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2096 count++;
2097 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2098 count++;
2099 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2100 count++;
2101 if (count > 1)
2102 die("--name-only, --name-status, --check and -s are mutually exclusive");
2103
2104 if (options->find_copies_harder)
2105 options->detect_rename = DIFF_DETECT_COPY;
2106
2107 if (options->output_format & (DIFF_FORMAT_NAME |
2108 DIFF_FORMAT_NAME_STATUS |
2109 DIFF_FORMAT_CHECKDIFF |
2110 DIFF_FORMAT_NO_OUTPUT))
2111 options->output_format &= ~(DIFF_FORMAT_RAW |
2112 DIFF_FORMAT_NUMSTAT |
2113 DIFF_FORMAT_DIFFSTAT |
2114 DIFF_FORMAT_SHORTSTAT |
2115 DIFF_FORMAT_SUMMARY |
2116 DIFF_FORMAT_PATCH);
2117
2118 /*
2119 * These cases always need recursive; we do not drop caller-supplied
2120 * recursive bits for other formats here.
2121 */
2122 if (options->output_format & (DIFF_FORMAT_PATCH |
2123 DIFF_FORMAT_NUMSTAT |
2124 DIFF_FORMAT_DIFFSTAT |
2125 DIFF_FORMAT_SHORTSTAT |
2126 DIFF_FORMAT_SUMMARY |
2127 DIFF_FORMAT_CHECKDIFF))
2128 options->recursive = 1;
2129 /*
2130 * Also pickaxe would not work very well if you do not say recursive
2131 */
2132 if (options->pickaxe)
2133 options->recursive = 1;
2134
2135 if (options->detect_rename && options->rename_limit < 0)
2136 options->rename_limit = diff_rename_limit_default;
2137 if (options->setup & DIFF_SETUP_USE_CACHE) {
2138 if (!active_cache)
2139 /* read-cache does not die even when it fails
2140 * so it is safe for us to do this here. Also
2141 * it does not smudge active_cache or active_nr
2142 * when it fails, so we do not have to worry about
2143 * cleaning it up ourselves either.
2144 */
2145 read_cache();
2146 }
2147 if (options->abbrev <= 0 || 40 < options->abbrev)
2148 options->abbrev = 40; /* full */
2149
2150 /*
2151 * It does not make sense to show the first hit we happened
2152 * to have found. It does not make sense not to return with
2153 * exit code in such a case either.
2154 */
2155 if (options->quiet) {
2156 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2157 options->exit_with_status = 1;
2158 }
2159
2160 /*
2161 * If we postprocess in diffcore, we cannot simply return
2162 * upon the first hit. We need to run diff as usual.
2163 */
2164 if (options->pickaxe || options->filter)
2165 options->quiet = 0;
2166
2167 return 0;
2168}
2169
2170static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2171{
2172 char c, *eq;
2173 int len;
2174
2175 if (*arg != '-')
2176 return 0;
2177 c = *++arg;
2178 if (!c)
2179 return 0;
2180 if (c == arg_short) {
2181 c = *++arg;
2182 if (!c)
2183 return 1;
2184 if (val && isdigit(c)) {
2185 char *end;
2186 int n = strtoul(arg, &end, 10);
2187 if (*end)
2188 return 0;
2189 *val = n;
2190 return 1;
2191 }
2192 return 0;
2193 }
2194 if (c != '-')
2195 return 0;
2196 arg++;
2197 eq = strchr(arg, '=');
2198 if (eq)
2199 len = eq - arg;
2200 else
2201 len = strlen(arg);
2202 if (!len || strncmp(arg, arg_long, len))
2203 return 0;
2204 if (eq) {
2205 int n;
2206 char *end;
2207 if (!isdigit(*++eq))
2208 return 0;
2209 n = strtoul(eq, &end, 10);
2210 if (*end)
2211 return 0;
2212 *val = n;
2213 }
2214 return 1;
2215}
2216
2217static int diff_scoreopt_parse(const char *opt);
2218
2219int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2220{
2221 const char *arg = av[0];
2222 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2223 options->output_format |= DIFF_FORMAT_PATCH;
2224 else if (opt_arg(arg, 'U', "unified", &options->context))
2225 options->output_format |= DIFF_FORMAT_PATCH;
2226 else if (!strcmp(arg, "--raw"))
2227 options->output_format |= DIFF_FORMAT_RAW;
2228 else if (!strcmp(arg, "--patch-with-raw")) {
2229 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2230 }
2231 else if (!strcmp(arg, "--numstat")) {
2232 options->output_format |= DIFF_FORMAT_NUMSTAT;
2233 }
2234 else if (!strcmp(arg, "--shortstat")) {
2235 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2236 }
2237 else if (!prefixcmp(arg, "--stat")) {
2238 char *end;
2239 int width = options->stat_width;
2240 int name_width = options->stat_name_width;
2241 arg += 6;
2242 end = (char *)arg;
2243
2244 switch (*arg) {
2245 case '-':
2246 if (!prefixcmp(arg, "-width="))
2247 width = strtoul(arg + 7, &end, 10);
2248 else if (!prefixcmp(arg, "-name-width="))
2249 name_width = strtoul(arg + 12, &end, 10);
2250 break;
2251 case '=':
2252 width = strtoul(arg+1, &end, 10);
2253 if (*end == ',')
2254 name_width = strtoul(end+1, &end, 10);
2255 }
2256
2257 /* Important! This checks all the error cases! */
2258 if (*end)
2259 return 0;
2260 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2261 options->stat_name_width = name_width;
2262 options->stat_width = width;
2263 }
2264 else if (!strcmp(arg, "--check"))
2265 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2266 else if (!strcmp(arg, "--summary"))
2267 options->output_format |= DIFF_FORMAT_SUMMARY;
2268 else if (!strcmp(arg, "--patch-with-stat")) {
2269 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2270 }
2271 else if (!strcmp(arg, "-z"))
2272 options->line_termination = 0;
2273 else if (!prefixcmp(arg, "-l"))
2274 options->rename_limit = strtoul(arg+2, NULL, 10);
2275 else if (!strcmp(arg, "--full-index"))
2276 options->full_index = 1;
2277 else if (!strcmp(arg, "--binary")) {
2278 options->output_format |= DIFF_FORMAT_PATCH;
2279 options->binary = 1;
2280 }
2281 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
2282 options->text = 1;
2283 }
2284 else if (!strcmp(arg, "--name-only"))
2285 options->output_format |= DIFF_FORMAT_NAME;
2286 else if (!strcmp(arg, "--name-status"))
2287 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2288 else if (!strcmp(arg, "-R"))
2289 options->reverse_diff = 1;
2290 else if (!prefixcmp(arg, "-S"))
2291 options->pickaxe = arg + 2;
2292 else if (!strcmp(arg, "-s")) {
2293 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2294 }
2295 else if (!prefixcmp(arg, "-O"))
2296 options->orderfile = arg + 2;
2297 else if (!prefixcmp(arg, "--diff-filter="))
2298 options->filter = arg + 14;
2299 else if (!strcmp(arg, "--pickaxe-all"))
2300 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2301 else if (!strcmp(arg, "--pickaxe-regex"))
2302 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2303 else if (!prefixcmp(arg, "-B")) {
2304 if ((options->break_opt =
2305 diff_scoreopt_parse(arg)) == -1)
2306 return -1;
2307 }
2308 else if (!prefixcmp(arg, "-M")) {
2309 if ((options->rename_score =
2310 diff_scoreopt_parse(arg)) == -1)
2311 return -1;
2312 options->detect_rename = DIFF_DETECT_RENAME;
2313 }
2314 else if (!prefixcmp(arg, "-C")) {
2315 if (options->detect_rename == DIFF_DETECT_COPY)
2316 options->find_copies_harder = 1;
2317 if ((options->rename_score =
2318 diff_scoreopt_parse(arg)) == -1)
2319 return -1;
2320 options->detect_rename = DIFF_DETECT_COPY;
2321 }
2322 else if (!strcmp(arg, "--find-copies-harder"))
2323 options->find_copies_harder = 1;
2324 else if (!strcmp(arg, "--follow"))
2325 options->follow_renames = 1;
2326 else if (!strcmp(arg, "--abbrev"))
2327 options->abbrev = DEFAULT_ABBREV;
2328 else if (!prefixcmp(arg, "--abbrev=")) {
2329 options->abbrev = strtoul(arg + 9, NULL, 10);
2330 if (options->abbrev < MINIMUM_ABBREV)
2331 options->abbrev = MINIMUM_ABBREV;
2332 else if (40 < options->abbrev)
2333 options->abbrev = 40;
2334 }
2335 else if (!strcmp(arg, "--color"))
2336 options->color_diff = 1;
2337 else if (!strcmp(arg, "--no-color"))
2338 options->color_diff = 0;
2339 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2340 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2341 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2342 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2343 else if (!strcmp(arg, "--ignore-space-at-eol"))
2344 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2345 else if (!strcmp(arg, "--color-words"))
2346 options->color_diff = options->color_diff_words = 1;
2347 else if (!strcmp(arg, "--no-renames"))
2348 options->detect_rename = 0;
2349 else if (!strcmp(arg, "--exit-code"))
2350 options->exit_with_status = 1;
2351 else if (!strcmp(arg, "--quiet"))
2352 options->quiet = 1;
2353 else if (!strcmp(arg, "--ext-diff"))
2354 options->allow_external = 1;
2355 else if (!strcmp(arg, "--no-ext-diff"))
2356 options->allow_external = 0;
2357 else
2358 return 0;
2359 return 1;
2360}
2361
2362static int parse_num(const char **cp_p)
2363{
2364 unsigned long num, scale;
2365 int ch, dot;
2366 const char *cp = *cp_p;
2367
2368 num = 0;
2369 scale = 1;
2370 dot = 0;
2371 for(;;) {
2372 ch = *cp;
2373 if ( !dot && ch == '.' ) {
2374 scale = 1;
2375 dot = 1;
2376 } else if ( ch == '%' ) {
2377 scale = dot ? scale*100 : 100;
2378 cp++; /* % is always at the end */
2379 break;
2380 } else if ( ch >= '0' && ch <= '9' ) {
2381 if ( scale < 100000 ) {
2382 scale *= 10;
2383 num = (num*10) + (ch-'0');
2384 }
2385 } else {
2386 break;
2387 }
2388 cp++;
2389 }
2390 *cp_p = cp;
2391
2392 /* user says num divided by scale and we say internally that
2393 * is MAX_SCORE * num / scale.
2394 */
2395 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2396}
2397
2398static int diff_scoreopt_parse(const char *opt)
2399{
2400 int opt1, opt2, cmd;
2401
2402 if (*opt++ != '-')
2403 return -1;
2404 cmd = *opt++;
2405 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2406 return -1; /* that is not a -M, -C nor -B option */
2407
2408 opt1 = parse_num(&opt);
2409 if (cmd != 'B')
2410 opt2 = 0;
2411 else {
2412 if (*opt == 0)
2413 opt2 = 0;
2414 else if (*opt != '/')
2415 return -1; /* we expect -B80/99 or -B80 */
2416 else {
2417 opt++;
2418 opt2 = parse_num(&opt);
2419 }
2420 }
2421 if (*opt != 0)
2422 return -1;
2423 return opt1 | (opt2 << 16);
2424}
2425
2426struct diff_queue_struct diff_queued_diff;
2427
2428void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2429{
2430 if (queue->alloc <= queue->nr) {
2431 queue->alloc = alloc_nr(queue->alloc);
2432 queue->queue = xrealloc(queue->queue,
2433 sizeof(dp) * queue->alloc);
2434 }
2435 queue->queue[queue->nr++] = dp;
2436}
2437
2438struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2439 struct diff_filespec *one,
2440 struct diff_filespec *two)
2441{
2442 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2443 dp->one = one;
2444 dp->two = two;
2445 if (queue)
2446 diff_q(queue, dp);
2447 return dp;
2448}
2449
2450void diff_free_filepair(struct diff_filepair *p)
2451{
2452 diff_free_filespec_data(p->one);
2453 diff_free_filespec_data(p->two);
2454 free(p->one);
2455 free(p->two);
2456 free(p);
2457}
2458
2459/* This is different from find_unique_abbrev() in that
2460 * it stuffs the result with dots for alignment.
2461 */
2462const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2463{
2464 int abblen;
2465 const char *abbrev;
2466 if (len == 40)
2467 return sha1_to_hex(sha1);
2468
2469 abbrev = find_unique_abbrev(sha1, len);
2470 if (!abbrev)
2471 return sha1_to_hex(sha1);
2472 abblen = strlen(abbrev);
2473 if (abblen < 37) {
2474 static char hex[41];
2475 if (len < abblen && abblen <= len + 2)
2476 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2477 else
2478 sprintf(hex, "%s...", abbrev);
2479 return hex;
2480 }
2481 return sha1_to_hex(sha1);
2482}
2483
2484static void diff_flush_raw(struct diff_filepair *p,
2485 struct diff_options *options)
2486{
2487 int two_paths;
2488 char status[10];
2489 int abbrev = options->abbrev;
2490 const char *path_one, *path_two;
2491 int inter_name_termination = '\t';
2492 int line_termination = options->line_termination;
2493
2494 if (!line_termination)
2495 inter_name_termination = 0;
2496
2497 path_one = p->one->path;
2498 path_two = p->two->path;
2499 if (line_termination) {
2500 path_one = quote_one(path_one);
2501 path_two = quote_one(path_two);
2502 }
2503
2504 if (p->score)
2505 sprintf(status, "%c%03d", p->status, similarity_index(p));
2506 else {
2507 status[0] = p->status;
2508 status[1] = 0;
2509 }
2510 switch (p->status) {
2511 case DIFF_STATUS_COPIED:
2512 case DIFF_STATUS_RENAMED:
2513 two_paths = 1;
2514 break;
2515 case DIFF_STATUS_ADDED:
2516 case DIFF_STATUS_DELETED:
2517 two_paths = 0;
2518 break;
2519 default:
2520 two_paths = 0;
2521 break;
2522 }
2523 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2524 printf(":%06o %06o %s ",
2525 p->one->mode, p->two->mode,
2526 diff_unique_abbrev(p->one->sha1, abbrev));
2527 printf("%s ",
2528 diff_unique_abbrev(p->two->sha1, abbrev));
2529 }
2530 printf("%s%c%s", status, inter_name_termination,
2531 two_paths || p->one->mode ? path_one : path_two);
2532 if (two_paths)
2533 printf("%c%s", inter_name_termination, path_two);
2534 putchar(line_termination);
2535 if (path_one != p->one->path)
2536 free((void*)path_one);
2537 if (path_two != p->two->path)
2538 free((void*)path_two);
2539}
2540
2541static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2542{
2543 char *path = p->two->path;
2544
2545 if (opt->line_termination)
2546 path = quote_one(p->two->path);
2547 printf("%s%c", path, opt->line_termination);
2548 if (p->two->path != path)
2549 free(path);
2550}
2551
2552int diff_unmodified_pair(struct diff_filepair *p)
2553{
2554 /* This function is written stricter than necessary to support
2555 * the currently implemented transformers, but the idea is to
2556 * let transformers to produce diff_filepairs any way they want,
2557 * and filter and clean them up here before producing the output.
2558 */
2559 struct diff_filespec *one, *two;
2560
2561 if (DIFF_PAIR_UNMERGED(p))
2562 return 0; /* unmerged is interesting */
2563
2564 one = p->one;
2565 two = p->two;
2566
2567 /* deletion, addition, mode or type change
2568 * and rename are all interesting.
2569 */
2570 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2571 DIFF_PAIR_MODE_CHANGED(p) ||
2572 strcmp(one->path, two->path))
2573 return 0;
2574
2575 /* both are valid and point at the same path. that is, we are
2576 * dealing with a change.
2577 */
2578 if (one->sha1_valid && two->sha1_valid &&
2579 !hashcmp(one->sha1, two->sha1))
2580 return 1; /* no change */
2581 if (!one->sha1_valid && !two->sha1_valid)
2582 return 1; /* both look at the same file on the filesystem. */
2583 return 0;
2584}
2585
2586static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2587{
2588 if (diff_unmodified_pair(p))
2589 return;
2590
2591 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2592 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2593 return; /* no tree diffs in patch format */
2594
2595 run_diff(p, o);
2596}
2597
2598static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2599 struct diffstat_t *diffstat)
2600{
2601 if (diff_unmodified_pair(p))
2602 return;
2603
2604 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2605 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2606 return; /* no tree diffs in patch format */
2607
2608 run_diffstat(p, o, diffstat);
2609}
2610
2611static void diff_flush_checkdiff(struct diff_filepair *p,
2612 struct diff_options *o)
2613{
2614 if (diff_unmodified_pair(p))
2615 return;
2616
2617 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2618 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2619 return; /* no tree diffs in patch format */
2620
2621 run_checkdiff(p, o);
2622}
2623
2624int diff_queue_is_empty(void)
2625{
2626 struct diff_queue_struct *q = &diff_queued_diff;
2627 int i;
2628 for (i = 0; i < q->nr; i++)
2629 if (!diff_unmodified_pair(q->queue[i]))
2630 return 0;
2631 return 1;
2632}
2633
2634#if DIFF_DEBUG
2635void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2636{
2637 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2638 x, one ? one : "",
2639 s->path,
2640 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2641 s->mode,
2642 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2643 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2644 x, one ? one : "",
2645 s->size, s->xfrm_flags);
2646}
2647
2648void diff_debug_filepair(const struct diff_filepair *p, int i)
2649{
2650 diff_debug_filespec(p->one, i, "one");
2651 diff_debug_filespec(p->two, i, "two");
2652 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2653 p->score, p->status ? p->status : '?',
2654 p->source_stays, p->broken_pair);
2655}
2656
2657void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2658{
2659 int i;
2660 if (msg)
2661 fprintf(stderr, "%s\n", msg);
2662 fprintf(stderr, "q->nr = %d\n", q->nr);
2663 for (i = 0; i < q->nr; i++) {
2664 struct diff_filepair *p = q->queue[i];
2665 diff_debug_filepair(p, i);
2666 }
2667}
2668#endif
2669
2670static void diff_resolve_rename_copy(void)
2671{
2672 int i, j;
2673 struct diff_filepair *p, *pp;
2674 struct diff_queue_struct *q = &diff_queued_diff;
2675
2676 diff_debug_queue("resolve-rename-copy", q);
2677
2678 for (i = 0; i < q->nr; i++) {
2679 p = q->queue[i];
2680 p->status = 0; /* undecided */
2681 if (DIFF_PAIR_UNMERGED(p))
2682 p->status = DIFF_STATUS_UNMERGED;
2683 else if (!DIFF_FILE_VALID(p->one))
2684 p->status = DIFF_STATUS_ADDED;
2685 else if (!DIFF_FILE_VALID(p->two))
2686 p->status = DIFF_STATUS_DELETED;
2687 else if (DIFF_PAIR_TYPE_CHANGED(p))
2688 p->status = DIFF_STATUS_TYPE_CHANGED;
2689
2690 /* from this point on, we are dealing with a pair
2691 * whose both sides are valid and of the same type, i.e.
2692 * either in-place edit or rename/copy edit.
2693 */
2694 else if (DIFF_PAIR_RENAME(p)) {
2695 if (p->source_stays) {
2696 p->status = DIFF_STATUS_COPIED;
2697 continue;
2698 }
2699 /* See if there is some other filepair that
2700 * copies from the same source as us. If so
2701 * we are a copy. Otherwise we are either a
2702 * copy if the path stays, or a rename if it
2703 * does not, but we already handled "stays" case.
2704 */
2705 for (j = i + 1; j < q->nr; j++) {
2706 pp = q->queue[j];
2707 if (strcmp(pp->one->path, p->one->path))
2708 continue; /* not us */
2709 if (!DIFF_PAIR_RENAME(pp))
2710 continue; /* not a rename/copy */
2711 /* pp is a rename/copy from the same source */
2712 p->status = DIFF_STATUS_COPIED;
2713 break;
2714 }
2715 if (!p->status)
2716 p->status = DIFF_STATUS_RENAMED;
2717 }
2718 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2719 p->one->mode != p->two->mode ||
2720 is_null_sha1(p->one->sha1))
2721 p->status = DIFF_STATUS_MODIFIED;
2722 else {
2723 /* This is a "no-change" entry and should not
2724 * happen anymore, but prepare for broken callers.
2725 */
2726 error("feeding unmodified %s to diffcore",
2727 p->one->path);
2728 p->status = DIFF_STATUS_UNKNOWN;
2729 }
2730 }
2731 diff_debug_queue("resolve-rename-copy done", q);
2732}
2733
2734static int check_pair_status(struct diff_filepair *p)
2735{
2736 switch (p->status) {
2737 case DIFF_STATUS_UNKNOWN:
2738 return 0;
2739 case 0:
2740 die("internal error in diff-resolve-rename-copy");
2741 default:
2742 return 1;
2743 }
2744}
2745
2746static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2747{
2748 int fmt = opt->output_format;
2749
2750 if (fmt & DIFF_FORMAT_CHECKDIFF)
2751 diff_flush_checkdiff(p, opt);
2752 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2753 diff_flush_raw(p, opt);
2754 else if (fmt & DIFF_FORMAT_NAME)
2755 diff_flush_name(p, opt);
2756}
2757
2758static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2759{
2760 char *name = quote_one(fs->path);
2761 if (fs->mode)
2762 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2763 else
2764 printf(" %s %s\n", newdelete, name);
2765 free(name);
2766}
2767
2768
2769static void show_mode_change(struct diff_filepair *p, int show_name)
2770{
2771 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2772 if (show_name) {
2773 char *name = quote_one(p->two->path);
2774 printf(" mode change %06o => %06o %s\n",
2775 p->one->mode, p->two->mode, name);
2776 free(name);
2777 }
2778 else
2779 printf(" mode change %06o => %06o\n",
2780 p->one->mode, p->two->mode);
2781 }
2782}
2783
2784static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2785{
2786 char *names = pprint_rename(p->one->path, p->two->path);
2787
2788 printf(" %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2789 free(names);
2790 show_mode_change(p, 0);
2791}
2792
2793static void diff_summary(struct diff_filepair *p)
2794{
2795 switch(p->status) {
2796 case DIFF_STATUS_DELETED:
2797 show_file_mode_name("delete", p->one);
2798 break;
2799 case DIFF_STATUS_ADDED:
2800 show_file_mode_name("create", p->two);
2801 break;
2802 case DIFF_STATUS_COPIED:
2803 show_rename_copy("copy", p);
2804 break;
2805 case DIFF_STATUS_RENAMED:
2806 show_rename_copy("rename", p);
2807 break;
2808 default:
2809 if (p->score) {
2810 char *name = quote_one(p->two->path);
2811 printf(" rewrite %s (%d%%)\n", name,
2812 similarity_index(p));
2813 free(name);
2814 show_mode_change(p, 0);
2815 } else show_mode_change(p, 1);
2816 break;
2817 }
2818}
2819
2820struct patch_id_t {
2821 struct xdiff_emit_state xm;
2822 SHA_CTX *ctx;
2823 int patchlen;
2824};
2825
2826static int remove_space(char *line, int len)
2827{
2828 int i;
2829 char *dst = line;
2830 unsigned char c;
2831
2832 for (i = 0; i < len; i++)
2833 if (!isspace((c = line[i])))
2834 *dst++ = c;
2835
2836 return dst - line;
2837}
2838
2839static void patch_id_consume(void *priv, char *line, unsigned long len)
2840{
2841 struct patch_id_t *data = priv;
2842 int new_len;
2843
2844 /* Ignore line numbers when computing the SHA1 of the patch */
2845 if (!prefixcmp(line, "@@ -"))
2846 return;
2847
2848 new_len = remove_space(line, len);
2849
2850 SHA1_Update(data->ctx, line, new_len);
2851 data->patchlen += new_len;
2852}
2853
2854/* returns 0 upon success, and writes result into sha1 */
2855static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2856{
2857 struct diff_queue_struct *q = &diff_queued_diff;
2858 int i;
2859 SHA_CTX ctx;
2860 struct patch_id_t data;
2861 char buffer[PATH_MAX * 4 + 20];
2862
2863 SHA1_Init(&ctx);
2864 memset(&data, 0, sizeof(struct patch_id_t));
2865 data.ctx = &ctx;
2866 data.xm.consume = patch_id_consume;
2867
2868 for (i = 0; i < q->nr; i++) {
2869 xpparam_t xpp;
2870 xdemitconf_t xecfg;
2871 xdemitcb_t ecb;
2872 mmfile_t mf1, mf2;
2873 struct diff_filepair *p = q->queue[i];
2874 int len1, len2;
2875
2876 memset(&xecfg, 0, sizeof(xecfg));
2877 if (p->status == 0)
2878 return error("internal diff status error");
2879 if (p->status == DIFF_STATUS_UNKNOWN)
2880 continue;
2881 if (diff_unmodified_pair(p))
2882 continue;
2883 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2884 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2885 continue;
2886 if (DIFF_PAIR_UNMERGED(p))
2887 continue;
2888
2889 diff_fill_sha1_info(p->one);
2890 diff_fill_sha1_info(p->two);
2891 if (fill_mmfile(&mf1, p->one) < 0 ||
2892 fill_mmfile(&mf2, p->two) < 0)
2893 return error("unable to read files to diff");
2894
2895 /* Maybe hash p->two? into the patch id? */
2896 if (diff_filespec_is_binary(p->two))
2897 continue;
2898
2899 len1 = remove_space(p->one->path, strlen(p->one->path));
2900 len2 = remove_space(p->two->path, strlen(p->two->path));
2901 if (p->one->mode == 0)
2902 len1 = snprintf(buffer, sizeof(buffer),
2903 "diff--gita/%.*sb/%.*s"
2904 "newfilemode%06o"
2905 "---/dev/null"
2906 "+++b/%.*s",
2907 len1, p->one->path,
2908 len2, p->two->path,
2909 p->two->mode,
2910 len2, p->two->path);
2911 else if (p->two->mode == 0)
2912 len1 = snprintf(buffer, sizeof(buffer),
2913 "diff--gita/%.*sb/%.*s"
2914 "deletedfilemode%06o"
2915 "---a/%.*s"
2916 "+++/dev/null",
2917 len1, p->one->path,
2918 len2, p->two->path,
2919 p->one->mode,
2920 len1, p->one->path);
2921 else
2922 len1 = snprintf(buffer, sizeof(buffer),
2923 "diff--gita/%.*sb/%.*s"
2924 "---a/%.*s"
2925 "+++b/%.*s",
2926 len1, p->one->path,
2927 len2, p->two->path,
2928 len1, p->one->path,
2929 len2, p->two->path);
2930 SHA1_Update(&ctx, buffer, len1);
2931
2932 xpp.flags = XDF_NEED_MINIMAL;
2933 xecfg.ctxlen = 3;
2934 xecfg.flags = XDL_EMIT_FUNCNAMES;
2935 ecb.outf = xdiff_outf;
2936 ecb.priv = &data;
2937 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2938 }
2939
2940 SHA1_Final(sha1, &ctx);
2941 return 0;
2942}
2943
2944int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2945{
2946 struct diff_queue_struct *q = &diff_queued_diff;
2947 int i;
2948 int result = diff_get_patch_id(options, sha1);
2949
2950 for (i = 0; i < q->nr; i++)
2951 diff_free_filepair(q->queue[i]);
2952
2953 free(q->queue);
2954 q->queue = NULL;
2955 q->nr = q->alloc = 0;
2956
2957 return result;
2958}
2959
2960static int is_summary_empty(const struct diff_queue_struct *q)
2961{
2962 int i;
2963
2964 for (i = 0; i < q->nr; i++) {
2965 const struct diff_filepair *p = q->queue[i];
2966
2967 switch (p->status) {
2968 case DIFF_STATUS_DELETED:
2969 case DIFF_STATUS_ADDED:
2970 case DIFF_STATUS_COPIED:
2971 case DIFF_STATUS_RENAMED:
2972 return 0;
2973 default:
2974 if (p->score)
2975 return 0;
2976 if (p->one->mode && p->two->mode &&
2977 p->one->mode != p->two->mode)
2978 return 0;
2979 break;
2980 }
2981 }
2982 return 1;
2983}
2984
2985void diff_flush(struct diff_options *options)
2986{
2987 struct diff_queue_struct *q = &diff_queued_diff;
2988 int i, output_format = options->output_format;
2989 int separator = 0;
2990
2991 /*
2992 * Order: raw, stat, summary, patch
2993 * or: name/name-status/checkdiff (other bits clear)
2994 */
2995 if (!q->nr)
2996 goto free_queue;
2997
2998 if (output_format & (DIFF_FORMAT_RAW |
2999 DIFF_FORMAT_NAME |
3000 DIFF_FORMAT_NAME_STATUS |
3001 DIFF_FORMAT_CHECKDIFF)) {
3002 for (i = 0; i < q->nr; i++) {
3003 struct diff_filepair *p = q->queue[i];
3004 if (check_pair_status(p))
3005 flush_one_pair(p, options);
3006 }
3007 separator++;
3008 }
3009
3010 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3011 struct diffstat_t diffstat;
3012
3013 memset(&diffstat, 0, sizeof(struct diffstat_t));
3014 diffstat.xm.consume = diffstat_consume;
3015 for (i = 0; i < q->nr; i++) {
3016 struct diff_filepair *p = q->queue[i];
3017 if (check_pair_status(p))
3018 diff_flush_stat(p, options, &diffstat);
3019 }
3020 if (output_format & DIFF_FORMAT_NUMSTAT)
3021 show_numstat(&diffstat, options);
3022 if (output_format & DIFF_FORMAT_DIFFSTAT)
3023 show_stats(&diffstat, options);
3024 else if (output_format & DIFF_FORMAT_SHORTSTAT)
3025 show_shortstats(&diffstat);
3026 separator++;
3027 }
3028
3029 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3030 for (i = 0; i < q->nr; i++)
3031 diff_summary(q->queue[i]);
3032 separator++;
3033 }
3034
3035 if (output_format & DIFF_FORMAT_PATCH) {
3036 if (separator) {
3037 if (options->stat_sep) {
3038 /* attach patch instead of inline */
3039 fputs(options->stat_sep, stdout);
3040 } else {
3041 putchar(options->line_termination);
3042 }
3043 }
3044
3045 for (i = 0; i < q->nr; i++) {
3046 struct diff_filepair *p = q->queue[i];
3047 if (check_pair_status(p))
3048 diff_flush_patch(p, options);
3049 }
3050 }
3051
3052 if (output_format & DIFF_FORMAT_CALLBACK)
3053 options->format_callback(q, options, options->format_callback_data);
3054
3055 for (i = 0; i < q->nr; i++)
3056 diff_free_filepair(q->queue[i]);
3057free_queue:
3058 free(q->queue);
3059 q->queue = NULL;
3060 q->nr = q->alloc = 0;
3061}
3062
3063static void diffcore_apply_filter(const char *filter)
3064{
3065 int i;
3066 struct diff_queue_struct *q = &diff_queued_diff;
3067 struct diff_queue_struct outq;
3068 outq.queue = NULL;
3069 outq.nr = outq.alloc = 0;
3070
3071 if (!filter)
3072 return;
3073
3074 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3075 int found;
3076 for (i = found = 0; !found && i < q->nr; i++) {
3077 struct diff_filepair *p = q->queue[i];
3078 if (((p->status == DIFF_STATUS_MODIFIED) &&
3079 ((p->score &&
3080 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3081 (!p->score &&
3082 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3083 ((p->status != DIFF_STATUS_MODIFIED) &&
3084 strchr(filter, p->status)))
3085 found++;
3086 }
3087 if (found)
3088 return;
3089
3090 /* otherwise we will clear the whole queue
3091 * by copying the empty outq at the end of this
3092 * function, but first clear the current entries
3093 * in the queue.
3094 */
3095 for (i = 0; i < q->nr; i++)
3096 diff_free_filepair(q->queue[i]);
3097 }
3098 else {
3099 /* Only the matching ones */
3100 for (i = 0; i < q->nr; i++) {
3101 struct diff_filepair *p = q->queue[i];
3102
3103 if (((p->status == DIFF_STATUS_MODIFIED) &&
3104 ((p->score &&
3105 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3106 (!p->score &&
3107 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3108 ((p->status != DIFF_STATUS_MODIFIED) &&
3109 strchr(filter, p->status)))
3110 diff_q(&outq, p);
3111 else
3112 diff_free_filepair(p);
3113 }
3114 }
3115 free(q->queue);
3116 *q = outq;
3117}
3118
3119void diffcore_std(struct diff_options *options)
3120{
3121 if (options->quiet)
3122 return;
3123
3124 if (options->break_opt != -1)
3125 diffcore_break(options->break_opt);
3126 if (options->detect_rename)
3127 diffcore_rename(options);
3128 if (options->break_opt != -1)
3129 diffcore_merge_broken();
3130 if (options->pickaxe)
3131 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3132 if (options->orderfile)
3133 diffcore_order(options->orderfile);
3134 diff_resolve_rename_copy();
3135 diffcore_apply_filter(options->filter);
3136
3137 options->has_changes = !!diff_queued_diff.nr;
3138}
3139
3140
3141void diff_addremove(struct diff_options *options,
3142 int addremove, unsigned mode,
3143 const unsigned char *sha1,
3144 const char *base, const char *path)
3145{
3146 char concatpath[PATH_MAX];
3147 struct diff_filespec *one, *two;
3148
3149 /* This may look odd, but it is a preparation for
3150 * feeding "there are unchanged files which should
3151 * not produce diffs, but when you are doing copy
3152 * detection you would need them, so here they are"
3153 * entries to the diff-core. They will be prefixed
3154 * with something like '=' or '*' (I haven't decided
3155 * which but should not make any difference).
3156 * Feeding the same new and old to diff_change()
3157 * also has the same effect.
3158 * Before the final output happens, they are pruned after
3159 * merged into rename/copy pairs as appropriate.
3160 */
3161 if (options->reverse_diff)
3162 addremove = (addremove == '+' ? '-' :
3163 addremove == '-' ? '+' : addremove);
3164
3165 if (!path) path = "";
3166 sprintf(concatpath, "%s%s", base, path);
3167 one = alloc_filespec(concatpath);
3168 two = alloc_filespec(concatpath);
3169
3170 if (addremove != '+')
3171 fill_filespec(one, sha1, mode);
3172 if (addremove != '-')
3173 fill_filespec(two, sha1, mode);
3174
3175 diff_queue(&diff_queued_diff, one, two);
3176 options->has_changes = 1;
3177}
3178
3179void diff_change(struct diff_options *options,
3180 unsigned old_mode, unsigned new_mode,
3181 const unsigned char *old_sha1,
3182 const unsigned char *new_sha1,
3183 const char *base, const char *path)
3184{
3185 char concatpath[PATH_MAX];
3186 struct diff_filespec *one, *two;
3187
3188 if (options->reverse_diff) {
3189 unsigned tmp;
3190 const unsigned char *tmp_c;
3191 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3192 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3193 }
3194 if (!path) path = "";
3195 sprintf(concatpath, "%s%s", base, path);
3196 one = alloc_filespec(concatpath);
3197 two = alloc_filespec(concatpath);
3198 fill_filespec(one, old_sha1, old_mode);
3199 fill_filespec(two, new_sha1, new_mode);
3200
3201 diff_queue(&diff_queued_diff, one, two);
3202 options->has_changes = 1;
3203}
3204
3205void diff_unmerge(struct diff_options *options,
3206 const char *path,
3207 unsigned mode, const unsigned char *sha1)
3208{
3209 struct diff_filespec *one, *two;
3210 one = alloc_filespec(path);
3211 two = alloc_filespec(path);
3212 fill_filespec(one, sha1, mode);
3213 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3214}