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