Do not leak pipe file handles into the child processes.
[git/mingw.git] / diff.c
blob12161b6f87889e5d0351fea586bafadb5752236f
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 (!strncmp(var, "diff.color.", 11) || !strncmp(var, "color.diff.", 11)) {
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)
190 int ch, nl_just_seen = 1;
191 while (0 < size--) {
192 ch = *data++;
193 if (nl_just_seen)
194 putchar(prefix);
195 putchar(ch);
196 if (ch == '\n')
197 nl_just_seen = 1;
198 else
199 nl_just_seen = 0;
201 if (!nl_just_seen)
202 printf("\n\\ No newline at end of file\n");
205 static void emit_rewrite_diff(const char *name_a,
206 const char *name_b,
207 struct diff_filespec *one,
208 struct diff_filespec *two)
210 int lc_a, lc_b;
211 const char *name_a_tab, *name_b_tab;
213 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
214 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
216 diff_populate_filespec(one, 0);
217 diff_populate_filespec(two, 0);
218 lc_a = count_lines(one->data, one->size);
219 lc_b = count_lines(two->data, two->size);
220 printf("--- a/%s%s\n+++ b/%s%s\n@@ -",
221 name_a, name_a_tab,
222 name_b, name_b_tab);
223 print_line_count(lc_a);
224 printf(" +");
225 print_line_count(lc_b);
226 printf(" @@\n");
227 if (lc_a)
228 copy_file('-', one->data, one->size);
229 if (lc_b)
230 copy_file('+', two->data, two->size);
233 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
235 if (!DIFF_FILE_VALID(one)) {
236 mf->ptr = (char *)""; /* does not matter */
237 mf->size = 0;
238 return 0;
240 else if (diff_populate_filespec(one, 0))
241 return -1;
242 mf->ptr = one->data;
243 mf->size = one->size;
244 return 0;
247 struct diff_words_buffer {
248 mmfile_t text;
249 long alloc;
250 long current; /* output pointer */
251 int suppressed_newline;
254 static void diff_words_append(char *line, unsigned long len,
255 struct diff_words_buffer *buffer)
257 if (buffer->text.size + len > buffer->alloc) {
258 buffer->alloc = (buffer->text.size + len) * 3 / 2;
259 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
261 line++;
262 len--;
263 memcpy(buffer->text.ptr + buffer->text.size, line, len);
264 buffer->text.size += len;
267 struct diff_words_data {
268 struct xdiff_emit_state xm;
269 struct diff_words_buffer minus, plus;
272 static void print_word(struct diff_words_buffer *buffer, int len, int color,
273 int suppress_newline)
275 const char *ptr;
276 int eol = 0;
278 if (len == 0)
279 return;
281 ptr = buffer->text.ptr + buffer->current;
282 buffer->current += len;
284 if (ptr[len - 1] == '\n') {
285 eol = 1;
286 len--;
289 fputs(diff_get_color(1, color), stdout);
290 fwrite(ptr, len, 1, stdout);
291 fputs(diff_get_color(1, DIFF_RESET), stdout);
293 if (eol) {
294 if (suppress_newline)
295 buffer->suppressed_newline = 1;
296 else
297 putchar('\n');
301 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
303 struct diff_words_data *diff_words = priv;
305 if (diff_words->minus.suppressed_newline) {
306 if (line[0] != '+')
307 putchar('\n');
308 diff_words->minus.suppressed_newline = 0;
311 len--;
312 switch (line[0]) {
313 case '-':
314 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
315 break;
316 case '+':
317 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
318 break;
319 case ' ':
320 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
321 diff_words->minus.current += len;
322 break;
326 /* this executes the word diff on the accumulated buffers */
327 static void diff_words_show(struct diff_words_data *diff_words)
329 xpparam_t xpp;
330 xdemitconf_t xecfg;
331 xdemitcb_t ecb;
332 mmfile_t minus, plus;
333 int i;
335 minus.size = diff_words->minus.text.size;
336 minus.ptr = xmalloc(minus.size);
337 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
338 for (i = 0; i < minus.size; i++)
339 if (isspace(minus.ptr[i]))
340 minus.ptr[i] = '\n';
341 diff_words->minus.current = 0;
343 plus.size = diff_words->plus.text.size;
344 plus.ptr = xmalloc(plus.size);
345 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
346 for (i = 0; i < plus.size; i++)
347 if (isspace(plus.ptr[i]))
348 plus.ptr[i] = '\n';
349 diff_words->plus.current = 0;
351 xpp.flags = XDF_NEED_MINIMAL;
352 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
353 xecfg.flags = 0;
354 ecb.outf = xdiff_outf;
355 ecb.priv = diff_words;
356 diff_words->xm.consume = fn_out_diff_words_aux;
357 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
359 free(minus.ptr);
360 free(plus.ptr);
361 diff_words->minus.text.size = diff_words->plus.text.size = 0;
363 if (diff_words->minus.suppressed_newline) {
364 putchar('\n');
365 diff_words->minus.suppressed_newline = 0;
369 struct emit_callback {
370 struct xdiff_emit_state xm;
371 int nparents, color_diff;
372 const char **label_path;
373 struct diff_words_data *diff_words;
376 static void free_diff_words_data(struct emit_callback *ecbdata)
378 if (ecbdata->diff_words) {
379 /* flush buffers */
380 if (ecbdata->diff_words->minus.text.size ||
381 ecbdata->diff_words->plus.text.size)
382 diff_words_show(ecbdata->diff_words);
384 if (ecbdata->diff_words->minus.text.ptr)
385 free (ecbdata->diff_words->minus.text.ptr);
386 if (ecbdata->diff_words->plus.text.ptr)
387 free (ecbdata->diff_words->plus.text.ptr);
388 free(ecbdata->diff_words);
389 ecbdata->diff_words = NULL;
393 const char *diff_get_color(int diff_use_color, enum color_diff ix)
395 if (diff_use_color)
396 return diff_colors[ix];
397 return "";
400 static void emit_line(const char *set, const char *reset, const char *line, int len)
402 if (len > 0 && line[len-1] == '\n')
403 len--;
404 fputs(set, stdout);
405 fwrite(line, len, 1, stdout);
406 puts(reset);
409 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
411 int col0 = ecbdata->nparents;
412 int last_tab_in_indent = -1;
413 int last_space_in_indent = -1;
414 int i;
415 int tail = len;
416 int need_highlight_leading_space = 0;
417 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
418 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
420 if (!*ws) {
421 emit_line(set, reset, line, len);
422 return;
425 /* The line is a newly added line. Does it have funny leading
426 * whitespaces? In indent, SP should never precede a TAB.
428 for (i = col0; i < len; i++) {
429 if (line[i] == '\t') {
430 last_tab_in_indent = i;
431 if (0 <= last_space_in_indent)
432 need_highlight_leading_space = 1;
434 else if (line[i] == ' ')
435 last_space_in_indent = i;
436 else
437 break;
439 fputs(set, stdout);
440 fwrite(line, col0, 1, stdout);
441 fputs(reset, stdout);
442 if (((i == len) || line[i] == '\n') && i != col0) {
443 /* The whole line was indent */
444 emit_line(ws, reset, line + col0, len - col0);
445 return;
447 i = col0;
448 if (need_highlight_leading_space) {
449 while (i < last_tab_in_indent) {
450 if (line[i] == ' ') {
451 fputs(ws, stdout);
452 putchar(' ');
453 fputs(reset, stdout);
455 else
456 putchar(line[i]);
457 i++;
460 tail = len - 1;
461 if (line[tail] == '\n' && i < tail)
462 tail--;
463 while (i < tail) {
464 if (!isspace(line[tail]))
465 break;
466 tail--;
468 if ((i < tail && line[tail + 1] != '\n')) {
469 /* This has whitespace between tail+1..len */
470 fputs(set, stdout);
471 fwrite(line + i, tail - i + 1, 1, stdout);
472 fputs(reset, stdout);
473 emit_line(ws, reset, line + tail + 1, len - tail - 1);
475 else
476 emit_line(set, reset, line + i, len - i);
479 static void fn_out_consume(void *priv, char *line, unsigned long len)
481 int i;
482 int color;
483 struct emit_callback *ecbdata = priv;
484 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
485 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
487 if (ecbdata->label_path[0]) {
488 const char *name_a_tab, *name_b_tab;
490 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
491 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
493 printf("%s--- %s%s%s\n",
494 set, ecbdata->label_path[0], reset, name_a_tab);
495 printf("%s+++ %s%s%s\n",
496 set, ecbdata->label_path[1], reset, name_b_tab);
497 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
500 /* This is not really necessary for now because
501 * this codepath only deals with two-way diffs.
503 for (i = 0; i < len && line[i] == '@'; i++)
505 if (2 <= i && i < len && line[i] == ' ') {
506 ecbdata->nparents = i - 1;
507 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
508 reset, line, len);
509 return;
512 if (len < ecbdata->nparents) {
513 set = reset;
514 emit_line(reset, reset, line, len);
515 return;
518 color = DIFF_PLAIN;
519 if (ecbdata->diff_words && ecbdata->nparents != 1)
520 /* fall back to normal diff */
521 free_diff_words_data(ecbdata);
522 if (ecbdata->diff_words) {
523 if (line[0] == '-') {
524 diff_words_append(line, len,
525 &ecbdata->diff_words->minus);
526 return;
527 } else if (line[0] == '+') {
528 diff_words_append(line, len,
529 &ecbdata->diff_words->plus);
530 return;
532 if (ecbdata->diff_words->minus.text.size ||
533 ecbdata->diff_words->plus.text.size)
534 diff_words_show(ecbdata->diff_words);
535 line++;
536 len--;
537 emit_line(set, reset, line, len);
538 return;
540 for (i = 0; i < ecbdata->nparents && len; i++) {
541 if (line[i] == '-')
542 color = DIFF_FILE_OLD;
543 else if (line[i] == '+')
544 color = DIFF_FILE_NEW;
547 if (color != DIFF_FILE_NEW) {
548 emit_line(diff_get_color(ecbdata->color_diff, color),
549 reset, line, len);
550 return;
552 emit_add_line(reset, ecbdata, line, len);
555 static char *pprint_rename(const char *a, const char *b)
557 const char *old = a;
558 const char *new = b;
559 char *name = NULL;
560 int pfx_length, sfx_length;
561 int len_a = strlen(a);
562 int len_b = strlen(b);
564 /* Find common prefix */
565 pfx_length = 0;
566 while (*old && *new && *old == *new) {
567 if (*old == '/')
568 pfx_length = old - a + 1;
569 old++;
570 new++;
573 /* Find common suffix */
574 old = a + len_a;
575 new = b + len_b;
576 sfx_length = 0;
577 while (a <= old && b <= new && *old == *new) {
578 if (*old == '/')
579 sfx_length = len_a - (old - a);
580 old--;
581 new--;
585 * pfx{mid-a => mid-b}sfx
586 * {pfx-a => pfx-b}sfx
587 * pfx{sfx-a => sfx-b}
588 * name-a => name-b
590 if (pfx_length + sfx_length) {
591 int a_midlen = len_a - pfx_length - sfx_length;
592 int b_midlen = len_b - pfx_length - sfx_length;
593 if (a_midlen < 0) a_midlen = 0;
594 if (b_midlen < 0) b_midlen = 0;
596 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
597 sprintf(name, "%.*s{%.*s => %.*s}%s",
598 pfx_length, a,
599 a_midlen, a + pfx_length,
600 b_midlen, b + pfx_length,
601 a + len_a - sfx_length);
603 else {
604 name = xmalloc(len_a + len_b + 5);
605 sprintf(name, "%s => %s", a, b);
607 return name;
610 struct diffstat_t {
611 struct xdiff_emit_state xm;
613 int nr;
614 int alloc;
615 struct diffstat_file {
616 char *name;
617 unsigned is_unmerged:1;
618 unsigned is_binary:1;
619 unsigned is_renamed:1;
620 unsigned int added, deleted;
621 } **files;
624 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
625 const char *name_a,
626 const char *name_b)
628 struct diffstat_file *x;
629 x = xcalloc(sizeof (*x), 1);
630 if (diffstat->nr == diffstat->alloc) {
631 diffstat->alloc = alloc_nr(diffstat->alloc);
632 diffstat->files = xrealloc(diffstat->files,
633 diffstat->alloc * sizeof(x));
635 diffstat->files[diffstat->nr++] = x;
636 if (name_b) {
637 x->name = pprint_rename(name_a, name_b);
638 x->is_renamed = 1;
640 else
641 x->name = xstrdup(name_a);
642 return x;
645 static void diffstat_consume(void *priv, char *line, unsigned long len)
647 struct diffstat_t *diffstat = priv;
648 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
650 if (line[0] == '+')
651 x->added++;
652 else if (line[0] == '-')
653 x->deleted++;
656 const char mime_boundary_leader[] = "------------";
658 static int scale_linear(int it, int width, int max_change)
661 * make sure that at least one '-' is printed if there were deletions,
662 * and likewise for '+'.
664 if (max_change < 2)
665 return it;
666 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
669 static void show_name(const char *prefix, const char *name, int len,
670 const char *reset, const char *set)
672 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
675 static void show_graph(char ch, int cnt, const char *set, const char *reset)
677 if (cnt <= 0)
678 return;
679 printf("%s", set);
680 while (cnt--)
681 putchar(ch);
682 printf("%s", reset);
685 static void show_stats(struct diffstat_t* data, struct diff_options *options)
687 int i, len, add, del, total, adds = 0, dels = 0;
688 int max_change = 0, max_len = 0;
689 int total_files = data->nr;
690 int width, name_width;
691 const char *reset, *set, *add_c, *del_c;
693 if (data->nr == 0)
694 return;
696 width = options->stat_width ? options->stat_width : 80;
697 name_width = options->stat_name_width ? options->stat_name_width : 50;
699 /* Sanity: give at least 5 columns to the graph,
700 * but leave at least 10 columns for the name.
702 if (width < name_width + 15) {
703 if (name_width <= 25)
704 width = name_width + 15;
705 else
706 name_width = width - 15;
709 /* Find the longest filename and max number of changes */
710 reset = diff_get_color(options->color_diff, DIFF_RESET);
711 set = diff_get_color(options->color_diff, DIFF_PLAIN);
712 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
713 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
715 for (i = 0; i < data->nr; i++) {
716 struct diffstat_file *file = data->files[i];
717 int change = file->added + file->deleted;
719 len = quote_c_style(file->name, NULL, NULL, 0);
720 if (len) {
721 char *qname = xmalloc(len + 1);
722 quote_c_style(file->name, qname, NULL, 0);
723 free(file->name);
724 file->name = qname;
727 len = strlen(file->name);
728 if (max_len < len)
729 max_len = len;
731 if (file->is_binary || file->is_unmerged)
732 continue;
733 if (max_change < change)
734 max_change = change;
737 /* Compute the width of the graph part;
738 * 10 is for one blank at the beginning of the line plus
739 * " | count " between the name and the graph.
741 * From here on, name_width is the width of the name area,
742 * and width is the width of the graph area.
744 name_width = (name_width < max_len) ? name_width : max_len;
745 if (width < (name_width + 10) + max_change)
746 width = width - (name_width + 10);
747 else
748 width = max_change;
750 for (i = 0; i < data->nr; i++) {
751 const char *prefix = "";
752 char *name = data->files[i]->name;
753 int added = data->files[i]->added;
754 int deleted = data->files[i]->deleted;
755 int name_len;
758 * "scale" the filename
760 len = name_width;
761 name_len = strlen(name);
762 if (name_width < name_len) {
763 char *slash;
764 prefix = "...";
765 len -= 3;
766 name += name_len - len;
767 slash = strchr(name, '/');
768 if (slash)
769 name = slash;
772 if (data->files[i]->is_binary) {
773 show_name(prefix, name, len, reset, set);
774 printf(" Bin\n");
775 goto free_diffstat_file;
777 else if (data->files[i]->is_unmerged) {
778 show_name(prefix, name, len, reset, set);
779 printf(" Unmerged\n");
780 goto free_diffstat_file;
782 else if (!data->files[i]->is_renamed &&
783 (added + deleted == 0)) {
784 total_files--;
785 goto free_diffstat_file;
789 * scale the add/delete
791 add = added;
792 del = deleted;
793 total = add + del;
794 adds += add;
795 dels += del;
797 if (width <= max_change) {
798 add = scale_linear(add, width, max_change);
799 del = scale_linear(del, width, max_change);
800 total = add + del;
802 show_name(prefix, name, len, reset, set);
803 printf("%5d ", added + deleted);
804 show_graph('+', add, add_c, reset);
805 show_graph('-', del, del_c, reset);
806 putchar('\n');
807 free_diffstat_file:
808 free(data->files[i]->name);
809 free(data->files[i]);
811 free(data->files);
812 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
813 set, total_files, adds, dels, reset);
816 static void show_shortstats(struct diffstat_t* data)
818 int i, adds = 0, dels = 0, total_files = data->nr;
820 if (data->nr == 0)
821 return;
823 for (i = 0; i < data->nr; i++) {
824 if (!data->files[i]->is_binary &&
825 !data->files[i]->is_unmerged) {
826 int added = data->files[i]->added;
827 int deleted= data->files[i]->deleted;
828 if (!data->files[i]->is_renamed &&
829 (added + deleted == 0)) {
830 total_files--;
831 } else {
832 adds += added;
833 dels += deleted;
836 free(data->files[i]->name);
837 free(data->files[i]);
839 free(data->files);
841 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
842 total_files, adds, dels);
845 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
847 int i;
849 for (i = 0; i < data->nr; i++) {
850 struct diffstat_file *file = data->files[i];
852 if (file->is_binary)
853 printf("-\t-\t");
854 else
855 printf("%d\t%d\t", file->added, file->deleted);
856 if (options->line_termination &&
857 quote_c_style(file->name, NULL, NULL, 0))
858 quote_c_style(file->name, NULL, stdout, 0);
859 else
860 fputs(file->name, stdout);
861 putchar(options->line_termination);
865 struct checkdiff_t {
866 struct xdiff_emit_state xm;
867 const char *filename;
868 int lineno;
871 static void checkdiff_consume(void *priv, char *line, unsigned long len)
873 struct checkdiff_t *data = priv;
875 if (line[0] == '+') {
876 int i, spaces = 0;
878 /* check space before tab */
879 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
880 if (line[i] == ' ')
881 spaces++;
882 if (line[i - 1] == '\t' && spaces)
883 printf("%s:%d: space before tab:%.*s\n",
884 data->filename, data->lineno, (int)len, line);
886 /* check white space at line end */
887 if (line[len - 1] == '\n')
888 len--;
889 if (isspace(line[len - 1]))
890 printf("%s:%d: white space at end: %.*s\n",
891 data->filename, data->lineno, (int)len, line);
893 data->lineno++;
894 } else if (line[0] == ' ')
895 data->lineno++;
896 else if (line[0] == '@') {
897 char *plus = strchr(line, '+');
898 if (plus)
899 data->lineno = strtol(plus, NULL, 10);
900 else
901 die("invalid diff");
905 static unsigned char *deflate_it(char *data,
906 unsigned long size,
907 unsigned long *result_size)
909 int bound;
910 unsigned char *deflated;
911 z_stream stream;
913 memset(&stream, 0, sizeof(stream));
914 deflateInit(&stream, zlib_compression_level);
915 bound = deflateBound(&stream, size);
916 deflated = xmalloc(bound);
917 stream.next_out = deflated;
918 stream.avail_out = bound;
920 stream.next_in = (unsigned char *)data;
921 stream.avail_in = size;
922 while (deflate(&stream, Z_FINISH) == Z_OK)
923 ; /* nothing */
924 deflateEnd(&stream);
925 *result_size = stream.total_out;
926 return deflated;
929 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
931 void *cp;
932 void *delta;
933 void *deflated;
934 void *data;
935 unsigned long orig_size;
936 unsigned long delta_size;
937 unsigned long deflate_size;
938 unsigned long data_size;
940 /* We could do deflated delta, or we could do just deflated two,
941 * whichever is smaller.
943 delta = NULL;
944 deflated = deflate_it(two->ptr, two->size, &deflate_size);
945 if (one->size && two->size) {
946 delta = diff_delta(one->ptr, one->size,
947 two->ptr, two->size,
948 &delta_size, deflate_size);
949 if (delta) {
950 void *to_free = delta;
951 orig_size = delta_size;
952 delta = deflate_it(delta, delta_size, &delta_size);
953 free(to_free);
957 if (delta && delta_size < deflate_size) {
958 printf("delta %lu\n", orig_size);
959 free(deflated);
960 data = delta;
961 data_size = delta_size;
963 else {
964 printf("literal %lu\n", two->size);
965 free(delta);
966 data = deflated;
967 data_size = deflate_size;
970 /* emit data encoded in base85 */
971 cp = data;
972 while (data_size) {
973 int bytes = (52 < data_size) ? 52 : data_size;
974 char line[70];
975 data_size -= bytes;
976 if (bytes <= 26)
977 line[0] = bytes + 'A' - 1;
978 else
979 line[0] = bytes - 26 + 'a' - 1;
980 encode_85(line + 1, cp, bytes);
981 cp = (char *) cp + bytes;
982 puts(line);
984 printf("\n");
985 free(data);
988 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
990 printf("GIT binary patch\n");
991 emit_binary_diff_body(one, two);
992 emit_binary_diff_body(two, one);
995 #define FIRST_FEW_BYTES 8000
996 static int mmfile_is_binary(mmfile_t *mf)
998 long sz = mf->size;
999 if (FIRST_FEW_BYTES < sz)
1000 sz = FIRST_FEW_BYTES;
1001 return !!memchr(mf->ptr, 0, sz);
1004 static void builtin_diff(const char *name_a,
1005 const char *name_b,
1006 struct diff_filespec *one,
1007 struct diff_filespec *two,
1008 const char *xfrm_msg,
1009 struct diff_options *o,
1010 int complete_rewrite)
1012 mmfile_t mf1, mf2;
1013 const char *lbl[2];
1014 char *a_one, *b_two;
1015 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1016 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1018 a_one = quote_two("a/", name_a);
1019 b_two = quote_two("b/", name_b);
1020 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1021 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1022 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1023 if (lbl[0][0] == '/') {
1024 /* /dev/null */
1025 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1026 if (xfrm_msg && xfrm_msg[0])
1027 printf("%s%s%s\n", set, xfrm_msg, reset);
1029 else if (lbl[1][0] == '/') {
1030 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1031 if (xfrm_msg && xfrm_msg[0])
1032 printf("%s%s%s\n", set, xfrm_msg, reset);
1034 else {
1035 if (one->mode != two->mode) {
1036 printf("%sold mode %06o%s\n", set, one->mode, reset);
1037 printf("%snew mode %06o%s\n", set, two->mode, reset);
1039 if (xfrm_msg && xfrm_msg[0])
1040 printf("%s%s%s\n", set, xfrm_msg, reset);
1042 * we do not run diff between different kind
1043 * of objects.
1045 if ((one->mode ^ two->mode) & S_IFMT)
1046 goto free_ab_and_return;
1047 if (complete_rewrite) {
1048 emit_rewrite_diff(name_a, name_b, one, two);
1049 goto free_ab_and_return;
1053 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1054 die("unable to read files to diff");
1056 if (!o->text && (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))) {
1057 /* Quite common confusing case */
1058 if (mf1.size == mf2.size &&
1059 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1060 goto free_ab_and_return;
1061 if (o->binary)
1062 emit_binary_diff(&mf1, &mf2);
1063 else
1064 printf("Binary files %s and %s differ\n",
1065 lbl[0], lbl[1]);
1067 else {
1068 /* Crazy xdl interfaces.. */
1069 const char *diffopts = getenv("GIT_DIFF_OPTS");
1070 xpparam_t xpp;
1071 xdemitconf_t xecfg;
1072 xdemitcb_t ecb;
1073 struct emit_callback ecbdata;
1075 memset(&ecbdata, 0, sizeof(ecbdata));
1076 ecbdata.label_path = lbl;
1077 ecbdata.color_diff = o->color_diff;
1078 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1079 xecfg.ctxlen = o->context;
1080 xecfg.flags = XDL_EMIT_FUNCNAMES;
1081 if (!diffopts)
1083 else if (!strncmp(diffopts, "--unified=", 10))
1084 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1085 else if (!strncmp(diffopts, "-u", 2))
1086 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1087 ecb.outf = xdiff_outf;
1088 ecb.priv = &ecbdata;
1089 ecbdata.xm.consume = fn_out_consume;
1090 if (o->color_diff_words)
1091 ecbdata.diff_words =
1092 xcalloc(1, sizeof(struct diff_words_data));
1093 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1094 if (o->color_diff_words)
1095 free_diff_words_data(&ecbdata);
1098 free_ab_and_return:
1099 free(a_one);
1100 free(b_two);
1101 return;
1104 static void builtin_diffstat(const char *name_a, const char *name_b,
1105 struct diff_filespec *one,
1106 struct diff_filespec *two,
1107 struct diffstat_t *diffstat,
1108 struct diff_options *o,
1109 int complete_rewrite)
1111 mmfile_t mf1, mf2;
1112 struct diffstat_file *data;
1114 data = diffstat_add(diffstat, name_a, name_b);
1116 if (!one || !two) {
1117 data->is_unmerged = 1;
1118 return;
1120 if (complete_rewrite) {
1121 diff_populate_filespec(one, 0);
1122 diff_populate_filespec(two, 0);
1123 data->deleted = count_lines(one->data, one->size);
1124 data->added = count_lines(two->data, two->size);
1125 return;
1127 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1128 die("unable to read files to diff");
1130 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
1131 data->is_binary = 1;
1132 else {
1133 /* Crazy xdl interfaces.. */
1134 xpparam_t xpp;
1135 xdemitconf_t xecfg;
1136 xdemitcb_t ecb;
1138 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1139 xecfg.ctxlen = 0;
1140 xecfg.flags = 0;
1141 ecb.outf = xdiff_outf;
1142 ecb.priv = diffstat;
1143 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1147 static void builtin_checkdiff(const char *name_a, const char *name_b,
1148 struct diff_filespec *one,
1149 struct diff_filespec *two)
1151 mmfile_t mf1, mf2;
1152 struct checkdiff_t data;
1154 if (!two)
1155 return;
1157 memset(&data, 0, sizeof(data));
1158 data.xm.consume = checkdiff_consume;
1159 data.filename = name_b ? name_b : name_a;
1160 data.lineno = 0;
1162 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1163 die("unable to read files to diff");
1165 if (mmfile_is_binary(&mf2))
1166 return;
1167 else {
1168 /* Crazy xdl interfaces.. */
1169 xpparam_t xpp;
1170 xdemitconf_t xecfg;
1171 xdemitcb_t ecb;
1173 xpp.flags = XDF_NEED_MINIMAL;
1174 xecfg.ctxlen = 0;
1175 xecfg.flags = 0;
1176 ecb.outf = xdiff_outf;
1177 ecb.priv = &data;
1178 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1182 struct diff_filespec *alloc_filespec(const char *path)
1184 int namelen = strlen(path);
1185 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1187 memset(spec, 0, sizeof(*spec));
1188 spec->path = (char *)(spec + 1);
1189 memcpy(spec->path, path, namelen+1);
1190 return spec;
1193 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1194 unsigned short mode)
1196 if (mode) {
1197 spec->mode = canon_mode(mode);
1198 hashcpy(spec->sha1, sha1);
1199 spec->sha1_valid = !is_null_sha1(sha1);
1204 * Given a name and sha1 pair, if the dircache tells us the file in
1205 * the work tree has that object contents, return true, so that
1206 * prepare_temp_file() does not have to inflate and extract.
1208 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1210 struct cache_entry *ce;
1211 struct stat st;
1212 int pos, len;
1214 /* We do not read the cache ourselves here, because the
1215 * benchmark with my previous version that always reads cache
1216 * shows that it makes things worse for diff-tree comparing
1217 * two linux-2.6 kernel trees in an already checked out work
1218 * tree. This is because most diff-tree comparisons deal with
1219 * only a small number of files, while reading the cache is
1220 * expensive for a large project, and its cost outweighs the
1221 * savings we get by not inflating the object to a temporary
1222 * file. Practically, this code only helps when we are used
1223 * by diff-cache --cached, which does read the cache before
1224 * calling us.
1226 if (!active_cache)
1227 return 0;
1229 /* We want to avoid the working directory if our caller
1230 * doesn't need the data in a normal file, this system
1231 * is rather slow with its stat/open/mmap/close syscalls,
1232 * and the object is contained in a pack file. The pack
1233 * is probably already open and will be faster to obtain
1234 * the data through than the working directory. Loose
1235 * objects however would tend to be slower as they need
1236 * to be individually opened and inflated.
1238 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1239 return 0;
1241 len = strlen(name);
1242 pos = cache_name_pos(name, len);
1243 if (pos < 0)
1244 return 0;
1245 ce = active_cache[pos];
1246 if ((lstat(name, &st) < 0) ||
1247 !S_ISREG(st.st_mode) || /* careful! */
1248 ce_match_stat(ce, &st, 0) ||
1249 hashcmp(sha1, ce->sha1))
1250 return 0;
1251 /* we return 1 only when we can stat, it is a regular file,
1252 * stat information matches, and sha1 recorded in the cache
1253 * matches. I.e. we know the file in the work tree really is
1254 * the same as the <name, sha1> pair.
1256 return 1;
1259 static struct sha1_size_cache {
1260 unsigned char sha1[20];
1261 unsigned long size;
1262 } **sha1_size_cache;
1263 static int sha1_size_cache_nr, sha1_size_cache_alloc;
1265 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
1266 int find_only,
1267 unsigned long size)
1269 int first, last;
1270 struct sha1_size_cache *e;
1272 first = 0;
1273 last = sha1_size_cache_nr;
1274 while (last > first) {
1275 int cmp, next = (last + first) >> 1;
1276 e = sha1_size_cache[next];
1277 cmp = hashcmp(e->sha1, sha1);
1278 if (!cmp)
1279 return e;
1280 if (cmp < 0) {
1281 last = next;
1282 continue;
1284 first = next+1;
1286 /* not found */
1287 if (find_only)
1288 return NULL;
1289 /* insert to make it at "first" */
1290 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
1291 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
1292 sha1_size_cache = xrealloc(sha1_size_cache,
1293 sha1_size_cache_alloc *
1294 sizeof(*sha1_size_cache));
1296 sha1_size_cache_nr++;
1297 if (first < sha1_size_cache_nr)
1298 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
1299 (sha1_size_cache_nr - first - 1) *
1300 sizeof(*sha1_size_cache));
1301 e = xmalloc(sizeof(struct sha1_size_cache));
1302 sha1_size_cache[first] = e;
1303 hashcpy(e->sha1, sha1);
1304 e->size = size;
1305 return e;
1309 * While doing rename detection and pickaxe operation, we may need to
1310 * grab the data for the blob (or file) for our own in-core comparison.
1311 * diff_filespec has data and size fields for this purpose.
1313 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1315 int err = 0;
1316 if (!DIFF_FILE_VALID(s))
1317 die("internal error: asking to populate invalid file.");
1318 if (S_ISDIR(s->mode))
1319 return -1;
1321 if (!use_size_cache)
1322 size_only = 0;
1324 if (s->data)
1325 return err;
1326 if (!s->sha1_valid ||
1327 reuse_worktree_file(s->path, s->sha1, 0)) {
1328 struct stat st;
1329 int fd;
1330 if (lstat(s->path, &st) < 0) {
1331 if (errno == ENOENT) {
1332 err_empty:
1333 err = -1;
1334 empty:
1335 s->data = (char *)"";
1336 s->size = 0;
1337 return err;
1340 s->size = st.st_size;
1341 if (!s->size)
1342 goto empty;
1343 if (size_only)
1344 return 0;
1345 if (S_ISLNK(st.st_mode)) {
1346 int ret;
1347 s->data = xmalloc(s->size);
1348 s->should_free = 1;
1349 ret = readlink(s->path, s->data, s->size);
1350 if (ret < 0) {
1351 free(s->data);
1352 goto err_empty;
1354 return 0;
1356 fd = open(s->path, O_RDONLY);
1357 if (fd < 0)
1358 goto err_empty;
1359 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1360 close(fd);
1361 s->should_munmap = 1;
1363 else {
1364 char type[20];
1365 struct sha1_size_cache *e;
1367 if (size_only) {
1368 e = locate_size_cache(s->sha1, 1, 0);
1369 if (e) {
1370 s->size = e->size;
1371 return 0;
1373 if (!sha1_object_info(s->sha1, type, &s->size))
1374 locate_size_cache(s->sha1, 0, s->size);
1376 else {
1377 s->data = read_sha1_file(s->sha1, type, &s->size);
1378 s->should_free = 1;
1381 return 0;
1384 void diff_free_filespec_data(struct diff_filespec *s)
1386 if (s->should_free)
1387 free(s->data);
1388 else if (s->should_munmap)
1389 munmap(s->data, s->size);
1390 s->should_free = s->should_munmap = 0;
1391 s->data = NULL;
1392 free(s->cnt_data);
1393 s->cnt_data = NULL;
1396 static void prep_temp_blob(struct diff_tempfile *temp,
1397 void *blob,
1398 unsigned long size,
1399 const unsigned char *sha1,
1400 int mode)
1402 int fd;
1404 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1405 if (fd < 0)
1406 die("unable to create temp-file");
1407 if (write_in_full(fd, blob, size) != size)
1408 die("unable to write temp-file");
1409 close(fd);
1410 temp->name = temp->tmp_path;
1411 strcpy(temp->hex, sha1_to_hex(sha1));
1412 temp->hex[40] = 0;
1413 sprintf(temp->mode, "%06o", mode);
1416 static void prepare_temp_file(const char *name,
1417 struct diff_tempfile *temp,
1418 struct diff_filespec *one)
1420 if (!DIFF_FILE_VALID(one)) {
1421 not_a_valid_file:
1422 /* A '-' entry produces this for file-2, and
1423 * a '+' entry produces this for file-1.
1425 temp->name = "/dev/null";
1426 strcpy(temp->hex, ".");
1427 strcpy(temp->mode, ".");
1428 return;
1431 if (!one->sha1_valid ||
1432 reuse_worktree_file(name, one->sha1, 1)) {
1433 struct stat st;
1434 if (lstat(name, &st) < 0) {
1435 if (errno == ENOENT)
1436 goto not_a_valid_file;
1437 die("stat(%s): %s", name, strerror(errno));
1439 if (S_ISLNK(st.st_mode)) {
1440 int ret;
1441 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1442 if (sizeof(buf) <= st.st_size)
1443 die("symlink too long: %s", name);
1444 ret = readlink(name, buf, st.st_size);
1445 if (ret < 0)
1446 die("readlink(%s)", name);
1447 prep_temp_blob(temp, buf, st.st_size,
1448 (one->sha1_valid ?
1449 one->sha1 : null_sha1),
1450 (one->sha1_valid ?
1451 one->mode : S_IFLNK));
1453 else {
1454 /* we can borrow from the file in the work tree */
1455 temp->name = name;
1456 if (!one->sha1_valid)
1457 strcpy(temp->hex, sha1_to_hex(null_sha1));
1458 else
1459 strcpy(temp->hex, sha1_to_hex(one->sha1));
1460 /* Even though we may sometimes borrow the
1461 * contents from the work tree, we always want
1462 * one->mode. mode is trustworthy even when
1463 * !(one->sha1_valid), as long as
1464 * DIFF_FILE_VALID(one).
1466 sprintf(temp->mode, "%06o", one->mode);
1468 return;
1470 else {
1471 if (diff_populate_filespec(one, 0))
1472 die("cannot read data blob for %s", one->path);
1473 prep_temp_blob(temp, one->data, one->size,
1474 one->sha1, one->mode);
1478 static void remove_tempfile(void)
1480 int i;
1482 for (i = 0; i < 2; i++)
1483 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1484 unlink(diff_temp[i].name);
1485 diff_temp[i].name = NULL;
1489 static void remove_tempfile_on_signal(int signo)
1491 remove_tempfile();
1492 signal(SIGINT, SIG_DFL);
1493 raise(signo);
1496 static int spawn_prog(const char *pgm, const char **arg)
1498 pid_t pid;
1499 int status;
1501 fflush(NULL);
1502 pid = spawnvpe_pipe(pgm, arg, environ, NULL, NULL);
1504 while (waitpid(pid, &status, 0) < 0) {
1505 if (errno == EINTR)
1506 continue;
1507 return -1;
1510 /* Earlier we did not check the exit status because
1511 * diff exits non-zero if files are different, and
1512 * we are not interested in knowing that. It was a
1513 * mistake which made it harder to quit a diff-*
1514 * session that uses the git-apply-patch-script as
1515 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1516 * should also exit non-zero only when it wants to
1517 * abort the entire diff-* session.
1519 if (WIFEXITED(status) && !WEXITSTATUS(status))
1520 return 0;
1521 return -1;
1524 /* An external diff command takes:
1526 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1527 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1530 static void run_external_diff(const char *pgm,
1531 const char *name,
1532 const char *other,
1533 struct diff_filespec *one,
1534 struct diff_filespec *two,
1535 const char *xfrm_msg,
1536 int complete_rewrite)
1538 const char *spawn_arg[10];
1539 struct diff_tempfile *temp = diff_temp;
1540 int retval;
1541 static int atexit_asked = 0;
1542 const char *othername;
1543 const char **arg = &spawn_arg[1];
1545 othername = (other? other : name);
1546 if (one && two) {
1547 prepare_temp_file(name, &temp[0], one);
1548 prepare_temp_file(othername, &temp[1], two);
1549 if (! atexit_asked &&
1550 (temp[0].name == temp[0].tmp_path ||
1551 temp[1].name == temp[1].tmp_path)) {
1552 atexit_asked = 1;
1553 atexit(remove_tempfile);
1555 signal(SIGINT, remove_tempfile_on_signal);
1558 if (one && two) {
1559 *arg++ = name;
1560 *arg++ = temp[0].name;
1561 *arg++ = temp[0].hex;
1562 *arg++ = temp[0].mode;
1563 *arg++ = temp[1].name;
1564 *arg++ = temp[1].hex;
1565 *arg++ = temp[1].mode;
1566 if (other) {
1567 *arg++ = other;
1568 *arg++ = xfrm_msg;
1570 } else {
1571 *arg++ = name;
1573 *arg = NULL;
1574 retval = spawn_prog(pgm, spawn_arg);
1575 remove_tempfile();
1576 if (retval) {
1577 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1578 exit(1);
1582 static void run_diff_cmd(const char *pgm,
1583 const char *name,
1584 const char *other,
1585 struct diff_filespec *one,
1586 struct diff_filespec *two,
1587 const char *xfrm_msg,
1588 struct diff_options *o,
1589 int complete_rewrite)
1591 if (pgm) {
1592 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1593 complete_rewrite);
1594 return;
1596 if (one && two)
1597 builtin_diff(name, other ? other : name,
1598 one, two, xfrm_msg, o, complete_rewrite);
1599 else
1600 printf("* Unmerged path %s\n", name);
1603 static void diff_fill_sha1_info(struct diff_filespec *one)
1605 if (DIFF_FILE_VALID(one)) {
1606 if (!one->sha1_valid) {
1607 struct stat st;
1608 if (lstat(one->path, &st) < 0)
1609 die("stat %s", one->path);
1610 if (index_path(one->sha1, one->path, &st, 0))
1611 die("cannot hash %s\n", one->path);
1614 else
1615 hashclr(one->sha1);
1618 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1620 const char *pgm = external_diff();
1621 char msg[PATH_MAX*2+300], *xfrm_msg;
1622 struct diff_filespec *one;
1623 struct diff_filespec *two;
1624 const char *name;
1625 const char *other;
1626 char *name_munged, *other_munged;
1627 int complete_rewrite = 0;
1628 int len;
1630 if (DIFF_PAIR_UNMERGED(p)) {
1631 /* unmerged */
1632 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1633 return;
1636 name = p->one->path;
1637 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1638 name_munged = quote_one(name);
1639 other_munged = quote_one(other);
1640 one = p->one; two = p->two;
1642 diff_fill_sha1_info(one);
1643 diff_fill_sha1_info(two);
1645 len = 0;
1646 switch (p->status) {
1647 case DIFF_STATUS_COPIED:
1648 len += snprintf(msg + len, sizeof(msg) - len,
1649 "similarity index %d%%\n"
1650 "copy from %s\n"
1651 "copy to %s\n",
1652 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1653 name_munged, other_munged);
1654 break;
1655 case DIFF_STATUS_RENAMED:
1656 len += snprintf(msg + len, sizeof(msg) - len,
1657 "similarity index %d%%\n"
1658 "rename from %s\n"
1659 "rename to %s\n",
1660 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1661 name_munged, other_munged);
1662 break;
1663 case DIFF_STATUS_MODIFIED:
1664 if (p->score) {
1665 len += snprintf(msg + len, sizeof(msg) - len,
1666 "dissimilarity index %d%%\n",
1667 (int)(0.5 + p->score *
1668 100.0/MAX_SCORE));
1669 complete_rewrite = 1;
1670 break;
1672 /* fallthru */
1673 default:
1674 /* nothing */
1678 if (hashcmp(one->sha1, two->sha1)) {
1679 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1681 if (o->binary) {
1682 mmfile_t mf;
1683 if ((!fill_mmfile(&mf, one) && mmfile_is_binary(&mf)) ||
1684 (!fill_mmfile(&mf, two) && mmfile_is_binary(&mf)))
1685 abbrev = 40;
1687 len += snprintf(msg + len, sizeof(msg) - len,
1688 "index %.*s..%.*s",
1689 abbrev, sha1_to_hex(one->sha1),
1690 abbrev, sha1_to_hex(two->sha1));
1691 if (one->mode == two->mode)
1692 len += snprintf(msg + len, sizeof(msg) - len,
1693 " %06o", one->mode);
1694 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1697 if (len)
1698 msg[--len] = 0;
1699 xfrm_msg = len ? msg : NULL;
1701 if (!pgm &&
1702 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1703 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1704 /* a filepair that changes between file and symlink
1705 * needs to be split into deletion and creation.
1707 struct diff_filespec *null = alloc_filespec(two->path);
1708 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1709 free(null);
1710 null = alloc_filespec(one->path);
1711 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1712 free(null);
1714 else
1715 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1716 complete_rewrite);
1718 free(name_munged);
1719 free(other_munged);
1722 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1723 struct diffstat_t *diffstat)
1725 const char *name;
1726 const char *other;
1727 int complete_rewrite = 0;
1729 if (DIFF_PAIR_UNMERGED(p)) {
1730 /* unmerged */
1731 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1732 return;
1735 name = p->one->path;
1736 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1738 diff_fill_sha1_info(p->one);
1739 diff_fill_sha1_info(p->two);
1741 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1742 complete_rewrite = 1;
1743 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1746 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1748 const char *name;
1749 const char *other;
1751 if (DIFF_PAIR_UNMERGED(p)) {
1752 /* unmerged */
1753 return;
1756 name = p->one->path;
1757 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1759 diff_fill_sha1_info(p->one);
1760 diff_fill_sha1_info(p->two);
1762 builtin_checkdiff(name, other, p->one, p->two);
1765 void diff_setup(struct diff_options *options)
1767 memset(options, 0, sizeof(*options));
1768 options->line_termination = '\n';
1769 options->break_opt = -1;
1770 options->rename_limit = -1;
1771 options->context = 3;
1772 options->msg_sep = "";
1774 options->change = diff_change;
1775 options->add_remove = diff_addremove;
1776 options->color_diff = diff_use_color_default;
1777 options->detect_rename = diff_detect_rename_default;
1780 int diff_setup_done(struct diff_options *options)
1782 int count = 0;
1784 if (options->output_format & DIFF_FORMAT_NAME)
1785 count++;
1786 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
1787 count++;
1788 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
1789 count++;
1790 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
1791 count++;
1792 if (count > 1)
1793 die("--name-only, --name-status, --check and -s are mutually exclusive");
1795 if (options->find_copies_harder)
1796 options->detect_rename = DIFF_DETECT_COPY;
1798 if (options->output_format & (DIFF_FORMAT_NAME |
1799 DIFF_FORMAT_NAME_STATUS |
1800 DIFF_FORMAT_CHECKDIFF |
1801 DIFF_FORMAT_NO_OUTPUT))
1802 options->output_format &= ~(DIFF_FORMAT_RAW |
1803 DIFF_FORMAT_NUMSTAT |
1804 DIFF_FORMAT_DIFFSTAT |
1805 DIFF_FORMAT_SHORTSTAT |
1806 DIFF_FORMAT_SUMMARY |
1807 DIFF_FORMAT_PATCH);
1810 * These cases always need recursive; we do not drop caller-supplied
1811 * recursive bits for other formats here.
1813 if (options->output_format & (DIFF_FORMAT_PATCH |
1814 DIFF_FORMAT_NUMSTAT |
1815 DIFF_FORMAT_DIFFSTAT |
1816 DIFF_FORMAT_SHORTSTAT |
1817 DIFF_FORMAT_SUMMARY |
1818 DIFF_FORMAT_CHECKDIFF))
1819 options->recursive = 1;
1821 * Also pickaxe would not work very well if you do not say recursive
1823 if (options->pickaxe)
1824 options->recursive = 1;
1826 if (options->detect_rename && options->rename_limit < 0)
1827 options->rename_limit = diff_rename_limit_default;
1828 if (options->setup & DIFF_SETUP_USE_CACHE) {
1829 if (!active_cache)
1830 /* read-cache does not die even when it fails
1831 * so it is safe for us to do this here. Also
1832 * it does not smudge active_cache or active_nr
1833 * when it fails, so we do not have to worry about
1834 * cleaning it up ourselves either.
1836 read_cache();
1838 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1839 use_size_cache = 1;
1840 if (options->abbrev <= 0 || 40 < options->abbrev)
1841 options->abbrev = 40; /* full */
1843 return 0;
1846 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1848 char c, *eq;
1849 int len;
1851 if (*arg != '-')
1852 return 0;
1853 c = *++arg;
1854 if (!c)
1855 return 0;
1856 if (c == arg_short) {
1857 c = *++arg;
1858 if (!c)
1859 return 1;
1860 if (val && isdigit(c)) {
1861 char *end;
1862 int n = strtoul(arg, &end, 10);
1863 if (*end)
1864 return 0;
1865 *val = n;
1866 return 1;
1868 return 0;
1870 if (c != '-')
1871 return 0;
1872 arg++;
1873 eq = strchr(arg, '=');
1874 if (eq)
1875 len = eq - arg;
1876 else
1877 len = strlen(arg);
1878 if (!len || strncmp(arg, arg_long, len))
1879 return 0;
1880 if (eq) {
1881 int n;
1882 char *end;
1883 if (!isdigit(*++eq))
1884 return 0;
1885 n = strtoul(eq, &end, 10);
1886 if (*end)
1887 return 0;
1888 *val = n;
1890 return 1;
1893 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1895 const char *arg = av[0];
1896 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1897 options->output_format |= DIFF_FORMAT_PATCH;
1898 else if (opt_arg(arg, 'U', "unified", &options->context))
1899 options->output_format |= DIFF_FORMAT_PATCH;
1900 else if (!strcmp(arg, "--raw"))
1901 options->output_format |= DIFF_FORMAT_RAW;
1902 else if (!strcmp(arg, "--patch-with-raw")) {
1903 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
1905 else if (!strcmp(arg, "--numstat")) {
1906 options->output_format |= DIFF_FORMAT_NUMSTAT;
1908 else if (!strcmp(arg, "--shortstat")) {
1909 options->output_format |= DIFF_FORMAT_SHORTSTAT;
1911 else if (!strncmp(arg, "--stat", 6)) {
1912 char *end;
1913 int width = options->stat_width;
1914 int name_width = options->stat_name_width;
1915 arg += 6;
1916 end = (char *)arg;
1918 switch (*arg) {
1919 case '-':
1920 if (!strncmp(arg, "-width=", 7))
1921 width = strtoul(arg + 7, &end, 10);
1922 else if (!strncmp(arg, "-name-width=", 12))
1923 name_width = strtoul(arg + 12, &end, 10);
1924 break;
1925 case '=':
1926 width = strtoul(arg+1, &end, 10);
1927 if (*end == ',')
1928 name_width = strtoul(end+1, &end, 10);
1931 /* Important! This checks all the error cases! */
1932 if (*end)
1933 return 0;
1934 options->output_format |= DIFF_FORMAT_DIFFSTAT;
1935 options->stat_name_width = name_width;
1936 options->stat_width = width;
1938 else if (!strcmp(arg, "--check"))
1939 options->output_format |= DIFF_FORMAT_CHECKDIFF;
1940 else if (!strcmp(arg, "--summary"))
1941 options->output_format |= DIFF_FORMAT_SUMMARY;
1942 else if (!strcmp(arg, "--patch-with-stat")) {
1943 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
1945 else if (!strcmp(arg, "-z"))
1946 options->line_termination = 0;
1947 else if (!strncmp(arg, "-l", 2))
1948 options->rename_limit = strtoul(arg+2, NULL, 10);
1949 else if (!strcmp(arg, "--full-index"))
1950 options->full_index = 1;
1951 else if (!strcmp(arg, "--binary")) {
1952 options->output_format |= DIFF_FORMAT_PATCH;
1953 options->binary = 1;
1955 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
1956 options->text = 1;
1958 else if (!strcmp(arg, "--name-only"))
1959 options->output_format |= DIFF_FORMAT_NAME;
1960 else if (!strcmp(arg, "--name-status"))
1961 options->output_format |= DIFF_FORMAT_NAME_STATUS;
1962 else if (!strcmp(arg, "-R"))
1963 options->reverse_diff = 1;
1964 else if (!strncmp(arg, "-S", 2))
1965 options->pickaxe = arg + 2;
1966 else if (!strcmp(arg, "-s")) {
1967 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
1969 else if (!strncmp(arg, "-O", 2))
1970 options->orderfile = arg + 2;
1971 else if (!strncmp(arg, "--diff-filter=", 14))
1972 options->filter = arg + 14;
1973 else if (!strcmp(arg, "--pickaxe-all"))
1974 options->pickaxe_opts = DIFF_PICKAXE_ALL;
1975 else if (!strcmp(arg, "--pickaxe-regex"))
1976 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
1977 else if (!strncmp(arg, "-B", 2)) {
1978 if ((options->break_opt =
1979 diff_scoreopt_parse(arg)) == -1)
1980 return -1;
1982 else if (!strncmp(arg, "-M", 2)) {
1983 if ((options->rename_score =
1984 diff_scoreopt_parse(arg)) == -1)
1985 return -1;
1986 options->detect_rename = DIFF_DETECT_RENAME;
1988 else if (!strncmp(arg, "-C", 2)) {
1989 if ((options->rename_score =
1990 diff_scoreopt_parse(arg)) == -1)
1991 return -1;
1992 options->detect_rename = DIFF_DETECT_COPY;
1994 else if (!strcmp(arg, "--find-copies-harder"))
1995 options->find_copies_harder = 1;
1996 else if (!strcmp(arg, "--abbrev"))
1997 options->abbrev = DEFAULT_ABBREV;
1998 else if (!strncmp(arg, "--abbrev=", 9)) {
1999 options->abbrev = strtoul(arg + 9, NULL, 10);
2000 if (options->abbrev < MINIMUM_ABBREV)
2001 options->abbrev = MINIMUM_ABBREV;
2002 else if (40 < options->abbrev)
2003 options->abbrev = 40;
2005 else if (!strcmp(arg, "--color"))
2006 options->color_diff = 1;
2007 else if (!strcmp(arg, "--no-color"))
2008 options->color_diff = 0;
2009 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2010 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2011 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2012 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2013 else if (!strcmp(arg, "--color-words"))
2014 options->color_diff = options->color_diff_words = 1;
2015 else if (!strcmp(arg, "--no-renames"))
2016 options->detect_rename = 0;
2017 else
2018 return 0;
2019 return 1;
2022 static int parse_num(const char **cp_p)
2024 unsigned long num, scale;
2025 int ch, dot;
2026 const char *cp = *cp_p;
2028 num = 0;
2029 scale = 1;
2030 dot = 0;
2031 for(;;) {
2032 ch = *cp;
2033 if ( !dot && ch == '.' ) {
2034 scale = 1;
2035 dot = 1;
2036 } else if ( ch == '%' ) {
2037 scale = dot ? scale*100 : 100;
2038 cp++; /* % is always at the end */
2039 break;
2040 } else if ( ch >= '0' && ch <= '9' ) {
2041 if ( scale < 100000 ) {
2042 scale *= 10;
2043 num = (num*10) + (ch-'0');
2045 } else {
2046 break;
2048 cp++;
2050 *cp_p = cp;
2052 /* user says num divided by scale and we say internally that
2053 * is MAX_SCORE * num / scale.
2055 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
2058 int diff_scoreopt_parse(const char *opt)
2060 int opt1, opt2, cmd;
2062 if (*opt++ != '-')
2063 return -1;
2064 cmd = *opt++;
2065 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2066 return -1; /* that is not a -M, -C nor -B option */
2068 opt1 = parse_num(&opt);
2069 if (cmd != 'B')
2070 opt2 = 0;
2071 else {
2072 if (*opt == 0)
2073 opt2 = 0;
2074 else if (*opt != '/')
2075 return -1; /* we expect -B80/99 or -B80 */
2076 else {
2077 opt++;
2078 opt2 = parse_num(&opt);
2081 if (*opt != 0)
2082 return -1;
2083 return opt1 | (opt2 << 16);
2086 struct diff_queue_struct diff_queued_diff;
2088 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2090 if (queue->alloc <= queue->nr) {
2091 queue->alloc = alloc_nr(queue->alloc);
2092 queue->queue = xrealloc(queue->queue,
2093 sizeof(dp) * queue->alloc);
2095 queue->queue[queue->nr++] = dp;
2098 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2099 struct diff_filespec *one,
2100 struct diff_filespec *two)
2102 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2103 dp->one = one;
2104 dp->two = two;
2105 if (queue)
2106 diff_q(queue, dp);
2107 return dp;
2110 void diff_free_filepair(struct diff_filepair *p)
2112 diff_free_filespec_data(p->one);
2113 diff_free_filespec_data(p->two);
2114 free(p->one);
2115 free(p->two);
2116 free(p);
2119 /* This is different from find_unique_abbrev() in that
2120 * it stuffs the result with dots for alignment.
2122 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2124 int abblen;
2125 const char *abbrev;
2126 if (len == 40)
2127 return sha1_to_hex(sha1);
2129 abbrev = find_unique_abbrev(sha1, len);
2130 if (!abbrev)
2131 return sha1_to_hex(sha1);
2132 abblen = strlen(abbrev);
2133 if (abblen < 37) {
2134 static char hex[41];
2135 if (len < abblen && abblen <= len + 2)
2136 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2137 else
2138 sprintf(hex, "%s...", abbrev);
2139 return hex;
2141 return sha1_to_hex(sha1);
2144 static void diff_flush_raw(struct diff_filepair *p,
2145 struct diff_options *options)
2147 int two_paths;
2148 char status[10];
2149 int abbrev = options->abbrev;
2150 const char *path_one, *path_two;
2151 int inter_name_termination = '\t';
2152 int line_termination = options->line_termination;
2154 if (!line_termination)
2155 inter_name_termination = 0;
2157 path_one = p->one->path;
2158 path_two = p->two->path;
2159 if (line_termination) {
2160 path_one = quote_one(path_one);
2161 path_two = quote_one(path_two);
2164 if (p->score)
2165 sprintf(status, "%c%03d", p->status,
2166 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2167 else {
2168 status[0] = p->status;
2169 status[1] = 0;
2171 switch (p->status) {
2172 case DIFF_STATUS_COPIED:
2173 case DIFF_STATUS_RENAMED:
2174 two_paths = 1;
2175 break;
2176 case DIFF_STATUS_ADDED:
2177 case DIFF_STATUS_DELETED:
2178 two_paths = 0;
2179 break;
2180 default:
2181 two_paths = 0;
2182 break;
2184 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2185 printf(":%06o %06o %s ",
2186 p->one->mode, p->two->mode,
2187 diff_unique_abbrev(p->one->sha1, abbrev));
2188 printf("%s ",
2189 diff_unique_abbrev(p->two->sha1, abbrev));
2191 printf("%s%c%s", status, inter_name_termination, path_one);
2192 if (two_paths)
2193 printf("%c%s", inter_name_termination, path_two);
2194 putchar(line_termination);
2195 if (path_one != p->one->path)
2196 free((void*)path_one);
2197 if (path_two != p->two->path)
2198 free((void*)path_two);
2201 static void diff_flush_name(struct diff_filepair *p, int line_termination)
2203 char *path = p->two->path;
2205 if (line_termination)
2206 path = quote_one(p->two->path);
2207 printf("%s%c", path, line_termination);
2208 if (p->two->path != path)
2209 free(path);
2212 int diff_unmodified_pair(struct diff_filepair *p)
2214 /* This function is written stricter than necessary to support
2215 * the currently implemented transformers, but the idea is to
2216 * let transformers to produce diff_filepairs any way they want,
2217 * and filter and clean them up here before producing the output.
2219 struct diff_filespec *one, *two;
2221 if (DIFF_PAIR_UNMERGED(p))
2222 return 0; /* unmerged is interesting */
2224 one = p->one;
2225 two = p->two;
2227 /* deletion, addition, mode or type change
2228 * and rename are all interesting.
2230 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2231 DIFF_PAIR_MODE_CHANGED(p) ||
2232 strcmp(one->path, two->path))
2233 return 0;
2235 /* both are valid and point at the same path. that is, we are
2236 * dealing with a change.
2238 if (one->sha1_valid && two->sha1_valid &&
2239 !hashcmp(one->sha1, two->sha1))
2240 return 1; /* no change */
2241 if (!one->sha1_valid && !two->sha1_valid)
2242 return 1; /* both look at the same file on the filesystem. */
2243 return 0;
2246 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2248 if (diff_unmodified_pair(p))
2249 return;
2251 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2252 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2253 return; /* no tree diffs in patch format */
2255 run_diff(p, o);
2258 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2259 struct diffstat_t *diffstat)
2261 if (diff_unmodified_pair(p))
2262 return;
2264 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2265 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2266 return; /* no tree diffs in patch format */
2268 run_diffstat(p, o, diffstat);
2271 static void diff_flush_checkdiff(struct diff_filepair *p,
2272 struct diff_options *o)
2274 if (diff_unmodified_pair(p))
2275 return;
2277 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2278 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2279 return; /* no tree diffs in patch format */
2281 run_checkdiff(p, o);
2284 int diff_queue_is_empty(void)
2286 struct diff_queue_struct *q = &diff_queued_diff;
2287 int i;
2288 for (i = 0; i < q->nr; i++)
2289 if (!diff_unmodified_pair(q->queue[i]))
2290 return 0;
2291 return 1;
2294 #if DIFF_DEBUG
2295 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2297 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2298 x, one ? one : "",
2299 s->path,
2300 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2301 s->mode,
2302 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2303 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2304 x, one ? one : "",
2305 s->size, s->xfrm_flags);
2308 void diff_debug_filepair(const struct diff_filepair *p, int i)
2310 diff_debug_filespec(p->one, i, "one");
2311 diff_debug_filespec(p->two, i, "two");
2312 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2313 p->score, p->status ? p->status : '?',
2314 p->source_stays, p->broken_pair);
2317 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2319 int i;
2320 if (msg)
2321 fprintf(stderr, "%s\n", msg);
2322 fprintf(stderr, "q->nr = %d\n", q->nr);
2323 for (i = 0; i < q->nr; i++) {
2324 struct diff_filepair *p = q->queue[i];
2325 diff_debug_filepair(p, i);
2328 #endif
2330 static void diff_resolve_rename_copy(void)
2332 int i, j;
2333 struct diff_filepair *p, *pp;
2334 struct diff_queue_struct *q = &diff_queued_diff;
2336 diff_debug_queue("resolve-rename-copy", q);
2338 for (i = 0; i < q->nr; i++) {
2339 p = q->queue[i];
2340 p->status = 0; /* undecided */
2341 if (DIFF_PAIR_UNMERGED(p))
2342 p->status = DIFF_STATUS_UNMERGED;
2343 else if (!DIFF_FILE_VALID(p->one))
2344 p->status = DIFF_STATUS_ADDED;
2345 else if (!DIFF_FILE_VALID(p->two))
2346 p->status = DIFF_STATUS_DELETED;
2347 else if (DIFF_PAIR_TYPE_CHANGED(p))
2348 p->status = DIFF_STATUS_TYPE_CHANGED;
2350 /* from this point on, we are dealing with a pair
2351 * whose both sides are valid and of the same type, i.e.
2352 * either in-place edit or rename/copy edit.
2354 else if (DIFF_PAIR_RENAME(p)) {
2355 if (p->source_stays) {
2356 p->status = DIFF_STATUS_COPIED;
2357 continue;
2359 /* See if there is some other filepair that
2360 * copies from the same source as us. If so
2361 * we are a copy. Otherwise we are either a
2362 * copy if the path stays, or a rename if it
2363 * does not, but we already handled "stays" case.
2365 for (j = i + 1; j < q->nr; j++) {
2366 pp = q->queue[j];
2367 if (strcmp(pp->one->path, p->one->path))
2368 continue; /* not us */
2369 if (!DIFF_PAIR_RENAME(pp))
2370 continue; /* not a rename/copy */
2371 /* pp is a rename/copy from the same source */
2372 p->status = DIFF_STATUS_COPIED;
2373 break;
2375 if (!p->status)
2376 p->status = DIFF_STATUS_RENAMED;
2378 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2379 p->one->mode != p->two->mode)
2380 p->status = DIFF_STATUS_MODIFIED;
2381 else {
2382 /* This is a "no-change" entry and should not
2383 * happen anymore, but prepare for broken callers.
2385 error("feeding unmodified %s to diffcore",
2386 p->one->path);
2387 p->status = DIFF_STATUS_UNKNOWN;
2390 diff_debug_queue("resolve-rename-copy done", q);
2393 static int check_pair_status(struct diff_filepair *p)
2395 switch (p->status) {
2396 case DIFF_STATUS_UNKNOWN:
2397 return 0;
2398 case 0:
2399 die("internal error in diff-resolve-rename-copy");
2400 default:
2401 return 1;
2405 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2407 int fmt = opt->output_format;
2409 if (fmt & DIFF_FORMAT_CHECKDIFF)
2410 diff_flush_checkdiff(p, opt);
2411 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2412 diff_flush_raw(p, opt);
2413 else if (fmt & DIFF_FORMAT_NAME)
2414 diff_flush_name(p, opt->line_termination);
2417 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2419 if (fs->mode)
2420 printf(" %s mode %06o %s\n", newdelete, fs->mode, fs->path);
2421 else
2422 printf(" %s %s\n", newdelete, fs->path);
2426 static void show_mode_change(struct diff_filepair *p, int show_name)
2428 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2429 if (show_name)
2430 printf(" mode change %06o => %06o %s\n",
2431 p->one->mode, p->two->mode, p->two->path);
2432 else
2433 printf(" mode change %06o => %06o\n",
2434 p->one->mode, p->two->mode);
2438 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2440 const char *old, *new;
2442 /* Find common prefix */
2443 old = p->one->path;
2444 new = p->two->path;
2445 while (1) {
2446 const char *slash_old, *slash_new;
2447 slash_old = strchr(old, '/');
2448 slash_new = strchr(new, '/');
2449 if (!slash_old ||
2450 !slash_new ||
2451 slash_old - old != slash_new - new ||
2452 memcmp(old, new, slash_new - new))
2453 break;
2454 old = slash_old + 1;
2455 new = slash_new + 1;
2457 /* p->one->path thru old is the common prefix, and old and new
2458 * through the end of names are renames
2460 if (old != p->one->path)
2461 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2462 (int)(old - p->one->path), p->one->path,
2463 old, new, (int)(0.5 + p->score * 100.0/MAX_SCORE));
2464 else
2465 printf(" %s %s => %s (%d%%)\n", renamecopy,
2466 p->one->path, p->two->path,
2467 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2468 show_mode_change(p, 0);
2471 static void diff_summary(struct diff_filepair *p)
2473 switch(p->status) {
2474 case DIFF_STATUS_DELETED:
2475 show_file_mode_name("delete", p->one);
2476 break;
2477 case DIFF_STATUS_ADDED:
2478 show_file_mode_name("create", p->two);
2479 break;
2480 case DIFF_STATUS_COPIED:
2481 show_rename_copy("copy", p);
2482 break;
2483 case DIFF_STATUS_RENAMED:
2484 show_rename_copy("rename", p);
2485 break;
2486 default:
2487 if (p->score) {
2488 printf(" rewrite %s (%d%%)\n", p->two->path,
2489 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2490 show_mode_change(p, 0);
2491 } else show_mode_change(p, 1);
2492 break;
2496 struct patch_id_t {
2497 struct xdiff_emit_state xm;
2498 SHA_CTX *ctx;
2499 int patchlen;
2502 static int remove_space(char *line, int len)
2504 int i;
2505 char *dst = line;
2506 unsigned char c;
2508 for (i = 0; i < len; i++)
2509 if (!isspace((c = line[i])))
2510 *dst++ = c;
2512 return dst - line;
2515 static void patch_id_consume(void *priv, char *line, unsigned long len)
2517 struct patch_id_t *data = priv;
2518 int new_len;
2520 /* Ignore line numbers when computing the SHA1 of the patch */
2521 if (!strncmp(line, "@@ -", 4))
2522 return;
2524 new_len = remove_space(line, len);
2526 SHA1_Update(data->ctx, line, new_len);
2527 data->patchlen += new_len;
2530 /* returns 0 upon success, and writes result into sha1 */
2531 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2533 struct diff_queue_struct *q = &diff_queued_diff;
2534 int i;
2535 SHA_CTX ctx;
2536 struct patch_id_t data;
2537 char buffer[PATH_MAX * 4 + 20];
2539 SHA1_Init(&ctx);
2540 memset(&data, 0, sizeof(struct patch_id_t));
2541 data.ctx = &ctx;
2542 data.xm.consume = patch_id_consume;
2544 for (i = 0; i < q->nr; i++) {
2545 xpparam_t xpp;
2546 xdemitconf_t xecfg;
2547 xdemitcb_t ecb;
2548 mmfile_t mf1, mf2;
2549 struct diff_filepair *p = q->queue[i];
2550 int len1, len2;
2552 if (p->status == 0)
2553 return error("internal diff status error");
2554 if (p->status == DIFF_STATUS_UNKNOWN)
2555 continue;
2556 if (diff_unmodified_pair(p))
2557 continue;
2558 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2559 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2560 continue;
2561 if (DIFF_PAIR_UNMERGED(p))
2562 continue;
2564 diff_fill_sha1_info(p->one);
2565 diff_fill_sha1_info(p->two);
2566 if (fill_mmfile(&mf1, p->one) < 0 ||
2567 fill_mmfile(&mf2, p->two) < 0)
2568 return error("unable to read files to diff");
2570 /* Maybe hash p->two? into the patch id? */
2571 if (mmfile_is_binary(&mf2))
2572 continue;
2574 len1 = remove_space(p->one->path, strlen(p->one->path));
2575 len2 = remove_space(p->two->path, strlen(p->two->path));
2576 if (p->one->mode == 0)
2577 len1 = snprintf(buffer, sizeof(buffer),
2578 "diff--gita/%.*sb/%.*s"
2579 "newfilemode%06o"
2580 "---/dev/null"
2581 "+++b/%.*s",
2582 len1, p->one->path,
2583 len2, p->two->path,
2584 p->two->mode,
2585 len2, p->two->path);
2586 else if (p->two->mode == 0)
2587 len1 = snprintf(buffer, sizeof(buffer),
2588 "diff--gita/%.*sb/%.*s"
2589 "deletedfilemode%06o"
2590 "---a/%.*s"
2591 "+++/dev/null",
2592 len1, p->one->path,
2593 len2, p->two->path,
2594 p->one->mode,
2595 len1, p->one->path);
2596 else
2597 len1 = snprintf(buffer, sizeof(buffer),
2598 "diff--gita/%.*sb/%.*s"
2599 "---a/%.*s"
2600 "+++b/%.*s",
2601 len1, p->one->path,
2602 len2, p->two->path,
2603 len1, p->one->path,
2604 len2, p->two->path);
2605 SHA1_Update(&ctx, buffer, len1);
2607 xpp.flags = XDF_NEED_MINIMAL;
2608 xecfg.ctxlen = 3;
2609 xecfg.flags = XDL_EMIT_FUNCNAMES;
2610 ecb.outf = xdiff_outf;
2611 ecb.priv = &data;
2612 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2615 SHA1_Final(sha1, &ctx);
2616 return 0;
2619 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2621 struct diff_queue_struct *q = &diff_queued_diff;
2622 int i;
2623 int result = diff_get_patch_id(options, sha1);
2625 for (i = 0; i < q->nr; i++)
2626 diff_free_filepair(q->queue[i]);
2628 free(q->queue);
2629 q->queue = NULL;
2630 q->nr = q->alloc = 0;
2632 return result;
2635 static int is_summary_empty(const struct diff_queue_struct *q)
2637 int i;
2639 for (i = 0; i < q->nr; i++) {
2640 const struct diff_filepair *p = q->queue[i];
2642 switch (p->status) {
2643 case DIFF_STATUS_DELETED:
2644 case DIFF_STATUS_ADDED:
2645 case DIFF_STATUS_COPIED:
2646 case DIFF_STATUS_RENAMED:
2647 return 0;
2648 default:
2649 if (p->score)
2650 return 0;
2651 if (p->one->mode && p->two->mode &&
2652 p->one->mode != p->two->mode)
2653 return 0;
2654 break;
2657 return 1;
2660 void diff_flush(struct diff_options *options)
2662 struct diff_queue_struct *q = &diff_queued_diff;
2663 int i, output_format = options->output_format;
2664 int separator = 0;
2667 * Order: raw, stat, summary, patch
2668 * or: name/name-status/checkdiff (other bits clear)
2670 if (!q->nr)
2671 goto free_queue;
2673 if (output_format & (DIFF_FORMAT_RAW |
2674 DIFF_FORMAT_NAME |
2675 DIFF_FORMAT_NAME_STATUS |
2676 DIFF_FORMAT_CHECKDIFF)) {
2677 for (i = 0; i < q->nr; i++) {
2678 struct diff_filepair *p = q->queue[i];
2679 if (check_pair_status(p))
2680 flush_one_pair(p, options);
2682 separator++;
2685 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
2686 struct diffstat_t diffstat;
2688 memset(&diffstat, 0, sizeof(struct diffstat_t));
2689 diffstat.xm.consume = diffstat_consume;
2690 for (i = 0; i < q->nr; i++) {
2691 struct diff_filepair *p = q->queue[i];
2692 if (check_pair_status(p))
2693 diff_flush_stat(p, options, &diffstat);
2695 if (output_format & DIFF_FORMAT_NUMSTAT)
2696 show_numstat(&diffstat, options);
2697 if (output_format & DIFF_FORMAT_DIFFSTAT)
2698 show_stats(&diffstat, options);
2699 else if (output_format & DIFF_FORMAT_SHORTSTAT)
2700 show_shortstats(&diffstat);
2701 separator++;
2704 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2705 for (i = 0; i < q->nr; i++)
2706 diff_summary(q->queue[i]);
2707 separator++;
2710 if (output_format & DIFF_FORMAT_PATCH) {
2711 if (separator) {
2712 if (options->stat_sep) {
2713 /* attach patch instead of inline */
2714 fputs(options->stat_sep, stdout);
2715 } else {
2716 putchar(options->line_termination);
2720 for (i = 0; i < q->nr; i++) {
2721 struct diff_filepair *p = q->queue[i];
2722 if (check_pair_status(p))
2723 diff_flush_patch(p, options);
2727 if (output_format & DIFF_FORMAT_CALLBACK)
2728 options->format_callback(q, options, options->format_callback_data);
2730 for (i = 0; i < q->nr; i++)
2731 diff_free_filepair(q->queue[i]);
2732 free_queue:
2733 free(q->queue);
2734 q->queue = NULL;
2735 q->nr = q->alloc = 0;
2738 static void diffcore_apply_filter(const char *filter)
2740 int i;
2741 struct diff_queue_struct *q = &diff_queued_diff;
2742 struct diff_queue_struct outq;
2743 outq.queue = NULL;
2744 outq.nr = outq.alloc = 0;
2746 if (!filter)
2747 return;
2749 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2750 int found;
2751 for (i = found = 0; !found && i < q->nr; i++) {
2752 struct diff_filepair *p = q->queue[i];
2753 if (((p->status == DIFF_STATUS_MODIFIED) &&
2754 ((p->score &&
2755 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2756 (!p->score &&
2757 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2758 ((p->status != DIFF_STATUS_MODIFIED) &&
2759 strchr(filter, p->status)))
2760 found++;
2762 if (found)
2763 return;
2765 /* otherwise we will clear the whole queue
2766 * by copying the empty outq at the end of this
2767 * function, but first clear the current entries
2768 * in the queue.
2770 for (i = 0; i < q->nr; i++)
2771 diff_free_filepair(q->queue[i]);
2773 else {
2774 /* Only the matching ones */
2775 for (i = 0; i < q->nr; i++) {
2776 struct diff_filepair *p = q->queue[i];
2778 if (((p->status == DIFF_STATUS_MODIFIED) &&
2779 ((p->score &&
2780 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2781 (!p->score &&
2782 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2783 ((p->status != DIFF_STATUS_MODIFIED) &&
2784 strchr(filter, p->status)))
2785 diff_q(&outq, p);
2786 else
2787 diff_free_filepair(p);
2790 free(q->queue);
2791 *q = outq;
2794 void diffcore_std(struct diff_options *options)
2796 if (options->break_opt != -1)
2797 diffcore_break(options->break_opt);
2798 if (options->detect_rename)
2799 diffcore_rename(options);
2800 if (options->break_opt != -1)
2801 diffcore_merge_broken();
2802 if (options->pickaxe)
2803 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2804 if (options->orderfile)
2805 diffcore_order(options->orderfile);
2806 diff_resolve_rename_copy();
2807 diffcore_apply_filter(options->filter);
2811 void diffcore_std_no_resolve(struct diff_options *options)
2813 if (options->pickaxe)
2814 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2815 if (options->orderfile)
2816 diffcore_order(options->orderfile);
2817 diffcore_apply_filter(options->filter);
2820 void diff_addremove(struct diff_options *options,
2821 int addremove, unsigned mode,
2822 const unsigned char *sha1,
2823 const char *base, const char *path)
2825 char concatpath[PATH_MAX];
2826 struct diff_filespec *one, *two;
2828 /* This may look odd, but it is a preparation for
2829 * feeding "there are unchanged files which should
2830 * not produce diffs, but when you are doing copy
2831 * detection you would need them, so here they are"
2832 * entries to the diff-core. They will be prefixed
2833 * with something like '=' or '*' (I haven't decided
2834 * which but should not make any difference).
2835 * Feeding the same new and old to diff_change()
2836 * also has the same effect.
2837 * Before the final output happens, they are pruned after
2838 * merged into rename/copy pairs as appropriate.
2840 if (options->reverse_diff)
2841 addremove = (addremove == '+' ? '-' :
2842 addremove == '-' ? '+' : addremove);
2844 if (!path) path = "";
2845 sprintf(concatpath, "%s%s", base, path);
2846 one = alloc_filespec(concatpath);
2847 two = alloc_filespec(concatpath);
2849 if (addremove != '+')
2850 fill_filespec(one, sha1, mode);
2851 if (addremove != '-')
2852 fill_filespec(two, sha1, mode);
2854 diff_queue(&diff_queued_diff, one, two);
2857 void diff_change(struct diff_options *options,
2858 unsigned old_mode, unsigned new_mode,
2859 const unsigned char *old_sha1,
2860 const unsigned char *new_sha1,
2861 const char *base, const char *path)
2863 char concatpath[PATH_MAX];
2864 struct diff_filespec *one, *two;
2866 if (options->reverse_diff) {
2867 unsigned tmp;
2868 const unsigned char *tmp_c;
2869 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2870 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2872 if (!path) path = "";
2873 sprintf(concatpath, "%s%s", base, path);
2874 one = alloc_filespec(concatpath);
2875 two = alloc_filespec(concatpath);
2876 fill_filespec(one, old_sha1, old_mode);
2877 fill_filespec(two, new_sha1, new_mode);
2879 diff_queue(&diff_queued_diff, one, two);
2882 void diff_unmerge(struct diff_options *options,
2883 const char *path,
2884 unsigned mode, const unsigned char *sha1)
2886 struct diff_filespec *one, *two;
2887 one = alloc_filespec(path);
2888 two = alloc_filespec(path);
2889 fill_filespec(one, sha1, mode);
2890 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;