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