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