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