Flush stdout before closing it.
[git/mingw.git] / diff.c
blobf463488e7eb7ec20f21a64387aa1f071503b450f
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 "spawn-pipe.h"
13 #ifdef NO_FAST_WORKING_DIRECTORY
14 #define FAST_WORKING_DIRECTORY 0
15 #else
16 #define FAST_WORKING_DIRECTORY 1
17 #endif
19 static int use_size_cache;
21 static int diff_detect_rename_default;
22 static int diff_rename_limit_default = -1;
23 static int diff_use_color_default;
25 static char diff_colors[][COLOR_MAXLEN] = {
26 "\033[m", /* reset */
27 "", /* PLAIN (normal) */
28 "\033[1m", /* METAINFO (bold) */
29 "\033[36m", /* FRAGINFO (cyan) */
30 "\033[31m", /* OLD (red) */
31 "\033[32m", /* NEW (green) */
32 "\033[33m", /* COMMIT (yellow) */
33 "\033[41m", /* WHITESPACE (red background) */
36 static int parse_diff_color_slot(const char *var, int ofs)
38 if (!strcasecmp(var+ofs, "plain"))
39 return DIFF_PLAIN;
40 if (!strcasecmp(var+ofs, "meta"))
41 return DIFF_METAINFO;
42 if (!strcasecmp(var+ofs, "frag"))
43 return DIFF_FRAGINFO;
44 if (!strcasecmp(var+ofs, "old"))
45 return DIFF_FILE_OLD;
46 if (!strcasecmp(var+ofs, "new"))
47 return DIFF_FILE_NEW;
48 if (!strcasecmp(var+ofs, "commit"))
49 return DIFF_COMMIT;
50 if (!strcasecmp(var+ofs, "whitespace"))
51 return DIFF_WHITESPACE;
52 die("bad config variable '%s'", var);
56 * These are to give UI layer defaults.
57 * The core-level commands such as git-diff-files should
58 * never be affected by the setting of diff.renames
59 * the user happens to have in the configuration file.
61 int git_diff_ui_config(const char *var, const char *value)
63 if (!strcmp(var, "diff.renamelimit")) {
64 diff_rename_limit_default = git_config_int(var, value);
65 return 0;
67 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
68 diff_use_color_default = git_config_colorbool(var, value);
69 return 0;
71 if (!strcmp(var, "diff.renames")) {
72 if (!value)
73 diff_detect_rename_default = DIFF_DETECT_RENAME;
74 else if (!strcasecmp(value, "copies") ||
75 !strcasecmp(value, "copy"))
76 diff_detect_rename_default = DIFF_DETECT_COPY;
77 else if (git_config_bool(var,value))
78 diff_detect_rename_default = DIFF_DETECT_RENAME;
79 return 0;
81 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
82 int slot = parse_diff_color_slot(var, 11);
83 color_parse(value, var, diff_colors[slot]);
84 return 0;
86 return git_default_config(var, value);
89 static char *quote_one(const char *str)
91 int needlen;
92 char *xp;
94 if (!str)
95 return NULL;
96 needlen = quote_c_style(str, NULL, NULL, 0);
97 if (!needlen)
98 return xstrdup(str);
99 xp = xmalloc(needlen + 1);
100 quote_c_style(str, xp, NULL, 0);
101 return xp;
104 static char *quote_two(const char *one, const char *two)
106 int need_one = quote_c_style(one, NULL, NULL, 1);
107 int need_two = quote_c_style(two, NULL, NULL, 1);
108 char *xp;
110 if (need_one + need_two) {
111 if (!need_one) need_one = strlen(one);
112 if (!need_two) need_one = strlen(two);
114 xp = xmalloc(need_one + need_two + 3);
115 xp[0] = '"';
116 quote_c_style(one, xp + 1, NULL, 1);
117 quote_c_style(two, xp + need_one + 1, NULL, 1);
118 strcpy(xp + need_one + need_two + 1, "\"");
119 return xp;
121 need_one = strlen(one);
122 need_two = strlen(two);
123 xp = xmalloc(need_one + need_two + 1);
124 strcpy(xp, one);
125 strcpy(xp + need_one, two);
126 return xp;
129 static const char *external_diff(void)
131 static const char *external_diff_cmd = NULL;
132 static int done_preparing = 0;
134 if (done_preparing)
135 return external_diff_cmd;
136 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
137 done_preparing = 1;
138 return external_diff_cmd;
141 #define TEMPFILE_PATH_LEN 50
143 static struct diff_tempfile {
144 const char *name; /* filename external diff should read from */
145 char hex[41];
146 char mode[10];
147 char tmp_path[TEMPFILE_PATH_LEN];
148 } diff_temp[2];
150 static int count_lines(const char *data, int size)
152 int count, ch, completely_empty = 1, nl_just_seen = 0;
153 count = 0;
154 while (0 < size--) {
155 ch = *data++;
156 if (ch == '\n') {
157 count++;
158 nl_just_seen = 1;
159 completely_empty = 0;
161 else {
162 nl_just_seen = 0;
163 completely_empty = 0;
166 if (completely_empty)
167 return 0;
168 if (!nl_just_seen)
169 count++; /* no trailing newline */
170 return count;
173 static void print_line_count(int count)
175 switch (count) {
176 case 0:
177 printf("0,0");
178 break;
179 case 1:
180 printf("1");
181 break;
182 default:
183 printf("1,%d", count);
184 break;
188 static void copy_file(int prefix, const char *data, int size,
189 const char *set, const char *reset)
191 int ch, nl_just_seen = 1;
192 while (0 < size--) {
193 ch = *data++;
194 if (nl_just_seen) {
195 fputs(set, stdout);
196 putchar(prefix);
198 if (ch == '\n') {
199 nl_just_seen = 1;
200 fputs(reset, stdout);
201 } else
202 nl_just_seen = 0;
203 putchar(ch);
205 if (!nl_just_seen)
206 printf("%s\n\\ No newline at end of file\n", reset);
209 static void emit_rewrite_diff(const char *name_a,
210 const char *name_b,
211 struct diff_filespec *one,
212 struct diff_filespec *two,
213 int color_diff)
215 int lc_a, lc_b;
216 const char *name_a_tab, *name_b_tab;
217 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
218 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
219 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
220 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
221 const char *reset = diff_get_color(color_diff, DIFF_RESET);
223 name_a += (*name_a == '/');
224 name_b += (*name_b == '/');
225 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
226 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
228 diff_populate_filespec(one, 0);
229 diff_populate_filespec(two, 0);
230 lc_a = count_lines(one->data, one->size);
231 lc_b = count_lines(two->data, two->size);
232 printf("%s--- a/%s%s%s\n%s+++ b/%s%s%s\n%s@@ -",
233 metainfo, name_a, name_a_tab, reset,
234 metainfo, name_b, name_b_tab, reset, fraginfo);
235 print_line_count(lc_a);
236 printf(" +");
237 print_line_count(lc_b);
238 printf(" @@%s\n", reset);
239 if (lc_a)
240 copy_file('-', one->data, one->size, old, reset);
241 if (lc_b)
242 copy_file('+', two->data, two->size, new, reset);
245 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
247 if (!DIFF_FILE_VALID(one)) {
248 mf->ptr = (char *)""; /* does not matter */
249 mf->size = 0;
250 return 0;
252 else if (diff_populate_filespec(one, 0))
253 return -1;
254 mf->ptr = one->data;
255 mf->size = one->size;
256 return 0;
259 struct diff_words_buffer {
260 mmfile_t text;
261 long alloc;
262 long current; /* output pointer */
263 int suppressed_newline;
266 static void diff_words_append(char *line, unsigned long len,
267 struct diff_words_buffer *buffer)
269 if (buffer->text.size + len > buffer->alloc) {
270 buffer->alloc = (buffer->text.size + len) * 3 / 2;
271 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
273 line++;
274 len--;
275 memcpy(buffer->text.ptr + buffer->text.size, line, len);
276 buffer->text.size += len;
279 struct diff_words_data {
280 struct xdiff_emit_state xm;
281 struct diff_words_buffer minus, plus;
284 static void print_word(struct diff_words_buffer *buffer, int len, int color,
285 int suppress_newline)
287 const char *ptr;
288 int eol = 0;
290 if (len == 0)
291 return;
293 ptr = buffer->text.ptr + buffer->current;
294 buffer->current += len;
296 if (ptr[len - 1] == '\n') {
297 eol = 1;
298 len--;
301 fputs(diff_get_color(1, color), stdout);
302 fwrite(ptr, len, 1, stdout);
303 fputs(diff_get_color(1, DIFF_RESET), stdout);
305 if (eol) {
306 if (suppress_newline)
307 buffer->suppressed_newline = 1;
308 else
309 putchar('\n');
313 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
315 struct diff_words_data *diff_words = priv;
317 if (diff_words->minus.suppressed_newline) {
318 if (line[0] != '+')
319 putchar('\n');
320 diff_words->minus.suppressed_newline = 0;
323 len--;
324 switch (line[0]) {
325 case '-':
326 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
327 break;
328 case '+':
329 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
330 break;
331 case ' ':
332 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
333 diff_words->minus.current += len;
334 break;
338 /* this executes the word diff on the accumulated buffers */
339 static void diff_words_show(struct diff_words_data *diff_words)
341 xpparam_t xpp;
342 xdemitconf_t xecfg;
343 xdemitcb_t ecb;
344 mmfile_t minus, plus;
345 int i;
347 minus.size = diff_words->minus.text.size;
348 minus.ptr = xmalloc(minus.size);
349 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
350 for (i = 0; i < minus.size; i++)
351 if (isspace(minus.ptr[i]))
352 minus.ptr[i] = '\n';
353 diff_words->minus.current = 0;
355 plus.size = diff_words->plus.text.size;
356 plus.ptr = xmalloc(plus.size);
357 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
358 for (i = 0; i < plus.size; i++)
359 if (isspace(plus.ptr[i]))
360 plus.ptr[i] = '\n';
361 diff_words->plus.current = 0;
363 xpp.flags = XDF_NEED_MINIMAL;
364 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
365 xecfg.flags = 0;
366 ecb.outf = xdiff_outf;
367 ecb.priv = diff_words;
368 diff_words->xm.consume = fn_out_diff_words_aux;
369 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
371 free(minus.ptr);
372 free(plus.ptr);
373 diff_words->minus.text.size = diff_words->plus.text.size = 0;
375 if (diff_words->minus.suppressed_newline) {
376 putchar('\n');
377 diff_words->minus.suppressed_newline = 0;
381 struct emit_callback {
382 struct xdiff_emit_state xm;
383 int nparents, color_diff;
384 const char **label_path;
385 struct diff_words_data *diff_words;
388 static void free_diff_words_data(struct emit_callback *ecbdata)
390 if (ecbdata->diff_words) {
391 /* flush buffers */
392 if (ecbdata->diff_words->minus.text.size ||
393 ecbdata->diff_words->plus.text.size)
394 diff_words_show(ecbdata->diff_words);
396 if (ecbdata->diff_words->minus.text.ptr)
397 free (ecbdata->diff_words->minus.text.ptr);
398 if (ecbdata->diff_words->plus.text.ptr)
399 free (ecbdata->diff_words->plus.text.ptr);
400 free(ecbdata->diff_words);
401 ecbdata->diff_words = NULL;
405 const char *diff_get_color(int diff_use_color, enum color_diff ix)
407 if (diff_use_color)
408 return diff_colors[ix];
409 return "";
412 static void emit_line(const char *set, const char *reset, const char *line, int len)
414 if (len > 0 && line[len-1] == '\n')
415 len--;
416 fputs(set, stdout);
417 fwrite(line, len, 1, stdout);
418 puts(reset);
421 static void emit_line_with_ws(int nparents,
422 const char *set, const char *reset, const char *ws,
423 const char *line, int len)
425 int col0 = nparents;
426 int last_tab_in_indent = -1;
427 int last_space_in_indent = -1;
428 int i;
429 int tail = len;
430 int need_highlight_leading_space = 0;
431 /* The line is a newly added line. Does it have funny leading
432 * whitespaces? In indent, SP should never precede a TAB.
434 for (i = col0; i < len; i++) {
435 if (line[i] == '\t') {
436 last_tab_in_indent = i;
437 if (0 <= last_space_in_indent)
438 need_highlight_leading_space = 1;
440 else if (line[i] == ' ')
441 last_space_in_indent = i;
442 else
443 break;
445 fputs(set, stdout);
446 fwrite(line, col0, 1, stdout);
447 fputs(reset, stdout);
448 if (((i == len) || line[i] == '\n') && i != col0) {
449 /* The whole line was indent */
450 emit_line(ws, reset, line + col0, len - col0);
451 return;
453 i = col0;
454 if (need_highlight_leading_space) {
455 while (i < last_tab_in_indent) {
456 if (line[i] == ' ') {
457 fputs(ws, stdout);
458 putchar(' ');
459 fputs(reset, stdout);
461 else
462 putchar(line[i]);
463 i++;
466 tail = len - 1;
467 if (line[tail] == '\n' && i < tail)
468 tail--;
469 while (i < tail) {
470 if (!isspace(line[tail]))
471 break;
472 tail--;
474 if ((i < tail && line[tail + 1] != '\n')) {
475 /* This has whitespace between tail+1..len */
476 fputs(set, stdout);
477 fwrite(line + i, tail - i + 1, 1, stdout);
478 fputs(reset, stdout);
479 emit_line(ws, reset, line + tail + 1, len - tail - 1);
481 else
482 emit_line(set, reset, line + i, len - i);
485 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
487 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
488 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
490 if (!*ws)
491 emit_line(set, reset, line, len);
492 else
493 emit_line_with_ws(ecbdata->nparents, set, reset, ws,
494 line, len);
497 static void fn_out_consume(void *priv, char *line, unsigned long len)
499 int i;
500 int color;
501 struct emit_callback *ecbdata = priv;
502 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
503 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
505 if (ecbdata->label_path[0]) {
506 const char *name_a_tab, *name_b_tab;
508 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
509 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
511 printf("%s--- %s%s%s\n",
512 set, ecbdata->label_path[0], reset, name_a_tab);
513 printf("%s+++ %s%s%s\n",
514 set, ecbdata->label_path[1], reset, name_b_tab);
515 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
518 /* This is not really necessary for now because
519 * this codepath only deals with two-way diffs.
521 for (i = 0; i < len && line[i] == '@'; i++)
523 if (2 <= i && i < len && line[i] == ' ') {
524 ecbdata->nparents = i - 1;
525 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
526 reset, line, len);
527 return;
530 if (len < ecbdata->nparents) {
531 set = reset;
532 emit_line(reset, reset, line, len);
533 return;
536 color = DIFF_PLAIN;
537 if (ecbdata->diff_words && ecbdata->nparents != 1)
538 /* fall back to normal diff */
539 free_diff_words_data(ecbdata);
540 if (ecbdata->diff_words) {
541 if (line[0] == '-') {
542 diff_words_append(line, len,
543 &ecbdata->diff_words->minus);
544 return;
545 } else if (line[0] == '+') {
546 diff_words_append(line, len,
547 &ecbdata->diff_words->plus);
548 return;
550 if (ecbdata->diff_words->minus.text.size ||
551 ecbdata->diff_words->plus.text.size)
552 diff_words_show(ecbdata->diff_words);
553 line++;
554 len--;
555 emit_line(set, reset, line, len);
556 return;
558 for (i = 0; i < ecbdata->nparents && len; i++) {
559 if (line[i] == '-')
560 color = DIFF_FILE_OLD;
561 else if (line[i] == '+')
562 color = DIFF_FILE_NEW;
565 if (color != DIFF_FILE_NEW) {
566 emit_line(diff_get_color(ecbdata->color_diff, color),
567 reset, line, len);
568 return;
570 emit_add_line(reset, ecbdata, line, len);
573 static char *pprint_rename(const char *a, const char *b)
575 const char *old = a;
576 const char *new = b;
577 char *name = NULL;
578 int pfx_length, sfx_length;
579 int len_a = strlen(a);
580 int len_b = strlen(b);
581 int qlen_a = quote_c_style(a, NULL, NULL, 0);
582 int qlen_b = quote_c_style(b, NULL, NULL, 0);
584 if (qlen_a || qlen_b) {
585 if (qlen_a) len_a = qlen_a;
586 if (qlen_b) len_b = qlen_b;
587 name = xmalloc( len_a + len_b + 5 );
588 if (qlen_a)
589 quote_c_style(a, name, NULL, 0);
590 else
591 memcpy(name, a, len_a);
592 memcpy(name + len_a, " => ", 4);
593 if (qlen_b)
594 quote_c_style(b, name + len_a + 4, NULL, 0);
595 else
596 memcpy(name + len_a + 4, b, len_b + 1);
597 return name;
600 /* Find common prefix */
601 pfx_length = 0;
602 while (*old && *new && *old == *new) {
603 if (*old == '/')
604 pfx_length = old - a + 1;
605 old++;
606 new++;
609 /* Find common suffix */
610 old = a + len_a;
611 new = b + len_b;
612 sfx_length = 0;
613 while (a <= old && b <= new && *old == *new) {
614 if (*old == '/')
615 sfx_length = len_a - (old - a);
616 old--;
617 new--;
621 * pfx{mid-a => mid-b}sfx
622 * {pfx-a => pfx-b}sfx
623 * pfx{sfx-a => sfx-b}
624 * name-a => name-b
626 if (pfx_length + sfx_length) {
627 int a_midlen = len_a - pfx_length - sfx_length;
628 int b_midlen = len_b - pfx_length - sfx_length;
629 if (a_midlen < 0) a_midlen = 0;
630 if (b_midlen < 0) b_midlen = 0;
632 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
633 sprintf(name, "%.*s{%.*s => %.*s}%s",
634 pfx_length, a,
635 a_midlen, a + pfx_length,
636 b_midlen, b + pfx_length,
637 a + len_a - sfx_length);
639 else {
640 name = xmalloc(len_a + len_b + 5);
641 sprintf(name, "%s => %s", a, b);
643 return name;
646 struct diffstat_t {
647 struct xdiff_emit_state xm;
649 int nr;
650 int alloc;
651 struct diffstat_file {
652 char *name;
653 unsigned is_unmerged:1;
654 unsigned is_binary:1;
655 unsigned is_renamed:1;
656 unsigned int added, deleted;
657 } **files;
660 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
661 const char *name_a,
662 const char *name_b)
664 struct diffstat_file *x;
665 x = xcalloc(sizeof (*x), 1);
666 if (diffstat->nr == diffstat->alloc) {
667 diffstat->alloc = alloc_nr(diffstat->alloc);
668 diffstat->files = xrealloc(diffstat->files,
669 diffstat->alloc * sizeof(x));
671 diffstat->files[diffstat->nr++] = x;
672 if (name_b) {
673 x->name = pprint_rename(name_a, name_b);
674 x->is_renamed = 1;
676 else
677 x->name = xstrdup(name_a);
678 return x;
681 static void diffstat_consume(void *priv, char *line, unsigned long len)
683 struct diffstat_t *diffstat = priv;
684 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
686 if (line[0] == '+')
687 x->added++;
688 else if (line[0] == '-')
689 x->deleted++;
692 const char mime_boundary_leader[] = "------------";
694 static int scale_linear(int it, int width, int max_change)
697 * make sure that at least one '-' is printed if there were deletions,
698 * and likewise for '+'.
700 if (max_change < 2)
701 return it;
702 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
705 static void show_name(const char *prefix, const char *name, int len,
706 const char *reset, const char *set)
708 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
711 static void show_graph(char ch, int cnt, const char *set, const char *reset)
713 if (cnt <= 0)
714 return;
715 printf("%s", set);
716 while (cnt--)
717 putchar(ch);
718 printf("%s", reset);
721 static void show_stats(struct diffstat_t* data, struct diff_options *options)
723 int i, len, add, del, total, adds = 0, dels = 0;
724 int max_change = 0, max_len = 0;
725 int total_files = data->nr;
726 int width, name_width;
727 const char *reset, *set, *add_c, *del_c;
729 if (data->nr == 0)
730 return;
732 width = options->stat_width ? options->stat_width : 80;
733 name_width = options->stat_name_width ? options->stat_name_width : 50;
735 /* Sanity: give at least 5 columns to the graph,
736 * but leave at least 10 columns for the name.
738 if (width < name_width + 15) {
739 if (name_width <= 25)
740 width = name_width + 15;
741 else
742 name_width = width - 15;
745 /* Find the longest filename and max number of changes */
746 reset = diff_get_color(options->color_diff, DIFF_RESET);
747 set = diff_get_color(options->color_diff, DIFF_PLAIN);
748 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
749 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
751 for (i = 0; i < data->nr; i++) {
752 struct diffstat_file *file = data->files[i];
753 int change = file->added + file->deleted;
755 if (!file->is_renamed) { /* renames are already quoted by pprint_rename */
756 len = quote_c_style(file->name, NULL, NULL, 0);
757 if (len) {
758 char *qname = xmalloc(len + 1);
759 quote_c_style(file->name, qname, NULL, 0);
760 free(file->name);
761 file->name = qname;
765 len = strlen(file->name);
766 if (max_len < len)
767 max_len = len;
769 if (file->is_binary || file->is_unmerged)
770 continue;
771 if (max_change < change)
772 max_change = change;
775 /* Compute the width of the graph part;
776 * 10 is for one blank at the beginning of the line plus
777 * " | count " between the name and the graph.
779 * From here on, name_width is the width of the name area,
780 * and width is the width of the graph area.
782 name_width = (name_width < max_len) ? name_width : max_len;
783 if (width < (name_width + 10) + max_change)
784 width = width - (name_width + 10);
785 else
786 width = max_change;
788 for (i = 0; i < data->nr; i++) {
789 const char *prefix = "";
790 char *name = data->files[i]->name;
791 int added = data->files[i]->added;
792 int deleted = data->files[i]->deleted;
793 int name_len;
796 * "scale" the filename
798 len = name_width;
799 name_len = strlen(name);
800 if (name_width < name_len) {
801 char *slash;
802 prefix = "...";
803 len -= 3;
804 name += name_len - len;
805 slash = strchr(name, '/');
806 if (slash)
807 name = slash;
810 if (data->files[i]->is_binary) {
811 show_name(prefix, name, len, reset, set);
812 printf(" Bin\n");
813 goto free_diffstat_file;
815 else if (data->files[i]->is_unmerged) {
816 show_name(prefix, name, len, reset, set);
817 printf(" Unmerged\n");
818 goto free_diffstat_file;
820 else if (!data->files[i]->is_renamed &&
821 (added + deleted == 0)) {
822 total_files--;
823 goto free_diffstat_file;
827 * scale the add/delete
829 add = added;
830 del = deleted;
831 total = add + del;
832 adds += add;
833 dels += del;
835 if (width <= max_change) {
836 add = scale_linear(add, width, max_change);
837 del = scale_linear(del, width, max_change);
838 total = add + del;
840 show_name(prefix, name, len, reset, set);
841 printf("%5d ", added + deleted);
842 show_graph('+', add, add_c, reset);
843 show_graph('-', del, del_c, reset);
844 putchar('\n');
845 free_diffstat_file:
846 free(data->files[i]->name);
847 free(data->files[i]);
849 free(data->files);
850 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
851 set, total_files, adds, dels, reset);
854 static void show_shortstats(struct diffstat_t* data)
856 int i, adds = 0, dels = 0, total_files = data->nr;
858 if (data->nr == 0)
859 return;
861 for (i = 0; i < data->nr; i++) {
862 if (!data->files[i]->is_binary &&
863 !data->files[i]->is_unmerged) {
864 int added = data->files[i]->added;
865 int deleted= data->files[i]->deleted;
866 if (!data->files[i]->is_renamed &&
867 (added + deleted == 0)) {
868 total_files--;
869 } else {
870 adds += added;
871 dels += deleted;
874 free(data->files[i]->name);
875 free(data->files[i]);
877 free(data->files);
879 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
880 total_files, adds, dels);
883 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
885 int i;
887 for (i = 0; i < data->nr; i++) {
888 struct diffstat_file *file = data->files[i];
890 if (file->is_binary)
891 printf("-\t-\t");
892 else
893 printf("%d\t%d\t", file->added, file->deleted);
894 if (options->line_termination && !file->is_renamed &&
895 quote_c_style(file->name, NULL, NULL, 0))
896 quote_c_style(file->name, NULL, stdout, 0);
897 else
898 fputs(file->name, stdout);
899 putchar(options->line_termination);
903 struct checkdiff_t {
904 struct xdiff_emit_state xm;
905 const char *filename;
906 int lineno, color_diff;
909 static void checkdiff_consume(void *priv, char *line, unsigned long len)
911 struct checkdiff_t *data = priv;
912 const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
913 const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
914 const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
916 if (line[0] == '+') {
917 int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
919 /* check space before tab */
920 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
921 if (line[i] == ' ')
922 spaces++;
923 if (line[i - 1] == '\t' && spaces)
924 space_before_tab = 1;
926 /* check white space at line end */
927 if (line[len - 1] == '\n')
928 len--;
929 if (isspace(line[len - 1]))
930 white_space_at_end = 1;
932 if (space_before_tab || white_space_at_end) {
933 printf("%s:%d: %s", data->filename, data->lineno, ws);
934 if (space_before_tab) {
935 printf("space before tab");
936 if (white_space_at_end)
937 putchar(',');
939 if (white_space_at_end)
940 printf("white space at end");
941 printf(":%s ", reset);
942 emit_line_with_ws(1, set, reset, ws, line, len);
945 data->lineno++;
946 } else if (line[0] == ' ')
947 data->lineno++;
948 else if (line[0] == '@') {
949 char *plus = strchr(line, '+');
950 if (plus)
951 data->lineno = strtol(plus, NULL, 10);
952 else
953 die("invalid diff");
957 static unsigned char *deflate_it(char *data,
958 unsigned long size,
959 unsigned long *result_size)
961 int bound;
962 unsigned char *deflated;
963 z_stream stream;
965 memset(&stream, 0, sizeof(stream));
966 deflateInit(&stream, zlib_compression_level);
967 bound = deflateBound(&stream, size);
968 deflated = xmalloc(bound);
969 stream.next_out = deflated;
970 stream.avail_out = bound;
972 stream.next_in = (unsigned char *)data;
973 stream.avail_in = size;
974 while (deflate(&stream, Z_FINISH) == Z_OK)
975 ; /* nothing */
976 deflateEnd(&stream);
977 *result_size = stream.total_out;
978 return deflated;
981 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
983 void *cp;
984 void *delta;
985 void *deflated;
986 void *data;
987 unsigned long orig_size;
988 unsigned long delta_size;
989 unsigned long deflate_size;
990 unsigned long data_size;
992 /* We could do deflated delta, or we could do just deflated two,
993 * whichever is smaller.
995 delta = NULL;
996 deflated = deflate_it(two->ptr, two->size, &deflate_size);
997 if (one->size && two->size) {
998 delta = diff_delta(one->ptr, one->size,
999 two->ptr, two->size,
1000 &delta_size, deflate_size);
1001 if (delta) {
1002 void *to_free = delta;
1003 orig_size = delta_size;
1004 delta = deflate_it(delta, delta_size, &delta_size);
1005 free(to_free);
1009 if (delta && delta_size < deflate_size) {
1010 printf("delta %lu\n", orig_size);
1011 free(deflated);
1012 data = delta;
1013 data_size = delta_size;
1015 else {
1016 printf("literal %lu\n", two->size);
1017 free(delta);
1018 data = deflated;
1019 data_size = deflate_size;
1022 /* emit data encoded in base85 */
1023 cp = data;
1024 while (data_size) {
1025 int bytes = (52 < data_size) ? 52 : data_size;
1026 char line[70];
1027 data_size -= bytes;
1028 if (bytes <= 26)
1029 line[0] = bytes + 'A' - 1;
1030 else
1031 line[0] = bytes - 26 + 'a' - 1;
1032 encode_85(line + 1, cp, bytes);
1033 cp = (char *) cp + bytes;
1034 puts(line);
1036 printf("\n");
1037 free(data);
1040 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1042 printf("GIT binary patch\n");
1043 emit_binary_diff_body(one, two);
1044 emit_binary_diff_body(two, one);
1047 #define FIRST_FEW_BYTES 8000
1048 static int mmfile_is_binary(mmfile_t *mf)
1050 long sz = mf->size;
1051 if (FIRST_FEW_BYTES < sz)
1052 sz = FIRST_FEW_BYTES;
1053 return !!memchr(mf->ptr, 0, sz);
1056 static void builtin_diff(const char *name_a,
1057 const char *name_b,
1058 struct diff_filespec *one,
1059 struct diff_filespec *two,
1060 const char *xfrm_msg,
1061 struct diff_options *o,
1062 int complete_rewrite)
1064 mmfile_t mf1, mf2;
1065 const char *lbl[2];
1066 char *a_one, *b_two;
1067 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1068 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1070 a_one = quote_two("a/", name_a + (*name_a == '/'));
1071 b_two = quote_two("b/", name_b + (*name_b == '/'));
1072 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1073 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1074 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1075 if (lbl[0][0] == '/') {
1076 /* /dev/null */
1077 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1078 if (xfrm_msg && xfrm_msg[0])
1079 printf("%s%s%s\n", set, xfrm_msg, reset);
1081 else if (lbl[1][0] == '/') {
1082 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1083 if (xfrm_msg && xfrm_msg[0])
1084 printf("%s%s%s\n", set, xfrm_msg, reset);
1086 else {
1087 if (one->mode != two->mode) {
1088 printf("%sold mode %06o%s\n", set, one->mode, reset);
1089 printf("%snew mode %06o%s\n", set, two->mode, reset);
1091 if (xfrm_msg && xfrm_msg[0])
1092 printf("%s%s%s\n", set, xfrm_msg, reset);
1094 * we do not run diff between different kind
1095 * of objects.
1097 if ((one->mode ^ two->mode) & S_IFMT)
1098 goto free_ab_and_return;
1099 if (complete_rewrite) {
1100 emit_rewrite_diff(name_a, name_b, one, two,
1101 o->color_diff);
1102 goto free_ab_and_return;
1106 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1107 die("unable to read files to diff");
1109 if (!o->text && (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))) {
1110 /* Quite common confusing case */
1111 if (mf1.size == mf2.size &&
1112 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1113 goto free_ab_and_return;
1114 if (o->binary)
1115 emit_binary_diff(&mf1, &mf2);
1116 else
1117 printf("Binary files %s and %s differ\n",
1118 lbl[0], lbl[1]);
1120 else {
1121 /* Crazy xdl interfaces.. */
1122 const char *diffopts = getenv("GIT_DIFF_OPTS");
1123 xpparam_t xpp;
1124 xdemitconf_t xecfg;
1125 xdemitcb_t ecb;
1126 struct emit_callback ecbdata;
1128 memset(&ecbdata, 0, sizeof(ecbdata));
1129 ecbdata.label_path = lbl;
1130 ecbdata.color_diff = o->color_diff;
1131 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1132 xecfg.ctxlen = o->context;
1133 xecfg.flags = XDL_EMIT_FUNCNAMES;
1134 if (!diffopts)
1136 else if (!prefixcmp(diffopts, "--unified="))
1137 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1138 else if (!prefixcmp(diffopts, "-u"))
1139 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1140 ecb.outf = xdiff_outf;
1141 ecb.priv = &ecbdata;
1142 ecbdata.xm.consume = fn_out_consume;
1143 if (o->color_diff_words)
1144 ecbdata.diff_words =
1145 xcalloc(1, sizeof(struct diff_words_data));
1146 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1147 if (o->color_diff_words)
1148 free_diff_words_data(&ecbdata);
1151 free_ab_and_return:
1152 free(a_one);
1153 free(b_two);
1154 return;
1157 static void builtin_diffstat(const char *name_a, const char *name_b,
1158 struct diff_filespec *one,
1159 struct diff_filespec *two,
1160 struct diffstat_t *diffstat,
1161 struct diff_options *o,
1162 int complete_rewrite)
1164 mmfile_t mf1, mf2;
1165 struct diffstat_file *data;
1167 data = diffstat_add(diffstat, name_a, name_b);
1169 if (!one || !two) {
1170 data->is_unmerged = 1;
1171 return;
1173 if (complete_rewrite) {
1174 diff_populate_filespec(one, 0);
1175 diff_populate_filespec(two, 0);
1176 data->deleted = count_lines(one->data, one->size);
1177 data->added = count_lines(two->data, two->size);
1178 return;
1180 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1181 die("unable to read files to diff");
1183 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
1184 data->is_binary = 1;
1185 else {
1186 /* Crazy xdl interfaces.. */
1187 xpparam_t xpp;
1188 xdemitconf_t xecfg;
1189 xdemitcb_t ecb;
1191 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1192 xecfg.ctxlen = 0;
1193 xecfg.flags = 0;
1194 ecb.outf = xdiff_outf;
1195 ecb.priv = diffstat;
1196 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1200 static void builtin_checkdiff(const char *name_a, const char *name_b,
1201 struct diff_filespec *one,
1202 struct diff_filespec *two, struct diff_options *o)
1204 mmfile_t mf1, mf2;
1205 struct checkdiff_t data;
1207 if (!two)
1208 return;
1210 memset(&data, 0, sizeof(data));
1211 data.xm.consume = checkdiff_consume;
1212 data.filename = name_b ? name_b : name_a;
1213 data.lineno = 0;
1214 data.color_diff = o->color_diff;
1216 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1217 die("unable to read files to diff");
1219 if (mmfile_is_binary(&mf2))
1220 return;
1221 else {
1222 /* Crazy xdl interfaces.. */
1223 xpparam_t xpp;
1224 xdemitconf_t xecfg;
1225 xdemitcb_t ecb;
1227 xpp.flags = XDF_NEED_MINIMAL;
1228 xecfg.ctxlen = 0;
1229 xecfg.flags = 0;
1230 ecb.outf = xdiff_outf;
1231 ecb.priv = &data;
1232 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1236 struct diff_filespec *alloc_filespec(const char *path)
1238 int namelen = strlen(path);
1239 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1241 memset(spec, 0, sizeof(*spec));
1242 spec->path = (char *)(spec + 1);
1243 memcpy(spec->path, path, namelen+1);
1244 return spec;
1247 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1248 unsigned short mode)
1250 if (mode) {
1251 spec->mode = canon_mode(mode);
1252 hashcpy(spec->sha1, sha1);
1253 spec->sha1_valid = !is_null_sha1(sha1);
1258 * Given a name and sha1 pair, if the dircache tells us the file in
1259 * the work tree has that object contents, return true, so that
1260 * prepare_temp_file() does not have to inflate and extract.
1262 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1264 struct cache_entry *ce;
1265 struct stat st;
1266 int pos, len;
1268 /* We do not read the cache ourselves here, because the
1269 * benchmark with my previous version that always reads cache
1270 * shows that it makes things worse for diff-tree comparing
1271 * two linux-2.6 kernel trees in an already checked out work
1272 * tree. This is because most diff-tree comparisons deal with
1273 * only a small number of files, while reading the cache is
1274 * expensive for a large project, and its cost outweighs the
1275 * savings we get by not inflating the object to a temporary
1276 * file. Practically, this code only helps when we are used
1277 * by diff-cache --cached, which does read the cache before
1278 * calling us.
1280 if (!active_cache)
1281 return 0;
1283 /* We want to avoid the working directory if our caller
1284 * doesn't need the data in a normal file, this system
1285 * is rather slow with its stat/open/mmap/close syscalls,
1286 * and the object is contained in a pack file. The pack
1287 * is probably already open and will be faster to obtain
1288 * the data through than the working directory. Loose
1289 * objects however would tend to be slower as they need
1290 * to be individually opened and inflated.
1292 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1293 return 0;
1295 len = strlen(name);
1296 pos = cache_name_pos(name, len);
1297 if (pos < 0)
1298 return 0;
1299 ce = active_cache[pos];
1300 if ((lstat(name, &st) < 0) ||
1301 !S_ISREG(st.st_mode) || /* careful! */
1302 ce_match_stat(ce, &st, 0) ||
1303 hashcmp(sha1, ce->sha1))
1304 return 0;
1305 /* we return 1 only when we can stat, it is a regular file,
1306 * stat information matches, and sha1 recorded in the cache
1307 * matches. I.e. we know the file in the work tree really is
1308 * the same as the <name, sha1> pair.
1310 return 1;
1313 static struct sha1_size_cache {
1314 unsigned char sha1[20];
1315 unsigned long size;
1316 } **sha1_size_cache;
1317 static int sha1_size_cache_nr, sha1_size_cache_alloc;
1319 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
1320 int find_only,
1321 unsigned long size)
1323 int first, last;
1324 struct sha1_size_cache *e;
1326 first = 0;
1327 last = sha1_size_cache_nr;
1328 while (last > first) {
1329 int cmp, next = (last + first) >> 1;
1330 e = sha1_size_cache[next];
1331 cmp = hashcmp(e->sha1, sha1);
1332 if (!cmp)
1333 return e;
1334 if (cmp < 0) {
1335 last = next;
1336 continue;
1338 first = next+1;
1340 /* not found */
1341 if (find_only)
1342 return NULL;
1343 /* insert to make it at "first" */
1344 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
1345 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
1346 sha1_size_cache = xrealloc(sha1_size_cache,
1347 sha1_size_cache_alloc *
1348 sizeof(*sha1_size_cache));
1350 sha1_size_cache_nr++;
1351 if (first < sha1_size_cache_nr)
1352 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
1353 (sha1_size_cache_nr - first - 1) *
1354 sizeof(*sha1_size_cache));
1355 e = xmalloc(sizeof(struct sha1_size_cache));
1356 sha1_size_cache[first] = e;
1357 hashcpy(e->sha1, sha1);
1358 e->size = size;
1359 return e;
1363 * While doing rename detection and pickaxe operation, we may need to
1364 * grab the data for the blob (or file) for our own in-core comparison.
1365 * diff_filespec has data and size fields for this purpose.
1367 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1369 int err = 0;
1370 if (!DIFF_FILE_VALID(s))
1371 die("internal error: asking to populate invalid file.");
1372 if (S_ISDIR(s->mode))
1373 return -1;
1375 if (!use_size_cache)
1376 size_only = 0;
1378 if (s->data)
1379 return err;
1380 if (!s->sha1_valid ||
1381 reuse_worktree_file(s->path, s->sha1, 0)) {
1382 struct stat st;
1383 int fd;
1384 char *buf;
1385 unsigned long size;
1387 if (lstat(s->path, &st) < 0) {
1388 if (errno == ENOENT) {
1389 err_empty:
1390 err = -1;
1391 empty:
1392 s->data = (char *)"";
1393 s->size = 0;
1394 return err;
1397 s->size = st.st_size;
1398 if (!s->size)
1399 goto empty;
1400 if (size_only)
1401 return 0;
1402 if (S_ISLNK(st.st_mode)) {
1403 int ret;
1404 s->data = xmalloc(s->size);
1405 s->should_free = 1;
1406 ret = readlink(s->path, s->data, s->size);
1407 if (ret < 0) {
1408 free(s->data);
1409 goto err_empty;
1411 return 0;
1413 fd = open(s->path, O_RDONLY);
1414 if (fd < 0)
1415 goto err_empty;
1416 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1417 close(fd);
1418 s->should_munmap = 1;
1421 * Convert from working tree format to canonical git format
1423 buf = s->data;
1424 size = s->size;
1425 if (convert_to_git(s->path, &buf, &size)) {
1426 munmap(s->data, s->size);
1427 s->should_munmap = 0;
1428 s->data = buf;
1429 s->size = size;
1430 s->should_free = 1;
1433 else {
1434 char type[20];
1435 struct sha1_size_cache *e;
1437 if (size_only) {
1438 e = locate_size_cache(s->sha1, 1, 0);
1439 if (e) {
1440 s->size = e->size;
1441 return 0;
1443 if (!sha1_object_info(s->sha1, type, &s->size))
1444 locate_size_cache(s->sha1, 0, s->size);
1446 else {
1447 s->data = read_sha1_file(s->sha1, type, &s->size);
1448 s->should_free = 1;
1451 return 0;
1454 void diff_free_filespec_data(struct diff_filespec *s)
1456 if (s->should_free)
1457 free(s->data);
1458 else if (s->should_munmap)
1459 munmap(s->data, s->size);
1460 s->should_free = s->should_munmap = 0;
1461 s->data = NULL;
1462 free(s->cnt_data);
1463 s->cnt_data = NULL;
1466 static void prep_temp_blob(struct diff_tempfile *temp,
1467 void *blob,
1468 unsigned long size,
1469 const unsigned char *sha1,
1470 int mode)
1472 int fd;
1474 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1475 if (fd < 0)
1476 die("unable to create temp-file");
1477 if (write_in_full(fd, blob, size) != size)
1478 die("unable to write temp-file");
1479 close(fd);
1480 temp->name = temp->tmp_path;
1481 strcpy(temp->hex, sha1_to_hex(sha1));
1482 temp->hex[40] = 0;
1483 sprintf(temp->mode, "%06o", mode);
1486 static void prepare_temp_file(const char *name,
1487 struct diff_tempfile *temp,
1488 struct diff_filespec *one)
1490 if (!DIFF_FILE_VALID(one)) {
1491 not_a_valid_file:
1492 /* A '-' entry produces this for file-2, and
1493 * a '+' entry produces this for file-1.
1495 temp->name = "/dev/null";
1496 strcpy(temp->hex, ".");
1497 strcpy(temp->mode, ".");
1498 return;
1501 if (!one->sha1_valid ||
1502 reuse_worktree_file(name, one->sha1, 1)) {
1503 struct stat st;
1504 if (lstat(name, &st) < 0) {
1505 if (errno == ENOENT)
1506 goto not_a_valid_file;
1507 die("stat(%s): %s", name, strerror(errno));
1509 if (S_ISLNK(st.st_mode)) {
1510 int ret;
1511 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1512 if (sizeof(buf) <= st.st_size)
1513 die("symlink too long: %s", name);
1514 ret = readlink(name, buf, st.st_size);
1515 if (ret < 0)
1516 die("readlink(%s)", name);
1517 prep_temp_blob(temp, buf, st.st_size,
1518 (one->sha1_valid ?
1519 one->sha1 : null_sha1),
1520 (one->sha1_valid ?
1521 one->mode : S_IFLNK));
1523 else {
1524 /* we can borrow from the file in the work tree */
1525 temp->name = name;
1526 if (!one->sha1_valid)
1527 strcpy(temp->hex, sha1_to_hex(null_sha1));
1528 else
1529 strcpy(temp->hex, sha1_to_hex(one->sha1));
1530 /* Even though we may sometimes borrow the
1531 * contents from the work tree, we always want
1532 * one->mode. mode is trustworthy even when
1533 * !(one->sha1_valid), as long as
1534 * DIFF_FILE_VALID(one).
1536 sprintf(temp->mode, "%06o", one->mode);
1538 return;
1540 else {
1541 if (diff_populate_filespec(one, 0))
1542 die("cannot read data blob for %s", one->path);
1543 prep_temp_blob(temp, one->data, one->size,
1544 one->sha1, one->mode);
1548 static void remove_tempfile(void)
1550 int i;
1552 for (i = 0; i < 2; i++)
1553 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1554 unlink(diff_temp[i].name);
1555 diff_temp[i].name = NULL;
1559 static void remove_tempfile_on_signal(int signo)
1561 remove_tempfile();
1562 signal(SIGINT, SIG_DFL);
1563 raise(signo);
1566 static int spawn_prog(const char *pgm, const char **arg)
1568 pid_t pid;
1569 int status;
1571 fflush(NULL);
1572 pid = spawnvpe_pipe(pgm, arg, environ, NULL, NULL);
1573 if (pid < 0)
1574 die("unable to fork");
1576 while (waitpid(pid, &status, 0) < 0) {
1577 if (errno == EINTR)
1578 continue;
1579 return -1;
1582 /* Earlier we did not check the exit status because
1583 * diff exits non-zero if files are different, and
1584 * we are not interested in knowing that. It was a
1585 * mistake which made it harder to quit a diff-*
1586 * session that uses the git-apply-patch-script as
1587 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1588 * should also exit non-zero only when it wants to
1589 * abort the entire diff-* session.
1591 if (WIFEXITED(status) && !WEXITSTATUS(status))
1592 return 0;
1593 return -1;
1596 /* An external diff command takes:
1598 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1599 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1602 static void run_external_diff(const char *pgm,
1603 const char *name,
1604 const char *other,
1605 struct diff_filespec *one,
1606 struct diff_filespec *two,
1607 const char *xfrm_msg,
1608 int complete_rewrite)
1610 const char *spawn_arg[10];
1611 struct diff_tempfile *temp = diff_temp;
1612 int retval;
1613 static int atexit_asked = 0;
1614 const char *othername;
1615 const char **arg = &spawn_arg[1];
1617 othername = (other? other : name);
1618 if (one && two) {
1619 prepare_temp_file(name, &temp[0], one);
1620 prepare_temp_file(othername, &temp[1], two);
1621 if (! atexit_asked &&
1622 (temp[0].name == temp[0].tmp_path ||
1623 temp[1].name == temp[1].tmp_path)) {
1624 atexit_asked = 1;
1625 atexit(remove_tempfile);
1627 signal(SIGINT, remove_tempfile_on_signal);
1630 if (one && two) {
1631 *arg++ = name;
1632 *arg++ = temp[0].name;
1633 *arg++ = temp[0].hex;
1634 *arg++ = temp[0].mode;
1635 *arg++ = temp[1].name;
1636 *arg++ = temp[1].hex;
1637 *arg++ = temp[1].mode;
1638 if (other) {
1639 *arg++ = other;
1640 *arg++ = xfrm_msg;
1642 } else {
1643 *arg++ = name;
1645 *arg = NULL;
1646 retval = spawn_prog(pgm, spawn_arg);
1647 remove_tempfile();
1648 if (retval) {
1649 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1650 exit(1);
1654 static void run_diff_cmd(const char *pgm,
1655 const char *name,
1656 const char *other,
1657 struct diff_filespec *one,
1658 struct diff_filespec *two,
1659 const char *xfrm_msg,
1660 struct diff_options *o,
1661 int complete_rewrite)
1663 if (pgm) {
1664 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1665 complete_rewrite);
1666 return;
1668 if (one && two)
1669 builtin_diff(name, other ? other : name,
1670 one, two, xfrm_msg, o, complete_rewrite);
1671 else
1672 printf("* Unmerged path %s\n", name);
1675 static void diff_fill_sha1_info(struct diff_filespec *one)
1677 if (DIFF_FILE_VALID(one)) {
1678 if (!one->sha1_valid) {
1679 struct stat st;
1680 if (lstat(one->path, &st) < 0)
1681 die("stat %s", one->path);
1682 if (index_path(one->sha1, one->path, &st, 0))
1683 die("cannot hash %s\n", one->path);
1686 else
1687 hashclr(one->sha1);
1690 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1692 const char *pgm = external_diff();
1693 char msg[PATH_MAX*2+300], *xfrm_msg;
1694 struct diff_filespec *one;
1695 struct diff_filespec *two;
1696 const char *name;
1697 const char *other;
1698 char *name_munged, *other_munged;
1699 int complete_rewrite = 0;
1700 int len;
1702 if (DIFF_PAIR_UNMERGED(p)) {
1703 /* unmerged */
1704 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1705 return;
1708 name = p->one->path;
1709 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1710 name_munged = quote_one(name);
1711 other_munged = quote_one(other);
1712 one = p->one; two = p->two;
1714 diff_fill_sha1_info(one);
1715 diff_fill_sha1_info(two);
1717 len = 0;
1718 switch (p->status) {
1719 case DIFF_STATUS_COPIED:
1720 len += snprintf(msg + len, sizeof(msg) - len,
1721 "similarity index %d%%\n"
1722 "copy from %s\n"
1723 "copy to %s\n",
1724 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1725 name_munged, other_munged);
1726 break;
1727 case DIFF_STATUS_RENAMED:
1728 len += snprintf(msg + len, sizeof(msg) - len,
1729 "similarity index %d%%\n"
1730 "rename from %s\n"
1731 "rename to %s\n",
1732 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1733 name_munged, other_munged);
1734 break;
1735 case DIFF_STATUS_MODIFIED:
1736 if (p->score) {
1737 len += snprintf(msg + len, sizeof(msg) - len,
1738 "dissimilarity index %d%%\n",
1739 (int)(0.5 + p->score *
1740 100.0/MAX_SCORE));
1741 complete_rewrite = 1;
1742 break;
1744 /* fallthru */
1745 default:
1746 /* nothing */
1750 if (hashcmp(one->sha1, two->sha1)) {
1751 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1753 if (o->binary) {
1754 mmfile_t mf;
1755 if ((!fill_mmfile(&mf, one) && mmfile_is_binary(&mf)) ||
1756 (!fill_mmfile(&mf, two) && mmfile_is_binary(&mf)))
1757 abbrev = 40;
1759 len += snprintf(msg + len, sizeof(msg) - len,
1760 "index %.*s..%.*s",
1761 abbrev, sha1_to_hex(one->sha1),
1762 abbrev, sha1_to_hex(two->sha1));
1763 if (one->mode == two->mode)
1764 len += snprintf(msg + len, sizeof(msg) - len,
1765 " %06o", one->mode);
1766 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1769 if (len)
1770 msg[--len] = 0;
1771 xfrm_msg = len ? msg : NULL;
1773 if (!pgm &&
1774 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1775 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1776 /* a filepair that changes between file and symlink
1777 * needs to be split into deletion and creation.
1779 struct diff_filespec *null = alloc_filespec(two->path);
1780 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1781 free(null);
1782 null = alloc_filespec(one->path);
1783 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1784 free(null);
1786 else
1787 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1788 complete_rewrite);
1790 free(name_munged);
1791 free(other_munged);
1794 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1795 struct diffstat_t *diffstat)
1797 const char *name;
1798 const char *other;
1799 int complete_rewrite = 0;
1801 if (DIFF_PAIR_UNMERGED(p)) {
1802 /* unmerged */
1803 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1804 return;
1807 name = p->one->path;
1808 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1810 diff_fill_sha1_info(p->one);
1811 diff_fill_sha1_info(p->two);
1813 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1814 complete_rewrite = 1;
1815 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1818 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1820 const char *name;
1821 const char *other;
1823 if (DIFF_PAIR_UNMERGED(p)) {
1824 /* unmerged */
1825 return;
1828 name = p->one->path;
1829 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1831 diff_fill_sha1_info(p->one);
1832 diff_fill_sha1_info(p->two);
1834 builtin_checkdiff(name, other, p->one, p->two, o);
1837 void diff_setup(struct diff_options *options)
1839 memset(options, 0, sizeof(*options));
1840 options->line_termination = '\n';
1841 options->break_opt = -1;
1842 options->rename_limit = -1;
1843 options->context = 3;
1844 options->msg_sep = "";
1846 options->change = diff_change;
1847 options->add_remove = diff_addremove;
1848 options->color_diff = diff_use_color_default;
1849 options->detect_rename = diff_detect_rename_default;
1852 int diff_setup_done(struct diff_options *options)
1854 int count = 0;
1856 if (options->output_format & DIFF_FORMAT_NAME)
1857 count++;
1858 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
1859 count++;
1860 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
1861 count++;
1862 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
1863 count++;
1864 if (count > 1)
1865 die("--name-only, --name-status, --check and -s are mutually exclusive");
1867 if (options->find_copies_harder)
1868 options->detect_rename = DIFF_DETECT_COPY;
1870 if (options->output_format & (DIFF_FORMAT_NAME |
1871 DIFF_FORMAT_NAME_STATUS |
1872 DIFF_FORMAT_CHECKDIFF |
1873 DIFF_FORMAT_NO_OUTPUT))
1874 options->output_format &= ~(DIFF_FORMAT_RAW |
1875 DIFF_FORMAT_NUMSTAT |
1876 DIFF_FORMAT_DIFFSTAT |
1877 DIFF_FORMAT_SHORTSTAT |
1878 DIFF_FORMAT_SUMMARY |
1879 DIFF_FORMAT_PATCH);
1882 * These cases always need recursive; we do not drop caller-supplied
1883 * recursive bits for other formats here.
1885 if (options->output_format & (DIFF_FORMAT_PATCH |
1886 DIFF_FORMAT_NUMSTAT |
1887 DIFF_FORMAT_DIFFSTAT |
1888 DIFF_FORMAT_SHORTSTAT |
1889 DIFF_FORMAT_SUMMARY |
1890 DIFF_FORMAT_CHECKDIFF))
1891 options->recursive = 1;
1893 * Also pickaxe would not work very well if you do not say recursive
1895 if (options->pickaxe)
1896 options->recursive = 1;
1898 if (options->detect_rename && options->rename_limit < 0)
1899 options->rename_limit = diff_rename_limit_default;
1900 if (options->setup & DIFF_SETUP_USE_CACHE) {
1901 if (!active_cache)
1902 /* read-cache does not die even when it fails
1903 * so it is safe for us to do this here. Also
1904 * it does not smudge active_cache or active_nr
1905 * when it fails, so we do not have to worry about
1906 * cleaning it up ourselves either.
1908 read_cache();
1910 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1911 use_size_cache = 1;
1912 if (options->abbrev <= 0 || 40 < options->abbrev)
1913 options->abbrev = 40; /* full */
1915 return 0;
1918 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1920 char c, *eq;
1921 int len;
1923 if (*arg != '-')
1924 return 0;
1925 c = *++arg;
1926 if (!c)
1927 return 0;
1928 if (c == arg_short) {
1929 c = *++arg;
1930 if (!c)
1931 return 1;
1932 if (val && isdigit(c)) {
1933 char *end;
1934 int n = strtoul(arg, &end, 10);
1935 if (*end)
1936 return 0;
1937 *val = n;
1938 return 1;
1940 return 0;
1942 if (c != '-')
1943 return 0;
1944 arg++;
1945 eq = strchr(arg, '=');
1946 if (eq)
1947 len = eq - arg;
1948 else
1949 len = strlen(arg);
1950 if (!len || strncmp(arg, arg_long, len))
1951 return 0;
1952 if (eq) {
1953 int n;
1954 char *end;
1955 if (!isdigit(*++eq))
1956 return 0;
1957 n = strtoul(eq, &end, 10);
1958 if (*end)
1959 return 0;
1960 *val = n;
1962 return 1;
1965 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1967 const char *arg = av[0];
1968 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1969 options->output_format |= DIFF_FORMAT_PATCH;
1970 else if (opt_arg(arg, 'U', "unified", &options->context))
1971 options->output_format |= DIFF_FORMAT_PATCH;
1972 else if (!strcmp(arg, "--raw"))
1973 options->output_format |= DIFF_FORMAT_RAW;
1974 else if (!strcmp(arg, "--patch-with-raw")) {
1975 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
1977 else if (!strcmp(arg, "--numstat")) {
1978 options->output_format |= DIFF_FORMAT_NUMSTAT;
1980 else if (!strcmp(arg, "--shortstat")) {
1981 options->output_format |= DIFF_FORMAT_SHORTSTAT;
1983 else if (!prefixcmp(arg, "--stat")) {
1984 char *end;
1985 int width = options->stat_width;
1986 int name_width = options->stat_name_width;
1987 arg += 6;
1988 end = (char *)arg;
1990 switch (*arg) {
1991 case '-':
1992 if (!prefixcmp(arg, "-width="))
1993 width = strtoul(arg + 7, &end, 10);
1994 else if (!prefixcmp(arg, "-name-width="))
1995 name_width = strtoul(arg + 12, &end, 10);
1996 break;
1997 case '=':
1998 width = strtoul(arg+1, &end, 10);
1999 if (*end == ',')
2000 name_width = strtoul(end+1, &end, 10);
2003 /* Important! This checks all the error cases! */
2004 if (*end)
2005 return 0;
2006 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2007 options->stat_name_width = name_width;
2008 options->stat_width = width;
2010 else if (!strcmp(arg, "--check"))
2011 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2012 else if (!strcmp(arg, "--summary"))
2013 options->output_format |= DIFF_FORMAT_SUMMARY;
2014 else if (!strcmp(arg, "--patch-with-stat")) {
2015 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2017 else if (!strcmp(arg, "-z"))
2018 options->line_termination = 0;
2019 else if (!prefixcmp(arg, "-l"))
2020 options->rename_limit = strtoul(arg+2, NULL, 10);
2021 else if (!strcmp(arg, "--full-index"))
2022 options->full_index = 1;
2023 else if (!strcmp(arg, "--binary")) {
2024 options->output_format |= DIFF_FORMAT_PATCH;
2025 options->binary = 1;
2027 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
2028 options->text = 1;
2030 else if (!strcmp(arg, "--name-only"))
2031 options->output_format |= DIFF_FORMAT_NAME;
2032 else if (!strcmp(arg, "--name-status"))
2033 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2034 else if (!strcmp(arg, "-R"))
2035 options->reverse_diff = 1;
2036 else if (!prefixcmp(arg, "-S"))
2037 options->pickaxe = arg + 2;
2038 else if (!strcmp(arg, "-s")) {
2039 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2041 else if (!prefixcmp(arg, "-O"))
2042 options->orderfile = arg + 2;
2043 else if (!prefixcmp(arg, "--diff-filter="))
2044 options->filter = arg + 14;
2045 else if (!strcmp(arg, "--pickaxe-all"))
2046 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2047 else if (!strcmp(arg, "--pickaxe-regex"))
2048 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2049 else if (!prefixcmp(arg, "-B")) {
2050 if ((options->break_opt =
2051 diff_scoreopt_parse(arg)) == -1)
2052 return -1;
2054 else if (!prefixcmp(arg, "-M")) {
2055 if ((options->rename_score =
2056 diff_scoreopt_parse(arg)) == -1)
2057 return -1;
2058 options->detect_rename = DIFF_DETECT_RENAME;
2060 else if (!prefixcmp(arg, "-C")) {
2061 if ((options->rename_score =
2062 diff_scoreopt_parse(arg)) == -1)
2063 return -1;
2064 options->detect_rename = DIFF_DETECT_COPY;
2066 else if (!strcmp(arg, "--find-copies-harder"))
2067 options->find_copies_harder = 1;
2068 else if (!strcmp(arg, "--abbrev"))
2069 options->abbrev = DEFAULT_ABBREV;
2070 else if (!prefixcmp(arg, "--abbrev=")) {
2071 options->abbrev = strtoul(arg + 9, NULL, 10);
2072 if (options->abbrev < MINIMUM_ABBREV)
2073 options->abbrev = MINIMUM_ABBREV;
2074 else if (40 < options->abbrev)
2075 options->abbrev = 40;
2077 else if (!strcmp(arg, "--color"))
2078 options->color_diff = 1;
2079 else if (!strcmp(arg, "--no-color"))
2080 options->color_diff = 0;
2081 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2082 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2083 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2084 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2085 else if (!strcmp(arg, "--ignore-space-at-eol"))
2086 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2087 else if (!strcmp(arg, "--color-words"))
2088 options->color_diff = options->color_diff_words = 1;
2089 else if (!strcmp(arg, "--no-renames"))
2090 options->detect_rename = 0;
2091 else
2092 return 0;
2093 return 1;
2096 static int parse_num(const char **cp_p)
2098 unsigned long num, scale;
2099 int ch, dot;
2100 const char *cp = *cp_p;
2102 num = 0;
2103 scale = 1;
2104 dot = 0;
2105 for(;;) {
2106 ch = *cp;
2107 if ( !dot && ch == '.' ) {
2108 scale = 1;
2109 dot = 1;
2110 } else if ( ch == '%' ) {
2111 scale = dot ? scale*100 : 100;
2112 cp++; /* % is always at the end */
2113 break;
2114 } else if ( ch >= '0' && ch <= '9' ) {
2115 if ( scale < 100000 ) {
2116 scale *= 10;
2117 num = (num*10) + (ch-'0');
2119 } else {
2120 break;
2122 cp++;
2124 *cp_p = cp;
2126 /* user says num divided by scale and we say internally that
2127 * is MAX_SCORE * num / scale.
2129 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
2132 int diff_scoreopt_parse(const char *opt)
2134 int opt1, opt2, cmd;
2136 if (*opt++ != '-')
2137 return -1;
2138 cmd = *opt++;
2139 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2140 return -1; /* that is not a -M, -C nor -B option */
2142 opt1 = parse_num(&opt);
2143 if (cmd != 'B')
2144 opt2 = 0;
2145 else {
2146 if (*opt == 0)
2147 opt2 = 0;
2148 else if (*opt != '/')
2149 return -1; /* we expect -B80/99 or -B80 */
2150 else {
2151 opt++;
2152 opt2 = parse_num(&opt);
2155 if (*opt != 0)
2156 return -1;
2157 return opt1 | (opt2 << 16);
2160 struct diff_queue_struct diff_queued_diff;
2162 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2164 if (queue->alloc <= queue->nr) {
2165 queue->alloc = alloc_nr(queue->alloc);
2166 queue->queue = xrealloc(queue->queue,
2167 sizeof(dp) * queue->alloc);
2169 queue->queue[queue->nr++] = dp;
2172 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2173 struct diff_filespec *one,
2174 struct diff_filespec *two)
2176 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2177 dp->one = one;
2178 dp->two = two;
2179 if (queue)
2180 diff_q(queue, dp);
2181 return dp;
2184 void diff_free_filepair(struct diff_filepair *p)
2186 diff_free_filespec_data(p->one);
2187 diff_free_filespec_data(p->two);
2188 free(p->one);
2189 free(p->two);
2190 free(p);
2193 /* This is different from find_unique_abbrev() in that
2194 * it stuffs the result with dots for alignment.
2196 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2198 int abblen;
2199 const char *abbrev;
2200 if (len == 40)
2201 return sha1_to_hex(sha1);
2203 abbrev = find_unique_abbrev(sha1, len);
2204 if (!abbrev)
2205 return sha1_to_hex(sha1);
2206 abblen = strlen(abbrev);
2207 if (abblen < 37) {
2208 static char hex[41];
2209 if (len < abblen && abblen <= len + 2)
2210 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2211 else
2212 sprintf(hex, "%s...", abbrev);
2213 return hex;
2215 return sha1_to_hex(sha1);
2218 static void diff_flush_raw(struct diff_filepair *p,
2219 struct diff_options *options)
2221 int two_paths;
2222 char status[10];
2223 int abbrev = options->abbrev;
2224 const char *path_one, *path_two;
2225 int inter_name_termination = '\t';
2226 int line_termination = options->line_termination;
2228 if (!line_termination)
2229 inter_name_termination = 0;
2231 path_one = p->one->path;
2232 path_two = p->two->path;
2233 if (line_termination) {
2234 path_one = quote_one(path_one);
2235 path_two = quote_one(path_two);
2238 if (p->score)
2239 sprintf(status, "%c%03d", p->status,
2240 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2241 else {
2242 status[0] = p->status;
2243 status[1] = 0;
2245 switch (p->status) {
2246 case DIFF_STATUS_COPIED:
2247 case DIFF_STATUS_RENAMED:
2248 two_paths = 1;
2249 break;
2250 case DIFF_STATUS_ADDED:
2251 case DIFF_STATUS_DELETED:
2252 two_paths = 0;
2253 break;
2254 default:
2255 two_paths = 0;
2256 break;
2258 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2259 printf(":%06o %06o %s ",
2260 p->one->mode, p->two->mode,
2261 diff_unique_abbrev(p->one->sha1, abbrev));
2262 printf("%s ",
2263 diff_unique_abbrev(p->two->sha1, abbrev));
2265 printf("%s%c%s", status, inter_name_termination, path_one);
2266 if (two_paths)
2267 printf("%c%s", inter_name_termination, path_two);
2268 putchar(line_termination);
2269 if (path_one != p->one->path)
2270 free((void*)path_one);
2271 if (path_two != p->two->path)
2272 free((void*)path_two);
2275 static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2277 char *path = p->two->path;
2279 if (opt->line_termination)
2280 path = quote_one(p->two->path);
2281 printf("%s%c", path, opt->line_termination);
2282 if (p->two->path != path)
2283 free(path);
2286 int diff_unmodified_pair(struct diff_filepair *p)
2288 /* This function is written stricter than necessary to support
2289 * the currently implemented transformers, but the idea is to
2290 * let transformers to produce diff_filepairs any way they want,
2291 * and filter and clean them up here before producing the output.
2293 struct diff_filespec *one, *two;
2295 if (DIFF_PAIR_UNMERGED(p))
2296 return 0; /* unmerged is interesting */
2298 one = p->one;
2299 two = p->two;
2301 /* deletion, addition, mode or type change
2302 * and rename are all interesting.
2304 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2305 DIFF_PAIR_MODE_CHANGED(p) ||
2306 strcmp(one->path, two->path))
2307 return 0;
2309 /* both are valid and point at the same path. that is, we are
2310 * dealing with a change.
2312 if (one->sha1_valid && two->sha1_valid &&
2313 !hashcmp(one->sha1, two->sha1))
2314 return 1; /* no change */
2315 if (!one->sha1_valid && !two->sha1_valid)
2316 return 1; /* both look at the same file on the filesystem. */
2317 return 0;
2320 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2322 if (diff_unmodified_pair(p))
2323 return;
2325 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2326 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2327 return; /* no tree diffs in patch format */
2329 run_diff(p, o);
2332 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2333 struct diffstat_t *diffstat)
2335 if (diff_unmodified_pair(p))
2336 return;
2338 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2339 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2340 return; /* no tree diffs in patch format */
2342 run_diffstat(p, o, diffstat);
2345 static void diff_flush_checkdiff(struct diff_filepair *p,
2346 struct diff_options *o)
2348 if (diff_unmodified_pair(p))
2349 return;
2351 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2352 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2353 return; /* no tree diffs in patch format */
2355 run_checkdiff(p, o);
2358 int diff_queue_is_empty(void)
2360 struct diff_queue_struct *q = &diff_queued_diff;
2361 int i;
2362 for (i = 0; i < q->nr; i++)
2363 if (!diff_unmodified_pair(q->queue[i]))
2364 return 0;
2365 return 1;
2368 #if DIFF_DEBUG
2369 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2371 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2372 x, one ? one : "",
2373 s->path,
2374 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2375 s->mode,
2376 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2377 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2378 x, one ? one : "",
2379 s->size, s->xfrm_flags);
2382 void diff_debug_filepair(const struct diff_filepair *p, int i)
2384 diff_debug_filespec(p->one, i, "one");
2385 diff_debug_filespec(p->two, i, "two");
2386 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2387 p->score, p->status ? p->status : '?',
2388 p->source_stays, p->broken_pair);
2391 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2393 int i;
2394 if (msg)
2395 fprintf(stderr, "%s\n", msg);
2396 fprintf(stderr, "q->nr = %d\n", q->nr);
2397 for (i = 0; i < q->nr; i++) {
2398 struct diff_filepair *p = q->queue[i];
2399 diff_debug_filepair(p, i);
2402 #endif
2404 static void diff_resolve_rename_copy(void)
2406 int i, j;
2407 struct diff_filepair *p, *pp;
2408 struct diff_queue_struct *q = &diff_queued_diff;
2410 diff_debug_queue("resolve-rename-copy", q);
2412 for (i = 0; i < q->nr; i++) {
2413 p = q->queue[i];
2414 p->status = 0; /* undecided */
2415 if (DIFF_PAIR_UNMERGED(p))
2416 p->status = DIFF_STATUS_UNMERGED;
2417 else if (!DIFF_FILE_VALID(p->one))
2418 p->status = DIFF_STATUS_ADDED;
2419 else if (!DIFF_FILE_VALID(p->two))
2420 p->status = DIFF_STATUS_DELETED;
2421 else if (DIFF_PAIR_TYPE_CHANGED(p))
2422 p->status = DIFF_STATUS_TYPE_CHANGED;
2424 /* from this point on, we are dealing with a pair
2425 * whose both sides are valid and of the same type, i.e.
2426 * either in-place edit or rename/copy edit.
2428 else if (DIFF_PAIR_RENAME(p)) {
2429 if (p->source_stays) {
2430 p->status = DIFF_STATUS_COPIED;
2431 continue;
2433 /* See if there is some other filepair that
2434 * copies from the same source as us. If so
2435 * we are a copy. Otherwise we are either a
2436 * copy if the path stays, or a rename if it
2437 * does not, but we already handled "stays" case.
2439 for (j = i + 1; j < q->nr; j++) {
2440 pp = q->queue[j];
2441 if (strcmp(pp->one->path, p->one->path))
2442 continue; /* not us */
2443 if (!DIFF_PAIR_RENAME(pp))
2444 continue; /* not a rename/copy */
2445 /* pp is a rename/copy from the same source */
2446 p->status = DIFF_STATUS_COPIED;
2447 break;
2449 if (!p->status)
2450 p->status = DIFF_STATUS_RENAMED;
2452 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2453 p->one->mode != p->two->mode)
2454 p->status = DIFF_STATUS_MODIFIED;
2455 else {
2456 /* This is a "no-change" entry and should not
2457 * happen anymore, but prepare for broken callers.
2459 error("feeding unmodified %s to diffcore",
2460 p->one->path);
2461 p->status = DIFF_STATUS_UNKNOWN;
2464 diff_debug_queue("resolve-rename-copy done", q);
2467 static int check_pair_status(struct diff_filepair *p)
2469 switch (p->status) {
2470 case DIFF_STATUS_UNKNOWN:
2471 return 0;
2472 case 0:
2473 die("internal error in diff-resolve-rename-copy");
2474 default:
2475 return 1;
2479 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2481 int fmt = opt->output_format;
2483 if (fmt & DIFF_FORMAT_CHECKDIFF)
2484 diff_flush_checkdiff(p, opt);
2485 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2486 diff_flush_raw(p, opt);
2487 else if (fmt & DIFF_FORMAT_NAME)
2488 diff_flush_name(p, opt);
2491 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2493 char *name = quote_one(fs->path);
2494 if (fs->mode)
2495 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2496 else
2497 printf(" %s %s\n", newdelete, name);
2498 free(name);
2502 static void show_mode_change(struct diff_filepair *p, int show_name)
2504 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2505 if (show_name) {
2506 char *name = quote_one(p->two->path);
2507 printf(" mode change %06o => %06o %s\n",
2508 p->one->mode, p->two->mode, name);
2509 free(name);
2511 else
2512 printf(" mode change %06o => %06o\n",
2513 p->one->mode, p->two->mode);
2517 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2519 char *names = pprint_rename(p->one->path, p->two->path);
2521 printf(" %s %s (%d%%)\n", renamecopy, names,
2522 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2523 free(names);
2524 show_mode_change(p, 0);
2527 static void diff_summary(struct diff_filepair *p)
2529 switch(p->status) {
2530 case DIFF_STATUS_DELETED:
2531 show_file_mode_name("delete", p->one);
2532 break;
2533 case DIFF_STATUS_ADDED:
2534 show_file_mode_name("create", p->two);
2535 break;
2536 case DIFF_STATUS_COPIED:
2537 show_rename_copy("copy", p);
2538 break;
2539 case DIFF_STATUS_RENAMED:
2540 show_rename_copy("rename", p);
2541 break;
2542 default:
2543 if (p->score) {
2544 char *name = quote_one(p->two->path);
2545 printf(" rewrite %s (%d%%)\n", name,
2546 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2547 free(name);
2548 show_mode_change(p, 0);
2549 } else show_mode_change(p, 1);
2550 break;
2554 struct patch_id_t {
2555 struct xdiff_emit_state xm;
2556 SHA_CTX *ctx;
2557 int patchlen;
2560 static int remove_space(char *line, int len)
2562 int i;
2563 char *dst = line;
2564 unsigned char c;
2566 for (i = 0; i < len; i++)
2567 if (!isspace((c = line[i])))
2568 *dst++ = c;
2570 return dst - line;
2573 static void patch_id_consume(void *priv, char *line, unsigned long len)
2575 struct patch_id_t *data = priv;
2576 int new_len;
2578 /* Ignore line numbers when computing the SHA1 of the patch */
2579 if (!prefixcmp(line, "@@ -"))
2580 return;
2582 new_len = remove_space(line, len);
2584 SHA1_Update(data->ctx, line, new_len);
2585 data->patchlen += new_len;
2588 /* returns 0 upon success, and writes result into sha1 */
2589 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2591 struct diff_queue_struct *q = &diff_queued_diff;
2592 int i;
2593 SHA_CTX ctx;
2594 struct patch_id_t data;
2595 char buffer[PATH_MAX * 4 + 20];
2597 SHA1_Init(&ctx);
2598 memset(&data, 0, sizeof(struct patch_id_t));
2599 data.ctx = &ctx;
2600 data.xm.consume = patch_id_consume;
2602 for (i = 0; i < q->nr; i++) {
2603 xpparam_t xpp;
2604 xdemitconf_t xecfg;
2605 xdemitcb_t ecb;
2606 mmfile_t mf1, mf2;
2607 struct diff_filepair *p = q->queue[i];
2608 int len1, len2;
2610 if (p->status == 0)
2611 return error("internal diff status error");
2612 if (p->status == DIFF_STATUS_UNKNOWN)
2613 continue;
2614 if (diff_unmodified_pair(p))
2615 continue;
2616 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2617 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2618 continue;
2619 if (DIFF_PAIR_UNMERGED(p))
2620 continue;
2622 diff_fill_sha1_info(p->one);
2623 diff_fill_sha1_info(p->two);
2624 if (fill_mmfile(&mf1, p->one) < 0 ||
2625 fill_mmfile(&mf2, p->two) < 0)
2626 return error("unable to read files to diff");
2628 /* Maybe hash p->two? into the patch id? */
2629 if (mmfile_is_binary(&mf2))
2630 continue;
2632 len1 = remove_space(p->one->path, strlen(p->one->path));
2633 len2 = remove_space(p->two->path, strlen(p->two->path));
2634 if (p->one->mode == 0)
2635 len1 = snprintf(buffer, sizeof(buffer),
2636 "diff--gita/%.*sb/%.*s"
2637 "newfilemode%06o"
2638 "---/dev/null"
2639 "+++b/%.*s",
2640 len1, p->one->path,
2641 len2, p->two->path,
2642 p->two->mode,
2643 len2, p->two->path);
2644 else if (p->two->mode == 0)
2645 len1 = snprintf(buffer, sizeof(buffer),
2646 "diff--gita/%.*sb/%.*s"
2647 "deletedfilemode%06o"
2648 "---a/%.*s"
2649 "+++/dev/null",
2650 len1, p->one->path,
2651 len2, p->two->path,
2652 p->one->mode,
2653 len1, p->one->path);
2654 else
2655 len1 = snprintf(buffer, sizeof(buffer),
2656 "diff--gita/%.*sb/%.*s"
2657 "---a/%.*s"
2658 "+++b/%.*s",
2659 len1, p->one->path,
2660 len2, p->two->path,
2661 len1, p->one->path,
2662 len2, p->two->path);
2663 SHA1_Update(&ctx, buffer, len1);
2665 xpp.flags = XDF_NEED_MINIMAL;
2666 xecfg.ctxlen = 3;
2667 xecfg.flags = XDL_EMIT_FUNCNAMES;
2668 ecb.outf = xdiff_outf;
2669 ecb.priv = &data;
2670 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2673 SHA1_Final(sha1, &ctx);
2674 return 0;
2677 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2679 struct diff_queue_struct *q = &diff_queued_diff;
2680 int i;
2681 int result = diff_get_patch_id(options, sha1);
2683 for (i = 0; i < q->nr; i++)
2684 diff_free_filepair(q->queue[i]);
2686 free(q->queue);
2687 q->queue = NULL;
2688 q->nr = q->alloc = 0;
2690 return result;
2693 static int is_summary_empty(const struct diff_queue_struct *q)
2695 int i;
2697 for (i = 0; i < q->nr; i++) {
2698 const struct diff_filepair *p = q->queue[i];
2700 switch (p->status) {
2701 case DIFF_STATUS_DELETED:
2702 case DIFF_STATUS_ADDED:
2703 case DIFF_STATUS_COPIED:
2704 case DIFF_STATUS_RENAMED:
2705 return 0;
2706 default:
2707 if (p->score)
2708 return 0;
2709 if (p->one->mode && p->two->mode &&
2710 p->one->mode != p->two->mode)
2711 return 0;
2712 break;
2715 return 1;
2718 void diff_flush(struct diff_options *options)
2720 struct diff_queue_struct *q = &diff_queued_diff;
2721 int i, output_format = options->output_format;
2722 int separator = 0;
2725 * Order: raw, stat, summary, patch
2726 * or: name/name-status/checkdiff (other bits clear)
2728 if (!q->nr)
2729 goto free_queue;
2731 if (output_format & (DIFF_FORMAT_RAW |
2732 DIFF_FORMAT_NAME |
2733 DIFF_FORMAT_NAME_STATUS |
2734 DIFF_FORMAT_CHECKDIFF)) {
2735 for (i = 0; i < q->nr; i++) {
2736 struct diff_filepair *p = q->queue[i];
2737 if (check_pair_status(p))
2738 flush_one_pair(p, options);
2740 separator++;
2743 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
2744 struct diffstat_t diffstat;
2746 memset(&diffstat, 0, sizeof(struct diffstat_t));
2747 diffstat.xm.consume = diffstat_consume;
2748 for (i = 0; i < q->nr; i++) {
2749 struct diff_filepair *p = q->queue[i];
2750 if (check_pair_status(p))
2751 diff_flush_stat(p, options, &diffstat);
2753 if (output_format & DIFF_FORMAT_NUMSTAT)
2754 show_numstat(&diffstat, options);
2755 if (output_format & DIFF_FORMAT_DIFFSTAT)
2756 show_stats(&diffstat, options);
2757 else if (output_format & DIFF_FORMAT_SHORTSTAT)
2758 show_shortstats(&diffstat);
2759 separator++;
2762 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2763 for (i = 0; i < q->nr; i++)
2764 diff_summary(q->queue[i]);
2765 separator++;
2768 if (output_format & DIFF_FORMAT_PATCH) {
2769 if (separator) {
2770 if (options->stat_sep) {
2771 /* attach patch instead of inline */
2772 fputs(options->stat_sep, stdout);
2773 } else {
2774 putchar(options->line_termination);
2778 for (i = 0; i < q->nr; i++) {
2779 struct diff_filepair *p = q->queue[i];
2780 if (check_pair_status(p))
2781 diff_flush_patch(p, options);
2785 if (output_format & DIFF_FORMAT_CALLBACK)
2786 options->format_callback(q, options, options->format_callback_data);
2788 for (i = 0; i < q->nr; i++)
2789 diff_free_filepair(q->queue[i]);
2790 free_queue:
2791 free(q->queue);
2792 q->queue = NULL;
2793 q->nr = q->alloc = 0;
2796 static void diffcore_apply_filter(const char *filter)
2798 int i;
2799 struct diff_queue_struct *q = &diff_queued_diff;
2800 struct diff_queue_struct outq;
2801 outq.queue = NULL;
2802 outq.nr = outq.alloc = 0;
2804 if (!filter)
2805 return;
2807 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2808 int found;
2809 for (i = found = 0; !found && i < q->nr; i++) {
2810 struct diff_filepair *p = q->queue[i];
2811 if (((p->status == DIFF_STATUS_MODIFIED) &&
2812 ((p->score &&
2813 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2814 (!p->score &&
2815 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2816 ((p->status != DIFF_STATUS_MODIFIED) &&
2817 strchr(filter, p->status)))
2818 found++;
2820 if (found)
2821 return;
2823 /* otherwise we will clear the whole queue
2824 * by copying the empty outq at the end of this
2825 * function, but first clear the current entries
2826 * in the queue.
2828 for (i = 0; i < q->nr; i++)
2829 diff_free_filepair(q->queue[i]);
2831 else {
2832 /* Only the matching ones */
2833 for (i = 0; i < q->nr; i++) {
2834 struct diff_filepair *p = q->queue[i];
2836 if (((p->status == DIFF_STATUS_MODIFIED) &&
2837 ((p->score &&
2838 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2839 (!p->score &&
2840 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2841 ((p->status != DIFF_STATUS_MODIFIED) &&
2842 strchr(filter, p->status)))
2843 diff_q(&outq, p);
2844 else
2845 diff_free_filepair(p);
2848 free(q->queue);
2849 *q = outq;
2852 void diffcore_std(struct diff_options *options)
2854 if (options->break_opt != -1)
2855 diffcore_break(options->break_opt);
2856 if (options->detect_rename)
2857 diffcore_rename(options);
2858 if (options->break_opt != -1)
2859 diffcore_merge_broken();
2860 if (options->pickaxe)
2861 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2862 if (options->orderfile)
2863 diffcore_order(options->orderfile);
2864 diff_resolve_rename_copy();
2865 diffcore_apply_filter(options->filter);
2869 void diffcore_std_no_resolve(struct diff_options *options)
2871 if (options->pickaxe)
2872 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2873 if (options->orderfile)
2874 diffcore_order(options->orderfile);
2875 diffcore_apply_filter(options->filter);
2878 void diff_addremove(struct diff_options *options,
2879 int addremove, unsigned mode,
2880 const unsigned char *sha1,
2881 const char *base, const char *path)
2883 char concatpath[PATH_MAX];
2884 struct diff_filespec *one, *two;
2886 /* This may look odd, but it is a preparation for
2887 * feeding "there are unchanged files which should
2888 * not produce diffs, but when you are doing copy
2889 * detection you would need them, so here they are"
2890 * entries to the diff-core. They will be prefixed
2891 * with something like '=' or '*' (I haven't decided
2892 * which but should not make any difference).
2893 * Feeding the same new and old to diff_change()
2894 * also has the same effect.
2895 * Before the final output happens, they are pruned after
2896 * merged into rename/copy pairs as appropriate.
2898 if (options->reverse_diff)
2899 addremove = (addremove == '+' ? '-' :
2900 addremove == '-' ? '+' : addremove);
2902 if (!path) path = "";
2903 sprintf(concatpath, "%s%s", base, path);
2904 one = alloc_filespec(concatpath);
2905 two = alloc_filespec(concatpath);
2907 if (addremove != '+')
2908 fill_filespec(one, sha1, mode);
2909 if (addremove != '-')
2910 fill_filespec(two, sha1, mode);
2912 diff_queue(&diff_queued_diff, one, two);
2915 void diff_change(struct diff_options *options,
2916 unsigned old_mode, unsigned new_mode,
2917 const unsigned char *old_sha1,
2918 const unsigned char *new_sha1,
2919 const char *base, const char *path)
2921 char concatpath[PATH_MAX];
2922 struct diff_filespec *one, *two;
2924 if (options->reverse_diff) {
2925 unsigned tmp;
2926 const unsigned char *tmp_c;
2927 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2928 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2930 if (!path) path = "";
2931 sprintf(concatpath, "%s%s", base, path);
2932 one = alloc_filespec(concatpath);
2933 two = alloc_filespec(concatpath);
2934 fill_filespec(one, old_sha1, old_mode);
2935 fill_filespec(two, new_sha1, new_mode);
2937 diff_queue(&diff_queued_diff, one, two);
2940 void diff_unmerge(struct diff_options *options,
2941 const char *path,
2942 unsigned mode, const unsigned char *sha1)
2944 struct diff_filespec *one, *two;
2945 one = alloc_filespec(path);
2946 two = alloc_filespec(path);
2947 fill_filespec(one, sha1, mode);
2948 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;