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