merge-base: update the clean-up postprocessing
[git/dkf.git] / diff.c
bloba00f9d1e5244c8a7d2edfcef55cb92d3d3df252a
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"
14 static int use_size_cache;
16 static int diff_rename_limit_default = -1;
17 static int diff_use_color_default = 0;
19 enum color_diff {
20 DIFF_RESET = 0,
21 DIFF_PLAIN = 1,
22 DIFF_METAINFO = 2,
23 DIFF_FRAGINFO = 3,
24 DIFF_FILE_OLD = 4,
25 DIFF_FILE_NEW = 5,
28 #define COLOR_NORMAL ""
29 #define COLOR_BOLD "\033[1m"
30 #define COLOR_DIM "\033[2m"
31 #define COLOR_UL "\033[4m"
32 #define COLOR_BLINK "\033[5m"
33 #define COLOR_REVERSE "\033[7m"
34 #define COLOR_RESET "\033[m"
36 #define COLOR_BLACK "\033[30m"
37 #define COLOR_RED "\033[31m"
38 #define COLOR_GREEN "\033[32m"
39 #define COLOR_YELLOW "\033[33m"
40 #define COLOR_BLUE "\033[34m"
41 #define COLOR_MAGENTA "\033[35m"
42 #define COLOR_CYAN "\033[36m"
43 #define COLOR_WHITE "\033[37m"
45 static const char *diff_colors[] = {
46 [DIFF_RESET] = COLOR_RESET,
47 [DIFF_PLAIN] = COLOR_NORMAL,
48 [DIFF_METAINFO] = COLOR_BOLD,
49 [DIFF_FRAGINFO] = COLOR_CYAN,
50 [DIFF_FILE_OLD] = COLOR_RED,
51 [DIFF_FILE_NEW] = COLOR_GREEN,
54 static int parse_diff_color_slot(const char *var, int ofs)
56 if (!strcasecmp(var+ofs, "plain"))
57 return DIFF_PLAIN;
58 if (!strcasecmp(var+ofs, "meta"))
59 return DIFF_METAINFO;
60 if (!strcasecmp(var+ofs, "frag"))
61 return DIFF_FRAGINFO;
62 if (!strcasecmp(var+ofs, "old"))
63 return DIFF_FILE_OLD;
64 if (!strcasecmp(var+ofs, "new"))
65 return DIFF_FILE_NEW;
66 die("bad config variable '%s'", var);
69 static const char *parse_diff_color_value(const char *value, const char *var)
71 if (!strcasecmp(value, "normal"))
72 return COLOR_NORMAL;
73 if (!strcasecmp(value, "bold"))
74 return COLOR_BOLD;
75 if (!strcasecmp(value, "dim"))
76 return COLOR_DIM;
77 if (!strcasecmp(value, "ul"))
78 return COLOR_UL;
79 if (!strcasecmp(value, "blink"))
80 return COLOR_BLINK;
81 if (!strcasecmp(value, "reverse"))
82 return COLOR_REVERSE;
83 if (!strcasecmp(value, "reset"))
84 return COLOR_RESET;
85 if (!strcasecmp(value, "black"))
86 return COLOR_BLACK;
87 if (!strcasecmp(value, "red"))
88 return COLOR_RED;
89 if (!strcasecmp(value, "green"))
90 return COLOR_GREEN;
91 if (!strcasecmp(value, "yellow"))
92 return COLOR_YELLOW;
93 if (!strcasecmp(value, "blue"))
94 return COLOR_BLUE;
95 if (!strcasecmp(value, "magenta"))
96 return COLOR_MAGENTA;
97 if (!strcasecmp(value, "cyan"))
98 return COLOR_CYAN;
99 if (!strcasecmp(value, "white"))
100 return COLOR_WHITE;
101 die("bad config value '%s' for variable '%s'", value, var);
104 int git_diff_config(const char *var, const char *value)
106 if (!strcmp(var, "diff.renamelimit")) {
107 diff_rename_limit_default = git_config_int(var, value);
108 return 0;
110 if (!strcmp(var, "diff.color")) {
111 if (!value)
112 diff_use_color_default = 1; /* bool */
113 else if (!strcasecmp(value, "auto")) {
114 diff_use_color_default = 0;
115 if (isatty(1) || pager_in_use) {
116 char *term = getenv("TERM");
117 if (term && strcmp(term, "dumb"))
118 diff_use_color_default = 1;
121 else if (!strcasecmp(value, "never"))
122 diff_use_color_default = 0;
123 else if (!strcasecmp(value, "always"))
124 diff_use_color_default = 1;
125 else
126 diff_use_color_default = git_config_bool(var, value);
127 return 0;
129 if (!strncmp(var, "diff.color.", 11)) {
130 int slot = parse_diff_color_slot(var, 11);
131 diff_colors[slot] = parse_diff_color_value(value, var);
132 return 0;
134 return git_default_config(var, value);
137 static char *quote_one(const char *str)
139 int needlen;
140 char *xp;
142 if (!str)
143 return NULL;
144 needlen = quote_c_style(str, NULL, NULL, 0);
145 if (!needlen)
146 return strdup(str);
147 xp = xmalloc(needlen + 1);
148 quote_c_style(str, xp, NULL, 0);
149 return xp;
152 static char *quote_two(const char *one, const char *two)
154 int need_one = quote_c_style(one, NULL, NULL, 1);
155 int need_two = quote_c_style(two, NULL, NULL, 1);
156 char *xp;
158 if (need_one + need_two) {
159 if (!need_one) need_one = strlen(one);
160 if (!need_two) need_one = strlen(two);
162 xp = xmalloc(need_one + need_two + 3);
163 xp[0] = '"';
164 quote_c_style(one, xp + 1, NULL, 1);
165 quote_c_style(two, xp + need_one + 1, NULL, 1);
166 strcpy(xp + need_one + need_two + 1, "\"");
167 return xp;
169 need_one = strlen(one);
170 need_two = strlen(two);
171 xp = xmalloc(need_one + need_two + 1);
172 strcpy(xp, one);
173 strcpy(xp + need_one, two);
174 return xp;
177 static const char *external_diff(void)
179 static const char *external_diff_cmd = NULL;
180 static int done_preparing = 0;
182 if (done_preparing)
183 return external_diff_cmd;
184 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
185 done_preparing = 1;
186 return external_diff_cmd;
189 #define TEMPFILE_PATH_LEN 50
191 static struct diff_tempfile {
192 const char *name; /* filename external diff should read from */
193 char hex[41];
194 char mode[10];
195 char tmp_path[TEMPFILE_PATH_LEN];
196 } diff_temp[2];
198 static int count_lines(const char *data, int size)
200 int count, ch, completely_empty = 1, nl_just_seen = 0;
201 count = 0;
202 while (0 < size--) {
203 ch = *data++;
204 if (ch == '\n') {
205 count++;
206 nl_just_seen = 1;
207 completely_empty = 0;
209 else {
210 nl_just_seen = 0;
211 completely_empty = 0;
214 if (completely_empty)
215 return 0;
216 if (!nl_just_seen)
217 count++; /* no trailing newline */
218 return count;
221 static void print_line_count(int count)
223 switch (count) {
224 case 0:
225 printf("0,0");
226 break;
227 case 1:
228 printf("1");
229 break;
230 default:
231 printf("1,%d", count);
232 break;
236 static void copy_file(int prefix, const char *data, int size)
238 int ch, nl_just_seen = 1;
239 while (0 < size--) {
240 ch = *data++;
241 if (nl_just_seen)
242 putchar(prefix);
243 putchar(ch);
244 if (ch == '\n')
245 nl_just_seen = 1;
246 else
247 nl_just_seen = 0;
249 if (!nl_just_seen)
250 printf("\n\\ No newline at end of file\n");
253 static void emit_rewrite_diff(const char *name_a,
254 const char *name_b,
255 struct diff_filespec *one,
256 struct diff_filespec *two)
258 int lc_a, lc_b;
259 diff_populate_filespec(one, 0);
260 diff_populate_filespec(two, 0);
261 lc_a = count_lines(one->data, one->size);
262 lc_b = count_lines(two->data, two->size);
263 printf("--- %s\n+++ %s\n@@ -", name_a, name_b);
264 print_line_count(lc_a);
265 printf(" +");
266 print_line_count(lc_b);
267 printf(" @@\n");
268 if (lc_a)
269 copy_file('-', one->data, one->size);
270 if (lc_b)
271 copy_file('+', two->data, two->size);
274 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
276 if (!DIFF_FILE_VALID(one)) {
277 mf->ptr = (char *)""; /* does not matter */
278 mf->size = 0;
279 return 0;
281 else if (diff_populate_filespec(one, 0))
282 return -1;
283 mf->ptr = one->data;
284 mf->size = one->size;
285 return 0;
288 struct emit_callback {
289 struct xdiff_emit_state xm;
290 int nparents, color_diff;
291 const char **label_path;
294 static inline const char *get_color(int diff_use_color, enum color_diff ix)
296 if (diff_use_color)
297 return diff_colors[ix];
298 return "";
301 static void fn_out_consume(void *priv, char *line, unsigned long len)
303 int i;
304 struct emit_callback *ecbdata = priv;
305 const char *set = get_color(ecbdata->color_diff, DIFF_METAINFO);
306 const char *reset = get_color(ecbdata->color_diff, DIFF_RESET);
308 if (ecbdata->label_path[0]) {
309 printf("%s--- %s%s\n", set, ecbdata->label_path[0], reset);
310 printf("%s+++ %s%s\n", set, ecbdata->label_path[1], reset);
311 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
314 /* This is not really necessary for now because
315 * this codepath only deals with two-way diffs.
317 for (i = 0; i < len && line[i] == '@'; i++)
319 if (2 <= i && i < len && line[i] == ' ') {
320 ecbdata->nparents = i - 1;
321 set = get_color(ecbdata->color_diff, DIFF_FRAGINFO);
323 else if (len < ecbdata->nparents)
324 set = reset;
325 else {
326 int nparents = ecbdata->nparents;
327 int color = DIFF_PLAIN;
328 for (i = 0; i < nparents && len; i++) {
329 if (line[i] == '-')
330 color = DIFF_FILE_OLD;
331 else if (line[i] == '+')
332 color = DIFF_FILE_NEW;
334 set = get_color(ecbdata->color_diff, color);
336 if (len > 0 && line[len-1] == '\n')
337 len--;
338 fputs (set, stdout);
339 fwrite (line, len, 1, stdout);
340 puts (reset);
343 static char *pprint_rename(const char *a, const char *b)
345 const char *old = a;
346 const char *new = b;
347 char *name = NULL;
348 int pfx_length, sfx_length;
349 int len_a = strlen(a);
350 int len_b = strlen(b);
352 /* Find common prefix */
353 pfx_length = 0;
354 while (*old && *new && *old == *new) {
355 if (*old == '/')
356 pfx_length = old - a + 1;
357 old++;
358 new++;
361 /* Find common suffix */
362 old = a + len_a;
363 new = b + len_b;
364 sfx_length = 0;
365 while (a <= old && b <= new && *old == *new) {
366 if (*old == '/')
367 sfx_length = len_a - (old - a);
368 old--;
369 new--;
373 * pfx{mid-a => mid-b}sfx
374 * {pfx-a => pfx-b}sfx
375 * pfx{sfx-a => sfx-b}
376 * name-a => name-b
378 if (pfx_length + sfx_length) {
379 int a_midlen = len_a - pfx_length - sfx_length;
380 int b_midlen = len_b - pfx_length - sfx_length;
381 if (a_midlen < 0) a_midlen = 0;
382 if (b_midlen < 0) b_midlen = 0;
384 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
385 sprintf(name, "%.*s{%.*s => %.*s}%s",
386 pfx_length, a,
387 a_midlen, a + pfx_length,
388 b_midlen, b + pfx_length,
389 a + len_a - sfx_length);
391 else {
392 name = xmalloc(len_a + len_b + 5);
393 sprintf(name, "%s => %s", a, b);
395 return name;
398 struct diffstat_t {
399 struct xdiff_emit_state xm;
401 int nr;
402 int alloc;
403 struct diffstat_file {
404 char *name;
405 unsigned is_unmerged:1;
406 unsigned is_binary:1;
407 unsigned is_renamed:1;
408 unsigned int added, deleted;
409 } **files;
412 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
413 const char *name_a,
414 const char *name_b)
416 struct diffstat_file *x;
417 x = xcalloc(sizeof (*x), 1);
418 if (diffstat->nr == diffstat->alloc) {
419 diffstat->alloc = alloc_nr(diffstat->alloc);
420 diffstat->files = xrealloc(diffstat->files,
421 diffstat->alloc * sizeof(x));
423 diffstat->files[diffstat->nr++] = x;
424 if (name_b) {
425 x->name = pprint_rename(name_a, name_b);
426 x->is_renamed = 1;
428 else
429 x->name = strdup(name_a);
430 return x;
433 static void diffstat_consume(void *priv, char *line, unsigned long len)
435 struct diffstat_t *diffstat = priv;
436 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
438 if (line[0] == '+')
439 x->added++;
440 else if (line[0] == '-')
441 x->deleted++;
444 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
445 static const char minuses[]= "----------------------------------------------------------------------";
446 const char mime_boundary_leader[] = "------------";
448 static void show_stats(struct diffstat_t* data)
450 int i, len, add, del, total, adds = 0, dels = 0;
451 int max, max_change = 0, max_len = 0;
452 int total_files = data->nr;
454 if (data->nr == 0)
455 return;
457 for (i = 0; i < data->nr; i++) {
458 struct diffstat_file *file = data->files[i];
460 len = strlen(file->name);
461 if (max_len < len)
462 max_len = len;
464 if (file->is_binary || file->is_unmerged)
465 continue;
466 if (max_change < file->added + file->deleted)
467 max_change = file->added + file->deleted;
470 for (i = 0; i < data->nr; i++) {
471 const char *prefix = "";
472 char *name = data->files[i]->name;
473 int added = data->files[i]->added;
474 int deleted = data->files[i]->deleted;
476 if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
477 char *qname = xmalloc(len + 1);
478 quote_c_style(name, qname, NULL, 0);
479 free(name);
480 data->files[i]->name = name = qname;
484 * "scale" the filename
486 len = strlen(name);
487 max = max_len;
488 if (max > 50)
489 max = 50;
490 if (len > max) {
491 char *slash;
492 prefix = "...";
493 max -= 3;
494 name += len - max;
495 slash = strchr(name, '/');
496 if (slash)
497 name = slash;
499 len = max;
502 * scale the add/delete
504 max = max_change;
505 if (max + len > 70)
506 max = 70 - len;
508 if (data->files[i]->is_binary) {
509 printf(" %s%-*s | Bin\n", prefix, len, name);
510 goto free_diffstat_file;
512 else if (data->files[i]->is_unmerged) {
513 printf(" %s%-*s | Unmerged\n", prefix, len, name);
514 goto free_diffstat_file;
516 else if (!data->files[i]->is_renamed &&
517 (added + deleted == 0)) {
518 total_files--;
519 goto free_diffstat_file;
522 add = added;
523 del = deleted;
524 total = add + del;
525 adds += add;
526 dels += del;
528 if (max_change > 0) {
529 total = (total * max + max_change / 2) / max_change;
530 add = (add * max + max_change / 2) / max_change;
531 del = total - add;
533 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
534 len, name, added + deleted,
535 add, pluses, del, minuses);
536 free_diffstat_file:
537 free(data->files[i]->name);
538 free(data->files[i]);
540 free(data->files);
541 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
542 total_files, adds, dels);
545 struct checkdiff_t {
546 struct xdiff_emit_state xm;
547 const char *filename;
548 int lineno;
551 static void checkdiff_consume(void *priv, char *line, unsigned long len)
553 struct checkdiff_t *data = priv;
555 if (line[0] == '+') {
556 int i, spaces = 0;
558 data->lineno++;
560 /* check space before tab */
561 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
562 if (line[i] == ' ')
563 spaces++;
564 if (line[i - 1] == '\t' && spaces)
565 printf("%s:%d: space before tab:%.*s\n",
566 data->filename, data->lineno, (int)len, line);
568 /* check white space at line end */
569 if (line[len - 1] == '\n')
570 len--;
571 if (isspace(line[len - 1]))
572 printf("%s:%d: white space at end: %.*s\n",
573 data->filename, data->lineno, (int)len, line);
574 } else if (line[0] == ' ')
575 data->lineno++;
576 else if (line[0] == '@') {
577 char *plus = strchr(line, '+');
578 if (plus)
579 data->lineno = strtol(plus, NULL, 10);
580 else
581 die("invalid diff");
585 static unsigned char *deflate_it(char *data,
586 unsigned long size,
587 unsigned long *result_size)
589 int bound;
590 unsigned char *deflated;
591 z_stream stream;
593 memset(&stream, 0, sizeof(stream));
594 deflateInit(&stream, zlib_compression_level);
595 bound = deflateBound(&stream, size);
596 deflated = xmalloc(bound);
597 stream.next_out = deflated;
598 stream.avail_out = bound;
600 stream.next_in = (unsigned char *)data;
601 stream.avail_in = size;
602 while (deflate(&stream, Z_FINISH) == Z_OK)
603 ; /* nothing */
604 deflateEnd(&stream);
605 *result_size = stream.total_out;
606 return deflated;
609 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
611 void *cp;
612 void *delta;
613 void *deflated;
614 void *data;
615 unsigned long orig_size;
616 unsigned long delta_size;
617 unsigned long deflate_size;
618 unsigned long data_size;
620 printf("GIT binary patch\n");
621 /* We could do deflated delta, or we could do just deflated two,
622 * whichever is smaller.
624 delta = NULL;
625 deflated = deflate_it(two->ptr, two->size, &deflate_size);
626 if (one->size && two->size) {
627 delta = diff_delta(one->ptr, one->size,
628 two->ptr, two->size,
629 &delta_size, deflate_size);
630 if (delta) {
631 void *to_free = delta;
632 orig_size = delta_size;
633 delta = deflate_it(delta, delta_size, &delta_size);
634 free(to_free);
638 if (delta && delta_size < deflate_size) {
639 printf("delta %lu\n", orig_size);
640 free(deflated);
641 data = delta;
642 data_size = delta_size;
644 else {
645 printf("literal %lu\n", two->size);
646 free(delta);
647 data = deflated;
648 data_size = deflate_size;
651 /* emit data encoded in base85 */
652 cp = data;
653 while (data_size) {
654 int bytes = (52 < data_size) ? 52 : data_size;
655 char line[70];
656 data_size -= bytes;
657 if (bytes <= 26)
658 line[0] = bytes + 'A' - 1;
659 else
660 line[0] = bytes - 26 + 'a' - 1;
661 encode_85(line + 1, cp, bytes);
662 cp = (char *) cp + bytes;
663 puts(line);
665 printf("\n");
666 free(data);
669 #define FIRST_FEW_BYTES 8000
670 static int mmfile_is_binary(mmfile_t *mf)
672 long sz = mf->size;
673 if (FIRST_FEW_BYTES < sz)
674 sz = FIRST_FEW_BYTES;
675 if (memchr(mf->ptr, 0, sz))
676 return 1;
677 return 0;
680 static void builtin_diff(const char *name_a,
681 const char *name_b,
682 struct diff_filespec *one,
683 struct diff_filespec *two,
684 const char *xfrm_msg,
685 struct diff_options *o,
686 int complete_rewrite)
688 mmfile_t mf1, mf2;
689 const char *lbl[2];
690 char *a_one, *b_two;
691 const char *set = get_color(o->color_diff, DIFF_METAINFO);
692 const char *reset = get_color(o->color_diff, DIFF_RESET);
694 a_one = quote_two("a/", name_a);
695 b_two = quote_two("b/", name_b);
696 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
697 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
698 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
699 if (lbl[0][0] == '/') {
700 /* /dev/null */
701 printf("%snew file mode %06o%s\n", set, two->mode, reset);
702 if (xfrm_msg && xfrm_msg[0])
703 printf("%s%s%s\n", set, xfrm_msg, reset);
705 else if (lbl[1][0] == '/') {
706 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
707 if (xfrm_msg && xfrm_msg[0])
708 printf("%s%s%s\n", set, xfrm_msg, reset);
710 else {
711 if (one->mode != two->mode) {
712 printf("%sold mode %06o%s\n", set, one->mode, reset);
713 printf("%snew mode %06o%s\n", set, two->mode, reset);
715 if (xfrm_msg && xfrm_msg[0])
716 printf("%s%s%s\n", set, xfrm_msg, reset);
718 * we do not run diff between different kind
719 * of objects.
721 if ((one->mode ^ two->mode) & S_IFMT)
722 goto free_ab_and_return;
723 if (complete_rewrite) {
724 emit_rewrite_diff(name_a, name_b, one, two);
725 goto free_ab_and_return;
729 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
730 die("unable to read files to diff");
732 if (!o->text && (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))) {
733 /* Quite common confusing case */
734 if (mf1.size == mf2.size &&
735 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
736 goto free_ab_and_return;
737 if (o->binary)
738 emit_binary_diff(&mf1, &mf2);
739 else
740 printf("Binary files %s and %s differ\n",
741 lbl[0], lbl[1]);
743 else {
744 /* Crazy xdl interfaces.. */
745 const char *diffopts = getenv("GIT_DIFF_OPTS");
746 xpparam_t xpp;
747 xdemitconf_t xecfg;
748 xdemitcb_t ecb;
749 struct emit_callback ecbdata;
751 memset(&ecbdata, 0, sizeof(ecbdata));
752 ecbdata.label_path = lbl;
753 ecbdata.color_diff = o->color_diff;
754 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
755 xecfg.ctxlen = o->context;
756 xecfg.flags = XDL_EMIT_FUNCNAMES;
757 if (!diffopts)
759 else if (!strncmp(diffopts, "--unified=", 10))
760 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
761 else if (!strncmp(diffopts, "-u", 2))
762 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
763 ecb.outf = xdiff_outf;
764 ecb.priv = &ecbdata;
765 ecbdata.xm.consume = fn_out_consume;
766 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
769 free_ab_and_return:
770 free(a_one);
771 free(b_two);
772 return;
775 static void builtin_diffstat(const char *name_a, const char *name_b,
776 struct diff_filespec *one,
777 struct diff_filespec *two,
778 struct diffstat_t *diffstat,
779 struct diff_options *o,
780 int complete_rewrite)
782 mmfile_t mf1, mf2;
783 struct diffstat_file *data;
785 data = diffstat_add(diffstat, name_a, name_b);
787 if (!one || !two) {
788 data->is_unmerged = 1;
789 return;
791 if (complete_rewrite) {
792 diff_populate_filespec(one, 0);
793 diff_populate_filespec(two, 0);
794 data->deleted = count_lines(one->data, one->size);
795 data->added = count_lines(two->data, two->size);
796 return;
798 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
799 die("unable to read files to diff");
801 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
802 data->is_binary = 1;
803 else {
804 /* Crazy xdl interfaces.. */
805 xpparam_t xpp;
806 xdemitconf_t xecfg;
807 xdemitcb_t ecb;
809 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
810 xecfg.ctxlen = 0;
811 xecfg.flags = 0;
812 ecb.outf = xdiff_outf;
813 ecb.priv = diffstat;
814 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
818 static void builtin_checkdiff(const char *name_a, const char *name_b,
819 struct diff_filespec *one,
820 struct diff_filespec *two)
822 mmfile_t mf1, mf2;
823 struct checkdiff_t data;
825 if (!two)
826 return;
828 memset(&data, 0, sizeof(data));
829 data.xm.consume = checkdiff_consume;
830 data.filename = name_b ? name_b : name_a;
831 data.lineno = 0;
833 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
834 die("unable to read files to diff");
836 if (mmfile_is_binary(&mf2))
837 return;
838 else {
839 /* Crazy xdl interfaces.. */
840 xpparam_t xpp;
841 xdemitconf_t xecfg;
842 xdemitcb_t ecb;
844 xpp.flags = XDF_NEED_MINIMAL;
845 xecfg.ctxlen = 0;
846 xecfg.flags = 0;
847 ecb.outf = xdiff_outf;
848 ecb.priv = &data;
849 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
853 struct diff_filespec *alloc_filespec(const char *path)
855 int namelen = strlen(path);
856 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
858 memset(spec, 0, sizeof(*spec));
859 spec->path = (char *)(spec + 1);
860 memcpy(spec->path, path, namelen+1);
861 return spec;
864 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
865 unsigned short mode)
867 if (mode) {
868 spec->mode = canon_mode(mode);
869 memcpy(spec->sha1, sha1, 20);
870 spec->sha1_valid = !!memcmp(sha1, null_sha1, 20);
875 * Given a name and sha1 pair, if the dircache tells us the file in
876 * the work tree has that object contents, return true, so that
877 * prepare_temp_file() does not have to inflate and extract.
879 static int work_tree_matches(const char *name, const unsigned char *sha1)
881 struct cache_entry *ce;
882 struct stat st;
883 int pos, len;
885 /* We do not read the cache ourselves here, because the
886 * benchmark with my previous version that always reads cache
887 * shows that it makes things worse for diff-tree comparing
888 * two linux-2.6 kernel trees in an already checked out work
889 * tree. This is because most diff-tree comparisons deal with
890 * only a small number of files, while reading the cache is
891 * expensive for a large project, and its cost outweighs the
892 * savings we get by not inflating the object to a temporary
893 * file. Practically, this code only helps when we are used
894 * by diff-cache --cached, which does read the cache before
895 * calling us.
897 if (!active_cache)
898 return 0;
900 len = strlen(name);
901 pos = cache_name_pos(name, len);
902 if (pos < 0)
903 return 0;
904 ce = active_cache[pos];
905 if ((lstat(name, &st) < 0) ||
906 !S_ISREG(st.st_mode) || /* careful! */
907 ce_match_stat(ce, &st, 0) ||
908 memcmp(sha1, ce->sha1, 20))
909 return 0;
910 /* we return 1 only when we can stat, it is a regular file,
911 * stat information matches, and sha1 recorded in the cache
912 * matches. I.e. we know the file in the work tree really is
913 * the same as the <name, sha1> pair.
915 return 1;
918 static struct sha1_size_cache {
919 unsigned char sha1[20];
920 unsigned long size;
921 } **sha1_size_cache;
922 static int sha1_size_cache_nr, sha1_size_cache_alloc;
924 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
925 int find_only,
926 unsigned long size)
928 int first, last;
929 struct sha1_size_cache *e;
931 first = 0;
932 last = sha1_size_cache_nr;
933 while (last > first) {
934 int cmp, next = (last + first) >> 1;
935 e = sha1_size_cache[next];
936 cmp = memcmp(e->sha1, sha1, 20);
937 if (!cmp)
938 return e;
939 if (cmp < 0) {
940 last = next;
941 continue;
943 first = next+1;
945 /* not found */
946 if (find_only)
947 return NULL;
948 /* insert to make it at "first" */
949 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
950 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
951 sha1_size_cache = xrealloc(sha1_size_cache,
952 sha1_size_cache_alloc *
953 sizeof(*sha1_size_cache));
955 sha1_size_cache_nr++;
956 if (first < sha1_size_cache_nr)
957 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
958 (sha1_size_cache_nr - first - 1) *
959 sizeof(*sha1_size_cache));
960 e = xmalloc(sizeof(struct sha1_size_cache));
961 sha1_size_cache[first] = e;
962 memcpy(e->sha1, sha1, 20);
963 e->size = size;
964 return e;
968 * While doing rename detection and pickaxe operation, we may need to
969 * grab the data for the blob (or file) for our own in-core comparison.
970 * diff_filespec has data and size fields for this purpose.
972 int diff_populate_filespec(struct diff_filespec *s, int size_only)
974 int err = 0;
975 if (!DIFF_FILE_VALID(s))
976 die("internal error: asking to populate invalid file.");
977 if (S_ISDIR(s->mode))
978 return -1;
980 if (!use_size_cache)
981 size_only = 0;
983 if (s->data)
984 return err;
985 if (!s->sha1_valid ||
986 work_tree_matches(s->path, s->sha1)) {
987 struct stat st;
988 int fd;
989 if (lstat(s->path, &st) < 0) {
990 if (errno == ENOENT) {
991 err_empty:
992 err = -1;
993 empty:
994 s->data = (char *)"";
995 s->size = 0;
996 return err;
999 s->size = st.st_size;
1000 if (!s->size)
1001 goto empty;
1002 if (size_only)
1003 return 0;
1004 if (S_ISLNK(st.st_mode)) {
1005 int ret;
1006 s->data = xmalloc(s->size);
1007 s->should_free = 1;
1008 ret = readlink(s->path, s->data, s->size);
1009 if (ret < 0) {
1010 free(s->data);
1011 goto err_empty;
1013 return 0;
1015 fd = open(s->path, O_RDONLY);
1016 if (fd < 0)
1017 goto err_empty;
1018 s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1019 close(fd);
1020 if (s->data == MAP_FAILED)
1021 goto err_empty;
1022 s->should_munmap = 1;
1024 else {
1025 char type[20];
1026 struct sha1_size_cache *e;
1028 if (size_only) {
1029 e = locate_size_cache(s->sha1, 1, 0);
1030 if (e) {
1031 s->size = e->size;
1032 return 0;
1034 if (!sha1_object_info(s->sha1, type, &s->size))
1035 locate_size_cache(s->sha1, 0, s->size);
1037 else {
1038 s->data = read_sha1_file(s->sha1, type, &s->size);
1039 s->should_free = 1;
1042 return 0;
1045 void diff_free_filespec_data(struct diff_filespec *s)
1047 if (s->should_free)
1048 free(s->data);
1049 else if (s->should_munmap)
1050 munmap(s->data, s->size);
1051 s->should_free = s->should_munmap = 0;
1052 s->data = NULL;
1053 free(s->cnt_data);
1054 s->cnt_data = NULL;
1057 static void prep_temp_blob(struct diff_tempfile *temp,
1058 void *blob,
1059 unsigned long size,
1060 const unsigned char *sha1,
1061 int mode)
1063 int fd;
1065 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1066 if (fd < 0)
1067 die("unable to create temp-file");
1068 if (write(fd, blob, size) != size)
1069 die("unable to write temp-file");
1070 close(fd);
1071 temp->name = temp->tmp_path;
1072 strcpy(temp->hex, sha1_to_hex(sha1));
1073 temp->hex[40] = 0;
1074 sprintf(temp->mode, "%06o", mode);
1077 static void prepare_temp_file(const char *name,
1078 struct diff_tempfile *temp,
1079 struct diff_filespec *one)
1081 if (!DIFF_FILE_VALID(one)) {
1082 not_a_valid_file:
1083 /* A '-' entry produces this for file-2, and
1084 * a '+' entry produces this for file-1.
1086 temp->name = "/dev/null";
1087 strcpy(temp->hex, ".");
1088 strcpy(temp->mode, ".");
1089 return;
1092 if (!one->sha1_valid ||
1093 work_tree_matches(name, one->sha1)) {
1094 struct stat st;
1095 if (lstat(name, &st) < 0) {
1096 if (errno == ENOENT)
1097 goto not_a_valid_file;
1098 die("stat(%s): %s", name, strerror(errno));
1100 if (S_ISLNK(st.st_mode)) {
1101 int ret;
1102 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1103 if (sizeof(buf) <= st.st_size)
1104 die("symlink too long: %s", name);
1105 ret = readlink(name, buf, st.st_size);
1106 if (ret < 0)
1107 die("readlink(%s)", name);
1108 prep_temp_blob(temp, buf, st.st_size,
1109 (one->sha1_valid ?
1110 one->sha1 : null_sha1),
1111 (one->sha1_valid ?
1112 one->mode : S_IFLNK));
1114 else {
1115 /* we can borrow from the file in the work tree */
1116 temp->name = name;
1117 if (!one->sha1_valid)
1118 strcpy(temp->hex, sha1_to_hex(null_sha1));
1119 else
1120 strcpy(temp->hex, sha1_to_hex(one->sha1));
1121 /* Even though we may sometimes borrow the
1122 * contents from the work tree, we always want
1123 * one->mode. mode is trustworthy even when
1124 * !(one->sha1_valid), as long as
1125 * DIFF_FILE_VALID(one).
1127 sprintf(temp->mode, "%06o", one->mode);
1129 return;
1131 else {
1132 if (diff_populate_filespec(one, 0))
1133 die("cannot read data blob for %s", one->path);
1134 prep_temp_blob(temp, one->data, one->size,
1135 one->sha1, one->mode);
1139 static void remove_tempfile(void)
1141 int i;
1143 for (i = 0; i < 2; i++)
1144 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1145 unlink(diff_temp[i].name);
1146 diff_temp[i].name = NULL;
1150 static void remove_tempfile_on_signal(int signo)
1152 remove_tempfile();
1153 signal(SIGINT, SIG_DFL);
1154 raise(signo);
1157 static int spawn_prog(const char *pgm, const char **arg)
1159 pid_t pid;
1160 int status;
1162 fflush(NULL);
1163 pid = fork();
1164 if (pid < 0)
1165 die("unable to fork");
1166 if (!pid) {
1167 execvp(pgm, (char *const*) arg);
1168 exit(255);
1171 while (waitpid(pid, &status, 0) < 0) {
1172 if (errno == EINTR)
1173 continue;
1174 return -1;
1177 /* Earlier we did not check the exit status because
1178 * diff exits non-zero if files are different, and
1179 * we are not interested in knowing that. It was a
1180 * mistake which made it harder to quit a diff-*
1181 * session that uses the git-apply-patch-script as
1182 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1183 * should also exit non-zero only when it wants to
1184 * abort the entire diff-* session.
1186 if (WIFEXITED(status) && !WEXITSTATUS(status))
1187 return 0;
1188 return -1;
1191 /* An external diff command takes:
1193 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1194 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1197 static void run_external_diff(const char *pgm,
1198 const char *name,
1199 const char *other,
1200 struct diff_filespec *one,
1201 struct diff_filespec *two,
1202 const char *xfrm_msg,
1203 int complete_rewrite)
1205 const char *spawn_arg[10];
1206 struct diff_tempfile *temp = diff_temp;
1207 int retval;
1208 static int atexit_asked = 0;
1209 const char *othername;
1210 const char **arg = &spawn_arg[0];
1212 othername = (other? other : name);
1213 if (one && two) {
1214 prepare_temp_file(name, &temp[0], one);
1215 prepare_temp_file(othername, &temp[1], two);
1216 if (! atexit_asked &&
1217 (temp[0].name == temp[0].tmp_path ||
1218 temp[1].name == temp[1].tmp_path)) {
1219 atexit_asked = 1;
1220 atexit(remove_tempfile);
1222 signal(SIGINT, remove_tempfile_on_signal);
1225 if (one && two) {
1226 *arg++ = pgm;
1227 *arg++ = name;
1228 *arg++ = temp[0].name;
1229 *arg++ = temp[0].hex;
1230 *arg++ = temp[0].mode;
1231 *arg++ = temp[1].name;
1232 *arg++ = temp[1].hex;
1233 *arg++ = temp[1].mode;
1234 if (other) {
1235 *arg++ = other;
1236 *arg++ = xfrm_msg;
1238 } else {
1239 *arg++ = pgm;
1240 *arg++ = name;
1242 *arg = NULL;
1243 retval = spawn_prog(pgm, spawn_arg);
1244 remove_tempfile();
1245 if (retval) {
1246 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1247 exit(1);
1251 static void run_diff_cmd(const char *pgm,
1252 const char *name,
1253 const char *other,
1254 struct diff_filespec *one,
1255 struct diff_filespec *two,
1256 const char *xfrm_msg,
1257 struct diff_options *o,
1258 int complete_rewrite)
1260 if (pgm) {
1261 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1262 complete_rewrite);
1263 return;
1265 if (one && two)
1266 builtin_diff(name, other ? other : name,
1267 one, two, xfrm_msg, o, complete_rewrite);
1268 else
1269 printf("* Unmerged path %s\n", name);
1272 static void diff_fill_sha1_info(struct diff_filespec *one)
1274 if (DIFF_FILE_VALID(one)) {
1275 if (!one->sha1_valid) {
1276 struct stat st;
1277 if (lstat(one->path, &st) < 0)
1278 die("stat %s", one->path);
1279 if (index_path(one->sha1, one->path, &st, 0))
1280 die("cannot hash %s\n", one->path);
1283 else
1284 memset(one->sha1, 0, 20);
1287 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1289 const char *pgm = external_diff();
1290 char msg[PATH_MAX*2+300], *xfrm_msg;
1291 struct diff_filespec *one;
1292 struct diff_filespec *two;
1293 const char *name;
1294 const char *other;
1295 char *name_munged, *other_munged;
1296 int complete_rewrite = 0;
1297 int len;
1299 if (DIFF_PAIR_UNMERGED(p)) {
1300 /* unmerged */
1301 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1302 return;
1305 name = p->one->path;
1306 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1307 name_munged = quote_one(name);
1308 other_munged = quote_one(other);
1309 one = p->one; two = p->two;
1311 diff_fill_sha1_info(one);
1312 diff_fill_sha1_info(two);
1314 len = 0;
1315 switch (p->status) {
1316 case DIFF_STATUS_COPIED:
1317 len += snprintf(msg + len, sizeof(msg) - len,
1318 "similarity index %d%%\n"
1319 "copy from %s\n"
1320 "copy to %s\n",
1321 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1322 name_munged, other_munged);
1323 break;
1324 case DIFF_STATUS_RENAMED:
1325 len += snprintf(msg + len, sizeof(msg) - len,
1326 "similarity index %d%%\n"
1327 "rename from %s\n"
1328 "rename to %s\n",
1329 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1330 name_munged, other_munged);
1331 break;
1332 case DIFF_STATUS_MODIFIED:
1333 if (p->score) {
1334 len += snprintf(msg + len, sizeof(msg) - len,
1335 "dissimilarity index %d%%\n",
1336 (int)(0.5 + p->score *
1337 100.0/MAX_SCORE));
1338 complete_rewrite = 1;
1339 break;
1341 /* fallthru */
1342 default:
1343 /* nothing */
1347 if (memcmp(one->sha1, two->sha1, 20)) {
1348 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1350 len += snprintf(msg + len, sizeof(msg) - len,
1351 "index %.*s..%.*s",
1352 abbrev, sha1_to_hex(one->sha1),
1353 abbrev, sha1_to_hex(two->sha1));
1354 if (one->mode == two->mode)
1355 len += snprintf(msg + len, sizeof(msg) - len,
1356 " %06o", one->mode);
1357 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1360 if (len)
1361 msg[--len] = 0;
1362 xfrm_msg = len ? msg : NULL;
1364 if (!pgm &&
1365 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1366 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1367 /* a filepair that changes between file and symlink
1368 * needs to be split into deletion and creation.
1370 struct diff_filespec *null = alloc_filespec(two->path);
1371 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1372 free(null);
1373 null = alloc_filespec(one->path);
1374 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1375 free(null);
1377 else
1378 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1379 complete_rewrite);
1381 free(name_munged);
1382 free(other_munged);
1385 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1386 struct diffstat_t *diffstat)
1388 const char *name;
1389 const char *other;
1390 int complete_rewrite = 0;
1392 if (DIFF_PAIR_UNMERGED(p)) {
1393 /* unmerged */
1394 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1395 return;
1398 name = p->one->path;
1399 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1401 diff_fill_sha1_info(p->one);
1402 diff_fill_sha1_info(p->two);
1404 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1405 complete_rewrite = 1;
1406 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1409 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1411 const char *name;
1412 const char *other;
1414 if (DIFF_PAIR_UNMERGED(p)) {
1415 /* unmerged */
1416 return;
1419 name = p->one->path;
1420 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1422 diff_fill_sha1_info(p->one);
1423 diff_fill_sha1_info(p->two);
1425 builtin_checkdiff(name, other, p->one, p->two);
1428 void diff_setup(struct diff_options *options)
1430 memset(options, 0, sizeof(*options));
1431 options->line_termination = '\n';
1432 options->break_opt = -1;
1433 options->rename_limit = -1;
1434 options->context = 3;
1435 options->msg_sep = "";
1437 options->change = diff_change;
1438 options->add_remove = diff_addremove;
1439 options->color_diff = diff_use_color_default;
1442 int diff_setup_done(struct diff_options *options)
1444 if ((options->find_copies_harder &&
1445 options->detect_rename != DIFF_DETECT_COPY) ||
1446 (0 <= options->rename_limit && !options->detect_rename))
1447 return -1;
1449 if (options->output_format & (DIFF_FORMAT_NAME |
1450 DIFF_FORMAT_NAME_STATUS |
1451 DIFF_FORMAT_CHECKDIFF |
1452 DIFF_FORMAT_NO_OUTPUT))
1453 options->output_format &= ~(DIFF_FORMAT_RAW |
1454 DIFF_FORMAT_DIFFSTAT |
1455 DIFF_FORMAT_SUMMARY |
1456 DIFF_FORMAT_PATCH);
1459 * These cases always need recursive; we do not drop caller-supplied
1460 * recursive bits for other formats here.
1462 if (options->output_format & (DIFF_FORMAT_PATCH |
1463 DIFF_FORMAT_DIFFSTAT |
1464 DIFF_FORMAT_CHECKDIFF))
1465 options->recursive = 1;
1467 * Also pickaxe would not work very well if you do not say recursive
1469 if (options->pickaxe)
1470 options->recursive = 1;
1472 if (options->detect_rename && options->rename_limit < 0)
1473 options->rename_limit = diff_rename_limit_default;
1474 if (options->setup & DIFF_SETUP_USE_CACHE) {
1475 if (!active_cache)
1476 /* read-cache does not die even when it fails
1477 * so it is safe for us to do this here. Also
1478 * it does not smudge active_cache or active_nr
1479 * when it fails, so we do not have to worry about
1480 * cleaning it up ourselves either.
1482 read_cache();
1484 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1485 use_size_cache = 1;
1486 if (options->abbrev <= 0 || 40 < options->abbrev)
1487 options->abbrev = 40; /* full */
1489 return 0;
1492 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1494 char c, *eq;
1495 int len;
1497 if (*arg != '-')
1498 return 0;
1499 c = *++arg;
1500 if (!c)
1501 return 0;
1502 if (c == arg_short) {
1503 c = *++arg;
1504 if (!c)
1505 return 1;
1506 if (val && isdigit(c)) {
1507 char *end;
1508 int n = strtoul(arg, &end, 10);
1509 if (*end)
1510 return 0;
1511 *val = n;
1512 return 1;
1514 return 0;
1516 if (c != '-')
1517 return 0;
1518 arg++;
1519 eq = strchr(arg, '=');
1520 if (eq)
1521 len = eq - arg;
1522 else
1523 len = strlen(arg);
1524 if (!len || strncmp(arg, arg_long, len))
1525 return 0;
1526 if (eq) {
1527 int n;
1528 char *end;
1529 if (!isdigit(*++eq))
1530 return 0;
1531 n = strtoul(eq, &end, 10);
1532 if (*end)
1533 return 0;
1534 *val = n;
1536 return 1;
1539 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1541 const char *arg = av[0];
1542 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1543 options->output_format |= DIFF_FORMAT_PATCH;
1544 else if (opt_arg(arg, 'U', "unified", &options->context))
1545 options->output_format |= DIFF_FORMAT_PATCH;
1546 else if (!strcmp(arg, "--raw"))
1547 options->output_format |= DIFF_FORMAT_RAW;
1548 else if (!strcmp(arg, "--patch-with-raw")) {
1549 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
1551 else if (!strcmp(arg, "--stat"))
1552 options->output_format |= DIFF_FORMAT_DIFFSTAT;
1553 else if (!strcmp(arg, "--check"))
1554 options->output_format |= DIFF_FORMAT_CHECKDIFF;
1555 else if (!strcmp(arg, "--summary"))
1556 options->output_format |= DIFF_FORMAT_SUMMARY;
1557 else if (!strcmp(arg, "--patch-with-stat")) {
1558 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
1560 else if (!strcmp(arg, "-z"))
1561 options->line_termination = 0;
1562 else if (!strncmp(arg, "-l", 2))
1563 options->rename_limit = strtoul(arg+2, NULL, 10);
1564 else if (!strcmp(arg, "--full-index"))
1565 options->full_index = 1;
1566 else if (!strcmp(arg, "--binary")) {
1567 options->output_format |= DIFF_FORMAT_PATCH;
1568 options->full_index = options->binary = 1;
1570 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
1571 options->text = 1;
1573 else if (!strcmp(arg, "--name-only"))
1574 options->output_format |= DIFF_FORMAT_NAME;
1575 else if (!strcmp(arg, "--name-status"))
1576 options->output_format |= DIFF_FORMAT_NAME_STATUS;
1577 else if (!strcmp(arg, "-R"))
1578 options->reverse_diff = 1;
1579 else if (!strncmp(arg, "-S", 2))
1580 options->pickaxe = arg + 2;
1581 else if (!strcmp(arg, "-s")) {
1582 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
1584 else if (!strncmp(arg, "-O", 2))
1585 options->orderfile = arg + 2;
1586 else if (!strncmp(arg, "--diff-filter=", 14))
1587 options->filter = arg + 14;
1588 else if (!strcmp(arg, "--pickaxe-all"))
1589 options->pickaxe_opts = DIFF_PICKAXE_ALL;
1590 else if (!strcmp(arg, "--pickaxe-regex"))
1591 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
1592 else if (!strncmp(arg, "-B", 2)) {
1593 if ((options->break_opt =
1594 diff_scoreopt_parse(arg)) == -1)
1595 return -1;
1597 else if (!strncmp(arg, "-M", 2)) {
1598 if ((options->rename_score =
1599 diff_scoreopt_parse(arg)) == -1)
1600 return -1;
1601 options->detect_rename = DIFF_DETECT_RENAME;
1603 else if (!strncmp(arg, "-C", 2)) {
1604 if ((options->rename_score =
1605 diff_scoreopt_parse(arg)) == -1)
1606 return -1;
1607 options->detect_rename = DIFF_DETECT_COPY;
1609 else if (!strcmp(arg, "--find-copies-harder"))
1610 options->find_copies_harder = 1;
1611 else if (!strcmp(arg, "--abbrev"))
1612 options->abbrev = DEFAULT_ABBREV;
1613 else if (!strncmp(arg, "--abbrev=", 9)) {
1614 options->abbrev = strtoul(arg + 9, NULL, 10);
1615 if (options->abbrev < MINIMUM_ABBREV)
1616 options->abbrev = MINIMUM_ABBREV;
1617 else if (40 < options->abbrev)
1618 options->abbrev = 40;
1620 else if (!strcmp(arg, "--color"))
1621 options->color_diff = 1;
1622 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
1623 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
1624 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
1625 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
1626 else
1627 return 0;
1628 return 1;
1631 static int parse_num(const char **cp_p)
1633 unsigned long num, scale;
1634 int ch, dot;
1635 const char *cp = *cp_p;
1637 num = 0;
1638 scale = 1;
1639 dot = 0;
1640 for(;;) {
1641 ch = *cp;
1642 if ( !dot && ch == '.' ) {
1643 scale = 1;
1644 dot = 1;
1645 } else if ( ch == '%' ) {
1646 scale = dot ? scale*100 : 100;
1647 cp++; /* % is always at the end */
1648 break;
1649 } else if ( ch >= '0' && ch <= '9' ) {
1650 if ( scale < 100000 ) {
1651 scale *= 10;
1652 num = (num*10) + (ch-'0');
1654 } else {
1655 break;
1657 cp++;
1659 *cp_p = cp;
1661 /* user says num divided by scale and we say internally that
1662 * is MAX_SCORE * num / scale.
1664 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
1667 int diff_scoreopt_parse(const char *opt)
1669 int opt1, opt2, cmd;
1671 if (*opt++ != '-')
1672 return -1;
1673 cmd = *opt++;
1674 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
1675 return -1; /* that is not a -M, -C nor -B option */
1677 opt1 = parse_num(&opt);
1678 if (cmd != 'B')
1679 opt2 = 0;
1680 else {
1681 if (*opt == 0)
1682 opt2 = 0;
1683 else if (*opt != '/')
1684 return -1; /* we expect -B80/99 or -B80 */
1685 else {
1686 opt++;
1687 opt2 = parse_num(&opt);
1690 if (*opt != 0)
1691 return -1;
1692 return opt1 | (opt2 << 16);
1695 struct diff_queue_struct diff_queued_diff;
1697 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
1699 if (queue->alloc <= queue->nr) {
1700 queue->alloc = alloc_nr(queue->alloc);
1701 queue->queue = xrealloc(queue->queue,
1702 sizeof(dp) * queue->alloc);
1704 queue->queue[queue->nr++] = dp;
1707 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
1708 struct diff_filespec *one,
1709 struct diff_filespec *two)
1711 struct diff_filepair *dp = xmalloc(sizeof(*dp));
1712 dp->one = one;
1713 dp->two = two;
1714 dp->score = 0;
1715 dp->status = 0;
1716 dp->source_stays = 0;
1717 dp->broken_pair = 0;
1718 if (queue)
1719 diff_q(queue, dp);
1720 return dp;
1723 void diff_free_filepair(struct diff_filepair *p)
1725 diff_free_filespec_data(p->one);
1726 diff_free_filespec_data(p->two);
1727 free(p->one);
1728 free(p->two);
1729 free(p);
1732 /* This is different from find_unique_abbrev() in that
1733 * it stuffs the result with dots for alignment.
1735 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
1737 int abblen;
1738 const char *abbrev;
1739 if (len == 40)
1740 return sha1_to_hex(sha1);
1742 abbrev = find_unique_abbrev(sha1, len);
1743 if (!abbrev)
1744 return sha1_to_hex(sha1);
1745 abblen = strlen(abbrev);
1746 if (abblen < 37) {
1747 static char hex[41];
1748 if (len < abblen && abblen <= len + 2)
1749 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
1750 else
1751 sprintf(hex, "%s...", abbrev);
1752 return hex;
1754 return sha1_to_hex(sha1);
1757 static void diff_flush_raw(struct diff_filepair *p,
1758 struct diff_options *options)
1760 int two_paths;
1761 char status[10];
1762 int abbrev = options->abbrev;
1763 const char *path_one, *path_two;
1764 int inter_name_termination = '\t';
1765 int line_termination = options->line_termination;
1767 if (!line_termination)
1768 inter_name_termination = 0;
1770 path_one = p->one->path;
1771 path_two = p->two->path;
1772 if (line_termination) {
1773 path_one = quote_one(path_one);
1774 path_two = quote_one(path_two);
1777 if (p->score)
1778 sprintf(status, "%c%03d", p->status,
1779 (int)(0.5 + p->score * 100.0/MAX_SCORE));
1780 else {
1781 status[0] = p->status;
1782 status[1] = 0;
1784 switch (p->status) {
1785 case DIFF_STATUS_COPIED:
1786 case DIFF_STATUS_RENAMED:
1787 two_paths = 1;
1788 break;
1789 case DIFF_STATUS_ADDED:
1790 case DIFF_STATUS_DELETED:
1791 two_paths = 0;
1792 break;
1793 default:
1794 two_paths = 0;
1795 break;
1797 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
1798 printf(":%06o %06o %s ",
1799 p->one->mode, p->two->mode,
1800 diff_unique_abbrev(p->one->sha1, abbrev));
1801 printf("%s ",
1802 diff_unique_abbrev(p->two->sha1, abbrev));
1804 printf("%s%c%s", status, inter_name_termination, path_one);
1805 if (two_paths)
1806 printf("%c%s", inter_name_termination, path_two);
1807 putchar(line_termination);
1808 if (path_one != p->one->path)
1809 free((void*)path_one);
1810 if (path_two != p->two->path)
1811 free((void*)path_two);
1814 static void diff_flush_name(struct diff_filepair *p, int line_termination)
1816 char *path = p->two->path;
1818 if (line_termination)
1819 path = quote_one(p->two->path);
1820 printf("%s%c", path, line_termination);
1821 if (p->two->path != path)
1822 free(path);
1825 int diff_unmodified_pair(struct diff_filepair *p)
1827 /* This function is written stricter than necessary to support
1828 * the currently implemented transformers, but the idea is to
1829 * let transformers to produce diff_filepairs any way they want,
1830 * and filter and clean them up here before producing the output.
1832 struct diff_filespec *one, *two;
1834 if (DIFF_PAIR_UNMERGED(p))
1835 return 0; /* unmerged is interesting */
1837 one = p->one;
1838 two = p->two;
1840 /* deletion, addition, mode or type change
1841 * and rename are all interesting.
1843 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
1844 DIFF_PAIR_MODE_CHANGED(p) ||
1845 strcmp(one->path, two->path))
1846 return 0;
1848 /* both are valid and point at the same path. that is, we are
1849 * dealing with a change.
1851 if (one->sha1_valid && two->sha1_valid &&
1852 !memcmp(one->sha1, two->sha1, sizeof(one->sha1)))
1853 return 1; /* no change */
1854 if (!one->sha1_valid && !two->sha1_valid)
1855 return 1; /* both look at the same file on the filesystem. */
1856 return 0;
1859 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
1861 if (diff_unmodified_pair(p))
1862 return;
1864 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1865 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1866 return; /* no tree diffs in patch format */
1868 run_diff(p, o);
1871 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
1872 struct diffstat_t *diffstat)
1874 if (diff_unmodified_pair(p))
1875 return;
1877 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1878 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1879 return; /* no tree diffs in patch format */
1881 run_diffstat(p, o, diffstat);
1884 static void diff_flush_checkdiff(struct diff_filepair *p,
1885 struct diff_options *o)
1887 if (diff_unmodified_pair(p))
1888 return;
1890 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1891 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1892 return; /* no tree diffs in patch format */
1894 run_checkdiff(p, o);
1897 int diff_queue_is_empty(void)
1899 struct diff_queue_struct *q = &diff_queued_diff;
1900 int i;
1901 for (i = 0; i < q->nr; i++)
1902 if (!diff_unmodified_pair(q->queue[i]))
1903 return 0;
1904 return 1;
1907 #if DIFF_DEBUG
1908 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
1910 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
1911 x, one ? one : "",
1912 s->path,
1913 DIFF_FILE_VALID(s) ? "valid" : "invalid",
1914 s->mode,
1915 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
1916 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
1917 x, one ? one : "",
1918 s->size, s->xfrm_flags);
1921 void diff_debug_filepair(const struct diff_filepair *p, int i)
1923 diff_debug_filespec(p->one, i, "one");
1924 diff_debug_filespec(p->two, i, "two");
1925 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
1926 p->score, p->status ? p->status : '?',
1927 p->source_stays, p->broken_pair);
1930 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
1932 int i;
1933 if (msg)
1934 fprintf(stderr, "%s\n", msg);
1935 fprintf(stderr, "q->nr = %d\n", q->nr);
1936 for (i = 0; i < q->nr; i++) {
1937 struct diff_filepair *p = q->queue[i];
1938 diff_debug_filepair(p, i);
1941 #endif
1943 static void diff_resolve_rename_copy(void)
1945 int i, j;
1946 struct diff_filepair *p, *pp;
1947 struct diff_queue_struct *q = &diff_queued_diff;
1949 diff_debug_queue("resolve-rename-copy", q);
1951 for (i = 0; i < q->nr; i++) {
1952 p = q->queue[i];
1953 p->status = 0; /* undecided */
1954 if (DIFF_PAIR_UNMERGED(p))
1955 p->status = DIFF_STATUS_UNMERGED;
1956 else if (!DIFF_FILE_VALID(p->one))
1957 p->status = DIFF_STATUS_ADDED;
1958 else if (!DIFF_FILE_VALID(p->two))
1959 p->status = DIFF_STATUS_DELETED;
1960 else if (DIFF_PAIR_TYPE_CHANGED(p))
1961 p->status = DIFF_STATUS_TYPE_CHANGED;
1963 /* from this point on, we are dealing with a pair
1964 * whose both sides are valid and of the same type, i.e.
1965 * either in-place edit or rename/copy edit.
1967 else if (DIFF_PAIR_RENAME(p)) {
1968 if (p->source_stays) {
1969 p->status = DIFF_STATUS_COPIED;
1970 continue;
1972 /* See if there is some other filepair that
1973 * copies from the same source as us. If so
1974 * we are a copy. Otherwise we are either a
1975 * copy if the path stays, or a rename if it
1976 * does not, but we already handled "stays" case.
1978 for (j = i + 1; j < q->nr; j++) {
1979 pp = q->queue[j];
1980 if (strcmp(pp->one->path, p->one->path))
1981 continue; /* not us */
1982 if (!DIFF_PAIR_RENAME(pp))
1983 continue; /* not a rename/copy */
1984 /* pp is a rename/copy from the same source */
1985 p->status = DIFF_STATUS_COPIED;
1986 break;
1988 if (!p->status)
1989 p->status = DIFF_STATUS_RENAMED;
1991 else if (memcmp(p->one->sha1, p->two->sha1, 20) ||
1992 p->one->mode != p->two->mode)
1993 p->status = DIFF_STATUS_MODIFIED;
1994 else {
1995 /* This is a "no-change" entry and should not
1996 * happen anymore, but prepare for broken callers.
1998 error("feeding unmodified %s to diffcore",
1999 p->one->path);
2000 p->status = DIFF_STATUS_UNKNOWN;
2003 diff_debug_queue("resolve-rename-copy done", q);
2006 static int check_pair_status(struct diff_filepair *p)
2008 switch (p->status) {
2009 case DIFF_STATUS_UNKNOWN:
2010 return 0;
2011 case 0:
2012 die("internal error in diff-resolve-rename-copy");
2013 default:
2014 return 1;
2018 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2020 int fmt = opt->output_format;
2022 if (fmt & DIFF_FORMAT_CHECKDIFF)
2023 diff_flush_checkdiff(p, opt);
2024 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2025 diff_flush_raw(p, opt);
2026 else if (fmt & DIFF_FORMAT_NAME)
2027 diff_flush_name(p, opt->line_termination);
2030 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2032 if (fs->mode)
2033 printf(" %s mode %06o %s\n", newdelete, fs->mode, fs->path);
2034 else
2035 printf(" %s %s\n", newdelete, fs->path);
2039 static void show_mode_change(struct diff_filepair *p, int show_name)
2041 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2042 if (show_name)
2043 printf(" mode change %06o => %06o %s\n",
2044 p->one->mode, p->two->mode, p->two->path);
2045 else
2046 printf(" mode change %06o => %06o\n",
2047 p->one->mode, p->two->mode);
2051 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2053 const char *old, *new;
2055 /* Find common prefix */
2056 old = p->one->path;
2057 new = p->two->path;
2058 while (1) {
2059 const char *slash_old, *slash_new;
2060 slash_old = strchr(old, '/');
2061 slash_new = strchr(new, '/');
2062 if (!slash_old ||
2063 !slash_new ||
2064 slash_old - old != slash_new - new ||
2065 memcmp(old, new, slash_new - new))
2066 break;
2067 old = slash_old + 1;
2068 new = slash_new + 1;
2070 /* p->one->path thru old is the common prefix, and old and new
2071 * through the end of names are renames
2073 if (old != p->one->path)
2074 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2075 (int)(old - p->one->path), p->one->path,
2076 old, new, (int)(0.5 + p->score * 100.0/MAX_SCORE));
2077 else
2078 printf(" %s %s => %s (%d%%)\n", renamecopy,
2079 p->one->path, p->two->path,
2080 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2081 show_mode_change(p, 0);
2084 static void diff_summary(struct diff_filepair *p)
2086 switch(p->status) {
2087 case DIFF_STATUS_DELETED:
2088 show_file_mode_name("delete", p->one);
2089 break;
2090 case DIFF_STATUS_ADDED:
2091 show_file_mode_name("create", p->two);
2092 break;
2093 case DIFF_STATUS_COPIED:
2094 show_rename_copy("copy", p);
2095 break;
2096 case DIFF_STATUS_RENAMED:
2097 show_rename_copy("rename", p);
2098 break;
2099 default:
2100 if (p->score) {
2101 printf(" rewrite %s (%d%%)\n", p->two->path,
2102 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2103 show_mode_change(p, 0);
2104 } else show_mode_change(p, 1);
2105 break;
2109 struct patch_id_t {
2110 struct xdiff_emit_state xm;
2111 SHA_CTX *ctx;
2112 int patchlen;
2115 static int remove_space(char *line, int len)
2117 int i;
2118 char *dst = line;
2119 unsigned char c;
2121 for (i = 0; i < len; i++)
2122 if (!isspace((c = line[i])))
2123 *dst++ = c;
2125 return dst - line;
2128 static void patch_id_consume(void *priv, char *line, unsigned long len)
2130 struct patch_id_t *data = priv;
2131 int new_len;
2133 /* Ignore line numbers when computing the SHA1 of the patch */
2134 if (!strncmp(line, "@@ -", 4))
2135 return;
2137 new_len = remove_space(line, len);
2139 SHA1_Update(data->ctx, line, new_len);
2140 data->patchlen += new_len;
2143 /* returns 0 upon success, and writes result into sha1 */
2144 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2146 struct diff_queue_struct *q = &diff_queued_diff;
2147 int i;
2148 SHA_CTX ctx;
2149 struct patch_id_t data;
2150 char buffer[PATH_MAX * 4 + 20];
2152 SHA1_Init(&ctx);
2153 memset(&data, 0, sizeof(struct patch_id_t));
2154 data.ctx = &ctx;
2155 data.xm.consume = patch_id_consume;
2157 for (i = 0; i < q->nr; i++) {
2158 xpparam_t xpp;
2159 xdemitconf_t xecfg;
2160 xdemitcb_t ecb;
2161 mmfile_t mf1, mf2;
2162 struct diff_filepair *p = q->queue[i];
2163 int len1, len2;
2165 if (p->status == 0)
2166 return error("internal diff status error");
2167 if (p->status == DIFF_STATUS_UNKNOWN)
2168 continue;
2169 if (diff_unmodified_pair(p))
2170 continue;
2171 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2172 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2173 continue;
2174 if (DIFF_PAIR_UNMERGED(p))
2175 continue;
2177 diff_fill_sha1_info(p->one);
2178 diff_fill_sha1_info(p->two);
2179 if (fill_mmfile(&mf1, p->one) < 0 ||
2180 fill_mmfile(&mf2, p->two) < 0)
2181 return error("unable to read files to diff");
2183 /* Maybe hash p->two? into the patch id? */
2184 if (mmfile_is_binary(&mf2))
2185 continue;
2187 len1 = remove_space(p->one->path, strlen(p->one->path));
2188 len2 = remove_space(p->two->path, strlen(p->two->path));
2189 if (p->one->mode == 0)
2190 len1 = snprintf(buffer, sizeof(buffer),
2191 "diff--gita/%.*sb/%.*s"
2192 "newfilemode%06o"
2193 "---/dev/null"
2194 "+++b/%.*s",
2195 len1, p->one->path,
2196 len2, p->two->path,
2197 p->two->mode,
2198 len2, p->two->path);
2199 else if (p->two->mode == 0)
2200 len1 = snprintf(buffer, sizeof(buffer),
2201 "diff--gita/%.*sb/%.*s"
2202 "deletedfilemode%06o"
2203 "---a/%.*s"
2204 "+++/dev/null",
2205 len1, p->one->path,
2206 len2, p->two->path,
2207 p->one->mode,
2208 len1, p->one->path);
2209 else
2210 len1 = snprintf(buffer, sizeof(buffer),
2211 "diff--gita/%.*sb/%.*s"
2212 "---a/%.*s"
2213 "+++b/%.*s",
2214 len1, p->one->path,
2215 len2, p->two->path,
2216 len1, p->one->path,
2217 len2, p->two->path);
2218 SHA1_Update(&ctx, buffer, len1);
2220 xpp.flags = XDF_NEED_MINIMAL;
2221 xecfg.ctxlen = 3;
2222 xecfg.flags = XDL_EMIT_FUNCNAMES;
2223 ecb.outf = xdiff_outf;
2224 ecb.priv = &data;
2225 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2228 SHA1_Final(sha1, &ctx);
2229 return 0;
2232 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2234 struct diff_queue_struct *q = &diff_queued_diff;
2235 int i;
2236 int result = diff_get_patch_id(options, sha1);
2238 for (i = 0; i < q->nr; i++)
2239 diff_free_filepair(q->queue[i]);
2241 free(q->queue);
2242 q->queue = NULL;
2243 q->nr = q->alloc = 0;
2245 return result;
2248 static int is_summary_empty(const struct diff_queue_struct *q)
2250 int i;
2252 for (i = 0; i < q->nr; i++) {
2253 const struct diff_filepair *p = q->queue[i];
2255 switch (p->status) {
2256 case DIFF_STATUS_DELETED:
2257 case DIFF_STATUS_ADDED:
2258 case DIFF_STATUS_COPIED:
2259 case DIFF_STATUS_RENAMED:
2260 return 0;
2261 default:
2262 if (p->score)
2263 return 0;
2264 if (p->one->mode && p->two->mode &&
2265 p->one->mode != p->two->mode)
2266 return 0;
2267 break;
2270 return 1;
2273 void diff_flush(struct diff_options *options)
2275 struct diff_queue_struct *q = &diff_queued_diff;
2276 int i, output_format = options->output_format;
2277 int separator = 0;
2280 * Order: raw, stat, summary, patch
2281 * or: name/name-status/checkdiff (other bits clear)
2283 if (!q->nr)
2284 goto free_queue;
2286 if (output_format & (DIFF_FORMAT_RAW |
2287 DIFF_FORMAT_NAME |
2288 DIFF_FORMAT_NAME_STATUS |
2289 DIFF_FORMAT_CHECKDIFF)) {
2290 for (i = 0; i < q->nr; i++) {
2291 struct diff_filepair *p = q->queue[i];
2292 if (check_pair_status(p))
2293 flush_one_pair(p, options);
2295 separator++;
2298 if (output_format & DIFF_FORMAT_DIFFSTAT) {
2299 struct diffstat_t diffstat;
2301 memset(&diffstat, 0, sizeof(struct diffstat_t));
2302 diffstat.xm.consume = diffstat_consume;
2303 for (i = 0; i < q->nr; i++) {
2304 struct diff_filepair *p = q->queue[i];
2305 if (check_pair_status(p))
2306 diff_flush_stat(p, options, &diffstat);
2308 show_stats(&diffstat);
2309 separator++;
2312 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2313 for (i = 0; i < q->nr; i++)
2314 diff_summary(q->queue[i]);
2315 separator++;
2318 if (output_format & DIFF_FORMAT_PATCH) {
2319 if (separator) {
2320 if (options->stat_sep) {
2321 /* attach patch instead of inline */
2322 fputs(options->stat_sep, stdout);
2323 } else {
2324 putchar(options->line_termination);
2328 for (i = 0; i < q->nr; i++) {
2329 struct diff_filepair *p = q->queue[i];
2330 if (check_pair_status(p))
2331 diff_flush_patch(p, options);
2335 for (i = 0; i < q->nr; i++)
2336 diff_free_filepair(q->queue[i]);
2337 free_queue:
2338 free(q->queue);
2339 q->queue = NULL;
2340 q->nr = q->alloc = 0;
2343 static void diffcore_apply_filter(const char *filter)
2345 int i;
2346 struct diff_queue_struct *q = &diff_queued_diff;
2347 struct diff_queue_struct outq;
2348 outq.queue = NULL;
2349 outq.nr = outq.alloc = 0;
2351 if (!filter)
2352 return;
2354 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2355 int found;
2356 for (i = found = 0; !found && i < q->nr; i++) {
2357 struct diff_filepair *p = q->queue[i];
2358 if (((p->status == DIFF_STATUS_MODIFIED) &&
2359 ((p->score &&
2360 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2361 (!p->score &&
2362 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2363 ((p->status != DIFF_STATUS_MODIFIED) &&
2364 strchr(filter, p->status)))
2365 found++;
2367 if (found)
2368 return;
2370 /* otherwise we will clear the whole queue
2371 * by copying the empty outq at the end of this
2372 * function, but first clear the current entries
2373 * in the queue.
2375 for (i = 0; i < q->nr; i++)
2376 diff_free_filepair(q->queue[i]);
2378 else {
2379 /* Only the matching ones */
2380 for (i = 0; i < q->nr; i++) {
2381 struct diff_filepair *p = q->queue[i];
2383 if (((p->status == DIFF_STATUS_MODIFIED) &&
2384 ((p->score &&
2385 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2386 (!p->score &&
2387 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2388 ((p->status != DIFF_STATUS_MODIFIED) &&
2389 strchr(filter, p->status)))
2390 diff_q(&outq, p);
2391 else
2392 diff_free_filepair(p);
2395 free(q->queue);
2396 *q = outq;
2399 void diffcore_std(struct diff_options *options)
2401 if (options->break_opt != -1)
2402 diffcore_break(options->break_opt);
2403 if (options->detect_rename)
2404 diffcore_rename(options);
2405 if (options->break_opt != -1)
2406 diffcore_merge_broken();
2407 if (options->pickaxe)
2408 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2409 if (options->orderfile)
2410 diffcore_order(options->orderfile);
2411 diff_resolve_rename_copy();
2412 diffcore_apply_filter(options->filter);
2416 void diffcore_std_no_resolve(struct diff_options *options)
2418 if (options->pickaxe)
2419 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2420 if (options->orderfile)
2421 diffcore_order(options->orderfile);
2422 diffcore_apply_filter(options->filter);
2425 void diff_addremove(struct diff_options *options,
2426 int addremove, unsigned mode,
2427 const unsigned char *sha1,
2428 const char *base, const char *path)
2430 char concatpath[PATH_MAX];
2431 struct diff_filespec *one, *two;
2433 /* This may look odd, but it is a preparation for
2434 * feeding "there are unchanged files which should
2435 * not produce diffs, but when you are doing copy
2436 * detection you would need them, so here they are"
2437 * entries to the diff-core. They will be prefixed
2438 * with something like '=' or '*' (I haven't decided
2439 * which but should not make any difference).
2440 * Feeding the same new and old to diff_change()
2441 * also has the same effect.
2442 * Before the final output happens, they are pruned after
2443 * merged into rename/copy pairs as appropriate.
2445 if (options->reverse_diff)
2446 addremove = (addremove == '+' ? '-' :
2447 addremove == '-' ? '+' : addremove);
2449 if (!path) path = "";
2450 sprintf(concatpath, "%s%s", base, path);
2451 one = alloc_filespec(concatpath);
2452 two = alloc_filespec(concatpath);
2454 if (addremove != '+')
2455 fill_filespec(one, sha1, mode);
2456 if (addremove != '-')
2457 fill_filespec(two, sha1, mode);
2459 diff_queue(&diff_queued_diff, one, two);
2462 void diff_change(struct diff_options *options,
2463 unsigned old_mode, unsigned new_mode,
2464 const unsigned char *old_sha1,
2465 const unsigned char *new_sha1,
2466 const char *base, const char *path)
2468 char concatpath[PATH_MAX];
2469 struct diff_filespec *one, *two;
2471 if (options->reverse_diff) {
2472 unsigned tmp;
2473 const unsigned char *tmp_c;
2474 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2475 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2477 if (!path) path = "";
2478 sprintf(concatpath, "%s%s", base, path);
2479 one = alloc_filespec(concatpath);
2480 two = alloc_filespec(concatpath);
2481 fill_filespec(one, old_sha1, old_mode);
2482 fill_filespec(two, new_sha1, new_mode);
2484 diff_queue(&diff_queued_diff, one, two);
2487 void diff_unmerge(struct diff_options *options,
2488 const char *path)
2490 struct diff_filespec *one, *two;
2491 one = alloc_filespec(path);
2492 two = alloc_filespec(path);
2493 diff_queue(&diff_queued_diff, one, two);