Fix PRIuMAX definition for MinGW.
[git/dscho.git] / diff.c
blobb247b9793ebc07c721678c7c9489fb6c347102a1
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;
386 int *found_changesp;
389 static void free_diff_words_data(struct emit_callback *ecbdata)
391 if (ecbdata->diff_words) {
392 /* flush buffers */
393 if (ecbdata->diff_words->minus.text.size ||
394 ecbdata->diff_words->plus.text.size)
395 diff_words_show(ecbdata->diff_words);
397 if (ecbdata->diff_words->minus.text.ptr)
398 free (ecbdata->diff_words->minus.text.ptr);
399 if (ecbdata->diff_words->plus.text.ptr)
400 free (ecbdata->diff_words->plus.text.ptr);
401 free(ecbdata->diff_words);
402 ecbdata->diff_words = NULL;
406 const char *diff_get_color(int diff_use_color, enum color_diff ix)
408 if (diff_use_color)
409 return diff_colors[ix];
410 return "";
413 static void emit_line(const char *set, const char *reset, const char *line, int len)
415 if (len > 0 && line[len-1] == '\n')
416 len--;
417 fputs(set, stdout);
418 fwrite(line, len, 1, stdout);
419 puts(reset);
422 static void emit_line_with_ws(int nparents,
423 const char *set, const char *reset, const char *ws,
424 const char *line, int len)
426 int col0 = nparents;
427 int last_tab_in_indent = -1;
428 int last_space_in_indent = -1;
429 int i;
430 int tail = len;
431 int need_highlight_leading_space = 0;
432 /* The line is a newly added line. Does it have funny leading
433 * whitespaces? In indent, SP should never precede a TAB.
435 for (i = col0; i < len; i++) {
436 if (line[i] == '\t') {
437 last_tab_in_indent = i;
438 if (0 <= last_space_in_indent)
439 need_highlight_leading_space = 1;
441 else if (line[i] == ' ')
442 last_space_in_indent = i;
443 else
444 break;
446 fputs(set, stdout);
447 fwrite(line, col0, 1, stdout);
448 fputs(reset, stdout);
449 if (((i == len) || line[i] == '\n') && i != col0) {
450 /* The whole line was indent */
451 emit_line(ws, reset, line + col0, len - col0);
452 return;
454 i = col0;
455 if (need_highlight_leading_space) {
456 while (i < last_tab_in_indent) {
457 if (line[i] == ' ') {
458 fputs(ws, stdout);
459 putchar(' ');
460 fputs(reset, stdout);
462 else
463 putchar(line[i]);
464 i++;
467 tail = len - 1;
468 if (line[tail] == '\n' && i < tail)
469 tail--;
470 while (i < tail) {
471 if (!isspace(line[tail]))
472 break;
473 tail--;
475 if ((i < tail && line[tail + 1] != '\n')) {
476 /* This has whitespace between tail+1..len */
477 fputs(set, stdout);
478 fwrite(line + i, tail - i + 1, 1, stdout);
479 fputs(reset, stdout);
480 emit_line(ws, reset, line + tail + 1, len - tail - 1);
482 else
483 emit_line(set, reset, line + i, len - i);
486 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
488 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
489 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
491 if (!*ws)
492 emit_line(set, reset, line, len);
493 else
494 emit_line_with_ws(ecbdata->nparents, set, reset, ws,
495 line, len);
498 static void fn_out_consume(void *priv, char *line, unsigned long len)
500 int i;
501 int color;
502 struct emit_callback *ecbdata = priv;
503 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
504 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
506 *(ecbdata->found_changesp) = 1;
508 if (ecbdata->label_path[0]) {
509 const char *name_a_tab, *name_b_tab;
511 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
512 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
514 printf("%s--- %s%s%s\n",
515 set, ecbdata->label_path[0], reset, name_a_tab);
516 printf("%s+++ %s%s%s\n",
517 set, ecbdata->label_path[1], reset, name_b_tab);
518 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
521 /* This is not really necessary for now because
522 * this codepath only deals with two-way diffs.
524 for (i = 0; i < len && line[i] == '@'; i++)
526 if (2 <= i && i < len && line[i] == ' ') {
527 ecbdata->nparents = i - 1;
528 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
529 reset, line, len);
530 return;
533 if (len < ecbdata->nparents) {
534 set = reset;
535 emit_line(reset, reset, line, len);
536 return;
539 color = DIFF_PLAIN;
540 if (ecbdata->diff_words && ecbdata->nparents != 1)
541 /* fall back to normal diff */
542 free_diff_words_data(ecbdata);
543 if (ecbdata->diff_words) {
544 if (line[0] == '-') {
545 diff_words_append(line, len,
546 &ecbdata->diff_words->minus);
547 return;
548 } else if (line[0] == '+') {
549 diff_words_append(line, len,
550 &ecbdata->diff_words->plus);
551 return;
553 if (ecbdata->diff_words->minus.text.size ||
554 ecbdata->diff_words->plus.text.size)
555 diff_words_show(ecbdata->diff_words);
556 line++;
557 len--;
558 emit_line(set, reset, line, len);
559 return;
561 for (i = 0; i < ecbdata->nparents && len; i++) {
562 if (line[i] == '-')
563 color = DIFF_FILE_OLD;
564 else if (line[i] == '+')
565 color = DIFF_FILE_NEW;
568 if (color != DIFF_FILE_NEW) {
569 emit_line(diff_get_color(ecbdata->color_diff, color),
570 reset, line, len);
571 return;
573 emit_add_line(reset, ecbdata, line, len);
576 static char *pprint_rename(const char *a, const char *b)
578 const char *old = a;
579 const char *new = b;
580 char *name = NULL;
581 int pfx_length, sfx_length;
582 int len_a = strlen(a);
583 int len_b = strlen(b);
584 int qlen_a = quote_c_style(a, NULL, NULL, 0);
585 int qlen_b = quote_c_style(b, NULL, NULL, 0);
587 if (qlen_a || qlen_b) {
588 if (qlen_a) len_a = qlen_a;
589 if (qlen_b) len_b = qlen_b;
590 name = xmalloc( len_a + len_b + 5 );
591 if (qlen_a)
592 quote_c_style(a, name, NULL, 0);
593 else
594 memcpy(name, a, len_a);
595 memcpy(name + len_a, " => ", 4);
596 if (qlen_b)
597 quote_c_style(b, name + len_a + 4, NULL, 0);
598 else
599 memcpy(name + len_a + 4, b, len_b + 1);
600 return name;
603 /* Find common prefix */
604 pfx_length = 0;
605 while (*old && *new && *old == *new) {
606 if (*old == '/')
607 pfx_length = old - a + 1;
608 old++;
609 new++;
612 /* Find common suffix */
613 old = a + len_a;
614 new = b + len_b;
615 sfx_length = 0;
616 while (a <= old && b <= new && *old == *new) {
617 if (*old == '/')
618 sfx_length = len_a - (old - a);
619 old--;
620 new--;
624 * pfx{mid-a => mid-b}sfx
625 * {pfx-a => pfx-b}sfx
626 * pfx{sfx-a => sfx-b}
627 * name-a => name-b
629 if (pfx_length + sfx_length) {
630 int a_midlen = len_a - pfx_length - sfx_length;
631 int b_midlen = len_b - pfx_length - sfx_length;
632 if (a_midlen < 0) a_midlen = 0;
633 if (b_midlen < 0) b_midlen = 0;
635 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
636 sprintf(name, "%.*s{%.*s => %.*s}%s",
637 pfx_length, a,
638 a_midlen, a + pfx_length,
639 b_midlen, b + pfx_length,
640 a + len_a - sfx_length);
642 else {
643 name = xmalloc(len_a + len_b + 5);
644 sprintf(name, "%s => %s", a, b);
646 return name;
649 struct diffstat_t {
650 struct xdiff_emit_state xm;
652 int nr;
653 int alloc;
654 struct diffstat_file {
655 char *name;
656 unsigned is_unmerged:1;
657 unsigned is_binary:1;
658 unsigned is_renamed:1;
659 unsigned int added, deleted;
660 } **files;
663 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
664 const char *name_a,
665 const char *name_b)
667 struct diffstat_file *x;
668 x = xcalloc(sizeof (*x), 1);
669 if (diffstat->nr == diffstat->alloc) {
670 diffstat->alloc = alloc_nr(diffstat->alloc);
671 diffstat->files = xrealloc(diffstat->files,
672 diffstat->alloc * sizeof(x));
674 diffstat->files[diffstat->nr++] = x;
675 if (name_b) {
676 x->name = pprint_rename(name_a, name_b);
677 x->is_renamed = 1;
679 else
680 x->name = xstrdup(name_a);
681 return x;
684 static void diffstat_consume(void *priv, char *line, unsigned long len)
686 struct diffstat_t *diffstat = priv;
687 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
689 if (line[0] == '+')
690 x->added++;
691 else if (line[0] == '-')
692 x->deleted++;
695 const char mime_boundary_leader[] = "------------";
697 static int scale_linear(int it, int width, int max_change)
700 * make sure that at least one '-' is printed if there were deletions,
701 * and likewise for '+'.
703 if (max_change < 2)
704 return it;
705 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
708 static void show_name(const char *prefix, const char *name, int len,
709 const char *reset, const char *set)
711 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
714 static void show_graph(char ch, int cnt, const char *set, const char *reset)
716 if (cnt <= 0)
717 return;
718 printf("%s", set);
719 while (cnt--)
720 putchar(ch);
721 printf("%s", reset);
724 static void show_stats(struct diffstat_t* data, struct diff_options *options)
726 int i, len, add, del, total, adds = 0, dels = 0;
727 int max_change = 0, max_len = 0;
728 int total_files = data->nr;
729 int width, name_width;
730 const char *reset, *set, *add_c, *del_c;
732 if (data->nr == 0)
733 return;
735 width = options->stat_width ? options->stat_width : 80;
736 name_width = options->stat_name_width ? options->stat_name_width : 50;
738 /* Sanity: give at least 5 columns to the graph,
739 * but leave at least 10 columns for the name.
741 if (width < name_width + 15) {
742 if (name_width <= 25)
743 width = name_width + 15;
744 else
745 name_width = width - 15;
748 /* Find the longest filename and max number of changes */
749 reset = diff_get_color(options->color_diff, DIFF_RESET);
750 set = diff_get_color(options->color_diff, DIFF_PLAIN);
751 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
752 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
754 for (i = 0; i < data->nr; i++) {
755 struct diffstat_file *file = data->files[i];
756 int change = file->added + file->deleted;
758 if (!file->is_renamed) { /* renames are already quoted by pprint_rename */
759 len = quote_c_style(file->name, NULL, NULL, 0);
760 if (len) {
761 char *qname = xmalloc(len + 1);
762 quote_c_style(file->name, qname, NULL, 0);
763 free(file->name);
764 file->name = qname;
768 len = strlen(file->name);
769 if (max_len < len)
770 max_len = len;
772 if (file->is_binary || file->is_unmerged)
773 continue;
774 if (max_change < change)
775 max_change = change;
778 /* Compute the width of the graph part;
779 * 10 is for one blank at the beginning of the line plus
780 * " | count " between the name and the graph.
782 * From here on, name_width is the width of the name area,
783 * and width is the width of the graph area.
785 name_width = (name_width < max_len) ? name_width : max_len;
786 if (width < (name_width + 10) + max_change)
787 width = width - (name_width + 10);
788 else
789 width = max_change;
791 for (i = 0; i < data->nr; i++) {
792 const char *prefix = "";
793 char *name = data->files[i]->name;
794 int added = data->files[i]->added;
795 int deleted = data->files[i]->deleted;
796 int name_len;
799 * "scale" the filename
801 len = name_width;
802 name_len = strlen(name);
803 if (name_width < name_len) {
804 char *slash;
805 prefix = "...";
806 len -= 3;
807 name += name_len - len;
808 slash = strchr(name, '/');
809 if (slash)
810 name = slash;
813 if (data->files[i]->is_binary) {
814 show_name(prefix, name, len, reset, set);
815 printf(" Bin\n");
816 goto free_diffstat_file;
818 else if (data->files[i]->is_unmerged) {
819 show_name(prefix, name, len, reset, set);
820 printf(" Unmerged\n");
821 goto free_diffstat_file;
823 else if (!data->files[i]->is_renamed &&
824 (added + deleted == 0)) {
825 total_files--;
826 goto free_diffstat_file;
830 * scale the add/delete
832 add = added;
833 del = deleted;
834 total = add + del;
835 adds += add;
836 dels += del;
838 if (width <= max_change) {
839 add = scale_linear(add, width, max_change);
840 del = scale_linear(del, width, max_change);
841 total = add + del;
843 show_name(prefix, name, len, reset, set);
844 printf("%5d ", added + deleted);
845 show_graph('+', add, add_c, reset);
846 show_graph('-', del, del_c, reset);
847 putchar('\n');
848 free_diffstat_file:
849 free(data->files[i]->name);
850 free(data->files[i]);
852 free(data->files);
853 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
854 set, total_files, adds, dels, reset);
857 static void show_shortstats(struct diffstat_t* data)
859 int i, adds = 0, dels = 0, total_files = data->nr;
861 if (data->nr == 0)
862 return;
864 for (i = 0; i < data->nr; i++) {
865 if (!data->files[i]->is_binary &&
866 !data->files[i]->is_unmerged) {
867 int added = data->files[i]->added;
868 int deleted= data->files[i]->deleted;
869 if (!data->files[i]->is_renamed &&
870 (added + deleted == 0)) {
871 total_files--;
872 } else {
873 adds += added;
874 dels += deleted;
877 free(data->files[i]->name);
878 free(data->files[i]);
880 free(data->files);
882 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
883 total_files, adds, dels);
886 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
888 int i;
890 for (i = 0; i < data->nr; i++) {
891 struct diffstat_file *file = data->files[i];
893 if (file->is_binary)
894 printf("-\t-\t");
895 else
896 printf("%d\t%d\t", file->added, file->deleted);
897 if (options->line_termination && !file->is_renamed &&
898 quote_c_style(file->name, NULL, NULL, 0))
899 quote_c_style(file->name, NULL, stdout, 0);
900 else
901 fputs(file->name, stdout);
902 putchar(options->line_termination);
906 struct checkdiff_t {
907 struct xdiff_emit_state xm;
908 const char *filename;
909 int lineno, color_diff;
912 static void checkdiff_consume(void *priv, char *line, unsigned long len)
914 struct checkdiff_t *data = priv;
915 const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
916 const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
917 const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
919 if (line[0] == '+') {
920 int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
922 /* check space before tab */
923 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
924 if (line[i] == ' ')
925 spaces++;
926 if (line[i - 1] == '\t' && spaces)
927 space_before_tab = 1;
929 /* check white space at line end */
930 if (line[len - 1] == '\n')
931 len--;
932 if (isspace(line[len - 1]))
933 white_space_at_end = 1;
935 if (space_before_tab || white_space_at_end) {
936 printf("%s:%d: %s", data->filename, data->lineno, ws);
937 if (space_before_tab) {
938 printf("space before tab");
939 if (white_space_at_end)
940 putchar(',');
942 if (white_space_at_end)
943 printf("white space at end");
944 printf(":%s ", reset);
945 emit_line_with_ws(1, set, reset, ws, line, len);
948 data->lineno++;
949 } else if (line[0] == ' ')
950 data->lineno++;
951 else if (line[0] == '@') {
952 char *plus = strchr(line, '+');
953 if (plus)
954 data->lineno = strtol(plus, NULL, 10);
955 else
956 die("invalid diff");
960 static unsigned char *deflate_it(char *data,
961 unsigned long size,
962 unsigned long *result_size)
964 int bound;
965 unsigned char *deflated;
966 z_stream stream;
968 memset(&stream, 0, sizeof(stream));
969 deflateInit(&stream, zlib_compression_level);
970 bound = deflateBound(&stream, size);
971 deflated = xmalloc(bound);
972 stream.next_out = deflated;
973 stream.avail_out = bound;
975 stream.next_in = (unsigned char *)data;
976 stream.avail_in = size;
977 while (deflate(&stream, Z_FINISH) == Z_OK)
978 ; /* nothing */
979 deflateEnd(&stream);
980 *result_size = stream.total_out;
981 return deflated;
984 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
986 void *cp;
987 void *delta;
988 void *deflated;
989 void *data;
990 unsigned long orig_size;
991 unsigned long delta_size;
992 unsigned long deflate_size;
993 unsigned long data_size;
995 /* We could do deflated delta, or we could do just deflated two,
996 * whichever is smaller.
998 delta = NULL;
999 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1000 if (one->size && two->size) {
1001 delta = diff_delta(one->ptr, one->size,
1002 two->ptr, two->size,
1003 &delta_size, deflate_size);
1004 if (delta) {
1005 void *to_free = delta;
1006 orig_size = delta_size;
1007 delta = deflate_it(delta, delta_size, &delta_size);
1008 free(to_free);
1012 if (delta && delta_size < deflate_size) {
1013 printf("delta %lu\n", orig_size);
1014 free(deflated);
1015 data = delta;
1016 data_size = delta_size;
1018 else {
1019 printf("literal %lu\n", two->size);
1020 free(delta);
1021 data = deflated;
1022 data_size = deflate_size;
1025 /* emit data encoded in base85 */
1026 cp = data;
1027 while (data_size) {
1028 int bytes = (52 < data_size) ? 52 : data_size;
1029 char line[70];
1030 data_size -= bytes;
1031 if (bytes <= 26)
1032 line[0] = bytes + 'A' - 1;
1033 else
1034 line[0] = bytes - 26 + 'a' - 1;
1035 encode_85(line + 1, cp, bytes);
1036 cp = (char *) cp + bytes;
1037 puts(line);
1039 printf("\n");
1040 free(data);
1043 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1045 printf("GIT binary patch\n");
1046 emit_binary_diff_body(one, two);
1047 emit_binary_diff_body(two, one);
1050 #define FIRST_FEW_BYTES 8000
1051 static int mmfile_is_binary(mmfile_t *mf)
1053 long sz = mf->size;
1054 if (FIRST_FEW_BYTES < sz)
1055 sz = FIRST_FEW_BYTES;
1056 return !!memchr(mf->ptr, 0, sz);
1059 static void builtin_diff(const char *name_a,
1060 const char *name_b,
1061 struct diff_filespec *one,
1062 struct diff_filespec *two,
1063 const char *xfrm_msg,
1064 struct diff_options *o,
1065 int complete_rewrite)
1067 mmfile_t mf1, mf2;
1068 const char *lbl[2];
1069 char *a_one, *b_two;
1070 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1071 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1073 a_one = quote_two("a/", name_a + (*name_a == '/'));
1074 b_two = quote_two("b/", name_b + (*name_b == '/'));
1075 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1076 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1077 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1078 if (lbl[0][0] == '/') {
1079 /* /dev/null */
1080 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1081 if (xfrm_msg && xfrm_msg[0])
1082 printf("%s%s%s\n", set, xfrm_msg, reset);
1084 else if (lbl[1][0] == '/') {
1085 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1086 if (xfrm_msg && xfrm_msg[0])
1087 printf("%s%s%s\n", set, xfrm_msg, reset);
1089 else {
1090 if (one->mode != two->mode) {
1091 printf("%sold mode %06o%s\n", set, one->mode, reset);
1092 printf("%snew mode %06o%s\n", set, two->mode, reset);
1094 if (xfrm_msg && xfrm_msg[0])
1095 printf("%s%s%s\n", set, xfrm_msg, reset);
1097 * we do not run diff between different kind
1098 * of objects.
1100 if ((one->mode ^ two->mode) & S_IFMT)
1101 goto free_ab_and_return;
1102 if (complete_rewrite) {
1103 emit_rewrite_diff(name_a, name_b, one, two,
1104 o->color_diff);
1105 o->found_changes = 1;
1106 goto free_ab_and_return;
1110 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1111 die("unable to read files to diff");
1113 if (!o->text && (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))) {
1114 /* Quite common confusing case */
1115 if (mf1.size == mf2.size &&
1116 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1117 goto free_ab_and_return;
1118 if (o->binary)
1119 emit_binary_diff(&mf1, &mf2);
1120 else
1121 printf("Binary files %s and %s differ\n",
1122 lbl[0], lbl[1]);
1123 o->found_changes = 1;
1125 else {
1126 /* Crazy xdl interfaces.. */
1127 const char *diffopts = getenv("GIT_DIFF_OPTS");
1128 xpparam_t xpp;
1129 xdemitconf_t xecfg;
1130 xdemitcb_t ecb;
1131 struct emit_callback ecbdata;
1133 memset(&ecbdata, 0, sizeof(ecbdata));
1134 ecbdata.label_path = lbl;
1135 ecbdata.color_diff = o->color_diff;
1136 ecbdata.found_changesp = &o->found_changes;
1137 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1138 xecfg.ctxlen = o->context;
1139 xecfg.flags = XDL_EMIT_FUNCNAMES;
1140 if (!diffopts)
1142 else if (!prefixcmp(diffopts, "--unified="))
1143 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1144 else if (!prefixcmp(diffopts, "-u"))
1145 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1146 ecb.outf = xdiff_outf;
1147 ecb.priv = &ecbdata;
1148 ecbdata.xm.consume = fn_out_consume;
1149 if (o->color_diff_words)
1150 ecbdata.diff_words =
1151 xcalloc(1, sizeof(struct diff_words_data));
1152 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1153 if (o->color_diff_words)
1154 free_diff_words_data(&ecbdata);
1157 free_ab_and_return:
1158 free(a_one);
1159 free(b_two);
1160 return;
1163 static void builtin_diffstat(const char *name_a, const char *name_b,
1164 struct diff_filespec *one,
1165 struct diff_filespec *two,
1166 struct diffstat_t *diffstat,
1167 struct diff_options *o,
1168 int complete_rewrite)
1170 mmfile_t mf1, mf2;
1171 struct diffstat_file *data;
1173 data = diffstat_add(diffstat, name_a, name_b);
1175 if (!one || !two) {
1176 data->is_unmerged = 1;
1177 return;
1179 if (complete_rewrite) {
1180 diff_populate_filespec(one, 0);
1181 diff_populate_filespec(two, 0);
1182 data->deleted = count_lines(one->data, one->size);
1183 data->added = count_lines(two->data, two->size);
1184 return;
1186 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1187 die("unable to read files to diff");
1189 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
1190 data->is_binary = 1;
1191 else {
1192 /* Crazy xdl interfaces.. */
1193 xpparam_t xpp;
1194 xdemitconf_t xecfg;
1195 xdemitcb_t ecb;
1197 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1198 xecfg.ctxlen = 0;
1199 xecfg.flags = 0;
1200 ecb.outf = xdiff_outf;
1201 ecb.priv = diffstat;
1202 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1206 static void builtin_checkdiff(const char *name_a, const char *name_b,
1207 struct diff_filespec *one,
1208 struct diff_filespec *two, struct diff_options *o)
1210 mmfile_t mf1, mf2;
1211 struct checkdiff_t data;
1213 if (!two)
1214 return;
1216 memset(&data, 0, sizeof(data));
1217 data.xm.consume = checkdiff_consume;
1218 data.filename = name_b ? name_b : name_a;
1219 data.lineno = 0;
1220 data.color_diff = o->color_diff;
1222 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1223 die("unable to read files to diff");
1225 if (mmfile_is_binary(&mf2))
1226 return;
1227 else {
1228 /* Crazy xdl interfaces.. */
1229 xpparam_t xpp;
1230 xdemitconf_t xecfg;
1231 xdemitcb_t ecb;
1233 xpp.flags = XDF_NEED_MINIMAL;
1234 xecfg.ctxlen = 0;
1235 xecfg.flags = 0;
1236 ecb.outf = xdiff_outf;
1237 ecb.priv = &data;
1238 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1242 struct diff_filespec *alloc_filespec(const char *path)
1244 int namelen = strlen(path);
1245 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1247 memset(spec, 0, sizeof(*spec));
1248 spec->path = (char *)(spec + 1);
1249 memcpy(spec->path, path, namelen+1);
1250 return spec;
1253 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1254 unsigned short mode)
1256 if (mode) {
1257 spec->mode = canon_mode(mode);
1258 hashcpy(spec->sha1, sha1);
1259 spec->sha1_valid = !is_null_sha1(sha1);
1264 * Given a name and sha1 pair, if the dircache tells us the file in
1265 * the work tree has that object contents, return true, so that
1266 * prepare_temp_file() does not have to inflate and extract.
1268 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1270 struct cache_entry *ce;
1271 struct stat st;
1272 int pos, len;
1274 /* We do not read the cache ourselves here, because the
1275 * benchmark with my previous version that always reads cache
1276 * shows that it makes things worse for diff-tree comparing
1277 * two linux-2.6 kernel trees in an already checked out work
1278 * tree. This is because most diff-tree comparisons deal with
1279 * only a small number of files, while reading the cache is
1280 * expensive for a large project, and its cost outweighs the
1281 * savings we get by not inflating the object to a temporary
1282 * file. Practically, this code only helps when we are used
1283 * by diff-cache --cached, which does read the cache before
1284 * calling us.
1286 if (!active_cache)
1287 return 0;
1289 /* We want to avoid the working directory if our caller
1290 * doesn't need the data in a normal file, this system
1291 * is rather slow with its stat/open/mmap/close syscalls,
1292 * and the object is contained in a pack file. The pack
1293 * is probably already open and will be faster to obtain
1294 * the data through than the working directory. Loose
1295 * objects however would tend to be slower as they need
1296 * to be individually opened and inflated.
1298 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1299 return 0;
1301 len = strlen(name);
1302 pos = cache_name_pos(name, len);
1303 if (pos < 0)
1304 return 0;
1305 ce = active_cache[pos];
1306 if ((lstat(name, &st) < 0) ||
1307 !S_ISREG(st.st_mode) || /* careful! */
1308 ce_match_stat(ce, &st, 0) ||
1309 hashcmp(sha1, ce->sha1))
1310 return 0;
1311 /* we return 1 only when we can stat, it is a regular file,
1312 * stat information matches, and sha1 recorded in the cache
1313 * matches. I.e. we know the file in the work tree really is
1314 * the same as the <name, sha1> pair.
1316 return 1;
1319 static struct sha1_size_cache {
1320 unsigned char sha1[20];
1321 unsigned long size;
1322 } **sha1_size_cache;
1323 static int sha1_size_cache_nr, sha1_size_cache_alloc;
1325 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
1326 int find_only,
1327 unsigned long size)
1329 int first, last;
1330 struct sha1_size_cache *e;
1332 first = 0;
1333 last = sha1_size_cache_nr;
1334 while (last > first) {
1335 int cmp, next = (last + first) >> 1;
1336 e = sha1_size_cache[next];
1337 cmp = hashcmp(e->sha1, sha1);
1338 if (!cmp)
1339 return e;
1340 if (cmp < 0) {
1341 last = next;
1342 continue;
1344 first = next+1;
1346 /* not found */
1347 if (find_only)
1348 return NULL;
1349 /* insert to make it at "first" */
1350 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
1351 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
1352 sha1_size_cache = xrealloc(sha1_size_cache,
1353 sha1_size_cache_alloc *
1354 sizeof(*sha1_size_cache));
1356 sha1_size_cache_nr++;
1357 if (first < sha1_size_cache_nr)
1358 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
1359 (sha1_size_cache_nr - first - 1) *
1360 sizeof(*sha1_size_cache));
1361 e = xmalloc(sizeof(struct sha1_size_cache));
1362 sha1_size_cache[first] = e;
1363 hashcpy(e->sha1, sha1);
1364 e->size = size;
1365 return e;
1368 static int populate_from_stdin(struct diff_filespec *s)
1370 #define INCREMENT 1024
1371 char *buf;
1372 unsigned long size;
1373 int got;
1375 size = 0;
1376 buf = NULL;
1377 while (1) {
1378 buf = xrealloc(buf, size + INCREMENT);
1379 got = xread(0, buf + size, INCREMENT);
1380 if (!got)
1381 break; /* EOF */
1382 if (got < 0)
1383 return error("error while reading from stdin %s",
1384 strerror(errno));
1385 size += got;
1387 s->should_munmap = 0;
1388 s->data = buf;
1389 s->size = size;
1390 s->should_free = 1;
1391 return 0;
1395 * While doing rename detection and pickaxe operation, we may need to
1396 * grab the data for the blob (or file) for our own in-core comparison.
1397 * diff_filespec has data and size fields for this purpose.
1399 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1401 int err = 0;
1402 if (!DIFF_FILE_VALID(s))
1403 die("internal error: asking to populate invalid file.");
1404 if (S_ISDIR(s->mode))
1405 return -1;
1407 if (!use_size_cache)
1408 size_only = 0;
1410 if (s->data)
1411 return err;
1412 if (!s->sha1_valid ||
1413 reuse_worktree_file(s->path, s->sha1, 0)) {
1414 struct stat st;
1415 int fd;
1416 char *buf;
1417 unsigned long size;
1419 if (!strcmp(s->path, "-"))
1420 return populate_from_stdin(s);
1422 if (lstat(s->path, &st) < 0) {
1423 if (errno == ENOENT) {
1424 err_empty:
1425 err = -1;
1426 empty:
1427 s->data = (char *)"";
1428 s->size = 0;
1429 return err;
1432 s->size = xsize_t(st.st_size);
1433 if (!s->size)
1434 goto empty;
1435 if (size_only)
1436 return 0;
1437 if (S_ISLNK(st.st_mode)) {
1438 int ret;
1439 s->data = xmalloc(s->size);
1440 s->should_free = 1;
1441 ret = readlink(s->path, s->data, s->size);
1442 if (ret < 0) {
1443 free(s->data);
1444 goto err_empty;
1446 return 0;
1448 fd = open(s->path, O_RDONLY);
1449 if (fd < 0)
1450 goto err_empty;
1451 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1452 close(fd);
1453 s->should_munmap = 1;
1456 * Convert from working tree format to canonical git format
1458 buf = s->data;
1459 size = s->size;
1460 if (convert_to_git(s->path, &buf, &size)) {
1461 munmap(s->data, s->size);
1462 s->should_munmap = 0;
1463 s->data = buf;
1464 s->size = size;
1465 s->should_free = 1;
1468 else {
1469 enum object_type type;
1470 struct sha1_size_cache *e;
1472 if (size_only) {
1473 e = locate_size_cache(s->sha1, 1, 0);
1474 if (e) {
1475 s->size = e->size;
1476 return 0;
1478 type = sha1_object_info(s->sha1, &s->size);
1479 if (type < 0)
1480 locate_size_cache(s->sha1, 0, s->size);
1482 else {
1483 s->data = read_sha1_file(s->sha1, &type, &s->size);
1484 s->should_free = 1;
1487 return 0;
1490 void diff_free_filespec_data(struct diff_filespec *s)
1492 if (s->should_free)
1493 free(s->data);
1494 else if (s->should_munmap)
1495 munmap(s->data, s->size);
1496 s->should_free = s->should_munmap = 0;
1497 s->data = NULL;
1498 free(s->cnt_data);
1499 s->cnt_data = NULL;
1502 static void prep_temp_blob(struct diff_tempfile *temp,
1503 void *blob,
1504 unsigned long size,
1505 const unsigned char *sha1,
1506 int mode)
1508 int fd;
1510 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1511 if (fd < 0)
1512 die("unable to create temp-file");
1513 if (write_in_full(fd, blob, size) != size)
1514 die("unable to write temp-file");
1515 close(fd);
1516 temp->name = temp->tmp_path;
1517 strcpy(temp->hex, sha1_to_hex(sha1));
1518 temp->hex[40] = 0;
1519 sprintf(temp->mode, "%06o", mode);
1522 static void prepare_temp_file(const char *name,
1523 struct diff_tempfile *temp,
1524 struct diff_filespec *one)
1526 if (!DIFF_FILE_VALID(one)) {
1527 not_a_valid_file:
1528 /* A '-' entry produces this for file-2, and
1529 * a '+' entry produces this for file-1.
1531 temp->name = "/dev/null";
1532 strcpy(temp->hex, ".");
1533 strcpy(temp->mode, ".");
1534 return;
1537 if (!one->sha1_valid ||
1538 reuse_worktree_file(name, one->sha1, 1)) {
1539 struct stat st;
1540 if (lstat(name, &st) < 0) {
1541 if (errno == ENOENT)
1542 goto not_a_valid_file;
1543 die("stat(%s): %s", name, strerror(errno));
1545 if (S_ISLNK(st.st_mode)) {
1546 int ret;
1547 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1548 size_t sz = xsize_t(st.st_size);
1549 if (sizeof(buf) <= st.st_size)
1550 die("symlink too long: %s", name);
1551 ret = readlink(name, buf, sz);
1552 if (ret < 0)
1553 die("readlink(%s)", name);
1554 prep_temp_blob(temp, buf, sz,
1555 (one->sha1_valid ?
1556 one->sha1 : null_sha1),
1557 (one->sha1_valid ?
1558 one->mode : S_IFLNK));
1560 else {
1561 /* we can borrow from the file in the work tree */
1562 temp->name = name;
1563 if (!one->sha1_valid)
1564 strcpy(temp->hex, sha1_to_hex(null_sha1));
1565 else
1566 strcpy(temp->hex, sha1_to_hex(one->sha1));
1567 /* Even though we may sometimes borrow the
1568 * contents from the work tree, we always want
1569 * one->mode. mode is trustworthy even when
1570 * !(one->sha1_valid), as long as
1571 * DIFF_FILE_VALID(one).
1573 sprintf(temp->mode, "%06o", one->mode);
1575 return;
1577 else {
1578 if (diff_populate_filespec(one, 0))
1579 die("cannot read data blob for %s", one->path);
1580 prep_temp_blob(temp, one->data, one->size,
1581 one->sha1, one->mode);
1585 static void remove_tempfile(void)
1587 int i;
1589 for (i = 0; i < 2; i++)
1590 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1591 unlink(diff_temp[i].name);
1592 diff_temp[i].name = NULL;
1596 static void remove_tempfile_on_signal(int signo)
1598 remove_tempfile();
1599 signal(SIGINT, SIG_DFL);
1600 raise(signo);
1603 static int spawn_prog(const char *pgm, const char **arg)
1605 pid_t pid;
1606 int status;
1608 fflush(NULL);
1609 pid = spawnvpe_pipe(pgm, arg, environ, NULL, NULL);
1610 if (pid < 0)
1611 die("unable to fork");
1613 while (waitpid(pid, &status, 0) < 0) {
1614 if (errno == EINTR)
1615 continue;
1616 return -1;
1619 /* Earlier we did not check the exit status because
1620 * diff exits non-zero if files are different, and
1621 * we are not interested in knowing that. It was a
1622 * mistake which made it harder to quit a diff-*
1623 * session that uses the git-apply-patch-script as
1624 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1625 * should also exit non-zero only when it wants to
1626 * abort the entire diff-* session.
1628 if (WIFEXITED(status) && !WEXITSTATUS(status))
1629 return 0;
1630 return -1;
1633 /* An external diff command takes:
1635 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1636 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1639 static void run_external_diff(const char *pgm,
1640 const char *name,
1641 const char *other,
1642 struct diff_filespec *one,
1643 struct diff_filespec *two,
1644 const char *xfrm_msg,
1645 int complete_rewrite)
1647 const char *spawn_arg[10];
1648 struct diff_tempfile *temp = diff_temp;
1649 int retval;
1650 static int atexit_asked = 0;
1651 const char *othername;
1652 const char **arg = &spawn_arg[1];
1654 othername = (other? other : name);
1655 if (one && two) {
1656 prepare_temp_file(name, &temp[0], one);
1657 prepare_temp_file(othername, &temp[1], two);
1658 if (! atexit_asked &&
1659 (temp[0].name == temp[0].tmp_path ||
1660 temp[1].name == temp[1].tmp_path)) {
1661 atexit_asked = 1;
1662 atexit(remove_tempfile);
1664 signal(SIGINT, remove_tempfile_on_signal);
1667 if (one && two) {
1668 *arg++ = name;
1669 *arg++ = temp[0].name;
1670 *arg++ = temp[0].hex;
1671 *arg++ = temp[0].mode;
1672 *arg++ = temp[1].name;
1673 *arg++ = temp[1].hex;
1674 *arg++ = temp[1].mode;
1675 if (other) {
1676 *arg++ = other;
1677 *arg++ = xfrm_msg;
1679 } else {
1680 *arg++ = name;
1682 *arg = NULL;
1683 retval = spawn_prog(pgm, spawn_arg);
1684 remove_tempfile();
1685 if (retval) {
1686 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1687 exit(1);
1691 static void run_diff_cmd(const char *pgm,
1692 const char *name,
1693 const char *other,
1694 struct diff_filespec *one,
1695 struct diff_filespec *two,
1696 const char *xfrm_msg,
1697 struct diff_options *o,
1698 int complete_rewrite)
1700 if (pgm) {
1701 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1702 complete_rewrite);
1703 return;
1705 if (one && two)
1706 builtin_diff(name, other ? other : name,
1707 one, two, xfrm_msg, o, complete_rewrite);
1708 else
1709 printf("* Unmerged path %s\n", name);
1712 static void diff_fill_sha1_info(struct diff_filespec *one)
1714 if (DIFF_FILE_VALID(one)) {
1715 if (!one->sha1_valid) {
1716 struct stat st;
1717 if (!strcmp(one->path, "-")) {
1718 hashcpy(one->sha1, null_sha1);
1719 return;
1721 if (lstat(one->path, &st) < 0)
1722 die("stat %s", one->path);
1723 if (index_path(one->sha1, one->path, &st, 0))
1724 die("cannot hash %s\n", one->path);
1727 else
1728 hashclr(one->sha1);
1731 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1733 const char *pgm = external_diff();
1734 char msg[PATH_MAX*2+300], *xfrm_msg;
1735 struct diff_filespec *one;
1736 struct diff_filespec *two;
1737 const char *name;
1738 const char *other;
1739 char *name_munged, *other_munged;
1740 int complete_rewrite = 0;
1741 int len;
1743 if (DIFF_PAIR_UNMERGED(p)) {
1744 /* unmerged */
1745 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1746 return;
1749 name = p->one->path;
1750 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1751 name_munged = quote_one(name);
1752 other_munged = quote_one(other);
1753 one = p->one; two = p->two;
1755 diff_fill_sha1_info(one);
1756 diff_fill_sha1_info(two);
1758 len = 0;
1759 switch (p->status) {
1760 case DIFF_STATUS_COPIED:
1761 len += snprintf(msg + len, sizeof(msg) - len,
1762 "similarity index %d%%\n"
1763 "copy from %s\n"
1764 "copy to %s\n",
1765 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1766 name_munged, other_munged);
1767 break;
1768 case DIFF_STATUS_RENAMED:
1769 len += snprintf(msg + len, sizeof(msg) - len,
1770 "similarity index %d%%\n"
1771 "rename from %s\n"
1772 "rename to %s\n",
1773 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1774 name_munged, other_munged);
1775 break;
1776 case DIFF_STATUS_MODIFIED:
1777 if (p->score) {
1778 len += snprintf(msg + len, sizeof(msg) - len,
1779 "dissimilarity index %d%%\n",
1780 (int)(0.5 + p->score *
1781 100.0/MAX_SCORE));
1782 complete_rewrite = 1;
1783 break;
1785 /* fallthru */
1786 default:
1787 /* nothing */
1791 if (hashcmp(one->sha1, two->sha1)) {
1792 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1794 if (o->binary) {
1795 mmfile_t mf;
1796 if ((!fill_mmfile(&mf, one) && mmfile_is_binary(&mf)) ||
1797 (!fill_mmfile(&mf, two) && mmfile_is_binary(&mf)))
1798 abbrev = 40;
1800 len += snprintf(msg + len, sizeof(msg) - len,
1801 "index %.*s..%.*s",
1802 abbrev, sha1_to_hex(one->sha1),
1803 abbrev, sha1_to_hex(two->sha1));
1804 if (one->mode == two->mode)
1805 len += snprintf(msg + len, sizeof(msg) - len,
1806 " %06o", one->mode);
1807 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1810 if (len)
1811 msg[--len] = 0;
1812 xfrm_msg = len ? msg : NULL;
1814 if (!pgm &&
1815 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1816 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1817 /* a filepair that changes between file and symlink
1818 * needs to be split into deletion and creation.
1820 struct diff_filespec *null = alloc_filespec(two->path);
1821 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1822 free(null);
1823 null = alloc_filespec(one->path);
1824 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1825 free(null);
1827 else
1828 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1829 complete_rewrite);
1831 free(name_munged);
1832 free(other_munged);
1835 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1836 struct diffstat_t *diffstat)
1838 const char *name;
1839 const char *other;
1840 int complete_rewrite = 0;
1842 if (DIFF_PAIR_UNMERGED(p)) {
1843 /* unmerged */
1844 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1845 return;
1848 name = p->one->path;
1849 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1851 diff_fill_sha1_info(p->one);
1852 diff_fill_sha1_info(p->two);
1854 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1855 complete_rewrite = 1;
1856 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1859 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1861 const char *name;
1862 const char *other;
1864 if (DIFF_PAIR_UNMERGED(p)) {
1865 /* unmerged */
1866 return;
1869 name = p->one->path;
1870 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1872 diff_fill_sha1_info(p->one);
1873 diff_fill_sha1_info(p->two);
1875 builtin_checkdiff(name, other, p->one, p->two, o);
1878 void diff_setup(struct diff_options *options)
1880 memset(options, 0, sizeof(*options));
1881 options->line_termination = '\n';
1882 options->break_opt = -1;
1883 options->rename_limit = -1;
1884 options->context = 3;
1885 options->msg_sep = "";
1887 options->change = diff_change;
1888 options->add_remove = diff_addremove;
1889 options->color_diff = diff_use_color_default;
1890 options->detect_rename = diff_detect_rename_default;
1893 int diff_setup_done(struct diff_options *options)
1895 int count = 0;
1897 if (options->output_format & DIFF_FORMAT_NAME)
1898 count++;
1899 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
1900 count++;
1901 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
1902 count++;
1903 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
1904 count++;
1905 if (count > 1)
1906 die("--name-only, --name-status, --check and -s are mutually exclusive");
1908 if (options->find_copies_harder)
1909 options->detect_rename = DIFF_DETECT_COPY;
1911 if (options->output_format & (DIFF_FORMAT_NAME |
1912 DIFF_FORMAT_NAME_STATUS |
1913 DIFF_FORMAT_CHECKDIFF |
1914 DIFF_FORMAT_NO_OUTPUT))
1915 options->output_format &= ~(DIFF_FORMAT_RAW |
1916 DIFF_FORMAT_NUMSTAT |
1917 DIFF_FORMAT_DIFFSTAT |
1918 DIFF_FORMAT_SHORTSTAT |
1919 DIFF_FORMAT_SUMMARY |
1920 DIFF_FORMAT_PATCH);
1923 * These cases always need recursive; we do not drop caller-supplied
1924 * recursive bits for other formats here.
1926 if (options->output_format & (DIFF_FORMAT_PATCH |
1927 DIFF_FORMAT_NUMSTAT |
1928 DIFF_FORMAT_DIFFSTAT |
1929 DIFF_FORMAT_SHORTSTAT |
1930 DIFF_FORMAT_SUMMARY |
1931 DIFF_FORMAT_CHECKDIFF))
1932 options->recursive = 1;
1934 * Also pickaxe would not work very well if you do not say recursive
1936 if (options->pickaxe)
1937 options->recursive = 1;
1939 if (options->detect_rename && options->rename_limit < 0)
1940 options->rename_limit = diff_rename_limit_default;
1941 if (options->setup & DIFF_SETUP_USE_CACHE) {
1942 if (!active_cache)
1943 /* read-cache does not die even when it fails
1944 * so it is safe for us to do this here. Also
1945 * it does not smudge active_cache or active_nr
1946 * when it fails, so we do not have to worry about
1947 * cleaning it up ourselves either.
1949 read_cache();
1951 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1952 use_size_cache = 1;
1953 if (options->abbrev <= 0 || 40 < options->abbrev)
1954 options->abbrev = 40; /* full */
1957 * It does not make sense to show the first hit we happened
1958 * to have found. It does not make sense not to return with
1959 * exit code in such a case either.
1961 if (options->quiet) {
1962 options->output_format = DIFF_FORMAT_NO_OUTPUT;
1963 options->exit_with_status = 1;
1967 * If we postprocess in diffcore, we cannot simply return
1968 * upon the first hit. We need to run diff as usual.
1970 if (options->pickaxe || options->filter)
1971 options->quiet = 0;
1973 return 0;
1976 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1978 char c, *eq;
1979 int len;
1981 if (*arg != '-')
1982 return 0;
1983 c = *++arg;
1984 if (!c)
1985 return 0;
1986 if (c == arg_short) {
1987 c = *++arg;
1988 if (!c)
1989 return 1;
1990 if (val && isdigit(c)) {
1991 char *end;
1992 int n = strtoul(arg, &end, 10);
1993 if (*end)
1994 return 0;
1995 *val = n;
1996 return 1;
1998 return 0;
2000 if (c != '-')
2001 return 0;
2002 arg++;
2003 eq = strchr(arg, '=');
2004 if (eq)
2005 len = eq - arg;
2006 else
2007 len = strlen(arg);
2008 if (!len || strncmp(arg, arg_long, len))
2009 return 0;
2010 if (eq) {
2011 int n;
2012 char *end;
2013 if (!isdigit(*++eq))
2014 return 0;
2015 n = strtoul(eq, &end, 10);
2016 if (*end)
2017 return 0;
2018 *val = n;
2020 return 1;
2023 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2025 const char *arg = av[0];
2026 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2027 options->output_format |= DIFF_FORMAT_PATCH;
2028 else if (opt_arg(arg, 'U', "unified", &options->context))
2029 options->output_format |= DIFF_FORMAT_PATCH;
2030 else if (!strcmp(arg, "--raw"))
2031 options->output_format |= DIFF_FORMAT_RAW;
2032 else if (!strcmp(arg, "--patch-with-raw")) {
2033 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2035 else if (!strcmp(arg, "--numstat")) {
2036 options->output_format |= DIFF_FORMAT_NUMSTAT;
2038 else if (!strcmp(arg, "--shortstat")) {
2039 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2041 else if (!prefixcmp(arg, "--stat")) {
2042 char *end;
2043 int width = options->stat_width;
2044 int name_width = options->stat_name_width;
2045 arg += 6;
2046 end = (char *)arg;
2048 switch (*arg) {
2049 case '-':
2050 if (!prefixcmp(arg, "-width="))
2051 width = strtoul(arg + 7, &end, 10);
2052 else if (!prefixcmp(arg, "-name-width="))
2053 name_width = strtoul(arg + 12, &end, 10);
2054 break;
2055 case '=':
2056 width = strtoul(arg+1, &end, 10);
2057 if (*end == ',')
2058 name_width = strtoul(end+1, &end, 10);
2061 /* Important! This checks all the error cases! */
2062 if (*end)
2063 return 0;
2064 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2065 options->stat_name_width = name_width;
2066 options->stat_width = width;
2068 else if (!strcmp(arg, "--check"))
2069 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2070 else if (!strcmp(arg, "--summary"))
2071 options->output_format |= DIFF_FORMAT_SUMMARY;
2072 else if (!strcmp(arg, "--patch-with-stat")) {
2073 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2075 else if (!strcmp(arg, "-z"))
2076 options->line_termination = 0;
2077 else if (!prefixcmp(arg, "-l"))
2078 options->rename_limit = strtoul(arg+2, NULL, 10);
2079 else if (!strcmp(arg, "--full-index"))
2080 options->full_index = 1;
2081 else if (!strcmp(arg, "--binary")) {
2082 options->output_format |= DIFF_FORMAT_PATCH;
2083 options->binary = 1;
2085 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
2086 options->text = 1;
2088 else if (!strcmp(arg, "--name-only"))
2089 options->output_format |= DIFF_FORMAT_NAME;
2090 else if (!strcmp(arg, "--name-status"))
2091 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2092 else if (!strcmp(arg, "-R"))
2093 options->reverse_diff = 1;
2094 else if (!prefixcmp(arg, "-S"))
2095 options->pickaxe = arg + 2;
2096 else if (!strcmp(arg, "-s")) {
2097 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2099 else if (!prefixcmp(arg, "-O"))
2100 options->orderfile = arg + 2;
2101 else if (!prefixcmp(arg, "--diff-filter="))
2102 options->filter = arg + 14;
2103 else if (!strcmp(arg, "--pickaxe-all"))
2104 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2105 else if (!strcmp(arg, "--pickaxe-regex"))
2106 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2107 else if (!prefixcmp(arg, "-B")) {
2108 if ((options->break_opt =
2109 diff_scoreopt_parse(arg)) == -1)
2110 return -1;
2112 else if (!prefixcmp(arg, "-M")) {
2113 if ((options->rename_score =
2114 diff_scoreopt_parse(arg)) == -1)
2115 return -1;
2116 options->detect_rename = DIFF_DETECT_RENAME;
2118 else if (!prefixcmp(arg, "-C")) {
2119 if ((options->rename_score =
2120 diff_scoreopt_parse(arg)) == -1)
2121 return -1;
2122 options->detect_rename = DIFF_DETECT_COPY;
2124 else if (!strcmp(arg, "--find-copies-harder"))
2125 options->find_copies_harder = 1;
2126 else if (!strcmp(arg, "--abbrev"))
2127 options->abbrev = DEFAULT_ABBREV;
2128 else if (!prefixcmp(arg, "--abbrev=")) {
2129 options->abbrev = strtoul(arg + 9, NULL, 10);
2130 if (options->abbrev < MINIMUM_ABBREV)
2131 options->abbrev = MINIMUM_ABBREV;
2132 else if (40 < options->abbrev)
2133 options->abbrev = 40;
2135 else if (!strcmp(arg, "--color"))
2136 options->color_diff = 1;
2137 else if (!strcmp(arg, "--no-color"))
2138 options->color_diff = 0;
2139 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2140 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2141 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2142 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2143 else if (!strcmp(arg, "--ignore-space-at-eol"))
2144 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2145 else if (!strcmp(arg, "--color-words"))
2146 options->color_diff = options->color_diff_words = 1;
2147 else if (!strcmp(arg, "--no-renames"))
2148 options->detect_rename = 0;
2149 else if (!strcmp(arg, "--exit-code"))
2150 options->exit_with_status = 1;
2151 else if (!strcmp(arg, "--quiet"))
2152 options->quiet = 1;
2153 else
2154 return 0;
2155 return 1;
2158 static int parse_num(const char **cp_p)
2160 unsigned long num, scale;
2161 int ch, dot;
2162 const char *cp = *cp_p;
2164 num = 0;
2165 scale = 1;
2166 dot = 0;
2167 for(;;) {
2168 ch = *cp;
2169 if ( !dot && ch == '.' ) {
2170 scale = 1;
2171 dot = 1;
2172 } else if ( ch == '%' ) {
2173 scale = dot ? scale*100 : 100;
2174 cp++; /* % is always at the end */
2175 break;
2176 } else if ( ch >= '0' && ch <= '9' ) {
2177 if ( scale < 100000 ) {
2178 scale *= 10;
2179 num = (num*10) + (ch-'0');
2181 } else {
2182 break;
2184 cp++;
2186 *cp_p = cp;
2188 /* user says num divided by scale and we say internally that
2189 * is MAX_SCORE * num / scale.
2191 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2194 int diff_scoreopt_parse(const char *opt)
2196 int opt1, opt2, cmd;
2198 if (*opt++ != '-')
2199 return -1;
2200 cmd = *opt++;
2201 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2202 return -1; /* that is not a -M, -C nor -B option */
2204 opt1 = parse_num(&opt);
2205 if (cmd != 'B')
2206 opt2 = 0;
2207 else {
2208 if (*opt == 0)
2209 opt2 = 0;
2210 else if (*opt != '/')
2211 return -1; /* we expect -B80/99 or -B80 */
2212 else {
2213 opt++;
2214 opt2 = parse_num(&opt);
2217 if (*opt != 0)
2218 return -1;
2219 return opt1 | (opt2 << 16);
2222 struct diff_queue_struct diff_queued_diff;
2224 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2226 if (queue->alloc <= queue->nr) {
2227 queue->alloc = alloc_nr(queue->alloc);
2228 queue->queue = xrealloc(queue->queue,
2229 sizeof(dp) * queue->alloc);
2231 queue->queue[queue->nr++] = dp;
2234 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2235 struct diff_filespec *one,
2236 struct diff_filespec *two)
2238 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2239 dp->one = one;
2240 dp->two = two;
2241 if (queue)
2242 diff_q(queue, dp);
2243 return dp;
2246 void diff_free_filepair(struct diff_filepair *p)
2248 diff_free_filespec_data(p->one);
2249 diff_free_filespec_data(p->two);
2250 free(p->one);
2251 free(p->two);
2252 free(p);
2255 /* This is different from find_unique_abbrev() in that
2256 * it stuffs the result with dots for alignment.
2258 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2260 int abblen;
2261 const char *abbrev;
2262 if (len == 40)
2263 return sha1_to_hex(sha1);
2265 abbrev = find_unique_abbrev(sha1, len);
2266 if (!abbrev)
2267 return sha1_to_hex(sha1);
2268 abblen = strlen(abbrev);
2269 if (abblen < 37) {
2270 static char hex[41];
2271 if (len < abblen && abblen <= len + 2)
2272 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2273 else
2274 sprintf(hex, "%s...", abbrev);
2275 return hex;
2277 return sha1_to_hex(sha1);
2280 static void diff_flush_raw(struct diff_filepair *p,
2281 struct diff_options *options)
2283 int two_paths;
2284 char status[10];
2285 int abbrev = options->abbrev;
2286 const char *path_one, *path_two;
2287 int inter_name_termination = '\t';
2288 int line_termination = options->line_termination;
2290 if (!line_termination)
2291 inter_name_termination = 0;
2293 path_one = p->one->path;
2294 path_two = p->two->path;
2295 if (line_termination) {
2296 path_one = quote_one(path_one);
2297 path_two = quote_one(path_two);
2300 if (p->score)
2301 sprintf(status, "%c%03d", p->status,
2302 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2303 else {
2304 status[0] = p->status;
2305 status[1] = 0;
2307 switch (p->status) {
2308 case DIFF_STATUS_COPIED:
2309 case DIFF_STATUS_RENAMED:
2310 two_paths = 1;
2311 break;
2312 case DIFF_STATUS_ADDED:
2313 case DIFF_STATUS_DELETED:
2314 two_paths = 0;
2315 break;
2316 default:
2317 two_paths = 0;
2318 break;
2320 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2321 printf(":%06o %06o %s ",
2322 p->one->mode, p->two->mode,
2323 diff_unique_abbrev(p->one->sha1, abbrev));
2324 printf("%s ",
2325 diff_unique_abbrev(p->two->sha1, abbrev));
2327 printf("%s%c%s", status, inter_name_termination, path_one);
2328 if (two_paths)
2329 printf("%c%s", inter_name_termination, path_two);
2330 putchar(line_termination);
2331 if (path_one != p->one->path)
2332 free((void*)path_one);
2333 if (path_two != p->two->path)
2334 free((void*)path_two);
2337 static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2339 char *path = p->two->path;
2341 if (opt->line_termination)
2342 path = quote_one(p->two->path);
2343 printf("%s%c", path, opt->line_termination);
2344 if (p->two->path != path)
2345 free(path);
2348 int diff_unmodified_pair(struct diff_filepair *p)
2350 /* This function is written stricter than necessary to support
2351 * the currently implemented transformers, but the idea is to
2352 * let transformers to produce diff_filepairs any way they want,
2353 * and filter and clean them up here before producing the output.
2355 struct diff_filespec *one, *two;
2357 if (DIFF_PAIR_UNMERGED(p))
2358 return 0; /* unmerged is interesting */
2360 one = p->one;
2361 two = p->two;
2363 /* deletion, addition, mode or type change
2364 * and rename are all interesting.
2366 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2367 DIFF_PAIR_MODE_CHANGED(p) ||
2368 strcmp(one->path, two->path))
2369 return 0;
2371 /* both are valid and point at the same path. that is, we are
2372 * dealing with a change.
2374 if (one->sha1_valid && two->sha1_valid &&
2375 !hashcmp(one->sha1, two->sha1))
2376 return 1; /* no change */
2377 if (!one->sha1_valid && !two->sha1_valid)
2378 return 1; /* both look at the same file on the filesystem. */
2379 return 0;
2382 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2384 if (diff_unmodified_pair(p))
2385 return;
2387 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2388 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2389 return; /* no tree diffs in patch format */
2391 run_diff(p, o);
2394 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2395 struct diffstat_t *diffstat)
2397 if (diff_unmodified_pair(p))
2398 return;
2400 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2401 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2402 return; /* no tree diffs in patch format */
2404 run_diffstat(p, o, diffstat);
2407 static void diff_flush_checkdiff(struct diff_filepair *p,
2408 struct diff_options *o)
2410 if (diff_unmodified_pair(p))
2411 return;
2413 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2414 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2415 return; /* no tree diffs in patch format */
2417 run_checkdiff(p, o);
2420 int diff_queue_is_empty(void)
2422 struct diff_queue_struct *q = &diff_queued_diff;
2423 int i;
2424 for (i = 0; i < q->nr; i++)
2425 if (!diff_unmodified_pair(q->queue[i]))
2426 return 0;
2427 return 1;
2430 #if DIFF_DEBUG
2431 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2433 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2434 x, one ? one : "",
2435 s->path,
2436 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2437 s->mode,
2438 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2439 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2440 x, one ? one : "",
2441 s->size, s->xfrm_flags);
2444 void diff_debug_filepair(const struct diff_filepair *p, int i)
2446 diff_debug_filespec(p->one, i, "one");
2447 diff_debug_filespec(p->two, i, "two");
2448 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2449 p->score, p->status ? p->status : '?',
2450 p->source_stays, p->broken_pair);
2453 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2455 int i;
2456 if (msg)
2457 fprintf(stderr, "%s\n", msg);
2458 fprintf(stderr, "q->nr = %d\n", q->nr);
2459 for (i = 0; i < q->nr; i++) {
2460 struct diff_filepair *p = q->queue[i];
2461 diff_debug_filepair(p, i);
2464 #endif
2466 static void diff_resolve_rename_copy(void)
2468 int i, j;
2469 struct diff_filepair *p, *pp;
2470 struct diff_queue_struct *q = &diff_queued_diff;
2472 diff_debug_queue("resolve-rename-copy", q);
2474 for (i = 0; i < q->nr; i++) {
2475 p = q->queue[i];
2476 p->status = 0; /* undecided */
2477 if (DIFF_PAIR_UNMERGED(p))
2478 p->status = DIFF_STATUS_UNMERGED;
2479 else if (!DIFF_FILE_VALID(p->one))
2480 p->status = DIFF_STATUS_ADDED;
2481 else if (!DIFF_FILE_VALID(p->two))
2482 p->status = DIFF_STATUS_DELETED;
2483 else if (DIFF_PAIR_TYPE_CHANGED(p))
2484 p->status = DIFF_STATUS_TYPE_CHANGED;
2486 /* from this point on, we are dealing with a pair
2487 * whose both sides are valid and of the same type, i.e.
2488 * either in-place edit or rename/copy edit.
2490 else if (DIFF_PAIR_RENAME(p)) {
2491 if (p->source_stays) {
2492 p->status = DIFF_STATUS_COPIED;
2493 continue;
2495 /* See if there is some other filepair that
2496 * copies from the same source as us. If so
2497 * we are a copy. Otherwise we are either a
2498 * copy if the path stays, or a rename if it
2499 * does not, but we already handled "stays" case.
2501 for (j = i + 1; j < q->nr; j++) {
2502 pp = q->queue[j];
2503 if (strcmp(pp->one->path, p->one->path))
2504 continue; /* not us */
2505 if (!DIFF_PAIR_RENAME(pp))
2506 continue; /* not a rename/copy */
2507 /* pp is a rename/copy from the same source */
2508 p->status = DIFF_STATUS_COPIED;
2509 break;
2511 if (!p->status)
2512 p->status = DIFF_STATUS_RENAMED;
2514 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2515 p->one->mode != p->two->mode ||
2516 is_null_sha1(p->one->sha1))
2517 p->status = DIFF_STATUS_MODIFIED;
2518 else {
2519 /* This is a "no-change" entry and should not
2520 * happen anymore, but prepare for broken callers.
2522 error("feeding unmodified %s to diffcore",
2523 p->one->path);
2524 p->status = DIFF_STATUS_UNKNOWN;
2527 diff_debug_queue("resolve-rename-copy done", q);
2530 static int check_pair_status(struct diff_filepair *p)
2532 switch (p->status) {
2533 case DIFF_STATUS_UNKNOWN:
2534 return 0;
2535 case 0:
2536 die("internal error in diff-resolve-rename-copy");
2537 default:
2538 return 1;
2542 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2544 int fmt = opt->output_format;
2546 if (fmt & DIFF_FORMAT_CHECKDIFF)
2547 diff_flush_checkdiff(p, opt);
2548 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2549 diff_flush_raw(p, opt);
2550 else if (fmt & DIFF_FORMAT_NAME)
2551 diff_flush_name(p, opt);
2554 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2556 char *name = quote_one(fs->path);
2557 if (fs->mode)
2558 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2559 else
2560 printf(" %s %s\n", newdelete, name);
2561 free(name);
2565 static void show_mode_change(struct diff_filepair *p, int show_name)
2567 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2568 if (show_name) {
2569 char *name = quote_one(p->two->path);
2570 printf(" mode change %06o => %06o %s\n",
2571 p->one->mode, p->two->mode, name);
2572 free(name);
2574 else
2575 printf(" mode change %06o => %06o\n",
2576 p->one->mode, p->two->mode);
2580 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2582 char *names = pprint_rename(p->one->path, p->two->path);
2584 printf(" %s %s (%d%%)\n", renamecopy, names,
2585 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2586 free(names);
2587 show_mode_change(p, 0);
2590 static void diff_summary(struct diff_filepair *p)
2592 switch(p->status) {
2593 case DIFF_STATUS_DELETED:
2594 show_file_mode_name("delete", p->one);
2595 break;
2596 case DIFF_STATUS_ADDED:
2597 show_file_mode_name("create", p->two);
2598 break;
2599 case DIFF_STATUS_COPIED:
2600 show_rename_copy("copy", p);
2601 break;
2602 case DIFF_STATUS_RENAMED:
2603 show_rename_copy("rename", p);
2604 break;
2605 default:
2606 if (p->score) {
2607 char *name = quote_one(p->two->path);
2608 printf(" rewrite %s (%d%%)\n", name,
2609 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2610 free(name);
2611 show_mode_change(p, 0);
2612 } else show_mode_change(p, 1);
2613 break;
2617 struct patch_id_t {
2618 struct xdiff_emit_state xm;
2619 SHA_CTX *ctx;
2620 int patchlen;
2623 static int remove_space(char *line, int len)
2625 int i;
2626 char *dst = line;
2627 unsigned char c;
2629 for (i = 0; i < len; i++)
2630 if (!isspace((c = line[i])))
2631 *dst++ = c;
2633 return dst - line;
2636 static void patch_id_consume(void *priv, char *line, unsigned long len)
2638 struct patch_id_t *data = priv;
2639 int new_len;
2641 /* Ignore line numbers when computing the SHA1 of the patch */
2642 if (!prefixcmp(line, "@@ -"))
2643 return;
2645 new_len = remove_space(line, len);
2647 SHA1_Update(data->ctx, line, new_len);
2648 data->patchlen += new_len;
2651 /* returns 0 upon success, and writes result into sha1 */
2652 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2654 struct diff_queue_struct *q = &diff_queued_diff;
2655 int i;
2656 SHA_CTX ctx;
2657 struct patch_id_t data;
2658 char buffer[PATH_MAX * 4 + 20];
2660 SHA1_Init(&ctx);
2661 memset(&data, 0, sizeof(struct patch_id_t));
2662 data.ctx = &ctx;
2663 data.xm.consume = patch_id_consume;
2665 for (i = 0; i < q->nr; i++) {
2666 xpparam_t xpp;
2667 xdemitconf_t xecfg;
2668 xdemitcb_t ecb;
2669 mmfile_t mf1, mf2;
2670 struct diff_filepair *p = q->queue[i];
2671 int len1, len2;
2673 if (p->status == 0)
2674 return error("internal diff status error");
2675 if (p->status == DIFF_STATUS_UNKNOWN)
2676 continue;
2677 if (diff_unmodified_pair(p))
2678 continue;
2679 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2680 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2681 continue;
2682 if (DIFF_PAIR_UNMERGED(p))
2683 continue;
2685 diff_fill_sha1_info(p->one);
2686 diff_fill_sha1_info(p->two);
2687 if (fill_mmfile(&mf1, p->one) < 0 ||
2688 fill_mmfile(&mf2, p->two) < 0)
2689 return error("unable to read files to diff");
2691 /* Maybe hash p->two? into the patch id? */
2692 if (mmfile_is_binary(&mf2))
2693 continue;
2695 len1 = remove_space(p->one->path, strlen(p->one->path));
2696 len2 = remove_space(p->two->path, strlen(p->two->path));
2697 if (p->one->mode == 0)
2698 len1 = snprintf(buffer, sizeof(buffer),
2699 "diff--gita/%.*sb/%.*s"
2700 "newfilemode%06o"
2701 "---/dev/null"
2702 "+++b/%.*s",
2703 len1, p->one->path,
2704 len2, p->two->path,
2705 p->two->mode,
2706 len2, p->two->path);
2707 else if (p->two->mode == 0)
2708 len1 = snprintf(buffer, sizeof(buffer),
2709 "diff--gita/%.*sb/%.*s"
2710 "deletedfilemode%06o"
2711 "---a/%.*s"
2712 "+++/dev/null",
2713 len1, p->one->path,
2714 len2, p->two->path,
2715 p->one->mode,
2716 len1, p->one->path);
2717 else
2718 len1 = snprintf(buffer, sizeof(buffer),
2719 "diff--gita/%.*sb/%.*s"
2720 "---a/%.*s"
2721 "+++b/%.*s",
2722 len1, p->one->path,
2723 len2, p->two->path,
2724 len1, p->one->path,
2725 len2, p->two->path);
2726 SHA1_Update(&ctx, buffer, len1);
2728 xpp.flags = XDF_NEED_MINIMAL;
2729 xecfg.ctxlen = 3;
2730 xecfg.flags = XDL_EMIT_FUNCNAMES;
2731 ecb.outf = xdiff_outf;
2732 ecb.priv = &data;
2733 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2736 SHA1_Final(sha1, &ctx);
2737 return 0;
2740 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2742 struct diff_queue_struct *q = &diff_queued_diff;
2743 int i;
2744 int result = diff_get_patch_id(options, sha1);
2746 for (i = 0; i < q->nr; i++)
2747 diff_free_filepair(q->queue[i]);
2749 free(q->queue);
2750 q->queue = NULL;
2751 q->nr = q->alloc = 0;
2753 return result;
2756 static int is_summary_empty(const struct diff_queue_struct *q)
2758 int i;
2760 for (i = 0; i < q->nr; i++) {
2761 const struct diff_filepair *p = q->queue[i];
2763 switch (p->status) {
2764 case DIFF_STATUS_DELETED:
2765 case DIFF_STATUS_ADDED:
2766 case DIFF_STATUS_COPIED:
2767 case DIFF_STATUS_RENAMED:
2768 return 0;
2769 default:
2770 if (p->score)
2771 return 0;
2772 if (p->one->mode && p->two->mode &&
2773 p->one->mode != p->two->mode)
2774 return 0;
2775 break;
2778 return 1;
2781 void diff_flush(struct diff_options *options)
2783 struct diff_queue_struct *q = &diff_queued_diff;
2784 int i, output_format = options->output_format;
2785 int separator = 0;
2788 * Order: raw, stat, summary, patch
2789 * or: name/name-status/checkdiff (other bits clear)
2791 if (!q->nr)
2792 goto free_queue;
2794 if (output_format & (DIFF_FORMAT_RAW |
2795 DIFF_FORMAT_NAME |
2796 DIFF_FORMAT_NAME_STATUS |
2797 DIFF_FORMAT_CHECKDIFF)) {
2798 for (i = 0; i < q->nr; i++) {
2799 struct diff_filepair *p = q->queue[i];
2800 if (check_pair_status(p))
2801 flush_one_pair(p, options);
2803 separator++;
2806 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
2807 struct diffstat_t diffstat;
2809 memset(&diffstat, 0, sizeof(struct diffstat_t));
2810 diffstat.xm.consume = diffstat_consume;
2811 for (i = 0; i < q->nr; i++) {
2812 struct diff_filepair *p = q->queue[i];
2813 if (check_pair_status(p))
2814 diff_flush_stat(p, options, &diffstat);
2816 if (output_format & DIFF_FORMAT_NUMSTAT)
2817 show_numstat(&diffstat, options);
2818 if (output_format & DIFF_FORMAT_DIFFSTAT)
2819 show_stats(&diffstat, options);
2820 else if (output_format & DIFF_FORMAT_SHORTSTAT)
2821 show_shortstats(&diffstat);
2822 separator++;
2825 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2826 for (i = 0; i < q->nr; i++)
2827 diff_summary(q->queue[i]);
2828 separator++;
2831 if (output_format & DIFF_FORMAT_PATCH) {
2832 if (separator) {
2833 if (options->stat_sep) {
2834 /* attach patch instead of inline */
2835 fputs(options->stat_sep, stdout);
2836 } else {
2837 putchar(options->line_termination);
2841 for (i = 0; i < q->nr; i++) {
2842 struct diff_filepair *p = q->queue[i];
2843 if (check_pair_status(p))
2844 diff_flush_patch(p, options);
2848 if (output_format & DIFF_FORMAT_CALLBACK)
2849 options->format_callback(q, options, options->format_callback_data);
2851 for (i = 0; i < q->nr; i++)
2852 diff_free_filepair(q->queue[i]);
2853 free_queue:
2854 free(q->queue);
2855 q->queue = NULL;
2856 q->nr = q->alloc = 0;
2859 static void diffcore_apply_filter(const char *filter)
2861 int i;
2862 struct diff_queue_struct *q = &diff_queued_diff;
2863 struct diff_queue_struct outq;
2864 outq.queue = NULL;
2865 outq.nr = outq.alloc = 0;
2867 if (!filter)
2868 return;
2870 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2871 int found;
2872 for (i = found = 0; !found && i < q->nr; i++) {
2873 struct diff_filepair *p = q->queue[i];
2874 if (((p->status == DIFF_STATUS_MODIFIED) &&
2875 ((p->score &&
2876 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2877 (!p->score &&
2878 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2879 ((p->status != DIFF_STATUS_MODIFIED) &&
2880 strchr(filter, p->status)))
2881 found++;
2883 if (found)
2884 return;
2886 /* otherwise we will clear the whole queue
2887 * by copying the empty outq at the end of this
2888 * function, but first clear the current entries
2889 * in the queue.
2891 for (i = 0; i < q->nr; i++)
2892 diff_free_filepair(q->queue[i]);
2894 else {
2895 /* Only the matching ones */
2896 for (i = 0; i < q->nr; i++) {
2897 struct diff_filepair *p = q->queue[i];
2899 if (((p->status == DIFF_STATUS_MODIFIED) &&
2900 ((p->score &&
2901 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2902 (!p->score &&
2903 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2904 ((p->status != DIFF_STATUS_MODIFIED) &&
2905 strchr(filter, p->status)))
2906 diff_q(&outq, p);
2907 else
2908 diff_free_filepair(p);
2911 free(q->queue);
2912 *q = outq;
2915 void diffcore_std(struct diff_options *options)
2917 if (options->quiet)
2918 return;
2919 if (options->break_opt != -1)
2920 diffcore_break(options->break_opt);
2921 if (options->detect_rename)
2922 diffcore_rename(options);
2923 if (options->break_opt != -1)
2924 diffcore_merge_broken();
2925 if (options->pickaxe)
2926 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2927 if (options->orderfile)
2928 diffcore_order(options->orderfile);
2929 diff_resolve_rename_copy();
2930 diffcore_apply_filter(options->filter);
2932 options->has_changes = !!diff_queued_diff.nr;
2936 void diff_addremove(struct diff_options *options,
2937 int addremove, unsigned mode,
2938 const unsigned char *sha1,
2939 const char *base, const char *path)
2941 char concatpath[PATH_MAX];
2942 struct diff_filespec *one, *two;
2944 /* This may look odd, but it is a preparation for
2945 * feeding "there are unchanged files which should
2946 * not produce diffs, but when you are doing copy
2947 * detection you would need them, so here they are"
2948 * entries to the diff-core. They will be prefixed
2949 * with something like '=' or '*' (I haven't decided
2950 * which but should not make any difference).
2951 * Feeding the same new and old to diff_change()
2952 * also has the same effect.
2953 * Before the final output happens, they are pruned after
2954 * merged into rename/copy pairs as appropriate.
2956 if (options->reverse_diff)
2957 addremove = (addremove == '+' ? '-' :
2958 addremove == '-' ? '+' : addremove);
2960 if (!path) path = "";
2961 sprintf(concatpath, "%s%s", base, path);
2962 one = alloc_filespec(concatpath);
2963 two = alloc_filespec(concatpath);
2965 if (addremove != '+')
2966 fill_filespec(one, sha1, mode);
2967 if (addremove != '-')
2968 fill_filespec(two, sha1, mode);
2970 diff_queue(&diff_queued_diff, one, two);
2971 options->has_changes = 1;
2974 void diff_change(struct diff_options *options,
2975 unsigned old_mode, unsigned new_mode,
2976 const unsigned char *old_sha1,
2977 const unsigned char *new_sha1,
2978 const char *base, const char *path)
2980 char concatpath[PATH_MAX];
2981 struct diff_filespec *one, *two;
2983 if (options->reverse_diff) {
2984 unsigned tmp;
2985 const unsigned char *tmp_c;
2986 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2987 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2989 if (!path) path = "";
2990 sprintf(concatpath, "%s%s", base, path);
2991 one = alloc_filespec(concatpath);
2992 two = alloc_filespec(concatpath);
2993 fill_filespec(one, old_sha1, old_mode);
2994 fill_filespec(two, new_sha1, new_mode);
2996 diff_queue(&diff_queued_diff, one, two);
2997 options->has_changes = 1;
3000 void diff_unmerge(struct diff_options *options,
3001 const char *path,
3002 unsigned mode, const unsigned char *sha1)
3004 struct diff_filespec *one, *two;
3005 one = alloc_filespec(path);
3006 two = alloc_filespec(path);
3007 fill_filespec(one, sha1, mode);
3008 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;