Code

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