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