Merge branch 'sb/fetch'
[alt-git.git] / diff.c
blobfb8243261cb3cc9165dbe990586d3865fad4ee61
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include <sys/types.h>
5 #include <sys/wait.h>
6 #include <signal.h>
7 #include "cache.h"
8 #include "quote.h"
9 #include "diff.h"
10 #include "diffcore.h"
11 #include "delta.h"
12 #include "xdiff-interface.h"
13 #include "color.h"
15 static int use_size_cache;
17 static int diff_detect_rename_default;
18 static int diff_rename_limit_default = -1;
19 static int diff_use_color_default;
21 static char diff_colors[][COLOR_MAXLEN] = {
22 "\033[m", /* reset */
23 "", /* PLAIN (normal) */
24 "\033[1m", /* METAINFO (bold) */
25 "\033[36m", /* FRAGINFO (cyan) */
26 "\033[31m", /* OLD (red) */
27 "\033[32m", /* NEW (green) */
28 "\033[33m", /* COMMIT (yellow) */
29 "\033[41m", /* WHITESPACE (red background) */
32 static int parse_diff_color_slot(const char *var, int ofs)
34 if (!strcasecmp(var+ofs, "plain"))
35 return DIFF_PLAIN;
36 if (!strcasecmp(var+ofs, "meta"))
37 return DIFF_METAINFO;
38 if (!strcasecmp(var+ofs, "frag"))
39 return DIFF_FRAGINFO;
40 if (!strcasecmp(var+ofs, "old"))
41 return DIFF_FILE_OLD;
42 if (!strcasecmp(var+ofs, "new"))
43 return DIFF_FILE_NEW;
44 if (!strcasecmp(var+ofs, "commit"))
45 return DIFF_COMMIT;
46 if (!strcasecmp(var+ofs, "whitespace"))
47 return DIFF_WHITESPACE;
48 die("bad config variable '%s'", var);
52 * These are to give UI layer defaults.
53 * The core-level commands such as git-diff-files should
54 * never be affected by the setting of diff.renames
55 * the user happens to have in the configuration file.
57 int git_diff_ui_config(const char *var, const char *value)
59 if (!strcmp(var, "diff.renamelimit")) {
60 diff_rename_limit_default = git_config_int(var, value);
61 return 0;
63 if (!strcmp(var, "diff.color")) {
64 diff_use_color_default = git_config_colorbool(var, value);
65 return 0;
67 if (!strcmp(var, "diff.renames")) {
68 if (!value)
69 diff_detect_rename_default = DIFF_DETECT_RENAME;
70 else if (!strcasecmp(value, "copies") ||
71 !strcasecmp(value, "copy"))
72 diff_detect_rename_default = DIFF_DETECT_COPY;
73 else if (git_config_bool(var,value))
74 diff_detect_rename_default = DIFF_DETECT_RENAME;
75 return 0;
77 if (!strncmp(var, "diff.color.", 11)) {
78 int slot = parse_diff_color_slot(var, 11);
79 color_parse(value, var, diff_colors[slot]);
80 return 0;
82 return git_default_config(var, value);
85 static char *quote_one(const char *str)
87 int needlen;
88 char *xp;
90 if (!str)
91 return NULL;
92 needlen = quote_c_style(str, NULL, NULL, 0);
93 if (!needlen)
94 return xstrdup(str);
95 xp = xmalloc(needlen + 1);
96 quote_c_style(str, xp, NULL, 0);
97 return xp;
100 static char *quote_two(const char *one, const char *two)
102 int need_one = quote_c_style(one, NULL, NULL, 1);
103 int need_two = quote_c_style(two, NULL, NULL, 1);
104 char *xp;
106 if (need_one + need_two) {
107 if (!need_one) need_one = strlen(one);
108 if (!need_two) need_one = strlen(two);
110 xp = xmalloc(need_one + need_two + 3);
111 xp[0] = '"';
112 quote_c_style(one, xp + 1, NULL, 1);
113 quote_c_style(two, xp + need_one + 1, NULL, 1);
114 strcpy(xp + need_one + need_two + 1, "\"");
115 return xp;
117 need_one = strlen(one);
118 need_two = strlen(two);
119 xp = xmalloc(need_one + need_two + 1);
120 strcpy(xp, one);
121 strcpy(xp + need_one, two);
122 return xp;
125 static const char *external_diff(void)
127 static const char *external_diff_cmd = NULL;
128 static int done_preparing = 0;
130 if (done_preparing)
131 return external_diff_cmd;
132 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
133 done_preparing = 1;
134 return external_diff_cmd;
137 #define TEMPFILE_PATH_LEN 50
139 static struct diff_tempfile {
140 const char *name; /* filename external diff should read from */
141 char hex[41];
142 char mode[10];
143 char tmp_path[TEMPFILE_PATH_LEN];
144 } diff_temp[2];
146 static int count_lines(const char *data, int size)
148 int count, ch, completely_empty = 1, nl_just_seen = 0;
149 count = 0;
150 while (0 < size--) {
151 ch = *data++;
152 if (ch == '\n') {
153 count++;
154 nl_just_seen = 1;
155 completely_empty = 0;
157 else {
158 nl_just_seen = 0;
159 completely_empty = 0;
162 if (completely_empty)
163 return 0;
164 if (!nl_just_seen)
165 count++; /* no trailing newline */
166 return count;
169 static void print_line_count(int count)
171 switch (count) {
172 case 0:
173 printf("0,0");
174 break;
175 case 1:
176 printf("1");
177 break;
178 default:
179 printf("1,%d", count);
180 break;
184 static void copy_file(int prefix, const char *data, int size)
186 int ch, nl_just_seen = 1;
187 while (0 < size--) {
188 ch = *data++;
189 if (nl_just_seen)
190 putchar(prefix);
191 putchar(ch);
192 if (ch == '\n')
193 nl_just_seen = 1;
194 else
195 nl_just_seen = 0;
197 if (!nl_just_seen)
198 printf("\n\\ No newline at end of file\n");
201 static void emit_rewrite_diff(const char *name_a,
202 const char *name_b,
203 struct diff_filespec *one,
204 struct diff_filespec *two)
206 int lc_a, lc_b;
207 diff_populate_filespec(one, 0);
208 diff_populate_filespec(two, 0);
209 lc_a = count_lines(one->data, one->size);
210 lc_b = count_lines(two->data, two->size);
211 printf("--- a/%s\n+++ b/%s\n@@ -", name_a, name_b);
212 print_line_count(lc_a);
213 printf(" +");
214 print_line_count(lc_b);
215 printf(" @@\n");
216 if (lc_a)
217 copy_file('-', one->data, one->size);
218 if (lc_b)
219 copy_file('+', two->data, two->size);
222 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
224 if (!DIFF_FILE_VALID(one)) {
225 mf->ptr = (char *)""; /* does not matter */
226 mf->size = 0;
227 return 0;
229 else if (diff_populate_filespec(one, 0))
230 return -1;
231 mf->ptr = one->data;
232 mf->size = one->size;
233 return 0;
236 struct diff_words_buffer {
237 mmfile_t text;
238 long alloc;
239 long current; /* output pointer */
240 int suppressed_newline;
243 static void diff_words_append(char *line, unsigned long len,
244 struct diff_words_buffer *buffer)
246 if (buffer->text.size + len > buffer->alloc) {
247 buffer->alloc = (buffer->text.size + len) * 3 / 2;
248 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
250 line++;
251 len--;
252 memcpy(buffer->text.ptr + buffer->text.size, line, len);
253 buffer->text.size += len;
256 struct diff_words_data {
257 struct xdiff_emit_state xm;
258 struct diff_words_buffer minus, plus;
261 static void print_word(struct diff_words_buffer *buffer, int len, int color,
262 int suppress_newline)
264 const char *ptr;
265 int eol = 0;
267 if (len == 0)
268 return;
270 ptr = buffer->text.ptr + buffer->current;
271 buffer->current += len;
273 if (ptr[len - 1] == '\n') {
274 eol = 1;
275 len--;
278 fputs(diff_get_color(1, color), stdout);
279 fwrite(ptr, len, 1, stdout);
280 fputs(diff_get_color(1, DIFF_RESET), stdout);
282 if (eol) {
283 if (suppress_newline)
284 buffer->suppressed_newline = 1;
285 else
286 putchar('\n');
290 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
292 struct diff_words_data *diff_words = priv;
294 if (diff_words->minus.suppressed_newline) {
295 if (line[0] != '+')
296 putchar('\n');
297 diff_words->minus.suppressed_newline = 0;
300 len--;
301 switch (line[0]) {
302 case '-':
303 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
304 break;
305 case '+':
306 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
307 break;
308 case ' ':
309 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
310 diff_words->minus.current += len;
311 break;
315 /* this executes the word diff on the accumulated buffers */
316 static void diff_words_show(struct diff_words_data *diff_words)
318 xpparam_t xpp;
319 xdemitconf_t xecfg;
320 xdemitcb_t ecb;
321 mmfile_t minus, plus;
322 int i;
324 minus.size = diff_words->minus.text.size;
325 minus.ptr = xmalloc(minus.size);
326 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
327 for (i = 0; i < minus.size; i++)
328 if (isspace(minus.ptr[i]))
329 minus.ptr[i] = '\n';
330 diff_words->minus.current = 0;
332 plus.size = diff_words->plus.text.size;
333 plus.ptr = xmalloc(plus.size);
334 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
335 for (i = 0; i < plus.size; i++)
336 if (isspace(plus.ptr[i]))
337 plus.ptr[i] = '\n';
338 diff_words->plus.current = 0;
340 xpp.flags = XDF_NEED_MINIMAL;
341 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
342 xecfg.flags = 0;
343 ecb.outf = xdiff_outf;
344 ecb.priv = diff_words;
345 diff_words->xm.consume = fn_out_diff_words_aux;
346 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
348 free(minus.ptr);
349 free(plus.ptr);
350 diff_words->minus.text.size = diff_words->plus.text.size = 0;
352 if (diff_words->minus.suppressed_newline) {
353 putchar('\n');
354 diff_words->minus.suppressed_newline = 0;
358 struct emit_callback {
359 struct xdiff_emit_state xm;
360 int nparents, color_diff;
361 const char **label_path;
362 struct diff_words_data *diff_words;
365 static void free_diff_words_data(struct emit_callback *ecbdata)
367 if (ecbdata->diff_words) {
368 /* flush buffers */
369 if (ecbdata->diff_words->minus.text.size ||
370 ecbdata->diff_words->plus.text.size)
371 diff_words_show(ecbdata->diff_words);
373 if (ecbdata->diff_words->minus.text.ptr)
374 free (ecbdata->diff_words->minus.text.ptr);
375 if (ecbdata->diff_words->plus.text.ptr)
376 free (ecbdata->diff_words->plus.text.ptr);
377 free(ecbdata->diff_words);
378 ecbdata->diff_words = NULL;
382 const char *diff_get_color(int diff_use_color, enum color_diff ix)
384 if (diff_use_color)
385 return diff_colors[ix];
386 return "";
389 static void emit_line(const char *set, const char *reset, const char *line, int len)
391 if (len > 0 && line[len-1] == '\n')
392 len--;
393 fputs(set, stdout);
394 fwrite(line, len, 1, stdout);
395 puts(reset);
398 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
400 int col0 = ecbdata->nparents;
401 int last_tab_in_indent = -1;
402 int last_space_in_indent = -1;
403 int i;
404 int tail = len;
405 int need_highlight_leading_space = 0;
406 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
407 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
409 if (!*ws) {
410 emit_line(set, reset, line, len);
411 return;
414 /* The line is a newly added line. Does it have funny leading
415 * whitespaces? In indent, SP should never precede a TAB.
417 for (i = col0; i < len; i++) {
418 if (line[i] == '\t') {
419 last_tab_in_indent = i;
420 if (0 <= last_space_in_indent)
421 need_highlight_leading_space = 1;
423 else if (line[i] == ' ')
424 last_space_in_indent = i;
425 else
426 break;
428 fputs(set, stdout);
429 fwrite(line, col0, 1, stdout);
430 fputs(reset, stdout);
431 if (((i == len) || line[i] == '\n') && i != col0) {
432 /* The whole line was indent */
433 emit_line(ws, reset, line + col0, len - col0);
434 return;
436 i = col0;
437 if (need_highlight_leading_space) {
438 while (i < last_tab_in_indent) {
439 if (line[i] == ' ') {
440 fputs(ws, stdout);
441 putchar(' ');
442 fputs(reset, stdout);
444 else
445 putchar(line[i]);
446 i++;
449 tail = len - 1;
450 if (line[tail] == '\n' && i < tail)
451 tail--;
452 while (i < tail) {
453 if (!isspace(line[tail]))
454 break;
455 tail--;
457 if ((i < tail && line[tail + 1] != '\n')) {
458 /* This has whitespace between tail+1..len */
459 fputs(set, stdout);
460 fwrite(line + i, tail - i + 1, 1, stdout);
461 fputs(reset, stdout);
462 emit_line(ws, reset, line + tail + 1, len - tail - 1);
464 else
465 emit_line(set, reset, line + i, len - i);
468 static void fn_out_consume(void *priv, char *line, unsigned long len)
470 int i;
471 int color;
472 struct emit_callback *ecbdata = priv;
473 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
474 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
476 if (ecbdata->label_path[0]) {
477 printf("%s--- %s%s\n", set, ecbdata->label_path[0], reset);
478 printf("%s+++ %s%s\n", set, ecbdata->label_path[1], reset);
479 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
482 /* This is not really necessary for now because
483 * this codepath only deals with two-way diffs.
485 for (i = 0; i < len && line[i] == '@'; i++)
487 if (2 <= i && i < len && line[i] == ' ') {
488 ecbdata->nparents = i - 1;
489 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
490 reset, line, len);
491 return;
494 if (len < ecbdata->nparents) {
495 set = reset;
496 emit_line(reset, reset, line, len);
497 return;
500 color = DIFF_PLAIN;
501 if (ecbdata->diff_words && ecbdata->nparents != 1)
502 /* fall back to normal diff */
503 free_diff_words_data(ecbdata);
504 if (ecbdata->diff_words) {
505 if (line[0] == '-') {
506 diff_words_append(line, len,
507 &ecbdata->diff_words->minus);
508 return;
509 } else if (line[0] == '+') {
510 diff_words_append(line, len,
511 &ecbdata->diff_words->plus);
512 return;
514 if (ecbdata->diff_words->minus.text.size ||
515 ecbdata->diff_words->plus.text.size)
516 diff_words_show(ecbdata->diff_words);
517 line++;
518 len--;
519 emit_line(set, reset, line, len);
520 return;
522 for (i = 0; i < ecbdata->nparents && len; i++) {
523 if (line[i] == '-')
524 color = DIFF_FILE_OLD;
525 else if (line[i] == '+')
526 color = DIFF_FILE_NEW;
529 if (color != DIFF_FILE_NEW) {
530 emit_line(diff_get_color(ecbdata->color_diff, color),
531 reset, line, len);
532 return;
534 emit_add_line(reset, ecbdata, line, len);
537 static char *pprint_rename(const char *a, const char *b)
539 const char *old = a;
540 const char *new = b;
541 char *name = NULL;
542 int pfx_length, sfx_length;
543 int len_a = strlen(a);
544 int len_b = strlen(b);
546 /* Find common prefix */
547 pfx_length = 0;
548 while (*old && *new && *old == *new) {
549 if (*old == '/')
550 pfx_length = old - a + 1;
551 old++;
552 new++;
555 /* Find common suffix */
556 old = a + len_a;
557 new = b + len_b;
558 sfx_length = 0;
559 while (a <= old && b <= new && *old == *new) {
560 if (*old == '/')
561 sfx_length = len_a - (old - a);
562 old--;
563 new--;
567 * pfx{mid-a => mid-b}sfx
568 * {pfx-a => pfx-b}sfx
569 * pfx{sfx-a => sfx-b}
570 * name-a => name-b
572 if (pfx_length + sfx_length) {
573 int a_midlen = len_a - pfx_length - sfx_length;
574 int b_midlen = len_b - pfx_length - sfx_length;
575 if (a_midlen < 0) a_midlen = 0;
576 if (b_midlen < 0) b_midlen = 0;
578 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
579 sprintf(name, "%.*s{%.*s => %.*s}%s",
580 pfx_length, a,
581 a_midlen, a + pfx_length,
582 b_midlen, b + pfx_length,
583 a + len_a - sfx_length);
585 else {
586 name = xmalloc(len_a + len_b + 5);
587 sprintf(name, "%s => %s", a, b);
589 return name;
592 struct diffstat_t {
593 struct xdiff_emit_state xm;
595 int nr;
596 int alloc;
597 struct diffstat_file {
598 char *name;
599 unsigned is_unmerged:1;
600 unsigned is_binary:1;
601 unsigned is_renamed:1;
602 unsigned int added, deleted;
603 } **files;
606 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
607 const char *name_a,
608 const char *name_b)
610 struct diffstat_file *x;
611 x = xcalloc(sizeof (*x), 1);
612 if (diffstat->nr == diffstat->alloc) {
613 diffstat->alloc = alloc_nr(diffstat->alloc);
614 diffstat->files = xrealloc(diffstat->files,
615 diffstat->alloc * sizeof(x));
617 diffstat->files[diffstat->nr++] = x;
618 if (name_b) {
619 x->name = pprint_rename(name_a, name_b);
620 x->is_renamed = 1;
622 else
623 x->name = xstrdup(name_a);
624 return x;
627 static void diffstat_consume(void *priv, char *line, unsigned long len)
629 struct diffstat_t *diffstat = priv;
630 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
632 if (line[0] == '+')
633 x->added++;
634 else if (line[0] == '-')
635 x->deleted++;
638 const char mime_boundary_leader[] = "------------";
640 static int scale_linear(int it, int width, int max_change)
643 * make sure that at least one '-' is printed if there were deletions,
644 * and likewise for '+'.
646 if (max_change < 2)
647 return it;
648 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
651 static void show_name(const char *prefix, const char *name, int len,
652 const char *reset, const char *set)
654 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
657 static void show_graph(char ch, int cnt, const char *set, const char *reset)
659 if (cnt <= 0)
660 return;
661 printf("%s", set);
662 while (cnt--)
663 putchar(ch);
664 printf("%s", reset);
667 static void show_stats(struct diffstat_t* data, struct diff_options *options)
669 int i, len, add, del, total, adds = 0, dels = 0;
670 int max_change = 0, max_len = 0;
671 int total_files = data->nr;
672 int width, name_width;
673 const char *reset, *set, *add_c, *del_c;
675 if (data->nr == 0)
676 return;
678 width = options->stat_width ? options->stat_width : 80;
679 name_width = options->stat_name_width ? options->stat_name_width : 50;
681 /* Sanity: give at least 5 columns to the graph,
682 * but leave at least 10 columns for the name.
684 if (width < name_width + 15) {
685 if (name_width <= 25)
686 width = name_width + 15;
687 else
688 name_width = width - 15;
691 /* Find the longest filename and max number of changes */
692 reset = diff_get_color(options->color_diff, DIFF_RESET);
693 set = diff_get_color(options->color_diff, DIFF_PLAIN);
694 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
695 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
697 for (i = 0; i < data->nr; i++) {
698 struct diffstat_file *file = data->files[i];
699 int change = file->added + file->deleted;
701 len = quote_c_style(file->name, NULL, NULL, 0);
702 if (len) {
703 char *qname = xmalloc(len + 1);
704 quote_c_style(file->name, qname, NULL, 0);
705 free(file->name);
706 file->name = qname;
709 len = strlen(file->name);
710 if (max_len < len)
711 max_len = len;
713 if (file->is_binary || file->is_unmerged)
714 continue;
715 if (max_change < change)
716 max_change = change;
719 /* Compute the width of the graph part;
720 * 10 is for one blank at the beginning of the line plus
721 * " | count " between the name and the graph.
723 * From here on, name_width is the width of the name area,
724 * and width is the width of the graph area.
726 name_width = (name_width < max_len) ? name_width : max_len;
727 if (width < (name_width + 10) + max_change)
728 width = width - (name_width + 10);
729 else
730 width = max_change;
732 for (i = 0; i < data->nr; i++) {
733 const char *prefix = "";
734 char *name = data->files[i]->name;
735 int added = data->files[i]->added;
736 int deleted = data->files[i]->deleted;
737 int name_len;
740 * "scale" the filename
742 len = name_width;
743 name_len = strlen(name);
744 if (name_width < name_len) {
745 char *slash;
746 prefix = "...";
747 len -= 3;
748 name += name_len - len;
749 slash = strchr(name, '/');
750 if (slash)
751 name = slash;
754 if (data->files[i]->is_binary) {
755 show_name(prefix, name, len, reset, set);
756 printf(" Bin\n");
757 goto free_diffstat_file;
759 else if (data->files[i]->is_unmerged) {
760 show_name(prefix, name, len, reset, set);
761 printf(" Unmerged\n");
762 goto free_diffstat_file;
764 else if (!data->files[i]->is_renamed &&
765 (added + deleted == 0)) {
766 total_files--;
767 goto free_diffstat_file;
771 * scale the add/delete
773 add = added;
774 del = deleted;
775 total = add + del;
776 adds += add;
777 dels += del;
779 if (width <= max_change) {
780 add = scale_linear(add, width, max_change);
781 del = scale_linear(del, width, max_change);
782 total = add + del;
784 show_name(prefix, name, len, reset, set);
785 printf("%5d ", added + deleted);
786 show_graph('+', add, add_c, reset);
787 show_graph('-', del, del_c, reset);
788 putchar('\n');
789 free_diffstat_file:
790 free(data->files[i]->name);
791 free(data->files[i]);
793 free(data->files);
794 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
795 set, total_files, adds, dels, reset);
798 struct checkdiff_t {
799 struct xdiff_emit_state xm;
800 const char *filename;
801 int lineno;
804 static void checkdiff_consume(void *priv, char *line, unsigned long len)
806 struct checkdiff_t *data = priv;
808 if (line[0] == '+') {
809 int i, spaces = 0;
811 data->lineno++;
813 /* check space before tab */
814 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
815 if (line[i] == ' ')
816 spaces++;
817 if (line[i - 1] == '\t' && spaces)
818 printf("%s:%d: space before tab:%.*s\n",
819 data->filename, data->lineno, (int)len, line);
821 /* check white space at line end */
822 if (line[len - 1] == '\n')
823 len--;
824 if (isspace(line[len - 1]))
825 printf("%s:%d: white space at end: %.*s\n",
826 data->filename, data->lineno, (int)len, line);
827 } else if (line[0] == ' ')
828 data->lineno++;
829 else if (line[0] == '@') {
830 char *plus = strchr(line, '+');
831 if (plus)
832 data->lineno = strtol(plus, NULL, 10);
833 else
834 die("invalid diff");
838 static unsigned char *deflate_it(char *data,
839 unsigned long size,
840 unsigned long *result_size)
842 int bound;
843 unsigned char *deflated;
844 z_stream stream;
846 memset(&stream, 0, sizeof(stream));
847 deflateInit(&stream, zlib_compression_level);
848 bound = deflateBound(&stream, size);
849 deflated = xmalloc(bound);
850 stream.next_out = deflated;
851 stream.avail_out = bound;
853 stream.next_in = (unsigned char *)data;
854 stream.avail_in = size;
855 while (deflate(&stream, Z_FINISH) == Z_OK)
856 ; /* nothing */
857 deflateEnd(&stream);
858 *result_size = stream.total_out;
859 return deflated;
862 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
864 void *cp;
865 void *delta;
866 void *deflated;
867 void *data;
868 unsigned long orig_size;
869 unsigned long delta_size;
870 unsigned long deflate_size;
871 unsigned long data_size;
873 /* We could do deflated delta, or we could do just deflated two,
874 * whichever is smaller.
876 delta = NULL;
877 deflated = deflate_it(two->ptr, two->size, &deflate_size);
878 if (one->size && two->size) {
879 delta = diff_delta(one->ptr, one->size,
880 two->ptr, two->size,
881 &delta_size, deflate_size);
882 if (delta) {
883 void *to_free = delta;
884 orig_size = delta_size;
885 delta = deflate_it(delta, delta_size, &delta_size);
886 free(to_free);
890 if (delta && delta_size < deflate_size) {
891 printf("delta %lu\n", orig_size);
892 free(deflated);
893 data = delta;
894 data_size = delta_size;
896 else {
897 printf("literal %lu\n", two->size);
898 free(delta);
899 data = deflated;
900 data_size = deflate_size;
903 /* emit data encoded in base85 */
904 cp = data;
905 while (data_size) {
906 int bytes = (52 < data_size) ? 52 : data_size;
907 char line[70];
908 data_size -= bytes;
909 if (bytes <= 26)
910 line[0] = bytes + 'A' - 1;
911 else
912 line[0] = bytes - 26 + 'a' - 1;
913 encode_85(line + 1, cp, bytes);
914 cp = (char *) cp + bytes;
915 puts(line);
917 printf("\n");
918 free(data);
921 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
923 printf("GIT binary patch\n");
924 emit_binary_diff_body(one, two);
925 emit_binary_diff_body(two, one);
928 #define FIRST_FEW_BYTES 8000
929 static int mmfile_is_binary(mmfile_t *mf)
931 long sz = mf->size;
932 if (FIRST_FEW_BYTES < sz)
933 sz = FIRST_FEW_BYTES;
934 return !!memchr(mf->ptr, 0, sz);
937 static void builtin_diff(const char *name_a,
938 const char *name_b,
939 struct diff_filespec *one,
940 struct diff_filespec *two,
941 const char *xfrm_msg,
942 struct diff_options *o,
943 int complete_rewrite)
945 mmfile_t mf1, mf2;
946 const char *lbl[2];
947 char *a_one, *b_two;
948 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
949 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
951 a_one = quote_two("a/", name_a);
952 b_two = quote_two("b/", name_b);
953 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
954 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
955 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
956 if (lbl[0][0] == '/') {
957 /* /dev/null */
958 printf("%snew file mode %06o%s\n", set, two->mode, reset);
959 if (xfrm_msg && xfrm_msg[0])
960 printf("%s%s%s\n", set, xfrm_msg, reset);
962 else if (lbl[1][0] == '/') {
963 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
964 if (xfrm_msg && xfrm_msg[0])
965 printf("%s%s%s\n", set, xfrm_msg, reset);
967 else {
968 if (one->mode != two->mode) {
969 printf("%sold mode %06o%s\n", set, one->mode, reset);
970 printf("%snew mode %06o%s\n", set, two->mode, reset);
972 if (xfrm_msg && xfrm_msg[0])
973 printf("%s%s%s\n", set, xfrm_msg, reset);
975 * we do not run diff between different kind
976 * of objects.
978 if ((one->mode ^ two->mode) & S_IFMT)
979 goto free_ab_and_return;
980 if (complete_rewrite) {
981 emit_rewrite_diff(name_a, name_b, one, two);
982 goto free_ab_and_return;
986 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
987 die("unable to read files to diff");
989 if (!o->text && (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))) {
990 /* Quite common confusing case */
991 if (mf1.size == mf2.size &&
992 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
993 goto free_ab_and_return;
994 if (o->binary)
995 emit_binary_diff(&mf1, &mf2);
996 else
997 printf("Binary files %s and %s differ\n",
998 lbl[0], lbl[1]);
1000 else {
1001 /* Crazy xdl interfaces.. */
1002 const char *diffopts = getenv("GIT_DIFF_OPTS");
1003 xpparam_t xpp;
1004 xdemitconf_t xecfg;
1005 xdemitcb_t ecb;
1006 struct emit_callback ecbdata;
1008 memset(&ecbdata, 0, sizeof(ecbdata));
1009 ecbdata.label_path = lbl;
1010 ecbdata.color_diff = o->color_diff;
1011 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1012 xecfg.ctxlen = o->context;
1013 xecfg.flags = XDL_EMIT_FUNCNAMES;
1014 if (!diffopts)
1016 else if (!strncmp(diffopts, "--unified=", 10))
1017 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1018 else if (!strncmp(diffopts, "-u", 2))
1019 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1020 ecb.outf = xdiff_outf;
1021 ecb.priv = &ecbdata;
1022 ecbdata.xm.consume = fn_out_consume;
1023 if (o->color_diff_words)
1024 ecbdata.diff_words =
1025 xcalloc(1, sizeof(struct diff_words_data));
1026 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1027 if (o->color_diff_words)
1028 free_diff_words_data(&ecbdata);
1031 free_ab_and_return:
1032 free(a_one);
1033 free(b_two);
1034 return;
1037 static void builtin_diffstat(const char *name_a, const char *name_b,
1038 struct diff_filespec *one,
1039 struct diff_filespec *two,
1040 struct diffstat_t *diffstat,
1041 struct diff_options *o,
1042 int complete_rewrite)
1044 mmfile_t mf1, mf2;
1045 struct diffstat_file *data;
1047 data = diffstat_add(diffstat, name_a, name_b);
1049 if (!one || !two) {
1050 data->is_unmerged = 1;
1051 return;
1053 if (complete_rewrite) {
1054 diff_populate_filespec(one, 0);
1055 diff_populate_filespec(two, 0);
1056 data->deleted = count_lines(one->data, one->size);
1057 data->added = count_lines(two->data, two->size);
1058 return;
1060 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1061 die("unable to read files to diff");
1063 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
1064 data->is_binary = 1;
1065 else {
1066 /* Crazy xdl interfaces.. */
1067 xpparam_t xpp;
1068 xdemitconf_t xecfg;
1069 xdemitcb_t ecb;
1071 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1072 xecfg.ctxlen = 0;
1073 xecfg.flags = 0;
1074 ecb.outf = xdiff_outf;
1075 ecb.priv = diffstat;
1076 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1080 static void builtin_checkdiff(const char *name_a, const char *name_b,
1081 struct diff_filespec *one,
1082 struct diff_filespec *two)
1084 mmfile_t mf1, mf2;
1085 struct checkdiff_t data;
1087 if (!two)
1088 return;
1090 memset(&data, 0, sizeof(data));
1091 data.xm.consume = checkdiff_consume;
1092 data.filename = name_b ? name_b : name_a;
1093 data.lineno = 0;
1095 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1096 die("unable to read files to diff");
1098 if (mmfile_is_binary(&mf2))
1099 return;
1100 else {
1101 /* Crazy xdl interfaces.. */
1102 xpparam_t xpp;
1103 xdemitconf_t xecfg;
1104 xdemitcb_t ecb;
1106 xpp.flags = XDF_NEED_MINIMAL;
1107 xecfg.ctxlen = 0;
1108 xecfg.flags = 0;
1109 ecb.outf = xdiff_outf;
1110 ecb.priv = &data;
1111 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1115 struct diff_filespec *alloc_filespec(const char *path)
1117 int namelen = strlen(path);
1118 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1120 memset(spec, 0, sizeof(*spec));
1121 spec->path = (char *)(spec + 1);
1122 memcpy(spec->path, path, namelen+1);
1123 return spec;
1126 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1127 unsigned short mode)
1129 if (mode) {
1130 spec->mode = canon_mode(mode);
1131 hashcpy(spec->sha1, sha1);
1132 spec->sha1_valid = !is_null_sha1(sha1);
1137 * Given a name and sha1 pair, if the dircache tells us the file in
1138 * the work tree has that object contents, return true, so that
1139 * prepare_temp_file() does not have to inflate and extract.
1141 static int work_tree_matches(const char *name, const unsigned char *sha1)
1143 struct cache_entry *ce;
1144 struct stat st;
1145 int pos, len;
1147 /* We do not read the cache ourselves here, because the
1148 * benchmark with my previous version that always reads cache
1149 * shows that it makes things worse for diff-tree comparing
1150 * two linux-2.6 kernel trees in an already checked out work
1151 * tree. This is because most diff-tree comparisons deal with
1152 * only a small number of files, while reading the cache is
1153 * expensive for a large project, and its cost outweighs the
1154 * savings we get by not inflating the object to a temporary
1155 * file. Practically, this code only helps when we are used
1156 * by diff-cache --cached, which does read the cache before
1157 * calling us.
1159 if (!active_cache)
1160 return 0;
1162 len = strlen(name);
1163 pos = cache_name_pos(name, len);
1164 if (pos < 0)
1165 return 0;
1166 ce = active_cache[pos];
1167 if ((lstat(name, &st) < 0) ||
1168 !S_ISREG(st.st_mode) || /* careful! */
1169 ce_match_stat(ce, &st, 0) ||
1170 hashcmp(sha1, ce->sha1))
1171 return 0;
1172 /* we return 1 only when we can stat, it is a regular file,
1173 * stat information matches, and sha1 recorded in the cache
1174 * matches. I.e. we know the file in the work tree really is
1175 * the same as the <name, sha1> pair.
1177 return 1;
1180 static struct sha1_size_cache {
1181 unsigned char sha1[20];
1182 unsigned long size;
1183 } **sha1_size_cache;
1184 static int sha1_size_cache_nr, sha1_size_cache_alloc;
1186 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
1187 int find_only,
1188 unsigned long size)
1190 int first, last;
1191 struct sha1_size_cache *e;
1193 first = 0;
1194 last = sha1_size_cache_nr;
1195 while (last > first) {
1196 int cmp, next = (last + first) >> 1;
1197 e = sha1_size_cache[next];
1198 cmp = hashcmp(e->sha1, sha1);
1199 if (!cmp)
1200 return e;
1201 if (cmp < 0) {
1202 last = next;
1203 continue;
1205 first = next+1;
1207 /* not found */
1208 if (find_only)
1209 return NULL;
1210 /* insert to make it at "first" */
1211 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
1212 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
1213 sha1_size_cache = xrealloc(sha1_size_cache,
1214 sha1_size_cache_alloc *
1215 sizeof(*sha1_size_cache));
1217 sha1_size_cache_nr++;
1218 if (first < sha1_size_cache_nr)
1219 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
1220 (sha1_size_cache_nr - first - 1) *
1221 sizeof(*sha1_size_cache));
1222 e = xmalloc(sizeof(struct sha1_size_cache));
1223 sha1_size_cache[first] = e;
1224 hashcpy(e->sha1, sha1);
1225 e->size = size;
1226 return e;
1230 * While doing rename detection and pickaxe operation, we may need to
1231 * grab the data for the blob (or file) for our own in-core comparison.
1232 * diff_filespec has data and size fields for this purpose.
1234 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1236 int err = 0;
1237 if (!DIFF_FILE_VALID(s))
1238 die("internal error: asking to populate invalid file.");
1239 if (S_ISDIR(s->mode))
1240 return -1;
1242 if (!use_size_cache)
1243 size_only = 0;
1245 if (s->data)
1246 return err;
1247 if (!s->sha1_valid ||
1248 work_tree_matches(s->path, s->sha1)) {
1249 struct stat st;
1250 int fd;
1251 if (lstat(s->path, &st) < 0) {
1252 if (errno == ENOENT) {
1253 err_empty:
1254 err = -1;
1255 empty:
1256 s->data = (char *)"";
1257 s->size = 0;
1258 return err;
1261 s->size = st.st_size;
1262 if (!s->size)
1263 goto empty;
1264 if (size_only)
1265 return 0;
1266 if (S_ISLNK(st.st_mode)) {
1267 int ret;
1268 s->data = xmalloc(s->size);
1269 s->should_free = 1;
1270 ret = readlink(s->path, s->data, s->size);
1271 if (ret < 0) {
1272 free(s->data);
1273 goto err_empty;
1275 return 0;
1277 fd = open(s->path, O_RDONLY);
1278 if (fd < 0)
1279 goto err_empty;
1280 s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1281 close(fd);
1282 if (s->data == MAP_FAILED)
1283 goto err_empty;
1284 s->should_munmap = 1;
1286 else {
1287 char type[20];
1288 struct sha1_size_cache *e;
1290 if (size_only) {
1291 e = locate_size_cache(s->sha1, 1, 0);
1292 if (e) {
1293 s->size = e->size;
1294 return 0;
1296 if (!sha1_object_info(s->sha1, type, &s->size))
1297 locate_size_cache(s->sha1, 0, s->size);
1299 else {
1300 s->data = read_sha1_file(s->sha1, type, &s->size);
1301 s->should_free = 1;
1304 return 0;
1307 void diff_free_filespec_data(struct diff_filespec *s)
1309 if (s->should_free)
1310 free(s->data);
1311 else if (s->should_munmap)
1312 munmap(s->data, s->size);
1313 s->should_free = s->should_munmap = 0;
1314 s->data = NULL;
1315 free(s->cnt_data);
1316 s->cnt_data = NULL;
1319 static void prep_temp_blob(struct diff_tempfile *temp,
1320 void *blob,
1321 unsigned long size,
1322 const unsigned char *sha1,
1323 int mode)
1325 int fd;
1327 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1328 if (fd < 0)
1329 die("unable to create temp-file");
1330 if (write(fd, blob, size) != size)
1331 die("unable to write temp-file");
1332 close(fd);
1333 temp->name = temp->tmp_path;
1334 strcpy(temp->hex, sha1_to_hex(sha1));
1335 temp->hex[40] = 0;
1336 sprintf(temp->mode, "%06o", mode);
1339 static void prepare_temp_file(const char *name,
1340 struct diff_tempfile *temp,
1341 struct diff_filespec *one)
1343 if (!DIFF_FILE_VALID(one)) {
1344 not_a_valid_file:
1345 /* A '-' entry produces this for file-2, and
1346 * a '+' entry produces this for file-1.
1348 temp->name = "/dev/null";
1349 strcpy(temp->hex, ".");
1350 strcpy(temp->mode, ".");
1351 return;
1354 if (!one->sha1_valid ||
1355 work_tree_matches(name, one->sha1)) {
1356 struct stat st;
1357 if (lstat(name, &st) < 0) {
1358 if (errno == ENOENT)
1359 goto not_a_valid_file;
1360 die("stat(%s): %s", name, strerror(errno));
1362 if (S_ISLNK(st.st_mode)) {
1363 int ret;
1364 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1365 if (sizeof(buf) <= st.st_size)
1366 die("symlink too long: %s", name);
1367 ret = readlink(name, buf, st.st_size);
1368 if (ret < 0)
1369 die("readlink(%s)", name);
1370 prep_temp_blob(temp, buf, st.st_size,
1371 (one->sha1_valid ?
1372 one->sha1 : null_sha1),
1373 (one->sha1_valid ?
1374 one->mode : S_IFLNK));
1376 else {
1377 /* we can borrow from the file in the work tree */
1378 temp->name = name;
1379 if (!one->sha1_valid)
1380 strcpy(temp->hex, sha1_to_hex(null_sha1));
1381 else
1382 strcpy(temp->hex, sha1_to_hex(one->sha1));
1383 /* Even though we may sometimes borrow the
1384 * contents from the work tree, we always want
1385 * one->mode. mode is trustworthy even when
1386 * !(one->sha1_valid), as long as
1387 * DIFF_FILE_VALID(one).
1389 sprintf(temp->mode, "%06o", one->mode);
1391 return;
1393 else {
1394 if (diff_populate_filespec(one, 0))
1395 die("cannot read data blob for %s", one->path);
1396 prep_temp_blob(temp, one->data, one->size,
1397 one->sha1, one->mode);
1401 static void remove_tempfile(void)
1403 int i;
1405 for (i = 0; i < 2; i++)
1406 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1407 unlink(diff_temp[i].name);
1408 diff_temp[i].name = NULL;
1412 static void remove_tempfile_on_signal(int signo)
1414 remove_tempfile();
1415 signal(SIGINT, SIG_DFL);
1416 raise(signo);
1419 static int spawn_prog(const char *pgm, const char **arg)
1421 pid_t pid;
1422 int status;
1424 fflush(NULL);
1425 pid = fork();
1426 if (pid < 0)
1427 die("unable to fork");
1428 if (!pid) {
1429 execvp(pgm, (char *const*) arg);
1430 exit(255);
1433 while (waitpid(pid, &status, 0) < 0) {
1434 if (errno == EINTR)
1435 continue;
1436 return -1;
1439 /* Earlier we did not check the exit status because
1440 * diff exits non-zero if files are different, and
1441 * we are not interested in knowing that. It was a
1442 * mistake which made it harder to quit a diff-*
1443 * session that uses the git-apply-patch-script as
1444 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1445 * should also exit non-zero only when it wants to
1446 * abort the entire diff-* session.
1448 if (WIFEXITED(status) && !WEXITSTATUS(status))
1449 return 0;
1450 return -1;
1453 /* An external diff command takes:
1455 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1456 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1459 static void run_external_diff(const char *pgm,
1460 const char *name,
1461 const char *other,
1462 struct diff_filespec *one,
1463 struct diff_filespec *two,
1464 const char *xfrm_msg,
1465 int complete_rewrite)
1467 const char *spawn_arg[10];
1468 struct diff_tempfile *temp = diff_temp;
1469 int retval;
1470 static int atexit_asked = 0;
1471 const char *othername;
1472 const char **arg = &spawn_arg[0];
1474 othername = (other? other : name);
1475 if (one && two) {
1476 prepare_temp_file(name, &temp[0], one);
1477 prepare_temp_file(othername, &temp[1], two);
1478 if (! atexit_asked &&
1479 (temp[0].name == temp[0].tmp_path ||
1480 temp[1].name == temp[1].tmp_path)) {
1481 atexit_asked = 1;
1482 atexit(remove_tempfile);
1484 signal(SIGINT, remove_tempfile_on_signal);
1487 if (one && two) {
1488 *arg++ = pgm;
1489 *arg++ = name;
1490 *arg++ = temp[0].name;
1491 *arg++ = temp[0].hex;
1492 *arg++ = temp[0].mode;
1493 *arg++ = temp[1].name;
1494 *arg++ = temp[1].hex;
1495 *arg++ = temp[1].mode;
1496 if (other) {
1497 *arg++ = other;
1498 *arg++ = xfrm_msg;
1500 } else {
1501 *arg++ = pgm;
1502 *arg++ = name;
1504 *arg = NULL;
1505 retval = spawn_prog(pgm, spawn_arg);
1506 remove_tempfile();
1507 if (retval) {
1508 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1509 exit(1);
1513 static void run_diff_cmd(const char *pgm,
1514 const char *name,
1515 const char *other,
1516 struct diff_filespec *one,
1517 struct diff_filespec *two,
1518 const char *xfrm_msg,
1519 struct diff_options *o,
1520 int complete_rewrite)
1522 if (pgm) {
1523 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1524 complete_rewrite);
1525 return;
1527 if (one && two)
1528 builtin_diff(name, other ? other : name,
1529 one, two, xfrm_msg, o, complete_rewrite);
1530 else
1531 printf("* Unmerged path %s\n", name);
1534 static void diff_fill_sha1_info(struct diff_filespec *one)
1536 if (DIFF_FILE_VALID(one)) {
1537 if (!one->sha1_valid) {
1538 struct stat st;
1539 if (lstat(one->path, &st) < 0)
1540 die("stat %s", one->path);
1541 if (index_path(one->sha1, one->path, &st, 0))
1542 die("cannot hash %s\n", one->path);
1545 else
1546 hashclr(one->sha1);
1549 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1551 const char *pgm = external_diff();
1552 char msg[PATH_MAX*2+300], *xfrm_msg;
1553 struct diff_filespec *one;
1554 struct diff_filespec *two;
1555 const char *name;
1556 const char *other;
1557 char *name_munged, *other_munged;
1558 int complete_rewrite = 0;
1559 int len;
1561 if (DIFF_PAIR_UNMERGED(p)) {
1562 /* unmerged */
1563 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1564 return;
1567 name = p->one->path;
1568 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1569 name_munged = quote_one(name);
1570 other_munged = quote_one(other);
1571 one = p->one; two = p->two;
1573 diff_fill_sha1_info(one);
1574 diff_fill_sha1_info(two);
1576 len = 0;
1577 switch (p->status) {
1578 case DIFF_STATUS_COPIED:
1579 len += snprintf(msg + len, sizeof(msg) - len,
1580 "similarity index %d%%\n"
1581 "copy from %s\n"
1582 "copy to %s\n",
1583 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1584 name_munged, other_munged);
1585 break;
1586 case DIFF_STATUS_RENAMED:
1587 len += snprintf(msg + len, sizeof(msg) - len,
1588 "similarity index %d%%\n"
1589 "rename from %s\n"
1590 "rename to %s\n",
1591 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1592 name_munged, other_munged);
1593 break;
1594 case DIFF_STATUS_MODIFIED:
1595 if (p->score) {
1596 len += snprintf(msg + len, sizeof(msg) - len,
1597 "dissimilarity index %d%%\n",
1598 (int)(0.5 + p->score *
1599 100.0/MAX_SCORE));
1600 complete_rewrite = 1;
1601 break;
1603 /* fallthru */
1604 default:
1605 /* nothing */
1609 if (hashcmp(one->sha1, two->sha1)) {
1610 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1612 if (o->binary) {
1613 mmfile_t mf;
1614 if ((!fill_mmfile(&mf, one) && mmfile_is_binary(&mf)) ||
1615 (!fill_mmfile(&mf, two) && mmfile_is_binary(&mf)))
1616 abbrev = 40;
1618 len += snprintf(msg + len, sizeof(msg) - len,
1619 "index %.*s..%.*s",
1620 abbrev, sha1_to_hex(one->sha1),
1621 abbrev, sha1_to_hex(two->sha1));
1622 if (one->mode == two->mode)
1623 len += snprintf(msg + len, sizeof(msg) - len,
1624 " %06o", one->mode);
1625 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1628 if (len)
1629 msg[--len] = 0;
1630 xfrm_msg = len ? msg : NULL;
1632 if (!pgm &&
1633 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1634 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1635 /* a filepair that changes between file and symlink
1636 * needs to be split into deletion and creation.
1638 struct diff_filespec *null = alloc_filespec(two->path);
1639 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1640 free(null);
1641 null = alloc_filespec(one->path);
1642 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1643 free(null);
1645 else
1646 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1647 complete_rewrite);
1649 free(name_munged);
1650 free(other_munged);
1653 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1654 struct diffstat_t *diffstat)
1656 const char *name;
1657 const char *other;
1658 int complete_rewrite = 0;
1660 if (DIFF_PAIR_UNMERGED(p)) {
1661 /* unmerged */
1662 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1663 return;
1666 name = p->one->path;
1667 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1669 diff_fill_sha1_info(p->one);
1670 diff_fill_sha1_info(p->two);
1672 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1673 complete_rewrite = 1;
1674 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1677 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1679 const char *name;
1680 const char *other;
1682 if (DIFF_PAIR_UNMERGED(p)) {
1683 /* unmerged */
1684 return;
1687 name = p->one->path;
1688 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1690 diff_fill_sha1_info(p->one);
1691 diff_fill_sha1_info(p->two);
1693 builtin_checkdiff(name, other, p->one, p->two);
1696 void diff_setup(struct diff_options *options)
1698 memset(options, 0, sizeof(*options));
1699 options->line_termination = '\n';
1700 options->break_opt = -1;
1701 options->rename_limit = -1;
1702 options->context = 3;
1703 options->msg_sep = "";
1705 options->change = diff_change;
1706 options->add_remove = diff_addremove;
1707 options->color_diff = diff_use_color_default;
1708 options->detect_rename = diff_detect_rename_default;
1711 int diff_setup_done(struct diff_options *options)
1713 int count = 0;
1715 if (options->output_format & DIFF_FORMAT_NAME)
1716 count++;
1717 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
1718 count++;
1719 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
1720 count++;
1721 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
1722 count++;
1723 if (count > 1)
1724 die("--name-only, --name-status, --check and -s are mutually exclusive");
1726 if (options->find_copies_harder)
1727 options->detect_rename = DIFF_DETECT_COPY;
1729 if (options->output_format & (DIFF_FORMAT_NAME |
1730 DIFF_FORMAT_NAME_STATUS |
1731 DIFF_FORMAT_CHECKDIFF |
1732 DIFF_FORMAT_NO_OUTPUT))
1733 options->output_format &= ~(DIFF_FORMAT_RAW |
1734 DIFF_FORMAT_DIFFSTAT |
1735 DIFF_FORMAT_SUMMARY |
1736 DIFF_FORMAT_PATCH);
1739 * These cases always need recursive; we do not drop caller-supplied
1740 * recursive bits for other formats here.
1742 if (options->output_format & (DIFF_FORMAT_PATCH |
1743 DIFF_FORMAT_DIFFSTAT |
1744 DIFF_FORMAT_CHECKDIFF))
1745 options->recursive = 1;
1747 * Also pickaxe would not work very well if you do not say recursive
1749 if (options->pickaxe)
1750 options->recursive = 1;
1752 if (options->detect_rename && options->rename_limit < 0)
1753 options->rename_limit = diff_rename_limit_default;
1754 if (options->setup & DIFF_SETUP_USE_CACHE) {
1755 if (!active_cache)
1756 /* read-cache does not die even when it fails
1757 * so it is safe for us to do this here. Also
1758 * it does not smudge active_cache or active_nr
1759 * when it fails, so we do not have to worry about
1760 * cleaning it up ourselves either.
1762 read_cache();
1764 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1765 use_size_cache = 1;
1766 if (options->abbrev <= 0 || 40 < options->abbrev)
1767 options->abbrev = 40; /* full */
1769 return 0;
1772 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1774 char c, *eq;
1775 int len;
1777 if (*arg != '-')
1778 return 0;
1779 c = *++arg;
1780 if (!c)
1781 return 0;
1782 if (c == arg_short) {
1783 c = *++arg;
1784 if (!c)
1785 return 1;
1786 if (val && isdigit(c)) {
1787 char *end;
1788 int n = strtoul(arg, &end, 10);
1789 if (*end)
1790 return 0;
1791 *val = n;
1792 return 1;
1794 return 0;
1796 if (c != '-')
1797 return 0;
1798 arg++;
1799 eq = strchr(arg, '=');
1800 if (eq)
1801 len = eq - arg;
1802 else
1803 len = strlen(arg);
1804 if (!len || strncmp(arg, arg_long, len))
1805 return 0;
1806 if (eq) {
1807 int n;
1808 char *end;
1809 if (!isdigit(*++eq))
1810 return 0;
1811 n = strtoul(eq, &end, 10);
1812 if (*end)
1813 return 0;
1814 *val = n;
1816 return 1;
1819 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1821 const char *arg = av[0];
1822 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1823 options->output_format |= DIFF_FORMAT_PATCH;
1824 else if (opt_arg(arg, 'U', "unified", &options->context))
1825 options->output_format |= DIFF_FORMAT_PATCH;
1826 else if (!strcmp(arg, "--raw"))
1827 options->output_format |= DIFF_FORMAT_RAW;
1828 else if (!strcmp(arg, "--patch-with-raw")) {
1829 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
1831 else if (!strncmp(arg, "--stat", 6)) {
1832 char *end;
1833 int width = options->stat_width;
1834 int name_width = options->stat_name_width;
1835 arg += 6;
1836 end = (char *)arg;
1838 switch (*arg) {
1839 case '-':
1840 if (!strncmp(arg, "-width=", 7))
1841 width = strtoul(arg + 7, &end, 10);
1842 else if (!strncmp(arg, "-name-width=", 12))
1843 name_width = strtoul(arg + 12, &end, 10);
1844 break;
1845 case '=':
1846 width = strtoul(arg+1, &end, 10);
1847 if (*end == ',')
1848 name_width = strtoul(end+1, &end, 10);
1851 /* Important! This checks all the error cases! */
1852 if (*end)
1853 return 0;
1854 options->output_format |= DIFF_FORMAT_DIFFSTAT;
1855 options->stat_name_width = name_width;
1856 options->stat_width = width;
1858 else if (!strcmp(arg, "--check"))
1859 options->output_format |= DIFF_FORMAT_CHECKDIFF;
1860 else if (!strcmp(arg, "--summary"))
1861 options->output_format |= DIFF_FORMAT_SUMMARY;
1862 else if (!strcmp(arg, "--patch-with-stat")) {
1863 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
1865 else if (!strcmp(arg, "-z"))
1866 options->line_termination = 0;
1867 else if (!strncmp(arg, "-l", 2))
1868 options->rename_limit = strtoul(arg+2, NULL, 10);
1869 else if (!strcmp(arg, "--full-index"))
1870 options->full_index = 1;
1871 else if (!strcmp(arg, "--binary")) {
1872 options->output_format |= DIFF_FORMAT_PATCH;
1873 options->binary = 1;
1875 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
1876 options->text = 1;
1878 else if (!strcmp(arg, "--name-only"))
1879 options->output_format |= DIFF_FORMAT_NAME;
1880 else if (!strcmp(arg, "--name-status"))
1881 options->output_format |= DIFF_FORMAT_NAME_STATUS;
1882 else if (!strcmp(arg, "-R"))
1883 options->reverse_diff = 1;
1884 else if (!strncmp(arg, "-S", 2))
1885 options->pickaxe = arg + 2;
1886 else if (!strcmp(arg, "-s")) {
1887 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
1889 else if (!strncmp(arg, "-O", 2))
1890 options->orderfile = arg + 2;
1891 else if (!strncmp(arg, "--diff-filter=", 14))
1892 options->filter = arg + 14;
1893 else if (!strcmp(arg, "--pickaxe-all"))
1894 options->pickaxe_opts = DIFF_PICKAXE_ALL;
1895 else if (!strcmp(arg, "--pickaxe-regex"))
1896 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
1897 else if (!strncmp(arg, "-B", 2)) {
1898 if ((options->break_opt =
1899 diff_scoreopt_parse(arg)) == -1)
1900 return -1;
1902 else if (!strncmp(arg, "-M", 2)) {
1903 if ((options->rename_score =
1904 diff_scoreopt_parse(arg)) == -1)
1905 return -1;
1906 options->detect_rename = DIFF_DETECT_RENAME;
1908 else if (!strncmp(arg, "-C", 2)) {
1909 if ((options->rename_score =
1910 diff_scoreopt_parse(arg)) == -1)
1911 return -1;
1912 options->detect_rename = DIFF_DETECT_COPY;
1914 else if (!strcmp(arg, "--find-copies-harder"))
1915 options->find_copies_harder = 1;
1916 else if (!strcmp(arg, "--abbrev"))
1917 options->abbrev = DEFAULT_ABBREV;
1918 else if (!strncmp(arg, "--abbrev=", 9)) {
1919 options->abbrev = strtoul(arg + 9, NULL, 10);
1920 if (options->abbrev < MINIMUM_ABBREV)
1921 options->abbrev = MINIMUM_ABBREV;
1922 else if (40 < options->abbrev)
1923 options->abbrev = 40;
1925 else if (!strcmp(arg, "--color"))
1926 options->color_diff = 1;
1927 else if (!strcmp(arg, "--no-color"))
1928 options->color_diff = 0;
1929 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
1930 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
1931 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
1932 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
1933 else if (!strcmp(arg, "--color-words"))
1934 options->color_diff = options->color_diff_words = 1;
1935 else if (!strcmp(arg, "--no-renames"))
1936 options->detect_rename = 0;
1937 else
1938 return 0;
1939 return 1;
1942 static int parse_num(const char **cp_p)
1944 unsigned long num, scale;
1945 int ch, dot;
1946 const char *cp = *cp_p;
1948 num = 0;
1949 scale = 1;
1950 dot = 0;
1951 for(;;) {
1952 ch = *cp;
1953 if ( !dot && ch == '.' ) {
1954 scale = 1;
1955 dot = 1;
1956 } else if ( ch == '%' ) {
1957 scale = dot ? scale*100 : 100;
1958 cp++; /* % is always at the end */
1959 break;
1960 } else if ( ch >= '0' && ch <= '9' ) {
1961 if ( scale < 100000 ) {
1962 scale *= 10;
1963 num = (num*10) + (ch-'0');
1965 } else {
1966 break;
1968 cp++;
1970 *cp_p = cp;
1972 /* user says num divided by scale and we say internally that
1973 * is MAX_SCORE * num / scale.
1975 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
1978 int diff_scoreopt_parse(const char *opt)
1980 int opt1, opt2, cmd;
1982 if (*opt++ != '-')
1983 return -1;
1984 cmd = *opt++;
1985 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
1986 return -1; /* that is not a -M, -C nor -B option */
1988 opt1 = parse_num(&opt);
1989 if (cmd != 'B')
1990 opt2 = 0;
1991 else {
1992 if (*opt == 0)
1993 opt2 = 0;
1994 else if (*opt != '/')
1995 return -1; /* we expect -B80/99 or -B80 */
1996 else {
1997 opt++;
1998 opt2 = parse_num(&opt);
2001 if (*opt != 0)
2002 return -1;
2003 return opt1 | (opt2 << 16);
2006 struct diff_queue_struct diff_queued_diff;
2008 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2010 if (queue->alloc <= queue->nr) {
2011 queue->alloc = alloc_nr(queue->alloc);
2012 queue->queue = xrealloc(queue->queue,
2013 sizeof(dp) * queue->alloc);
2015 queue->queue[queue->nr++] = dp;
2018 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2019 struct diff_filespec *one,
2020 struct diff_filespec *two)
2022 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2023 dp->one = one;
2024 dp->two = two;
2025 if (queue)
2026 diff_q(queue, dp);
2027 return dp;
2030 void diff_free_filepair(struct diff_filepair *p)
2032 diff_free_filespec_data(p->one);
2033 diff_free_filespec_data(p->two);
2034 free(p->one);
2035 free(p->two);
2036 free(p);
2039 /* This is different from find_unique_abbrev() in that
2040 * it stuffs the result with dots for alignment.
2042 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2044 int abblen;
2045 const char *abbrev;
2046 if (len == 40)
2047 return sha1_to_hex(sha1);
2049 abbrev = find_unique_abbrev(sha1, len);
2050 if (!abbrev)
2051 return sha1_to_hex(sha1);
2052 abblen = strlen(abbrev);
2053 if (abblen < 37) {
2054 static char hex[41];
2055 if (len < abblen && abblen <= len + 2)
2056 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2057 else
2058 sprintf(hex, "%s...", abbrev);
2059 return hex;
2061 return sha1_to_hex(sha1);
2064 static void diff_flush_raw(struct diff_filepair *p,
2065 struct diff_options *options)
2067 int two_paths;
2068 char status[10];
2069 int abbrev = options->abbrev;
2070 const char *path_one, *path_two;
2071 int inter_name_termination = '\t';
2072 int line_termination = options->line_termination;
2074 if (!line_termination)
2075 inter_name_termination = 0;
2077 path_one = p->one->path;
2078 path_two = p->two->path;
2079 if (line_termination) {
2080 path_one = quote_one(path_one);
2081 path_two = quote_one(path_two);
2084 if (p->score)
2085 sprintf(status, "%c%03d", p->status,
2086 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2087 else {
2088 status[0] = p->status;
2089 status[1] = 0;
2091 switch (p->status) {
2092 case DIFF_STATUS_COPIED:
2093 case DIFF_STATUS_RENAMED:
2094 two_paths = 1;
2095 break;
2096 case DIFF_STATUS_ADDED:
2097 case DIFF_STATUS_DELETED:
2098 two_paths = 0;
2099 break;
2100 default:
2101 two_paths = 0;
2102 break;
2104 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2105 printf(":%06o %06o %s ",
2106 p->one->mode, p->two->mode,
2107 diff_unique_abbrev(p->one->sha1, abbrev));
2108 printf("%s ",
2109 diff_unique_abbrev(p->two->sha1, abbrev));
2111 printf("%s%c%s", status, inter_name_termination, path_one);
2112 if (two_paths)
2113 printf("%c%s", inter_name_termination, path_two);
2114 putchar(line_termination);
2115 if (path_one != p->one->path)
2116 free((void*)path_one);
2117 if (path_two != p->two->path)
2118 free((void*)path_two);
2121 static void diff_flush_name(struct diff_filepair *p, int line_termination)
2123 char *path = p->two->path;
2125 if (line_termination)
2126 path = quote_one(p->two->path);
2127 printf("%s%c", path, line_termination);
2128 if (p->two->path != path)
2129 free(path);
2132 int diff_unmodified_pair(struct diff_filepair *p)
2134 /* This function is written stricter than necessary to support
2135 * the currently implemented transformers, but the idea is to
2136 * let transformers to produce diff_filepairs any way they want,
2137 * and filter and clean them up here before producing the output.
2139 struct diff_filespec *one, *two;
2141 if (DIFF_PAIR_UNMERGED(p))
2142 return 0; /* unmerged is interesting */
2144 one = p->one;
2145 two = p->two;
2147 /* deletion, addition, mode or type change
2148 * and rename are all interesting.
2150 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2151 DIFF_PAIR_MODE_CHANGED(p) ||
2152 strcmp(one->path, two->path))
2153 return 0;
2155 /* both are valid and point at the same path. that is, we are
2156 * dealing with a change.
2158 if (one->sha1_valid && two->sha1_valid &&
2159 !hashcmp(one->sha1, two->sha1))
2160 return 1; /* no change */
2161 if (!one->sha1_valid && !two->sha1_valid)
2162 return 1; /* both look at the same file on the filesystem. */
2163 return 0;
2166 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2168 if (diff_unmodified_pair(p))
2169 return;
2171 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2172 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2173 return; /* no tree diffs in patch format */
2175 run_diff(p, o);
2178 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2179 struct diffstat_t *diffstat)
2181 if (diff_unmodified_pair(p))
2182 return;
2184 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2185 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2186 return; /* no tree diffs in patch format */
2188 run_diffstat(p, o, diffstat);
2191 static void diff_flush_checkdiff(struct diff_filepair *p,
2192 struct diff_options *o)
2194 if (diff_unmodified_pair(p))
2195 return;
2197 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2198 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2199 return; /* no tree diffs in patch format */
2201 run_checkdiff(p, o);
2204 int diff_queue_is_empty(void)
2206 struct diff_queue_struct *q = &diff_queued_diff;
2207 int i;
2208 for (i = 0; i < q->nr; i++)
2209 if (!diff_unmodified_pair(q->queue[i]))
2210 return 0;
2211 return 1;
2214 #if DIFF_DEBUG
2215 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2217 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2218 x, one ? one : "",
2219 s->path,
2220 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2221 s->mode,
2222 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2223 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2224 x, one ? one : "",
2225 s->size, s->xfrm_flags);
2228 void diff_debug_filepair(const struct diff_filepair *p, int i)
2230 diff_debug_filespec(p->one, i, "one");
2231 diff_debug_filespec(p->two, i, "two");
2232 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2233 p->score, p->status ? p->status : '?',
2234 p->source_stays, p->broken_pair);
2237 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2239 int i;
2240 if (msg)
2241 fprintf(stderr, "%s\n", msg);
2242 fprintf(stderr, "q->nr = %d\n", q->nr);
2243 for (i = 0; i < q->nr; i++) {
2244 struct diff_filepair *p = q->queue[i];
2245 diff_debug_filepair(p, i);
2248 #endif
2250 static void diff_resolve_rename_copy(void)
2252 int i, j;
2253 struct diff_filepair *p, *pp;
2254 struct diff_queue_struct *q = &diff_queued_diff;
2256 diff_debug_queue("resolve-rename-copy", q);
2258 for (i = 0; i < q->nr; i++) {
2259 p = q->queue[i];
2260 p->status = 0; /* undecided */
2261 if (DIFF_PAIR_UNMERGED(p))
2262 p->status = DIFF_STATUS_UNMERGED;
2263 else if (!DIFF_FILE_VALID(p->one))
2264 p->status = DIFF_STATUS_ADDED;
2265 else if (!DIFF_FILE_VALID(p->two))
2266 p->status = DIFF_STATUS_DELETED;
2267 else if (DIFF_PAIR_TYPE_CHANGED(p))
2268 p->status = DIFF_STATUS_TYPE_CHANGED;
2270 /* from this point on, we are dealing with a pair
2271 * whose both sides are valid and of the same type, i.e.
2272 * either in-place edit or rename/copy edit.
2274 else if (DIFF_PAIR_RENAME(p)) {
2275 if (p->source_stays) {
2276 p->status = DIFF_STATUS_COPIED;
2277 continue;
2279 /* See if there is some other filepair that
2280 * copies from the same source as us. If so
2281 * we are a copy. Otherwise we are either a
2282 * copy if the path stays, or a rename if it
2283 * does not, but we already handled "stays" case.
2285 for (j = i + 1; j < q->nr; j++) {
2286 pp = q->queue[j];
2287 if (strcmp(pp->one->path, p->one->path))
2288 continue; /* not us */
2289 if (!DIFF_PAIR_RENAME(pp))
2290 continue; /* not a rename/copy */
2291 /* pp is a rename/copy from the same source */
2292 p->status = DIFF_STATUS_COPIED;
2293 break;
2295 if (!p->status)
2296 p->status = DIFF_STATUS_RENAMED;
2298 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2299 p->one->mode != p->two->mode)
2300 p->status = DIFF_STATUS_MODIFIED;
2301 else {
2302 /* This is a "no-change" entry and should not
2303 * happen anymore, but prepare for broken callers.
2305 error("feeding unmodified %s to diffcore",
2306 p->one->path);
2307 p->status = DIFF_STATUS_UNKNOWN;
2310 diff_debug_queue("resolve-rename-copy done", q);
2313 static int check_pair_status(struct diff_filepair *p)
2315 switch (p->status) {
2316 case DIFF_STATUS_UNKNOWN:
2317 return 0;
2318 case 0:
2319 die("internal error in diff-resolve-rename-copy");
2320 default:
2321 return 1;
2325 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2327 int fmt = opt->output_format;
2329 if (fmt & DIFF_FORMAT_CHECKDIFF)
2330 diff_flush_checkdiff(p, opt);
2331 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2332 diff_flush_raw(p, opt);
2333 else if (fmt & DIFF_FORMAT_NAME)
2334 diff_flush_name(p, opt->line_termination);
2337 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2339 if (fs->mode)
2340 printf(" %s mode %06o %s\n", newdelete, fs->mode, fs->path);
2341 else
2342 printf(" %s %s\n", newdelete, fs->path);
2346 static void show_mode_change(struct diff_filepair *p, int show_name)
2348 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2349 if (show_name)
2350 printf(" mode change %06o => %06o %s\n",
2351 p->one->mode, p->two->mode, p->two->path);
2352 else
2353 printf(" mode change %06o => %06o\n",
2354 p->one->mode, p->two->mode);
2358 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2360 const char *old, *new;
2362 /* Find common prefix */
2363 old = p->one->path;
2364 new = p->two->path;
2365 while (1) {
2366 const char *slash_old, *slash_new;
2367 slash_old = strchr(old, '/');
2368 slash_new = strchr(new, '/');
2369 if (!slash_old ||
2370 !slash_new ||
2371 slash_old - old != slash_new - new ||
2372 memcmp(old, new, slash_new - new))
2373 break;
2374 old = slash_old + 1;
2375 new = slash_new + 1;
2377 /* p->one->path thru old is the common prefix, and old and new
2378 * through the end of names are renames
2380 if (old != p->one->path)
2381 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2382 (int)(old - p->one->path), p->one->path,
2383 old, new, (int)(0.5 + p->score * 100.0/MAX_SCORE));
2384 else
2385 printf(" %s %s => %s (%d%%)\n", renamecopy,
2386 p->one->path, p->two->path,
2387 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2388 show_mode_change(p, 0);
2391 static void diff_summary(struct diff_filepair *p)
2393 switch(p->status) {
2394 case DIFF_STATUS_DELETED:
2395 show_file_mode_name("delete", p->one);
2396 break;
2397 case DIFF_STATUS_ADDED:
2398 show_file_mode_name("create", p->two);
2399 break;
2400 case DIFF_STATUS_COPIED:
2401 show_rename_copy("copy", p);
2402 break;
2403 case DIFF_STATUS_RENAMED:
2404 show_rename_copy("rename", p);
2405 break;
2406 default:
2407 if (p->score) {
2408 printf(" rewrite %s (%d%%)\n", p->two->path,
2409 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2410 show_mode_change(p, 0);
2411 } else show_mode_change(p, 1);
2412 break;
2416 struct patch_id_t {
2417 struct xdiff_emit_state xm;
2418 SHA_CTX *ctx;
2419 int patchlen;
2422 static int remove_space(char *line, int len)
2424 int i;
2425 char *dst = line;
2426 unsigned char c;
2428 for (i = 0; i < len; i++)
2429 if (!isspace((c = line[i])))
2430 *dst++ = c;
2432 return dst - line;
2435 static void patch_id_consume(void *priv, char *line, unsigned long len)
2437 struct patch_id_t *data = priv;
2438 int new_len;
2440 /* Ignore line numbers when computing the SHA1 of the patch */
2441 if (!strncmp(line, "@@ -", 4))
2442 return;
2444 new_len = remove_space(line, len);
2446 SHA1_Update(data->ctx, line, new_len);
2447 data->patchlen += new_len;
2450 /* returns 0 upon success, and writes result into sha1 */
2451 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2453 struct diff_queue_struct *q = &diff_queued_diff;
2454 int i;
2455 SHA_CTX ctx;
2456 struct patch_id_t data;
2457 char buffer[PATH_MAX * 4 + 20];
2459 SHA1_Init(&ctx);
2460 memset(&data, 0, sizeof(struct patch_id_t));
2461 data.ctx = &ctx;
2462 data.xm.consume = patch_id_consume;
2464 for (i = 0; i < q->nr; i++) {
2465 xpparam_t xpp;
2466 xdemitconf_t xecfg;
2467 xdemitcb_t ecb;
2468 mmfile_t mf1, mf2;
2469 struct diff_filepair *p = q->queue[i];
2470 int len1, len2;
2472 if (p->status == 0)
2473 return error("internal diff status error");
2474 if (p->status == DIFF_STATUS_UNKNOWN)
2475 continue;
2476 if (diff_unmodified_pair(p))
2477 continue;
2478 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2479 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2480 continue;
2481 if (DIFF_PAIR_UNMERGED(p))
2482 continue;
2484 diff_fill_sha1_info(p->one);
2485 diff_fill_sha1_info(p->two);
2486 if (fill_mmfile(&mf1, p->one) < 0 ||
2487 fill_mmfile(&mf2, p->two) < 0)
2488 return error("unable to read files to diff");
2490 /* Maybe hash p->two? into the patch id? */
2491 if (mmfile_is_binary(&mf2))
2492 continue;
2494 len1 = remove_space(p->one->path, strlen(p->one->path));
2495 len2 = remove_space(p->two->path, strlen(p->two->path));
2496 if (p->one->mode == 0)
2497 len1 = snprintf(buffer, sizeof(buffer),
2498 "diff--gita/%.*sb/%.*s"
2499 "newfilemode%06o"
2500 "---/dev/null"
2501 "+++b/%.*s",
2502 len1, p->one->path,
2503 len2, p->two->path,
2504 p->two->mode,
2505 len2, p->two->path);
2506 else if (p->two->mode == 0)
2507 len1 = snprintf(buffer, sizeof(buffer),
2508 "diff--gita/%.*sb/%.*s"
2509 "deletedfilemode%06o"
2510 "---a/%.*s"
2511 "+++/dev/null",
2512 len1, p->one->path,
2513 len2, p->two->path,
2514 p->one->mode,
2515 len1, p->one->path);
2516 else
2517 len1 = snprintf(buffer, sizeof(buffer),
2518 "diff--gita/%.*sb/%.*s"
2519 "---a/%.*s"
2520 "+++b/%.*s",
2521 len1, p->one->path,
2522 len2, p->two->path,
2523 len1, p->one->path,
2524 len2, p->two->path);
2525 SHA1_Update(&ctx, buffer, len1);
2527 xpp.flags = XDF_NEED_MINIMAL;
2528 xecfg.ctxlen = 3;
2529 xecfg.flags = XDL_EMIT_FUNCNAMES;
2530 ecb.outf = xdiff_outf;
2531 ecb.priv = &data;
2532 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2535 SHA1_Final(sha1, &ctx);
2536 return 0;
2539 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2541 struct diff_queue_struct *q = &diff_queued_diff;
2542 int i;
2543 int result = diff_get_patch_id(options, sha1);
2545 for (i = 0; i < q->nr; i++)
2546 diff_free_filepair(q->queue[i]);
2548 free(q->queue);
2549 q->queue = NULL;
2550 q->nr = q->alloc = 0;
2552 return result;
2555 static int is_summary_empty(const struct diff_queue_struct *q)
2557 int i;
2559 for (i = 0; i < q->nr; i++) {
2560 const struct diff_filepair *p = q->queue[i];
2562 switch (p->status) {
2563 case DIFF_STATUS_DELETED:
2564 case DIFF_STATUS_ADDED:
2565 case DIFF_STATUS_COPIED:
2566 case DIFF_STATUS_RENAMED:
2567 return 0;
2568 default:
2569 if (p->score)
2570 return 0;
2571 if (p->one->mode && p->two->mode &&
2572 p->one->mode != p->two->mode)
2573 return 0;
2574 break;
2577 return 1;
2580 void diff_flush(struct diff_options *options)
2582 struct diff_queue_struct *q = &diff_queued_diff;
2583 int i, output_format = options->output_format;
2584 int separator = 0;
2587 * Order: raw, stat, summary, patch
2588 * or: name/name-status/checkdiff (other bits clear)
2590 if (!q->nr)
2591 goto free_queue;
2593 if (output_format & (DIFF_FORMAT_RAW |
2594 DIFF_FORMAT_NAME |
2595 DIFF_FORMAT_NAME_STATUS |
2596 DIFF_FORMAT_CHECKDIFF)) {
2597 for (i = 0; i < q->nr; i++) {
2598 struct diff_filepair *p = q->queue[i];
2599 if (check_pair_status(p))
2600 flush_one_pair(p, options);
2602 separator++;
2605 if (output_format & DIFF_FORMAT_DIFFSTAT) {
2606 struct diffstat_t diffstat;
2608 memset(&diffstat, 0, sizeof(struct diffstat_t));
2609 diffstat.xm.consume = diffstat_consume;
2610 for (i = 0; i < q->nr; i++) {
2611 struct diff_filepair *p = q->queue[i];
2612 if (check_pair_status(p))
2613 diff_flush_stat(p, options, &diffstat);
2615 show_stats(&diffstat, options);
2616 separator++;
2619 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2620 for (i = 0; i < q->nr; i++)
2621 diff_summary(q->queue[i]);
2622 separator++;
2625 if (output_format & DIFF_FORMAT_PATCH) {
2626 if (separator) {
2627 if (options->stat_sep) {
2628 /* attach patch instead of inline */
2629 fputs(options->stat_sep, stdout);
2630 } else {
2631 putchar(options->line_termination);
2635 for (i = 0; i < q->nr; i++) {
2636 struct diff_filepair *p = q->queue[i];
2637 if (check_pair_status(p))
2638 diff_flush_patch(p, options);
2642 if (output_format & DIFF_FORMAT_CALLBACK)
2643 options->format_callback(q, options, options->format_callback_data);
2645 for (i = 0; i < q->nr; i++)
2646 diff_free_filepair(q->queue[i]);
2647 free_queue:
2648 free(q->queue);
2649 q->queue = NULL;
2650 q->nr = q->alloc = 0;
2653 static void diffcore_apply_filter(const char *filter)
2655 int i;
2656 struct diff_queue_struct *q = &diff_queued_diff;
2657 struct diff_queue_struct outq;
2658 outq.queue = NULL;
2659 outq.nr = outq.alloc = 0;
2661 if (!filter)
2662 return;
2664 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2665 int found;
2666 for (i = found = 0; !found && i < q->nr; i++) {
2667 struct diff_filepair *p = q->queue[i];
2668 if (((p->status == DIFF_STATUS_MODIFIED) &&
2669 ((p->score &&
2670 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2671 (!p->score &&
2672 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2673 ((p->status != DIFF_STATUS_MODIFIED) &&
2674 strchr(filter, p->status)))
2675 found++;
2677 if (found)
2678 return;
2680 /* otherwise we will clear the whole queue
2681 * by copying the empty outq at the end of this
2682 * function, but first clear the current entries
2683 * in the queue.
2685 for (i = 0; i < q->nr; i++)
2686 diff_free_filepair(q->queue[i]);
2688 else {
2689 /* Only the matching ones */
2690 for (i = 0; i < q->nr; i++) {
2691 struct diff_filepair *p = q->queue[i];
2693 if (((p->status == DIFF_STATUS_MODIFIED) &&
2694 ((p->score &&
2695 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2696 (!p->score &&
2697 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2698 ((p->status != DIFF_STATUS_MODIFIED) &&
2699 strchr(filter, p->status)))
2700 diff_q(&outq, p);
2701 else
2702 diff_free_filepair(p);
2705 free(q->queue);
2706 *q = outq;
2709 void diffcore_std(struct diff_options *options)
2711 if (options->break_opt != -1)
2712 diffcore_break(options->break_opt);
2713 if (options->detect_rename)
2714 diffcore_rename(options);
2715 if (options->break_opt != -1)
2716 diffcore_merge_broken();
2717 if (options->pickaxe)
2718 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2719 if (options->orderfile)
2720 diffcore_order(options->orderfile);
2721 diff_resolve_rename_copy();
2722 diffcore_apply_filter(options->filter);
2726 void diffcore_std_no_resolve(struct diff_options *options)
2728 if (options->pickaxe)
2729 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2730 if (options->orderfile)
2731 diffcore_order(options->orderfile);
2732 diffcore_apply_filter(options->filter);
2735 void diff_addremove(struct diff_options *options,
2736 int addremove, unsigned mode,
2737 const unsigned char *sha1,
2738 const char *base, const char *path)
2740 char concatpath[PATH_MAX];
2741 struct diff_filespec *one, *two;
2743 /* This may look odd, but it is a preparation for
2744 * feeding "there are unchanged files which should
2745 * not produce diffs, but when you are doing copy
2746 * detection you would need them, so here they are"
2747 * entries to the diff-core. They will be prefixed
2748 * with something like '=' or '*' (I haven't decided
2749 * which but should not make any difference).
2750 * Feeding the same new and old to diff_change()
2751 * also has the same effect.
2752 * Before the final output happens, they are pruned after
2753 * merged into rename/copy pairs as appropriate.
2755 if (options->reverse_diff)
2756 addremove = (addremove == '+' ? '-' :
2757 addremove == '-' ? '+' : addremove);
2759 if (!path) path = "";
2760 sprintf(concatpath, "%s%s", base, path);
2761 one = alloc_filespec(concatpath);
2762 two = alloc_filespec(concatpath);
2764 if (addremove != '+')
2765 fill_filespec(one, sha1, mode);
2766 if (addremove != '-')
2767 fill_filespec(two, sha1, mode);
2769 diff_queue(&diff_queued_diff, one, two);
2772 void diff_change(struct diff_options *options,
2773 unsigned old_mode, unsigned new_mode,
2774 const unsigned char *old_sha1,
2775 const unsigned char *new_sha1,
2776 const char *base, const char *path)
2778 char concatpath[PATH_MAX];
2779 struct diff_filespec *one, *two;
2781 if (options->reverse_diff) {
2782 unsigned tmp;
2783 const unsigned char *tmp_c;
2784 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2785 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2787 if (!path) path = "";
2788 sprintf(concatpath, "%s%s", base, path);
2789 one = alloc_filespec(concatpath);
2790 two = alloc_filespec(concatpath);
2791 fill_filespec(one, old_sha1, old_mode);
2792 fill_filespec(two, new_sha1, new_mode);
2794 diff_queue(&diff_queued_diff, one, two);
2797 void diff_unmerge(struct diff_options *options,
2798 const char *path)
2800 struct diff_filespec *one, *two;
2801 one = alloc_filespec(path);
2802 two = alloc_filespec(path);
2803 diff_queue(&diff_queued_diff, one, two);