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