Code

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