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