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