MinGW: Make git native protocol work.
[git/mingw.git] / diff.c
blob224d3692881066f9cd80064142462955b134d5cd
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);
1503 if (pid < 0)
1504 die("unable to fork");
1506 while (waitpid(pid, &status, 0) < 0) {
1507 if (errno == EINTR)
1508 continue;
1509 return -1;
1512 /* Earlier we did not check the exit status because
1513 * diff exits non-zero if files are different, and
1514 * we are not interested in knowing that. It was a
1515 * mistake which made it harder to quit a diff-*
1516 * session that uses the git-apply-patch-script as
1517 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1518 * should also exit non-zero only when it wants to
1519 * abort the entire diff-* session.
1521 if (WIFEXITED(status) && !WEXITSTATUS(status))
1522 return 0;
1523 return -1;
1526 /* An external diff command takes:
1528 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1529 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1532 static void run_external_diff(const char *pgm,
1533 const char *name,
1534 const char *other,
1535 struct diff_filespec *one,
1536 struct diff_filespec *two,
1537 const char *xfrm_msg,
1538 int complete_rewrite)
1540 const char *spawn_arg[10];
1541 struct diff_tempfile *temp = diff_temp;
1542 int retval;
1543 static int atexit_asked = 0;
1544 const char *othername;
1545 const char **arg = &spawn_arg[1];
1547 othername = (other? other : name);
1548 if (one && two) {
1549 prepare_temp_file(name, &temp[0], one);
1550 prepare_temp_file(othername, &temp[1], two);
1551 if (! atexit_asked &&
1552 (temp[0].name == temp[0].tmp_path ||
1553 temp[1].name == temp[1].tmp_path)) {
1554 atexit_asked = 1;
1555 atexit(remove_tempfile);
1557 signal(SIGINT, remove_tempfile_on_signal);
1560 if (one && two) {
1561 *arg++ = name;
1562 *arg++ = temp[0].name;
1563 *arg++ = temp[0].hex;
1564 *arg++ = temp[0].mode;
1565 *arg++ = temp[1].name;
1566 *arg++ = temp[1].hex;
1567 *arg++ = temp[1].mode;
1568 if (other) {
1569 *arg++ = other;
1570 *arg++ = xfrm_msg;
1572 } else {
1573 *arg++ = name;
1575 *arg = NULL;
1576 retval = spawn_prog(pgm, spawn_arg);
1577 remove_tempfile();
1578 if (retval) {
1579 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1580 exit(1);
1584 static void run_diff_cmd(const char *pgm,
1585 const char *name,
1586 const char *other,
1587 struct diff_filespec *one,
1588 struct diff_filespec *two,
1589 const char *xfrm_msg,
1590 struct diff_options *o,
1591 int complete_rewrite)
1593 if (pgm) {
1594 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1595 complete_rewrite);
1596 return;
1598 if (one && two)
1599 builtin_diff(name, other ? other : name,
1600 one, two, xfrm_msg, o, complete_rewrite);
1601 else
1602 printf("* Unmerged path %s\n", name);
1605 static void diff_fill_sha1_info(struct diff_filespec *one)
1607 if (DIFF_FILE_VALID(one)) {
1608 if (!one->sha1_valid) {
1609 struct stat st;
1610 if (lstat(one->path, &st) < 0)
1611 die("stat %s", one->path);
1612 if (index_path(one->sha1, one->path, &st, 0))
1613 die("cannot hash %s\n", one->path);
1616 else
1617 hashclr(one->sha1);
1620 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1622 const char *pgm = external_diff();
1623 char msg[PATH_MAX*2+300], *xfrm_msg;
1624 struct diff_filespec *one;
1625 struct diff_filespec *two;
1626 const char *name;
1627 const char *other;
1628 char *name_munged, *other_munged;
1629 int complete_rewrite = 0;
1630 int len;
1632 if (DIFF_PAIR_UNMERGED(p)) {
1633 /* unmerged */
1634 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1635 return;
1638 name = p->one->path;
1639 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1640 name_munged = quote_one(name);
1641 other_munged = quote_one(other);
1642 one = p->one; two = p->two;
1644 diff_fill_sha1_info(one);
1645 diff_fill_sha1_info(two);
1647 len = 0;
1648 switch (p->status) {
1649 case DIFF_STATUS_COPIED:
1650 len += snprintf(msg + len, sizeof(msg) - len,
1651 "similarity index %d%%\n"
1652 "copy from %s\n"
1653 "copy to %s\n",
1654 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1655 name_munged, other_munged);
1656 break;
1657 case DIFF_STATUS_RENAMED:
1658 len += snprintf(msg + len, sizeof(msg) - len,
1659 "similarity index %d%%\n"
1660 "rename from %s\n"
1661 "rename to %s\n",
1662 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1663 name_munged, other_munged);
1664 break;
1665 case DIFF_STATUS_MODIFIED:
1666 if (p->score) {
1667 len += snprintf(msg + len, sizeof(msg) - len,
1668 "dissimilarity index %d%%\n",
1669 (int)(0.5 + p->score *
1670 100.0/MAX_SCORE));
1671 complete_rewrite = 1;
1672 break;
1674 /* fallthru */
1675 default:
1676 /* nothing */
1680 if (hashcmp(one->sha1, two->sha1)) {
1681 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1683 if (o->binary) {
1684 mmfile_t mf;
1685 if ((!fill_mmfile(&mf, one) && mmfile_is_binary(&mf)) ||
1686 (!fill_mmfile(&mf, two) && mmfile_is_binary(&mf)))
1687 abbrev = 40;
1689 len += snprintf(msg + len, sizeof(msg) - len,
1690 "index %.*s..%.*s",
1691 abbrev, sha1_to_hex(one->sha1),
1692 abbrev, sha1_to_hex(two->sha1));
1693 if (one->mode == two->mode)
1694 len += snprintf(msg + len, sizeof(msg) - len,
1695 " %06o", one->mode);
1696 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1699 if (len)
1700 msg[--len] = 0;
1701 xfrm_msg = len ? msg : NULL;
1703 if (!pgm &&
1704 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1705 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1706 /* a filepair that changes between file and symlink
1707 * needs to be split into deletion and creation.
1709 struct diff_filespec *null = alloc_filespec(two->path);
1710 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1711 free(null);
1712 null = alloc_filespec(one->path);
1713 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1714 free(null);
1716 else
1717 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1718 complete_rewrite);
1720 free(name_munged);
1721 free(other_munged);
1724 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1725 struct diffstat_t *diffstat)
1727 const char *name;
1728 const char *other;
1729 int complete_rewrite = 0;
1731 if (DIFF_PAIR_UNMERGED(p)) {
1732 /* unmerged */
1733 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1734 return;
1737 name = p->one->path;
1738 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1740 diff_fill_sha1_info(p->one);
1741 diff_fill_sha1_info(p->two);
1743 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1744 complete_rewrite = 1;
1745 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1748 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1750 const char *name;
1751 const char *other;
1753 if (DIFF_PAIR_UNMERGED(p)) {
1754 /* unmerged */
1755 return;
1758 name = p->one->path;
1759 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1761 diff_fill_sha1_info(p->one);
1762 diff_fill_sha1_info(p->two);
1764 builtin_checkdiff(name, other, p->one, p->two);
1767 void diff_setup(struct diff_options *options)
1769 memset(options, 0, sizeof(*options));
1770 options->line_termination = '\n';
1771 options->break_opt = -1;
1772 options->rename_limit = -1;
1773 options->context = 3;
1774 options->msg_sep = "";
1776 options->change = diff_change;
1777 options->add_remove = diff_addremove;
1778 options->color_diff = diff_use_color_default;
1779 options->detect_rename = diff_detect_rename_default;
1782 int diff_setup_done(struct diff_options *options)
1784 int count = 0;
1786 if (options->output_format & DIFF_FORMAT_NAME)
1787 count++;
1788 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
1789 count++;
1790 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
1791 count++;
1792 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
1793 count++;
1794 if (count > 1)
1795 die("--name-only, --name-status, --check and -s are mutually exclusive");
1797 if (options->find_copies_harder)
1798 options->detect_rename = DIFF_DETECT_COPY;
1800 if (options->output_format & (DIFF_FORMAT_NAME |
1801 DIFF_FORMAT_NAME_STATUS |
1802 DIFF_FORMAT_CHECKDIFF |
1803 DIFF_FORMAT_NO_OUTPUT))
1804 options->output_format &= ~(DIFF_FORMAT_RAW |
1805 DIFF_FORMAT_NUMSTAT |
1806 DIFF_FORMAT_DIFFSTAT |
1807 DIFF_FORMAT_SHORTSTAT |
1808 DIFF_FORMAT_SUMMARY |
1809 DIFF_FORMAT_PATCH);
1812 * These cases always need recursive; we do not drop caller-supplied
1813 * recursive bits for other formats here.
1815 if (options->output_format & (DIFF_FORMAT_PATCH |
1816 DIFF_FORMAT_NUMSTAT |
1817 DIFF_FORMAT_DIFFSTAT |
1818 DIFF_FORMAT_SHORTSTAT |
1819 DIFF_FORMAT_SUMMARY |
1820 DIFF_FORMAT_CHECKDIFF))
1821 options->recursive = 1;
1823 * Also pickaxe would not work very well if you do not say recursive
1825 if (options->pickaxe)
1826 options->recursive = 1;
1828 if (options->detect_rename && options->rename_limit < 0)
1829 options->rename_limit = diff_rename_limit_default;
1830 if (options->setup & DIFF_SETUP_USE_CACHE) {
1831 if (!active_cache)
1832 /* read-cache does not die even when it fails
1833 * so it is safe for us to do this here. Also
1834 * it does not smudge active_cache or active_nr
1835 * when it fails, so we do not have to worry about
1836 * cleaning it up ourselves either.
1838 read_cache();
1840 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1841 use_size_cache = 1;
1842 if (options->abbrev <= 0 || 40 < options->abbrev)
1843 options->abbrev = 40; /* full */
1845 return 0;
1848 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1850 char c, *eq;
1851 int len;
1853 if (*arg != '-')
1854 return 0;
1855 c = *++arg;
1856 if (!c)
1857 return 0;
1858 if (c == arg_short) {
1859 c = *++arg;
1860 if (!c)
1861 return 1;
1862 if (val && isdigit(c)) {
1863 char *end;
1864 int n = strtoul(arg, &end, 10);
1865 if (*end)
1866 return 0;
1867 *val = n;
1868 return 1;
1870 return 0;
1872 if (c != '-')
1873 return 0;
1874 arg++;
1875 eq = strchr(arg, '=');
1876 if (eq)
1877 len = eq - arg;
1878 else
1879 len = strlen(arg);
1880 if (!len || strncmp(arg, arg_long, len))
1881 return 0;
1882 if (eq) {
1883 int n;
1884 char *end;
1885 if (!isdigit(*++eq))
1886 return 0;
1887 n = strtoul(eq, &end, 10);
1888 if (*end)
1889 return 0;
1890 *val = n;
1892 return 1;
1895 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1897 const char *arg = av[0];
1898 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1899 options->output_format |= DIFF_FORMAT_PATCH;
1900 else if (opt_arg(arg, 'U', "unified", &options->context))
1901 options->output_format |= DIFF_FORMAT_PATCH;
1902 else if (!strcmp(arg, "--raw"))
1903 options->output_format |= DIFF_FORMAT_RAW;
1904 else if (!strcmp(arg, "--patch-with-raw")) {
1905 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
1907 else if (!strcmp(arg, "--numstat")) {
1908 options->output_format |= DIFF_FORMAT_NUMSTAT;
1910 else if (!strcmp(arg, "--shortstat")) {
1911 options->output_format |= DIFF_FORMAT_SHORTSTAT;
1913 else if (!strncmp(arg, "--stat", 6)) {
1914 char *end;
1915 int width = options->stat_width;
1916 int name_width = options->stat_name_width;
1917 arg += 6;
1918 end = (char *)arg;
1920 switch (*arg) {
1921 case '-':
1922 if (!strncmp(arg, "-width=", 7))
1923 width = strtoul(arg + 7, &end, 10);
1924 else if (!strncmp(arg, "-name-width=", 12))
1925 name_width = strtoul(arg + 12, &end, 10);
1926 break;
1927 case '=':
1928 width = strtoul(arg+1, &end, 10);
1929 if (*end == ',')
1930 name_width = strtoul(end+1, &end, 10);
1933 /* Important! This checks all the error cases! */
1934 if (*end)
1935 return 0;
1936 options->output_format |= DIFF_FORMAT_DIFFSTAT;
1937 options->stat_name_width = name_width;
1938 options->stat_width = width;
1940 else if (!strcmp(arg, "--check"))
1941 options->output_format |= DIFF_FORMAT_CHECKDIFF;
1942 else if (!strcmp(arg, "--summary"))
1943 options->output_format |= DIFF_FORMAT_SUMMARY;
1944 else if (!strcmp(arg, "--patch-with-stat")) {
1945 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
1947 else if (!strcmp(arg, "-z"))
1948 options->line_termination = 0;
1949 else if (!strncmp(arg, "-l", 2))
1950 options->rename_limit = strtoul(arg+2, NULL, 10);
1951 else if (!strcmp(arg, "--full-index"))
1952 options->full_index = 1;
1953 else if (!strcmp(arg, "--binary")) {
1954 options->output_format |= DIFF_FORMAT_PATCH;
1955 options->binary = 1;
1957 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
1958 options->text = 1;
1960 else if (!strcmp(arg, "--name-only"))
1961 options->output_format |= DIFF_FORMAT_NAME;
1962 else if (!strcmp(arg, "--name-status"))
1963 options->output_format |= DIFF_FORMAT_NAME_STATUS;
1964 else if (!strcmp(arg, "-R"))
1965 options->reverse_diff = 1;
1966 else if (!strncmp(arg, "-S", 2))
1967 options->pickaxe = arg + 2;
1968 else if (!strcmp(arg, "-s")) {
1969 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
1971 else if (!strncmp(arg, "-O", 2))
1972 options->orderfile = arg + 2;
1973 else if (!strncmp(arg, "--diff-filter=", 14))
1974 options->filter = arg + 14;
1975 else if (!strcmp(arg, "--pickaxe-all"))
1976 options->pickaxe_opts = DIFF_PICKAXE_ALL;
1977 else if (!strcmp(arg, "--pickaxe-regex"))
1978 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
1979 else if (!strncmp(arg, "-B", 2)) {
1980 if ((options->break_opt =
1981 diff_scoreopt_parse(arg)) == -1)
1982 return -1;
1984 else if (!strncmp(arg, "-M", 2)) {
1985 if ((options->rename_score =
1986 diff_scoreopt_parse(arg)) == -1)
1987 return -1;
1988 options->detect_rename = DIFF_DETECT_RENAME;
1990 else if (!strncmp(arg, "-C", 2)) {
1991 if ((options->rename_score =
1992 diff_scoreopt_parse(arg)) == -1)
1993 return -1;
1994 options->detect_rename = DIFF_DETECT_COPY;
1996 else if (!strcmp(arg, "--find-copies-harder"))
1997 options->find_copies_harder = 1;
1998 else if (!strcmp(arg, "--abbrev"))
1999 options->abbrev = DEFAULT_ABBREV;
2000 else if (!strncmp(arg, "--abbrev=", 9)) {
2001 options->abbrev = strtoul(arg + 9, NULL, 10);
2002 if (options->abbrev < MINIMUM_ABBREV)
2003 options->abbrev = MINIMUM_ABBREV;
2004 else if (40 < options->abbrev)
2005 options->abbrev = 40;
2007 else if (!strcmp(arg, "--color"))
2008 options->color_diff = 1;
2009 else if (!strcmp(arg, "--no-color"))
2010 options->color_diff = 0;
2011 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2012 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2013 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2014 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2015 else if (!strcmp(arg, "--color-words"))
2016 options->color_diff = options->color_diff_words = 1;
2017 else if (!strcmp(arg, "--no-renames"))
2018 options->detect_rename = 0;
2019 else
2020 return 0;
2021 return 1;
2024 static int parse_num(const char **cp_p)
2026 unsigned long num, scale;
2027 int ch, dot;
2028 const char *cp = *cp_p;
2030 num = 0;
2031 scale = 1;
2032 dot = 0;
2033 for(;;) {
2034 ch = *cp;
2035 if ( !dot && ch == '.' ) {
2036 scale = 1;
2037 dot = 1;
2038 } else if ( ch == '%' ) {
2039 scale = dot ? scale*100 : 100;
2040 cp++; /* % is always at the end */
2041 break;
2042 } else if ( ch >= '0' && ch <= '9' ) {
2043 if ( scale < 100000 ) {
2044 scale *= 10;
2045 num = (num*10) + (ch-'0');
2047 } else {
2048 break;
2050 cp++;
2052 *cp_p = cp;
2054 /* user says num divided by scale and we say internally that
2055 * is MAX_SCORE * num / scale.
2057 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
2060 int diff_scoreopt_parse(const char *opt)
2062 int opt1, opt2, cmd;
2064 if (*opt++ != '-')
2065 return -1;
2066 cmd = *opt++;
2067 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2068 return -1; /* that is not a -M, -C nor -B option */
2070 opt1 = parse_num(&opt);
2071 if (cmd != 'B')
2072 opt2 = 0;
2073 else {
2074 if (*opt == 0)
2075 opt2 = 0;
2076 else if (*opt != '/')
2077 return -1; /* we expect -B80/99 or -B80 */
2078 else {
2079 opt++;
2080 opt2 = parse_num(&opt);
2083 if (*opt != 0)
2084 return -1;
2085 return opt1 | (opt2 << 16);
2088 struct diff_queue_struct diff_queued_diff;
2090 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2092 if (queue->alloc <= queue->nr) {
2093 queue->alloc = alloc_nr(queue->alloc);
2094 queue->queue = xrealloc(queue->queue,
2095 sizeof(dp) * queue->alloc);
2097 queue->queue[queue->nr++] = dp;
2100 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2101 struct diff_filespec *one,
2102 struct diff_filespec *two)
2104 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2105 dp->one = one;
2106 dp->two = two;
2107 if (queue)
2108 diff_q(queue, dp);
2109 return dp;
2112 void diff_free_filepair(struct diff_filepair *p)
2114 diff_free_filespec_data(p->one);
2115 diff_free_filespec_data(p->two);
2116 free(p->one);
2117 free(p->two);
2118 free(p);
2121 /* This is different from find_unique_abbrev() in that
2122 * it stuffs the result with dots for alignment.
2124 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2126 int abblen;
2127 const char *abbrev;
2128 if (len == 40)
2129 return sha1_to_hex(sha1);
2131 abbrev = find_unique_abbrev(sha1, len);
2132 if (!abbrev)
2133 return sha1_to_hex(sha1);
2134 abblen = strlen(abbrev);
2135 if (abblen < 37) {
2136 static char hex[41];
2137 if (len < abblen && abblen <= len + 2)
2138 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2139 else
2140 sprintf(hex, "%s...", abbrev);
2141 return hex;
2143 return sha1_to_hex(sha1);
2146 static void diff_flush_raw(struct diff_filepair *p,
2147 struct diff_options *options)
2149 int two_paths;
2150 char status[10];
2151 int abbrev = options->abbrev;
2152 const char *path_one, *path_two;
2153 int inter_name_termination = '\t';
2154 int line_termination = options->line_termination;
2156 if (!line_termination)
2157 inter_name_termination = 0;
2159 path_one = p->one->path;
2160 path_two = p->two->path;
2161 if (line_termination) {
2162 path_one = quote_one(path_one);
2163 path_two = quote_one(path_two);
2166 if (p->score)
2167 sprintf(status, "%c%03d", p->status,
2168 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2169 else {
2170 status[0] = p->status;
2171 status[1] = 0;
2173 switch (p->status) {
2174 case DIFF_STATUS_COPIED:
2175 case DIFF_STATUS_RENAMED:
2176 two_paths = 1;
2177 break;
2178 case DIFF_STATUS_ADDED:
2179 case DIFF_STATUS_DELETED:
2180 two_paths = 0;
2181 break;
2182 default:
2183 two_paths = 0;
2184 break;
2186 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2187 printf(":%06o %06o %s ",
2188 p->one->mode, p->two->mode,
2189 diff_unique_abbrev(p->one->sha1, abbrev));
2190 printf("%s ",
2191 diff_unique_abbrev(p->two->sha1, abbrev));
2193 printf("%s%c%s", status, inter_name_termination, path_one);
2194 if (two_paths)
2195 printf("%c%s", inter_name_termination, path_two);
2196 putchar(line_termination);
2197 if (path_one != p->one->path)
2198 free((void*)path_one);
2199 if (path_two != p->two->path)
2200 free((void*)path_two);
2203 static void diff_flush_name(struct diff_filepair *p, int line_termination)
2205 char *path = p->two->path;
2207 if (line_termination)
2208 path = quote_one(p->two->path);
2209 printf("%s%c", path, line_termination);
2210 if (p->two->path != path)
2211 free(path);
2214 int diff_unmodified_pair(struct diff_filepair *p)
2216 /* This function is written stricter than necessary to support
2217 * the currently implemented transformers, but the idea is to
2218 * let transformers to produce diff_filepairs any way they want,
2219 * and filter and clean them up here before producing the output.
2221 struct diff_filespec *one, *two;
2223 if (DIFF_PAIR_UNMERGED(p))
2224 return 0; /* unmerged is interesting */
2226 one = p->one;
2227 two = p->two;
2229 /* deletion, addition, mode or type change
2230 * and rename are all interesting.
2232 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2233 DIFF_PAIR_MODE_CHANGED(p) ||
2234 strcmp(one->path, two->path))
2235 return 0;
2237 /* both are valid and point at the same path. that is, we are
2238 * dealing with a change.
2240 if (one->sha1_valid && two->sha1_valid &&
2241 !hashcmp(one->sha1, two->sha1))
2242 return 1; /* no change */
2243 if (!one->sha1_valid && !two->sha1_valid)
2244 return 1; /* both look at the same file on the filesystem. */
2245 return 0;
2248 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2250 if (diff_unmodified_pair(p))
2251 return;
2253 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2254 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2255 return; /* no tree diffs in patch format */
2257 run_diff(p, o);
2260 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2261 struct diffstat_t *diffstat)
2263 if (diff_unmodified_pair(p))
2264 return;
2266 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2267 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2268 return; /* no tree diffs in patch format */
2270 run_diffstat(p, o, diffstat);
2273 static void diff_flush_checkdiff(struct diff_filepair *p,
2274 struct diff_options *o)
2276 if (diff_unmodified_pair(p))
2277 return;
2279 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2280 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2281 return; /* no tree diffs in patch format */
2283 run_checkdiff(p, o);
2286 int diff_queue_is_empty(void)
2288 struct diff_queue_struct *q = &diff_queued_diff;
2289 int i;
2290 for (i = 0; i < q->nr; i++)
2291 if (!diff_unmodified_pair(q->queue[i]))
2292 return 0;
2293 return 1;
2296 #if DIFF_DEBUG
2297 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2299 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2300 x, one ? one : "",
2301 s->path,
2302 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2303 s->mode,
2304 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2305 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2306 x, one ? one : "",
2307 s->size, s->xfrm_flags);
2310 void diff_debug_filepair(const struct diff_filepair *p, int i)
2312 diff_debug_filespec(p->one, i, "one");
2313 diff_debug_filespec(p->two, i, "two");
2314 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2315 p->score, p->status ? p->status : '?',
2316 p->source_stays, p->broken_pair);
2319 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2321 int i;
2322 if (msg)
2323 fprintf(stderr, "%s\n", msg);
2324 fprintf(stderr, "q->nr = %d\n", q->nr);
2325 for (i = 0; i < q->nr; i++) {
2326 struct diff_filepair *p = q->queue[i];
2327 diff_debug_filepair(p, i);
2330 #endif
2332 static void diff_resolve_rename_copy(void)
2334 int i, j;
2335 struct diff_filepair *p, *pp;
2336 struct diff_queue_struct *q = &diff_queued_diff;
2338 diff_debug_queue("resolve-rename-copy", q);
2340 for (i = 0; i < q->nr; i++) {
2341 p = q->queue[i];
2342 p->status = 0; /* undecided */
2343 if (DIFF_PAIR_UNMERGED(p))
2344 p->status = DIFF_STATUS_UNMERGED;
2345 else if (!DIFF_FILE_VALID(p->one))
2346 p->status = DIFF_STATUS_ADDED;
2347 else if (!DIFF_FILE_VALID(p->two))
2348 p->status = DIFF_STATUS_DELETED;
2349 else if (DIFF_PAIR_TYPE_CHANGED(p))
2350 p->status = DIFF_STATUS_TYPE_CHANGED;
2352 /* from this point on, we are dealing with a pair
2353 * whose both sides are valid and of the same type, i.e.
2354 * either in-place edit or rename/copy edit.
2356 else if (DIFF_PAIR_RENAME(p)) {
2357 if (p->source_stays) {
2358 p->status = DIFF_STATUS_COPIED;
2359 continue;
2361 /* See if there is some other filepair that
2362 * copies from the same source as us. If so
2363 * we are a copy. Otherwise we are either a
2364 * copy if the path stays, or a rename if it
2365 * does not, but we already handled "stays" case.
2367 for (j = i + 1; j < q->nr; j++) {
2368 pp = q->queue[j];
2369 if (strcmp(pp->one->path, p->one->path))
2370 continue; /* not us */
2371 if (!DIFF_PAIR_RENAME(pp))
2372 continue; /* not a rename/copy */
2373 /* pp is a rename/copy from the same source */
2374 p->status = DIFF_STATUS_COPIED;
2375 break;
2377 if (!p->status)
2378 p->status = DIFF_STATUS_RENAMED;
2380 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2381 p->one->mode != p->two->mode)
2382 p->status = DIFF_STATUS_MODIFIED;
2383 else {
2384 /* This is a "no-change" entry and should not
2385 * happen anymore, but prepare for broken callers.
2387 error("feeding unmodified %s to diffcore",
2388 p->one->path);
2389 p->status = DIFF_STATUS_UNKNOWN;
2392 diff_debug_queue("resolve-rename-copy done", q);
2395 static int check_pair_status(struct diff_filepair *p)
2397 switch (p->status) {
2398 case DIFF_STATUS_UNKNOWN:
2399 return 0;
2400 case 0:
2401 die("internal error in diff-resolve-rename-copy");
2402 default:
2403 return 1;
2407 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2409 int fmt = opt->output_format;
2411 if (fmt & DIFF_FORMAT_CHECKDIFF)
2412 diff_flush_checkdiff(p, opt);
2413 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2414 diff_flush_raw(p, opt);
2415 else if (fmt & DIFF_FORMAT_NAME)
2416 diff_flush_name(p, opt->line_termination);
2419 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2421 if (fs->mode)
2422 printf(" %s mode %06o %s\n", newdelete, fs->mode, fs->path);
2423 else
2424 printf(" %s %s\n", newdelete, fs->path);
2428 static void show_mode_change(struct diff_filepair *p, int show_name)
2430 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2431 if (show_name)
2432 printf(" mode change %06o => %06o %s\n",
2433 p->one->mode, p->two->mode, p->two->path);
2434 else
2435 printf(" mode change %06o => %06o\n",
2436 p->one->mode, p->two->mode);
2440 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2442 const char *old, *new;
2444 /* Find common prefix */
2445 old = p->one->path;
2446 new = p->two->path;
2447 while (1) {
2448 const char *slash_old, *slash_new;
2449 slash_old = strchr(old, '/');
2450 slash_new = strchr(new, '/');
2451 if (!slash_old ||
2452 !slash_new ||
2453 slash_old - old != slash_new - new ||
2454 memcmp(old, new, slash_new - new))
2455 break;
2456 old = slash_old + 1;
2457 new = slash_new + 1;
2459 /* p->one->path thru old is the common prefix, and old and new
2460 * through the end of names are renames
2462 if (old != p->one->path)
2463 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2464 (int)(old - p->one->path), p->one->path,
2465 old, new, (int)(0.5 + p->score * 100.0/MAX_SCORE));
2466 else
2467 printf(" %s %s => %s (%d%%)\n", renamecopy,
2468 p->one->path, p->two->path,
2469 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2470 show_mode_change(p, 0);
2473 static void diff_summary(struct diff_filepair *p)
2475 switch(p->status) {
2476 case DIFF_STATUS_DELETED:
2477 show_file_mode_name("delete", p->one);
2478 break;
2479 case DIFF_STATUS_ADDED:
2480 show_file_mode_name("create", p->two);
2481 break;
2482 case DIFF_STATUS_COPIED:
2483 show_rename_copy("copy", p);
2484 break;
2485 case DIFF_STATUS_RENAMED:
2486 show_rename_copy("rename", p);
2487 break;
2488 default:
2489 if (p->score) {
2490 printf(" rewrite %s (%d%%)\n", p->two->path,
2491 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2492 show_mode_change(p, 0);
2493 } else show_mode_change(p, 1);
2494 break;
2498 struct patch_id_t {
2499 struct xdiff_emit_state xm;
2500 SHA_CTX *ctx;
2501 int patchlen;
2504 static int remove_space(char *line, int len)
2506 int i;
2507 char *dst = line;
2508 unsigned char c;
2510 for (i = 0; i < len; i++)
2511 if (!isspace((c = line[i])))
2512 *dst++ = c;
2514 return dst - line;
2517 static void patch_id_consume(void *priv, char *line, unsigned long len)
2519 struct patch_id_t *data = priv;
2520 int new_len;
2522 /* Ignore line numbers when computing the SHA1 of the patch */
2523 if (!strncmp(line, "@@ -", 4))
2524 return;
2526 new_len = remove_space(line, len);
2528 SHA1_Update(data->ctx, line, new_len);
2529 data->patchlen += new_len;
2532 /* returns 0 upon success, and writes result into sha1 */
2533 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2535 struct diff_queue_struct *q = &diff_queued_diff;
2536 int i;
2537 SHA_CTX ctx;
2538 struct patch_id_t data;
2539 char buffer[PATH_MAX * 4 + 20];
2541 SHA1_Init(&ctx);
2542 memset(&data, 0, sizeof(struct patch_id_t));
2543 data.ctx = &ctx;
2544 data.xm.consume = patch_id_consume;
2546 for (i = 0; i < q->nr; i++) {
2547 xpparam_t xpp;
2548 xdemitconf_t xecfg;
2549 xdemitcb_t ecb;
2550 mmfile_t mf1, mf2;
2551 struct diff_filepair *p = q->queue[i];
2552 int len1, len2;
2554 if (p->status == 0)
2555 return error("internal diff status error");
2556 if (p->status == DIFF_STATUS_UNKNOWN)
2557 continue;
2558 if (diff_unmodified_pair(p))
2559 continue;
2560 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2561 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2562 continue;
2563 if (DIFF_PAIR_UNMERGED(p))
2564 continue;
2566 diff_fill_sha1_info(p->one);
2567 diff_fill_sha1_info(p->two);
2568 if (fill_mmfile(&mf1, p->one) < 0 ||
2569 fill_mmfile(&mf2, p->two) < 0)
2570 return error("unable to read files to diff");
2572 /* Maybe hash p->two? into the patch id? */
2573 if (mmfile_is_binary(&mf2))
2574 continue;
2576 len1 = remove_space(p->one->path, strlen(p->one->path));
2577 len2 = remove_space(p->two->path, strlen(p->two->path));
2578 if (p->one->mode == 0)
2579 len1 = snprintf(buffer, sizeof(buffer),
2580 "diff--gita/%.*sb/%.*s"
2581 "newfilemode%06o"
2582 "---/dev/null"
2583 "+++b/%.*s",
2584 len1, p->one->path,
2585 len2, p->two->path,
2586 p->two->mode,
2587 len2, p->two->path);
2588 else if (p->two->mode == 0)
2589 len1 = snprintf(buffer, sizeof(buffer),
2590 "diff--gita/%.*sb/%.*s"
2591 "deletedfilemode%06o"
2592 "---a/%.*s"
2593 "+++/dev/null",
2594 len1, p->one->path,
2595 len2, p->two->path,
2596 p->one->mode,
2597 len1, p->one->path);
2598 else
2599 len1 = snprintf(buffer, sizeof(buffer),
2600 "diff--gita/%.*sb/%.*s"
2601 "---a/%.*s"
2602 "+++b/%.*s",
2603 len1, p->one->path,
2604 len2, p->two->path,
2605 len1, p->one->path,
2606 len2, p->two->path);
2607 SHA1_Update(&ctx, buffer, len1);
2609 xpp.flags = XDF_NEED_MINIMAL;
2610 xecfg.ctxlen = 3;
2611 xecfg.flags = XDL_EMIT_FUNCNAMES;
2612 ecb.outf = xdiff_outf;
2613 ecb.priv = &data;
2614 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2617 SHA1_Final(sha1, &ctx);
2618 return 0;
2621 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2623 struct diff_queue_struct *q = &diff_queued_diff;
2624 int i;
2625 int result = diff_get_patch_id(options, sha1);
2627 for (i = 0; i < q->nr; i++)
2628 diff_free_filepair(q->queue[i]);
2630 free(q->queue);
2631 q->queue = NULL;
2632 q->nr = q->alloc = 0;
2634 return result;
2637 static int is_summary_empty(const struct diff_queue_struct *q)
2639 int i;
2641 for (i = 0; i < q->nr; i++) {
2642 const struct diff_filepair *p = q->queue[i];
2644 switch (p->status) {
2645 case DIFF_STATUS_DELETED:
2646 case DIFF_STATUS_ADDED:
2647 case DIFF_STATUS_COPIED:
2648 case DIFF_STATUS_RENAMED:
2649 return 0;
2650 default:
2651 if (p->score)
2652 return 0;
2653 if (p->one->mode && p->two->mode &&
2654 p->one->mode != p->two->mode)
2655 return 0;
2656 break;
2659 return 1;
2662 void diff_flush(struct diff_options *options)
2664 struct diff_queue_struct *q = &diff_queued_diff;
2665 int i, output_format = options->output_format;
2666 int separator = 0;
2669 * Order: raw, stat, summary, patch
2670 * or: name/name-status/checkdiff (other bits clear)
2672 if (!q->nr)
2673 goto free_queue;
2675 if (output_format & (DIFF_FORMAT_RAW |
2676 DIFF_FORMAT_NAME |
2677 DIFF_FORMAT_NAME_STATUS |
2678 DIFF_FORMAT_CHECKDIFF)) {
2679 for (i = 0; i < q->nr; i++) {
2680 struct diff_filepair *p = q->queue[i];
2681 if (check_pair_status(p))
2682 flush_one_pair(p, options);
2684 separator++;
2687 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
2688 struct diffstat_t diffstat;
2690 memset(&diffstat, 0, sizeof(struct diffstat_t));
2691 diffstat.xm.consume = diffstat_consume;
2692 for (i = 0; i < q->nr; i++) {
2693 struct diff_filepair *p = q->queue[i];
2694 if (check_pair_status(p))
2695 diff_flush_stat(p, options, &diffstat);
2697 if (output_format & DIFF_FORMAT_NUMSTAT)
2698 show_numstat(&diffstat, options);
2699 if (output_format & DIFF_FORMAT_DIFFSTAT)
2700 show_stats(&diffstat, options);
2701 else if (output_format & DIFF_FORMAT_SHORTSTAT)
2702 show_shortstats(&diffstat);
2703 separator++;
2706 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2707 for (i = 0; i < q->nr; i++)
2708 diff_summary(q->queue[i]);
2709 separator++;
2712 if (output_format & DIFF_FORMAT_PATCH) {
2713 if (separator) {
2714 if (options->stat_sep) {
2715 /* attach patch instead of inline */
2716 fputs(options->stat_sep, stdout);
2717 } else {
2718 putchar(options->line_termination);
2722 for (i = 0; i < q->nr; i++) {
2723 struct diff_filepair *p = q->queue[i];
2724 if (check_pair_status(p))
2725 diff_flush_patch(p, options);
2729 if (output_format & DIFF_FORMAT_CALLBACK)
2730 options->format_callback(q, options, options->format_callback_data);
2732 for (i = 0; i < q->nr; i++)
2733 diff_free_filepair(q->queue[i]);
2734 free_queue:
2735 free(q->queue);
2736 q->queue = NULL;
2737 q->nr = q->alloc = 0;
2740 static void diffcore_apply_filter(const char *filter)
2742 int i;
2743 struct diff_queue_struct *q = &diff_queued_diff;
2744 struct diff_queue_struct outq;
2745 outq.queue = NULL;
2746 outq.nr = outq.alloc = 0;
2748 if (!filter)
2749 return;
2751 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2752 int found;
2753 for (i = found = 0; !found && i < q->nr; i++) {
2754 struct diff_filepair *p = q->queue[i];
2755 if (((p->status == DIFF_STATUS_MODIFIED) &&
2756 ((p->score &&
2757 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2758 (!p->score &&
2759 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2760 ((p->status != DIFF_STATUS_MODIFIED) &&
2761 strchr(filter, p->status)))
2762 found++;
2764 if (found)
2765 return;
2767 /* otherwise we will clear the whole queue
2768 * by copying the empty outq at the end of this
2769 * function, but first clear the current entries
2770 * in the queue.
2772 for (i = 0; i < q->nr; i++)
2773 diff_free_filepair(q->queue[i]);
2775 else {
2776 /* Only the matching ones */
2777 for (i = 0; i < q->nr; i++) {
2778 struct diff_filepair *p = q->queue[i];
2780 if (((p->status == DIFF_STATUS_MODIFIED) &&
2781 ((p->score &&
2782 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2783 (!p->score &&
2784 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2785 ((p->status != DIFF_STATUS_MODIFIED) &&
2786 strchr(filter, p->status)))
2787 diff_q(&outq, p);
2788 else
2789 diff_free_filepair(p);
2792 free(q->queue);
2793 *q = outq;
2796 void diffcore_std(struct diff_options *options)
2798 if (options->break_opt != -1)
2799 diffcore_break(options->break_opt);
2800 if (options->detect_rename)
2801 diffcore_rename(options);
2802 if (options->break_opt != -1)
2803 diffcore_merge_broken();
2804 if (options->pickaxe)
2805 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2806 if (options->orderfile)
2807 diffcore_order(options->orderfile);
2808 diff_resolve_rename_copy();
2809 diffcore_apply_filter(options->filter);
2813 void diffcore_std_no_resolve(struct diff_options *options)
2815 if (options->pickaxe)
2816 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2817 if (options->orderfile)
2818 diffcore_order(options->orderfile);
2819 diffcore_apply_filter(options->filter);
2822 void diff_addremove(struct diff_options *options,
2823 int addremove, unsigned mode,
2824 const unsigned char *sha1,
2825 const char *base, const char *path)
2827 char concatpath[PATH_MAX];
2828 struct diff_filespec *one, *two;
2830 /* This may look odd, but it is a preparation for
2831 * feeding "there are unchanged files which should
2832 * not produce diffs, but when you are doing copy
2833 * detection you would need them, so here they are"
2834 * entries to the diff-core. They will be prefixed
2835 * with something like '=' or '*' (I haven't decided
2836 * which but should not make any difference).
2837 * Feeding the same new and old to diff_change()
2838 * also has the same effect.
2839 * Before the final output happens, they are pruned after
2840 * merged into rename/copy pairs as appropriate.
2842 if (options->reverse_diff)
2843 addremove = (addremove == '+' ? '-' :
2844 addremove == '-' ? '+' : addremove);
2846 if (!path) path = "";
2847 sprintf(concatpath, "%s%s", base, path);
2848 one = alloc_filespec(concatpath);
2849 two = alloc_filespec(concatpath);
2851 if (addremove != '+')
2852 fill_filespec(one, sha1, mode);
2853 if (addremove != '-')
2854 fill_filespec(two, sha1, mode);
2856 diff_queue(&diff_queued_diff, one, two);
2859 void diff_change(struct diff_options *options,
2860 unsigned old_mode, unsigned new_mode,
2861 const unsigned char *old_sha1,
2862 const unsigned char *new_sha1,
2863 const char *base, const char *path)
2865 char concatpath[PATH_MAX];
2866 struct diff_filespec *one, *two;
2868 if (options->reverse_diff) {
2869 unsigned tmp;
2870 const unsigned char *tmp_c;
2871 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2872 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2874 if (!path) path = "";
2875 sprintf(concatpath, "%s%s", base, path);
2876 one = alloc_filespec(concatpath);
2877 two = alloc_filespec(concatpath);
2878 fill_filespec(one, old_sha1, old_mode);
2879 fill_filespec(two, new_sha1, new_mode);
2881 diff_queue(&diff_queued_diff, one, two);
2884 void diff_unmerge(struct diff_options *options,
2885 const char *path,
2886 unsigned mode, const unsigned char *sha1)
2888 struct diff_filespec *one, *two;
2889 one = alloc_filespec(path);
2890 two = alloc_filespec(path);
2891 fill_filespec(one, sha1, mode);
2892 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;