Code

diff: refactor tempfile cleanup handling
[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"
11 #include "attr.h"
12 #include "run-command.h"
13 #include "utf8.h"
14 #include "userdiff.h"
16 #ifdef NO_FAST_WORKING_DIRECTORY
17 #define FAST_WORKING_DIRECTORY 0
18 #else
19 #define FAST_WORKING_DIRECTORY 1
20 #endif
22 static int diff_detect_rename_default;
23 static int diff_rename_limit_default = 200;
24 static int diff_suppress_blank_empty;
25 int diff_use_color_default = -1;
26 static const char *external_diff_cmd_cfg;
27 int diff_auto_refresh_index = 1;
28 static int diff_mnemonic_prefix;
30 static char diff_colors[][COLOR_MAXLEN] = {
31         "\033[m",       /* reset */
32         "",             /* PLAIN (normal) */
33         "\033[1m",      /* METAINFO (bold) */
34         "\033[36m",     /* FRAGINFO (cyan) */
35         "\033[31m",     /* OLD (red) */
36         "\033[32m",     /* NEW (green) */
37         "\033[33m",     /* COMMIT (yellow) */
38         "\033[41m",     /* WHITESPACE (red background) */
39 };
41 static void diff_filespec_load_driver(struct diff_filespec *one);
42 static char *run_textconv(const char *, struct diff_filespec *, size_t *);
44 static int parse_diff_color_slot(const char *var, int ofs)
45 {
46         if (!strcasecmp(var+ofs, "plain"))
47                 return DIFF_PLAIN;
48         if (!strcasecmp(var+ofs, "meta"))
49                 return DIFF_METAINFO;
50         if (!strcasecmp(var+ofs, "frag"))
51                 return DIFF_FRAGINFO;
52         if (!strcasecmp(var+ofs, "old"))
53                 return DIFF_FILE_OLD;
54         if (!strcasecmp(var+ofs, "new"))
55                 return DIFF_FILE_NEW;
56         if (!strcasecmp(var+ofs, "commit"))
57                 return DIFF_COMMIT;
58         if (!strcasecmp(var+ofs, "whitespace"))
59                 return DIFF_WHITESPACE;
60         die("bad config variable '%s'", var);
61 }
63 /*
64  * These are to give UI layer defaults.
65  * The core-level commands such as git-diff-files should
66  * never be affected by the setting of diff.renames
67  * the user happens to have in the configuration file.
68  */
69 int git_diff_ui_config(const char *var, const char *value, void *cb)
70 {
71         if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
72                 diff_use_color_default = git_config_colorbool(var, value, -1);
73                 return 0;
74         }
75         if (!strcmp(var, "diff.renames")) {
76                 if (!value)
77                         diff_detect_rename_default = DIFF_DETECT_RENAME;
78                 else if (!strcasecmp(value, "copies") ||
79                          !strcasecmp(value, "copy"))
80                         diff_detect_rename_default = DIFF_DETECT_COPY;
81                 else if (git_config_bool(var,value))
82                         diff_detect_rename_default = DIFF_DETECT_RENAME;
83                 return 0;
84         }
85         if (!strcmp(var, "diff.autorefreshindex")) {
86                 diff_auto_refresh_index = git_config_bool(var, value);
87                 return 0;
88         }
89         if (!strcmp(var, "diff.mnemonicprefix")) {
90                 diff_mnemonic_prefix = git_config_bool(var, value);
91                 return 0;
92         }
93         if (!strcmp(var, "diff.external"))
94                 return git_config_string(&external_diff_cmd_cfg, var, value);
96         return git_diff_basic_config(var, value, cb);
97 }
99 int git_diff_basic_config(const char *var, const char *value, void *cb)
101         if (!strcmp(var, "diff.renamelimit")) {
102                 diff_rename_limit_default = git_config_int(var, value);
103                 return 0;
104         }
106         switch (userdiff_config(var, value)) {
107                 case 0: break;
108                 case -1: return -1;
109                 default: return 0;
110         }
112         if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
113                 int slot = parse_diff_color_slot(var, 11);
114                 if (!value)
115                         return config_error_nonbool(var);
116                 color_parse(value, var, diff_colors[slot]);
117                 return 0;
118         }
120         /* like GNU diff's --suppress-blank-empty option  */
121         if (!strcmp(var, "diff.suppress-blank-empty")) {
122                 diff_suppress_blank_empty = git_config_bool(var, value);
123                 return 0;
124         }
126         return git_color_default_config(var, value, cb);
129 static char *quote_two(const char *one, const char *two)
131         int need_one = quote_c_style(one, NULL, NULL, 1);
132         int need_two = quote_c_style(two, NULL, NULL, 1);
133         struct strbuf res = STRBUF_INIT;
135         if (need_one + need_two) {
136                 strbuf_addch(&res, '"');
137                 quote_c_style(one, &res, NULL, 1);
138                 quote_c_style(two, &res, NULL, 1);
139                 strbuf_addch(&res, '"');
140         } else {
141                 strbuf_addstr(&res, one);
142                 strbuf_addstr(&res, two);
143         }
144         return strbuf_detach(&res, NULL);
147 static const char *external_diff(void)
149         static const char *external_diff_cmd = NULL;
150         static int done_preparing = 0;
152         if (done_preparing)
153                 return external_diff_cmd;
154         external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
155         if (!external_diff_cmd)
156                 external_diff_cmd = external_diff_cmd_cfg;
157         done_preparing = 1;
158         return external_diff_cmd;
161 static struct diff_tempfile {
162         const char *name; /* filename external diff should read from */
163         char hex[41];
164         char mode[10];
165         char tmp_path[PATH_MAX];
166 } diff_temp[2];
168 static struct diff_tempfile *claim_diff_tempfile(void) {
169         int i;
170         for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
171                 if (!diff_temp[i].name)
172                         return diff_temp + i;
173         die("BUG: diff is failing to clean up its tempfiles");
176 static int remove_tempfile_installed;
178 static void remove_tempfile(void)
180         int i;
181         for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
182                 if (diff_temp[i].name == diff_temp[i].tmp_path) {
183                         unlink(diff_temp[i].name);
184                         diff_temp[i].name = NULL;
185                 }
188 static void remove_tempfile_on_signal(int signo)
190         remove_tempfile();
191         signal(SIGINT, SIG_DFL);
192         raise(signo);
195 static int count_lines(const char *data, int size)
197         int count, ch, completely_empty = 1, nl_just_seen = 0;
198         count = 0;
199         while (0 < size--) {
200                 ch = *data++;
201                 if (ch == '\n') {
202                         count++;
203                         nl_just_seen = 1;
204                         completely_empty = 0;
205                 }
206                 else {
207                         nl_just_seen = 0;
208                         completely_empty = 0;
209                 }
210         }
211         if (completely_empty)
212                 return 0;
213         if (!nl_just_seen)
214                 count++; /* no trailing newline */
215         return count;
218 static void print_line_count(FILE *file, int count)
220         switch (count) {
221         case 0:
222                 fprintf(file, "0,0");
223                 break;
224         case 1:
225                 fprintf(file, "1");
226                 break;
227         default:
228                 fprintf(file, "1,%d", count);
229                 break;
230         }
233 static void copy_file_with_prefix(FILE *file,
234                                   int prefix, const char *data, int size,
235                                   const char *set, const char *reset)
237         int ch, nl_just_seen = 1;
238         while (0 < size--) {
239                 ch = *data++;
240                 if (nl_just_seen) {
241                         fputs(set, file);
242                         putc(prefix, file);
243                 }
244                 if (ch == '\n') {
245                         nl_just_seen = 1;
246                         fputs(reset, file);
247                 } else
248                         nl_just_seen = 0;
249                 putc(ch, file);
250         }
251         if (!nl_just_seen)
252                 fprintf(file, "%s\n\\ No newline at end of file\n", reset);
255 static void emit_rewrite_diff(const char *name_a,
256                               const char *name_b,
257                               struct diff_filespec *one,
258                               struct diff_filespec *two,
259                               const char *textconv_one,
260                               const char *textconv_two,
261                               struct diff_options *o)
263         int lc_a, lc_b;
264         int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
265         const char *name_a_tab, *name_b_tab;
266         const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
267         const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
268         const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
269         const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
270         const char *reset = diff_get_color(color_diff, DIFF_RESET);
271         static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
272         const char *a_prefix, *b_prefix;
273         const char *data_one, *data_two;
274         size_t size_one, size_two;
276         if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
277                 a_prefix = o->b_prefix;
278                 b_prefix = o->a_prefix;
279         } else {
280                 a_prefix = o->a_prefix;
281                 b_prefix = o->b_prefix;
282         }
284         name_a += (*name_a == '/');
285         name_b += (*name_b == '/');
286         name_a_tab = strchr(name_a, ' ') ? "\t" : "";
287         name_b_tab = strchr(name_b, ' ') ? "\t" : "";
289         strbuf_reset(&a_name);
290         strbuf_reset(&b_name);
291         quote_two_c_style(&a_name, a_prefix, name_a, 0);
292         quote_two_c_style(&b_name, b_prefix, name_b, 0);
294         diff_populate_filespec(one, 0);
295         diff_populate_filespec(two, 0);
296         if (textconv_one) {
297                 data_one = run_textconv(textconv_one, one, &size_one);
298                 if (!data_one)
299                         die("unable to read files to diff");
300         }
301         else {
302                 data_one = one->data;
303                 size_one = one->size;
304         }
305         if (textconv_two) {
306                 data_two = run_textconv(textconv_two, two, &size_two);
307                 if (!data_two)
308                         die("unable to read files to diff");
309         }
310         else {
311                 data_two = two->data;
312                 size_two = two->size;
313         }
315         lc_a = count_lines(data_one, size_one);
316         lc_b = count_lines(data_two, size_two);
317         fprintf(o->file,
318                 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
319                 metainfo, a_name.buf, name_a_tab, reset,
320                 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
321         print_line_count(o->file, lc_a);
322         fprintf(o->file, " +");
323         print_line_count(o->file, lc_b);
324         fprintf(o->file, " @@%s\n", reset);
325         if (lc_a)
326                 copy_file_with_prefix(o->file, '-', data_one, size_one, old, reset);
327         if (lc_b)
328                 copy_file_with_prefix(o->file, '+', data_two, size_two, new, reset);
331 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
333         if (!DIFF_FILE_VALID(one)) {
334                 mf->ptr = (char *)""; /* does not matter */
335                 mf->size = 0;
336                 return 0;
337         }
338         else if (diff_populate_filespec(one, 0))
339                 return -1;
341         mf->ptr = one->data;
342         mf->size = one->size;
343         return 0;
346 struct diff_words_buffer {
347         mmfile_t text;
348         long alloc;
349         long current; /* output pointer */
350         int suppressed_newline;
351 };
353 static void diff_words_append(char *line, unsigned long len,
354                 struct diff_words_buffer *buffer)
356         if (buffer->text.size + len > buffer->alloc) {
357                 buffer->alloc = (buffer->text.size + len) * 3 / 2;
358                 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
359         }
360         line++;
361         len--;
362         memcpy(buffer->text.ptr + buffer->text.size, line, len);
363         buffer->text.size += len;
366 struct diff_words_data {
367         struct diff_words_buffer minus, plus;
368         FILE *file;
369 };
371 static void print_word(FILE *file, struct diff_words_buffer *buffer, int len, int color,
372                 int suppress_newline)
374         const char *ptr;
375         int eol = 0;
377         if (len == 0)
378                 return;
380         ptr  = buffer->text.ptr + buffer->current;
381         buffer->current += len;
383         if (ptr[len - 1] == '\n') {
384                 eol = 1;
385                 len--;
386         }
388         fputs(diff_get_color(1, color), file);
389         fwrite(ptr, len, 1, file);
390         fputs(diff_get_color(1, DIFF_RESET), file);
392         if (eol) {
393                 if (suppress_newline)
394                         buffer->suppressed_newline = 1;
395                 else
396                         putc('\n', file);
397         }
400 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
402         struct diff_words_data *diff_words = priv;
404         if (diff_words->minus.suppressed_newline) {
405                 if (line[0] != '+')
406                         putc('\n', diff_words->file);
407                 diff_words->minus.suppressed_newline = 0;
408         }
410         len--;
411         switch (line[0]) {
412                 case '-':
413                         print_word(diff_words->file,
414                                    &diff_words->minus, len, DIFF_FILE_OLD, 1);
415                         break;
416                 case '+':
417                         print_word(diff_words->file,
418                                    &diff_words->plus, len, DIFF_FILE_NEW, 0);
419                         break;
420                 case ' ':
421                         print_word(diff_words->file,
422                                    &diff_words->plus, len, DIFF_PLAIN, 0);
423                         diff_words->minus.current += len;
424                         break;
425         }
428 /* this executes the word diff on the accumulated buffers */
429 static void diff_words_show(struct diff_words_data *diff_words)
431         xpparam_t xpp;
432         xdemitconf_t xecfg;
433         xdemitcb_t ecb;
434         mmfile_t minus, plus;
435         int i;
437         memset(&xpp, 0, sizeof(xpp));
438         memset(&xecfg, 0, sizeof(xecfg));
439         minus.size = diff_words->minus.text.size;
440         minus.ptr = xmalloc(minus.size);
441         memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
442         for (i = 0; i < minus.size; i++)
443                 if (isspace(minus.ptr[i]))
444                         minus.ptr[i] = '\n';
445         diff_words->minus.current = 0;
447         plus.size = diff_words->plus.text.size;
448         plus.ptr = xmalloc(plus.size);
449         memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
450         for (i = 0; i < plus.size; i++)
451                 if (isspace(plus.ptr[i]))
452                         plus.ptr[i] = '\n';
453         diff_words->plus.current = 0;
455         xpp.flags = XDF_NEED_MINIMAL;
456         xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
457         xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
458                       &xpp, &xecfg, &ecb);
459         free(minus.ptr);
460         free(plus.ptr);
461         diff_words->minus.text.size = diff_words->plus.text.size = 0;
463         if (diff_words->minus.suppressed_newline) {
464                 putc('\n', diff_words->file);
465                 diff_words->minus.suppressed_newline = 0;
466         }
469 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
471 struct emit_callback {
472         int nparents, color_diff;
473         unsigned ws_rule;
474         sane_truncate_fn truncate;
475         const char **label_path;
476         struct diff_words_data *diff_words;
477         int *found_changesp;
478         FILE *file;
479 };
481 static void free_diff_words_data(struct emit_callback *ecbdata)
483         if (ecbdata->diff_words) {
484                 /* flush buffers */
485                 if (ecbdata->diff_words->minus.text.size ||
486                                 ecbdata->diff_words->plus.text.size)
487                         diff_words_show(ecbdata->diff_words);
489                 free (ecbdata->diff_words->minus.text.ptr);
490                 free (ecbdata->diff_words->plus.text.ptr);
491                 free(ecbdata->diff_words);
492                 ecbdata->diff_words = NULL;
493         }
496 const char *diff_get_color(int diff_use_color, enum color_diff ix)
498         if (diff_use_color)
499                 return diff_colors[ix];
500         return "";
503 static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
505         int has_trailing_newline, has_trailing_carriage_return;
507         has_trailing_newline = (len > 0 && line[len-1] == '\n');
508         if (has_trailing_newline)
509                 len--;
510         has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
511         if (has_trailing_carriage_return)
512                 len--;
514         fputs(set, file);
515         fwrite(line, len, 1, file);
516         fputs(reset, file);
517         if (has_trailing_carriage_return)
518                 fputc('\r', file);
519         if (has_trailing_newline)
520                 fputc('\n', file);
523 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
525         const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
526         const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
528         if (!*ws)
529                 emit_line(ecbdata->file, set, reset, line, len);
530         else {
531                 /* Emit just the prefix, then the rest. */
532                 emit_line(ecbdata->file, set, reset, line, ecbdata->nparents);
533                 ws_check_emit(line + ecbdata->nparents,
534                               len - ecbdata->nparents, ecbdata->ws_rule,
535                               ecbdata->file, set, reset, ws);
536         }
539 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
541         const char *cp;
542         unsigned long allot;
543         size_t l = len;
545         if (ecb->truncate)
546                 return ecb->truncate(line, len);
547         cp = line;
548         allot = l;
549         while (0 < l) {
550                 (void) utf8_width(&cp, &l);
551                 if (!cp)
552                         break; /* truncated in the middle? */
553         }
554         return allot - l;
557 static void fn_out_consume(void *priv, char *line, unsigned long len)
559         int i;
560         int color;
561         struct emit_callback *ecbdata = priv;
562         const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
563         const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
564         const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
566         *(ecbdata->found_changesp) = 1;
568         if (ecbdata->label_path[0]) {
569                 const char *name_a_tab, *name_b_tab;
571                 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
572                 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
574                 fprintf(ecbdata->file, "%s--- %s%s%s\n",
575                         meta, ecbdata->label_path[0], reset, name_a_tab);
576                 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
577                         meta, ecbdata->label_path[1], reset, name_b_tab);
578                 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
579         }
581         if (diff_suppress_blank_empty
582             && len == 2 && line[0] == ' ' && line[1] == '\n') {
583                 line[0] = '\n';
584                 len = 1;
585         }
587         /* This is not really necessary for now because
588          * this codepath only deals with two-way diffs.
589          */
590         for (i = 0; i < len && line[i] == '@'; i++)
591                 ;
592         if (2 <= i && i < len && line[i] == ' ') {
593                 ecbdata->nparents = i - 1;
594                 len = sane_truncate_line(ecbdata, line, len);
595                 emit_line(ecbdata->file,
596                           diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
597                           reset, line, len);
598                 if (line[len-1] != '\n')
599                         putc('\n', ecbdata->file);
600                 return;
601         }
603         if (len < ecbdata->nparents) {
604                 emit_line(ecbdata->file, reset, reset, line, len);
605                 return;
606         }
608         color = DIFF_PLAIN;
609         if (ecbdata->diff_words && ecbdata->nparents != 1)
610                 /* fall back to normal diff */
611                 free_diff_words_data(ecbdata);
612         if (ecbdata->diff_words) {
613                 if (line[0] == '-') {
614                         diff_words_append(line, len,
615                                           &ecbdata->diff_words->minus);
616                         return;
617                 } else if (line[0] == '+') {
618                         diff_words_append(line, len,
619                                           &ecbdata->diff_words->plus);
620                         return;
621                 }
622                 if (ecbdata->diff_words->minus.text.size ||
623                     ecbdata->diff_words->plus.text.size)
624                         diff_words_show(ecbdata->diff_words);
625                 line++;
626                 len--;
627                 emit_line(ecbdata->file, plain, reset, line, len);
628                 return;
629         }
630         for (i = 0; i < ecbdata->nparents && len; i++) {
631                 if (line[i] == '-')
632                         color = DIFF_FILE_OLD;
633                 else if (line[i] == '+')
634                         color = DIFF_FILE_NEW;
635         }
637         if (color != DIFF_FILE_NEW) {
638                 emit_line(ecbdata->file,
639                           diff_get_color(ecbdata->color_diff, color),
640                           reset, line, len);
641                 return;
642         }
643         emit_add_line(reset, ecbdata, line, len);
646 static char *pprint_rename(const char *a, const char *b)
648         const char *old = a;
649         const char *new = b;
650         struct strbuf name = STRBUF_INIT;
651         int pfx_length, sfx_length;
652         int len_a = strlen(a);
653         int len_b = strlen(b);
654         int a_midlen, b_midlen;
655         int qlen_a = quote_c_style(a, NULL, NULL, 0);
656         int qlen_b = quote_c_style(b, NULL, NULL, 0);
658         if (qlen_a || qlen_b) {
659                 quote_c_style(a, &name, NULL, 0);
660                 strbuf_addstr(&name, " => ");
661                 quote_c_style(b, &name, NULL, 0);
662                 return strbuf_detach(&name, NULL);
663         }
665         /* Find common prefix */
666         pfx_length = 0;
667         while (*old && *new && *old == *new) {
668                 if (*old == '/')
669                         pfx_length = old - a + 1;
670                 old++;
671                 new++;
672         }
674         /* Find common suffix */
675         old = a + len_a;
676         new = b + len_b;
677         sfx_length = 0;
678         while (a <= old && b <= new && *old == *new) {
679                 if (*old == '/')
680                         sfx_length = len_a - (old - a);
681                 old--;
682                 new--;
683         }
685         /*
686          * pfx{mid-a => mid-b}sfx
687          * {pfx-a => pfx-b}sfx
688          * pfx{sfx-a => sfx-b}
689          * name-a => name-b
690          */
691         a_midlen = len_a - pfx_length - sfx_length;
692         b_midlen = len_b - pfx_length - sfx_length;
693         if (a_midlen < 0)
694                 a_midlen = 0;
695         if (b_midlen < 0)
696                 b_midlen = 0;
698         strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
699         if (pfx_length + sfx_length) {
700                 strbuf_add(&name, a, pfx_length);
701                 strbuf_addch(&name, '{');
702         }
703         strbuf_add(&name, a + pfx_length, a_midlen);
704         strbuf_addstr(&name, " => ");
705         strbuf_add(&name, b + pfx_length, b_midlen);
706         if (pfx_length + sfx_length) {
707                 strbuf_addch(&name, '}');
708                 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
709         }
710         return strbuf_detach(&name, NULL);
713 struct diffstat_t {
714         int nr;
715         int alloc;
716         struct diffstat_file {
717                 char *from_name;
718                 char *name;
719                 char *print_name;
720                 unsigned is_unmerged:1;
721                 unsigned is_binary:1;
722                 unsigned is_renamed:1;
723                 unsigned int added, deleted;
724         } **files;
725 };
727 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
728                                           const char *name_a,
729                                           const char *name_b)
731         struct diffstat_file *x;
732         x = xcalloc(sizeof (*x), 1);
733         if (diffstat->nr == diffstat->alloc) {
734                 diffstat->alloc = alloc_nr(diffstat->alloc);
735                 diffstat->files = xrealloc(diffstat->files,
736                                 diffstat->alloc * sizeof(x));
737         }
738         diffstat->files[diffstat->nr++] = x;
739         if (name_b) {
740                 x->from_name = xstrdup(name_a);
741                 x->name = xstrdup(name_b);
742                 x->is_renamed = 1;
743         }
744         else {
745                 x->from_name = NULL;
746                 x->name = xstrdup(name_a);
747         }
748         return x;
751 static void diffstat_consume(void *priv, char *line, unsigned long len)
753         struct diffstat_t *diffstat = priv;
754         struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
756         if (line[0] == '+')
757                 x->added++;
758         else if (line[0] == '-')
759                 x->deleted++;
762 const char mime_boundary_leader[] = "------------";
764 static int scale_linear(int it, int width, int max_change)
766         /*
767          * make sure that at least one '-' is printed if there were deletions,
768          * and likewise for '+'.
769          */
770         if (max_change < 2)
771                 return it;
772         return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
775 static void show_name(FILE *file,
776                       const char *prefix, const char *name, int len,
777                       const char *reset, const char *set)
779         fprintf(file, " %s%s%-*s%s |", set, prefix, len, name, reset);
782 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
784         if (cnt <= 0)
785                 return;
786         fprintf(file, "%s", set);
787         while (cnt--)
788                 putc(ch, file);
789         fprintf(file, "%s", reset);
792 static void fill_print_name(struct diffstat_file *file)
794         char *pname;
796         if (file->print_name)
797                 return;
799         if (!file->is_renamed) {
800                 struct strbuf buf = STRBUF_INIT;
801                 if (quote_c_style(file->name, &buf, NULL, 0)) {
802                         pname = strbuf_detach(&buf, NULL);
803                 } else {
804                         pname = file->name;
805                         strbuf_release(&buf);
806                 }
807         } else {
808                 pname = pprint_rename(file->from_name, file->name);
809         }
810         file->print_name = pname;
813 static void show_stats(struct diffstat_t* data, struct diff_options *options)
815         int i, len, add, del, total, adds = 0, dels = 0;
816         int max_change = 0, max_len = 0;
817         int total_files = data->nr;
818         int width, name_width;
819         const char *reset, *set, *add_c, *del_c;
821         if (data->nr == 0)
822                 return;
824         width = options->stat_width ? options->stat_width : 80;
825         name_width = options->stat_name_width ? options->stat_name_width : 50;
827         /* Sanity: give at least 5 columns to the graph,
828          * but leave at least 10 columns for the name.
829          */
830         if (width < 25)
831                 width = 25;
832         if (name_width < 10)
833                 name_width = 10;
834         else if (width < name_width + 15)
835                 name_width = width - 15;
837         /* Find the longest filename and max number of changes */
838         reset = diff_get_color_opt(options, DIFF_RESET);
839         set   = diff_get_color_opt(options, DIFF_PLAIN);
840         add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
841         del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
843         for (i = 0; i < data->nr; i++) {
844                 struct diffstat_file *file = data->files[i];
845                 int change = file->added + file->deleted;
846                 fill_print_name(file);
847                 len = strlen(file->print_name);
848                 if (max_len < len)
849                         max_len = len;
851                 if (file->is_binary || file->is_unmerged)
852                         continue;
853                 if (max_change < change)
854                         max_change = change;
855         }
857         /* Compute the width of the graph part;
858          * 10 is for one blank at the beginning of the line plus
859          * " | count " between the name and the graph.
860          *
861          * From here on, name_width is the width of the name area,
862          * and width is the width of the graph area.
863          */
864         name_width = (name_width < max_len) ? name_width : max_len;
865         if (width < (name_width + 10) + max_change)
866                 width = width - (name_width + 10);
867         else
868                 width = max_change;
870         for (i = 0; i < data->nr; i++) {
871                 const char *prefix = "";
872                 char *name = data->files[i]->print_name;
873                 int added = data->files[i]->added;
874                 int deleted = data->files[i]->deleted;
875                 int name_len;
877                 /*
878                  * "scale" the filename
879                  */
880                 len = name_width;
881                 name_len = strlen(name);
882                 if (name_width < name_len) {
883                         char *slash;
884                         prefix = "...";
885                         len -= 3;
886                         name += name_len - len;
887                         slash = strchr(name, '/');
888                         if (slash)
889                                 name = slash;
890                 }
892                 if (data->files[i]->is_binary) {
893                         show_name(options->file, prefix, name, len, reset, set);
894                         fprintf(options->file, "  Bin ");
895                         fprintf(options->file, "%s%d%s", del_c, deleted, reset);
896                         fprintf(options->file, " -> ");
897                         fprintf(options->file, "%s%d%s", add_c, added, reset);
898                         fprintf(options->file, " bytes");
899                         fprintf(options->file, "\n");
900                         continue;
901                 }
902                 else if (data->files[i]->is_unmerged) {
903                         show_name(options->file, prefix, name, len, reset, set);
904                         fprintf(options->file, "  Unmerged\n");
905                         continue;
906                 }
907                 else if (!data->files[i]->is_renamed &&
908                          (added + deleted == 0)) {
909                         total_files--;
910                         continue;
911                 }
913                 /*
914                  * scale the add/delete
915                  */
916                 add = added;
917                 del = deleted;
918                 total = add + del;
919                 adds += add;
920                 dels += del;
922                 if (width <= max_change) {
923                         add = scale_linear(add, width, max_change);
924                         del = scale_linear(del, width, max_change);
925                         total = add + del;
926                 }
927                 show_name(options->file, prefix, name, len, reset, set);
928                 fprintf(options->file, "%5d%s", added + deleted,
929                                 added + deleted ? " " : "");
930                 show_graph(options->file, '+', add, add_c, reset);
931                 show_graph(options->file, '-', del, del_c, reset);
932                 fprintf(options->file, "\n");
933         }
934         fprintf(options->file,
935                "%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
936                set, total_files, adds, dels, reset);
939 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
941         int i, adds = 0, dels = 0, total_files = data->nr;
943         if (data->nr == 0)
944                 return;
946         for (i = 0; i < data->nr; i++) {
947                 if (!data->files[i]->is_binary &&
948                     !data->files[i]->is_unmerged) {
949                         int added = data->files[i]->added;
950                         int deleted= data->files[i]->deleted;
951                         if (!data->files[i]->is_renamed &&
952                             (added + deleted == 0)) {
953                                 total_files--;
954                         } else {
955                                 adds += added;
956                                 dels += deleted;
957                         }
958                 }
959         }
960         fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
961                total_files, adds, dels);
964 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
966         int i;
968         if (data->nr == 0)
969                 return;
971         for (i = 0; i < data->nr; i++) {
972                 struct diffstat_file *file = data->files[i];
974                 if (file->is_binary)
975                         fprintf(options->file, "-\t-\t");
976                 else
977                         fprintf(options->file,
978                                 "%d\t%d\t", file->added, file->deleted);
979                 if (options->line_termination) {
980                         fill_print_name(file);
981                         if (!file->is_renamed)
982                                 write_name_quoted(file->name, options->file,
983                                                   options->line_termination);
984                         else {
985                                 fputs(file->print_name, options->file);
986                                 putc(options->line_termination, options->file);
987                         }
988                 } else {
989                         if (file->is_renamed) {
990                                 putc('\0', options->file);
991                                 write_name_quoted(file->from_name, options->file, '\0');
992                         }
993                         write_name_quoted(file->name, options->file, '\0');
994                 }
995         }
998 struct dirstat_file {
999         const char *name;
1000         unsigned long changed;
1001 };
1003 struct dirstat_dir {
1004         struct dirstat_file *files;
1005         int alloc, nr, percent, cumulative;
1006 };
1008 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1010         unsigned long this_dir = 0;
1011         unsigned int sources = 0;
1013         while (dir->nr) {
1014                 struct dirstat_file *f = dir->files;
1015                 int namelen = strlen(f->name);
1016                 unsigned long this;
1017                 char *slash;
1019                 if (namelen < baselen)
1020                         break;
1021                 if (memcmp(f->name, base, baselen))
1022                         break;
1023                 slash = strchr(f->name + baselen, '/');
1024                 if (slash) {
1025                         int newbaselen = slash + 1 - f->name;
1026                         this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1027                         sources++;
1028                 } else {
1029                         this = f->changed;
1030                         dir->files++;
1031                         dir->nr--;
1032                         sources += 2;
1033                 }
1034                 this_dir += this;
1035         }
1037         /*
1038          * We don't report dirstat's for
1039          *  - the top level
1040          *  - or cases where everything came from a single directory
1041          *    under this directory (sources == 1).
1042          */
1043         if (baselen && sources != 1) {
1044                 int permille = this_dir * 1000 / changed;
1045                 if (permille) {
1046                         int percent = permille / 10;
1047                         if (percent >= dir->percent) {
1048                                 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1049                                 if (!dir->cumulative)
1050                                         return 0;
1051                         }
1052                 }
1053         }
1054         return this_dir;
1057 static int dirstat_compare(const void *_a, const void *_b)
1059         const struct dirstat_file *a = _a;
1060         const struct dirstat_file *b = _b;
1061         return strcmp(a->name, b->name);
1064 static void show_dirstat(struct diff_options *options)
1066         int i;
1067         unsigned long changed;
1068         struct dirstat_dir dir;
1069         struct diff_queue_struct *q = &diff_queued_diff;
1071         dir.files = NULL;
1072         dir.alloc = 0;
1073         dir.nr = 0;
1074         dir.percent = options->dirstat_percent;
1075         dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1077         changed = 0;
1078         for (i = 0; i < q->nr; i++) {
1079                 struct diff_filepair *p = q->queue[i];
1080                 const char *name;
1081                 unsigned long copied, added, damage;
1083                 name = p->one->path ? p->one->path : p->two->path;
1085                 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1086                         diff_populate_filespec(p->one, 0);
1087                         diff_populate_filespec(p->two, 0);
1088                         diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1089                                                &copied, &added);
1090                         diff_free_filespec_data(p->one);
1091                         diff_free_filespec_data(p->two);
1092                 } else if (DIFF_FILE_VALID(p->one)) {
1093                         diff_populate_filespec(p->one, 1);
1094                         copied = added = 0;
1095                         diff_free_filespec_data(p->one);
1096                 } else if (DIFF_FILE_VALID(p->two)) {
1097                         diff_populate_filespec(p->two, 1);
1098                         copied = 0;
1099                         added = p->two->size;
1100                         diff_free_filespec_data(p->two);
1101                 } else
1102                         continue;
1104                 /*
1105                  * Original minus copied is the removed material,
1106                  * added is the new material.  They are both damages
1107                  * made to the preimage. In --dirstat-by-file mode, count
1108                  * damaged files, not damaged lines. This is done by
1109                  * counting only a single damaged line per file.
1110                  */
1111                 damage = (p->one->size - copied) + added;
1112                 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1113                         damage = 1;
1115                 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1116                 dir.files[dir.nr].name = name;
1117                 dir.files[dir.nr].changed = damage;
1118                 changed += damage;
1119                 dir.nr++;
1120         }
1122         /* This can happen even with many files, if everything was renames */
1123         if (!changed)
1124                 return;
1126         /* Show all directories with more than x% of the changes */
1127         qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1128         gather_dirstat(options->file, &dir, changed, "", 0);
1131 static void free_diffstat_info(struct diffstat_t *diffstat)
1133         int i;
1134         for (i = 0; i < diffstat->nr; i++) {
1135                 struct diffstat_file *f = diffstat->files[i];
1136                 if (f->name != f->print_name)
1137                         free(f->print_name);
1138                 free(f->name);
1139                 free(f->from_name);
1140                 free(f);
1141         }
1142         free(diffstat->files);
1145 struct checkdiff_t {
1146         const char *filename;
1147         int lineno;
1148         struct diff_options *o;
1149         unsigned ws_rule;
1150         unsigned status;
1151         int trailing_blanks_start;
1152 };
1154 static int is_conflict_marker(const char *line, unsigned long len)
1156         char firstchar;
1157         int cnt;
1159         if (len < 8)
1160                 return 0;
1161         firstchar = line[0];
1162         switch (firstchar) {
1163         case '=': case '>': case '<':
1164                 break;
1165         default:
1166                 return 0;
1167         }
1168         for (cnt = 1; cnt < 7; cnt++)
1169                 if (line[cnt] != firstchar)
1170                         return 0;
1171         /* line[0] thru line[6] are same as firstchar */
1172         if (firstchar == '=') {
1173                 /* divider between ours and theirs? */
1174                 if (len != 8 || line[7] != '\n')
1175                         return 0;
1176         } else if (len < 8 || !isspace(line[7])) {
1177                 /* not divider before ours nor after theirs */
1178                 return 0;
1179         }
1180         return 1;
1183 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1185         struct checkdiff_t *data = priv;
1186         int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1187         const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1188         const char *reset = diff_get_color(color_diff, DIFF_RESET);
1189         const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1190         char *err;
1192         if (line[0] == '+') {
1193                 unsigned bad;
1194                 data->lineno++;
1195                 if (!ws_blank_line(line + 1, len - 1, data->ws_rule))
1196                         data->trailing_blanks_start = 0;
1197                 else if (!data->trailing_blanks_start)
1198                         data->trailing_blanks_start = data->lineno;
1199                 if (is_conflict_marker(line + 1, len - 1)) {
1200                         data->status |= 1;
1201                         fprintf(data->o->file,
1202                                 "%s:%d: leftover conflict marker\n",
1203                                 data->filename, data->lineno);
1204                 }
1205                 bad = ws_check(line + 1, len - 1, data->ws_rule);
1206                 if (!bad)
1207                         return;
1208                 data->status |= bad;
1209                 err = whitespace_error_string(bad);
1210                 fprintf(data->o->file, "%s:%d: %s.\n",
1211                         data->filename, data->lineno, err);
1212                 free(err);
1213                 emit_line(data->o->file, set, reset, line, 1);
1214                 ws_check_emit(line + 1, len - 1, data->ws_rule,
1215                               data->o->file, set, reset, ws);
1216         } else if (line[0] == ' ') {
1217                 data->lineno++;
1218                 data->trailing_blanks_start = 0;
1219         } else if (line[0] == '@') {
1220                 char *plus = strchr(line, '+');
1221                 if (plus)
1222                         data->lineno = strtol(plus, NULL, 10) - 1;
1223                 else
1224                         die("invalid diff");
1225                 data->trailing_blanks_start = 0;
1226         }
1229 static unsigned char *deflate_it(char *data,
1230                                  unsigned long size,
1231                                  unsigned long *result_size)
1233         int bound;
1234         unsigned char *deflated;
1235         z_stream stream;
1237         memset(&stream, 0, sizeof(stream));
1238         deflateInit(&stream, zlib_compression_level);
1239         bound = deflateBound(&stream, size);
1240         deflated = xmalloc(bound);
1241         stream.next_out = deflated;
1242         stream.avail_out = bound;
1244         stream.next_in = (unsigned char *)data;
1245         stream.avail_in = size;
1246         while (deflate(&stream, Z_FINISH) == Z_OK)
1247                 ; /* nothing */
1248         deflateEnd(&stream);
1249         *result_size = stream.total_out;
1250         return deflated;
1253 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1255         void *cp;
1256         void *delta;
1257         void *deflated;
1258         void *data;
1259         unsigned long orig_size;
1260         unsigned long delta_size;
1261         unsigned long deflate_size;
1262         unsigned long data_size;
1264         /* We could do deflated delta, or we could do just deflated two,
1265          * whichever is smaller.
1266          */
1267         delta = NULL;
1268         deflated = deflate_it(two->ptr, two->size, &deflate_size);
1269         if (one->size && two->size) {
1270                 delta = diff_delta(one->ptr, one->size,
1271                                    two->ptr, two->size,
1272                                    &delta_size, deflate_size);
1273                 if (delta) {
1274                         void *to_free = delta;
1275                         orig_size = delta_size;
1276                         delta = deflate_it(delta, delta_size, &delta_size);
1277                         free(to_free);
1278                 }
1279         }
1281         if (delta && delta_size < deflate_size) {
1282                 fprintf(file, "delta %lu\n", orig_size);
1283                 free(deflated);
1284                 data = delta;
1285                 data_size = delta_size;
1286         }
1287         else {
1288                 fprintf(file, "literal %lu\n", two->size);
1289                 free(delta);
1290                 data = deflated;
1291                 data_size = deflate_size;
1292         }
1294         /* emit data encoded in base85 */
1295         cp = data;
1296         while (data_size) {
1297                 int bytes = (52 < data_size) ? 52 : data_size;
1298                 char line[70];
1299                 data_size -= bytes;
1300                 if (bytes <= 26)
1301                         line[0] = bytes + 'A' - 1;
1302                 else
1303                         line[0] = bytes - 26 + 'a' - 1;
1304                 encode_85(line + 1, cp, bytes);
1305                 cp = (char *) cp + bytes;
1306                 fputs(line, file);
1307                 fputc('\n', file);
1308         }
1309         fprintf(file, "\n");
1310         free(data);
1313 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1315         fprintf(file, "GIT binary patch\n");
1316         emit_binary_diff_body(file, one, two);
1317         emit_binary_diff_body(file, two, one);
1320 static void diff_filespec_load_driver(struct diff_filespec *one)
1322         if (!one->driver)
1323                 one->driver = userdiff_find_by_path(one->path);
1324         if (!one->driver)
1325                 one->driver = userdiff_find_by_name("default");
1328 int diff_filespec_is_binary(struct diff_filespec *one)
1330         if (one->is_binary == -1) {
1331                 diff_filespec_load_driver(one);
1332                 if (one->driver->binary != -1)
1333                         one->is_binary = one->driver->binary;
1334                 else {
1335                         if (!one->data && DIFF_FILE_VALID(one))
1336                                 diff_populate_filespec(one, 0);
1337                         if (one->data)
1338                                 one->is_binary = buffer_is_binary(one->data,
1339                                                 one->size);
1340                         if (one->is_binary == -1)
1341                                 one->is_binary = 0;
1342                 }
1343         }
1344         return one->is_binary;
1347 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1349         diff_filespec_load_driver(one);
1350         return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1353 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1355         if (!options->a_prefix)
1356                 options->a_prefix = a;
1357         if (!options->b_prefix)
1358                 options->b_prefix = b;
1361 static const char *get_textconv(struct diff_filespec *one)
1363         if (!DIFF_FILE_VALID(one))
1364                 return NULL;
1365         if (!S_ISREG(one->mode))
1366                 return NULL;
1367         diff_filespec_load_driver(one);
1368         return one->driver->textconv;
1371 static void builtin_diff(const char *name_a,
1372                          const char *name_b,
1373                          struct diff_filespec *one,
1374                          struct diff_filespec *two,
1375                          const char *xfrm_msg,
1376                          struct diff_options *o,
1377                          int complete_rewrite)
1379         mmfile_t mf1, mf2;
1380         const char *lbl[2];
1381         char *a_one, *b_two;
1382         const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1383         const char *reset = diff_get_color_opt(o, DIFF_RESET);
1384         const char *a_prefix, *b_prefix;
1385         const char *textconv_one = NULL, *textconv_two = NULL;
1387         if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1388                 textconv_one = get_textconv(one);
1389                 textconv_two = get_textconv(two);
1390         }
1392         diff_set_mnemonic_prefix(o, "a/", "b/");
1393         if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1394                 a_prefix = o->b_prefix;
1395                 b_prefix = o->a_prefix;
1396         } else {
1397                 a_prefix = o->a_prefix;
1398                 b_prefix = o->b_prefix;
1399         }
1401         /* Never use a non-valid filename anywhere if at all possible */
1402         name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1403         name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1405         a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1406         b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1407         lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1408         lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1409         fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1410         if (lbl[0][0] == '/') {
1411                 /* /dev/null */
1412                 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1413                 if (xfrm_msg && xfrm_msg[0])
1414                         fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1415         }
1416         else if (lbl[1][0] == '/') {
1417                 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1418                 if (xfrm_msg && xfrm_msg[0])
1419                         fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1420         }
1421         else {
1422                 if (one->mode != two->mode) {
1423                         fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1424                         fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1425                 }
1426                 if (xfrm_msg && xfrm_msg[0])
1427                         fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1428                 /*
1429                  * we do not run diff between different kind
1430                  * of objects.
1431                  */
1432                 if ((one->mode ^ two->mode) & S_IFMT)
1433                         goto free_ab_and_return;
1434                 if (complete_rewrite &&
1435                     (textconv_one || !diff_filespec_is_binary(one)) &&
1436                     (textconv_two || !diff_filespec_is_binary(two))) {
1437                         emit_rewrite_diff(name_a, name_b, one, two,
1438                                                 textconv_one, textconv_two, o);
1439                         o->found_changes = 1;
1440                         goto free_ab_and_return;
1441                 }
1442         }
1444         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1445                 die("unable to read files to diff");
1447         if (!DIFF_OPT_TST(o, TEXT) &&
1448             ( (diff_filespec_is_binary(one) && !textconv_one) ||
1449               (diff_filespec_is_binary(two) && !textconv_two) )) {
1450                 /* Quite common confusing case */
1451                 if (mf1.size == mf2.size &&
1452                     !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1453                         goto free_ab_and_return;
1454                 if (DIFF_OPT_TST(o, BINARY))
1455                         emit_binary_diff(o->file, &mf1, &mf2);
1456                 else
1457                         fprintf(o->file, "Binary files %s and %s differ\n",
1458                                 lbl[0], lbl[1]);
1459                 o->found_changes = 1;
1460         }
1461         else {
1462                 /* Crazy xdl interfaces.. */
1463                 const char *diffopts = getenv("GIT_DIFF_OPTS");
1464                 xpparam_t xpp;
1465                 xdemitconf_t xecfg;
1466                 xdemitcb_t ecb;
1467                 struct emit_callback ecbdata;
1468                 const struct userdiff_funcname *pe;
1470                 if (textconv_one) {
1471                         size_t size;
1472                         mf1.ptr = run_textconv(textconv_one, one, &size);
1473                         if (!mf1.ptr)
1474                                 die("unable to read files to diff");
1475                         mf1.size = size;
1476                 }
1477                 if (textconv_two) {
1478                         size_t size;
1479                         mf2.ptr = run_textconv(textconv_two, two, &size);
1480                         if (!mf2.ptr)
1481                                 die("unable to read files to diff");
1482                         mf2.size = size;
1483                 }
1485                 pe = diff_funcname_pattern(one);
1486                 if (!pe)
1487                         pe = diff_funcname_pattern(two);
1489                 memset(&xpp, 0, sizeof(xpp));
1490                 memset(&xecfg, 0, sizeof(xecfg));
1491                 memset(&ecbdata, 0, sizeof(ecbdata));
1492                 ecbdata.label_path = lbl;
1493                 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1494                 ecbdata.found_changesp = &o->found_changes;
1495                 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1496                 ecbdata.file = o->file;
1497                 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1498                 xecfg.ctxlen = o->context;
1499                 xecfg.interhunkctxlen = o->interhunkcontext;
1500                 xecfg.flags = XDL_EMIT_FUNCNAMES;
1501                 if (pe)
1502                         xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1503                 if (!diffopts)
1504                         ;
1505                 else if (!prefixcmp(diffopts, "--unified="))
1506                         xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1507                 else if (!prefixcmp(diffopts, "-u"))
1508                         xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1509                 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1510                         ecbdata.diff_words =
1511                                 xcalloc(1, sizeof(struct diff_words_data));
1512                         ecbdata.diff_words->file = o->file;
1513                 }
1514                 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1515                               &xpp, &xecfg, &ecb);
1516                 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1517                         free_diff_words_data(&ecbdata);
1518                 if (textconv_one)
1519                         free(mf1.ptr);
1520                 if (textconv_two)
1521                         free(mf2.ptr);
1522         }
1524  free_ab_and_return:
1525         diff_free_filespec_data(one);
1526         diff_free_filespec_data(two);
1527         free(a_one);
1528         free(b_two);
1529         return;
1532 static void builtin_diffstat(const char *name_a, const char *name_b,
1533                              struct diff_filespec *one,
1534                              struct diff_filespec *two,
1535                              struct diffstat_t *diffstat,
1536                              struct diff_options *o,
1537                              int complete_rewrite)
1539         mmfile_t mf1, mf2;
1540         struct diffstat_file *data;
1542         data = diffstat_add(diffstat, name_a, name_b);
1544         if (!one || !two) {
1545                 data->is_unmerged = 1;
1546                 return;
1547         }
1548         if (complete_rewrite) {
1549                 diff_populate_filespec(one, 0);
1550                 diff_populate_filespec(two, 0);
1551                 data->deleted = count_lines(one->data, one->size);
1552                 data->added = count_lines(two->data, two->size);
1553                 goto free_and_return;
1554         }
1555         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1556                 die("unable to read files to diff");
1558         if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1559                 data->is_binary = 1;
1560                 data->added = mf2.size;
1561                 data->deleted = mf1.size;
1562         } else {
1563                 /* Crazy xdl interfaces.. */
1564                 xpparam_t xpp;
1565                 xdemitconf_t xecfg;
1566                 xdemitcb_t ecb;
1568                 memset(&xpp, 0, sizeof(xpp));
1569                 memset(&xecfg, 0, sizeof(xecfg));
1570                 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1571                 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1572                               &xpp, &xecfg, &ecb);
1573         }
1575  free_and_return:
1576         diff_free_filespec_data(one);
1577         diff_free_filespec_data(two);
1580 static void builtin_checkdiff(const char *name_a, const char *name_b,
1581                               const char *attr_path,
1582                               struct diff_filespec *one,
1583                               struct diff_filespec *two,
1584                               struct diff_options *o)
1586         mmfile_t mf1, mf2;
1587         struct checkdiff_t data;
1589         if (!two)
1590                 return;
1592         memset(&data, 0, sizeof(data));
1593         data.filename = name_b ? name_b : name_a;
1594         data.lineno = 0;
1595         data.o = o;
1596         data.ws_rule = whitespace_rule(attr_path);
1598         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1599                 die("unable to read files to diff");
1601         /*
1602          * All the other codepaths check both sides, but not checking
1603          * the "old" side here is deliberate.  We are checking the newly
1604          * introduced changes, and as long as the "new" side is text, we
1605          * can and should check what it introduces.
1606          */
1607         if (diff_filespec_is_binary(two))
1608                 goto free_and_return;
1609         else {
1610                 /* Crazy xdl interfaces.. */
1611                 xpparam_t xpp;
1612                 xdemitconf_t xecfg;
1613                 xdemitcb_t ecb;
1615                 memset(&xpp, 0, sizeof(xpp));
1616                 memset(&xecfg, 0, sizeof(xecfg));
1617                 xecfg.ctxlen = 1; /* at least one context line */
1618                 xpp.flags = XDF_NEED_MINIMAL;
1619                 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1620                               &xpp, &xecfg, &ecb);
1622                 if ((data.ws_rule & WS_TRAILING_SPACE) &&
1623                     data.trailing_blanks_start) {
1624                         fprintf(o->file, "%s:%d: ends with blank lines.\n",
1625                                 data.filename, data.trailing_blanks_start);
1626                         data.status = 1; /* report errors */
1627                 }
1628         }
1629  free_and_return:
1630         diff_free_filespec_data(one);
1631         diff_free_filespec_data(two);
1632         if (data.status)
1633                 DIFF_OPT_SET(o, CHECK_FAILED);
1636 struct diff_filespec *alloc_filespec(const char *path)
1638         int namelen = strlen(path);
1639         struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1641         memset(spec, 0, sizeof(*spec));
1642         spec->path = (char *)(spec + 1);
1643         memcpy(spec->path, path, namelen+1);
1644         spec->count = 1;
1645         spec->is_binary = -1;
1646         return spec;
1649 void free_filespec(struct diff_filespec *spec)
1651         if (!--spec->count) {
1652                 diff_free_filespec_data(spec);
1653                 free(spec);
1654         }
1657 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1658                    unsigned short mode)
1660         if (mode) {
1661                 spec->mode = canon_mode(mode);
1662                 hashcpy(spec->sha1, sha1);
1663                 spec->sha1_valid = !is_null_sha1(sha1);
1664         }
1667 /*
1668  * Given a name and sha1 pair, if the index tells us the file in
1669  * the work tree has that object contents, return true, so that
1670  * prepare_temp_file() does not have to inflate and extract.
1671  */
1672 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1674         struct cache_entry *ce;
1675         struct stat st;
1676         int pos, len;
1678         /* We do not read the cache ourselves here, because the
1679          * benchmark with my previous version that always reads cache
1680          * shows that it makes things worse for diff-tree comparing
1681          * two linux-2.6 kernel trees in an already checked out work
1682          * tree.  This is because most diff-tree comparisons deal with
1683          * only a small number of files, while reading the cache is
1684          * expensive for a large project, and its cost outweighs the
1685          * savings we get by not inflating the object to a temporary
1686          * file.  Practically, this code only helps when we are used
1687          * by diff-cache --cached, which does read the cache before
1688          * calling us.
1689          */
1690         if (!active_cache)
1691                 return 0;
1693         /* We want to avoid the working directory if our caller
1694          * doesn't need the data in a normal file, this system
1695          * is rather slow with its stat/open/mmap/close syscalls,
1696          * and the object is contained in a pack file.  The pack
1697          * is probably already open and will be faster to obtain
1698          * the data through than the working directory.  Loose
1699          * objects however would tend to be slower as they need
1700          * to be individually opened and inflated.
1701          */
1702         if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1703                 return 0;
1705         len = strlen(name);
1706         pos = cache_name_pos(name, len);
1707         if (pos < 0)
1708                 return 0;
1709         ce = active_cache[pos];
1711         /*
1712          * This is not the sha1 we are looking for, or
1713          * unreusable because it is not a regular file.
1714          */
1715         if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1716                 return 0;
1718         /*
1719          * If ce matches the file in the work tree, we can reuse it.
1720          */
1721         if (ce_uptodate(ce) ||
1722             (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1723                 return 1;
1725         return 0;
1728 static int populate_from_stdin(struct diff_filespec *s)
1730         struct strbuf buf = STRBUF_INIT;
1731         size_t size = 0;
1733         if (strbuf_read(&buf, 0, 0) < 0)
1734                 return error("error while reading from stdin %s",
1735                                      strerror(errno));
1737         s->should_munmap = 0;
1738         s->data = strbuf_detach(&buf, &size);
1739         s->size = size;
1740         s->should_free = 1;
1741         return 0;
1744 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1746         int len;
1747         char *data = xmalloc(100);
1748         len = snprintf(data, 100,
1749                 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1750         s->data = data;
1751         s->size = len;
1752         s->should_free = 1;
1753         if (size_only) {
1754                 s->data = NULL;
1755                 free(data);
1756         }
1757         return 0;
1760 /*
1761  * While doing rename detection and pickaxe operation, we may need to
1762  * grab the data for the blob (or file) for our own in-core comparison.
1763  * diff_filespec has data and size fields for this purpose.
1764  */
1765 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1767         int err = 0;
1768         if (!DIFF_FILE_VALID(s))
1769                 die("internal error: asking to populate invalid file.");
1770         if (S_ISDIR(s->mode))
1771                 return -1;
1773         if (s->data)
1774                 return 0;
1776         if (size_only && 0 < s->size)
1777                 return 0;
1779         if (S_ISGITLINK(s->mode))
1780                 return diff_populate_gitlink(s, size_only);
1782         if (!s->sha1_valid ||
1783             reuse_worktree_file(s->path, s->sha1, 0)) {
1784                 struct strbuf buf = STRBUF_INIT;
1785                 struct stat st;
1786                 int fd;
1788                 if (!strcmp(s->path, "-"))
1789                         return populate_from_stdin(s);
1791                 if (lstat(s->path, &st) < 0) {
1792                         if (errno == ENOENT) {
1793                         err_empty:
1794                                 err = -1;
1795                         empty:
1796                                 s->data = (char *)"";
1797                                 s->size = 0;
1798                                 return err;
1799                         }
1800                 }
1801                 s->size = xsize_t(st.st_size);
1802                 if (!s->size)
1803                         goto empty;
1804                 if (S_ISLNK(st.st_mode)) {
1805                         struct strbuf sb = STRBUF_INIT;
1807                         if (strbuf_readlink(&sb, s->path, s->size))
1808                                 goto err_empty;
1809                         s->size = sb.len;
1810                         s->data = strbuf_detach(&sb, NULL);
1811                         s->should_free = 1;
1812                         return 0;
1813                 }
1814                 if (size_only)
1815                         return 0;
1816                 fd = open(s->path, O_RDONLY);
1817                 if (fd < 0)
1818                         goto err_empty;
1819                 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1820                 close(fd);
1821                 s->should_munmap = 1;
1823                 /*
1824                  * Convert from working tree format to canonical git format
1825                  */
1826                 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
1827                         size_t size = 0;
1828                         munmap(s->data, s->size);
1829                         s->should_munmap = 0;
1830                         s->data = strbuf_detach(&buf, &size);
1831                         s->size = size;
1832                         s->should_free = 1;
1833                 }
1834         }
1835         else {
1836                 enum object_type type;
1837                 if (size_only)
1838                         type = sha1_object_info(s->sha1, &s->size);
1839                 else {
1840                         s->data = read_sha1_file(s->sha1, &type, &s->size);
1841                         s->should_free = 1;
1842                 }
1843         }
1844         return 0;
1847 void diff_free_filespec_blob(struct diff_filespec *s)
1849         if (s->should_free)
1850                 free(s->data);
1851         else if (s->should_munmap)
1852                 munmap(s->data, s->size);
1854         if (s->should_free || s->should_munmap) {
1855                 s->should_free = s->should_munmap = 0;
1856                 s->data = NULL;
1857         }
1860 void diff_free_filespec_data(struct diff_filespec *s)
1862         diff_free_filespec_blob(s);
1863         free(s->cnt_data);
1864         s->cnt_data = NULL;
1867 static void prep_temp_blob(struct diff_tempfile *temp,
1868                            void *blob,
1869                            unsigned long size,
1870                            const unsigned char *sha1,
1871                            int mode)
1873         int fd;
1875         fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1876         if (fd < 0)
1877                 die("unable to create temp-file: %s", strerror(errno));
1878         if (write_in_full(fd, blob, size) != size)
1879                 die("unable to write temp-file");
1880         close(fd);
1881         temp->name = temp->tmp_path;
1882         strcpy(temp->hex, sha1_to_hex(sha1));
1883         temp->hex[40] = 0;
1884         sprintf(temp->mode, "%06o", mode);
1887 static struct diff_tempfile *prepare_temp_file(const char *name,
1888                 struct diff_filespec *one)
1890         struct diff_tempfile *temp = claim_diff_tempfile();
1892         if (!DIFF_FILE_VALID(one)) {
1893         not_a_valid_file:
1894                 /* A '-' entry produces this for file-2, and
1895                  * a '+' entry produces this for file-1.
1896                  */
1897                 temp->name = "/dev/null";
1898                 strcpy(temp->hex, ".");
1899                 strcpy(temp->mode, ".");
1900                 return temp;
1901         }
1903         if (!remove_tempfile_installed) {
1904                 atexit(remove_tempfile);
1905                 signal(SIGINT, remove_tempfile_on_signal);
1906                 remove_tempfile_installed = 1;
1907         }
1909         if (!one->sha1_valid ||
1910             reuse_worktree_file(name, one->sha1, 1)) {
1911                 struct stat st;
1912                 if (lstat(name, &st) < 0) {
1913                         if (errno == ENOENT)
1914                                 goto not_a_valid_file;
1915                         die("stat(%s): %s", name, strerror(errno));
1916                 }
1917                 if (S_ISLNK(st.st_mode)) {
1918                         int ret;
1919                         char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1920                         ret = readlink(name, buf, sizeof(buf));
1921                         if (ret < 0)
1922                                 die("readlink(%s)", name);
1923                         if (ret == sizeof(buf))
1924                                 die("symlink too long: %s", name);
1925                         prep_temp_blob(temp, buf, ret,
1926                                        (one->sha1_valid ?
1927                                         one->sha1 : null_sha1),
1928                                        (one->sha1_valid ?
1929                                         one->mode : S_IFLNK));
1930                 }
1931                 else {
1932                         /* we can borrow from the file in the work tree */
1933                         temp->name = name;
1934                         if (!one->sha1_valid)
1935                                 strcpy(temp->hex, sha1_to_hex(null_sha1));
1936                         else
1937                                 strcpy(temp->hex, sha1_to_hex(one->sha1));
1938                         /* Even though we may sometimes borrow the
1939                          * contents from the work tree, we always want
1940                          * one->mode.  mode is trustworthy even when
1941                          * !(one->sha1_valid), as long as
1942                          * DIFF_FILE_VALID(one).
1943                          */
1944                         sprintf(temp->mode, "%06o", one->mode);
1945                 }
1946                 return temp;
1947         }
1948         else {
1949                 if (diff_populate_filespec(one, 0))
1950                         die("cannot read data blob for %s", one->path);
1951                 prep_temp_blob(temp, one->data, one->size,
1952                                one->sha1, one->mode);
1953         }
1954         return temp;
1957 /* An external diff command takes:
1958  *
1959  * diff-cmd name infile1 infile1-sha1 infile1-mode \
1960  *               infile2 infile2-sha1 infile2-mode [ rename-to ]
1961  *
1962  */
1963 static void run_external_diff(const char *pgm,
1964                               const char *name,
1965                               const char *other,
1966                               struct diff_filespec *one,
1967                               struct diff_filespec *two,
1968                               const char *xfrm_msg,
1969                               int complete_rewrite)
1971         const char *spawn_arg[10];
1972         int retval;
1973         const char **arg = &spawn_arg[0];
1975         if (one && two) {
1976                 struct diff_tempfile *temp_one, *temp_two;
1977                 const char *othername = (other ? other : name);
1978                 temp_one = prepare_temp_file(name, one);
1979                 temp_two = prepare_temp_file(othername, two);
1980                 *arg++ = pgm;
1981                 *arg++ = name;
1982                 *arg++ = temp_one->name;
1983                 *arg++ = temp_one->hex;
1984                 *arg++ = temp_one->mode;
1985                 *arg++ = temp_two->name;
1986                 *arg++ = temp_two->hex;
1987                 *arg++ = temp_two->mode;
1988                 if (other) {
1989                         *arg++ = other;
1990                         *arg++ = xfrm_msg;
1991                 }
1992         } else {
1993                 *arg++ = pgm;
1994                 *arg++ = name;
1995         }
1996         *arg = NULL;
1997         fflush(NULL);
1998         retval = run_command_v_opt(spawn_arg, 0);
1999         remove_tempfile();
2000         if (retval) {
2001                 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2002                 exit(1);
2003         }
2006 static void run_diff_cmd(const char *pgm,
2007                          const char *name,
2008                          const char *other,
2009                          const char *attr_path,
2010                          struct diff_filespec *one,
2011                          struct diff_filespec *two,
2012                          const char *xfrm_msg,
2013                          struct diff_options *o,
2014                          int complete_rewrite)
2016         if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2017                 pgm = NULL;
2018         else {
2019                 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2020                 if (drv && drv->external)
2021                         pgm = drv->external;
2022         }
2024         if (pgm) {
2025                 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2026                                   complete_rewrite);
2027                 return;
2028         }
2029         if (one && two)
2030                 builtin_diff(name, other ? other : name,
2031                              one, two, xfrm_msg, o, complete_rewrite);
2032         else
2033                 fprintf(o->file, "* Unmerged path %s\n", name);
2036 static void diff_fill_sha1_info(struct diff_filespec *one)
2038         if (DIFF_FILE_VALID(one)) {
2039                 if (!one->sha1_valid) {
2040                         struct stat st;
2041                         if (!strcmp(one->path, "-")) {
2042                                 hashcpy(one->sha1, null_sha1);
2043                                 return;
2044                         }
2045                         if (lstat(one->path, &st) < 0)
2046                                 die("stat %s", one->path);
2047                         if (index_path(one->sha1, one->path, &st, 0))
2048                                 die("cannot hash %s", one->path);
2049                 }
2050         }
2051         else
2052                 hashclr(one->sha1);
2055 static int similarity_index(struct diff_filepair *p)
2057         return p->score * 100 / MAX_SCORE;
2060 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2062         /* Strip the prefix but do not molest /dev/null and absolute paths */
2063         if (*namep && **namep != '/')
2064                 *namep += prefix_length;
2065         if (*otherp && **otherp != '/')
2066                 *otherp += prefix_length;
2069 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2071         const char *pgm = external_diff();
2072         struct strbuf msg;
2073         char *xfrm_msg;
2074         struct diff_filespec *one = p->one;
2075         struct diff_filespec *two = p->two;
2076         const char *name;
2077         const char *other;
2078         const char *attr_path;
2079         int complete_rewrite = 0;
2081         name  = p->one->path;
2082         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2083         attr_path = name;
2084         if (o->prefix_length)
2085                 strip_prefix(o->prefix_length, &name, &other);
2087         if (DIFF_PAIR_UNMERGED(p)) {
2088                 run_diff_cmd(pgm, name, NULL, attr_path,
2089                              NULL, NULL, NULL, o, 0);
2090                 return;
2091         }
2093         diff_fill_sha1_info(one);
2094         diff_fill_sha1_info(two);
2096         strbuf_init(&msg, PATH_MAX * 2 + 300);
2097         switch (p->status) {
2098         case DIFF_STATUS_COPIED:
2099                 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2100                 strbuf_addstr(&msg, "\ncopy from ");
2101                 quote_c_style(name, &msg, NULL, 0);
2102                 strbuf_addstr(&msg, "\ncopy to ");
2103                 quote_c_style(other, &msg, NULL, 0);
2104                 strbuf_addch(&msg, '\n');
2105                 break;
2106         case DIFF_STATUS_RENAMED:
2107                 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2108                 strbuf_addstr(&msg, "\nrename from ");
2109                 quote_c_style(name, &msg, NULL, 0);
2110                 strbuf_addstr(&msg, "\nrename to ");
2111                 quote_c_style(other, &msg, NULL, 0);
2112                 strbuf_addch(&msg, '\n');
2113                 break;
2114         case DIFF_STATUS_MODIFIED:
2115                 if (p->score) {
2116                         strbuf_addf(&msg, "dissimilarity index %d%%\n",
2117                                         similarity_index(p));
2118                         complete_rewrite = 1;
2119                         break;
2120                 }
2121                 /* fallthru */
2122         default:
2123                 /* nothing */
2124                 ;
2125         }
2127         if (hashcmp(one->sha1, two->sha1)) {
2128                 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2130                 if (DIFF_OPT_TST(o, BINARY)) {
2131                         mmfile_t mf;
2132                         if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2133                             (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2134                                 abbrev = 40;
2135                 }
2136                 strbuf_addf(&msg, "index %.*s..%.*s",
2137                                 abbrev, sha1_to_hex(one->sha1),
2138                                 abbrev, sha1_to_hex(two->sha1));
2139                 if (one->mode == two->mode)
2140                         strbuf_addf(&msg, " %06o", one->mode);
2141                 strbuf_addch(&msg, '\n');
2142         }
2144         if (msg.len)
2145                 strbuf_setlen(&msg, msg.len - 1);
2146         xfrm_msg = msg.len ? msg.buf : NULL;
2148         if (!pgm &&
2149             DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2150             (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2151                 /* a filepair that changes between file and symlink
2152                  * needs to be split into deletion and creation.
2153                  */
2154                 struct diff_filespec *null = alloc_filespec(two->path);
2155                 run_diff_cmd(NULL, name, other, attr_path,
2156                              one, null, xfrm_msg, o, 0);
2157                 free(null);
2158                 null = alloc_filespec(one->path);
2159                 run_diff_cmd(NULL, name, other, attr_path,
2160                              null, two, xfrm_msg, o, 0);
2161                 free(null);
2162         }
2163         else
2164                 run_diff_cmd(pgm, name, other, attr_path,
2165                              one, two, xfrm_msg, o, complete_rewrite);
2167         strbuf_release(&msg);
2170 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2171                          struct diffstat_t *diffstat)
2173         const char *name;
2174         const char *other;
2175         int complete_rewrite = 0;
2177         if (DIFF_PAIR_UNMERGED(p)) {
2178                 /* unmerged */
2179                 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2180                 return;
2181         }
2183         name = p->one->path;
2184         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2186         if (o->prefix_length)
2187                 strip_prefix(o->prefix_length, &name, &other);
2189         diff_fill_sha1_info(p->one);
2190         diff_fill_sha1_info(p->two);
2192         if (p->status == DIFF_STATUS_MODIFIED && p->score)
2193                 complete_rewrite = 1;
2194         builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2197 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2199         const char *name;
2200         const char *other;
2201         const char *attr_path;
2203         if (DIFF_PAIR_UNMERGED(p)) {
2204                 /* unmerged */
2205                 return;
2206         }
2208         name = p->one->path;
2209         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2210         attr_path = other ? other : name;
2212         if (o->prefix_length)
2213                 strip_prefix(o->prefix_length, &name, &other);
2215         diff_fill_sha1_info(p->one);
2216         diff_fill_sha1_info(p->two);
2218         builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2221 void diff_setup(struct diff_options *options)
2223         memset(options, 0, sizeof(*options));
2225         options->file = stdout;
2227         options->line_termination = '\n';
2228         options->break_opt = -1;
2229         options->rename_limit = -1;
2230         options->dirstat_percent = 3;
2231         DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
2232         options->context = 3;
2234         options->change = diff_change;
2235         options->add_remove = diff_addremove;
2236         if (diff_use_color_default > 0)
2237                 DIFF_OPT_SET(options, COLOR_DIFF);
2238         else
2239                 DIFF_OPT_CLR(options, COLOR_DIFF);
2240         options->detect_rename = diff_detect_rename_default;
2242         if (!diff_mnemonic_prefix) {
2243                 options->a_prefix = "a/";
2244                 options->b_prefix = "b/";
2245         }
2248 int diff_setup_done(struct diff_options *options)
2250         int count = 0;
2252         if (options->output_format & DIFF_FORMAT_NAME)
2253                 count++;
2254         if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2255                 count++;
2256         if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2257                 count++;
2258         if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2259                 count++;
2260         if (count > 1)
2261                 die("--name-only, --name-status, --check and -s are mutually exclusive");
2263         if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2264                 options->detect_rename = DIFF_DETECT_COPY;
2266         if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2267                 options->prefix = NULL;
2268         if (options->prefix)
2269                 options->prefix_length = strlen(options->prefix);
2270         else
2271                 options->prefix_length = 0;
2273         if (options->output_format & (DIFF_FORMAT_NAME |
2274                                       DIFF_FORMAT_NAME_STATUS |
2275                                       DIFF_FORMAT_CHECKDIFF |
2276                                       DIFF_FORMAT_NO_OUTPUT))
2277                 options->output_format &= ~(DIFF_FORMAT_RAW |
2278                                             DIFF_FORMAT_NUMSTAT |
2279                                             DIFF_FORMAT_DIFFSTAT |
2280                                             DIFF_FORMAT_SHORTSTAT |
2281                                             DIFF_FORMAT_DIRSTAT |
2282                                             DIFF_FORMAT_SUMMARY |
2283                                             DIFF_FORMAT_PATCH);
2285         /*
2286          * These cases always need recursive; we do not drop caller-supplied
2287          * recursive bits for other formats here.
2288          */
2289         if (options->output_format & (DIFF_FORMAT_PATCH |
2290                                       DIFF_FORMAT_NUMSTAT |
2291                                       DIFF_FORMAT_DIFFSTAT |
2292                                       DIFF_FORMAT_SHORTSTAT |
2293                                       DIFF_FORMAT_DIRSTAT |
2294                                       DIFF_FORMAT_SUMMARY |
2295                                       DIFF_FORMAT_CHECKDIFF))
2296                 DIFF_OPT_SET(options, RECURSIVE);
2297         /*
2298          * Also pickaxe would not work very well if you do not say recursive
2299          */
2300         if (options->pickaxe)
2301                 DIFF_OPT_SET(options, RECURSIVE);
2303         if (options->detect_rename && options->rename_limit < 0)
2304                 options->rename_limit = diff_rename_limit_default;
2305         if (options->setup & DIFF_SETUP_USE_CACHE) {
2306                 if (!active_cache)
2307                         /* read-cache does not die even when it fails
2308                          * so it is safe for us to do this here.  Also
2309                          * it does not smudge active_cache or active_nr
2310                          * when it fails, so we do not have to worry about
2311                          * cleaning it up ourselves either.
2312                          */
2313                         read_cache();
2314         }
2315         if (options->abbrev <= 0 || 40 < options->abbrev)
2316                 options->abbrev = 40; /* full */
2318         /*
2319          * It does not make sense to show the first hit we happened
2320          * to have found.  It does not make sense not to return with
2321          * exit code in such a case either.
2322          */
2323         if (DIFF_OPT_TST(options, QUIET)) {
2324                 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2325                 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2326         }
2328         return 0;
2331 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2333         char c, *eq;
2334         int len;
2336         if (*arg != '-')
2337                 return 0;
2338         c = *++arg;
2339         if (!c)
2340                 return 0;
2341         if (c == arg_short) {
2342                 c = *++arg;
2343                 if (!c)
2344                         return 1;
2345                 if (val && isdigit(c)) {
2346                         char *end;
2347                         int n = strtoul(arg, &end, 10);
2348                         if (*end)
2349                                 return 0;
2350                         *val = n;
2351                         return 1;
2352                 }
2353                 return 0;
2354         }
2355         if (c != '-')
2356                 return 0;
2357         arg++;
2358         eq = strchr(arg, '=');
2359         if (eq)
2360                 len = eq - arg;
2361         else
2362                 len = strlen(arg);
2363         if (!len || strncmp(arg, arg_long, len))
2364                 return 0;
2365         if (eq) {
2366                 int n;
2367                 char *end;
2368                 if (!isdigit(*++eq))
2369                         return 0;
2370                 n = strtoul(eq, &end, 10);
2371                 if (*end)
2372                         return 0;
2373                 *val = n;
2374         }
2375         return 1;
2378 static int diff_scoreopt_parse(const char *opt);
2380 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2382         const char *arg = av[0];
2384         /* Output format options */
2385         if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2386                 options->output_format |= DIFF_FORMAT_PATCH;
2387         else if (opt_arg(arg, 'U', "unified", &options->context))
2388                 options->output_format |= DIFF_FORMAT_PATCH;
2389         else if (!strcmp(arg, "--raw"))
2390                 options->output_format |= DIFF_FORMAT_RAW;
2391         else if (!strcmp(arg, "--patch-with-raw"))
2392                 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2393         else if (!strcmp(arg, "--numstat"))
2394                 options->output_format |= DIFF_FORMAT_NUMSTAT;
2395         else if (!strcmp(arg, "--shortstat"))
2396                 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2397         else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2398                 options->output_format |= DIFF_FORMAT_DIRSTAT;
2399         else if (!strcmp(arg, "--cumulative")) {
2400                 options->output_format |= DIFF_FORMAT_DIRSTAT;
2401                 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2402         } else if (opt_arg(arg, 0, "dirstat-by-file",
2403                            &options->dirstat_percent)) {
2404                 options->output_format |= DIFF_FORMAT_DIRSTAT;
2405                 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2406         }
2407         else if (!strcmp(arg, "--check"))
2408                 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2409         else if (!strcmp(arg, "--summary"))
2410                 options->output_format |= DIFF_FORMAT_SUMMARY;
2411         else if (!strcmp(arg, "--patch-with-stat"))
2412                 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2413         else if (!strcmp(arg, "--name-only"))
2414                 options->output_format |= DIFF_FORMAT_NAME;
2415         else if (!strcmp(arg, "--name-status"))
2416                 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2417         else if (!strcmp(arg, "-s"))
2418                 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2419         else if (!prefixcmp(arg, "--stat")) {
2420                 char *end;
2421                 int width = options->stat_width;
2422                 int name_width = options->stat_name_width;
2423                 arg += 6;
2424                 end = (char *)arg;
2426                 switch (*arg) {
2427                 case '-':
2428                         if (!prefixcmp(arg, "-width="))
2429                                 width = strtoul(arg + 7, &end, 10);
2430                         else if (!prefixcmp(arg, "-name-width="))
2431                                 name_width = strtoul(arg + 12, &end, 10);
2432                         break;
2433                 case '=':
2434                         width = strtoul(arg+1, &end, 10);
2435                         if (*end == ',')
2436                                 name_width = strtoul(end+1, &end, 10);
2437                 }
2439                 /* Important! This checks all the error cases! */
2440                 if (*end)
2441                         return 0;
2442                 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2443                 options->stat_name_width = name_width;
2444                 options->stat_width = width;
2445         }
2447         /* renames options */
2448         else if (!prefixcmp(arg, "-B")) {
2449                 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2450                         return -1;
2451         }
2452         else if (!prefixcmp(arg, "-M")) {
2453                 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2454                         return -1;
2455                 options->detect_rename = DIFF_DETECT_RENAME;
2456         }
2457         else if (!prefixcmp(arg, "-C")) {
2458                 if (options->detect_rename == DIFF_DETECT_COPY)
2459                         DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2460                 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2461                         return -1;
2462                 options->detect_rename = DIFF_DETECT_COPY;
2463         }
2464         else if (!strcmp(arg, "--no-renames"))
2465                 options->detect_rename = 0;
2466         else if (!strcmp(arg, "--relative"))
2467                 DIFF_OPT_SET(options, RELATIVE_NAME);
2468         else if (!prefixcmp(arg, "--relative=")) {
2469                 DIFF_OPT_SET(options, RELATIVE_NAME);
2470                 options->prefix = arg + 11;
2471         }
2473         /* xdiff options */
2474         else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2475                 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2476         else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2477                 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2478         else if (!strcmp(arg, "--ignore-space-at-eol"))
2479                 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2481         /* flags options */
2482         else if (!strcmp(arg, "--binary")) {
2483                 options->output_format |= DIFF_FORMAT_PATCH;
2484                 DIFF_OPT_SET(options, BINARY);
2485         }
2486         else if (!strcmp(arg, "--full-index"))
2487                 DIFF_OPT_SET(options, FULL_INDEX);
2488         else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2489                 DIFF_OPT_SET(options, TEXT);
2490         else if (!strcmp(arg, "-R"))
2491                 DIFF_OPT_SET(options, REVERSE_DIFF);
2492         else if (!strcmp(arg, "--find-copies-harder"))
2493                 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2494         else if (!strcmp(arg, "--follow"))
2495                 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2496         else if (!strcmp(arg, "--color"))
2497                 DIFF_OPT_SET(options, COLOR_DIFF);
2498         else if (!strcmp(arg, "--no-color"))
2499                 DIFF_OPT_CLR(options, COLOR_DIFF);
2500         else if (!strcmp(arg, "--color-words"))
2501                 options->flags |= DIFF_OPT_COLOR_DIFF | DIFF_OPT_COLOR_DIFF_WORDS;
2502         else if (!strcmp(arg, "--exit-code"))
2503                 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2504         else if (!strcmp(arg, "--quiet"))
2505                 DIFF_OPT_SET(options, QUIET);
2506         else if (!strcmp(arg, "--ext-diff"))
2507                 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2508         else if (!strcmp(arg, "--no-ext-diff"))
2509                 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2510         else if (!strcmp(arg, "--textconv"))
2511                 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2512         else if (!strcmp(arg, "--no-textconv"))
2513                 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2514         else if (!strcmp(arg, "--ignore-submodules"))
2515                 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2517         /* misc options */
2518         else if (!strcmp(arg, "-z"))
2519                 options->line_termination = 0;
2520         else if (!prefixcmp(arg, "-l"))
2521                 options->rename_limit = strtoul(arg+2, NULL, 10);
2522         else if (!prefixcmp(arg, "-S"))
2523                 options->pickaxe = arg + 2;
2524         else if (!strcmp(arg, "--pickaxe-all"))
2525                 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2526         else if (!strcmp(arg, "--pickaxe-regex"))
2527                 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2528         else if (!prefixcmp(arg, "-O"))
2529                 options->orderfile = arg + 2;
2530         else if (!prefixcmp(arg, "--diff-filter="))
2531                 options->filter = arg + 14;
2532         else if (!strcmp(arg, "--abbrev"))
2533                 options->abbrev = DEFAULT_ABBREV;
2534         else if (!prefixcmp(arg, "--abbrev=")) {
2535                 options->abbrev = strtoul(arg + 9, NULL, 10);
2536                 if (options->abbrev < MINIMUM_ABBREV)
2537                         options->abbrev = MINIMUM_ABBREV;
2538                 else if (40 < options->abbrev)
2539                         options->abbrev = 40;
2540         }
2541         else if (!prefixcmp(arg, "--src-prefix="))
2542                 options->a_prefix = arg + 13;
2543         else if (!prefixcmp(arg, "--dst-prefix="))
2544                 options->b_prefix = arg + 13;
2545         else if (!strcmp(arg, "--no-prefix"))
2546                 options->a_prefix = options->b_prefix = "";
2547         else if (opt_arg(arg, '\0', "inter-hunk-context",
2548                          &options->interhunkcontext))
2549                 ;
2550         else if (!prefixcmp(arg, "--output=")) {
2551                 options->file = fopen(arg + strlen("--output="), "w");
2552                 options->close_file = 1;
2553         } else
2554                 return 0;
2555         return 1;
2558 static int parse_num(const char **cp_p)
2560         unsigned long num, scale;
2561         int ch, dot;
2562         const char *cp = *cp_p;
2564         num = 0;
2565         scale = 1;
2566         dot = 0;
2567         for(;;) {
2568                 ch = *cp;
2569                 if ( !dot && ch == '.' ) {
2570                         scale = 1;
2571                         dot = 1;
2572                 } else if ( ch == '%' ) {
2573                         scale = dot ? scale*100 : 100;
2574                         cp++;   /* % is always at the end */
2575                         break;
2576                 } else if ( ch >= '0' && ch <= '9' ) {
2577                         if ( scale < 100000 ) {
2578                                 scale *= 10;
2579                                 num = (num*10) + (ch-'0');
2580                         }
2581                 } else {
2582                         break;
2583                 }
2584                 cp++;
2585         }
2586         *cp_p = cp;
2588         /* user says num divided by scale and we say internally that
2589          * is MAX_SCORE * num / scale.
2590          */
2591         return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2594 static int diff_scoreopt_parse(const char *opt)
2596         int opt1, opt2, cmd;
2598         if (*opt++ != '-')
2599                 return -1;
2600         cmd = *opt++;
2601         if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2602                 return -1; /* that is not a -M, -C nor -B option */
2604         opt1 = parse_num(&opt);
2605         if (cmd != 'B')
2606                 opt2 = 0;
2607         else {
2608                 if (*opt == 0)
2609                         opt2 = 0;
2610                 else if (*opt != '/')
2611                         return -1; /* we expect -B80/99 or -B80 */
2612                 else {
2613                         opt++;
2614                         opt2 = parse_num(&opt);
2615                 }
2616         }
2617         if (*opt != 0)
2618                 return -1;
2619         return opt1 | (opt2 << 16);
2622 struct diff_queue_struct diff_queued_diff;
2624 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2626         if (queue->alloc <= queue->nr) {
2627                 queue->alloc = alloc_nr(queue->alloc);
2628                 queue->queue = xrealloc(queue->queue,
2629                                         sizeof(dp) * queue->alloc);
2630         }
2631         queue->queue[queue->nr++] = dp;
2634 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2635                                  struct diff_filespec *one,
2636                                  struct diff_filespec *two)
2638         struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2639         dp->one = one;
2640         dp->two = two;
2641         if (queue)
2642                 diff_q(queue, dp);
2643         return dp;
2646 void diff_free_filepair(struct diff_filepair *p)
2648         free_filespec(p->one);
2649         free_filespec(p->two);
2650         free(p);
2653 /* This is different from find_unique_abbrev() in that
2654  * it stuffs the result with dots for alignment.
2655  */
2656 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2658         int abblen;
2659         const char *abbrev;
2660         if (len == 40)
2661                 return sha1_to_hex(sha1);
2663         abbrev = find_unique_abbrev(sha1, len);
2664         abblen = strlen(abbrev);
2665         if (abblen < 37) {
2666                 static char hex[41];
2667                 if (len < abblen && abblen <= len + 2)
2668                         sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2669                 else
2670                         sprintf(hex, "%s...", abbrev);
2671                 return hex;
2672         }
2673         return sha1_to_hex(sha1);
2676 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2678         int line_termination = opt->line_termination;
2679         int inter_name_termination = line_termination ? '\t' : '\0';
2681         if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2682                 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2683                         diff_unique_abbrev(p->one->sha1, opt->abbrev));
2684                 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2685         }
2686         if (p->score) {
2687                 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2688                         inter_name_termination);
2689         } else {
2690                 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2691         }
2693         if (p->status == DIFF_STATUS_COPIED ||
2694             p->status == DIFF_STATUS_RENAMED) {
2695                 const char *name_a, *name_b;
2696                 name_a = p->one->path;
2697                 name_b = p->two->path;
2698                 strip_prefix(opt->prefix_length, &name_a, &name_b);
2699                 write_name_quoted(name_a, opt->file, inter_name_termination);
2700                 write_name_quoted(name_b, opt->file, line_termination);
2701         } else {
2702                 const char *name_a, *name_b;
2703                 name_a = p->one->mode ? p->one->path : p->two->path;
2704                 name_b = NULL;
2705                 strip_prefix(opt->prefix_length, &name_a, &name_b);
2706                 write_name_quoted(name_a, opt->file, line_termination);
2707         }
2710 int diff_unmodified_pair(struct diff_filepair *p)
2712         /* This function is written stricter than necessary to support
2713          * the currently implemented transformers, but the idea is to
2714          * let transformers to produce diff_filepairs any way they want,
2715          * and filter and clean them up here before producing the output.
2716          */
2717         struct diff_filespec *one = p->one, *two = p->two;
2719         if (DIFF_PAIR_UNMERGED(p))
2720                 return 0; /* unmerged is interesting */
2722         /* deletion, addition, mode or type change
2723          * and rename are all interesting.
2724          */
2725         if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2726             DIFF_PAIR_MODE_CHANGED(p) ||
2727             strcmp(one->path, two->path))
2728                 return 0;
2730         /* both are valid and point at the same path.  that is, we are
2731          * dealing with a change.
2732          */
2733         if (one->sha1_valid && two->sha1_valid &&
2734             !hashcmp(one->sha1, two->sha1))
2735                 return 1; /* no change */
2736         if (!one->sha1_valid && !two->sha1_valid)
2737                 return 1; /* both look at the same file on the filesystem. */
2738         return 0;
2741 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2743         if (diff_unmodified_pair(p))
2744                 return;
2746         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2747             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2748                 return; /* no tree diffs in patch format */
2750         run_diff(p, o);
2753 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2754                             struct diffstat_t *diffstat)
2756         if (diff_unmodified_pair(p))
2757                 return;
2759         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2760             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2761                 return; /* no tree diffs in patch format */
2763         run_diffstat(p, o, diffstat);
2766 static void diff_flush_checkdiff(struct diff_filepair *p,
2767                 struct diff_options *o)
2769         if (diff_unmodified_pair(p))
2770                 return;
2772         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2773             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2774                 return; /* no tree diffs in patch format */
2776         run_checkdiff(p, o);
2779 int diff_queue_is_empty(void)
2781         struct diff_queue_struct *q = &diff_queued_diff;
2782         int i;
2783         for (i = 0; i < q->nr; i++)
2784                 if (!diff_unmodified_pair(q->queue[i]))
2785                         return 0;
2786         return 1;
2789 #if DIFF_DEBUG
2790 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2792         fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2793                 x, one ? one : "",
2794                 s->path,
2795                 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2796                 s->mode,
2797                 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2798         fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2799                 x, one ? one : "",
2800                 s->size, s->xfrm_flags);
2803 void diff_debug_filepair(const struct diff_filepair *p, int i)
2805         diff_debug_filespec(p->one, i, "one");
2806         diff_debug_filespec(p->two, i, "two");
2807         fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2808                 p->score, p->status ? p->status : '?',
2809                 p->one->rename_used, p->broken_pair);
2812 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2814         int i;
2815         if (msg)
2816                 fprintf(stderr, "%s\n", msg);
2817         fprintf(stderr, "q->nr = %d\n", q->nr);
2818         for (i = 0; i < q->nr; i++) {
2819                 struct diff_filepair *p = q->queue[i];
2820                 diff_debug_filepair(p, i);
2821         }
2823 #endif
2825 static void diff_resolve_rename_copy(void)
2827         int i;
2828         struct diff_filepair *p;
2829         struct diff_queue_struct *q = &diff_queued_diff;
2831         diff_debug_queue("resolve-rename-copy", q);
2833         for (i = 0; i < q->nr; i++) {
2834                 p = q->queue[i];
2835                 p->status = 0; /* undecided */
2836                 if (DIFF_PAIR_UNMERGED(p))
2837                         p->status = DIFF_STATUS_UNMERGED;
2838                 else if (!DIFF_FILE_VALID(p->one))
2839                         p->status = DIFF_STATUS_ADDED;
2840                 else if (!DIFF_FILE_VALID(p->two))
2841                         p->status = DIFF_STATUS_DELETED;
2842                 else if (DIFF_PAIR_TYPE_CHANGED(p))
2843                         p->status = DIFF_STATUS_TYPE_CHANGED;
2845                 /* from this point on, we are dealing with a pair
2846                  * whose both sides are valid and of the same type, i.e.
2847                  * either in-place edit or rename/copy edit.
2848                  */
2849                 else if (DIFF_PAIR_RENAME(p)) {
2850                         /*
2851                          * A rename might have re-connected a broken
2852                          * pair up, causing the pathnames to be the
2853                          * same again. If so, that's not a rename at
2854                          * all, just a modification..
2855                          *
2856                          * Otherwise, see if this source was used for
2857                          * multiple renames, in which case we decrement
2858                          * the count, and call it a copy.
2859                          */
2860                         if (!strcmp(p->one->path, p->two->path))
2861                                 p->status = DIFF_STATUS_MODIFIED;
2862                         else if (--p->one->rename_used > 0)
2863                                 p->status = DIFF_STATUS_COPIED;
2864                         else
2865                                 p->status = DIFF_STATUS_RENAMED;
2866                 }
2867                 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2868                          p->one->mode != p->two->mode ||
2869                          is_null_sha1(p->one->sha1))
2870                         p->status = DIFF_STATUS_MODIFIED;
2871                 else {
2872                         /* This is a "no-change" entry and should not
2873                          * happen anymore, but prepare for broken callers.
2874                          */
2875                         error("feeding unmodified %s to diffcore",
2876                               p->one->path);
2877                         p->status = DIFF_STATUS_UNKNOWN;
2878                 }
2879         }
2880         diff_debug_queue("resolve-rename-copy done", q);
2883 static int check_pair_status(struct diff_filepair *p)
2885         switch (p->status) {
2886         case DIFF_STATUS_UNKNOWN:
2887                 return 0;
2888         case 0:
2889                 die("internal error in diff-resolve-rename-copy");
2890         default:
2891                 return 1;
2892         }
2895 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2897         int fmt = opt->output_format;
2899         if (fmt & DIFF_FORMAT_CHECKDIFF)
2900                 diff_flush_checkdiff(p, opt);
2901         else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2902                 diff_flush_raw(p, opt);
2903         else if (fmt & DIFF_FORMAT_NAME) {
2904                 const char *name_a, *name_b;
2905                 name_a = p->two->path;
2906                 name_b = NULL;
2907                 strip_prefix(opt->prefix_length, &name_a, &name_b);
2908                 write_name_quoted(name_a, opt->file, opt->line_termination);
2909         }
2912 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
2914         if (fs->mode)
2915                 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
2916         else
2917                 fprintf(file, " %s ", newdelete);
2918         write_name_quoted(fs->path, file, '\n');
2922 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
2924         if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2925                 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
2926                         show_name ? ' ' : '\n');
2927                 if (show_name) {
2928                         write_name_quoted(p->two->path, file, '\n');
2929                 }
2930         }
2933 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
2935         char *names = pprint_rename(p->one->path, p->two->path);
2937         fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2938         free(names);
2939         show_mode_change(file, p, 0);
2942 static void diff_summary(FILE *file, struct diff_filepair *p)
2944         switch(p->status) {
2945         case DIFF_STATUS_DELETED:
2946                 show_file_mode_name(file, "delete", p->one);
2947                 break;
2948         case DIFF_STATUS_ADDED:
2949                 show_file_mode_name(file, "create", p->two);
2950                 break;
2951         case DIFF_STATUS_COPIED:
2952                 show_rename_copy(file, "copy", p);
2953                 break;
2954         case DIFF_STATUS_RENAMED:
2955                 show_rename_copy(file, "rename", p);
2956                 break;
2957         default:
2958                 if (p->score) {
2959                         fputs(" rewrite ", file);
2960                         write_name_quoted(p->two->path, file, ' ');
2961                         fprintf(file, "(%d%%)\n", similarity_index(p));
2962                 }
2963                 show_mode_change(file, p, !p->score);
2964                 break;
2965         }
2968 struct patch_id_t {
2969         git_SHA_CTX *ctx;
2970         int patchlen;
2971 };
2973 static int remove_space(char *line, int len)
2975         int i;
2976         char *dst = line;
2977         unsigned char c;
2979         for (i = 0; i < len; i++)
2980                 if (!isspace((c = line[i])))
2981                         *dst++ = c;
2983         return dst - line;
2986 static void patch_id_consume(void *priv, char *line, unsigned long len)
2988         struct patch_id_t *data = priv;
2989         int new_len;
2991         /* Ignore line numbers when computing the SHA1 of the patch */
2992         if (!prefixcmp(line, "@@ -"))
2993                 return;
2995         new_len = remove_space(line, len);
2997         git_SHA1_Update(data->ctx, line, new_len);
2998         data->patchlen += new_len;
3001 /* returns 0 upon success, and writes result into sha1 */
3002 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3004         struct diff_queue_struct *q = &diff_queued_diff;
3005         int i;
3006         git_SHA_CTX ctx;
3007         struct patch_id_t data;
3008         char buffer[PATH_MAX * 4 + 20];
3010         git_SHA1_Init(&ctx);
3011         memset(&data, 0, sizeof(struct patch_id_t));
3012         data.ctx = &ctx;
3014         for (i = 0; i < q->nr; i++) {
3015                 xpparam_t xpp;
3016                 xdemitconf_t xecfg;
3017                 xdemitcb_t ecb;
3018                 mmfile_t mf1, mf2;
3019                 struct diff_filepair *p = q->queue[i];
3020                 int len1, len2;
3022                 memset(&xpp, 0, sizeof(xpp));
3023                 memset(&xecfg, 0, sizeof(xecfg));
3024                 if (p->status == 0)
3025                         return error("internal diff status error");
3026                 if (p->status == DIFF_STATUS_UNKNOWN)
3027                         continue;
3028                 if (diff_unmodified_pair(p))
3029                         continue;
3030                 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3031                     (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3032                         continue;
3033                 if (DIFF_PAIR_UNMERGED(p))
3034                         continue;
3036                 diff_fill_sha1_info(p->one);
3037                 diff_fill_sha1_info(p->two);
3038                 if (fill_mmfile(&mf1, p->one) < 0 ||
3039                                 fill_mmfile(&mf2, p->two) < 0)
3040                         return error("unable to read files to diff");
3042                 len1 = remove_space(p->one->path, strlen(p->one->path));
3043                 len2 = remove_space(p->two->path, strlen(p->two->path));
3044                 if (p->one->mode == 0)
3045                         len1 = snprintf(buffer, sizeof(buffer),
3046                                         "diff--gita/%.*sb/%.*s"
3047                                         "newfilemode%06o"
3048                                         "---/dev/null"
3049                                         "+++b/%.*s",
3050                                         len1, p->one->path,
3051                                         len2, p->two->path,
3052                                         p->two->mode,
3053                                         len2, p->two->path);
3054                 else if (p->two->mode == 0)
3055                         len1 = snprintf(buffer, sizeof(buffer),
3056                                         "diff--gita/%.*sb/%.*s"
3057                                         "deletedfilemode%06o"
3058                                         "---a/%.*s"
3059                                         "+++/dev/null",
3060                                         len1, p->one->path,
3061                                         len2, p->two->path,
3062                                         p->one->mode,
3063                                         len1, p->one->path);
3064                 else
3065                         len1 = snprintf(buffer, sizeof(buffer),
3066                                         "diff--gita/%.*sb/%.*s"
3067                                         "---a/%.*s"
3068                                         "+++b/%.*s",
3069                                         len1, p->one->path,
3070                                         len2, p->two->path,
3071                                         len1, p->one->path,
3072                                         len2, p->two->path);
3073                 git_SHA1_Update(&ctx, buffer, len1);
3075                 xpp.flags = XDF_NEED_MINIMAL;
3076                 xecfg.ctxlen = 3;
3077                 xecfg.flags = XDL_EMIT_FUNCNAMES;
3078                 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3079                               &xpp, &xecfg, &ecb);
3080         }
3082         git_SHA1_Final(sha1, &ctx);
3083         return 0;
3086 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3088         struct diff_queue_struct *q = &diff_queued_diff;
3089         int i;
3090         int result = diff_get_patch_id(options, sha1);
3092         for (i = 0; i < q->nr; i++)
3093                 diff_free_filepair(q->queue[i]);
3095         free(q->queue);
3096         q->queue = NULL;
3097         q->nr = q->alloc = 0;
3099         return result;
3102 static int is_summary_empty(const struct diff_queue_struct *q)
3104         int i;
3106         for (i = 0; i < q->nr; i++) {
3107                 const struct diff_filepair *p = q->queue[i];
3109                 switch (p->status) {
3110                 case DIFF_STATUS_DELETED:
3111                 case DIFF_STATUS_ADDED:
3112                 case DIFF_STATUS_COPIED:
3113                 case DIFF_STATUS_RENAMED:
3114                         return 0;
3115                 default:
3116                         if (p->score)
3117                                 return 0;
3118                         if (p->one->mode && p->two->mode &&
3119                             p->one->mode != p->two->mode)
3120                                 return 0;
3121                         break;
3122                 }
3123         }
3124         return 1;
3127 void diff_flush(struct diff_options *options)
3129         struct diff_queue_struct *q = &diff_queued_diff;
3130         int i, output_format = options->output_format;
3131         int separator = 0;
3133         /*
3134          * Order: raw, stat, summary, patch
3135          * or:    name/name-status/checkdiff (other bits clear)
3136          */
3137         if (!q->nr)
3138                 goto free_queue;
3140         if (output_format & (DIFF_FORMAT_RAW |
3141                              DIFF_FORMAT_NAME |
3142                              DIFF_FORMAT_NAME_STATUS |
3143                              DIFF_FORMAT_CHECKDIFF)) {
3144                 for (i = 0; i < q->nr; i++) {
3145                         struct diff_filepair *p = q->queue[i];
3146                         if (check_pair_status(p))
3147                                 flush_one_pair(p, options);
3148                 }
3149                 separator++;
3150         }
3152         if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3153                 struct diffstat_t diffstat;
3155                 memset(&diffstat, 0, sizeof(struct diffstat_t));
3156                 for (i = 0; i < q->nr; i++) {
3157                         struct diff_filepair *p = q->queue[i];
3158                         if (check_pair_status(p))
3159                                 diff_flush_stat(p, options, &diffstat);
3160                 }
3161                 if (output_format & DIFF_FORMAT_NUMSTAT)
3162                         show_numstat(&diffstat, options);
3163                 if (output_format & DIFF_FORMAT_DIFFSTAT)
3164                         show_stats(&diffstat, options);
3165                 if (output_format & DIFF_FORMAT_SHORTSTAT)
3166                         show_shortstats(&diffstat, options);
3167                 free_diffstat_info(&diffstat);
3168                 separator++;
3169         }
3170         if (output_format & DIFF_FORMAT_DIRSTAT)
3171                 show_dirstat(options);
3173         if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3174                 for (i = 0; i < q->nr; i++)
3175                         diff_summary(options->file, q->queue[i]);
3176                 separator++;
3177         }
3179         if (output_format & DIFF_FORMAT_PATCH) {
3180                 if (separator) {
3181                         putc(options->line_termination, options->file);
3182                         if (options->stat_sep) {
3183                                 /* attach patch instead of inline */
3184                                 fputs(options->stat_sep, options->file);
3185                         }
3186                 }
3188                 for (i = 0; i < q->nr; i++) {
3189                         struct diff_filepair *p = q->queue[i];
3190                         if (check_pair_status(p))
3191                                 diff_flush_patch(p, options);
3192                 }
3193         }
3195         if (output_format & DIFF_FORMAT_CALLBACK)
3196                 options->format_callback(q, options, options->format_callback_data);
3198         for (i = 0; i < q->nr; i++)
3199                 diff_free_filepair(q->queue[i]);
3200 free_queue:
3201         free(q->queue);
3202         q->queue = NULL;
3203         q->nr = q->alloc = 0;
3204         if (options->close_file)
3205                 fclose(options->file);
3208 static void diffcore_apply_filter(const char *filter)
3210         int i;
3211         struct diff_queue_struct *q = &diff_queued_diff;
3212         struct diff_queue_struct outq;
3213         outq.queue = NULL;
3214         outq.nr = outq.alloc = 0;
3216         if (!filter)
3217                 return;
3219         if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3220                 int found;
3221                 for (i = found = 0; !found && i < q->nr; i++) {
3222                         struct diff_filepair *p = q->queue[i];
3223                         if (((p->status == DIFF_STATUS_MODIFIED) &&
3224                              ((p->score &&
3225                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3226                               (!p->score &&
3227                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3228                             ((p->status != DIFF_STATUS_MODIFIED) &&
3229                              strchr(filter, p->status)))
3230                                 found++;
3231                 }
3232                 if (found)
3233                         return;
3235                 /* otherwise we will clear the whole queue
3236                  * by copying the empty outq at the end of this
3237                  * function, but first clear the current entries
3238                  * in the queue.
3239                  */
3240                 for (i = 0; i < q->nr; i++)
3241                         diff_free_filepair(q->queue[i]);
3242         }
3243         else {
3244                 /* Only the matching ones */
3245                 for (i = 0; i < q->nr; i++) {
3246                         struct diff_filepair *p = q->queue[i];
3248                         if (((p->status == DIFF_STATUS_MODIFIED) &&
3249                              ((p->score &&
3250                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3251                               (!p->score &&
3252                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3253                             ((p->status != DIFF_STATUS_MODIFIED) &&
3254                              strchr(filter, p->status)))
3255                                 diff_q(&outq, p);
3256                         else
3257                                 diff_free_filepair(p);
3258                 }
3259         }
3260         free(q->queue);
3261         *q = outq;
3264 /* Check whether two filespecs with the same mode and size are identical */
3265 static int diff_filespec_is_identical(struct diff_filespec *one,
3266                                       struct diff_filespec *two)
3268         if (S_ISGITLINK(one->mode))
3269                 return 0;
3270         if (diff_populate_filespec(one, 0))
3271                 return 0;
3272         if (diff_populate_filespec(two, 0))
3273                 return 0;
3274         return !memcmp(one->data, two->data, one->size);
3277 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3279         int i;
3280         struct diff_queue_struct *q = &diff_queued_diff;
3281         struct diff_queue_struct outq;
3282         outq.queue = NULL;
3283         outq.nr = outq.alloc = 0;
3285         for (i = 0; i < q->nr; i++) {
3286                 struct diff_filepair *p = q->queue[i];
3288                 /*
3289                  * 1. Entries that come from stat info dirtyness
3290                  *    always have both sides (iow, not create/delete),
3291                  *    one side of the object name is unknown, with
3292                  *    the same mode and size.  Keep the ones that
3293                  *    do not match these criteria.  They have real
3294                  *    differences.
3295                  *
3296                  * 2. At this point, the file is known to be modified,
3297                  *    with the same mode and size, and the object
3298                  *    name of one side is unknown.  Need to inspect
3299                  *    the identical contents.
3300                  */
3301                 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3302                     !DIFF_FILE_VALID(p->two) ||
3303                     (p->one->sha1_valid && p->two->sha1_valid) ||
3304                     (p->one->mode != p->two->mode) ||
3305                     diff_populate_filespec(p->one, 1) ||
3306                     diff_populate_filespec(p->two, 1) ||
3307                     (p->one->size != p->two->size) ||
3308                     !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3309                         diff_q(&outq, p);
3310                 else {
3311                         /*
3312                          * The caller can subtract 1 from skip_stat_unmatch
3313                          * to determine how many paths were dirty only
3314                          * due to stat info mismatch.
3315                          */
3316                         if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3317                                 diffopt->skip_stat_unmatch++;
3318                         diff_free_filepair(p);
3319                 }
3320         }
3321         free(q->queue);
3322         *q = outq;
3325 void diffcore_std(struct diff_options *options)
3327         if (options->skip_stat_unmatch)
3328                 diffcore_skip_stat_unmatch(options);
3329         if (options->break_opt != -1)
3330                 diffcore_break(options->break_opt);
3331         if (options->detect_rename)
3332                 diffcore_rename(options);
3333         if (options->break_opt != -1)
3334                 diffcore_merge_broken();
3335         if (options->pickaxe)
3336                 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3337         if (options->orderfile)
3338                 diffcore_order(options->orderfile);
3339         diff_resolve_rename_copy();
3340         diffcore_apply_filter(options->filter);
3342         if (diff_queued_diff.nr)
3343                 DIFF_OPT_SET(options, HAS_CHANGES);
3344         else
3345                 DIFF_OPT_CLR(options, HAS_CHANGES);
3348 int diff_result_code(struct diff_options *opt, int status)
3350         int result = 0;
3351         if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3352             !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3353                 return status;
3354         if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3355             DIFF_OPT_TST(opt, HAS_CHANGES))
3356                 result |= 01;
3357         if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3358             DIFF_OPT_TST(opt, CHECK_FAILED))
3359                 result |= 02;
3360         return result;
3363 void diff_addremove(struct diff_options *options,
3364                     int addremove, unsigned mode,
3365                     const unsigned char *sha1,
3366                     const char *concatpath)
3368         struct diff_filespec *one, *two;
3370         if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3371                 return;
3373         /* This may look odd, but it is a preparation for
3374          * feeding "there are unchanged files which should
3375          * not produce diffs, but when you are doing copy
3376          * detection you would need them, so here they are"
3377          * entries to the diff-core.  They will be prefixed
3378          * with something like '=' or '*' (I haven't decided
3379          * which but should not make any difference).
3380          * Feeding the same new and old to diff_change()
3381          * also has the same effect.
3382          * Before the final output happens, they are pruned after
3383          * merged into rename/copy pairs as appropriate.
3384          */
3385         if (DIFF_OPT_TST(options, REVERSE_DIFF))
3386                 addremove = (addremove == '+' ? '-' :
3387                              addremove == '-' ? '+' : addremove);
3389         if (options->prefix &&
3390             strncmp(concatpath, options->prefix, options->prefix_length))
3391                 return;
3393         one = alloc_filespec(concatpath);
3394         two = alloc_filespec(concatpath);
3396         if (addremove != '+')
3397                 fill_filespec(one, sha1, mode);
3398         if (addremove != '-')
3399                 fill_filespec(two, sha1, mode);
3401         diff_queue(&diff_queued_diff, one, two);
3402         DIFF_OPT_SET(options, HAS_CHANGES);
3405 void diff_change(struct diff_options *options,
3406                  unsigned old_mode, unsigned new_mode,
3407                  const unsigned char *old_sha1,
3408                  const unsigned char *new_sha1,
3409                  const char *concatpath)
3411         struct diff_filespec *one, *two;
3413         if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3414                         && S_ISGITLINK(new_mode))
3415                 return;
3417         if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3418                 unsigned tmp;
3419                 const unsigned char *tmp_c;
3420                 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3421                 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3422         }
3424         if (options->prefix &&
3425             strncmp(concatpath, options->prefix, options->prefix_length))
3426                 return;
3428         one = alloc_filespec(concatpath);
3429         two = alloc_filespec(concatpath);
3430         fill_filespec(one, old_sha1, old_mode);
3431         fill_filespec(two, new_sha1, new_mode);
3433         diff_queue(&diff_queued_diff, one, two);
3434         DIFF_OPT_SET(options, HAS_CHANGES);
3437 void diff_unmerge(struct diff_options *options,
3438                   const char *path,
3439                   unsigned mode, const unsigned char *sha1)
3441         struct diff_filespec *one, *two;
3443         if (options->prefix &&
3444             strncmp(path, options->prefix, options->prefix_length))
3445                 return;
3447         one = alloc_filespec(path);
3448         two = alloc_filespec(path);
3449         fill_filespec(one, sha1, mode);
3450         diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3453 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3454                 size_t *outsize)
3456         struct diff_tempfile *temp;
3457         const char *argv[3];
3458         const char **arg = argv;
3459         struct child_process child;
3460         struct strbuf buf = STRBUF_INIT;
3462         temp = prepare_temp_file(spec->path, spec);
3463         *arg++ = pgm;
3464         *arg++ = temp->name;
3465         *arg = NULL;
3467         memset(&child, 0, sizeof(child));
3468         child.argv = argv;
3469         child.out = -1;
3470         if (start_command(&child) != 0 ||
3471             strbuf_read(&buf, child.out, 0) < 0 ||
3472             finish_command(&child) != 0) {
3473                 remove_tempfile();
3474                 error("error running textconv command '%s'", pgm);
3475                 return NULL;
3476         }
3477         remove_tempfile();
3479         return strbuf_detach(&buf, outsize);