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