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