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