git-svn: add support for using svnsync properties
[git/jnareb-git/bp-gitweb.git] / diff.c
blob5ecb12225560e19142ad5b2936b311a9fce2a16a
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"
12 #ifdef NO_FAST_WORKING_DIRECTORY
13 #define FAST_WORKING_DIRECTORY 0
14 #else
15 #define FAST_WORKING_DIRECTORY 1
16 #endif
18 static int use_size_cache;
20 static int diff_detect_rename_default;
21 static int diff_rename_limit_default = -1;
22 static int diff_use_color_default;
24 static char diff_colors[][COLOR_MAXLEN] = {
25 "\033[m", /* reset */
26 "", /* PLAIN (normal) */
27 "\033[1m", /* METAINFO (bold) */
28 "\033[36m", /* FRAGINFO (cyan) */
29 "\033[31m", /* OLD (red) */
30 "\033[32m", /* NEW (green) */
31 "\033[33m", /* COMMIT (yellow) */
32 "\033[41m", /* WHITESPACE (red background) */
35 static int parse_diff_color_slot(const char *var, int ofs)
37 if (!strcasecmp(var+ofs, "plain"))
38 return DIFF_PLAIN;
39 if (!strcasecmp(var+ofs, "meta"))
40 return DIFF_METAINFO;
41 if (!strcasecmp(var+ofs, "frag"))
42 return DIFF_FRAGINFO;
43 if (!strcasecmp(var+ofs, "old"))
44 return DIFF_FILE_OLD;
45 if (!strcasecmp(var+ofs, "new"))
46 return DIFF_FILE_NEW;
47 if (!strcasecmp(var+ofs, "commit"))
48 return DIFF_COMMIT;
49 if (!strcasecmp(var+ofs, "whitespace"))
50 return DIFF_WHITESPACE;
51 die("bad config variable '%s'", var);
55 * These are to give UI layer defaults.
56 * The core-level commands such as git-diff-files should
57 * never be affected by the setting of diff.renames
58 * the user happens to have in the configuration file.
60 int git_diff_ui_config(const char *var, const char *value)
62 if (!strcmp(var, "diff.renamelimit")) {
63 diff_rename_limit_default = git_config_int(var, value);
64 return 0;
66 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
67 diff_use_color_default = git_config_colorbool(var, value);
68 return 0;
70 if (!strcmp(var, "diff.renames")) {
71 if (!value)
72 diff_detect_rename_default = DIFF_DETECT_RENAME;
73 else if (!strcasecmp(value, "copies") ||
74 !strcasecmp(value, "copy"))
75 diff_detect_rename_default = DIFF_DETECT_COPY;
76 else if (git_config_bool(var,value))
77 diff_detect_rename_default = DIFF_DETECT_RENAME;
78 return 0;
80 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
81 int slot = parse_diff_color_slot(var, 11);
82 color_parse(value, var, diff_colors[slot]);
83 return 0;
85 return git_default_config(var, value);
88 static char *quote_one(const char *str)
90 int needlen;
91 char *xp;
93 if (!str)
94 return NULL;
95 needlen = quote_c_style(str, NULL, NULL, 0);
96 if (!needlen)
97 return xstrdup(str);
98 xp = xmalloc(needlen + 1);
99 quote_c_style(str, xp, NULL, 0);
100 return xp;
103 static char *quote_two(const char *one, const char *two)
105 int need_one = quote_c_style(one, NULL, NULL, 1);
106 int need_two = quote_c_style(two, NULL, NULL, 1);
107 char *xp;
109 if (need_one + need_two) {
110 if (!need_one) need_one = strlen(one);
111 if (!need_two) need_one = strlen(two);
113 xp = xmalloc(need_one + need_two + 3);
114 xp[0] = '"';
115 quote_c_style(one, xp + 1, NULL, 1);
116 quote_c_style(two, xp + need_one + 1, NULL, 1);
117 strcpy(xp + need_one + need_two + 1, "\"");
118 return xp;
120 need_one = strlen(one);
121 need_two = strlen(two);
122 xp = xmalloc(need_one + need_two + 1);
123 strcpy(xp, one);
124 strcpy(xp + need_one, two);
125 return xp;
128 static const char *external_diff(void)
130 static const char *external_diff_cmd = NULL;
131 static int done_preparing = 0;
133 if (done_preparing)
134 return external_diff_cmd;
135 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
136 done_preparing = 1;
137 return external_diff_cmd;
140 #define TEMPFILE_PATH_LEN 50
142 static struct diff_tempfile {
143 const char *name; /* filename external diff should read from */
144 char hex[41];
145 char mode[10];
146 char tmp_path[TEMPFILE_PATH_LEN];
147 } diff_temp[2];
149 static int count_lines(const char *data, int size)
151 int count, ch, completely_empty = 1, nl_just_seen = 0;
152 count = 0;
153 while (0 < size--) {
154 ch = *data++;
155 if (ch == '\n') {
156 count++;
157 nl_just_seen = 1;
158 completely_empty = 0;
160 else {
161 nl_just_seen = 0;
162 completely_empty = 0;
165 if (completely_empty)
166 return 0;
167 if (!nl_just_seen)
168 count++; /* no trailing newline */
169 return count;
172 static void print_line_count(int count)
174 switch (count) {
175 case 0:
176 printf("0,0");
177 break;
178 case 1:
179 printf("1");
180 break;
181 default:
182 printf("1,%d", count);
183 break;
187 static void copy_file(int prefix, const char *data, int size,
188 const char *set, const char *reset)
190 int ch, nl_just_seen = 1;
191 while (0 < size--) {
192 ch = *data++;
193 if (nl_just_seen) {
194 fputs(set, stdout);
195 putchar(prefix);
197 if (ch == '\n') {
198 nl_just_seen = 1;
199 fputs(reset, stdout);
200 } else
201 nl_just_seen = 0;
202 putchar(ch);
204 if (!nl_just_seen)
205 printf("%s\n\\ No newline at end of file\n", reset);
208 static void emit_rewrite_diff(const char *name_a,
209 const char *name_b,
210 struct diff_filespec *one,
211 struct diff_filespec *two,
212 int color_diff)
214 int lc_a, lc_b;
215 const char *name_a_tab, *name_b_tab;
216 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
217 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
218 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
219 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
220 const char *reset = diff_get_color(color_diff, DIFF_RESET);
222 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
223 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
225 diff_populate_filespec(one, 0);
226 diff_populate_filespec(two, 0);
227 lc_a = count_lines(one->data, one->size);
228 lc_b = count_lines(two->data, two->size);
229 printf("%s--- a/%s%s%s\n%s+++ b/%s%s%s\n%s@@ -",
230 metainfo, name_a, name_a_tab, reset,
231 metainfo, name_b, name_b_tab, reset, fraginfo);
232 print_line_count(lc_a);
233 printf(" +");
234 print_line_count(lc_b);
235 printf(" @@%s\n", reset);
236 if (lc_a)
237 copy_file('-', one->data, one->size, old, reset);
238 if (lc_b)
239 copy_file('+', two->data, two->size, new, reset);
242 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
244 if (!DIFF_FILE_VALID(one)) {
245 mf->ptr = (char *)""; /* does not matter */
246 mf->size = 0;
247 return 0;
249 else if (diff_populate_filespec(one, 0))
250 return -1;
251 mf->ptr = one->data;
252 mf->size = one->size;
253 return 0;
256 struct diff_words_buffer {
257 mmfile_t text;
258 long alloc;
259 long current; /* output pointer */
260 int suppressed_newline;
263 static void diff_words_append(char *line, unsigned long len,
264 struct diff_words_buffer *buffer)
266 if (buffer->text.size + len > buffer->alloc) {
267 buffer->alloc = (buffer->text.size + len) * 3 / 2;
268 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
270 line++;
271 len--;
272 memcpy(buffer->text.ptr + buffer->text.size, line, len);
273 buffer->text.size += len;
276 struct diff_words_data {
277 struct xdiff_emit_state xm;
278 struct diff_words_buffer minus, plus;
281 static void print_word(struct diff_words_buffer *buffer, int len, int color,
282 int suppress_newline)
284 const char *ptr;
285 int eol = 0;
287 if (len == 0)
288 return;
290 ptr = buffer->text.ptr + buffer->current;
291 buffer->current += len;
293 if (ptr[len - 1] == '\n') {
294 eol = 1;
295 len--;
298 fputs(diff_get_color(1, color), stdout);
299 fwrite(ptr, len, 1, stdout);
300 fputs(diff_get_color(1, DIFF_RESET), stdout);
302 if (eol) {
303 if (suppress_newline)
304 buffer->suppressed_newline = 1;
305 else
306 putchar('\n');
310 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
312 struct diff_words_data *diff_words = priv;
314 if (diff_words->minus.suppressed_newline) {
315 if (line[0] != '+')
316 putchar('\n');
317 diff_words->minus.suppressed_newline = 0;
320 len--;
321 switch (line[0]) {
322 case '-':
323 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
324 break;
325 case '+':
326 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
327 break;
328 case ' ':
329 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
330 diff_words->minus.current += len;
331 break;
335 /* this executes the word diff on the accumulated buffers */
336 static void diff_words_show(struct diff_words_data *diff_words)
338 xpparam_t xpp;
339 xdemitconf_t xecfg;
340 xdemitcb_t ecb;
341 mmfile_t minus, plus;
342 int i;
344 minus.size = diff_words->minus.text.size;
345 minus.ptr = xmalloc(minus.size);
346 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
347 for (i = 0; i < minus.size; i++)
348 if (isspace(minus.ptr[i]))
349 minus.ptr[i] = '\n';
350 diff_words->minus.current = 0;
352 plus.size = diff_words->plus.text.size;
353 plus.ptr = xmalloc(plus.size);
354 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
355 for (i = 0; i < plus.size; i++)
356 if (isspace(plus.ptr[i]))
357 plus.ptr[i] = '\n';
358 diff_words->plus.current = 0;
360 xpp.flags = XDF_NEED_MINIMAL;
361 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
362 xecfg.flags = 0;
363 ecb.outf = xdiff_outf;
364 ecb.priv = diff_words;
365 diff_words->xm.consume = fn_out_diff_words_aux;
366 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
368 free(minus.ptr);
369 free(plus.ptr);
370 diff_words->minus.text.size = diff_words->plus.text.size = 0;
372 if (diff_words->minus.suppressed_newline) {
373 putchar('\n');
374 diff_words->minus.suppressed_newline = 0;
378 struct emit_callback {
379 struct xdiff_emit_state xm;
380 int nparents, color_diff;
381 const char **label_path;
382 struct diff_words_data *diff_words;
385 static void free_diff_words_data(struct emit_callback *ecbdata)
387 if (ecbdata->diff_words) {
388 /* flush buffers */
389 if (ecbdata->diff_words->minus.text.size ||
390 ecbdata->diff_words->plus.text.size)
391 diff_words_show(ecbdata->diff_words);
393 if (ecbdata->diff_words->minus.text.ptr)
394 free (ecbdata->diff_words->minus.text.ptr);
395 if (ecbdata->diff_words->plus.text.ptr)
396 free (ecbdata->diff_words->plus.text.ptr);
397 free(ecbdata->diff_words);
398 ecbdata->diff_words = NULL;
402 const char *diff_get_color(int diff_use_color, enum color_diff ix)
404 if (diff_use_color)
405 return diff_colors[ix];
406 return "";
409 static void emit_line(const char *set, const char *reset, const char *line, int len)
411 if (len > 0 && line[len-1] == '\n')
412 len--;
413 fputs(set, stdout);
414 fwrite(line, len, 1, stdout);
415 puts(reset);
418 static void emit_line_with_ws(int nparents,
419 const char *set, const char *reset, const char *ws,
420 const char *line, int len)
422 int col0 = nparents;
423 int last_tab_in_indent = -1;
424 int last_space_in_indent = -1;
425 int i;
426 int tail = len;
427 int need_highlight_leading_space = 0;
428 /* The line is a newly added line. Does it have funny leading
429 * whitespaces? In indent, SP should never precede a TAB.
431 for (i = col0; i < len; i++) {
432 if (line[i] == '\t') {
433 last_tab_in_indent = i;
434 if (0 <= last_space_in_indent)
435 need_highlight_leading_space = 1;
437 else if (line[i] == ' ')
438 last_space_in_indent = i;
439 else
440 break;
442 fputs(set, stdout);
443 fwrite(line, col0, 1, stdout);
444 fputs(reset, stdout);
445 if (((i == len) || line[i] == '\n') && i != col0) {
446 /* The whole line was indent */
447 emit_line(ws, reset, line + col0, len - col0);
448 return;
450 i = col0;
451 if (need_highlight_leading_space) {
452 while (i < last_tab_in_indent) {
453 if (line[i] == ' ') {
454 fputs(ws, stdout);
455 putchar(' ');
456 fputs(reset, stdout);
458 else
459 putchar(line[i]);
460 i++;
463 tail = len - 1;
464 if (line[tail] == '\n' && i < tail)
465 tail--;
466 while (i < tail) {
467 if (!isspace(line[tail]))
468 break;
469 tail--;
471 if ((i < tail && line[tail + 1] != '\n')) {
472 /* This has whitespace between tail+1..len */
473 fputs(set, stdout);
474 fwrite(line + i, tail - i + 1, 1, stdout);
475 fputs(reset, stdout);
476 emit_line(ws, reset, line + tail + 1, len - tail - 1);
478 else
479 emit_line(set, reset, line + i, len - i);
482 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
484 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
485 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
487 if (!*ws)
488 emit_line(set, reset, line, len);
489 else
490 emit_line_with_ws(ecbdata->nparents, set, reset, ws,
491 line, len);
494 static void fn_out_consume(void *priv, char *line, unsigned long len)
496 int i;
497 int color;
498 struct emit_callback *ecbdata = priv;
499 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
500 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
502 if (ecbdata->label_path[0]) {
503 const char *name_a_tab, *name_b_tab;
505 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
506 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
508 printf("%s--- %s%s%s\n",
509 set, ecbdata->label_path[0], reset, name_a_tab);
510 printf("%s+++ %s%s%s\n",
511 set, ecbdata->label_path[1], reset, name_b_tab);
512 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
515 /* This is not really necessary for now because
516 * this codepath only deals with two-way diffs.
518 for (i = 0; i < len && line[i] == '@'; i++)
520 if (2 <= i && i < len && line[i] == ' ') {
521 ecbdata->nparents = i - 1;
522 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
523 reset, line, len);
524 return;
527 if (len < ecbdata->nparents) {
528 set = reset;
529 emit_line(reset, reset, line, len);
530 return;
533 color = DIFF_PLAIN;
534 if (ecbdata->diff_words && ecbdata->nparents != 1)
535 /* fall back to normal diff */
536 free_diff_words_data(ecbdata);
537 if (ecbdata->diff_words) {
538 if (line[0] == '-') {
539 diff_words_append(line, len,
540 &ecbdata->diff_words->minus);
541 return;
542 } else if (line[0] == '+') {
543 diff_words_append(line, len,
544 &ecbdata->diff_words->plus);
545 return;
547 if (ecbdata->diff_words->minus.text.size ||
548 ecbdata->diff_words->plus.text.size)
549 diff_words_show(ecbdata->diff_words);
550 line++;
551 len--;
552 emit_line(set, reset, line, len);
553 return;
555 for (i = 0; i < ecbdata->nparents && len; i++) {
556 if (line[i] == '-')
557 color = DIFF_FILE_OLD;
558 else if (line[i] == '+')
559 color = DIFF_FILE_NEW;
562 if (color != DIFF_FILE_NEW) {
563 emit_line(diff_get_color(ecbdata->color_diff, color),
564 reset, line, len);
565 return;
567 emit_add_line(reset, ecbdata, line, len);
570 static char *pprint_rename(const char *a, const char *b)
572 const char *old = a;
573 const char *new = b;
574 char *name = NULL;
575 int pfx_length, sfx_length;
576 int len_a = strlen(a);
577 int len_b = strlen(b);
578 int qlen_a = quote_c_style(a, NULL, NULL, 0);
579 int qlen_b = quote_c_style(b, NULL, NULL, 0);
581 if (qlen_a || qlen_b) {
582 if (qlen_a) len_a = qlen_a;
583 if (qlen_b) len_b = qlen_b;
584 name = xmalloc( len_a + len_b + 5 );
585 if (qlen_a)
586 quote_c_style(a, name, NULL, 0);
587 else
588 memcpy(name, a, len_a);
589 memcpy(name + len_a, " => ", 4);
590 if (qlen_b)
591 quote_c_style(b, name + len_a + 4, NULL, 0);
592 else
593 memcpy(name + len_a + 4, b, len_b + 1);
594 return name;
597 /* Find common prefix */
598 pfx_length = 0;
599 while (*old && *new && *old == *new) {
600 if (*old == '/')
601 pfx_length = old - a + 1;
602 old++;
603 new++;
606 /* Find common suffix */
607 old = a + len_a;
608 new = b + len_b;
609 sfx_length = 0;
610 while (a <= old && b <= new && *old == *new) {
611 if (*old == '/')
612 sfx_length = len_a - (old - a);
613 old--;
614 new--;
618 * pfx{mid-a => mid-b}sfx
619 * {pfx-a => pfx-b}sfx
620 * pfx{sfx-a => sfx-b}
621 * name-a => name-b
623 if (pfx_length + sfx_length) {
624 int a_midlen = len_a - pfx_length - sfx_length;
625 int b_midlen = len_b - pfx_length - sfx_length;
626 if (a_midlen < 0) a_midlen = 0;
627 if (b_midlen < 0) b_midlen = 0;
629 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
630 sprintf(name, "%.*s{%.*s => %.*s}%s",
631 pfx_length, a,
632 a_midlen, a + pfx_length,
633 b_midlen, b + pfx_length,
634 a + len_a - sfx_length);
636 else {
637 name = xmalloc(len_a + len_b + 5);
638 sprintf(name, "%s => %s", a, b);
640 return name;
643 struct diffstat_t {
644 struct xdiff_emit_state xm;
646 int nr;
647 int alloc;
648 struct diffstat_file {
649 char *name;
650 unsigned is_unmerged:1;
651 unsigned is_binary:1;
652 unsigned is_renamed:1;
653 unsigned int added, deleted;
654 } **files;
657 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
658 const char *name_a,
659 const char *name_b)
661 struct diffstat_file *x;
662 x = xcalloc(sizeof (*x), 1);
663 if (diffstat->nr == diffstat->alloc) {
664 diffstat->alloc = alloc_nr(diffstat->alloc);
665 diffstat->files = xrealloc(diffstat->files,
666 diffstat->alloc * sizeof(x));
668 diffstat->files[diffstat->nr++] = x;
669 if (name_b) {
670 x->name = pprint_rename(name_a, name_b);
671 x->is_renamed = 1;
673 else
674 x->name = xstrdup(name_a);
675 return x;
678 static void diffstat_consume(void *priv, char *line, unsigned long len)
680 struct diffstat_t *diffstat = priv;
681 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
683 if (line[0] == '+')
684 x->added++;
685 else if (line[0] == '-')
686 x->deleted++;
689 const char mime_boundary_leader[] = "------------";
691 static int scale_linear(int it, int width, int max_change)
694 * make sure that at least one '-' is printed if there were deletions,
695 * and likewise for '+'.
697 if (max_change < 2)
698 return it;
699 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
702 static void show_name(const char *prefix, const char *name, int len,
703 const char *reset, const char *set)
705 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
708 static void show_graph(char ch, int cnt, const char *set, const char *reset)
710 if (cnt <= 0)
711 return;
712 printf("%s", set);
713 while (cnt--)
714 putchar(ch);
715 printf("%s", reset);
718 static void show_stats(struct diffstat_t* data, struct diff_options *options)
720 int i, len, add, del, total, adds = 0, dels = 0;
721 int max_change = 0, max_len = 0;
722 int total_files = data->nr;
723 int width, name_width;
724 const char *reset, *set, *add_c, *del_c;
726 if (data->nr == 0)
727 return;
729 width = options->stat_width ? options->stat_width : 80;
730 name_width = options->stat_name_width ? options->stat_name_width : 50;
732 /* Sanity: give at least 5 columns to the graph,
733 * but leave at least 10 columns for the name.
735 if (width < name_width + 15) {
736 if (name_width <= 25)
737 width = name_width + 15;
738 else
739 name_width = width - 15;
742 /* Find the longest filename and max number of changes */
743 reset = diff_get_color(options->color_diff, DIFF_RESET);
744 set = diff_get_color(options->color_diff, DIFF_PLAIN);
745 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
746 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
748 for (i = 0; i < data->nr; i++) {
749 struct diffstat_file *file = data->files[i];
750 int change = file->added + file->deleted;
752 if (!file->is_renamed) { /* renames are already quoted by pprint_rename */
753 len = quote_c_style(file->name, NULL, NULL, 0);
754 if (len) {
755 char *qname = xmalloc(len + 1);
756 quote_c_style(file->name, qname, NULL, 0);
757 free(file->name);
758 file->name = qname;
762 len = strlen(file->name);
763 if (max_len < len)
764 max_len = len;
766 if (file->is_binary || file->is_unmerged)
767 continue;
768 if (max_change < change)
769 max_change = change;
772 /* Compute the width of the graph part;
773 * 10 is for one blank at the beginning of the line plus
774 * " | count " between the name and the graph.
776 * From here on, name_width is the width of the name area,
777 * and width is the width of the graph area.
779 name_width = (name_width < max_len) ? name_width : max_len;
780 if (width < (name_width + 10) + max_change)
781 width = width - (name_width + 10);
782 else
783 width = max_change;
785 for (i = 0; i < data->nr; i++) {
786 const char *prefix = "";
787 char *name = data->files[i]->name;
788 int added = data->files[i]->added;
789 int deleted = data->files[i]->deleted;
790 int name_len;
793 * "scale" the filename
795 len = name_width;
796 name_len = strlen(name);
797 if (name_width < name_len) {
798 char *slash;
799 prefix = "...";
800 len -= 3;
801 name += name_len - len;
802 slash = strchr(name, '/');
803 if (slash)
804 name = slash;
807 if (data->files[i]->is_binary) {
808 show_name(prefix, name, len, reset, set);
809 printf(" Bin\n");
810 goto free_diffstat_file;
812 else if (data->files[i]->is_unmerged) {
813 show_name(prefix, name, len, reset, set);
814 printf(" Unmerged\n");
815 goto free_diffstat_file;
817 else if (!data->files[i]->is_renamed &&
818 (added + deleted == 0)) {
819 total_files--;
820 goto free_diffstat_file;
824 * scale the add/delete
826 add = added;
827 del = deleted;
828 total = add + del;
829 adds += add;
830 dels += del;
832 if (width <= max_change) {
833 add = scale_linear(add, width, max_change);
834 del = scale_linear(del, width, max_change);
835 total = add + del;
837 show_name(prefix, name, len, reset, set);
838 printf("%5d ", added + deleted);
839 show_graph('+', add, add_c, reset);
840 show_graph('-', del, del_c, reset);
841 putchar('\n');
842 free_diffstat_file:
843 free(data->files[i]->name);
844 free(data->files[i]);
846 free(data->files);
847 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
848 set, total_files, adds, dels, reset);
851 static void show_shortstats(struct diffstat_t* data)
853 int i, adds = 0, dels = 0, total_files = data->nr;
855 if (data->nr == 0)
856 return;
858 for (i = 0; i < data->nr; i++) {
859 if (!data->files[i]->is_binary &&
860 !data->files[i]->is_unmerged) {
861 int added = data->files[i]->added;
862 int deleted= data->files[i]->deleted;
863 if (!data->files[i]->is_renamed &&
864 (added + deleted == 0)) {
865 total_files--;
866 } else {
867 adds += added;
868 dels += deleted;
871 free(data->files[i]->name);
872 free(data->files[i]);
874 free(data->files);
876 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
877 total_files, adds, dels);
880 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
882 int i;
884 for (i = 0; i < data->nr; i++) {
885 struct diffstat_file *file = data->files[i];
887 if (file->is_binary)
888 printf("-\t-\t");
889 else
890 printf("%d\t%d\t", file->added, file->deleted);
891 if (options->line_termination && !file->is_renamed &&
892 quote_c_style(file->name, NULL, NULL, 0))
893 quote_c_style(file->name, NULL, stdout, 0);
894 else
895 fputs(file->name, stdout);
896 putchar(options->line_termination);
900 struct checkdiff_t {
901 struct xdiff_emit_state xm;
902 const char *filename;
903 int lineno, color_diff;
906 static void checkdiff_consume(void *priv, char *line, unsigned long len)
908 struct checkdiff_t *data = priv;
909 const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
910 const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
911 const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
913 if (line[0] == '+') {
914 int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
916 /* check space before tab */
917 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
918 if (line[i] == ' ')
919 spaces++;
920 if (line[i - 1] == '\t' && spaces)
921 space_before_tab = 1;
923 /* check white space at line end */
924 if (line[len - 1] == '\n')
925 len--;
926 if (isspace(line[len - 1]))
927 white_space_at_end = 1;
929 if (space_before_tab || white_space_at_end) {
930 printf("%s:%d: %s", data->filename, data->lineno, ws);
931 if (space_before_tab) {
932 printf("space before tab");
933 if (white_space_at_end)
934 putchar(',');
936 if (white_space_at_end)
937 printf("white space at end");
938 printf(":%s ", reset);
939 emit_line_with_ws(1, set, reset, ws, line, len);
942 data->lineno++;
943 } else if (line[0] == ' ')
944 data->lineno++;
945 else if (line[0] == '@') {
946 char *plus = strchr(line, '+');
947 if (plus)
948 data->lineno = strtol(plus, NULL, 10);
949 else
950 die("invalid diff");
954 static unsigned char *deflate_it(char *data,
955 unsigned long size,
956 unsigned long *result_size)
958 int bound;
959 unsigned char *deflated;
960 z_stream stream;
962 memset(&stream, 0, sizeof(stream));
963 deflateInit(&stream, zlib_compression_level);
964 bound = deflateBound(&stream, size);
965 deflated = xmalloc(bound);
966 stream.next_out = deflated;
967 stream.avail_out = bound;
969 stream.next_in = (unsigned char *)data;
970 stream.avail_in = size;
971 while (deflate(&stream, Z_FINISH) == Z_OK)
972 ; /* nothing */
973 deflateEnd(&stream);
974 *result_size = stream.total_out;
975 return deflated;
978 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
980 void *cp;
981 void *delta;
982 void *deflated;
983 void *data;
984 unsigned long orig_size;
985 unsigned long delta_size;
986 unsigned long deflate_size;
987 unsigned long data_size;
989 /* We could do deflated delta, or we could do just deflated two,
990 * whichever is smaller.
992 delta = NULL;
993 deflated = deflate_it(two->ptr, two->size, &deflate_size);
994 if (one->size && two->size) {
995 delta = diff_delta(one->ptr, one->size,
996 two->ptr, two->size,
997 &delta_size, deflate_size);
998 if (delta) {
999 void *to_free = delta;
1000 orig_size = delta_size;
1001 delta = deflate_it(delta, delta_size, &delta_size);
1002 free(to_free);
1006 if (delta && delta_size < deflate_size) {
1007 printf("delta %lu\n", orig_size);
1008 free(deflated);
1009 data = delta;
1010 data_size = delta_size;
1012 else {
1013 printf("literal %lu\n", two->size);
1014 free(delta);
1015 data = deflated;
1016 data_size = deflate_size;
1019 /* emit data encoded in base85 */
1020 cp = data;
1021 while (data_size) {
1022 int bytes = (52 < data_size) ? 52 : data_size;
1023 char line[70];
1024 data_size -= bytes;
1025 if (bytes <= 26)
1026 line[0] = bytes + 'A' - 1;
1027 else
1028 line[0] = bytes - 26 + 'a' - 1;
1029 encode_85(line + 1, cp, bytes);
1030 cp = (char *) cp + bytes;
1031 puts(line);
1033 printf("\n");
1034 free(data);
1037 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1039 printf("GIT binary patch\n");
1040 emit_binary_diff_body(one, two);
1041 emit_binary_diff_body(two, one);
1044 #define FIRST_FEW_BYTES 8000
1045 static int mmfile_is_binary(mmfile_t *mf)
1047 long sz = mf->size;
1048 if (FIRST_FEW_BYTES < sz)
1049 sz = FIRST_FEW_BYTES;
1050 return !!memchr(mf->ptr, 0, sz);
1053 static void builtin_diff(const char *name_a,
1054 const char *name_b,
1055 struct diff_filespec *one,
1056 struct diff_filespec *two,
1057 const char *xfrm_msg,
1058 struct diff_options *o,
1059 int complete_rewrite)
1061 mmfile_t mf1, mf2;
1062 const char *lbl[2];
1063 char *a_one, *b_two;
1064 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1065 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1067 a_one = quote_two("a/", name_a);
1068 b_two = quote_two("b/", name_b);
1069 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1070 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1071 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1072 if (lbl[0][0] == '/') {
1073 /* /dev/null */
1074 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1075 if (xfrm_msg && xfrm_msg[0])
1076 printf("%s%s%s\n", set, xfrm_msg, reset);
1078 else if (lbl[1][0] == '/') {
1079 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1080 if (xfrm_msg && xfrm_msg[0])
1081 printf("%s%s%s\n", set, xfrm_msg, reset);
1083 else {
1084 if (one->mode != two->mode) {
1085 printf("%sold mode %06o%s\n", set, one->mode, reset);
1086 printf("%snew mode %06o%s\n", set, two->mode, reset);
1088 if (xfrm_msg && xfrm_msg[0])
1089 printf("%s%s%s\n", set, xfrm_msg, reset);
1091 * we do not run diff between different kind
1092 * of objects.
1094 if ((one->mode ^ two->mode) & S_IFMT)
1095 goto free_ab_and_return;
1096 if (complete_rewrite) {
1097 emit_rewrite_diff(name_a, name_b, one, two,
1098 o->color_diff);
1099 goto free_ab_and_return;
1103 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1104 die("unable to read files to diff");
1106 if (!o->text && (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))) {
1107 /* Quite common confusing case */
1108 if (mf1.size == mf2.size &&
1109 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1110 goto free_ab_and_return;
1111 if (o->binary)
1112 emit_binary_diff(&mf1, &mf2);
1113 else
1114 printf("Binary files %s and %s differ\n",
1115 lbl[0], lbl[1]);
1117 else {
1118 /* Crazy xdl interfaces.. */
1119 const char *diffopts = getenv("GIT_DIFF_OPTS");
1120 xpparam_t xpp;
1121 xdemitconf_t xecfg;
1122 xdemitcb_t ecb;
1123 struct emit_callback ecbdata;
1125 memset(&ecbdata, 0, sizeof(ecbdata));
1126 ecbdata.label_path = lbl;
1127 ecbdata.color_diff = o->color_diff;
1128 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1129 xecfg.ctxlen = o->context;
1130 xecfg.flags = XDL_EMIT_FUNCNAMES;
1131 if (!diffopts)
1133 else if (!prefixcmp(diffopts, "--unified="))
1134 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1135 else if (!prefixcmp(diffopts, "-u"))
1136 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1137 ecb.outf = xdiff_outf;
1138 ecb.priv = &ecbdata;
1139 ecbdata.xm.consume = fn_out_consume;
1140 if (o->color_diff_words)
1141 ecbdata.diff_words =
1142 xcalloc(1, sizeof(struct diff_words_data));
1143 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1144 if (o->color_diff_words)
1145 free_diff_words_data(&ecbdata);
1148 free_ab_and_return:
1149 free(a_one);
1150 free(b_two);
1151 return;
1154 static void builtin_diffstat(const char *name_a, const char *name_b,
1155 struct diff_filespec *one,
1156 struct diff_filespec *two,
1157 struct diffstat_t *diffstat,
1158 struct diff_options *o,
1159 int complete_rewrite)
1161 mmfile_t mf1, mf2;
1162 struct diffstat_file *data;
1164 data = diffstat_add(diffstat, name_a, name_b);
1166 if (!one || !two) {
1167 data->is_unmerged = 1;
1168 return;
1170 if (complete_rewrite) {
1171 diff_populate_filespec(one, 0);
1172 diff_populate_filespec(two, 0);
1173 data->deleted = count_lines(one->data, one->size);
1174 data->added = count_lines(two->data, two->size);
1175 return;
1177 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1178 die("unable to read files to diff");
1180 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
1181 data->is_binary = 1;
1182 else {
1183 /* Crazy xdl interfaces.. */
1184 xpparam_t xpp;
1185 xdemitconf_t xecfg;
1186 xdemitcb_t ecb;
1188 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1189 xecfg.ctxlen = 0;
1190 xecfg.flags = 0;
1191 ecb.outf = xdiff_outf;
1192 ecb.priv = diffstat;
1193 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1197 static void builtin_checkdiff(const char *name_a, const char *name_b,
1198 struct diff_filespec *one,
1199 struct diff_filespec *two, struct diff_options *o)
1201 mmfile_t mf1, mf2;
1202 struct checkdiff_t data;
1204 if (!two)
1205 return;
1207 memset(&data, 0, sizeof(data));
1208 data.xm.consume = checkdiff_consume;
1209 data.filename = name_b ? name_b : name_a;
1210 data.lineno = 0;
1211 data.color_diff = o->color_diff;
1213 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1214 die("unable to read files to diff");
1216 if (mmfile_is_binary(&mf2))
1217 return;
1218 else {
1219 /* Crazy xdl interfaces.. */
1220 xpparam_t xpp;
1221 xdemitconf_t xecfg;
1222 xdemitcb_t ecb;
1224 xpp.flags = XDF_NEED_MINIMAL;
1225 xecfg.ctxlen = 0;
1226 xecfg.flags = 0;
1227 ecb.outf = xdiff_outf;
1228 ecb.priv = &data;
1229 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1233 struct diff_filespec *alloc_filespec(const char *path)
1235 int namelen = strlen(path);
1236 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1238 memset(spec, 0, sizeof(*spec));
1239 spec->path = (char *)(spec + 1);
1240 memcpy(spec->path, path, namelen+1);
1241 return spec;
1244 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1245 unsigned short mode)
1247 if (mode) {
1248 spec->mode = canon_mode(mode);
1249 hashcpy(spec->sha1, sha1);
1250 spec->sha1_valid = !is_null_sha1(sha1);
1255 * Given a name and sha1 pair, if the dircache tells us the file in
1256 * the work tree has that object contents, return true, so that
1257 * prepare_temp_file() does not have to inflate and extract.
1259 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1261 struct cache_entry *ce;
1262 struct stat st;
1263 int pos, len;
1265 /* We do not read the cache ourselves here, because the
1266 * benchmark with my previous version that always reads cache
1267 * shows that it makes things worse for diff-tree comparing
1268 * two linux-2.6 kernel trees in an already checked out work
1269 * tree. This is because most diff-tree comparisons deal with
1270 * only a small number of files, while reading the cache is
1271 * expensive for a large project, and its cost outweighs the
1272 * savings we get by not inflating the object to a temporary
1273 * file. Practically, this code only helps when we are used
1274 * by diff-cache --cached, which does read the cache before
1275 * calling us.
1277 if (!active_cache)
1278 return 0;
1280 /* We want to avoid the working directory if our caller
1281 * doesn't need the data in a normal file, this system
1282 * is rather slow with its stat/open/mmap/close syscalls,
1283 * and the object is contained in a pack file. The pack
1284 * is probably already open and will be faster to obtain
1285 * the data through than the working directory. Loose
1286 * objects however would tend to be slower as they need
1287 * to be individually opened and inflated.
1289 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1290 return 0;
1292 len = strlen(name);
1293 pos = cache_name_pos(name, len);
1294 if (pos < 0)
1295 return 0;
1296 ce = active_cache[pos];
1297 if ((lstat(name, &st) < 0) ||
1298 !S_ISREG(st.st_mode) || /* careful! */
1299 ce_match_stat(ce, &st, 0) ||
1300 hashcmp(sha1, ce->sha1))
1301 return 0;
1302 /* we return 1 only when we can stat, it is a regular file,
1303 * stat information matches, and sha1 recorded in the cache
1304 * matches. I.e. we know the file in the work tree really is
1305 * the same as the <name, sha1> pair.
1307 return 1;
1310 static struct sha1_size_cache {
1311 unsigned char sha1[20];
1312 unsigned long size;
1313 } **sha1_size_cache;
1314 static int sha1_size_cache_nr, sha1_size_cache_alloc;
1316 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
1317 int find_only,
1318 unsigned long size)
1320 int first, last;
1321 struct sha1_size_cache *e;
1323 first = 0;
1324 last = sha1_size_cache_nr;
1325 while (last > first) {
1326 int cmp, next = (last + first) >> 1;
1327 e = sha1_size_cache[next];
1328 cmp = hashcmp(e->sha1, sha1);
1329 if (!cmp)
1330 return e;
1331 if (cmp < 0) {
1332 last = next;
1333 continue;
1335 first = next+1;
1337 /* not found */
1338 if (find_only)
1339 return NULL;
1340 /* insert to make it at "first" */
1341 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
1342 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
1343 sha1_size_cache = xrealloc(sha1_size_cache,
1344 sha1_size_cache_alloc *
1345 sizeof(*sha1_size_cache));
1347 sha1_size_cache_nr++;
1348 if (first < sha1_size_cache_nr)
1349 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
1350 (sha1_size_cache_nr - first - 1) *
1351 sizeof(*sha1_size_cache));
1352 e = xmalloc(sizeof(struct sha1_size_cache));
1353 sha1_size_cache[first] = e;
1354 hashcpy(e->sha1, sha1);
1355 e->size = size;
1356 return e;
1360 * While doing rename detection and pickaxe operation, we may need to
1361 * grab the data for the blob (or file) for our own in-core comparison.
1362 * diff_filespec has data and size fields for this purpose.
1364 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1366 int err = 0;
1367 if (!DIFF_FILE_VALID(s))
1368 die("internal error: asking to populate invalid file.");
1369 if (S_ISDIR(s->mode))
1370 return -1;
1372 if (!use_size_cache)
1373 size_only = 0;
1375 if (s->data)
1376 return err;
1377 if (!s->sha1_valid ||
1378 reuse_worktree_file(s->path, s->sha1, 0)) {
1379 struct stat st;
1380 int fd;
1381 char *buf;
1382 unsigned long size;
1384 if (lstat(s->path, &st) < 0) {
1385 if (errno == ENOENT) {
1386 err_empty:
1387 err = -1;
1388 empty:
1389 s->data = (char *)"";
1390 s->size = 0;
1391 return err;
1394 s->size = st.st_size;
1395 if (!s->size)
1396 goto empty;
1397 if (size_only)
1398 return 0;
1399 if (S_ISLNK(st.st_mode)) {
1400 int ret;
1401 s->data = xmalloc(s->size);
1402 s->should_free = 1;
1403 ret = readlink(s->path, s->data, s->size);
1404 if (ret < 0) {
1405 free(s->data);
1406 goto err_empty;
1408 return 0;
1410 fd = open(s->path, O_RDONLY);
1411 if (fd < 0)
1412 goto err_empty;
1413 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1414 close(fd);
1415 s->should_munmap = 1;
1418 * Convert from working tree format to canonical git format
1420 buf = s->data;
1421 size = s->size;
1422 if (convert_to_git(s->path, &buf, &size)) {
1423 munmap(s->data, s->size);
1424 s->should_munmap = 0;
1425 s->data = buf;
1426 s->size = size;
1427 s->should_free = 1;
1430 else {
1431 char type[20];
1432 struct sha1_size_cache *e;
1434 if (size_only) {
1435 e = locate_size_cache(s->sha1, 1, 0);
1436 if (e) {
1437 s->size = e->size;
1438 return 0;
1440 if (!sha1_object_info(s->sha1, type, &s->size))
1441 locate_size_cache(s->sha1, 0, s->size);
1443 else {
1444 s->data = read_sha1_file(s->sha1, type, &s->size);
1445 s->should_free = 1;
1448 return 0;
1451 void diff_free_filespec_data(struct diff_filespec *s)
1453 if (s->should_free)
1454 free(s->data);
1455 else if (s->should_munmap)
1456 munmap(s->data, s->size);
1457 s->should_free = s->should_munmap = 0;
1458 s->data = NULL;
1459 free(s->cnt_data);
1460 s->cnt_data = NULL;
1463 static void prep_temp_blob(struct diff_tempfile *temp,
1464 void *blob,
1465 unsigned long size,
1466 const unsigned char *sha1,
1467 int mode)
1469 int fd;
1471 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1472 if (fd < 0)
1473 die("unable to create temp-file");
1474 if (write_in_full(fd, blob, size) != size)
1475 die("unable to write temp-file");
1476 close(fd);
1477 temp->name = temp->tmp_path;
1478 strcpy(temp->hex, sha1_to_hex(sha1));
1479 temp->hex[40] = 0;
1480 sprintf(temp->mode, "%06o", mode);
1483 static void prepare_temp_file(const char *name,
1484 struct diff_tempfile *temp,
1485 struct diff_filespec *one)
1487 if (!DIFF_FILE_VALID(one)) {
1488 not_a_valid_file:
1489 /* A '-' entry produces this for file-2, and
1490 * a '+' entry produces this for file-1.
1492 temp->name = "/dev/null";
1493 strcpy(temp->hex, ".");
1494 strcpy(temp->mode, ".");
1495 return;
1498 if (!one->sha1_valid ||
1499 reuse_worktree_file(name, one->sha1, 1)) {
1500 struct stat st;
1501 if (lstat(name, &st) < 0) {
1502 if (errno == ENOENT)
1503 goto not_a_valid_file;
1504 die("stat(%s): %s", name, strerror(errno));
1506 if (S_ISLNK(st.st_mode)) {
1507 int ret;
1508 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1509 if (sizeof(buf) <= st.st_size)
1510 die("symlink too long: %s", name);
1511 ret = readlink(name, buf, st.st_size);
1512 if (ret < 0)
1513 die("readlink(%s)", name);
1514 prep_temp_blob(temp, buf, st.st_size,
1515 (one->sha1_valid ?
1516 one->sha1 : null_sha1),
1517 (one->sha1_valid ?
1518 one->mode : S_IFLNK));
1520 else {
1521 /* we can borrow from the file in the work tree */
1522 temp->name = name;
1523 if (!one->sha1_valid)
1524 strcpy(temp->hex, sha1_to_hex(null_sha1));
1525 else
1526 strcpy(temp->hex, sha1_to_hex(one->sha1));
1527 /* Even though we may sometimes borrow the
1528 * contents from the work tree, we always want
1529 * one->mode. mode is trustworthy even when
1530 * !(one->sha1_valid), as long as
1531 * DIFF_FILE_VALID(one).
1533 sprintf(temp->mode, "%06o", one->mode);
1535 return;
1537 else {
1538 if (diff_populate_filespec(one, 0))
1539 die("cannot read data blob for %s", one->path);
1540 prep_temp_blob(temp, one->data, one->size,
1541 one->sha1, one->mode);
1545 static void remove_tempfile(void)
1547 int i;
1549 for (i = 0; i < 2; i++)
1550 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1551 unlink(diff_temp[i].name);
1552 diff_temp[i].name = NULL;
1556 static void remove_tempfile_on_signal(int signo)
1558 remove_tempfile();
1559 signal(SIGINT, SIG_DFL);
1560 raise(signo);
1563 static int spawn_prog(const char *pgm, const char **arg)
1565 pid_t pid;
1566 int status;
1568 fflush(NULL);
1569 pid = fork();
1570 if (pid < 0)
1571 die("unable to fork");
1572 if (!pid) {
1573 execvp(pgm, (char *const*) arg);
1574 exit(255);
1577 while (waitpid(pid, &status, 0) < 0) {
1578 if (errno == EINTR)
1579 continue;
1580 return -1;
1583 /* Earlier we did not check the exit status because
1584 * diff exits non-zero if files are different, and
1585 * we are not interested in knowing that. It was a
1586 * mistake which made it harder to quit a diff-*
1587 * session that uses the git-apply-patch-script as
1588 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1589 * should also exit non-zero only when it wants to
1590 * abort the entire diff-* session.
1592 if (WIFEXITED(status) && !WEXITSTATUS(status))
1593 return 0;
1594 return -1;
1597 /* An external diff command takes:
1599 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1600 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1603 static void run_external_diff(const char *pgm,
1604 const char *name,
1605 const char *other,
1606 struct diff_filespec *one,
1607 struct diff_filespec *two,
1608 const char *xfrm_msg,
1609 int complete_rewrite)
1611 const char *spawn_arg[10];
1612 struct diff_tempfile *temp = diff_temp;
1613 int retval;
1614 static int atexit_asked = 0;
1615 const char *othername;
1616 const char **arg = &spawn_arg[0];
1618 othername = (other? other : name);
1619 if (one && two) {
1620 prepare_temp_file(name, &temp[0], one);
1621 prepare_temp_file(othername, &temp[1], two);
1622 if (! atexit_asked &&
1623 (temp[0].name == temp[0].tmp_path ||
1624 temp[1].name == temp[1].tmp_path)) {
1625 atexit_asked = 1;
1626 atexit(remove_tempfile);
1628 signal(SIGINT, remove_tempfile_on_signal);
1631 if (one && two) {
1632 *arg++ = pgm;
1633 *arg++ = name;
1634 *arg++ = temp[0].name;
1635 *arg++ = temp[0].hex;
1636 *arg++ = temp[0].mode;
1637 *arg++ = temp[1].name;
1638 *arg++ = temp[1].hex;
1639 *arg++ = temp[1].mode;
1640 if (other) {
1641 *arg++ = other;
1642 *arg++ = xfrm_msg;
1644 } else {
1645 *arg++ = pgm;
1646 *arg++ = name;
1648 *arg = NULL;
1649 retval = spawn_prog(pgm, spawn_arg);
1650 remove_tempfile();
1651 if (retval) {
1652 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1653 exit(1);
1657 static void run_diff_cmd(const char *pgm,
1658 const char *name,
1659 const char *other,
1660 struct diff_filespec *one,
1661 struct diff_filespec *two,
1662 const char *xfrm_msg,
1663 struct diff_options *o,
1664 int complete_rewrite)
1666 if (pgm) {
1667 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1668 complete_rewrite);
1669 return;
1671 if (one && two)
1672 builtin_diff(name, other ? other : name,
1673 one, two, xfrm_msg, o, complete_rewrite);
1674 else
1675 printf("* Unmerged path %s\n", name);
1678 static void diff_fill_sha1_info(struct diff_filespec *one)
1680 if (DIFF_FILE_VALID(one)) {
1681 if (!one->sha1_valid) {
1682 struct stat st;
1683 if (lstat(one->path, &st) < 0)
1684 die("stat %s", one->path);
1685 if (index_path(one->sha1, one->path, &st, 0))
1686 die("cannot hash %s\n", one->path);
1689 else
1690 hashclr(one->sha1);
1693 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1695 const char *pgm = external_diff();
1696 char msg[PATH_MAX*2+300], *xfrm_msg;
1697 struct diff_filespec *one;
1698 struct diff_filespec *two;
1699 const char *name;
1700 const char *other;
1701 char *name_munged, *other_munged;
1702 int complete_rewrite = 0;
1703 int len;
1705 if (DIFF_PAIR_UNMERGED(p)) {
1706 /* unmerged */
1707 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1708 return;
1711 name = p->one->path;
1712 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1713 name_munged = quote_one(name);
1714 other_munged = quote_one(other);
1715 one = p->one; two = p->two;
1717 diff_fill_sha1_info(one);
1718 diff_fill_sha1_info(two);
1720 len = 0;
1721 switch (p->status) {
1722 case DIFF_STATUS_COPIED:
1723 len += snprintf(msg + len, sizeof(msg) - len,
1724 "similarity index %d%%\n"
1725 "copy from %s\n"
1726 "copy to %s\n",
1727 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1728 name_munged, other_munged);
1729 break;
1730 case DIFF_STATUS_RENAMED:
1731 len += snprintf(msg + len, sizeof(msg) - len,
1732 "similarity index %d%%\n"
1733 "rename from %s\n"
1734 "rename to %s\n",
1735 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1736 name_munged, other_munged);
1737 break;
1738 case DIFF_STATUS_MODIFIED:
1739 if (p->score) {
1740 len += snprintf(msg + len, sizeof(msg) - len,
1741 "dissimilarity index %d%%\n",
1742 (int)(0.5 + p->score *
1743 100.0/MAX_SCORE));
1744 complete_rewrite = 1;
1745 break;
1747 /* fallthru */
1748 default:
1749 /* nothing */
1753 if (hashcmp(one->sha1, two->sha1)) {
1754 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1756 if (o->binary) {
1757 mmfile_t mf;
1758 if ((!fill_mmfile(&mf, one) && mmfile_is_binary(&mf)) ||
1759 (!fill_mmfile(&mf, two) && mmfile_is_binary(&mf)))
1760 abbrev = 40;
1762 len += snprintf(msg + len, sizeof(msg) - len,
1763 "index %.*s..%.*s",
1764 abbrev, sha1_to_hex(one->sha1),
1765 abbrev, sha1_to_hex(two->sha1));
1766 if (one->mode == two->mode)
1767 len += snprintf(msg + len, sizeof(msg) - len,
1768 " %06o", one->mode);
1769 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1772 if (len)
1773 msg[--len] = 0;
1774 xfrm_msg = len ? msg : NULL;
1776 if (!pgm &&
1777 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1778 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1779 /* a filepair that changes between file and symlink
1780 * needs to be split into deletion and creation.
1782 struct diff_filespec *null = alloc_filespec(two->path);
1783 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1784 free(null);
1785 null = alloc_filespec(one->path);
1786 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1787 free(null);
1789 else
1790 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1791 complete_rewrite);
1793 free(name_munged);
1794 free(other_munged);
1797 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1798 struct diffstat_t *diffstat)
1800 const char *name;
1801 const char *other;
1802 int complete_rewrite = 0;
1804 if (DIFF_PAIR_UNMERGED(p)) {
1805 /* unmerged */
1806 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1807 return;
1810 name = p->one->path;
1811 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1813 diff_fill_sha1_info(p->one);
1814 diff_fill_sha1_info(p->two);
1816 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1817 complete_rewrite = 1;
1818 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1821 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1823 const char *name;
1824 const char *other;
1826 if (DIFF_PAIR_UNMERGED(p)) {
1827 /* unmerged */
1828 return;
1831 name = p->one->path;
1832 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1834 diff_fill_sha1_info(p->one);
1835 diff_fill_sha1_info(p->two);
1837 builtin_checkdiff(name, other, p->one, p->two, o);
1840 void diff_setup(struct diff_options *options)
1842 memset(options, 0, sizeof(*options));
1843 options->line_termination = '\n';
1844 options->break_opt = -1;
1845 options->rename_limit = -1;
1846 options->context = 3;
1847 options->msg_sep = "";
1849 options->change = diff_change;
1850 options->add_remove = diff_addremove;
1851 options->color_diff = diff_use_color_default;
1852 options->detect_rename = diff_detect_rename_default;
1855 int diff_setup_done(struct diff_options *options)
1857 int count = 0;
1859 if (options->output_format & DIFF_FORMAT_NAME)
1860 count++;
1861 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
1862 count++;
1863 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
1864 count++;
1865 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
1866 count++;
1867 if (count > 1)
1868 die("--name-only, --name-status, --check and -s are mutually exclusive");
1870 if (options->find_copies_harder)
1871 options->detect_rename = DIFF_DETECT_COPY;
1873 if (options->output_format & (DIFF_FORMAT_NAME |
1874 DIFF_FORMAT_NAME_STATUS |
1875 DIFF_FORMAT_CHECKDIFF |
1876 DIFF_FORMAT_NO_OUTPUT))
1877 options->output_format &= ~(DIFF_FORMAT_RAW |
1878 DIFF_FORMAT_NUMSTAT |
1879 DIFF_FORMAT_DIFFSTAT |
1880 DIFF_FORMAT_SHORTSTAT |
1881 DIFF_FORMAT_SUMMARY |
1882 DIFF_FORMAT_PATCH);
1885 * These cases always need recursive; we do not drop caller-supplied
1886 * recursive bits for other formats here.
1888 if (options->output_format & (DIFF_FORMAT_PATCH |
1889 DIFF_FORMAT_NUMSTAT |
1890 DIFF_FORMAT_DIFFSTAT |
1891 DIFF_FORMAT_SHORTSTAT |
1892 DIFF_FORMAT_SUMMARY |
1893 DIFF_FORMAT_CHECKDIFF))
1894 options->recursive = 1;
1896 * Also pickaxe would not work very well if you do not say recursive
1898 if (options->pickaxe)
1899 options->recursive = 1;
1901 if (options->detect_rename && options->rename_limit < 0)
1902 options->rename_limit = diff_rename_limit_default;
1903 if (options->setup & DIFF_SETUP_USE_CACHE) {
1904 if (!active_cache)
1905 /* read-cache does not die even when it fails
1906 * so it is safe for us to do this here. Also
1907 * it does not smudge active_cache or active_nr
1908 * when it fails, so we do not have to worry about
1909 * cleaning it up ourselves either.
1911 read_cache();
1913 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1914 use_size_cache = 1;
1915 if (options->abbrev <= 0 || 40 < options->abbrev)
1916 options->abbrev = 40; /* full */
1918 return 0;
1921 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1923 char c, *eq;
1924 int len;
1926 if (*arg != '-')
1927 return 0;
1928 c = *++arg;
1929 if (!c)
1930 return 0;
1931 if (c == arg_short) {
1932 c = *++arg;
1933 if (!c)
1934 return 1;
1935 if (val && isdigit(c)) {
1936 char *end;
1937 int n = strtoul(arg, &end, 10);
1938 if (*end)
1939 return 0;
1940 *val = n;
1941 return 1;
1943 return 0;
1945 if (c != '-')
1946 return 0;
1947 arg++;
1948 eq = strchr(arg, '=');
1949 if (eq)
1950 len = eq - arg;
1951 else
1952 len = strlen(arg);
1953 if (!len || strncmp(arg, arg_long, len))
1954 return 0;
1955 if (eq) {
1956 int n;
1957 char *end;
1958 if (!isdigit(*++eq))
1959 return 0;
1960 n = strtoul(eq, &end, 10);
1961 if (*end)
1962 return 0;
1963 *val = n;
1965 return 1;
1968 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1970 const char *arg = av[0];
1971 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1972 options->output_format |= DIFF_FORMAT_PATCH;
1973 else if (opt_arg(arg, 'U', "unified", &options->context))
1974 options->output_format |= DIFF_FORMAT_PATCH;
1975 else if (!strcmp(arg, "--raw"))
1976 options->output_format |= DIFF_FORMAT_RAW;
1977 else if (!strcmp(arg, "--patch-with-raw")) {
1978 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
1980 else if (!strcmp(arg, "--numstat")) {
1981 options->output_format |= DIFF_FORMAT_NUMSTAT;
1983 else if (!strcmp(arg, "--shortstat")) {
1984 options->output_format |= DIFF_FORMAT_SHORTSTAT;
1986 else if (!prefixcmp(arg, "--stat")) {
1987 char *end;
1988 int width = options->stat_width;
1989 int name_width = options->stat_name_width;
1990 arg += 6;
1991 end = (char *)arg;
1993 switch (*arg) {
1994 case '-':
1995 if (!prefixcmp(arg, "-width="))
1996 width = strtoul(arg + 7, &end, 10);
1997 else if (!prefixcmp(arg, "-name-width="))
1998 name_width = strtoul(arg + 12, &end, 10);
1999 break;
2000 case '=':
2001 width = strtoul(arg+1, &end, 10);
2002 if (*end == ',')
2003 name_width = strtoul(end+1, &end, 10);
2006 /* Important! This checks all the error cases! */
2007 if (*end)
2008 return 0;
2009 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2010 options->stat_name_width = name_width;
2011 options->stat_width = width;
2013 else if (!strcmp(arg, "--check"))
2014 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2015 else if (!strcmp(arg, "--summary"))
2016 options->output_format |= DIFF_FORMAT_SUMMARY;
2017 else if (!strcmp(arg, "--patch-with-stat")) {
2018 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2020 else if (!strcmp(arg, "-z"))
2021 options->line_termination = 0;
2022 else if (!prefixcmp(arg, "-l"))
2023 options->rename_limit = strtoul(arg+2, NULL, 10);
2024 else if (!strcmp(arg, "--full-index"))
2025 options->full_index = 1;
2026 else if (!strcmp(arg, "--binary")) {
2027 options->output_format |= DIFF_FORMAT_PATCH;
2028 options->binary = 1;
2030 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
2031 options->text = 1;
2033 else if (!strcmp(arg, "--name-only"))
2034 options->output_format |= DIFF_FORMAT_NAME;
2035 else if (!strcmp(arg, "--name-status"))
2036 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2037 else if (!strcmp(arg, "-R"))
2038 options->reverse_diff = 1;
2039 else if (!prefixcmp(arg, "-S"))
2040 options->pickaxe = arg + 2;
2041 else if (!strcmp(arg, "-s")) {
2042 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2044 else if (!prefixcmp(arg, "-O"))
2045 options->orderfile = arg + 2;
2046 else if (!prefixcmp(arg, "--diff-filter="))
2047 options->filter = arg + 14;
2048 else if (!strcmp(arg, "--pickaxe-all"))
2049 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2050 else if (!strcmp(arg, "--pickaxe-regex"))
2051 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2052 else if (!prefixcmp(arg, "-B")) {
2053 if ((options->break_opt =
2054 diff_scoreopt_parse(arg)) == -1)
2055 return -1;
2057 else if (!prefixcmp(arg, "-M")) {
2058 if ((options->rename_score =
2059 diff_scoreopt_parse(arg)) == -1)
2060 return -1;
2061 options->detect_rename = DIFF_DETECT_RENAME;
2063 else if (!prefixcmp(arg, "-C")) {
2064 if ((options->rename_score =
2065 diff_scoreopt_parse(arg)) == -1)
2066 return -1;
2067 options->detect_rename = DIFF_DETECT_COPY;
2069 else if (!strcmp(arg, "--find-copies-harder"))
2070 options->find_copies_harder = 1;
2071 else if (!strcmp(arg, "--abbrev"))
2072 options->abbrev = DEFAULT_ABBREV;
2073 else if (!prefixcmp(arg, "--abbrev=")) {
2074 options->abbrev = strtoul(arg + 9, NULL, 10);
2075 if (options->abbrev < MINIMUM_ABBREV)
2076 options->abbrev = MINIMUM_ABBREV;
2077 else if (40 < options->abbrev)
2078 options->abbrev = 40;
2080 else if (!strcmp(arg, "--color"))
2081 options->color_diff = 1;
2082 else if (!strcmp(arg, "--no-color"))
2083 options->color_diff = 0;
2084 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2085 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2086 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2087 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2088 else if (!strcmp(arg, "--ignore-space-at-eol"))
2089 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2090 else if (!strcmp(arg, "--color-words"))
2091 options->color_diff = options->color_diff_words = 1;
2092 else if (!strcmp(arg, "--no-renames"))
2093 options->detect_rename = 0;
2094 else
2095 return 0;
2096 return 1;
2099 static int parse_num(const char **cp_p)
2101 unsigned long num, scale;
2102 int ch, dot;
2103 const char *cp = *cp_p;
2105 num = 0;
2106 scale = 1;
2107 dot = 0;
2108 for(;;) {
2109 ch = *cp;
2110 if ( !dot && ch == '.' ) {
2111 scale = 1;
2112 dot = 1;
2113 } else if ( ch == '%' ) {
2114 scale = dot ? scale*100 : 100;
2115 cp++; /* % is always at the end */
2116 break;
2117 } else if ( ch >= '0' && ch <= '9' ) {
2118 if ( scale < 100000 ) {
2119 scale *= 10;
2120 num = (num*10) + (ch-'0');
2122 } else {
2123 break;
2125 cp++;
2127 *cp_p = cp;
2129 /* user says num divided by scale and we say internally that
2130 * is MAX_SCORE * num / scale.
2132 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
2135 int diff_scoreopt_parse(const char *opt)
2137 int opt1, opt2, cmd;
2139 if (*opt++ != '-')
2140 return -1;
2141 cmd = *opt++;
2142 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2143 return -1; /* that is not a -M, -C nor -B option */
2145 opt1 = parse_num(&opt);
2146 if (cmd != 'B')
2147 opt2 = 0;
2148 else {
2149 if (*opt == 0)
2150 opt2 = 0;
2151 else if (*opt != '/')
2152 return -1; /* we expect -B80/99 or -B80 */
2153 else {
2154 opt++;
2155 opt2 = parse_num(&opt);
2158 if (*opt != 0)
2159 return -1;
2160 return opt1 | (opt2 << 16);
2163 struct diff_queue_struct diff_queued_diff;
2165 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2167 if (queue->alloc <= queue->nr) {
2168 queue->alloc = alloc_nr(queue->alloc);
2169 queue->queue = xrealloc(queue->queue,
2170 sizeof(dp) * queue->alloc);
2172 queue->queue[queue->nr++] = dp;
2175 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2176 struct diff_filespec *one,
2177 struct diff_filespec *two)
2179 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2180 dp->one = one;
2181 dp->two = two;
2182 if (queue)
2183 diff_q(queue, dp);
2184 return dp;
2187 void diff_free_filepair(struct diff_filepair *p)
2189 diff_free_filespec_data(p->one);
2190 diff_free_filespec_data(p->two);
2191 free(p->one);
2192 free(p->two);
2193 free(p);
2196 /* This is different from find_unique_abbrev() in that
2197 * it stuffs the result with dots for alignment.
2199 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2201 int abblen;
2202 const char *abbrev;
2203 if (len == 40)
2204 return sha1_to_hex(sha1);
2206 abbrev = find_unique_abbrev(sha1, len);
2207 if (!abbrev)
2208 return sha1_to_hex(sha1);
2209 abblen = strlen(abbrev);
2210 if (abblen < 37) {
2211 static char hex[41];
2212 if (len < abblen && abblen <= len + 2)
2213 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2214 else
2215 sprintf(hex, "%s...", abbrev);
2216 return hex;
2218 return sha1_to_hex(sha1);
2221 static void diff_flush_raw(struct diff_filepair *p,
2222 struct diff_options *options)
2224 int two_paths;
2225 char status[10];
2226 int abbrev = options->abbrev;
2227 const char *path_one, *path_two;
2228 int inter_name_termination = '\t';
2229 int line_termination = options->line_termination;
2231 if (!line_termination)
2232 inter_name_termination = 0;
2234 path_one = p->one->path;
2235 path_two = p->two->path;
2236 if (line_termination) {
2237 path_one = quote_one(path_one);
2238 path_two = quote_one(path_two);
2241 if (p->score)
2242 sprintf(status, "%c%03d", p->status,
2243 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2244 else {
2245 status[0] = p->status;
2246 status[1] = 0;
2248 switch (p->status) {
2249 case DIFF_STATUS_COPIED:
2250 case DIFF_STATUS_RENAMED:
2251 two_paths = 1;
2252 break;
2253 case DIFF_STATUS_ADDED:
2254 case DIFF_STATUS_DELETED:
2255 two_paths = 0;
2256 break;
2257 default:
2258 two_paths = 0;
2259 break;
2261 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2262 printf(":%06o %06o %s ",
2263 p->one->mode, p->two->mode,
2264 diff_unique_abbrev(p->one->sha1, abbrev));
2265 printf("%s ",
2266 diff_unique_abbrev(p->two->sha1, abbrev));
2268 printf("%s%c%s", status, inter_name_termination, path_one);
2269 if (two_paths)
2270 printf("%c%s", inter_name_termination, path_two);
2271 putchar(line_termination);
2272 if (path_one != p->one->path)
2273 free((void*)path_one);
2274 if (path_two != p->two->path)
2275 free((void*)path_two);
2278 static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2280 char *path = p->two->path;
2282 if (opt->line_termination)
2283 path = quote_one(p->two->path);
2284 printf("%s%c", path, opt->line_termination);
2285 if (p->two->path != path)
2286 free(path);
2289 int diff_unmodified_pair(struct diff_filepair *p)
2291 /* This function is written stricter than necessary to support
2292 * the currently implemented transformers, but the idea is to
2293 * let transformers to produce diff_filepairs any way they want,
2294 * and filter and clean them up here before producing the output.
2296 struct diff_filespec *one, *two;
2298 if (DIFF_PAIR_UNMERGED(p))
2299 return 0; /* unmerged is interesting */
2301 one = p->one;
2302 two = p->two;
2304 /* deletion, addition, mode or type change
2305 * and rename are all interesting.
2307 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2308 DIFF_PAIR_MODE_CHANGED(p) ||
2309 strcmp(one->path, two->path))
2310 return 0;
2312 /* both are valid and point at the same path. that is, we are
2313 * dealing with a change.
2315 if (one->sha1_valid && two->sha1_valid &&
2316 !hashcmp(one->sha1, two->sha1))
2317 return 1; /* no change */
2318 if (!one->sha1_valid && !two->sha1_valid)
2319 return 1; /* both look at the same file on the filesystem. */
2320 return 0;
2323 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2325 if (diff_unmodified_pair(p))
2326 return;
2328 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2329 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2330 return; /* no tree diffs in patch format */
2332 run_diff(p, o);
2335 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2336 struct diffstat_t *diffstat)
2338 if (diff_unmodified_pair(p))
2339 return;
2341 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2342 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2343 return; /* no tree diffs in patch format */
2345 run_diffstat(p, o, diffstat);
2348 static void diff_flush_checkdiff(struct diff_filepair *p,
2349 struct diff_options *o)
2351 if (diff_unmodified_pair(p))
2352 return;
2354 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2355 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2356 return; /* no tree diffs in patch format */
2358 run_checkdiff(p, o);
2361 int diff_queue_is_empty(void)
2363 struct diff_queue_struct *q = &diff_queued_diff;
2364 int i;
2365 for (i = 0; i < q->nr; i++)
2366 if (!diff_unmodified_pair(q->queue[i]))
2367 return 0;
2368 return 1;
2371 #if DIFF_DEBUG
2372 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2374 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2375 x, one ? one : "",
2376 s->path,
2377 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2378 s->mode,
2379 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2380 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2381 x, one ? one : "",
2382 s->size, s->xfrm_flags);
2385 void diff_debug_filepair(const struct diff_filepair *p, int i)
2387 diff_debug_filespec(p->one, i, "one");
2388 diff_debug_filespec(p->two, i, "two");
2389 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2390 p->score, p->status ? p->status : '?',
2391 p->source_stays, p->broken_pair);
2394 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2396 int i;
2397 if (msg)
2398 fprintf(stderr, "%s\n", msg);
2399 fprintf(stderr, "q->nr = %d\n", q->nr);
2400 for (i = 0; i < q->nr; i++) {
2401 struct diff_filepair *p = q->queue[i];
2402 diff_debug_filepair(p, i);
2405 #endif
2407 static void diff_resolve_rename_copy(void)
2409 int i, j;
2410 struct diff_filepair *p, *pp;
2411 struct diff_queue_struct *q = &diff_queued_diff;
2413 diff_debug_queue("resolve-rename-copy", q);
2415 for (i = 0; i < q->nr; i++) {
2416 p = q->queue[i];
2417 p->status = 0; /* undecided */
2418 if (DIFF_PAIR_UNMERGED(p))
2419 p->status = DIFF_STATUS_UNMERGED;
2420 else if (!DIFF_FILE_VALID(p->one))
2421 p->status = DIFF_STATUS_ADDED;
2422 else if (!DIFF_FILE_VALID(p->two))
2423 p->status = DIFF_STATUS_DELETED;
2424 else if (DIFF_PAIR_TYPE_CHANGED(p))
2425 p->status = DIFF_STATUS_TYPE_CHANGED;
2427 /* from this point on, we are dealing with a pair
2428 * whose both sides are valid and of the same type, i.e.
2429 * either in-place edit or rename/copy edit.
2431 else if (DIFF_PAIR_RENAME(p)) {
2432 if (p->source_stays) {
2433 p->status = DIFF_STATUS_COPIED;
2434 continue;
2436 /* See if there is some other filepair that
2437 * copies from the same source as us. If so
2438 * we are a copy. Otherwise we are either a
2439 * copy if the path stays, or a rename if it
2440 * does not, but we already handled "stays" case.
2442 for (j = i + 1; j < q->nr; j++) {
2443 pp = q->queue[j];
2444 if (strcmp(pp->one->path, p->one->path))
2445 continue; /* not us */
2446 if (!DIFF_PAIR_RENAME(pp))
2447 continue; /* not a rename/copy */
2448 /* pp is a rename/copy from the same source */
2449 p->status = DIFF_STATUS_COPIED;
2450 break;
2452 if (!p->status)
2453 p->status = DIFF_STATUS_RENAMED;
2455 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2456 p->one->mode != p->two->mode)
2457 p->status = DIFF_STATUS_MODIFIED;
2458 else {
2459 /* This is a "no-change" entry and should not
2460 * happen anymore, but prepare for broken callers.
2462 error("feeding unmodified %s to diffcore",
2463 p->one->path);
2464 p->status = DIFF_STATUS_UNKNOWN;
2467 diff_debug_queue("resolve-rename-copy done", q);
2470 static int check_pair_status(struct diff_filepair *p)
2472 switch (p->status) {
2473 case DIFF_STATUS_UNKNOWN:
2474 return 0;
2475 case 0:
2476 die("internal error in diff-resolve-rename-copy");
2477 default:
2478 return 1;
2482 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2484 int fmt = opt->output_format;
2486 if (fmt & DIFF_FORMAT_CHECKDIFF)
2487 diff_flush_checkdiff(p, opt);
2488 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2489 diff_flush_raw(p, opt);
2490 else if (fmt & DIFF_FORMAT_NAME)
2491 diff_flush_name(p, opt);
2494 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2496 char *name = quote_one(fs->path);
2497 if (fs->mode)
2498 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2499 else
2500 printf(" %s %s\n", newdelete, name);
2501 free(name);
2505 static void show_mode_change(struct diff_filepair *p, int show_name)
2507 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2508 if (show_name) {
2509 char *name = quote_one(p->two->path);
2510 printf(" mode change %06o => %06o %s\n",
2511 p->one->mode, p->two->mode, name);
2512 free(name);
2514 else
2515 printf(" mode change %06o => %06o\n",
2516 p->one->mode, p->two->mode);
2520 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2522 char *names = pprint_rename(p->one->path, p->two->path);
2524 printf(" %s %s (%d%%)\n", renamecopy, names,
2525 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2526 free(names);
2527 show_mode_change(p, 0);
2530 static void diff_summary(struct diff_filepair *p)
2532 switch(p->status) {
2533 case DIFF_STATUS_DELETED:
2534 show_file_mode_name("delete", p->one);
2535 break;
2536 case DIFF_STATUS_ADDED:
2537 show_file_mode_name("create", p->two);
2538 break;
2539 case DIFF_STATUS_COPIED:
2540 show_rename_copy("copy", p);
2541 break;
2542 case DIFF_STATUS_RENAMED:
2543 show_rename_copy("rename", p);
2544 break;
2545 default:
2546 if (p->score) {
2547 char *name = quote_one(p->two->path);
2548 printf(" rewrite %s (%d%%)\n", name,
2549 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2550 free(name);
2551 show_mode_change(p, 0);
2552 } else show_mode_change(p, 1);
2553 break;
2557 struct patch_id_t {
2558 struct xdiff_emit_state xm;
2559 SHA_CTX *ctx;
2560 int patchlen;
2563 static int remove_space(char *line, int len)
2565 int i;
2566 char *dst = line;
2567 unsigned char c;
2569 for (i = 0; i < len; i++)
2570 if (!isspace((c = line[i])))
2571 *dst++ = c;
2573 return dst - line;
2576 static void patch_id_consume(void *priv, char *line, unsigned long len)
2578 struct patch_id_t *data = priv;
2579 int new_len;
2581 /* Ignore line numbers when computing the SHA1 of the patch */
2582 if (!prefixcmp(line, "@@ -"))
2583 return;
2585 new_len = remove_space(line, len);
2587 SHA1_Update(data->ctx, line, new_len);
2588 data->patchlen += new_len;
2591 /* returns 0 upon success, and writes result into sha1 */
2592 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2594 struct diff_queue_struct *q = &diff_queued_diff;
2595 int i;
2596 SHA_CTX ctx;
2597 struct patch_id_t data;
2598 char buffer[PATH_MAX * 4 + 20];
2600 SHA1_Init(&ctx);
2601 memset(&data, 0, sizeof(struct patch_id_t));
2602 data.ctx = &ctx;
2603 data.xm.consume = patch_id_consume;
2605 for (i = 0; i < q->nr; i++) {
2606 xpparam_t xpp;
2607 xdemitconf_t xecfg;
2608 xdemitcb_t ecb;
2609 mmfile_t mf1, mf2;
2610 struct diff_filepair *p = q->queue[i];
2611 int len1, len2;
2613 if (p->status == 0)
2614 return error("internal diff status error");
2615 if (p->status == DIFF_STATUS_UNKNOWN)
2616 continue;
2617 if (diff_unmodified_pair(p))
2618 continue;
2619 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2620 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2621 continue;
2622 if (DIFF_PAIR_UNMERGED(p))
2623 continue;
2625 diff_fill_sha1_info(p->one);
2626 diff_fill_sha1_info(p->two);
2627 if (fill_mmfile(&mf1, p->one) < 0 ||
2628 fill_mmfile(&mf2, p->two) < 0)
2629 return error("unable to read files to diff");
2631 /* Maybe hash p->two? into the patch id? */
2632 if (mmfile_is_binary(&mf2))
2633 continue;
2635 len1 = remove_space(p->one->path, strlen(p->one->path));
2636 len2 = remove_space(p->two->path, strlen(p->two->path));
2637 if (p->one->mode == 0)
2638 len1 = snprintf(buffer, sizeof(buffer),
2639 "diff--gita/%.*sb/%.*s"
2640 "newfilemode%06o"
2641 "---/dev/null"
2642 "+++b/%.*s",
2643 len1, p->one->path,
2644 len2, p->two->path,
2645 p->two->mode,
2646 len2, p->two->path);
2647 else if (p->two->mode == 0)
2648 len1 = snprintf(buffer, sizeof(buffer),
2649 "diff--gita/%.*sb/%.*s"
2650 "deletedfilemode%06o"
2651 "---a/%.*s"
2652 "+++/dev/null",
2653 len1, p->one->path,
2654 len2, p->two->path,
2655 p->one->mode,
2656 len1, p->one->path);
2657 else
2658 len1 = snprintf(buffer, sizeof(buffer),
2659 "diff--gita/%.*sb/%.*s"
2660 "---a/%.*s"
2661 "+++b/%.*s",
2662 len1, p->one->path,
2663 len2, p->two->path,
2664 len1, p->one->path,
2665 len2, p->two->path);
2666 SHA1_Update(&ctx, buffer, len1);
2668 xpp.flags = XDF_NEED_MINIMAL;
2669 xecfg.ctxlen = 3;
2670 xecfg.flags = XDL_EMIT_FUNCNAMES;
2671 ecb.outf = xdiff_outf;
2672 ecb.priv = &data;
2673 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2676 SHA1_Final(sha1, &ctx);
2677 return 0;
2680 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2682 struct diff_queue_struct *q = &diff_queued_diff;
2683 int i;
2684 int result = diff_get_patch_id(options, sha1);
2686 for (i = 0; i < q->nr; i++)
2687 diff_free_filepair(q->queue[i]);
2689 free(q->queue);
2690 q->queue = NULL;
2691 q->nr = q->alloc = 0;
2693 return result;
2696 static int is_summary_empty(const struct diff_queue_struct *q)
2698 int i;
2700 for (i = 0; i < q->nr; i++) {
2701 const struct diff_filepair *p = q->queue[i];
2703 switch (p->status) {
2704 case DIFF_STATUS_DELETED:
2705 case DIFF_STATUS_ADDED:
2706 case DIFF_STATUS_COPIED:
2707 case DIFF_STATUS_RENAMED:
2708 return 0;
2709 default:
2710 if (p->score)
2711 return 0;
2712 if (p->one->mode && p->two->mode &&
2713 p->one->mode != p->two->mode)
2714 return 0;
2715 break;
2718 return 1;
2721 void diff_flush(struct diff_options *options)
2723 struct diff_queue_struct *q = &diff_queued_diff;
2724 int i, output_format = options->output_format;
2725 int separator = 0;
2728 * Order: raw, stat, summary, patch
2729 * or: name/name-status/checkdiff (other bits clear)
2731 if (!q->nr)
2732 goto free_queue;
2734 if (output_format & (DIFF_FORMAT_RAW |
2735 DIFF_FORMAT_NAME |
2736 DIFF_FORMAT_NAME_STATUS |
2737 DIFF_FORMAT_CHECKDIFF)) {
2738 for (i = 0; i < q->nr; i++) {
2739 struct diff_filepair *p = q->queue[i];
2740 if (check_pair_status(p))
2741 flush_one_pair(p, options);
2743 separator++;
2746 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
2747 struct diffstat_t diffstat;
2749 memset(&diffstat, 0, sizeof(struct diffstat_t));
2750 diffstat.xm.consume = diffstat_consume;
2751 for (i = 0; i < q->nr; i++) {
2752 struct diff_filepair *p = q->queue[i];
2753 if (check_pair_status(p))
2754 diff_flush_stat(p, options, &diffstat);
2756 if (output_format & DIFF_FORMAT_NUMSTAT)
2757 show_numstat(&diffstat, options);
2758 if (output_format & DIFF_FORMAT_DIFFSTAT)
2759 show_stats(&diffstat, options);
2760 else if (output_format & DIFF_FORMAT_SHORTSTAT)
2761 show_shortstats(&diffstat);
2762 separator++;
2765 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2766 for (i = 0; i < q->nr; i++)
2767 diff_summary(q->queue[i]);
2768 separator++;
2771 if (output_format & DIFF_FORMAT_PATCH) {
2772 if (separator) {
2773 if (options->stat_sep) {
2774 /* attach patch instead of inline */
2775 fputs(options->stat_sep, stdout);
2776 } else {
2777 putchar(options->line_termination);
2781 for (i = 0; i < q->nr; i++) {
2782 struct diff_filepair *p = q->queue[i];
2783 if (check_pair_status(p))
2784 diff_flush_patch(p, options);
2788 if (output_format & DIFF_FORMAT_CALLBACK)
2789 options->format_callback(q, options, options->format_callback_data);
2791 for (i = 0; i < q->nr; i++)
2792 diff_free_filepair(q->queue[i]);
2793 free_queue:
2794 free(q->queue);
2795 q->queue = NULL;
2796 q->nr = q->alloc = 0;
2799 static void diffcore_apply_filter(const char *filter)
2801 int i;
2802 struct diff_queue_struct *q = &diff_queued_diff;
2803 struct diff_queue_struct outq;
2804 outq.queue = NULL;
2805 outq.nr = outq.alloc = 0;
2807 if (!filter)
2808 return;
2810 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2811 int found;
2812 for (i = found = 0; !found && i < q->nr; i++) {
2813 struct diff_filepair *p = q->queue[i];
2814 if (((p->status == DIFF_STATUS_MODIFIED) &&
2815 ((p->score &&
2816 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2817 (!p->score &&
2818 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2819 ((p->status != DIFF_STATUS_MODIFIED) &&
2820 strchr(filter, p->status)))
2821 found++;
2823 if (found)
2824 return;
2826 /* otherwise we will clear the whole queue
2827 * by copying the empty outq at the end of this
2828 * function, but first clear the current entries
2829 * in the queue.
2831 for (i = 0; i < q->nr; i++)
2832 diff_free_filepair(q->queue[i]);
2834 else {
2835 /* Only the matching ones */
2836 for (i = 0; i < q->nr; i++) {
2837 struct diff_filepair *p = q->queue[i];
2839 if (((p->status == DIFF_STATUS_MODIFIED) &&
2840 ((p->score &&
2841 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2842 (!p->score &&
2843 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2844 ((p->status != DIFF_STATUS_MODIFIED) &&
2845 strchr(filter, p->status)))
2846 diff_q(&outq, p);
2847 else
2848 diff_free_filepair(p);
2851 free(q->queue);
2852 *q = outq;
2855 void diffcore_std(struct diff_options *options)
2857 if (options->break_opt != -1)
2858 diffcore_break(options->break_opt);
2859 if (options->detect_rename)
2860 diffcore_rename(options);
2861 if (options->break_opt != -1)
2862 diffcore_merge_broken();
2863 if (options->pickaxe)
2864 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2865 if (options->orderfile)
2866 diffcore_order(options->orderfile);
2867 diff_resolve_rename_copy();
2868 diffcore_apply_filter(options->filter);
2872 void diffcore_std_no_resolve(struct diff_options *options)
2874 if (options->pickaxe)
2875 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2876 if (options->orderfile)
2877 diffcore_order(options->orderfile);
2878 diffcore_apply_filter(options->filter);
2881 void diff_addremove(struct diff_options *options,
2882 int addremove, unsigned mode,
2883 const unsigned char *sha1,
2884 const char *base, const char *path)
2886 char concatpath[PATH_MAX];
2887 struct diff_filespec *one, *two;
2889 /* This may look odd, but it is a preparation for
2890 * feeding "there are unchanged files which should
2891 * not produce diffs, but when you are doing copy
2892 * detection you would need them, so here they are"
2893 * entries to the diff-core. They will be prefixed
2894 * with something like '=' or '*' (I haven't decided
2895 * which but should not make any difference).
2896 * Feeding the same new and old to diff_change()
2897 * also has the same effect.
2898 * Before the final output happens, they are pruned after
2899 * merged into rename/copy pairs as appropriate.
2901 if (options->reverse_diff)
2902 addremove = (addremove == '+' ? '-' :
2903 addremove == '-' ? '+' : addremove);
2905 if (!path) path = "";
2906 sprintf(concatpath, "%s%s", base, path);
2907 one = alloc_filespec(concatpath);
2908 two = alloc_filespec(concatpath);
2910 if (addremove != '+')
2911 fill_filespec(one, sha1, mode);
2912 if (addremove != '-')
2913 fill_filespec(two, sha1, mode);
2915 diff_queue(&diff_queued_diff, one, two);
2918 void diff_change(struct diff_options *options,
2919 unsigned old_mode, unsigned new_mode,
2920 const unsigned char *old_sha1,
2921 const unsigned char *new_sha1,
2922 const char *base, const char *path)
2924 char concatpath[PATH_MAX];
2925 struct diff_filespec *one, *two;
2927 if (options->reverse_diff) {
2928 unsigned tmp;
2929 const unsigned char *tmp_c;
2930 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2931 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2933 if (!path) path = "";
2934 sprintf(concatpath, "%s%s", base, path);
2935 one = alloc_filespec(concatpath);
2936 two = alloc_filespec(concatpath);
2937 fill_filespec(one, old_sha1, old_mode);
2938 fill_filespec(two, new_sha1, new_mode);
2940 diff_queue(&diff_queued_diff, one, two);
2943 void diff_unmerge(struct diff_options *options,
2944 const char *path,
2945 unsigned mode, const unsigned char *sha1)
2947 struct diff_filespec *one, *two;
2948 one = alloc_filespec(path);
2949 two = alloc_filespec(path);
2950 fill_filespec(one, sha1, mode);
2951 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;