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