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