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