Code

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