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