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