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