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