Code

Merge branch 'fk/autoconf'
[git.git] / diff.c
1 /*
2  * Copyright (C) 2005 Junio C Hamano
3  */
4 #include "cache.h"
5 #include "quote.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "delta.h"
9 #include "xdiff-interface.h"
10 #include "color.h"
12 #ifdef NO_FAST_WORKING_DIRECTORY
13 #define FAST_WORKING_DIRECTORY 0
14 #else
15 #define FAST_WORKING_DIRECTORY 1
16 #endif
18 static int use_size_cache;
20 static int diff_detect_rename_default;
21 static int diff_rename_limit_default = -1;
22 static int diff_use_color_default;
24 static char diff_colors[][COLOR_MAXLEN] = {
25         "\033[m",       /* reset */
26         "",             /* PLAIN (normal) */
27         "\033[1m",      /* METAINFO (bold) */
28         "\033[36m",     /* FRAGINFO (cyan) */
29         "\033[31m",     /* OLD (red) */
30         "\033[32m",     /* NEW (green) */
31         "\033[33m",     /* COMMIT (yellow) */
32         "\033[41m",     /* WHITESPACE (red background) */
33 };
35 static int parse_diff_color_slot(const char *var, int ofs)
36 {
37         if (!strcasecmp(var+ofs, "plain"))
38                 return DIFF_PLAIN;
39         if (!strcasecmp(var+ofs, "meta"))
40                 return DIFF_METAINFO;
41         if (!strcasecmp(var+ofs, "frag"))
42                 return DIFF_FRAGINFO;
43         if (!strcasecmp(var+ofs, "old"))
44                 return DIFF_FILE_OLD;
45         if (!strcasecmp(var+ofs, "new"))
46                 return DIFF_FILE_NEW;
47         if (!strcasecmp(var+ofs, "commit"))
48                 return DIFF_COMMIT;
49         if (!strcasecmp(var+ofs, "whitespace"))
50                 return DIFF_WHITESPACE;
51         die("bad config variable '%s'", var);
52 }
54 /*
55  * These are to give UI layer defaults.
56  * The core-level commands such as git-diff-files should
57  * never be affected by the setting of diff.renames
58  * the user happens to have in the configuration file.
59  */
60 int git_diff_ui_config(const char *var, const char *value)
61 {
62         if (!strcmp(var, "diff.renamelimit")) {
63                 diff_rename_limit_default = git_config_int(var, value);
64                 return 0;
65         }
66         if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
67                 diff_use_color_default = git_config_colorbool(var, value);
68                 return 0;
69         }
70         if (!strcmp(var, "diff.renames")) {
71                 if (!value)
72                         diff_detect_rename_default = DIFF_DETECT_RENAME;
73                 else if (!strcasecmp(value, "copies") ||
74                          !strcasecmp(value, "copy"))
75                         diff_detect_rename_default = DIFF_DETECT_COPY;
76                 else if (git_config_bool(var,value))
77                         diff_detect_rename_default = DIFF_DETECT_RENAME;
78                 return 0;
79         }
80         if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
81                 int slot = parse_diff_color_slot(var, 11);
82                 color_parse(value, var, diff_colors[slot]);
83                 return 0;
84         }
85         return git_default_config(var, value);
86 }
88 static char *quote_one(const char *str)
89 {
90         int needlen;
91         char *xp;
93         if (!str)
94                 return NULL;
95         needlen = quote_c_style(str, NULL, NULL, 0);
96         if (!needlen)
97                 return xstrdup(str);
98         xp = xmalloc(needlen + 1);
99         quote_c_style(str, xp, NULL, 0);
100         return xp;
103 static char *quote_two(const char *one, const char *two)
105         int need_one = quote_c_style(one, NULL, NULL, 1);
106         int need_two = quote_c_style(two, NULL, NULL, 1);
107         char *xp;
109         if (need_one + need_two) {
110                 if (!need_one) need_one = strlen(one);
111                 if (!need_two) need_one = strlen(two);
113                 xp = xmalloc(need_one + need_two + 3);
114                 xp[0] = '"';
115                 quote_c_style(one, xp + 1, NULL, 1);
116                 quote_c_style(two, xp + need_one + 1, NULL, 1);
117                 strcpy(xp + need_one + need_two + 1, "\"");
118                 return xp;
119         }
120         need_one = strlen(one);
121         need_two = strlen(two);
122         xp = xmalloc(need_one + need_two + 1);
123         strcpy(xp, one);
124         strcpy(xp + need_one, two);
125         return xp;
128 static const char *external_diff(void)
130         static const char *external_diff_cmd = NULL;
131         static int done_preparing = 0;
133         if (done_preparing)
134                 return external_diff_cmd;
135         external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
136         done_preparing = 1;
137         return external_diff_cmd;
140 #define TEMPFILE_PATH_LEN               50
142 static struct diff_tempfile {
143         const char *name; /* filename external diff should read from */
144         char hex[41];
145         char mode[10];
146         char tmp_path[TEMPFILE_PATH_LEN];
147 } diff_temp[2];
149 static int count_lines(const char *data, int size)
151         int count, ch, completely_empty = 1, nl_just_seen = 0;
152         count = 0;
153         while (0 < size--) {
154                 ch = *data++;
155                 if (ch == '\n') {
156                         count++;
157                         nl_just_seen = 1;
158                         completely_empty = 0;
159                 }
160                 else {
161                         nl_just_seen = 0;
162                         completely_empty = 0;
163                 }
164         }
165         if (completely_empty)
166                 return 0;
167         if (!nl_just_seen)
168                 count++; /* no trailing newline */
169         return count;
172 static void print_line_count(int count)
174         switch (count) {
175         case 0:
176                 printf("0,0");
177                 break;
178         case 1:
179                 printf("1");
180                 break;
181         default:
182                 printf("1,%d", count);
183                 break;
184         }
187 static void copy_file(int prefix, const char *data, int size)
189         int ch, nl_just_seen = 1;
190         while (0 < size--) {
191                 ch = *data++;
192                 if (nl_just_seen)
193                         putchar(prefix);
194                 putchar(ch);
195                 if (ch == '\n')
196                         nl_just_seen = 1;
197                 else
198                         nl_just_seen = 0;
199         }
200         if (!nl_just_seen)
201                 printf("\n\\ No newline at end of file\n");
204 static void emit_rewrite_diff(const char *name_a,
205                               const char *name_b,
206                               struct diff_filespec *one,
207                               struct diff_filespec *two)
209         int lc_a, lc_b;
210         const char *name_a_tab, *name_b_tab;
212         name_a_tab = strchr(name_a, ' ') ? "\t" : "";
213         name_b_tab = strchr(name_b, ' ') ? "\t" : "";
215         diff_populate_filespec(one, 0);
216         diff_populate_filespec(two, 0);
217         lc_a = count_lines(one->data, one->size);
218         lc_b = count_lines(two->data, two->size);
219         printf("--- a/%s%s\n+++ b/%s%s\n@@ -",
220                name_a, name_a_tab,
221                name_b, name_b_tab);
222         print_line_count(lc_a);
223         printf(" +");
224         print_line_count(lc_b);
225         printf(" @@\n");
226         if (lc_a)
227                 copy_file('-', one->data, one->size);
228         if (lc_b)
229                 copy_file('+', two->data, two->size);
232 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
234         if (!DIFF_FILE_VALID(one)) {
235                 mf->ptr = (char *)""; /* does not matter */
236                 mf->size = 0;
237                 return 0;
238         }
239         else if (diff_populate_filespec(one, 0))
240                 return -1;
241         mf->ptr = one->data;
242         mf->size = one->size;
243         return 0;
246 struct diff_words_buffer {
247         mmfile_t text;
248         long alloc;
249         long current; /* output pointer */
250         int suppressed_newline;
251 };
253 static void diff_words_append(char *line, unsigned long len,
254                 struct diff_words_buffer *buffer)
256         if (buffer->text.size + len > buffer->alloc) {
257                 buffer->alloc = (buffer->text.size + len) * 3 / 2;
258                 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
259         }
260         line++;
261         len--;
262         memcpy(buffer->text.ptr + buffer->text.size, line, len);
263         buffer->text.size += len;
266 struct diff_words_data {
267         struct xdiff_emit_state xm;
268         struct diff_words_buffer minus, plus;
269 };
271 static void print_word(struct diff_words_buffer *buffer, int len, int color,
272                 int suppress_newline)
274         const char *ptr;
275         int eol = 0;
277         if (len == 0)
278                 return;
280         ptr  = buffer->text.ptr + buffer->current;
281         buffer->current += len;
283         if (ptr[len - 1] == '\n') {
284                 eol = 1;
285                 len--;
286         }
288         fputs(diff_get_color(1, color), stdout);
289         fwrite(ptr, len, 1, stdout);
290         fputs(diff_get_color(1, DIFF_RESET), stdout);
292         if (eol) {
293                 if (suppress_newline)
294                         buffer->suppressed_newline = 1;
295                 else
296                         putchar('\n');
297         }
300 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
302         struct diff_words_data *diff_words = priv;
304         if (diff_words->minus.suppressed_newline) {
305                 if (line[0] != '+')
306                         putchar('\n');
307                 diff_words->minus.suppressed_newline = 0;
308         }
310         len--;
311         switch (line[0]) {
312                 case '-':
313                         print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
314                         break;
315                 case '+':
316                         print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
317                         break;
318                 case ' ':
319                         print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
320                         diff_words->minus.current += len;
321                         break;
322         }
325 /* this executes the word diff on the accumulated buffers */
326 static void diff_words_show(struct diff_words_data *diff_words)
328         xpparam_t xpp;
329         xdemitconf_t xecfg;
330         xdemitcb_t ecb;
331         mmfile_t minus, plus;
332         int i;
334         minus.size = diff_words->minus.text.size;
335         minus.ptr = xmalloc(minus.size);
336         memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
337         for (i = 0; i < minus.size; i++)
338                 if (isspace(minus.ptr[i]))
339                         minus.ptr[i] = '\n';
340         diff_words->minus.current = 0;
342         plus.size = diff_words->plus.text.size;
343         plus.ptr = xmalloc(plus.size);
344         memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
345         for (i = 0; i < plus.size; i++)
346                 if (isspace(plus.ptr[i]))
347                         plus.ptr[i] = '\n';
348         diff_words->plus.current = 0;
350         xpp.flags = XDF_NEED_MINIMAL;
351         xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
352         xecfg.flags = 0;
353         ecb.outf = xdiff_outf;
354         ecb.priv = diff_words;
355         diff_words->xm.consume = fn_out_diff_words_aux;
356         xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
358         free(minus.ptr);
359         free(plus.ptr);
360         diff_words->minus.text.size = diff_words->plus.text.size = 0;
362         if (diff_words->minus.suppressed_newline) {
363                 putchar('\n');
364                 diff_words->minus.suppressed_newline = 0;
365         }
368 struct emit_callback {
369         struct xdiff_emit_state xm;
370         int nparents, color_diff;
371         const char **label_path;
372         struct diff_words_data *diff_words;
373 };
375 static void free_diff_words_data(struct emit_callback *ecbdata)
377         if (ecbdata->diff_words) {
378                 /* flush buffers */
379                 if (ecbdata->diff_words->minus.text.size ||
380                                 ecbdata->diff_words->plus.text.size)
381                         diff_words_show(ecbdata->diff_words);
383                 if (ecbdata->diff_words->minus.text.ptr)
384                         free (ecbdata->diff_words->minus.text.ptr);
385                 if (ecbdata->diff_words->plus.text.ptr)
386                         free (ecbdata->diff_words->plus.text.ptr);
387                 free(ecbdata->diff_words);
388                 ecbdata->diff_words = NULL;
389         }
392 const char *diff_get_color(int diff_use_color, enum color_diff ix)
394         if (diff_use_color)
395                 return diff_colors[ix];
396         return "";
399 static void emit_line(const char *set, const char *reset, const char *line, int len)
401         if (len > 0 && line[len-1] == '\n')
402                 len--;
403         fputs(set, stdout);
404         fwrite(line, len, 1, stdout);
405         puts(reset);
408 static void emit_line_with_ws(int nparents,
409                 const char *set, const char *reset, const char *ws,
410                 const char *line, int len)
412         int col0 = nparents;
413         int last_tab_in_indent = -1;
414         int last_space_in_indent = -1;
415         int i;
416         int tail = len;
417         int need_highlight_leading_space = 0;
418         /* The line is a newly added line.  Does it have funny leading
419          * whitespaces?  In indent, SP should never precede a TAB.
420          */
421         for (i = col0; i < len; i++) {
422                 if (line[i] == '\t') {
423                         last_tab_in_indent = i;
424                         if (0 <= last_space_in_indent)
425                                 need_highlight_leading_space = 1;
426                 }
427                 else if (line[i] == ' ')
428                         last_space_in_indent = i;
429                 else
430                         break;
431         }
432         fputs(set, stdout);
433         fwrite(line, col0, 1, stdout);
434         fputs(reset, stdout);
435         if (((i == len) || line[i] == '\n') && i != col0) {
436                 /* The whole line was indent */
437                 emit_line(ws, reset, line + col0, len - col0);
438                 return;
439         }
440         i = col0;
441         if (need_highlight_leading_space) {
442                 while (i < last_tab_in_indent) {
443                         if (line[i] == ' ') {
444                                 fputs(ws, stdout);
445                                 putchar(' ');
446                                 fputs(reset, stdout);
447                         }
448                         else
449                                 putchar(line[i]);
450                         i++;
451                 }
452         }
453         tail = len - 1;
454         if (line[tail] == '\n' && i < tail)
455                 tail--;
456         while (i < tail) {
457                 if (!isspace(line[tail]))
458                         break;
459                 tail--;
460         }
461         if ((i < tail && line[tail + 1] != '\n')) {
462                 /* This has whitespace between tail+1..len */
463                 fputs(set, stdout);
464                 fwrite(line + i, tail - i + 1, 1, stdout);
465                 fputs(reset, stdout);
466                 emit_line(ws, reset, line + tail + 1, len - tail - 1);
467         }
468         else
469                 emit_line(set, reset, line + i, len - i);
472 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
474         const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
475         const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
477         if (!*ws)
478                 emit_line(set, reset, line, len);
479         else
480                 emit_line_with_ws(ecbdata->nparents, set, reset, ws,
481                                 line, len);
484 static void fn_out_consume(void *priv, char *line, unsigned long len)
486         int i;
487         int color;
488         struct emit_callback *ecbdata = priv;
489         const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
490         const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
492         if (ecbdata->label_path[0]) {
493                 const char *name_a_tab, *name_b_tab;
495                 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
496                 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
498                 printf("%s--- %s%s%s\n",
499                        set, ecbdata->label_path[0], reset, name_a_tab);
500                 printf("%s+++ %s%s%s\n",
501                        set, ecbdata->label_path[1], reset, name_b_tab);
502                 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
503         }
505         /* This is not really necessary for now because
506          * this codepath only deals with two-way diffs.
507          */
508         for (i = 0; i < len && line[i] == '@'; i++)
509                 ;
510         if (2 <= i && i < len && line[i] == ' ') {
511                 ecbdata->nparents = i - 1;
512                 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
513                           reset, line, len);
514                 return;
515         }
517         if (len < ecbdata->nparents) {
518                 set = reset;
519                 emit_line(reset, reset, line, len);
520                 return;
521         }
523         color = DIFF_PLAIN;
524         if (ecbdata->diff_words && ecbdata->nparents != 1)
525                 /* fall back to normal diff */
526                 free_diff_words_data(ecbdata);
527         if (ecbdata->diff_words) {
528                 if (line[0] == '-') {
529                         diff_words_append(line, len,
530                                           &ecbdata->diff_words->minus);
531                         return;
532                 } else if (line[0] == '+') {
533                         diff_words_append(line, len,
534                                           &ecbdata->diff_words->plus);
535                         return;
536                 }
537                 if (ecbdata->diff_words->minus.text.size ||
538                     ecbdata->diff_words->plus.text.size)
539                         diff_words_show(ecbdata->diff_words);
540                 line++;
541                 len--;
542                 emit_line(set, reset, line, len);
543                 return;
544         }
545         for (i = 0; i < ecbdata->nparents && len; i++) {
546                 if (line[i] == '-')
547                         color = DIFF_FILE_OLD;
548                 else if (line[i] == '+')
549                         color = DIFF_FILE_NEW;
550         }
552         if (color != DIFF_FILE_NEW) {
553                 emit_line(diff_get_color(ecbdata->color_diff, color),
554                           reset, line, len);
555                 return;
556         }
557         emit_add_line(reset, ecbdata, line, len);
560 static char *pprint_rename(const char *a, const char *b)
562         const char *old = a;
563         const char *new = b;
564         char *name = NULL;
565         int pfx_length, sfx_length;
566         int len_a = strlen(a);
567         int len_b = strlen(b);
568         int qlen_a = quote_c_style(a, NULL, NULL, 0);
569         int qlen_b = quote_c_style(b, NULL, NULL, 0);
571         if (qlen_a || qlen_b) {
572                 if (qlen_a) len_a = qlen_a;
573                 if (qlen_b) len_b = qlen_b;
574                 name = xmalloc( len_a + len_b + 5 );
575                 if (qlen_a)
576                         quote_c_style(a, name, NULL, 0);
577                 else
578                         memcpy(name, a, len_a);
579                 memcpy(name + len_a, " => ", 4);
580                 if (qlen_b)
581                         quote_c_style(b, name + len_a + 4, NULL, 0);
582                 else
583                         memcpy(name + len_a + 4, b, len_b + 1);
584                 return name;
585         }
587         /* Find common prefix */
588         pfx_length = 0;
589         while (*old && *new && *old == *new) {
590                 if (*old == '/')
591                         pfx_length = old - a + 1;
592                 old++;
593                 new++;
594         }
596         /* Find common suffix */
597         old = a + len_a;
598         new = b + len_b;
599         sfx_length = 0;
600         while (a <= old && b <= new && *old == *new) {
601                 if (*old == '/')
602                         sfx_length = len_a - (old - a);
603                 old--;
604                 new--;
605         }
607         /*
608          * pfx{mid-a => mid-b}sfx
609          * {pfx-a => pfx-b}sfx
610          * pfx{sfx-a => sfx-b}
611          * name-a => name-b
612          */
613         if (pfx_length + sfx_length) {
614                 int a_midlen = len_a - pfx_length - sfx_length;
615                 int b_midlen = len_b - pfx_length - sfx_length;
616                 if (a_midlen < 0) a_midlen = 0;
617                 if (b_midlen < 0) b_midlen = 0;
619                 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
620                 sprintf(name, "%.*s{%.*s => %.*s}%s",
621                         pfx_length, a,
622                         a_midlen, a + pfx_length,
623                         b_midlen, b + pfx_length,
624                         a + len_a - sfx_length);
625         }
626         else {
627                 name = xmalloc(len_a + len_b + 5);
628                 sprintf(name, "%s => %s", a, b);
629         }
630         return name;
633 struct diffstat_t {
634         struct xdiff_emit_state xm;
636         int nr;
637         int alloc;
638         struct diffstat_file {
639                 char *name;
640                 unsigned is_unmerged:1;
641                 unsigned is_binary:1;
642                 unsigned is_renamed:1;
643                 unsigned int added, deleted;
644         } **files;
645 };
647 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
648                                           const char *name_a,
649                                           const char *name_b)
651         struct diffstat_file *x;
652         x = xcalloc(sizeof (*x), 1);
653         if (diffstat->nr == diffstat->alloc) {
654                 diffstat->alloc = alloc_nr(diffstat->alloc);
655                 diffstat->files = xrealloc(diffstat->files,
656                                 diffstat->alloc * sizeof(x));
657         }
658         diffstat->files[diffstat->nr++] = x;
659         if (name_b) {
660                 x->name = pprint_rename(name_a, name_b);
661                 x->is_renamed = 1;
662         }
663         else
664                 x->name = xstrdup(name_a);
665         return x;
668 static void diffstat_consume(void *priv, char *line, unsigned long len)
670         struct diffstat_t *diffstat = priv;
671         struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
673         if (line[0] == '+')
674                 x->added++;
675         else if (line[0] == '-')
676                 x->deleted++;
679 const char mime_boundary_leader[] = "------------";
681 static int scale_linear(int it, int width, int max_change)
683         /*
684          * make sure that at least one '-' is printed if there were deletions,
685          * and likewise for '+'.
686          */
687         if (max_change < 2)
688                 return it;
689         return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
692 static void show_name(const char *prefix, const char *name, int len,
693                       const char *reset, const char *set)
695         printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
698 static void show_graph(char ch, int cnt, const char *set, const char *reset)
700         if (cnt <= 0)
701                 return;
702         printf("%s", set);
703         while (cnt--)
704                 putchar(ch);
705         printf("%s", reset);
708 static void show_stats(struct diffstat_t* data, struct diff_options *options)
710         int i, len, add, del, total, adds = 0, dels = 0;
711         int max_change = 0, max_len = 0;
712         int total_files = data->nr;
713         int width, name_width;
714         const char *reset, *set, *add_c, *del_c;
716         if (data->nr == 0)
717                 return;
719         width = options->stat_width ? options->stat_width : 80;
720         name_width = options->stat_name_width ? options->stat_name_width : 50;
722         /* Sanity: give at least 5 columns to the graph,
723          * but leave at least 10 columns for the name.
724          */
725         if (width < name_width + 15) {
726                 if (name_width <= 25)
727                         width = name_width + 15;
728                 else
729                         name_width = width - 15;
730         }
732         /* Find the longest filename and max number of changes */
733         reset = diff_get_color(options->color_diff, DIFF_RESET);
734         set = diff_get_color(options->color_diff, DIFF_PLAIN);
735         add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
736         del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
738         for (i = 0; i < data->nr; i++) {
739                 struct diffstat_file *file = data->files[i];
740                 int change = file->added + file->deleted;
742                 if (!file->is_renamed) {  /* renames are already quoted by pprint_rename */
743                         len = quote_c_style(file->name, NULL, NULL, 0);
744                         if (len) {
745                                 char *qname = xmalloc(len + 1);
746                                 quote_c_style(file->name, qname, NULL, 0);
747                                 free(file->name);
748                                 file->name = qname;
749                         }
750                 }
752                 len = strlen(file->name);
753                 if (max_len < len)
754                         max_len = len;
756                 if (file->is_binary || file->is_unmerged)
757                         continue;
758                 if (max_change < change)
759                         max_change = change;
760         }
762         /* Compute the width of the graph part;
763          * 10 is for one blank at the beginning of the line plus
764          * " | count " between the name and the graph.
765          *
766          * From here on, name_width is the width of the name area,
767          * and width is the width of the graph area.
768          */
769         name_width = (name_width < max_len) ? name_width : max_len;
770         if (width < (name_width + 10) + max_change)
771                 width = width - (name_width + 10);
772         else
773                 width = max_change;
775         for (i = 0; i < data->nr; i++) {
776                 const char *prefix = "";
777                 char *name = data->files[i]->name;
778                 int added = data->files[i]->added;
779                 int deleted = data->files[i]->deleted;
780                 int name_len;
782                 /*
783                  * "scale" the filename
784                  */
785                 len = name_width;
786                 name_len = strlen(name);
787                 if (name_width < name_len) {
788                         char *slash;
789                         prefix = "...";
790                         len -= 3;
791                         name += name_len - len;
792                         slash = strchr(name, '/');
793                         if (slash)
794                                 name = slash;
795                 }
797                 if (data->files[i]->is_binary) {
798                         show_name(prefix, name, len, reset, set);
799                         printf("  Bin\n");
800                         goto free_diffstat_file;
801                 }
802                 else if (data->files[i]->is_unmerged) {
803                         show_name(prefix, name, len, reset, set);
804                         printf("  Unmerged\n");
805                         goto free_diffstat_file;
806                 }
807                 else if (!data->files[i]->is_renamed &&
808                          (added + deleted == 0)) {
809                         total_files--;
810                         goto free_diffstat_file;
811                 }
813                 /*
814                  * scale the add/delete
815                  */
816                 add = added;
817                 del = deleted;
818                 total = add + del;
819                 adds += add;
820                 dels += del;
822                 if (width <= max_change) {
823                         add = scale_linear(add, width, max_change);
824                         del = scale_linear(del, width, max_change);
825                         total = add + del;
826                 }
827                 show_name(prefix, name, len, reset, set);
828                 printf("%5d ", added + deleted);
829                 show_graph('+', add, add_c, reset);
830                 show_graph('-', del, del_c, reset);
831                 putchar('\n');
832         free_diffstat_file:
833                 free(data->files[i]->name);
834                 free(data->files[i]);
835         }
836         free(data->files);
837         printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
838                set, total_files, adds, dels, reset);
841 static void show_shortstats(struct diffstat_t* data)
843         int i, adds = 0, dels = 0, total_files = data->nr;
845         if (data->nr == 0)
846                 return;
848         for (i = 0; i < data->nr; i++) {
849                 if (!data->files[i]->is_binary &&
850                     !data->files[i]->is_unmerged) {
851                         int added = data->files[i]->added;
852                         int deleted= data->files[i]->deleted;
853                         if (!data->files[i]->is_renamed &&
854                             (added + deleted == 0)) {
855                                 total_files--;
856                         } else {
857                                 adds += added;
858                                 dels += deleted;
859                         }
860                 }
861                 free(data->files[i]->name);
862                 free(data->files[i]);
863         }
864         free(data->files);
866         printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
867                total_files, adds, dels);
870 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
872         int i;
874         for (i = 0; i < data->nr; i++) {
875                 struct diffstat_file *file = data->files[i];
877                 if (file->is_binary)
878                         printf("-\t-\t");
879                 else
880                         printf("%d\t%d\t", file->added, file->deleted);
881                 if (options->line_termination && !file->is_renamed &&
882                     quote_c_style(file->name, NULL, NULL, 0))
883                         quote_c_style(file->name, NULL, stdout, 0);
884                 else
885                         fputs(file->name, stdout);
886                 putchar(options->line_termination);
887         }
890 struct checkdiff_t {
891         struct xdiff_emit_state xm;
892         const char *filename;
893         int lineno, color_diff;
894 };
896 static void checkdiff_consume(void *priv, char *line, unsigned long len)
898         struct checkdiff_t *data = priv;
899         const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
900         const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
901         const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
903         if (line[0] == '+') {
904                 int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
906                 /* check space before tab */
907                 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
908                         if (line[i] == ' ')
909                                 spaces++;
910                 if (line[i - 1] == '\t' && spaces)
911                         space_before_tab = 1;
913                 /* check white space at line end */
914                 if (line[len - 1] == '\n')
915                         len--;
916                 if (isspace(line[len - 1]))
917                         white_space_at_end = 1;
919                 if (space_before_tab || white_space_at_end) {
920                         printf("%s:%d: %s", data->filename, data->lineno, ws);
921                         if (space_before_tab) {
922                                 printf("space before tab");
923                                 if (white_space_at_end)
924                                         putchar(',');
925                         }
926                         if (white_space_at_end)
927                                 printf("white space at end");
928                         printf(":%s ", reset);
929                         emit_line_with_ws(1, set, reset, ws, line, len);
930                 }
932                 data->lineno++;
933         } else if (line[0] == ' ')
934                 data->lineno++;
935         else if (line[0] == '@') {
936                 char *plus = strchr(line, '+');
937                 if (plus)
938                         data->lineno = strtol(plus, NULL, 10);
939                 else
940                         die("invalid diff");
941         }
944 static unsigned char *deflate_it(char *data,
945                                  unsigned long size,
946                                  unsigned long *result_size)
948         int bound;
949         unsigned char *deflated;
950         z_stream stream;
952         memset(&stream, 0, sizeof(stream));
953         deflateInit(&stream, zlib_compression_level);
954         bound = deflateBound(&stream, size);
955         deflated = xmalloc(bound);
956         stream.next_out = deflated;
957         stream.avail_out = bound;
959         stream.next_in = (unsigned char *)data;
960         stream.avail_in = size;
961         while (deflate(&stream, Z_FINISH) == Z_OK)
962                 ; /* nothing */
963         deflateEnd(&stream);
964         *result_size = stream.total_out;
965         return deflated;
968 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
970         void *cp;
971         void *delta;
972         void *deflated;
973         void *data;
974         unsigned long orig_size;
975         unsigned long delta_size;
976         unsigned long deflate_size;
977         unsigned long data_size;
979         /* We could do deflated delta, or we could do just deflated two,
980          * whichever is smaller.
981          */
982         delta = NULL;
983         deflated = deflate_it(two->ptr, two->size, &deflate_size);
984         if (one->size && two->size) {
985                 delta = diff_delta(one->ptr, one->size,
986                                    two->ptr, two->size,
987                                    &delta_size, deflate_size);
988                 if (delta) {
989                         void *to_free = delta;
990                         orig_size = delta_size;
991                         delta = deflate_it(delta, delta_size, &delta_size);
992                         free(to_free);
993                 }
994         }
996         if (delta && delta_size < deflate_size) {
997                 printf("delta %lu\n", orig_size);
998                 free(deflated);
999                 data = delta;
1000                 data_size = delta_size;
1001         }
1002         else {
1003                 printf("literal %lu\n", two->size);
1004                 free(delta);
1005                 data = deflated;
1006                 data_size = deflate_size;
1007         }
1009         /* emit data encoded in base85 */
1010         cp = data;
1011         while (data_size) {
1012                 int bytes = (52 < data_size) ? 52 : data_size;
1013                 char line[70];
1014                 data_size -= bytes;
1015                 if (bytes <= 26)
1016                         line[0] = bytes + 'A' - 1;
1017                 else
1018                         line[0] = bytes - 26 + 'a' - 1;
1019                 encode_85(line + 1, cp, bytes);
1020                 cp = (char *) cp + bytes;
1021                 puts(line);
1022         }
1023         printf("\n");
1024         free(data);
1027 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1029         printf("GIT binary patch\n");
1030         emit_binary_diff_body(one, two);
1031         emit_binary_diff_body(two, one);
1034 #define FIRST_FEW_BYTES 8000
1035 static int mmfile_is_binary(mmfile_t *mf)
1037         long sz = mf->size;
1038         if (FIRST_FEW_BYTES < sz)
1039                 sz = FIRST_FEW_BYTES;
1040         return !!memchr(mf->ptr, 0, sz);
1043 static void builtin_diff(const char *name_a,
1044                          const char *name_b,
1045                          struct diff_filespec *one,
1046                          struct diff_filespec *two,
1047                          const char *xfrm_msg,
1048                          struct diff_options *o,
1049                          int complete_rewrite)
1051         mmfile_t mf1, mf2;
1052         const char *lbl[2];
1053         char *a_one, *b_two;
1054         const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1055         const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1057         a_one = quote_two("a/", name_a);
1058         b_two = quote_two("b/", name_b);
1059         lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1060         lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1061         printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1062         if (lbl[0][0] == '/') {
1063                 /* /dev/null */
1064                 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1065                 if (xfrm_msg && xfrm_msg[0])
1066                         printf("%s%s%s\n", set, xfrm_msg, reset);
1067         }
1068         else if (lbl[1][0] == '/') {
1069                 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1070                 if (xfrm_msg && xfrm_msg[0])
1071                         printf("%s%s%s\n", set, xfrm_msg, reset);
1072         }
1073         else {
1074                 if (one->mode != two->mode) {
1075                         printf("%sold mode %06o%s\n", set, one->mode, reset);
1076                         printf("%snew mode %06o%s\n", set, two->mode, reset);
1077                 }
1078                 if (xfrm_msg && xfrm_msg[0])
1079                         printf("%s%s%s\n", set, xfrm_msg, reset);
1080                 /*
1081                  * we do not run diff between different kind
1082                  * of objects.
1083                  */
1084                 if ((one->mode ^ two->mode) & S_IFMT)
1085                         goto free_ab_and_return;
1086                 if (complete_rewrite) {
1087                         emit_rewrite_diff(name_a, name_b, one, two);
1088                         goto free_ab_and_return;
1089                 }
1090         }
1092         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1093                 die("unable to read files to diff");
1095         if (!o->text && (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))) {
1096                 /* Quite common confusing case */
1097                 if (mf1.size == mf2.size &&
1098                     !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1099                         goto free_ab_and_return;
1100                 if (o->binary)
1101                         emit_binary_diff(&mf1, &mf2);
1102                 else
1103                         printf("Binary files %s and %s differ\n",
1104                                lbl[0], lbl[1]);
1105         }
1106         else {
1107                 /* Crazy xdl interfaces.. */
1108                 const char *diffopts = getenv("GIT_DIFF_OPTS");
1109                 xpparam_t xpp;
1110                 xdemitconf_t xecfg;
1111                 xdemitcb_t ecb;
1112                 struct emit_callback ecbdata;
1114                 memset(&ecbdata, 0, sizeof(ecbdata));
1115                 ecbdata.label_path = lbl;
1116                 ecbdata.color_diff = o->color_diff;
1117                 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1118                 xecfg.ctxlen = o->context;
1119                 xecfg.flags = XDL_EMIT_FUNCNAMES;
1120                 if (!diffopts)
1121                         ;
1122                 else if (!prefixcmp(diffopts, "--unified="))
1123                         xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1124                 else if (!prefixcmp(diffopts, "-u"))
1125                         xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1126                 ecb.outf = xdiff_outf;
1127                 ecb.priv = &ecbdata;
1128                 ecbdata.xm.consume = fn_out_consume;
1129                 if (o->color_diff_words)
1130                         ecbdata.diff_words =
1131                                 xcalloc(1, sizeof(struct diff_words_data));
1132                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1133                 if (o->color_diff_words)
1134                         free_diff_words_data(&ecbdata);
1135         }
1137  free_ab_and_return:
1138         free(a_one);
1139         free(b_two);
1140         return;
1143 static void builtin_diffstat(const char *name_a, const char *name_b,
1144                              struct diff_filespec *one,
1145                              struct diff_filespec *two,
1146                              struct diffstat_t *diffstat,
1147                              struct diff_options *o,
1148                              int complete_rewrite)
1150         mmfile_t mf1, mf2;
1151         struct diffstat_file *data;
1153         data = diffstat_add(diffstat, name_a, name_b);
1155         if (!one || !two) {
1156                 data->is_unmerged = 1;
1157                 return;
1158         }
1159         if (complete_rewrite) {
1160                 diff_populate_filespec(one, 0);
1161                 diff_populate_filespec(two, 0);
1162                 data->deleted = count_lines(one->data, one->size);
1163                 data->added = count_lines(two->data, two->size);
1164                 return;
1165         }
1166         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1167                 die("unable to read files to diff");
1169         if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
1170                 data->is_binary = 1;
1171         else {
1172                 /* Crazy xdl interfaces.. */
1173                 xpparam_t xpp;
1174                 xdemitconf_t xecfg;
1175                 xdemitcb_t ecb;
1177                 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1178                 xecfg.ctxlen = 0;
1179                 xecfg.flags = 0;
1180                 ecb.outf = xdiff_outf;
1181                 ecb.priv = diffstat;
1182                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1183         }
1186 static void builtin_checkdiff(const char *name_a, const char *name_b,
1187                              struct diff_filespec *one,
1188                              struct diff_filespec *two, struct diff_options *o)
1190         mmfile_t mf1, mf2;
1191         struct checkdiff_t data;
1193         if (!two)
1194                 return;
1196         memset(&data, 0, sizeof(data));
1197         data.xm.consume = checkdiff_consume;
1198         data.filename = name_b ? name_b : name_a;
1199         data.lineno = 0;
1200         data.color_diff = o->color_diff;
1202         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1203                 die("unable to read files to diff");
1205         if (mmfile_is_binary(&mf2))
1206                 return;
1207         else {
1208                 /* Crazy xdl interfaces.. */
1209                 xpparam_t xpp;
1210                 xdemitconf_t xecfg;
1211                 xdemitcb_t ecb;
1213                 xpp.flags = XDF_NEED_MINIMAL;
1214                 xecfg.ctxlen = 0;
1215                 xecfg.flags = 0;
1216                 ecb.outf = xdiff_outf;
1217                 ecb.priv = &data;
1218                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1219         }
1222 struct diff_filespec *alloc_filespec(const char *path)
1224         int namelen = strlen(path);
1225         struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1227         memset(spec, 0, sizeof(*spec));
1228         spec->path = (char *)(spec + 1);
1229         memcpy(spec->path, path, namelen+1);
1230         return spec;
1233 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1234                    unsigned short mode)
1236         if (mode) {
1237                 spec->mode = canon_mode(mode);
1238                 hashcpy(spec->sha1, sha1);
1239                 spec->sha1_valid = !is_null_sha1(sha1);
1240         }
1243 /*
1244  * Given a name and sha1 pair, if the dircache tells us the file in
1245  * the work tree has that object contents, return true, so that
1246  * prepare_temp_file() does not have to inflate and extract.
1247  */
1248 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1250         struct cache_entry *ce;
1251         struct stat st;
1252         int pos, len;
1254         /* We do not read the cache ourselves here, because the
1255          * benchmark with my previous version that always reads cache
1256          * shows that it makes things worse for diff-tree comparing
1257          * two linux-2.6 kernel trees in an already checked out work
1258          * tree.  This is because most diff-tree comparisons deal with
1259          * only a small number of files, while reading the cache is
1260          * expensive for a large project, and its cost outweighs the
1261          * savings we get by not inflating the object to a temporary
1262          * file.  Practically, this code only helps when we are used
1263          * by diff-cache --cached, which does read the cache before
1264          * calling us.
1265          */
1266         if (!active_cache)
1267                 return 0;
1269         /* We want to avoid the working directory if our caller
1270          * doesn't need the data in a normal file, this system
1271          * is rather slow with its stat/open/mmap/close syscalls,
1272          * and the object is contained in a pack file.  The pack
1273          * is probably already open and will be faster to obtain
1274          * the data through than the working directory.  Loose
1275          * objects however would tend to be slower as they need
1276          * to be individually opened and inflated.
1277          */
1278         if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1279                 return 0;
1281         len = strlen(name);
1282         pos = cache_name_pos(name, len);
1283         if (pos < 0)
1284                 return 0;
1285         ce = active_cache[pos];
1286         if ((lstat(name, &st) < 0) ||
1287             !S_ISREG(st.st_mode) || /* careful! */
1288             ce_match_stat(ce, &st, 0) ||
1289             hashcmp(sha1, ce->sha1))
1290                 return 0;
1291         /* we return 1 only when we can stat, it is a regular file,
1292          * stat information matches, and sha1 recorded in the cache
1293          * matches.  I.e. we know the file in the work tree really is
1294          * the same as the <name, sha1> pair.
1295          */
1296         return 1;
1299 static struct sha1_size_cache {
1300         unsigned char sha1[20];
1301         unsigned long size;
1302 } **sha1_size_cache;
1303 static int sha1_size_cache_nr, sha1_size_cache_alloc;
1305 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
1306                                                  int find_only,
1307                                                  unsigned long size)
1309         int first, last;
1310         struct sha1_size_cache *e;
1312         first = 0;
1313         last = sha1_size_cache_nr;
1314         while (last > first) {
1315                 int cmp, next = (last + first) >> 1;
1316                 e = sha1_size_cache[next];
1317                 cmp = hashcmp(e->sha1, sha1);
1318                 if (!cmp)
1319                         return e;
1320                 if (cmp < 0) {
1321                         last = next;
1322                         continue;
1323                 }
1324                 first = next+1;
1325         }
1326         /* not found */
1327         if (find_only)
1328                 return NULL;
1329         /* insert to make it at "first" */
1330         if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
1331                 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
1332                 sha1_size_cache = xrealloc(sha1_size_cache,
1333                                            sha1_size_cache_alloc *
1334                                            sizeof(*sha1_size_cache));
1335         }
1336         sha1_size_cache_nr++;
1337         if (first < sha1_size_cache_nr)
1338                 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
1339                         (sha1_size_cache_nr - first - 1) *
1340                         sizeof(*sha1_size_cache));
1341         e = xmalloc(sizeof(struct sha1_size_cache));
1342         sha1_size_cache[first] = e;
1343         hashcpy(e->sha1, sha1);
1344         e->size = size;
1345         return e;
1348 /*
1349  * While doing rename detection and pickaxe operation, we may need to
1350  * grab the data for the blob (or file) for our own in-core comparison.
1351  * diff_filespec has data and size fields for this purpose.
1352  */
1353 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1355         int err = 0;
1356         if (!DIFF_FILE_VALID(s))
1357                 die("internal error: asking to populate invalid file.");
1358         if (S_ISDIR(s->mode))
1359                 return -1;
1361         if (!use_size_cache)
1362                 size_only = 0;
1364         if (s->data)
1365                 return err;
1366         if (!s->sha1_valid ||
1367             reuse_worktree_file(s->path, s->sha1, 0)) {
1368                 struct stat st;
1369                 int fd;
1370                 if (lstat(s->path, &st) < 0) {
1371                         if (errno == ENOENT) {
1372                         err_empty:
1373                                 err = -1;
1374                         empty:
1375                                 s->data = (char *)"";
1376                                 s->size = 0;
1377                                 return err;
1378                         }
1379                 }
1380                 s->size = st.st_size;
1381                 if (!s->size)
1382                         goto empty;
1383                 if (size_only)
1384                         return 0;
1385                 if (S_ISLNK(st.st_mode)) {
1386                         int ret;
1387                         s->data = xmalloc(s->size);
1388                         s->should_free = 1;
1389                         ret = readlink(s->path, s->data, s->size);
1390                         if (ret < 0) {
1391                                 free(s->data);
1392                                 goto err_empty;
1393                         }
1394                         return 0;
1395                 }
1396                 fd = open(s->path, O_RDONLY);
1397                 if (fd < 0)
1398                         goto err_empty;
1399                 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1400                 close(fd);
1401                 s->should_munmap = 1;
1402                 /* FIXME! CRLF -> LF conversion goes here, based on "s->path" */
1403         }
1404         else {
1405                 char type[20];
1406                 struct sha1_size_cache *e;
1408                 if (size_only) {
1409                         e = locate_size_cache(s->sha1, 1, 0);
1410                         if (e) {
1411                                 s->size = e->size;
1412                                 return 0;
1413                         }
1414                         if (!sha1_object_info(s->sha1, type, &s->size))
1415                                 locate_size_cache(s->sha1, 0, s->size);
1416                 }
1417                 else {
1418                         s->data = read_sha1_file(s->sha1, type, &s->size);
1419                         s->should_free = 1;
1420                 }
1421         }
1422         return 0;
1425 void diff_free_filespec_data(struct diff_filespec *s)
1427         if (s->should_free)
1428                 free(s->data);
1429         else if (s->should_munmap)
1430                 munmap(s->data, s->size);
1431         s->should_free = s->should_munmap = 0;
1432         s->data = NULL;
1433         free(s->cnt_data);
1434         s->cnt_data = NULL;
1437 static void prep_temp_blob(struct diff_tempfile *temp,
1438                            void *blob,
1439                            unsigned long size,
1440                            const unsigned char *sha1,
1441                            int mode)
1443         int fd;
1445         fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1446         if (fd < 0)
1447                 die("unable to create temp-file");
1448         if (write_in_full(fd, blob, size) != size)
1449                 die("unable to write temp-file");
1450         close(fd);
1451         temp->name = temp->tmp_path;
1452         strcpy(temp->hex, sha1_to_hex(sha1));
1453         temp->hex[40] = 0;
1454         sprintf(temp->mode, "%06o", mode);
1457 static void prepare_temp_file(const char *name,
1458                               struct diff_tempfile *temp,
1459                               struct diff_filespec *one)
1461         if (!DIFF_FILE_VALID(one)) {
1462         not_a_valid_file:
1463                 /* A '-' entry produces this for file-2, and
1464                  * a '+' entry produces this for file-1.
1465                  */
1466                 temp->name = "/dev/null";
1467                 strcpy(temp->hex, ".");
1468                 strcpy(temp->mode, ".");
1469                 return;
1470         }
1472         if (!one->sha1_valid ||
1473             reuse_worktree_file(name, one->sha1, 1)) {
1474                 struct stat st;
1475                 if (lstat(name, &st) < 0) {
1476                         if (errno == ENOENT)
1477                                 goto not_a_valid_file;
1478                         die("stat(%s): %s", name, strerror(errno));
1479                 }
1480                 if (S_ISLNK(st.st_mode)) {
1481                         int ret;
1482                         char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1483                         if (sizeof(buf) <= st.st_size)
1484                                 die("symlink too long: %s", name);
1485                         ret = readlink(name, buf, st.st_size);
1486                         if (ret < 0)
1487                                 die("readlink(%s)", name);
1488                         prep_temp_blob(temp, buf, st.st_size,
1489                                        (one->sha1_valid ?
1490                                         one->sha1 : null_sha1),
1491                                        (one->sha1_valid ?
1492                                         one->mode : S_IFLNK));
1493                 }
1494                 else {
1495                         /* we can borrow from the file in the work tree */
1496                         temp->name = name;
1497                         if (!one->sha1_valid)
1498                                 strcpy(temp->hex, sha1_to_hex(null_sha1));
1499                         else
1500                                 strcpy(temp->hex, sha1_to_hex(one->sha1));
1501                         /* Even though we may sometimes borrow the
1502                          * contents from the work tree, we always want
1503                          * one->mode.  mode is trustworthy even when
1504                          * !(one->sha1_valid), as long as
1505                          * DIFF_FILE_VALID(one).
1506                          */
1507                         sprintf(temp->mode, "%06o", one->mode);
1508                 }
1509                 return;
1510         }
1511         else {
1512                 if (diff_populate_filespec(one, 0))
1513                         die("cannot read data blob for %s", one->path);
1514                 prep_temp_blob(temp, one->data, one->size,
1515                                one->sha1, one->mode);
1516         }
1519 static void remove_tempfile(void)
1521         int i;
1523         for (i = 0; i < 2; i++)
1524                 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1525                         unlink(diff_temp[i].name);
1526                         diff_temp[i].name = NULL;
1527                 }
1530 static void remove_tempfile_on_signal(int signo)
1532         remove_tempfile();
1533         signal(SIGINT, SIG_DFL);
1534         raise(signo);
1537 static int spawn_prog(const char *pgm, const char **arg)
1539         pid_t pid;
1540         int status;
1542         fflush(NULL);
1543         pid = fork();
1544         if (pid < 0)
1545                 die("unable to fork");
1546         if (!pid) {
1547                 execvp(pgm, (char *const*) arg);
1548                 exit(255);
1549         }
1551         while (waitpid(pid, &status, 0) < 0) {
1552                 if (errno == EINTR)
1553                         continue;
1554                 return -1;
1555         }
1557         /* Earlier we did not check the exit status because
1558          * diff exits non-zero if files are different, and
1559          * we are not interested in knowing that.  It was a
1560          * mistake which made it harder to quit a diff-*
1561          * session that uses the git-apply-patch-script as
1562          * the GIT_EXTERNAL_DIFF.  A custom GIT_EXTERNAL_DIFF
1563          * should also exit non-zero only when it wants to
1564          * abort the entire diff-* session.
1565          */
1566         if (WIFEXITED(status) && !WEXITSTATUS(status))
1567                 return 0;
1568         return -1;
1571 /* An external diff command takes:
1572  *
1573  * diff-cmd name infile1 infile1-sha1 infile1-mode \
1574  *               infile2 infile2-sha1 infile2-mode [ rename-to ]
1575  *
1576  */
1577 static void run_external_diff(const char *pgm,
1578                               const char *name,
1579                               const char *other,
1580                               struct diff_filespec *one,
1581                               struct diff_filespec *two,
1582                               const char *xfrm_msg,
1583                               int complete_rewrite)
1585         const char *spawn_arg[10];
1586         struct diff_tempfile *temp = diff_temp;
1587         int retval;
1588         static int atexit_asked = 0;
1589         const char *othername;
1590         const char **arg = &spawn_arg[0];
1592         othername = (other? other : name);
1593         if (one && two) {
1594                 prepare_temp_file(name, &temp[0], one);
1595                 prepare_temp_file(othername, &temp[1], two);
1596                 if (! atexit_asked &&
1597                     (temp[0].name == temp[0].tmp_path ||
1598                      temp[1].name == temp[1].tmp_path)) {
1599                         atexit_asked = 1;
1600                         atexit(remove_tempfile);
1601                 }
1602                 signal(SIGINT, remove_tempfile_on_signal);
1603         }
1605         if (one && two) {
1606                 *arg++ = pgm;
1607                 *arg++ = name;
1608                 *arg++ = temp[0].name;
1609                 *arg++ = temp[0].hex;
1610                 *arg++ = temp[0].mode;
1611                 *arg++ = temp[1].name;
1612                 *arg++ = temp[1].hex;
1613                 *arg++ = temp[1].mode;
1614                 if (other) {
1615                         *arg++ = other;
1616                         *arg++ = xfrm_msg;
1617                 }
1618         } else {
1619                 *arg++ = pgm;
1620                 *arg++ = name;
1621         }
1622         *arg = NULL;
1623         retval = spawn_prog(pgm, spawn_arg);
1624         remove_tempfile();
1625         if (retval) {
1626                 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1627                 exit(1);
1628         }
1631 static void run_diff_cmd(const char *pgm,
1632                          const char *name,
1633                          const char *other,
1634                          struct diff_filespec *one,
1635                          struct diff_filespec *two,
1636                          const char *xfrm_msg,
1637                          struct diff_options *o,
1638                          int complete_rewrite)
1640         if (pgm) {
1641                 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1642                                   complete_rewrite);
1643                 return;
1644         }
1645         if (one && two)
1646                 builtin_diff(name, other ? other : name,
1647                              one, two, xfrm_msg, o, complete_rewrite);
1648         else
1649                 printf("* Unmerged path %s\n", name);
1652 static void diff_fill_sha1_info(struct diff_filespec *one)
1654         if (DIFF_FILE_VALID(one)) {
1655                 if (!one->sha1_valid) {
1656                         struct stat st;
1657                         if (lstat(one->path, &st) < 0)
1658                                 die("stat %s", one->path);
1659                         if (index_path(one->sha1, one->path, &st, 0))
1660                                 die("cannot hash %s\n", one->path);
1661                 }
1662         }
1663         else
1664                 hashclr(one->sha1);
1667 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1669         const char *pgm = external_diff();
1670         char msg[PATH_MAX*2+300], *xfrm_msg;
1671         struct diff_filespec *one;
1672         struct diff_filespec *two;
1673         const char *name;
1674         const char *other;
1675         char *name_munged, *other_munged;
1676         int complete_rewrite = 0;
1677         int len;
1679         if (DIFF_PAIR_UNMERGED(p)) {
1680                 /* unmerged */
1681                 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1682                 return;
1683         }
1685         name = p->one->path;
1686         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1687         name_munged = quote_one(name);
1688         other_munged = quote_one(other);
1689         one = p->one; two = p->two;
1691         diff_fill_sha1_info(one);
1692         diff_fill_sha1_info(two);
1694         len = 0;
1695         switch (p->status) {
1696         case DIFF_STATUS_COPIED:
1697                 len += snprintf(msg + len, sizeof(msg) - len,
1698                                 "similarity index %d%%\n"
1699                                 "copy from %s\n"
1700                                 "copy to %s\n",
1701                                 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1702                                 name_munged, other_munged);
1703                 break;
1704         case DIFF_STATUS_RENAMED:
1705                 len += snprintf(msg + len, sizeof(msg) - len,
1706                                 "similarity index %d%%\n"
1707                                 "rename from %s\n"
1708                                 "rename to %s\n",
1709                                 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1710                                 name_munged, other_munged);
1711                 break;
1712         case DIFF_STATUS_MODIFIED:
1713                 if (p->score) {
1714                         len += snprintf(msg + len, sizeof(msg) - len,
1715                                         "dissimilarity index %d%%\n",
1716                                         (int)(0.5 + p->score *
1717                                               100.0/MAX_SCORE));
1718                         complete_rewrite = 1;
1719                         break;
1720                 }
1721                 /* fallthru */
1722         default:
1723                 /* nothing */
1724                 ;
1725         }
1727         if (hashcmp(one->sha1, two->sha1)) {
1728                 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1730                 if (o->binary) {
1731                         mmfile_t mf;
1732                         if ((!fill_mmfile(&mf, one) && mmfile_is_binary(&mf)) ||
1733                             (!fill_mmfile(&mf, two) && mmfile_is_binary(&mf)))
1734                                 abbrev = 40;
1735                 }
1736                 len += snprintf(msg + len, sizeof(msg) - len,
1737                                 "index %.*s..%.*s",
1738                                 abbrev, sha1_to_hex(one->sha1),
1739                                 abbrev, sha1_to_hex(two->sha1));
1740                 if (one->mode == two->mode)
1741                         len += snprintf(msg + len, sizeof(msg) - len,
1742                                         " %06o", one->mode);
1743                 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1744         }
1746         if (len)
1747                 msg[--len] = 0;
1748         xfrm_msg = len ? msg : NULL;
1750         if (!pgm &&
1751             DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1752             (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1753                 /* a filepair that changes between file and symlink
1754                  * needs to be split into deletion and creation.
1755                  */
1756                 struct diff_filespec *null = alloc_filespec(two->path);
1757                 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1758                 free(null);
1759                 null = alloc_filespec(one->path);
1760                 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1761                 free(null);
1762         }
1763         else
1764                 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1765                              complete_rewrite);
1767         free(name_munged);
1768         free(other_munged);
1771 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1772                          struct diffstat_t *diffstat)
1774         const char *name;
1775         const char *other;
1776         int complete_rewrite = 0;
1778         if (DIFF_PAIR_UNMERGED(p)) {
1779                 /* unmerged */
1780                 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1781                 return;
1782         }
1784         name = p->one->path;
1785         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1787         diff_fill_sha1_info(p->one);
1788         diff_fill_sha1_info(p->two);
1790         if (p->status == DIFF_STATUS_MODIFIED && p->score)
1791                 complete_rewrite = 1;
1792         builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1795 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1797         const char *name;
1798         const char *other;
1800         if (DIFF_PAIR_UNMERGED(p)) {
1801                 /* unmerged */
1802                 return;
1803         }
1805         name = p->one->path;
1806         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1808         diff_fill_sha1_info(p->one);
1809         diff_fill_sha1_info(p->two);
1811         builtin_checkdiff(name, other, p->one, p->two, o);
1814 void diff_setup(struct diff_options *options)
1816         memset(options, 0, sizeof(*options));
1817         options->line_termination = '\n';
1818         options->break_opt = -1;
1819         options->rename_limit = -1;
1820         options->context = 3;
1821         options->msg_sep = "";
1823         options->change = diff_change;
1824         options->add_remove = diff_addremove;
1825         options->color_diff = diff_use_color_default;
1826         options->detect_rename = diff_detect_rename_default;
1829 int diff_setup_done(struct diff_options *options)
1831         int count = 0;
1833         if (options->output_format & DIFF_FORMAT_NAME)
1834                 count++;
1835         if (options->output_format & DIFF_FORMAT_NAME_STATUS)
1836                 count++;
1837         if (options->output_format & DIFF_FORMAT_CHECKDIFF)
1838                 count++;
1839         if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
1840                 count++;
1841         if (count > 1)
1842                 die("--name-only, --name-status, --check and -s are mutually exclusive");
1844         if (options->find_copies_harder)
1845                 options->detect_rename = DIFF_DETECT_COPY;
1847         if (options->output_format & (DIFF_FORMAT_NAME |
1848                                       DIFF_FORMAT_NAME_STATUS |
1849                                       DIFF_FORMAT_CHECKDIFF |
1850                                       DIFF_FORMAT_NO_OUTPUT))
1851                 options->output_format &= ~(DIFF_FORMAT_RAW |
1852                                             DIFF_FORMAT_NUMSTAT |
1853                                             DIFF_FORMAT_DIFFSTAT |
1854                                             DIFF_FORMAT_SHORTSTAT |
1855                                             DIFF_FORMAT_SUMMARY |
1856                                             DIFF_FORMAT_PATCH);
1858         /*
1859          * These cases always need recursive; we do not drop caller-supplied
1860          * recursive bits for other formats here.
1861          */
1862         if (options->output_format & (DIFF_FORMAT_PATCH |
1863                                       DIFF_FORMAT_NUMSTAT |
1864                                       DIFF_FORMAT_DIFFSTAT |
1865                                       DIFF_FORMAT_SHORTSTAT |
1866                                       DIFF_FORMAT_SUMMARY |
1867                                       DIFF_FORMAT_CHECKDIFF))
1868                 options->recursive = 1;
1869         /*
1870          * Also pickaxe would not work very well if you do not say recursive
1871          */
1872         if (options->pickaxe)
1873                 options->recursive = 1;
1875         if (options->detect_rename && options->rename_limit < 0)
1876                 options->rename_limit = diff_rename_limit_default;
1877         if (options->setup & DIFF_SETUP_USE_CACHE) {
1878                 if (!active_cache)
1879                         /* read-cache does not die even when it fails
1880                          * so it is safe for us to do this here.  Also
1881                          * it does not smudge active_cache or active_nr
1882                          * when it fails, so we do not have to worry about
1883                          * cleaning it up ourselves either.
1884                          */
1885                         read_cache();
1886         }
1887         if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1888                 use_size_cache = 1;
1889         if (options->abbrev <= 0 || 40 < options->abbrev)
1890                 options->abbrev = 40; /* full */
1892         return 0;
1895 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1897         char c, *eq;
1898         int len;
1900         if (*arg != '-')
1901                 return 0;
1902         c = *++arg;
1903         if (!c)
1904                 return 0;
1905         if (c == arg_short) {
1906                 c = *++arg;
1907                 if (!c)
1908                         return 1;
1909                 if (val && isdigit(c)) {
1910                         char *end;
1911                         int n = strtoul(arg, &end, 10);
1912                         if (*end)
1913                                 return 0;
1914                         *val = n;
1915                         return 1;
1916                 }
1917                 return 0;
1918         }
1919         if (c != '-')
1920                 return 0;
1921         arg++;
1922         eq = strchr(arg, '=');
1923         if (eq)
1924                 len = eq - arg;
1925         else
1926                 len = strlen(arg);
1927         if (!len || strncmp(arg, arg_long, len))
1928                 return 0;
1929         if (eq) {
1930                 int n;
1931                 char *end;
1932                 if (!isdigit(*++eq))
1933                         return 0;
1934                 n = strtoul(eq, &end, 10);
1935                 if (*end)
1936                         return 0;
1937                 *val = n;
1938         }
1939         return 1;
1942 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1944         const char *arg = av[0];
1945         if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1946                 options->output_format |= DIFF_FORMAT_PATCH;
1947         else if (opt_arg(arg, 'U', "unified", &options->context))
1948                 options->output_format |= DIFF_FORMAT_PATCH;
1949         else if (!strcmp(arg, "--raw"))
1950                 options->output_format |= DIFF_FORMAT_RAW;
1951         else if (!strcmp(arg, "--patch-with-raw")) {
1952                 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
1953         }
1954         else if (!strcmp(arg, "--numstat")) {
1955                 options->output_format |= DIFF_FORMAT_NUMSTAT;
1956         }
1957         else if (!strcmp(arg, "--shortstat")) {
1958                 options->output_format |= DIFF_FORMAT_SHORTSTAT;
1959         }
1960         else if (!prefixcmp(arg, "--stat")) {
1961                 char *end;
1962                 int width = options->stat_width;
1963                 int name_width = options->stat_name_width;
1964                 arg += 6;
1965                 end = (char *)arg;
1967                 switch (*arg) {
1968                 case '-':
1969                         if (!prefixcmp(arg, "-width="))
1970                                 width = strtoul(arg + 7, &end, 10);
1971                         else if (!prefixcmp(arg, "-name-width="))
1972                                 name_width = strtoul(arg + 12, &end, 10);
1973                         break;
1974                 case '=':
1975                         width = strtoul(arg+1, &end, 10);
1976                         if (*end == ',')
1977                                 name_width = strtoul(end+1, &end, 10);
1978                 }
1980                 /* Important! This checks all the error cases! */
1981                 if (*end)
1982                         return 0;
1983                 options->output_format |= DIFF_FORMAT_DIFFSTAT;
1984                 options->stat_name_width = name_width;
1985                 options->stat_width = width;
1986         }
1987         else if (!strcmp(arg, "--check"))
1988                 options->output_format |= DIFF_FORMAT_CHECKDIFF;
1989         else if (!strcmp(arg, "--summary"))
1990                 options->output_format |= DIFF_FORMAT_SUMMARY;
1991         else if (!strcmp(arg, "--patch-with-stat")) {
1992                 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
1993         }
1994         else if (!strcmp(arg, "-z"))
1995                 options->line_termination = 0;
1996         else if (!prefixcmp(arg, "-l"))
1997                 options->rename_limit = strtoul(arg+2, NULL, 10);
1998         else if (!strcmp(arg, "--full-index"))
1999                 options->full_index = 1;
2000         else if (!strcmp(arg, "--binary")) {
2001                 options->output_format |= DIFF_FORMAT_PATCH;
2002                 options->binary = 1;
2003         }
2004         else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
2005                 options->text = 1;
2006         }
2007         else if (!strcmp(arg, "--name-only"))
2008                 options->output_format |= DIFF_FORMAT_NAME;
2009         else if (!strcmp(arg, "--name-status"))
2010                 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2011         else if (!strcmp(arg, "-R"))
2012                 options->reverse_diff = 1;
2013         else if (!prefixcmp(arg, "-S"))
2014                 options->pickaxe = arg + 2;
2015         else if (!strcmp(arg, "-s")) {
2016                 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2017         }
2018         else if (!prefixcmp(arg, "-O"))
2019                 options->orderfile = arg + 2;
2020         else if (!prefixcmp(arg, "--diff-filter="))
2021                 options->filter = arg + 14;
2022         else if (!strcmp(arg, "--pickaxe-all"))
2023                 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2024         else if (!strcmp(arg, "--pickaxe-regex"))
2025                 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2026         else if (!prefixcmp(arg, "-B")) {
2027                 if ((options->break_opt =
2028                      diff_scoreopt_parse(arg)) == -1)
2029                         return -1;
2030         }
2031         else if (!prefixcmp(arg, "-M")) {
2032                 if ((options->rename_score =
2033                      diff_scoreopt_parse(arg)) == -1)
2034                         return -1;
2035                 options->detect_rename = DIFF_DETECT_RENAME;
2036         }
2037         else if (!prefixcmp(arg, "-C")) {
2038                 if ((options->rename_score =
2039                      diff_scoreopt_parse(arg)) == -1)
2040                         return -1;
2041                 options->detect_rename = DIFF_DETECT_COPY;
2042         }
2043         else if (!strcmp(arg, "--find-copies-harder"))
2044                 options->find_copies_harder = 1;
2045         else if (!strcmp(arg, "--abbrev"))
2046                 options->abbrev = DEFAULT_ABBREV;
2047         else if (!prefixcmp(arg, "--abbrev=")) {
2048                 options->abbrev = strtoul(arg + 9, NULL, 10);
2049                 if (options->abbrev < MINIMUM_ABBREV)
2050                         options->abbrev = MINIMUM_ABBREV;
2051                 else if (40 < options->abbrev)
2052                         options->abbrev = 40;
2053         }
2054         else if (!strcmp(arg, "--color"))
2055                 options->color_diff = 1;
2056         else if (!strcmp(arg, "--no-color"))
2057                 options->color_diff = 0;
2058         else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2059                 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2060         else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2061                 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2062         else if (!strcmp(arg, "--ignore-space-at-eol"))
2063                 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2064         else if (!strcmp(arg, "--color-words"))
2065                 options->color_diff = options->color_diff_words = 1;
2066         else if (!strcmp(arg, "--no-renames"))
2067                 options->detect_rename = 0;
2068         else
2069                 return 0;
2070         return 1;
2073 static int parse_num(const char **cp_p)
2075         unsigned long num, scale;
2076         int ch, dot;
2077         const char *cp = *cp_p;
2079         num = 0;
2080         scale = 1;
2081         dot = 0;
2082         for(;;) {
2083                 ch = *cp;
2084                 if ( !dot && ch == '.' ) {
2085                         scale = 1;
2086                         dot = 1;
2087                 } else if ( ch == '%' ) {
2088                         scale = dot ? scale*100 : 100;
2089                         cp++;   /* % is always at the end */
2090                         break;
2091                 } else if ( ch >= '0' && ch <= '9' ) {
2092                         if ( scale < 100000 ) {
2093                                 scale *= 10;
2094                                 num = (num*10) + (ch-'0');
2095                         }
2096                 } else {
2097                         break;
2098                 }
2099                 cp++;
2100         }
2101         *cp_p = cp;
2103         /* user says num divided by scale and we say internally that
2104          * is MAX_SCORE * num / scale.
2105          */
2106         return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
2109 int diff_scoreopt_parse(const char *opt)
2111         int opt1, opt2, cmd;
2113         if (*opt++ != '-')
2114                 return -1;
2115         cmd = *opt++;
2116         if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2117                 return -1; /* that is not a -M, -C nor -B option */
2119         opt1 = parse_num(&opt);
2120         if (cmd != 'B')
2121                 opt2 = 0;
2122         else {
2123                 if (*opt == 0)
2124                         opt2 = 0;
2125                 else if (*opt != '/')
2126                         return -1; /* we expect -B80/99 or -B80 */
2127                 else {
2128                         opt++;
2129                         opt2 = parse_num(&opt);
2130                 }
2131         }
2132         if (*opt != 0)
2133                 return -1;
2134         return opt1 | (opt2 << 16);
2137 struct diff_queue_struct diff_queued_diff;
2139 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2141         if (queue->alloc <= queue->nr) {
2142                 queue->alloc = alloc_nr(queue->alloc);
2143                 queue->queue = xrealloc(queue->queue,
2144                                         sizeof(dp) * queue->alloc);
2145         }
2146         queue->queue[queue->nr++] = dp;
2149 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2150                                  struct diff_filespec *one,
2151                                  struct diff_filespec *two)
2153         struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2154         dp->one = one;
2155         dp->two = two;
2156         if (queue)
2157                 diff_q(queue, dp);
2158         return dp;
2161 void diff_free_filepair(struct diff_filepair *p)
2163         diff_free_filespec_data(p->one);
2164         diff_free_filespec_data(p->two);
2165         free(p->one);
2166         free(p->two);
2167         free(p);
2170 /* This is different from find_unique_abbrev() in that
2171  * it stuffs the result with dots for alignment.
2172  */
2173 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2175         int abblen;
2176         const char *abbrev;
2177         if (len == 40)
2178                 return sha1_to_hex(sha1);
2180         abbrev = find_unique_abbrev(sha1, len);
2181         if (!abbrev)
2182                 return sha1_to_hex(sha1);
2183         abblen = strlen(abbrev);
2184         if (abblen < 37) {
2185                 static char hex[41];
2186                 if (len < abblen && abblen <= len + 2)
2187                         sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2188                 else
2189                         sprintf(hex, "%s...", abbrev);
2190                 return hex;
2191         }
2192         return sha1_to_hex(sha1);
2195 static void diff_flush_raw(struct diff_filepair *p,
2196                            struct diff_options *options)
2198         int two_paths;
2199         char status[10];
2200         int abbrev = options->abbrev;
2201         const char *path_one, *path_two;
2202         int inter_name_termination = '\t';
2203         int line_termination = options->line_termination;
2205         if (!line_termination)
2206                 inter_name_termination = 0;
2208         path_one = p->one->path;
2209         path_two = p->two->path;
2210         if (line_termination) {
2211                 path_one = quote_one(path_one);
2212                 path_two = quote_one(path_two);
2213         }
2215         if (p->score)
2216                 sprintf(status, "%c%03d", p->status,
2217                         (int)(0.5 + p->score * 100.0/MAX_SCORE));
2218         else {
2219                 status[0] = p->status;
2220                 status[1] = 0;
2221         }
2222         switch (p->status) {
2223         case DIFF_STATUS_COPIED:
2224         case DIFF_STATUS_RENAMED:
2225                 two_paths = 1;
2226                 break;
2227         case DIFF_STATUS_ADDED:
2228         case DIFF_STATUS_DELETED:
2229                 two_paths = 0;
2230                 break;
2231         default:
2232                 two_paths = 0;
2233                 break;
2234         }
2235         if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2236                 printf(":%06o %06o %s ",
2237                        p->one->mode, p->two->mode,
2238                        diff_unique_abbrev(p->one->sha1, abbrev));
2239                 printf("%s ",
2240                        diff_unique_abbrev(p->two->sha1, abbrev));
2241         }
2242         printf("%s%c%s", status, inter_name_termination, path_one);
2243         if (two_paths)
2244                 printf("%c%s", inter_name_termination, path_two);
2245         putchar(line_termination);
2246         if (path_one != p->one->path)
2247                 free((void*)path_one);
2248         if (path_two != p->two->path)
2249                 free((void*)path_two);
2252 static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2254         char *path = p->two->path;
2256         if (opt->line_termination)
2257                 path = quote_one(p->two->path);
2258         printf("%s%c", path, opt->line_termination);
2259         if (p->two->path != path)
2260                 free(path);
2263 int diff_unmodified_pair(struct diff_filepair *p)
2265         /* This function is written stricter than necessary to support
2266          * the currently implemented transformers, but the idea is to
2267          * let transformers to produce diff_filepairs any way they want,
2268          * and filter and clean them up here before producing the output.
2269          */
2270         struct diff_filespec *one, *two;
2272         if (DIFF_PAIR_UNMERGED(p))
2273                 return 0; /* unmerged is interesting */
2275         one = p->one;
2276         two = p->two;
2278         /* deletion, addition, mode or type change
2279          * and rename are all interesting.
2280          */
2281         if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2282             DIFF_PAIR_MODE_CHANGED(p) ||
2283             strcmp(one->path, two->path))
2284                 return 0;
2286         /* both are valid and point at the same path.  that is, we are
2287          * dealing with a change.
2288          */
2289         if (one->sha1_valid && two->sha1_valid &&
2290             !hashcmp(one->sha1, two->sha1))
2291                 return 1; /* no change */
2292         if (!one->sha1_valid && !two->sha1_valid)
2293                 return 1; /* both look at the same file on the filesystem. */
2294         return 0;
2297 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2299         if (diff_unmodified_pair(p))
2300                 return;
2302         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2303             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2304                 return; /* no tree diffs in patch format */
2306         run_diff(p, o);
2309 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2310                             struct diffstat_t *diffstat)
2312         if (diff_unmodified_pair(p))
2313                 return;
2315         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2316             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2317                 return; /* no tree diffs in patch format */
2319         run_diffstat(p, o, diffstat);
2322 static void diff_flush_checkdiff(struct diff_filepair *p,
2323                 struct diff_options *o)
2325         if (diff_unmodified_pair(p))
2326                 return;
2328         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2329             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2330                 return; /* no tree diffs in patch format */
2332         run_checkdiff(p, o);
2335 int diff_queue_is_empty(void)
2337         struct diff_queue_struct *q = &diff_queued_diff;
2338         int i;
2339         for (i = 0; i < q->nr; i++)
2340                 if (!diff_unmodified_pair(q->queue[i]))
2341                         return 0;
2342         return 1;
2345 #if DIFF_DEBUG
2346 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2348         fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2349                 x, one ? one : "",
2350                 s->path,
2351                 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2352                 s->mode,
2353                 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2354         fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2355                 x, one ? one : "",
2356                 s->size, s->xfrm_flags);
2359 void diff_debug_filepair(const struct diff_filepair *p, int i)
2361         diff_debug_filespec(p->one, i, "one");
2362         diff_debug_filespec(p->two, i, "two");
2363         fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2364                 p->score, p->status ? p->status : '?',
2365                 p->source_stays, p->broken_pair);
2368 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2370         int i;
2371         if (msg)
2372                 fprintf(stderr, "%s\n", msg);
2373         fprintf(stderr, "q->nr = %d\n", q->nr);
2374         for (i = 0; i < q->nr; i++) {
2375                 struct diff_filepair *p = q->queue[i];
2376                 diff_debug_filepair(p, i);
2377         }
2379 #endif
2381 static void diff_resolve_rename_copy(void)
2383         int i, j;
2384         struct diff_filepair *p, *pp;
2385         struct diff_queue_struct *q = &diff_queued_diff;
2387         diff_debug_queue("resolve-rename-copy", q);
2389         for (i = 0; i < q->nr; i++) {
2390                 p = q->queue[i];
2391                 p->status = 0; /* undecided */
2392                 if (DIFF_PAIR_UNMERGED(p))
2393                         p->status = DIFF_STATUS_UNMERGED;
2394                 else if (!DIFF_FILE_VALID(p->one))
2395                         p->status = DIFF_STATUS_ADDED;
2396                 else if (!DIFF_FILE_VALID(p->two))
2397                         p->status = DIFF_STATUS_DELETED;
2398                 else if (DIFF_PAIR_TYPE_CHANGED(p))
2399                         p->status = DIFF_STATUS_TYPE_CHANGED;
2401                 /* from this point on, we are dealing with a pair
2402                  * whose both sides are valid and of the same type, i.e.
2403                  * either in-place edit or rename/copy edit.
2404                  */
2405                 else if (DIFF_PAIR_RENAME(p)) {
2406                         if (p->source_stays) {
2407                                 p->status = DIFF_STATUS_COPIED;
2408                                 continue;
2409                         }
2410                         /* See if there is some other filepair that
2411                          * copies from the same source as us.  If so
2412                          * we are a copy.  Otherwise we are either a
2413                          * copy if the path stays, or a rename if it
2414                          * does not, but we already handled "stays" case.
2415                          */
2416                         for (j = i + 1; j < q->nr; j++) {
2417                                 pp = q->queue[j];
2418                                 if (strcmp(pp->one->path, p->one->path))
2419                                         continue; /* not us */
2420                                 if (!DIFF_PAIR_RENAME(pp))
2421                                         continue; /* not a rename/copy */
2422                                 /* pp is a rename/copy from the same source */
2423                                 p->status = DIFF_STATUS_COPIED;
2424                                 break;
2425                         }
2426                         if (!p->status)
2427                                 p->status = DIFF_STATUS_RENAMED;
2428                 }
2429                 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2430                          p->one->mode != p->two->mode)
2431                         p->status = DIFF_STATUS_MODIFIED;
2432                 else {
2433                         /* This is a "no-change" entry and should not
2434                          * happen anymore, but prepare for broken callers.
2435                          */
2436                         error("feeding unmodified %s to diffcore",
2437                               p->one->path);
2438                         p->status = DIFF_STATUS_UNKNOWN;
2439                 }
2440         }
2441         diff_debug_queue("resolve-rename-copy done", q);
2444 static int check_pair_status(struct diff_filepair *p)
2446         switch (p->status) {
2447         case DIFF_STATUS_UNKNOWN:
2448                 return 0;
2449         case 0:
2450                 die("internal error in diff-resolve-rename-copy");
2451         default:
2452                 return 1;
2453         }
2456 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2458         int fmt = opt->output_format;
2460         if (fmt & DIFF_FORMAT_CHECKDIFF)
2461                 diff_flush_checkdiff(p, opt);
2462         else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2463                 diff_flush_raw(p, opt);
2464         else if (fmt & DIFF_FORMAT_NAME)
2465                 diff_flush_name(p, opt);
2468 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2470         char *name = quote_one(fs->path);
2471         if (fs->mode)
2472                 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2473         else
2474                 printf(" %s %s\n", newdelete, name);
2475         free(name);
2479 static void show_mode_change(struct diff_filepair *p, int show_name)
2481         if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2482                 if (show_name) {
2483                         char *name = quote_one(p->two->path);
2484                         printf(" mode change %06o => %06o %s\n",
2485                                p->one->mode, p->two->mode, name);
2486                         free(name);
2487                 }
2488                 else
2489                         printf(" mode change %06o => %06o\n",
2490                                p->one->mode, p->two->mode);
2491         }
2494 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2496         char *names = pprint_rename(p->one->path, p->two->path);
2498         printf(" %s %s (%d%%)\n", renamecopy, names,
2499                (int)(0.5 + p->score * 100.0/MAX_SCORE));
2500         free(names);
2501         show_mode_change(p, 0);
2504 static void diff_summary(struct diff_filepair *p)
2506         switch(p->status) {
2507         case DIFF_STATUS_DELETED:
2508                 show_file_mode_name("delete", p->one);
2509                 break;
2510         case DIFF_STATUS_ADDED:
2511                 show_file_mode_name("create", p->two);
2512                 break;
2513         case DIFF_STATUS_COPIED:
2514                 show_rename_copy("copy", p);
2515                 break;
2516         case DIFF_STATUS_RENAMED:
2517                 show_rename_copy("rename", p);
2518                 break;
2519         default:
2520                 if (p->score) {
2521                         char *name = quote_one(p->two->path);
2522                         printf(" rewrite %s (%d%%)\n", name,
2523                                 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2524                         free(name);
2525                         show_mode_change(p, 0);
2526                 } else  show_mode_change(p, 1);
2527                 break;
2528         }
2531 struct patch_id_t {
2532         struct xdiff_emit_state xm;
2533         SHA_CTX *ctx;
2534         int patchlen;
2535 };
2537 static int remove_space(char *line, int len)
2539         int i;
2540         char *dst = line;
2541         unsigned char c;
2543         for (i = 0; i < len; i++)
2544                 if (!isspace((c = line[i])))
2545                         *dst++ = c;
2547         return dst - line;
2550 static void patch_id_consume(void *priv, char *line, unsigned long len)
2552         struct patch_id_t *data = priv;
2553         int new_len;
2555         /* Ignore line numbers when computing the SHA1 of the patch */
2556         if (!prefixcmp(line, "@@ -"))
2557                 return;
2559         new_len = remove_space(line, len);
2561         SHA1_Update(data->ctx, line, new_len);
2562         data->patchlen += new_len;
2565 /* returns 0 upon success, and writes result into sha1 */
2566 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2568         struct diff_queue_struct *q = &diff_queued_diff;
2569         int i;
2570         SHA_CTX ctx;
2571         struct patch_id_t data;
2572         char buffer[PATH_MAX * 4 + 20];
2574         SHA1_Init(&ctx);
2575         memset(&data, 0, sizeof(struct patch_id_t));
2576         data.ctx = &ctx;
2577         data.xm.consume = patch_id_consume;
2579         for (i = 0; i < q->nr; i++) {
2580                 xpparam_t xpp;
2581                 xdemitconf_t xecfg;
2582                 xdemitcb_t ecb;
2583                 mmfile_t mf1, mf2;
2584                 struct diff_filepair *p = q->queue[i];
2585                 int len1, len2;
2587                 if (p->status == 0)
2588                         return error("internal diff status error");
2589                 if (p->status == DIFF_STATUS_UNKNOWN)
2590                         continue;
2591                 if (diff_unmodified_pair(p))
2592                         continue;
2593                 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2594                     (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2595                         continue;
2596                 if (DIFF_PAIR_UNMERGED(p))
2597                         continue;
2599                 diff_fill_sha1_info(p->one);
2600                 diff_fill_sha1_info(p->two);
2601                 if (fill_mmfile(&mf1, p->one) < 0 ||
2602                                 fill_mmfile(&mf2, p->two) < 0)
2603                         return error("unable to read files to diff");
2605                 /* Maybe hash p->two? into the patch id? */
2606                 if (mmfile_is_binary(&mf2))
2607                         continue;
2609                 len1 = remove_space(p->one->path, strlen(p->one->path));
2610                 len2 = remove_space(p->two->path, strlen(p->two->path));
2611                 if (p->one->mode == 0)
2612                         len1 = snprintf(buffer, sizeof(buffer),
2613                                         "diff--gita/%.*sb/%.*s"
2614                                         "newfilemode%06o"
2615                                         "---/dev/null"
2616                                         "+++b/%.*s",
2617                                         len1, p->one->path,
2618                                         len2, p->two->path,
2619                                         p->two->mode,
2620                                         len2, p->two->path);
2621                 else if (p->two->mode == 0)
2622                         len1 = snprintf(buffer, sizeof(buffer),
2623                                         "diff--gita/%.*sb/%.*s"
2624                                         "deletedfilemode%06o"
2625                                         "---a/%.*s"
2626                                         "+++/dev/null",
2627                                         len1, p->one->path,
2628                                         len2, p->two->path,
2629                                         p->one->mode,
2630                                         len1, p->one->path);
2631                 else
2632                         len1 = snprintf(buffer, sizeof(buffer),
2633                                         "diff--gita/%.*sb/%.*s"
2634                                         "---a/%.*s"
2635                                         "+++b/%.*s",
2636                                         len1, p->one->path,
2637                                         len2, p->two->path,
2638                                         len1, p->one->path,
2639                                         len2, p->two->path);
2640                 SHA1_Update(&ctx, buffer, len1);
2642                 xpp.flags = XDF_NEED_MINIMAL;
2643                 xecfg.ctxlen = 3;
2644                 xecfg.flags = XDL_EMIT_FUNCNAMES;
2645                 ecb.outf = xdiff_outf;
2646                 ecb.priv = &data;
2647                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2648         }
2650         SHA1_Final(sha1, &ctx);
2651         return 0;
2654 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2656         struct diff_queue_struct *q = &diff_queued_diff;
2657         int i;
2658         int result = diff_get_patch_id(options, sha1);
2660         for (i = 0; i < q->nr; i++)
2661                 diff_free_filepair(q->queue[i]);
2663         free(q->queue);
2664         q->queue = NULL;
2665         q->nr = q->alloc = 0;
2667         return result;
2670 static int is_summary_empty(const struct diff_queue_struct *q)
2672         int i;
2674         for (i = 0; i < q->nr; i++) {
2675                 const struct diff_filepair *p = q->queue[i];
2677                 switch (p->status) {
2678                 case DIFF_STATUS_DELETED:
2679                 case DIFF_STATUS_ADDED:
2680                 case DIFF_STATUS_COPIED:
2681                 case DIFF_STATUS_RENAMED:
2682                         return 0;
2683                 default:
2684                         if (p->score)
2685                                 return 0;
2686                         if (p->one->mode && p->two->mode &&
2687                             p->one->mode != p->two->mode)
2688                                 return 0;
2689                         break;
2690                 }
2691         }
2692         return 1;
2695 void diff_flush(struct diff_options *options)
2697         struct diff_queue_struct *q = &diff_queued_diff;
2698         int i, output_format = options->output_format;
2699         int separator = 0;
2701         /*
2702          * Order: raw, stat, summary, patch
2703          * or:    name/name-status/checkdiff (other bits clear)
2704          */
2705         if (!q->nr)
2706                 goto free_queue;
2708         if (output_format & (DIFF_FORMAT_RAW |
2709                              DIFF_FORMAT_NAME |
2710                              DIFF_FORMAT_NAME_STATUS |
2711                              DIFF_FORMAT_CHECKDIFF)) {
2712                 for (i = 0; i < q->nr; i++) {
2713                         struct diff_filepair *p = q->queue[i];
2714                         if (check_pair_status(p))
2715                                 flush_one_pair(p, options);
2716                 }
2717                 separator++;
2718         }
2720         if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
2721                 struct diffstat_t diffstat;
2723                 memset(&diffstat, 0, sizeof(struct diffstat_t));
2724                 diffstat.xm.consume = diffstat_consume;
2725                 for (i = 0; i < q->nr; i++) {
2726                         struct diff_filepair *p = q->queue[i];
2727                         if (check_pair_status(p))
2728                                 diff_flush_stat(p, options, &diffstat);
2729                 }
2730                 if (output_format & DIFF_FORMAT_NUMSTAT)
2731                         show_numstat(&diffstat, options);
2732                 if (output_format & DIFF_FORMAT_DIFFSTAT)
2733                         show_stats(&diffstat, options);
2734                 else if (output_format & DIFF_FORMAT_SHORTSTAT)
2735                         show_shortstats(&diffstat);
2736                 separator++;
2737         }
2739         if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2740                 for (i = 0; i < q->nr; i++)
2741                         diff_summary(q->queue[i]);
2742                 separator++;
2743         }
2745         if (output_format & DIFF_FORMAT_PATCH) {
2746                 if (separator) {
2747                         if (options->stat_sep) {
2748                                 /* attach patch instead of inline */
2749                                 fputs(options->stat_sep, stdout);
2750                         } else {
2751                                 putchar(options->line_termination);
2752                         }
2753                 }
2755                 for (i = 0; i < q->nr; i++) {
2756                         struct diff_filepair *p = q->queue[i];
2757                         if (check_pair_status(p))
2758                                 diff_flush_patch(p, options);
2759                 }
2760         }
2762         if (output_format & DIFF_FORMAT_CALLBACK)
2763                 options->format_callback(q, options, options->format_callback_data);
2765         for (i = 0; i < q->nr; i++)
2766                 diff_free_filepair(q->queue[i]);
2767 free_queue:
2768         free(q->queue);
2769         q->queue = NULL;
2770         q->nr = q->alloc = 0;
2773 static void diffcore_apply_filter(const char *filter)
2775         int i;
2776         struct diff_queue_struct *q = &diff_queued_diff;
2777         struct diff_queue_struct outq;
2778         outq.queue = NULL;
2779         outq.nr = outq.alloc = 0;
2781         if (!filter)
2782                 return;
2784         if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2785                 int found;
2786                 for (i = found = 0; !found && i < q->nr; i++) {
2787                         struct diff_filepair *p = q->queue[i];
2788                         if (((p->status == DIFF_STATUS_MODIFIED) &&
2789                              ((p->score &&
2790                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2791                               (!p->score &&
2792                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2793                             ((p->status != DIFF_STATUS_MODIFIED) &&
2794                              strchr(filter, p->status)))
2795                                 found++;
2796                 }
2797                 if (found)
2798                         return;
2800                 /* otherwise we will clear the whole queue
2801                  * by copying the empty outq at the end of this
2802                  * function, but first clear the current entries
2803                  * in the queue.
2804                  */
2805                 for (i = 0; i < q->nr; i++)
2806                         diff_free_filepair(q->queue[i]);
2807         }
2808         else {
2809                 /* Only the matching ones */
2810                 for (i = 0; i < q->nr; i++) {
2811                         struct diff_filepair *p = q->queue[i];
2813                         if (((p->status == DIFF_STATUS_MODIFIED) &&
2814                              ((p->score &&
2815                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2816                               (!p->score &&
2817                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2818                             ((p->status != DIFF_STATUS_MODIFIED) &&
2819                              strchr(filter, p->status)))
2820                                 diff_q(&outq, p);
2821                         else
2822                                 diff_free_filepair(p);
2823                 }
2824         }
2825         free(q->queue);
2826         *q = outq;
2829 void diffcore_std(struct diff_options *options)
2831         if (options->break_opt != -1)
2832                 diffcore_break(options->break_opt);
2833         if (options->detect_rename)
2834                 diffcore_rename(options);
2835         if (options->break_opt != -1)
2836                 diffcore_merge_broken();
2837         if (options->pickaxe)
2838                 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2839         if (options->orderfile)
2840                 diffcore_order(options->orderfile);
2841         diff_resolve_rename_copy();
2842         diffcore_apply_filter(options->filter);
2846 void diffcore_std_no_resolve(struct diff_options *options)
2848         if (options->pickaxe)
2849                 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2850         if (options->orderfile)
2851                 diffcore_order(options->orderfile);
2852         diffcore_apply_filter(options->filter);
2855 void diff_addremove(struct diff_options *options,
2856                     int addremove, unsigned mode,
2857                     const unsigned char *sha1,
2858                     const char *base, const char *path)
2860         char concatpath[PATH_MAX];
2861         struct diff_filespec *one, *two;
2863         /* This may look odd, but it is a preparation for
2864          * feeding "there are unchanged files which should
2865          * not produce diffs, but when you are doing copy
2866          * detection you would need them, so here they are"
2867          * entries to the diff-core.  They will be prefixed
2868          * with something like '=' or '*' (I haven't decided
2869          * which but should not make any difference).
2870          * Feeding the same new and old to diff_change() 
2871          * also has the same effect.
2872          * Before the final output happens, they are pruned after
2873          * merged into rename/copy pairs as appropriate.
2874          */
2875         if (options->reverse_diff)
2876                 addremove = (addremove == '+' ? '-' :
2877                              addremove == '-' ? '+' : addremove);
2879         if (!path) path = "";
2880         sprintf(concatpath, "%s%s", base, path);
2881         one = alloc_filespec(concatpath);
2882         two = alloc_filespec(concatpath);
2884         if (addremove != '+')
2885                 fill_filespec(one, sha1, mode);
2886         if (addremove != '-')
2887                 fill_filespec(two, sha1, mode);
2889         diff_queue(&diff_queued_diff, one, two);
2892 void diff_change(struct diff_options *options,
2893                  unsigned old_mode, unsigned new_mode,
2894                  const unsigned char *old_sha1,
2895                  const unsigned char *new_sha1,
2896                  const char *base, const char *path) 
2898         char concatpath[PATH_MAX];
2899         struct diff_filespec *one, *two;
2901         if (options->reverse_diff) {
2902                 unsigned tmp;
2903                 const unsigned char *tmp_c;
2904                 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2905                 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2906         }
2907         if (!path) path = "";
2908         sprintf(concatpath, "%s%s", base, path);
2909         one = alloc_filespec(concatpath);
2910         two = alloc_filespec(concatpath);
2911         fill_filespec(one, old_sha1, old_mode);
2912         fill_filespec(two, new_sha1, new_mode);
2914         diff_queue(&diff_queued_diff, one, two);
2917 void diff_unmerge(struct diff_options *options,
2918                   const char *path,
2919                   unsigned mode, const unsigned char *sha1)
2921         struct diff_filespec *one, *two;
2922         one = alloc_filespec(path);
2923         two = alloc_filespec(path);
2924         fill_filespec(one, sha1, mode);
2925         diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;