diff --color-words -U0: fix the location of hunk headers
[git/gitweb.git] / diff.c
blobb7ecfe3b179cc68d18b34e675b3c0e67c13ba95d
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"
17 #ifdef NO_FAST_WORKING_DIRECTORY
18 #define FAST_WORKING_DIRECTORY 0
19 #else
20 #define FAST_WORKING_DIRECTORY 1
21 #endif
23 static int diff_detect_rename_default;
24 static int diff_rename_limit_default = 200;
25 static int diff_suppress_blank_empty;
26 int diff_use_color_default = -1;
27 static const char *diff_word_regex_cfg;
28 static const char *external_diff_cmd_cfg;
29 int diff_auto_refresh_index = 1;
30 static int diff_mnemonic_prefix;
32 static char diff_colors[][COLOR_MAXLEN] = {
33 GIT_COLOR_RESET,
34 GIT_COLOR_NORMAL, /* PLAIN */
35 GIT_COLOR_BOLD, /* METAINFO */
36 GIT_COLOR_CYAN, /* FRAGINFO */
37 GIT_COLOR_RED, /* OLD */
38 GIT_COLOR_GREEN, /* NEW */
39 GIT_COLOR_YELLOW, /* COMMIT */
40 GIT_COLOR_BG_RED, /* WHITESPACE */
43 static void diff_filespec_load_driver(struct diff_filespec *one);
44 static char *run_textconv(const char *, struct diff_filespec *, size_t *);
46 static int parse_diff_color_slot(const char *var, int ofs)
48 if (!strcasecmp(var+ofs, "plain"))
49 return DIFF_PLAIN;
50 if (!strcasecmp(var+ofs, "meta"))
51 return DIFF_METAINFO;
52 if (!strcasecmp(var+ofs, "frag"))
53 return DIFF_FRAGINFO;
54 if (!strcasecmp(var+ofs, "old"))
55 return DIFF_FILE_OLD;
56 if (!strcasecmp(var+ofs, "new"))
57 return DIFF_FILE_NEW;
58 if (!strcasecmp(var+ofs, "commit"))
59 return DIFF_COMMIT;
60 if (!strcasecmp(var+ofs, "whitespace"))
61 return DIFF_WHITESPACE;
62 die("bad config variable '%s'", var);
65 static int git_config_rename(const char *var, const char *value)
67 if (!value)
68 return DIFF_DETECT_RENAME;
69 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
70 return DIFF_DETECT_COPY;
71 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
75 * These are to give UI layer defaults.
76 * The core-level commands such as git-diff-files should
77 * never be affected by the setting of diff.renames
78 * the user happens to have in the configuration file.
80 int git_diff_ui_config(const char *var, const char *value, void *cb)
82 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
83 diff_use_color_default = git_config_colorbool(var, value, -1);
84 return 0;
86 if (!strcmp(var, "diff.renames")) {
87 diff_detect_rename_default = git_config_rename(var, value);
88 return 0;
90 if (!strcmp(var, "diff.autorefreshindex")) {
91 diff_auto_refresh_index = git_config_bool(var, value);
92 return 0;
94 if (!strcmp(var, "diff.mnemonicprefix")) {
95 diff_mnemonic_prefix = git_config_bool(var, value);
96 return 0;
98 if (!strcmp(var, "diff.external"))
99 return git_config_string(&external_diff_cmd_cfg, var, value);
100 if (!strcmp(var, "diff.wordregex"))
101 return git_config_string(&diff_word_regex_cfg, var, value);
103 return git_diff_basic_config(var, value, cb);
106 int git_diff_basic_config(const char *var, const char *value, void *cb)
108 if (!strcmp(var, "diff.renamelimit")) {
109 diff_rename_limit_default = git_config_int(var, value);
110 return 0;
113 switch (userdiff_config(var, value)) {
114 case 0: break;
115 case -1: return -1;
116 default: return 0;
119 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
120 int slot = parse_diff_color_slot(var, 11);
121 if (!value)
122 return config_error_nonbool(var);
123 color_parse(value, var, diff_colors[slot]);
124 return 0;
127 /* like GNU diff's --suppress-blank-empty option */
128 if (!strcmp(var, "diff.suppressblankempty") ||
129 /* for backwards compatibility */
130 !strcmp(var, "diff.suppress-blank-empty")) {
131 diff_suppress_blank_empty = git_config_bool(var, value);
132 return 0;
135 return git_color_default_config(var, value, cb);
138 static char *quote_two(const char *one, const char *two)
140 int need_one = quote_c_style(one, NULL, NULL, 1);
141 int need_two = quote_c_style(two, NULL, NULL, 1);
142 struct strbuf res = STRBUF_INIT;
144 if (need_one + need_two) {
145 strbuf_addch(&res, '"');
146 quote_c_style(one, &res, NULL, 1);
147 quote_c_style(two, &res, NULL, 1);
148 strbuf_addch(&res, '"');
149 } else {
150 strbuf_addstr(&res, one);
151 strbuf_addstr(&res, two);
153 return strbuf_detach(&res, NULL);
156 static const char *external_diff(void)
158 static const char *external_diff_cmd = NULL;
159 static int done_preparing = 0;
161 if (done_preparing)
162 return external_diff_cmd;
163 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
164 if (!external_diff_cmd)
165 external_diff_cmd = external_diff_cmd_cfg;
166 done_preparing = 1;
167 return external_diff_cmd;
170 static struct diff_tempfile {
171 const char *name; /* filename external diff should read from */
172 char hex[41];
173 char mode[10];
174 char tmp_path[PATH_MAX];
175 } diff_temp[2];
177 static struct diff_tempfile *claim_diff_tempfile(void) {
178 int i;
179 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
180 if (!diff_temp[i].name)
181 return diff_temp + i;
182 die("BUG: diff is failing to clean up its tempfiles");
185 static int remove_tempfile_installed;
187 static void remove_tempfile(void)
189 int i;
190 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
191 if (diff_temp[i].name == diff_temp[i].tmp_path)
192 unlink_or_warn(diff_temp[i].name);
193 diff_temp[i].name = NULL;
197 static void remove_tempfile_on_signal(int signo)
199 remove_tempfile();
200 sigchain_pop(signo);
201 raise(signo);
204 static int count_lines(const char *data, int size)
206 int count, ch, completely_empty = 1, nl_just_seen = 0;
207 count = 0;
208 while (0 < size--) {
209 ch = *data++;
210 if (ch == '\n') {
211 count++;
212 nl_just_seen = 1;
213 completely_empty = 0;
215 else {
216 nl_just_seen = 0;
217 completely_empty = 0;
220 if (completely_empty)
221 return 0;
222 if (!nl_just_seen)
223 count++; /* no trailing newline */
224 return count;
227 static void print_line_count(FILE *file, int count)
229 switch (count) {
230 case 0:
231 fprintf(file, "0,0");
232 break;
233 case 1:
234 fprintf(file, "1");
235 break;
236 default:
237 fprintf(file, "1,%d", count);
238 break;
242 static void copy_file_with_prefix(FILE *file,
243 int prefix, const char *data, int size,
244 const char *set, const char *reset)
246 int ch, nl_just_seen = 1;
247 while (0 < size--) {
248 ch = *data++;
249 if (nl_just_seen) {
250 fputs(set, file);
251 putc(prefix, file);
253 if (ch == '\n') {
254 nl_just_seen = 1;
255 fputs(reset, file);
256 } else
257 nl_just_seen = 0;
258 putc(ch, file);
260 if (!nl_just_seen)
261 fprintf(file, "%s\n\\ No newline at end of file\n", reset);
264 static void emit_rewrite_diff(const char *name_a,
265 const char *name_b,
266 struct diff_filespec *one,
267 struct diff_filespec *two,
268 const char *textconv_one,
269 const char *textconv_two,
270 struct diff_options *o)
272 int lc_a, lc_b;
273 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
274 const char *name_a_tab, *name_b_tab;
275 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
276 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
277 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
278 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
279 const char *reset = diff_get_color(color_diff, DIFF_RESET);
280 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
281 const char *a_prefix, *b_prefix;
282 const char *data_one, *data_two;
283 size_t size_one, size_two;
285 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
286 a_prefix = o->b_prefix;
287 b_prefix = o->a_prefix;
288 } else {
289 a_prefix = o->a_prefix;
290 b_prefix = o->b_prefix;
293 name_a += (*name_a == '/');
294 name_b += (*name_b == '/');
295 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
296 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
298 strbuf_reset(&a_name);
299 strbuf_reset(&b_name);
300 quote_two_c_style(&a_name, a_prefix, name_a, 0);
301 quote_two_c_style(&b_name, b_prefix, name_b, 0);
303 diff_populate_filespec(one, 0);
304 diff_populate_filespec(two, 0);
305 if (textconv_one) {
306 data_one = run_textconv(textconv_one, one, &size_one);
307 if (!data_one)
308 die("unable to read files to diff");
310 else {
311 data_one = one->data;
312 size_one = one->size;
314 if (textconv_two) {
315 data_two = run_textconv(textconv_two, two, &size_two);
316 if (!data_two)
317 die("unable to read files to diff");
319 else {
320 data_two = two->data;
321 size_two = two->size;
324 lc_a = count_lines(data_one, size_one);
325 lc_b = count_lines(data_two, size_two);
326 fprintf(o->file,
327 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
328 metainfo, a_name.buf, name_a_tab, reset,
329 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
330 print_line_count(o->file, lc_a);
331 fprintf(o->file, " +");
332 print_line_count(o->file, lc_b);
333 fprintf(o->file, " @@%s\n", reset);
334 if (lc_a)
335 copy_file_with_prefix(o->file, '-', data_one, size_one, old, reset);
336 if (lc_b)
337 copy_file_with_prefix(o->file, '+', data_two, size_two, new, reset);
340 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
342 if (!DIFF_FILE_VALID(one)) {
343 mf->ptr = (char *)""; /* does not matter */
344 mf->size = 0;
345 return 0;
347 else if (diff_populate_filespec(one, 0))
348 return -1;
350 mf->ptr = one->data;
351 mf->size = one->size;
352 return 0;
355 struct diff_words_buffer {
356 mmfile_t text;
357 long alloc;
358 struct diff_words_orig {
359 const char *begin, *end;
360 } *orig;
361 int orig_nr, orig_alloc;
364 static void diff_words_append(char *line, unsigned long len,
365 struct diff_words_buffer *buffer)
367 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
368 line++;
369 len--;
370 memcpy(buffer->text.ptr + buffer->text.size, line, len);
371 buffer->text.size += len;
372 buffer->text.ptr[buffer->text.size] = '\0';
375 struct diff_words_data {
376 struct diff_words_buffer minus, plus;
377 const char *current_plus;
378 FILE *file;
379 regex_t *word_regex;
382 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
384 struct diff_words_data *diff_words = priv;
385 int minus_first, minus_len, plus_first, plus_len;
386 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
388 if (line[0] != '@' || parse_hunk_header(line, len,
389 &minus_first, &minus_len, &plus_first, &plus_len))
390 return;
392 /* POSIX requires that first be decremented by one if len == 0... */
393 if (minus_len) {
394 minus_begin = diff_words->minus.orig[minus_first].begin;
395 minus_end =
396 diff_words->minus.orig[minus_first + minus_len - 1].end;
397 } else
398 minus_begin = minus_end =
399 diff_words->minus.orig[minus_first].end;
401 if (plus_len) {
402 plus_begin = diff_words->plus.orig[plus_first].begin;
403 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
404 } else
405 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
407 if (diff_words->current_plus != plus_begin)
408 fwrite(diff_words->current_plus,
409 plus_begin - diff_words->current_plus, 1,
410 diff_words->file);
411 if (minus_begin != minus_end)
412 color_fwrite_lines(diff_words->file,
413 diff_get_color(1, DIFF_FILE_OLD),
414 minus_end - minus_begin, minus_begin);
415 if (plus_begin != plus_end)
416 color_fwrite_lines(diff_words->file,
417 diff_get_color(1, DIFF_FILE_NEW),
418 plus_end - plus_begin, plus_begin);
420 diff_words->current_plus = plus_end;
423 /* This function starts looking at *begin, and returns 0 iff a word was found. */
424 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
425 int *begin, int *end)
427 if (word_regex && *begin < buffer->size) {
428 regmatch_t match[1];
429 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
430 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
431 '\n', match[0].rm_eo - match[0].rm_so);
432 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
433 *begin += match[0].rm_so;
434 return *begin >= *end;
436 return -1;
439 /* find the next word */
440 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
441 (*begin)++;
442 if (*begin >= buffer->size)
443 return -1;
445 /* find the end of the word */
446 *end = *begin + 1;
447 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
448 (*end)++;
450 return 0;
454 * This function splits the words in buffer->text, stores the list with
455 * newline separator into out, and saves the offsets of the original words
456 * in buffer->orig.
458 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
459 regex_t *word_regex)
461 int i, j;
462 long alloc = 0;
464 out->size = 0;
465 out->ptr = NULL;
467 /* fake an empty "0th" word */
468 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
469 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
470 buffer->orig_nr = 1;
472 for (i = 0; i < buffer->text.size; i++) {
473 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
474 return;
476 /* store original boundaries */
477 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
478 buffer->orig_alloc);
479 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
480 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
481 buffer->orig_nr++;
483 /* store one word */
484 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
485 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
486 out->ptr[out->size + j - i] = '\n';
487 out->size += j - i + 1;
489 i = j - 1;
493 /* this executes the word diff on the accumulated buffers */
494 static void diff_words_show(struct diff_words_data *diff_words)
496 xpparam_t xpp;
497 xdemitconf_t xecfg;
498 xdemitcb_t ecb;
499 mmfile_t minus, plus;
501 /* special case: only removal */
502 if (!diff_words->plus.text.size) {
503 color_fwrite_lines(diff_words->file,
504 diff_get_color(1, DIFF_FILE_OLD),
505 diff_words->minus.text.size, diff_words->minus.text.ptr);
506 diff_words->minus.text.size = 0;
507 return;
510 diff_words->current_plus = diff_words->plus.text.ptr;
512 memset(&xpp, 0, sizeof(xpp));
513 memset(&xecfg, 0, sizeof(xecfg));
514 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
515 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
516 xpp.flags = XDF_NEED_MINIMAL;
517 /* as only the hunk header will be parsed, we need a 0-context */
518 xecfg.ctxlen = 0;
519 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
520 &xpp, &xecfg, &ecb);
521 free(minus.ptr);
522 free(plus.ptr);
523 if (diff_words->current_plus != diff_words->plus.text.ptr +
524 diff_words->plus.text.size)
525 fwrite(diff_words->current_plus,
526 diff_words->plus.text.ptr + diff_words->plus.text.size
527 - diff_words->current_plus, 1,
528 diff_words->file);
529 diff_words->minus.text.size = diff_words->plus.text.size = 0;
532 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
534 struct emit_callback {
535 int nparents, color_diff;
536 unsigned ws_rule;
537 sane_truncate_fn truncate;
538 const char **label_path;
539 struct diff_words_data *diff_words;
540 int *found_changesp;
541 FILE *file;
544 static void free_diff_words_data(struct emit_callback *ecbdata)
546 if (ecbdata->diff_words) {
547 /* flush buffers */
548 if (ecbdata->diff_words->minus.text.size ||
549 ecbdata->diff_words->plus.text.size)
550 diff_words_show(ecbdata->diff_words);
552 free (ecbdata->diff_words->minus.text.ptr);
553 free (ecbdata->diff_words->minus.orig);
554 free (ecbdata->diff_words->plus.text.ptr);
555 free (ecbdata->diff_words->plus.orig);
556 free(ecbdata->diff_words->word_regex);
557 free(ecbdata->diff_words);
558 ecbdata->diff_words = NULL;
562 const char *diff_get_color(int diff_use_color, enum color_diff ix)
564 if (diff_use_color)
565 return diff_colors[ix];
566 return "";
569 static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
571 int has_trailing_newline, has_trailing_carriage_return;
573 has_trailing_newline = (len > 0 && line[len-1] == '\n');
574 if (has_trailing_newline)
575 len--;
576 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
577 if (has_trailing_carriage_return)
578 len--;
580 fputs(set, file);
581 fwrite(line, len, 1, file);
582 fputs(reset, file);
583 if (has_trailing_carriage_return)
584 fputc('\r', file);
585 if (has_trailing_newline)
586 fputc('\n', file);
589 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
591 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
592 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
594 if (!*ws)
595 emit_line(ecbdata->file, set, reset, line, len);
596 else {
597 /* Emit just the prefix, then the rest. */
598 emit_line(ecbdata->file, set, reset, line, ecbdata->nparents);
599 ws_check_emit(line + ecbdata->nparents,
600 len - ecbdata->nparents, ecbdata->ws_rule,
601 ecbdata->file, set, reset, ws);
605 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
607 const char *cp;
608 unsigned long allot;
609 size_t l = len;
611 if (ecb->truncate)
612 return ecb->truncate(line, len);
613 cp = line;
614 allot = l;
615 while (0 < l) {
616 (void) utf8_width(&cp, &l);
617 if (!cp)
618 break; /* truncated in the middle? */
620 return allot - l;
623 static void fn_out_consume(void *priv, char *line, unsigned long len)
625 int i;
626 int color;
627 struct emit_callback *ecbdata = priv;
628 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
629 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
630 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
632 *(ecbdata->found_changesp) = 1;
634 if (ecbdata->label_path[0]) {
635 const char *name_a_tab, *name_b_tab;
637 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
638 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
640 fprintf(ecbdata->file, "%s--- %s%s%s\n",
641 meta, ecbdata->label_path[0], reset, name_a_tab);
642 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
643 meta, ecbdata->label_path[1], reset, name_b_tab);
644 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
647 if (diff_suppress_blank_empty
648 && len == 2 && line[0] == ' ' && line[1] == '\n') {
649 line[0] = '\n';
650 len = 1;
653 /* This is not really necessary for now because
654 * this codepath only deals with two-way diffs.
656 for (i = 0; i < len && line[i] == '@'; i++)
658 if (2 <= i && i < len && line[i] == ' ') {
659 /* flush --color-words even for --unified=0 */
660 if (ecbdata->diff_words &&
661 (ecbdata->diff_words->minus.text.size ||
662 ecbdata->diff_words->plus.text.size))
663 diff_words_show(ecbdata->diff_words);
665 ecbdata->nparents = i - 1;
666 len = sane_truncate_line(ecbdata, line, len);
667 emit_line(ecbdata->file,
668 diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
669 reset, line, len);
670 if (line[len-1] != '\n')
671 putc('\n', ecbdata->file);
672 return;
675 if (len < ecbdata->nparents) {
676 emit_line(ecbdata->file, reset, reset, line, len);
677 return;
680 color = DIFF_PLAIN;
681 if (ecbdata->diff_words && ecbdata->nparents != 1)
682 /* fall back to normal diff */
683 free_diff_words_data(ecbdata);
684 if (ecbdata->diff_words) {
685 if (line[0] == '-') {
686 diff_words_append(line, len,
687 &ecbdata->diff_words->minus);
688 return;
689 } else if (line[0] == '+') {
690 diff_words_append(line, len,
691 &ecbdata->diff_words->plus);
692 return;
694 if (ecbdata->diff_words->minus.text.size ||
695 ecbdata->diff_words->plus.text.size)
696 diff_words_show(ecbdata->diff_words);
697 line++;
698 len--;
699 emit_line(ecbdata->file, plain, reset, line, len);
700 return;
702 for (i = 0; i < ecbdata->nparents && len; i++) {
703 if (line[i] == '-')
704 color = DIFF_FILE_OLD;
705 else if (line[i] == '+')
706 color = DIFF_FILE_NEW;
709 if (color != DIFF_FILE_NEW) {
710 emit_line(ecbdata->file,
711 diff_get_color(ecbdata->color_diff, color),
712 reset, line, len);
713 return;
715 emit_add_line(reset, ecbdata, line, len);
718 static char *pprint_rename(const char *a, const char *b)
720 const char *old = a;
721 const char *new = b;
722 struct strbuf name = STRBUF_INIT;
723 int pfx_length, sfx_length;
724 int len_a = strlen(a);
725 int len_b = strlen(b);
726 int a_midlen, b_midlen;
727 int qlen_a = quote_c_style(a, NULL, NULL, 0);
728 int qlen_b = quote_c_style(b, NULL, NULL, 0);
730 if (qlen_a || qlen_b) {
731 quote_c_style(a, &name, NULL, 0);
732 strbuf_addstr(&name, " => ");
733 quote_c_style(b, &name, NULL, 0);
734 return strbuf_detach(&name, NULL);
737 /* Find common prefix */
738 pfx_length = 0;
739 while (*old && *new && *old == *new) {
740 if (*old == '/')
741 pfx_length = old - a + 1;
742 old++;
743 new++;
746 /* Find common suffix */
747 old = a + len_a;
748 new = b + len_b;
749 sfx_length = 0;
750 while (a <= old && b <= new && *old == *new) {
751 if (*old == '/')
752 sfx_length = len_a - (old - a);
753 old--;
754 new--;
758 * pfx{mid-a => mid-b}sfx
759 * {pfx-a => pfx-b}sfx
760 * pfx{sfx-a => sfx-b}
761 * name-a => name-b
763 a_midlen = len_a - pfx_length - sfx_length;
764 b_midlen = len_b - pfx_length - sfx_length;
765 if (a_midlen < 0)
766 a_midlen = 0;
767 if (b_midlen < 0)
768 b_midlen = 0;
770 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
771 if (pfx_length + sfx_length) {
772 strbuf_add(&name, a, pfx_length);
773 strbuf_addch(&name, '{');
775 strbuf_add(&name, a + pfx_length, a_midlen);
776 strbuf_addstr(&name, " => ");
777 strbuf_add(&name, b + pfx_length, b_midlen);
778 if (pfx_length + sfx_length) {
779 strbuf_addch(&name, '}');
780 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
782 return strbuf_detach(&name, NULL);
785 struct diffstat_t {
786 int nr;
787 int alloc;
788 struct diffstat_file {
789 char *from_name;
790 char *name;
791 char *print_name;
792 unsigned is_unmerged:1;
793 unsigned is_binary:1;
794 unsigned is_renamed:1;
795 unsigned int added, deleted;
796 } **files;
799 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
800 const char *name_a,
801 const char *name_b)
803 struct diffstat_file *x;
804 x = xcalloc(sizeof (*x), 1);
805 if (diffstat->nr == diffstat->alloc) {
806 diffstat->alloc = alloc_nr(diffstat->alloc);
807 diffstat->files = xrealloc(diffstat->files,
808 diffstat->alloc * sizeof(x));
810 diffstat->files[diffstat->nr++] = x;
811 if (name_b) {
812 x->from_name = xstrdup(name_a);
813 x->name = xstrdup(name_b);
814 x->is_renamed = 1;
816 else {
817 x->from_name = NULL;
818 x->name = xstrdup(name_a);
820 return x;
823 static void diffstat_consume(void *priv, char *line, unsigned long len)
825 struct diffstat_t *diffstat = priv;
826 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
828 if (line[0] == '+')
829 x->added++;
830 else if (line[0] == '-')
831 x->deleted++;
834 const char mime_boundary_leader[] = "------------";
836 static int scale_linear(int it, int width, int max_change)
839 * make sure that at least one '-' is printed if there were deletions,
840 * and likewise for '+'.
842 if (max_change < 2)
843 return it;
844 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
847 static void show_name(FILE *file,
848 const char *prefix, const char *name, int len)
850 fprintf(file, " %s%-*s |", prefix, len, name);
853 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
855 if (cnt <= 0)
856 return;
857 fprintf(file, "%s", set);
858 while (cnt--)
859 putc(ch, file);
860 fprintf(file, "%s", reset);
863 static void fill_print_name(struct diffstat_file *file)
865 char *pname;
867 if (file->print_name)
868 return;
870 if (!file->is_renamed) {
871 struct strbuf buf = STRBUF_INIT;
872 if (quote_c_style(file->name, &buf, NULL, 0)) {
873 pname = strbuf_detach(&buf, NULL);
874 } else {
875 pname = file->name;
876 strbuf_release(&buf);
878 } else {
879 pname = pprint_rename(file->from_name, file->name);
881 file->print_name = pname;
884 static void show_stats(struct diffstat_t *data, struct diff_options *options)
886 int i, len, add, del, adds = 0, dels = 0;
887 int max_change = 0, max_len = 0;
888 int total_files = data->nr;
889 int width, name_width;
890 const char *reset, *set, *add_c, *del_c;
892 if (data->nr == 0)
893 return;
895 width = options->stat_width ? options->stat_width : 80;
896 name_width = options->stat_name_width ? options->stat_name_width : 50;
898 /* Sanity: give at least 5 columns to the graph,
899 * but leave at least 10 columns for the name.
901 if (width < 25)
902 width = 25;
903 if (name_width < 10)
904 name_width = 10;
905 else if (width < name_width + 15)
906 name_width = width - 15;
908 /* Find the longest filename and max number of changes */
909 reset = diff_get_color_opt(options, DIFF_RESET);
910 set = diff_get_color_opt(options, DIFF_PLAIN);
911 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
912 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
914 for (i = 0; i < data->nr; i++) {
915 struct diffstat_file *file = data->files[i];
916 int change = file->added + file->deleted;
917 fill_print_name(file);
918 len = strlen(file->print_name);
919 if (max_len < len)
920 max_len = len;
922 if (file->is_binary || file->is_unmerged)
923 continue;
924 if (max_change < change)
925 max_change = change;
928 /* Compute the width of the graph part;
929 * 10 is for one blank at the beginning of the line plus
930 * " | count " between the name and the graph.
932 * From here on, name_width is the width of the name area,
933 * and width is the width of the graph area.
935 name_width = (name_width < max_len) ? name_width : max_len;
936 if (width < (name_width + 10) + max_change)
937 width = width - (name_width + 10);
938 else
939 width = max_change;
941 for (i = 0; i < data->nr; i++) {
942 const char *prefix = "";
943 char *name = data->files[i]->print_name;
944 int added = data->files[i]->added;
945 int deleted = data->files[i]->deleted;
946 int name_len;
949 * "scale" the filename
951 len = name_width;
952 name_len = strlen(name);
953 if (name_width < name_len) {
954 char *slash;
955 prefix = "...";
956 len -= 3;
957 name += name_len - len;
958 slash = strchr(name, '/');
959 if (slash)
960 name = slash;
963 if (data->files[i]->is_binary) {
964 show_name(options->file, prefix, name, len);
965 fprintf(options->file, " Bin ");
966 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
967 fprintf(options->file, " -> ");
968 fprintf(options->file, "%s%d%s", add_c, added, reset);
969 fprintf(options->file, " bytes");
970 fprintf(options->file, "\n");
971 continue;
973 else if (data->files[i]->is_unmerged) {
974 show_name(options->file, prefix, name, len);
975 fprintf(options->file, " Unmerged\n");
976 continue;
978 else if (!data->files[i]->is_renamed &&
979 (added + deleted == 0)) {
980 total_files--;
981 continue;
985 * scale the add/delete
987 add = added;
988 del = deleted;
989 adds += add;
990 dels += del;
992 if (width <= max_change) {
993 add = scale_linear(add, width, max_change);
994 del = scale_linear(del, width, max_change);
996 show_name(options->file, prefix, name, len);
997 fprintf(options->file, "%5d%s", added + deleted,
998 added + deleted ? " " : "");
999 show_graph(options->file, '+', add, add_c, reset);
1000 show_graph(options->file, '-', del, del_c, reset);
1001 fprintf(options->file, "\n");
1003 fprintf(options->file,
1004 " %d files changed, %d insertions(+), %d deletions(-)\n",
1005 total_files, adds, dels);
1008 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
1010 int i, adds = 0, dels = 0, total_files = data->nr;
1012 if (data->nr == 0)
1013 return;
1015 for (i = 0; i < data->nr; i++) {
1016 if (!data->files[i]->is_binary &&
1017 !data->files[i]->is_unmerged) {
1018 int added = data->files[i]->added;
1019 int deleted= data->files[i]->deleted;
1020 if (!data->files[i]->is_renamed &&
1021 (added + deleted == 0)) {
1022 total_files--;
1023 } else {
1024 adds += added;
1025 dels += deleted;
1029 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1030 total_files, adds, dels);
1033 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1035 int i;
1037 if (data->nr == 0)
1038 return;
1040 for (i = 0; i < data->nr; i++) {
1041 struct diffstat_file *file = data->files[i];
1043 if (file->is_binary)
1044 fprintf(options->file, "-\t-\t");
1045 else
1046 fprintf(options->file,
1047 "%d\t%d\t", file->added, file->deleted);
1048 if (options->line_termination) {
1049 fill_print_name(file);
1050 if (!file->is_renamed)
1051 write_name_quoted(file->name, options->file,
1052 options->line_termination);
1053 else {
1054 fputs(file->print_name, options->file);
1055 putc(options->line_termination, options->file);
1057 } else {
1058 if (file->is_renamed) {
1059 putc('\0', options->file);
1060 write_name_quoted(file->from_name, options->file, '\0');
1062 write_name_quoted(file->name, options->file, '\0');
1067 struct dirstat_file {
1068 const char *name;
1069 unsigned long changed;
1072 struct dirstat_dir {
1073 struct dirstat_file *files;
1074 int alloc, nr, percent, cumulative;
1077 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1079 unsigned long this_dir = 0;
1080 unsigned int sources = 0;
1082 while (dir->nr) {
1083 struct dirstat_file *f = dir->files;
1084 int namelen = strlen(f->name);
1085 unsigned long this;
1086 char *slash;
1088 if (namelen < baselen)
1089 break;
1090 if (memcmp(f->name, base, baselen))
1091 break;
1092 slash = strchr(f->name + baselen, '/');
1093 if (slash) {
1094 int newbaselen = slash + 1 - f->name;
1095 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1096 sources++;
1097 } else {
1098 this = f->changed;
1099 dir->files++;
1100 dir->nr--;
1101 sources += 2;
1103 this_dir += this;
1107 * We don't report dirstat's for
1108 * - the top level
1109 * - or cases where everything came from a single directory
1110 * under this directory (sources == 1).
1112 if (baselen && sources != 1) {
1113 int permille = this_dir * 1000 / changed;
1114 if (permille) {
1115 int percent = permille / 10;
1116 if (percent >= dir->percent) {
1117 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1118 if (!dir->cumulative)
1119 return 0;
1123 return this_dir;
1126 static int dirstat_compare(const void *_a, const void *_b)
1128 const struct dirstat_file *a = _a;
1129 const struct dirstat_file *b = _b;
1130 return strcmp(a->name, b->name);
1133 static void show_dirstat(struct diff_options *options)
1135 int i;
1136 unsigned long changed;
1137 struct dirstat_dir dir;
1138 struct diff_queue_struct *q = &diff_queued_diff;
1140 dir.files = NULL;
1141 dir.alloc = 0;
1142 dir.nr = 0;
1143 dir.percent = options->dirstat_percent;
1144 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1146 changed = 0;
1147 for (i = 0; i < q->nr; i++) {
1148 struct diff_filepair *p = q->queue[i];
1149 const char *name;
1150 unsigned long copied, added, damage;
1152 name = p->one->path ? p->one->path : p->two->path;
1154 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1155 diff_populate_filespec(p->one, 0);
1156 diff_populate_filespec(p->two, 0);
1157 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1158 &copied, &added);
1159 diff_free_filespec_data(p->one);
1160 diff_free_filespec_data(p->two);
1161 } else if (DIFF_FILE_VALID(p->one)) {
1162 diff_populate_filespec(p->one, 1);
1163 copied = added = 0;
1164 diff_free_filespec_data(p->one);
1165 } else if (DIFF_FILE_VALID(p->two)) {
1166 diff_populate_filespec(p->two, 1);
1167 copied = 0;
1168 added = p->two->size;
1169 diff_free_filespec_data(p->two);
1170 } else
1171 continue;
1174 * Original minus copied is the removed material,
1175 * added is the new material. They are both damages
1176 * made to the preimage. In --dirstat-by-file mode, count
1177 * damaged files, not damaged lines. This is done by
1178 * counting only a single damaged line per file.
1180 damage = (p->one->size - copied) + added;
1181 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1182 damage = 1;
1184 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1185 dir.files[dir.nr].name = name;
1186 dir.files[dir.nr].changed = damage;
1187 changed += damage;
1188 dir.nr++;
1191 /* This can happen even with many files, if everything was renames */
1192 if (!changed)
1193 return;
1195 /* Show all directories with more than x% of the changes */
1196 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1197 gather_dirstat(options->file, &dir, changed, "", 0);
1200 static void free_diffstat_info(struct diffstat_t *diffstat)
1202 int i;
1203 for (i = 0; i < diffstat->nr; i++) {
1204 struct diffstat_file *f = diffstat->files[i];
1205 if (f->name != f->print_name)
1206 free(f->print_name);
1207 free(f->name);
1208 free(f->from_name);
1209 free(f);
1211 free(diffstat->files);
1214 struct checkdiff_t {
1215 const char *filename;
1216 int lineno;
1217 struct diff_options *o;
1218 unsigned ws_rule;
1219 unsigned status;
1220 int trailing_blanks_start;
1223 static int is_conflict_marker(const char *line, unsigned long len)
1225 char firstchar;
1226 int cnt;
1228 if (len < 8)
1229 return 0;
1230 firstchar = line[0];
1231 switch (firstchar) {
1232 case '=': case '>': case '<':
1233 break;
1234 default:
1235 return 0;
1237 for (cnt = 1; cnt < 7; cnt++)
1238 if (line[cnt] != firstchar)
1239 return 0;
1240 /* line[0] thru line[6] are same as firstchar */
1241 if (firstchar == '=') {
1242 /* divider between ours and theirs? */
1243 if (len != 8 || line[7] != '\n')
1244 return 0;
1245 } else if (len < 8 || !isspace(line[7])) {
1246 /* not divider before ours nor after theirs */
1247 return 0;
1249 return 1;
1252 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1254 struct checkdiff_t *data = priv;
1255 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1256 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1257 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1258 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1259 char *err;
1261 if (line[0] == '+') {
1262 unsigned bad;
1263 data->lineno++;
1264 if (!ws_blank_line(line + 1, len - 1, data->ws_rule))
1265 data->trailing_blanks_start = 0;
1266 else if (!data->trailing_blanks_start)
1267 data->trailing_blanks_start = data->lineno;
1268 if (is_conflict_marker(line + 1, len - 1)) {
1269 data->status |= 1;
1270 fprintf(data->o->file,
1271 "%s:%d: leftover conflict marker\n",
1272 data->filename, data->lineno);
1274 bad = ws_check(line + 1, len - 1, data->ws_rule);
1275 if (!bad)
1276 return;
1277 data->status |= bad;
1278 err = whitespace_error_string(bad);
1279 fprintf(data->o->file, "%s:%d: %s.\n",
1280 data->filename, data->lineno, err);
1281 free(err);
1282 emit_line(data->o->file, set, reset, line, 1);
1283 ws_check_emit(line + 1, len - 1, data->ws_rule,
1284 data->o->file, set, reset, ws);
1285 } else if (line[0] == ' ') {
1286 data->lineno++;
1287 data->trailing_blanks_start = 0;
1288 } else if (line[0] == '@') {
1289 char *plus = strchr(line, '+');
1290 if (plus)
1291 data->lineno = strtol(plus, NULL, 10) - 1;
1292 else
1293 die("invalid diff");
1294 data->trailing_blanks_start = 0;
1298 static unsigned char *deflate_it(char *data,
1299 unsigned long size,
1300 unsigned long *result_size)
1302 int bound;
1303 unsigned char *deflated;
1304 z_stream stream;
1306 memset(&stream, 0, sizeof(stream));
1307 deflateInit(&stream, zlib_compression_level);
1308 bound = deflateBound(&stream, size);
1309 deflated = xmalloc(bound);
1310 stream.next_out = deflated;
1311 stream.avail_out = bound;
1313 stream.next_in = (unsigned char *)data;
1314 stream.avail_in = size;
1315 while (deflate(&stream, Z_FINISH) == Z_OK)
1316 ; /* nothing */
1317 deflateEnd(&stream);
1318 *result_size = stream.total_out;
1319 return deflated;
1322 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1324 void *cp;
1325 void *delta;
1326 void *deflated;
1327 void *data;
1328 unsigned long orig_size;
1329 unsigned long delta_size;
1330 unsigned long deflate_size;
1331 unsigned long data_size;
1333 /* We could do deflated delta, or we could do just deflated two,
1334 * whichever is smaller.
1336 delta = NULL;
1337 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1338 if (one->size && two->size) {
1339 delta = diff_delta(one->ptr, one->size,
1340 two->ptr, two->size,
1341 &delta_size, deflate_size);
1342 if (delta) {
1343 void *to_free = delta;
1344 orig_size = delta_size;
1345 delta = deflate_it(delta, delta_size, &delta_size);
1346 free(to_free);
1350 if (delta && delta_size < deflate_size) {
1351 fprintf(file, "delta %lu\n", orig_size);
1352 free(deflated);
1353 data = delta;
1354 data_size = delta_size;
1356 else {
1357 fprintf(file, "literal %lu\n", two->size);
1358 free(delta);
1359 data = deflated;
1360 data_size = deflate_size;
1363 /* emit data encoded in base85 */
1364 cp = data;
1365 while (data_size) {
1366 int bytes = (52 < data_size) ? 52 : data_size;
1367 char line[70];
1368 data_size -= bytes;
1369 if (bytes <= 26)
1370 line[0] = bytes + 'A' - 1;
1371 else
1372 line[0] = bytes - 26 + 'a' - 1;
1373 encode_85(line + 1, cp, bytes);
1374 cp = (char *) cp + bytes;
1375 fputs(line, file);
1376 fputc('\n', file);
1378 fprintf(file, "\n");
1379 free(data);
1382 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1384 fprintf(file, "GIT binary patch\n");
1385 emit_binary_diff_body(file, one, two);
1386 emit_binary_diff_body(file, two, one);
1389 static void diff_filespec_load_driver(struct diff_filespec *one)
1391 if (!one->driver)
1392 one->driver = userdiff_find_by_path(one->path);
1393 if (!one->driver)
1394 one->driver = userdiff_find_by_name("default");
1397 int diff_filespec_is_binary(struct diff_filespec *one)
1399 if (one->is_binary == -1) {
1400 diff_filespec_load_driver(one);
1401 if (one->driver->binary != -1)
1402 one->is_binary = one->driver->binary;
1403 else {
1404 if (!one->data && DIFF_FILE_VALID(one))
1405 diff_populate_filespec(one, 0);
1406 if (one->data)
1407 one->is_binary = buffer_is_binary(one->data,
1408 one->size);
1409 if (one->is_binary == -1)
1410 one->is_binary = 0;
1413 return one->is_binary;
1416 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1418 diff_filespec_load_driver(one);
1419 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1422 static const char *userdiff_word_regex(struct diff_filespec *one)
1424 diff_filespec_load_driver(one);
1425 return one->driver->word_regex;
1428 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1430 if (!options->a_prefix)
1431 options->a_prefix = a;
1432 if (!options->b_prefix)
1433 options->b_prefix = b;
1436 static const char *get_textconv(struct diff_filespec *one)
1438 if (!DIFF_FILE_VALID(one))
1439 return NULL;
1440 if (!S_ISREG(one->mode))
1441 return NULL;
1442 diff_filespec_load_driver(one);
1443 return one->driver->textconv;
1446 static void builtin_diff(const char *name_a,
1447 const char *name_b,
1448 struct diff_filespec *one,
1449 struct diff_filespec *two,
1450 const char *xfrm_msg,
1451 struct diff_options *o,
1452 int complete_rewrite)
1454 mmfile_t mf1, mf2;
1455 const char *lbl[2];
1456 char *a_one, *b_two;
1457 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1458 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1459 const char *a_prefix, *b_prefix;
1460 const char *textconv_one = NULL, *textconv_two = NULL;
1462 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1463 textconv_one = get_textconv(one);
1464 textconv_two = get_textconv(two);
1467 diff_set_mnemonic_prefix(o, "a/", "b/");
1468 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1469 a_prefix = o->b_prefix;
1470 b_prefix = o->a_prefix;
1471 } else {
1472 a_prefix = o->a_prefix;
1473 b_prefix = o->b_prefix;
1476 /* Never use a non-valid filename anywhere if at all possible */
1477 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1478 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1480 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1481 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1482 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1483 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1484 fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1485 if (lbl[0][0] == '/') {
1486 /* /dev/null */
1487 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1488 if (xfrm_msg && xfrm_msg[0])
1489 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1491 else if (lbl[1][0] == '/') {
1492 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1493 if (xfrm_msg && xfrm_msg[0])
1494 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1496 else {
1497 if (one->mode != two->mode) {
1498 fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1499 fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1501 if (xfrm_msg && xfrm_msg[0])
1502 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1504 * we do not run diff between different kind
1505 * of objects.
1507 if ((one->mode ^ two->mode) & S_IFMT)
1508 goto free_ab_and_return;
1509 if (complete_rewrite &&
1510 (textconv_one || !diff_filespec_is_binary(one)) &&
1511 (textconv_two || !diff_filespec_is_binary(two))) {
1512 emit_rewrite_diff(name_a, name_b, one, two,
1513 textconv_one, textconv_two, o);
1514 o->found_changes = 1;
1515 goto free_ab_and_return;
1519 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1520 die("unable to read files to diff");
1522 if (!DIFF_OPT_TST(o, TEXT) &&
1523 ( (diff_filespec_is_binary(one) && !textconv_one) ||
1524 (diff_filespec_is_binary(two) && !textconv_two) )) {
1525 /* Quite common confusing case */
1526 if (mf1.size == mf2.size &&
1527 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1528 goto free_ab_and_return;
1529 if (DIFF_OPT_TST(o, BINARY))
1530 emit_binary_diff(o->file, &mf1, &mf2);
1531 else
1532 fprintf(o->file, "Binary files %s and %s differ\n",
1533 lbl[0], lbl[1]);
1534 o->found_changes = 1;
1536 else {
1537 /* Crazy xdl interfaces.. */
1538 const char *diffopts = getenv("GIT_DIFF_OPTS");
1539 xpparam_t xpp;
1540 xdemitconf_t xecfg;
1541 xdemitcb_t ecb;
1542 struct emit_callback ecbdata;
1543 const struct userdiff_funcname *pe;
1545 if (textconv_one) {
1546 size_t size;
1547 mf1.ptr = run_textconv(textconv_one, one, &size);
1548 if (!mf1.ptr)
1549 die("unable to read files to diff");
1550 mf1.size = size;
1552 if (textconv_two) {
1553 size_t size;
1554 mf2.ptr = run_textconv(textconv_two, two, &size);
1555 if (!mf2.ptr)
1556 die("unable to read files to diff");
1557 mf2.size = size;
1560 pe = diff_funcname_pattern(one);
1561 if (!pe)
1562 pe = diff_funcname_pattern(two);
1564 memset(&xpp, 0, sizeof(xpp));
1565 memset(&xecfg, 0, sizeof(xecfg));
1566 memset(&ecbdata, 0, sizeof(ecbdata));
1567 ecbdata.label_path = lbl;
1568 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1569 ecbdata.found_changesp = &o->found_changes;
1570 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1571 ecbdata.file = o->file;
1572 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1573 xecfg.ctxlen = o->context;
1574 xecfg.interhunkctxlen = o->interhunkcontext;
1575 xecfg.flags = XDL_EMIT_FUNCNAMES;
1576 if (pe)
1577 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1578 if (!diffopts)
1580 else if (!prefixcmp(diffopts, "--unified="))
1581 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1582 else if (!prefixcmp(diffopts, "-u"))
1583 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1584 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1585 ecbdata.diff_words =
1586 xcalloc(1, sizeof(struct diff_words_data));
1587 ecbdata.diff_words->file = o->file;
1588 if (!o->word_regex)
1589 o->word_regex = userdiff_word_regex(one);
1590 if (!o->word_regex)
1591 o->word_regex = userdiff_word_regex(two);
1592 if (!o->word_regex)
1593 o->word_regex = diff_word_regex_cfg;
1594 if (o->word_regex) {
1595 ecbdata.diff_words->word_regex = (regex_t *)
1596 xmalloc(sizeof(regex_t));
1597 if (regcomp(ecbdata.diff_words->word_regex,
1598 o->word_regex,
1599 REG_EXTENDED | REG_NEWLINE))
1600 die ("Invalid regular expression: %s",
1601 o->word_regex);
1604 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1605 &xpp, &xecfg, &ecb);
1606 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1607 free_diff_words_data(&ecbdata);
1608 if (textconv_one)
1609 free(mf1.ptr);
1610 if (textconv_two)
1611 free(mf2.ptr);
1612 xdiff_clear_find_func(&xecfg);
1615 free_ab_and_return:
1616 diff_free_filespec_data(one);
1617 diff_free_filespec_data(two);
1618 free(a_one);
1619 free(b_two);
1620 return;
1623 static void builtin_diffstat(const char *name_a, const char *name_b,
1624 struct diff_filespec *one,
1625 struct diff_filespec *two,
1626 struct diffstat_t *diffstat,
1627 struct diff_options *o,
1628 int complete_rewrite)
1630 mmfile_t mf1, mf2;
1631 struct diffstat_file *data;
1633 data = diffstat_add(diffstat, name_a, name_b);
1635 if (!one || !two) {
1636 data->is_unmerged = 1;
1637 return;
1639 if (complete_rewrite) {
1640 diff_populate_filespec(one, 0);
1641 diff_populate_filespec(two, 0);
1642 data->deleted = count_lines(one->data, one->size);
1643 data->added = count_lines(two->data, two->size);
1644 goto free_and_return;
1646 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1647 die("unable to read files to diff");
1649 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1650 data->is_binary = 1;
1651 data->added = mf2.size;
1652 data->deleted = mf1.size;
1653 } else {
1654 /* Crazy xdl interfaces.. */
1655 xpparam_t xpp;
1656 xdemitconf_t xecfg;
1657 xdemitcb_t ecb;
1659 memset(&xpp, 0, sizeof(xpp));
1660 memset(&xecfg, 0, sizeof(xecfg));
1661 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1662 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1663 &xpp, &xecfg, &ecb);
1666 free_and_return:
1667 diff_free_filespec_data(one);
1668 diff_free_filespec_data(two);
1671 static void builtin_checkdiff(const char *name_a, const char *name_b,
1672 const char *attr_path,
1673 struct diff_filespec *one,
1674 struct diff_filespec *two,
1675 struct diff_options *o)
1677 mmfile_t mf1, mf2;
1678 struct checkdiff_t data;
1680 if (!two)
1681 return;
1683 memset(&data, 0, sizeof(data));
1684 data.filename = name_b ? name_b : name_a;
1685 data.lineno = 0;
1686 data.o = o;
1687 data.ws_rule = whitespace_rule(attr_path);
1689 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1690 die("unable to read files to diff");
1693 * All the other codepaths check both sides, but not checking
1694 * the "old" side here is deliberate. We are checking the newly
1695 * introduced changes, and as long as the "new" side is text, we
1696 * can and should check what it introduces.
1698 if (diff_filespec_is_binary(two))
1699 goto free_and_return;
1700 else {
1701 /* Crazy xdl interfaces.. */
1702 xpparam_t xpp;
1703 xdemitconf_t xecfg;
1704 xdemitcb_t ecb;
1706 memset(&xpp, 0, sizeof(xpp));
1707 memset(&xecfg, 0, sizeof(xecfg));
1708 xecfg.ctxlen = 1; /* at least one context line */
1709 xpp.flags = XDF_NEED_MINIMAL;
1710 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1711 &xpp, &xecfg, &ecb);
1713 if ((data.ws_rule & WS_TRAILING_SPACE) &&
1714 data.trailing_blanks_start) {
1715 fprintf(o->file, "%s:%d: ends with blank lines.\n",
1716 data.filename, data.trailing_blanks_start);
1717 data.status = 1; /* report errors */
1720 free_and_return:
1721 diff_free_filespec_data(one);
1722 diff_free_filespec_data(two);
1723 if (data.status)
1724 DIFF_OPT_SET(o, CHECK_FAILED);
1727 struct diff_filespec *alloc_filespec(const char *path)
1729 int namelen = strlen(path);
1730 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1732 memset(spec, 0, sizeof(*spec));
1733 spec->path = (char *)(spec + 1);
1734 memcpy(spec->path, path, namelen+1);
1735 spec->count = 1;
1736 spec->is_binary = -1;
1737 return spec;
1740 void free_filespec(struct diff_filespec *spec)
1742 if (!--spec->count) {
1743 diff_free_filespec_data(spec);
1744 free(spec);
1748 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1749 unsigned short mode)
1751 if (mode) {
1752 spec->mode = canon_mode(mode);
1753 hashcpy(spec->sha1, sha1);
1754 spec->sha1_valid = !is_null_sha1(sha1);
1759 * Given a name and sha1 pair, if the index tells us the file in
1760 * the work tree has that object contents, return true, so that
1761 * prepare_temp_file() does not have to inflate and extract.
1763 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1765 struct cache_entry *ce;
1766 struct stat st;
1767 int pos, len;
1770 * We do not read the cache ourselves here, because the
1771 * benchmark with my previous version that always reads cache
1772 * shows that it makes things worse for diff-tree comparing
1773 * two linux-2.6 kernel trees in an already checked out work
1774 * tree. This is because most diff-tree comparisons deal with
1775 * only a small number of files, while reading the cache is
1776 * expensive for a large project, and its cost outweighs the
1777 * savings we get by not inflating the object to a temporary
1778 * file. Practically, this code only helps when we are used
1779 * by diff-cache --cached, which does read the cache before
1780 * calling us.
1782 if (!active_cache)
1783 return 0;
1785 /* We want to avoid the working directory if our caller
1786 * doesn't need the data in a normal file, this system
1787 * is rather slow with its stat/open/mmap/close syscalls,
1788 * and the object is contained in a pack file. The pack
1789 * is probably already open and will be faster to obtain
1790 * the data through than the working directory. Loose
1791 * objects however would tend to be slower as they need
1792 * to be individually opened and inflated.
1794 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1795 return 0;
1797 len = strlen(name);
1798 pos = cache_name_pos(name, len);
1799 if (pos < 0)
1800 return 0;
1801 ce = active_cache[pos];
1804 * This is not the sha1 we are looking for, or
1805 * unreusable because it is not a regular file.
1807 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1808 return 0;
1811 * If ce is marked as "assume unchanged", there is no
1812 * guarantee that work tree matches what we are looking for.
1814 if (ce->ce_flags & CE_VALID)
1815 return 0;
1818 * If ce matches the file in the work tree, we can reuse it.
1820 if (ce_uptodate(ce) ||
1821 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1822 return 1;
1824 return 0;
1827 static int populate_from_stdin(struct diff_filespec *s)
1829 struct strbuf buf = STRBUF_INIT;
1830 size_t size = 0;
1832 if (strbuf_read(&buf, 0, 0) < 0)
1833 return error("error while reading from stdin %s",
1834 strerror(errno));
1836 s->should_munmap = 0;
1837 s->data = strbuf_detach(&buf, &size);
1838 s->size = size;
1839 s->should_free = 1;
1840 return 0;
1843 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1845 int len;
1846 char *data = xmalloc(100);
1847 len = snprintf(data, 100,
1848 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1849 s->data = data;
1850 s->size = len;
1851 s->should_free = 1;
1852 if (size_only) {
1853 s->data = NULL;
1854 free(data);
1856 return 0;
1860 * While doing rename detection and pickaxe operation, we may need to
1861 * grab the data for the blob (or file) for our own in-core comparison.
1862 * diff_filespec has data and size fields for this purpose.
1864 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1866 int err = 0;
1867 if (!DIFF_FILE_VALID(s))
1868 die("internal error: asking to populate invalid file.");
1869 if (S_ISDIR(s->mode))
1870 return -1;
1872 if (s->data)
1873 return 0;
1875 if (size_only && 0 < s->size)
1876 return 0;
1878 if (S_ISGITLINK(s->mode))
1879 return diff_populate_gitlink(s, size_only);
1881 if (!s->sha1_valid ||
1882 reuse_worktree_file(s->path, s->sha1, 0)) {
1883 struct strbuf buf = STRBUF_INIT;
1884 struct stat st;
1885 int fd;
1887 if (!strcmp(s->path, "-"))
1888 return populate_from_stdin(s);
1890 if (lstat(s->path, &st) < 0) {
1891 if (errno == ENOENT) {
1892 err_empty:
1893 err = -1;
1894 empty:
1895 s->data = (char *)"";
1896 s->size = 0;
1897 return err;
1900 s->size = xsize_t(st.st_size);
1901 if (!s->size)
1902 goto empty;
1903 if (S_ISLNK(st.st_mode)) {
1904 struct strbuf sb = STRBUF_INIT;
1906 if (strbuf_readlink(&sb, s->path, s->size))
1907 goto err_empty;
1908 s->size = sb.len;
1909 s->data = strbuf_detach(&sb, NULL);
1910 s->should_free = 1;
1911 return 0;
1913 if (size_only)
1914 return 0;
1915 fd = open(s->path, O_RDONLY);
1916 if (fd < 0)
1917 goto err_empty;
1918 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1919 close(fd);
1920 s->should_munmap = 1;
1923 * Convert from working tree format to canonical git format
1925 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
1926 size_t size = 0;
1927 munmap(s->data, s->size);
1928 s->should_munmap = 0;
1929 s->data = strbuf_detach(&buf, &size);
1930 s->size = size;
1931 s->should_free = 1;
1934 else {
1935 enum object_type type;
1936 if (size_only)
1937 type = sha1_object_info(s->sha1, &s->size);
1938 else {
1939 s->data = read_sha1_file(s->sha1, &type, &s->size);
1940 s->should_free = 1;
1943 return 0;
1946 void diff_free_filespec_blob(struct diff_filespec *s)
1948 if (s->should_free)
1949 free(s->data);
1950 else if (s->should_munmap)
1951 munmap(s->data, s->size);
1953 if (s->should_free || s->should_munmap) {
1954 s->should_free = s->should_munmap = 0;
1955 s->data = NULL;
1959 void diff_free_filespec_data(struct diff_filespec *s)
1961 diff_free_filespec_blob(s);
1962 free(s->cnt_data);
1963 s->cnt_data = NULL;
1966 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
1967 void *blob,
1968 unsigned long size,
1969 const unsigned char *sha1,
1970 int mode)
1972 int fd;
1973 struct strbuf buf = STRBUF_INIT;
1974 struct strbuf template = STRBUF_INIT;
1975 char *path_dup = xstrdup(path);
1976 const char *base = basename(path_dup);
1978 /* Generate "XXXXXX_basename.ext" */
1979 strbuf_addstr(&template, "XXXXXX_");
1980 strbuf_addstr(&template, base);
1982 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
1983 strlen(base) + 1);
1984 if (fd < 0)
1985 die_errno("unable to create temp-file");
1986 if (convert_to_working_tree(path,
1987 (const char *)blob, (size_t)size, &buf)) {
1988 blob = buf.buf;
1989 size = buf.len;
1991 if (write_in_full(fd, blob, size) != size)
1992 die_errno("unable to write temp-file");
1993 close(fd);
1994 temp->name = temp->tmp_path;
1995 strcpy(temp->hex, sha1_to_hex(sha1));
1996 temp->hex[40] = 0;
1997 sprintf(temp->mode, "%06o", mode);
1998 strbuf_release(&buf);
1999 strbuf_release(&template);
2000 free(path_dup);
2003 static struct diff_tempfile *prepare_temp_file(const char *name,
2004 struct diff_filespec *one)
2006 struct diff_tempfile *temp = claim_diff_tempfile();
2008 if (!DIFF_FILE_VALID(one)) {
2009 not_a_valid_file:
2010 /* A '-' entry produces this for file-2, and
2011 * a '+' entry produces this for file-1.
2013 temp->name = "/dev/null";
2014 strcpy(temp->hex, ".");
2015 strcpy(temp->mode, ".");
2016 return temp;
2019 if (!remove_tempfile_installed) {
2020 atexit(remove_tempfile);
2021 sigchain_push_common(remove_tempfile_on_signal);
2022 remove_tempfile_installed = 1;
2025 if (!one->sha1_valid ||
2026 reuse_worktree_file(name, one->sha1, 1)) {
2027 struct stat st;
2028 if (lstat(name, &st) < 0) {
2029 if (errno == ENOENT)
2030 goto not_a_valid_file;
2031 die_errno("stat(%s)", name);
2033 if (S_ISLNK(st.st_mode)) {
2034 struct strbuf sb = STRBUF_INIT;
2035 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2036 die_errno("readlink(%s)", name);
2037 prep_temp_blob(name, temp, sb.buf, sb.len,
2038 (one->sha1_valid ?
2039 one->sha1 : null_sha1),
2040 (one->sha1_valid ?
2041 one->mode : S_IFLNK));
2042 strbuf_release(&sb);
2044 else {
2045 /* we can borrow from the file in the work tree */
2046 temp->name = name;
2047 if (!one->sha1_valid)
2048 strcpy(temp->hex, sha1_to_hex(null_sha1));
2049 else
2050 strcpy(temp->hex, sha1_to_hex(one->sha1));
2051 /* Even though we may sometimes borrow the
2052 * contents from the work tree, we always want
2053 * one->mode. mode is trustworthy even when
2054 * !(one->sha1_valid), as long as
2055 * DIFF_FILE_VALID(one).
2057 sprintf(temp->mode, "%06o", one->mode);
2059 return temp;
2061 else {
2062 if (diff_populate_filespec(one, 0))
2063 die("cannot read data blob for %s", one->path);
2064 prep_temp_blob(name, temp, one->data, one->size,
2065 one->sha1, one->mode);
2067 return temp;
2070 /* An external diff command takes:
2072 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2073 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2076 static void run_external_diff(const char *pgm,
2077 const char *name,
2078 const char *other,
2079 struct diff_filespec *one,
2080 struct diff_filespec *two,
2081 const char *xfrm_msg,
2082 int complete_rewrite)
2084 const char *spawn_arg[10];
2085 int retval;
2086 const char **arg = &spawn_arg[0];
2088 if (one && two) {
2089 struct diff_tempfile *temp_one, *temp_two;
2090 const char *othername = (other ? other : name);
2091 temp_one = prepare_temp_file(name, one);
2092 temp_two = prepare_temp_file(othername, two);
2093 *arg++ = pgm;
2094 *arg++ = name;
2095 *arg++ = temp_one->name;
2096 *arg++ = temp_one->hex;
2097 *arg++ = temp_one->mode;
2098 *arg++ = temp_two->name;
2099 *arg++ = temp_two->hex;
2100 *arg++ = temp_two->mode;
2101 if (other) {
2102 *arg++ = other;
2103 *arg++ = xfrm_msg;
2105 } else {
2106 *arg++ = pgm;
2107 *arg++ = name;
2109 *arg = NULL;
2110 fflush(NULL);
2111 retval = run_command_v_opt(spawn_arg, 0);
2112 remove_tempfile();
2113 if (retval) {
2114 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2115 exit(1);
2119 static int similarity_index(struct diff_filepair *p)
2121 return p->score * 100 / MAX_SCORE;
2124 static void fill_metainfo(struct strbuf *msg,
2125 const char *name,
2126 const char *other,
2127 struct diff_filespec *one,
2128 struct diff_filespec *two,
2129 struct diff_options *o,
2130 struct diff_filepair *p)
2132 strbuf_init(msg, PATH_MAX * 2 + 300);
2133 switch (p->status) {
2134 case DIFF_STATUS_COPIED:
2135 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2136 strbuf_addstr(msg, "\ncopy from ");
2137 quote_c_style(name, msg, NULL, 0);
2138 strbuf_addstr(msg, "\ncopy to ");
2139 quote_c_style(other, msg, NULL, 0);
2140 strbuf_addch(msg, '\n');
2141 break;
2142 case DIFF_STATUS_RENAMED:
2143 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2144 strbuf_addstr(msg, "\nrename from ");
2145 quote_c_style(name, msg, NULL, 0);
2146 strbuf_addstr(msg, "\nrename to ");
2147 quote_c_style(other, msg, NULL, 0);
2148 strbuf_addch(msg, '\n');
2149 break;
2150 case DIFF_STATUS_MODIFIED:
2151 if (p->score) {
2152 strbuf_addf(msg, "dissimilarity index %d%%\n",
2153 similarity_index(p));
2154 break;
2156 /* fallthru */
2157 default:
2158 /* nothing */
2161 if (one && two && hashcmp(one->sha1, two->sha1)) {
2162 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2164 if (DIFF_OPT_TST(o, BINARY)) {
2165 mmfile_t mf;
2166 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2167 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2168 abbrev = 40;
2170 strbuf_addf(msg, "index %.*s..%.*s",
2171 abbrev, sha1_to_hex(one->sha1),
2172 abbrev, sha1_to_hex(two->sha1));
2173 if (one->mode == two->mode)
2174 strbuf_addf(msg, " %06o", one->mode);
2175 strbuf_addch(msg, '\n');
2177 if (msg->len)
2178 strbuf_setlen(msg, msg->len - 1);
2181 static void run_diff_cmd(const char *pgm,
2182 const char *name,
2183 const char *other,
2184 const char *attr_path,
2185 struct diff_filespec *one,
2186 struct diff_filespec *two,
2187 struct strbuf *msg,
2188 struct diff_options *o,
2189 struct diff_filepair *p)
2191 const char *xfrm_msg = NULL;
2192 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2194 if (msg) {
2195 fill_metainfo(msg, name, other, one, two, o, p);
2196 xfrm_msg = msg->len ? msg->buf : NULL;
2199 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2200 pgm = NULL;
2201 else {
2202 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2203 if (drv && drv->external)
2204 pgm = drv->external;
2207 if (pgm) {
2208 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2209 complete_rewrite);
2210 return;
2212 if (one && two)
2213 builtin_diff(name, other ? other : name,
2214 one, two, xfrm_msg, o, complete_rewrite);
2215 else
2216 fprintf(o->file, "* Unmerged path %s\n", name);
2219 static void diff_fill_sha1_info(struct diff_filespec *one)
2221 if (DIFF_FILE_VALID(one)) {
2222 if (!one->sha1_valid) {
2223 struct stat st;
2224 if (!strcmp(one->path, "-")) {
2225 hashcpy(one->sha1, null_sha1);
2226 return;
2228 if (lstat(one->path, &st) < 0)
2229 die_errno("stat '%s'", one->path);
2230 if (index_path(one->sha1, one->path, &st, 0))
2231 die("cannot hash %s", one->path);
2234 else
2235 hashclr(one->sha1);
2238 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2240 /* Strip the prefix but do not molest /dev/null and absolute paths */
2241 if (*namep && **namep != '/')
2242 *namep += prefix_length;
2243 if (*otherp && **otherp != '/')
2244 *otherp += prefix_length;
2247 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2249 const char *pgm = external_diff();
2250 struct strbuf msg;
2251 struct diff_filespec *one = p->one;
2252 struct diff_filespec *two = p->two;
2253 const char *name;
2254 const char *other;
2255 const char *attr_path;
2257 name = p->one->path;
2258 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2259 attr_path = name;
2260 if (o->prefix_length)
2261 strip_prefix(o->prefix_length, &name, &other);
2263 if (DIFF_PAIR_UNMERGED(p)) {
2264 run_diff_cmd(pgm, name, NULL, attr_path,
2265 NULL, NULL, NULL, o, p);
2266 return;
2269 diff_fill_sha1_info(one);
2270 diff_fill_sha1_info(two);
2272 if (!pgm &&
2273 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2274 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2276 * a filepair that changes between file and symlink
2277 * needs to be split into deletion and creation.
2279 struct diff_filespec *null = alloc_filespec(two->path);
2280 run_diff_cmd(NULL, name, other, attr_path,
2281 one, null, &msg, o, p);
2282 free(null);
2283 strbuf_release(&msg);
2285 null = alloc_filespec(one->path);
2286 run_diff_cmd(NULL, name, other, attr_path,
2287 null, two, &msg, o, p);
2288 free(null);
2290 else
2291 run_diff_cmd(pgm, name, other, attr_path,
2292 one, two, &msg, o, p);
2294 strbuf_release(&msg);
2297 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2298 struct diffstat_t *diffstat)
2300 const char *name;
2301 const char *other;
2302 int complete_rewrite = 0;
2304 if (DIFF_PAIR_UNMERGED(p)) {
2305 /* unmerged */
2306 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2307 return;
2310 name = p->one->path;
2311 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2313 if (o->prefix_length)
2314 strip_prefix(o->prefix_length, &name, &other);
2316 diff_fill_sha1_info(p->one);
2317 diff_fill_sha1_info(p->two);
2319 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2320 complete_rewrite = 1;
2321 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2324 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2326 const char *name;
2327 const char *other;
2328 const char *attr_path;
2330 if (DIFF_PAIR_UNMERGED(p)) {
2331 /* unmerged */
2332 return;
2335 name = p->one->path;
2336 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2337 attr_path = other ? other : name;
2339 if (o->prefix_length)
2340 strip_prefix(o->prefix_length, &name, &other);
2342 diff_fill_sha1_info(p->one);
2343 diff_fill_sha1_info(p->two);
2345 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2348 void diff_setup(struct diff_options *options)
2350 memset(options, 0, sizeof(*options));
2352 options->file = stdout;
2354 options->line_termination = '\n';
2355 options->break_opt = -1;
2356 options->rename_limit = -1;
2357 options->dirstat_percent = 3;
2358 options->context = 3;
2360 options->change = diff_change;
2361 options->add_remove = diff_addremove;
2362 if (diff_use_color_default > 0)
2363 DIFF_OPT_SET(options, COLOR_DIFF);
2364 options->detect_rename = diff_detect_rename_default;
2366 if (!diff_mnemonic_prefix) {
2367 options->a_prefix = "a/";
2368 options->b_prefix = "b/";
2372 int diff_setup_done(struct diff_options *options)
2374 int count = 0;
2376 if (options->output_format & DIFF_FORMAT_NAME)
2377 count++;
2378 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2379 count++;
2380 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2381 count++;
2382 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2383 count++;
2384 if (count > 1)
2385 die("--name-only, --name-status, --check and -s are mutually exclusive");
2387 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2388 options->detect_rename = DIFF_DETECT_COPY;
2390 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2391 options->prefix = NULL;
2392 if (options->prefix)
2393 options->prefix_length = strlen(options->prefix);
2394 else
2395 options->prefix_length = 0;
2397 if (options->output_format & (DIFF_FORMAT_NAME |
2398 DIFF_FORMAT_NAME_STATUS |
2399 DIFF_FORMAT_CHECKDIFF |
2400 DIFF_FORMAT_NO_OUTPUT))
2401 options->output_format &= ~(DIFF_FORMAT_RAW |
2402 DIFF_FORMAT_NUMSTAT |
2403 DIFF_FORMAT_DIFFSTAT |
2404 DIFF_FORMAT_SHORTSTAT |
2405 DIFF_FORMAT_DIRSTAT |
2406 DIFF_FORMAT_SUMMARY |
2407 DIFF_FORMAT_PATCH);
2410 * These cases always need recursive; we do not drop caller-supplied
2411 * recursive bits for other formats here.
2413 if (options->output_format & (DIFF_FORMAT_PATCH |
2414 DIFF_FORMAT_NUMSTAT |
2415 DIFF_FORMAT_DIFFSTAT |
2416 DIFF_FORMAT_SHORTSTAT |
2417 DIFF_FORMAT_DIRSTAT |
2418 DIFF_FORMAT_SUMMARY |
2419 DIFF_FORMAT_CHECKDIFF))
2420 DIFF_OPT_SET(options, RECURSIVE);
2422 * Also pickaxe would not work very well if you do not say recursive
2424 if (options->pickaxe)
2425 DIFF_OPT_SET(options, RECURSIVE);
2427 if (options->detect_rename && options->rename_limit < 0)
2428 options->rename_limit = diff_rename_limit_default;
2429 if (options->setup & DIFF_SETUP_USE_CACHE) {
2430 if (!active_cache)
2431 /* read-cache does not die even when it fails
2432 * so it is safe for us to do this here. Also
2433 * it does not smudge active_cache or active_nr
2434 * when it fails, so we do not have to worry about
2435 * cleaning it up ourselves either.
2437 read_cache();
2439 if (options->abbrev <= 0 || 40 < options->abbrev)
2440 options->abbrev = 40; /* full */
2443 * It does not make sense to show the first hit we happened
2444 * to have found. It does not make sense not to return with
2445 * exit code in such a case either.
2447 if (DIFF_OPT_TST(options, QUIET)) {
2448 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2449 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2452 return 0;
2455 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2457 char c, *eq;
2458 int len;
2460 if (*arg != '-')
2461 return 0;
2462 c = *++arg;
2463 if (!c)
2464 return 0;
2465 if (c == arg_short) {
2466 c = *++arg;
2467 if (!c)
2468 return 1;
2469 if (val && isdigit(c)) {
2470 char *end;
2471 int n = strtoul(arg, &end, 10);
2472 if (*end)
2473 return 0;
2474 *val = n;
2475 return 1;
2477 return 0;
2479 if (c != '-')
2480 return 0;
2481 arg++;
2482 eq = strchr(arg, '=');
2483 if (eq)
2484 len = eq - arg;
2485 else
2486 len = strlen(arg);
2487 if (!len || strncmp(arg, arg_long, len))
2488 return 0;
2489 if (eq) {
2490 int n;
2491 char *end;
2492 if (!isdigit(*++eq))
2493 return 0;
2494 n = strtoul(eq, &end, 10);
2495 if (*end)
2496 return 0;
2497 *val = n;
2499 return 1;
2502 static int diff_scoreopt_parse(const char *opt);
2504 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2506 const char *arg = av[0];
2508 /* Output format options */
2509 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2510 options->output_format |= DIFF_FORMAT_PATCH;
2511 else if (opt_arg(arg, 'U', "unified", &options->context))
2512 options->output_format |= DIFF_FORMAT_PATCH;
2513 else if (!strcmp(arg, "--raw"))
2514 options->output_format |= DIFF_FORMAT_RAW;
2515 else if (!strcmp(arg, "--patch-with-raw"))
2516 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2517 else if (!strcmp(arg, "--numstat"))
2518 options->output_format |= DIFF_FORMAT_NUMSTAT;
2519 else if (!strcmp(arg, "--shortstat"))
2520 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2521 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2522 options->output_format |= DIFF_FORMAT_DIRSTAT;
2523 else if (!strcmp(arg, "--cumulative")) {
2524 options->output_format |= DIFF_FORMAT_DIRSTAT;
2525 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2526 } else if (opt_arg(arg, 0, "dirstat-by-file",
2527 &options->dirstat_percent)) {
2528 options->output_format |= DIFF_FORMAT_DIRSTAT;
2529 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2531 else if (!strcmp(arg, "--check"))
2532 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2533 else if (!strcmp(arg, "--summary"))
2534 options->output_format |= DIFF_FORMAT_SUMMARY;
2535 else if (!strcmp(arg, "--patch-with-stat"))
2536 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2537 else if (!strcmp(arg, "--name-only"))
2538 options->output_format |= DIFF_FORMAT_NAME;
2539 else if (!strcmp(arg, "--name-status"))
2540 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2541 else if (!strcmp(arg, "-s"))
2542 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2543 else if (!prefixcmp(arg, "--stat")) {
2544 char *end;
2545 int width = options->stat_width;
2546 int name_width = options->stat_name_width;
2547 arg += 6;
2548 end = (char *)arg;
2550 switch (*arg) {
2551 case '-':
2552 if (!prefixcmp(arg, "-width="))
2553 width = strtoul(arg + 7, &end, 10);
2554 else if (!prefixcmp(arg, "-name-width="))
2555 name_width = strtoul(arg + 12, &end, 10);
2556 break;
2557 case '=':
2558 width = strtoul(arg+1, &end, 10);
2559 if (*end == ',')
2560 name_width = strtoul(end+1, &end, 10);
2563 /* Important! This checks all the error cases! */
2564 if (*end)
2565 return 0;
2566 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2567 options->stat_name_width = name_width;
2568 options->stat_width = width;
2571 /* renames options */
2572 else if (!prefixcmp(arg, "-B")) {
2573 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2574 return -1;
2576 else if (!prefixcmp(arg, "-M")) {
2577 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2578 return -1;
2579 options->detect_rename = DIFF_DETECT_RENAME;
2581 else if (!prefixcmp(arg, "-C")) {
2582 if (options->detect_rename == DIFF_DETECT_COPY)
2583 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2584 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2585 return -1;
2586 options->detect_rename = DIFF_DETECT_COPY;
2588 else if (!strcmp(arg, "--no-renames"))
2589 options->detect_rename = 0;
2590 else if (!strcmp(arg, "--relative"))
2591 DIFF_OPT_SET(options, RELATIVE_NAME);
2592 else if (!prefixcmp(arg, "--relative=")) {
2593 DIFF_OPT_SET(options, RELATIVE_NAME);
2594 options->prefix = arg + 11;
2597 /* xdiff options */
2598 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2599 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2600 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2601 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2602 else if (!strcmp(arg, "--ignore-space-at-eol"))
2603 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2604 else if (!strcmp(arg, "--patience"))
2605 DIFF_XDL_SET(options, PATIENCE_DIFF);
2607 /* flags options */
2608 else if (!strcmp(arg, "--binary")) {
2609 options->output_format |= DIFF_FORMAT_PATCH;
2610 DIFF_OPT_SET(options, BINARY);
2612 else if (!strcmp(arg, "--full-index"))
2613 DIFF_OPT_SET(options, FULL_INDEX);
2614 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2615 DIFF_OPT_SET(options, TEXT);
2616 else if (!strcmp(arg, "-R"))
2617 DIFF_OPT_SET(options, REVERSE_DIFF);
2618 else if (!strcmp(arg, "--find-copies-harder"))
2619 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2620 else if (!strcmp(arg, "--follow"))
2621 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2622 else if (!strcmp(arg, "--color"))
2623 DIFF_OPT_SET(options, COLOR_DIFF);
2624 else if (!strcmp(arg, "--no-color"))
2625 DIFF_OPT_CLR(options, COLOR_DIFF);
2626 else if (!strcmp(arg, "--color-words")) {
2627 DIFF_OPT_SET(options, COLOR_DIFF);
2628 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2630 else if (!prefixcmp(arg, "--color-words=")) {
2631 DIFF_OPT_SET(options, COLOR_DIFF);
2632 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2633 options->word_regex = arg + 14;
2635 else if (!strcmp(arg, "--exit-code"))
2636 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2637 else if (!strcmp(arg, "--quiet"))
2638 DIFF_OPT_SET(options, QUIET);
2639 else if (!strcmp(arg, "--ext-diff"))
2640 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2641 else if (!strcmp(arg, "--no-ext-diff"))
2642 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2643 else if (!strcmp(arg, "--textconv"))
2644 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2645 else if (!strcmp(arg, "--no-textconv"))
2646 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2647 else if (!strcmp(arg, "--ignore-submodules"))
2648 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2650 /* misc options */
2651 else if (!strcmp(arg, "-z"))
2652 options->line_termination = 0;
2653 else if (!prefixcmp(arg, "-l"))
2654 options->rename_limit = strtoul(arg+2, NULL, 10);
2655 else if (!prefixcmp(arg, "-S"))
2656 options->pickaxe = arg + 2;
2657 else if (!strcmp(arg, "--pickaxe-all"))
2658 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2659 else if (!strcmp(arg, "--pickaxe-regex"))
2660 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2661 else if (!prefixcmp(arg, "-O"))
2662 options->orderfile = arg + 2;
2663 else if (!prefixcmp(arg, "--diff-filter="))
2664 options->filter = arg + 14;
2665 else if (!strcmp(arg, "--abbrev"))
2666 options->abbrev = DEFAULT_ABBREV;
2667 else if (!prefixcmp(arg, "--abbrev=")) {
2668 options->abbrev = strtoul(arg + 9, NULL, 10);
2669 if (options->abbrev < MINIMUM_ABBREV)
2670 options->abbrev = MINIMUM_ABBREV;
2671 else if (40 < options->abbrev)
2672 options->abbrev = 40;
2674 else if (!prefixcmp(arg, "--src-prefix="))
2675 options->a_prefix = arg + 13;
2676 else if (!prefixcmp(arg, "--dst-prefix="))
2677 options->b_prefix = arg + 13;
2678 else if (!strcmp(arg, "--no-prefix"))
2679 options->a_prefix = options->b_prefix = "";
2680 else if (opt_arg(arg, '\0', "inter-hunk-context",
2681 &options->interhunkcontext))
2683 else if (!prefixcmp(arg, "--output=")) {
2684 options->file = fopen(arg + strlen("--output="), "w");
2685 options->close_file = 1;
2686 } else
2687 return 0;
2688 return 1;
2691 static int parse_num(const char **cp_p)
2693 unsigned long num, scale;
2694 int ch, dot;
2695 const char *cp = *cp_p;
2697 num = 0;
2698 scale = 1;
2699 dot = 0;
2700 for (;;) {
2701 ch = *cp;
2702 if ( !dot && ch == '.' ) {
2703 scale = 1;
2704 dot = 1;
2705 } else if ( ch == '%' ) {
2706 scale = dot ? scale*100 : 100;
2707 cp++; /* % is always at the end */
2708 break;
2709 } else if ( ch >= '0' && ch <= '9' ) {
2710 if ( scale < 100000 ) {
2711 scale *= 10;
2712 num = (num*10) + (ch-'0');
2714 } else {
2715 break;
2717 cp++;
2719 *cp_p = cp;
2721 /* user says num divided by scale and we say internally that
2722 * is MAX_SCORE * num / scale.
2724 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2727 static int diff_scoreopt_parse(const char *opt)
2729 int opt1, opt2, cmd;
2731 if (*opt++ != '-')
2732 return -1;
2733 cmd = *opt++;
2734 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2735 return -1; /* that is not a -M, -C nor -B option */
2737 opt1 = parse_num(&opt);
2738 if (cmd != 'B')
2739 opt2 = 0;
2740 else {
2741 if (*opt == 0)
2742 opt2 = 0;
2743 else if (*opt != '/')
2744 return -1; /* we expect -B80/99 or -B80 */
2745 else {
2746 opt++;
2747 opt2 = parse_num(&opt);
2750 if (*opt != 0)
2751 return -1;
2752 return opt1 | (opt2 << 16);
2755 struct diff_queue_struct diff_queued_diff;
2757 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2759 if (queue->alloc <= queue->nr) {
2760 queue->alloc = alloc_nr(queue->alloc);
2761 queue->queue = xrealloc(queue->queue,
2762 sizeof(dp) * queue->alloc);
2764 queue->queue[queue->nr++] = dp;
2767 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2768 struct diff_filespec *one,
2769 struct diff_filespec *two)
2771 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2772 dp->one = one;
2773 dp->two = two;
2774 if (queue)
2775 diff_q(queue, dp);
2776 return dp;
2779 void diff_free_filepair(struct diff_filepair *p)
2781 free_filespec(p->one);
2782 free_filespec(p->two);
2783 free(p);
2786 /* This is different from find_unique_abbrev() in that
2787 * it stuffs the result with dots for alignment.
2789 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2791 int abblen;
2792 const char *abbrev;
2793 if (len == 40)
2794 return sha1_to_hex(sha1);
2796 abbrev = find_unique_abbrev(sha1, len);
2797 abblen = strlen(abbrev);
2798 if (abblen < 37) {
2799 static char hex[41];
2800 if (len < abblen && abblen <= len + 2)
2801 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2802 else
2803 sprintf(hex, "%s...", abbrev);
2804 return hex;
2806 return sha1_to_hex(sha1);
2809 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2811 int line_termination = opt->line_termination;
2812 int inter_name_termination = line_termination ? '\t' : '\0';
2814 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2815 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2816 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2817 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2819 if (p->score) {
2820 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2821 inter_name_termination);
2822 } else {
2823 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2826 if (p->status == DIFF_STATUS_COPIED ||
2827 p->status == DIFF_STATUS_RENAMED) {
2828 const char *name_a, *name_b;
2829 name_a = p->one->path;
2830 name_b = p->two->path;
2831 strip_prefix(opt->prefix_length, &name_a, &name_b);
2832 write_name_quoted(name_a, opt->file, inter_name_termination);
2833 write_name_quoted(name_b, opt->file, line_termination);
2834 } else {
2835 const char *name_a, *name_b;
2836 name_a = p->one->mode ? p->one->path : p->two->path;
2837 name_b = NULL;
2838 strip_prefix(opt->prefix_length, &name_a, &name_b);
2839 write_name_quoted(name_a, opt->file, line_termination);
2843 int diff_unmodified_pair(struct diff_filepair *p)
2845 /* This function is written stricter than necessary to support
2846 * the currently implemented transformers, but the idea is to
2847 * let transformers to produce diff_filepairs any way they want,
2848 * and filter and clean them up here before producing the output.
2850 struct diff_filespec *one = p->one, *two = p->two;
2852 if (DIFF_PAIR_UNMERGED(p))
2853 return 0; /* unmerged is interesting */
2855 /* deletion, addition, mode or type change
2856 * and rename are all interesting.
2858 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2859 DIFF_PAIR_MODE_CHANGED(p) ||
2860 strcmp(one->path, two->path))
2861 return 0;
2863 /* both are valid and point at the same path. that is, we are
2864 * dealing with a change.
2866 if (one->sha1_valid && two->sha1_valid &&
2867 !hashcmp(one->sha1, two->sha1))
2868 return 1; /* no change */
2869 if (!one->sha1_valid && !two->sha1_valid)
2870 return 1; /* both look at the same file on the filesystem. */
2871 return 0;
2874 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2876 if (diff_unmodified_pair(p))
2877 return;
2879 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2880 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2881 return; /* no tree diffs in patch format */
2883 run_diff(p, o);
2886 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2887 struct diffstat_t *diffstat)
2889 if (diff_unmodified_pair(p))
2890 return;
2892 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2893 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2894 return; /* no tree diffs in patch format */
2896 run_diffstat(p, o, diffstat);
2899 static void diff_flush_checkdiff(struct diff_filepair *p,
2900 struct diff_options *o)
2902 if (diff_unmodified_pair(p))
2903 return;
2905 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2906 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2907 return; /* no tree diffs in patch format */
2909 run_checkdiff(p, o);
2912 int diff_queue_is_empty(void)
2914 struct diff_queue_struct *q = &diff_queued_diff;
2915 int i;
2916 for (i = 0; i < q->nr; i++)
2917 if (!diff_unmodified_pair(q->queue[i]))
2918 return 0;
2919 return 1;
2922 #if DIFF_DEBUG
2923 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2925 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2926 x, one ? one : "",
2927 s->path,
2928 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2929 s->mode,
2930 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2931 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2932 x, one ? one : "",
2933 s->size, s->xfrm_flags);
2936 void diff_debug_filepair(const struct diff_filepair *p, int i)
2938 diff_debug_filespec(p->one, i, "one");
2939 diff_debug_filespec(p->two, i, "two");
2940 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2941 p->score, p->status ? p->status : '?',
2942 p->one->rename_used, p->broken_pair);
2945 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2947 int i;
2948 if (msg)
2949 fprintf(stderr, "%s\n", msg);
2950 fprintf(stderr, "q->nr = %d\n", q->nr);
2951 for (i = 0; i < q->nr; i++) {
2952 struct diff_filepair *p = q->queue[i];
2953 diff_debug_filepair(p, i);
2956 #endif
2958 static void diff_resolve_rename_copy(void)
2960 int i;
2961 struct diff_filepair *p;
2962 struct diff_queue_struct *q = &diff_queued_diff;
2964 diff_debug_queue("resolve-rename-copy", q);
2966 for (i = 0; i < q->nr; i++) {
2967 p = q->queue[i];
2968 p->status = 0; /* undecided */
2969 if (DIFF_PAIR_UNMERGED(p))
2970 p->status = DIFF_STATUS_UNMERGED;
2971 else if (!DIFF_FILE_VALID(p->one))
2972 p->status = DIFF_STATUS_ADDED;
2973 else if (!DIFF_FILE_VALID(p->two))
2974 p->status = DIFF_STATUS_DELETED;
2975 else if (DIFF_PAIR_TYPE_CHANGED(p))
2976 p->status = DIFF_STATUS_TYPE_CHANGED;
2978 /* from this point on, we are dealing with a pair
2979 * whose both sides are valid and of the same type, i.e.
2980 * either in-place edit or rename/copy edit.
2982 else if (DIFF_PAIR_RENAME(p)) {
2984 * A rename might have re-connected a broken
2985 * pair up, causing the pathnames to be the
2986 * same again. If so, that's not a rename at
2987 * all, just a modification..
2989 * Otherwise, see if this source was used for
2990 * multiple renames, in which case we decrement
2991 * the count, and call it a copy.
2993 if (!strcmp(p->one->path, p->two->path))
2994 p->status = DIFF_STATUS_MODIFIED;
2995 else if (--p->one->rename_used > 0)
2996 p->status = DIFF_STATUS_COPIED;
2997 else
2998 p->status = DIFF_STATUS_RENAMED;
3000 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3001 p->one->mode != p->two->mode ||
3002 is_null_sha1(p->one->sha1))
3003 p->status = DIFF_STATUS_MODIFIED;
3004 else {
3005 /* This is a "no-change" entry and should not
3006 * happen anymore, but prepare for broken callers.
3008 error("feeding unmodified %s to diffcore",
3009 p->one->path);
3010 p->status = DIFF_STATUS_UNKNOWN;
3013 diff_debug_queue("resolve-rename-copy done", q);
3016 static int check_pair_status(struct diff_filepair *p)
3018 switch (p->status) {
3019 case DIFF_STATUS_UNKNOWN:
3020 return 0;
3021 case 0:
3022 die("internal error in diff-resolve-rename-copy");
3023 default:
3024 return 1;
3028 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3030 int fmt = opt->output_format;
3032 if (fmt & DIFF_FORMAT_CHECKDIFF)
3033 diff_flush_checkdiff(p, opt);
3034 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3035 diff_flush_raw(p, opt);
3036 else if (fmt & DIFF_FORMAT_NAME) {
3037 const char *name_a, *name_b;
3038 name_a = p->two->path;
3039 name_b = NULL;
3040 strip_prefix(opt->prefix_length, &name_a, &name_b);
3041 write_name_quoted(name_a, opt->file, opt->line_termination);
3045 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3047 if (fs->mode)
3048 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3049 else
3050 fprintf(file, " %s ", newdelete);
3051 write_name_quoted(fs->path, file, '\n');
3055 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3057 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3058 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3059 show_name ? ' ' : '\n');
3060 if (show_name) {
3061 write_name_quoted(p->two->path, file, '\n');
3066 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3068 char *names = pprint_rename(p->one->path, p->two->path);
3070 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3071 free(names);
3072 show_mode_change(file, p, 0);
3075 static void diff_summary(FILE *file, struct diff_filepair *p)
3077 switch(p->status) {
3078 case DIFF_STATUS_DELETED:
3079 show_file_mode_name(file, "delete", p->one);
3080 break;
3081 case DIFF_STATUS_ADDED:
3082 show_file_mode_name(file, "create", p->two);
3083 break;
3084 case DIFF_STATUS_COPIED:
3085 show_rename_copy(file, "copy", p);
3086 break;
3087 case DIFF_STATUS_RENAMED:
3088 show_rename_copy(file, "rename", p);
3089 break;
3090 default:
3091 if (p->score) {
3092 fputs(" rewrite ", file);
3093 write_name_quoted(p->two->path, file, ' ');
3094 fprintf(file, "(%d%%)\n", similarity_index(p));
3096 show_mode_change(file, p, !p->score);
3097 break;
3101 struct patch_id_t {
3102 git_SHA_CTX *ctx;
3103 int patchlen;
3106 static int remove_space(char *line, int len)
3108 int i;
3109 char *dst = line;
3110 unsigned char c;
3112 for (i = 0; i < len; i++)
3113 if (!isspace((c = line[i])))
3114 *dst++ = c;
3116 return dst - line;
3119 static void patch_id_consume(void *priv, char *line, unsigned long len)
3121 struct patch_id_t *data = priv;
3122 int new_len;
3124 /* Ignore line numbers when computing the SHA1 of the patch */
3125 if (!prefixcmp(line, "@@ -"))
3126 return;
3128 new_len = remove_space(line, len);
3130 git_SHA1_Update(data->ctx, line, new_len);
3131 data->patchlen += new_len;
3134 /* returns 0 upon success, and writes result into sha1 */
3135 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3137 struct diff_queue_struct *q = &diff_queued_diff;
3138 int i;
3139 git_SHA_CTX ctx;
3140 struct patch_id_t data;
3141 char buffer[PATH_MAX * 4 + 20];
3143 git_SHA1_Init(&ctx);
3144 memset(&data, 0, sizeof(struct patch_id_t));
3145 data.ctx = &ctx;
3147 for (i = 0; i < q->nr; i++) {
3148 xpparam_t xpp;
3149 xdemitconf_t xecfg;
3150 xdemitcb_t ecb;
3151 mmfile_t mf1, mf2;
3152 struct diff_filepair *p = q->queue[i];
3153 int len1, len2;
3155 memset(&xpp, 0, sizeof(xpp));
3156 memset(&xecfg, 0, sizeof(xecfg));
3157 if (p->status == 0)
3158 return error("internal diff status error");
3159 if (p->status == DIFF_STATUS_UNKNOWN)
3160 continue;
3161 if (diff_unmodified_pair(p))
3162 continue;
3163 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3164 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3165 continue;
3166 if (DIFF_PAIR_UNMERGED(p))
3167 continue;
3169 diff_fill_sha1_info(p->one);
3170 diff_fill_sha1_info(p->two);
3171 if (fill_mmfile(&mf1, p->one) < 0 ||
3172 fill_mmfile(&mf2, p->two) < 0)
3173 return error("unable to read files to diff");
3175 len1 = remove_space(p->one->path, strlen(p->one->path));
3176 len2 = remove_space(p->two->path, strlen(p->two->path));
3177 if (p->one->mode == 0)
3178 len1 = snprintf(buffer, sizeof(buffer),
3179 "diff--gita/%.*sb/%.*s"
3180 "newfilemode%06o"
3181 "---/dev/null"
3182 "+++b/%.*s",
3183 len1, p->one->path,
3184 len2, p->two->path,
3185 p->two->mode,
3186 len2, p->two->path);
3187 else if (p->two->mode == 0)
3188 len1 = snprintf(buffer, sizeof(buffer),
3189 "diff--gita/%.*sb/%.*s"
3190 "deletedfilemode%06o"
3191 "---a/%.*s"
3192 "+++/dev/null",
3193 len1, p->one->path,
3194 len2, p->two->path,
3195 p->one->mode,
3196 len1, p->one->path);
3197 else
3198 len1 = snprintf(buffer, sizeof(buffer),
3199 "diff--gita/%.*sb/%.*s"
3200 "---a/%.*s"
3201 "+++b/%.*s",
3202 len1, p->one->path,
3203 len2, p->two->path,
3204 len1, p->one->path,
3205 len2, p->two->path);
3206 git_SHA1_Update(&ctx, buffer, len1);
3208 xpp.flags = XDF_NEED_MINIMAL;
3209 xecfg.ctxlen = 3;
3210 xecfg.flags = XDL_EMIT_FUNCNAMES;
3211 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3212 &xpp, &xecfg, &ecb);
3215 git_SHA1_Final(sha1, &ctx);
3216 return 0;
3219 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3221 struct diff_queue_struct *q = &diff_queued_diff;
3222 int i;
3223 int result = diff_get_patch_id(options, sha1);
3225 for (i = 0; i < q->nr; i++)
3226 diff_free_filepair(q->queue[i]);
3228 free(q->queue);
3229 q->queue = NULL;
3230 q->nr = q->alloc = 0;
3232 return result;
3235 static int is_summary_empty(const struct diff_queue_struct *q)
3237 int i;
3239 for (i = 0; i < q->nr; i++) {
3240 const struct diff_filepair *p = q->queue[i];
3242 switch (p->status) {
3243 case DIFF_STATUS_DELETED:
3244 case DIFF_STATUS_ADDED:
3245 case DIFF_STATUS_COPIED:
3246 case DIFF_STATUS_RENAMED:
3247 return 0;
3248 default:
3249 if (p->score)
3250 return 0;
3251 if (p->one->mode && p->two->mode &&
3252 p->one->mode != p->two->mode)
3253 return 0;
3254 break;
3257 return 1;
3260 void diff_flush(struct diff_options *options)
3262 struct diff_queue_struct *q = &diff_queued_diff;
3263 int i, output_format = options->output_format;
3264 int separator = 0;
3267 * Order: raw, stat, summary, patch
3268 * or: name/name-status/checkdiff (other bits clear)
3270 if (!q->nr)
3271 goto free_queue;
3273 if (output_format & (DIFF_FORMAT_RAW |
3274 DIFF_FORMAT_NAME |
3275 DIFF_FORMAT_NAME_STATUS |
3276 DIFF_FORMAT_CHECKDIFF)) {
3277 for (i = 0; i < q->nr; i++) {
3278 struct diff_filepair *p = q->queue[i];
3279 if (check_pair_status(p))
3280 flush_one_pair(p, options);
3282 separator++;
3285 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3286 struct diffstat_t diffstat;
3288 memset(&diffstat, 0, sizeof(struct diffstat_t));
3289 for (i = 0; i < q->nr; i++) {
3290 struct diff_filepair *p = q->queue[i];
3291 if (check_pair_status(p))
3292 diff_flush_stat(p, options, &diffstat);
3294 if (output_format & DIFF_FORMAT_NUMSTAT)
3295 show_numstat(&diffstat, options);
3296 if (output_format & DIFF_FORMAT_DIFFSTAT)
3297 show_stats(&diffstat, options);
3298 if (output_format & DIFF_FORMAT_SHORTSTAT)
3299 show_shortstats(&diffstat, options);
3300 free_diffstat_info(&diffstat);
3301 separator++;
3303 if (output_format & DIFF_FORMAT_DIRSTAT)
3304 show_dirstat(options);
3306 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3307 for (i = 0; i < q->nr; i++)
3308 diff_summary(options->file, q->queue[i]);
3309 separator++;
3312 if (output_format & DIFF_FORMAT_PATCH) {
3313 if (separator) {
3314 putc(options->line_termination, options->file);
3315 if (options->stat_sep) {
3316 /* attach patch instead of inline */
3317 fputs(options->stat_sep, options->file);
3321 for (i = 0; i < q->nr; i++) {
3322 struct diff_filepair *p = q->queue[i];
3323 if (check_pair_status(p))
3324 diff_flush_patch(p, options);
3328 if (output_format & DIFF_FORMAT_CALLBACK)
3329 options->format_callback(q, options, options->format_callback_data);
3331 for (i = 0; i < q->nr; i++)
3332 diff_free_filepair(q->queue[i]);
3333 free_queue:
3334 free(q->queue);
3335 q->queue = NULL;
3336 q->nr = q->alloc = 0;
3337 if (options->close_file)
3338 fclose(options->file);
3341 static void diffcore_apply_filter(const char *filter)
3343 int i;
3344 struct diff_queue_struct *q = &diff_queued_diff;
3345 struct diff_queue_struct outq;
3346 outq.queue = NULL;
3347 outq.nr = outq.alloc = 0;
3349 if (!filter)
3350 return;
3352 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3353 int found;
3354 for (i = found = 0; !found && i < q->nr; i++) {
3355 struct diff_filepair *p = q->queue[i];
3356 if (((p->status == DIFF_STATUS_MODIFIED) &&
3357 ((p->score &&
3358 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3359 (!p->score &&
3360 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3361 ((p->status != DIFF_STATUS_MODIFIED) &&
3362 strchr(filter, p->status)))
3363 found++;
3365 if (found)
3366 return;
3368 /* otherwise we will clear the whole queue
3369 * by copying the empty outq at the end of this
3370 * function, but first clear the current entries
3371 * in the queue.
3373 for (i = 0; i < q->nr; i++)
3374 diff_free_filepair(q->queue[i]);
3376 else {
3377 /* Only the matching ones */
3378 for (i = 0; i < q->nr; i++) {
3379 struct diff_filepair *p = q->queue[i];
3381 if (((p->status == DIFF_STATUS_MODIFIED) &&
3382 ((p->score &&
3383 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3384 (!p->score &&
3385 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3386 ((p->status != DIFF_STATUS_MODIFIED) &&
3387 strchr(filter, p->status)))
3388 diff_q(&outq, p);
3389 else
3390 diff_free_filepair(p);
3393 free(q->queue);
3394 *q = outq;
3397 /* Check whether two filespecs with the same mode and size are identical */
3398 static int diff_filespec_is_identical(struct diff_filespec *one,
3399 struct diff_filespec *two)
3401 if (S_ISGITLINK(one->mode))
3402 return 0;
3403 if (diff_populate_filespec(one, 0))
3404 return 0;
3405 if (diff_populate_filespec(two, 0))
3406 return 0;
3407 return !memcmp(one->data, two->data, one->size);
3410 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3412 int i;
3413 struct diff_queue_struct *q = &diff_queued_diff;
3414 struct diff_queue_struct outq;
3415 outq.queue = NULL;
3416 outq.nr = outq.alloc = 0;
3418 for (i = 0; i < q->nr; i++) {
3419 struct diff_filepair *p = q->queue[i];
3422 * 1. Entries that come from stat info dirtyness
3423 * always have both sides (iow, not create/delete),
3424 * one side of the object name is unknown, with
3425 * the same mode and size. Keep the ones that
3426 * do not match these criteria. They have real
3427 * differences.
3429 * 2. At this point, the file is known to be modified,
3430 * with the same mode and size, and the object
3431 * name of one side is unknown. Need to inspect
3432 * the identical contents.
3434 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3435 !DIFF_FILE_VALID(p->two) ||
3436 (p->one->sha1_valid && p->two->sha1_valid) ||
3437 (p->one->mode != p->two->mode) ||
3438 diff_populate_filespec(p->one, 1) ||
3439 diff_populate_filespec(p->two, 1) ||
3440 (p->one->size != p->two->size) ||
3441 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3442 diff_q(&outq, p);
3443 else {
3445 * The caller can subtract 1 from skip_stat_unmatch
3446 * to determine how many paths were dirty only
3447 * due to stat info mismatch.
3449 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3450 diffopt->skip_stat_unmatch++;
3451 diff_free_filepair(p);
3454 free(q->queue);
3455 *q = outq;
3458 void diffcore_std(struct diff_options *options)
3460 if (options->skip_stat_unmatch)
3461 diffcore_skip_stat_unmatch(options);
3462 if (options->break_opt != -1)
3463 diffcore_break(options->break_opt);
3464 if (options->detect_rename)
3465 diffcore_rename(options);
3466 if (options->break_opt != -1)
3467 diffcore_merge_broken();
3468 if (options->pickaxe)
3469 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3470 if (options->orderfile)
3471 diffcore_order(options->orderfile);
3472 diff_resolve_rename_copy();
3473 diffcore_apply_filter(options->filter);
3475 if (diff_queued_diff.nr)
3476 DIFF_OPT_SET(options, HAS_CHANGES);
3477 else
3478 DIFF_OPT_CLR(options, HAS_CHANGES);
3481 int diff_result_code(struct diff_options *opt, int status)
3483 int result = 0;
3484 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3485 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3486 return status;
3487 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3488 DIFF_OPT_TST(opt, HAS_CHANGES))
3489 result |= 01;
3490 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3491 DIFF_OPT_TST(opt, CHECK_FAILED))
3492 result |= 02;
3493 return result;
3496 void diff_addremove(struct diff_options *options,
3497 int addremove, unsigned mode,
3498 const unsigned char *sha1,
3499 const char *concatpath)
3501 struct diff_filespec *one, *two;
3503 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3504 return;
3506 /* This may look odd, but it is a preparation for
3507 * feeding "there are unchanged files which should
3508 * not produce diffs, but when you are doing copy
3509 * detection you would need them, so here they are"
3510 * entries to the diff-core. They will be prefixed
3511 * with something like '=' or '*' (I haven't decided
3512 * which but should not make any difference).
3513 * Feeding the same new and old to diff_change()
3514 * also has the same effect.
3515 * Before the final output happens, they are pruned after
3516 * merged into rename/copy pairs as appropriate.
3518 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3519 addremove = (addremove == '+' ? '-' :
3520 addremove == '-' ? '+' : addremove);
3522 if (options->prefix &&
3523 strncmp(concatpath, options->prefix, options->prefix_length))
3524 return;
3526 one = alloc_filespec(concatpath);
3527 two = alloc_filespec(concatpath);
3529 if (addremove != '+')
3530 fill_filespec(one, sha1, mode);
3531 if (addremove != '-')
3532 fill_filespec(two, sha1, mode);
3534 diff_queue(&diff_queued_diff, one, two);
3535 DIFF_OPT_SET(options, HAS_CHANGES);
3538 void diff_change(struct diff_options *options,
3539 unsigned old_mode, unsigned new_mode,
3540 const unsigned char *old_sha1,
3541 const unsigned char *new_sha1,
3542 const char *concatpath)
3544 struct diff_filespec *one, *two;
3546 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3547 && S_ISGITLINK(new_mode))
3548 return;
3550 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3551 unsigned tmp;
3552 const unsigned char *tmp_c;
3553 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3554 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3557 if (options->prefix &&
3558 strncmp(concatpath, options->prefix, options->prefix_length))
3559 return;
3561 one = alloc_filespec(concatpath);
3562 two = alloc_filespec(concatpath);
3563 fill_filespec(one, old_sha1, old_mode);
3564 fill_filespec(two, new_sha1, new_mode);
3566 diff_queue(&diff_queued_diff, one, two);
3567 DIFF_OPT_SET(options, HAS_CHANGES);
3570 void diff_unmerge(struct diff_options *options,
3571 const char *path,
3572 unsigned mode, const unsigned char *sha1)
3574 struct diff_filespec *one, *two;
3576 if (options->prefix &&
3577 strncmp(path, options->prefix, options->prefix_length))
3578 return;
3580 one = alloc_filespec(path);
3581 two = alloc_filespec(path);
3582 fill_filespec(one, sha1, mode);
3583 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3586 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3587 size_t *outsize)
3589 struct diff_tempfile *temp;
3590 const char *argv[3];
3591 const char **arg = argv;
3592 struct child_process child;
3593 struct strbuf buf = STRBUF_INIT;
3595 temp = prepare_temp_file(spec->path, spec);
3596 *arg++ = pgm;
3597 *arg++ = temp->name;
3598 *arg = NULL;
3600 memset(&child, 0, sizeof(child));
3601 child.argv = argv;
3602 child.out = -1;
3603 if (start_command(&child) != 0 ||
3604 strbuf_read(&buf, child.out, 0) < 0 ||
3605 finish_command(&child) != 0) {
3606 strbuf_release(&buf);
3607 remove_tempfile();
3608 error("error running textconv command '%s'", pgm);
3609 return NULL;
3611 remove_tempfile();
3613 return strbuf_detach(&buf, outsize);