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