Code

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