Code

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