Code

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