Code

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