2 * Copyright (C) 2005 Junio C Hamano
12 #include "xdiff-interface.h"
15 static int use_size_cache;
17 static int diff_detect_rename_default;
18 static int diff_rename_limit_default = -1;
19 static int diff_use_color_default;
21 static char diff_colors[][COLOR_MAXLEN] = {
25 "\033[36m", /* cyan */
27 "\033[32m", /* green */
28 "\033[33m" /* yellow */
31 static int parse_diff_color_slot(const char *var, int ofs)
33 if (!strcasecmp(var+ofs, "plain"))
35 if (!strcasecmp(var+ofs, "meta"))
37 if (!strcasecmp(var+ofs, "frag"))
39 if (!strcasecmp(var+ofs, "old"))
41 if (!strcasecmp(var+ofs, "new"))
43 if (!strcasecmp(var+ofs, "commit"))
45 die("bad config variable '%s'", var);
49 * These are to give UI layer defaults.
50 * The core-level commands such as git-diff-files should
51 * never be affected by the setting of diff.renames
52 * the user happens to have in the configuration file.
54 int git_diff_ui_config(const char *var, const char *value)
56 if (!strcmp(var, "diff.renamelimit")) {
57 diff_rename_limit_default = git_config_int(var, value);
60 if (!strcmp(var, "diff.color")) {
61 diff_use_color_default = git_config_colorbool(var, value);
64 if (!strcmp(var, "diff.renames")) {
66 diff_detect_rename_default = DIFF_DETECT_RENAME;
67 else if (!strcasecmp(value, "copies") ||
68 !strcasecmp(value, "copy"))
69 diff_detect_rename_default = DIFF_DETECT_COPY;
70 else if (git_config_bool(var,value))
71 diff_detect_rename_default = DIFF_DETECT_RENAME;
74 if (!strncmp(var, "diff.color.", 11)) {
75 int slot = parse_diff_color_slot(var, 11);
76 color_parse(value, var, diff_colors[slot]);
79 return git_default_config(var, value);
82 static char *quote_one(const char *str)
89 needlen = quote_c_style(str, NULL, NULL, 0);
92 xp = xmalloc(needlen + 1);
93 quote_c_style(str, xp, NULL, 0);
97 static char *quote_two(const char *one, const char *two)
99 int need_one = quote_c_style(one, NULL, NULL, 1);
100 int need_two = quote_c_style(two, NULL, NULL, 1);
103 if (need_one + need_two) {
104 if (!need_one) need_one = strlen(one);
105 if (!need_two) need_one = strlen(two);
107 xp = xmalloc(need_one + need_two + 3);
109 quote_c_style(one, xp + 1, NULL, 1);
110 quote_c_style(two, xp + need_one + 1, NULL, 1);
111 strcpy(xp + need_one + need_two + 1, "\"");
114 need_one = strlen(one);
115 need_two = strlen(two);
116 xp = xmalloc(need_one + need_two + 1);
118 strcpy(xp + need_one, two);
122 static const char *external_diff(void)
124 static const char *external_diff_cmd = NULL;
125 static int done_preparing = 0;
128 return external_diff_cmd;
129 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
131 return external_diff_cmd;
134 #define TEMPFILE_PATH_LEN 50
136 static struct diff_tempfile {
137 const char *name; /* filename external diff should read from */
140 char tmp_path[TEMPFILE_PATH_LEN];
143 static int count_lines(const char *data, int size)
145 int count, ch, completely_empty = 1, nl_just_seen = 0;
152 completely_empty = 0;
156 completely_empty = 0;
159 if (completely_empty)
162 count++; /* no trailing newline */
166 static void print_line_count(int count)
176 printf("1,%d", count);
181 static void copy_file(int prefix, const char *data, int size)
183 int ch, nl_just_seen = 1;
195 printf("\n\\ No newline at end of file\n");
198 static void emit_rewrite_diff(const char *name_a,
200 struct diff_filespec *one,
201 struct diff_filespec *two)
204 diff_populate_filespec(one, 0);
205 diff_populate_filespec(two, 0);
206 lc_a = count_lines(one->data, one->size);
207 lc_b = count_lines(two->data, two->size);
208 printf("--- %s\n+++ %s\n@@ -", name_a, name_b);
209 print_line_count(lc_a);
211 print_line_count(lc_b);
214 copy_file('-', one->data, one->size);
216 copy_file('+', two->data, two->size);
219 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
221 if (!DIFF_FILE_VALID(one)) {
222 mf->ptr = (char *)""; /* does not matter */
226 else if (diff_populate_filespec(one, 0))
229 mf->size = one->size;
233 struct diff_words_buffer {
236 long current; /* output pointer */
237 int suppressed_newline;
240 static void diff_words_append(char *line, unsigned long len,
241 struct diff_words_buffer *buffer)
243 if (buffer->text.size + len > buffer->alloc) {
244 buffer->alloc = (buffer->text.size + len) * 3 / 2;
245 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
249 memcpy(buffer->text.ptr + buffer->text.size, line, len);
250 buffer->text.size += len;
253 struct diff_words_data {
254 struct xdiff_emit_state xm;
255 struct diff_words_buffer minus, plus;
258 static void print_word(struct diff_words_buffer *buffer, int len, int color,
259 int suppress_newline)
267 ptr = buffer->text.ptr + buffer->current;
268 buffer->current += len;
270 if (ptr[len - 1] == '\n') {
275 fputs(diff_get_color(1, color), stdout);
276 fwrite(ptr, len, 1, stdout);
277 fputs(diff_get_color(1, DIFF_RESET), stdout);
280 if (suppress_newline)
281 buffer->suppressed_newline = 1;
287 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
289 struct diff_words_data *diff_words = priv;
291 if (diff_words->minus.suppressed_newline) {
294 diff_words->minus.suppressed_newline = 0;
300 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
303 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
306 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
307 diff_words->minus.current += len;
312 /* this executes the word diff on the accumulated buffers */
313 static void diff_words_show(struct diff_words_data *diff_words)
318 mmfile_t minus, plus;
321 minus.size = diff_words->minus.text.size;
322 minus.ptr = xmalloc(minus.size);
323 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
324 for (i = 0; i < minus.size; i++)
325 if (isspace(minus.ptr[i]))
327 diff_words->minus.current = 0;
329 plus.size = diff_words->plus.text.size;
330 plus.ptr = xmalloc(plus.size);
331 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
332 for (i = 0; i < plus.size; i++)
333 if (isspace(plus.ptr[i]))
335 diff_words->plus.current = 0;
337 xpp.flags = XDF_NEED_MINIMAL;
338 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
340 ecb.outf = xdiff_outf;
341 ecb.priv = diff_words;
342 diff_words->xm.consume = fn_out_diff_words_aux;
343 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
347 diff_words->minus.text.size = diff_words->plus.text.size = 0;
349 if (diff_words->minus.suppressed_newline) {
351 diff_words->minus.suppressed_newline = 0;
355 struct emit_callback {
356 struct xdiff_emit_state xm;
357 int nparents, color_diff;
358 const char **label_path;
359 struct diff_words_data *diff_words;
362 static void free_diff_words_data(struct emit_callback *ecbdata)
364 if (ecbdata->diff_words) {
366 if (ecbdata->diff_words->minus.text.size ||
367 ecbdata->diff_words->plus.text.size)
368 diff_words_show(ecbdata->diff_words);
370 if (ecbdata->diff_words->minus.text.ptr)
371 free (ecbdata->diff_words->minus.text.ptr);
372 if (ecbdata->diff_words->plus.text.ptr)
373 free (ecbdata->diff_words->plus.text.ptr);
374 free(ecbdata->diff_words);
375 ecbdata->diff_words = NULL;
379 const char *diff_get_color(int diff_use_color, enum color_diff ix)
382 return diff_colors[ix];
386 static void fn_out_consume(void *priv, char *line, unsigned long len)
389 struct emit_callback *ecbdata = priv;
390 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
391 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
393 if (ecbdata->label_path[0]) {
394 printf("%s--- %s%s\n", set, ecbdata->label_path[0], reset);
395 printf("%s+++ %s%s\n", set, ecbdata->label_path[1], reset);
396 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
399 /* This is not really necessary for now because
400 * this codepath only deals with two-way diffs.
402 for (i = 0; i < len && line[i] == '@'; i++)
404 if (2 <= i && i < len && line[i] == ' ') {
405 ecbdata->nparents = i - 1;
406 set = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
408 else if (len < ecbdata->nparents)
411 int nparents = ecbdata->nparents;
412 int color = DIFF_PLAIN;
413 if (ecbdata->diff_words && nparents != 1)
414 /* fall back to normal diff */
415 free_diff_words_data(ecbdata);
416 if (ecbdata->diff_words) {
417 if (line[0] == '-') {
418 diff_words_append(line, len,
419 &ecbdata->diff_words->minus);
421 } else if (line[0] == '+') {
422 diff_words_append(line, len,
423 &ecbdata->diff_words->plus);
426 if (ecbdata->diff_words->minus.text.size ||
427 ecbdata->diff_words->plus.text.size)
428 diff_words_show(ecbdata->diff_words);
432 for (i = 0; i < nparents && len; i++) {
434 color = DIFF_FILE_OLD;
435 else if (line[i] == '+')
436 color = DIFF_FILE_NEW;
438 set = diff_get_color(ecbdata->color_diff, color);
440 if (len > 0 && line[len-1] == '\n')
443 fwrite (line, len, 1, stdout);
447 static char *pprint_rename(const char *a, const char *b)
452 int pfx_length, sfx_length;
453 int len_a = strlen(a);
454 int len_b = strlen(b);
456 /* Find common prefix */
458 while (*old && *new && *old == *new) {
460 pfx_length = old - a + 1;
465 /* Find common suffix */
469 while (a <= old && b <= new && *old == *new) {
471 sfx_length = len_a - (old - a);
477 * pfx{mid-a => mid-b}sfx
478 * {pfx-a => pfx-b}sfx
479 * pfx{sfx-a => sfx-b}
482 if (pfx_length + sfx_length) {
483 int a_midlen = len_a - pfx_length - sfx_length;
484 int b_midlen = len_b - pfx_length - sfx_length;
485 if (a_midlen < 0) a_midlen = 0;
486 if (b_midlen < 0) b_midlen = 0;
488 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
489 sprintf(name, "%.*s{%.*s => %.*s}%s",
491 a_midlen, a + pfx_length,
492 b_midlen, b + pfx_length,
493 a + len_a - sfx_length);
496 name = xmalloc(len_a + len_b + 5);
497 sprintf(name, "%s => %s", a, b);
503 struct xdiff_emit_state xm;
507 struct diffstat_file {
509 unsigned is_unmerged:1;
510 unsigned is_binary:1;
511 unsigned is_renamed:1;
512 unsigned int added, deleted;
516 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
520 struct diffstat_file *x;
521 x = xcalloc(sizeof (*x), 1);
522 if (diffstat->nr == diffstat->alloc) {
523 diffstat->alloc = alloc_nr(diffstat->alloc);
524 diffstat->files = xrealloc(diffstat->files,
525 diffstat->alloc * sizeof(x));
527 diffstat->files[diffstat->nr++] = x;
529 x->name = pprint_rename(name_a, name_b);
533 x->name = xstrdup(name_a);
537 static void diffstat_consume(void *priv, char *line, unsigned long len)
539 struct diffstat_t *diffstat = priv;
540 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
544 else if (line[0] == '-')
548 const char mime_boundary_leader[] = "------------";
550 static int scale_linear(int it, int width, int max_change)
553 * round(width * it / max_change);
555 return (it * width * 2 + max_change) / (max_change * 2);
558 static void show_name(const char *prefix, const char *name, int len,
559 const char *reset, const char *set)
561 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
564 static void show_graph(char ch, int cnt, const char *set, const char *reset)
574 static void show_stats(struct diffstat_t* data, struct diff_options *options)
576 int i, len, add, del, total, adds = 0, dels = 0;
577 int max_change = 0, max_len = 0;
578 int total_files = data->nr;
579 int width, name_width;
580 const char *reset, *set, *add_c, *del_c;
585 width = options->stat_width ? options->stat_width : 80;
586 name_width = options->stat_name_width ? options->stat_name_width : 50;
588 /* Sanity: give at least 5 columns to the graph,
589 * but leave at least 10 columns for the name.
591 if (width < name_width + 15) {
592 if (name_width <= 25)
593 width = name_width + 15;
595 name_width = width - 15;
598 /* Find the longest filename and max number of changes */
599 reset = diff_get_color(options->color_diff, DIFF_RESET);
600 set = diff_get_color(options->color_diff, DIFF_PLAIN);
601 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
602 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
604 for (i = 0; i < data->nr; i++) {
605 struct diffstat_file *file = data->files[i];
606 int change = file->added + file->deleted;
608 len = quote_c_style(file->name, NULL, NULL, 0);
610 char *qname = xmalloc(len + 1);
611 quote_c_style(file->name, qname, NULL, 0);
616 len = strlen(file->name);
620 if (file->is_binary || file->is_unmerged)
622 if (max_change < change)
626 /* Compute the width of the graph part;
627 * 10 is for one blank at the beginning of the line plus
628 * " | count " between the name and the graph.
630 * From here on, name_width is the width of the name area,
631 * and width is the width of the graph area.
633 name_width = (name_width < max_len) ? name_width : max_len;
634 if (width < (name_width + 10) + max_change)
635 width = width - (name_width + 10);
639 for (i = 0; i < data->nr; i++) {
640 const char *prefix = "";
641 char *name = data->files[i]->name;
642 int added = data->files[i]->added;
643 int deleted = data->files[i]->deleted;
647 * "scale" the filename
650 name_len = strlen(name);
651 if (name_width < name_len) {
655 name += name_len - len;
656 slash = strchr(name, '/');
661 if (data->files[i]->is_binary) {
662 show_name(prefix, name, len, reset, set);
664 goto free_diffstat_file;
666 else if (data->files[i]->is_unmerged) {
667 show_name(prefix, name, len, reset, set);
668 printf(" Unmerged\n");
669 goto free_diffstat_file;
671 else if (!data->files[i]->is_renamed &&
672 (added + deleted == 0)) {
674 goto free_diffstat_file;
678 * scale the add/delete
686 if (width <= max_change) {
687 total = scale_linear(total, width, max_change);
688 add = scale_linear(add, width, max_change);
691 show_name(prefix, name, len, reset, set);
692 printf("%5d ", added + deleted);
693 show_graph('+', add, add_c, reset);
694 show_graph('-', del, del_c, reset);
697 free(data->files[i]->name);
698 free(data->files[i]);
701 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
702 set, total_files, adds, dels, reset);
706 struct xdiff_emit_state xm;
707 const char *filename;
711 static void checkdiff_consume(void *priv, char *line, unsigned long len)
713 struct checkdiff_t *data = priv;
715 if (line[0] == '+') {
720 /* check space before tab */
721 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
724 if (line[i - 1] == '\t' && spaces)
725 printf("%s:%d: space before tab:%.*s\n",
726 data->filename, data->lineno, (int)len, line);
728 /* check white space at line end */
729 if (line[len - 1] == '\n')
731 if (isspace(line[len - 1]))
732 printf("%s:%d: white space at end: %.*s\n",
733 data->filename, data->lineno, (int)len, line);
734 } else if (line[0] == ' ')
736 else if (line[0] == '@') {
737 char *plus = strchr(line, '+');
739 data->lineno = strtol(plus, NULL, 10);
745 static unsigned char *deflate_it(char *data,
747 unsigned long *result_size)
750 unsigned char *deflated;
753 memset(&stream, 0, sizeof(stream));
754 deflateInit(&stream, zlib_compression_level);
755 bound = deflateBound(&stream, size);
756 deflated = xmalloc(bound);
757 stream.next_out = deflated;
758 stream.avail_out = bound;
760 stream.next_in = (unsigned char *)data;
761 stream.avail_in = size;
762 while (deflate(&stream, Z_FINISH) == Z_OK)
765 *result_size = stream.total_out;
769 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
775 unsigned long orig_size;
776 unsigned long delta_size;
777 unsigned long deflate_size;
778 unsigned long data_size;
780 /* We could do deflated delta, or we could do just deflated two,
781 * whichever is smaller.
784 deflated = deflate_it(two->ptr, two->size, &deflate_size);
785 if (one->size && two->size) {
786 delta = diff_delta(one->ptr, one->size,
788 &delta_size, deflate_size);
790 void *to_free = delta;
791 orig_size = delta_size;
792 delta = deflate_it(delta, delta_size, &delta_size);
797 if (delta && delta_size < deflate_size) {
798 printf("delta %lu\n", orig_size);
801 data_size = delta_size;
804 printf("literal %lu\n", two->size);
807 data_size = deflate_size;
810 /* emit data encoded in base85 */
813 int bytes = (52 < data_size) ? 52 : data_size;
817 line[0] = bytes + 'A' - 1;
819 line[0] = bytes - 26 + 'a' - 1;
820 encode_85(line + 1, cp, bytes);
821 cp = (char *) cp + bytes;
828 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
830 printf("GIT binary patch\n");
831 emit_binary_diff_body(one, two);
832 emit_binary_diff_body(two, one);
835 #define FIRST_FEW_BYTES 8000
836 static int mmfile_is_binary(mmfile_t *mf)
839 if (FIRST_FEW_BYTES < sz)
840 sz = FIRST_FEW_BYTES;
841 return !!memchr(mf->ptr, 0, sz);
844 static void builtin_diff(const char *name_a,
846 struct diff_filespec *one,
847 struct diff_filespec *two,
848 const char *xfrm_msg,
849 struct diff_options *o,
850 int complete_rewrite)
855 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
856 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
858 a_one = quote_two("a/", name_a);
859 b_two = quote_two("b/", name_b);
860 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
861 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
862 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
863 if (lbl[0][0] == '/') {
865 printf("%snew file mode %06o%s\n", set, two->mode, reset);
866 if (xfrm_msg && xfrm_msg[0])
867 printf("%s%s%s\n", set, xfrm_msg, reset);
869 else if (lbl[1][0] == '/') {
870 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
871 if (xfrm_msg && xfrm_msg[0])
872 printf("%s%s%s\n", set, xfrm_msg, reset);
875 if (one->mode != two->mode) {
876 printf("%sold mode %06o%s\n", set, one->mode, reset);
877 printf("%snew mode %06o%s\n", set, two->mode, reset);
879 if (xfrm_msg && xfrm_msg[0])
880 printf("%s%s%s\n", set, xfrm_msg, reset);
882 * we do not run diff between different kind
885 if ((one->mode ^ two->mode) & S_IFMT)
886 goto free_ab_and_return;
887 if (complete_rewrite) {
888 emit_rewrite_diff(name_a, name_b, one, two);
889 goto free_ab_and_return;
893 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
894 die("unable to read files to diff");
896 if (!o->text && (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))) {
897 /* Quite common confusing case */
898 if (mf1.size == mf2.size &&
899 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
900 goto free_ab_and_return;
902 emit_binary_diff(&mf1, &mf2);
904 printf("Binary files %s and %s differ\n",
908 /* Crazy xdl interfaces.. */
909 const char *diffopts = getenv("GIT_DIFF_OPTS");
913 struct emit_callback ecbdata;
915 memset(&ecbdata, 0, sizeof(ecbdata));
916 ecbdata.label_path = lbl;
917 ecbdata.color_diff = o->color_diff;
918 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
919 xecfg.ctxlen = o->context;
920 xecfg.flags = XDL_EMIT_FUNCNAMES;
923 else if (!strncmp(diffopts, "--unified=", 10))
924 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
925 else if (!strncmp(diffopts, "-u", 2))
926 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
927 ecb.outf = xdiff_outf;
929 ecbdata.xm.consume = fn_out_consume;
930 if (o->color_diff_words)
932 xcalloc(1, sizeof(struct diff_words_data));
933 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
934 if (o->color_diff_words)
935 free_diff_words_data(&ecbdata);
944 static void builtin_diffstat(const char *name_a, const char *name_b,
945 struct diff_filespec *one,
946 struct diff_filespec *two,
947 struct diffstat_t *diffstat,
948 struct diff_options *o,
949 int complete_rewrite)
952 struct diffstat_file *data;
954 data = diffstat_add(diffstat, name_a, name_b);
957 data->is_unmerged = 1;
960 if (complete_rewrite) {
961 diff_populate_filespec(one, 0);
962 diff_populate_filespec(two, 0);
963 data->deleted = count_lines(one->data, one->size);
964 data->added = count_lines(two->data, two->size);
967 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
968 die("unable to read files to diff");
970 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
973 /* Crazy xdl interfaces.. */
978 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
981 ecb.outf = xdiff_outf;
983 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
987 static void builtin_checkdiff(const char *name_a, const char *name_b,
988 struct diff_filespec *one,
989 struct diff_filespec *two)
992 struct checkdiff_t data;
997 memset(&data, 0, sizeof(data));
998 data.xm.consume = checkdiff_consume;
999 data.filename = name_b ? name_b : name_a;
1002 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1003 die("unable to read files to diff");
1005 if (mmfile_is_binary(&mf2))
1008 /* Crazy xdl interfaces.. */
1013 xpp.flags = XDF_NEED_MINIMAL;
1016 ecb.outf = xdiff_outf;
1018 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1022 struct diff_filespec *alloc_filespec(const char *path)
1024 int namelen = strlen(path);
1025 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1027 memset(spec, 0, sizeof(*spec));
1028 spec->path = (char *)(spec + 1);
1029 memcpy(spec->path, path, namelen+1);
1033 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1034 unsigned short mode)
1037 spec->mode = canon_mode(mode);
1038 hashcpy(spec->sha1, sha1);
1039 spec->sha1_valid = !is_null_sha1(sha1);
1044 * Given a name and sha1 pair, if the dircache tells us the file in
1045 * the work tree has that object contents, return true, so that
1046 * prepare_temp_file() does not have to inflate and extract.
1048 static int work_tree_matches(const char *name, const unsigned char *sha1)
1050 struct cache_entry *ce;
1054 /* We do not read the cache ourselves here, because the
1055 * benchmark with my previous version that always reads cache
1056 * shows that it makes things worse for diff-tree comparing
1057 * two linux-2.6 kernel trees in an already checked out work
1058 * tree. This is because most diff-tree comparisons deal with
1059 * only a small number of files, while reading the cache is
1060 * expensive for a large project, and its cost outweighs the
1061 * savings we get by not inflating the object to a temporary
1062 * file. Practically, this code only helps when we are used
1063 * by diff-cache --cached, which does read the cache before
1070 pos = cache_name_pos(name, len);
1073 ce = active_cache[pos];
1074 if ((lstat(name, &st) < 0) ||
1075 !S_ISREG(st.st_mode) || /* careful! */
1076 ce_match_stat(ce, &st, 0) ||
1077 hashcmp(sha1, ce->sha1))
1079 /* we return 1 only when we can stat, it is a regular file,
1080 * stat information matches, and sha1 recorded in the cache
1081 * matches. I.e. we know the file in the work tree really is
1082 * the same as the <name, sha1> pair.
1087 static struct sha1_size_cache {
1088 unsigned char sha1[20];
1090 } **sha1_size_cache;
1091 static int sha1_size_cache_nr, sha1_size_cache_alloc;
1093 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
1098 struct sha1_size_cache *e;
1101 last = sha1_size_cache_nr;
1102 while (last > first) {
1103 int cmp, next = (last + first) >> 1;
1104 e = sha1_size_cache[next];
1105 cmp = hashcmp(e->sha1, sha1);
1117 /* insert to make it at "first" */
1118 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
1119 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
1120 sha1_size_cache = xrealloc(sha1_size_cache,
1121 sha1_size_cache_alloc *
1122 sizeof(*sha1_size_cache));
1124 sha1_size_cache_nr++;
1125 if (first < sha1_size_cache_nr)
1126 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
1127 (sha1_size_cache_nr - first - 1) *
1128 sizeof(*sha1_size_cache));
1129 e = xmalloc(sizeof(struct sha1_size_cache));
1130 sha1_size_cache[first] = e;
1131 hashcpy(e->sha1, sha1);
1137 * While doing rename detection and pickaxe operation, we may need to
1138 * grab the data for the blob (or file) for our own in-core comparison.
1139 * diff_filespec has data and size fields for this purpose.
1141 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1144 if (!DIFF_FILE_VALID(s))
1145 die("internal error: asking to populate invalid file.");
1146 if (S_ISDIR(s->mode))
1149 if (!use_size_cache)
1154 if (!s->sha1_valid ||
1155 work_tree_matches(s->path, s->sha1)) {
1158 if (lstat(s->path, &st) < 0) {
1159 if (errno == ENOENT) {
1163 s->data = (char *)"";
1168 s->size = st.st_size;
1173 if (S_ISLNK(st.st_mode)) {
1175 s->data = xmalloc(s->size);
1177 ret = readlink(s->path, s->data, s->size);
1184 fd = open(s->path, O_RDONLY);
1187 s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1189 if (s->data == MAP_FAILED)
1191 s->should_munmap = 1;
1195 struct sha1_size_cache *e;
1198 e = locate_size_cache(s->sha1, 1, 0);
1203 if (!sha1_object_info(s->sha1, type, &s->size))
1204 locate_size_cache(s->sha1, 0, s->size);
1207 s->data = read_sha1_file(s->sha1, type, &s->size);
1214 void diff_free_filespec_data(struct diff_filespec *s)
1218 else if (s->should_munmap)
1219 munmap(s->data, s->size);
1220 s->should_free = s->should_munmap = 0;
1226 static void prep_temp_blob(struct diff_tempfile *temp,
1229 const unsigned char *sha1,
1234 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1236 die("unable to create temp-file");
1237 if (write(fd, blob, size) != size)
1238 die("unable to write temp-file");
1240 temp->name = temp->tmp_path;
1241 strcpy(temp->hex, sha1_to_hex(sha1));
1243 sprintf(temp->mode, "%06o", mode);
1246 static void prepare_temp_file(const char *name,
1247 struct diff_tempfile *temp,
1248 struct diff_filespec *one)
1250 if (!DIFF_FILE_VALID(one)) {
1252 /* A '-' entry produces this for file-2, and
1253 * a '+' entry produces this for file-1.
1255 temp->name = "/dev/null";
1256 strcpy(temp->hex, ".");
1257 strcpy(temp->mode, ".");
1261 if (!one->sha1_valid ||
1262 work_tree_matches(name, one->sha1)) {
1264 if (lstat(name, &st) < 0) {
1265 if (errno == ENOENT)
1266 goto not_a_valid_file;
1267 die("stat(%s): %s", name, strerror(errno));
1269 if (S_ISLNK(st.st_mode)) {
1271 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1272 if (sizeof(buf) <= st.st_size)
1273 die("symlink too long: %s", name);
1274 ret = readlink(name, buf, st.st_size);
1276 die("readlink(%s)", name);
1277 prep_temp_blob(temp, buf, st.st_size,
1279 one->sha1 : null_sha1),
1281 one->mode : S_IFLNK));
1284 /* we can borrow from the file in the work tree */
1286 if (!one->sha1_valid)
1287 strcpy(temp->hex, sha1_to_hex(null_sha1));
1289 strcpy(temp->hex, sha1_to_hex(one->sha1));
1290 /* Even though we may sometimes borrow the
1291 * contents from the work tree, we always want
1292 * one->mode. mode is trustworthy even when
1293 * !(one->sha1_valid), as long as
1294 * DIFF_FILE_VALID(one).
1296 sprintf(temp->mode, "%06o", one->mode);
1301 if (diff_populate_filespec(one, 0))
1302 die("cannot read data blob for %s", one->path);
1303 prep_temp_blob(temp, one->data, one->size,
1304 one->sha1, one->mode);
1308 static void remove_tempfile(void)
1312 for (i = 0; i < 2; i++)
1313 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1314 unlink(diff_temp[i].name);
1315 diff_temp[i].name = NULL;
1319 static void remove_tempfile_on_signal(int signo)
1322 signal(SIGINT, SIG_DFL);
1326 static int spawn_prog(const char *pgm, const char **arg)
1334 die("unable to fork");
1336 execvp(pgm, (char *const*) arg);
1340 while (waitpid(pid, &status, 0) < 0) {
1346 /* Earlier we did not check the exit status because
1347 * diff exits non-zero if files are different, and
1348 * we are not interested in knowing that. It was a
1349 * mistake which made it harder to quit a diff-*
1350 * session that uses the git-apply-patch-script as
1351 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1352 * should also exit non-zero only when it wants to
1353 * abort the entire diff-* session.
1355 if (WIFEXITED(status) && !WEXITSTATUS(status))
1360 /* An external diff command takes:
1362 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1363 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1366 static void run_external_diff(const char *pgm,
1369 struct diff_filespec *one,
1370 struct diff_filespec *two,
1371 const char *xfrm_msg,
1372 int complete_rewrite)
1374 const char *spawn_arg[10];
1375 struct diff_tempfile *temp = diff_temp;
1377 static int atexit_asked = 0;
1378 const char *othername;
1379 const char **arg = &spawn_arg[0];
1381 othername = (other? other : name);
1383 prepare_temp_file(name, &temp[0], one);
1384 prepare_temp_file(othername, &temp[1], two);
1385 if (! atexit_asked &&
1386 (temp[0].name == temp[0].tmp_path ||
1387 temp[1].name == temp[1].tmp_path)) {
1389 atexit(remove_tempfile);
1391 signal(SIGINT, remove_tempfile_on_signal);
1397 *arg++ = temp[0].name;
1398 *arg++ = temp[0].hex;
1399 *arg++ = temp[0].mode;
1400 *arg++ = temp[1].name;
1401 *arg++ = temp[1].hex;
1402 *arg++ = temp[1].mode;
1412 retval = spawn_prog(pgm, spawn_arg);
1415 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1420 static void run_diff_cmd(const char *pgm,
1423 struct diff_filespec *one,
1424 struct diff_filespec *two,
1425 const char *xfrm_msg,
1426 struct diff_options *o,
1427 int complete_rewrite)
1430 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1435 builtin_diff(name, other ? other : name,
1436 one, two, xfrm_msg, o, complete_rewrite);
1438 printf("* Unmerged path %s\n", name);
1441 static void diff_fill_sha1_info(struct diff_filespec *one)
1443 if (DIFF_FILE_VALID(one)) {
1444 if (!one->sha1_valid) {
1446 if (lstat(one->path, &st) < 0)
1447 die("stat %s", one->path);
1448 if (index_path(one->sha1, one->path, &st, 0))
1449 die("cannot hash %s\n", one->path);
1456 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1458 const char *pgm = external_diff();
1459 char msg[PATH_MAX*2+300], *xfrm_msg;
1460 struct diff_filespec *one;
1461 struct diff_filespec *two;
1464 char *name_munged, *other_munged;
1465 int complete_rewrite = 0;
1468 if (DIFF_PAIR_UNMERGED(p)) {
1470 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1474 name = p->one->path;
1475 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1476 name_munged = quote_one(name);
1477 other_munged = quote_one(other);
1478 one = p->one; two = p->two;
1480 diff_fill_sha1_info(one);
1481 diff_fill_sha1_info(two);
1484 switch (p->status) {
1485 case DIFF_STATUS_COPIED:
1486 len += snprintf(msg + len, sizeof(msg) - len,
1487 "similarity index %d%%\n"
1490 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1491 name_munged, other_munged);
1493 case DIFF_STATUS_RENAMED:
1494 len += snprintf(msg + len, sizeof(msg) - len,
1495 "similarity index %d%%\n"
1498 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1499 name_munged, other_munged);
1501 case DIFF_STATUS_MODIFIED:
1503 len += snprintf(msg + len, sizeof(msg) - len,
1504 "dissimilarity index %d%%\n",
1505 (int)(0.5 + p->score *
1507 complete_rewrite = 1;
1516 if (hashcmp(one->sha1, two->sha1)) {
1517 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1521 if ((!fill_mmfile(&mf, one) && mmfile_is_binary(&mf)) ||
1522 (!fill_mmfile(&mf, two) && mmfile_is_binary(&mf)))
1525 len += snprintf(msg + len, sizeof(msg) - len,
1527 abbrev, sha1_to_hex(one->sha1),
1528 abbrev, sha1_to_hex(two->sha1));
1529 if (one->mode == two->mode)
1530 len += snprintf(msg + len, sizeof(msg) - len,
1531 " %06o", one->mode);
1532 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1537 xfrm_msg = len ? msg : NULL;
1540 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1541 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1542 /* a filepair that changes between file and symlink
1543 * needs to be split into deletion and creation.
1545 struct diff_filespec *null = alloc_filespec(two->path);
1546 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1548 null = alloc_filespec(one->path);
1549 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1553 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1560 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1561 struct diffstat_t *diffstat)
1565 int complete_rewrite = 0;
1567 if (DIFF_PAIR_UNMERGED(p)) {
1569 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1573 name = p->one->path;
1574 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1576 diff_fill_sha1_info(p->one);
1577 diff_fill_sha1_info(p->two);
1579 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1580 complete_rewrite = 1;
1581 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1584 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1589 if (DIFF_PAIR_UNMERGED(p)) {
1594 name = p->one->path;
1595 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1597 diff_fill_sha1_info(p->one);
1598 diff_fill_sha1_info(p->two);
1600 builtin_checkdiff(name, other, p->one, p->two);
1603 void diff_setup(struct diff_options *options)
1605 memset(options, 0, sizeof(*options));
1606 options->line_termination = '\n';
1607 options->break_opt = -1;
1608 options->rename_limit = -1;
1609 options->context = 3;
1610 options->msg_sep = "";
1612 options->change = diff_change;
1613 options->add_remove = diff_addremove;
1614 options->color_diff = diff_use_color_default;
1615 options->detect_rename = diff_detect_rename_default;
1618 int diff_setup_done(struct diff_options *options)
1622 if (options->output_format & DIFF_FORMAT_NAME)
1624 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
1626 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
1628 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
1631 die("--name-only, --name-status, --check and -s are mutually exclusive");
1633 if (options->find_copies_harder)
1634 options->detect_rename = DIFF_DETECT_COPY;
1636 if (options->output_format & (DIFF_FORMAT_NAME |
1637 DIFF_FORMAT_NAME_STATUS |
1638 DIFF_FORMAT_CHECKDIFF |
1639 DIFF_FORMAT_NO_OUTPUT))
1640 options->output_format &= ~(DIFF_FORMAT_RAW |
1641 DIFF_FORMAT_DIFFSTAT |
1642 DIFF_FORMAT_SUMMARY |
1646 * These cases always need recursive; we do not drop caller-supplied
1647 * recursive bits for other formats here.
1649 if (options->output_format & (DIFF_FORMAT_PATCH |
1650 DIFF_FORMAT_DIFFSTAT |
1651 DIFF_FORMAT_CHECKDIFF))
1652 options->recursive = 1;
1654 * Also pickaxe would not work very well if you do not say recursive
1656 if (options->pickaxe)
1657 options->recursive = 1;
1659 if (options->detect_rename && options->rename_limit < 0)
1660 options->rename_limit = diff_rename_limit_default;
1661 if (options->setup & DIFF_SETUP_USE_CACHE) {
1663 /* read-cache does not die even when it fails
1664 * so it is safe for us to do this here. Also
1665 * it does not smudge active_cache or active_nr
1666 * when it fails, so we do not have to worry about
1667 * cleaning it up ourselves either.
1671 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1673 if (options->abbrev <= 0 || 40 < options->abbrev)
1674 options->abbrev = 40; /* full */
1679 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1689 if (c == arg_short) {
1693 if (val && isdigit(c)) {
1695 int n = strtoul(arg, &end, 10);
1706 eq = strchr(arg, '=');
1711 if (!len || strncmp(arg, arg_long, len))
1716 if (!isdigit(*++eq))
1718 n = strtoul(eq, &end, 10);
1726 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1728 const char *arg = av[0];
1729 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1730 options->output_format |= DIFF_FORMAT_PATCH;
1731 else if (opt_arg(arg, 'U', "unified", &options->context))
1732 options->output_format |= DIFF_FORMAT_PATCH;
1733 else if (!strcmp(arg, "--raw"))
1734 options->output_format |= DIFF_FORMAT_RAW;
1735 else if (!strcmp(arg, "--patch-with-raw")) {
1736 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
1738 else if (!strcmp(arg, "--stat"))
1739 options->output_format |= DIFF_FORMAT_DIFFSTAT;
1740 else if (!strncmp(arg, "--stat-width=", 13)) {
1741 options->stat_width = strtoul(arg + 13, NULL, 10);
1742 options->output_format |= DIFF_FORMAT_DIFFSTAT;
1744 else if (!strncmp(arg, "--stat-name-width=", 18)) {
1745 options->stat_name_width = strtoul(arg + 18, NULL, 10);
1746 options->output_format |= DIFF_FORMAT_DIFFSTAT;
1748 else if (!strcmp(arg, "--check"))
1749 options->output_format |= DIFF_FORMAT_CHECKDIFF;
1750 else if (!strcmp(arg, "--summary"))
1751 options->output_format |= DIFF_FORMAT_SUMMARY;
1752 else if (!strcmp(arg, "--patch-with-stat")) {
1753 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
1755 else if (!strcmp(arg, "-z"))
1756 options->line_termination = 0;
1757 else if (!strncmp(arg, "-l", 2))
1758 options->rename_limit = strtoul(arg+2, NULL, 10);
1759 else if (!strcmp(arg, "--full-index"))
1760 options->full_index = 1;
1761 else if (!strcmp(arg, "--binary")) {
1762 options->output_format |= DIFF_FORMAT_PATCH;
1763 options->binary = 1;
1765 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
1768 else if (!strcmp(arg, "--name-only"))
1769 options->output_format |= DIFF_FORMAT_NAME;
1770 else if (!strcmp(arg, "--name-status"))
1771 options->output_format |= DIFF_FORMAT_NAME_STATUS;
1772 else if (!strcmp(arg, "-R"))
1773 options->reverse_diff = 1;
1774 else if (!strncmp(arg, "-S", 2))
1775 options->pickaxe = arg + 2;
1776 else if (!strcmp(arg, "-s")) {
1777 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
1779 else if (!strncmp(arg, "-O", 2))
1780 options->orderfile = arg + 2;
1781 else if (!strncmp(arg, "--diff-filter=", 14))
1782 options->filter = arg + 14;
1783 else if (!strcmp(arg, "--pickaxe-all"))
1784 options->pickaxe_opts = DIFF_PICKAXE_ALL;
1785 else if (!strcmp(arg, "--pickaxe-regex"))
1786 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
1787 else if (!strncmp(arg, "-B", 2)) {
1788 if ((options->break_opt =
1789 diff_scoreopt_parse(arg)) == -1)
1792 else if (!strncmp(arg, "-M", 2)) {
1793 if ((options->rename_score =
1794 diff_scoreopt_parse(arg)) == -1)
1796 options->detect_rename = DIFF_DETECT_RENAME;
1798 else if (!strncmp(arg, "-C", 2)) {
1799 if ((options->rename_score =
1800 diff_scoreopt_parse(arg)) == -1)
1802 options->detect_rename = DIFF_DETECT_COPY;
1804 else if (!strcmp(arg, "--find-copies-harder"))
1805 options->find_copies_harder = 1;
1806 else if (!strcmp(arg, "--abbrev"))
1807 options->abbrev = DEFAULT_ABBREV;
1808 else if (!strncmp(arg, "--abbrev=", 9)) {
1809 options->abbrev = strtoul(arg + 9, NULL, 10);
1810 if (options->abbrev < MINIMUM_ABBREV)
1811 options->abbrev = MINIMUM_ABBREV;
1812 else if (40 < options->abbrev)
1813 options->abbrev = 40;
1815 else if (!strcmp(arg, "--color"))
1816 options->color_diff = 1;
1817 else if (!strcmp(arg, "--no-color"))
1818 options->color_diff = 0;
1819 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
1820 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
1821 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
1822 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
1823 else if (!strcmp(arg, "--color-words"))
1824 options->color_diff = options->color_diff_words = 1;
1825 else if (!strcmp(arg, "--no-renames"))
1826 options->detect_rename = 0;
1832 static int parse_num(const char **cp_p)
1834 unsigned long num, scale;
1836 const char *cp = *cp_p;
1843 if ( !dot && ch == '.' ) {
1846 } else if ( ch == '%' ) {
1847 scale = dot ? scale*100 : 100;
1848 cp++; /* % is always at the end */
1850 } else if ( ch >= '0' && ch <= '9' ) {
1851 if ( scale < 100000 ) {
1853 num = (num*10) + (ch-'0');
1862 /* user says num divided by scale and we say internally that
1863 * is MAX_SCORE * num / scale.
1865 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
1868 int diff_scoreopt_parse(const char *opt)
1870 int opt1, opt2, cmd;
1875 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
1876 return -1; /* that is not a -M, -C nor -B option */
1878 opt1 = parse_num(&opt);
1884 else if (*opt != '/')
1885 return -1; /* we expect -B80/99 or -B80 */
1888 opt2 = parse_num(&opt);
1893 return opt1 | (opt2 << 16);
1896 struct diff_queue_struct diff_queued_diff;
1898 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
1900 if (queue->alloc <= queue->nr) {
1901 queue->alloc = alloc_nr(queue->alloc);
1902 queue->queue = xrealloc(queue->queue,
1903 sizeof(dp) * queue->alloc);
1905 queue->queue[queue->nr++] = dp;
1908 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
1909 struct diff_filespec *one,
1910 struct diff_filespec *two)
1912 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
1920 void diff_free_filepair(struct diff_filepair *p)
1922 diff_free_filespec_data(p->one);
1923 diff_free_filespec_data(p->two);
1929 /* This is different from find_unique_abbrev() in that
1930 * it stuffs the result with dots for alignment.
1932 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
1937 return sha1_to_hex(sha1);
1939 abbrev = find_unique_abbrev(sha1, len);
1941 return sha1_to_hex(sha1);
1942 abblen = strlen(abbrev);
1944 static char hex[41];
1945 if (len < abblen && abblen <= len + 2)
1946 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
1948 sprintf(hex, "%s...", abbrev);
1951 return sha1_to_hex(sha1);
1954 static void diff_flush_raw(struct diff_filepair *p,
1955 struct diff_options *options)
1959 int abbrev = options->abbrev;
1960 const char *path_one, *path_two;
1961 int inter_name_termination = '\t';
1962 int line_termination = options->line_termination;
1964 if (!line_termination)
1965 inter_name_termination = 0;
1967 path_one = p->one->path;
1968 path_two = p->two->path;
1969 if (line_termination) {
1970 path_one = quote_one(path_one);
1971 path_two = quote_one(path_two);
1975 sprintf(status, "%c%03d", p->status,
1976 (int)(0.5 + p->score * 100.0/MAX_SCORE));
1978 status[0] = p->status;
1981 switch (p->status) {
1982 case DIFF_STATUS_COPIED:
1983 case DIFF_STATUS_RENAMED:
1986 case DIFF_STATUS_ADDED:
1987 case DIFF_STATUS_DELETED:
1994 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
1995 printf(":%06o %06o %s ",
1996 p->one->mode, p->two->mode,
1997 diff_unique_abbrev(p->one->sha1, abbrev));
1999 diff_unique_abbrev(p->two->sha1, abbrev));
2001 printf("%s%c%s", status, inter_name_termination, path_one);
2003 printf("%c%s", inter_name_termination, path_two);
2004 putchar(line_termination);
2005 if (path_one != p->one->path)
2006 free((void*)path_one);
2007 if (path_two != p->two->path)
2008 free((void*)path_two);
2011 static void diff_flush_name(struct diff_filepair *p, int line_termination)
2013 char *path = p->two->path;
2015 if (line_termination)
2016 path = quote_one(p->two->path);
2017 printf("%s%c", path, line_termination);
2018 if (p->two->path != path)
2022 int diff_unmodified_pair(struct diff_filepair *p)
2024 /* This function is written stricter than necessary to support
2025 * the currently implemented transformers, but the idea is to
2026 * let transformers to produce diff_filepairs any way they want,
2027 * and filter and clean them up here before producing the output.
2029 struct diff_filespec *one, *two;
2031 if (DIFF_PAIR_UNMERGED(p))
2032 return 0; /* unmerged is interesting */
2037 /* deletion, addition, mode or type change
2038 * and rename are all interesting.
2040 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2041 DIFF_PAIR_MODE_CHANGED(p) ||
2042 strcmp(one->path, two->path))
2045 /* both are valid and point at the same path. that is, we are
2046 * dealing with a change.
2048 if (one->sha1_valid && two->sha1_valid &&
2049 !hashcmp(one->sha1, two->sha1))
2050 return 1; /* no change */
2051 if (!one->sha1_valid && !two->sha1_valid)
2052 return 1; /* both look at the same file on the filesystem. */
2056 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2058 if (diff_unmodified_pair(p))
2061 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2062 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2063 return; /* no tree diffs in patch format */
2068 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2069 struct diffstat_t *diffstat)
2071 if (diff_unmodified_pair(p))
2074 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2075 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2076 return; /* no tree diffs in patch format */
2078 run_diffstat(p, o, diffstat);
2081 static void diff_flush_checkdiff(struct diff_filepair *p,
2082 struct diff_options *o)
2084 if (diff_unmodified_pair(p))
2087 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2088 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2089 return; /* no tree diffs in patch format */
2091 run_checkdiff(p, o);
2094 int diff_queue_is_empty(void)
2096 struct diff_queue_struct *q = &diff_queued_diff;
2098 for (i = 0; i < q->nr; i++)
2099 if (!diff_unmodified_pair(q->queue[i]))
2105 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2107 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2110 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2112 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2113 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2115 s->size, s->xfrm_flags);
2118 void diff_debug_filepair(const struct diff_filepair *p, int i)
2120 diff_debug_filespec(p->one, i, "one");
2121 diff_debug_filespec(p->two, i, "two");
2122 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2123 p->score, p->status ? p->status : '?',
2124 p->source_stays, p->broken_pair);
2127 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2131 fprintf(stderr, "%s\n", msg);
2132 fprintf(stderr, "q->nr = %d\n", q->nr);
2133 for (i = 0; i < q->nr; i++) {
2134 struct diff_filepair *p = q->queue[i];
2135 diff_debug_filepair(p, i);
2140 static void diff_resolve_rename_copy(void)
2143 struct diff_filepair *p, *pp;
2144 struct diff_queue_struct *q = &diff_queued_diff;
2146 diff_debug_queue("resolve-rename-copy", q);
2148 for (i = 0; i < q->nr; i++) {
2150 p->status = 0; /* undecided */
2151 if (DIFF_PAIR_UNMERGED(p))
2152 p->status = DIFF_STATUS_UNMERGED;
2153 else if (!DIFF_FILE_VALID(p->one))
2154 p->status = DIFF_STATUS_ADDED;
2155 else if (!DIFF_FILE_VALID(p->two))
2156 p->status = DIFF_STATUS_DELETED;
2157 else if (DIFF_PAIR_TYPE_CHANGED(p))
2158 p->status = DIFF_STATUS_TYPE_CHANGED;
2160 /* from this point on, we are dealing with a pair
2161 * whose both sides are valid and of the same type, i.e.
2162 * either in-place edit or rename/copy edit.
2164 else if (DIFF_PAIR_RENAME(p)) {
2165 if (p->source_stays) {
2166 p->status = DIFF_STATUS_COPIED;
2169 /* See if there is some other filepair that
2170 * copies from the same source as us. If so
2171 * we are a copy. Otherwise we are either a
2172 * copy if the path stays, or a rename if it
2173 * does not, but we already handled "stays" case.
2175 for (j = i + 1; j < q->nr; j++) {
2177 if (strcmp(pp->one->path, p->one->path))
2178 continue; /* not us */
2179 if (!DIFF_PAIR_RENAME(pp))
2180 continue; /* not a rename/copy */
2181 /* pp is a rename/copy from the same source */
2182 p->status = DIFF_STATUS_COPIED;
2186 p->status = DIFF_STATUS_RENAMED;
2188 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2189 p->one->mode != p->two->mode)
2190 p->status = DIFF_STATUS_MODIFIED;
2192 /* This is a "no-change" entry and should not
2193 * happen anymore, but prepare for broken callers.
2195 error("feeding unmodified %s to diffcore",
2197 p->status = DIFF_STATUS_UNKNOWN;
2200 diff_debug_queue("resolve-rename-copy done", q);
2203 static int check_pair_status(struct diff_filepair *p)
2205 switch (p->status) {
2206 case DIFF_STATUS_UNKNOWN:
2209 die("internal error in diff-resolve-rename-copy");
2215 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2217 int fmt = opt->output_format;
2219 if (fmt & DIFF_FORMAT_CHECKDIFF)
2220 diff_flush_checkdiff(p, opt);
2221 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2222 diff_flush_raw(p, opt);
2223 else if (fmt & DIFF_FORMAT_NAME)
2224 diff_flush_name(p, opt->line_termination);
2227 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2230 printf(" %s mode %06o %s\n", newdelete, fs->mode, fs->path);
2232 printf(" %s %s\n", newdelete, fs->path);
2236 static void show_mode_change(struct diff_filepair *p, int show_name)
2238 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2240 printf(" mode change %06o => %06o %s\n",
2241 p->one->mode, p->two->mode, p->two->path);
2243 printf(" mode change %06o => %06o\n",
2244 p->one->mode, p->two->mode);
2248 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2250 const char *old, *new;
2252 /* Find common prefix */
2256 const char *slash_old, *slash_new;
2257 slash_old = strchr(old, '/');
2258 slash_new = strchr(new, '/');
2261 slash_old - old != slash_new - new ||
2262 memcmp(old, new, slash_new - new))
2264 old = slash_old + 1;
2265 new = slash_new + 1;
2267 /* p->one->path thru old is the common prefix, and old and new
2268 * through the end of names are renames
2270 if (old != p->one->path)
2271 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2272 (int)(old - p->one->path), p->one->path,
2273 old, new, (int)(0.5 + p->score * 100.0/MAX_SCORE));
2275 printf(" %s %s => %s (%d%%)\n", renamecopy,
2276 p->one->path, p->two->path,
2277 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2278 show_mode_change(p, 0);
2281 static void diff_summary(struct diff_filepair *p)
2284 case DIFF_STATUS_DELETED:
2285 show_file_mode_name("delete", p->one);
2287 case DIFF_STATUS_ADDED:
2288 show_file_mode_name("create", p->two);
2290 case DIFF_STATUS_COPIED:
2291 show_rename_copy("copy", p);
2293 case DIFF_STATUS_RENAMED:
2294 show_rename_copy("rename", p);
2298 printf(" rewrite %s (%d%%)\n", p->two->path,
2299 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2300 show_mode_change(p, 0);
2301 } else show_mode_change(p, 1);
2307 struct xdiff_emit_state xm;
2312 static int remove_space(char *line, int len)
2318 for (i = 0; i < len; i++)
2319 if (!isspace((c = line[i])))
2325 static void patch_id_consume(void *priv, char *line, unsigned long len)
2327 struct patch_id_t *data = priv;
2330 /* Ignore line numbers when computing the SHA1 of the patch */
2331 if (!strncmp(line, "@@ -", 4))
2334 new_len = remove_space(line, len);
2336 SHA1_Update(data->ctx, line, new_len);
2337 data->patchlen += new_len;
2340 /* returns 0 upon success, and writes result into sha1 */
2341 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2343 struct diff_queue_struct *q = &diff_queued_diff;
2346 struct patch_id_t data;
2347 char buffer[PATH_MAX * 4 + 20];
2350 memset(&data, 0, sizeof(struct patch_id_t));
2352 data.xm.consume = patch_id_consume;
2354 for (i = 0; i < q->nr; i++) {
2359 struct diff_filepair *p = q->queue[i];
2363 return error("internal diff status error");
2364 if (p->status == DIFF_STATUS_UNKNOWN)
2366 if (diff_unmodified_pair(p))
2368 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2369 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2371 if (DIFF_PAIR_UNMERGED(p))
2374 diff_fill_sha1_info(p->one);
2375 diff_fill_sha1_info(p->two);
2376 if (fill_mmfile(&mf1, p->one) < 0 ||
2377 fill_mmfile(&mf2, p->two) < 0)
2378 return error("unable to read files to diff");
2380 /* Maybe hash p->two? into the patch id? */
2381 if (mmfile_is_binary(&mf2))
2384 len1 = remove_space(p->one->path, strlen(p->one->path));
2385 len2 = remove_space(p->two->path, strlen(p->two->path));
2386 if (p->one->mode == 0)
2387 len1 = snprintf(buffer, sizeof(buffer),
2388 "diff--gita/%.*sb/%.*s"
2395 len2, p->two->path);
2396 else if (p->two->mode == 0)
2397 len1 = snprintf(buffer, sizeof(buffer),
2398 "diff--gita/%.*sb/%.*s"
2399 "deletedfilemode%06o"
2405 len1, p->one->path);
2407 len1 = snprintf(buffer, sizeof(buffer),
2408 "diff--gita/%.*sb/%.*s"
2414 len2, p->two->path);
2415 SHA1_Update(&ctx, buffer, len1);
2417 xpp.flags = XDF_NEED_MINIMAL;
2419 xecfg.flags = XDL_EMIT_FUNCNAMES;
2420 ecb.outf = xdiff_outf;
2422 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2425 SHA1_Final(sha1, &ctx);
2429 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2431 struct diff_queue_struct *q = &diff_queued_diff;
2433 int result = diff_get_patch_id(options, sha1);
2435 for (i = 0; i < q->nr; i++)
2436 diff_free_filepair(q->queue[i]);
2440 q->nr = q->alloc = 0;
2445 static int is_summary_empty(const struct diff_queue_struct *q)
2449 for (i = 0; i < q->nr; i++) {
2450 const struct diff_filepair *p = q->queue[i];
2452 switch (p->status) {
2453 case DIFF_STATUS_DELETED:
2454 case DIFF_STATUS_ADDED:
2455 case DIFF_STATUS_COPIED:
2456 case DIFF_STATUS_RENAMED:
2461 if (p->one->mode && p->two->mode &&
2462 p->one->mode != p->two->mode)
2470 void diff_flush(struct diff_options *options)
2472 struct diff_queue_struct *q = &diff_queued_diff;
2473 int i, output_format = options->output_format;
2477 * Order: raw, stat, summary, patch
2478 * or: name/name-status/checkdiff (other bits clear)
2483 if (output_format & (DIFF_FORMAT_RAW |
2485 DIFF_FORMAT_NAME_STATUS |
2486 DIFF_FORMAT_CHECKDIFF)) {
2487 for (i = 0; i < q->nr; i++) {
2488 struct diff_filepair *p = q->queue[i];
2489 if (check_pair_status(p))
2490 flush_one_pair(p, options);
2495 if (output_format & DIFF_FORMAT_DIFFSTAT) {
2496 struct diffstat_t diffstat;
2498 memset(&diffstat, 0, sizeof(struct diffstat_t));
2499 diffstat.xm.consume = diffstat_consume;
2500 for (i = 0; i < q->nr; i++) {
2501 struct diff_filepair *p = q->queue[i];
2502 if (check_pair_status(p))
2503 diff_flush_stat(p, options, &diffstat);
2505 show_stats(&diffstat, options);
2509 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2510 for (i = 0; i < q->nr; i++)
2511 diff_summary(q->queue[i]);
2515 if (output_format & DIFF_FORMAT_PATCH) {
2517 if (options->stat_sep) {
2518 /* attach patch instead of inline */
2519 fputs(options->stat_sep, stdout);
2521 putchar(options->line_termination);
2525 for (i = 0; i < q->nr; i++) {
2526 struct diff_filepair *p = q->queue[i];
2527 if (check_pair_status(p))
2528 diff_flush_patch(p, options);
2532 if (output_format & DIFF_FORMAT_CALLBACK)
2533 options->format_callback(q, options, options->format_callback_data);
2535 for (i = 0; i < q->nr; i++)
2536 diff_free_filepair(q->queue[i]);
2540 q->nr = q->alloc = 0;
2543 static void diffcore_apply_filter(const char *filter)
2546 struct diff_queue_struct *q = &diff_queued_diff;
2547 struct diff_queue_struct outq;
2549 outq.nr = outq.alloc = 0;
2554 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2556 for (i = found = 0; !found && i < q->nr; i++) {
2557 struct diff_filepair *p = q->queue[i];
2558 if (((p->status == DIFF_STATUS_MODIFIED) &&
2560 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2562 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2563 ((p->status != DIFF_STATUS_MODIFIED) &&
2564 strchr(filter, p->status)))
2570 /* otherwise we will clear the whole queue
2571 * by copying the empty outq at the end of this
2572 * function, but first clear the current entries
2575 for (i = 0; i < q->nr; i++)
2576 diff_free_filepair(q->queue[i]);
2579 /* Only the matching ones */
2580 for (i = 0; i < q->nr; i++) {
2581 struct diff_filepair *p = q->queue[i];
2583 if (((p->status == DIFF_STATUS_MODIFIED) &&
2585 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2587 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2588 ((p->status != DIFF_STATUS_MODIFIED) &&
2589 strchr(filter, p->status)))
2592 diff_free_filepair(p);
2599 void diffcore_std(struct diff_options *options)
2601 if (options->break_opt != -1)
2602 diffcore_break(options->break_opt);
2603 if (options->detect_rename)
2604 diffcore_rename(options);
2605 if (options->break_opt != -1)
2606 diffcore_merge_broken();
2607 if (options->pickaxe)
2608 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2609 if (options->orderfile)
2610 diffcore_order(options->orderfile);
2611 diff_resolve_rename_copy();
2612 diffcore_apply_filter(options->filter);
2616 void diffcore_std_no_resolve(struct diff_options *options)
2618 if (options->pickaxe)
2619 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2620 if (options->orderfile)
2621 diffcore_order(options->orderfile);
2622 diffcore_apply_filter(options->filter);
2625 void diff_addremove(struct diff_options *options,
2626 int addremove, unsigned mode,
2627 const unsigned char *sha1,
2628 const char *base, const char *path)
2630 char concatpath[PATH_MAX];
2631 struct diff_filespec *one, *two;
2633 /* This may look odd, but it is a preparation for
2634 * feeding "there are unchanged files which should
2635 * not produce diffs, but when you are doing copy
2636 * detection you would need them, so here they are"
2637 * entries to the diff-core. They will be prefixed
2638 * with something like '=' or '*' (I haven't decided
2639 * which but should not make any difference).
2640 * Feeding the same new and old to diff_change()
2641 * also has the same effect.
2642 * Before the final output happens, they are pruned after
2643 * merged into rename/copy pairs as appropriate.
2645 if (options->reverse_diff)
2646 addremove = (addremove == '+' ? '-' :
2647 addremove == '-' ? '+' : addremove);
2649 if (!path) path = "";
2650 sprintf(concatpath, "%s%s", base, path);
2651 one = alloc_filespec(concatpath);
2652 two = alloc_filespec(concatpath);
2654 if (addremove != '+')
2655 fill_filespec(one, sha1, mode);
2656 if (addremove != '-')
2657 fill_filespec(two, sha1, mode);
2659 diff_queue(&diff_queued_diff, one, two);
2662 void diff_change(struct diff_options *options,
2663 unsigned old_mode, unsigned new_mode,
2664 const unsigned char *old_sha1,
2665 const unsigned char *new_sha1,
2666 const char *base, const char *path)
2668 char concatpath[PATH_MAX];
2669 struct diff_filespec *one, *two;
2671 if (options->reverse_diff) {
2673 const unsigned char *tmp_c;
2674 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2675 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2677 if (!path) path = "";
2678 sprintf(concatpath, "%s%s", base, path);
2679 one = alloc_filespec(concatpath);
2680 two = alloc_filespec(concatpath);
2681 fill_filespec(one, old_sha1, old_mode);
2682 fill_filespec(two, new_sha1, new_mode);
2684 diff_queue(&diff_queued_diff, one, two);
2687 void diff_unmerge(struct diff_options *options,
2690 struct diff_filespec *one, *two;
2691 one = alloc_filespec(path);
2692 two = alloc_filespec(path);
2693 diff_queue(&diff_queued_diff, one, two);