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