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