git-format-patch: now built-in.
[git/gitweb.git] / diff.c
blobbe459cac6946fffeba71301416dd9443c1d44eff
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 int diff_rename_limit_default = -1;
18 int git_diff_config(const char *var, const char *value)
20 if (!strcmp(var, "diff.renamelimit")) {
21 diff_rename_limit_default = git_config_int(var, value);
22 return 0;
25 return git_default_config(var, value);
28 static char *quote_one(const char *str)
30 int needlen;
31 char *xp;
33 if (!str)
34 return NULL;
35 needlen = quote_c_style(str, NULL, NULL, 0);
36 if (!needlen)
37 return strdup(str);
38 xp = xmalloc(needlen + 1);
39 quote_c_style(str, xp, NULL, 0);
40 return xp;
43 static char *quote_two(const char *one, const char *two)
45 int need_one = quote_c_style(one, NULL, NULL, 1);
46 int need_two = quote_c_style(two, NULL, NULL, 1);
47 char *xp;
49 if (need_one + need_two) {
50 if (!need_one) need_one = strlen(one);
51 if (!need_two) need_one = strlen(two);
53 xp = xmalloc(need_one + need_two + 3);
54 xp[0] = '"';
55 quote_c_style(one, xp + 1, NULL, 1);
56 quote_c_style(two, xp + need_one + 1, NULL, 1);
57 strcpy(xp + need_one + need_two + 1, "\"");
58 return xp;
60 need_one = strlen(one);
61 need_two = strlen(two);
62 xp = xmalloc(need_one + need_two + 1);
63 strcpy(xp, one);
64 strcpy(xp + need_one, two);
65 return xp;
68 static const char *external_diff(void)
70 static const char *external_diff_cmd = NULL;
71 static int done_preparing = 0;
73 if (done_preparing)
74 return external_diff_cmd;
75 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
76 done_preparing = 1;
77 return external_diff_cmd;
80 #define TEMPFILE_PATH_LEN 50
82 static struct diff_tempfile {
83 const char *name; /* filename external diff should read from */
84 char hex[41];
85 char mode[10];
86 char tmp_path[TEMPFILE_PATH_LEN];
87 } diff_temp[2];
89 static int count_lines(const char *data, int size)
91 int count, ch, completely_empty = 1, nl_just_seen = 0;
92 count = 0;
93 while (0 < size--) {
94 ch = *data++;
95 if (ch == '\n') {
96 count++;
97 nl_just_seen = 1;
98 completely_empty = 0;
100 else {
101 nl_just_seen = 0;
102 completely_empty = 0;
105 if (completely_empty)
106 return 0;
107 if (!nl_just_seen)
108 count++; /* no trailing newline */
109 return count;
112 static void print_line_count(int count)
114 switch (count) {
115 case 0:
116 printf("0,0");
117 break;
118 case 1:
119 printf("1");
120 break;
121 default:
122 printf("1,%d", count);
123 break;
127 static void copy_file(int prefix, const char *data, int size)
129 int ch, nl_just_seen = 1;
130 while (0 < size--) {
131 ch = *data++;
132 if (nl_just_seen)
133 putchar(prefix);
134 putchar(ch);
135 if (ch == '\n')
136 nl_just_seen = 1;
137 else
138 nl_just_seen = 0;
140 if (!nl_just_seen)
141 printf("\n\\ No newline at end of file\n");
144 static void emit_rewrite_diff(const char *name_a,
145 const char *name_b,
146 struct diff_filespec *one,
147 struct diff_filespec *two)
149 int lc_a, lc_b;
150 diff_populate_filespec(one, 0);
151 diff_populate_filespec(two, 0);
152 lc_a = count_lines(one->data, one->size);
153 lc_b = count_lines(two->data, two->size);
154 printf("--- %s\n+++ %s\n@@ -", name_a, name_b);
155 print_line_count(lc_a);
156 printf(" +");
157 print_line_count(lc_b);
158 printf(" @@\n");
159 if (lc_a)
160 copy_file('-', one->data, one->size);
161 if (lc_b)
162 copy_file('+', two->data, two->size);
165 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
167 if (!DIFF_FILE_VALID(one)) {
168 mf->ptr = ""; /* does not matter */
169 mf->size = 0;
170 return 0;
172 else if (diff_populate_filespec(one, 0))
173 return -1;
174 mf->ptr = one->data;
175 mf->size = one->size;
176 return 0;
179 struct emit_callback {
180 const char **label_path;
183 static int fn_out(void *priv, mmbuffer_t *mb, int nbuf)
185 int i;
186 struct emit_callback *ecbdata = priv;
188 if (ecbdata->label_path[0]) {
189 printf("--- %s\n", ecbdata->label_path[0]);
190 printf("+++ %s\n", ecbdata->label_path[1]);
191 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
193 for (i = 0; i < nbuf; i++)
194 if (!fwrite(mb[i].ptr, mb[i].size, 1, stdout))
195 return -1;
196 return 0;
199 static char *pprint_rename(const char *a, const char *b)
201 const char *old = a;
202 const char *new = b;
203 char *name = NULL;
204 int pfx_length, sfx_length;
205 int len_a = strlen(a);
206 int len_b = strlen(b);
208 /* Find common prefix */
209 pfx_length = 0;
210 while (*old && *new && *old == *new) {
211 if (*old == '/')
212 pfx_length = old - a + 1;
213 old++;
214 new++;
217 /* Find common suffix */
218 old = a + len_a;
219 new = b + len_b;
220 sfx_length = 0;
221 while (a <= old && b <= new && *old == *new) {
222 if (*old == '/')
223 sfx_length = len_a - (old - a);
224 old--;
225 new--;
229 * pfx{mid-a => mid-b}sfx
230 * {pfx-a => pfx-b}sfx
231 * pfx{sfx-a => sfx-b}
232 * name-a => name-b
234 if (pfx_length + sfx_length) {
235 int a_midlen = len_a - pfx_length - sfx_length;
236 int b_midlen = len_b - pfx_length - sfx_length;
237 if (a_midlen < 0) a_midlen = 0;
238 if (b_midlen < 0) b_midlen = 0;
240 name = xmalloc(len_a + len_b - pfx_length - sfx_length + 7);
241 sprintf(name, "%.*s{%.*s => %.*s}%s",
242 pfx_length, a,
243 a_midlen, a + pfx_length,
244 b_midlen, b + pfx_length,
245 a + len_a - sfx_length);
247 else {
248 name = xmalloc(len_a + len_b + 5);
249 sprintf(name, "%s => %s", a, b);
251 return name;
254 struct diffstat_t {
255 struct xdiff_emit_state xm;
257 int nr;
258 int alloc;
259 struct diffstat_file {
260 char *name;
261 unsigned is_unmerged:1;
262 unsigned is_binary:1;
263 unsigned is_renamed:1;
264 unsigned int added, deleted;
265 } **files;
268 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
269 const char *name_a,
270 const char *name_b)
272 struct diffstat_file *x;
273 x = xcalloc(sizeof (*x), 1);
274 if (diffstat->nr == diffstat->alloc) {
275 diffstat->alloc = alloc_nr(diffstat->alloc);
276 diffstat->files = xrealloc(diffstat->files,
277 diffstat->alloc * sizeof(x));
279 diffstat->files[diffstat->nr++] = x;
280 if (name_b) {
281 x->name = pprint_rename(name_a, name_b);
282 x->is_renamed = 1;
284 else
285 x->name = strdup(name_a);
286 return x;
289 static void diffstat_consume(void *priv, char *line, unsigned long len)
291 struct diffstat_t *diffstat = priv;
292 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
294 if (line[0] == '+')
295 x->added++;
296 else if (line[0] == '-')
297 x->deleted++;
300 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
301 static const char minuses[]= "----------------------------------------------------------------------";
302 const char mime_boundary_leader[] = "------------";
304 static void show_stats(struct diffstat_t* data)
306 int i, len, add, del, total, adds = 0, dels = 0;
307 int max, max_change = 0, max_len = 0;
308 int total_files = data->nr;
310 if (data->nr == 0)
311 return;
313 for (i = 0; i < data->nr; i++) {
314 struct diffstat_file *file = data->files[i];
316 len = strlen(file->name);
317 if (max_len < len)
318 max_len = len;
320 if (file->is_binary || file->is_unmerged)
321 continue;
322 if (max_change < file->added + file->deleted)
323 max_change = file->added + file->deleted;
326 for (i = 0; i < data->nr; i++) {
327 char *prefix = "";
328 char *name = data->files[i]->name;
329 int added = data->files[i]->added;
330 int deleted = data->files[i]->deleted;
332 if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
333 char *qname = xmalloc(len + 1);
334 quote_c_style(name, qname, NULL, 0);
335 free(name);
336 data->files[i]->name = name = qname;
340 * "scale" the filename
342 len = strlen(name);
343 max = max_len;
344 if (max > 50)
345 max = 50;
346 if (len > max) {
347 char *slash;
348 prefix = "...";
349 max -= 3;
350 name += len - max;
351 slash = strchr(name, '/');
352 if (slash)
353 name = slash;
355 len = max;
358 * scale the add/delete
360 max = max_change;
361 if (max + len > 70)
362 max = 70 - len;
364 if (data->files[i]->is_binary) {
365 printf(" %s%-*s | Bin\n", prefix, len, name);
366 goto free_diffstat_file;
368 else if (data->files[i]->is_unmerged) {
369 printf(" %s%-*s | Unmerged\n", prefix, len, name);
370 goto free_diffstat_file;
372 else if (!data->files[i]->is_renamed &&
373 (added + deleted == 0)) {
374 total_files--;
375 goto free_diffstat_file;
378 add = added;
379 del = deleted;
380 total = add + del;
381 adds += add;
382 dels += del;
384 if (max_change > 0) {
385 total = (total * max + max_change / 2) / max_change;
386 add = (add * max + max_change / 2) / max_change;
387 del = total - add;
389 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
390 len, name, added + deleted,
391 add, pluses, del, minuses);
392 free_diffstat_file:
393 free(data->files[i]->name);
394 free(data->files[i]);
396 free(data->files);
397 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
398 total_files, adds, dels);
401 struct checkdiff_t {
402 struct xdiff_emit_state xm;
403 const char *filename;
404 int lineno;
407 static void checkdiff_consume(void *priv, char *line, unsigned long len)
409 struct checkdiff_t *data = priv;
411 if (line[0] == '+') {
412 int i, spaces = 0;
414 data->lineno++;
416 /* check space before tab */
417 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
418 if (line[i] == ' ')
419 spaces++;
420 if (line[i - 1] == '\t' && spaces)
421 printf("%s:%d: space before tab:%.*s\n",
422 data->filename, data->lineno, (int)len, line);
424 /* check white space at line end */
425 if (line[len - 1] == '\n')
426 len--;
427 if (isspace(line[len - 1]))
428 printf("%s:%d: white space at end: %.*s\n",
429 data->filename, data->lineno, (int)len, line);
430 } else if (line[0] == ' ')
431 data->lineno++;
432 else if (line[0] == '@') {
433 char *plus = strchr(line, '+');
434 if (plus)
435 data->lineno = strtol(plus, line + len, 10);
436 else
437 die("invalid diff");
441 static unsigned char *deflate_it(char *data,
442 unsigned long size,
443 unsigned long *result_size)
445 int bound;
446 unsigned char *deflated;
447 z_stream stream;
449 memset(&stream, 0, sizeof(stream));
450 deflateInit(&stream, Z_BEST_COMPRESSION);
451 bound = deflateBound(&stream, size);
452 deflated = xmalloc(bound);
453 stream.next_out = deflated;
454 stream.avail_out = bound;
456 stream.next_in = (unsigned char *)data;
457 stream.avail_in = size;
458 while (deflate(&stream, Z_FINISH) == Z_OK)
459 ; /* nothing */
460 deflateEnd(&stream);
461 *result_size = stream.total_out;
462 return deflated;
465 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
467 void *cp;
468 void *delta;
469 void *deflated;
470 void *data;
471 unsigned long orig_size;
472 unsigned long delta_size;
473 unsigned long deflate_size;
474 unsigned long data_size;
476 printf("GIT binary patch\n");
477 /* We could do deflated delta, or we could do just deflated two,
478 * whichever is smaller.
480 delta = NULL;
481 deflated = deflate_it(two->ptr, two->size, &deflate_size);
482 if (one->size && two->size) {
483 delta = diff_delta(one->ptr, one->size,
484 two->ptr, two->size,
485 &delta_size, deflate_size);
486 if (delta) {
487 void *to_free = delta;
488 orig_size = delta_size;
489 delta = deflate_it(delta, delta_size, &delta_size);
490 free(to_free);
494 if (delta && delta_size < deflate_size) {
495 printf("delta %lu\n", orig_size);
496 free(deflated);
497 data = delta;
498 data_size = delta_size;
500 else {
501 printf("literal %lu\n", two->size);
502 free(delta);
503 data = deflated;
504 data_size = deflate_size;
507 /* emit data encoded in base85 */
508 cp = data;
509 while (data_size) {
510 int bytes = (52 < data_size) ? 52 : data_size;
511 char line[70];
512 data_size -= bytes;
513 if (bytes <= 26)
514 line[0] = bytes + 'A' - 1;
515 else
516 line[0] = bytes - 26 + 'a' - 1;
517 encode_85(line + 1, cp, bytes);
518 cp += bytes;
519 puts(line);
521 printf("\n");
522 free(data);
525 #define FIRST_FEW_BYTES 8000
526 static int mmfile_is_binary(mmfile_t *mf)
528 long sz = mf->size;
529 if (FIRST_FEW_BYTES < sz)
530 sz = FIRST_FEW_BYTES;
531 if (memchr(mf->ptr, 0, sz))
532 return 1;
533 return 0;
536 static void builtin_diff(const char *name_a,
537 const char *name_b,
538 struct diff_filespec *one,
539 struct diff_filespec *two,
540 const char *xfrm_msg,
541 struct diff_options *o,
542 int complete_rewrite)
544 mmfile_t mf1, mf2;
545 const char *lbl[2];
546 char *a_one, *b_two;
548 a_one = quote_two("a/", name_a);
549 b_two = quote_two("b/", name_b);
550 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
551 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
552 printf("diff --git %s %s\n", a_one, b_two);
553 if (lbl[0][0] == '/') {
554 /* /dev/null */
555 printf("new file mode %06o\n", two->mode);
556 if (xfrm_msg && xfrm_msg[0])
557 puts(xfrm_msg);
559 else if (lbl[1][0] == '/') {
560 printf("deleted file mode %06o\n", one->mode);
561 if (xfrm_msg && xfrm_msg[0])
562 puts(xfrm_msg);
564 else {
565 if (one->mode != two->mode) {
566 printf("old mode %06o\n", one->mode);
567 printf("new mode %06o\n", two->mode);
569 if (xfrm_msg && xfrm_msg[0])
570 puts(xfrm_msg);
572 * we do not run diff between different kind
573 * of objects.
575 if ((one->mode ^ two->mode) & S_IFMT)
576 goto free_ab_and_return;
577 if (complete_rewrite) {
578 emit_rewrite_diff(name_a, name_b, one, two);
579 goto free_ab_and_return;
583 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
584 die("unable to read files to diff");
586 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2)) {
587 /* Quite common confusing case */
588 if (mf1.size == mf2.size &&
589 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
590 goto free_ab_and_return;
591 if (o->binary)
592 emit_binary_diff(&mf1, &mf2);
593 else
594 printf("Binary files %s and %s differ\n",
595 lbl[0], lbl[1]);
597 else {
598 /* Crazy xdl interfaces.. */
599 const char *diffopts = getenv("GIT_DIFF_OPTS");
600 xpparam_t xpp;
601 xdemitconf_t xecfg;
602 xdemitcb_t ecb;
603 struct emit_callback ecbdata;
605 ecbdata.label_path = lbl;
606 xpp.flags = XDF_NEED_MINIMAL;
607 xecfg.ctxlen = o->context;
608 xecfg.flags = XDL_EMIT_FUNCNAMES;
609 if (!diffopts)
611 else if (!strncmp(diffopts, "--unified=", 10))
612 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
613 else if (!strncmp(diffopts, "-u", 2))
614 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
615 ecb.outf = fn_out;
616 ecb.priv = &ecbdata;
617 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
620 free_ab_and_return:
621 free(a_one);
622 free(b_two);
623 return;
626 static void builtin_diffstat(const char *name_a, const char *name_b,
627 struct diff_filespec *one,
628 struct diff_filespec *two,
629 struct diffstat_t *diffstat,
630 int complete_rewrite)
632 mmfile_t mf1, mf2;
633 struct diffstat_file *data;
635 data = diffstat_add(diffstat, name_a, name_b);
637 if (!one || !two) {
638 data->is_unmerged = 1;
639 return;
641 if (complete_rewrite) {
642 diff_populate_filespec(one, 0);
643 diff_populate_filespec(two, 0);
644 data->deleted = count_lines(one->data, one->size);
645 data->added = count_lines(two->data, two->size);
646 return;
648 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
649 die("unable to read files to diff");
651 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
652 data->is_binary = 1;
653 else {
654 /* Crazy xdl interfaces.. */
655 xpparam_t xpp;
656 xdemitconf_t xecfg;
657 xdemitcb_t ecb;
659 xpp.flags = XDF_NEED_MINIMAL;
660 xecfg.ctxlen = 0;
661 xecfg.flags = 0;
662 ecb.outf = xdiff_outf;
663 ecb.priv = diffstat;
664 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
668 static void builtin_checkdiff(const char *name_a, const char *name_b,
669 struct diff_filespec *one,
670 struct diff_filespec *two)
672 mmfile_t mf1, mf2;
673 struct checkdiff_t data;
675 if (!two)
676 return;
678 memset(&data, 0, sizeof(data));
679 data.xm.consume = checkdiff_consume;
680 data.filename = name_b ? name_b : name_a;
681 data.lineno = 0;
683 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
684 die("unable to read files to diff");
686 if (mmfile_is_binary(&mf2))
687 return;
688 else {
689 /* Crazy xdl interfaces.. */
690 xpparam_t xpp;
691 xdemitconf_t xecfg;
692 xdemitcb_t ecb;
694 xpp.flags = XDF_NEED_MINIMAL;
695 xecfg.ctxlen = 0;
696 xecfg.flags = 0;
697 ecb.outf = xdiff_outf;
698 ecb.priv = &data;
699 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
703 struct diff_filespec *alloc_filespec(const char *path)
705 int namelen = strlen(path);
706 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
708 memset(spec, 0, sizeof(*spec));
709 spec->path = (char *)(spec + 1);
710 memcpy(spec->path, path, namelen+1);
711 return spec;
714 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
715 unsigned short mode)
717 if (mode) {
718 spec->mode = canon_mode(mode);
719 memcpy(spec->sha1, sha1, 20);
720 spec->sha1_valid = !!memcmp(sha1, null_sha1, 20);
725 * Given a name and sha1 pair, if the dircache tells us the file in
726 * the work tree has that object contents, return true, so that
727 * prepare_temp_file() does not have to inflate and extract.
729 static int work_tree_matches(const char *name, const unsigned char *sha1)
731 struct cache_entry *ce;
732 struct stat st;
733 int pos, len;
735 /* We do not read the cache ourselves here, because the
736 * benchmark with my previous version that always reads cache
737 * shows that it makes things worse for diff-tree comparing
738 * two linux-2.6 kernel trees in an already checked out work
739 * tree. This is because most diff-tree comparisons deal with
740 * only a small number of files, while reading the cache is
741 * expensive for a large project, and its cost outweighs the
742 * savings we get by not inflating the object to a temporary
743 * file. Practically, this code only helps when we are used
744 * by diff-cache --cached, which does read the cache before
745 * calling us.
747 if (!active_cache)
748 return 0;
750 len = strlen(name);
751 pos = cache_name_pos(name, len);
752 if (pos < 0)
753 return 0;
754 ce = active_cache[pos];
755 if ((lstat(name, &st) < 0) ||
756 !S_ISREG(st.st_mode) || /* careful! */
757 ce_match_stat(ce, &st, 0) ||
758 memcmp(sha1, ce->sha1, 20))
759 return 0;
760 /* we return 1 only when we can stat, it is a regular file,
761 * stat information matches, and sha1 recorded in the cache
762 * matches. I.e. we know the file in the work tree really is
763 * the same as the <name, sha1> pair.
765 return 1;
768 static struct sha1_size_cache {
769 unsigned char sha1[20];
770 unsigned long size;
771 } **sha1_size_cache;
772 static int sha1_size_cache_nr, sha1_size_cache_alloc;
774 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
775 int find_only,
776 unsigned long size)
778 int first, last;
779 struct sha1_size_cache *e;
781 first = 0;
782 last = sha1_size_cache_nr;
783 while (last > first) {
784 int cmp, next = (last + first) >> 1;
785 e = sha1_size_cache[next];
786 cmp = memcmp(e->sha1, sha1, 20);
787 if (!cmp)
788 return e;
789 if (cmp < 0) {
790 last = next;
791 continue;
793 first = next+1;
795 /* not found */
796 if (find_only)
797 return NULL;
798 /* insert to make it at "first" */
799 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
800 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
801 sha1_size_cache = xrealloc(sha1_size_cache,
802 sha1_size_cache_alloc *
803 sizeof(*sha1_size_cache));
805 sha1_size_cache_nr++;
806 if (first < sha1_size_cache_nr)
807 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
808 (sha1_size_cache_nr - first - 1) *
809 sizeof(*sha1_size_cache));
810 e = xmalloc(sizeof(struct sha1_size_cache));
811 sha1_size_cache[first] = e;
812 memcpy(e->sha1, sha1, 20);
813 e->size = size;
814 return e;
818 * While doing rename detection and pickaxe operation, we may need to
819 * grab the data for the blob (or file) for our own in-core comparison.
820 * diff_filespec has data and size fields for this purpose.
822 int diff_populate_filespec(struct diff_filespec *s, int size_only)
824 int err = 0;
825 if (!DIFF_FILE_VALID(s))
826 die("internal error: asking to populate invalid file.");
827 if (S_ISDIR(s->mode))
828 return -1;
830 if (!use_size_cache)
831 size_only = 0;
833 if (s->data)
834 return err;
835 if (!s->sha1_valid ||
836 work_tree_matches(s->path, s->sha1)) {
837 struct stat st;
838 int fd;
839 if (lstat(s->path, &st) < 0) {
840 if (errno == ENOENT) {
841 err_empty:
842 err = -1;
843 empty:
844 s->data = "";
845 s->size = 0;
846 return err;
849 s->size = st.st_size;
850 if (!s->size)
851 goto empty;
852 if (size_only)
853 return 0;
854 if (S_ISLNK(st.st_mode)) {
855 int ret;
856 s->data = xmalloc(s->size);
857 s->should_free = 1;
858 ret = readlink(s->path, s->data, s->size);
859 if (ret < 0) {
860 free(s->data);
861 goto err_empty;
863 return 0;
865 fd = open(s->path, O_RDONLY);
866 if (fd < 0)
867 goto err_empty;
868 s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
869 close(fd);
870 if (s->data == MAP_FAILED)
871 goto err_empty;
872 s->should_munmap = 1;
874 else {
875 char type[20];
876 struct sha1_size_cache *e;
878 if (size_only) {
879 e = locate_size_cache(s->sha1, 1, 0);
880 if (e) {
881 s->size = e->size;
882 return 0;
884 if (!sha1_object_info(s->sha1, type, &s->size))
885 locate_size_cache(s->sha1, 0, s->size);
887 else {
888 s->data = read_sha1_file(s->sha1, type, &s->size);
889 s->should_free = 1;
892 return 0;
895 void diff_free_filespec_data(struct diff_filespec *s)
897 if (s->should_free)
898 free(s->data);
899 else if (s->should_munmap)
900 munmap(s->data, s->size);
901 s->should_free = s->should_munmap = 0;
902 s->data = NULL;
903 free(s->cnt_data);
904 s->cnt_data = NULL;
907 static void prep_temp_blob(struct diff_tempfile *temp,
908 void *blob,
909 unsigned long size,
910 const unsigned char *sha1,
911 int mode)
913 int fd;
915 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
916 if (fd < 0)
917 die("unable to create temp-file");
918 if (write(fd, blob, size) != size)
919 die("unable to write temp-file");
920 close(fd);
921 temp->name = temp->tmp_path;
922 strcpy(temp->hex, sha1_to_hex(sha1));
923 temp->hex[40] = 0;
924 sprintf(temp->mode, "%06o", mode);
927 static void prepare_temp_file(const char *name,
928 struct diff_tempfile *temp,
929 struct diff_filespec *one)
931 if (!DIFF_FILE_VALID(one)) {
932 not_a_valid_file:
933 /* A '-' entry produces this for file-2, and
934 * a '+' entry produces this for file-1.
936 temp->name = "/dev/null";
937 strcpy(temp->hex, ".");
938 strcpy(temp->mode, ".");
939 return;
942 if (!one->sha1_valid ||
943 work_tree_matches(name, one->sha1)) {
944 struct stat st;
945 if (lstat(name, &st) < 0) {
946 if (errno == ENOENT)
947 goto not_a_valid_file;
948 die("stat(%s): %s", name, strerror(errno));
950 if (S_ISLNK(st.st_mode)) {
951 int ret;
952 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
953 if (sizeof(buf) <= st.st_size)
954 die("symlink too long: %s", name);
955 ret = readlink(name, buf, st.st_size);
956 if (ret < 0)
957 die("readlink(%s)", name);
958 prep_temp_blob(temp, buf, st.st_size,
959 (one->sha1_valid ?
960 one->sha1 : null_sha1),
961 (one->sha1_valid ?
962 one->mode : S_IFLNK));
964 else {
965 /* we can borrow from the file in the work tree */
966 temp->name = name;
967 if (!one->sha1_valid)
968 strcpy(temp->hex, sha1_to_hex(null_sha1));
969 else
970 strcpy(temp->hex, sha1_to_hex(one->sha1));
971 /* Even though we may sometimes borrow the
972 * contents from the work tree, we always want
973 * one->mode. mode is trustworthy even when
974 * !(one->sha1_valid), as long as
975 * DIFF_FILE_VALID(one).
977 sprintf(temp->mode, "%06o", one->mode);
979 return;
981 else {
982 if (diff_populate_filespec(one, 0))
983 die("cannot read data blob for %s", one->path);
984 prep_temp_blob(temp, one->data, one->size,
985 one->sha1, one->mode);
989 static void remove_tempfile(void)
991 int i;
993 for (i = 0; i < 2; i++)
994 if (diff_temp[i].name == diff_temp[i].tmp_path) {
995 unlink(diff_temp[i].name);
996 diff_temp[i].name = NULL;
1000 static void remove_tempfile_on_signal(int signo)
1002 remove_tempfile();
1003 signal(SIGINT, SIG_DFL);
1004 raise(signo);
1007 static int spawn_prog(const char *pgm, const char **arg)
1009 pid_t pid;
1010 int status;
1012 fflush(NULL);
1013 pid = fork();
1014 if (pid < 0)
1015 die("unable to fork");
1016 if (!pid) {
1017 execvp(pgm, (char *const*) arg);
1018 exit(255);
1021 while (waitpid(pid, &status, 0) < 0) {
1022 if (errno == EINTR)
1023 continue;
1024 return -1;
1027 /* Earlier we did not check the exit status because
1028 * diff exits non-zero if files are different, and
1029 * we are not interested in knowing that. It was a
1030 * mistake which made it harder to quit a diff-*
1031 * session that uses the git-apply-patch-script as
1032 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1033 * should also exit non-zero only when it wants to
1034 * abort the entire diff-* session.
1036 if (WIFEXITED(status) && !WEXITSTATUS(status))
1037 return 0;
1038 return -1;
1041 /* An external diff command takes:
1043 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1044 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1047 static void run_external_diff(const char *pgm,
1048 const char *name,
1049 const char *other,
1050 struct diff_filespec *one,
1051 struct diff_filespec *two,
1052 const char *xfrm_msg,
1053 int complete_rewrite)
1055 const char *spawn_arg[10];
1056 struct diff_tempfile *temp = diff_temp;
1057 int retval;
1058 static int atexit_asked = 0;
1059 const char *othername;
1060 const char **arg = &spawn_arg[0];
1062 othername = (other? other : name);
1063 if (one && two) {
1064 prepare_temp_file(name, &temp[0], one);
1065 prepare_temp_file(othername, &temp[1], two);
1066 if (! atexit_asked &&
1067 (temp[0].name == temp[0].tmp_path ||
1068 temp[1].name == temp[1].tmp_path)) {
1069 atexit_asked = 1;
1070 atexit(remove_tempfile);
1072 signal(SIGINT, remove_tempfile_on_signal);
1075 if (one && two) {
1076 *arg++ = pgm;
1077 *arg++ = name;
1078 *arg++ = temp[0].name;
1079 *arg++ = temp[0].hex;
1080 *arg++ = temp[0].mode;
1081 *arg++ = temp[1].name;
1082 *arg++ = temp[1].hex;
1083 *arg++ = temp[1].mode;
1084 if (other) {
1085 *arg++ = other;
1086 *arg++ = xfrm_msg;
1088 } else {
1089 *arg++ = pgm;
1090 *arg++ = name;
1092 *arg = NULL;
1093 retval = spawn_prog(pgm, spawn_arg);
1094 remove_tempfile();
1095 if (retval) {
1096 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1097 exit(1);
1101 static void run_diff_cmd(const char *pgm,
1102 const char *name,
1103 const char *other,
1104 struct diff_filespec *one,
1105 struct diff_filespec *two,
1106 const char *xfrm_msg,
1107 struct diff_options *o,
1108 int complete_rewrite)
1110 if (pgm) {
1111 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1112 complete_rewrite);
1113 return;
1115 if (one && two)
1116 builtin_diff(name, other ? other : name,
1117 one, two, xfrm_msg, o, complete_rewrite);
1118 else
1119 printf("* Unmerged path %s\n", name);
1122 static void diff_fill_sha1_info(struct diff_filespec *one)
1124 if (DIFF_FILE_VALID(one)) {
1125 if (!one->sha1_valid) {
1126 struct stat st;
1127 if (lstat(one->path, &st) < 0)
1128 die("stat %s", one->path);
1129 if (index_path(one->sha1, one->path, &st, 0))
1130 die("cannot hash %s\n", one->path);
1133 else
1134 memset(one->sha1, 0, 20);
1137 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1139 const char *pgm = external_diff();
1140 char msg[PATH_MAX*2+300], *xfrm_msg;
1141 struct diff_filespec *one;
1142 struct diff_filespec *two;
1143 const char *name;
1144 const char *other;
1145 char *name_munged, *other_munged;
1146 int complete_rewrite = 0;
1147 int len;
1149 if (DIFF_PAIR_UNMERGED(p)) {
1150 /* unmerged */
1151 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1152 return;
1155 name = p->one->path;
1156 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1157 name_munged = quote_one(name);
1158 other_munged = quote_one(other);
1159 one = p->one; two = p->two;
1161 diff_fill_sha1_info(one);
1162 diff_fill_sha1_info(two);
1164 len = 0;
1165 switch (p->status) {
1166 case DIFF_STATUS_COPIED:
1167 len += snprintf(msg + len, sizeof(msg) - len,
1168 "similarity index %d%%\n"
1169 "copy from %s\n"
1170 "copy to %s\n",
1171 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1172 name_munged, other_munged);
1173 break;
1174 case DIFF_STATUS_RENAMED:
1175 len += snprintf(msg + len, sizeof(msg) - len,
1176 "similarity index %d%%\n"
1177 "rename from %s\n"
1178 "rename to %s\n",
1179 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1180 name_munged, other_munged);
1181 break;
1182 case DIFF_STATUS_MODIFIED:
1183 if (p->score) {
1184 len += snprintf(msg + len, sizeof(msg) - len,
1185 "dissimilarity index %d%%\n",
1186 (int)(0.5 + p->score *
1187 100.0/MAX_SCORE));
1188 complete_rewrite = 1;
1189 break;
1191 /* fallthru */
1192 default:
1193 /* nothing */
1197 if (memcmp(one->sha1, two->sha1, 20)) {
1198 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1200 len += snprintf(msg + len, sizeof(msg) - len,
1201 "index %.*s..%.*s",
1202 abbrev, sha1_to_hex(one->sha1),
1203 abbrev, sha1_to_hex(two->sha1));
1204 if (one->mode == two->mode)
1205 len += snprintf(msg + len, sizeof(msg) - len,
1206 " %06o", one->mode);
1207 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1210 if (len)
1211 msg[--len] = 0;
1212 xfrm_msg = len ? msg : NULL;
1214 if (!pgm &&
1215 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1216 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1217 /* a filepair that changes between file and symlink
1218 * needs to be split into deletion and creation.
1220 struct diff_filespec *null = alloc_filespec(two->path);
1221 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1222 free(null);
1223 null = alloc_filespec(one->path);
1224 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1225 free(null);
1227 else
1228 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1229 complete_rewrite);
1231 free(name_munged);
1232 free(other_munged);
1235 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1236 struct diffstat_t *diffstat)
1238 const char *name;
1239 const char *other;
1240 int complete_rewrite = 0;
1242 if (DIFF_PAIR_UNMERGED(p)) {
1243 /* unmerged */
1244 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, 0);
1245 return;
1248 name = p->one->path;
1249 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1251 diff_fill_sha1_info(p->one);
1252 diff_fill_sha1_info(p->two);
1254 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1255 complete_rewrite = 1;
1256 builtin_diffstat(name, other, p->one, p->two, diffstat, complete_rewrite);
1259 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1261 const char *name;
1262 const char *other;
1264 if (DIFF_PAIR_UNMERGED(p)) {
1265 /* unmerged */
1266 return;
1269 name = p->one->path;
1270 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1272 diff_fill_sha1_info(p->one);
1273 diff_fill_sha1_info(p->two);
1275 builtin_checkdiff(name, other, p->one, p->two);
1278 void diff_setup(struct diff_options *options)
1280 memset(options, 0, sizeof(*options));
1281 options->output_format = DIFF_FORMAT_RAW;
1282 options->line_termination = '\n';
1283 options->break_opt = -1;
1284 options->rename_limit = -1;
1285 options->context = 3;
1287 options->change = diff_change;
1288 options->add_remove = diff_addremove;
1291 int diff_setup_done(struct diff_options *options)
1293 if ((options->find_copies_harder &&
1294 options->detect_rename != DIFF_DETECT_COPY) ||
1295 (0 <= options->rename_limit && !options->detect_rename))
1296 return -1;
1299 * These cases always need recursive; we do not drop caller-supplied
1300 * recursive bits for other formats here.
1302 if ((options->output_format == DIFF_FORMAT_PATCH) ||
1303 (options->output_format == DIFF_FORMAT_DIFFSTAT) ||
1304 (options->output_format == DIFF_FORMAT_CHECKDIFF))
1305 options->recursive = 1;
1307 if (options->detect_rename && options->rename_limit < 0)
1308 options->rename_limit = diff_rename_limit_default;
1309 if (options->setup & DIFF_SETUP_USE_CACHE) {
1310 if (!active_cache)
1311 /* read-cache does not die even when it fails
1312 * so it is safe for us to do this here. Also
1313 * it does not smudge active_cache or active_nr
1314 * when it fails, so we do not have to worry about
1315 * cleaning it up ourselves either.
1317 read_cache();
1319 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1320 use_size_cache = 1;
1321 if (options->abbrev <= 0 || 40 < options->abbrev)
1322 options->abbrev = 40; /* full */
1324 return 0;
1327 int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1329 char c, *eq;
1330 int len;
1332 if (*arg != '-')
1333 return 0;
1334 c = *++arg;
1335 if (!c)
1336 return 0;
1337 if (c == arg_short) {
1338 c = *++arg;
1339 if (!c)
1340 return 1;
1341 if (val && isdigit(c)) {
1342 char *end;
1343 int n = strtoul(arg, &end, 10);
1344 if (*end)
1345 return 0;
1346 *val = n;
1347 return 1;
1349 return 0;
1351 if (c != '-')
1352 return 0;
1353 arg++;
1354 eq = strchr(arg, '=');
1355 if (eq)
1356 len = eq - arg;
1357 else
1358 len = strlen(arg);
1359 if (!len || strncmp(arg, arg_long, len))
1360 return 0;
1361 if (eq) {
1362 int n;
1363 char *end;
1364 if (!isdigit(*++eq))
1365 return 0;
1366 n = strtoul(eq, &end, 10);
1367 if (*end)
1368 return 0;
1369 *val = n;
1371 return 1;
1374 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1376 const char *arg = av[0];
1377 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1378 options->output_format = DIFF_FORMAT_PATCH;
1379 else if (opt_arg(arg, 'U', "unified", &options->context))
1380 options->output_format = DIFF_FORMAT_PATCH;
1381 else if (!strcmp(arg, "--patch-with-raw")) {
1382 options->output_format = DIFF_FORMAT_PATCH;
1383 options->with_raw = 1;
1385 else if (!strcmp(arg, "--stat"))
1386 options->output_format = DIFF_FORMAT_DIFFSTAT;
1387 else if (!strcmp(arg, "--check"))
1388 options->output_format = DIFF_FORMAT_CHECKDIFF;
1389 else if (!strcmp(arg, "--summary"))
1390 options->summary = 1;
1391 else if (!strcmp(arg, "--patch-with-stat")) {
1392 options->output_format = DIFF_FORMAT_PATCH;
1393 options->with_stat = 1;
1395 else if (!strcmp(arg, "-z"))
1396 options->line_termination = 0;
1397 else if (!strncmp(arg, "-l", 2))
1398 options->rename_limit = strtoul(arg+2, NULL, 10);
1399 else if (!strcmp(arg, "--full-index"))
1400 options->full_index = 1;
1401 else if (!strcmp(arg, "--binary")) {
1402 options->output_format = DIFF_FORMAT_PATCH;
1403 options->full_index = options->binary = 1;
1405 else if (!strcmp(arg, "--name-only"))
1406 options->output_format = DIFF_FORMAT_NAME;
1407 else if (!strcmp(arg, "--name-status"))
1408 options->output_format = DIFF_FORMAT_NAME_STATUS;
1409 else if (!strcmp(arg, "-R"))
1410 options->reverse_diff = 1;
1411 else if (!strncmp(arg, "-S", 2))
1412 options->pickaxe = arg + 2;
1413 else if (!strcmp(arg, "-s"))
1414 options->output_format = DIFF_FORMAT_NO_OUTPUT;
1415 else if (!strncmp(arg, "-O", 2))
1416 options->orderfile = arg + 2;
1417 else if (!strncmp(arg, "--diff-filter=", 14))
1418 options->filter = arg + 14;
1419 else if (!strcmp(arg, "--pickaxe-all"))
1420 options->pickaxe_opts = DIFF_PICKAXE_ALL;
1421 else if (!strcmp(arg, "--pickaxe-regex"))
1422 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
1423 else if (!strncmp(arg, "-B", 2)) {
1424 if ((options->break_opt =
1425 diff_scoreopt_parse(arg)) == -1)
1426 return -1;
1428 else if (!strncmp(arg, "-M", 2)) {
1429 if ((options->rename_score =
1430 diff_scoreopt_parse(arg)) == -1)
1431 return -1;
1432 options->detect_rename = DIFF_DETECT_RENAME;
1434 else if (!strncmp(arg, "-C", 2)) {
1435 if ((options->rename_score =
1436 diff_scoreopt_parse(arg)) == -1)
1437 return -1;
1438 options->detect_rename = DIFF_DETECT_COPY;
1440 else if (!strcmp(arg, "--find-copies-harder"))
1441 options->find_copies_harder = 1;
1442 else if (!strcmp(arg, "--abbrev"))
1443 options->abbrev = DEFAULT_ABBREV;
1444 else if (!strncmp(arg, "--abbrev=", 9)) {
1445 options->abbrev = strtoul(arg + 9, NULL, 10);
1446 if (options->abbrev < MINIMUM_ABBREV)
1447 options->abbrev = MINIMUM_ABBREV;
1448 else if (40 < options->abbrev)
1449 options->abbrev = 40;
1451 else
1452 return 0;
1453 return 1;
1456 static int parse_num(const char **cp_p)
1458 unsigned long num, scale;
1459 int ch, dot;
1460 const char *cp = *cp_p;
1462 num = 0;
1463 scale = 1;
1464 dot = 0;
1465 for(;;) {
1466 ch = *cp;
1467 if ( !dot && ch == '.' ) {
1468 scale = 1;
1469 dot = 1;
1470 } else if ( ch == '%' ) {
1471 scale = dot ? scale*100 : 100;
1472 cp++; /* % is always at the end */
1473 break;
1474 } else if ( ch >= '0' && ch <= '9' ) {
1475 if ( scale < 100000 ) {
1476 scale *= 10;
1477 num = (num*10) + (ch-'0');
1479 } else {
1480 break;
1482 cp++;
1484 *cp_p = cp;
1486 /* user says num divided by scale and we say internally that
1487 * is MAX_SCORE * num / scale.
1489 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
1492 int diff_scoreopt_parse(const char *opt)
1494 int opt1, opt2, cmd;
1496 if (*opt++ != '-')
1497 return -1;
1498 cmd = *opt++;
1499 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
1500 return -1; /* that is not a -M, -C nor -B option */
1502 opt1 = parse_num(&opt);
1503 if (cmd != 'B')
1504 opt2 = 0;
1505 else {
1506 if (*opt == 0)
1507 opt2 = 0;
1508 else if (*opt != '/')
1509 return -1; /* we expect -B80/99 or -B80 */
1510 else {
1511 opt++;
1512 opt2 = parse_num(&opt);
1515 if (*opt != 0)
1516 return -1;
1517 return opt1 | (opt2 << 16);
1520 struct diff_queue_struct diff_queued_diff;
1522 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
1524 if (queue->alloc <= queue->nr) {
1525 queue->alloc = alloc_nr(queue->alloc);
1526 queue->queue = xrealloc(queue->queue,
1527 sizeof(dp) * queue->alloc);
1529 queue->queue[queue->nr++] = dp;
1532 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
1533 struct diff_filespec *one,
1534 struct diff_filespec *two)
1536 struct diff_filepair *dp = xmalloc(sizeof(*dp));
1537 dp->one = one;
1538 dp->two = two;
1539 dp->score = 0;
1540 dp->status = 0;
1541 dp->source_stays = 0;
1542 dp->broken_pair = 0;
1543 if (queue)
1544 diff_q(queue, dp);
1545 return dp;
1548 void diff_free_filepair(struct diff_filepair *p)
1550 diff_free_filespec_data(p->one);
1551 diff_free_filespec_data(p->two);
1552 free(p->one);
1553 free(p->two);
1554 free(p);
1557 /* This is different from find_unique_abbrev() in that
1558 * it stuffs the result with dots for alignment.
1560 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
1562 int abblen;
1563 const char *abbrev;
1564 if (len == 40)
1565 return sha1_to_hex(sha1);
1567 abbrev = find_unique_abbrev(sha1, len);
1568 if (!abbrev)
1569 return sha1_to_hex(sha1);
1570 abblen = strlen(abbrev);
1571 if (abblen < 37) {
1572 static char hex[41];
1573 if (len < abblen && abblen <= len + 2)
1574 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
1575 else
1576 sprintf(hex, "%s...", abbrev);
1577 return hex;
1579 return sha1_to_hex(sha1);
1582 static void diff_flush_raw(struct diff_filepair *p,
1583 int line_termination,
1584 int inter_name_termination,
1585 struct diff_options *options,
1586 int output_format)
1588 int two_paths;
1589 char status[10];
1590 int abbrev = options->abbrev;
1591 const char *path_one, *path_two;
1593 path_one = p->one->path;
1594 path_two = p->two->path;
1595 if (line_termination) {
1596 path_one = quote_one(path_one);
1597 path_two = quote_one(path_two);
1600 if (p->score)
1601 sprintf(status, "%c%03d", p->status,
1602 (int)(0.5 + p->score * 100.0/MAX_SCORE));
1603 else {
1604 status[0] = p->status;
1605 status[1] = 0;
1607 switch (p->status) {
1608 case DIFF_STATUS_COPIED:
1609 case DIFF_STATUS_RENAMED:
1610 two_paths = 1;
1611 break;
1612 case DIFF_STATUS_ADDED:
1613 case DIFF_STATUS_DELETED:
1614 two_paths = 0;
1615 break;
1616 default:
1617 two_paths = 0;
1618 break;
1620 if (output_format != DIFF_FORMAT_NAME_STATUS) {
1621 printf(":%06o %06o %s ",
1622 p->one->mode, p->two->mode,
1623 diff_unique_abbrev(p->one->sha1, abbrev));
1624 printf("%s ",
1625 diff_unique_abbrev(p->two->sha1, abbrev));
1627 printf("%s%c%s", status, inter_name_termination, path_one);
1628 if (two_paths)
1629 printf("%c%s", inter_name_termination, path_two);
1630 putchar(line_termination);
1631 if (path_one != p->one->path)
1632 free((void*)path_one);
1633 if (path_two != p->two->path)
1634 free((void*)path_two);
1637 static void diff_flush_name(struct diff_filepair *p,
1638 int inter_name_termination,
1639 int line_termination)
1641 char *path = p->two->path;
1643 if (line_termination)
1644 path = quote_one(p->two->path);
1645 else
1646 path = p->two->path;
1647 printf("%s%c", path, line_termination);
1648 if (p->two->path != path)
1649 free(path);
1652 int diff_unmodified_pair(struct diff_filepair *p)
1654 /* This function is written stricter than necessary to support
1655 * the currently implemented transformers, but the idea is to
1656 * let transformers to produce diff_filepairs any way they want,
1657 * and filter and clean them up here before producing the output.
1659 struct diff_filespec *one, *two;
1661 if (DIFF_PAIR_UNMERGED(p))
1662 return 0; /* unmerged is interesting */
1664 one = p->one;
1665 two = p->two;
1667 /* deletion, addition, mode or type change
1668 * and rename are all interesting.
1670 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
1671 DIFF_PAIR_MODE_CHANGED(p) ||
1672 strcmp(one->path, two->path))
1673 return 0;
1675 /* both are valid and point at the same path. that is, we are
1676 * dealing with a change.
1678 if (one->sha1_valid && two->sha1_valid &&
1679 !memcmp(one->sha1, two->sha1, sizeof(one->sha1)))
1680 return 1; /* no change */
1681 if (!one->sha1_valid && !two->sha1_valid)
1682 return 1; /* both look at the same file on the filesystem. */
1683 return 0;
1686 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
1688 if (diff_unmodified_pair(p))
1689 return;
1691 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1692 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1693 return; /* no tree diffs in patch format */
1695 run_diff(p, o);
1698 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
1699 struct diffstat_t *diffstat)
1701 if (diff_unmodified_pair(p))
1702 return;
1704 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1705 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1706 return; /* no tree diffs in patch format */
1708 run_diffstat(p, o, diffstat);
1711 static void diff_flush_checkdiff(struct diff_filepair *p,
1712 struct diff_options *o)
1714 if (diff_unmodified_pair(p))
1715 return;
1717 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1718 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1719 return; /* no tree diffs in patch format */
1721 run_checkdiff(p, o);
1724 int diff_queue_is_empty(void)
1726 struct diff_queue_struct *q = &diff_queued_diff;
1727 int i;
1728 for (i = 0; i < q->nr; i++)
1729 if (!diff_unmodified_pair(q->queue[i]))
1730 return 0;
1731 return 1;
1734 #if DIFF_DEBUG
1735 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
1737 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
1738 x, one ? one : "",
1739 s->path,
1740 DIFF_FILE_VALID(s) ? "valid" : "invalid",
1741 s->mode,
1742 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
1743 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
1744 x, one ? one : "",
1745 s->size, s->xfrm_flags);
1748 void diff_debug_filepair(const struct diff_filepair *p, int i)
1750 diff_debug_filespec(p->one, i, "one");
1751 diff_debug_filespec(p->two, i, "two");
1752 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
1753 p->score, p->status ? p->status : '?',
1754 p->source_stays, p->broken_pair);
1757 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
1759 int i;
1760 if (msg)
1761 fprintf(stderr, "%s\n", msg);
1762 fprintf(stderr, "q->nr = %d\n", q->nr);
1763 for (i = 0; i < q->nr; i++) {
1764 struct diff_filepair *p = q->queue[i];
1765 diff_debug_filepair(p, i);
1768 #endif
1770 static void diff_resolve_rename_copy(void)
1772 int i, j;
1773 struct diff_filepair *p, *pp;
1774 struct diff_queue_struct *q = &diff_queued_diff;
1776 diff_debug_queue("resolve-rename-copy", q);
1778 for (i = 0; i < q->nr; i++) {
1779 p = q->queue[i];
1780 p->status = 0; /* undecided */
1781 if (DIFF_PAIR_UNMERGED(p))
1782 p->status = DIFF_STATUS_UNMERGED;
1783 else if (!DIFF_FILE_VALID(p->one))
1784 p->status = DIFF_STATUS_ADDED;
1785 else if (!DIFF_FILE_VALID(p->two))
1786 p->status = DIFF_STATUS_DELETED;
1787 else if (DIFF_PAIR_TYPE_CHANGED(p))
1788 p->status = DIFF_STATUS_TYPE_CHANGED;
1790 /* from this point on, we are dealing with a pair
1791 * whose both sides are valid and of the same type, i.e.
1792 * either in-place edit or rename/copy edit.
1794 else if (DIFF_PAIR_RENAME(p)) {
1795 if (p->source_stays) {
1796 p->status = DIFF_STATUS_COPIED;
1797 continue;
1799 /* See if there is some other filepair that
1800 * copies from the same source as us. If so
1801 * we are a copy. Otherwise we are either a
1802 * copy if the path stays, or a rename if it
1803 * does not, but we already handled "stays" case.
1805 for (j = i + 1; j < q->nr; j++) {
1806 pp = q->queue[j];
1807 if (strcmp(pp->one->path, p->one->path))
1808 continue; /* not us */
1809 if (!DIFF_PAIR_RENAME(pp))
1810 continue; /* not a rename/copy */
1811 /* pp is a rename/copy from the same source */
1812 p->status = DIFF_STATUS_COPIED;
1813 break;
1815 if (!p->status)
1816 p->status = DIFF_STATUS_RENAMED;
1818 else if (memcmp(p->one->sha1, p->two->sha1, 20) ||
1819 p->one->mode != p->two->mode)
1820 p->status = DIFF_STATUS_MODIFIED;
1821 else {
1822 /* This is a "no-change" entry and should not
1823 * happen anymore, but prepare for broken callers.
1825 error("feeding unmodified %s to diffcore",
1826 p->one->path);
1827 p->status = DIFF_STATUS_UNKNOWN;
1830 diff_debug_queue("resolve-rename-copy done", q);
1833 static void flush_one_pair(struct diff_filepair *p,
1834 int diff_output_format,
1835 struct diff_options *options,
1836 struct diffstat_t *diffstat)
1838 int inter_name_termination = '\t';
1839 int line_termination = options->line_termination;
1840 if (!line_termination)
1841 inter_name_termination = 0;
1843 switch (p->status) {
1844 case DIFF_STATUS_UNKNOWN:
1845 break;
1846 case 0:
1847 die("internal error in diff-resolve-rename-copy");
1848 break;
1849 default:
1850 switch (diff_output_format) {
1851 case DIFF_FORMAT_DIFFSTAT:
1852 diff_flush_stat(p, options, diffstat);
1853 break;
1854 case DIFF_FORMAT_CHECKDIFF:
1855 diff_flush_checkdiff(p, options);
1856 break;
1857 case DIFF_FORMAT_PATCH:
1858 diff_flush_patch(p, options);
1859 break;
1860 case DIFF_FORMAT_RAW:
1861 case DIFF_FORMAT_NAME_STATUS:
1862 diff_flush_raw(p, line_termination,
1863 inter_name_termination,
1864 options, diff_output_format);
1865 break;
1866 case DIFF_FORMAT_NAME:
1867 diff_flush_name(p,
1868 inter_name_termination,
1869 line_termination);
1870 break;
1871 case DIFF_FORMAT_NO_OUTPUT:
1872 break;
1877 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
1879 if (fs->mode)
1880 printf(" %s mode %06o %s\n", newdelete, fs->mode, fs->path);
1881 else
1882 printf(" %s %s\n", newdelete, fs->path);
1886 static void show_mode_change(struct diff_filepair *p, int show_name)
1888 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
1889 if (show_name)
1890 printf(" mode change %06o => %06o %s\n",
1891 p->one->mode, p->two->mode, p->two->path);
1892 else
1893 printf(" mode change %06o => %06o\n",
1894 p->one->mode, p->two->mode);
1898 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
1900 const char *old, *new;
1902 /* Find common prefix */
1903 old = p->one->path;
1904 new = p->two->path;
1905 while (1) {
1906 const char *slash_old, *slash_new;
1907 slash_old = strchr(old, '/');
1908 slash_new = strchr(new, '/');
1909 if (!slash_old ||
1910 !slash_new ||
1911 slash_old - old != slash_new - new ||
1912 memcmp(old, new, slash_new - new))
1913 break;
1914 old = slash_old + 1;
1915 new = slash_new + 1;
1917 /* p->one->path thru old is the common prefix, and old and new
1918 * through the end of names are renames
1920 if (old != p->one->path)
1921 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1922 (int)(old - p->one->path), p->one->path,
1923 old, new, (int)(0.5 + p->score * 100.0/MAX_SCORE));
1924 else
1925 printf(" %s %s => %s (%d%%)\n", renamecopy,
1926 p->one->path, p->two->path,
1927 (int)(0.5 + p->score * 100.0/MAX_SCORE));
1928 show_mode_change(p, 0);
1931 static void diff_summary(struct diff_filepair *p)
1933 switch(p->status) {
1934 case DIFF_STATUS_DELETED:
1935 show_file_mode_name("delete", p->one);
1936 break;
1937 case DIFF_STATUS_ADDED:
1938 show_file_mode_name("create", p->two);
1939 break;
1940 case DIFF_STATUS_COPIED:
1941 show_rename_copy("copy", p);
1942 break;
1943 case DIFF_STATUS_RENAMED:
1944 show_rename_copy("rename", p);
1945 break;
1946 default:
1947 if (p->score) {
1948 printf(" rewrite %s (%d%%)\n", p->two->path,
1949 (int)(0.5 + p->score * 100.0/MAX_SCORE));
1950 show_mode_change(p, 0);
1951 } else show_mode_change(p, 1);
1952 break;
1956 void diff_flush(struct diff_options *options)
1958 struct diff_queue_struct *q = &diff_queued_diff;
1959 int i;
1960 int diff_output_format = options->output_format;
1961 struct diffstat_t *diffstat = NULL;
1963 if (diff_output_format == DIFF_FORMAT_DIFFSTAT || options->with_stat) {
1964 diffstat = xcalloc(sizeof (struct diffstat_t), 1);
1965 diffstat->xm.consume = diffstat_consume;
1968 if (options->with_raw) {
1969 for (i = 0; i < q->nr; i++) {
1970 struct diff_filepair *p = q->queue[i];
1971 flush_one_pair(p, DIFF_FORMAT_RAW, options, NULL);
1973 putchar(options->line_termination);
1975 if (options->with_stat) {
1976 for (i = 0; i < q->nr; i++) {
1977 struct diff_filepair *p = q->queue[i];
1978 flush_one_pair(p, DIFF_FORMAT_DIFFSTAT, options,
1979 diffstat);
1981 show_stats(diffstat);
1982 free(diffstat);
1983 diffstat = NULL;
1984 if (options->stat_sep)
1985 fputs(options->stat_sep, stdout);
1986 else
1987 putchar(options->line_termination);
1989 for (i = 0; i < q->nr; i++) {
1990 struct diff_filepair *p = q->queue[i];
1991 flush_one_pair(p, diff_output_format, options, diffstat);
1994 if (diffstat) {
1995 show_stats(diffstat);
1996 free(diffstat);
1999 for (i = 0; i < q->nr; i++) {
2000 if (options->summary)
2001 diff_summary(q->queue[i]);
2002 diff_free_filepair(q->queue[i]);
2005 free(q->queue);
2006 q->queue = NULL;
2007 q->nr = q->alloc = 0;
2010 static void diffcore_apply_filter(const char *filter)
2012 int i;
2013 struct diff_queue_struct *q = &diff_queued_diff;
2014 struct diff_queue_struct outq;
2015 outq.queue = NULL;
2016 outq.nr = outq.alloc = 0;
2018 if (!filter)
2019 return;
2021 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2022 int found;
2023 for (i = found = 0; !found && i < q->nr; i++) {
2024 struct diff_filepair *p = q->queue[i];
2025 if (((p->status == DIFF_STATUS_MODIFIED) &&
2026 ((p->score &&
2027 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2028 (!p->score &&
2029 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2030 ((p->status != DIFF_STATUS_MODIFIED) &&
2031 strchr(filter, p->status)))
2032 found++;
2034 if (found)
2035 return;
2037 /* otherwise we will clear the whole queue
2038 * by copying the empty outq at the end of this
2039 * function, but first clear the current entries
2040 * in the queue.
2042 for (i = 0; i < q->nr; i++)
2043 diff_free_filepair(q->queue[i]);
2045 else {
2046 /* Only the matching ones */
2047 for (i = 0; i < q->nr; i++) {
2048 struct diff_filepair *p = q->queue[i];
2050 if (((p->status == DIFF_STATUS_MODIFIED) &&
2051 ((p->score &&
2052 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2053 (!p->score &&
2054 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2055 ((p->status != DIFF_STATUS_MODIFIED) &&
2056 strchr(filter, p->status)))
2057 diff_q(&outq, p);
2058 else
2059 diff_free_filepair(p);
2062 free(q->queue);
2063 *q = outq;
2066 void diffcore_std(struct diff_options *options)
2068 if (options->break_opt != -1)
2069 diffcore_break(options->break_opt);
2070 if (options->detect_rename)
2071 diffcore_rename(options);
2072 if (options->break_opt != -1)
2073 diffcore_merge_broken();
2074 if (options->pickaxe)
2075 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2076 if (options->orderfile)
2077 diffcore_order(options->orderfile);
2078 diff_resolve_rename_copy();
2079 diffcore_apply_filter(options->filter);
2083 void diffcore_std_no_resolve(struct diff_options *options)
2085 if (options->pickaxe)
2086 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2087 if (options->orderfile)
2088 diffcore_order(options->orderfile);
2089 diffcore_apply_filter(options->filter);
2092 void diff_addremove(struct diff_options *options,
2093 int addremove, unsigned mode,
2094 const unsigned char *sha1,
2095 const char *base, const char *path)
2097 char concatpath[PATH_MAX];
2098 struct diff_filespec *one, *two;
2100 /* This may look odd, but it is a preparation for
2101 * feeding "there are unchanged files which should
2102 * not produce diffs, but when you are doing copy
2103 * detection you would need them, so here they are"
2104 * entries to the diff-core. They will be prefixed
2105 * with something like '=' or '*' (I haven't decided
2106 * which but should not make any difference).
2107 * Feeding the same new and old to diff_change()
2108 * also has the same effect.
2109 * Before the final output happens, they are pruned after
2110 * merged into rename/copy pairs as appropriate.
2112 if (options->reverse_diff)
2113 addremove = (addremove == '+' ? '-' :
2114 addremove == '-' ? '+' : addremove);
2116 if (!path) path = "";
2117 sprintf(concatpath, "%s%s", base, path);
2118 one = alloc_filespec(concatpath);
2119 two = alloc_filespec(concatpath);
2121 if (addremove != '+')
2122 fill_filespec(one, sha1, mode);
2123 if (addremove != '-')
2124 fill_filespec(two, sha1, mode);
2126 diff_queue(&diff_queued_diff, one, two);
2129 void diff_change(struct diff_options *options,
2130 unsigned old_mode, unsigned new_mode,
2131 const unsigned char *old_sha1,
2132 const unsigned char *new_sha1,
2133 const char *base, const char *path)
2135 char concatpath[PATH_MAX];
2136 struct diff_filespec *one, *two;
2138 if (options->reverse_diff) {
2139 unsigned tmp;
2140 const unsigned char *tmp_c;
2141 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2142 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2144 if (!path) path = "";
2145 sprintf(concatpath, "%s%s", base, path);
2146 one = alloc_filespec(concatpath);
2147 two = alloc_filespec(concatpath);
2148 fill_filespec(one, old_sha1, old_mode);
2149 fill_filespec(two, new_sha1, new_mode);
2151 diff_queue(&diff_queued_diff, one, two);
2154 void diff_unmerge(struct diff_options *options,
2155 const char *path)
2157 struct diff_filespec *one, *two;
2158 one = alloc_filespec(path);
2159 two = alloc_filespec(path);
2160 diff_queue(&diff_queued_diff, one, two);