Code

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