Remove dependency on a file named "-lz"
[git/haiku.git] / diff.c
blob562ca01218c6db870dd0b1b5c0a34ac1cbc1cb2a
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;
489 static void prep_temp_blob(struct diff_tempfile *temp,
490 void *blob,
491 unsigned long size,
492 const unsigned char *sha1,
493 int mode)
495 int fd;
497 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
498 if (fd < 0)
499 die("unable to create temp-file");
500 if (write(fd, blob, size) != size)
501 die("unable to write temp-file");
502 close(fd);
503 temp->name = temp->tmp_path;
504 strcpy(temp->hex, sha1_to_hex(sha1));
505 temp->hex[40] = 0;
506 sprintf(temp->mode, "%06o", mode);
509 static void prepare_temp_file(const char *name,
510 struct diff_tempfile *temp,
511 struct diff_filespec *one)
513 if (!DIFF_FILE_VALID(one)) {
514 not_a_valid_file:
515 /* A '-' entry produces this for file-2, and
516 * a '+' entry produces this for file-1.
518 temp->name = "/dev/null";
519 strcpy(temp->hex, ".");
520 strcpy(temp->mode, ".");
521 return;
524 if (!one->sha1_valid ||
525 work_tree_matches(name, one->sha1)) {
526 struct stat st;
527 if (lstat(name, &st) < 0) {
528 if (errno == ENOENT)
529 goto not_a_valid_file;
530 die("stat(%s): %s", name, strerror(errno));
532 if (S_ISLNK(st.st_mode)) {
533 int ret;
534 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
535 if (sizeof(buf) <= st.st_size)
536 die("symlink too long: %s", name);
537 ret = readlink(name, buf, st.st_size);
538 if (ret < 0)
539 die("readlink(%s)", name);
540 prep_temp_blob(temp, buf, st.st_size,
541 (one->sha1_valid ?
542 one->sha1 : null_sha1),
543 (one->sha1_valid ?
544 one->mode : S_IFLNK));
546 else {
547 /* we can borrow from the file in the work tree */
548 temp->name = name;
549 if (!one->sha1_valid)
550 strcpy(temp->hex, sha1_to_hex(null_sha1));
551 else
552 strcpy(temp->hex, sha1_to_hex(one->sha1));
553 /* Even though we may sometimes borrow the
554 * contents from the work tree, we always want
555 * one->mode. mode is trustworthy even when
556 * !(one->sha1_valid), as long as
557 * DIFF_FILE_VALID(one).
559 sprintf(temp->mode, "%06o", one->mode);
561 return;
563 else {
564 if (diff_populate_filespec(one, 0))
565 die("cannot read data blob for %s", one->path);
566 prep_temp_blob(temp, one->data, one->size,
567 one->sha1, one->mode);
571 static void remove_tempfile(void)
573 int i;
575 for (i = 0; i < 2; i++)
576 if (diff_temp[i].name == diff_temp[i].tmp_path) {
577 unlink(diff_temp[i].name);
578 diff_temp[i].name = NULL;
582 static void remove_tempfile_on_signal(int signo)
584 remove_tempfile();
585 signal(SIGINT, SIG_DFL);
586 raise(signo);
589 static int spawn_prog(const char *pgm, const char **arg)
591 pid_t pid;
592 int status;
594 fflush(NULL);
595 pid = fork();
596 if (pid < 0)
597 die("unable to fork");
598 if (!pid) {
599 execvp(pgm, (char *const*) arg);
600 exit(255);
603 while (waitpid(pid, &status, 0) < 0) {
604 if (errno == EINTR)
605 continue;
606 return -1;
609 /* Earlier we did not check the exit status because
610 * diff exits non-zero if files are different, and
611 * we are not interested in knowing that. It was a
612 * mistake which made it harder to quit a diff-*
613 * session that uses the git-apply-patch-script as
614 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
615 * should also exit non-zero only when it wants to
616 * abort the entire diff-* session.
618 if (WIFEXITED(status) && !WEXITSTATUS(status))
619 return 0;
620 return -1;
623 /* An external diff command takes:
625 * diff-cmd name infile1 infile1-sha1 infile1-mode \
626 * infile2 infile2-sha1 infile2-mode [ rename-to ]
629 static void run_external_diff(const char *pgm,
630 const char *name,
631 const char *other,
632 struct diff_filespec *one,
633 struct diff_filespec *two,
634 const char *xfrm_msg,
635 int complete_rewrite)
637 const char *spawn_arg[10];
638 struct diff_tempfile *temp = diff_temp;
639 int retval;
640 static int atexit_asked = 0;
641 const char *othername;
642 const char **arg = &spawn_arg[0];
644 othername = (other? other : name);
645 if (one && two) {
646 prepare_temp_file(name, &temp[0], one);
647 prepare_temp_file(othername, &temp[1], two);
648 if (! atexit_asked &&
649 (temp[0].name == temp[0].tmp_path ||
650 temp[1].name == temp[1].tmp_path)) {
651 atexit_asked = 1;
652 atexit(remove_tempfile);
654 signal(SIGINT, remove_tempfile_on_signal);
657 if (one && two) {
658 *arg++ = pgm;
659 *arg++ = name;
660 *arg++ = temp[0].name;
661 *arg++ = temp[0].hex;
662 *arg++ = temp[0].mode;
663 *arg++ = temp[1].name;
664 *arg++ = temp[1].hex;
665 *arg++ = temp[1].mode;
666 if (other) {
667 *arg++ = other;
668 *arg++ = xfrm_msg;
670 } else {
671 *arg++ = pgm;
672 *arg++ = name;
674 *arg = NULL;
675 retval = spawn_prog(pgm, spawn_arg);
676 remove_tempfile();
677 if (retval) {
678 fprintf(stderr, "external diff died, stopping at %s.\n", name);
679 exit(1);
683 static void run_diff_cmd(const char *pgm,
684 const char *name,
685 const char *other,
686 struct diff_filespec *one,
687 struct diff_filespec *two,
688 const char *xfrm_msg,
689 int complete_rewrite)
691 if (pgm) {
692 run_external_diff(pgm, name, other, one, two, xfrm_msg,
693 complete_rewrite);
694 return;
696 if (one && two)
697 builtin_diff(name, other ? other : name,
698 one, two, xfrm_msg, complete_rewrite);
699 else
700 printf("* Unmerged path %s\n", name);
703 static void diff_fill_sha1_info(struct diff_filespec *one)
705 if (DIFF_FILE_VALID(one)) {
706 if (!one->sha1_valid) {
707 struct stat st;
708 if (lstat(one->path, &st) < 0)
709 die("stat %s", one->path);
710 if (index_path(one->sha1, one->path, &st, 0))
711 die("cannot hash %s\n", one->path);
714 else
715 memset(one->sha1, 0, 20);
718 static void run_diff(struct diff_filepair *p, struct diff_options *o)
720 const char *pgm = external_diff();
721 char msg[PATH_MAX*2+300], *xfrm_msg;
722 struct diff_filespec *one;
723 struct diff_filespec *two;
724 const char *name;
725 const char *other;
726 char *name_munged, *other_munged;
727 int complete_rewrite = 0;
728 int len;
730 if (DIFF_PAIR_UNMERGED(p)) {
731 /* unmerged */
732 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, 0);
733 return;
736 name = p->one->path;
737 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
738 name_munged = quote_one(name);
739 other_munged = quote_one(other);
740 one = p->one; two = p->two;
742 diff_fill_sha1_info(one);
743 diff_fill_sha1_info(two);
745 len = 0;
746 switch (p->status) {
747 case DIFF_STATUS_COPIED:
748 len += snprintf(msg + len, sizeof(msg) - len,
749 "similarity index %d%%\n"
750 "copy from %s\n"
751 "copy to %s\n",
752 (int)(0.5 + p->score * 100.0/MAX_SCORE),
753 name_munged, other_munged);
754 break;
755 case DIFF_STATUS_RENAMED:
756 len += snprintf(msg + len, sizeof(msg) - len,
757 "similarity index %d%%\n"
758 "rename from %s\n"
759 "rename to %s\n",
760 (int)(0.5 + p->score * 100.0/MAX_SCORE),
761 name_munged, other_munged);
762 break;
763 case DIFF_STATUS_MODIFIED:
764 if (p->score) {
765 len += snprintf(msg + len, sizeof(msg) - len,
766 "dissimilarity index %d%%\n",
767 (int)(0.5 + p->score *
768 100.0/MAX_SCORE));
769 complete_rewrite = 1;
770 break;
772 /* fallthru */
773 default:
774 /* nothing */
778 if (memcmp(one->sha1, two->sha1, 20)) {
779 char one_sha1[41];
780 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
781 memcpy(one_sha1, sha1_to_hex(one->sha1), 41);
783 len += snprintf(msg + len, sizeof(msg) - len,
784 "index %.*s..%.*s",
785 abbrev, one_sha1, abbrev,
786 sha1_to_hex(two->sha1));
787 if (one->mode == two->mode)
788 len += snprintf(msg + len, sizeof(msg) - len,
789 " %06o", one->mode);
790 len += snprintf(msg + len, sizeof(msg) - len, "\n");
793 if (len)
794 msg[--len] = 0;
795 xfrm_msg = len ? msg : NULL;
797 if (!pgm &&
798 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
799 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
800 /* a filepair that changes between file and symlink
801 * needs to be split into deletion and creation.
803 struct diff_filespec *null = alloc_filespec(two->path);
804 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, 0);
805 free(null);
806 null = alloc_filespec(one->path);
807 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, 0);
808 free(null);
810 else
811 run_diff_cmd(pgm, name, other, one, two, xfrm_msg,
812 complete_rewrite);
814 free(name_munged);
815 free(other_munged);
818 void diff_setup(struct diff_options *options)
820 memset(options, 0, sizeof(*options));
821 options->output_format = DIFF_FORMAT_RAW;
822 options->line_termination = '\n';
823 options->break_opt = -1;
824 options->rename_limit = -1;
826 options->change = diff_change;
827 options->add_remove = diff_addremove;
830 int diff_setup_done(struct diff_options *options)
832 if ((options->find_copies_harder &&
833 options->detect_rename != DIFF_DETECT_COPY) ||
834 (0 <= options->rename_limit && !options->detect_rename))
835 return -1;
836 if (options->detect_rename && options->rename_limit < 0)
837 options->rename_limit = diff_rename_limit_default;
838 if (options->setup & DIFF_SETUP_USE_CACHE) {
839 if (!active_cache)
840 /* read-cache does not die even when it fails
841 * so it is safe for us to do this here. Also
842 * it does not smudge active_cache or active_nr
843 * when it fails, so we do not have to worry about
844 * cleaning it up ourselves either.
846 read_cache();
848 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
849 use_size_cache = 1;
850 if (options->abbrev <= 0 || 40 < options->abbrev)
851 options->abbrev = 40; /* full */
853 return 0;
856 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
858 const char *arg = av[0];
859 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
860 options->output_format = DIFF_FORMAT_PATCH;
861 else if (!strcmp(arg, "-z"))
862 options->line_termination = 0;
863 else if (!strncmp(arg, "-l", 2))
864 options->rename_limit = strtoul(arg+2, NULL, 10);
865 else if (!strcmp(arg, "--full-index"))
866 options->full_index = 1;
867 else if (!strcmp(arg, "--name-only"))
868 options->output_format = DIFF_FORMAT_NAME;
869 else if (!strcmp(arg, "--name-status"))
870 options->output_format = DIFF_FORMAT_NAME_STATUS;
871 else if (!strcmp(arg, "-R"))
872 options->reverse_diff = 1;
873 else if (!strncmp(arg, "-S", 2))
874 options->pickaxe = arg + 2;
875 else if (!strcmp(arg, "-s"))
876 options->output_format = DIFF_FORMAT_NO_OUTPUT;
877 else if (!strncmp(arg, "-O", 2))
878 options->orderfile = arg + 2;
879 else if (!strncmp(arg, "--diff-filter=", 14))
880 options->filter = arg + 14;
881 else if (!strcmp(arg, "--pickaxe-all"))
882 options->pickaxe_opts = DIFF_PICKAXE_ALL;
883 else if (!strncmp(arg, "-B", 2)) {
884 if ((options->break_opt =
885 diff_scoreopt_parse(arg)) == -1)
886 return -1;
888 else if (!strncmp(arg, "-M", 2)) {
889 if ((options->rename_score =
890 diff_scoreopt_parse(arg)) == -1)
891 return -1;
892 options->detect_rename = DIFF_DETECT_RENAME;
894 else if (!strncmp(arg, "-C", 2)) {
895 if ((options->rename_score =
896 diff_scoreopt_parse(arg)) == -1)
897 return -1;
898 options->detect_rename = DIFF_DETECT_COPY;
900 else if (!strcmp(arg, "--find-copies-harder"))
901 options->find_copies_harder = 1;
902 else if (!strcmp(arg, "--abbrev"))
903 options->abbrev = DEFAULT_ABBREV;
904 else if (!strncmp(arg, "--abbrev=", 9)) {
905 options->abbrev = strtoul(arg + 9, NULL, 10);
906 if (options->abbrev < MINIMUM_ABBREV)
907 options->abbrev = MINIMUM_ABBREV;
908 else if (40 < options->abbrev)
909 options->abbrev = 40;
911 else
912 return 0;
913 return 1;
916 static int parse_num(const char **cp_p)
918 unsigned long num, scale;
919 int ch, dot;
920 const char *cp = *cp_p;
922 num = 0;
923 scale = 1;
924 dot = 0;
925 for(;;) {
926 ch = *cp;
927 if ( !dot && ch == '.' ) {
928 scale = 1;
929 dot = 1;
930 } else if ( ch == '%' ) {
931 scale = dot ? scale*100 : 100;
932 cp++; /* % is always at the end */
933 break;
934 } else if ( ch >= '0' && ch <= '9' ) {
935 if ( scale < 100000 ) {
936 scale *= 10;
937 num = (num*10) + (ch-'0');
939 } else {
940 break;
942 cp++;
944 *cp_p = cp;
946 /* user says num divided by scale and we say internally that
947 * is MAX_SCORE * num / scale.
949 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
952 int diff_scoreopt_parse(const char *opt)
954 int opt1, opt2, cmd;
956 if (*opt++ != '-')
957 return -1;
958 cmd = *opt++;
959 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
960 return -1; /* that is not a -M, -C nor -B option */
962 opt1 = parse_num(&opt);
963 if (cmd != 'B')
964 opt2 = 0;
965 else {
966 if (*opt == 0)
967 opt2 = 0;
968 else if (*opt != '/')
969 return -1; /* we expect -B80/99 or -B80 */
970 else {
971 opt++;
972 opt2 = parse_num(&opt);
975 if (*opt != 0)
976 return -1;
977 return opt1 | (opt2 << 16);
980 struct diff_queue_struct diff_queued_diff;
982 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
984 if (queue->alloc <= queue->nr) {
985 queue->alloc = alloc_nr(queue->alloc);
986 queue->queue = xrealloc(queue->queue,
987 sizeof(dp) * queue->alloc);
989 queue->queue[queue->nr++] = dp;
992 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
993 struct diff_filespec *one,
994 struct diff_filespec *two)
996 struct diff_filepair *dp = xmalloc(sizeof(*dp));
997 dp->one = one;
998 dp->two = two;
999 dp->score = 0;
1000 dp->status = 0;
1001 dp->source_stays = 0;
1002 dp->broken_pair = 0;
1003 if (queue)
1004 diff_q(queue, dp);
1005 return dp;
1008 void diff_free_filepair(struct diff_filepair *p)
1010 diff_free_filespec_data(p->one);
1011 diff_free_filespec_data(p->two);
1012 free(p->one);
1013 free(p->two);
1014 free(p);
1017 /* This is different from find_unique_abbrev() in that
1018 * it stuffs the result with dots for alignment.
1020 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
1022 int abblen;
1023 const char *abbrev;
1024 if (len == 40)
1025 return sha1_to_hex(sha1);
1027 abbrev = find_unique_abbrev(sha1, len);
1028 if (!abbrev)
1029 return sha1_to_hex(sha1);
1030 abblen = strlen(abbrev);
1031 if (abblen < 37) {
1032 static char hex[41];
1033 if (len < abblen && abblen <= len + 2)
1034 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
1035 else
1036 sprintf(hex, "%s...", abbrev);
1037 return hex;
1039 return sha1_to_hex(sha1);
1042 static void diff_flush_raw(struct diff_filepair *p,
1043 int line_termination,
1044 int inter_name_termination,
1045 struct diff_options *options)
1047 int two_paths;
1048 char status[10];
1049 int abbrev = options->abbrev;
1050 const char *path_one, *path_two;
1051 int output_format = options->output_format;
1053 path_one = p->one->path;
1054 path_two = p->two->path;
1055 if (line_termination) {
1056 path_one = quote_one(path_one);
1057 path_two = quote_one(path_two);
1060 if (p->score)
1061 sprintf(status, "%c%03d", p->status,
1062 (int)(0.5 + p->score * 100.0/MAX_SCORE));
1063 else {
1064 status[0] = p->status;
1065 status[1] = 0;
1067 switch (p->status) {
1068 case DIFF_STATUS_COPIED:
1069 case DIFF_STATUS_RENAMED:
1070 two_paths = 1;
1071 break;
1072 case DIFF_STATUS_ADDED:
1073 case DIFF_STATUS_DELETED:
1074 two_paths = 0;
1075 break;
1076 default:
1077 two_paths = 0;
1078 break;
1080 if (output_format != DIFF_FORMAT_NAME_STATUS) {
1081 printf(":%06o %06o %s ",
1082 p->one->mode, p->two->mode,
1083 diff_unique_abbrev(p->one->sha1, abbrev));
1084 printf("%s ",
1085 diff_unique_abbrev(p->two->sha1, abbrev));
1087 printf("%s%c%s", status, inter_name_termination, path_one);
1088 if (two_paths)
1089 printf("%c%s", inter_name_termination, path_two);
1090 putchar(line_termination);
1091 if (path_one != p->one->path)
1092 free((void*)path_one);
1093 if (path_two != p->two->path)
1094 free((void*)path_two);
1097 static void diff_flush_name(struct diff_filepair *p,
1098 int inter_name_termination,
1099 int line_termination)
1101 char *path = p->two->path;
1103 if (line_termination)
1104 path = quote_one(p->two->path);
1105 else
1106 path = p->two->path;
1107 printf("%s%c", path, line_termination);
1108 if (p->two->path != path)
1109 free(path);
1112 int diff_unmodified_pair(struct diff_filepair *p)
1114 /* This function is written stricter than necessary to support
1115 * the currently implemented transformers, but the idea is to
1116 * let transformers to produce diff_filepairs any way they want,
1117 * and filter and clean them up here before producing the output.
1119 struct diff_filespec *one, *two;
1121 if (DIFF_PAIR_UNMERGED(p))
1122 return 0; /* unmerged is interesting */
1124 one = p->one;
1125 two = p->two;
1127 /* deletion, addition, mode or type change
1128 * and rename are all interesting.
1130 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
1131 DIFF_PAIR_MODE_CHANGED(p) ||
1132 strcmp(one->path, two->path))
1133 return 0;
1135 /* both are valid and point at the same path. that is, we are
1136 * dealing with a change.
1138 if (one->sha1_valid && two->sha1_valid &&
1139 !memcmp(one->sha1, two->sha1, sizeof(one->sha1)))
1140 return 1; /* no change */
1141 if (!one->sha1_valid && !two->sha1_valid)
1142 return 1; /* both look at the same file on the filesystem. */
1143 return 0;
1146 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
1148 if (diff_unmodified_pair(p))
1149 return;
1151 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1152 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1153 return; /* no tree diffs in patch format */
1155 run_diff(p, o);
1158 int diff_queue_is_empty(void)
1160 struct diff_queue_struct *q = &diff_queued_diff;
1161 int i;
1162 for (i = 0; i < q->nr; i++)
1163 if (!diff_unmodified_pair(q->queue[i]))
1164 return 0;
1165 return 1;
1168 #if DIFF_DEBUG
1169 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
1171 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
1172 x, one ? one : "",
1173 s->path,
1174 DIFF_FILE_VALID(s) ? "valid" : "invalid",
1175 s->mode,
1176 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
1177 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
1178 x, one ? one : "",
1179 s->size, s->xfrm_flags);
1182 void diff_debug_filepair(const struct diff_filepair *p, int i)
1184 diff_debug_filespec(p->one, i, "one");
1185 diff_debug_filespec(p->two, i, "two");
1186 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
1187 p->score, p->status ? p->status : '?',
1188 p->source_stays, p->broken_pair);
1191 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
1193 int i;
1194 if (msg)
1195 fprintf(stderr, "%s\n", msg);
1196 fprintf(stderr, "q->nr = %d\n", q->nr);
1197 for (i = 0; i < q->nr; i++) {
1198 struct diff_filepair *p = q->queue[i];
1199 diff_debug_filepair(p, i);
1202 #endif
1204 static void diff_resolve_rename_copy(void)
1206 int i, j;
1207 struct diff_filepair *p, *pp;
1208 struct diff_queue_struct *q = &diff_queued_diff;
1210 diff_debug_queue("resolve-rename-copy", q);
1212 for (i = 0; i < q->nr; i++) {
1213 p = q->queue[i];
1214 p->status = 0; /* undecided */
1215 if (DIFF_PAIR_UNMERGED(p))
1216 p->status = DIFF_STATUS_UNMERGED;
1217 else if (!DIFF_FILE_VALID(p->one))
1218 p->status = DIFF_STATUS_ADDED;
1219 else if (!DIFF_FILE_VALID(p->two))
1220 p->status = DIFF_STATUS_DELETED;
1221 else if (DIFF_PAIR_TYPE_CHANGED(p))
1222 p->status = DIFF_STATUS_TYPE_CHANGED;
1224 /* from this point on, we are dealing with a pair
1225 * whose both sides are valid and of the same type, i.e.
1226 * either in-place edit or rename/copy edit.
1228 else if (DIFF_PAIR_RENAME(p)) {
1229 if (p->source_stays) {
1230 p->status = DIFF_STATUS_COPIED;
1231 continue;
1233 /* See if there is some other filepair that
1234 * copies from the same source as us. If so
1235 * we are a copy. Otherwise we are either a
1236 * copy if the path stays, or a rename if it
1237 * does not, but we already handled "stays" case.
1239 for (j = i + 1; j < q->nr; j++) {
1240 pp = q->queue[j];
1241 if (strcmp(pp->one->path, p->one->path))
1242 continue; /* not us */
1243 if (!DIFF_PAIR_RENAME(pp))
1244 continue; /* not a rename/copy */
1245 /* pp is a rename/copy from the same source */
1246 p->status = DIFF_STATUS_COPIED;
1247 break;
1249 if (!p->status)
1250 p->status = DIFF_STATUS_RENAMED;
1252 else if (memcmp(p->one->sha1, p->two->sha1, 20) ||
1253 p->one->mode != p->two->mode)
1254 p->status = DIFF_STATUS_MODIFIED;
1255 else {
1256 /* This is a "no-change" entry and should not
1257 * happen anymore, but prepare for broken callers.
1259 error("feeding unmodified %s to diffcore",
1260 p->one->path);
1261 p->status = DIFF_STATUS_UNKNOWN;
1264 diff_debug_queue("resolve-rename-copy done", q);
1267 void diff_flush(struct diff_options *options)
1269 struct diff_queue_struct *q = &diff_queued_diff;
1270 int i;
1271 int inter_name_termination = '\t';
1272 int diff_output_format = options->output_format;
1273 int line_termination = options->line_termination;
1275 if (!line_termination)
1276 inter_name_termination = 0;
1278 for (i = 0; i < q->nr; i++) {
1279 struct diff_filepair *p = q->queue[i];
1280 if ((diff_output_format == DIFF_FORMAT_NO_OUTPUT) ||
1281 (p->status == DIFF_STATUS_UNKNOWN))
1282 continue;
1283 if (p->status == 0)
1284 die("internal error in diff-resolve-rename-copy");
1285 switch (diff_output_format) {
1286 case DIFF_FORMAT_PATCH:
1287 diff_flush_patch(p, options);
1288 break;
1289 case DIFF_FORMAT_RAW:
1290 case DIFF_FORMAT_NAME_STATUS:
1291 diff_flush_raw(p, line_termination,
1292 inter_name_termination,
1293 options);
1294 break;
1295 case DIFF_FORMAT_NAME:
1296 diff_flush_name(p,
1297 inter_name_termination,
1298 line_termination);
1299 break;
1301 diff_free_filepair(q->queue[i]);
1303 free(q->queue);
1304 q->queue = NULL;
1305 q->nr = q->alloc = 0;
1308 static void diffcore_apply_filter(const char *filter)
1310 int i;
1311 struct diff_queue_struct *q = &diff_queued_diff;
1312 struct diff_queue_struct outq;
1313 outq.queue = NULL;
1314 outq.nr = outq.alloc = 0;
1316 if (!filter)
1317 return;
1319 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
1320 int found;
1321 for (i = found = 0; !found && i < q->nr; i++) {
1322 struct diff_filepair *p = q->queue[i];
1323 if (((p->status == DIFF_STATUS_MODIFIED) &&
1324 ((p->score &&
1325 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
1326 (!p->score &&
1327 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
1328 ((p->status != DIFF_STATUS_MODIFIED) &&
1329 strchr(filter, p->status)))
1330 found++;
1332 if (found)
1333 return;
1335 /* otherwise we will clear the whole queue
1336 * by copying the empty outq at the end of this
1337 * function, but first clear the current entries
1338 * in the queue.
1340 for (i = 0; i < q->nr; i++)
1341 diff_free_filepair(q->queue[i]);
1343 else {
1344 /* Only the matching ones */
1345 for (i = 0; i < q->nr; i++) {
1346 struct diff_filepair *p = q->queue[i];
1348 if (((p->status == DIFF_STATUS_MODIFIED) &&
1349 ((p->score &&
1350 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
1351 (!p->score &&
1352 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
1353 ((p->status != DIFF_STATUS_MODIFIED) &&
1354 strchr(filter, p->status)))
1355 diff_q(&outq, p);
1356 else
1357 diff_free_filepair(p);
1360 free(q->queue);
1361 *q = outq;
1364 void diffcore_std(struct diff_options *options)
1366 if (options->paths && options->paths[0])
1367 diffcore_pathspec(options->paths);
1368 if (options->break_opt != -1)
1369 diffcore_break(options->break_opt);
1370 if (options->detect_rename)
1371 diffcore_rename(options);
1372 if (options->break_opt != -1)
1373 diffcore_merge_broken();
1374 if (options->pickaxe)
1375 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
1376 if (options->orderfile)
1377 diffcore_order(options->orderfile);
1378 diff_resolve_rename_copy();
1379 diffcore_apply_filter(options->filter);
1383 void diffcore_std_no_resolve(struct diff_options *options)
1385 if (options->pickaxe)
1386 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
1387 if (options->orderfile)
1388 diffcore_order(options->orderfile);
1389 diffcore_apply_filter(options->filter);
1392 void diff_addremove(struct diff_options *options,
1393 int addremove, unsigned mode,
1394 const unsigned char *sha1,
1395 const char *base, const char *path)
1397 char concatpath[PATH_MAX];
1398 struct diff_filespec *one, *two;
1400 /* This may look odd, but it is a preparation for
1401 * feeding "there are unchanged files which should
1402 * not produce diffs, but when you are doing copy
1403 * detection you would need them, so here they are"
1404 * entries to the diff-core. They will be prefixed
1405 * with something like '=' or '*' (I haven't decided
1406 * which but should not make any difference).
1407 * Feeding the same new and old to diff_change()
1408 * also has the same effect.
1409 * Before the final output happens, they are pruned after
1410 * merged into rename/copy pairs as appropriate.
1412 if (options->reverse_diff)
1413 addremove = (addremove == '+' ? '-' :
1414 addremove == '-' ? '+' : addremove);
1416 if (!path) path = "";
1417 sprintf(concatpath, "%s%s", base, path);
1418 one = alloc_filespec(concatpath);
1419 two = alloc_filespec(concatpath);
1421 if (addremove != '+')
1422 fill_filespec(one, sha1, mode);
1423 if (addremove != '-')
1424 fill_filespec(two, sha1, mode);
1426 diff_queue(&diff_queued_diff, one, two);
1429 void diff_change(struct diff_options *options,
1430 unsigned old_mode, unsigned new_mode,
1431 const unsigned char *old_sha1,
1432 const unsigned char *new_sha1,
1433 const char *base, const char *path)
1435 char concatpath[PATH_MAX];
1436 struct diff_filespec *one, *two;
1438 if (options->reverse_diff) {
1439 unsigned tmp;
1440 const unsigned char *tmp_c;
1441 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
1442 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
1444 if (!path) path = "";
1445 sprintf(concatpath, "%s%s", base, path);
1446 one = alloc_filespec(concatpath);
1447 two = alloc_filespec(concatpath);
1448 fill_filespec(one, old_sha1, old_mode);
1449 fill_filespec(two, new_sha1, new_mode);
1451 diff_queue(&diff_queued_diff, one, two);
1454 void diff_unmerge(struct diff_options *options,
1455 const char *path)
1457 struct diff_filespec *one, *two;
1458 one = alloc_filespec(path);
1459 two = alloc_filespec(path);
1460 diff_queue(&diff_queued_diff, one, two);