Teach core.autocrlf to 'git apply'
[debian-git.git] / diff.c
blob561587cace6d94ce2d2c4653588bcba237555f37
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"
12 #ifdef NO_FAST_WORKING_DIRECTORY
13 #define FAST_WORKING_DIRECTORY 0
14 #else
15 #define FAST_WORKING_DIRECTORY 1
16 #endif
18 static int use_size_cache;
20 static int diff_detect_rename_default;
21 static int diff_rename_limit_default = -1;
22 static int diff_use_color_default;
24 static char diff_colors[][COLOR_MAXLEN] = {
25 "\033[m", /* reset */
26 "", /* PLAIN (normal) */
27 "\033[1m", /* METAINFO (bold) */
28 "\033[36m", /* FRAGINFO (cyan) */
29 "\033[31m", /* OLD (red) */
30 "\033[32m", /* NEW (green) */
31 "\033[33m", /* COMMIT (yellow) */
32 "\033[41m", /* WHITESPACE (red background) */
35 static int parse_diff_color_slot(const char *var, int ofs)
37 if (!strcasecmp(var+ofs, "plain"))
38 return DIFF_PLAIN;
39 if (!strcasecmp(var+ofs, "meta"))
40 return DIFF_METAINFO;
41 if (!strcasecmp(var+ofs, "frag"))
42 return DIFF_FRAGINFO;
43 if (!strcasecmp(var+ofs, "old"))
44 return DIFF_FILE_OLD;
45 if (!strcasecmp(var+ofs, "new"))
46 return DIFF_FILE_NEW;
47 if (!strcasecmp(var+ofs, "commit"))
48 return DIFF_COMMIT;
49 if (!strcasecmp(var+ofs, "whitespace"))
50 return DIFF_WHITESPACE;
51 die("bad config variable '%s'", var);
55 * These are to give UI layer defaults.
56 * The core-level commands such as git-diff-files should
57 * never be affected by the setting of diff.renames
58 * the user happens to have in the configuration file.
60 int git_diff_ui_config(const char *var, const char *value)
62 if (!strcmp(var, "diff.renamelimit")) {
63 diff_rename_limit_default = git_config_int(var, value);
64 return 0;
66 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
67 diff_use_color_default = git_config_colorbool(var, value);
68 return 0;
70 if (!strcmp(var, "diff.renames")) {
71 if (!value)
72 diff_detect_rename_default = DIFF_DETECT_RENAME;
73 else if (!strcasecmp(value, "copies") ||
74 !strcasecmp(value, "copy"))
75 diff_detect_rename_default = DIFF_DETECT_COPY;
76 else if (git_config_bool(var,value))
77 diff_detect_rename_default = DIFF_DETECT_RENAME;
78 return 0;
80 if (!strncmp(var, "diff.color.", 11) || !strncmp(var, "color.diff.", 11)) {
81 int slot = parse_diff_color_slot(var, 11);
82 color_parse(value, var, diff_colors[slot]);
83 return 0;
85 return git_default_config(var, value);
88 static char *quote_one(const char *str)
90 int needlen;
91 char *xp;
93 if (!str)
94 return NULL;
95 needlen = quote_c_style(str, NULL, NULL, 0);
96 if (!needlen)
97 return xstrdup(str);
98 xp = xmalloc(needlen + 1);
99 quote_c_style(str, xp, NULL, 0);
100 return xp;
103 static char *quote_two(const char *one, const char *two)
105 int need_one = quote_c_style(one, NULL, NULL, 1);
106 int need_two = quote_c_style(two, NULL, NULL, 1);
107 char *xp;
109 if (need_one + need_two) {
110 if (!need_one) need_one = strlen(one);
111 if (!need_two) need_one = strlen(two);
113 xp = xmalloc(need_one + need_two + 3);
114 xp[0] = '"';
115 quote_c_style(one, xp + 1, NULL, 1);
116 quote_c_style(two, xp + need_one + 1, NULL, 1);
117 strcpy(xp + need_one + need_two + 1, "\"");
118 return xp;
120 need_one = strlen(one);
121 need_two = strlen(two);
122 xp = xmalloc(need_one + need_two + 1);
123 strcpy(xp, one);
124 strcpy(xp + need_one, two);
125 return xp;
128 static const char *external_diff(void)
130 static const char *external_diff_cmd = NULL;
131 static int done_preparing = 0;
133 if (done_preparing)
134 return external_diff_cmd;
135 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
136 done_preparing = 1;
137 return external_diff_cmd;
140 #define TEMPFILE_PATH_LEN 50
142 static struct diff_tempfile {
143 const char *name; /* filename external diff should read from */
144 char hex[41];
145 char mode[10];
146 char tmp_path[TEMPFILE_PATH_LEN];
147 } diff_temp[2];
149 static int count_lines(const char *data, int size)
151 int count, ch, completely_empty = 1, nl_just_seen = 0;
152 count = 0;
153 while (0 < size--) {
154 ch = *data++;
155 if (ch == '\n') {
156 count++;
157 nl_just_seen = 1;
158 completely_empty = 0;
160 else {
161 nl_just_seen = 0;
162 completely_empty = 0;
165 if (completely_empty)
166 return 0;
167 if (!nl_just_seen)
168 count++; /* no trailing newline */
169 return count;
172 static void print_line_count(int count)
174 switch (count) {
175 case 0:
176 printf("0,0");
177 break;
178 case 1:
179 printf("1");
180 break;
181 default:
182 printf("1,%d", count);
183 break;
187 static void copy_file(int prefix, const char *data, int size)
189 int ch, nl_just_seen = 1;
190 while (0 < size--) {
191 ch = *data++;
192 if (nl_just_seen)
193 putchar(prefix);
194 putchar(ch);
195 if (ch == '\n')
196 nl_just_seen = 1;
197 else
198 nl_just_seen = 0;
200 if (!nl_just_seen)
201 printf("\n\\ No newline at end of file\n");
204 static void emit_rewrite_diff(const char *name_a,
205 const char *name_b,
206 struct diff_filespec *one,
207 struct diff_filespec *two)
209 int lc_a, lc_b;
210 diff_populate_filespec(one, 0);
211 diff_populate_filespec(two, 0);
212 lc_a = count_lines(one->data, one->size);
213 lc_b = count_lines(two->data, two->size);
214 printf("--- a/%s\n+++ b/%s\n@@ -", name_a, name_b);
215 print_line_count(lc_a);
216 printf(" +");
217 print_line_count(lc_b);
218 printf(" @@\n");
219 if (lc_a)
220 copy_file('-', one->data, one->size);
221 if (lc_b)
222 copy_file('+', two->data, two->size);
225 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
227 if (!DIFF_FILE_VALID(one)) {
228 mf->ptr = (char *)""; /* does not matter */
229 mf->size = 0;
230 return 0;
232 else if (diff_populate_filespec(one, 0))
233 return -1;
234 mf->ptr = one->data;
235 mf->size = one->size;
236 return 0;
239 struct diff_words_buffer {
240 mmfile_t text;
241 long alloc;
242 long current; /* output pointer */
243 int suppressed_newline;
246 static void diff_words_append(char *line, unsigned long len,
247 struct diff_words_buffer *buffer)
249 if (buffer->text.size + len > buffer->alloc) {
250 buffer->alloc = (buffer->text.size + len) * 3 / 2;
251 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
253 line++;
254 len--;
255 memcpy(buffer->text.ptr + buffer->text.size, line, len);
256 buffer->text.size += len;
259 struct diff_words_data {
260 struct xdiff_emit_state xm;
261 struct diff_words_buffer minus, plus;
264 static void print_word(struct diff_words_buffer *buffer, int len, int color,
265 int suppress_newline)
267 const char *ptr;
268 int eol = 0;
270 if (len == 0)
271 return;
273 ptr = buffer->text.ptr + buffer->current;
274 buffer->current += len;
276 if (ptr[len - 1] == '\n') {
277 eol = 1;
278 len--;
281 fputs(diff_get_color(1, color), stdout);
282 fwrite(ptr, len, 1, stdout);
283 fputs(diff_get_color(1, DIFF_RESET), stdout);
285 if (eol) {
286 if (suppress_newline)
287 buffer->suppressed_newline = 1;
288 else
289 putchar('\n');
293 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
295 struct diff_words_data *diff_words = priv;
297 if (diff_words->minus.suppressed_newline) {
298 if (line[0] != '+')
299 putchar('\n');
300 diff_words->minus.suppressed_newline = 0;
303 len--;
304 switch (line[0]) {
305 case '-':
306 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
307 break;
308 case '+':
309 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
310 break;
311 case ' ':
312 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
313 diff_words->minus.current += len;
314 break;
318 /* this executes the word diff on the accumulated buffers */
319 static void diff_words_show(struct diff_words_data *diff_words)
321 xpparam_t xpp;
322 xdemitconf_t xecfg;
323 xdemitcb_t ecb;
324 mmfile_t minus, plus;
325 int i;
327 minus.size = diff_words->minus.text.size;
328 minus.ptr = xmalloc(minus.size);
329 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
330 for (i = 0; i < minus.size; i++)
331 if (isspace(minus.ptr[i]))
332 minus.ptr[i] = '\n';
333 diff_words->minus.current = 0;
335 plus.size = diff_words->plus.text.size;
336 plus.ptr = xmalloc(plus.size);
337 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
338 for (i = 0; i < plus.size; i++)
339 if (isspace(plus.ptr[i]))
340 plus.ptr[i] = '\n';
341 diff_words->plus.current = 0;
343 xpp.flags = XDF_NEED_MINIMAL;
344 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
345 xecfg.flags = 0;
346 ecb.outf = xdiff_outf;
347 ecb.priv = diff_words;
348 diff_words->xm.consume = fn_out_diff_words_aux;
349 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
351 free(minus.ptr);
352 free(plus.ptr);
353 diff_words->minus.text.size = diff_words->plus.text.size = 0;
355 if (diff_words->minus.suppressed_newline) {
356 putchar('\n');
357 diff_words->minus.suppressed_newline = 0;
361 struct emit_callback {
362 struct xdiff_emit_state xm;
363 int nparents, color_diff;
364 const char **label_path;
365 struct diff_words_data *diff_words;
368 static void free_diff_words_data(struct emit_callback *ecbdata)
370 if (ecbdata->diff_words) {
371 /* flush buffers */
372 if (ecbdata->diff_words->minus.text.size ||
373 ecbdata->diff_words->plus.text.size)
374 diff_words_show(ecbdata->diff_words);
376 if (ecbdata->diff_words->minus.text.ptr)
377 free (ecbdata->diff_words->minus.text.ptr);
378 if (ecbdata->diff_words->plus.text.ptr)
379 free (ecbdata->diff_words->plus.text.ptr);
380 free(ecbdata->diff_words);
381 ecbdata->diff_words = NULL;
385 const char *diff_get_color(int diff_use_color, enum color_diff ix)
387 if (diff_use_color)
388 return diff_colors[ix];
389 return "";
392 static void emit_line(const char *set, const char *reset, const char *line, int len)
394 if (len > 0 && line[len-1] == '\n')
395 len--;
396 fputs(set, stdout);
397 fwrite(line, len, 1, stdout);
398 puts(reset);
401 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
403 int col0 = ecbdata->nparents;
404 int last_tab_in_indent = -1;
405 int last_space_in_indent = -1;
406 int i;
407 int tail = len;
408 int need_highlight_leading_space = 0;
409 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
410 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
412 if (!*ws) {
413 emit_line(set, reset, line, len);
414 return;
417 /* The line is a newly added line. Does it have funny leading
418 * whitespaces? In indent, SP should never precede a TAB.
420 for (i = col0; i < len; i++) {
421 if (line[i] == '\t') {
422 last_tab_in_indent = i;
423 if (0 <= last_space_in_indent)
424 need_highlight_leading_space = 1;
426 else if (line[i] == ' ')
427 last_space_in_indent = i;
428 else
429 break;
431 fputs(set, stdout);
432 fwrite(line, col0, 1, stdout);
433 fputs(reset, stdout);
434 if (((i == len) || line[i] == '\n') && i != col0) {
435 /* The whole line was indent */
436 emit_line(ws, reset, line + col0, len - col0);
437 return;
439 i = col0;
440 if (need_highlight_leading_space) {
441 while (i < last_tab_in_indent) {
442 if (line[i] == ' ') {
443 fputs(ws, stdout);
444 putchar(' ');
445 fputs(reset, stdout);
447 else
448 putchar(line[i]);
449 i++;
452 tail = len - 1;
453 if (line[tail] == '\n' && i < tail)
454 tail--;
455 while (i < tail) {
456 if (!isspace(line[tail]))
457 break;
458 tail--;
460 if ((i < tail && line[tail + 1] != '\n')) {
461 /* This has whitespace between tail+1..len */
462 fputs(set, stdout);
463 fwrite(line + i, tail - i + 1, 1, stdout);
464 fputs(reset, stdout);
465 emit_line(ws, reset, line + tail + 1, len - tail - 1);
467 else
468 emit_line(set, reset, line + i, len - i);
471 static void fn_out_consume(void *priv, char *line, unsigned long len)
473 int i;
474 int color;
475 struct emit_callback *ecbdata = priv;
476 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
477 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
479 if (ecbdata->label_path[0]) {
480 printf("%s--- %s%s\n", set, ecbdata->label_path[0], reset);
481 printf("%s+++ %s%s\n", set, ecbdata->label_path[1], reset);
482 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
485 /* This is not really necessary for now because
486 * this codepath only deals with two-way diffs.
488 for (i = 0; i < len && line[i] == '@'; i++)
490 if (2 <= i && i < len && line[i] == ' ') {
491 ecbdata->nparents = i - 1;
492 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
493 reset, line, len);
494 return;
497 if (len < ecbdata->nparents) {
498 set = reset;
499 emit_line(reset, reset, line, len);
500 return;
503 color = DIFF_PLAIN;
504 if (ecbdata->diff_words && ecbdata->nparents != 1)
505 /* fall back to normal diff */
506 free_diff_words_data(ecbdata);
507 if (ecbdata->diff_words) {
508 if (line[0] == '-') {
509 diff_words_append(line, len,
510 &ecbdata->diff_words->minus);
511 return;
512 } else if (line[0] == '+') {
513 diff_words_append(line, len,
514 &ecbdata->diff_words->plus);
515 return;
517 if (ecbdata->diff_words->minus.text.size ||
518 ecbdata->diff_words->plus.text.size)
519 diff_words_show(ecbdata->diff_words);
520 line++;
521 len--;
522 emit_line(set, reset, line, len);
523 return;
525 for (i = 0; i < ecbdata->nparents && len; i++) {
526 if (line[i] == '-')
527 color = DIFF_FILE_OLD;
528 else if (line[i] == '+')
529 color = DIFF_FILE_NEW;
532 if (color != DIFF_FILE_NEW) {
533 emit_line(diff_get_color(ecbdata->color_diff, color),
534 reset, line, len);
535 return;
537 emit_add_line(reset, ecbdata, line, len);
540 static char *pprint_rename(const char *a, const char *b)
542 const char *old = a;
543 const char *new = b;
544 char *name = NULL;
545 int pfx_length, sfx_length;
546 int len_a = strlen(a);
547 int len_b = strlen(b);
548 int qlen_a = quote_c_style(a, NULL, NULL, 0);
549 int qlen_b = quote_c_style(b, NULL, NULL, 0);
551 if (qlen_a || qlen_b) {
552 if (qlen_a) len_a = qlen_a;
553 if (qlen_b) len_b = qlen_b;
554 name = xmalloc( len_a + len_b + 5 );
555 if (qlen_a)
556 quote_c_style(a, name, NULL, 0);
557 else
558 memcpy(name, a, len_a);
559 memcpy(name + len_a, " => ", 4);
560 if (qlen_b)
561 quote_c_style(b, name + len_a + 4, NULL, 0);
562 else
563 memcpy(name + len_a + 4, b, len_b + 1);
564 return name;
567 /* Find common prefix */
568 pfx_length = 0;
569 while (*old && *new && *old == *new) {
570 if (*old == '/')
571 pfx_length = old - a + 1;
572 old++;
573 new++;
576 /* Find common suffix */
577 old = a + len_a;
578 new = b + len_b;
579 sfx_length = 0;
580 while (a <= old && b <= new && *old == *new) {
581 if (*old == '/')
582 sfx_length = len_a - (old - a);
583 old--;
584 new--;
588 * pfx{mid-a => mid-b}sfx
589 * {pfx-a => pfx-b}sfx
590 * pfx{sfx-a => sfx-b}
591 * name-a => name-b
593 if (pfx_length + sfx_length) {
594 int a_midlen = len_a - pfx_length - sfx_length;
595 int b_midlen = len_b - pfx_length - sfx_length;
596 if (a_midlen < 0) a_midlen = 0;
597 if (b_midlen < 0) b_midlen = 0;
599 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
600 sprintf(name, "%.*s{%.*s => %.*s}%s",
601 pfx_length, a,
602 a_midlen, a + pfx_length,
603 b_midlen, b + pfx_length,
604 a + len_a - sfx_length);
606 else {
607 name = xmalloc(len_a + len_b + 5);
608 sprintf(name, "%s => %s", a, b);
610 return name;
613 struct diffstat_t {
614 struct xdiff_emit_state xm;
616 int nr;
617 int alloc;
618 struct diffstat_file {
619 char *name;
620 unsigned is_unmerged:1;
621 unsigned is_binary:1;
622 unsigned is_renamed:1;
623 unsigned int added, deleted;
624 } **files;
627 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
628 const char *name_a,
629 const char *name_b)
631 struct diffstat_file *x;
632 x = xcalloc(sizeof (*x), 1);
633 if (diffstat->nr == diffstat->alloc) {
634 diffstat->alloc = alloc_nr(diffstat->alloc);
635 diffstat->files = xrealloc(diffstat->files,
636 diffstat->alloc * sizeof(x));
638 diffstat->files[diffstat->nr++] = x;
639 if (name_b) {
640 x->name = pprint_rename(name_a, name_b);
641 x->is_renamed = 1;
643 else
644 x->name = xstrdup(name_a);
645 return x;
648 static void diffstat_consume(void *priv, char *line, unsigned long len)
650 struct diffstat_t *diffstat = priv;
651 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
653 if (line[0] == '+')
654 x->added++;
655 else if (line[0] == '-')
656 x->deleted++;
659 const char mime_boundary_leader[] = "------------";
661 static int scale_linear(int it, int width, int max_change)
664 * make sure that at least one '-' is printed if there were deletions,
665 * and likewise for '+'.
667 if (max_change < 2)
668 return it;
669 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
672 static void show_name(const char *prefix, const char *name, int len,
673 const char *reset, const char *set)
675 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
678 static void show_graph(char ch, int cnt, const char *set, const char *reset)
680 if (cnt <= 0)
681 return;
682 printf("%s", set);
683 while (cnt--)
684 putchar(ch);
685 printf("%s", reset);
688 static void show_stats(struct diffstat_t* data, struct diff_options *options)
690 int i, len, add, del, total, adds = 0, dels = 0;
691 int max_change = 0, max_len = 0;
692 int total_files = data->nr;
693 int width, name_width;
694 const char *reset, *set, *add_c, *del_c;
696 if (data->nr == 0)
697 return;
699 width = options->stat_width ? options->stat_width : 80;
700 name_width = options->stat_name_width ? options->stat_name_width : 50;
702 /* Sanity: give at least 5 columns to the graph,
703 * but leave at least 10 columns for the name.
705 if (width < name_width + 15) {
706 if (name_width <= 25)
707 width = name_width + 15;
708 else
709 name_width = width - 15;
712 /* Find the longest filename and max number of changes */
713 reset = diff_get_color(options->color_diff, DIFF_RESET);
714 set = diff_get_color(options->color_diff, DIFF_PLAIN);
715 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
716 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
718 for (i = 0; i < data->nr; i++) {
719 struct diffstat_file *file = data->files[i];
720 int change = file->added + file->deleted;
722 if (!file->is_renamed) { /* renames are already quoted by pprint_rename */
723 len = quote_c_style(file->name, NULL, NULL, 0);
724 if (len) {
725 char *qname = xmalloc(len + 1);
726 quote_c_style(file->name, qname, NULL, 0);
727 free(file->name);
728 file->name = qname;
732 len = strlen(file->name);
733 if (max_len < len)
734 max_len = len;
736 if (file->is_binary || file->is_unmerged)
737 continue;
738 if (max_change < change)
739 max_change = change;
742 /* Compute the width of the graph part;
743 * 10 is for one blank at the beginning of the line plus
744 * " | count " between the name and the graph.
746 * From here on, name_width is the width of the name area,
747 * and width is the width of the graph area.
749 name_width = (name_width < max_len) ? name_width : max_len;
750 if (width < (name_width + 10) + max_change)
751 width = width - (name_width + 10);
752 else
753 width = max_change;
755 for (i = 0; i < data->nr; i++) {
756 const char *prefix = "";
757 char *name = data->files[i]->name;
758 int added = data->files[i]->added;
759 int deleted = data->files[i]->deleted;
760 int name_len;
763 * "scale" the filename
765 len = name_width;
766 name_len = strlen(name);
767 if (name_width < name_len) {
768 char *slash;
769 prefix = "...";
770 len -= 3;
771 name += name_len - len;
772 slash = strchr(name, '/');
773 if (slash)
774 name = slash;
777 if (data->files[i]->is_binary) {
778 show_name(prefix, name, len, reset, set);
779 printf(" Bin\n");
780 goto free_diffstat_file;
782 else if (data->files[i]->is_unmerged) {
783 show_name(prefix, name, len, reset, set);
784 printf(" Unmerged\n");
785 goto free_diffstat_file;
787 else if (!data->files[i]->is_renamed &&
788 (added + deleted == 0)) {
789 total_files--;
790 goto free_diffstat_file;
794 * scale the add/delete
796 add = added;
797 del = deleted;
798 total = add + del;
799 adds += add;
800 dels += del;
802 if (width <= max_change) {
803 add = scale_linear(add, width, max_change);
804 del = scale_linear(del, width, max_change);
805 total = add + del;
807 show_name(prefix, name, len, reset, set);
808 printf("%5d ", added + deleted);
809 show_graph('+', add, add_c, reset);
810 show_graph('-', del, del_c, reset);
811 putchar('\n');
812 free_diffstat_file:
813 free(data->files[i]->name);
814 free(data->files[i]);
816 free(data->files);
817 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
818 set, total_files, adds, dels, reset);
821 static void show_shortstats(struct diffstat_t* data)
823 int i, adds = 0, dels = 0, total_files = data->nr;
825 if (data->nr == 0)
826 return;
828 for (i = 0; i < data->nr; i++) {
829 if (!data->files[i]->is_binary &&
830 !data->files[i]->is_unmerged) {
831 int added = data->files[i]->added;
832 int deleted= data->files[i]->deleted;
833 if (!data->files[i]->is_renamed &&
834 (added + deleted == 0)) {
835 total_files--;
836 } else {
837 adds += added;
838 dels += deleted;
841 free(data->files[i]->name);
842 free(data->files[i]);
844 free(data->files);
846 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
847 total_files, adds, dels);
850 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
852 int i;
854 for (i = 0; i < data->nr; i++) {
855 struct diffstat_file *file = data->files[i];
857 if (file->is_binary)
858 printf("-\t-\t");
859 else
860 printf("%d\t%d\t", file->added, file->deleted);
861 if (options->line_termination && !file->is_renamed &&
862 quote_c_style(file->name, NULL, NULL, 0))
863 quote_c_style(file->name, NULL, stdout, 0);
864 else
865 fputs(file->name, stdout);
866 putchar(options->line_termination);
870 struct checkdiff_t {
871 struct xdiff_emit_state xm;
872 const char *filename;
873 int lineno;
876 static void checkdiff_consume(void *priv, char *line, unsigned long len)
878 struct checkdiff_t *data = priv;
880 if (line[0] == '+') {
881 int i, spaces = 0;
883 /* check space before tab */
884 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
885 if (line[i] == ' ')
886 spaces++;
887 if (line[i - 1] == '\t' && spaces)
888 printf("%s:%d: space before tab:%.*s\n",
889 data->filename, data->lineno, (int)len, line);
891 /* check white space at line end */
892 if (line[len - 1] == '\n')
893 len--;
894 if (isspace(line[len - 1]))
895 printf("%s:%d: white space at end: %.*s\n",
896 data->filename, data->lineno, (int)len, line);
898 data->lineno++;
899 } else if (line[0] == ' ')
900 data->lineno++;
901 else if (line[0] == '@') {
902 char *plus = strchr(line, '+');
903 if (plus)
904 data->lineno = strtol(plus, NULL, 10);
905 else
906 die("invalid diff");
910 static unsigned char *deflate_it(char *data,
911 unsigned long size,
912 unsigned long *result_size)
914 int bound;
915 unsigned char *deflated;
916 z_stream stream;
918 memset(&stream, 0, sizeof(stream));
919 deflateInit(&stream, zlib_compression_level);
920 bound = deflateBound(&stream, size);
921 deflated = xmalloc(bound);
922 stream.next_out = deflated;
923 stream.avail_out = bound;
925 stream.next_in = (unsigned char *)data;
926 stream.avail_in = size;
927 while (deflate(&stream, Z_FINISH) == Z_OK)
928 ; /* nothing */
929 deflateEnd(&stream);
930 *result_size = stream.total_out;
931 return deflated;
934 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
936 void *cp;
937 void *delta;
938 void *deflated;
939 void *data;
940 unsigned long orig_size;
941 unsigned long delta_size;
942 unsigned long deflate_size;
943 unsigned long data_size;
945 /* We could do deflated delta, or we could do just deflated two,
946 * whichever is smaller.
948 delta = NULL;
949 deflated = deflate_it(two->ptr, two->size, &deflate_size);
950 if (one->size && two->size) {
951 delta = diff_delta(one->ptr, one->size,
952 two->ptr, two->size,
953 &delta_size, deflate_size);
954 if (delta) {
955 void *to_free = delta;
956 orig_size = delta_size;
957 delta = deflate_it(delta, delta_size, &delta_size);
958 free(to_free);
962 if (delta && delta_size < deflate_size) {
963 printf("delta %lu\n", orig_size);
964 free(deflated);
965 data = delta;
966 data_size = delta_size;
968 else {
969 printf("literal %lu\n", two->size);
970 free(delta);
971 data = deflated;
972 data_size = deflate_size;
975 /* emit data encoded in base85 */
976 cp = data;
977 while (data_size) {
978 int bytes = (52 < data_size) ? 52 : data_size;
979 char line[70];
980 data_size -= bytes;
981 if (bytes <= 26)
982 line[0] = bytes + 'A' - 1;
983 else
984 line[0] = bytes - 26 + 'a' - 1;
985 encode_85(line + 1, cp, bytes);
986 cp = (char *) cp + bytes;
987 puts(line);
989 printf("\n");
990 free(data);
993 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
995 printf("GIT binary patch\n");
996 emit_binary_diff_body(one, two);
997 emit_binary_diff_body(two, one);
1000 #define FIRST_FEW_BYTES 8000
1001 static int mmfile_is_binary(mmfile_t *mf)
1003 long sz = mf->size;
1004 if (FIRST_FEW_BYTES < sz)
1005 sz = FIRST_FEW_BYTES;
1006 return !!memchr(mf->ptr, 0, sz);
1009 static void builtin_diff(const char *name_a,
1010 const char *name_b,
1011 struct diff_filespec *one,
1012 struct diff_filespec *two,
1013 const char *xfrm_msg,
1014 struct diff_options *o,
1015 int complete_rewrite)
1017 mmfile_t mf1, mf2;
1018 const char *lbl[2];
1019 char *a_one, *b_two;
1020 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1021 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1023 a_one = quote_two("a/", name_a);
1024 b_two = quote_two("b/", name_b);
1025 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1026 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1027 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1028 if (lbl[0][0] == '/') {
1029 /* /dev/null */
1030 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1031 if (xfrm_msg && xfrm_msg[0])
1032 printf("%s%s%s\n", set, xfrm_msg, reset);
1034 else if (lbl[1][0] == '/') {
1035 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1036 if (xfrm_msg && xfrm_msg[0])
1037 printf("%s%s%s\n", set, xfrm_msg, reset);
1039 else {
1040 if (one->mode != two->mode) {
1041 printf("%sold mode %06o%s\n", set, one->mode, reset);
1042 printf("%snew mode %06o%s\n", set, two->mode, reset);
1044 if (xfrm_msg && xfrm_msg[0])
1045 printf("%s%s%s\n", set, xfrm_msg, reset);
1047 * we do not run diff between different kind
1048 * of objects.
1050 if ((one->mode ^ two->mode) & S_IFMT)
1051 goto free_ab_and_return;
1052 if (complete_rewrite) {
1053 emit_rewrite_diff(name_a, name_b, one, two);
1054 goto free_ab_and_return;
1058 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1059 die("unable to read files to diff");
1061 if (!o->text && (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))) {
1062 /* Quite common confusing case */
1063 if (mf1.size == mf2.size &&
1064 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1065 goto free_ab_and_return;
1066 if (o->binary)
1067 emit_binary_diff(&mf1, &mf2);
1068 else
1069 printf("Binary files %s and %s differ\n",
1070 lbl[0], lbl[1]);
1072 else {
1073 /* Crazy xdl interfaces.. */
1074 const char *diffopts = getenv("GIT_DIFF_OPTS");
1075 xpparam_t xpp;
1076 xdemitconf_t xecfg;
1077 xdemitcb_t ecb;
1078 struct emit_callback ecbdata;
1080 memset(&ecbdata, 0, sizeof(ecbdata));
1081 ecbdata.label_path = lbl;
1082 ecbdata.color_diff = o->color_diff;
1083 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1084 xecfg.ctxlen = o->context;
1085 xecfg.flags = XDL_EMIT_FUNCNAMES;
1086 if (!diffopts)
1088 else if (!strncmp(diffopts, "--unified=", 10))
1089 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1090 else if (!strncmp(diffopts, "-u", 2))
1091 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1092 ecb.outf = xdiff_outf;
1093 ecb.priv = &ecbdata;
1094 ecbdata.xm.consume = fn_out_consume;
1095 if (o->color_diff_words)
1096 ecbdata.diff_words =
1097 xcalloc(1, sizeof(struct diff_words_data));
1098 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1099 if (o->color_diff_words)
1100 free_diff_words_data(&ecbdata);
1103 free_ab_and_return:
1104 free(a_one);
1105 free(b_two);
1106 return;
1109 static void builtin_diffstat(const char *name_a, const char *name_b,
1110 struct diff_filespec *one,
1111 struct diff_filespec *two,
1112 struct diffstat_t *diffstat,
1113 struct diff_options *o,
1114 int complete_rewrite)
1116 mmfile_t mf1, mf2;
1117 struct diffstat_file *data;
1119 data = diffstat_add(diffstat, name_a, name_b);
1121 if (!one || !two) {
1122 data->is_unmerged = 1;
1123 return;
1125 if (complete_rewrite) {
1126 diff_populate_filespec(one, 0);
1127 diff_populate_filespec(two, 0);
1128 data->deleted = count_lines(one->data, one->size);
1129 data->added = count_lines(two->data, two->size);
1130 return;
1132 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1133 die("unable to read files to diff");
1135 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
1136 data->is_binary = 1;
1137 else {
1138 /* Crazy xdl interfaces.. */
1139 xpparam_t xpp;
1140 xdemitconf_t xecfg;
1141 xdemitcb_t ecb;
1143 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1144 xecfg.ctxlen = 0;
1145 xecfg.flags = 0;
1146 ecb.outf = xdiff_outf;
1147 ecb.priv = diffstat;
1148 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1152 static void builtin_checkdiff(const char *name_a, const char *name_b,
1153 struct diff_filespec *one,
1154 struct diff_filespec *two)
1156 mmfile_t mf1, mf2;
1157 struct checkdiff_t data;
1159 if (!two)
1160 return;
1162 memset(&data, 0, sizeof(data));
1163 data.xm.consume = checkdiff_consume;
1164 data.filename = name_b ? name_b : name_a;
1165 data.lineno = 0;
1167 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1168 die("unable to read files to diff");
1170 if (mmfile_is_binary(&mf2))
1171 return;
1172 else {
1173 /* Crazy xdl interfaces.. */
1174 xpparam_t xpp;
1175 xdemitconf_t xecfg;
1176 xdemitcb_t ecb;
1178 xpp.flags = XDF_NEED_MINIMAL;
1179 xecfg.ctxlen = 0;
1180 xecfg.flags = 0;
1181 ecb.outf = xdiff_outf;
1182 ecb.priv = &data;
1183 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1187 struct diff_filespec *alloc_filespec(const char *path)
1189 int namelen = strlen(path);
1190 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1192 memset(spec, 0, sizeof(*spec));
1193 spec->path = (char *)(spec + 1);
1194 memcpy(spec->path, path, namelen+1);
1195 return spec;
1198 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1199 unsigned short mode)
1201 if (mode) {
1202 spec->mode = canon_mode(mode);
1203 hashcpy(spec->sha1, sha1);
1204 spec->sha1_valid = !is_null_sha1(sha1);
1209 * Given a name and sha1 pair, if the dircache tells us the file in
1210 * the work tree has that object contents, return true, so that
1211 * prepare_temp_file() does not have to inflate and extract.
1213 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1215 struct cache_entry *ce;
1216 struct stat st;
1217 int pos, len;
1219 /* We do not read the cache ourselves here, because the
1220 * benchmark with my previous version that always reads cache
1221 * shows that it makes things worse for diff-tree comparing
1222 * two linux-2.6 kernel trees in an already checked out work
1223 * tree. This is because most diff-tree comparisons deal with
1224 * only a small number of files, while reading the cache is
1225 * expensive for a large project, and its cost outweighs the
1226 * savings we get by not inflating the object to a temporary
1227 * file. Practically, this code only helps when we are used
1228 * by diff-cache --cached, which does read the cache before
1229 * calling us.
1231 if (!active_cache)
1232 return 0;
1234 /* We want to avoid the working directory if our caller
1235 * doesn't need the data in a normal file, this system
1236 * is rather slow with its stat/open/mmap/close syscalls,
1237 * and the object is contained in a pack file. The pack
1238 * is probably already open and will be faster to obtain
1239 * the data through than the working directory. Loose
1240 * objects however would tend to be slower as they need
1241 * to be individually opened and inflated.
1243 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1244 return 0;
1246 len = strlen(name);
1247 pos = cache_name_pos(name, len);
1248 if (pos < 0)
1249 return 0;
1250 ce = active_cache[pos];
1251 if ((lstat(name, &st) < 0) ||
1252 !S_ISREG(st.st_mode) || /* careful! */
1253 ce_match_stat(ce, &st, 0) ||
1254 hashcmp(sha1, ce->sha1))
1255 return 0;
1256 /* we return 1 only when we can stat, it is a regular file,
1257 * stat information matches, and sha1 recorded in the cache
1258 * matches. I.e. we know the file in the work tree really is
1259 * the same as the <name, sha1> pair.
1261 return 1;
1264 static struct sha1_size_cache {
1265 unsigned char sha1[20];
1266 unsigned long size;
1267 } **sha1_size_cache;
1268 static int sha1_size_cache_nr, sha1_size_cache_alloc;
1270 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
1271 int find_only,
1272 unsigned long size)
1274 int first, last;
1275 struct sha1_size_cache *e;
1277 first = 0;
1278 last = sha1_size_cache_nr;
1279 while (last > first) {
1280 int cmp, next = (last + first) >> 1;
1281 e = sha1_size_cache[next];
1282 cmp = hashcmp(e->sha1, sha1);
1283 if (!cmp)
1284 return e;
1285 if (cmp < 0) {
1286 last = next;
1287 continue;
1289 first = next+1;
1291 /* not found */
1292 if (find_only)
1293 return NULL;
1294 /* insert to make it at "first" */
1295 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
1296 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
1297 sha1_size_cache = xrealloc(sha1_size_cache,
1298 sha1_size_cache_alloc *
1299 sizeof(*sha1_size_cache));
1301 sha1_size_cache_nr++;
1302 if (first < sha1_size_cache_nr)
1303 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
1304 (sha1_size_cache_nr - first - 1) *
1305 sizeof(*sha1_size_cache));
1306 e = xmalloc(sizeof(struct sha1_size_cache));
1307 sha1_size_cache[first] = e;
1308 hashcpy(e->sha1, sha1);
1309 e->size = size;
1310 return e;
1314 * While doing rename detection and pickaxe operation, we may need to
1315 * grab the data for the blob (or file) for our own in-core comparison.
1316 * diff_filespec has data and size fields for this purpose.
1318 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1320 int err = 0;
1321 if (!DIFF_FILE_VALID(s))
1322 die("internal error: asking to populate invalid file.");
1323 if (S_ISDIR(s->mode))
1324 return -1;
1326 if (!use_size_cache)
1327 size_only = 0;
1329 if (s->data)
1330 return err;
1331 if (!s->sha1_valid ||
1332 reuse_worktree_file(s->path, s->sha1, 0)) {
1333 struct stat st;
1334 int fd;
1335 char *buf;
1336 unsigned long size;
1338 if (lstat(s->path, &st) < 0) {
1339 if (errno == ENOENT) {
1340 err_empty:
1341 err = -1;
1342 empty:
1343 s->data = (char *)"";
1344 s->size = 0;
1345 return err;
1348 s->size = st.st_size;
1349 if (!s->size)
1350 goto empty;
1351 if (size_only)
1352 return 0;
1353 if (S_ISLNK(st.st_mode)) {
1354 int ret;
1355 s->data = xmalloc(s->size);
1356 s->should_free = 1;
1357 ret = readlink(s->path, s->data, s->size);
1358 if (ret < 0) {
1359 free(s->data);
1360 goto err_empty;
1362 return 0;
1364 fd = open(s->path, O_RDONLY);
1365 if (fd < 0)
1366 goto err_empty;
1367 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1368 close(fd);
1369 s->should_munmap = 1;
1372 * Convert from working tree format to canonical git format
1374 buf = s->data;
1375 size = s->size;
1376 if (convert_to_git(s->path, &buf, &size)) {
1377 munmap(s->data, s->size);
1378 s->should_munmap = 0;
1379 s->data = buf;
1380 s->size = size;
1381 s->should_free = 1;
1384 else {
1385 char type[20];
1386 struct sha1_size_cache *e;
1388 if (size_only) {
1389 e = locate_size_cache(s->sha1, 1, 0);
1390 if (e) {
1391 s->size = e->size;
1392 return 0;
1394 if (!sha1_object_info(s->sha1, type, &s->size))
1395 locate_size_cache(s->sha1, 0, s->size);
1397 else {
1398 s->data = read_sha1_file(s->sha1, type, &s->size);
1399 s->should_free = 1;
1402 return 0;
1405 void diff_free_filespec_data(struct diff_filespec *s)
1407 if (s->should_free)
1408 free(s->data);
1409 else if (s->should_munmap)
1410 munmap(s->data, s->size);
1411 s->should_free = s->should_munmap = 0;
1412 s->data = NULL;
1413 free(s->cnt_data);
1414 s->cnt_data = NULL;
1417 static void prep_temp_blob(struct diff_tempfile *temp,
1418 void *blob,
1419 unsigned long size,
1420 const unsigned char *sha1,
1421 int mode)
1423 int fd;
1425 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1426 if (fd < 0)
1427 die("unable to create temp-file");
1428 if (write_in_full(fd, blob, size) != size)
1429 die("unable to write temp-file");
1430 close(fd);
1431 temp->name = temp->tmp_path;
1432 strcpy(temp->hex, sha1_to_hex(sha1));
1433 temp->hex[40] = 0;
1434 sprintf(temp->mode, "%06o", mode);
1437 static void prepare_temp_file(const char *name,
1438 struct diff_tempfile *temp,
1439 struct diff_filespec *one)
1441 if (!DIFF_FILE_VALID(one)) {
1442 not_a_valid_file:
1443 /* A '-' entry produces this for file-2, and
1444 * a '+' entry produces this for file-1.
1446 temp->name = "/dev/null";
1447 strcpy(temp->hex, ".");
1448 strcpy(temp->mode, ".");
1449 return;
1452 if (!one->sha1_valid ||
1453 reuse_worktree_file(name, one->sha1, 1)) {
1454 struct stat st;
1455 if (lstat(name, &st) < 0) {
1456 if (errno == ENOENT)
1457 goto not_a_valid_file;
1458 die("stat(%s): %s", name, strerror(errno));
1460 if (S_ISLNK(st.st_mode)) {
1461 int ret;
1462 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1463 if (sizeof(buf) <= st.st_size)
1464 die("symlink too long: %s", name);
1465 ret = readlink(name, buf, st.st_size);
1466 if (ret < 0)
1467 die("readlink(%s)", name);
1468 prep_temp_blob(temp, buf, st.st_size,
1469 (one->sha1_valid ?
1470 one->sha1 : null_sha1),
1471 (one->sha1_valid ?
1472 one->mode : S_IFLNK));
1474 else {
1475 /* we can borrow from the file in the work tree */
1476 temp->name = name;
1477 if (!one->sha1_valid)
1478 strcpy(temp->hex, sha1_to_hex(null_sha1));
1479 else
1480 strcpy(temp->hex, sha1_to_hex(one->sha1));
1481 /* Even though we may sometimes borrow the
1482 * contents from the work tree, we always want
1483 * one->mode. mode is trustworthy even when
1484 * !(one->sha1_valid), as long as
1485 * DIFF_FILE_VALID(one).
1487 sprintf(temp->mode, "%06o", one->mode);
1489 return;
1491 else {
1492 if (diff_populate_filespec(one, 0))
1493 die("cannot read data blob for %s", one->path);
1494 prep_temp_blob(temp, one->data, one->size,
1495 one->sha1, one->mode);
1499 static void remove_tempfile(void)
1501 int i;
1503 for (i = 0; i < 2; i++)
1504 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1505 unlink(diff_temp[i].name);
1506 diff_temp[i].name = NULL;
1510 static void remove_tempfile_on_signal(int signo)
1512 remove_tempfile();
1513 signal(SIGINT, SIG_DFL);
1514 raise(signo);
1517 static int spawn_prog(const char *pgm, const char **arg)
1519 pid_t pid;
1520 int status;
1522 fflush(NULL);
1523 pid = fork();
1524 if (pid < 0)
1525 die("unable to fork");
1526 if (!pid) {
1527 execvp(pgm, (char *const*) arg);
1528 exit(255);
1531 while (waitpid(pid, &status, 0) < 0) {
1532 if (errno == EINTR)
1533 continue;
1534 return -1;
1537 /* Earlier we did not check the exit status because
1538 * diff exits non-zero if files are different, and
1539 * we are not interested in knowing that. It was a
1540 * mistake which made it harder to quit a diff-*
1541 * session that uses the git-apply-patch-script as
1542 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1543 * should also exit non-zero only when it wants to
1544 * abort the entire diff-* session.
1546 if (WIFEXITED(status) && !WEXITSTATUS(status))
1547 return 0;
1548 return -1;
1551 /* An external diff command takes:
1553 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1554 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1557 static void run_external_diff(const char *pgm,
1558 const char *name,
1559 const char *other,
1560 struct diff_filespec *one,
1561 struct diff_filespec *two,
1562 const char *xfrm_msg,
1563 int complete_rewrite)
1565 const char *spawn_arg[10];
1566 struct diff_tempfile *temp = diff_temp;
1567 int retval;
1568 static int atexit_asked = 0;
1569 const char *othername;
1570 const char **arg = &spawn_arg[0];
1572 othername = (other? other : name);
1573 if (one && two) {
1574 prepare_temp_file(name, &temp[0], one);
1575 prepare_temp_file(othername, &temp[1], two);
1576 if (! atexit_asked &&
1577 (temp[0].name == temp[0].tmp_path ||
1578 temp[1].name == temp[1].tmp_path)) {
1579 atexit_asked = 1;
1580 atexit(remove_tempfile);
1582 signal(SIGINT, remove_tempfile_on_signal);
1585 if (one && two) {
1586 *arg++ = pgm;
1587 *arg++ = name;
1588 *arg++ = temp[0].name;
1589 *arg++ = temp[0].hex;
1590 *arg++ = temp[0].mode;
1591 *arg++ = temp[1].name;
1592 *arg++ = temp[1].hex;
1593 *arg++ = temp[1].mode;
1594 if (other) {
1595 *arg++ = other;
1596 *arg++ = xfrm_msg;
1598 } else {
1599 *arg++ = pgm;
1600 *arg++ = name;
1602 *arg = NULL;
1603 retval = spawn_prog(pgm, spawn_arg);
1604 remove_tempfile();
1605 if (retval) {
1606 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1607 exit(1);
1611 static void run_diff_cmd(const char *pgm,
1612 const char *name,
1613 const char *other,
1614 struct diff_filespec *one,
1615 struct diff_filespec *two,
1616 const char *xfrm_msg,
1617 struct diff_options *o,
1618 int complete_rewrite)
1620 if (pgm) {
1621 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1622 complete_rewrite);
1623 return;
1625 if (one && two)
1626 builtin_diff(name, other ? other : name,
1627 one, two, xfrm_msg, o, complete_rewrite);
1628 else
1629 printf("* Unmerged path %s\n", name);
1632 static void diff_fill_sha1_info(struct diff_filespec *one)
1634 if (DIFF_FILE_VALID(one)) {
1635 if (!one->sha1_valid) {
1636 struct stat st;
1637 if (lstat(one->path, &st) < 0)
1638 die("stat %s", one->path);
1639 if (index_path(one->sha1, one->path, &st, 0))
1640 die("cannot hash %s\n", one->path);
1643 else
1644 hashclr(one->sha1);
1647 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1649 const char *pgm = external_diff();
1650 char msg[PATH_MAX*2+300], *xfrm_msg;
1651 struct diff_filespec *one;
1652 struct diff_filespec *two;
1653 const char *name;
1654 const char *other;
1655 char *name_munged, *other_munged;
1656 int complete_rewrite = 0;
1657 int len;
1659 if (DIFF_PAIR_UNMERGED(p)) {
1660 /* unmerged */
1661 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1662 return;
1665 name = p->one->path;
1666 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1667 name_munged = quote_one(name);
1668 other_munged = quote_one(other);
1669 one = p->one; two = p->two;
1671 diff_fill_sha1_info(one);
1672 diff_fill_sha1_info(two);
1674 len = 0;
1675 switch (p->status) {
1676 case DIFF_STATUS_COPIED:
1677 len += snprintf(msg + len, sizeof(msg) - len,
1678 "similarity index %d%%\n"
1679 "copy from %s\n"
1680 "copy to %s\n",
1681 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1682 name_munged, other_munged);
1683 break;
1684 case DIFF_STATUS_RENAMED:
1685 len += snprintf(msg + len, sizeof(msg) - len,
1686 "similarity index %d%%\n"
1687 "rename from %s\n"
1688 "rename to %s\n",
1689 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1690 name_munged, other_munged);
1691 break;
1692 case DIFF_STATUS_MODIFIED:
1693 if (p->score) {
1694 len += snprintf(msg + len, sizeof(msg) - len,
1695 "dissimilarity index %d%%\n",
1696 (int)(0.5 + p->score *
1697 100.0/MAX_SCORE));
1698 complete_rewrite = 1;
1699 break;
1701 /* fallthru */
1702 default:
1703 /* nothing */
1707 if (hashcmp(one->sha1, two->sha1)) {
1708 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1710 if (o->binary) {
1711 mmfile_t mf;
1712 if ((!fill_mmfile(&mf, one) && mmfile_is_binary(&mf)) ||
1713 (!fill_mmfile(&mf, two) && mmfile_is_binary(&mf)))
1714 abbrev = 40;
1716 len += snprintf(msg + len, sizeof(msg) - len,
1717 "index %.*s..%.*s",
1718 abbrev, sha1_to_hex(one->sha1),
1719 abbrev, sha1_to_hex(two->sha1));
1720 if (one->mode == two->mode)
1721 len += snprintf(msg + len, sizeof(msg) - len,
1722 " %06o", one->mode);
1723 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1726 if (len)
1727 msg[--len] = 0;
1728 xfrm_msg = len ? msg : NULL;
1730 if (!pgm &&
1731 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1732 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1733 /* a filepair that changes between file and symlink
1734 * needs to be split into deletion and creation.
1736 struct diff_filespec *null = alloc_filespec(two->path);
1737 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1738 free(null);
1739 null = alloc_filespec(one->path);
1740 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1741 free(null);
1743 else
1744 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1745 complete_rewrite);
1747 free(name_munged);
1748 free(other_munged);
1751 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1752 struct diffstat_t *diffstat)
1754 const char *name;
1755 const char *other;
1756 int complete_rewrite = 0;
1758 if (DIFF_PAIR_UNMERGED(p)) {
1759 /* unmerged */
1760 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1761 return;
1764 name = p->one->path;
1765 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1767 diff_fill_sha1_info(p->one);
1768 diff_fill_sha1_info(p->two);
1770 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1771 complete_rewrite = 1;
1772 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1775 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1777 const char *name;
1778 const char *other;
1780 if (DIFF_PAIR_UNMERGED(p)) {
1781 /* unmerged */
1782 return;
1785 name = p->one->path;
1786 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1788 diff_fill_sha1_info(p->one);
1789 diff_fill_sha1_info(p->two);
1791 builtin_checkdiff(name, other, p->one, p->two);
1794 void diff_setup(struct diff_options *options)
1796 memset(options, 0, sizeof(*options));
1797 options->line_termination = '\n';
1798 options->break_opt = -1;
1799 options->rename_limit = -1;
1800 options->context = 3;
1801 options->msg_sep = "";
1803 options->change = diff_change;
1804 options->add_remove = diff_addremove;
1805 options->color_diff = diff_use_color_default;
1806 options->detect_rename = diff_detect_rename_default;
1809 int diff_setup_done(struct diff_options *options)
1811 int count = 0;
1813 if (options->output_format & DIFF_FORMAT_NAME)
1814 count++;
1815 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
1816 count++;
1817 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
1818 count++;
1819 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
1820 count++;
1821 if (count > 1)
1822 die("--name-only, --name-status, --check and -s are mutually exclusive");
1824 if (options->find_copies_harder)
1825 options->detect_rename = DIFF_DETECT_COPY;
1827 if (options->output_format & (DIFF_FORMAT_NAME |
1828 DIFF_FORMAT_NAME_STATUS |
1829 DIFF_FORMAT_CHECKDIFF |
1830 DIFF_FORMAT_NO_OUTPUT))
1831 options->output_format &= ~(DIFF_FORMAT_RAW |
1832 DIFF_FORMAT_NUMSTAT |
1833 DIFF_FORMAT_DIFFSTAT |
1834 DIFF_FORMAT_SHORTSTAT |
1835 DIFF_FORMAT_SUMMARY |
1836 DIFF_FORMAT_PATCH);
1839 * These cases always need recursive; we do not drop caller-supplied
1840 * recursive bits for other formats here.
1842 if (options->output_format & (DIFF_FORMAT_PATCH |
1843 DIFF_FORMAT_NUMSTAT |
1844 DIFF_FORMAT_DIFFSTAT |
1845 DIFF_FORMAT_SHORTSTAT |
1846 DIFF_FORMAT_SUMMARY |
1847 DIFF_FORMAT_CHECKDIFF))
1848 options->recursive = 1;
1850 * Also pickaxe would not work very well if you do not say recursive
1852 if (options->pickaxe)
1853 options->recursive = 1;
1855 if (options->detect_rename && options->rename_limit < 0)
1856 options->rename_limit = diff_rename_limit_default;
1857 if (options->setup & DIFF_SETUP_USE_CACHE) {
1858 if (!active_cache)
1859 /* read-cache does not die even when it fails
1860 * so it is safe for us to do this here. Also
1861 * it does not smudge active_cache or active_nr
1862 * when it fails, so we do not have to worry about
1863 * cleaning it up ourselves either.
1865 read_cache();
1867 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1868 use_size_cache = 1;
1869 if (options->abbrev <= 0 || 40 < options->abbrev)
1870 options->abbrev = 40; /* full */
1872 return 0;
1875 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1877 char c, *eq;
1878 int len;
1880 if (*arg != '-')
1881 return 0;
1882 c = *++arg;
1883 if (!c)
1884 return 0;
1885 if (c == arg_short) {
1886 c = *++arg;
1887 if (!c)
1888 return 1;
1889 if (val && isdigit(c)) {
1890 char *end;
1891 int n = strtoul(arg, &end, 10);
1892 if (*end)
1893 return 0;
1894 *val = n;
1895 return 1;
1897 return 0;
1899 if (c != '-')
1900 return 0;
1901 arg++;
1902 eq = strchr(arg, '=');
1903 if (eq)
1904 len = eq - arg;
1905 else
1906 len = strlen(arg);
1907 if (!len || strncmp(arg, arg_long, len))
1908 return 0;
1909 if (eq) {
1910 int n;
1911 char *end;
1912 if (!isdigit(*++eq))
1913 return 0;
1914 n = strtoul(eq, &end, 10);
1915 if (*end)
1916 return 0;
1917 *val = n;
1919 return 1;
1922 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1924 const char *arg = av[0];
1925 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1926 options->output_format |= DIFF_FORMAT_PATCH;
1927 else if (opt_arg(arg, 'U', "unified", &options->context))
1928 options->output_format |= DIFF_FORMAT_PATCH;
1929 else if (!strcmp(arg, "--raw"))
1930 options->output_format |= DIFF_FORMAT_RAW;
1931 else if (!strcmp(arg, "--patch-with-raw")) {
1932 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
1934 else if (!strcmp(arg, "--numstat")) {
1935 options->output_format |= DIFF_FORMAT_NUMSTAT;
1937 else if (!strcmp(arg, "--shortstat")) {
1938 options->output_format |= DIFF_FORMAT_SHORTSTAT;
1940 else if (!strncmp(arg, "--stat", 6)) {
1941 char *end;
1942 int width = options->stat_width;
1943 int name_width = options->stat_name_width;
1944 arg += 6;
1945 end = (char *)arg;
1947 switch (*arg) {
1948 case '-':
1949 if (!strncmp(arg, "-width=", 7))
1950 width = strtoul(arg + 7, &end, 10);
1951 else if (!strncmp(arg, "-name-width=", 12))
1952 name_width = strtoul(arg + 12, &end, 10);
1953 break;
1954 case '=':
1955 width = strtoul(arg+1, &end, 10);
1956 if (*end == ',')
1957 name_width = strtoul(end+1, &end, 10);
1960 /* Important! This checks all the error cases! */
1961 if (*end)
1962 return 0;
1963 options->output_format |= DIFF_FORMAT_DIFFSTAT;
1964 options->stat_name_width = name_width;
1965 options->stat_width = width;
1967 else if (!strcmp(arg, "--check"))
1968 options->output_format |= DIFF_FORMAT_CHECKDIFF;
1969 else if (!strcmp(arg, "--summary"))
1970 options->output_format |= DIFF_FORMAT_SUMMARY;
1971 else if (!strcmp(arg, "--patch-with-stat")) {
1972 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
1974 else if (!strcmp(arg, "-z"))
1975 options->line_termination = 0;
1976 else if (!strncmp(arg, "-l", 2))
1977 options->rename_limit = strtoul(arg+2, NULL, 10);
1978 else if (!strcmp(arg, "--full-index"))
1979 options->full_index = 1;
1980 else if (!strcmp(arg, "--binary")) {
1981 options->output_format |= DIFF_FORMAT_PATCH;
1982 options->binary = 1;
1984 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
1985 options->text = 1;
1987 else if (!strcmp(arg, "--name-only"))
1988 options->output_format |= DIFF_FORMAT_NAME;
1989 else if (!strcmp(arg, "--name-status"))
1990 options->output_format |= DIFF_FORMAT_NAME_STATUS;
1991 else if (!strcmp(arg, "-R"))
1992 options->reverse_diff = 1;
1993 else if (!strncmp(arg, "-S", 2))
1994 options->pickaxe = arg + 2;
1995 else if (!strcmp(arg, "-s")) {
1996 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
1998 else if (!strncmp(arg, "-O", 2))
1999 options->orderfile = arg + 2;
2000 else if (!strncmp(arg, "--diff-filter=", 14))
2001 options->filter = arg + 14;
2002 else if (!strcmp(arg, "--pickaxe-all"))
2003 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2004 else if (!strcmp(arg, "--pickaxe-regex"))
2005 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2006 else if (!strncmp(arg, "-B", 2)) {
2007 if ((options->break_opt =
2008 diff_scoreopt_parse(arg)) == -1)
2009 return -1;
2011 else if (!strncmp(arg, "-M", 2)) {
2012 if ((options->rename_score =
2013 diff_scoreopt_parse(arg)) == -1)
2014 return -1;
2015 options->detect_rename = DIFF_DETECT_RENAME;
2017 else if (!strncmp(arg, "-C", 2)) {
2018 if ((options->rename_score =
2019 diff_scoreopt_parse(arg)) == -1)
2020 return -1;
2021 options->detect_rename = DIFF_DETECT_COPY;
2023 else if (!strcmp(arg, "--find-copies-harder"))
2024 options->find_copies_harder = 1;
2025 else if (!strcmp(arg, "--abbrev"))
2026 options->abbrev = DEFAULT_ABBREV;
2027 else if (!strncmp(arg, "--abbrev=", 9)) {
2028 options->abbrev = strtoul(arg + 9, NULL, 10);
2029 if (options->abbrev < MINIMUM_ABBREV)
2030 options->abbrev = MINIMUM_ABBREV;
2031 else if (40 < options->abbrev)
2032 options->abbrev = 40;
2034 else if (!strcmp(arg, "--color"))
2035 options->color_diff = 1;
2036 else if (!strcmp(arg, "--no-color"))
2037 options->color_diff = 0;
2038 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2039 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2040 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2041 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2042 else if (!strcmp(arg, "--color-words"))
2043 options->color_diff = options->color_diff_words = 1;
2044 else if (!strcmp(arg, "--no-renames"))
2045 options->detect_rename = 0;
2046 else
2047 return 0;
2048 return 1;
2051 static int parse_num(const char **cp_p)
2053 unsigned long num, scale;
2054 int ch, dot;
2055 const char *cp = *cp_p;
2057 num = 0;
2058 scale = 1;
2059 dot = 0;
2060 for(;;) {
2061 ch = *cp;
2062 if ( !dot && ch == '.' ) {
2063 scale = 1;
2064 dot = 1;
2065 } else if ( ch == '%' ) {
2066 scale = dot ? scale*100 : 100;
2067 cp++; /* % is always at the end */
2068 break;
2069 } else if ( ch >= '0' && ch <= '9' ) {
2070 if ( scale < 100000 ) {
2071 scale *= 10;
2072 num = (num*10) + (ch-'0');
2074 } else {
2075 break;
2077 cp++;
2079 *cp_p = cp;
2081 /* user says num divided by scale and we say internally that
2082 * is MAX_SCORE * num / scale.
2084 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
2087 int diff_scoreopt_parse(const char *opt)
2089 int opt1, opt2, cmd;
2091 if (*opt++ != '-')
2092 return -1;
2093 cmd = *opt++;
2094 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2095 return -1; /* that is not a -M, -C nor -B option */
2097 opt1 = parse_num(&opt);
2098 if (cmd != 'B')
2099 opt2 = 0;
2100 else {
2101 if (*opt == 0)
2102 opt2 = 0;
2103 else if (*opt != '/')
2104 return -1; /* we expect -B80/99 or -B80 */
2105 else {
2106 opt++;
2107 opt2 = parse_num(&opt);
2110 if (*opt != 0)
2111 return -1;
2112 return opt1 | (opt2 << 16);
2115 struct diff_queue_struct diff_queued_diff;
2117 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2119 if (queue->alloc <= queue->nr) {
2120 queue->alloc = alloc_nr(queue->alloc);
2121 queue->queue = xrealloc(queue->queue,
2122 sizeof(dp) * queue->alloc);
2124 queue->queue[queue->nr++] = dp;
2127 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2128 struct diff_filespec *one,
2129 struct diff_filespec *two)
2131 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2132 dp->one = one;
2133 dp->two = two;
2134 if (queue)
2135 diff_q(queue, dp);
2136 return dp;
2139 void diff_free_filepair(struct diff_filepair *p)
2141 diff_free_filespec_data(p->one);
2142 diff_free_filespec_data(p->two);
2143 free(p->one);
2144 free(p->two);
2145 free(p);
2148 /* This is different from find_unique_abbrev() in that
2149 * it stuffs the result with dots for alignment.
2151 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2153 int abblen;
2154 const char *abbrev;
2155 if (len == 40)
2156 return sha1_to_hex(sha1);
2158 abbrev = find_unique_abbrev(sha1, len);
2159 if (!abbrev)
2160 return sha1_to_hex(sha1);
2161 abblen = strlen(abbrev);
2162 if (abblen < 37) {
2163 static char hex[41];
2164 if (len < abblen && abblen <= len + 2)
2165 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2166 else
2167 sprintf(hex, "%s...", abbrev);
2168 return hex;
2170 return sha1_to_hex(sha1);
2173 static void diff_flush_raw(struct diff_filepair *p,
2174 struct diff_options *options)
2176 int two_paths;
2177 char status[10];
2178 int abbrev = options->abbrev;
2179 const char *path_one, *path_two;
2180 int inter_name_termination = '\t';
2181 int line_termination = options->line_termination;
2183 if (!line_termination)
2184 inter_name_termination = 0;
2186 path_one = p->one->path;
2187 path_two = p->two->path;
2188 if (line_termination) {
2189 path_one = quote_one(path_one);
2190 path_two = quote_one(path_two);
2193 if (p->score)
2194 sprintf(status, "%c%03d", p->status,
2195 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2196 else {
2197 status[0] = p->status;
2198 status[1] = 0;
2200 switch (p->status) {
2201 case DIFF_STATUS_COPIED:
2202 case DIFF_STATUS_RENAMED:
2203 two_paths = 1;
2204 break;
2205 case DIFF_STATUS_ADDED:
2206 case DIFF_STATUS_DELETED:
2207 two_paths = 0;
2208 break;
2209 default:
2210 two_paths = 0;
2211 break;
2213 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2214 printf(":%06o %06o %s ",
2215 p->one->mode, p->two->mode,
2216 diff_unique_abbrev(p->one->sha1, abbrev));
2217 printf("%s ",
2218 diff_unique_abbrev(p->two->sha1, abbrev));
2220 printf("%s%c%s", status, inter_name_termination, path_one);
2221 if (two_paths)
2222 printf("%c%s", inter_name_termination, path_two);
2223 putchar(line_termination);
2224 if (path_one != p->one->path)
2225 free((void*)path_one);
2226 if (path_two != p->two->path)
2227 free((void*)path_two);
2230 static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2232 char *path = p->two->path;
2234 if (opt->line_termination)
2235 path = quote_one(p->two->path);
2236 printf("%s%c", path, opt->line_termination);
2237 if (p->two->path != path)
2238 free(path);
2241 int diff_unmodified_pair(struct diff_filepair *p)
2243 /* This function is written stricter than necessary to support
2244 * the currently implemented transformers, but the idea is to
2245 * let transformers to produce diff_filepairs any way they want,
2246 * and filter and clean them up here before producing the output.
2248 struct diff_filespec *one, *two;
2250 if (DIFF_PAIR_UNMERGED(p))
2251 return 0; /* unmerged is interesting */
2253 one = p->one;
2254 two = p->two;
2256 /* deletion, addition, mode or type change
2257 * and rename are all interesting.
2259 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2260 DIFF_PAIR_MODE_CHANGED(p) ||
2261 strcmp(one->path, two->path))
2262 return 0;
2264 /* both are valid and point at the same path. that is, we are
2265 * dealing with a change.
2267 if (one->sha1_valid && two->sha1_valid &&
2268 !hashcmp(one->sha1, two->sha1))
2269 return 1; /* no change */
2270 if (!one->sha1_valid && !two->sha1_valid)
2271 return 1; /* both look at the same file on the filesystem. */
2272 return 0;
2275 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2277 if (diff_unmodified_pair(p))
2278 return;
2280 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2281 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2282 return; /* no tree diffs in patch format */
2284 run_diff(p, o);
2287 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2288 struct diffstat_t *diffstat)
2290 if (diff_unmodified_pair(p))
2291 return;
2293 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2294 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2295 return; /* no tree diffs in patch format */
2297 run_diffstat(p, o, diffstat);
2300 static void diff_flush_checkdiff(struct diff_filepair *p,
2301 struct diff_options *o)
2303 if (diff_unmodified_pair(p))
2304 return;
2306 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2307 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2308 return; /* no tree diffs in patch format */
2310 run_checkdiff(p, o);
2313 int diff_queue_is_empty(void)
2315 struct diff_queue_struct *q = &diff_queued_diff;
2316 int i;
2317 for (i = 0; i < q->nr; i++)
2318 if (!diff_unmodified_pair(q->queue[i]))
2319 return 0;
2320 return 1;
2323 #if DIFF_DEBUG
2324 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2326 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2327 x, one ? one : "",
2328 s->path,
2329 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2330 s->mode,
2331 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2332 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2333 x, one ? one : "",
2334 s->size, s->xfrm_flags);
2337 void diff_debug_filepair(const struct diff_filepair *p, int i)
2339 diff_debug_filespec(p->one, i, "one");
2340 diff_debug_filespec(p->two, i, "two");
2341 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2342 p->score, p->status ? p->status : '?',
2343 p->source_stays, p->broken_pair);
2346 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2348 int i;
2349 if (msg)
2350 fprintf(stderr, "%s\n", msg);
2351 fprintf(stderr, "q->nr = %d\n", q->nr);
2352 for (i = 0; i < q->nr; i++) {
2353 struct diff_filepair *p = q->queue[i];
2354 diff_debug_filepair(p, i);
2357 #endif
2359 static void diff_resolve_rename_copy(void)
2361 int i, j;
2362 struct diff_filepair *p, *pp;
2363 struct diff_queue_struct *q = &diff_queued_diff;
2365 diff_debug_queue("resolve-rename-copy", q);
2367 for (i = 0; i < q->nr; i++) {
2368 p = q->queue[i];
2369 p->status = 0; /* undecided */
2370 if (DIFF_PAIR_UNMERGED(p))
2371 p->status = DIFF_STATUS_UNMERGED;
2372 else if (!DIFF_FILE_VALID(p->one))
2373 p->status = DIFF_STATUS_ADDED;
2374 else if (!DIFF_FILE_VALID(p->two))
2375 p->status = DIFF_STATUS_DELETED;
2376 else if (DIFF_PAIR_TYPE_CHANGED(p))
2377 p->status = DIFF_STATUS_TYPE_CHANGED;
2379 /* from this point on, we are dealing with a pair
2380 * whose both sides are valid and of the same type, i.e.
2381 * either in-place edit or rename/copy edit.
2383 else if (DIFF_PAIR_RENAME(p)) {
2384 if (p->source_stays) {
2385 p->status = DIFF_STATUS_COPIED;
2386 continue;
2388 /* See if there is some other filepair that
2389 * copies from the same source as us. If so
2390 * we are a copy. Otherwise we are either a
2391 * copy if the path stays, or a rename if it
2392 * does not, but we already handled "stays" case.
2394 for (j = i + 1; j < q->nr; j++) {
2395 pp = q->queue[j];
2396 if (strcmp(pp->one->path, p->one->path))
2397 continue; /* not us */
2398 if (!DIFF_PAIR_RENAME(pp))
2399 continue; /* not a rename/copy */
2400 /* pp is a rename/copy from the same source */
2401 p->status = DIFF_STATUS_COPIED;
2402 break;
2404 if (!p->status)
2405 p->status = DIFF_STATUS_RENAMED;
2407 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2408 p->one->mode != p->two->mode)
2409 p->status = DIFF_STATUS_MODIFIED;
2410 else {
2411 /* This is a "no-change" entry and should not
2412 * happen anymore, but prepare for broken callers.
2414 error("feeding unmodified %s to diffcore",
2415 p->one->path);
2416 p->status = DIFF_STATUS_UNKNOWN;
2419 diff_debug_queue("resolve-rename-copy done", q);
2422 static int check_pair_status(struct diff_filepair *p)
2424 switch (p->status) {
2425 case DIFF_STATUS_UNKNOWN:
2426 return 0;
2427 case 0:
2428 die("internal error in diff-resolve-rename-copy");
2429 default:
2430 return 1;
2434 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2436 int fmt = opt->output_format;
2438 if (fmt & DIFF_FORMAT_CHECKDIFF)
2439 diff_flush_checkdiff(p, opt);
2440 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2441 diff_flush_raw(p, opt);
2442 else if (fmt & DIFF_FORMAT_NAME)
2443 diff_flush_name(p, opt);
2446 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2448 char *name = quote_one(fs->path);
2449 if (fs->mode)
2450 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2451 else
2452 printf(" %s %s\n", newdelete, name);
2453 free(name);
2457 static void show_mode_change(struct diff_filepair *p, int show_name)
2459 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2460 if (show_name) {
2461 char *name = quote_one(p->two->path);
2462 printf(" mode change %06o => %06o %s\n",
2463 p->one->mode, p->two->mode, name);
2464 free(name);
2466 else
2467 printf(" mode change %06o => %06o\n",
2468 p->one->mode, p->two->mode);
2472 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2474 char *names = pprint_rename(p->one->path, p->two->path);
2476 printf(" %s %s (%d%%)\n", renamecopy, names,
2477 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2478 free(names);
2479 show_mode_change(p, 0);
2482 static void diff_summary(struct diff_filepair *p)
2484 switch(p->status) {
2485 case DIFF_STATUS_DELETED:
2486 show_file_mode_name("delete", p->one);
2487 break;
2488 case DIFF_STATUS_ADDED:
2489 show_file_mode_name("create", p->two);
2490 break;
2491 case DIFF_STATUS_COPIED:
2492 show_rename_copy("copy", p);
2493 break;
2494 case DIFF_STATUS_RENAMED:
2495 show_rename_copy("rename", p);
2496 break;
2497 default:
2498 if (p->score) {
2499 char *name = quote_one(p->two->path);
2500 printf(" rewrite %s (%d%%)\n", name,
2501 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2502 free(name);
2503 show_mode_change(p, 0);
2504 } else show_mode_change(p, 1);
2505 break;
2509 struct patch_id_t {
2510 struct xdiff_emit_state xm;
2511 SHA_CTX *ctx;
2512 int patchlen;
2515 static int remove_space(char *line, int len)
2517 int i;
2518 char *dst = line;
2519 unsigned char c;
2521 for (i = 0; i < len; i++)
2522 if (!isspace((c = line[i])))
2523 *dst++ = c;
2525 return dst - line;
2528 static void patch_id_consume(void *priv, char *line, unsigned long len)
2530 struct patch_id_t *data = priv;
2531 int new_len;
2533 /* Ignore line numbers when computing the SHA1 of the patch */
2534 if (!strncmp(line, "@@ -", 4))
2535 return;
2537 new_len = remove_space(line, len);
2539 SHA1_Update(data->ctx, line, new_len);
2540 data->patchlen += new_len;
2543 /* returns 0 upon success, and writes result into sha1 */
2544 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2546 struct diff_queue_struct *q = &diff_queued_diff;
2547 int i;
2548 SHA_CTX ctx;
2549 struct patch_id_t data;
2550 char buffer[PATH_MAX * 4 + 20];
2552 SHA1_Init(&ctx);
2553 memset(&data, 0, sizeof(struct patch_id_t));
2554 data.ctx = &ctx;
2555 data.xm.consume = patch_id_consume;
2557 for (i = 0; i < q->nr; i++) {
2558 xpparam_t xpp;
2559 xdemitconf_t xecfg;
2560 xdemitcb_t ecb;
2561 mmfile_t mf1, mf2;
2562 struct diff_filepair *p = q->queue[i];
2563 int len1, len2;
2565 if (p->status == 0)
2566 return error("internal diff status error");
2567 if (p->status == DIFF_STATUS_UNKNOWN)
2568 continue;
2569 if (diff_unmodified_pair(p))
2570 continue;
2571 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2572 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2573 continue;
2574 if (DIFF_PAIR_UNMERGED(p))
2575 continue;
2577 diff_fill_sha1_info(p->one);
2578 diff_fill_sha1_info(p->two);
2579 if (fill_mmfile(&mf1, p->one) < 0 ||
2580 fill_mmfile(&mf2, p->two) < 0)
2581 return error("unable to read files to diff");
2583 /* Maybe hash p->two? into the patch id? */
2584 if (mmfile_is_binary(&mf2))
2585 continue;
2587 len1 = remove_space(p->one->path, strlen(p->one->path));
2588 len2 = remove_space(p->two->path, strlen(p->two->path));
2589 if (p->one->mode == 0)
2590 len1 = snprintf(buffer, sizeof(buffer),
2591 "diff--gita/%.*sb/%.*s"
2592 "newfilemode%06o"
2593 "---/dev/null"
2594 "+++b/%.*s",
2595 len1, p->one->path,
2596 len2, p->two->path,
2597 p->two->mode,
2598 len2, p->two->path);
2599 else if (p->two->mode == 0)
2600 len1 = snprintf(buffer, sizeof(buffer),
2601 "diff--gita/%.*sb/%.*s"
2602 "deletedfilemode%06o"
2603 "---a/%.*s"
2604 "+++/dev/null",
2605 len1, p->one->path,
2606 len2, p->two->path,
2607 p->one->mode,
2608 len1, p->one->path);
2609 else
2610 len1 = snprintf(buffer, sizeof(buffer),
2611 "diff--gita/%.*sb/%.*s"
2612 "---a/%.*s"
2613 "+++b/%.*s",
2614 len1, p->one->path,
2615 len2, p->two->path,
2616 len1, p->one->path,
2617 len2, p->two->path);
2618 SHA1_Update(&ctx, buffer, len1);
2620 xpp.flags = XDF_NEED_MINIMAL;
2621 xecfg.ctxlen = 3;
2622 xecfg.flags = XDL_EMIT_FUNCNAMES;
2623 ecb.outf = xdiff_outf;
2624 ecb.priv = &data;
2625 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2628 SHA1_Final(sha1, &ctx);
2629 return 0;
2632 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2634 struct diff_queue_struct *q = &diff_queued_diff;
2635 int i;
2636 int result = diff_get_patch_id(options, sha1);
2638 for (i = 0; i < q->nr; i++)
2639 diff_free_filepair(q->queue[i]);
2641 free(q->queue);
2642 q->queue = NULL;
2643 q->nr = q->alloc = 0;
2645 return result;
2648 static int is_summary_empty(const struct diff_queue_struct *q)
2650 int i;
2652 for (i = 0; i < q->nr; i++) {
2653 const struct diff_filepair *p = q->queue[i];
2655 switch (p->status) {
2656 case DIFF_STATUS_DELETED:
2657 case DIFF_STATUS_ADDED:
2658 case DIFF_STATUS_COPIED:
2659 case DIFF_STATUS_RENAMED:
2660 return 0;
2661 default:
2662 if (p->score)
2663 return 0;
2664 if (p->one->mode && p->two->mode &&
2665 p->one->mode != p->two->mode)
2666 return 0;
2667 break;
2670 return 1;
2673 void diff_flush(struct diff_options *options)
2675 struct diff_queue_struct *q = &diff_queued_diff;
2676 int i, output_format = options->output_format;
2677 int separator = 0;
2680 * Order: raw, stat, summary, patch
2681 * or: name/name-status/checkdiff (other bits clear)
2683 if (!q->nr)
2684 goto free_queue;
2686 if (output_format & (DIFF_FORMAT_RAW |
2687 DIFF_FORMAT_NAME |
2688 DIFF_FORMAT_NAME_STATUS |
2689 DIFF_FORMAT_CHECKDIFF)) {
2690 for (i = 0; i < q->nr; i++) {
2691 struct diff_filepair *p = q->queue[i];
2692 if (check_pair_status(p))
2693 flush_one_pair(p, options);
2695 separator++;
2698 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
2699 struct diffstat_t diffstat;
2701 memset(&diffstat, 0, sizeof(struct diffstat_t));
2702 diffstat.xm.consume = diffstat_consume;
2703 for (i = 0; i < q->nr; i++) {
2704 struct diff_filepair *p = q->queue[i];
2705 if (check_pair_status(p))
2706 diff_flush_stat(p, options, &diffstat);
2708 if (output_format & DIFF_FORMAT_NUMSTAT)
2709 show_numstat(&diffstat, options);
2710 if (output_format & DIFF_FORMAT_DIFFSTAT)
2711 show_stats(&diffstat, options);
2712 else if (output_format & DIFF_FORMAT_SHORTSTAT)
2713 show_shortstats(&diffstat);
2714 separator++;
2717 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2718 for (i = 0; i < q->nr; i++)
2719 diff_summary(q->queue[i]);
2720 separator++;
2723 if (output_format & DIFF_FORMAT_PATCH) {
2724 if (separator) {
2725 if (options->stat_sep) {
2726 /* attach patch instead of inline */
2727 fputs(options->stat_sep, stdout);
2728 } else {
2729 putchar(options->line_termination);
2733 for (i = 0; i < q->nr; i++) {
2734 struct diff_filepair *p = q->queue[i];
2735 if (check_pair_status(p))
2736 diff_flush_patch(p, options);
2740 if (output_format & DIFF_FORMAT_CALLBACK)
2741 options->format_callback(q, options, options->format_callback_data);
2743 for (i = 0; i < q->nr; i++)
2744 diff_free_filepair(q->queue[i]);
2745 free_queue:
2746 free(q->queue);
2747 q->queue = NULL;
2748 q->nr = q->alloc = 0;
2751 static void diffcore_apply_filter(const char *filter)
2753 int i;
2754 struct diff_queue_struct *q = &diff_queued_diff;
2755 struct diff_queue_struct outq;
2756 outq.queue = NULL;
2757 outq.nr = outq.alloc = 0;
2759 if (!filter)
2760 return;
2762 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2763 int found;
2764 for (i = found = 0; !found && i < q->nr; i++) {
2765 struct diff_filepair *p = q->queue[i];
2766 if (((p->status == DIFF_STATUS_MODIFIED) &&
2767 ((p->score &&
2768 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2769 (!p->score &&
2770 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2771 ((p->status != DIFF_STATUS_MODIFIED) &&
2772 strchr(filter, p->status)))
2773 found++;
2775 if (found)
2776 return;
2778 /* otherwise we will clear the whole queue
2779 * by copying the empty outq at the end of this
2780 * function, but first clear the current entries
2781 * in the queue.
2783 for (i = 0; i < q->nr; i++)
2784 diff_free_filepair(q->queue[i]);
2786 else {
2787 /* Only the matching ones */
2788 for (i = 0; i < q->nr; i++) {
2789 struct diff_filepair *p = q->queue[i];
2791 if (((p->status == DIFF_STATUS_MODIFIED) &&
2792 ((p->score &&
2793 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2794 (!p->score &&
2795 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2796 ((p->status != DIFF_STATUS_MODIFIED) &&
2797 strchr(filter, p->status)))
2798 diff_q(&outq, p);
2799 else
2800 diff_free_filepair(p);
2803 free(q->queue);
2804 *q = outq;
2807 void diffcore_std(struct diff_options *options)
2809 if (options->break_opt != -1)
2810 diffcore_break(options->break_opt);
2811 if (options->detect_rename)
2812 diffcore_rename(options);
2813 if (options->break_opt != -1)
2814 diffcore_merge_broken();
2815 if (options->pickaxe)
2816 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2817 if (options->orderfile)
2818 diffcore_order(options->orderfile);
2819 diff_resolve_rename_copy();
2820 diffcore_apply_filter(options->filter);
2824 void diffcore_std_no_resolve(struct diff_options *options)
2826 if (options->pickaxe)
2827 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2828 if (options->orderfile)
2829 diffcore_order(options->orderfile);
2830 diffcore_apply_filter(options->filter);
2833 void diff_addremove(struct diff_options *options,
2834 int addremove, unsigned mode,
2835 const unsigned char *sha1,
2836 const char *base, const char *path)
2838 char concatpath[PATH_MAX];
2839 struct diff_filespec *one, *two;
2841 /* This may look odd, but it is a preparation for
2842 * feeding "there are unchanged files which should
2843 * not produce diffs, but when you are doing copy
2844 * detection you would need them, so here they are"
2845 * entries to the diff-core. They will be prefixed
2846 * with something like '=' or '*' (I haven't decided
2847 * which but should not make any difference).
2848 * Feeding the same new and old to diff_change()
2849 * also has the same effect.
2850 * Before the final output happens, they are pruned after
2851 * merged into rename/copy pairs as appropriate.
2853 if (options->reverse_diff)
2854 addremove = (addremove == '+' ? '-' :
2855 addremove == '-' ? '+' : addremove);
2857 if (!path) path = "";
2858 sprintf(concatpath, "%s%s", base, path);
2859 one = alloc_filespec(concatpath);
2860 two = alloc_filespec(concatpath);
2862 if (addremove != '+')
2863 fill_filespec(one, sha1, mode);
2864 if (addremove != '-')
2865 fill_filespec(two, sha1, mode);
2867 diff_queue(&diff_queued_diff, one, two);
2870 void diff_change(struct diff_options *options,
2871 unsigned old_mode, unsigned new_mode,
2872 const unsigned char *old_sha1,
2873 const unsigned char *new_sha1,
2874 const char *base, const char *path)
2876 char concatpath[PATH_MAX];
2877 struct diff_filespec *one, *two;
2879 if (options->reverse_diff) {
2880 unsigned tmp;
2881 const unsigned char *tmp_c;
2882 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2883 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2885 if (!path) path = "";
2886 sprintf(concatpath, "%s%s", base, path);
2887 one = alloc_filespec(concatpath);
2888 two = alloc_filespec(concatpath);
2889 fill_filespec(one, old_sha1, old_mode);
2890 fill_filespec(two, new_sha1, new_mode);
2892 diff_queue(&diff_queued_diff, one, two);
2895 void diff_unmerge(struct diff_options *options,
2896 const char *path,
2897 unsigned mode, const unsigned char *sha1)
2899 struct diff_filespec *one, *two;
2900 one = alloc_filespec(path);
2901 two = alloc_filespec(path);
2902 fill_filespec(one, sha1, mode);
2903 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;