GIT 1.3.0 rc1
[git/mingw/4msysgit/kblees.git] / diff.c
blob5eae0947f35606eab6ff3421fe64fa5cb236f2ad
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 "xdiff/xdiff.h"
13 static int use_size_cache;
15 int diff_rename_limit_default = -1;
17 int git_diff_config(const char *var, const char *value)
19 if (!strcmp(var, "diff.renamelimit")) {
20 diff_rename_limit_default = git_config_int(var, value);
21 return 0;
24 return git_default_config(var, value);
27 static char *quote_one(const char *str)
29 int needlen;
30 char *xp;
32 if (!str)
33 return NULL;
34 needlen = quote_c_style(str, NULL, NULL, 0);
35 if (!needlen)
36 return strdup(str);
37 xp = xmalloc(needlen + 1);
38 quote_c_style(str, xp, NULL, 0);
39 return xp;
42 static char *quote_two(const char *one, const char *two)
44 int need_one = quote_c_style(one, NULL, NULL, 1);
45 int need_two = quote_c_style(two, NULL, NULL, 1);
46 char *xp;
48 if (need_one + need_two) {
49 if (!need_one) need_one = strlen(one);
50 if (!need_two) need_one = strlen(two);
52 xp = xmalloc(need_one + need_two + 3);
53 xp[0] = '"';
54 quote_c_style(one, xp + 1, NULL, 1);
55 quote_c_style(two, xp + need_one + 1, NULL, 1);
56 strcpy(xp + need_one + need_two + 1, "\"");
57 return xp;
59 need_one = strlen(one);
60 need_two = strlen(two);
61 xp = xmalloc(need_one + need_two + 1);
62 strcpy(xp, one);
63 strcpy(xp + need_one, two);
64 return xp;
67 static const char *external_diff(void)
69 static const char *external_diff_cmd = NULL;
70 static int done_preparing = 0;
72 if (done_preparing)
73 return external_diff_cmd;
74 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
75 done_preparing = 1;
76 return external_diff_cmd;
79 #define TEMPFILE_PATH_LEN 50
81 static struct diff_tempfile {
82 const char *name; /* filename external diff should read from */
83 char hex[41];
84 char mode[10];
85 char tmp_path[TEMPFILE_PATH_LEN];
86 } diff_temp[2];
88 static int count_lines(const char *data, int size)
90 int count, ch, completely_empty = 1, nl_just_seen = 0;
91 count = 0;
92 while (0 < size--) {
93 ch = *data++;
94 if (ch == '\n') {
95 count++;
96 nl_just_seen = 1;
97 completely_empty = 0;
99 else {
100 nl_just_seen = 0;
101 completely_empty = 0;
104 if (completely_empty)
105 return 0;
106 if (!nl_just_seen)
107 count++; /* no trailing newline */
108 return count;
111 static void print_line_count(int count)
113 switch (count) {
114 case 0:
115 printf("0,0");
116 break;
117 case 1:
118 printf("1");
119 break;
120 default:
121 printf("1,%d", count);
122 break;
126 static void copy_file(int prefix, const char *data, int size)
128 int ch, nl_just_seen = 1;
129 while (0 < size--) {
130 ch = *data++;
131 if (nl_just_seen)
132 putchar(prefix);
133 putchar(ch);
134 if (ch == '\n')
135 nl_just_seen = 1;
136 else
137 nl_just_seen = 0;
139 if (!nl_just_seen)
140 printf("\n\\ No newline at end of file\n");
143 static void emit_rewrite_diff(const char *name_a,
144 const char *name_b,
145 struct diff_filespec *one,
146 struct diff_filespec *two)
148 /* Use temp[i].name as input, name_a and name_b as labels */
149 int lc_a, lc_b;
150 lc_a = count_lines(one->data, one->size);
151 lc_b = count_lines(two->data, two->size);
152 printf("--- %s\n+++ %s\n@@ -", name_a, name_b);
153 print_line_count(lc_a);
154 printf(" +");
155 print_line_count(lc_b);
156 printf(" @@\n");
157 if (lc_a)
158 copy_file('-', one->data, one->size);
159 if (lc_b)
160 copy_file('+', two->data, two->size);
163 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
165 if (!DIFF_FILE_VALID(one)) {
166 mf->ptr = ""; /* does not matter */
167 mf->size = 0;
168 return 0;
170 else if (diff_populate_filespec(one, 0))
171 return -1;
172 mf->ptr = one->data;
173 mf->size = one->size;
174 return 0;
177 struct emit_callback {
178 const char **label_path;
181 static int fn_out(void *priv, mmbuffer_t *mb, int nbuf)
183 int i;
184 struct emit_callback *ecbdata = priv;
186 if (ecbdata->label_path[0]) {
187 printf("--- %s\n", ecbdata->label_path[0]);
188 printf("+++ %s\n", ecbdata->label_path[1]);
189 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
191 for (i = 0; i < nbuf; i++)
192 if (!fwrite(mb[i].ptr, mb[i].size, 1, stdout))
193 return -1;
194 return 0;
197 #define FIRST_FEW_BYTES 8000
198 static int mmfile_is_binary(mmfile_t *mf)
200 long sz = mf->size;
201 if (FIRST_FEW_BYTES < sz)
202 sz = FIRST_FEW_BYTES;
203 if (memchr(mf->ptr, 0, sz))
204 return 1;
205 return 0;
208 static void builtin_diff(const char *name_a,
209 const char *name_b,
210 struct diff_filespec *one,
211 struct diff_filespec *two,
212 const char *xfrm_msg,
213 int complete_rewrite)
215 mmfile_t mf1, mf2;
216 const char *lbl[2];
217 char *a_one, *b_two;
219 a_one = quote_two("a/", name_a);
220 b_two = quote_two("b/", name_b);
221 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
222 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
223 printf("diff --git %s %s\n", a_one, b_two);
224 if (lbl[0][0] == '/') {
225 /* /dev/null */
226 printf("new file mode %06o\n", two->mode);
227 if (xfrm_msg && xfrm_msg[0])
228 puts(xfrm_msg);
230 else if (lbl[1][0] == '/') {
231 printf("deleted file mode %06o\n", one->mode);
232 if (xfrm_msg && xfrm_msg[0])
233 puts(xfrm_msg);
235 else {
236 if (one->mode != two->mode) {
237 printf("old mode %06o\n", one->mode);
238 printf("new mode %06o\n", two->mode);
240 if (xfrm_msg && xfrm_msg[0])
241 puts(xfrm_msg);
243 * we do not run diff between different kind
244 * of objects.
246 if ((one->mode ^ two->mode) & S_IFMT)
247 goto free_ab_and_return;
248 if (complete_rewrite) {
249 emit_rewrite_diff(name_a, name_b, one, two);
250 goto free_ab_and_return;
254 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
255 die("unable to read files to diff");
257 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
258 printf("Binary files %s and %s differ\n", lbl[0], lbl[1]);
259 else {
260 /* Crazy xdl interfaces.. */
261 const char *diffopts = getenv("GIT_DIFF_OPTS");
262 xpparam_t xpp;
263 xdemitconf_t xecfg;
264 xdemitcb_t ecb;
265 struct emit_callback ecbdata;
267 ecbdata.label_path = lbl;
268 xpp.flags = XDF_NEED_MINIMAL;
269 xecfg.ctxlen = 3;
270 if (!diffopts)
272 else if (!strncmp(diffopts, "--unified=", 10))
273 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
274 else if (!strncmp(diffopts, "-u", 2))
275 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
276 ecb.outf = fn_out;
277 ecb.priv = &ecbdata;
278 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
281 free_ab_and_return:
282 free(a_one);
283 free(b_two);
284 return;
287 struct diff_filespec *alloc_filespec(const char *path)
289 int namelen = strlen(path);
290 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
292 memset(spec, 0, sizeof(*spec));
293 spec->path = (char *)(spec + 1);
294 memcpy(spec->path, path, namelen+1);
295 return spec;
298 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
299 unsigned short mode)
301 if (mode) {
302 spec->mode = DIFF_FILE_CANON_MODE(mode);
303 memcpy(spec->sha1, sha1, 20);
304 spec->sha1_valid = !!memcmp(sha1, null_sha1, 20);
309 * Given a name and sha1 pair, if the dircache tells us the file in
310 * the work tree has that object contents, return true, so that
311 * prepare_temp_file() does not have to inflate and extract.
313 static int work_tree_matches(const char *name, const unsigned char *sha1)
315 struct cache_entry *ce;
316 struct stat st;
317 int pos, len;
319 /* We do not read the cache ourselves here, because the
320 * benchmark with my previous version that always reads cache
321 * shows that it makes things worse for diff-tree comparing
322 * two linux-2.6 kernel trees in an already checked out work
323 * tree. This is because most diff-tree comparisons deal with
324 * only a small number of files, while reading the cache is
325 * expensive for a large project, and its cost outweighs the
326 * savings we get by not inflating the object to a temporary
327 * file. Practically, this code only helps when we are used
328 * by diff-cache --cached, which does read the cache before
329 * calling us.
331 if (!active_cache)
332 return 0;
334 len = strlen(name);
335 pos = cache_name_pos(name, len);
336 if (pos < 0)
337 return 0;
338 ce = active_cache[pos];
339 if ((lstat(name, &st) < 0) ||
340 !S_ISREG(st.st_mode) || /* careful! */
341 ce_match_stat(ce, &st, 0) ||
342 memcmp(sha1, ce->sha1, 20))
343 return 0;
344 /* we return 1 only when we can stat, it is a regular file,
345 * stat information matches, and sha1 recorded in the cache
346 * matches. I.e. we know the file in the work tree really is
347 * the same as the <name, sha1> pair.
349 return 1;
352 static struct sha1_size_cache {
353 unsigned char sha1[20];
354 unsigned long size;
355 } **sha1_size_cache;
356 static int sha1_size_cache_nr, sha1_size_cache_alloc;
358 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
359 int find_only,
360 unsigned long size)
362 int first, last;
363 struct sha1_size_cache *e;
365 first = 0;
366 last = sha1_size_cache_nr;
367 while (last > first) {
368 int cmp, next = (last + first) >> 1;
369 e = sha1_size_cache[next];
370 cmp = memcmp(e->sha1, sha1, 20);
371 if (!cmp)
372 return e;
373 if (cmp < 0) {
374 last = next;
375 continue;
377 first = next+1;
379 /* not found */
380 if (find_only)
381 return NULL;
382 /* insert to make it at "first" */
383 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
384 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
385 sha1_size_cache = xrealloc(sha1_size_cache,
386 sha1_size_cache_alloc *
387 sizeof(*sha1_size_cache));
389 sha1_size_cache_nr++;
390 if (first < sha1_size_cache_nr)
391 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
392 (sha1_size_cache_nr - first - 1) *
393 sizeof(*sha1_size_cache));
394 e = xmalloc(sizeof(struct sha1_size_cache));
395 sha1_size_cache[first] = e;
396 memcpy(e->sha1, sha1, 20);
397 e->size = size;
398 return e;
402 * While doing rename detection and pickaxe operation, we may need to
403 * grab the data for the blob (or file) for our own in-core comparison.
404 * diff_filespec has data and size fields for this purpose.
406 int diff_populate_filespec(struct diff_filespec *s, int size_only)
408 int err = 0;
409 if (!DIFF_FILE_VALID(s))
410 die("internal error: asking to populate invalid file.");
411 if (S_ISDIR(s->mode))
412 return -1;
414 if (!use_size_cache)
415 size_only = 0;
417 if (s->data)
418 return err;
419 if (!s->sha1_valid ||
420 work_tree_matches(s->path, s->sha1)) {
421 struct stat st;
422 int fd;
423 if (lstat(s->path, &st) < 0) {
424 if (errno == ENOENT) {
425 err_empty:
426 err = -1;
427 empty:
428 s->data = "";
429 s->size = 0;
430 return err;
433 s->size = st.st_size;
434 if (!s->size)
435 goto empty;
436 if (size_only)
437 return 0;
438 if (S_ISLNK(st.st_mode)) {
439 int ret;
440 s->data = xmalloc(s->size);
441 s->should_free = 1;
442 ret = readlink(s->path, s->data, s->size);
443 if (ret < 0) {
444 free(s->data);
445 goto err_empty;
447 return 0;
449 fd = open(s->path, O_RDONLY);
450 if (fd < 0)
451 goto err_empty;
452 s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
453 close(fd);
454 if (s->data == MAP_FAILED)
455 goto err_empty;
456 s->should_munmap = 1;
458 else {
459 char type[20];
460 struct sha1_size_cache *e;
462 if (size_only) {
463 e = locate_size_cache(s->sha1, 1, 0);
464 if (e) {
465 s->size = e->size;
466 return 0;
468 if (!sha1_object_info(s->sha1, type, &s->size))
469 locate_size_cache(s->sha1, 0, s->size);
471 else {
472 s->data = read_sha1_file(s->sha1, type, &s->size);
473 s->should_free = 1;
476 return 0;
479 void diff_free_filespec_data(struct diff_filespec *s)
481 if (s->should_free)
482 free(s->data);
483 else if (s->should_munmap)
484 munmap(s->data, s->size);
485 s->should_free = s->should_munmap = 0;
486 s->data = NULL;
487 free(s->cnt_data);
488 s->cnt_data = NULL;
491 static void prep_temp_blob(struct diff_tempfile *temp,
492 void *blob,
493 unsigned long size,
494 const unsigned char *sha1,
495 int mode)
497 int fd;
499 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
500 if (fd < 0)
501 die("unable to create temp-file");
502 if (write(fd, blob, size) != size)
503 die("unable to write temp-file");
504 close(fd);
505 temp->name = temp->tmp_path;
506 strcpy(temp->hex, sha1_to_hex(sha1));
507 temp->hex[40] = 0;
508 sprintf(temp->mode, "%06o", mode);
511 static void prepare_temp_file(const char *name,
512 struct diff_tempfile *temp,
513 struct diff_filespec *one)
515 if (!DIFF_FILE_VALID(one)) {
516 not_a_valid_file:
517 /* A '-' entry produces this for file-2, and
518 * a '+' entry produces this for file-1.
520 temp->name = "/dev/null";
521 strcpy(temp->hex, ".");
522 strcpy(temp->mode, ".");
523 return;
526 if (!one->sha1_valid ||
527 work_tree_matches(name, one->sha1)) {
528 struct stat st;
529 if (lstat(name, &st) < 0) {
530 if (errno == ENOENT)
531 goto not_a_valid_file;
532 die("stat(%s): %s", name, strerror(errno));
534 if (S_ISLNK(st.st_mode)) {
535 int ret;
536 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
537 if (sizeof(buf) <= st.st_size)
538 die("symlink too long: %s", name);
539 ret = readlink(name, buf, st.st_size);
540 if (ret < 0)
541 die("readlink(%s)", name);
542 prep_temp_blob(temp, buf, st.st_size,
543 (one->sha1_valid ?
544 one->sha1 : null_sha1),
545 (one->sha1_valid ?
546 one->mode : S_IFLNK));
548 else {
549 /* we can borrow from the file in the work tree */
550 temp->name = name;
551 if (!one->sha1_valid)
552 strcpy(temp->hex, sha1_to_hex(null_sha1));
553 else
554 strcpy(temp->hex, sha1_to_hex(one->sha1));
555 /* Even though we may sometimes borrow the
556 * contents from the work tree, we always want
557 * one->mode. mode is trustworthy even when
558 * !(one->sha1_valid), as long as
559 * DIFF_FILE_VALID(one).
561 sprintf(temp->mode, "%06o", one->mode);
563 return;
565 else {
566 if (diff_populate_filespec(one, 0))
567 die("cannot read data blob for %s", one->path);
568 prep_temp_blob(temp, one->data, one->size,
569 one->sha1, one->mode);
573 static void remove_tempfile(void)
575 int i;
577 for (i = 0; i < 2; i++)
578 if (diff_temp[i].name == diff_temp[i].tmp_path) {
579 unlink(diff_temp[i].name);
580 diff_temp[i].name = NULL;
584 static void remove_tempfile_on_signal(int signo)
586 remove_tempfile();
587 signal(SIGINT, SIG_DFL);
588 raise(signo);
591 static int spawn_prog(const char *pgm, const char **arg)
593 pid_t pid;
594 int status;
596 fflush(NULL);
597 pid = fork();
598 if (pid < 0)
599 die("unable to fork");
600 if (!pid) {
601 execvp(pgm, (char *const*) arg);
602 exit(255);
605 while (waitpid(pid, &status, 0) < 0) {
606 if (errno == EINTR)
607 continue;
608 return -1;
611 /* Earlier we did not check the exit status because
612 * diff exits non-zero if files are different, and
613 * we are not interested in knowing that. It was a
614 * mistake which made it harder to quit a diff-*
615 * session that uses the git-apply-patch-script as
616 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
617 * should also exit non-zero only when it wants to
618 * abort the entire diff-* session.
620 if (WIFEXITED(status) && !WEXITSTATUS(status))
621 return 0;
622 return -1;
625 /* An external diff command takes:
627 * diff-cmd name infile1 infile1-sha1 infile1-mode \
628 * infile2 infile2-sha1 infile2-mode [ rename-to ]
631 static void run_external_diff(const char *pgm,
632 const char *name,
633 const char *other,
634 struct diff_filespec *one,
635 struct diff_filespec *two,
636 const char *xfrm_msg,
637 int complete_rewrite)
639 const char *spawn_arg[10];
640 struct diff_tempfile *temp = diff_temp;
641 int retval;
642 static int atexit_asked = 0;
643 const char *othername;
644 const char **arg = &spawn_arg[0];
646 othername = (other? other : name);
647 if (one && two) {
648 prepare_temp_file(name, &temp[0], one);
649 prepare_temp_file(othername, &temp[1], two);
650 if (! atexit_asked &&
651 (temp[0].name == temp[0].tmp_path ||
652 temp[1].name == temp[1].tmp_path)) {
653 atexit_asked = 1;
654 atexit(remove_tempfile);
656 signal(SIGINT, remove_tempfile_on_signal);
659 if (one && two) {
660 *arg++ = pgm;
661 *arg++ = name;
662 *arg++ = temp[0].name;
663 *arg++ = temp[0].hex;
664 *arg++ = temp[0].mode;
665 *arg++ = temp[1].name;
666 *arg++ = temp[1].hex;
667 *arg++ = temp[1].mode;
668 if (other) {
669 *arg++ = other;
670 *arg++ = xfrm_msg;
672 } else {
673 *arg++ = pgm;
674 *arg++ = name;
676 *arg = NULL;
677 retval = spawn_prog(pgm, spawn_arg);
678 remove_tempfile();
679 if (retval) {
680 fprintf(stderr, "external diff died, stopping at %s.\n", name);
681 exit(1);
685 static void run_diff_cmd(const char *pgm,
686 const char *name,
687 const char *other,
688 struct diff_filespec *one,
689 struct diff_filespec *two,
690 const char *xfrm_msg,
691 int complete_rewrite)
693 if (pgm) {
694 run_external_diff(pgm, name, other, one, two, xfrm_msg,
695 complete_rewrite);
696 return;
698 if (one && two)
699 builtin_diff(name, other ? other : name,
700 one, two, xfrm_msg, complete_rewrite);
701 else
702 printf("* Unmerged path %s\n", name);
705 static void diff_fill_sha1_info(struct diff_filespec *one)
707 if (DIFF_FILE_VALID(one)) {
708 if (!one->sha1_valid) {
709 struct stat st;
710 if (lstat(one->path, &st) < 0)
711 die("stat %s", one->path);
712 if (index_path(one->sha1, one->path, &st, 0))
713 die("cannot hash %s\n", one->path);
716 else
717 memset(one->sha1, 0, 20);
720 static void run_diff(struct diff_filepair *p, struct diff_options *o)
722 const char *pgm = external_diff();
723 char msg[PATH_MAX*2+300], *xfrm_msg;
724 struct diff_filespec *one;
725 struct diff_filespec *two;
726 const char *name;
727 const char *other;
728 char *name_munged, *other_munged;
729 int complete_rewrite = 0;
730 int len;
732 if (DIFF_PAIR_UNMERGED(p)) {
733 /* unmerged */
734 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, 0);
735 return;
738 name = p->one->path;
739 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
740 name_munged = quote_one(name);
741 other_munged = quote_one(other);
742 one = p->one; two = p->two;
744 diff_fill_sha1_info(one);
745 diff_fill_sha1_info(two);
747 len = 0;
748 switch (p->status) {
749 case DIFF_STATUS_COPIED:
750 len += snprintf(msg + len, sizeof(msg) - len,
751 "similarity index %d%%\n"
752 "copy from %s\n"
753 "copy to %s\n",
754 (int)(0.5 + p->score * 100.0/MAX_SCORE),
755 name_munged, other_munged);
756 break;
757 case DIFF_STATUS_RENAMED:
758 len += snprintf(msg + len, sizeof(msg) - len,
759 "similarity index %d%%\n"
760 "rename from %s\n"
761 "rename to %s\n",
762 (int)(0.5 + p->score * 100.0/MAX_SCORE),
763 name_munged, other_munged);
764 break;
765 case DIFF_STATUS_MODIFIED:
766 if (p->score) {
767 len += snprintf(msg + len, sizeof(msg) - len,
768 "dissimilarity index %d%%\n",
769 (int)(0.5 + p->score *
770 100.0/MAX_SCORE));
771 complete_rewrite = 1;
772 break;
774 /* fallthru */
775 default:
776 /* nothing */
780 if (memcmp(one->sha1, two->sha1, 20)) {
781 char one_sha1[41];
782 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
783 memcpy(one_sha1, sha1_to_hex(one->sha1), 41);
785 len += snprintf(msg + len, sizeof(msg) - len,
786 "index %.*s..%.*s",
787 abbrev, one_sha1, abbrev,
788 sha1_to_hex(two->sha1));
789 if (one->mode == two->mode)
790 len += snprintf(msg + len, sizeof(msg) - len,
791 " %06o", one->mode);
792 len += snprintf(msg + len, sizeof(msg) - len, "\n");
795 if (len)
796 msg[--len] = 0;
797 xfrm_msg = len ? msg : NULL;
799 if (!pgm &&
800 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
801 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
802 /* a filepair that changes between file and symlink
803 * needs to be split into deletion and creation.
805 struct diff_filespec *null = alloc_filespec(two->path);
806 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, 0);
807 free(null);
808 null = alloc_filespec(one->path);
809 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, 0);
810 free(null);
812 else
813 run_diff_cmd(pgm, name, other, one, two, xfrm_msg,
814 complete_rewrite);
816 free(name_munged);
817 free(other_munged);
820 void diff_setup(struct diff_options *options)
822 memset(options, 0, sizeof(*options));
823 options->output_format = DIFF_FORMAT_RAW;
824 options->line_termination = '\n';
825 options->break_opt = -1;
826 options->rename_limit = -1;
828 options->change = diff_change;
829 options->add_remove = diff_addremove;
832 int diff_setup_done(struct diff_options *options)
834 if ((options->find_copies_harder &&
835 options->detect_rename != DIFF_DETECT_COPY) ||
836 (0 <= options->rename_limit && !options->detect_rename))
837 return -1;
838 if (options->detect_rename && options->rename_limit < 0)
839 options->rename_limit = diff_rename_limit_default;
840 if (options->setup & DIFF_SETUP_USE_CACHE) {
841 if (!active_cache)
842 /* read-cache does not die even when it fails
843 * so it is safe for us to do this here. Also
844 * it does not smudge active_cache or active_nr
845 * when it fails, so we do not have to worry about
846 * cleaning it up ourselves either.
848 read_cache();
850 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
851 use_size_cache = 1;
852 if (options->abbrev <= 0 || 40 < options->abbrev)
853 options->abbrev = 40; /* full */
855 return 0;
858 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
860 const char *arg = av[0];
861 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
862 options->output_format = DIFF_FORMAT_PATCH;
863 else if (!strcmp(arg, "-z"))
864 options->line_termination = 0;
865 else if (!strncmp(arg, "-l", 2))
866 options->rename_limit = strtoul(arg+2, NULL, 10);
867 else if (!strcmp(arg, "--full-index"))
868 options->full_index = 1;
869 else if (!strcmp(arg, "--name-only"))
870 options->output_format = DIFF_FORMAT_NAME;
871 else if (!strcmp(arg, "--name-status"))
872 options->output_format = DIFF_FORMAT_NAME_STATUS;
873 else if (!strcmp(arg, "-R"))
874 options->reverse_diff = 1;
875 else if (!strncmp(arg, "-S", 2))
876 options->pickaxe = arg + 2;
877 else if (!strcmp(arg, "-s"))
878 options->output_format = DIFF_FORMAT_NO_OUTPUT;
879 else if (!strncmp(arg, "-O", 2))
880 options->orderfile = arg + 2;
881 else if (!strncmp(arg, "--diff-filter=", 14))
882 options->filter = arg + 14;
883 else if (!strcmp(arg, "--pickaxe-all"))
884 options->pickaxe_opts = DIFF_PICKAXE_ALL;
885 else if (!strncmp(arg, "-B", 2)) {
886 if ((options->break_opt =
887 diff_scoreopt_parse(arg)) == -1)
888 return -1;
890 else if (!strncmp(arg, "-M", 2)) {
891 if ((options->rename_score =
892 diff_scoreopt_parse(arg)) == -1)
893 return -1;
894 options->detect_rename = DIFF_DETECT_RENAME;
896 else if (!strncmp(arg, "-C", 2)) {
897 if ((options->rename_score =
898 diff_scoreopt_parse(arg)) == -1)
899 return -1;
900 options->detect_rename = DIFF_DETECT_COPY;
902 else if (!strcmp(arg, "--find-copies-harder"))
903 options->find_copies_harder = 1;
904 else if (!strcmp(arg, "--abbrev"))
905 options->abbrev = DEFAULT_ABBREV;
906 else if (!strncmp(arg, "--abbrev=", 9)) {
907 options->abbrev = strtoul(arg + 9, NULL, 10);
908 if (options->abbrev < MINIMUM_ABBREV)
909 options->abbrev = MINIMUM_ABBREV;
910 else if (40 < options->abbrev)
911 options->abbrev = 40;
913 else
914 return 0;
915 return 1;
918 static int parse_num(const char **cp_p)
920 unsigned long num, scale;
921 int ch, dot;
922 const char *cp = *cp_p;
924 num = 0;
925 scale = 1;
926 dot = 0;
927 for(;;) {
928 ch = *cp;
929 if ( !dot && ch == '.' ) {
930 scale = 1;
931 dot = 1;
932 } else if ( ch == '%' ) {
933 scale = dot ? scale*100 : 100;
934 cp++; /* % is always at the end */
935 break;
936 } else if ( ch >= '0' && ch <= '9' ) {
937 if ( scale < 100000 ) {
938 scale *= 10;
939 num = (num*10) + (ch-'0');
941 } else {
942 break;
944 cp++;
946 *cp_p = cp;
948 /* user says num divided by scale and we say internally that
949 * is MAX_SCORE * num / scale.
951 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
954 int diff_scoreopt_parse(const char *opt)
956 int opt1, opt2, cmd;
958 if (*opt++ != '-')
959 return -1;
960 cmd = *opt++;
961 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
962 return -1; /* that is not a -M, -C nor -B option */
964 opt1 = parse_num(&opt);
965 if (cmd != 'B')
966 opt2 = 0;
967 else {
968 if (*opt == 0)
969 opt2 = 0;
970 else if (*opt != '/')
971 return -1; /* we expect -B80/99 or -B80 */
972 else {
973 opt++;
974 opt2 = parse_num(&opt);
977 if (*opt != 0)
978 return -1;
979 return opt1 | (opt2 << 16);
982 struct diff_queue_struct diff_queued_diff;
984 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
986 if (queue->alloc <= queue->nr) {
987 queue->alloc = alloc_nr(queue->alloc);
988 queue->queue = xrealloc(queue->queue,
989 sizeof(dp) * queue->alloc);
991 queue->queue[queue->nr++] = dp;
994 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
995 struct diff_filespec *one,
996 struct diff_filespec *two)
998 struct diff_filepair *dp = xmalloc(sizeof(*dp));
999 dp->one = one;
1000 dp->two = two;
1001 dp->score = 0;
1002 dp->status = 0;
1003 dp->source_stays = 0;
1004 dp->broken_pair = 0;
1005 if (queue)
1006 diff_q(queue, dp);
1007 return dp;
1010 void diff_free_filepair(struct diff_filepair *p)
1012 diff_free_filespec_data(p->one);
1013 diff_free_filespec_data(p->two);
1014 free(p->one);
1015 free(p->two);
1016 free(p);
1019 /* This is different from find_unique_abbrev() in that
1020 * it stuffs the result with dots for alignment.
1022 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
1024 int abblen;
1025 const char *abbrev;
1026 if (len == 40)
1027 return sha1_to_hex(sha1);
1029 abbrev = find_unique_abbrev(sha1, len);
1030 if (!abbrev)
1031 return sha1_to_hex(sha1);
1032 abblen = strlen(abbrev);
1033 if (abblen < 37) {
1034 static char hex[41];
1035 if (len < abblen && abblen <= len + 2)
1036 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
1037 else
1038 sprintf(hex, "%s...", abbrev);
1039 return hex;
1041 return sha1_to_hex(sha1);
1044 static void diff_flush_raw(struct diff_filepair *p,
1045 int line_termination,
1046 int inter_name_termination,
1047 struct diff_options *options)
1049 int two_paths;
1050 char status[10];
1051 int abbrev = options->abbrev;
1052 const char *path_one, *path_two;
1053 int output_format = options->output_format;
1055 path_one = p->one->path;
1056 path_two = p->two->path;
1057 if (line_termination) {
1058 path_one = quote_one(path_one);
1059 path_two = quote_one(path_two);
1062 if (p->score)
1063 sprintf(status, "%c%03d", p->status,
1064 (int)(0.5 + p->score * 100.0/MAX_SCORE));
1065 else {
1066 status[0] = p->status;
1067 status[1] = 0;
1069 switch (p->status) {
1070 case DIFF_STATUS_COPIED:
1071 case DIFF_STATUS_RENAMED:
1072 two_paths = 1;
1073 break;
1074 case DIFF_STATUS_ADDED:
1075 case DIFF_STATUS_DELETED:
1076 two_paths = 0;
1077 break;
1078 default:
1079 two_paths = 0;
1080 break;
1082 if (output_format != DIFF_FORMAT_NAME_STATUS) {
1083 printf(":%06o %06o %s ",
1084 p->one->mode, p->two->mode,
1085 diff_unique_abbrev(p->one->sha1, abbrev));
1086 printf("%s ",
1087 diff_unique_abbrev(p->two->sha1, abbrev));
1089 printf("%s%c%s", status, inter_name_termination, path_one);
1090 if (two_paths)
1091 printf("%c%s", inter_name_termination, path_two);
1092 putchar(line_termination);
1093 if (path_one != p->one->path)
1094 free((void*)path_one);
1095 if (path_two != p->two->path)
1096 free((void*)path_two);
1099 static void diff_flush_name(struct diff_filepair *p,
1100 int inter_name_termination,
1101 int line_termination)
1103 char *path = p->two->path;
1105 if (line_termination)
1106 path = quote_one(p->two->path);
1107 else
1108 path = p->two->path;
1109 printf("%s%c", path, line_termination);
1110 if (p->two->path != path)
1111 free(path);
1114 int diff_unmodified_pair(struct diff_filepair *p)
1116 /* This function is written stricter than necessary to support
1117 * the currently implemented transformers, but the idea is to
1118 * let transformers to produce diff_filepairs any way they want,
1119 * and filter and clean them up here before producing the output.
1121 struct diff_filespec *one, *two;
1123 if (DIFF_PAIR_UNMERGED(p))
1124 return 0; /* unmerged is interesting */
1126 one = p->one;
1127 two = p->two;
1129 /* deletion, addition, mode or type change
1130 * and rename are all interesting.
1132 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
1133 DIFF_PAIR_MODE_CHANGED(p) ||
1134 strcmp(one->path, two->path))
1135 return 0;
1137 /* both are valid and point at the same path. that is, we are
1138 * dealing with a change.
1140 if (one->sha1_valid && two->sha1_valid &&
1141 !memcmp(one->sha1, two->sha1, sizeof(one->sha1)))
1142 return 1; /* no change */
1143 if (!one->sha1_valid && !two->sha1_valid)
1144 return 1; /* both look at the same file on the filesystem. */
1145 return 0;
1148 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
1150 if (diff_unmodified_pair(p))
1151 return;
1153 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1154 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1155 return; /* no tree diffs in patch format */
1157 run_diff(p, o);
1160 int diff_queue_is_empty(void)
1162 struct diff_queue_struct *q = &diff_queued_diff;
1163 int i;
1164 for (i = 0; i < q->nr; i++)
1165 if (!diff_unmodified_pair(q->queue[i]))
1166 return 0;
1167 return 1;
1170 #if DIFF_DEBUG
1171 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
1173 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
1174 x, one ? one : "",
1175 s->path,
1176 DIFF_FILE_VALID(s) ? "valid" : "invalid",
1177 s->mode,
1178 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
1179 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
1180 x, one ? one : "",
1181 s->size, s->xfrm_flags);
1184 void diff_debug_filepair(const struct diff_filepair *p, int i)
1186 diff_debug_filespec(p->one, i, "one");
1187 diff_debug_filespec(p->two, i, "two");
1188 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
1189 p->score, p->status ? p->status : '?',
1190 p->source_stays, p->broken_pair);
1193 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
1195 int i;
1196 if (msg)
1197 fprintf(stderr, "%s\n", msg);
1198 fprintf(stderr, "q->nr = %d\n", q->nr);
1199 for (i = 0; i < q->nr; i++) {
1200 struct diff_filepair *p = q->queue[i];
1201 diff_debug_filepair(p, i);
1204 #endif
1206 static void diff_resolve_rename_copy(void)
1208 int i, j;
1209 struct diff_filepair *p, *pp;
1210 struct diff_queue_struct *q = &diff_queued_diff;
1212 diff_debug_queue("resolve-rename-copy", q);
1214 for (i = 0; i < q->nr; i++) {
1215 p = q->queue[i];
1216 p->status = 0; /* undecided */
1217 if (DIFF_PAIR_UNMERGED(p))
1218 p->status = DIFF_STATUS_UNMERGED;
1219 else if (!DIFF_FILE_VALID(p->one))
1220 p->status = DIFF_STATUS_ADDED;
1221 else if (!DIFF_FILE_VALID(p->two))
1222 p->status = DIFF_STATUS_DELETED;
1223 else if (DIFF_PAIR_TYPE_CHANGED(p))
1224 p->status = DIFF_STATUS_TYPE_CHANGED;
1226 /* from this point on, we are dealing with a pair
1227 * whose both sides are valid and of the same type, i.e.
1228 * either in-place edit or rename/copy edit.
1230 else if (DIFF_PAIR_RENAME(p)) {
1231 if (p->source_stays) {
1232 p->status = DIFF_STATUS_COPIED;
1233 continue;
1235 /* See if there is some other filepair that
1236 * copies from the same source as us. If so
1237 * we are a copy. Otherwise we are either a
1238 * copy if the path stays, or a rename if it
1239 * does not, but we already handled "stays" case.
1241 for (j = i + 1; j < q->nr; j++) {
1242 pp = q->queue[j];
1243 if (strcmp(pp->one->path, p->one->path))
1244 continue; /* not us */
1245 if (!DIFF_PAIR_RENAME(pp))
1246 continue; /* not a rename/copy */
1247 /* pp is a rename/copy from the same source */
1248 p->status = DIFF_STATUS_COPIED;
1249 break;
1251 if (!p->status)
1252 p->status = DIFF_STATUS_RENAMED;
1254 else if (memcmp(p->one->sha1, p->two->sha1, 20) ||
1255 p->one->mode != p->two->mode)
1256 p->status = DIFF_STATUS_MODIFIED;
1257 else {
1258 /* This is a "no-change" entry and should not
1259 * happen anymore, but prepare for broken callers.
1261 error("feeding unmodified %s to diffcore",
1262 p->one->path);
1263 p->status = DIFF_STATUS_UNKNOWN;
1266 diff_debug_queue("resolve-rename-copy done", q);
1269 void diff_flush(struct diff_options *options)
1271 struct diff_queue_struct *q = &diff_queued_diff;
1272 int i;
1273 int inter_name_termination = '\t';
1274 int diff_output_format = options->output_format;
1275 int line_termination = options->line_termination;
1277 if (!line_termination)
1278 inter_name_termination = 0;
1280 for (i = 0; i < q->nr; i++) {
1281 struct diff_filepair *p = q->queue[i];
1282 if ((diff_output_format == DIFF_FORMAT_NO_OUTPUT) ||
1283 (p->status == DIFF_STATUS_UNKNOWN))
1284 continue;
1285 if (p->status == 0)
1286 die("internal error in diff-resolve-rename-copy");
1287 switch (diff_output_format) {
1288 case DIFF_FORMAT_PATCH:
1289 diff_flush_patch(p, options);
1290 break;
1291 case DIFF_FORMAT_RAW:
1292 case DIFF_FORMAT_NAME_STATUS:
1293 diff_flush_raw(p, line_termination,
1294 inter_name_termination,
1295 options);
1296 break;
1297 case DIFF_FORMAT_NAME:
1298 diff_flush_name(p,
1299 inter_name_termination,
1300 line_termination);
1301 break;
1303 diff_free_filepair(q->queue[i]);
1305 free(q->queue);
1306 q->queue = NULL;
1307 q->nr = q->alloc = 0;
1310 static void diffcore_apply_filter(const char *filter)
1312 int i;
1313 struct diff_queue_struct *q = &diff_queued_diff;
1314 struct diff_queue_struct outq;
1315 outq.queue = NULL;
1316 outq.nr = outq.alloc = 0;
1318 if (!filter)
1319 return;
1321 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
1322 int found;
1323 for (i = found = 0; !found && i < q->nr; i++) {
1324 struct diff_filepair *p = q->queue[i];
1325 if (((p->status == DIFF_STATUS_MODIFIED) &&
1326 ((p->score &&
1327 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
1328 (!p->score &&
1329 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
1330 ((p->status != DIFF_STATUS_MODIFIED) &&
1331 strchr(filter, p->status)))
1332 found++;
1334 if (found)
1335 return;
1337 /* otherwise we will clear the whole queue
1338 * by copying the empty outq at the end of this
1339 * function, but first clear the current entries
1340 * in the queue.
1342 for (i = 0; i < q->nr; i++)
1343 diff_free_filepair(q->queue[i]);
1345 else {
1346 /* Only the matching ones */
1347 for (i = 0; i < q->nr; i++) {
1348 struct diff_filepair *p = q->queue[i];
1350 if (((p->status == DIFF_STATUS_MODIFIED) &&
1351 ((p->score &&
1352 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
1353 (!p->score &&
1354 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
1355 ((p->status != DIFF_STATUS_MODIFIED) &&
1356 strchr(filter, p->status)))
1357 diff_q(&outq, p);
1358 else
1359 diff_free_filepair(p);
1362 free(q->queue);
1363 *q = outq;
1366 void diffcore_std(struct diff_options *options)
1368 if (options->paths && options->paths[0])
1369 diffcore_pathspec(options->paths);
1370 if (options->break_opt != -1)
1371 diffcore_break(options->break_opt);
1372 if (options->detect_rename)
1373 diffcore_rename(options);
1374 if (options->break_opt != -1)
1375 diffcore_merge_broken();
1376 if (options->pickaxe)
1377 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
1378 if (options->orderfile)
1379 diffcore_order(options->orderfile);
1380 diff_resolve_rename_copy();
1381 diffcore_apply_filter(options->filter);
1385 void diffcore_std_no_resolve(struct diff_options *options)
1387 if (options->pickaxe)
1388 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
1389 if (options->orderfile)
1390 diffcore_order(options->orderfile);
1391 diffcore_apply_filter(options->filter);
1394 void diff_addremove(struct diff_options *options,
1395 int addremove, unsigned mode,
1396 const unsigned char *sha1,
1397 const char *base, const char *path)
1399 char concatpath[PATH_MAX];
1400 struct diff_filespec *one, *two;
1402 /* This may look odd, but it is a preparation for
1403 * feeding "there are unchanged files which should
1404 * not produce diffs, but when you are doing copy
1405 * detection you would need them, so here they are"
1406 * entries to the diff-core. They will be prefixed
1407 * with something like '=' or '*' (I haven't decided
1408 * which but should not make any difference).
1409 * Feeding the same new and old to diff_change()
1410 * also has the same effect.
1411 * Before the final output happens, they are pruned after
1412 * merged into rename/copy pairs as appropriate.
1414 if (options->reverse_diff)
1415 addremove = (addremove == '+' ? '-' :
1416 addremove == '-' ? '+' : addremove);
1418 if (!path) path = "";
1419 sprintf(concatpath, "%s%s", base, path);
1420 one = alloc_filespec(concatpath);
1421 two = alloc_filespec(concatpath);
1423 if (addremove != '+')
1424 fill_filespec(one, sha1, mode);
1425 if (addremove != '-')
1426 fill_filespec(two, sha1, mode);
1428 diff_queue(&diff_queued_diff, one, two);
1431 void diff_change(struct diff_options *options,
1432 unsigned old_mode, unsigned new_mode,
1433 const unsigned char *old_sha1,
1434 const unsigned char *new_sha1,
1435 const char *base, const char *path)
1437 char concatpath[PATH_MAX];
1438 struct diff_filespec *one, *two;
1440 if (options->reverse_diff) {
1441 unsigned tmp;
1442 const unsigned char *tmp_c;
1443 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
1444 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
1446 if (!path) path = "";
1447 sprintf(concatpath, "%s%s", base, path);
1448 one = alloc_filespec(concatpath);
1449 two = alloc_filespec(concatpath);
1450 fill_filespec(one, old_sha1, old_mode);
1451 fill_filespec(two, new_sha1, new_mode);
1453 diff_queue(&diff_queued_diff, one, two);
1456 void diff_unmerge(struct diff_options *options,
1457 const char *path)
1459 struct diff_filespec *one, *two;
1460 one = alloc_filespec(path);
1461 two = alloc_filespec(path);
1462 diff_queue(&diff_queued_diff, one, two);