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