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