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