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