Merge branch 'master' into next
[git/spearce.git] / diff.c
blob32af734912417559c9330ee647907d4b606fa3f8
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 color_diff;
536 unsigned ws_rule;
537 int blank_at_eof;
538 int lno_in_preimage;
539 sane_truncate_fn truncate;
540 const char **label_path;
541 struct diff_words_data *diff_words;
542 int *found_changesp;
543 FILE *file;
546 static void free_diff_words_data(struct emit_callback *ecbdata)
548 if (ecbdata->diff_words) {
549 /* flush buffers */
550 if (ecbdata->diff_words->minus.text.size ||
551 ecbdata->diff_words->plus.text.size)
552 diff_words_show(ecbdata->diff_words);
554 free (ecbdata->diff_words->minus.text.ptr);
555 free (ecbdata->diff_words->minus.orig);
556 free (ecbdata->diff_words->plus.text.ptr);
557 free (ecbdata->diff_words->plus.orig);
558 free(ecbdata->diff_words->word_regex);
559 free(ecbdata->diff_words);
560 ecbdata->diff_words = NULL;
564 const char *diff_get_color(int diff_use_color, enum color_diff ix)
566 if (diff_use_color)
567 return diff_colors[ix];
568 return "";
571 static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
573 int has_trailing_newline, has_trailing_carriage_return;
575 has_trailing_newline = (len > 0 && line[len-1] == '\n');
576 if (has_trailing_newline)
577 len--;
578 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
579 if (has_trailing_carriage_return)
580 len--;
582 fputs(set, file);
583 fwrite(line, len, 1, file);
584 fputs(reset, file);
585 if (has_trailing_carriage_return)
586 fputc('\r', file);
587 if (has_trailing_newline)
588 fputc('\n', file);
591 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
593 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
594 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
596 if (!*ws)
597 emit_line(ecbdata->file, set, reset, line, len);
598 else if ((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
599 ecbdata->blank_at_eof &&
600 (ecbdata->blank_at_eof <= ecbdata->lno_in_preimage) &&
601 ws_blank_line(line + 1, len - 1, ecbdata->ws_rule))
602 /* Blank line at EOF */
603 emit_line(ecbdata->file, ws, reset, line, len);
604 else {
605 /* Emit just the prefix, then the rest. */
606 emit_line(ecbdata->file, set, reset, line, 1);
607 ws_check_emit(line + 1, len - 1, ecbdata->ws_rule,
608 ecbdata->file, set, reset, ws);
612 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
614 const char *cp;
615 unsigned long allot;
616 size_t l = len;
618 if (ecb->truncate)
619 return ecb->truncate(line, len);
620 cp = line;
621 allot = l;
622 while (0 < l) {
623 (void) utf8_width(&cp, &l);
624 if (!cp)
625 break; /* truncated in the middle? */
627 return allot - l;
630 static int find_preimage_lno(const char *line)
632 char *p = strchr(line, '-');
633 if (!p)
634 return 0; /* should not happen */
635 return strtol(p+1, NULL, 10);
638 static void fn_out_consume(void *priv, char *line, unsigned long len)
640 struct emit_callback *ecbdata = priv;
641 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
642 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
643 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
645 *(ecbdata->found_changesp) = 1;
647 if (ecbdata->label_path[0]) {
648 const char *name_a_tab, *name_b_tab;
650 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
651 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
653 fprintf(ecbdata->file, "%s--- %s%s%s\n",
654 meta, ecbdata->label_path[0], reset, name_a_tab);
655 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
656 meta, ecbdata->label_path[1], reset, name_b_tab);
657 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
660 if (diff_suppress_blank_empty
661 && len == 2 && line[0] == ' ' && line[1] == '\n') {
662 line[0] = '\n';
663 len = 1;
666 if (line[0] == '@') {
667 len = sane_truncate_line(ecbdata, line, len);
668 ecbdata->lno_in_preimage = find_preimage_lno(line);
669 emit_line(ecbdata->file,
670 diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
671 reset, line, len);
672 if (line[len-1] != '\n')
673 putc('\n', ecbdata->file);
674 return;
677 if (len < 1) {
678 emit_line(ecbdata->file, reset, reset, line, len);
679 return;
682 if (ecbdata->diff_words) {
683 if (line[0] == '-') {
684 diff_words_append(line, len,
685 &ecbdata->diff_words->minus);
686 return;
687 } else if (line[0] == '+') {
688 diff_words_append(line, len,
689 &ecbdata->diff_words->plus);
690 return;
692 if (ecbdata->diff_words->minus.text.size ||
693 ecbdata->diff_words->plus.text.size)
694 diff_words_show(ecbdata->diff_words);
695 line++;
696 len--;
697 emit_line(ecbdata->file, plain, reset, line, len);
698 return;
701 if (line[0] != '+') {
702 const char *color =
703 diff_get_color(ecbdata->color_diff,
704 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
705 ecbdata->lno_in_preimage++;
706 emit_line(ecbdata->file, color, reset, line, len);
707 return;
709 emit_add_line(reset, ecbdata, line, len);
712 static char *pprint_rename(const char *a, const char *b)
714 const char *old = a;
715 const char *new = b;
716 struct strbuf name = STRBUF_INIT;
717 int pfx_length, sfx_length;
718 int len_a = strlen(a);
719 int len_b = strlen(b);
720 int a_midlen, b_midlen;
721 int qlen_a = quote_c_style(a, NULL, NULL, 0);
722 int qlen_b = quote_c_style(b, NULL, NULL, 0);
724 if (qlen_a || qlen_b) {
725 quote_c_style(a, &name, NULL, 0);
726 strbuf_addstr(&name, " => ");
727 quote_c_style(b, &name, NULL, 0);
728 return strbuf_detach(&name, NULL);
731 /* Find common prefix */
732 pfx_length = 0;
733 while (*old && *new && *old == *new) {
734 if (*old == '/')
735 pfx_length = old - a + 1;
736 old++;
737 new++;
740 /* Find common suffix */
741 old = a + len_a;
742 new = b + len_b;
743 sfx_length = 0;
744 while (a <= old && b <= new && *old == *new) {
745 if (*old == '/')
746 sfx_length = len_a - (old - a);
747 old--;
748 new--;
752 * pfx{mid-a => mid-b}sfx
753 * {pfx-a => pfx-b}sfx
754 * pfx{sfx-a => sfx-b}
755 * name-a => name-b
757 a_midlen = len_a - pfx_length - sfx_length;
758 b_midlen = len_b - pfx_length - sfx_length;
759 if (a_midlen < 0)
760 a_midlen = 0;
761 if (b_midlen < 0)
762 b_midlen = 0;
764 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
765 if (pfx_length + sfx_length) {
766 strbuf_add(&name, a, pfx_length);
767 strbuf_addch(&name, '{');
769 strbuf_add(&name, a + pfx_length, a_midlen);
770 strbuf_addstr(&name, " => ");
771 strbuf_add(&name, b + pfx_length, b_midlen);
772 if (pfx_length + sfx_length) {
773 strbuf_addch(&name, '}');
774 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
776 return strbuf_detach(&name, NULL);
779 struct diffstat_t {
780 int nr;
781 int alloc;
782 struct diffstat_file {
783 char *from_name;
784 char *name;
785 char *print_name;
786 unsigned is_unmerged:1;
787 unsigned is_binary:1;
788 unsigned is_renamed:1;
789 unsigned int added, deleted;
790 } **files;
793 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
794 const char *name_a,
795 const char *name_b)
797 struct diffstat_file *x;
798 x = xcalloc(sizeof (*x), 1);
799 if (diffstat->nr == diffstat->alloc) {
800 diffstat->alloc = alloc_nr(diffstat->alloc);
801 diffstat->files = xrealloc(diffstat->files,
802 diffstat->alloc * sizeof(x));
804 diffstat->files[diffstat->nr++] = x;
805 if (name_b) {
806 x->from_name = xstrdup(name_a);
807 x->name = xstrdup(name_b);
808 x->is_renamed = 1;
810 else {
811 x->from_name = NULL;
812 x->name = xstrdup(name_a);
814 return x;
817 static void diffstat_consume(void *priv, char *line, unsigned long len)
819 struct diffstat_t *diffstat = priv;
820 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
822 if (line[0] == '+')
823 x->added++;
824 else if (line[0] == '-')
825 x->deleted++;
828 const char mime_boundary_leader[] = "------------";
830 static int scale_linear(int it, int width, int max_change)
833 * make sure that at least one '-' is printed if there were deletions,
834 * and likewise for '+'.
836 if (max_change < 2)
837 return it;
838 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
841 static void show_name(FILE *file,
842 const char *prefix, const char *name, int len)
844 fprintf(file, " %s%-*s |", prefix, len, name);
847 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
849 if (cnt <= 0)
850 return;
851 fprintf(file, "%s", set);
852 while (cnt--)
853 putc(ch, file);
854 fprintf(file, "%s", reset);
857 static void fill_print_name(struct diffstat_file *file)
859 char *pname;
861 if (file->print_name)
862 return;
864 if (!file->is_renamed) {
865 struct strbuf buf = STRBUF_INIT;
866 if (quote_c_style(file->name, &buf, NULL, 0)) {
867 pname = strbuf_detach(&buf, NULL);
868 } else {
869 pname = file->name;
870 strbuf_release(&buf);
872 } else {
873 pname = pprint_rename(file->from_name, file->name);
875 file->print_name = pname;
878 static void show_stats(struct diffstat_t *data, struct diff_options *options)
880 int i, len, add, del, adds = 0, dels = 0;
881 int max_change = 0, max_len = 0;
882 int total_files = data->nr;
883 int width, name_width;
884 const char *reset, *set, *add_c, *del_c;
886 if (data->nr == 0)
887 return;
889 width = options->stat_width ? options->stat_width : 80;
890 name_width = options->stat_name_width ? options->stat_name_width : 50;
892 /* Sanity: give at least 5 columns to the graph,
893 * but leave at least 10 columns for the name.
895 if (width < 25)
896 width = 25;
897 if (name_width < 10)
898 name_width = 10;
899 else if (width < name_width + 15)
900 name_width = width - 15;
902 /* Find the longest filename and max number of changes */
903 reset = diff_get_color_opt(options, DIFF_RESET);
904 set = diff_get_color_opt(options, DIFF_PLAIN);
905 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
906 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
908 for (i = 0; i < data->nr; i++) {
909 struct diffstat_file *file = data->files[i];
910 int change = file->added + file->deleted;
911 fill_print_name(file);
912 len = strlen(file->print_name);
913 if (max_len < len)
914 max_len = len;
916 if (file->is_binary || file->is_unmerged)
917 continue;
918 if (max_change < change)
919 max_change = change;
922 /* Compute the width of the graph part;
923 * 10 is for one blank at the beginning of the line plus
924 * " | count " between the name and the graph.
926 * From here on, name_width is the width of the name area,
927 * and width is the width of the graph area.
929 name_width = (name_width < max_len) ? name_width : max_len;
930 if (width < (name_width + 10) + max_change)
931 width = width - (name_width + 10);
932 else
933 width = max_change;
935 for (i = 0; i < data->nr; i++) {
936 const char *prefix = "";
937 char *name = data->files[i]->print_name;
938 int added = data->files[i]->added;
939 int deleted = data->files[i]->deleted;
940 int name_len;
943 * "scale" the filename
945 len = name_width;
946 name_len = strlen(name);
947 if (name_width < name_len) {
948 char *slash;
949 prefix = "...";
950 len -= 3;
951 name += name_len - len;
952 slash = strchr(name, '/');
953 if (slash)
954 name = slash;
957 if (data->files[i]->is_binary) {
958 show_name(options->file, prefix, name, len);
959 fprintf(options->file, " Bin ");
960 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
961 fprintf(options->file, " -> ");
962 fprintf(options->file, "%s%d%s", add_c, added, reset);
963 fprintf(options->file, " bytes");
964 fprintf(options->file, "\n");
965 continue;
967 else if (data->files[i]->is_unmerged) {
968 show_name(options->file, prefix, name, len);
969 fprintf(options->file, " Unmerged\n");
970 continue;
972 else if (!data->files[i]->is_renamed &&
973 (added + deleted == 0)) {
974 total_files--;
975 continue;
979 * scale the add/delete
981 add = added;
982 del = deleted;
983 adds += add;
984 dels += del;
986 if (width <= max_change) {
987 add = scale_linear(add, width, max_change);
988 del = scale_linear(del, width, max_change);
990 show_name(options->file, prefix, name, len);
991 fprintf(options->file, "%5d%s", added + deleted,
992 added + deleted ? " " : "");
993 show_graph(options->file, '+', add, add_c, reset);
994 show_graph(options->file, '-', del, del_c, reset);
995 fprintf(options->file, "\n");
997 fprintf(options->file,
998 " %d files changed, %d insertions(+), %d deletions(-)\n",
999 total_files, adds, dels);
1002 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
1004 int i, adds = 0, dels = 0, total_files = data->nr;
1006 if (data->nr == 0)
1007 return;
1009 for (i = 0; i < data->nr; i++) {
1010 if (!data->files[i]->is_binary &&
1011 !data->files[i]->is_unmerged) {
1012 int added = data->files[i]->added;
1013 int deleted= data->files[i]->deleted;
1014 if (!data->files[i]->is_renamed &&
1015 (added + deleted == 0)) {
1016 total_files--;
1017 } else {
1018 adds += added;
1019 dels += deleted;
1023 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1024 total_files, adds, dels);
1027 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1029 int i;
1031 if (data->nr == 0)
1032 return;
1034 for (i = 0; i < data->nr; i++) {
1035 struct diffstat_file *file = data->files[i];
1037 if (file->is_binary)
1038 fprintf(options->file, "-\t-\t");
1039 else
1040 fprintf(options->file,
1041 "%d\t%d\t", file->added, file->deleted);
1042 if (options->line_termination) {
1043 fill_print_name(file);
1044 if (!file->is_renamed)
1045 write_name_quoted(file->name, options->file,
1046 options->line_termination);
1047 else {
1048 fputs(file->print_name, options->file);
1049 putc(options->line_termination, options->file);
1051 } else {
1052 if (file->is_renamed) {
1053 putc('\0', options->file);
1054 write_name_quoted(file->from_name, options->file, '\0');
1056 write_name_quoted(file->name, options->file, '\0');
1061 struct dirstat_file {
1062 const char *name;
1063 unsigned long changed;
1066 struct dirstat_dir {
1067 struct dirstat_file *files;
1068 int alloc, nr, percent, cumulative;
1071 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1073 unsigned long this_dir = 0;
1074 unsigned int sources = 0;
1076 while (dir->nr) {
1077 struct dirstat_file *f = dir->files;
1078 int namelen = strlen(f->name);
1079 unsigned long this;
1080 char *slash;
1082 if (namelen < baselen)
1083 break;
1084 if (memcmp(f->name, base, baselen))
1085 break;
1086 slash = strchr(f->name + baselen, '/');
1087 if (slash) {
1088 int newbaselen = slash + 1 - f->name;
1089 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1090 sources++;
1091 } else {
1092 this = f->changed;
1093 dir->files++;
1094 dir->nr--;
1095 sources += 2;
1097 this_dir += this;
1101 * We don't report dirstat's for
1102 * - the top level
1103 * - or cases where everything came from a single directory
1104 * under this directory (sources == 1).
1106 if (baselen && sources != 1) {
1107 int permille = this_dir * 1000 / changed;
1108 if (permille) {
1109 int percent = permille / 10;
1110 if (percent >= dir->percent) {
1111 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1112 if (!dir->cumulative)
1113 return 0;
1117 return this_dir;
1120 static int dirstat_compare(const void *_a, const void *_b)
1122 const struct dirstat_file *a = _a;
1123 const struct dirstat_file *b = _b;
1124 return strcmp(a->name, b->name);
1127 static void show_dirstat(struct diff_options *options)
1129 int i;
1130 unsigned long changed;
1131 struct dirstat_dir dir;
1132 struct diff_queue_struct *q = &diff_queued_diff;
1134 dir.files = NULL;
1135 dir.alloc = 0;
1136 dir.nr = 0;
1137 dir.percent = options->dirstat_percent;
1138 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1140 changed = 0;
1141 for (i = 0; i < q->nr; i++) {
1142 struct diff_filepair *p = q->queue[i];
1143 const char *name;
1144 unsigned long copied, added, damage;
1146 name = p->one->path ? p->one->path : p->two->path;
1148 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1149 diff_populate_filespec(p->one, 0);
1150 diff_populate_filespec(p->two, 0);
1151 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1152 &copied, &added);
1153 diff_free_filespec_data(p->one);
1154 diff_free_filespec_data(p->two);
1155 } else if (DIFF_FILE_VALID(p->one)) {
1156 diff_populate_filespec(p->one, 1);
1157 copied = added = 0;
1158 diff_free_filespec_data(p->one);
1159 } else if (DIFF_FILE_VALID(p->two)) {
1160 diff_populate_filespec(p->two, 1);
1161 copied = 0;
1162 added = p->two->size;
1163 diff_free_filespec_data(p->two);
1164 } else
1165 continue;
1168 * Original minus copied is the removed material,
1169 * added is the new material. They are both damages
1170 * made to the preimage. In --dirstat-by-file mode, count
1171 * damaged files, not damaged lines. This is done by
1172 * counting only a single damaged line per file.
1174 damage = (p->one->size - copied) + added;
1175 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1176 damage = 1;
1178 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1179 dir.files[dir.nr].name = name;
1180 dir.files[dir.nr].changed = damage;
1181 changed += damage;
1182 dir.nr++;
1185 /* This can happen even with many files, if everything was renames */
1186 if (!changed)
1187 return;
1189 /* Show all directories with more than x% of the changes */
1190 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1191 gather_dirstat(options->file, &dir, changed, "", 0);
1194 static void free_diffstat_info(struct diffstat_t *diffstat)
1196 int i;
1197 for (i = 0; i < diffstat->nr; i++) {
1198 struct diffstat_file *f = diffstat->files[i];
1199 if (f->name != f->print_name)
1200 free(f->print_name);
1201 free(f->name);
1202 free(f->from_name);
1203 free(f);
1205 free(diffstat->files);
1208 struct checkdiff_t {
1209 const char *filename;
1210 int lineno;
1211 struct diff_options *o;
1212 unsigned ws_rule;
1213 unsigned status;
1216 static int is_conflict_marker(const char *line, unsigned long len)
1218 char firstchar;
1219 int cnt;
1221 if (len < 8)
1222 return 0;
1223 firstchar = line[0];
1224 switch (firstchar) {
1225 case '=': case '>': case '<':
1226 break;
1227 default:
1228 return 0;
1230 for (cnt = 1; cnt < 7; cnt++)
1231 if (line[cnt] != firstchar)
1232 return 0;
1233 /* line[0] thru line[6] are same as firstchar */
1234 if (firstchar == '=') {
1235 /* divider between ours and theirs? */
1236 if (len != 8 || line[7] != '\n')
1237 return 0;
1238 } else if (len < 8 || !isspace(line[7])) {
1239 /* not divider before ours nor after theirs */
1240 return 0;
1242 return 1;
1245 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1247 struct checkdiff_t *data = priv;
1248 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1249 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1250 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1251 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1252 char *err;
1254 if (line[0] == '+') {
1255 unsigned bad;
1256 data->lineno++;
1257 if (is_conflict_marker(line + 1, len - 1)) {
1258 data->status |= 1;
1259 fprintf(data->o->file,
1260 "%s:%d: leftover conflict marker\n",
1261 data->filename, data->lineno);
1263 bad = ws_check(line + 1, len - 1, data->ws_rule);
1264 if (!bad)
1265 return;
1266 data->status |= bad;
1267 err = whitespace_error_string(bad);
1268 fprintf(data->o->file, "%s:%d: %s.\n",
1269 data->filename, data->lineno, err);
1270 free(err);
1271 emit_line(data->o->file, set, reset, line, 1);
1272 ws_check_emit(line + 1, len - 1, data->ws_rule,
1273 data->o->file, set, reset, ws);
1274 } else if (line[0] == ' ') {
1275 data->lineno++;
1276 } else if (line[0] == '@') {
1277 char *plus = strchr(line, '+');
1278 if (plus)
1279 data->lineno = strtol(plus, NULL, 10) - 1;
1280 else
1281 die("invalid diff");
1285 static unsigned char *deflate_it(char *data,
1286 unsigned long size,
1287 unsigned long *result_size)
1289 int bound;
1290 unsigned char *deflated;
1291 z_stream stream;
1293 memset(&stream, 0, sizeof(stream));
1294 deflateInit(&stream, zlib_compression_level);
1295 bound = deflateBound(&stream, size);
1296 deflated = xmalloc(bound);
1297 stream.next_out = deflated;
1298 stream.avail_out = bound;
1300 stream.next_in = (unsigned char *)data;
1301 stream.avail_in = size;
1302 while (deflate(&stream, Z_FINISH) == Z_OK)
1303 ; /* nothing */
1304 deflateEnd(&stream);
1305 *result_size = stream.total_out;
1306 return deflated;
1309 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1311 void *cp;
1312 void *delta;
1313 void *deflated;
1314 void *data;
1315 unsigned long orig_size;
1316 unsigned long delta_size;
1317 unsigned long deflate_size;
1318 unsigned long data_size;
1320 /* We could do deflated delta, or we could do just deflated two,
1321 * whichever is smaller.
1323 delta = NULL;
1324 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1325 if (one->size && two->size) {
1326 delta = diff_delta(one->ptr, one->size,
1327 two->ptr, two->size,
1328 &delta_size, deflate_size);
1329 if (delta) {
1330 void *to_free = delta;
1331 orig_size = delta_size;
1332 delta = deflate_it(delta, delta_size, &delta_size);
1333 free(to_free);
1337 if (delta && delta_size < deflate_size) {
1338 fprintf(file, "delta %lu\n", orig_size);
1339 free(deflated);
1340 data = delta;
1341 data_size = delta_size;
1343 else {
1344 fprintf(file, "literal %lu\n", two->size);
1345 free(delta);
1346 data = deflated;
1347 data_size = deflate_size;
1350 /* emit data encoded in base85 */
1351 cp = data;
1352 while (data_size) {
1353 int bytes = (52 < data_size) ? 52 : data_size;
1354 char line[70];
1355 data_size -= bytes;
1356 if (bytes <= 26)
1357 line[0] = bytes + 'A' - 1;
1358 else
1359 line[0] = bytes - 26 + 'a' - 1;
1360 encode_85(line + 1, cp, bytes);
1361 cp = (char *) cp + bytes;
1362 fputs(line, file);
1363 fputc('\n', file);
1365 fprintf(file, "\n");
1366 free(data);
1369 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1371 fprintf(file, "GIT binary patch\n");
1372 emit_binary_diff_body(file, one, two);
1373 emit_binary_diff_body(file, two, one);
1376 static void diff_filespec_load_driver(struct diff_filespec *one)
1378 if (!one->driver)
1379 one->driver = userdiff_find_by_path(one->path);
1380 if (!one->driver)
1381 one->driver = userdiff_find_by_name("default");
1384 int diff_filespec_is_binary(struct diff_filespec *one)
1386 if (one->is_binary == -1) {
1387 diff_filespec_load_driver(one);
1388 if (one->driver->binary != -1)
1389 one->is_binary = one->driver->binary;
1390 else {
1391 if (!one->data && DIFF_FILE_VALID(one))
1392 diff_populate_filespec(one, 0);
1393 if (one->data)
1394 one->is_binary = buffer_is_binary(one->data,
1395 one->size);
1396 if (one->is_binary == -1)
1397 one->is_binary = 0;
1400 return one->is_binary;
1403 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1405 diff_filespec_load_driver(one);
1406 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1409 static const char *userdiff_word_regex(struct diff_filespec *one)
1411 diff_filespec_load_driver(one);
1412 return one->driver->word_regex;
1415 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1417 if (!options->a_prefix)
1418 options->a_prefix = a;
1419 if (!options->b_prefix)
1420 options->b_prefix = b;
1423 static const char *get_textconv(struct diff_filespec *one)
1425 if (!DIFF_FILE_VALID(one))
1426 return NULL;
1427 if (!S_ISREG(one->mode))
1428 return NULL;
1429 diff_filespec_load_driver(one);
1430 return one->driver->textconv;
1433 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
1435 char *ptr = mf->ptr;
1436 long size = mf->size;
1437 int cnt = 0;
1439 if (!size)
1440 return cnt;
1441 ptr += size - 1; /* pointing at the very end */
1442 if (*ptr != '\n')
1443 ; /* incomplete line */
1444 else
1445 ptr--; /* skip the last LF */
1446 while (mf->ptr < ptr) {
1447 char *prev_eol;
1448 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
1449 if (*prev_eol == '\n')
1450 break;
1451 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
1452 break;
1453 cnt++;
1454 ptr = prev_eol - 1;
1456 return cnt;
1459 static int adds_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2, unsigned ws_rule)
1461 int l1, l2, at;
1462 l1 = count_trailing_blank(mf1, ws_rule);
1463 l2 = count_trailing_blank(mf2, ws_rule);
1464 if (l2 <= l1)
1465 return 0;
1466 /* starting where? */
1467 at = count_lines(mf1->ptr, mf1->size);
1468 return (at - l1) + 1; /* the line number counts from 1 */
1471 static void builtin_diff(const char *name_a,
1472 const char *name_b,
1473 struct diff_filespec *one,
1474 struct diff_filespec *two,
1475 const char *xfrm_msg,
1476 struct diff_options *o,
1477 int complete_rewrite)
1479 mmfile_t mf1, mf2;
1480 const char *lbl[2];
1481 char *a_one, *b_two;
1482 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1483 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1484 const char *a_prefix, *b_prefix;
1485 const char *textconv_one = NULL, *textconv_two = NULL;
1487 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1488 textconv_one = get_textconv(one);
1489 textconv_two = get_textconv(two);
1492 diff_set_mnemonic_prefix(o, "a/", "b/");
1493 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1494 a_prefix = o->b_prefix;
1495 b_prefix = o->a_prefix;
1496 } else {
1497 a_prefix = o->a_prefix;
1498 b_prefix = o->b_prefix;
1501 /* Never use a non-valid filename anywhere if at all possible */
1502 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1503 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1505 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1506 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1507 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1508 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1509 fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1510 if (lbl[0][0] == '/') {
1511 /* /dev/null */
1512 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1513 if (xfrm_msg && xfrm_msg[0])
1514 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1516 else if (lbl[1][0] == '/') {
1517 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1518 if (xfrm_msg && xfrm_msg[0])
1519 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1521 else {
1522 if (one->mode != two->mode) {
1523 fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1524 fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1526 if (xfrm_msg && xfrm_msg[0])
1527 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1529 * we do not run diff between different kind
1530 * of objects.
1532 if ((one->mode ^ two->mode) & S_IFMT)
1533 goto free_ab_and_return;
1534 if (complete_rewrite &&
1535 (textconv_one || !diff_filespec_is_binary(one)) &&
1536 (textconv_two || !diff_filespec_is_binary(two))) {
1537 emit_rewrite_diff(name_a, name_b, one, two,
1538 textconv_one, textconv_two, o);
1539 o->found_changes = 1;
1540 goto free_ab_and_return;
1544 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1545 die("unable to read files to diff");
1547 if (!DIFF_OPT_TST(o, TEXT) &&
1548 ( (diff_filespec_is_binary(one) && !textconv_one) ||
1549 (diff_filespec_is_binary(two) && !textconv_two) )) {
1550 /* Quite common confusing case */
1551 if (mf1.size == mf2.size &&
1552 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1553 goto free_ab_and_return;
1554 if (DIFF_OPT_TST(o, BINARY))
1555 emit_binary_diff(o->file, &mf1, &mf2);
1556 else
1557 fprintf(o->file, "Binary files %s and %s differ\n",
1558 lbl[0], lbl[1]);
1559 o->found_changes = 1;
1561 else {
1562 /* Crazy xdl interfaces.. */
1563 const char *diffopts = getenv("GIT_DIFF_OPTS");
1564 xpparam_t xpp;
1565 xdemitconf_t xecfg;
1566 xdemitcb_t ecb;
1567 struct emit_callback ecbdata;
1568 const struct userdiff_funcname *pe;
1570 if (textconv_one) {
1571 size_t size;
1572 mf1.ptr = run_textconv(textconv_one, one, &size);
1573 if (!mf1.ptr)
1574 die("unable to read files to diff");
1575 mf1.size = size;
1577 if (textconv_two) {
1578 size_t size;
1579 mf2.ptr = run_textconv(textconv_two, two, &size);
1580 if (!mf2.ptr)
1581 die("unable to read files to diff");
1582 mf2.size = size;
1585 pe = diff_funcname_pattern(one);
1586 if (!pe)
1587 pe = diff_funcname_pattern(two);
1589 memset(&xpp, 0, sizeof(xpp));
1590 memset(&xecfg, 0, sizeof(xecfg));
1591 memset(&ecbdata, 0, sizeof(ecbdata));
1592 ecbdata.label_path = lbl;
1593 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1594 ecbdata.found_changesp = &o->found_changes;
1595 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1596 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1597 ecbdata.blank_at_eof =
1598 adds_blank_at_eof(&mf1, &mf2, ecbdata.ws_rule);
1599 ecbdata.file = o->file;
1600 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1601 xecfg.ctxlen = o->context;
1602 xecfg.interhunkctxlen = o->interhunkcontext;
1603 xecfg.flags = XDL_EMIT_FUNCNAMES;
1604 if (pe)
1605 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1606 if (!diffopts)
1608 else if (!prefixcmp(diffopts, "--unified="))
1609 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1610 else if (!prefixcmp(diffopts, "-u"))
1611 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1612 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1613 ecbdata.diff_words =
1614 xcalloc(1, sizeof(struct diff_words_data));
1615 ecbdata.diff_words->file = o->file;
1616 if (!o->word_regex)
1617 o->word_regex = userdiff_word_regex(one);
1618 if (!o->word_regex)
1619 o->word_regex = userdiff_word_regex(two);
1620 if (!o->word_regex)
1621 o->word_regex = diff_word_regex_cfg;
1622 if (o->word_regex) {
1623 ecbdata.diff_words->word_regex = (regex_t *)
1624 xmalloc(sizeof(regex_t));
1625 if (regcomp(ecbdata.diff_words->word_regex,
1626 o->word_regex,
1627 REG_EXTENDED | REG_NEWLINE))
1628 die ("Invalid regular expression: %s",
1629 o->word_regex);
1632 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1633 &xpp, &xecfg, &ecb);
1634 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1635 free_diff_words_data(&ecbdata);
1636 if (textconv_one)
1637 free(mf1.ptr);
1638 if (textconv_two)
1639 free(mf2.ptr);
1640 xdiff_clear_find_func(&xecfg);
1643 free_ab_and_return:
1644 diff_free_filespec_data(one);
1645 diff_free_filespec_data(two);
1646 free(a_one);
1647 free(b_two);
1648 return;
1651 static void builtin_diffstat(const char *name_a, const char *name_b,
1652 struct diff_filespec *one,
1653 struct diff_filespec *two,
1654 struct diffstat_t *diffstat,
1655 struct diff_options *o,
1656 int complete_rewrite)
1658 mmfile_t mf1, mf2;
1659 struct diffstat_file *data;
1661 data = diffstat_add(diffstat, name_a, name_b);
1663 if (!one || !two) {
1664 data->is_unmerged = 1;
1665 return;
1667 if (complete_rewrite) {
1668 diff_populate_filespec(one, 0);
1669 diff_populate_filespec(two, 0);
1670 data->deleted = count_lines(one->data, one->size);
1671 data->added = count_lines(two->data, two->size);
1672 goto free_and_return;
1674 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1675 die("unable to read files to diff");
1677 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1678 data->is_binary = 1;
1679 data->added = mf2.size;
1680 data->deleted = mf1.size;
1681 } else {
1682 /* Crazy xdl interfaces.. */
1683 xpparam_t xpp;
1684 xdemitconf_t xecfg;
1685 xdemitcb_t ecb;
1687 memset(&xpp, 0, sizeof(xpp));
1688 memset(&xecfg, 0, sizeof(xecfg));
1689 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1690 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1691 &xpp, &xecfg, &ecb);
1694 free_and_return:
1695 diff_free_filespec_data(one);
1696 diff_free_filespec_data(two);
1699 static void builtin_checkdiff(const char *name_a, const char *name_b,
1700 const char *attr_path,
1701 struct diff_filespec *one,
1702 struct diff_filespec *two,
1703 struct diff_options *o)
1705 mmfile_t mf1, mf2;
1706 struct checkdiff_t data;
1708 if (!two)
1709 return;
1711 memset(&data, 0, sizeof(data));
1712 data.filename = name_b ? name_b : name_a;
1713 data.lineno = 0;
1714 data.o = o;
1715 data.ws_rule = whitespace_rule(attr_path);
1717 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1718 die("unable to read files to diff");
1721 * All the other codepaths check both sides, but not checking
1722 * the "old" side here is deliberate. We are checking the newly
1723 * introduced changes, and as long as the "new" side is text, we
1724 * can and should check what it introduces.
1726 if (diff_filespec_is_binary(two))
1727 goto free_and_return;
1728 else {
1729 /* Crazy xdl interfaces.. */
1730 xpparam_t xpp;
1731 xdemitconf_t xecfg;
1732 xdemitcb_t ecb;
1734 memset(&xpp, 0, sizeof(xpp));
1735 memset(&xecfg, 0, sizeof(xecfg));
1736 xecfg.ctxlen = 1; /* at least one context line */
1737 xpp.flags = XDF_NEED_MINIMAL;
1738 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1739 &xpp, &xecfg, &ecb);
1741 if (data.ws_rule & WS_BLANK_AT_EOF) {
1742 int blank_at_eof = adds_blank_at_eof(&mf1, &mf2, data.ws_rule);
1743 if (blank_at_eof) {
1744 static char *err;
1745 if (!err)
1746 err = whitespace_error_string(WS_BLANK_AT_EOF);
1747 fprintf(o->file, "%s:%d: %s.\n",
1748 data.filename, blank_at_eof, err);
1749 data.status = 1; /* report errors */
1753 free_and_return:
1754 diff_free_filespec_data(one);
1755 diff_free_filespec_data(two);
1756 if (data.status)
1757 DIFF_OPT_SET(o, CHECK_FAILED);
1760 struct diff_filespec *alloc_filespec(const char *path)
1762 int namelen = strlen(path);
1763 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1765 memset(spec, 0, sizeof(*spec));
1766 spec->path = (char *)(spec + 1);
1767 memcpy(spec->path, path, namelen+1);
1768 spec->count = 1;
1769 spec->is_binary = -1;
1770 return spec;
1773 void free_filespec(struct diff_filespec *spec)
1775 if (!--spec->count) {
1776 diff_free_filespec_data(spec);
1777 free(spec);
1781 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1782 unsigned short mode)
1784 if (mode) {
1785 spec->mode = canon_mode(mode);
1786 hashcpy(spec->sha1, sha1);
1787 spec->sha1_valid = !is_null_sha1(sha1);
1792 * Given a name and sha1 pair, if the index tells us the file in
1793 * the work tree has that object contents, return true, so that
1794 * prepare_temp_file() does not have to inflate and extract.
1796 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1798 struct cache_entry *ce;
1799 struct stat st;
1800 int pos, len;
1803 * We do not read the cache ourselves here, because the
1804 * benchmark with my previous version that always reads cache
1805 * shows that it makes things worse for diff-tree comparing
1806 * two linux-2.6 kernel trees in an already checked out work
1807 * tree. This is because most diff-tree comparisons deal with
1808 * only a small number of files, while reading the cache is
1809 * expensive for a large project, and its cost outweighs the
1810 * savings we get by not inflating the object to a temporary
1811 * file. Practically, this code only helps when we are used
1812 * by diff-cache --cached, which does read the cache before
1813 * calling us.
1815 if (!active_cache)
1816 return 0;
1818 /* We want to avoid the working directory if our caller
1819 * doesn't need the data in a normal file, this system
1820 * is rather slow with its stat/open/mmap/close syscalls,
1821 * and the object is contained in a pack file. The pack
1822 * is probably already open and will be faster to obtain
1823 * the data through than the working directory. Loose
1824 * objects however would tend to be slower as they need
1825 * to be individually opened and inflated.
1827 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1828 return 0;
1830 len = strlen(name);
1831 pos = cache_name_pos(name, len);
1832 if (pos < 0)
1833 return 0;
1834 ce = active_cache[pos];
1837 * This is not the sha1 we are looking for, or
1838 * unreusable because it is not a regular file.
1840 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1841 return 0;
1844 * If ce is marked as "assume unchanged", there is no
1845 * guarantee that work tree matches what we are looking for.
1847 if (ce->ce_flags & CE_VALID)
1848 return 0;
1851 * If ce matches the file in the work tree, we can reuse it.
1853 if (ce_uptodate(ce) ||
1854 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1855 return 1;
1857 return 0;
1860 static int populate_from_stdin(struct diff_filespec *s)
1862 struct strbuf buf = STRBUF_INIT;
1863 size_t size = 0;
1865 if (strbuf_read(&buf, 0, 0) < 0)
1866 return error("error while reading from stdin %s",
1867 strerror(errno));
1869 s->should_munmap = 0;
1870 s->data = strbuf_detach(&buf, &size);
1871 s->size = size;
1872 s->should_free = 1;
1873 return 0;
1876 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1878 int len;
1879 char *data = xmalloc(100);
1880 len = snprintf(data, 100,
1881 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1882 s->data = data;
1883 s->size = len;
1884 s->should_free = 1;
1885 if (size_only) {
1886 s->data = NULL;
1887 free(data);
1889 return 0;
1893 * While doing rename detection and pickaxe operation, we may need to
1894 * grab the data for the blob (or file) for our own in-core comparison.
1895 * diff_filespec has data and size fields for this purpose.
1897 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1899 int err = 0;
1900 if (!DIFF_FILE_VALID(s))
1901 die("internal error: asking to populate invalid file.");
1902 if (S_ISDIR(s->mode))
1903 return -1;
1905 if (s->data)
1906 return 0;
1908 if (size_only && 0 < s->size)
1909 return 0;
1911 if (S_ISGITLINK(s->mode))
1912 return diff_populate_gitlink(s, size_only);
1914 if (!s->sha1_valid ||
1915 reuse_worktree_file(s->path, s->sha1, 0)) {
1916 struct strbuf buf = STRBUF_INIT;
1917 struct stat st;
1918 int fd;
1920 if (!strcmp(s->path, "-"))
1921 return populate_from_stdin(s);
1923 if (lstat(s->path, &st) < 0) {
1924 if (errno == ENOENT) {
1925 err_empty:
1926 err = -1;
1927 empty:
1928 s->data = (char *)"";
1929 s->size = 0;
1930 return err;
1933 s->size = xsize_t(st.st_size);
1934 if (!s->size)
1935 goto empty;
1936 if (S_ISLNK(st.st_mode)) {
1937 struct strbuf sb = STRBUF_INIT;
1939 if (strbuf_readlink(&sb, s->path, s->size))
1940 goto err_empty;
1941 s->size = sb.len;
1942 s->data = strbuf_detach(&sb, NULL);
1943 s->should_free = 1;
1944 return 0;
1946 if (size_only)
1947 return 0;
1948 fd = open(s->path, O_RDONLY);
1949 if (fd < 0)
1950 goto err_empty;
1951 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1952 close(fd);
1953 s->should_munmap = 1;
1956 * Convert from working tree format to canonical git format
1958 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
1959 size_t size = 0;
1960 munmap(s->data, s->size);
1961 s->should_munmap = 0;
1962 s->data = strbuf_detach(&buf, &size);
1963 s->size = size;
1964 s->should_free = 1;
1967 else {
1968 enum object_type type;
1969 if (size_only)
1970 type = sha1_object_info(s->sha1, &s->size);
1971 else {
1972 s->data = read_sha1_file(s->sha1, &type, &s->size);
1973 s->should_free = 1;
1976 return 0;
1979 void diff_free_filespec_blob(struct diff_filespec *s)
1981 if (s->should_free)
1982 free(s->data);
1983 else if (s->should_munmap)
1984 munmap(s->data, s->size);
1986 if (s->should_free || s->should_munmap) {
1987 s->should_free = s->should_munmap = 0;
1988 s->data = NULL;
1992 void diff_free_filespec_data(struct diff_filespec *s)
1994 diff_free_filespec_blob(s);
1995 free(s->cnt_data);
1996 s->cnt_data = NULL;
1999 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2000 void *blob,
2001 unsigned long size,
2002 const unsigned char *sha1,
2003 int mode)
2005 int fd;
2006 struct strbuf buf = STRBUF_INIT;
2007 struct strbuf template = STRBUF_INIT;
2008 char *path_dup = xstrdup(path);
2009 const char *base = basename(path_dup);
2011 /* Generate "XXXXXX_basename.ext" */
2012 strbuf_addstr(&template, "XXXXXX_");
2013 strbuf_addstr(&template, base);
2015 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2016 strlen(base) + 1);
2017 if (fd < 0)
2018 die_errno("unable to create temp-file");
2019 if (convert_to_working_tree(path,
2020 (const char *)blob, (size_t)size, &buf)) {
2021 blob = buf.buf;
2022 size = buf.len;
2024 if (write_in_full(fd, blob, size) != size)
2025 die_errno("unable to write temp-file");
2026 close(fd);
2027 temp->name = temp->tmp_path;
2028 strcpy(temp->hex, sha1_to_hex(sha1));
2029 temp->hex[40] = 0;
2030 sprintf(temp->mode, "%06o", mode);
2031 strbuf_release(&buf);
2032 strbuf_release(&template);
2033 free(path_dup);
2036 static struct diff_tempfile *prepare_temp_file(const char *name,
2037 struct diff_filespec *one)
2039 struct diff_tempfile *temp = claim_diff_tempfile();
2041 if (!DIFF_FILE_VALID(one)) {
2042 not_a_valid_file:
2043 /* A '-' entry produces this for file-2, and
2044 * a '+' entry produces this for file-1.
2046 temp->name = "/dev/null";
2047 strcpy(temp->hex, ".");
2048 strcpy(temp->mode, ".");
2049 return temp;
2052 if (!remove_tempfile_installed) {
2053 atexit(remove_tempfile);
2054 sigchain_push_common(remove_tempfile_on_signal);
2055 remove_tempfile_installed = 1;
2058 if (!one->sha1_valid ||
2059 reuse_worktree_file(name, one->sha1, 1)) {
2060 struct stat st;
2061 if (lstat(name, &st) < 0) {
2062 if (errno == ENOENT)
2063 goto not_a_valid_file;
2064 die_errno("stat(%s)", name);
2066 if (S_ISLNK(st.st_mode)) {
2067 struct strbuf sb = STRBUF_INIT;
2068 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2069 die_errno("readlink(%s)", name);
2070 prep_temp_blob(name, temp, sb.buf, sb.len,
2071 (one->sha1_valid ?
2072 one->sha1 : null_sha1),
2073 (one->sha1_valid ?
2074 one->mode : S_IFLNK));
2075 strbuf_release(&sb);
2077 else {
2078 /* we can borrow from the file in the work tree */
2079 temp->name = name;
2080 if (!one->sha1_valid)
2081 strcpy(temp->hex, sha1_to_hex(null_sha1));
2082 else
2083 strcpy(temp->hex, sha1_to_hex(one->sha1));
2084 /* Even though we may sometimes borrow the
2085 * contents from the work tree, we always want
2086 * one->mode. mode is trustworthy even when
2087 * !(one->sha1_valid), as long as
2088 * DIFF_FILE_VALID(one).
2090 sprintf(temp->mode, "%06o", one->mode);
2092 return temp;
2094 else {
2095 if (diff_populate_filespec(one, 0))
2096 die("cannot read data blob for %s", one->path);
2097 prep_temp_blob(name, temp, one->data, one->size,
2098 one->sha1, one->mode);
2100 return temp;
2103 /* An external diff command takes:
2105 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2106 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2109 static void run_external_diff(const char *pgm,
2110 const char *name,
2111 const char *other,
2112 struct diff_filespec *one,
2113 struct diff_filespec *two,
2114 const char *xfrm_msg,
2115 int complete_rewrite)
2117 const char *spawn_arg[10];
2118 int retval;
2119 const char **arg = &spawn_arg[0];
2121 if (one && two) {
2122 struct diff_tempfile *temp_one, *temp_two;
2123 const char *othername = (other ? other : name);
2124 temp_one = prepare_temp_file(name, one);
2125 temp_two = prepare_temp_file(othername, two);
2126 *arg++ = pgm;
2127 *arg++ = name;
2128 *arg++ = temp_one->name;
2129 *arg++ = temp_one->hex;
2130 *arg++ = temp_one->mode;
2131 *arg++ = temp_two->name;
2132 *arg++ = temp_two->hex;
2133 *arg++ = temp_two->mode;
2134 if (other) {
2135 *arg++ = other;
2136 *arg++ = xfrm_msg;
2138 } else {
2139 *arg++ = pgm;
2140 *arg++ = name;
2142 *arg = NULL;
2143 fflush(NULL);
2144 retval = run_command_v_opt(spawn_arg, 0);
2145 remove_tempfile();
2146 if (retval) {
2147 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2148 exit(1);
2152 static int similarity_index(struct diff_filepair *p)
2154 return p->score * 100 / MAX_SCORE;
2157 static void fill_metainfo(struct strbuf *msg,
2158 const char *name,
2159 const char *other,
2160 struct diff_filespec *one,
2161 struct diff_filespec *two,
2162 struct diff_options *o,
2163 struct diff_filepair *p)
2165 strbuf_init(msg, PATH_MAX * 2 + 300);
2166 switch (p->status) {
2167 case DIFF_STATUS_COPIED:
2168 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2169 strbuf_addstr(msg, "\ncopy from ");
2170 quote_c_style(name, msg, NULL, 0);
2171 strbuf_addstr(msg, "\ncopy to ");
2172 quote_c_style(other, msg, NULL, 0);
2173 strbuf_addch(msg, '\n');
2174 break;
2175 case DIFF_STATUS_RENAMED:
2176 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2177 strbuf_addstr(msg, "\nrename from ");
2178 quote_c_style(name, msg, NULL, 0);
2179 strbuf_addstr(msg, "\nrename to ");
2180 quote_c_style(other, msg, NULL, 0);
2181 strbuf_addch(msg, '\n');
2182 break;
2183 case DIFF_STATUS_MODIFIED:
2184 if (p->score) {
2185 strbuf_addf(msg, "dissimilarity index %d%%\n",
2186 similarity_index(p));
2187 break;
2189 /* fallthru */
2190 default:
2191 /* nothing */
2194 if (one && two && hashcmp(one->sha1, two->sha1)) {
2195 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2197 if (DIFF_OPT_TST(o, BINARY)) {
2198 mmfile_t mf;
2199 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2200 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2201 abbrev = 40;
2203 strbuf_addf(msg, "index %.*s..%.*s",
2204 abbrev, sha1_to_hex(one->sha1),
2205 abbrev, sha1_to_hex(two->sha1));
2206 if (one->mode == two->mode)
2207 strbuf_addf(msg, " %06o", one->mode);
2208 strbuf_addch(msg, '\n');
2210 if (msg->len)
2211 strbuf_setlen(msg, msg->len - 1);
2214 static void run_diff_cmd(const char *pgm,
2215 const char *name,
2216 const char *other,
2217 const char *attr_path,
2218 struct diff_filespec *one,
2219 struct diff_filespec *two,
2220 struct strbuf *msg,
2221 struct diff_options *o,
2222 struct diff_filepair *p)
2224 const char *xfrm_msg = NULL;
2225 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2227 if (msg) {
2228 fill_metainfo(msg, name, other, one, two, o, p);
2229 xfrm_msg = msg->len ? msg->buf : NULL;
2232 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2233 pgm = NULL;
2234 else {
2235 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2236 if (drv && drv->external)
2237 pgm = drv->external;
2240 if (pgm) {
2241 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2242 complete_rewrite);
2243 return;
2245 if (one && two)
2246 builtin_diff(name, other ? other : name,
2247 one, two, xfrm_msg, o, complete_rewrite);
2248 else
2249 fprintf(o->file, "* Unmerged path %s\n", name);
2252 static void diff_fill_sha1_info(struct diff_filespec *one)
2254 if (DIFF_FILE_VALID(one)) {
2255 if (!one->sha1_valid) {
2256 struct stat st;
2257 if (!strcmp(one->path, "-")) {
2258 hashcpy(one->sha1, null_sha1);
2259 return;
2261 if (lstat(one->path, &st) < 0)
2262 die_errno("stat '%s'", one->path);
2263 if (index_path(one->sha1, one->path, &st, 0))
2264 die("cannot hash %s", one->path);
2267 else
2268 hashclr(one->sha1);
2271 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2273 /* Strip the prefix but do not molest /dev/null and absolute paths */
2274 if (*namep && **namep != '/')
2275 *namep += prefix_length;
2276 if (*otherp && **otherp != '/')
2277 *otherp += prefix_length;
2280 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2282 const char *pgm = external_diff();
2283 struct strbuf msg;
2284 struct diff_filespec *one = p->one;
2285 struct diff_filespec *two = p->two;
2286 const char *name;
2287 const char *other;
2288 const char *attr_path;
2290 name = p->one->path;
2291 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2292 attr_path = name;
2293 if (o->prefix_length)
2294 strip_prefix(o->prefix_length, &name, &other);
2296 if (DIFF_PAIR_UNMERGED(p)) {
2297 run_diff_cmd(pgm, name, NULL, attr_path,
2298 NULL, NULL, NULL, o, p);
2299 return;
2302 diff_fill_sha1_info(one);
2303 diff_fill_sha1_info(two);
2305 if (!pgm &&
2306 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2307 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2309 * a filepair that changes between file and symlink
2310 * needs to be split into deletion and creation.
2312 struct diff_filespec *null = alloc_filespec(two->path);
2313 run_diff_cmd(NULL, name, other, attr_path,
2314 one, null, &msg, o, p);
2315 free(null);
2316 strbuf_release(&msg);
2318 null = alloc_filespec(one->path);
2319 run_diff_cmd(NULL, name, other, attr_path,
2320 null, two, &msg, o, p);
2321 free(null);
2323 else
2324 run_diff_cmd(pgm, name, other, attr_path,
2325 one, two, &msg, o, p);
2327 strbuf_release(&msg);
2330 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2331 struct diffstat_t *diffstat)
2333 const char *name;
2334 const char *other;
2335 int complete_rewrite = 0;
2337 if (DIFF_PAIR_UNMERGED(p)) {
2338 /* unmerged */
2339 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2340 return;
2343 name = p->one->path;
2344 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2346 if (o->prefix_length)
2347 strip_prefix(o->prefix_length, &name, &other);
2349 diff_fill_sha1_info(p->one);
2350 diff_fill_sha1_info(p->two);
2352 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2353 complete_rewrite = 1;
2354 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2357 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2359 const char *name;
2360 const char *other;
2361 const char *attr_path;
2363 if (DIFF_PAIR_UNMERGED(p)) {
2364 /* unmerged */
2365 return;
2368 name = p->one->path;
2369 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2370 attr_path = other ? other : name;
2372 if (o->prefix_length)
2373 strip_prefix(o->prefix_length, &name, &other);
2375 diff_fill_sha1_info(p->one);
2376 diff_fill_sha1_info(p->two);
2378 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2381 void diff_setup(struct diff_options *options)
2383 memset(options, 0, sizeof(*options));
2385 options->file = stdout;
2387 options->line_termination = '\n';
2388 options->break_opt = -1;
2389 options->rename_limit = -1;
2390 options->dirstat_percent = 3;
2391 options->context = 3;
2393 options->change = diff_change;
2394 options->add_remove = diff_addremove;
2395 if (diff_use_color_default > 0)
2396 DIFF_OPT_SET(options, COLOR_DIFF);
2397 options->detect_rename = diff_detect_rename_default;
2399 if (!diff_mnemonic_prefix) {
2400 options->a_prefix = "a/";
2401 options->b_prefix = "b/";
2405 int diff_setup_done(struct diff_options *options)
2407 int count = 0;
2409 if (options->output_format & DIFF_FORMAT_NAME)
2410 count++;
2411 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2412 count++;
2413 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2414 count++;
2415 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2416 count++;
2417 if (count > 1)
2418 die("--name-only, --name-status, --check and -s are mutually exclusive");
2421 * Most of the time we can say "there are changes"
2422 * only by checking if there are changed paths, but
2423 * --ignore-whitespace* options force us to look
2424 * inside contents.
2427 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2428 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2429 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2430 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2431 else
2432 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2434 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2435 options->detect_rename = DIFF_DETECT_COPY;
2437 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2438 options->prefix = NULL;
2439 if (options->prefix)
2440 options->prefix_length = strlen(options->prefix);
2441 else
2442 options->prefix_length = 0;
2444 if (options->output_format & (DIFF_FORMAT_NAME |
2445 DIFF_FORMAT_NAME_STATUS |
2446 DIFF_FORMAT_CHECKDIFF |
2447 DIFF_FORMAT_NO_OUTPUT))
2448 options->output_format &= ~(DIFF_FORMAT_RAW |
2449 DIFF_FORMAT_NUMSTAT |
2450 DIFF_FORMAT_DIFFSTAT |
2451 DIFF_FORMAT_SHORTSTAT |
2452 DIFF_FORMAT_DIRSTAT |
2453 DIFF_FORMAT_SUMMARY |
2454 DIFF_FORMAT_PATCH);
2457 * These cases always need recursive; we do not drop caller-supplied
2458 * recursive bits for other formats here.
2460 if (options->output_format & (DIFF_FORMAT_PATCH |
2461 DIFF_FORMAT_NUMSTAT |
2462 DIFF_FORMAT_DIFFSTAT |
2463 DIFF_FORMAT_SHORTSTAT |
2464 DIFF_FORMAT_DIRSTAT |
2465 DIFF_FORMAT_SUMMARY |
2466 DIFF_FORMAT_CHECKDIFF))
2467 DIFF_OPT_SET(options, RECURSIVE);
2469 * Also pickaxe would not work very well if you do not say recursive
2471 if (options->pickaxe)
2472 DIFF_OPT_SET(options, RECURSIVE);
2474 if (options->detect_rename && options->rename_limit < 0)
2475 options->rename_limit = diff_rename_limit_default;
2476 if (options->setup & DIFF_SETUP_USE_CACHE) {
2477 if (!active_cache)
2478 /* read-cache does not die even when it fails
2479 * so it is safe for us to do this here. Also
2480 * it does not smudge active_cache or active_nr
2481 * when it fails, so we do not have to worry about
2482 * cleaning it up ourselves either.
2484 read_cache();
2486 if (options->abbrev <= 0 || 40 < options->abbrev)
2487 options->abbrev = 40; /* full */
2490 * It does not make sense to show the first hit we happened
2491 * to have found. It does not make sense not to return with
2492 * exit code in such a case either.
2494 if (DIFF_OPT_TST(options, QUICK)) {
2495 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2496 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2499 return 0;
2502 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2504 char c, *eq;
2505 int len;
2507 if (*arg != '-')
2508 return 0;
2509 c = *++arg;
2510 if (!c)
2511 return 0;
2512 if (c == arg_short) {
2513 c = *++arg;
2514 if (!c)
2515 return 1;
2516 if (val && isdigit(c)) {
2517 char *end;
2518 int n = strtoul(arg, &end, 10);
2519 if (*end)
2520 return 0;
2521 *val = n;
2522 return 1;
2524 return 0;
2526 if (c != '-')
2527 return 0;
2528 arg++;
2529 eq = strchr(arg, '=');
2530 if (eq)
2531 len = eq - arg;
2532 else
2533 len = strlen(arg);
2534 if (!len || strncmp(arg, arg_long, len))
2535 return 0;
2536 if (eq) {
2537 int n;
2538 char *end;
2539 if (!isdigit(*++eq))
2540 return 0;
2541 n = strtoul(eq, &end, 10);
2542 if (*end)
2543 return 0;
2544 *val = n;
2546 return 1;
2549 static int diff_scoreopt_parse(const char *opt);
2551 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2553 const char *arg = av[0];
2555 /* Output format options */
2556 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2557 options->output_format |= DIFF_FORMAT_PATCH;
2558 else if (opt_arg(arg, 'U', "unified", &options->context))
2559 options->output_format |= DIFF_FORMAT_PATCH;
2560 else if (!strcmp(arg, "--raw"))
2561 options->output_format |= DIFF_FORMAT_RAW;
2562 else if (!strcmp(arg, "--patch-with-raw"))
2563 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2564 else if (!strcmp(arg, "--numstat"))
2565 options->output_format |= DIFF_FORMAT_NUMSTAT;
2566 else if (!strcmp(arg, "--shortstat"))
2567 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2568 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2569 options->output_format |= DIFF_FORMAT_DIRSTAT;
2570 else if (!strcmp(arg, "--cumulative")) {
2571 options->output_format |= DIFF_FORMAT_DIRSTAT;
2572 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2573 } else if (opt_arg(arg, 0, "dirstat-by-file",
2574 &options->dirstat_percent)) {
2575 options->output_format |= DIFF_FORMAT_DIRSTAT;
2576 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2578 else if (!strcmp(arg, "--check"))
2579 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2580 else if (!strcmp(arg, "--summary"))
2581 options->output_format |= DIFF_FORMAT_SUMMARY;
2582 else if (!strcmp(arg, "--patch-with-stat"))
2583 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2584 else if (!strcmp(arg, "--name-only"))
2585 options->output_format |= DIFF_FORMAT_NAME;
2586 else if (!strcmp(arg, "--name-status"))
2587 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2588 else if (!strcmp(arg, "-s"))
2589 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2590 else if (!prefixcmp(arg, "--stat")) {
2591 char *end;
2592 int width = options->stat_width;
2593 int name_width = options->stat_name_width;
2594 arg += 6;
2595 end = (char *)arg;
2597 switch (*arg) {
2598 case '-':
2599 if (!prefixcmp(arg, "-width="))
2600 width = strtoul(arg + 7, &end, 10);
2601 else if (!prefixcmp(arg, "-name-width="))
2602 name_width = strtoul(arg + 12, &end, 10);
2603 break;
2604 case '=':
2605 width = strtoul(arg+1, &end, 10);
2606 if (*end == ',')
2607 name_width = strtoul(end+1, &end, 10);
2610 /* Important! This checks all the error cases! */
2611 if (*end)
2612 return 0;
2613 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2614 options->stat_name_width = name_width;
2615 options->stat_width = width;
2618 /* renames options */
2619 else if (!prefixcmp(arg, "-B")) {
2620 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2621 return -1;
2623 else if (!prefixcmp(arg, "-M")) {
2624 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2625 return -1;
2626 options->detect_rename = DIFF_DETECT_RENAME;
2628 else if (!prefixcmp(arg, "-C")) {
2629 if (options->detect_rename == DIFF_DETECT_COPY)
2630 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2631 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2632 return -1;
2633 options->detect_rename = DIFF_DETECT_COPY;
2635 else if (!strcmp(arg, "--no-renames"))
2636 options->detect_rename = 0;
2637 else if (!strcmp(arg, "--relative"))
2638 DIFF_OPT_SET(options, RELATIVE_NAME);
2639 else if (!prefixcmp(arg, "--relative=")) {
2640 DIFF_OPT_SET(options, RELATIVE_NAME);
2641 options->prefix = arg + 11;
2644 /* xdiff options */
2645 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2646 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2647 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2648 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2649 else if (!strcmp(arg, "--ignore-space-at-eol"))
2650 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2651 else if (!strcmp(arg, "--patience"))
2652 DIFF_XDL_SET(options, PATIENCE_DIFF);
2654 /* flags options */
2655 else if (!strcmp(arg, "--binary")) {
2656 options->output_format |= DIFF_FORMAT_PATCH;
2657 DIFF_OPT_SET(options, BINARY);
2659 else if (!strcmp(arg, "--full-index"))
2660 DIFF_OPT_SET(options, FULL_INDEX);
2661 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2662 DIFF_OPT_SET(options, TEXT);
2663 else if (!strcmp(arg, "-R"))
2664 DIFF_OPT_SET(options, REVERSE_DIFF);
2665 else if (!strcmp(arg, "--find-copies-harder"))
2666 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2667 else if (!strcmp(arg, "--follow"))
2668 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2669 else if (!strcmp(arg, "--color"))
2670 DIFF_OPT_SET(options, COLOR_DIFF);
2671 else if (!strcmp(arg, "--no-color"))
2672 DIFF_OPT_CLR(options, COLOR_DIFF);
2673 else if (!strcmp(arg, "--color-words")) {
2674 DIFF_OPT_SET(options, COLOR_DIFF);
2675 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2677 else if (!prefixcmp(arg, "--color-words=")) {
2678 DIFF_OPT_SET(options, COLOR_DIFF);
2679 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2680 options->word_regex = arg + 14;
2682 else if (!strcmp(arg, "--exit-code"))
2683 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2684 else if (!strcmp(arg, "--quiet"))
2685 DIFF_OPT_SET(options, QUICK);
2686 else if (!strcmp(arg, "--ext-diff"))
2687 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2688 else if (!strcmp(arg, "--no-ext-diff"))
2689 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2690 else if (!strcmp(arg, "--textconv"))
2691 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2692 else if (!strcmp(arg, "--no-textconv"))
2693 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2694 else if (!strcmp(arg, "--ignore-submodules"))
2695 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2697 /* misc options */
2698 else if (!strcmp(arg, "-z"))
2699 options->line_termination = 0;
2700 else if (!prefixcmp(arg, "-l"))
2701 options->rename_limit = strtoul(arg+2, NULL, 10);
2702 else if (!prefixcmp(arg, "-S"))
2703 options->pickaxe = arg + 2;
2704 else if (!strcmp(arg, "--pickaxe-all"))
2705 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2706 else if (!strcmp(arg, "--pickaxe-regex"))
2707 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2708 else if (!prefixcmp(arg, "-O"))
2709 options->orderfile = arg + 2;
2710 else if (!prefixcmp(arg, "--diff-filter="))
2711 options->filter = arg + 14;
2712 else if (!strcmp(arg, "--abbrev"))
2713 options->abbrev = DEFAULT_ABBREV;
2714 else if (!prefixcmp(arg, "--abbrev=")) {
2715 options->abbrev = strtoul(arg + 9, NULL, 10);
2716 if (options->abbrev < MINIMUM_ABBREV)
2717 options->abbrev = MINIMUM_ABBREV;
2718 else if (40 < options->abbrev)
2719 options->abbrev = 40;
2721 else if (!prefixcmp(arg, "--src-prefix="))
2722 options->a_prefix = arg + 13;
2723 else if (!prefixcmp(arg, "--dst-prefix="))
2724 options->b_prefix = arg + 13;
2725 else if (!strcmp(arg, "--no-prefix"))
2726 options->a_prefix = options->b_prefix = "";
2727 else if (opt_arg(arg, '\0', "inter-hunk-context",
2728 &options->interhunkcontext))
2730 else if (!prefixcmp(arg, "--output=")) {
2731 options->file = fopen(arg + strlen("--output="), "w");
2732 options->close_file = 1;
2733 } else
2734 return 0;
2735 return 1;
2738 static int parse_num(const char **cp_p)
2740 unsigned long num, scale;
2741 int ch, dot;
2742 const char *cp = *cp_p;
2744 num = 0;
2745 scale = 1;
2746 dot = 0;
2747 for (;;) {
2748 ch = *cp;
2749 if ( !dot && ch == '.' ) {
2750 scale = 1;
2751 dot = 1;
2752 } else if ( ch == '%' ) {
2753 scale = dot ? scale*100 : 100;
2754 cp++; /* % is always at the end */
2755 break;
2756 } else if ( ch >= '0' && ch <= '9' ) {
2757 if ( scale < 100000 ) {
2758 scale *= 10;
2759 num = (num*10) + (ch-'0');
2761 } else {
2762 break;
2764 cp++;
2766 *cp_p = cp;
2768 /* user says num divided by scale and we say internally that
2769 * is MAX_SCORE * num / scale.
2771 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2774 static int diff_scoreopt_parse(const char *opt)
2776 int opt1, opt2, cmd;
2778 if (*opt++ != '-')
2779 return -1;
2780 cmd = *opt++;
2781 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2782 return -1; /* that is not a -M, -C nor -B option */
2784 opt1 = parse_num(&opt);
2785 if (cmd != 'B')
2786 opt2 = 0;
2787 else {
2788 if (*opt == 0)
2789 opt2 = 0;
2790 else if (*opt != '/')
2791 return -1; /* we expect -B80/99 or -B80 */
2792 else {
2793 opt++;
2794 opt2 = parse_num(&opt);
2797 if (*opt != 0)
2798 return -1;
2799 return opt1 | (opt2 << 16);
2802 struct diff_queue_struct diff_queued_diff;
2804 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2806 if (queue->alloc <= queue->nr) {
2807 queue->alloc = alloc_nr(queue->alloc);
2808 queue->queue = xrealloc(queue->queue,
2809 sizeof(dp) * queue->alloc);
2811 queue->queue[queue->nr++] = dp;
2814 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2815 struct diff_filespec *one,
2816 struct diff_filespec *two)
2818 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2819 dp->one = one;
2820 dp->two = two;
2821 if (queue)
2822 diff_q(queue, dp);
2823 return dp;
2826 void diff_free_filepair(struct diff_filepair *p)
2828 free_filespec(p->one);
2829 free_filespec(p->two);
2830 free(p);
2833 /* This is different from find_unique_abbrev() in that
2834 * it stuffs the result with dots for alignment.
2836 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2838 int abblen;
2839 const char *abbrev;
2840 if (len == 40)
2841 return sha1_to_hex(sha1);
2843 abbrev = find_unique_abbrev(sha1, len);
2844 abblen = strlen(abbrev);
2845 if (abblen < 37) {
2846 static char hex[41];
2847 if (len < abblen && abblen <= len + 2)
2848 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2849 else
2850 sprintf(hex, "%s...", abbrev);
2851 return hex;
2853 return sha1_to_hex(sha1);
2856 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2858 int line_termination = opt->line_termination;
2859 int inter_name_termination = line_termination ? '\t' : '\0';
2861 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2862 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2863 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2864 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2866 if (p->score) {
2867 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2868 inter_name_termination);
2869 } else {
2870 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2873 if (p->status == DIFF_STATUS_COPIED ||
2874 p->status == DIFF_STATUS_RENAMED) {
2875 const char *name_a, *name_b;
2876 name_a = p->one->path;
2877 name_b = p->two->path;
2878 strip_prefix(opt->prefix_length, &name_a, &name_b);
2879 write_name_quoted(name_a, opt->file, inter_name_termination);
2880 write_name_quoted(name_b, opt->file, line_termination);
2881 } else {
2882 const char *name_a, *name_b;
2883 name_a = p->one->mode ? p->one->path : p->two->path;
2884 name_b = NULL;
2885 strip_prefix(opt->prefix_length, &name_a, &name_b);
2886 write_name_quoted(name_a, opt->file, line_termination);
2890 int diff_unmodified_pair(struct diff_filepair *p)
2892 /* This function is written stricter than necessary to support
2893 * the currently implemented transformers, but the idea is to
2894 * let transformers to produce diff_filepairs any way they want,
2895 * and filter and clean them up here before producing the output.
2897 struct diff_filespec *one = p->one, *two = p->two;
2899 if (DIFF_PAIR_UNMERGED(p))
2900 return 0; /* unmerged is interesting */
2902 /* deletion, addition, mode or type change
2903 * and rename are all interesting.
2905 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2906 DIFF_PAIR_MODE_CHANGED(p) ||
2907 strcmp(one->path, two->path))
2908 return 0;
2910 /* both are valid and point at the same path. that is, we are
2911 * dealing with a change.
2913 if (one->sha1_valid && two->sha1_valid &&
2914 !hashcmp(one->sha1, two->sha1))
2915 return 1; /* no change */
2916 if (!one->sha1_valid && !two->sha1_valid)
2917 return 1; /* both look at the same file on the filesystem. */
2918 return 0;
2921 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2923 if (diff_unmodified_pair(p))
2924 return;
2926 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2927 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2928 return; /* no tree diffs in patch format */
2930 run_diff(p, o);
2933 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2934 struct diffstat_t *diffstat)
2936 if (diff_unmodified_pair(p))
2937 return;
2939 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2940 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2941 return; /* no tree diffs in patch format */
2943 run_diffstat(p, o, diffstat);
2946 static void diff_flush_checkdiff(struct diff_filepair *p,
2947 struct diff_options *o)
2949 if (diff_unmodified_pair(p))
2950 return;
2952 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2953 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2954 return; /* no tree diffs in patch format */
2956 run_checkdiff(p, o);
2959 int diff_queue_is_empty(void)
2961 struct diff_queue_struct *q = &diff_queued_diff;
2962 int i;
2963 for (i = 0; i < q->nr; i++)
2964 if (!diff_unmodified_pair(q->queue[i]))
2965 return 0;
2966 return 1;
2969 #if DIFF_DEBUG
2970 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2972 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2973 x, one ? one : "",
2974 s->path,
2975 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2976 s->mode,
2977 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2978 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2979 x, one ? one : "",
2980 s->size, s->xfrm_flags);
2983 void diff_debug_filepair(const struct diff_filepair *p, int i)
2985 diff_debug_filespec(p->one, i, "one");
2986 diff_debug_filespec(p->two, i, "two");
2987 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2988 p->score, p->status ? p->status : '?',
2989 p->one->rename_used, p->broken_pair);
2992 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2994 int i;
2995 if (msg)
2996 fprintf(stderr, "%s\n", msg);
2997 fprintf(stderr, "q->nr = %d\n", q->nr);
2998 for (i = 0; i < q->nr; i++) {
2999 struct diff_filepair *p = q->queue[i];
3000 diff_debug_filepair(p, i);
3003 #endif
3005 static void diff_resolve_rename_copy(void)
3007 int i;
3008 struct diff_filepair *p;
3009 struct diff_queue_struct *q = &diff_queued_diff;
3011 diff_debug_queue("resolve-rename-copy", q);
3013 for (i = 0; i < q->nr; i++) {
3014 p = q->queue[i];
3015 p->status = 0; /* undecided */
3016 if (DIFF_PAIR_UNMERGED(p))
3017 p->status = DIFF_STATUS_UNMERGED;
3018 else if (!DIFF_FILE_VALID(p->one))
3019 p->status = DIFF_STATUS_ADDED;
3020 else if (!DIFF_FILE_VALID(p->two))
3021 p->status = DIFF_STATUS_DELETED;
3022 else if (DIFF_PAIR_TYPE_CHANGED(p))
3023 p->status = DIFF_STATUS_TYPE_CHANGED;
3025 /* from this point on, we are dealing with a pair
3026 * whose both sides are valid and of the same type, i.e.
3027 * either in-place edit or rename/copy edit.
3029 else if (DIFF_PAIR_RENAME(p)) {
3031 * A rename might have re-connected a broken
3032 * pair up, causing the pathnames to be the
3033 * same again. If so, that's not a rename at
3034 * all, just a modification..
3036 * Otherwise, see if this source was used for
3037 * multiple renames, in which case we decrement
3038 * the count, and call it a copy.
3040 if (!strcmp(p->one->path, p->two->path))
3041 p->status = DIFF_STATUS_MODIFIED;
3042 else if (--p->one->rename_used > 0)
3043 p->status = DIFF_STATUS_COPIED;
3044 else
3045 p->status = DIFF_STATUS_RENAMED;
3047 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3048 p->one->mode != p->two->mode ||
3049 is_null_sha1(p->one->sha1))
3050 p->status = DIFF_STATUS_MODIFIED;
3051 else {
3052 /* This is a "no-change" entry and should not
3053 * happen anymore, but prepare for broken callers.
3055 error("feeding unmodified %s to diffcore",
3056 p->one->path);
3057 p->status = DIFF_STATUS_UNKNOWN;
3060 diff_debug_queue("resolve-rename-copy done", q);
3063 static int check_pair_status(struct diff_filepair *p)
3065 switch (p->status) {
3066 case DIFF_STATUS_UNKNOWN:
3067 return 0;
3068 case 0:
3069 die("internal error in diff-resolve-rename-copy");
3070 default:
3071 return 1;
3075 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3077 int fmt = opt->output_format;
3079 if (fmt & DIFF_FORMAT_CHECKDIFF)
3080 diff_flush_checkdiff(p, opt);
3081 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3082 diff_flush_raw(p, opt);
3083 else if (fmt & DIFF_FORMAT_NAME) {
3084 const char *name_a, *name_b;
3085 name_a = p->two->path;
3086 name_b = NULL;
3087 strip_prefix(opt->prefix_length, &name_a, &name_b);
3088 write_name_quoted(name_a, opt->file, opt->line_termination);
3092 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3094 if (fs->mode)
3095 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3096 else
3097 fprintf(file, " %s ", newdelete);
3098 write_name_quoted(fs->path, file, '\n');
3102 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3104 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3105 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3106 show_name ? ' ' : '\n');
3107 if (show_name) {
3108 write_name_quoted(p->two->path, file, '\n');
3113 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3115 char *names = pprint_rename(p->one->path, p->two->path);
3117 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3118 free(names);
3119 show_mode_change(file, p, 0);
3122 static void diff_summary(FILE *file, struct diff_filepair *p)
3124 switch(p->status) {
3125 case DIFF_STATUS_DELETED:
3126 show_file_mode_name(file, "delete", p->one);
3127 break;
3128 case DIFF_STATUS_ADDED:
3129 show_file_mode_name(file, "create", p->two);
3130 break;
3131 case DIFF_STATUS_COPIED:
3132 show_rename_copy(file, "copy", p);
3133 break;
3134 case DIFF_STATUS_RENAMED:
3135 show_rename_copy(file, "rename", p);
3136 break;
3137 default:
3138 if (p->score) {
3139 fputs(" rewrite ", file);
3140 write_name_quoted(p->two->path, file, ' ');
3141 fprintf(file, "(%d%%)\n", similarity_index(p));
3143 show_mode_change(file, p, !p->score);
3144 break;
3148 struct patch_id_t {
3149 git_SHA_CTX *ctx;
3150 int patchlen;
3153 static int remove_space(char *line, int len)
3155 int i;
3156 char *dst = line;
3157 unsigned char c;
3159 for (i = 0; i < len; i++)
3160 if (!isspace((c = line[i])))
3161 *dst++ = c;
3163 return dst - line;
3166 static void patch_id_consume(void *priv, char *line, unsigned long len)
3168 struct patch_id_t *data = priv;
3169 int new_len;
3171 /* Ignore line numbers when computing the SHA1 of the patch */
3172 if (!prefixcmp(line, "@@ -"))
3173 return;
3175 new_len = remove_space(line, len);
3177 git_SHA1_Update(data->ctx, line, new_len);
3178 data->patchlen += new_len;
3181 /* returns 0 upon success, and writes result into sha1 */
3182 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3184 struct diff_queue_struct *q = &diff_queued_diff;
3185 int i;
3186 git_SHA_CTX ctx;
3187 struct patch_id_t data;
3188 char buffer[PATH_MAX * 4 + 20];
3190 git_SHA1_Init(&ctx);
3191 memset(&data, 0, sizeof(struct patch_id_t));
3192 data.ctx = &ctx;
3194 for (i = 0; i < q->nr; i++) {
3195 xpparam_t xpp;
3196 xdemitconf_t xecfg;
3197 xdemitcb_t ecb;
3198 mmfile_t mf1, mf2;
3199 struct diff_filepair *p = q->queue[i];
3200 int len1, len2;
3202 memset(&xpp, 0, sizeof(xpp));
3203 memset(&xecfg, 0, sizeof(xecfg));
3204 if (p->status == 0)
3205 return error("internal diff status error");
3206 if (p->status == DIFF_STATUS_UNKNOWN)
3207 continue;
3208 if (diff_unmodified_pair(p))
3209 continue;
3210 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3211 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3212 continue;
3213 if (DIFF_PAIR_UNMERGED(p))
3214 continue;
3216 diff_fill_sha1_info(p->one);
3217 diff_fill_sha1_info(p->two);
3218 if (fill_mmfile(&mf1, p->one) < 0 ||
3219 fill_mmfile(&mf2, p->two) < 0)
3220 return error("unable to read files to diff");
3222 len1 = remove_space(p->one->path, strlen(p->one->path));
3223 len2 = remove_space(p->two->path, strlen(p->two->path));
3224 if (p->one->mode == 0)
3225 len1 = snprintf(buffer, sizeof(buffer),
3226 "diff--gita/%.*sb/%.*s"
3227 "newfilemode%06o"
3228 "---/dev/null"
3229 "+++b/%.*s",
3230 len1, p->one->path,
3231 len2, p->two->path,
3232 p->two->mode,
3233 len2, p->two->path);
3234 else if (p->two->mode == 0)
3235 len1 = snprintf(buffer, sizeof(buffer),
3236 "diff--gita/%.*sb/%.*s"
3237 "deletedfilemode%06o"
3238 "---a/%.*s"
3239 "+++/dev/null",
3240 len1, p->one->path,
3241 len2, p->two->path,
3242 p->one->mode,
3243 len1, p->one->path);
3244 else
3245 len1 = snprintf(buffer, sizeof(buffer),
3246 "diff--gita/%.*sb/%.*s"
3247 "---a/%.*s"
3248 "+++b/%.*s",
3249 len1, p->one->path,
3250 len2, p->two->path,
3251 len1, p->one->path,
3252 len2, p->two->path);
3253 git_SHA1_Update(&ctx, buffer, len1);
3255 xpp.flags = XDF_NEED_MINIMAL;
3256 xecfg.ctxlen = 3;
3257 xecfg.flags = XDL_EMIT_FUNCNAMES;
3258 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3259 &xpp, &xecfg, &ecb);
3262 git_SHA1_Final(sha1, &ctx);
3263 return 0;
3266 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3268 struct diff_queue_struct *q = &diff_queued_diff;
3269 int i;
3270 int result = diff_get_patch_id(options, sha1);
3272 for (i = 0; i < q->nr; i++)
3273 diff_free_filepair(q->queue[i]);
3275 free(q->queue);
3276 q->queue = NULL;
3277 q->nr = q->alloc = 0;
3279 return result;
3282 static int is_summary_empty(const struct diff_queue_struct *q)
3284 int i;
3286 for (i = 0; i < q->nr; i++) {
3287 const struct diff_filepair *p = q->queue[i];
3289 switch (p->status) {
3290 case DIFF_STATUS_DELETED:
3291 case DIFF_STATUS_ADDED:
3292 case DIFF_STATUS_COPIED:
3293 case DIFF_STATUS_RENAMED:
3294 return 0;
3295 default:
3296 if (p->score)
3297 return 0;
3298 if (p->one->mode && p->two->mode &&
3299 p->one->mode != p->two->mode)
3300 return 0;
3301 break;
3304 return 1;
3307 void diff_flush(struct diff_options *options)
3309 struct diff_queue_struct *q = &diff_queued_diff;
3310 int i, output_format = options->output_format;
3311 int separator = 0;
3314 * Order: raw, stat, summary, patch
3315 * or: name/name-status/checkdiff (other bits clear)
3317 if (!q->nr)
3318 goto free_queue;
3320 if (output_format & (DIFF_FORMAT_RAW |
3321 DIFF_FORMAT_NAME |
3322 DIFF_FORMAT_NAME_STATUS |
3323 DIFF_FORMAT_CHECKDIFF)) {
3324 for (i = 0; i < q->nr; i++) {
3325 struct diff_filepair *p = q->queue[i];
3326 if (check_pair_status(p))
3327 flush_one_pair(p, options);
3329 separator++;
3332 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3333 struct diffstat_t diffstat;
3335 memset(&diffstat, 0, sizeof(struct diffstat_t));
3336 for (i = 0; i < q->nr; i++) {
3337 struct diff_filepair *p = q->queue[i];
3338 if (check_pair_status(p))
3339 diff_flush_stat(p, options, &diffstat);
3341 if (output_format & DIFF_FORMAT_NUMSTAT)
3342 show_numstat(&diffstat, options);
3343 if (output_format & DIFF_FORMAT_DIFFSTAT)
3344 show_stats(&diffstat, options);
3345 if (output_format & DIFF_FORMAT_SHORTSTAT)
3346 show_shortstats(&diffstat, options);
3347 free_diffstat_info(&diffstat);
3348 separator++;
3350 if (output_format & DIFF_FORMAT_DIRSTAT)
3351 show_dirstat(options);
3353 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3354 for (i = 0; i < q->nr; i++)
3355 diff_summary(options->file, q->queue[i]);
3356 separator++;
3359 if (output_format & DIFF_FORMAT_PATCH) {
3360 if (separator) {
3361 putc(options->line_termination, options->file);
3362 if (options->stat_sep) {
3363 /* attach patch instead of inline */
3364 fputs(options->stat_sep, options->file);
3368 for (i = 0; i < q->nr; i++) {
3369 struct diff_filepair *p = q->queue[i];
3370 if (check_pair_status(p))
3371 diff_flush_patch(p, options);
3375 if (output_format & DIFF_FORMAT_CALLBACK)
3376 options->format_callback(q, options, options->format_callback_data);
3378 for (i = 0; i < q->nr; i++)
3379 diff_free_filepair(q->queue[i]);
3380 free_queue:
3381 free(q->queue);
3382 q->queue = NULL;
3383 q->nr = q->alloc = 0;
3384 if (options->close_file)
3385 fclose(options->file);
3388 * Report the content-level differences with HAS_CHANGES;
3389 * diff_addremove/diff_change does not set the bit when
3390 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3392 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3393 if (options->found_changes)
3394 DIFF_OPT_SET(options, HAS_CHANGES);
3395 else
3396 DIFF_OPT_CLR(options, HAS_CHANGES);
3400 static void diffcore_apply_filter(const char *filter)
3402 int i;
3403 struct diff_queue_struct *q = &diff_queued_diff;
3404 struct diff_queue_struct outq;
3405 outq.queue = NULL;
3406 outq.nr = outq.alloc = 0;
3408 if (!filter)
3409 return;
3411 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3412 int found;
3413 for (i = found = 0; !found && i < q->nr; i++) {
3414 struct diff_filepair *p = q->queue[i];
3415 if (((p->status == DIFF_STATUS_MODIFIED) &&
3416 ((p->score &&
3417 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3418 (!p->score &&
3419 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3420 ((p->status != DIFF_STATUS_MODIFIED) &&
3421 strchr(filter, p->status)))
3422 found++;
3424 if (found)
3425 return;
3427 /* otherwise we will clear the whole queue
3428 * by copying the empty outq at the end of this
3429 * function, but first clear the current entries
3430 * in the queue.
3432 for (i = 0; i < q->nr; i++)
3433 diff_free_filepair(q->queue[i]);
3435 else {
3436 /* Only the matching ones */
3437 for (i = 0; i < q->nr; i++) {
3438 struct diff_filepair *p = q->queue[i];
3440 if (((p->status == DIFF_STATUS_MODIFIED) &&
3441 ((p->score &&
3442 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3443 (!p->score &&
3444 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3445 ((p->status != DIFF_STATUS_MODIFIED) &&
3446 strchr(filter, p->status)))
3447 diff_q(&outq, p);
3448 else
3449 diff_free_filepair(p);
3452 free(q->queue);
3453 *q = outq;
3456 /* Check whether two filespecs with the same mode and size are identical */
3457 static int diff_filespec_is_identical(struct diff_filespec *one,
3458 struct diff_filespec *two)
3460 if (S_ISGITLINK(one->mode))
3461 return 0;
3462 if (diff_populate_filespec(one, 0))
3463 return 0;
3464 if (diff_populate_filespec(two, 0))
3465 return 0;
3466 return !memcmp(one->data, two->data, one->size);
3469 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3471 int i;
3472 struct diff_queue_struct *q = &diff_queued_diff;
3473 struct diff_queue_struct outq;
3474 outq.queue = NULL;
3475 outq.nr = outq.alloc = 0;
3477 for (i = 0; i < q->nr; i++) {
3478 struct diff_filepair *p = q->queue[i];
3481 * 1. Entries that come from stat info dirtyness
3482 * always have both sides (iow, not create/delete),
3483 * one side of the object name is unknown, with
3484 * the same mode and size. Keep the ones that
3485 * do not match these criteria. They have real
3486 * differences.
3488 * 2. At this point, the file is known to be modified,
3489 * with the same mode and size, and the object
3490 * name of one side is unknown. Need to inspect
3491 * the identical contents.
3493 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3494 !DIFF_FILE_VALID(p->two) ||
3495 (p->one->sha1_valid && p->two->sha1_valid) ||
3496 (p->one->mode != p->two->mode) ||
3497 diff_populate_filespec(p->one, 1) ||
3498 diff_populate_filespec(p->two, 1) ||
3499 (p->one->size != p->two->size) ||
3500 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3501 diff_q(&outq, p);
3502 else {
3504 * The caller can subtract 1 from skip_stat_unmatch
3505 * to determine how many paths were dirty only
3506 * due to stat info mismatch.
3508 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3509 diffopt->skip_stat_unmatch++;
3510 diff_free_filepair(p);
3513 free(q->queue);
3514 *q = outq;
3517 void diffcore_std(struct diff_options *options)
3519 if (options->skip_stat_unmatch)
3520 diffcore_skip_stat_unmatch(options);
3521 if (options->break_opt != -1)
3522 diffcore_break(options->break_opt);
3523 if (options->detect_rename)
3524 diffcore_rename(options);
3525 if (options->break_opt != -1)
3526 diffcore_merge_broken();
3527 if (options->pickaxe)
3528 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3529 if (options->orderfile)
3530 diffcore_order(options->orderfile);
3531 diff_resolve_rename_copy();
3532 diffcore_apply_filter(options->filter);
3534 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3535 DIFF_OPT_SET(options, HAS_CHANGES);
3536 else
3537 DIFF_OPT_CLR(options, HAS_CHANGES);
3540 int diff_result_code(struct diff_options *opt, int status)
3542 int result = 0;
3543 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3544 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3545 return status;
3546 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3547 DIFF_OPT_TST(opt, HAS_CHANGES))
3548 result |= 01;
3549 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3550 DIFF_OPT_TST(opt, CHECK_FAILED))
3551 result |= 02;
3552 return result;
3555 void diff_addremove(struct diff_options *options,
3556 int addremove, unsigned mode,
3557 const unsigned char *sha1,
3558 const char *concatpath)
3560 struct diff_filespec *one, *two;
3562 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3563 return;
3565 /* This may look odd, but it is a preparation for
3566 * feeding "there are unchanged files which should
3567 * not produce diffs, but when you are doing copy
3568 * detection you would need them, so here they are"
3569 * entries to the diff-core. They will be prefixed
3570 * with something like '=' or '*' (I haven't decided
3571 * which but should not make any difference).
3572 * Feeding the same new and old to diff_change()
3573 * also has the same effect.
3574 * Before the final output happens, they are pruned after
3575 * merged into rename/copy pairs as appropriate.
3577 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3578 addremove = (addremove == '+' ? '-' :
3579 addremove == '-' ? '+' : addremove);
3581 if (options->prefix &&
3582 strncmp(concatpath, options->prefix, options->prefix_length))
3583 return;
3585 one = alloc_filespec(concatpath);
3586 two = alloc_filespec(concatpath);
3588 if (addremove != '+')
3589 fill_filespec(one, sha1, mode);
3590 if (addremove != '-')
3591 fill_filespec(two, sha1, mode);
3593 diff_queue(&diff_queued_diff, one, two);
3594 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3595 DIFF_OPT_SET(options, HAS_CHANGES);
3598 void diff_change(struct diff_options *options,
3599 unsigned old_mode, unsigned new_mode,
3600 const unsigned char *old_sha1,
3601 const unsigned char *new_sha1,
3602 const char *concatpath)
3604 struct diff_filespec *one, *two;
3606 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3607 && S_ISGITLINK(new_mode))
3608 return;
3610 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3611 unsigned tmp;
3612 const unsigned char *tmp_c;
3613 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3614 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3617 if (options->prefix &&
3618 strncmp(concatpath, options->prefix, options->prefix_length))
3619 return;
3621 one = alloc_filespec(concatpath);
3622 two = alloc_filespec(concatpath);
3623 fill_filespec(one, old_sha1, old_mode);
3624 fill_filespec(two, new_sha1, new_mode);
3626 diff_queue(&diff_queued_diff, one, two);
3627 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3628 DIFF_OPT_SET(options, HAS_CHANGES);
3631 void diff_unmerge(struct diff_options *options,
3632 const char *path,
3633 unsigned mode, const unsigned char *sha1)
3635 struct diff_filespec *one, *two;
3637 if (options->prefix &&
3638 strncmp(path, options->prefix, options->prefix_length))
3639 return;
3641 one = alloc_filespec(path);
3642 two = alloc_filespec(path);
3643 fill_filespec(one, sha1, mode);
3644 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3647 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3648 size_t *outsize)
3650 struct diff_tempfile *temp;
3651 const char *argv[3];
3652 const char **arg = argv;
3653 struct child_process child;
3654 struct strbuf buf = STRBUF_INIT;
3656 temp = prepare_temp_file(spec->path, spec);
3657 *arg++ = pgm;
3658 *arg++ = temp->name;
3659 *arg = NULL;
3661 memset(&child, 0, sizeof(child));
3662 child.argv = argv;
3663 child.out = -1;
3664 if (start_command(&child) != 0 ||
3665 strbuf_read(&buf, child.out, 0) < 0 ||
3666 finish_command(&child) != 0) {
3667 strbuf_release(&buf);
3668 remove_tempfile();
3669 error("error running textconv command '%s'", pgm);
3670 return NULL;
3672 remove_tempfile();
3674 return strbuf_detach(&buf, outsize);