Add the diff option --no-defaults
[git/dscho.git] / diff.c
blob903dbb4cbdcc2d2645a905899634db30c4c8b8a0
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"
15 #include "sigchain.h"
16 #include "parse-options.h"
18 #ifdef NO_FAST_WORKING_DIRECTORY
19 #define FAST_WORKING_DIRECTORY 0
20 #else
21 #define FAST_WORKING_DIRECTORY 1
22 #endif
24 static int diff_detect_rename_default;
25 static int diff_rename_limit_default = 200;
26 static int diff_suppress_blank_empty;
27 int diff_use_color_default = -1;
28 static const char *diff_word_regex_cfg;
29 static const char *external_diff_cmd_cfg;
30 int diff_auto_refresh_index = 1;
31 static int diff_mnemonic_prefix;
33 static char diff_colors[][COLOR_MAXLEN] = {
34 GIT_COLOR_RESET,
35 GIT_COLOR_NORMAL, /* PLAIN */
36 GIT_COLOR_BOLD, /* METAINFO */
37 GIT_COLOR_CYAN, /* FRAGINFO */
38 GIT_COLOR_RED, /* OLD */
39 GIT_COLOR_GREEN, /* NEW */
40 GIT_COLOR_YELLOW, /* COMMIT */
41 GIT_COLOR_BG_RED, /* WHITESPACE */
44 static void diff_filespec_load_driver(struct diff_filespec *one);
45 static char *run_textconv(const char *, struct diff_filespec *, size_t *);
47 static int parse_diff_color_slot(const char *var, int ofs)
49 if (!strcasecmp(var+ofs, "plain"))
50 return DIFF_PLAIN;
51 if (!strcasecmp(var+ofs, "meta"))
52 return DIFF_METAINFO;
53 if (!strcasecmp(var+ofs, "frag"))
54 return DIFF_FRAGINFO;
55 if (!strcasecmp(var+ofs, "old"))
56 return DIFF_FILE_OLD;
57 if (!strcasecmp(var+ofs, "new"))
58 return DIFF_FILE_NEW;
59 if (!strcasecmp(var+ofs, "commit"))
60 return DIFF_COMMIT;
61 if (!strcasecmp(var+ofs, "whitespace"))
62 return DIFF_WHITESPACE;
63 die("bad config variable '%s'", var);
67 * These are to give UI layer defaults.
68 * The core-level commands such as git-diff-files should
69 * never be affected by the setting of diff.renames
70 * the user happens to have in the configuration file.
72 int git_diff_ui_config(const char *var, const char *value, void *cb)
74 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
75 diff_use_color_default = git_config_colorbool(var, value, -1);
76 return 0;
78 if (!strcmp(var, "diff.renames")) {
79 if (!value)
80 diff_detect_rename_default = DIFF_DETECT_RENAME;
81 else if (!strcasecmp(value, "copies") ||
82 !strcasecmp(value, "copy"))
83 diff_detect_rename_default = DIFF_DETECT_COPY;
84 else if (git_config_bool(var,value))
85 diff_detect_rename_default = DIFF_DETECT_RENAME;
86 return 0;
88 if (!strcmp(var, "diff.autorefreshindex")) {
89 diff_auto_refresh_index = git_config_bool(var, value);
90 return 0;
92 if (!strcmp(var, "diff.mnemonicprefix")) {
93 diff_mnemonic_prefix = git_config_bool(var, value);
94 return 0;
96 if (!strcmp(var, "diff.external"))
97 return git_config_string(&external_diff_cmd_cfg, var, value);
98 if (!strcmp(var, "diff.wordregex"))
99 return git_config_string(&diff_word_regex_cfg, var, value);
101 return git_diff_basic_config(var, value, cb);
104 int git_diff_basic_config(const char *var, const char *value, void *cb)
106 if (!strcmp(var, "diff.renamelimit")) {
107 diff_rename_limit_default = git_config_int(var, value);
108 return 0;
111 switch (userdiff_config(var, value)) {
112 case 0: break;
113 case -1: return -1;
114 default: return 0;
117 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
118 int slot = parse_diff_color_slot(var, 11);
119 if (!value)
120 return config_error_nonbool(var);
121 color_parse(value, var, diff_colors[slot]);
122 return 0;
125 /* like GNU diff's --suppress-blank-empty option */
126 if (!strcmp(var, "diff.suppressblankempty") ||
127 /* for backwards compatibility */
128 !strcmp(var, "diff.suppress-blank-empty")) {
129 diff_suppress_blank_empty = git_config_bool(var, value);
130 return 0;
133 return git_color_default_config(var, value, cb);
136 static char *quote_two(const char *one, const char *two)
138 int need_one = quote_c_style(one, NULL, NULL, 1);
139 int need_two = quote_c_style(two, NULL, NULL, 1);
140 struct strbuf res = STRBUF_INIT;
142 if (need_one + need_two) {
143 strbuf_addch(&res, '"');
144 quote_c_style(one, &res, NULL, 1);
145 quote_c_style(two, &res, NULL, 1);
146 strbuf_addch(&res, '"');
147 } else {
148 strbuf_addstr(&res, one);
149 strbuf_addstr(&res, two);
151 return strbuf_detach(&res, NULL);
154 static const char *external_diff(void)
156 static const char *external_diff_cmd = NULL;
157 static int done_preparing = 0;
159 if (done_preparing)
160 return external_diff_cmd;
161 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
162 if (!external_diff_cmd)
163 external_diff_cmd = external_diff_cmd_cfg;
164 done_preparing = 1;
165 return external_diff_cmd;
168 static struct diff_tempfile {
169 const char *name; /* filename external diff should read from */
170 char hex[41];
171 char mode[10];
172 char tmp_path[PATH_MAX];
173 } diff_temp[2];
175 static struct diff_tempfile *claim_diff_tempfile(void) {
176 int i;
177 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
178 if (!diff_temp[i].name)
179 return diff_temp + i;
180 die("BUG: diff is failing to clean up its tempfiles");
183 static int remove_tempfile_installed;
185 static void remove_tempfile(void)
187 int i;
188 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
189 if (diff_temp[i].name == diff_temp[i].tmp_path)
190 unlink(diff_temp[i].name);
191 diff_temp[i].name = NULL;
195 static void remove_tempfile_on_signal(int signo)
197 remove_tempfile();
198 sigchain_pop(signo);
199 raise(signo);
202 static int count_lines(const char *data, int size)
204 int count, ch, completely_empty = 1, nl_just_seen = 0;
205 count = 0;
206 while (0 < size--) {
207 ch = *data++;
208 if (ch == '\n') {
209 count++;
210 nl_just_seen = 1;
211 completely_empty = 0;
213 else {
214 nl_just_seen = 0;
215 completely_empty = 0;
218 if (completely_empty)
219 return 0;
220 if (!nl_just_seen)
221 count++; /* no trailing newline */
222 return count;
225 static void print_line_count(FILE *file, int count)
227 switch (count) {
228 case 0:
229 fprintf(file, "0,0");
230 break;
231 case 1:
232 fprintf(file, "1");
233 break;
234 default:
235 fprintf(file, "1,%d", count);
236 break;
240 static void copy_file_with_prefix(FILE *file,
241 int prefix, const char *data, int size,
242 const char *set, const char *reset)
244 int ch, nl_just_seen = 1;
245 while (0 < size--) {
246 ch = *data++;
247 if (nl_just_seen) {
248 fputs(set, file);
249 putc(prefix, file);
251 if (ch == '\n') {
252 nl_just_seen = 1;
253 fputs(reset, file);
254 } else
255 nl_just_seen = 0;
256 putc(ch, file);
258 if (!nl_just_seen)
259 fprintf(file, "%s\n\\ No newline at end of file\n", reset);
262 static void emit_rewrite_diff(const char *name_a,
263 const char *name_b,
264 struct diff_filespec *one,
265 struct diff_filespec *two,
266 const char *textconv_one,
267 const char *textconv_two,
268 struct diff_options *o)
270 int lc_a, lc_b;
271 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
272 const char *name_a_tab, *name_b_tab;
273 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
274 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
275 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
276 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
277 const char *reset = diff_get_color(color_diff, DIFF_RESET);
278 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
279 const char *a_prefix, *b_prefix;
280 const char *data_one, *data_two;
281 size_t size_one, size_two;
283 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
284 a_prefix = o->b_prefix;
285 b_prefix = o->a_prefix;
286 } else {
287 a_prefix = o->a_prefix;
288 b_prefix = o->b_prefix;
291 name_a += (*name_a == '/');
292 name_b += (*name_b == '/');
293 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
294 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
296 strbuf_reset(&a_name);
297 strbuf_reset(&b_name);
298 quote_two_c_style(&a_name, a_prefix, name_a, 0);
299 quote_two_c_style(&b_name, b_prefix, name_b, 0);
301 diff_populate_filespec(one, 0);
302 diff_populate_filespec(two, 0);
303 if (textconv_one) {
304 data_one = run_textconv(textconv_one, one, &size_one);
305 if (!data_one)
306 die("unable to read files to diff");
308 else {
309 data_one = one->data;
310 size_one = one->size;
312 if (textconv_two) {
313 data_two = run_textconv(textconv_two, two, &size_two);
314 if (!data_two)
315 die("unable to read files to diff");
317 else {
318 data_two = two->data;
319 size_two = two->size;
322 lc_a = count_lines(data_one, size_one);
323 lc_b = count_lines(data_two, size_two);
324 fprintf(o->file,
325 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
326 metainfo, a_name.buf, name_a_tab, reset,
327 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
328 print_line_count(o->file, lc_a);
329 fprintf(o->file, " +");
330 print_line_count(o->file, lc_b);
331 fprintf(o->file, " @@%s\n", reset);
332 if (lc_a)
333 copy_file_with_prefix(o->file, '-', data_one, size_one, old, reset);
334 if (lc_b)
335 copy_file_with_prefix(o->file, '+', data_two, size_two, new, reset);
338 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
340 if (!DIFF_FILE_VALID(one)) {
341 mf->ptr = (char *)""; /* does not matter */
342 mf->size = 0;
343 return 0;
345 else if (diff_populate_filespec(one, 0))
346 return -1;
348 mf->ptr = one->data;
349 mf->size = one->size;
350 return 0;
353 struct diff_words_buffer {
354 mmfile_t text;
355 long alloc;
356 struct diff_words_orig {
357 const char *begin, *end;
358 } *orig;
359 int orig_nr, orig_alloc;
362 static void diff_words_append(char *line, unsigned long len,
363 struct diff_words_buffer *buffer)
365 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
366 line++;
367 len--;
368 memcpy(buffer->text.ptr + buffer->text.size, line, len);
369 buffer->text.size += len;
370 buffer->text.ptr[buffer->text.size] = '\0';
373 struct diff_words_data {
374 struct diff_words_buffer minus, plus;
375 const char *current_plus;
376 FILE *file;
377 regex_t *word_regex;
380 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
382 struct diff_words_data *diff_words = priv;
383 int minus_first, minus_len, plus_first, plus_len;
384 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
386 if (line[0] != '@' || parse_hunk_header(line, len,
387 &minus_first, &minus_len, &plus_first, &plus_len))
388 return;
390 /* POSIX requires that first be decremented by one if len == 0... */
391 if (minus_len) {
392 minus_begin = diff_words->minus.orig[minus_first].begin;
393 minus_end =
394 diff_words->minus.orig[minus_first + minus_len - 1].end;
395 } else
396 minus_begin = minus_end =
397 diff_words->minus.orig[minus_first].end;
399 if (plus_len) {
400 plus_begin = diff_words->plus.orig[plus_first].begin;
401 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
402 } else
403 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
405 if (diff_words->current_plus != plus_begin)
406 fwrite(diff_words->current_plus,
407 plus_begin - diff_words->current_plus, 1,
408 diff_words->file);
409 if (minus_begin != minus_end)
410 color_fwrite_lines(diff_words->file,
411 diff_get_color(1, DIFF_FILE_OLD),
412 minus_end - minus_begin, minus_begin);
413 if (plus_begin != plus_end)
414 color_fwrite_lines(diff_words->file,
415 diff_get_color(1, DIFF_FILE_NEW),
416 plus_end - plus_begin, plus_begin);
418 diff_words->current_plus = plus_end;
421 /* This function starts looking at *begin, and returns 0 iff a word was found. */
422 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
423 int *begin, int *end)
425 if (word_regex && *begin < buffer->size) {
426 regmatch_t match[1];
427 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
428 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
429 '\n', match[0].rm_eo - match[0].rm_so);
430 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
431 *begin += match[0].rm_so;
432 return *begin >= *end;
434 return -1;
437 /* find the next word */
438 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
439 (*begin)++;
440 if (*begin >= buffer->size)
441 return -1;
443 /* find the end of the word */
444 *end = *begin + 1;
445 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
446 (*end)++;
448 return 0;
452 * This function splits the words in buffer->text, stores the list with
453 * newline separator into out, and saves the offsets of the original words
454 * in buffer->orig.
456 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
457 regex_t *word_regex)
459 int i, j;
460 long alloc = 0;
462 out->size = 0;
463 out->ptr = NULL;
465 /* fake an empty "0th" word */
466 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
467 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
468 buffer->orig_nr = 1;
470 for (i = 0; i < buffer->text.size; i++) {
471 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
472 return;
474 /* store original boundaries */
475 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
476 buffer->orig_alloc);
477 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
478 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
479 buffer->orig_nr++;
481 /* store one word */
482 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
483 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
484 out->ptr[out->size + j - i] = '\n';
485 out->size += j - i + 1;
487 i = j - 1;
491 /* this executes the word diff on the accumulated buffers */
492 static void diff_words_show(struct diff_words_data *diff_words)
494 xpparam_t xpp;
495 xdemitconf_t xecfg;
496 xdemitcb_t ecb;
497 mmfile_t minus, plus;
499 /* special case: only removal */
500 if (!diff_words->plus.text.size) {
501 color_fwrite_lines(diff_words->file,
502 diff_get_color(1, DIFF_FILE_OLD),
503 diff_words->minus.text.size, diff_words->minus.text.ptr);
504 diff_words->minus.text.size = 0;
505 return;
508 diff_words->current_plus = diff_words->plus.text.ptr;
510 memset(&xpp, 0, sizeof(xpp));
511 memset(&xecfg, 0, sizeof(xecfg));
512 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
513 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
514 xpp.flags = XDF_NEED_MINIMAL;
515 /* as only the hunk header will be parsed, we need a 0-context */
516 xecfg.ctxlen = 0;
517 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
518 &xpp, &xecfg, &ecb);
519 free(minus.ptr);
520 free(plus.ptr);
521 if (diff_words->current_plus != diff_words->plus.text.ptr +
522 diff_words->plus.text.size)
523 fwrite(diff_words->current_plus,
524 diff_words->plus.text.ptr + diff_words->plus.text.size
525 - diff_words->current_plus, 1,
526 diff_words->file);
527 diff_words->minus.text.size = diff_words->plus.text.size = 0;
530 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
532 struct emit_callback {
533 int nparents, color_diff;
534 unsigned ws_rule;
535 sane_truncate_fn truncate;
536 const char **label_path;
537 struct diff_words_data *diff_words;
538 int *found_changesp;
539 FILE *file;
542 static void free_diff_words_data(struct emit_callback *ecbdata)
544 if (ecbdata->diff_words) {
545 /* flush buffers */
546 if (ecbdata->diff_words->minus.text.size ||
547 ecbdata->diff_words->plus.text.size)
548 diff_words_show(ecbdata->diff_words);
550 free (ecbdata->diff_words->minus.text.ptr);
551 free (ecbdata->diff_words->minus.orig);
552 free (ecbdata->diff_words->plus.text.ptr);
553 free (ecbdata->diff_words->plus.orig);
554 free(ecbdata->diff_words->word_regex);
555 free(ecbdata->diff_words);
556 ecbdata->diff_words = NULL;
560 const char *diff_get_color(int diff_use_color, enum color_diff ix)
562 if (diff_use_color)
563 return diff_colors[ix];
564 return "";
567 static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
569 int has_trailing_newline, has_trailing_carriage_return;
571 has_trailing_newline = (len > 0 && line[len-1] == '\n');
572 if (has_trailing_newline)
573 len--;
574 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
575 if (has_trailing_carriage_return)
576 len--;
578 fputs(set, file);
579 fwrite(line, len, 1, file);
580 fputs(reset, file);
581 if (has_trailing_carriage_return)
582 fputc('\r', file);
583 if (has_trailing_newline)
584 fputc('\n', file);
587 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
589 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
590 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
592 if (!*ws)
593 emit_line(ecbdata->file, set, reset, line, len);
594 else {
595 /* Emit just the prefix, then the rest. */
596 emit_line(ecbdata->file, set, reset, line, ecbdata->nparents);
597 ws_check_emit(line + ecbdata->nparents,
598 len - ecbdata->nparents, ecbdata->ws_rule,
599 ecbdata->file, set, reset, ws);
603 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
605 const char *cp;
606 unsigned long allot;
607 size_t l = len;
609 if (ecb->truncate)
610 return ecb->truncate(line, len);
611 cp = line;
612 allot = l;
613 while (0 < l) {
614 (void) utf8_width(&cp, &l);
615 if (!cp)
616 break; /* truncated in the middle? */
618 return allot - l;
621 static void fn_out_consume(void *priv, char *line, unsigned long len)
623 int i;
624 int color;
625 struct emit_callback *ecbdata = priv;
626 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
627 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
628 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
630 *(ecbdata->found_changesp) = 1;
632 if (ecbdata->label_path[0]) {
633 const char *name_a_tab, *name_b_tab;
635 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
636 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
638 fprintf(ecbdata->file, "%s--- %s%s%s\n",
639 meta, ecbdata->label_path[0], reset, name_a_tab);
640 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
641 meta, ecbdata->label_path[1], reset, name_b_tab);
642 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
645 if (diff_suppress_blank_empty
646 && len == 2 && line[0] == ' ' && line[1] == '\n') {
647 line[0] = '\n';
648 len = 1;
651 /* This is not really necessary for now because
652 * this codepath only deals with two-way diffs.
654 for (i = 0; i < len && line[i] == '@'; i++)
656 if (2 <= i && i < len && line[i] == ' ') {
657 ecbdata->nparents = i - 1;
658 len = sane_truncate_line(ecbdata, line, len);
659 emit_line(ecbdata->file,
660 diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
661 reset, line, len);
662 if (line[len-1] != '\n')
663 putc('\n', ecbdata->file);
664 return;
667 if (len < ecbdata->nparents) {
668 emit_line(ecbdata->file, reset, reset, line, len);
669 return;
672 color = DIFF_PLAIN;
673 if (ecbdata->diff_words && ecbdata->nparents != 1)
674 /* fall back to normal diff */
675 free_diff_words_data(ecbdata);
676 if (ecbdata->diff_words) {
677 if (line[0] == '-') {
678 diff_words_append(line, len,
679 &ecbdata->diff_words->minus);
680 return;
681 } else if (line[0] == '+') {
682 diff_words_append(line, len,
683 &ecbdata->diff_words->plus);
684 return;
686 if (ecbdata->diff_words->minus.text.size ||
687 ecbdata->diff_words->plus.text.size)
688 diff_words_show(ecbdata->diff_words);
689 line++;
690 len--;
691 emit_line(ecbdata->file, plain, reset, line, len);
692 return;
694 for (i = 0; i < ecbdata->nparents && len; i++) {
695 if (line[i] == '-')
696 color = DIFF_FILE_OLD;
697 else if (line[i] == '+')
698 color = DIFF_FILE_NEW;
701 if (color != DIFF_FILE_NEW) {
702 emit_line(ecbdata->file,
703 diff_get_color(ecbdata->color_diff, color),
704 reset, line, len);
705 return;
707 emit_add_line(reset, ecbdata, line, len);
710 static char *pprint_rename(const char *a, const char *b)
712 const char *old = a;
713 const char *new = b;
714 struct strbuf name = STRBUF_INIT;
715 int pfx_length, sfx_length;
716 int len_a = strlen(a);
717 int len_b = strlen(b);
718 int a_midlen, b_midlen;
719 int qlen_a = quote_c_style(a, NULL, NULL, 0);
720 int qlen_b = quote_c_style(b, NULL, NULL, 0);
722 if (qlen_a || qlen_b) {
723 quote_c_style(a, &name, NULL, 0);
724 strbuf_addstr(&name, " => ");
725 quote_c_style(b, &name, NULL, 0);
726 return strbuf_detach(&name, NULL);
729 /* Find common prefix */
730 pfx_length = 0;
731 while (*old && *new && *old == *new) {
732 if (*old == '/')
733 pfx_length = old - a + 1;
734 old++;
735 new++;
738 /* Find common suffix */
739 old = a + len_a;
740 new = b + len_b;
741 sfx_length = 0;
742 while (a <= old && b <= new && *old == *new) {
743 if (*old == '/')
744 sfx_length = len_a - (old - a);
745 old--;
746 new--;
750 * pfx{mid-a => mid-b}sfx
751 * {pfx-a => pfx-b}sfx
752 * pfx{sfx-a => sfx-b}
753 * name-a => name-b
755 a_midlen = len_a - pfx_length - sfx_length;
756 b_midlen = len_b - pfx_length - sfx_length;
757 if (a_midlen < 0)
758 a_midlen = 0;
759 if (b_midlen < 0)
760 b_midlen = 0;
762 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
763 if (pfx_length + sfx_length) {
764 strbuf_add(&name, a, pfx_length);
765 strbuf_addch(&name, '{');
767 strbuf_add(&name, a + pfx_length, a_midlen);
768 strbuf_addstr(&name, " => ");
769 strbuf_add(&name, b + pfx_length, b_midlen);
770 if (pfx_length + sfx_length) {
771 strbuf_addch(&name, '}');
772 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
774 return strbuf_detach(&name, NULL);
777 struct diffstat_t {
778 int nr;
779 int alloc;
780 struct diffstat_file {
781 char *from_name;
782 char *name;
783 char *print_name;
784 unsigned is_unmerged:1;
785 unsigned is_binary:1;
786 unsigned is_renamed:1;
787 unsigned int added, deleted;
788 } **files;
791 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
792 const char *name_a,
793 const char *name_b)
795 struct diffstat_file *x;
796 x = xcalloc(sizeof (*x), 1);
797 if (diffstat->nr == diffstat->alloc) {
798 diffstat->alloc = alloc_nr(diffstat->alloc);
799 diffstat->files = xrealloc(diffstat->files,
800 diffstat->alloc * sizeof(x));
802 diffstat->files[diffstat->nr++] = x;
803 if (name_b) {
804 x->from_name = xstrdup(name_a);
805 x->name = xstrdup(name_b);
806 x->is_renamed = 1;
808 else {
809 x->from_name = NULL;
810 x->name = xstrdup(name_a);
812 return x;
815 static void diffstat_consume(void *priv, char *line, unsigned long len)
817 struct diffstat_t *diffstat = priv;
818 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
820 if (line[0] == '+')
821 x->added++;
822 else if (line[0] == '-')
823 x->deleted++;
826 const char mime_boundary_leader[] = "------------";
828 static int scale_linear(int it, int width, int max_change)
831 * make sure that at least one '-' is printed if there were deletions,
832 * and likewise for '+'.
834 if (max_change < 2)
835 return it;
836 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
839 static void show_name(FILE *file,
840 const char *prefix, const char *name, int len,
841 const char *reset, const char *set)
843 fprintf(file, " %s%s%-*s%s |", set, prefix, len, name, reset);
846 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
848 if (cnt <= 0)
849 return;
850 fprintf(file, "%s", set);
851 while (cnt--)
852 putc(ch, file);
853 fprintf(file, "%s", reset);
856 static void fill_print_name(struct diffstat_file *file)
858 char *pname;
860 if (file->print_name)
861 return;
863 if (!file->is_renamed) {
864 struct strbuf buf = STRBUF_INIT;
865 if (quote_c_style(file->name, &buf, NULL, 0)) {
866 pname = strbuf_detach(&buf, NULL);
867 } else {
868 pname = file->name;
869 strbuf_release(&buf);
871 } else {
872 pname = pprint_rename(file->from_name, file->name);
874 file->print_name = pname;
877 static void show_stats(struct diffstat_t* data, struct diff_options *options)
879 int i, len, add, del, adds = 0, dels = 0;
880 int max_change = 0, max_len = 0;
881 int total_files = data->nr;
882 int width, name_width;
883 const char *reset, *set, *add_c, *del_c;
885 if (data->nr == 0)
886 return;
888 width = options->stat_width ? options->stat_width : 80;
889 name_width = options->stat_name_width ? options->stat_name_width : 50;
891 /* Sanity: give at least 5 columns to the graph,
892 * but leave at least 10 columns for the name.
894 if (width < 25)
895 width = 25;
896 if (name_width < 10)
897 name_width = 10;
898 else if (width < name_width + 15)
899 name_width = width - 15;
901 /* Find the longest filename and max number of changes */
902 reset = diff_get_color_opt(options, DIFF_RESET);
903 set = diff_get_color_opt(options, DIFF_PLAIN);
904 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
905 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
907 for (i = 0; i < data->nr; i++) {
908 struct diffstat_file *file = data->files[i];
909 int change = file->added + file->deleted;
910 fill_print_name(file);
911 len = strlen(file->print_name);
912 if (max_len < len)
913 max_len = len;
915 if (file->is_binary || file->is_unmerged)
916 continue;
917 if (max_change < change)
918 max_change = change;
921 /* Compute the width of the graph part;
922 * 10 is for one blank at the beginning of the line plus
923 * " | count " between the name and the graph.
925 * From here on, name_width is the width of the name area,
926 * and width is the width of the graph area.
928 name_width = (name_width < max_len) ? name_width : max_len;
929 if (width < (name_width + 10) + max_change)
930 width = width - (name_width + 10);
931 else
932 width = max_change;
934 for (i = 0; i < data->nr; i++) {
935 const char *prefix = "";
936 char *name = data->files[i]->print_name;
937 int added = data->files[i]->added;
938 int deleted = data->files[i]->deleted;
939 int name_len;
942 * "scale" the filename
944 len = name_width;
945 name_len = strlen(name);
946 if (name_width < name_len) {
947 char *slash;
948 prefix = "...";
949 len -= 3;
950 name += name_len - len;
951 slash = strchr(name, '/');
952 if (slash)
953 name = slash;
956 if (data->files[i]->is_binary) {
957 show_name(options->file, prefix, name, len, reset, set);
958 fprintf(options->file, " Bin ");
959 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
960 fprintf(options->file, " -> ");
961 fprintf(options->file, "%s%d%s", add_c, added, reset);
962 fprintf(options->file, " bytes");
963 fprintf(options->file, "\n");
964 continue;
966 else if (data->files[i]->is_unmerged) {
967 show_name(options->file, prefix, name, len, reset, set);
968 fprintf(options->file, " Unmerged\n");
969 continue;
971 else if (!data->files[i]->is_renamed &&
972 (added + deleted == 0)) {
973 total_files--;
974 continue;
978 * scale the add/delete
980 add = added;
981 del = deleted;
982 adds += add;
983 dels += del;
985 if (width <= max_change) {
986 add = scale_linear(add, width, max_change);
987 del = scale_linear(del, width, max_change);
989 show_name(options->file, prefix, name, len, reset, set);
990 fprintf(options->file, "%5d%s", added + deleted,
991 added + deleted ? " " : "");
992 show_graph(options->file, '+', add, add_c, reset);
993 show_graph(options->file, '-', del, del_c, reset);
994 fprintf(options->file, "\n");
996 fprintf(options->file,
997 "%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
998 set, total_files, adds, dels, reset);
1001 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
1003 int i, adds = 0, dels = 0, total_files = data->nr;
1005 if (data->nr == 0)
1006 return;
1008 for (i = 0; i < data->nr; i++) {
1009 if (!data->files[i]->is_binary &&
1010 !data->files[i]->is_unmerged) {
1011 int added = data->files[i]->added;
1012 int deleted= data->files[i]->deleted;
1013 if (!data->files[i]->is_renamed &&
1014 (added + deleted == 0)) {
1015 total_files--;
1016 } else {
1017 adds += added;
1018 dels += deleted;
1022 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1023 total_files, adds, dels);
1026 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
1028 int i;
1030 if (data->nr == 0)
1031 return;
1033 for (i = 0; i < data->nr; i++) {
1034 struct diffstat_file *file = data->files[i];
1036 if (file->is_binary)
1037 fprintf(options->file, "-\t-\t");
1038 else
1039 fprintf(options->file,
1040 "%d\t%d\t", file->added, file->deleted);
1041 if (options->line_termination) {
1042 fill_print_name(file);
1043 if (!file->is_renamed)
1044 write_name_quoted(file->name, options->file,
1045 options->line_termination);
1046 else {
1047 fputs(file->print_name, options->file);
1048 putc(options->line_termination, options->file);
1050 } else {
1051 if (file->is_renamed) {
1052 putc('\0', options->file);
1053 write_name_quoted(file->from_name, options->file, '\0');
1055 write_name_quoted(file->name, options->file, '\0');
1060 struct dirstat_file {
1061 const char *name;
1062 unsigned long changed;
1065 struct dirstat_dir {
1066 struct dirstat_file *files;
1067 int alloc, nr, percent, cumulative;
1070 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1072 unsigned long this_dir = 0;
1073 unsigned int sources = 0;
1075 while (dir->nr) {
1076 struct dirstat_file *f = dir->files;
1077 int namelen = strlen(f->name);
1078 unsigned long this;
1079 char *slash;
1081 if (namelen < baselen)
1082 break;
1083 if (memcmp(f->name, base, baselen))
1084 break;
1085 slash = strchr(f->name + baselen, '/');
1086 if (slash) {
1087 int newbaselen = slash + 1 - f->name;
1088 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1089 sources++;
1090 } else {
1091 this = f->changed;
1092 dir->files++;
1093 dir->nr--;
1094 sources += 2;
1096 this_dir += this;
1100 * We don't report dirstat's for
1101 * - the top level
1102 * - or cases where everything came from a single directory
1103 * under this directory (sources == 1).
1105 if (baselen && sources != 1) {
1106 int permille = this_dir * 1000 / changed;
1107 if (permille) {
1108 int percent = permille / 10;
1109 if (percent >= dir->percent) {
1110 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1111 if (!dir->cumulative)
1112 return 0;
1116 return this_dir;
1119 static int dirstat_compare(const void *_a, const void *_b)
1121 const struct dirstat_file *a = _a;
1122 const struct dirstat_file *b = _b;
1123 return strcmp(a->name, b->name);
1126 static void show_dirstat(struct diff_options *options)
1128 int i;
1129 unsigned long changed;
1130 struct dirstat_dir dir;
1131 struct diff_queue_struct *q = &diff_queued_diff;
1133 dir.files = NULL;
1134 dir.alloc = 0;
1135 dir.nr = 0;
1136 dir.percent = options->dirstat_percent;
1137 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1139 changed = 0;
1140 for (i = 0; i < q->nr; i++) {
1141 struct diff_filepair *p = q->queue[i];
1142 const char *name;
1143 unsigned long copied, added, damage;
1145 name = p->one->path ? p->one->path : p->two->path;
1147 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1148 diff_populate_filespec(p->one, 0);
1149 diff_populate_filespec(p->two, 0);
1150 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1151 &copied, &added);
1152 diff_free_filespec_data(p->one);
1153 diff_free_filespec_data(p->two);
1154 } else if (DIFF_FILE_VALID(p->one)) {
1155 diff_populate_filespec(p->one, 1);
1156 copied = added = 0;
1157 diff_free_filespec_data(p->one);
1158 } else if (DIFF_FILE_VALID(p->two)) {
1159 diff_populate_filespec(p->two, 1);
1160 copied = 0;
1161 added = p->two->size;
1162 diff_free_filespec_data(p->two);
1163 } else
1164 continue;
1167 * Original minus copied is the removed material,
1168 * added is the new material. They are both damages
1169 * made to the preimage. In --dirstat-by-file mode, count
1170 * damaged files, not damaged lines. This is done by
1171 * counting only a single damaged line per file.
1173 damage = (p->one->size - copied) + added;
1174 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1175 damage = 1;
1177 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1178 dir.files[dir.nr].name = name;
1179 dir.files[dir.nr].changed = damage;
1180 changed += damage;
1181 dir.nr++;
1184 /* This can happen even with many files, if everything was renames */
1185 if (!changed)
1186 return;
1188 /* Show all directories with more than x% of the changes */
1189 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1190 gather_dirstat(options->file, &dir, changed, "", 0);
1193 static void free_diffstat_info(struct diffstat_t *diffstat)
1195 int i;
1196 for (i = 0; i < diffstat->nr; i++) {
1197 struct diffstat_file *f = diffstat->files[i];
1198 if (f->name != f->print_name)
1199 free(f->print_name);
1200 free(f->name);
1201 free(f->from_name);
1202 free(f);
1204 free(diffstat->files);
1207 struct checkdiff_t {
1208 const char *filename;
1209 int lineno;
1210 struct diff_options *o;
1211 unsigned ws_rule;
1212 unsigned status;
1213 int trailing_blanks_start;
1216 static int is_conflict_marker(const char *line, unsigned long len)
1218 char firstchar;
1219 int cnt;
1221 if (len < 8)
1222 return 0;
1223 firstchar = line[0];
1224 switch (firstchar) {
1225 case '=': case '>': case '<':
1226 break;
1227 default:
1228 return 0;
1230 for (cnt = 1; cnt < 7; cnt++)
1231 if (line[cnt] != firstchar)
1232 return 0;
1233 /* line[0] thru line[6] are same as firstchar */
1234 if (firstchar == '=') {
1235 /* divider between ours and theirs? */
1236 if (len != 8 || line[7] != '\n')
1237 return 0;
1238 } else if (len < 8 || !isspace(line[7])) {
1239 /* not divider before ours nor after theirs */
1240 return 0;
1242 return 1;
1245 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1247 struct checkdiff_t *data = priv;
1248 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1249 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1250 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1251 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1252 char *err;
1254 if (line[0] == '+') {
1255 unsigned bad;
1256 data->lineno++;
1257 if (!ws_blank_line(line + 1, len - 1, data->ws_rule))
1258 data->trailing_blanks_start = 0;
1259 else if (!data->trailing_blanks_start)
1260 data->trailing_blanks_start = data->lineno;
1261 if (is_conflict_marker(line + 1, len - 1)) {
1262 data->status |= 1;
1263 fprintf(data->o->file,
1264 "%s:%d: leftover conflict marker\n",
1265 data->filename, data->lineno);
1267 bad = ws_check(line + 1, len - 1, data->ws_rule);
1268 if (!bad)
1269 return;
1270 data->status |= bad;
1271 err = whitespace_error_string(bad);
1272 fprintf(data->o->file, "%s:%d: %s.\n",
1273 data->filename, data->lineno, err);
1274 free(err);
1275 emit_line(data->o->file, set, reset, line, 1);
1276 ws_check_emit(line + 1, len - 1, data->ws_rule,
1277 data->o->file, set, reset, ws);
1278 } else if (line[0] == ' ') {
1279 data->lineno++;
1280 data->trailing_blanks_start = 0;
1281 } else if (line[0] == '@') {
1282 char *plus = strchr(line, '+');
1283 if (plus)
1284 data->lineno = strtol(plus, NULL, 10) - 1;
1285 else
1286 die("invalid diff");
1287 data->trailing_blanks_start = 0;
1291 static unsigned char *deflate_it(char *data,
1292 unsigned long size,
1293 unsigned long *result_size)
1295 int bound;
1296 unsigned char *deflated;
1297 z_stream stream;
1299 memset(&stream, 0, sizeof(stream));
1300 deflateInit(&stream, zlib_compression_level);
1301 bound = deflateBound(&stream, size);
1302 deflated = xmalloc(bound);
1303 stream.next_out = deflated;
1304 stream.avail_out = bound;
1306 stream.next_in = (unsigned char *)data;
1307 stream.avail_in = size;
1308 while (deflate(&stream, Z_FINISH) == Z_OK)
1309 ; /* nothing */
1310 deflateEnd(&stream);
1311 *result_size = stream.total_out;
1312 return deflated;
1315 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1317 void *cp;
1318 void *delta;
1319 void *deflated;
1320 void *data;
1321 unsigned long orig_size;
1322 unsigned long delta_size;
1323 unsigned long deflate_size;
1324 unsigned long data_size;
1326 /* We could do deflated delta, or we could do just deflated two,
1327 * whichever is smaller.
1329 delta = NULL;
1330 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1331 if (one->size && two->size) {
1332 delta = diff_delta(one->ptr, one->size,
1333 two->ptr, two->size,
1334 &delta_size, deflate_size);
1335 if (delta) {
1336 void *to_free = delta;
1337 orig_size = delta_size;
1338 delta = deflate_it(delta, delta_size, &delta_size);
1339 free(to_free);
1343 if (delta && delta_size < deflate_size) {
1344 fprintf(file, "delta %lu\n", orig_size);
1345 free(deflated);
1346 data = delta;
1347 data_size = delta_size;
1349 else {
1350 fprintf(file, "literal %lu\n", two->size);
1351 free(delta);
1352 data = deflated;
1353 data_size = deflate_size;
1356 /* emit data encoded in base85 */
1357 cp = data;
1358 while (data_size) {
1359 int bytes = (52 < data_size) ? 52 : data_size;
1360 char line[70];
1361 data_size -= bytes;
1362 if (bytes <= 26)
1363 line[0] = bytes + 'A' - 1;
1364 else
1365 line[0] = bytes - 26 + 'a' - 1;
1366 encode_85(line + 1, cp, bytes);
1367 cp = (char *) cp + bytes;
1368 fputs(line, file);
1369 fputc('\n', file);
1371 fprintf(file, "\n");
1372 free(data);
1375 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1377 fprintf(file, "GIT binary patch\n");
1378 emit_binary_diff_body(file, one, two);
1379 emit_binary_diff_body(file, two, one);
1382 static void diff_filespec_load_driver(struct diff_filespec *one)
1384 if (!one->driver)
1385 one->driver = userdiff_find_by_path(one->path);
1386 if (!one->driver)
1387 one->driver = userdiff_find_by_name("default");
1390 int diff_filespec_is_binary(struct diff_filespec *one)
1392 if (one->is_binary == -1) {
1393 diff_filespec_load_driver(one);
1394 if (one->driver->binary != -1)
1395 one->is_binary = one->driver->binary;
1396 else {
1397 if (!one->data && DIFF_FILE_VALID(one))
1398 diff_populate_filespec(one, 0);
1399 if (one->data)
1400 one->is_binary = buffer_is_binary(one->data,
1401 one->size);
1402 if (one->is_binary == -1)
1403 one->is_binary = 0;
1406 return one->is_binary;
1409 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1411 diff_filespec_load_driver(one);
1412 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1415 static const char *userdiff_word_regex(struct diff_filespec *one)
1417 diff_filespec_load_driver(one);
1418 return one->driver->word_regex;
1421 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1423 if (!options->a_prefix)
1424 options->a_prefix = a;
1425 if (!options->b_prefix)
1426 options->b_prefix = b;
1429 static const char *get_textconv(struct diff_filespec *one)
1431 if (!DIFF_FILE_VALID(one))
1432 return NULL;
1433 if (!S_ISREG(one->mode))
1434 return NULL;
1435 diff_filespec_load_driver(one);
1436 return one->driver->textconv;
1439 static void builtin_diff(const char *name_a,
1440 const char *name_b,
1441 struct diff_filespec *one,
1442 struct diff_filespec *two,
1443 const char *xfrm_msg,
1444 struct diff_options *o,
1445 int complete_rewrite)
1447 mmfile_t mf1, mf2;
1448 const char *lbl[2];
1449 char *a_one, *b_two;
1450 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1451 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1452 const char *a_prefix, *b_prefix;
1453 const char *textconv_one = NULL, *textconv_two = NULL;
1455 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1456 textconv_one = get_textconv(one);
1457 textconv_two = get_textconv(two);
1460 diff_set_mnemonic_prefix(o, "a/", "b/");
1461 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1462 a_prefix = o->b_prefix;
1463 b_prefix = o->a_prefix;
1464 } else {
1465 a_prefix = o->a_prefix;
1466 b_prefix = o->b_prefix;
1469 /* Never use a non-valid filename anywhere if at all possible */
1470 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1471 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1473 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1474 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1475 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1476 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1477 fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1478 if (lbl[0][0] == '/') {
1479 /* /dev/null */
1480 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1481 if (xfrm_msg && xfrm_msg[0])
1482 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1484 else if (lbl[1][0] == '/') {
1485 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1486 if (xfrm_msg && xfrm_msg[0])
1487 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1489 else {
1490 if (one->mode != two->mode) {
1491 fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1492 fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1494 if (xfrm_msg && xfrm_msg[0])
1495 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1497 * we do not run diff between different kind
1498 * of objects.
1500 if ((one->mode ^ two->mode) & S_IFMT)
1501 goto free_ab_and_return;
1502 if (complete_rewrite &&
1503 (textconv_one || !diff_filespec_is_binary(one)) &&
1504 (textconv_two || !diff_filespec_is_binary(two))) {
1505 emit_rewrite_diff(name_a, name_b, one, two,
1506 textconv_one, textconv_two, o);
1507 o->found_changes = 1;
1508 goto free_ab_and_return;
1512 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1513 die("unable to read files to diff");
1515 if (!DIFF_OPT_TST(o, TEXT) &&
1516 ( (diff_filespec_is_binary(one) && !textconv_one) ||
1517 (diff_filespec_is_binary(two) && !textconv_two) )) {
1518 /* Quite common confusing case */
1519 if (mf1.size == mf2.size &&
1520 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1521 goto free_ab_and_return;
1522 if (DIFF_OPT_TST(o, BINARY))
1523 emit_binary_diff(o->file, &mf1, &mf2);
1524 else
1525 fprintf(o->file, "Binary files %s and %s differ\n",
1526 lbl[0], lbl[1]);
1527 o->found_changes = 1;
1529 else {
1530 /* Crazy xdl interfaces.. */
1531 const char *diffopts = getenv("GIT_DIFF_OPTS");
1532 xpparam_t xpp;
1533 xdemitconf_t xecfg;
1534 xdemitcb_t ecb;
1535 struct emit_callback ecbdata;
1536 const struct userdiff_funcname *pe;
1538 if (textconv_one) {
1539 size_t size;
1540 mf1.ptr = run_textconv(textconv_one, one, &size);
1541 if (!mf1.ptr)
1542 die("unable to read files to diff");
1543 mf1.size = size;
1545 if (textconv_two) {
1546 size_t size;
1547 mf2.ptr = run_textconv(textconv_two, two, &size);
1548 if (!mf2.ptr)
1549 die("unable to read files to diff");
1550 mf2.size = size;
1553 pe = diff_funcname_pattern(one);
1554 if (!pe)
1555 pe = diff_funcname_pattern(two);
1557 memset(&xpp, 0, sizeof(xpp));
1558 memset(&xecfg, 0, sizeof(xecfg));
1559 memset(&ecbdata, 0, sizeof(ecbdata));
1560 ecbdata.label_path = lbl;
1561 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1562 ecbdata.found_changesp = &o->found_changes;
1563 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1564 ecbdata.file = o->file;
1565 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1566 xecfg.ctxlen = o->context;
1567 xecfg.interhunkctxlen = o->interhunkcontext;
1568 xecfg.flags = XDL_EMIT_FUNCNAMES;
1569 if (pe)
1570 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1571 if (!diffopts)
1573 else if (!prefixcmp(diffopts, "--unified="))
1574 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1575 else if (!prefixcmp(diffopts, "-u"))
1576 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1577 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1578 ecbdata.diff_words =
1579 xcalloc(1, sizeof(struct diff_words_data));
1580 ecbdata.diff_words->file = o->file;
1581 if (!o->word_regex)
1582 o->word_regex = userdiff_word_regex(one);
1583 if (!o->word_regex)
1584 o->word_regex = userdiff_word_regex(two);
1585 if (!o->word_regex)
1586 o->word_regex = diff_word_regex_cfg;
1587 if (o->word_regex) {
1588 ecbdata.diff_words->word_regex = (regex_t *)
1589 xmalloc(sizeof(regex_t));
1590 if (regcomp(ecbdata.diff_words->word_regex,
1591 o->word_regex,
1592 REG_EXTENDED | REG_NEWLINE))
1593 die ("Invalid regular expression: %s",
1594 o->word_regex);
1597 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1598 &xpp, &xecfg, &ecb);
1599 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1600 free_diff_words_data(&ecbdata);
1601 if (textconv_one)
1602 free(mf1.ptr);
1603 if (textconv_two)
1604 free(mf2.ptr);
1607 free_ab_and_return:
1608 diff_free_filespec_data(one);
1609 diff_free_filespec_data(two);
1610 free(a_one);
1611 free(b_two);
1612 return;
1615 static void builtin_diffstat(const char *name_a, const char *name_b,
1616 struct diff_filespec *one,
1617 struct diff_filespec *two,
1618 struct diffstat_t *diffstat,
1619 struct diff_options *o,
1620 int complete_rewrite)
1622 mmfile_t mf1, mf2;
1623 struct diffstat_file *data;
1625 data = diffstat_add(diffstat, name_a, name_b);
1627 if (!one || !two) {
1628 data->is_unmerged = 1;
1629 return;
1631 if (complete_rewrite) {
1632 diff_populate_filespec(one, 0);
1633 diff_populate_filespec(two, 0);
1634 data->deleted = count_lines(one->data, one->size);
1635 data->added = count_lines(two->data, two->size);
1636 goto free_and_return;
1638 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1639 die("unable to read files to diff");
1641 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1642 data->is_binary = 1;
1643 data->added = mf2.size;
1644 data->deleted = mf1.size;
1645 } else {
1646 /* Crazy xdl interfaces.. */
1647 xpparam_t xpp;
1648 xdemitconf_t xecfg;
1649 xdemitcb_t ecb;
1651 memset(&xpp, 0, sizeof(xpp));
1652 memset(&xecfg, 0, sizeof(xecfg));
1653 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1654 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1655 &xpp, &xecfg, &ecb);
1658 free_and_return:
1659 diff_free_filespec_data(one);
1660 diff_free_filespec_data(two);
1663 static void builtin_checkdiff(const char *name_a, const char *name_b,
1664 const char *attr_path,
1665 struct diff_filespec *one,
1666 struct diff_filespec *two,
1667 struct diff_options *o)
1669 mmfile_t mf1, mf2;
1670 struct checkdiff_t data;
1672 if (!two)
1673 return;
1675 memset(&data, 0, sizeof(data));
1676 data.filename = name_b ? name_b : name_a;
1677 data.lineno = 0;
1678 data.o = o;
1679 data.ws_rule = whitespace_rule(attr_path);
1681 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1682 die("unable to read files to diff");
1685 * All the other codepaths check both sides, but not checking
1686 * the "old" side here is deliberate. We are checking the newly
1687 * introduced changes, and as long as the "new" side is text, we
1688 * can and should check what it introduces.
1690 if (diff_filespec_is_binary(two))
1691 goto free_and_return;
1692 else {
1693 /* Crazy xdl interfaces.. */
1694 xpparam_t xpp;
1695 xdemitconf_t xecfg;
1696 xdemitcb_t ecb;
1698 memset(&xpp, 0, sizeof(xpp));
1699 memset(&xecfg, 0, sizeof(xecfg));
1700 xecfg.ctxlen = 1; /* at least one context line */
1701 xpp.flags = XDF_NEED_MINIMAL;
1702 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1703 &xpp, &xecfg, &ecb);
1705 if ((data.ws_rule & WS_TRAILING_SPACE) &&
1706 data.trailing_blanks_start) {
1707 fprintf(o->file, "%s:%d: ends with blank lines.\n",
1708 data.filename, data.trailing_blanks_start);
1709 data.status = 1; /* report errors */
1712 free_and_return:
1713 diff_free_filespec_data(one);
1714 diff_free_filespec_data(two);
1715 if (data.status)
1716 DIFF_OPT_SET(o, CHECK_FAILED);
1719 struct diff_filespec *alloc_filespec(const char *path)
1721 int namelen = strlen(path);
1722 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1724 memset(spec, 0, sizeof(*spec));
1725 spec->path = (char *)(spec + 1);
1726 memcpy(spec->path, path, namelen+1);
1727 spec->count = 1;
1728 spec->is_binary = -1;
1729 return spec;
1732 void free_filespec(struct diff_filespec *spec)
1734 if (!--spec->count) {
1735 diff_free_filespec_data(spec);
1736 free(spec);
1740 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1741 unsigned short mode)
1743 if (mode) {
1744 spec->mode = canon_mode(mode);
1745 hashcpy(spec->sha1, sha1);
1746 spec->sha1_valid = !is_null_sha1(sha1);
1751 * Given a name and sha1 pair, if the index tells us the file in
1752 * the work tree has that object contents, return true, so that
1753 * prepare_temp_file() does not have to inflate and extract.
1755 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1757 struct cache_entry *ce;
1758 struct stat st;
1759 int pos, len;
1762 * We do not read the cache ourselves here, because the
1763 * benchmark with my previous version that always reads cache
1764 * shows that it makes things worse for diff-tree comparing
1765 * two linux-2.6 kernel trees in an already checked out work
1766 * tree. This is because most diff-tree comparisons deal with
1767 * only a small number of files, while reading the cache is
1768 * expensive for a large project, and its cost outweighs the
1769 * savings we get by not inflating the object to a temporary
1770 * file. Practically, this code only helps when we are used
1771 * by diff-cache --cached, which does read the cache before
1772 * calling us.
1774 if (!active_cache)
1775 return 0;
1777 /* We want to avoid the working directory if our caller
1778 * doesn't need the data in a normal file, this system
1779 * is rather slow with its stat/open/mmap/close syscalls,
1780 * and the object is contained in a pack file. The pack
1781 * is probably already open and will be faster to obtain
1782 * the data through than the working directory. Loose
1783 * objects however would tend to be slower as they need
1784 * to be individually opened and inflated.
1786 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1787 return 0;
1789 len = strlen(name);
1790 pos = cache_name_pos(name, len);
1791 if (pos < 0)
1792 return 0;
1793 ce = active_cache[pos];
1796 * This is not the sha1 we are looking for, or
1797 * unreusable because it is not a regular file.
1799 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1800 return 0;
1803 * If ce is marked as "assume unchanged", there is no
1804 * guarantee that work tree matches what we are looking for.
1806 if (ce->ce_flags & CE_VALID)
1807 return 0;
1810 * If ce matches the file in the work tree, we can reuse it.
1812 if (ce_uptodate(ce) ||
1813 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1814 return 1;
1816 return 0;
1819 static int populate_from_stdin(struct diff_filespec *s)
1821 struct strbuf buf = STRBUF_INIT;
1822 size_t size = 0;
1824 if (strbuf_read(&buf, 0, 0) < 0)
1825 return error("error while reading from stdin %s",
1826 strerror(errno));
1828 s->should_munmap = 0;
1829 s->data = strbuf_detach(&buf, &size);
1830 s->size = size;
1831 s->should_free = 1;
1832 return 0;
1835 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1837 int len;
1838 char *data = xmalloc(100);
1839 len = snprintf(data, 100,
1840 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1841 s->data = data;
1842 s->size = len;
1843 s->should_free = 1;
1844 if (size_only) {
1845 s->data = NULL;
1846 free(data);
1848 return 0;
1852 * While doing rename detection and pickaxe operation, we may need to
1853 * grab the data for the blob (or file) for our own in-core comparison.
1854 * diff_filespec has data and size fields for this purpose.
1856 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1858 int err = 0;
1859 if (!DIFF_FILE_VALID(s))
1860 die("internal error: asking to populate invalid file.");
1861 if (S_ISDIR(s->mode))
1862 return -1;
1864 if (s->data)
1865 return 0;
1867 if (size_only && 0 < s->size)
1868 return 0;
1870 if (S_ISGITLINK(s->mode))
1871 return diff_populate_gitlink(s, size_only);
1873 if (!s->sha1_valid ||
1874 reuse_worktree_file(s->path, s->sha1, 0)) {
1875 struct strbuf buf = STRBUF_INIT;
1876 struct stat st;
1877 int fd;
1879 if (!strcmp(s->path, "-"))
1880 return populate_from_stdin(s);
1882 if (lstat(s->path, &st) < 0) {
1883 if (errno == ENOENT) {
1884 err_empty:
1885 err = -1;
1886 empty:
1887 s->data = (char *)"";
1888 s->size = 0;
1889 return err;
1892 s->size = xsize_t(st.st_size);
1893 if (!s->size)
1894 goto empty;
1895 if (S_ISLNK(st.st_mode)) {
1896 struct strbuf sb = STRBUF_INIT;
1898 if (strbuf_readlink(&sb, s->path, s->size))
1899 goto err_empty;
1900 s->size = sb.len;
1901 s->data = strbuf_detach(&sb, NULL);
1902 s->should_free = 1;
1903 return 0;
1905 if (size_only)
1906 return 0;
1907 fd = open(s->path, O_RDONLY);
1908 if (fd < 0)
1909 goto err_empty;
1910 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1911 close(fd);
1912 s->should_munmap = 1;
1915 * Convert from working tree format to canonical git format
1917 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
1918 size_t size = 0;
1919 munmap(s->data, s->size);
1920 s->should_munmap = 0;
1921 s->data = strbuf_detach(&buf, &size);
1922 s->size = size;
1923 s->should_free = 1;
1926 else {
1927 enum object_type type;
1928 if (size_only)
1929 type = sha1_object_info(s->sha1, &s->size);
1930 else {
1931 s->data = read_sha1_file(s->sha1, &type, &s->size);
1932 s->should_free = 1;
1935 return 0;
1938 void diff_free_filespec_blob(struct diff_filespec *s)
1940 if (s->should_free)
1941 free(s->data);
1942 else if (s->should_munmap)
1943 munmap(s->data, s->size);
1945 if (s->should_free || s->should_munmap) {
1946 s->should_free = s->should_munmap = 0;
1947 s->data = NULL;
1951 void diff_free_filespec_data(struct diff_filespec *s)
1953 diff_free_filespec_blob(s);
1954 free(s->cnt_data);
1955 s->cnt_data = NULL;
1958 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
1959 void *blob,
1960 unsigned long size,
1961 const unsigned char *sha1,
1962 int mode)
1964 int fd;
1965 struct strbuf buf = STRBUF_INIT;
1967 fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1968 if (fd < 0)
1969 die("unable to create temp-file: %s", strerror(errno));
1970 if (convert_to_working_tree(path,
1971 (const char *)blob, (size_t)size, &buf)) {
1972 blob = buf.buf;
1973 size = buf.len;
1975 if (write_in_full(fd, blob, size) != size)
1976 die("unable to write temp-file");
1977 close(fd);
1978 temp->name = temp->tmp_path;
1979 strcpy(temp->hex, sha1_to_hex(sha1));
1980 temp->hex[40] = 0;
1981 sprintf(temp->mode, "%06o", mode);
1982 strbuf_release(&buf);
1985 static struct diff_tempfile *prepare_temp_file(const char *name,
1986 struct diff_filespec *one)
1988 struct diff_tempfile *temp = claim_diff_tempfile();
1990 if (!DIFF_FILE_VALID(one)) {
1991 not_a_valid_file:
1992 /* A '-' entry produces this for file-2, and
1993 * a '+' entry produces this for file-1.
1995 temp->name = "/dev/null";
1996 strcpy(temp->hex, ".");
1997 strcpy(temp->mode, ".");
1998 return temp;
2001 if (!remove_tempfile_installed) {
2002 atexit(remove_tempfile);
2003 sigchain_push_common(remove_tempfile_on_signal);
2004 remove_tempfile_installed = 1;
2007 if (!one->sha1_valid ||
2008 reuse_worktree_file(name, one->sha1, 1)) {
2009 struct stat st;
2010 if (lstat(name, &st) < 0) {
2011 if (errno == ENOENT)
2012 goto not_a_valid_file;
2013 die("stat(%s): %s", name, strerror(errno));
2015 if (S_ISLNK(st.st_mode)) {
2016 int ret;
2017 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
2018 ret = readlink(name, buf, sizeof(buf));
2019 if (ret < 0)
2020 die("readlink(%s)", name);
2021 if (ret == sizeof(buf))
2022 die("symlink too long: %s", name);
2023 prep_temp_blob(name, temp, buf, ret,
2024 (one->sha1_valid ?
2025 one->sha1 : null_sha1),
2026 (one->sha1_valid ?
2027 one->mode : S_IFLNK));
2029 else {
2030 /* we can borrow from the file in the work tree */
2031 temp->name = name;
2032 if (!one->sha1_valid)
2033 strcpy(temp->hex, sha1_to_hex(null_sha1));
2034 else
2035 strcpy(temp->hex, sha1_to_hex(one->sha1));
2036 /* Even though we may sometimes borrow the
2037 * contents from the work tree, we always want
2038 * one->mode. mode is trustworthy even when
2039 * !(one->sha1_valid), as long as
2040 * DIFF_FILE_VALID(one).
2042 sprintf(temp->mode, "%06o", one->mode);
2044 return temp;
2046 else {
2047 if (diff_populate_filespec(one, 0))
2048 die("cannot read data blob for %s", one->path);
2049 prep_temp_blob(name, temp, one->data, one->size,
2050 one->sha1, one->mode);
2052 return temp;
2055 /* An external diff command takes:
2057 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2058 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2061 static void run_external_diff(const char *pgm,
2062 const char *name,
2063 const char *other,
2064 struct diff_filespec *one,
2065 struct diff_filespec *two,
2066 const char *xfrm_msg,
2067 int complete_rewrite)
2069 const char *spawn_arg[10];
2070 int retval;
2071 const char **arg = &spawn_arg[0];
2073 if (one && two) {
2074 struct diff_tempfile *temp_one, *temp_two;
2075 const char *othername = (other ? other : name);
2076 temp_one = prepare_temp_file(name, one);
2077 temp_two = prepare_temp_file(othername, two);
2078 *arg++ = pgm;
2079 *arg++ = name;
2080 *arg++ = temp_one->name;
2081 *arg++ = temp_one->hex;
2082 *arg++ = temp_one->mode;
2083 *arg++ = temp_two->name;
2084 *arg++ = temp_two->hex;
2085 *arg++ = temp_two->mode;
2086 if (other) {
2087 *arg++ = other;
2088 *arg++ = xfrm_msg;
2090 } else {
2091 *arg++ = pgm;
2092 *arg++ = name;
2094 *arg = NULL;
2095 fflush(NULL);
2096 retval = run_command_v_opt(spawn_arg, 0);
2097 remove_tempfile();
2098 if (retval) {
2099 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2100 exit(1);
2104 static int similarity_index(struct diff_filepair *p)
2106 return p->score * 100 / MAX_SCORE;
2109 static void fill_metainfo(struct strbuf *msg,
2110 const char *name,
2111 const char *other,
2112 struct diff_filespec *one,
2113 struct diff_filespec *two,
2114 struct diff_options *o,
2115 struct diff_filepair *p)
2117 strbuf_init(msg, PATH_MAX * 2 + 300);
2118 switch (p->status) {
2119 case DIFF_STATUS_COPIED:
2120 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2121 strbuf_addstr(msg, "\ncopy from ");
2122 quote_c_style(name, msg, NULL, 0);
2123 strbuf_addstr(msg, "\ncopy to ");
2124 quote_c_style(other, msg, NULL, 0);
2125 strbuf_addch(msg, '\n');
2126 break;
2127 case DIFF_STATUS_RENAMED:
2128 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2129 strbuf_addstr(msg, "\nrename from ");
2130 quote_c_style(name, msg, NULL, 0);
2131 strbuf_addstr(msg, "\nrename to ");
2132 quote_c_style(other, msg, NULL, 0);
2133 strbuf_addch(msg, '\n');
2134 break;
2135 case DIFF_STATUS_MODIFIED:
2136 if (p->score) {
2137 strbuf_addf(msg, "dissimilarity index %d%%\n",
2138 similarity_index(p));
2139 break;
2141 /* fallthru */
2142 default:
2143 /* nothing */
2146 if (one && two && hashcmp(one->sha1, two->sha1)) {
2147 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2149 if (DIFF_OPT_TST(o, BINARY)) {
2150 mmfile_t mf;
2151 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2152 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2153 abbrev = 40;
2155 strbuf_addf(msg, "index %.*s..%.*s",
2156 abbrev, sha1_to_hex(one->sha1),
2157 abbrev, sha1_to_hex(two->sha1));
2158 if (one->mode == two->mode)
2159 strbuf_addf(msg, " %06o", one->mode);
2160 strbuf_addch(msg, '\n');
2162 if (msg->len)
2163 strbuf_setlen(msg, msg->len - 1);
2166 static void run_diff_cmd(const char *pgm,
2167 const char *name,
2168 const char *other,
2169 const char *attr_path,
2170 struct diff_filespec *one,
2171 struct diff_filespec *two,
2172 struct strbuf *msg,
2173 struct diff_options *o,
2174 struct diff_filepair *p)
2176 const char *xfrm_msg = NULL;
2177 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2179 if (msg) {
2180 fill_metainfo(msg, name, other, one, two, o, p);
2181 xfrm_msg = msg->len ? msg->buf : NULL;
2184 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2185 pgm = NULL;
2186 else {
2187 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2188 if (drv && drv->external)
2189 pgm = drv->external;
2192 if (pgm) {
2193 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2194 complete_rewrite);
2195 return;
2197 if (one && two)
2198 builtin_diff(name, other ? other : name,
2199 one, two, xfrm_msg, o, complete_rewrite);
2200 else
2201 fprintf(o->file, "* Unmerged path %s\n", name);
2204 static void diff_fill_sha1_info(struct diff_filespec *one)
2206 if (DIFF_FILE_VALID(one)) {
2207 if (!one->sha1_valid) {
2208 struct stat st;
2209 if (!strcmp(one->path, "-")) {
2210 hashcpy(one->sha1, null_sha1);
2211 return;
2213 if (lstat(one->path, &st) < 0)
2214 die("stat %s", one->path);
2215 if (index_path(one->sha1, one->path, &st, 0))
2216 die("cannot hash %s", one->path);
2219 else
2220 hashclr(one->sha1);
2223 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2225 /* Strip the prefix but do not molest /dev/null and absolute paths */
2226 if (*namep && **namep != '/')
2227 *namep += prefix_length;
2228 if (*otherp && **otherp != '/')
2229 *otherp += prefix_length;
2232 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2234 const char *pgm = external_diff();
2235 struct strbuf msg;
2236 struct diff_filespec *one = p->one;
2237 struct diff_filespec *two = p->two;
2238 const char *name;
2239 const char *other;
2240 const char *attr_path;
2242 name = p->one->path;
2243 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2244 attr_path = name;
2245 if (o->prefix_length)
2246 strip_prefix(o->prefix_length, &name, &other);
2248 if (DIFF_PAIR_UNMERGED(p)) {
2249 run_diff_cmd(pgm, name, NULL, attr_path,
2250 NULL, NULL, NULL, o, p);
2251 return;
2254 diff_fill_sha1_info(one);
2255 diff_fill_sha1_info(two);
2257 if (!pgm &&
2258 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2259 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2261 * a filepair that changes between file and symlink
2262 * needs to be split into deletion and creation.
2264 struct diff_filespec *null = alloc_filespec(two->path);
2265 run_diff_cmd(NULL, name, other, attr_path,
2266 one, null, &msg, o, p);
2267 free(null);
2268 strbuf_release(&msg);
2270 null = alloc_filespec(one->path);
2271 run_diff_cmd(NULL, name, other, attr_path,
2272 null, two, &msg, o, p);
2273 free(null);
2275 else
2276 run_diff_cmd(pgm, name, other, attr_path,
2277 one, two, &msg, o, p);
2279 strbuf_release(&msg);
2282 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2283 struct diffstat_t *diffstat)
2285 const char *name;
2286 const char *other;
2287 int complete_rewrite = 0;
2289 if (DIFF_PAIR_UNMERGED(p)) {
2290 /* unmerged */
2291 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2292 return;
2295 name = p->one->path;
2296 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2298 if (o->prefix_length)
2299 strip_prefix(o->prefix_length, &name, &other);
2301 diff_fill_sha1_info(p->one);
2302 diff_fill_sha1_info(p->two);
2304 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2305 complete_rewrite = 1;
2306 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2309 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2311 const char *name;
2312 const char *other;
2313 const char *attr_path;
2315 if (DIFF_PAIR_UNMERGED(p)) {
2316 /* unmerged */
2317 return;
2320 name = p->one->path;
2321 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2322 attr_path = other ? other : name;
2324 if (o->prefix_length)
2325 strip_prefix(o->prefix_length, &name, &other);
2327 diff_fill_sha1_info(p->one);
2328 diff_fill_sha1_info(p->two);
2330 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2333 void diff_setup(struct diff_options *options)
2335 memset(options, 0, sizeof(*options));
2337 options->file = stdout;
2339 options->line_termination = '\n';
2340 options->break_opt = -1;
2341 options->rename_limit = -1;
2342 options->dirstat_percent = 3;
2343 options->context = 3;
2345 options->change = diff_change;
2346 options->add_remove = diff_addremove;
2347 if (diff_use_color_default > 0)
2348 DIFF_OPT_SET(options, COLOR_DIFF);
2349 options->detect_rename = diff_detect_rename_default;
2351 if (!diff_mnemonic_prefix) {
2352 options->a_prefix = "a/";
2353 options->b_prefix = "b/";
2357 int diff_setup_done(struct diff_options *options)
2359 int count = 0;
2361 if (options->output_format & DIFF_FORMAT_NAME)
2362 count++;
2363 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2364 count++;
2365 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2366 count++;
2367 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2368 count++;
2369 if (count > 1)
2370 die("--name-only, --name-status, --check and -s are mutually exclusive");
2372 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2373 options->detect_rename = DIFF_DETECT_COPY;
2375 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2376 options->prefix = NULL;
2377 if (options->prefix)
2378 options->prefix_length = strlen(options->prefix);
2379 else
2380 options->prefix_length = 0;
2382 if (options->output_format & (DIFF_FORMAT_NAME |
2383 DIFF_FORMAT_NAME_STATUS |
2384 DIFF_FORMAT_CHECKDIFF |
2385 DIFF_FORMAT_NO_OUTPUT))
2386 options->output_format &= ~(DIFF_FORMAT_RAW |
2387 DIFF_FORMAT_NUMSTAT |
2388 DIFF_FORMAT_DIFFSTAT |
2389 DIFF_FORMAT_SHORTSTAT |
2390 DIFF_FORMAT_DIRSTAT |
2391 DIFF_FORMAT_SUMMARY |
2392 DIFF_FORMAT_PATCH);
2395 * These cases always need recursive; we do not drop caller-supplied
2396 * recursive bits for other formats here.
2398 if (options->output_format & (DIFF_FORMAT_PATCH |
2399 DIFF_FORMAT_NUMSTAT |
2400 DIFF_FORMAT_DIFFSTAT |
2401 DIFF_FORMAT_SHORTSTAT |
2402 DIFF_FORMAT_DIRSTAT |
2403 DIFF_FORMAT_SUMMARY |
2404 DIFF_FORMAT_CHECKDIFF))
2405 DIFF_OPT_SET(options, RECURSIVE);
2407 * Also pickaxe would not work very well if you do not say recursive
2409 if (options->pickaxe)
2410 DIFF_OPT_SET(options, RECURSIVE);
2412 if (options->detect_rename && options->rename_limit < 0)
2413 options->rename_limit = diff_rename_limit_default;
2414 if (options->setup & DIFF_SETUP_USE_CACHE) {
2415 if (!active_cache)
2416 /* read-cache does not die even when it fails
2417 * so it is safe for us to do this here. Also
2418 * it does not smudge active_cache or active_nr
2419 * when it fails, so we do not have to worry about
2420 * cleaning it up ourselves either.
2422 read_cache();
2424 if (options->abbrev <= 0 || 40 < options->abbrev)
2425 options->abbrev = 40; /* full */
2428 * It does not make sense to show the first hit we happened
2429 * to have found. It does not make sense not to return with
2430 * exit code in such a case either.
2432 if (DIFF_OPT_TST(options, QUIET)) {
2433 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2434 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2437 return 0;
2440 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2442 char c, *eq;
2443 int len;
2445 if (*arg != '-')
2446 return 0;
2447 c = *++arg;
2448 if (!c)
2449 return 0;
2450 if (c == arg_short) {
2451 c = *++arg;
2452 if (!c)
2453 return 1;
2454 if (val && isdigit(c)) {
2455 char *end;
2456 int n = strtoul(arg, &end, 10);
2457 if (*end)
2458 return 0;
2459 *val = n;
2460 return 1;
2462 return 0;
2464 if (c != '-')
2465 return 0;
2466 arg++;
2467 eq = strchr(arg, '=');
2468 if (eq)
2469 len = eq - arg;
2470 else
2471 len = strlen(arg);
2472 if (!len || strncmp(arg, arg_long, len))
2473 return 0;
2474 if (eq) {
2475 int n;
2476 char *end;
2477 if (!isdigit(*++eq))
2478 return 0;
2479 n = strtoul(eq, &end, 10);
2480 if (*end)
2481 return 0;
2482 *val = n;
2484 return 1;
2487 static int diff_scoreopt_parse(const char *opt);
2489 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2491 const char *arg = av[0];
2493 /* Output format options */
2494 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2495 options->output_format |= DIFF_FORMAT_PATCH;
2496 else if (opt_arg(arg, 'U', "unified", &options->context))
2497 options->output_format |= DIFF_FORMAT_PATCH;
2498 else if (!strcmp(arg, "--raw"))
2499 options->output_format |= DIFF_FORMAT_RAW;
2500 else if (!strcmp(arg, "--patch-with-raw"))
2501 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2502 else if (!strcmp(arg, "--numstat"))
2503 options->output_format |= DIFF_FORMAT_NUMSTAT;
2504 else if (!strcmp(arg, "--shortstat"))
2505 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2506 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2507 options->output_format |= DIFF_FORMAT_DIRSTAT;
2508 else if (!strcmp(arg, "--cumulative")) {
2509 options->output_format |= DIFF_FORMAT_DIRSTAT;
2510 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2511 } else if (opt_arg(arg, 0, "dirstat-by-file",
2512 &options->dirstat_percent)) {
2513 options->output_format |= DIFF_FORMAT_DIRSTAT;
2514 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2516 else if (!strcmp(arg, "--check"))
2517 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2518 else if (!strcmp(arg, "--summary"))
2519 options->output_format |= DIFF_FORMAT_SUMMARY;
2520 else if (!strcmp(arg, "--patch-with-stat"))
2521 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2522 else if (!strcmp(arg, "--name-only"))
2523 options->output_format |= DIFF_FORMAT_NAME;
2524 else if (!strcmp(arg, "--name-status"))
2525 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2526 else if (!strcmp(arg, "-s"))
2527 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2528 else if (!prefixcmp(arg, "--stat")) {
2529 char *end;
2530 int width = options->stat_width;
2531 int name_width = options->stat_name_width;
2532 arg += 6;
2533 end = (char *)arg;
2535 switch (*arg) {
2536 case '-':
2537 if (!prefixcmp(arg, "-width="))
2538 width = strtoul(arg + 7, &end, 10);
2539 else if (!prefixcmp(arg, "-name-width="))
2540 name_width = strtoul(arg + 12, &end, 10);
2541 break;
2542 case '=':
2543 width = strtoul(arg+1, &end, 10);
2544 if (*end == ',')
2545 name_width = strtoul(end+1, &end, 10);
2548 /* Important! This checks all the error cases! */
2549 if (*end)
2550 return 0;
2551 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2552 options->stat_name_width = name_width;
2553 options->stat_width = width;
2556 /* renames options */
2557 else if (!prefixcmp(arg, "-B")) {
2558 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2559 return -1;
2561 else if (!prefixcmp(arg, "-M")) {
2562 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2563 return -1;
2564 options->detect_rename = DIFF_DETECT_RENAME;
2566 else if (!prefixcmp(arg, "-C")) {
2567 if (options->detect_rename == DIFF_DETECT_COPY)
2568 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2569 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2570 return -1;
2571 options->detect_rename = DIFF_DETECT_COPY;
2573 else if (!strcmp(arg, "--no-renames"))
2574 options->detect_rename = 0;
2575 else if (!strcmp(arg, "--relative"))
2576 DIFF_OPT_SET(options, RELATIVE_NAME);
2577 else if (!prefixcmp(arg, "--relative=")) {
2578 DIFF_OPT_SET(options, RELATIVE_NAME);
2579 options->prefix = arg + 11;
2582 /* xdiff options */
2583 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2584 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2585 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2586 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2587 else if (!strcmp(arg, "--ignore-space-at-eol"))
2588 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2589 else if (!strcmp(arg, "--patience"))
2590 DIFF_XDL_SET(options, PATIENCE_DIFF);
2592 /* flags options */
2593 else if (!strcmp(arg, "--binary")) {
2594 options->output_format |= DIFF_FORMAT_PATCH;
2595 DIFF_OPT_SET(options, BINARY);
2597 else if (!strcmp(arg, "--full-index"))
2598 DIFF_OPT_SET(options, FULL_INDEX);
2599 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2600 DIFF_OPT_SET(options, TEXT);
2601 else if (!strcmp(arg, "-R"))
2602 DIFF_OPT_SET(options, REVERSE_DIFF);
2603 else if (!strcmp(arg, "--find-copies-harder"))
2604 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2605 else if (!strcmp(arg, "--follow"))
2606 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2607 else if (!strcmp(arg, "--color"))
2608 DIFF_OPT_SET(options, COLOR_DIFF);
2609 else if (!strcmp(arg, "--no-color"))
2610 DIFF_OPT_CLR(options, COLOR_DIFF);
2611 else if (!strcmp(arg, "--color-words")) {
2612 DIFF_OPT_SET(options, COLOR_DIFF);
2613 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2615 else if (!prefixcmp(arg, "--color-words=")) {
2616 DIFF_OPT_SET(options, COLOR_DIFF);
2617 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2618 options->word_regex = arg + 14;
2620 else if (!strcmp(arg, "--exit-code"))
2621 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2622 else if (!strcmp(arg, "--quiet"))
2623 DIFF_OPT_SET(options, QUIET);
2624 else if (!strcmp(arg, "--ext-diff"))
2625 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2626 else if (!strcmp(arg, "--no-ext-diff"))
2627 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2628 else if (!strcmp(arg, "--textconv"))
2629 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2630 else if (!strcmp(arg, "--no-textconv"))
2631 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2632 else if (!strcmp(arg, "--ignore-submodules"))
2633 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2635 /* misc options */
2636 else if (!strcmp(arg, "-z"))
2637 options->line_termination = 0;
2638 else if (!prefixcmp(arg, "-l"))
2639 options->rename_limit = strtoul(arg+2, NULL, 10);
2640 else if (!prefixcmp(arg, "-S"))
2641 options->pickaxe = arg + 2;
2642 else if (!strcmp(arg, "--pickaxe-all"))
2643 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2644 else if (!strcmp(arg, "--pickaxe-regex"))
2645 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2646 else if (!prefixcmp(arg, "-O"))
2647 options->orderfile = arg + 2;
2648 else if (!prefixcmp(arg, "--diff-filter="))
2649 options->filter = arg + 14;
2650 else if (!strcmp(arg, "--abbrev"))
2651 options->abbrev = DEFAULT_ABBREV;
2652 else if (!prefixcmp(arg, "--abbrev=")) {
2653 options->abbrev = strtoul(arg + 9, NULL, 10);
2654 if (options->abbrev < MINIMUM_ABBREV)
2655 options->abbrev = MINIMUM_ABBREV;
2656 else if (40 < options->abbrev)
2657 options->abbrev = 40;
2659 else if (!prefixcmp(arg, "--src-prefix="))
2660 options->a_prefix = arg + 13;
2661 else if (!prefixcmp(arg, "--dst-prefix="))
2662 options->b_prefix = arg + 13;
2663 else if (!strcmp(arg, "--no-prefix"))
2664 options->a_prefix = options->b_prefix = "";
2665 else if (opt_arg(arg, '\0', "inter-hunk-context",
2666 &options->interhunkcontext))
2668 else if (!prefixcmp(arg, "--output=")) {
2669 options->file = fopen(arg + strlen("--output="), "w");
2670 options->close_file = 1;
2671 } else
2672 return 0;
2673 return 1;
2676 static int default_diff_options(const char *key, const char *value, void *cb)
2678 if (!strcmp(key, "diff.defaultoptions")) {
2679 char **options = cb;
2680 free(*options);
2681 *options = xstrdup(value);
2683 return 0;
2686 int parse_default_diff_options(int real_argc, const char **real_argv,
2687 struct diff_options *options)
2689 int use_defaults = 1;
2690 struct option option[] = {
2691 OPT_BOOLEAN(0, "defaults", &use_defaults, "use diff defaults"),
2692 OPT_END()
2694 char *default_options = NULL;
2695 const char **argv;
2696 int argc;
2698 real_argc = parse_options(real_argc, real_argv, option, NULL,
2699 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
2700 PARSE_OPT_NO_INTERNAL_HELP);
2702 if (use_defaults) {
2703 git_config(default_diff_options, &default_options);
2704 if (!default_options)
2705 return real_argc;
2707 argc = split_cmdline(default_options, &argv);
2708 diff_opt_parse(options, argv, argc);
2709 free(argv);
2712 return real_argc;
2715 static int parse_num(const char **cp_p)
2717 unsigned long num, scale;
2718 int ch, dot;
2719 const char *cp = *cp_p;
2721 num = 0;
2722 scale = 1;
2723 dot = 0;
2724 for(;;) {
2725 ch = *cp;
2726 if ( !dot && ch == '.' ) {
2727 scale = 1;
2728 dot = 1;
2729 } else if ( ch == '%' ) {
2730 scale = dot ? scale*100 : 100;
2731 cp++; /* % is always at the end */
2732 break;
2733 } else if ( ch >= '0' && ch <= '9' ) {
2734 if ( scale < 100000 ) {
2735 scale *= 10;
2736 num = (num*10) + (ch-'0');
2738 } else {
2739 break;
2741 cp++;
2743 *cp_p = cp;
2745 /* user says num divided by scale and we say internally that
2746 * is MAX_SCORE * num / scale.
2748 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2751 static int diff_scoreopt_parse(const char *opt)
2753 int opt1, opt2, cmd;
2755 if (*opt++ != '-')
2756 return -1;
2757 cmd = *opt++;
2758 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2759 return -1; /* that is not a -M, -C nor -B option */
2761 opt1 = parse_num(&opt);
2762 if (cmd != 'B')
2763 opt2 = 0;
2764 else {
2765 if (*opt == 0)
2766 opt2 = 0;
2767 else if (*opt != '/')
2768 return -1; /* we expect -B80/99 or -B80 */
2769 else {
2770 opt++;
2771 opt2 = parse_num(&opt);
2774 if (*opt != 0)
2775 return -1;
2776 return opt1 | (opt2 << 16);
2779 struct diff_queue_struct diff_queued_diff;
2781 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2783 if (queue->alloc <= queue->nr) {
2784 queue->alloc = alloc_nr(queue->alloc);
2785 queue->queue = xrealloc(queue->queue,
2786 sizeof(dp) * queue->alloc);
2788 queue->queue[queue->nr++] = dp;
2791 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2792 struct diff_filespec *one,
2793 struct diff_filespec *two)
2795 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2796 dp->one = one;
2797 dp->two = two;
2798 if (queue)
2799 diff_q(queue, dp);
2800 return dp;
2803 void diff_free_filepair(struct diff_filepair *p)
2805 free_filespec(p->one);
2806 free_filespec(p->two);
2807 free(p);
2810 /* This is different from find_unique_abbrev() in that
2811 * it stuffs the result with dots for alignment.
2813 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2815 int abblen;
2816 const char *abbrev;
2817 if (len == 40)
2818 return sha1_to_hex(sha1);
2820 abbrev = find_unique_abbrev(sha1, len);
2821 abblen = strlen(abbrev);
2822 if (abblen < 37) {
2823 static char hex[41];
2824 if (len < abblen && abblen <= len + 2)
2825 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2826 else
2827 sprintf(hex, "%s...", abbrev);
2828 return hex;
2830 return sha1_to_hex(sha1);
2833 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2835 int line_termination = opt->line_termination;
2836 int inter_name_termination = line_termination ? '\t' : '\0';
2838 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2839 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2840 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2841 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2843 if (p->score) {
2844 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2845 inter_name_termination);
2846 } else {
2847 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2850 if (p->status == DIFF_STATUS_COPIED ||
2851 p->status == DIFF_STATUS_RENAMED) {
2852 const char *name_a, *name_b;
2853 name_a = p->one->path;
2854 name_b = p->two->path;
2855 strip_prefix(opt->prefix_length, &name_a, &name_b);
2856 write_name_quoted(name_a, opt->file, inter_name_termination);
2857 write_name_quoted(name_b, opt->file, line_termination);
2858 } else {
2859 const char *name_a, *name_b;
2860 name_a = p->one->mode ? p->one->path : p->two->path;
2861 name_b = NULL;
2862 strip_prefix(opt->prefix_length, &name_a, &name_b);
2863 write_name_quoted(name_a, opt->file, line_termination);
2867 int diff_unmodified_pair(struct diff_filepair *p)
2869 /* This function is written stricter than necessary to support
2870 * the currently implemented transformers, but the idea is to
2871 * let transformers to produce diff_filepairs any way they want,
2872 * and filter and clean them up here before producing the output.
2874 struct diff_filespec *one = p->one, *two = p->two;
2876 if (DIFF_PAIR_UNMERGED(p))
2877 return 0; /* unmerged is interesting */
2879 /* deletion, addition, mode or type change
2880 * and rename are all interesting.
2882 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2883 DIFF_PAIR_MODE_CHANGED(p) ||
2884 strcmp(one->path, two->path))
2885 return 0;
2887 /* both are valid and point at the same path. that is, we are
2888 * dealing with a change.
2890 if (one->sha1_valid && two->sha1_valid &&
2891 !hashcmp(one->sha1, two->sha1))
2892 return 1; /* no change */
2893 if (!one->sha1_valid && !two->sha1_valid)
2894 return 1; /* both look at the same file on the filesystem. */
2895 return 0;
2898 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2900 if (diff_unmodified_pair(p))
2901 return;
2903 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2904 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2905 return; /* no tree diffs in patch format */
2907 run_diff(p, o);
2910 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2911 struct diffstat_t *diffstat)
2913 if (diff_unmodified_pair(p))
2914 return;
2916 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2917 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2918 return; /* no tree diffs in patch format */
2920 run_diffstat(p, o, diffstat);
2923 static void diff_flush_checkdiff(struct diff_filepair *p,
2924 struct diff_options *o)
2926 if (diff_unmodified_pair(p))
2927 return;
2929 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2930 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2931 return; /* no tree diffs in patch format */
2933 run_checkdiff(p, o);
2936 int diff_queue_is_empty(void)
2938 struct diff_queue_struct *q = &diff_queued_diff;
2939 int i;
2940 for (i = 0; i < q->nr; i++)
2941 if (!diff_unmodified_pair(q->queue[i]))
2942 return 0;
2943 return 1;
2946 #if DIFF_DEBUG
2947 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2949 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2950 x, one ? one : "",
2951 s->path,
2952 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2953 s->mode,
2954 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2955 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2956 x, one ? one : "",
2957 s->size, s->xfrm_flags);
2960 void diff_debug_filepair(const struct diff_filepair *p, int i)
2962 diff_debug_filespec(p->one, i, "one");
2963 diff_debug_filespec(p->two, i, "two");
2964 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2965 p->score, p->status ? p->status : '?',
2966 p->one->rename_used, p->broken_pair);
2969 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2971 int i;
2972 if (msg)
2973 fprintf(stderr, "%s\n", msg);
2974 fprintf(stderr, "q->nr = %d\n", q->nr);
2975 for (i = 0; i < q->nr; i++) {
2976 struct diff_filepair *p = q->queue[i];
2977 diff_debug_filepair(p, i);
2980 #endif
2982 static void diff_resolve_rename_copy(void)
2984 int i;
2985 struct diff_filepair *p;
2986 struct diff_queue_struct *q = &diff_queued_diff;
2988 diff_debug_queue("resolve-rename-copy", q);
2990 for (i = 0; i < q->nr; i++) {
2991 p = q->queue[i];
2992 p->status = 0; /* undecided */
2993 if (DIFF_PAIR_UNMERGED(p))
2994 p->status = DIFF_STATUS_UNMERGED;
2995 else if (!DIFF_FILE_VALID(p->one))
2996 p->status = DIFF_STATUS_ADDED;
2997 else if (!DIFF_FILE_VALID(p->two))
2998 p->status = DIFF_STATUS_DELETED;
2999 else if (DIFF_PAIR_TYPE_CHANGED(p))
3000 p->status = DIFF_STATUS_TYPE_CHANGED;
3002 /* from this point on, we are dealing with a pair
3003 * whose both sides are valid and of the same type, i.e.
3004 * either in-place edit or rename/copy edit.
3006 else if (DIFF_PAIR_RENAME(p)) {
3008 * A rename might have re-connected a broken
3009 * pair up, causing the pathnames to be the
3010 * same again. If so, that's not a rename at
3011 * all, just a modification..
3013 * Otherwise, see if this source was used for
3014 * multiple renames, in which case we decrement
3015 * the count, and call it a copy.
3017 if (!strcmp(p->one->path, p->two->path))
3018 p->status = DIFF_STATUS_MODIFIED;
3019 else if (--p->one->rename_used > 0)
3020 p->status = DIFF_STATUS_COPIED;
3021 else
3022 p->status = DIFF_STATUS_RENAMED;
3024 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3025 p->one->mode != p->two->mode ||
3026 is_null_sha1(p->one->sha1))
3027 p->status = DIFF_STATUS_MODIFIED;
3028 else {
3029 /* This is a "no-change" entry and should not
3030 * happen anymore, but prepare for broken callers.
3032 error("feeding unmodified %s to diffcore",
3033 p->one->path);
3034 p->status = DIFF_STATUS_UNKNOWN;
3037 diff_debug_queue("resolve-rename-copy done", q);
3040 static int check_pair_status(struct diff_filepair *p)
3042 switch (p->status) {
3043 case DIFF_STATUS_UNKNOWN:
3044 return 0;
3045 case 0:
3046 die("internal error in diff-resolve-rename-copy");
3047 default:
3048 return 1;
3052 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3054 int fmt = opt->output_format;
3056 if (fmt & DIFF_FORMAT_CHECKDIFF)
3057 diff_flush_checkdiff(p, opt);
3058 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3059 diff_flush_raw(p, opt);
3060 else if (fmt & DIFF_FORMAT_NAME) {
3061 const char *name_a, *name_b;
3062 name_a = p->two->path;
3063 name_b = NULL;
3064 strip_prefix(opt->prefix_length, &name_a, &name_b);
3065 write_name_quoted(name_a, opt->file, opt->line_termination);
3069 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3071 if (fs->mode)
3072 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3073 else
3074 fprintf(file, " %s ", newdelete);
3075 write_name_quoted(fs->path, file, '\n');
3079 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3081 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3082 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3083 show_name ? ' ' : '\n');
3084 if (show_name) {
3085 write_name_quoted(p->two->path, file, '\n');
3090 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3092 char *names = pprint_rename(p->one->path, p->two->path);
3094 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3095 free(names);
3096 show_mode_change(file, p, 0);
3099 static void diff_summary(FILE *file, struct diff_filepair *p)
3101 switch(p->status) {
3102 case DIFF_STATUS_DELETED:
3103 show_file_mode_name(file, "delete", p->one);
3104 break;
3105 case DIFF_STATUS_ADDED:
3106 show_file_mode_name(file, "create", p->two);
3107 break;
3108 case DIFF_STATUS_COPIED:
3109 show_rename_copy(file, "copy", p);
3110 break;
3111 case DIFF_STATUS_RENAMED:
3112 show_rename_copy(file, "rename", p);
3113 break;
3114 default:
3115 if (p->score) {
3116 fputs(" rewrite ", file);
3117 write_name_quoted(p->two->path, file, ' ');
3118 fprintf(file, "(%d%%)\n", similarity_index(p));
3120 show_mode_change(file, p, !p->score);
3121 break;
3125 struct patch_id_t {
3126 git_SHA_CTX *ctx;
3127 int patchlen;
3130 static int remove_space(char *line, int len)
3132 int i;
3133 char *dst = line;
3134 unsigned char c;
3136 for (i = 0; i < len; i++)
3137 if (!isspace((c = line[i])))
3138 *dst++ = c;
3140 return dst - line;
3143 static void patch_id_consume(void *priv, char *line, unsigned long len)
3145 struct patch_id_t *data = priv;
3146 int new_len;
3148 /* Ignore line numbers when computing the SHA1 of the patch */
3149 if (!prefixcmp(line, "@@ -"))
3150 return;
3152 new_len = remove_space(line, len);
3154 git_SHA1_Update(data->ctx, line, new_len);
3155 data->patchlen += new_len;
3158 /* returns 0 upon success, and writes result into sha1 */
3159 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3161 struct diff_queue_struct *q = &diff_queued_diff;
3162 int i;
3163 git_SHA_CTX ctx;
3164 struct patch_id_t data;
3165 char buffer[PATH_MAX * 4 + 20];
3167 git_SHA1_Init(&ctx);
3168 memset(&data, 0, sizeof(struct patch_id_t));
3169 data.ctx = &ctx;
3171 for (i = 0; i < q->nr; i++) {
3172 xpparam_t xpp;
3173 xdemitconf_t xecfg;
3174 xdemitcb_t ecb;
3175 mmfile_t mf1, mf2;
3176 struct diff_filepair *p = q->queue[i];
3177 int len1, len2;
3179 memset(&xpp, 0, sizeof(xpp));
3180 memset(&xecfg, 0, sizeof(xecfg));
3181 if (p->status == 0)
3182 return error("internal diff status error");
3183 if (p->status == DIFF_STATUS_UNKNOWN)
3184 continue;
3185 if (diff_unmodified_pair(p))
3186 continue;
3187 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3188 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3189 continue;
3190 if (DIFF_PAIR_UNMERGED(p))
3191 continue;
3193 diff_fill_sha1_info(p->one);
3194 diff_fill_sha1_info(p->two);
3195 if (fill_mmfile(&mf1, p->one) < 0 ||
3196 fill_mmfile(&mf2, p->two) < 0)
3197 return error("unable to read files to diff");
3199 len1 = remove_space(p->one->path, strlen(p->one->path));
3200 len2 = remove_space(p->two->path, strlen(p->two->path));
3201 if (p->one->mode == 0)
3202 len1 = snprintf(buffer, sizeof(buffer),
3203 "diff--gita/%.*sb/%.*s"
3204 "newfilemode%06o"
3205 "---/dev/null"
3206 "+++b/%.*s",
3207 len1, p->one->path,
3208 len2, p->two->path,
3209 p->two->mode,
3210 len2, p->two->path);
3211 else if (p->two->mode == 0)
3212 len1 = snprintf(buffer, sizeof(buffer),
3213 "diff--gita/%.*sb/%.*s"
3214 "deletedfilemode%06o"
3215 "---a/%.*s"
3216 "+++/dev/null",
3217 len1, p->one->path,
3218 len2, p->two->path,
3219 p->one->mode,
3220 len1, p->one->path);
3221 else
3222 len1 = snprintf(buffer, sizeof(buffer),
3223 "diff--gita/%.*sb/%.*s"
3224 "---a/%.*s"
3225 "+++b/%.*s",
3226 len1, p->one->path,
3227 len2, p->two->path,
3228 len1, p->one->path,
3229 len2, p->two->path);
3230 git_SHA1_Update(&ctx, buffer, len1);
3232 xpp.flags = XDF_NEED_MINIMAL;
3233 xecfg.ctxlen = 3;
3234 xecfg.flags = XDL_EMIT_FUNCNAMES;
3235 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3236 &xpp, &xecfg, &ecb);
3239 git_SHA1_Final(sha1, &ctx);
3240 return 0;
3243 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3245 struct diff_queue_struct *q = &diff_queued_diff;
3246 int i;
3247 int result = diff_get_patch_id(options, sha1);
3249 for (i = 0; i < q->nr; i++)
3250 diff_free_filepair(q->queue[i]);
3252 free(q->queue);
3253 q->queue = NULL;
3254 q->nr = q->alloc = 0;
3256 return result;
3259 static int is_summary_empty(const struct diff_queue_struct *q)
3261 int i;
3263 for (i = 0; i < q->nr; i++) {
3264 const struct diff_filepair *p = q->queue[i];
3266 switch (p->status) {
3267 case DIFF_STATUS_DELETED:
3268 case DIFF_STATUS_ADDED:
3269 case DIFF_STATUS_COPIED:
3270 case DIFF_STATUS_RENAMED:
3271 return 0;
3272 default:
3273 if (p->score)
3274 return 0;
3275 if (p->one->mode && p->two->mode &&
3276 p->one->mode != p->two->mode)
3277 return 0;
3278 break;
3281 return 1;
3284 void diff_flush(struct diff_options *options)
3286 struct diff_queue_struct *q = &diff_queued_diff;
3287 int i, output_format = options->output_format;
3288 int separator = 0;
3291 * Order: raw, stat, summary, patch
3292 * or: name/name-status/checkdiff (other bits clear)
3294 if (!q->nr)
3295 goto free_queue;
3297 if (output_format & (DIFF_FORMAT_RAW |
3298 DIFF_FORMAT_NAME |
3299 DIFF_FORMAT_NAME_STATUS |
3300 DIFF_FORMAT_CHECKDIFF)) {
3301 for (i = 0; i < q->nr; i++) {
3302 struct diff_filepair *p = q->queue[i];
3303 if (check_pair_status(p))
3304 flush_one_pair(p, options);
3306 separator++;
3309 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3310 struct diffstat_t diffstat;
3312 memset(&diffstat, 0, sizeof(struct diffstat_t));
3313 for (i = 0; i < q->nr; i++) {
3314 struct diff_filepair *p = q->queue[i];
3315 if (check_pair_status(p))
3316 diff_flush_stat(p, options, &diffstat);
3318 if (output_format & DIFF_FORMAT_NUMSTAT)
3319 show_numstat(&diffstat, options);
3320 if (output_format & DIFF_FORMAT_DIFFSTAT)
3321 show_stats(&diffstat, options);
3322 if (output_format & DIFF_FORMAT_SHORTSTAT)
3323 show_shortstats(&diffstat, options);
3324 free_diffstat_info(&diffstat);
3325 separator++;
3327 if (output_format & DIFF_FORMAT_DIRSTAT)
3328 show_dirstat(options);
3330 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3331 for (i = 0; i < q->nr; i++)
3332 diff_summary(options->file, q->queue[i]);
3333 separator++;
3336 if (output_format & DIFF_FORMAT_PATCH) {
3337 if (separator) {
3338 putc(options->line_termination, options->file);
3339 if (options->stat_sep) {
3340 /* attach patch instead of inline */
3341 fputs(options->stat_sep, options->file);
3345 for (i = 0; i < q->nr; i++) {
3346 struct diff_filepair *p = q->queue[i];
3347 if (check_pair_status(p))
3348 diff_flush_patch(p, options);
3352 if (output_format & DIFF_FORMAT_CALLBACK)
3353 options->format_callback(q, options, options->format_callback_data);
3355 for (i = 0; i < q->nr; i++)
3356 diff_free_filepair(q->queue[i]);
3357 free_queue:
3358 free(q->queue);
3359 q->queue = NULL;
3360 q->nr = q->alloc = 0;
3361 if (options->close_file)
3362 fclose(options->file);
3365 static void diffcore_apply_filter(const char *filter)
3367 int i;
3368 struct diff_queue_struct *q = &diff_queued_diff;
3369 struct diff_queue_struct outq;
3370 outq.queue = NULL;
3371 outq.nr = outq.alloc = 0;
3373 if (!filter)
3374 return;
3376 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3377 int found;
3378 for (i = found = 0; !found && i < q->nr; i++) {
3379 struct diff_filepair *p = q->queue[i];
3380 if (((p->status == DIFF_STATUS_MODIFIED) &&
3381 ((p->score &&
3382 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3383 (!p->score &&
3384 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3385 ((p->status != DIFF_STATUS_MODIFIED) &&
3386 strchr(filter, p->status)))
3387 found++;
3389 if (found)
3390 return;
3392 /* otherwise we will clear the whole queue
3393 * by copying the empty outq at the end of this
3394 * function, but first clear the current entries
3395 * in the queue.
3397 for (i = 0; i < q->nr; i++)
3398 diff_free_filepair(q->queue[i]);
3400 else {
3401 /* Only the matching ones */
3402 for (i = 0; i < q->nr; i++) {
3403 struct diff_filepair *p = q->queue[i];
3405 if (((p->status == DIFF_STATUS_MODIFIED) &&
3406 ((p->score &&
3407 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3408 (!p->score &&
3409 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3410 ((p->status != DIFF_STATUS_MODIFIED) &&
3411 strchr(filter, p->status)))
3412 diff_q(&outq, p);
3413 else
3414 diff_free_filepair(p);
3417 free(q->queue);
3418 *q = outq;
3421 /* Check whether two filespecs with the same mode and size are identical */
3422 static int diff_filespec_is_identical(struct diff_filespec *one,
3423 struct diff_filespec *two)
3425 if (S_ISGITLINK(one->mode))
3426 return 0;
3427 if (diff_populate_filespec(one, 0))
3428 return 0;
3429 if (diff_populate_filespec(two, 0))
3430 return 0;
3431 return !memcmp(one->data, two->data, one->size);
3434 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3436 int i;
3437 struct diff_queue_struct *q = &diff_queued_diff;
3438 struct diff_queue_struct outq;
3439 outq.queue = NULL;
3440 outq.nr = outq.alloc = 0;
3442 for (i = 0; i < q->nr; i++) {
3443 struct diff_filepair *p = q->queue[i];
3446 * 1. Entries that come from stat info dirtyness
3447 * always have both sides (iow, not create/delete),
3448 * one side of the object name is unknown, with
3449 * the same mode and size. Keep the ones that
3450 * do not match these criteria. They have real
3451 * differences.
3453 * 2. At this point, the file is known to be modified,
3454 * with the same mode and size, and the object
3455 * name of one side is unknown. Need to inspect
3456 * the identical contents.
3458 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3459 !DIFF_FILE_VALID(p->two) ||
3460 (p->one->sha1_valid && p->two->sha1_valid) ||
3461 (p->one->mode != p->two->mode) ||
3462 diff_populate_filespec(p->one, 1) ||
3463 diff_populate_filespec(p->two, 1) ||
3464 (p->one->size != p->two->size) ||
3465 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3466 diff_q(&outq, p);
3467 else {
3469 * The caller can subtract 1 from skip_stat_unmatch
3470 * to determine how many paths were dirty only
3471 * due to stat info mismatch.
3473 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3474 diffopt->skip_stat_unmatch++;
3475 diff_free_filepair(p);
3478 free(q->queue);
3479 *q = outq;
3482 void diffcore_std(struct diff_options *options)
3484 if (options->skip_stat_unmatch)
3485 diffcore_skip_stat_unmatch(options);
3486 if (options->break_opt != -1)
3487 diffcore_break(options->break_opt);
3488 if (options->detect_rename)
3489 diffcore_rename(options);
3490 if (options->break_opt != -1)
3491 diffcore_merge_broken();
3492 if (options->pickaxe)
3493 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3494 if (options->orderfile)
3495 diffcore_order(options->orderfile);
3496 diff_resolve_rename_copy();
3497 diffcore_apply_filter(options->filter);
3499 if (diff_queued_diff.nr)
3500 DIFF_OPT_SET(options, HAS_CHANGES);
3501 else
3502 DIFF_OPT_CLR(options, HAS_CHANGES);
3505 int diff_result_code(struct diff_options *opt, int status)
3507 int result = 0;
3508 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3509 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3510 return status;
3511 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3512 DIFF_OPT_TST(opt, HAS_CHANGES))
3513 result |= 01;
3514 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3515 DIFF_OPT_TST(opt, CHECK_FAILED))
3516 result |= 02;
3517 return result;
3520 void diff_addremove(struct diff_options *options,
3521 int addremove, unsigned mode,
3522 const unsigned char *sha1,
3523 const char *concatpath)
3525 struct diff_filespec *one, *two;
3527 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3528 return;
3530 /* This may look odd, but it is a preparation for
3531 * feeding "there are unchanged files which should
3532 * not produce diffs, but when you are doing copy
3533 * detection you would need them, so here they are"
3534 * entries to the diff-core. They will be prefixed
3535 * with something like '=' or '*' (I haven't decided
3536 * which but should not make any difference).
3537 * Feeding the same new and old to diff_change()
3538 * also has the same effect.
3539 * Before the final output happens, they are pruned after
3540 * merged into rename/copy pairs as appropriate.
3542 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3543 addremove = (addremove == '+' ? '-' :
3544 addremove == '-' ? '+' : addremove);
3546 if (options->prefix &&
3547 strncmp(concatpath, options->prefix, options->prefix_length))
3548 return;
3550 one = alloc_filespec(concatpath);
3551 two = alloc_filespec(concatpath);
3553 if (addremove != '+')
3554 fill_filespec(one, sha1, mode);
3555 if (addremove != '-')
3556 fill_filespec(two, sha1, mode);
3558 diff_queue(&diff_queued_diff, one, two);
3559 DIFF_OPT_SET(options, HAS_CHANGES);
3562 void diff_change(struct diff_options *options,
3563 unsigned old_mode, unsigned new_mode,
3564 const unsigned char *old_sha1,
3565 const unsigned char *new_sha1,
3566 const char *concatpath)
3568 struct diff_filespec *one, *two;
3570 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3571 && S_ISGITLINK(new_mode))
3572 return;
3574 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3575 unsigned tmp;
3576 const unsigned char *tmp_c;
3577 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3578 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3581 if (options->prefix &&
3582 strncmp(concatpath, options->prefix, options->prefix_length))
3583 return;
3585 one = alloc_filespec(concatpath);
3586 two = alloc_filespec(concatpath);
3587 fill_filespec(one, old_sha1, old_mode);
3588 fill_filespec(two, new_sha1, new_mode);
3590 diff_queue(&diff_queued_diff, one, two);
3591 DIFF_OPT_SET(options, HAS_CHANGES);
3594 void diff_unmerge(struct diff_options *options,
3595 const char *path,
3596 unsigned mode, const unsigned char *sha1)
3598 struct diff_filespec *one, *two;
3600 if (options->prefix &&
3601 strncmp(path, options->prefix, options->prefix_length))
3602 return;
3604 one = alloc_filespec(path);
3605 two = alloc_filespec(path);
3606 fill_filespec(one, sha1, mode);
3607 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3610 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3611 size_t *outsize)
3613 struct diff_tempfile *temp;
3614 const char *argv[3];
3615 const char **arg = argv;
3616 struct child_process child;
3617 struct strbuf buf = STRBUF_INIT;
3619 temp = prepare_temp_file(spec->path, spec);
3620 *arg++ = pgm;
3621 *arg++ = temp->name;
3622 *arg = NULL;
3624 memset(&child, 0, sizeof(child));
3625 child.argv = argv;
3626 child.out = -1;
3627 if (start_command(&child) != 0 ||
3628 strbuf_read(&buf, child.out, 0) < 0 ||
3629 finish_command(&child) != 0) {
3630 remove_tempfile();
3631 error("error running textconv command '%s'", pgm);
3632 return NULL;
3634 remove_tempfile();
3636 return strbuf_detach(&buf, outsize);