Code

50277b82b2289395fd11a3d5b4d63cf45f825a51
[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 int count_lines(const char *data, int size)
170         int count, ch, completely_empty = 1, nl_just_seen = 0;
171         count = 0;
172         while (0 < size--) {
173                 ch = *data++;
174                 if (ch == '\n') {
175                         count++;
176                         nl_just_seen = 1;
177                         completely_empty = 0;
178                 }
179                 else {
180                         nl_just_seen = 0;
181                         completely_empty = 0;
182                 }
183         }
184         if (completely_empty)
185                 return 0;
186         if (!nl_just_seen)
187                 count++; /* no trailing newline */
188         return count;
191 static void print_line_count(FILE *file, int count)
193         switch (count) {
194         case 0:
195                 fprintf(file, "0,0");
196                 break;
197         case 1:
198                 fprintf(file, "1");
199                 break;
200         default:
201                 fprintf(file, "1,%d", count);
202                 break;
203         }
206 static void copy_file_with_prefix(FILE *file,
207                                   int prefix, const char *data, int size,
208                                   const char *set, const char *reset)
210         int ch, nl_just_seen = 1;
211         while (0 < size--) {
212                 ch = *data++;
213                 if (nl_just_seen) {
214                         fputs(set, file);
215                         putc(prefix, file);
216                 }
217                 if (ch == '\n') {
218                         nl_just_seen = 1;
219                         fputs(reset, file);
220                 } else
221                         nl_just_seen = 0;
222                 putc(ch, file);
223         }
224         if (!nl_just_seen)
225                 fprintf(file, "%s\n\\ No newline at end of file\n", reset);
228 static void emit_rewrite_diff(const char *name_a,
229                               const char *name_b,
230                               struct diff_filespec *one,
231                               struct diff_filespec *two,
232                               struct diff_options *o)
234         int lc_a, lc_b;
235         int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
236         const char *name_a_tab, *name_b_tab;
237         const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
238         const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
239         const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
240         const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
241         const char *reset = diff_get_color(color_diff, DIFF_RESET);
242         static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
243         const char *a_prefix, *b_prefix;
245         if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
246                 a_prefix = o->b_prefix;
247                 b_prefix = o->a_prefix;
248         } else {
249                 a_prefix = o->a_prefix;
250                 b_prefix = o->b_prefix;
251         }
253         name_a += (*name_a == '/');
254         name_b += (*name_b == '/');
255         name_a_tab = strchr(name_a, ' ') ? "\t" : "";
256         name_b_tab = strchr(name_b, ' ') ? "\t" : "";
258         strbuf_reset(&a_name);
259         strbuf_reset(&b_name);
260         quote_two_c_style(&a_name, a_prefix, name_a, 0);
261         quote_two_c_style(&b_name, b_prefix, name_b, 0);
263         diff_populate_filespec(one, 0);
264         diff_populate_filespec(two, 0);
265         lc_a = count_lines(one->data, one->size);
266         lc_b = count_lines(two->data, two->size);
267         fprintf(o->file,
268                 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
269                 metainfo, a_name.buf, name_a_tab, reset,
270                 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
271         print_line_count(o->file, lc_a);
272         fprintf(o->file, " +");
273         print_line_count(o->file, lc_b);
274         fprintf(o->file, " @@%s\n", reset);
275         if (lc_a)
276                 copy_file_with_prefix(o->file, '-', one->data, one->size, old, reset);
277         if (lc_b)
278                 copy_file_with_prefix(o->file, '+', two->data, two->size, new, reset);
281 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
283         if (!DIFF_FILE_VALID(one)) {
284                 mf->ptr = (char *)""; /* does not matter */
285                 mf->size = 0;
286                 return 0;
287         }
288         else if (diff_populate_filespec(one, 0))
289                 return -1;
291         mf->ptr = one->data;
292         mf->size = one->size;
293         return 0;
296 struct diff_words_buffer {
297         mmfile_t text;
298         long alloc;
299         long current; /* output pointer */
300         int suppressed_newline;
301 };
303 static void diff_words_append(char *line, unsigned long len,
304                 struct diff_words_buffer *buffer)
306         if (buffer->text.size + len > buffer->alloc) {
307                 buffer->alloc = (buffer->text.size + len) * 3 / 2;
308                 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
309         }
310         line++;
311         len--;
312         memcpy(buffer->text.ptr + buffer->text.size, line, len);
313         buffer->text.size += len;
316 struct diff_words_data {
317         struct diff_words_buffer minus, plus;
318         FILE *file;
319 };
321 static void print_word(FILE *file, struct diff_words_buffer *buffer, int len, int color,
322                 int suppress_newline)
324         const char *ptr;
325         int eol = 0;
327         if (len == 0)
328                 return;
330         ptr  = buffer->text.ptr + buffer->current;
331         buffer->current += len;
333         if (ptr[len - 1] == '\n') {
334                 eol = 1;
335                 len--;
336         }
338         fputs(diff_get_color(1, color), file);
339         fwrite(ptr, len, 1, file);
340         fputs(diff_get_color(1, DIFF_RESET), file);
342         if (eol) {
343                 if (suppress_newline)
344                         buffer->suppressed_newline = 1;
345                 else
346                         putc('\n', file);
347         }
350 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
352         struct diff_words_data *diff_words = priv;
354         if (diff_words->minus.suppressed_newline) {
355                 if (line[0] != '+')
356                         putc('\n', diff_words->file);
357                 diff_words->minus.suppressed_newline = 0;
358         }
360         len--;
361         switch (line[0]) {
362                 case '-':
363                         print_word(diff_words->file,
364                                    &diff_words->minus, len, DIFF_FILE_OLD, 1);
365                         break;
366                 case '+':
367                         print_word(diff_words->file,
368                                    &diff_words->plus, len, DIFF_FILE_NEW, 0);
369                         break;
370                 case ' ':
371                         print_word(diff_words->file,
372                                    &diff_words->plus, len, DIFF_PLAIN, 0);
373                         diff_words->minus.current += len;
374                         break;
375         }
378 /* this executes the word diff on the accumulated buffers */
379 static void diff_words_show(struct diff_words_data *diff_words)
381         xpparam_t xpp;
382         xdemitconf_t xecfg;
383         xdemitcb_t ecb;
384         mmfile_t minus, plus;
385         int i;
387         memset(&xpp, 0, sizeof(xpp));
388         memset(&xecfg, 0, sizeof(xecfg));
389         minus.size = diff_words->minus.text.size;
390         minus.ptr = xmalloc(minus.size);
391         memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
392         for (i = 0; i < minus.size; i++)
393                 if (isspace(minus.ptr[i]))
394                         minus.ptr[i] = '\n';
395         diff_words->minus.current = 0;
397         plus.size = diff_words->plus.text.size;
398         plus.ptr = xmalloc(plus.size);
399         memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
400         for (i = 0; i < plus.size; i++)
401                 if (isspace(plus.ptr[i]))
402                         plus.ptr[i] = '\n';
403         diff_words->plus.current = 0;
405         xpp.flags = XDF_NEED_MINIMAL;
406         xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
407         xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
408                       &xpp, &xecfg, &ecb);
409         free(minus.ptr);
410         free(plus.ptr);
411         diff_words->minus.text.size = diff_words->plus.text.size = 0;
413         if (diff_words->minus.suppressed_newline) {
414                 putc('\n', diff_words->file);
415                 diff_words->minus.suppressed_newline = 0;
416         }
419 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
421 struct emit_callback {
422         int nparents, color_diff;
423         unsigned ws_rule;
424         sane_truncate_fn truncate;
425         const char **label_path;
426         struct diff_words_data *diff_words;
427         int *found_changesp;
428         FILE *file;
429 };
431 static void free_diff_words_data(struct emit_callback *ecbdata)
433         if (ecbdata->diff_words) {
434                 /* flush buffers */
435                 if (ecbdata->diff_words->minus.text.size ||
436                                 ecbdata->diff_words->plus.text.size)
437                         diff_words_show(ecbdata->diff_words);
439                 free (ecbdata->diff_words->minus.text.ptr);
440                 free (ecbdata->diff_words->plus.text.ptr);
441                 free(ecbdata->diff_words);
442                 ecbdata->diff_words = NULL;
443         }
446 const char *diff_get_color(int diff_use_color, enum color_diff ix)
448         if (diff_use_color)
449                 return diff_colors[ix];
450         return "";
453 static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
455         int has_trailing_newline, has_trailing_carriage_return;
457         has_trailing_newline = (len > 0 && line[len-1] == '\n');
458         if (has_trailing_newline)
459                 len--;
460         has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
461         if (has_trailing_carriage_return)
462                 len--;
464         fputs(set, file);
465         fwrite(line, len, 1, file);
466         fputs(reset, file);
467         if (has_trailing_carriage_return)
468                 fputc('\r', file);
469         if (has_trailing_newline)
470                 fputc('\n', file);
473 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
475         const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
476         const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
478         if (!*ws)
479                 emit_line(ecbdata->file, set, reset, line, len);
480         else {
481                 /* Emit just the prefix, then the rest. */
482                 emit_line(ecbdata->file, set, reset, line, ecbdata->nparents);
483                 ws_check_emit(line + ecbdata->nparents,
484                               len - ecbdata->nparents, ecbdata->ws_rule,
485                               ecbdata->file, set, reset, ws);
486         }
489 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
491         const char *cp;
492         unsigned long allot;
493         size_t l = len;
495         if (ecb->truncate)
496                 return ecb->truncate(line, len);
497         cp = line;
498         allot = l;
499         while (0 < l) {
500                 (void) utf8_width(&cp, &l);
501                 if (!cp)
502                         break; /* truncated in the middle? */
503         }
504         return allot - l;
507 static void fn_out_consume(void *priv, char *line, unsigned long len)
509         int i;
510         int color;
511         struct emit_callback *ecbdata = priv;
512         const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
513         const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
514         const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
516         *(ecbdata->found_changesp) = 1;
518         if (ecbdata->label_path[0]) {
519                 const char *name_a_tab, *name_b_tab;
521                 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
522                 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
524                 fprintf(ecbdata->file, "%s--- %s%s%s\n",
525                         meta, ecbdata->label_path[0], reset, name_a_tab);
526                 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
527                         meta, ecbdata->label_path[1], reset, name_b_tab);
528                 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
529         }
531         if (diff_suppress_blank_empty
532             && len == 2 && line[0] == ' ' && line[1] == '\n') {
533                 line[0] = '\n';
534                 len = 1;
535         }
537         /* This is not really necessary for now because
538          * this codepath only deals with two-way diffs.
539          */
540         for (i = 0; i < len && line[i] == '@'; i++)
541                 ;
542         if (2 <= i && i < len && line[i] == ' ') {
543                 ecbdata->nparents = i - 1;
544                 len = sane_truncate_line(ecbdata, line, len);
545                 emit_line(ecbdata->file,
546                           diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
547                           reset, line, len);
548                 if (line[len-1] != '\n')
549                         putc('\n', ecbdata->file);
550                 return;
551         }
553         if (len < ecbdata->nparents) {
554                 emit_line(ecbdata->file, reset, reset, line, len);
555                 return;
556         }
558         color = DIFF_PLAIN;
559         if (ecbdata->diff_words && ecbdata->nparents != 1)
560                 /* fall back to normal diff */
561                 free_diff_words_data(ecbdata);
562         if (ecbdata->diff_words) {
563                 if (line[0] == '-') {
564                         diff_words_append(line, len,
565                                           &ecbdata->diff_words->minus);
566                         return;
567                 } else if (line[0] == '+') {
568                         diff_words_append(line, len,
569                                           &ecbdata->diff_words->plus);
570                         return;
571                 }
572                 if (ecbdata->diff_words->minus.text.size ||
573                     ecbdata->diff_words->plus.text.size)
574                         diff_words_show(ecbdata->diff_words);
575                 line++;
576                 len--;
577                 emit_line(ecbdata->file, plain, reset, line, len);
578                 return;
579         }
580         for (i = 0; i < ecbdata->nparents && len; i++) {
581                 if (line[i] == '-')
582                         color = DIFF_FILE_OLD;
583                 else if (line[i] == '+')
584                         color = DIFF_FILE_NEW;
585         }
587         if (color != DIFF_FILE_NEW) {
588                 emit_line(ecbdata->file,
589                           diff_get_color(ecbdata->color_diff, color),
590                           reset, line, len);
591                 return;
592         }
593         emit_add_line(reset, ecbdata, line, len);
596 static char *pprint_rename(const char *a, const char *b)
598         const char *old = a;
599         const char *new = b;
600         struct strbuf name = STRBUF_INIT;
601         int pfx_length, sfx_length;
602         int len_a = strlen(a);
603         int len_b = strlen(b);
604         int a_midlen, b_midlen;
605         int qlen_a = quote_c_style(a, NULL, NULL, 0);
606         int qlen_b = quote_c_style(b, NULL, NULL, 0);
608         if (qlen_a || qlen_b) {
609                 quote_c_style(a, &name, NULL, 0);
610                 strbuf_addstr(&name, " => ");
611                 quote_c_style(b, &name, NULL, 0);
612                 return strbuf_detach(&name, NULL);
613         }
615         /* Find common prefix */
616         pfx_length = 0;
617         while (*old && *new && *old == *new) {
618                 if (*old == '/')
619                         pfx_length = old - a + 1;
620                 old++;
621                 new++;
622         }
624         /* Find common suffix */
625         old = a + len_a;
626         new = b + len_b;
627         sfx_length = 0;
628         while (a <= old && b <= new && *old == *new) {
629                 if (*old == '/')
630                         sfx_length = len_a - (old - a);
631                 old--;
632                 new--;
633         }
635         /*
636          * pfx{mid-a => mid-b}sfx
637          * {pfx-a => pfx-b}sfx
638          * pfx{sfx-a => sfx-b}
639          * name-a => name-b
640          */
641         a_midlen = len_a - pfx_length - sfx_length;
642         b_midlen = len_b - pfx_length - sfx_length;
643         if (a_midlen < 0)
644                 a_midlen = 0;
645         if (b_midlen < 0)
646                 b_midlen = 0;
648         strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
649         if (pfx_length + sfx_length) {
650                 strbuf_add(&name, a, pfx_length);
651                 strbuf_addch(&name, '{');
652         }
653         strbuf_add(&name, a + pfx_length, a_midlen);
654         strbuf_addstr(&name, " => ");
655         strbuf_add(&name, b + pfx_length, b_midlen);
656         if (pfx_length + sfx_length) {
657                 strbuf_addch(&name, '}');
658                 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
659         }
660         return strbuf_detach(&name, NULL);
663 struct diffstat_t {
664         int nr;
665         int alloc;
666         struct diffstat_file {
667                 char *from_name;
668                 char *name;
669                 char *print_name;
670                 unsigned is_unmerged:1;
671                 unsigned is_binary:1;
672                 unsigned is_renamed:1;
673                 unsigned int added, deleted;
674         } **files;
675 };
677 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
678                                           const char *name_a,
679                                           const char *name_b)
681         struct diffstat_file *x;
682         x = xcalloc(sizeof (*x), 1);
683         if (diffstat->nr == diffstat->alloc) {
684                 diffstat->alloc = alloc_nr(diffstat->alloc);
685                 diffstat->files = xrealloc(diffstat->files,
686                                 diffstat->alloc * sizeof(x));
687         }
688         diffstat->files[diffstat->nr++] = x;
689         if (name_b) {
690                 x->from_name = xstrdup(name_a);
691                 x->name = xstrdup(name_b);
692                 x->is_renamed = 1;
693         }
694         else {
695                 x->from_name = NULL;
696                 x->name = xstrdup(name_a);
697         }
698         return x;
701 static void diffstat_consume(void *priv, char *line, unsigned long len)
703         struct diffstat_t *diffstat = priv;
704         struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
706         if (line[0] == '+')
707                 x->added++;
708         else if (line[0] == '-')
709                 x->deleted++;
712 const char mime_boundary_leader[] = "------------";
714 static int scale_linear(int it, int width, int max_change)
716         /*
717          * make sure that at least one '-' is printed if there were deletions,
718          * and likewise for '+'.
719          */
720         if (max_change < 2)
721                 return it;
722         return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
725 static void show_name(FILE *file,
726                       const char *prefix, const char *name, int len,
727                       const char *reset, const char *set)
729         fprintf(file, " %s%s%-*s%s |", set, prefix, len, name, reset);
732 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
734         if (cnt <= 0)
735                 return;
736         fprintf(file, "%s", set);
737         while (cnt--)
738                 putc(ch, file);
739         fprintf(file, "%s", reset);
742 static void fill_print_name(struct diffstat_file *file)
744         char *pname;
746         if (file->print_name)
747                 return;
749         if (!file->is_renamed) {
750                 struct strbuf buf = STRBUF_INIT;
751                 if (quote_c_style(file->name, &buf, NULL, 0)) {
752                         pname = strbuf_detach(&buf, NULL);
753                 } else {
754                         pname = file->name;
755                         strbuf_release(&buf);
756                 }
757         } else {
758                 pname = pprint_rename(file->from_name, file->name);
759         }
760         file->print_name = pname;
763 static void show_stats(struct diffstat_t* data, struct diff_options *options)
765         int i, len, add, del, total, adds = 0, dels = 0;
766         int max_change = 0, max_len = 0;
767         int total_files = data->nr;
768         int width, name_width;
769         const char *reset, *set, *add_c, *del_c;
771         if (data->nr == 0)
772                 return;
774         width = options->stat_width ? options->stat_width : 80;
775         name_width = options->stat_name_width ? options->stat_name_width : 50;
777         /* Sanity: give at least 5 columns to the graph,
778          * but leave at least 10 columns for the name.
779          */
780         if (width < 25)
781                 width = 25;
782         if (name_width < 10)
783                 name_width = 10;
784         else if (width < name_width + 15)
785                 name_width = width - 15;
787         /* Find the longest filename and max number of changes */
788         reset = diff_get_color_opt(options, DIFF_RESET);
789         set   = diff_get_color_opt(options, DIFF_PLAIN);
790         add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
791         del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
793         for (i = 0; i < data->nr; i++) {
794                 struct diffstat_file *file = data->files[i];
795                 int change = file->added + file->deleted;
796                 fill_print_name(file);
797                 len = strlen(file->print_name);
798                 if (max_len < len)
799                         max_len = len;
801                 if (file->is_binary || file->is_unmerged)
802                         continue;
803                 if (max_change < change)
804                         max_change = change;
805         }
807         /* Compute the width of the graph part;
808          * 10 is for one blank at the beginning of the line plus
809          * " | count " between the name and the graph.
810          *
811          * From here on, name_width is the width of the name area,
812          * and width is the width of the graph area.
813          */
814         name_width = (name_width < max_len) ? name_width : max_len;
815         if (width < (name_width + 10) + max_change)
816                 width = width - (name_width + 10);
817         else
818                 width = max_change;
820         for (i = 0; i < data->nr; i++) {
821                 const char *prefix = "";
822                 char *name = data->files[i]->print_name;
823                 int added = data->files[i]->added;
824                 int deleted = data->files[i]->deleted;
825                 int name_len;
827                 /*
828                  * "scale" the filename
829                  */
830                 len = name_width;
831                 name_len = strlen(name);
832                 if (name_width < name_len) {
833                         char *slash;
834                         prefix = "...";
835                         len -= 3;
836                         name += name_len - len;
837                         slash = strchr(name, '/');
838                         if (slash)
839                                 name = slash;
840                 }
842                 if (data->files[i]->is_binary) {
843                         show_name(options->file, prefix, name, len, reset, set);
844                         fprintf(options->file, "  Bin ");
845                         fprintf(options->file, "%s%d%s", del_c, deleted, reset);
846                         fprintf(options->file, " -> ");
847                         fprintf(options->file, "%s%d%s", add_c, added, reset);
848                         fprintf(options->file, " bytes");
849                         fprintf(options->file, "\n");
850                         continue;
851                 }
852                 else if (data->files[i]->is_unmerged) {
853                         show_name(options->file, prefix, name, len, reset, set);
854                         fprintf(options->file, "  Unmerged\n");
855                         continue;
856                 }
857                 else if (!data->files[i]->is_renamed &&
858                          (added + deleted == 0)) {
859                         total_files--;
860                         continue;
861                 }
863                 /*
864                  * scale the add/delete
865                  */
866                 add = added;
867                 del = deleted;
868                 total = add + del;
869                 adds += add;
870                 dels += del;
872                 if (width <= max_change) {
873                         add = scale_linear(add, width, max_change);
874                         del = scale_linear(del, width, max_change);
875                         total = add + del;
876                 }
877                 show_name(options->file, prefix, name, len, reset, set);
878                 fprintf(options->file, "%5d%s", added + deleted,
879                                 added + deleted ? " " : "");
880                 show_graph(options->file, '+', add, add_c, reset);
881                 show_graph(options->file, '-', del, del_c, reset);
882                 fprintf(options->file, "\n");
883         }
884         fprintf(options->file,
885                "%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
886                set, total_files, adds, dels, reset);
889 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
891         int i, adds = 0, dels = 0, total_files = data->nr;
893         if (data->nr == 0)
894                 return;
896         for (i = 0; i < data->nr; i++) {
897                 if (!data->files[i]->is_binary &&
898                     !data->files[i]->is_unmerged) {
899                         int added = data->files[i]->added;
900                         int deleted= data->files[i]->deleted;
901                         if (!data->files[i]->is_renamed &&
902                             (added + deleted == 0)) {
903                                 total_files--;
904                         } else {
905                                 adds += added;
906                                 dels += deleted;
907                         }
908                 }
909         }
910         fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
911                total_files, adds, dels);
914 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
916         int i;
918         if (data->nr == 0)
919                 return;
921         for (i = 0; i < data->nr; i++) {
922                 struct diffstat_file *file = data->files[i];
924                 if (file->is_binary)
925                         fprintf(options->file, "-\t-\t");
926                 else
927                         fprintf(options->file,
928                                 "%d\t%d\t", file->added, file->deleted);
929                 if (options->line_termination) {
930                         fill_print_name(file);
931                         if (!file->is_renamed)
932                                 write_name_quoted(file->name, options->file,
933                                                   options->line_termination);
934                         else {
935                                 fputs(file->print_name, options->file);
936                                 putc(options->line_termination, options->file);
937                         }
938                 } else {
939                         if (file->is_renamed) {
940                                 putc('\0', options->file);
941                                 write_name_quoted(file->from_name, options->file, '\0');
942                         }
943                         write_name_quoted(file->name, options->file, '\0');
944                 }
945         }
948 struct dirstat_file {
949         const char *name;
950         unsigned long changed;
951 };
953 struct dirstat_dir {
954         struct dirstat_file *files;
955         int alloc, nr, percent, cumulative;
956 };
958 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
960         unsigned long this_dir = 0;
961         unsigned int sources = 0;
963         while (dir->nr) {
964                 struct dirstat_file *f = dir->files;
965                 int namelen = strlen(f->name);
966                 unsigned long this;
967                 char *slash;
969                 if (namelen < baselen)
970                         break;
971                 if (memcmp(f->name, base, baselen))
972                         break;
973                 slash = strchr(f->name + baselen, '/');
974                 if (slash) {
975                         int newbaselen = slash + 1 - f->name;
976                         this = gather_dirstat(file, dir, changed, f->name, newbaselen);
977                         sources++;
978                 } else {
979                         this = f->changed;
980                         dir->files++;
981                         dir->nr--;
982                         sources += 2;
983                 }
984                 this_dir += this;
985         }
987         /*
988          * We don't report dirstat's for
989          *  - the top level
990          *  - or cases where everything came from a single directory
991          *    under this directory (sources == 1).
992          */
993         if (baselen && sources != 1) {
994                 int permille = this_dir * 1000 / changed;
995                 if (permille) {
996                         int percent = permille / 10;
997                         if (percent >= dir->percent) {
998                                 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
999                                 if (!dir->cumulative)
1000                                         return 0;
1001                         }
1002                 }
1003         }
1004         return this_dir;
1007 static int dirstat_compare(const void *_a, const void *_b)
1009         const struct dirstat_file *a = _a;
1010         const struct dirstat_file *b = _b;
1011         return strcmp(a->name, b->name);
1014 static void show_dirstat(struct diff_options *options)
1016         int i;
1017         unsigned long changed;
1018         struct dirstat_dir dir;
1019         struct diff_queue_struct *q = &diff_queued_diff;
1021         dir.files = NULL;
1022         dir.alloc = 0;
1023         dir.nr = 0;
1024         dir.percent = options->dirstat_percent;
1025         dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1027         changed = 0;
1028         for (i = 0; i < q->nr; i++) {
1029                 struct diff_filepair *p = q->queue[i];
1030                 const char *name;
1031                 unsigned long copied, added, damage;
1033                 name = p->one->path ? p->one->path : p->two->path;
1035                 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1036                         diff_populate_filespec(p->one, 0);
1037                         diff_populate_filespec(p->two, 0);
1038                         diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1039                                                &copied, &added);
1040                         diff_free_filespec_data(p->one);
1041                         diff_free_filespec_data(p->two);
1042                 } else if (DIFF_FILE_VALID(p->one)) {
1043                         diff_populate_filespec(p->one, 1);
1044                         copied = added = 0;
1045                         diff_free_filespec_data(p->one);
1046                 } else if (DIFF_FILE_VALID(p->two)) {
1047                         diff_populate_filespec(p->two, 1);
1048                         copied = 0;
1049                         added = p->two->size;
1050                         diff_free_filespec_data(p->two);
1051                 } else
1052                         continue;
1054                 /*
1055                  * Original minus copied is the removed material,
1056                  * added is the new material.  They are both damages
1057                  * made to the preimage. In --dirstat-by-file mode, count
1058                  * damaged files, not damaged lines. This is done by
1059                  * counting only a single damaged line per file.
1060                  */
1061                 damage = (p->one->size - copied) + added;
1062                 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1063                         damage = 1;
1065                 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1066                 dir.files[dir.nr].name = name;
1067                 dir.files[dir.nr].changed = damage;
1068                 changed += damage;
1069                 dir.nr++;
1070         }
1072         /* This can happen even with many files, if everything was renames */
1073         if (!changed)
1074                 return;
1076         /* Show all directories with more than x% of the changes */
1077         qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1078         gather_dirstat(options->file, &dir, changed, "", 0);
1081 static void free_diffstat_info(struct diffstat_t *diffstat)
1083         int i;
1084         for (i = 0; i < diffstat->nr; i++) {
1085                 struct diffstat_file *f = diffstat->files[i];
1086                 if (f->name != f->print_name)
1087                         free(f->print_name);
1088                 free(f->name);
1089                 free(f->from_name);
1090                 free(f);
1091         }
1092         free(diffstat->files);
1095 struct checkdiff_t {
1096         const char *filename;
1097         int lineno;
1098         struct diff_options *o;
1099         unsigned ws_rule;
1100         unsigned status;
1101         int trailing_blanks_start;
1102 };
1104 static int is_conflict_marker(const char *line, unsigned long len)
1106         char firstchar;
1107         int cnt;
1109         if (len < 8)
1110                 return 0;
1111         firstchar = line[0];
1112         switch (firstchar) {
1113         case '=': case '>': case '<':
1114                 break;
1115         default:
1116                 return 0;
1117         }
1118         for (cnt = 1; cnt < 7; cnt++)
1119                 if (line[cnt] != firstchar)
1120                         return 0;
1121         /* line[0] thru line[6] are same as firstchar */
1122         if (firstchar == '=') {
1123                 /* divider between ours and theirs? */
1124                 if (len != 8 || line[7] != '\n')
1125                         return 0;
1126         } else if (len < 8 || !isspace(line[7])) {
1127                 /* not divider before ours nor after theirs */
1128                 return 0;
1129         }
1130         return 1;
1133 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1135         struct checkdiff_t *data = priv;
1136         int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1137         const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1138         const char *reset = diff_get_color(color_diff, DIFF_RESET);
1139         const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1140         char *err;
1142         if (line[0] == '+') {
1143                 unsigned bad;
1144                 data->lineno++;
1145                 if (!ws_blank_line(line + 1, len - 1, data->ws_rule))
1146                         data->trailing_blanks_start = 0;
1147                 else if (!data->trailing_blanks_start)
1148                         data->trailing_blanks_start = data->lineno;
1149                 if (is_conflict_marker(line + 1, len - 1)) {
1150                         data->status |= 1;
1151                         fprintf(data->o->file,
1152                                 "%s:%d: leftover conflict marker\n",
1153                                 data->filename, data->lineno);
1154                 }
1155                 bad = ws_check(line + 1, len - 1, data->ws_rule);
1156                 if (!bad)
1157                         return;
1158                 data->status |= bad;
1159                 err = whitespace_error_string(bad);
1160                 fprintf(data->o->file, "%s:%d: %s.\n",
1161                         data->filename, data->lineno, err);
1162                 free(err);
1163                 emit_line(data->o->file, set, reset, line, 1);
1164                 ws_check_emit(line + 1, len - 1, data->ws_rule,
1165                               data->o->file, set, reset, ws);
1166         } else if (line[0] == ' ') {
1167                 data->lineno++;
1168                 data->trailing_blanks_start = 0;
1169         } else if (line[0] == '@') {
1170                 char *plus = strchr(line, '+');
1171                 if (plus)
1172                         data->lineno = strtol(plus, NULL, 10) - 1;
1173                 else
1174                         die("invalid diff");
1175                 data->trailing_blanks_start = 0;
1176         }
1179 static unsigned char *deflate_it(char *data,
1180                                  unsigned long size,
1181                                  unsigned long *result_size)
1183         int bound;
1184         unsigned char *deflated;
1185         z_stream stream;
1187         memset(&stream, 0, sizeof(stream));
1188         deflateInit(&stream, zlib_compression_level);
1189         bound = deflateBound(&stream, size);
1190         deflated = xmalloc(bound);
1191         stream.next_out = deflated;
1192         stream.avail_out = bound;
1194         stream.next_in = (unsigned char *)data;
1195         stream.avail_in = size;
1196         while (deflate(&stream, Z_FINISH) == Z_OK)
1197                 ; /* nothing */
1198         deflateEnd(&stream);
1199         *result_size = stream.total_out;
1200         return deflated;
1203 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1205         void *cp;
1206         void *delta;
1207         void *deflated;
1208         void *data;
1209         unsigned long orig_size;
1210         unsigned long delta_size;
1211         unsigned long deflate_size;
1212         unsigned long data_size;
1214         /* We could do deflated delta, or we could do just deflated two,
1215          * whichever is smaller.
1216          */
1217         delta = NULL;
1218         deflated = deflate_it(two->ptr, two->size, &deflate_size);
1219         if (one->size && two->size) {
1220                 delta = diff_delta(one->ptr, one->size,
1221                                    two->ptr, two->size,
1222                                    &delta_size, deflate_size);
1223                 if (delta) {
1224                         void *to_free = delta;
1225                         orig_size = delta_size;
1226                         delta = deflate_it(delta, delta_size, &delta_size);
1227                         free(to_free);
1228                 }
1229         }
1231         if (delta && delta_size < deflate_size) {
1232                 fprintf(file, "delta %lu\n", orig_size);
1233                 free(deflated);
1234                 data = delta;
1235                 data_size = delta_size;
1236         }
1237         else {
1238                 fprintf(file, "literal %lu\n", two->size);
1239                 free(delta);
1240                 data = deflated;
1241                 data_size = deflate_size;
1242         }
1244         /* emit data encoded in base85 */
1245         cp = data;
1246         while (data_size) {
1247                 int bytes = (52 < data_size) ? 52 : data_size;
1248                 char line[70];
1249                 data_size -= bytes;
1250                 if (bytes <= 26)
1251                         line[0] = bytes + 'A' - 1;
1252                 else
1253                         line[0] = bytes - 26 + 'a' - 1;
1254                 encode_85(line + 1, cp, bytes);
1255                 cp = (char *) cp + bytes;
1256                 fputs(line, file);
1257                 fputc('\n', file);
1258         }
1259         fprintf(file, "\n");
1260         free(data);
1263 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1265         fprintf(file, "GIT binary patch\n");
1266         emit_binary_diff_body(file, one, two);
1267         emit_binary_diff_body(file, two, one);
1270 static void diff_filespec_load_driver(struct diff_filespec *one)
1272         if (!one->driver)
1273                 one->driver = userdiff_find_by_path(one->path);
1274         if (!one->driver)
1275                 one->driver = userdiff_find_by_name("default");
1278 int diff_filespec_is_binary(struct diff_filespec *one)
1280         if (one->is_binary == -1) {
1281                 diff_filespec_load_driver(one);
1282                 if (one->driver->binary != -1)
1283                         one->is_binary = one->driver->binary;
1284                 else {
1285                         if (!one->data && DIFF_FILE_VALID(one))
1286                                 diff_populate_filespec(one, 0);
1287                         if (one->data)
1288                                 one->is_binary = buffer_is_binary(one->data,
1289                                                 one->size);
1290                         if (one->is_binary == -1)
1291                                 one->is_binary = 0;
1292                 }
1293         }
1294         return one->is_binary;
1297 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1299         diff_filespec_load_driver(one);
1300         return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1303 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1305         if (!options->a_prefix)
1306                 options->a_prefix = a;
1307         if (!options->b_prefix)
1308                 options->b_prefix = b;
1311 static const char *get_textconv(struct diff_filespec *one)
1313         if (!DIFF_FILE_VALID(one))
1314                 return NULL;
1315         if (!S_ISREG(one->mode))
1316                 return NULL;
1317         diff_filespec_load_driver(one);
1318         return one->driver->textconv;
1321 static void builtin_diff(const char *name_a,
1322                          const char *name_b,
1323                          struct diff_filespec *one,
1324                          struct diff_filespec *two,
1325                          const char *xfrm_msg,
1326                          struct diff_options *o,
1327                          int complete_rewrite)
1329         mmfile_t mf1, mf2;
1330         const char *lbl[2];
1331         char *a_one, *b_two;
1332         const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1333         const char *reset = diff_get_color_opt(o, DIFF_RESET);
1334         const char *a_prefix, *b_prefix;
1335         const char *textconv_one = NULL, *textconv_two = NULL;
1337         diff_set_mnemonic_prefix(o, "a/", "b/");
1338         if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1339                 a_prefix = o->b_prefix;
1340                 b_prefix = o->a_prefix;
1341         } else {
1342                 a_prefix = o->a_prefix;
1343                 b_prefix = o->b_prefix;
1344         }
1346         /* Never use a non-valid filename anywhere if at all possible */
1347         name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1348         name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1350         a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1351         b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1352         lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1353         lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1354         fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1355         if (lbl[0][0] == '/') {
1356                 /* /dev/null */
1357                 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1358                 if (xfrm_msg && xfrm_msg[0])
1359                         fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1360         }
1361         else if (lbl[1][0] == '/') {
1362                 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1363                 if (xfrm_msg && xfrm_msg[0])
1364                         fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1365         }
1366         else {
1367                 if (one->mode != two->mode) {
1368                         fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1369                         fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1370                 }
1371                 if (xfrm_msg && xfrm_msg[0])
1372                         fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1373                 /*
1374                  * we do not run diff between different kind
1375                  * of objects.
1376                  */
1377                 if ((one->mode ^ two->mode) & S_IFMT)
1378                         goto free_ab_and_return;
1379                 if (complete_rewrite &&
1380                     !diff_filespec_is_binary(one) &&
1381                     !diff_filespec_is_binary(two)) {
1382                         emit_rewrite_diff(name_a, name_b, one, two, o);
1383                         o->found_changes = 1;
1384                         goto free_ab_and_return;
1385                 }
1386         }
1388         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1389                 die("unable to read files to diff");
1391         if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1392                 textconv_one = get_textconv(one);
1393                 textconv_two = get_textconv(two);
1394         }
1396         if (!DIFF_OPT_TST(o, TEXT) &&
1397             ( (diff_filespec_is_binary(one) && !textconv_one) ||
1398               (diff_filespec_is_binary(two) && !textconv_two) )) {
1399                 /* Quite common confusing case */
1400                 if (mf1.size == mf2.size &&
1401                     !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1402                         goto free_ab_and_return;
1403                 if (DIFF_OPT_TST(o, BINARY))
1404                         emit_binary_diff(o->file, &mf1, &mf2);
1405                 else
1406                         fprintf(o->file, "Binary files %s and %s differ\n",
1407                                 lbl[0], lbl[1]);
1408                 o->found_changes = 1;
1409         }
1410         else {
1411                 /* Crazy xdl interfaces.. */
1412                 const char *diffopts = getenv("GIT_DIFF_OPTS");
1413                 xpparam_t xpp;
1414                 xdemitconf_t xecfg;
1415                 xdemitcb_t ecb;
1416                 struct emit_callback ecbdata;
1417                 const struct userdiff_funcname *pe;
1419                 if (textconv_one) {
1420                         size_t size;
1421                         mf1.ptr = run_textconv(textconv_one, one, &size);
1422                         if (!mf1.ptr)
1423                                 die("unable to read files to diff");
1424                         mf1.size = size;
1425                 }
1426                 if (textconv_two) {
1427                         size_t size;
1428                         mf2.ptr = run_textconv(textconv_two, two, &size);
1429                         if (!mf2.ptr)
1430                                 die("unable to read files to diff");
1431                         mf2.size = size;
1432                 }
1434                 pe = diff_funcname_pattern(one);
1435                 if (!pe)
1436                         pe = diff_funcname_pattern(two);
1438                 memset(&xpp, 0, sizeof(xpp));
1439                 memset(&xecfg, 0, sizeof(xecfg));
1440                 memset(&ecbdata, 0, sizeof(ecbdata));
1441                 ecbdata.label_path = lbl;
1442                 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1443                 ecbdata.found_changesp = &o->found_changes;
1444                 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1445                 ecbdata.file = o->file;
1446                 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1447                 xecfg.ctxlen = o->context;
1448                 xecfg.flags = XDL_EMIT_FUNCNAMES;
1449                 if (pe)
1450                         xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1451                 if (!diffopts)
1452                         ;
1453                 else if (!prefixcmp(diffopts, "--unified="))
1454                         xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1455                 else if (!prefixcmp(diffopts, "-u"))
1456                         xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1457                 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1458                         ecbdata.diff_words =
1459                                 xcalloc(1, sizeof(struct diff_words_data));
1460                         ecbdata.diff_words->file = o->file;
1461                 }
1462                 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1463                               &xpp, &xecfg, &ecb);
1464                 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1465                         free_diff_words_data(&ecbdata);
1466                 if (textconv_one)
1467                         free(mf1.ptr);
1468                 if (textconv_two)
1469                         free(mf2.ptr);
1470         }
1472  free_ab_and_return:
1473         diff_free_filespec_data(one);
1474         diff_free_filespec_data(two);
1475         free(a_one);
1476         free(b_two);
1477         return;
1480 static void builtin_diffstat(const char *name_a, const char *name_b,
1481                              struct diff_filespec *one,
1482                              struct diff_filespec *two,
1483                              struct diffstat_t *diffstat,
1484                              struct diff_options *o,
1485                              int complete_rewrite)
1487         mmfile_t mf1, mf2;
1488         struct diffstat_file *data;
1490         data = diffstat_add(diffstat, name_a, name_b);
1492         if (!one || !two) {
1493                 data->is_unmerged = 1;
1494                 return;
1495         }
1496         if (complete_rewrite) {
1497                 diff_populate_filespec(one, 0);
1498                 diff_populate_filespec(two, 0);
1499                 data->deleted = count_lines(one->data, one->size);
1500                 data->added = count_lines(two->data, two->size);
1501                 goto free_and_return;
1502         }
1503         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1504                 die("unable to read files to diff");
1506         if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1507                 data->is_binary = 1;
1508                 data->added = mf2.size;
1509                 data->deleted = mf1.size;
1510         } else {
1511                 /* Crazy xdl interfaces.. */
1512                 xpparam_t xpp;
1513                 xdemitconf_t xecfg;
1514                 xdemitcb_t ecb;
1516                 memset(&xpp, 0, sizeof(xpp));
1517                 memset(&xecfg, 0, sizeof(xecfg));
1518                 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1519                 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1520                               &xpp, &xecfg, &ecb);
1521         }
1523  free_and_return:
1524         diff_free_filespec_data(one);
1525         diff_free_filespec_data(two);
1528 static void builtin_checkdiff(const char *name_a, const char *name_b,
1529                               const char *attr_path,
1530                               struct diff_filespec *one,
1531                               struct diff_filespec *two,
1532                               struct diff_options *o)
1534         mmfile_t mf1, mf2;
1535         struct checkdiff_t data;
1537         if (!two)
1538                 return;
1540         memset(&data, 0, sizeof(data));
1541         data.filename = name_b ? name_b : name_a;
1542         data.lineno = 0;
1543         data.o = o;
1544         data.ws_rule = whitespace_rule(attr_path);
1546         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1547                 die("unable to read files to diff");
1549         /*
1550          * All the other codepaths check both sides, but not checking
1551          * the "old" side here is deliberate.  We are checking the newly
1552          * introduced changes, and as long as the "new" side is text, we
1553          * can and should check what it introduces.
1554          */
1555         if (diff_filespec_is_binary(two))
1556                 goto free_and_return;
1557         else {
1558                 /* Crazy xdl interfaces.. */
1559                 xpparam_t xpp;
1560                 xdemitconf_t xecfg;
1561                 xdemitcb_t ecb;
1563                 memset(&xpp, 0, sizeof(xpp));
1564                 memset(&xecfg, 0, sizeof(xecfg));
1565                 xecfg.ctxlen = 1; /* at least one context line */
1566                 xpp.flags = XDF_NEED_MINIMAL;
1567                 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1568                               &xpp, &xecfg, &ecb);
1570                 if ((data.ws_rule & WS_TRAILING_SPACE) &&
1571                     data.trailing_blanks_start) {
1572                         fprintf(o->file, "%s:%d: ends with blank lines.\n",
1573                                 data.filename, data.trailing_blanks_start);
1574                         data.status = 1; /* report errors */
1575                 }
1576         }
1577  free_and_return:
1578         diff_free_filespec_data(one);
1579         diff_free_filespec_data(two);
1580         if (data.status)
1581                 DIFF_OPT_SET(o, CHECK_FAILED);
1584 struct diff_filespec *alloc_filespec(const char *path)
1586         int namelen = strlen(path);
1587         struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1589         memset(spec, 0, sizeof(*spec));
1590         spec->path = (char *)(spec + 1);
1591         memcpy(spec->path, path, namelen+1);
1592         spec->count = 1;
1593         spec->is_binary = -1;
1594         return spec;
1597 void free_filespec(struct diff_filespec *spec)
1599         if (!--spec->count) {
1600                 diff_free_filespec_data(spec);
1601                 free(spec);
1602         }
1605 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1606                    unsigned short mode)
1608         if (mode) {
1609                 spec->mode = canon_mode(mode);
1610                 hashcpy(spec->sha1, sha1);
1611                 spec->sha1_valid = !is_null_sha1(sha1);
1612         }
1615 /*
1616  * Given a name and sha1 pair, if the index tells us the file in
1617  * the work tree has that object contents, return true, so that
1618  * prepare_temp_file() does not have to inflate and extract.
1619  */
1620 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1622         struct cache_entry *ce;
1623         struct stat st;
1624         int pos, len;
1626         /* We do not read the cache ourselves here, because the
1627          * benchmark with my previous version that always reads cache
1628          * shows that it makes things worse for diff-tree comparing
1629          * two linux-2.6 kernel trees in an already checked out work
1630          * tree.  This is because most diff-tree comparisons deal with
1631          * only a small number of files, while reading the cache is
1632          * expensive for a large project, and its cost outweighs the
1633          * savings we get by not inflating the object to a temporary
1634          * file.  Practically, this code only helps when we are used
1635          * by diff-cache --cached, which does read the cache before
1636          * calling us.
1637          */
1638         if (!active_cache)
1639                 return 0;
1641         /* We want to avoid the working directory if our caller
1642          * doesn't need the data in a normal file, this system
1643          * is rather slow with its stat/open/mmap/close syscalls,
1644          * and the object is contained in a pack file.  The pack
1645          * is probably already open and will be faster to obtain
1646          * the data through than the working directory.  Loose
1647          * objects however would tend to be slower as they need
1648          * to be individually opened and inflated.
1649          */
1650         if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1651                 return 0;
1653         len = strlen(name);
1654         pos = cache_name_pos(name, len);
1655         if (pos < 0)
1656                 return 0;
1657         ce = active_cache[pos];
1659         /*
1660          * This is not the sha1 we are looking for, or
1661          * unreusable because it is not a regular file.
1662          */
1663         if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1664                 return 0;
1666         /*
1667          * If ce matches the file in the work tree, we can reuse it.
1668          */
1669         if (ce_uptodate(ce) ||
1670             (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1671                 return 1;
1673         return 0;
1676 static int populate_from_stdin(struct diff_filespec *s)
1678         struct strbuf buf = STRBUF_INIT;
1679         size_t size = 0;
1681         if (strbuf_read(&buf, 0, 0) < 0)
1682                 return error("error while reading from stdin %s",
1683                                      strerror(errno));
1685         s->should_munmap = 0;
1686         s->data = strbuf_detach(&buf, &size);
1687         s->size = size;
1688         s->should_free = 1;
1689         return 0;
1692 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1694         int len;
1695         char *data = xmalloc(100);
1696         len = snprintf(data, 100,
1697                 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1698         s->data = data;
1699         s->size = len;
1700         s->should_free = 1;
1701         if (size_only) {
1702                 s->data = NULL;
1703                 free(data);
1704         }
1705         return 0;
1708 /*
1709  * While doing rename detection and pickaxe operation, we may need to
1710  * grab the data for the blob (or file) for our own in-core comparison.
1711  * diff_filespec has data and size fields for this purpose.
1712  */
1713 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1715         int err = 0;
1716         if (!DIFF_FILE_VALID(s))
1717                 die("internal error: asking to populate invalid file.");
1718         if (S_ISDIR(s->mode))
1719                 return -1;
1721         if (s->data)
1722                 return 0;
1724         if (size_only && 0 < s->size)
1725                 return 0;
1727         if (S_ISGITLINK(s->mode))
1728                 return diff_populate_gitlink(s, size_only);
1730         if (!s->sha1_valid ||
1731             reuse_worktree_file(s->path, s->sha1, 0)) {
1732                 struct strbuf buf = STRBUF_INIT;
1733                 struct stat st;
1734                 int fd;
1736                 if (!strcmp(s->path, "-"))
1737                         return populate_from_stdin(s);
1739                 if (lstat(s->path, &st) < 0) {
1740                         if (errno == ENOENT) {
1741                         err_empty:
1742                                 err = -1;
1743                         empty:
1744                                 s->data = (char *)"";
1745                                 s->size = 0;
1746                                 return err;
1747                         }
1748                 }
1749                 s->size = xsize_t(st.st_size);
1750                 if (!s->size)
1751                         goto empty;
1752                 if (size_only)
1753                         return 0;
1754                 if (S_ISLNK(st.st_mode)) {
1755                         int ret;
1756                         s->data = xmalloc(s->size);
1757                         s->should_free = 1;
1758                         ret = readlink(s->path, s->data, s->size);
1759                         if (ret < 0) {
1760                                 free(s->data);
1761                                 goto err_empty;
1762                         }
1763                         return 0;
1764                 }
1765                 fd = open(s->path, O_RDONLY);
1766                 if (fd < 0)
1767                         goto err_empty;
1768                 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1769                 close(fd);
1770                 s->should_munmap = 1;
1772                 /*
1773                  * Convert from working tree format to canonical git format
1774                  */
1775                 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
1776                         size_t size = 0;
1777                         munmap(s->data, s->size);
1778                         s->should_munmap = 0;
1779                         s->data = strbuf_detach(&buf, &size);
1780                         s->size = size;
1781                         s->should_free = 1;
1782                 }
1783         }
1784         else {
1785                 enum object_type type;
1786                 if (size_only)
1787                         type = sha1_object_info(s->sha1, &s->size);
1788                 else {
1789                         s->data = read_sha1_file(s->sha1, &type, &s->size);
1790                         s->should_free = 1;
1791                 }
1792         }
1793         return 0;
1796 void diff_free_filespec_blob(struct diff_filespec *s)
1798         if (s->should_free)
1799                 free(s->data);
1800         else if (s->should_munmap)
1801                 munmap(s->data, s->size);
1803         if (s->should_free || s->should_munmap) {
1804                 s->should_free = s->should_munmap = 0;
1805                 s->data = NULL;
1806         }
1809 void diff_free_filespec_data(struct diff_filespec *s)
1811         diff_free_filespec_blob(s);
1812         free(s->cnt_data);
1813         s->cnt_data = NULL;
1816 static void prep_temp_blob(struct diff_tempfile *temp,
1817                            void *blob,
1818                            unsigned long size,
1819                            const unsigned char *sha1,
1820                            int mode)
1822         int fd;
1824         fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1825         if (fd < 0)
1826                 die("unable to create temp-file: %s", strerror(errno));
1827         if (write_in_full(fd, blob, size) != size)
1828                 die("unable to write temp-file");
1829         close(fd);
1830         temp->name = temp->tmp_path;
1831         strcpy(temp->hex, sha1_to_hex(sha1));
1832         temp->hex[40] = 0;
1833         sprintf(temp->mode, "%06o", mode);
1836 static void prepare_temp_file(const char *name,
1837                               struct diff_tempfile *temp,
1838                               struct diff_filespec *one)
1840         if (!DIFF_FILE_VALID(one)) {
1841         not_a_valid_file:
1842                 /* A '-' entry produces this for file-2, and
1843                  * a '+' entry produces this for file-1.
1844                  */
1845                 temp->name = "/dev/null";
1846                 strcpy(temp->hex, ".");
1847                 strcpy(temp->mode, ".");
1848                 return;
1849         }
1851         if (!one->sha1_valid ||
1852             reuse_worktree_file(name, one->sha1, 1)) {
1853                 struct stat st;
1854                 if (lstat(name, &st) < 0) {
1855                         if (errno == ENOENT)
1856                                 goto not_a_valid_file;
1857                         die("stat(%s): %s", name, strerror(errno));
1858                 }
1859                 if (S_ISLNK(st.st_mode)) {
1860                         int ret;
1861                         char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1862                         size_t sz = xsize_t(st.st_size);
1863                         if (sizeof(buf) <= st.st_size)
1864                                 die("symlink too long: %s", name);
1865                         ret = readlink(name, buf, sz);
1866                         if (ret < 0)
1867                                 die("readlink(%s)", name);
1868                         prep_temp_blob(temp, buf, sz,
1869                                        (one->sha1_valid ?
1870                                         one->sha1 : null_sha1),
1871                                        (one->sha1_valid ?
1872                                         one->mode : S_IFLNK));
1873                 }
1874                 else {
1875                         /* we can borrow from the file in the work tree */
1876                         temp->name = name;
1877                         if (!one->sha1_valid)
1878                                 strcpy(temp->hex, sha1_to_hex(null_sha1));
1879                         else
1880                                 strcpy(temp->hex, sha1_to_hex(one->sha1));
1881                         /* Even though we may sometimes borrow the
1882                          * contents from the work tree, we always want
1883                          * one->mode.  mode is trustworthy even when
1884                          * !(one->sha1_valid), as long as
1885                          * DIFF_FILE_VALID(one).
1886                          */
1887                         sprintf(temp->mode, "%06o", one->mode);
1888                 }
1889                 return;
1890         }
1891         else {
1892                 if (diff_populate_filespec(one, 0))
1893                         die("cannot read data blob for %s", one->path);
1894                 prep_temp_blob(temp, one->data, one->size,
1895                                one->sha1, one->mode);
1896         }
1899 static void remove_tempfile(void)
1901         int i;
1903         for (i = 0; i < 2; i++)
1904                 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1905                         unlink(diff_temp[i].name);
1906                         diff_temp[i].name = NULL;
1907                 }
1910 static void remove_tempfile_on_signal(int signo)
1912         remove_tempfile();
1913         signal(SIGINT, SIG_DFL);
1914         raise(signo);
1917 /* An external diff command takes:
1918  *
1919  * diff-cmd name infile1 infile1-sha1 infile1-mode \
1920  *               infile2 infile2-sha1 infile2-mode [ rename-to ]
1921  *
1922  */
1923 static void run_external_diff(const char *pgm,
1924                               const char *name,
1925                               const char *other,
1926                               struct diff_filespec *one,
1927                               struct diff_filespec *two,
1928                               const char *xfrm_msg,
1929                               int complete_rewrite)
1931         const char *spawn_arg[10];
1932         struct diff_tempfile *temp = diff_temp;
1933         int retval;
1934         static int atexit_asked = 0;
1935         const char *othername;
1936         const char **arg = &spawn_arg[0];
1938         othername = (other? other : name);
1939         if (one && two) {
1940                 prepare_temp_file(name, &temp[0], one);
1941                 prepare_temp_file(othername, &temp[1], two);
1942                 if (! atexit_asked &&
1943                     (temp[0].name == temp[0].tmp_path ||
1944                      temp[1].name == temp[1].tmp_path)) {
1945                         atexit_asked = 1;
1946                         atexit(remove_tempfile);
1947                 }
1948                 signal(SIGINT, remove_tempfile_on_signal);
1949         }
1951         if (one && two) {
1952                 *arg++ = pgm;
1953                 *arg++ = name;
1954                 *arg++ = temp[0].name;
1955                 *arg++ = temp[0].hex;
1956                 *arg++ = temp[0].mode;
1957                 *arg++ = temp[1].name;
1958                 *arg++ = temp[1].hex;
1959                 *arg++ = temp[1].mode;
1960                 if (other) {
1961                         *arg++ = other;
1962                         *arg++ = xfrm_msg;
1963                 }
1964         } else {
1965                 *arg++ = pgm;
1966                 *arg++ = name;
1967         }
1968         *arg = NULL;
1969         fflush(NULL);
1970         retval = run_command_v_opt(spawn_arg, 0);
1971         remove_tempfile();
1972         if (retval) {
1973                 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1974                 exit(1);
1975         }
1978 static void run_diff_cmd(const char *pgm,
1979                          const char *name,
1980                          const char *other,
1981                          const char *attr_path,
1982                          struct diff_filespec *one,
1983                          struct diff_filespec *two,
1984                          const char *xfrm_msg,
1985                          struct diff_options *o,
1986                          int complete_rewrite)
1988         if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
1989                 pgm = NULL;
1990         else {
1991                 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
1992                 if (drv && drv->external)
1993                         pgm = drv->external;
1994         }
1996         if (pgm) {
1997                 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1998                                   complete_rewrite);
1999                 return;
2000         }
2001         if (one && two)
2002                 builtin_diff(name, other ? other : name,
2003                              one, two, xfrm_msg, o, complete_rewrite);
2004         else
2005                 fprintf(o->file, "* Unmerged path %s\n", name);
2008 static void diff_fill_sha1_info(struct diff_filespec *one)
2010         if (DIFF_FILE_VALID(one)) {
2011                 if (!one->sha1_valid) {
2012                         struct stat st;
2013                         if (!strcmp(one->path, "-")) {
2014                                 hashcpy(one->sha1, null_sha1);
2015                                 return;
2016                         }
2017                         if (lstat(one->path, &st) < 0)
2018                                 die("stat %s", one->path);
2019                         if (index_path(one->sha1, one->path, &st, 0))
2020                                 die("cannot hash %s\n", one->path);
2021                 }
2022         }
2023         else
2024                 hashclr(one->sha1);
2027 static int similarity_index(struct diff_filepair *p)
2029         return p->score * 100 / MAX_SCORE;
2032 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2034         /* Strip the prefix but do not molest /dev/null and absolute paths */
2035         if (*namep && **namep != '/')
2036                 *namep += prefix_length;
2037         if (*otherp && **otherp != '/')
2038                 *otherp += prefix_length;
2041 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2043         const char *pgm = external_diff();
2044         struct strbuf msg;
2045         char *xfrm_msg;
2046         struct diff_filespec *one = p->one;
2047         struct diff_filespec *two = p->two;
2048         const char *name;
2049         const char *other;
2050         const char *attr_path;
2051         int complete_rewrite = 0;
2053         name  = p->one->path;
2054         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2055         attr_path = name;
2056         if (o->prefix_length)
2057                 strip_prefix(o->prefix_length, &name, &other);
2059         if (DIFF_PAIR_UNMERGED(p)) {
2060                 run_diff_cmd(pgm, name, NULL, attr_path,
2061                              NULL, NULL, NULL, o, 0);
2062                 return;
2063         }
2065         diff_fill_sha1_info(one);
2066         diff_fill_sha1_info(two);
2068         strbuf_init(&msg, PATH_MAX * 2 + 300);
2069         switch (p->status) {
2070         case DIFF_STATUS_COPIED:
2071                 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2072                 strbuf_addstr(&msg, "\ncopy from ");
2073                 quote_c_style(name, &msg, NULL, 0);
2074                 strbuf_addstr(&msg, "\ncopy to ");
2075                 quote_c_style(other, &msg, NULL, 0);
2076                 strbuf_addch(&msg, '\n');
2077                 break;
2078         case DIFF_STATUS_RENAMED:
2079                 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2080                 strbuf_addstr(&msg, "\nrename from ");
2081                 quote_c_style(name, &msg, NULL, 0);
2082                 strbuf_addstr(&msg, "\nrename to ");
2083                 quote_c_style(other, &msg, NULL, 0);
2084                 strbuf_addch(&msg, '\n');
2085                 break;
2086         case DIFF_STATUS_MODIFIED:
2087                 if (p->score) {
2088                         strbuf_addf(&msg, "dissimilarity index %d%%\n",
2089                                         similarity_index(p));
2090                         complete_rewrite = 1;
2091                         break;
2092                 }
2093                 /* fallthru */
2094         default:
2095                 /* nothing */
2096                 ;
2097         }
2099         if (hashcmp(one->sha1, two->sha1)) {
2100                 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2102                 if (DIFF_OPT_TST(o, BINARY)) {
2103                         mmfile_t mf;
2104                         if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2105                             (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2106                                 abbrev = 40;
2107                 }
2108                 strbuf_addf(&msg, "index %.*s..%.*s",
2109                                 abbrev, sha1_to_hex(one->sha1),
2110                                 abbrev, sha1_to_hex(two->sha1));
2111                 if (one->mode == two->mode)
2112                         strbuf_addf(&msg, " %06o", one->mode);
2113                 strbuf_addch(&msg, '\n');
2114         }
2116         if (msg.len)
2117                 strbuf_setlen(&msg, msg.len - 1);
2118         xfrm_msg = msg.len ? msg.buf : NULL;
2120         if (!pgm &&
2121             DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2122             (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2123                 /* a filepair that changes between file and symlink
2124                  * needs to be split into deletion and creation.
2125                  */
2126                 struct diff_filespec *null = alloc_filespec(two->path);
2127                 run_diff_cmd(NULL, name, other, attr_path,
2128                              one, null, xfrm_msg, o, 0);
2129                 free(null);
2130                 null = alloc_filespec(one->path);
2131                 run_diff_cmd(NULL, name, other, attr_path,
2132                              null, two, xfrm_msg, o, 0);
2133                 free(null);
2134         }
2135         else
2136                 run_diff_cmd(pgm, name, other, attr_path,
2137                              one, two, xfrm_msg, o, complete_rewrite);
2139         strbuf_release(&msg);
2142 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2143                          struct diffstat_t *diffstat)
2145         const char *name;
2146         const char *other;
2147         int complete_rewrite = 0;
2149         if (DIFF_PAIR_UNMERGED(p)) {
2150                 /* unmerged */
2151                 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2152                 return;
2153         }
2155         name = p->one->path;
2156         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2158         if (o->prefix_length)
2159                 strip_prefix(o->prefix_length, &name, &other);
2161         diff_fill_sha1_info(p->one);
2162         diff_fill_sha1_info(p->two);
2164         if (p->status == DIFF_STATUS_MODIFIED && p->score)
2165                 complete_rewrite = 1;
2166         builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2169 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2171         const char *name;
2172         const char *other;
2173         const char *attr_path;
2175         if (DIFF_PAIR_UNMERGED(p)) {
2176                 /* unmerged */
2177                 return;
2178         }
2180         name = p->one->path;
2181         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2182         attr_path = other ? other : name;
2184         if (o->prefix_length)
2185                 strip_prefix(o->prefix_length, &name, &other);
2187         diff_fill_sha1_info(p->one);
2188         diff_fill_sha1_info(p->two);
2190         builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2193 void diff_setup(struct diff_options *options)
2195         memset(options, 0, sizeof(*options));
2197         options->file = stdout;
2199         options->line_termination = '\n';
2200         options->break_opt = -1;
2201         options->rename_limit = -1;
2202         options->dirstat_percent = 3;
2203         DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
2204         options->context = 3;
2206         options->change = diff_change;
2207         options->add_remove = diff_addremove;
2208         if (diff_use_color_default > 0)
2209                 DIFF_OPT_SET(options, COLOR_DIFF);
2210         else
2211                 DIFF_OPT_CLR(options, COLOR_DIFF);
2212         options->detect_rename = diff_detect_rename_default;
2214         if (!diff_mnemonic_prefix) {
2215                 options->a_prefix = "a/";
2216                 options->b_prefix = "b/";
2217         }
2220 int diff_setup_done(struct diff_options *options)
2222         int count = 0;
2224         if (options->output_format & DIFF_FORMAT_NAME)
2225                 count++;
2226         if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2227                 count++;
2228         if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2229                 count++;
2230         if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2231                 count++;
2232         if (count > 1)
2233                 die("--name-only, --name-status, --check and -s are mutually exclusive");
2235         if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2236                 options->detect_rename = DIFF_DETECT_COPY;
2238         if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2239                 options->prefix = NULL;
2240         if (options->prefix)
2241                 options->prefix_length = strlen(options->prefix);
2242         else
2243                 options->prefix_length = 0;
2245         if (options->output_format & (DIFF_FORMAT_NAME |
2246                                       DIFF_FORMAT_NAME_STATUS |
2247                                       DIFF_FORMAT_CHECKDIFF |
2248                                       DIFF_FORMAT_NO_OUTPUT))
2249                 options->output_format &= ~(DIFF_FORMAT_RAW |
2250                                             DIFF_FORMAT_NUMSTAT |
2251                                             DIFF_FORMAT_DIFFSTAT |
2252                                             DIFF_FORMAT_SHORTSTAT |
2253                                             DIFF_FORMAT_DIRSTAT |
2254                                             DIFF_FORMAT_SUMMARY |
2255                                             DIFF_FORMAT_PATCH);
2257         /*
2258          * These cases always need recursive; we do not drop caller-supplied
2259          * recursive bits for other formats here.
2260          */
2261         if (options->output_format & (DIFF_FORMAT_PATCH |
2262                                       DIFF_FORMAT_NUMSTAT |
2263                                       DIFF_FORMAT_DIFFSTAT |
2264                                       DIFF_FORMAT_SHORTSTAT |
2265                                       DIFF_FORMAT_DIRSTAT |
2266                                       DIFF_FORMAT_SUMMARY |
2267                                       DIFF_FORMAT_CHECKDIFF))
2268                 DIFF_OPT_SET(options, RECURSIVE);
2269         /*
2270          * Also pickaxe would not work very well if you do not say recursive
2271          */
2272         if (options->pickaxe)
2273                 DIFF_OPT_SET(options, RECURSIVE);
2275         if (options->detect_rename && options->rename_limit < 0)
2276                 options->rename_limit = diff_rename_limit_default;
2277         if (options->setup & DIFF_SETUP_USE_CACHE) {
2278                 if (!active_cache)
2279                         /* read-cache does not die even when it fails
2280                          * so it is safe for us to do this here.  Also
2281                          * it does not smudge active_cache or active_nr
2282                          * when it fails, so we do not have to worry about
2283                          * cleaning it up ourselves either.
2284                          */
2285                         read_cache();
2286         }
2287         if (options->abbrev <= 0 || 40 < options->abbrev)
2288                 options->abbrev = 40; /* full */
2290         /*
2291          * It does not make sense to show the first hit we happened
2292          * to have found.  It does not make sense not to return with
2293          * exit code in such a case either.
2294          */
2295         if (DIFF_OPT_TST(options, QUIET)) {
2296                 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2297                 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2298         }
2300         return 0;
2303 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2305         char c, *eq;
2306         int len;
2308         if (*arg != '-')
2309                 return 0;
2310         c = *++arg;
2311         if (!c)
2312                 return 0;
2313         if (c == arg_short) {
2314                 c = *++arg;
2315                 if (!c)
2316                         return 1;
2317                 if (val && isdigit(c)) {
2318                         char *end;
2319                         int n = strtoul(arg, &end, 10);
2320                         if (*end)
2321                                 return 0;
2322                         *val = n;
2323                         return 1;
2324                 }
2325                 return 0;
2326         }
2327         if (c != '-')
2328                 return 0;
2329         arg++;
2330         eq = strchr(arg, '=');
2331         if (eq)
2332                 len = eq - arg;
2333         else
2334                 len = strlen(arg);
2335         if (!len || strncmp(arg, arg_long, len))
2336                 return 0;
2337         if (eq) {
2338                 int n;
2339                 char *end;
2340                 if (!isdigit(*++eq))
2341                         return 0;
2342                 n = strtoul(eq, &end, 10);
2343                 if (*end)
2344                         return 0;
2345                 *val = n;
2346         }
2347         return 1;
2350 static int diff_scoreopt_parse(const char *opt);
2352 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2354         const char *arg = av[0];
2356         /* Output format options */
2357         if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2358                 options->output_format |= DIFF_FORMAT_PATCH;
2359         else if (opt_arg(arg, 'U', "unified", &options->context))
2360                 options->output_format |= DIFF_FORMAT_PATCH;
2361         else if (!strcmp(arg, "--raw"))
2362                 options->output_format |= DIFF_FORMAT_RAW;
2363         else if (!strcmp(arg, "--patch-with-raw"))
2364                 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2365         else if (!strcmp(arg, "--numstat"))
2366                 options->output_format |= DIFF_FORMAT_NUMSTAT;
2367         else if (!strcmp(arg, "--shortstat"))
2368                 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2369         else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2370                 options->output_format |= DIFF_FORMAT_DIRSTAT;
2371         else if (!strcmp(arg, "--cumulative")) {
2372                 options->output_format |= DIFF_FORMAT_DIRSTAT;
2373                 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2374         } else if (opt_arg(arg, 0, "dirstat-by-file",
2375                            &options->dirstat_percent)) {
2376                 options->output_format |= DIFF_FORMAT_DIRSTAT;
2377                 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2378         }
2379         else if (!strcmp(arg, "--check"))
2380                 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2381         else if (!strcmp(arg, "--summary"))
2382                 options->output_format |= DIFF_FORMAT_SUMMARY;
2383         else if (!strcmp(arg, "--patch-with-stat"))
2384                 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2385         else if (!strcmp(arg, "--name-only"))
2386                 options->output_format |= DIFF_FORMAT_NAME;
2387         else if (!strcmp(arg, "--name-status"))
2388                 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2389         else if (!strcmp(arg, "-s"))
2390                 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2391         else if (!prefixcmp(arg, "--stat")) {
2392                 char *end;
2393                 int width = options->stat_width;
2394                 int name_width = options->stat_name_width;
2395                 arg += 6;
2396                 end = (char *)arg;
2398                 switch (*arg) {
2399                 case '-':
2400                         if (!prefixcmp(arg, "-width="))
2401                                 width = strtoul(arg + 7, &end, 10);
2402                         else if (!prefixcmp(arg, "-name-width="))
2403                                 name_width = strtoul(arg + 12, &end, 10);
2404                         break;
2405                 case '=':
2406                         width = strtoul(arg+1, &end, 10);
2407                         if (*end == ',')
2408                                 name_width = strtoul(end+1, &end, 10);
2409                 }
2411                 /* Important! This checks all the error cases! */
2412                 if (*end)
2413                         return 0;
2414                 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2415                 options->stat_name_width = name_width;
2416                 options->stat_width = width;
2417         }
2419         /* renames options */
2420         else if (!prefixcmp(arg, "-B")) {
2421                 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2422                         return -1;
2423         }
2424         else if (!prefixcmp(arg, "-M")) {
2425                 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2426                         return -1;
2427                 options->detect_rename = DIFF_DETECT_RENAME;
2428         }
2429         else if (!prefixcmp(arg, "-C")) {
2430                 if (options->detect_rename == DIFF_DETECT_COPY)
2431                         DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2432                 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2433                         return -1;
2434                 options->detect_rename = DIFF_DETECT_COPY;
2435         }
2436         else if (!strcmp(arg, "--no-renames"))
2437                 options->detect_rename = 0;
2438         else if (!strcmp(arg, "--relative"))
2439                 DIFF_OPT_SET(options, RELATIVE_NAME);
2440         else if (!prefixcmp(arg, "--relative=")) {
2441                 DIFF_OPT_SET(options, RELATIVE_NAME);
2442                 options->prefix = arg + 11;
2443         }
2445         /* xdiff options */
2446         else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2447                 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2448         else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2449                 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2450         else if (!strcmp(arg, "--ignore-space-at-eol"))
2451                 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2453         /* flags options */
2454         else if (!strcmp(arg, "--binary")) {
2455                 options->output_format |= DIFF_FORMAT_PATCH;
2456                 DIFF_OPT_SET(options, BINARY);
2457         }
2458         else if (!strcmp(arg, "--full-index"))
2459                 DIFF_OPT_SET(options, FULL_INDEX);
2460         else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2461                 DIFF_OPT_SET(options, TEXT);
2462         else if (!strcmp(arg, "-R"))
2463                 DIFF_OPT_SET(options, REVERSE_DIFF);
2464         else if (!strcmp(arg, "--find-copies-harder"))
2465                 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2466         else if (!strcmp(arg, "--follow"))
2467                 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2468         else if (!strcmp(arg, "--color"))
2469                 DIFF_OPT_SET(options, COLOR_DIFF);
2470         else if (!strcmp(arg, "--no-color"))
2471                 DIFF_OPT_CLR(options, COLOR_DIFF);
2472         else if (!strcmp(arg, "--color-words"))
2473                 options->flags |= DIFF_OPT_COLOR_DIFF | DIFF_OPT_COLOR_DIFF_WORDS;
2474         else if (!strcmp(arg, "--exit-code"))
2475                 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2476         else if (!strcmp(arg, "--quiet"))
2477                 DIFF_OPT_SET(options, QUIET);
2478         else if (!strcmp(arg, "--ext-diff"))
2479                 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2480         else if (!strcmp(arg, "--no-ext-diff"))
2481                 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2482         else if (!strcmp(arg, "--textconv"))
2483                 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2484         else if (!strcmp(arg, "--no-textconv"))
2485                 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2486         else if (!strcmp(arg, "--ignore-submodules"))
2487                 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2489         /* misc options */
2490         else if (!strcmp(arg, "-z"))
2491                 options->line_termination = 0;
2492         else if (!prefixcmp(arg, "-l"))
2493                 options->rename_limit = strtoul(arg+2, NULL, 10);
2494         else if (!prefixcmp(arg, "-S"))
2495                 options->pickaxe = arg + 2;
2496         else if (!strcmp(arg, "--pickaxe-all"))
2497                 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2498         else if (!strcmp(arg, "--pickaxe-regex"))
2499                 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2500         else if (!prefixcmp(arg, "-O"))
2501                 options->orderfile = arg + 2;
2502         else if (!prefixcmp(arg, "--diff-filter="))
2503                 options->filter = arg + 14;
2504         else if (!strcmp(arg, "--abbrev"))
2505                 options->abbrev = DEFAULT_ABBREV;
2506         else if (!prefixcmp(arg, "--abbrev=")) {
2507                 options->abbrev = strtoul(arg + 9, NULL, 10);
2508                 if (options->abbrev < MINIMUM_ABBREV)
2509                         options->abbrev = MINIMUM_ABBREV;
2510                 else if (40 < options->abbrev)
2511                         options->abbrev = 40;
2512         }
2513         else if (!prefixcmp(arg, "--src-prefix="))
2514                 options->a_prefix = arg + 13;
2515         else if (!prefixcmp(arg, "--dst-prefix="))
2516                 options->b_prefix = arg + 13;
2517         else if (!strcmp(arg, "--no-prefix"))
2518                 options->a_prefix = options->b_prefix = "";
2519         else if (!prefixcmp(arg, "--output=")) {
2520                 options->file = fopen(arg + strlen("--output="), "w");
2521                 options->close_file = 1;
2522         } else
2523                 return 0;
2524         return 1;
2527 static int parse_num(const char **cp_p)
2529         unsigned long num, scale;
2530         int ch, dot;
2531         const char *cp = *cp_p;
2533         num = 0;
2534         scale = 1;
2535         dot = 0;
2536         for(;;) {
2537                 ch = *cp;
2538                 if ( !dot && ch == '.' ) {
2539                         scale = 1;
2540                         dot = 1;
2541                 } else if ( ch == '%' ) {
2542                         scale = dot ? scale*100 : 100;
2543                         cp++;   /* % is always at the end */
2544                         break;
2545                 } else if ( ch >= '0' && ch <= '9' ) {
2546                         if ( scale < 100000 ) {
2547                                 scale *= 10;
2548                                 num = (num*10) + (ch-'0');
2549                         }
2550                 } else {
2551                         break;
2552                 }
2553                 cp++;
2554         }
2555         *cp_p = cp;
2557         /* user says num divided by scale and we say internally that
2558          * is MAX_SCORE * num / scale.
2559          */
2560         return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2563 static int diff_scoreopt_parse(const char *opt)
2565         int opt1, opt2, cmd;
2567         if (*opt++ != '-')
2568                 return -1;
2569         cmd = *opt++;
2570         if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2571                 return -1; /* that is not a -M, -C nor -B option */
2573         opt1 = parse_num(&opt);
2574         if (cmd != 'B')
2575                 opt2 = 0;
2576         else {
2577                 if (*opt == 0)
2578                         opt2 = 0;
2579                 else if (*opt != '/')
2580                         return -1; /* we expect -B80/99 or -B80 */
2581                 else {
2582                         opt++;
2583                         opt2 = parse_num(&opt);
2584                 }
2585         }
2586         if (*opt != 0)
2587                 return -1;
2588         return opt1 | (opt2 << 16);
2591 struct diff_queue_struct diff_queued_diff;
2593 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2595         if (queue->alloc <= queue->nr) {
2596                 queue->alloc = alloc_nr(queue->alloc);
2597                 queue->queue = xrealloc(queue->queue,
2598                                         sizeof(dp) * queue->alloc);
2599         }
2600         queue->queue[queue->nr++] = dp;
2603 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2604                                  struct diff_filespec *one,
2605                                  struct diff_filespec *two)
2607         struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2608         dp->one = one;
2609         dp->two = two;
2610         if (queue)
2611                 diff_q(queue, dp);
2612         return dp;
2615 void diff_free_filepair(struct diff_filepair *p)
2617         free_filespec(p->one);
2618         free_filespec(p->two);
2619         free(p);
2622 /* This is different from find_unique_abbrev() in that
2623  * it stuffs the result with dots for alignment.
2624  */
2625 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2627         int abblen;
2628         const char *abbrev;
2629         if (len == 40)
2630                 return sha1_to_hex(sha1);
2632         abbrev = find_unique_abbrev(sha1, len);
2633         abblen = strlen(abbrev);
2634         if (abblen < 37) {
2635                 static char hex[41];
2636                 if (len < abblen && abblen <= len + 2)
2637                         sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2638                 else
2639                         sprintf(hex, "%s...", abbrev);
2640                 return hex;
2641         }
2642         return sha1_to_hex(sha1);
2645 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2647         int line_termination = opt->line_termination;
2648         int inter_name_termination = line_termination ? '\t' : '\0';
2650         if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2651                 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2652                         diff_unique_abbrev(p->one->sha1, opt->abbrev));
2653                 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2654         }
2655         if (p->score) {
2656                 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2657                         inter_name_termination);
2658         } else {
2659                 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2660         }
2662         if (p->status == DIFF_STATUS_COPIED ||
2663             p->status == DIFF_STATUS_RENAMED) {
2664                 const char *name_a, *name_b;
2665                 name_a = p->one->path;
2666                 name_b = p->two->path;
2667                 strip_prefix(opt->prefix_length, &name_a, &name_b);
2668                 write_name_quoted(name_a, opt->file, inter_name_termination);
2669                 write_name_quoted(name_b, opt->file, line_termination);
2670         } else {
2671                 const char *name_a, *name_b;
2672                 name_a = p->one->mode ? p->one->path : p->two->path;
2673                 name_b = NULL;
2674                 strip_prefix(opt->prefix_length, &name_a, &name_b);
2675                 write_name_quoted(name_a, opt->file, line_termination);
2676         }
2679 int diff_unmodified_pair(struct diff_filepair *p)
2681         /* This function is written stricter than necessary to support
2682          * the currently implemented transformers, but the idea is to
2683          * let transformers to produce diff_filepairs any way they want,
2684          * and filter and clean them up here before producing the output.
2685          */
2686         struct diff_filespec *one = p->one, *two = p->two;
2688         if (DIFF_PAIR_UNMERGED(p))
2689                 return 0; /* unmerged is interesting */
2691         /* deletion, addition, mode or type change
2692          * and rename are all interesting.
2693          */
2694         if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2695             DIFF_PAIR_MODE_CHANGED(p) ||
2696             strcmp(one->path, two->path))
2697                 return 0;
2699         /* both are valid and point at the same path.  that is, we are
2700          * dealing with a change.
2701          */
2702         if (one->sha1_valid && two->sha1_valid &&
2703             !hashcmp(one->sha1, two->sha1))
2704                 return 1; /* no change */
2705         if (!one->sha1_valid && !two->sha1_valid)
2706                 return 1; /* both look at the same file on the filesystem. */
2707         return 0;
2710 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2712         if (diff_unmodified_pair(p))
2713                 return;
2715         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2716             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2717                 return; /* no tree diffs in patch format */
2719         run_diff(p, o);
2722 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2723                             struct diffstat_t *diffstat)
2725         if (diff_unmodified_pair(p))
2726                 return;
2728         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2729             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2730                 return; /* no tree diffs in patch format */
2732         run_diffstat(p, o, diffstat);
2735 static void diff_flush_checkdiff(struct diff_filepair *p,
2736                 struct diff_options *o)
2738         if (diff_unmodified_pair(p))
2739                 return;
2741         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2742             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2743                 return; /* no tree diffs in patch format */
2745         run_checkdiff(p, o);
2748 int diff_queue_is_empty(void)
2750         struct diff_queue_struct *q = &diff_queued_diff;
2751         int i;
2752         for (i = 0; i < q->nr; i++)
2753                 if (!diff_unmodified_pair(q->queue[i]))
2754                         return 0;
2755         return 1;
2758 #if DIFF_DEBUG
2759 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2761         fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2762                 x, one ? one : "",
2763                 s->path,
2764                 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2765                 s->mode,
2766                 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2767         fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2768                 x, one ? one : "",
2769                 s->size, s->xfrm_flags);
2772 void diff_debug_filepair(const struct diff_filepair *p, int i)
2774         diff_debug_filespec(p->one, i, "one");
2775         diff_debug_filespec(p->two, i, "two");
2776         fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2777                 p->score, p->status ? p->status : '?',
2778                 p->one->rename_used, p->broken_pair);
2781 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2783         int i;
2784         if (msg)
2785                 fprintf(stderr, "%s\n", msg);
2786         fprintf(stderr, "q->nr = %d\n", q->nr);
2787         for (i = 0; i < q->nr; i++) {
2788                 struct diff_filepair *p = q->queue[i];
2789                 diff_debug_filepair(p, i);
2790         }
2792 #endif
2794 static void diff_resolve_rename_copy(void)
2796         int i;
2797         struct diff_filepair *p;
2798         struct diff_queue_struct *q = &diff_queued_diff;
2800         diff_debug_queue("resolve-rename-copy", q);
2802         for (i = 0; i < q->nr; i++) {
2803                 p = q->queue[i];
2804                 p->status = 0; /* undecided */
2805                 if (DIFF_PAIR_UNMERGED(p))
2806                         p->status = DIFF_STATUS_UNMERGED;
2807                 else if (!DIFF_FILE_VALID(p->one))
2808                         p->status = DIFF_STATUS_ADDED;
2809                 else if (!DIFF_FILE_VALID(p->two))
2810                         p->status = DIFF_STATUS_DELETED;
2811                 else if (DIFF_PAIR_TYPE_CHANGED(p))
2812                         p->status = DIFF_STATUS_TYPE_CHANGED;
2814                 /* from this point on, we are dealing with a pair
2815                  * whose both sides are valid and of the same type, i.e.
2816                  * either in-place edit or rename/copy edit.
2817                  */
2818                 else if (DIFF_PAIR_RENAME(p)) {
2819                         /*
2820                          * A rename might have re-connected a broken
2821                          * pair up, causing the pathnames to be the
2822                          * same again. If so, that's not a rename at
2823                          * all, just a modification..
2824                          *
2825                          * Otherwise, see if this source was used for
2826                          * multiple renames, in which case we decrement
2827                          * the count, and call it a copy.
2828                          */
2829                         if (!strcmp(p->one->path, p->two->path))
2830                                 p->status = DIFF_STATUS_MODIFIED;
2831                         else if (--p->one->rename_used > 0)
2832                                 p->status = DIFF_STATUS_COPIED;
2833                         else
2834                                 p->status = DIFF_STATUS_RENAMED;
2835                 }
2836                 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2837                          p->one->mode != p->two->mode ||
2838                          is_null_sha1(p->one->sha1))
2839                         p->status = DIFF_STATUS_MODIFIED;
2840                 else {
2841                         /* This is a "no-change" entry and should not
2842                          * happen anymore, but prepare for broken callers.
2843                          */
2844                         error("feeding unmodified %s to diffcore",
2845                               p->one->path);
2846                         p->status = DIFF_STATUS_UNKNOWN;
2847                 }
2848         }
2849         diff_debug_queue("resolve-rename-copy done", q);
2852 static int check_pair_status(struct diff_filepair *p)
2854         switch (p->status) {
2855         case DIFF_STATUS_UNKNOWN:
2856                 return 0;
2857         case 0:
2858                 die("internal error in diff-resolve-rename-copy");
2859         default:
2860                 return 1;
2861         }
2864 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2866         int fmt = opt->output_format;
2868         if (fmt & DIFF_FORMAT_CHECKDIFF)
2869                 diff_flush_checkdiff(p, opt);
2870         else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2871                 diff_flush_raw(p, opt);
2872         else if (fmt & DIFF_FORMAT_NAME) {
2873                 const char *name_a, *name_b;
2874                 name_a = p->two->path;
2875                 name_b = NULL;
2876                 strip_prefix(opt->prefix_length, &name_a, &name_b);
2877                 write_name_quoted(name_a, opt->file, opt->line_termination);
2878         }
2881 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
2883         if (fs->mode)
2884                 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
2885         else
2886                 fprintf(file, " %s ", newdelete);
2887         write_name_quoted(fs->path, file, '\n');
2891 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
2893         if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2894                 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
2895                         show_name ? ' ' : '\n');
2896                 if (show_name) {
2897                         write_name_quoted(p->two->path, file, '\n');
2898                 }
2899         }
2902 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
2904         char *names = pprint_rename(p->one->path, p->two->path);
2906         fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2907         free(names);
2908         show_mode_change(file, p, 0);
2911 static void diff_summary(FILE *file, struct diff_filepair *p)
2913         switch(p->status) {
2914         case DIFF_STATUS_DELETED:
2915                 show_file_mode_name(file, "delete", p->one);
2916                 break;
2917         case DIFF_STATUS_ADDED:
2918                 show_file_mode_name(file, "create", p->two);
2919                 break;
2920         case DIFF_STATUS_COPIED:
2921                 show_rename_copy(file, "copy", p);
2922                 break;
2923         case DIFF_STATUS_RENAMED:
2924                 show_rename_copy(file, "rename", p);
2925                 break;
2926         default:
2927                 if (p->score) {
2928                         fputs(" rewrite ", file);
2929                         write_name_quoted(p->two->path, file, ' ');
2930                         fprintf(file, "(%d%%)\n", similarity_index(p));
2931                 }
2932                 show_mode_change(file, p, !p->score);
2933                 break;
2934         }
2937 struct patch_id_t {
2938         git_SHA_CTX *ctx;
2939         int patchlen;
2940 };
2942 static int remove_space(char *line, int len)
2944         int i;
2945         char *dst = line;
2946         unsigned char c;
2948         for (i = 0; i < len; i++)
2949                 if (!isspace((c = line[i])))
2950                         *dst++ = c;
2952         return dst - line;
2955 static void patch_id_consume(void *priv, char *line, unsigned long len)
2957         struct patch_id_t *data = priv;
2958         int new_len;
2960         /* Ignore line numbers when computing the SHA1 of the patch */
2961         if (!prefixcmp(line, "@@ -"))
2962                 return;
2964         new_len = remove_space(line, len);
2966         git_SHA1_Update(data->ctx, line, new_len);
2967         data->patchlen += new_len;
2970 /* returns 0 upon success, and writes result into sha1 */
2971 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2973         struct diff_queue_struct *q = &diff_queued_diff;
2974         int i;
2975         git_SHA_CTX ctx;
2976         struct patch_id_t data;
2977         char buffer[PATH_MAX * 4 + 20];
2979         git_SHA1_Init(&ctx);
2980         memset(&data, 0, sizeof(struct patch_id_t));
2981         data.ctx = &ctx;
2983         for (i = 0; i < q->nr; i++) {
2984                 xpparam_t xpp;
2985                 xdemitconf_t xecfg;
2986                 xdemitcb_t ecb;
2987                 mmfile_t mf1, mf2;
2988                 struct diff_filepair *p = q->queue[i];
2989                 int len1, len2;
2991                 memset(&xpp, 0, sizeof(xpp));
2992                 memset(&xecfg, 0, sizeof(xecfg));
2993                 if (p->status == 0)
2994                         return error("internal diff status error");
2995                 if (p->status == DIFF_STATUS_UNKNOWN)
2996                         continue;
2997                 if (diff_unmodified_pair(p))
2998                         continue;
2999                 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3000                     (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3001                         continue;
3002                 if (DIFF_PAIR_UNMERGED(p))
3003                         continue;
3005                 diff_fill_sha1_info(p->one);
3006                 diff_fill_sha1_info(p->two);
3007                 if (fill_mmfile(&mf1, p->one) < 0 ||
3008                                 fill_mmfile(&mf2, p->two) < 0)
3009                         return error("unable to read files to diff");
3011                 len1 = remove_space(p->one->path, strlen(p->one->path));
3012                 len2 = remove_space(p->two->path, strlen(p->two->path));
3013                 if (p->one->mode == 0)
3014                         len1 = snprintf(buffer, sizeof(buffer),
3015                                         "diff--gita/%.*sb/%.*s"
3016                                         "newfilemode%06o"
3017                                         "---/dev/null"
3018                                         "+++b/%.*s",
3019                                         len1, p->one->path,
3020                                         len2, p->two->path,
3021                                         p->two->mode,
3022                                         len2, p->two->path);
3023                 else if (p->two->mode == 0)
3024                         len1 = snprintf(buffer, sizeof(buffer),
3025                                         "diff--gita/%.*sb/%.*s"
3026                                         "deletedfilemode%06o"
3027                                         "---a/%.*s"
3028                                         "+++/dev/null",
3029                                         len1, p->one->path,
3030                                         len2, p->two->path,
3031                                         p->one->mode,
3032                                         len1, p->one->path);
3033                 else
3034                         len1 = snprintf(buffer, sizeof(buffer),
3035                                         "diff--gita/%.*sb/%.*s"
3036                                         "---a/%.*s"
3037                                         "+++b/%.*s",
3038                                         len1, p->one->path,
3039                                         len2, p->two->path,
3040                                         len1, p->one->path,
3041                                         len2, p->two->path);
3042                 git_SHA1_Update(&ctx, buffer, len1);
3044                 xpp.flags = XDF_NEED_MINIMAL;
3045                 xecfg.ctxlen = 3;
3046                 xecfg.flags = XDL_EMIT_FUNCNAMES;
3047                 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3048                               &xpp, &xecfg, &ecb);
3049         }
3051         git_SHA1_Final(sha1, &ctx);
3052         return 0;
3055 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3057         struct diff_queue_struct *q = &diff_queued_diff;
3058         int i;
3059         int result = diff_get_patch_id(options, sha1);
3061         for (i = 0; i < q->nr; i++)
3062                 diff_free_filepair(q->queue[i]);
3064         free(q->queue);
3065         q->queue = NULL;
3066         q->nr = q->alloc = 0;
3068         return result;
3071 static int is_summary_empty(const struct diff_queue_struct *q)
3073         int i;
3075         for (i = 0; i < q->nr; i++) {
3076                 const struct diff_filepair *p = q->queue[i];
3078                 switch (p->status) {
3079                 case DIFF_STATUS_DELETED:
3080                 case DIFF_STATUS_ADDED:
3081                 case DIFF_STATUS_COPIED:
3082                 case DIFF_STATUS_RENAMED:
3083                         return 0;
3084                 default:
3085                         if (p->score)
3086                                 return 0;
3087                         if (p->one->mode && p->two->mode &&
3088                             p->one->mode != p->two->mode)
3089                                 return 0;
3090                         break;
3091                 }
3092         }
3093         return 1;
3096 void diff_flush(struct diff_options *options)
3098         struct diff_queue_struct *q = &diff_queued_diff;
3099         int i, output_format = options->output_format;
3100         int separator = 0;
3102         /*
3103          * Order: raw, stat, summary, patch
3104          * or:    name/name-status/checkdiff (other bits clear)
3105          */
3106         if (!q->nr)
3107                 goto free_queue;
3109         if (output_format & (DIFF_FORMAT_RAW |
3110                              DIFF_FORMAT_NAME |
3111                              DIFF_FORMAT_NAME_STATUS |
3112                              DIFF_FORMAT_CHECKDIFF)) {
3113                 for (i = 0; i < q->nr; i++) {
3114                         struct diff_filepair *p = q->queue[i];
3115                         if (check_pair_status(p))
3116                                 flush_one_pair(p, options);
3117                 }
3118                 separator++;
3119         }
3121         if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3122                 struct diffstat_t diffstat;
3124                 memset(&diffstat, 0, sizeof(struct diffstat_t));
3125                 for (i = 0; i < q->nr; i++) {
3126                         struct diff_filepair *p = q->queue[i];
3127                         if (check_pair_status(p))
3128                                 diff_flush_stat(p, options, &diffstat);
3129                 }
3130                 if (output_format & DIFF_FORMAT_NUMSTAT)
3131                         show_numstat(&diffstat, options);
3132                 if (output_format & DIFF_FORMAT_DIFFSTAT)
3133                         show_stats(&diffstat, options);
3134                 if (output_format & DIFF_FORMAT_SHORTSTAT)
3135                         show_shortstats(&diffstat, options);
3136                 free_diffstat_info(&diffstat);
3137                 separator++;
3138         }
3139         if (output_format & DIFF_FORMAT_DIRSTAT)
3140                 show_dirstat(options);
3142         if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3143                 for (i = 0; i < q->nr; i++)
3144                         diff_summary(options->file, q->queue[i]);
3145                 separator++;
3146         }
3148         if (output_format & DIFF_FORMAT_PATCH) {
3149                 if (separator) {
3150                         putc(options->line_termination, options->file);
3151                         if (options->stat_sep) {
3152                                 /* attach patch instead of inline */
3153                                 fputs(options->stat_sep, options->file);
3154                         }
3155                 }
3157                 for (i = 0; i < q->nr; i++) {
3158                         struct diff_filepair *p = q->queue[i];
3159                         if (check_pair_status(p))
3160                                 diff_flush_patch(p, options);
3161                 }
3162         }
3164         if (output_format & DIFF_FORMAT_CALLBACK)
3165                 options->format_callback(q, options, options->format_callback_data);
3167         for (i = 0; i < q->nr; i++)
3168                 diff_free_filepair(q->queue[i]);
3169 free_queue:
3170         free(q->queue);
3171         q->queue = NULL;
3172         q->nr = q->alloc = 0;
3173         if (options->close_file)
3174                 fclose(options->file);
3177 static void diffcore_apply_filter(const char *filter)
3179         int i;
3180         struct diff_queue_struct *q = &diff_queued_diff;
3181         struct diff_queue_struct outq;
3182         outq.queue = NULL;
3183         outq.nr = outq.alloc = 0;
3185         if (!filter)
3186                 return;
3188         if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3189                 int found;
3190                 for (i = found = 0; !found && i < q->nr; i++) {
3191                         struct diff_filepair *p = q->queue[i];
3192                         if (((p->status == DIFF_STATUS_MODIFIED) &&
3193                              ((p->score &&
3194                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3195                               (!p->score &&
3196                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3197                             ((p->status != DIFF_STATUS_MODIFIED) &&
3198                              strchr(filter, p->status)))
3199                                 found++;
3200                 }
3201                 if (found)
3202                         return;
3204                 /* otherwise we will clear the whole queue
3205                  * by copying the empty outq at the end of this
3206                  * function, but first clear the current entries
3207                  * in the queue.
3208                  */
3209                 for (i = 0; i < q->nr; i++)
3210                         diff_free_filepair(q->queue[i]);
3211         }
3212         else {
3213                 /* Only the matching ones */
3214                 for (i = 0; i < q->nr; i++) {
3215                         struct diff_filepair *p = q->queue[i];
3217                         if (((p->status == DIFF_STATUS_MODIFIED) &&
3218                              ((p->score &&
3219                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3220                               (!p->score &&
3221                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3222                             ((p->status != DIFF_STATUS_MODIFIED) &&
3223                              strchr(filter, p->status)))
3224                                 diff_q(&outq, p);
3225                         else
3226                                 diff_free_filepair(p);
3227                 }
3228         }
3229         free(q->queue);
3230         *q = outq;
3233 /* Check whether two filespecs with the same mode and size are identical */
3234 static int diff_filespec_is_identical(struct diff_filespec *one,
3235                                       struct diff_filespec *two)
3237         if (S_ISGITLINK(one->mode))
3238                 return 0;
3239         if (diff_populate_filespec(one, 0))
3240                 return 0;
3241         if (diff_populate_filespec(two, 0))
3242                 return 0;
3243         return !memcmp(one->data, two->data, one->size);
3246 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3248         int i;
3249         struct diff_queue_struct *q = &diff_queued_diff;
3250         struct diff_queue_struct outq;
3251         outq.queue = NULL;
3252         outq.nr = outq.alloc = 0;
3254         for (i = 0; i < q->nr; i++) {
3255                 struct diff_filepair *p = q->queue[i];
3257                 /*
3258                  * 1. Entries that come from stat info dirtyness
3259                  *    always have both sides (iow, not create/delete),
3260                  *    one side of the object name is unknown, with
3261                  *    the same mode and size.  Keep the ones that
3262                  *    do not match these criteria.  They have real
3263                  *    differences.
3264                  *
3265                  * 2. At this point, the file is known to be modified,
3266                  *    with the same mode and size, and the object
3267                  *    name of one side is unknown.  Need to inspect
3268                  *    the identical contents.
3269                  */
3270                 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3271                     !DIFF_FILE_VALID(p->two) ||
3272                     (p->one->sha1_valid && p->two->sha1_valid) ||
3273                     (p->one->mode != p->two->mode) ||
3274                     diff_populate_filespec(p->one, 1) ||
3275                     diff_populate_filespec(p->two, 1) ||
3276                     (p->one->size != p->two->size) ||
3277                     !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3278                         diff_q(&outq, p);
3279                 else {
3280                         /*
3281                          * The caller can subtract 1 from skip_stat_unmatch
3282                          * to determine how many paths were dirty only
3283                          * due to stat info mismatch.
3284                          */
3285                         if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3286                                 diffopt->skip_stat_unmatch++;
3287                         diff_free_filepair(p);
3288                 }
3289         }
3290         free(q->queue);
3291         *q = outq;
3294 void diffcore_std(struct diff_options *options)
3296         if (options->skip_stat_unmatch)
3297                 diffcore_skip_stat_unmatch(options);
3298         if (options->break_opt != -1)
3299                 diffcore_break(options->break_opt);
3300         if (options->detect_rename)
3301                 diffcore_rename(options);
3302         if (options->break_opt != -1)
3303                 diffcore_merge_broken();
3304         if (options->pickaxe)
3305                 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3306         if (options->orderfile)
3307                 diffcore_order(options->orderfile);
3308         diff_resolve_rename_copy();
3309         diffcore_apply_filter(options->filter);
3311         if (diff_queued_diff.nr)
3312                 DIFF_OPT_SET(options, HAS_CHANGES);
3313         else
3314                 DIFF_OPT_CLR(options, HAS_CHANGES);
3317 int diff_result_code(struct diff_options *opt, int status)
3319         int result = 0;
3320         if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3321             !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3322                 return status;
3323         if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3324             DIFF_OPT_TST(opt, HAS_CHANGES))
3325                 result |= 01;
3326         if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3327             DIFF_OPT_TST(opt, CHECK_FAILED))
3328                 result |= 02;
3329         return result;
3332 void diff_addremove(struct diff_options *options,
3333                     int addremove, unsigned mode,
3334                     const unsigned char *sha1,
3335                     const char *concatpath)
3337         struct diff_filespec *one, *two;
3339         if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3340                 return;
3342         /* This may look odd, but it is a preparation for
3343          * feeding "there are unchanged files which should
3344          * not produce diffs, but when you are doing copy
3345          * detection you would need them, so here they are"
3346          * entries to the diff-core.  They will be prefixed
3347          * with something like '=' or '*' (I haven't decided
3348          * which but should not make any difference).
3349          * Feeding the same new and old to diff_change()
3350          * also has the same effect.
3351          * Before the final output happens, they are pruned after
3352          * merged into rename/copy pairs as appropriate.
3353          */
3354         if (DIFF_OPT_TST(options, REVERSE_DIFF))
3355                 addremove = (addremove == '+' ? '-' :
3356                              addremove == '-' ? '+' : addremove);
3358         if (options->prefix &&
3359             strncmp(concatpath, options->prefix, options->prefix_length))
3360                 return;
3362         one = alloc_filespec(concatpath);
3363         two = alloc_filespec(concatpath);
3365         if (addremove != '+')
3366                 fill_filespec(one, sha1, mode);
3367         if (addremove != '-')
3368                 fill_filespec(two, sha1, mode);
3370         diff_queue(&diff_queued_diff, one, two);
3371         DIFF_OPT_SET(options, HAS_CHANGES);
3374 void diff_change(struct diff_options *options,
3375                  unsigned old_mode, unsigned new_mode,
3376                  const unsigned char *old_sha1,
3377                  const unsigned char *new_sha1,
3378                  const char *concatpath)
3380         struct diff_filespec *one, *two;
3382         if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3383                         && S_ISGITLINK(new_mode))
3384                 return;
3386         if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3387                 unsigned tmp;
3388                 const unsigned char *tmp_c;
3389                 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3390                 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3391         }
3393         if (options->prefix &&
3394             strncmp(concatpath, options->prefix, options->prefix_length))
3395                 return;
3397         one = alloc_filespec(concatpath);
3398         two = alloc_filespec(concatpath);
3399         fill_filespec(one, old_sha1, old_mode);
3400         fill_filespec(two, new_sha1, new_mode);
3402         diff_queue(&diff_queued_diff, one, two);
3403         DIFF_OPT_SET(options, HAS_CHANGES);
3406 void diff_unmerge(struct diff_options *options,
3407                   const char *path,
3408                   unsigned mode, const unsigned char *sha1)
3410         struct diff_filespec *one, *two;
3412         if (options->prefix &&
3413             strncmp(path, options->prefix, options->prefix_length))
3414                 return;
3416         one = alloc_filespec(path);
3417         two = alloc_filespec(path);
3418         fill_filespec(one, sha1, mode);
3419         diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3422 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3423                 size_t *outsize)
3425         struct diff_tempfile temp;
3426         const char *argv[3];
3427         const char **arg = argv;
3428         struct child_process child;
3429         struct strbuf buf = STRBUF_INIT;
3431         prepare_temp_file(spec->path, &temp, spec);
3432         *arg++ = pgm;
3433         *arg++ = temp.name;
3434         *arg = NULL;
3436         memset(&child, 0, sizeof(child));
3437         child.argv = argv;
3438         child.out = -1;
3439         if (start_command(&child) != 0 ||
3440             strbuf_read(&buf, child.out, 0) < 0 ||
3441             finish_command(&child) != 0) {
3442                 if (temp.name == temp.tmp_path)
3443                         unlink(temp.name);
3444                 error("error running textconv command '%s'", pgm);
3445                 return NULL;
3446         }
3447         if (temp.name == temp.tmp_path)
3448                 unlink(temp.name);
3450         return strbuf_detach(&buf, outsize);