Sample update hook: typofix and modernization to use "git log"
[git/platforms.git] / diff.c
blobe225de230599bb35d9fe5b219ff4b8e8de9bfd97
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "quote.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "delta.h"
9 #include "xdiff-interface.h"
10 #include "color.h"
12 #ifdef NO_FAST_WORKING_DIRECTORY
13 #define FAST_WORKING_DIRECTORY 0
14 #else
15 #define FAST_WORKING_DIRECTORY 1
16 #endif
18 static int use_size_cache;
20 static int diff_detect_rename_default;
21 static int diff_rename_limit_default = -1;
22 static int diff_use_color_default;
24 static char diff_colors[][COLOR_MAXLEN] = {
25 "\033[m", /* reset */
26 "", /* PLAIN (normal) */
27 "\033[1m", /* METAINFO (bold) */
28 "\033[36m", /* FRAGINFO (cyan) */
29 "\033[31m", /* OLD (red) */
30 "\033[32m", /* NEW (green) */
31 "\033[33m", /* COMMIT (yellow) */
32 "\033[41m", /* WHITESPACE (red background) */
35 static int parse_diff_color_slot(const char *var, int ofs)
37 if (!strcasecmp(var+ofs, "plain"))
38 return DIFF_PLAIN;
39 if (!strcasecmp(var+ofs, "meta"))
40 return DIFF_METAINFO;
41 if (!strcasecmp(var+ofs, "frag"))
42 return DIFF_FRAGINFO;
43 if (!strcasecmp(var+ofs, "old"))
44 return DIFF_FILE_OLD;
45 if (!strcasecmp(var+ofs, "new"))
46 return DIFF_FILE_NEW;
47 if (!strcasecmp(var+ofs, "commit"))
48 return DIFF_COMMIT;
49 if (!strcasecmp(var+ofs, "whitespace"))
50 return DIFF_WHITESPACE;
51 die("bad config variable '%s'", var);
55 * These are to give UI layer defaults.
56 * The core-level commands such as git-diff-files should
57 * never be affected by the setting of diff.renames
58 * the user happens to have in the configuration file.
60 int git_diff_ui_config(const char *var, const char *value)
62 if (!strcmp(var, "diff.renamelimit")) {
63 diff_rename_limit_default = git_config_int(var, value);
64 return 0;
66 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
67 diff_use_color_default = git_config_colorbool(var, value);
68 return 0;
70 if (!strcmp(var, "diff.renames")) {
71 if (!value)
72 diff_detect_rename_default = DIFF_DETECT_RENAME;
73 else if (!strcasecmp(value, "copies") ||
74 !strcasecmp(value, "copy"))
75 diff_detect_rename_default = DIFF_DETECT_COPY;
76 else if (git_config_bool(var,value))
77 diff_detect_rename_default = DIFF_DETECT_RENAME;
78 return 0;
80 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
81 int slot = parse_diff_color_slot(var, 11);
82 color_parse(value, var, diff_colors[slot]);
83 return 0;
85 return git_default_config(var, value);
88 static char *quote_one(const char *str)
90 int needlen;
91 char *xp;
93 if (!str)
94 return NULL;
95 needlen = quote_c_style(str, NULL, NULL, 0);
96 if (!needlen)
97 return xstrdup(str);
98 xp = xmalloc(needlen + 1);
99 quote_c_style(str, xp, NULL, 0);
100 return xp;
103 static char *quote_two(const char *one, const char *two)
105 int need_one = quote_c_style(one, NULL, NULL, 1);
106 int need_two = quote_c_style(two, NULL, NULL, 1);
107 char *xp;
109 if (need_one + need_two) {
110 if (!need_one) need_one = strlen(one);
111 if (!need_two) need_one = strlen(two);
113 xp = xmalloc(need_one + need_two + 3);
114 xp[0] = '"';
115 quote_c_style(one, xp + 1, NULL, 1);
116 quote_c_style(two, xp + need_one + 1, NULL, 1);
117 strcpy(xp + need_one + need_two + 1, "\"");
118 return xp;
120 need_one = strlen(one);
121 need_two = strlen(two);
122 xp = xmalloc(need_one + need_two + 1);
123 strcpy(xp, one);
124 strcpy(xp + need_one, two);
125 return xp;
128 static const char *external_diff(void)
130 static const char *external_diff_cmd = NULL;
131 static int done_preparing = 0;
133 if (done_preparing)
134 return external_diff_cmd;
135 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
136 done_preparing = 1;
137 return external_diff_cmd;
140 #define TEMPFILE_PATH_LEN 50
142 static struct diff_tempfile {
143 const char *name; /* filename external diff should read from */
144 char hex[41];
145 char mode[10];
146 char tmp_path[TEMPFILE_PATH_LEN];
147 } diff_temp[2];
149 static int count_lines(const char *data, int size)
151 int count, ch, completely_empty = 1, nl_just_seen = 0;
152 count = 0;
153 while (0 < size--) {
154 ch = *data++;
155 if (ch == '\n') {
156 count++;
157 nl_just_seen = 1;
158 completely_empty = 0;
160 else {
161 nl_just_seen = 0;
162 completely_empty = 0;
165 if (completely_empty)
166 return 0;
167 if (!nl_just_seen)
168 count++; /* no trailing newline */
169 return count;
172 static void print_line_count(int count)
174 switch (count) {
175 case 0:
176 printf("0,0");
177 break;
178 case 1:
179 printf("1");
180 break;
181 default:
182 printf("1,%d", count);
183 break;
187 static void copy_file(int prefix, const char *data, int size,
188 const char *set, const char *reset)
190 int ch, nl_just_seen = 1;
191 while (0 < size--) {
192 ch = *data++;
193 if (nl_just_seen) {
194 fputs(set, stdout);
195 putchar(prefix);
197 if (ch == '\n') {
198 nl_just_seen = 1;
199 fputs(reset, stdout);
200 } else
201 nl_just_seen = 0;
202 putchar(ch);
204 if (!nl_just_seen)
205 printf("%s\n\\ No newline at end of file\n", reset);
208 static void emit_rewrite_diff(const char *name_a,
209 const char *name_b,
210 struct diff_filespec *one,
211 struct diff_filespec *two,
212 int color_diff)
214 int lc_a, lc_b;
215 const char *name_a_tab, *name_b_tab;
216 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
217 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
218 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
219 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
220 const char *reset = diff_get_color(color_diff, DIFF_RESET);
222 name_a += (*name_a == '/');
223 name_b += (*name_b == '/');
224 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
225 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
227 diff_populate_filespec(one, 0);
228 diff_populate_filespec(two, 0);
229 lc_a = count_lines(one->data, one->size);
230 lc_b = count_lines(two->data, two->size);
231 printf("%s--- a/%s%s%s\n%s+++ b/%s%s%s\n%s@@ -",
232 metainfo, name_a, name_a_tab, reset,
233 metainfo, name_b, name_b_tab, reset, fraginfo);
234 print_line_count(lc_a);
235 printf(" +");
236 print_line_count(lc_b);
237 printf(" @@%s\n", reset);
238 if (lc_a)
239 copy_file('-', one->data, one->size, old, reset);
240 if (lc_b)
241 copy_file('+', two->data, two->size, new, reset);
244 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
246 if (!DIFF_FILE_VALID(one)) {
247 mf->ptr = (char *)""; /* does not matter */
248 mf->size = 0;
249 return 0;
251 else if (diff_populate_filespec(one, 0))
252 return -1;
253 mf->ptr = one->data;
254 mf->size = one->size;
255 return 0;
258 struct diff_words_buffer {
259 mmfile_t text;
260 long alloc;
261 long current; /* output pointer */
262 int suppressed_newline;
265 static void diff_words_append(char *line, unsigned long len,
266 struct diff_words_buffer *buffer)
268 if (buffer->text.size + len > buffer->alloc) {
269 buffer->alloc = (buffer->text.size + len) * 3 / 2;
270 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
272 line++;
273 len--;
274 memcpy(buffer->text.ptr + buffer->text.size, line, len);
275 buffer->text.size += len;
278 struct diff_words_data {
279 struct xdiff_emit_state xm;
280 struct diff_words_buffer minus, plus;
283 static void print_word(struct diff_words_buffer *buffer, int len, int color,
284 int suppress_newline)
286 const char *ptr;
287 int eol = 0;
289 if (len == 0)
290 return;
292 ptr = buffer->text.ptr + buffer->current;
293 buffer->current += len;
295 if (ptr[len - 1] == '\n') {
296 eol = 1;
297 len--;
300 fputs(diff_get_color(1, color), stdout);
301 fwrite(ptr, len, 1, stdout);
302 fputs(diff_get_color(1, DIFF_RESET), stdout);
304 if (eol) {
305 if (suppress_newline)
306 buffer->suppressed_newline = 1;
307 else
308 putchar('\n');
312 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
314 struct diff_words_data *diff_words = priv;
316 if (diff_words->minus.suppressed_newline) {
317 if (line[0] != '+')
318 putchar('\n');
319 diff_words->minus.suppressed_newline = 0;
322 len--;
323 switch (line[0]) {
324 case '-':
325 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
326 break;
327 case '+':
328 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
329 break;
330 case ' ':
331 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
332 diff_words->minus.current += len;
333 break;
337 /* this executes the word diff on the accumulated buffers */
338 static void diff_words_show(struct diff_words_data *diff_words)
340 xpparam_t xpp;
341 xdemitconf_t xecfg;
342 xdemitcb_t ecb;
343 mmfile_t minus, plus;
344 int i;
346 minus.size = diff_words->minus.text.size;
347 minus.ptr = xmalloc(minus.size);
348 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
349 for (i = 0; i < minus.size; i++)
350 if (isspace(minus.ptr[i]))
351 minus.ptr[i] = '\n';
352 diff_words->minus.current = 0;
354 plus.size = diff_words->plus.text.size;
355 plus.ptr = xmalloc(plus.size);
356 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
357 for (i = 0; i < plus.size; i++)
358 if (isspace(plus.ptr[i]))
359 plus.ptr[i] = '\n';
360 diff_words->plus.current = 0;
362 xpp.flags = XDF_NEED_MINIMAL;
363 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
364 xecfg.flags = 0;
365 ecb.outf = xdiff_outf;
366 ecb.priv = diff_words;
367 diff_words->xm.consume = fn_out_diff_words_aux;
368 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
370 free(minus.ptr);
371 free(plus.ptr);
372 diff_words->minus.text.size = diff_words->plus.text.size = 0;
374 if (diff_words->minus.suppressed_newline) {
375 putchar('\n');
376 diff_words->minus.suppressed_newline = 0;
380 struct emit_callback {
381 struct xdiff_emit_state xm;
382 int nparents, color_diff;
383 const char **label_path;
384 struct diff_words_data *diff_words;
385 int *found_changesp;
388 static void free_diff_words_data(struct emit_callback *ecbdata)
390 if (ecbdata->diff_words) {
391 /* flush buffers */
392 if (ecbdata->diff_words->minus.text.size ||
393 ecbdata->diff_words->plus.text.size)
394 diff_words_show(ecbdata->diff_words);
396 if (ecbdata->diff_words->minus.text.ptr)
397 free (ecbdata->diff_words->minus.text.ptr);
398 if (ecbdata->diff_words->plus.text.ptr)
399 free (ecbdata->diff_words->plus.text.ptr);
400 free(ecbdata->diff_words);
401 ecbdata->diff_words = NULL;
405 const char *diff_get_color(int diff_use_color, enum color_diff ix)
407 if (diff_use_color)
408 return diff_colors[ix];
409 return "";
412 static void emit_line(const char *set, const char *reset, const char *line, int len)
414 if (len > 0 && line[len-1] == '\n')
415 len--;
416 fputs(set, stdout);
417 fwrite(line, len, 1, stdout);
418 puts(reset);
421 static void emit_line_with_ws(int nparents,
422 const char *set, const char *reset, const char *ws,
423 const char *line, int len)
425 int col0 = nparents;
426 int last_tab_in_indent = -1;
427 int last_space_in_indent = -1;
428 int i;
429 int tail = len;
430 int need_highlight_leading_space = 0;
431 /* The line is a newly added line. Does it have funny leading
432 * whitespaces? In indent, SP should never precede a TAB.
434 for (i = col0; i < len; i++) {
435 if (line[i] == '\t') {
436 last_tab_in_indent = i;
437 if (0 <= last_space_in_indent)
438 need_highlight_leading_space = 1;
440 else if (line[i] == ' ')
441 last_space_in_indent = i;
442 else
443 break;
445 fputs(set, stdout);
446 fwrite(line, col0, 1, stdout);
447 fputs(reset, stdout);
448 if (((i == len) || line[i] == '\n') && i != col0) {
449 /* The whole line was indent */
450 emit_line(ws, reset, line + col0, len - col0);
451 return;
453 i = col0;
454 if (need_highlight_leading_space) {
455 while (i < last_tab_in_indent) {
456 if (line[i] == ' ') {
457 fputs(ws, stdout);
458 putchar(' ');
459 fputs(reset, stdout);
461 else
462 putchar(line[i]);
463 i++;
466 tail = len - 1;
467 if (line[tail] == '\n' && i < tail)
468 tail--;
469 while (i < tail) {
470 if (!isspace(line[tail]))
471 break;
472 tail--;
474 if ((i < tail && line[tail + 1] != '\n')) {
475 /* This has whitespace between tail+1..len */
476 fputs(set, stdout);
477 fwrite(line + i, tail - i + 1, 1, stdout);
478 fputs(reset, stdout);
479 emit_line(ws, reset, line + tail + 1, len - tail - 1);
481 else
482 emit_line(set, reset, line + i, len - i);
485 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
487 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
488 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
490 if (!*ws)
491 emit_line(set, reset, line, len);
492 else
493 emit_line_with_ws(ecbdata->nparents, set, reset, ws,
494 line, len);
497 static void fn_out_consume(void *priv, char *line, unsigned long len)
499 int i;
500 int color;
501 struct emit_callback *ecbdata = priv;
502 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
503 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
505 *(ecbdata->found_changesp) = 1;
507 if (ecbdata->label_path[0]) {
508 const char *name_a_tab, *name_b_tab;
510 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
511 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
513 printf("%s--- %s%s%s\n",
514 set, ecbdata->label_path[0], reset, name_a_tab);
515 printf("%s+++ %s%s%s\n",
516 set, ecbdata->label_path[1], reset, name_b_tab);
517 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
520 /* This is not really necessary for now because
521 * this codepath only deals with two-way diffs.
523 for (i = 0; i < len && line[i] == '@'; i++)
525 if (2 <= i && i < len && line[i] == ' ') {
526 ecbdata->nparents = i - 1;
527 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
528 reset, line, len);
529 return;
532 if (len < ecbdata->nparents) {
533 set = reset;
534 emit_line(reset, reset, line, len);
535 return;
538 color = DIFF_PLAIN;
539 if (ecbdata->diff_words && ecbdata->nparents != 1)
540 /* fall back to normal diff */
541 free_diff_words_data(ecbdata);
542 if (ecbdata->diff_words) {
543 if (line[0] == '-') {
544 diff_words_append(line, len,
545 &ecbdata->diff_words->minus);
546 return;
547 } else if (line[0] == '+') {
548 diff_words_append(line, len,
549 &ecbdata->diff_words->plus);
550 return;
552 if (ecbdata->diff_words->minus.text.size ||
553 ecbdata->diff_words->plus.text.size)
554 diff_words_show(ecbdata->diff_words);
555 line++;
556 len--;
557 emit_line(set, reset, line, len);
558 return;
560 for (i = 0; i < ecbdata->nparents && len; i++) {
561 if (line[i] == '-')
562 color = DIFF_FILE_OLD;
563 else if (line[i] == '+')
564 color = DIFF_FILE_NEW;
567 if (color != DIFF_FILE_NEW) {
568 emit_line(diff_get_color(ecbdata->color_diff, color),
569 reset, line, len);
570 return;
572 emit_add_line(reset, ecbdata, line, len);
575 static char *pprint_rename(const char *a, const char *b)
577 const char *old = a;
578 const char *new = b;
579 char *name = NULL;
580 int pfx_length, sfx_length;
581 int len_a = strlen(a);
582 int len_b = strlen(b);
583 int qlen_a = quote_c_style(a, NULL, NULL, 0);
584 int qlen_b = quote_c_style(b, NULL, NULL, 0);
586 if (qlen_a || qlen_b) {
587 if (qlen_a) len_a = qlen_a;
588 if (qlen_b) len_b = qlen_b;
589 name = xmalloc( len_a + len_b + 5 );
590 if (qlen_a)
591 quote_c_style(a, name, NULL, 0);
592 else
593 memcpy(name, a, len_a);
594 memcpy(name + len_a, " => ", 4);
595 if (qlen_b)
596 quote_c_style(b, name + len_a + 4, NULL, 0);
597 else
598 memcpy(name + len_a + 4, b, len_b + 1);
599 return name;
602 /* Find common prefix */
603 pfx_length = 0;
604 while (*old && *new && *old == *new) {
605 if (*old == '/')
606 pfx_length = old - a + 1;
607 old++;
608 new++;
611 /* Find common suffix */
612 old = a + len_a;
613 new = b + len_b;
614 sfx_length = 0;
615 while (a <= old && b <= new && *old == *new) {
616 if (*old == '/')
617 sfx_length = len_a - (old - a);
618 old--;
619 new--;
623 * pfx{mid-a => mid-b}sfx
624 * {pfx-a => pfx-b}sfx
625 * pfx{sfx-a => sfx-b}
626 * name-a => name-b
628 if (pfx_length + sfx_length) {
629 int a_midlen = len_a - pfx_length - sfx_length;
630 int b_midlen = len_b - pfx_length - sfx_length;
631 if (a_midlen < 0) a_midlen = 0;
632 if (b_midlen < 0) b_midlen = 0;
634 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
635 sprintf(name, "%.*s{%.*s => %.*s}%s",
636 pfx_length, a,
637 a_midlen, a + pfx_length,
638 b_midlen, b + pfx_length,
639 a + len_a - sfx_length);
641 else {
642 name = xmalloc(len_a + len_b + 5);
643 sprintf(name, "%s => %s", a, b);
645 return name;
648 struct diffstat_t {
649 struct xdiff_emit_state xm;
651 int nr;
652 int alloc;
653 struct diffstat_file {
654 char *name;
655 unsigned is_unmerged:1;
656 unsigned is_binary:1;
657 unsigned is_renamed:1;
658 unsigned int added, deleted;
659 } **files;
662 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
663 const char *name_a,
664 const char *name_b)
666 struct diffstat_file *x;
667 x = xcalloc(sizeof (*x), 1);
668 if (diffstat->nr == diffstat->alloc) {
669 diffstat->alloc = alloc_nr(diffstat->alloc);
670 diffstat->files = xrealloc(diffstat->files,
671 diffstat->alloc * sizeof(x));
673 diffstat->files[diffstat->nr++] = x;
674 if (name_b) {
675 x->name = pprint_rename(name_a, name_b);
676 x->is_renamed = 1;
678 else
679 x->name = xstrdup(name_a);
680 return x;
683 static void diffstat_consume(void *priv, char *line, unsigned long len)
685 struct diffstat_t *diffstat = priv;
686 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
688 if (line[0] == '+')
689 x->added++;
690 else if (line[0] == '-')
691 x->deleted++;
694 const char mime_boundary_leader[] = "------------";
696 static int scale_linear(int it, int width, int max_change)
699 * make sure that at least one '-' is printed if there were deletions,
700 * and likewise for '+'.
702 if (max_change < 2)
703 return it;
704 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
707 static void show_name(const char *prefix, const char *name, int len,
708 const char *reset, const char *set)
710 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
713 static void show_graph(char ch, int cnt, const char *set, const char *reset)
715 if (cnt <= 0)
716 return;
717 printf("%s", set);
718 while (cnt--)
719 putchar(ch);
720 printf("%s", reset);
723 static void show_stats(struct diffstat_t* data, struct diff_options *options)
725 int i, len, add, del, total, adds = 0, dels = 0;
726 int max_change = 0, max_len = 0;
727 int total_files = data->nr;
728 int width, name_width;
729 const char *reset, *set, *add_c, *del_c;
731 if (data->nr == 0)
732 return;
734 width = options->stat_width ? options->stat_width : 80;
735 name_width = options->stat_name_width ? options->stat_name_width : 50;
737 /* Sanity: give at least 5 columns to the graph,
738 * but leave at least 10 columns for the name.
740 if (width < name_width + 15) {
741 if (name_width <= 25)
742 width = name_width + 15;
743 else
744 name_width = width - 15;
747 /* Find the longest filename and max number of changes */
748 reset = diff_get_color(options->color_diff, DIFF_RESET);
749 set = diff_get_color(options->color_diff, DIFF_PLAIN);
750 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
751 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
753 for (i = 0; i < data->nr; i++) {
754 struct diffstat_file *file = data->files[i];
755 int change = file->added + file->deleted;
757 if (!file->is_renamed) { /* renames are already quoted by pprint_rename */
758 len = quote_c_style(file->name, NULL, NULL, 0);
759 if (len) {
760 char *qname = xmalloc(len + 1);
761 quote_c_style(file->name, qname, NULL, 0);
762 free(file->name);
763 file->name = qname;
767 len = strlen(file->name);
768 if (max_len < len)
769 max_len = len;
771 if (file->is_binary || file->is_unmerged)
772 continue;
773 if (max_change < change)
774 max_change = change;
777 /* Compute the width of the graph part;
778 * 10 is for one blank at the beginning of the line plus
779 * " | count " between the name and the graph.
781 * From here on, name_width is the width of the name area,
782 * and width is the width of the graph area.
784 name_width = (name_width < max_len) ? name_width : max_len;
785 if (width < (name_width + 10) + max_change)
786 width = width - (name_width + 10);
787 else
788 width = max_change;
790 for (i = 0; i < data->nr; i++) {
791 const char *prefix = "";
792 char *name = data->files[i]->name;
793 int added = data->files[i]->added;
794 int deleted = data->files[i]->deleted;
795 int name_len;
798 * "scale" the filename
800 len = name_width;
801 name_len = strlen(name);
802 if (name_width < name_len) {
803 char *slash;
804 prefix = "...";
805 len -= 3;
806 name += name_len - len;
807 slash = strchr(name, '/');
808 if (slash)
809 name = slash;
812 if (data->files[i]->is_binary) {
813 show_name(prefix, name, len, reset, set);
814 printf(" Bin\n");
815 goto free_diffstat_file;
817 else if (data->files[i]->is_unmerged) {
818 show_name(prefix, name, len, reset, set);
819 printf(" Unmerged\n");
820 goto free_diffstat_file;
822 else if (!data->files[i]->is_renamed &&
823 (added + deleted == 0)) {
824 total_files--;
825 goto free_diffstat_file;
829 * scale the add/delete
831 add = added;
832 del = deleted;
833 total = add + del;
834 adds += add;
835 dels += del;
837 if (width <= max_change) {
838 add = scale_linear(add, width, max_change);
839 del = scale_linear(del, width, max_change);
840 total = add + del;
842 show_name(prefix, name, len, reset, set);
843 printf("%5d ", added + deleted);
844 show_graph('+', add, add_c, reset);
845 show_graph('-', del, del_c, reset);
846 putchar('\n');
847 free_diffstat_file:
848 free(data->files[i]->name);
849 free(data->files[i]);
851 free(data->files);
852 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
853 set, total_files, adds, dels, reset);
856 static void show_shortstats(struct diffstat_t* data)
858 int i, adds = 0, dels = 0, total_files = data->nr;
860 if (data->nr == 0)
861 return;
863 for (i = 0; i < data->nr; i++) {
864 if (!data->files[i]->is_binary &&
865 !data->files[i]->is_unmerged) {
866 int added = data->files[i]->added;
867 int deleted= data->files[i]->deleted;
868 if (!data->files[i]->is_renamed &&
869 (added + deleted == 0)) {
870 total_files--;
871 } else {
872 adds += added;
873 dels += deleted;
876 free(data->files[i]->name);
877 free(data->files[i]);
879 free(data->files);
881 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
882 total_files, adds, dels);
885 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
887 int i;
889 for (i = 0; i < data->nr; i++) {
890 struct diffstat_file *file = data->files[i];
892 if (file->is_binary)
893 printf("-\t-\t");
894 else
895 printf("%d\t%d\t", file->added, file->deleted);
896 if (options->line_termination && !file->is_renamed &&
897 quote_c_style(file->name, NULL, NULL, 0))
898 quote_c_style(file->name, NULL, stdout, 0);
899 else
900 fputs(file->name, stdout);
901 putchar(options->line_termination);
905 struct checkdiff_t {
906 struct xdiff_emit_state xm;
907 const char *filename;
908 int lineno, color_diff;
911 static void checkdiff_consume(void *priv, char *line, unsigned long len)
913 struct checkdiff_t *data = priv;
914 const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
915 const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
916 const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
918 if (line[0] == '+') {
919 int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
921 /* check space before tab */
922 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
923 if (line[i] == ' ')
924 spaces++;
925 if (line[i - 1] == '\t' && spaces)
926 space_before_tab = 1;
928 /* check white space at line end */
929 if (line[len - 1] == '\n')
930 len--;
931 if (isspace(line[len - 1]))
932 white_space_at_end = 1;
934 if (space_before_tab || white_space_at_end) {
935 printf("%s:%d: %s", data->filename, data->lineno, ws);
936 if (space_before_tab) {
937 printf("space before tab");
938 if (white_space_at_end)
939 putchar(',');
941 if (white_space_at_end)
942 printf("white space at end");
943 printf(":%s ", reset);
944 emit_line_with_ws(1, set, reset, ws, line, len);
947 data->lineno++;
948 } else if (line[0] == ' ')
949 data->lineno++;
950 else if (line[0] == '@') {
951 char *plus = strchr(line, '+');
952 if (plus)
953 data->lineno = strtol(plus, NULL, 10);
954 else
955 die("invalid diff");
959 static unsigned char *deflate_it(char *data,
960 unsigned long size,
961 unsigned long *result_size)
963 int bound;
964 unsigned char *deflated;
965 z_stream stream;
967 memset(&stream, 0, sizeof(stream));
968 deflateInit(&stream, zlib_compression_level);
969 bound = deflateBound(&stream, size);
970 deflated = xmalloc(bound);
971 stream.next_out = deflated;
972 stream.avail_out = bound;
974 stream.next_in = (unsigned char *)data;
975 stream.avail_in = size;
976 while (deflate(&stream, Z_FINISH) == Z_OK)
977 ; /* nothing */
978 deflateEnd(&stream);
979 *result_size = stream.total_out;
980 return deflated;
983 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
985 void *cp;
986 void *delta;
987 void *deflated;
988 void *data;
989 unsigned long orig_size;
990 unsigned long delta_size;
991 unsigned long deflate_size;
992 unsigned long data_size;
994 /* We could do deflated delta, or we could do just deflated two,
995 * whichever is smaller.
997 delta = NULL;
998 deflated = deflate_it(two->ptr, two->size, &deflate_size);
999 if (one->size && two->size) {
1000 delta = diff_delta(one->ptr, one->size,
1001 two->ptr, two->size,
1002 &delta_size, deflate_size);
1003 if (delta) {
1004 void *to_free = delta;
1005 orig_size = delta_size;
1006 delta = deflate_it(delta, delta_size, &delta_size);
1007 free(to_free);
1011 if (delta && delta_size < deflate_size) {
1012 printf("delta %lu\n", orig_size);
1013 free(deflated);
1014 data = delta;
1015 data_size = delta_size;
1017 else {
1018 printf("literal %lu\n", two->size);
1019 free(delta);
1020 data = deflated;
1021 data_size = deflate_size;
1024 /* emit data encoded in base85 */
1025 cp = data;
1026 while (data_size) {
1027 int bytes = (52 < data_size) ? 52 : data_size;
1028 char line[70];
1029 data_size -= bytes;
1030 if (bytes <= 26)
1031 line[0] = bytes + 'A' - 1;
1032 else
1033 line[0] = bytes - 26 + 'a' - 1;
1034 encode_85(line + 1, cp, bytes);
1035 cp = (char *) cp + bytes;
1036 puts(line);
1038 printf("\n");
1039 free(data);
1042 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1044 printf("GIT binary patch\n");
1045 emit_binary_diff_body(one, two);
1046 emit_binary_diff_body(two, one);
1049 #define FIRST_FEW_BYTES 8000
1050 static int mmfile_is_binary(mmfile_t *mf)
1052 long sz = mf->size;
1053 if (FIRST_FEW_BYTES < sz)
1054 sz = FIRST_FEW_BYTES;
1055 return !!memchr(mf->ptr, 0, sz);
1058 static void builtin_diff(const char *name_a,
1059 const char *name_b,
1060 struct diff_filespec *one,
1061 struct diff_filespec *two,
1062 const char *xfrm_msg,
1063 struct diff_options *o,
1064 int complete_rewrite)
1066 mmfile_t mf1, mf2;
1067 const char *lbl[2];
1068 char *a_one, *b_two;
1069 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1070 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1072 a_one = quote_two("a/", name_a + (*name_a == '/'));
1073 b_two = quote_two("b/", name_b + (*name_b == '/'));
1074 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1075 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1076 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1077 if (lbl[0][0] == '/') {
1078 /* /dev/null */
1079 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1080 if (xfrm_msg && xfrm_msg[0])
1081 printf("%s%s%s\n", set, xfrm_msg, reset);
1083 else if (lbl[1][0] == '/') {
1084 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1085 if (xfrm_msg && xfrm_msg[0])
1086 printf("%s%s%s\n", set, xfrm_msg, reset);
1088 else {
1089 if (one->mode != two->mode) {
1090 printf("%sold mode %06o%s\n", set, one->mode, reset);
1091 printf("%snew mode %06o%s\n", set, two->mode, reset);
1093 if (xfrm_msg && xfrm_msg[0])
1094 printf("%s%s%s\n", set, xfrm_msg, reset);
1096 * we do not run diff between different kind
1097 * of objects.
1099 if ((one->mode ^ two->mode) & S_IFMT)
1100 goto free_ab_and_return;
1101 if (complete_rewrite) {
1102 emit_rewrite_diff(name_a, name_b, one, two,
1103 o->color_diff);
1104 o->found_changes = 1;
1105 goto free_ab_and_return;
1109 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1110 die("unable to read files to diff");
1112 if (!o->text && (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))) {
1113 /* Quite common confusing case */
1114 if (mf1.size == mf2.size &&
1115 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1116 goto free_ab_and_return;
1117 if (o->binary)
1118 emit_binary_diff(&mf1, &mf2);
1119 else
1120 printf("Binary files %s and %s differ\n",
1121 lbl[0], lbl[1]);
1122 o->found_changes = 1;
1124 else {
1125 /* Crazy xdl interfaces.. */
1126 const char *diffopts = getenv("GIT_DIFF_OPTS");
1127 xpparam_t xpp;
1128 xdemitconf_t xecfg;
1129 xdemitcb_t ecb;
1130 struct emit_callback ecbdata;
1132 memset(&ecbdata, 0, sizeof(ecbdata));
1133 ecbdata.label_path = lbl;
1134 ecbdata.color_diff = o->color_diff;
1135 ecbdata.found_changesp = &o->found_changes;
1136 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1137 xecfg.ctxlen = o->context;
1138 xecfg.flags = XDL_EMIT_FUNCNAMES;
1139 if (!diffopts)
1141 else if (!prefixcmp(diffopts, "--unified="))
1142 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1143 else if (!prefixcmp(diffopts, "-u"))
1144 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1145 ecb.outf = xdiff_outf;
1146 ecb.priv = &ecbdata;
1147 ecbdata.xm.consume = fn_out_consume;
1148 if (o->color_diff_words)
1149 ecbdata.diff_words =
1150 xcalloc(1, sizeof(struct diff_words_data));
1151 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1152 if (o->color_diff_words)
1153 free_diff_words_data(&ecbdata);
1156 free_ab_and_return:
1157 free(a_one);
1158 free(b_two);
1159 return;
1162 static void builtin_diffstat(const char *name_a, const char *name_b,
1163 struct diff_filespec *one,
1164 struct diff_filespec *two,
1165 struct diffstat_t *diffstat,
1166 struct diff_options *o,
1167 int complete_rewrite)
1169 mmfile_t mf1, mf2;
1170 struct diffstat_file *data;
1172 data = diffstat_add(diffstat, name_a, name_b);
1174 if (!one || !two) {
1175 data->is_unmerged = 1;
1176 return;
1178 if (complete_rewrite) {
1179 diff_populate_filespec(one, 0);
1180 diff_populate_filespec(two, 0);
1181 data->deleted = count_lines(one->data, one->size);
1182 data->added = count_lines(two->data, two->size);
1183 return;
1185 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1186 die("unable to read files to diff");
1188 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
1189 data->is_binary = 1;
1190 else {
1191 /* Crazy xdl interfaces.. */
1192 xpparam_t xpp;
1193 xdemitconf_t xecfg;
1194 xdemitcb_t ecb;
1196 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1197 xecfg.ctxlen = 0;
1198 xecfg.flags = 0;
1199 ecb.outf = xdiff_outf;
1200 ecb.priv = diffstat;
1201 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1205 static void builtin_checkdiff(const char *name_a, const char *name_b,
1206 struct diff_filespec *one,
1207 struct diff_filespec *two, struct diff_options *o)
1209 mmfile_t mf1, mf2;
1210 struct checkdiff_t data;
1212 if (!two)
1213 return;
1215 memset(&data, 0, sizeof(data));
1216 data.xm.consume = checkdiff_consume;
1217 data.filename = name_b ? name_b : name_a;
1218 data.lineno = 0;
1219 data.color_diff = o->color_diff;
1221 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1222 die("unable to read files to diff");
1224 if (mmfile_is_binary(&mf2))
1225 return;
1226 else {
1227 /* Crazy xdl interfaces.. */
1228 xpparam_t xpp;
1229 xdemitconf_t xecfg;
1230 xdemitcb_t ecb;
1232 xpp.flags = XDF_NEED_MINIMAL;
1233 xecfg.ctxlen = 0;
1234 xecfg.flags = 0;
1235 ecb.outf = xdiff_outf;
1236 ecb.priv = &data;
1237 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1241 struct diff_filespec *alloc_filespec(const char *path)
1243 int namelen = strlen(path);
1244 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1246 memset(spec, 0, sizeof(*spec));
1247 spec->path = (char *)(spec + 1);
1248 memcpy(spec->path, path, namelen+1);
1249 return spec;
1252 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1253 unsigned short mode)
1255 if (mode) {
1256 spec->mode = canon_mode(mode);
1257 hashcpy(spec->sha1, sha1);
1258 spec->sha1_valid = !is_null_sha1(sha1);
1263 * Given a name and sha1 pair, if the dircache tells us the file in
1264 * the work tree has that object contents, return true, so that
1265 * prepare_temp_file() does not have to inflate and extract.
1267 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1269 struct cache_entry *ce;
1270 struct stat st;
1271 int pos, len;
1273 /* We do not read the cache ourselves here, because the
1274 * benchmark with my previous version that always reads cache
1275 * shows that it makes things worse for diff-tree comparing
1276 * two linux-2.6 kernel trees in an already checked out work
1277 * tree. This is because most diff-tree comparisons deal with
1278 * only a small number of files, while reading the cache is
1279 * expensive for a large project, and its cost outweighs the
1280 * savings we get by not inflating the object to a temporary
1281 * file. Practically, this code only helps when we are used
1282 * by diff-cache --cached, which does read the cache before
1283 * calling us.
1285 if (!active_cache)
1286 return 0;
1288 /* We want to avoid the working directory if our caller
1289 * doesn't need the data in a normal file, this system
1290 * is rather slow with its stat/open/mmap/close syscalls,
1291 * and the object is contained in a pack file. The pack
1292 * is probably already open and will be faster to obtain
1293 * the data through than the working directory. Loose
1294 * objects however would tend to be slower as they need
1295 * to be individually opened and inflated.
1297 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1298 return 0;
1300 len = strlen(name);
1301 pos = cache_name_pos(name, len);
1302 if (pos < 0)
1303 return 0;
1304 ce = active_cache[pos];
1305 if ((lstat(name, &st) < 0) ||
1306 !S_ISREG(st.st_mode) || /* careful! */
1307 ce_match_stat(ce, &st, 0) ||
1308 hashcmp(sha1, ce->sha1))
1309 return 0;
1310 /* we return 1 only when we can stat, it is a regular file,
1311 * stat information matches, and sha1 recorded in the cache
1312 * matches. I.e. we know the file in the work tree really is
1313 * the same as the <name, sha1> pair.
1315 return 1;
1318 static struct sha1_size_cache {
1319 unsigned char sha1[20];
1320 unsigned long size;
1321 } **sha1_size_cache;
1322 static int sha1_size_cache_nr, sha1_size_cache_alloc;
1324 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
1325 int find_only,
1326 unsigned long size)
1328 int first, last;
1329 struct sha1_size_cache *e;
1331 first = 0;
1332 last = sha1_size_cache_nr;
1333 while (last > first) {
1334 int cmp, next = (last + first) >> 1;
1335 e = sha1_size_cache[next];
1336 cmp = hashcmp(e->sha1, sha1);
1337 if (!cmp)
1338 return e;
1339 if (cmp < 0) {
1340 last = next;
1341 continue;
1343 first = next+1;
1345 /* not found */
1346 if (find_only)
1347 return NULL;
1348 /* insert to make it at "first" */
1349 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
1350 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
1351 sha1_size_cache = xrealloc(sha1_size_cache,
1352 sha1_size_cache_alloc *
1353 sizeof(*sha1_size_cache));
1355 sha1_size_cache_nr++;
1356 if (first < sha1_size_cache_nr)
1357 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
1358 (sha1_size_cache_nr - first - 1) *
1359 sizeof(*sha1_size_cache));
1360 e = xmalloc(sizeof(struct sha1_size_cache));
1361 sha1_size_cache[first] = e;
1362 hashcpy(e->sha1, sha1);
1363 e->size = size;
1364 return e;
1368 * While doing rename detection and pickaxe operation, we may need to
1369 * grab the data for the blob (or file) for our own in-core comparison.
1370 * diff_filespec has data and size fields for this purpose.
1372 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1374 int err = 0;
1375 if (!DIFF_FILE_VALID(s))
1376 die("internal error: asking to populate invalid file.");
1377 if (S_ISDIR(s->mode))
1378 return -1;
1380 if (!use_size_cache)
1381 size_only = 0;
1383 if (s->data)
1384 return err;
1385 if (!s->sha1_valid ||
1386 reuse_worktree_file(s->path, s->sha1, 0)) {
1387 struct stat st;
1388 int fd;
1389 char *buf;
1390 unsigned long size;
1392 if (lstat(s->path, &st) < 0) {
1393 if (errno == ENOENT) {
1394 err_empty:
1395 err = -1;
1396 empty:
1397 s->data = (char *)"";
1398 s->size = 0;
1399 return err;
1402 s->size = st.st_size;
1403 if (!s->size)
1404 goto empty;
1405 if (size_only)
1406 return 0;
1407 if (S_ISLNK(st.st_mode)) {
1408 int ret;
1409 s->data = xmalloc(s->size);
1410 s->should_free = 1;
1411 ret = readlink(s->path, s->data, s->size);
1412 if (ret < 0) {
1413 free(s->data);
1414 goto err_empty;
1416 return 0;
1418 fd = open(s->path, O_RDONLY);
1419 if (fd < 0)
1420 goto err_empty;
1421 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1422 close(fd);
1423 s->should_munmap = 1;
1426 * Convert from working tree format to canonical git format
1428 buf = s->data;
1429 size = s->size;
1430 if (convert_to_git(s->path, &buf, &size)) {
1431 munmap(s->data, s->size);
1432 s->should_munmap = 0;
1433 s->data = buf;
1434 s->size = size;
1435 s->should_free = 1;
1438 else {
1439 enum object_type type;
1440 struct sha1_size_cache *e;
1442 if (size_only) {
1443 e = locate_size_cache(s->sha1, 1, 0);
1444 if (e) {
1445 s->size = e->size;
1446 return 0;
1448 type = sha1_object_info(s->sha1, &s->size);
1449 if (type < 0)
1450 locate_size_cache(s->sha1, 0, s->size);
1452 else {
1453 s->data = read_sha1_file(s->sha1, &type, &s->size);
1454 s->should_free = 1;
1457 return 0;
1460 void diff_free_filespec_data(struct diff_filespec *s)
1462 if (s->should_free)
1463 free(s->data);
1464 else if (s->should_munmap)
1465 munmap(s->data, s->size);
1466 s->should_free = s->should_munmap = 0;
1467 s->data = NULL;
1468 free(s->cnt_data);
1469 s->cnt_data = NULL;
1472 static void prep_temp_blob(struct diff_tempfile *temp,
1473 void *blob,
1474 unsigned long size,
1475 const unsigned char *sha1,
1476 int mode)
1478 int fd;
1480 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1481 if (fd < 0)
1482 die("unable to create temp-file");
1483 if (write_in_full(fd, blob, size) != size)
1484 die("unable to write temp-file");
1485 close(fd);
1486 temp->name = temp->tmp_path;
1487 strcpy(temp->hex, sha1_to_hex(sha1));
1488 temp->hex[40] = 0;
1489 sprintf(temp->mode, "%06o", mode);
1492 static void prepare_temp_file(const char *name,
1493 struct diff_tempfile *temp,
1494 struct diff_filespec *one)
1496 if (!DIFF_FILE_VALID(one)) {
1497 not_a_valid_file:
1498 /* A '-' entry produces this for file-2, and
1499 * a '+' entry produces this for file-1.
1501 temp->name = "/dev/null";
1502 strcpy(temp->hex, ".");
1503 strcpy(temp->mode, ".");
1504 return;
1507 if (!one->sha1_valid ||
1508 reuse_worktree_file(name, one->sha1, 1)) {
1509 struct stat st;
1510 if (lstat(name, &st) < 0) {
1511 if (errno == ENOENT)
1512 goto not_a_valid_file;
1513 die("stat(%s): %s", name, strerror(errno));
1515 if (S_ISLNK(st.st_mode)) {
1516 int ret;
1517 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1518 if (sizeof(buf) <= st.st_size)
1519 die("symlink too long: %s", name);
1520 ret = readlink(name, buf, st.st_size);
1521 if (ret < 0)
1522 die("readlink(%s)", name);
1523 prep_temp_blob(temp, buf, st.st_size,
1524 (one->sha1_valid ?
1525 one->sha1 : null_sha1),
1526 (one->sha1_valid ?
1527 one->mode : S_IFLNK));
1529 else {
1530 /* we can borrow from the file in the work tree */
1531 temp->name = name;
1532 if (!one->sha1_valid)
1533 strcpy(temp->hex, sha1_to_hex(null_sha1));
1534 else
1535 strcpy(temp->hex, sha1_to_hex(one->sha1));
1536 /* Even though we may sometimes borrow the
1537 * contents from the work tree, we always want
1538 * one->mode. mode is trustworthy even when
1539 * !(one->sha1_valid), as long as
1540 * DIFF_FILE_VALID(one).
1542 sprintf(temp->mode, "%06o", one->mode);
1544 return;
1546 else {
1547 if (diff_populate_filespec(one, 0))
1548 die("cannot read data blob for %s", one->path);
1549 prep_temp_blob(temp, one->data, one->size,
1550 one->sha1, one->mode);
1554 static void remove_tempfile(void)
1556 int i;
1558 for (i = 0; i < 2; i++)
1559 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1560 unlink(diff_temp[i].name);
1561 diff_temp[i].name = NULL;
1565 static void remove_tempfile_on_signal(int signo)
1567 remove_tempfile();
1568 signal(SIGINT, SIG_DFL);
1569 raise(signo);
1572 static int spawn_prog(const char *pgm, const char **arg)
1574 pid_t pid;
1575 int status;
1577 fflush(NULL);
1578 pid = fork();
1579 if (pid < 0)
1580 die("unable to fork");
1581 if (!pid) {
1582 execvp(pgm, (char *const*) arg);
1583 exit(255);
1586 while (waitpid(pid, &status, 0) < 0) {
1587 if (errno == EINTR)
1588 continue;
1589 return -1;
1592 /* Earlier we did not check the exit status because
1593 * diff exits non-zero if files are different, and
1594 * we are not interested in knowing that. It was a
1595 * mistake which made it harder to quit a diff-*
1596 * session that uses the git-apply-patch-script as
1597 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1598 * should also exit non-zero only when it wants to
1599 * abort the entire diff-* session.
1601 if (WIFEXITED(status) && !WEXITSTATUS(status))
1602 return 0;
1603 return -1;
1606 /* An external diff command takes:
1608 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1609 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1612 static void run_external_diff(const char *pgm,
1613 const char *name,
1614 const char *other,
1615 struct diff_filespec *one,
1616 struct diff_filespec *two,
1617 const char *xfrm_msg,
1618 int complete_rewrite)
1620 const char *spawn_arg[10];
1621 struct diff_tempfile *temp = diff_temp;
1622 int retval;
1623 static int atexit_asked = 0;
1624 const char *othername;
1625 const char **arg = &spawn_arg[0];
1627 othername = (other? other : name);
1628 if (one && two) {
1629 prepare_temp_file(name, &temp[0], one);
1630 prepare_temp_file(othername, &temp[1], two);
1631 if (! atexit_asked &&
1632 (temp[0].name == temp[0].tmp_path ||
1633 temp[1].name == temp[1].tmp_path)) {
1634 atexit_asked = 1;
1635 atexit(remove_tempfile);
1637 signal(SIGINT, remove_tempfile_on_signal);
1640 if (one && two) {
1641 *arg++ = pgm;
1642 *arg++ = name;
1643 *arg++ = temp[0].name;
1644 *arg++ = temp[0].hex;
1645 *arg++ = temp[0].mode;
1646 *arg++ = temp[1].name;
1647 *arg++ = temp[1].hex;
1648 *arg++ = temp[1].mode;
1649 if (other) {
1650 *arg++ = other;
1651 *arg++ = xfrm_msg;
1653 } else {
1654 *arg++ = pgm;
1655 *arg++ = name;
1657 *arg = NULL;
1658 retval = spawn_prog(pgm, spawn_arg);
1659 remove_tempfile();
1660 if (retval) {
1661 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1662 exit(1);
1666 static void run_diff_cmd(const char *pgm,
1667 const char *name,
1668 const char *other,
1669 struct diff_filespec *one,
1670 struct diff_filespec *two,
1671 const char *xfrm_msg,
1672 struct diff_options *o,
1673 int complete_rewrite)
1675 if (pgm) {
1676 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1677 complete_rewrite);
1678 return;
1680 if (one && two)
1681 builtin_diff(name, other ? other : name,
1682 one, two, xfrm_msg, o, complete_rewrite);
1683 else
1684 printf("* Unmerged path %s\n", name);
1687 static void diff_fill_sha1_info(struct diff_filespec *one)
1689 if (DIFF_FILE_VALID(one)) {
1690 if (!one->sha1_valid) {
1691 struct stat st;
1692 if (lstat(one->path, &st) < 0)
1693 die("stat %s", one->path);
1694 if (index_path(one->sha1, one->path, &st, 0))
1695 die("cannot hash %s\n", one->path);
1698 else
1699 hashclr(one->sha1);
1702 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1704 const char *pgm = external_diff();
1705 char msg[PATH_MAX*2+300], *xfrm_msg;
1706 struct diff_filespec *one;
1707 struct diff_filespec *two;
1708 const char *name;
1709 const char *other;
1710 char *name_munged, *other_munged;
1711 int complete_rewrite = 0;
1712 int len;
1714 if (DIFF_PAIR_UNMERGED(p)) {
1715 /* unmerged */
1716 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1717 return;
1720 name = p->one->path;
1721 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1722 name_munged = quote_one(name);
1723 other_munged = quote_one(other);
1724 one = p->one; two = p->two;
1726 diff_fill_sha1_info(one);
1727 diff_fill_sha1_info(two);
1729 len = 0;
1730 switch (p->status) {
1731 case DIFF_STATUS_COPIED:
1732 len += snprintf(msg + len, sizeof(msg) - len,
1733 "similarity index %d%%\n"
1734 "copy from %s\n"
1735 "copy to %s\n",
1736 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1737 name_munged, other_munged);
1738 break;
1739 case DIFF_STATUS_RENAMED:
1740 len += snprintf(msg + len, sizeof(msg) - len,
1741 "similarity index %d%%\n"
1742 "rename from %s\n"
1743 "rename to %s\n",
1744 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1745 name_munged, other_munged);
1746 break;
1747 case DIFF_STATUS_MODIFIED:
1748 if (p->score) {
1749 len += snprintf(msg + len, sizeof(msg) - len,
1750 "dissimilarity index %d%%\n",
1751 (int)(0.5 + p->score *
1752 100.0/MAX_SCORE));
1753 complete_rewrite = 1;
1754 break;
1756 /* fallthru */
1757 default:
1758 /* nothing */
1762 if (hashcmp(one->sha1, two->sha1)) {
1763 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1765 if (o->binary) {
1766 mmfile_t mf;
1767 if ((!fill_mmfile(&mf, one) && mmfile_is_binary(&mf)) ||
1768 (!fill_mmfile(&mf, two) && mmfile_is_binary(&mf)))
1769 abbrev = 40;
1771 len += snprintf(msg + len, sizeof(msg) - len,
1772 "index %.*s..%.*s",
1773 abbrev, sha1_to_hex(one->sha1),
1774 abbrev, sha1_to_hex(two->sha1));
1775 if (one->mode == two->mode)
1776 len += snprintf(msg + len, sizeof(msg) - len,
1777 " %06o", one->mode);
1778 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1781 if (len)
1782 msg[--len] = 0;
1783 xfrm_msg = len ? msg : NULL;
1785 if (!pgm &&
1786 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1787 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1788 /* a filepair that changes between file and symlink
1789 * needs to be split into deletion and creation.
1791 struct diff_filespec *null = alloc_filespec(two->path);
1792 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1793 free(null);
1794 null = alloc_filespec(one->path);
1795 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1796 free(null);
1798 else
1799 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1800 complete_rewrite);
1802 free(name_munged);
1803 free(other_munged);
1806 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1807 struct diffstat_t *diffstat)
1809 const char *name;
1810 const char *other;
1811 int complete_rewrite = 0;
1813 if (DIFF_PAIR_UNMERGED(p)) {
1814 /* unmerged */
1815 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1816 return;
1819 name = p->one->path;
1820 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1822 diff_fill_sha1_info(p->one);
1823 diff_fill_sha1_info(p->two);
1825 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1826 complete_rewrite = 1;
1827 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1830 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1832 const char *name;
1833 const char *other;
1835 if (DIFF_PAIR_UNMERGED(p)) {
1836 /* unmerged */
1837 return;
1840 name = p->one->path;
1841 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1843 diff_fill_sha1_info(p->one);
1844 diff_fill_sha1_info(p->two);
1846 builtin_checkdiff(name, other, p->one, p->two, o);
1849 void diff_setup(struct diff_options *options)
1851 memset(options, 0, sizeof(*options));
1852 options->line_termination = '\n';
1853 options->break_opt = -1;
1854 options->rename_limit = -1;
1855 options->context = 3;
1856 options->msg_sep = "";
1858 options->change = diff_change;
1859 options->add_remove = diff_addremove;
1860 options->color_diff = diff_use_color_default;
1861 options->detect_rename = diff_detect_rename_default;
1864 int diff_setup_done(struct diff_options *options)
1866 int count = 0;
1868 if (options->output_format & DIFF_FORMAT_NAME)
1869 count++;
1870 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
1871 count++;
1872 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
1873 count++;
1874 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
1875 count++;
1876 if (count > 1)
1877 die("--name-only, --name-status, --check and -s are mutually exclusive");
1879 if (options->find_copies_harder)
1880 options->detect_rename = DIFF_DETECT_COPY;
1882 if (options->output_format & (DIFF_FORMAT_NAME |
1883 DIFF_FORMAT_NAME_STATUS |
1884 DIFF_FORMAT_CHECKDIFF |
1885 DIFF_FORMAT_NO_OUTPUT))
1886 options->output_format &= ~(DIFF_FORMAT_RAW |
1887 DIFF_FORMAT_NUMSTAT |
1888 DIFF_FORMAT_DIFFSTAT |
1889 DIFF_FORMAT_SHORTSTAT |
1890 DIFF_FORMAT_SUMMARY |
1891 DIFF_FORMAT_PATCH);
1894 * These cases always need recursive; we do not drop caller-supplied
1895 * recursive bits for other formats here.
1897 if (options->output_format & (DIFF_FORMAT_PATCH |
1898 DIFF_FORMAT_NUMSTAT |
1899 DIFF_FORMAT_DIFFSTAT |
1900 DIFF_FORMAT_SHORTSTAT |
1901 DIFF_FORMAT_SUMMARY |
1902 DIFF_FORMAT_CHECKDIFF))
1903 options->recursive = 1;
1905 * Also pickaxe would not work very well if you do not say recursive
1907 if (options->pickaxe)
1908 options->recursive = 1;
1910 if (options->detect_rename && options->rename_limit < 0)
1911 options->rename_limit = diff_rename_limit_default;
1912 if (options->setup & DIFF_SETUP_USE_CACHE) {
1913 if (!active_cache)
1914 /* read-cache does not die even when it fails
1915 * so it is safe for us to do this here. Also
1916 * it does not smudge active_cache or active_nr
1917 * when it fails, so we do not have to worry about
1918 * cleaning it up ourselves either.
1920 read_cache();
1922 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1923 use_size_cache = 1;
1924 if (options->abbrev <= 0 || 40 < options->abbrev)
1925 options->abbrev = 40; /* full */
1927 return 0;
1930 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1932 char c, *eq;
1933 int len;
1935 if (*arg != '-')
1936 return 0;
1937 c = *++arg;
1938 if (!c)
1939 return 0;
1940 if (c == arg_short) {
1941 c = *++arg;
1942 if (!c)
1943 return 1;
1944 if (val && isdigit(c)) {
1945 char *end;
1946 int n = strtoul(arg, &end, 10);
1947 if (*end)
1948 return 0;
1949 *val = n;
1950 return 1;
1952 return 0;
1954 if (c != '-')
1955 return 0;
1956 arg++;
1957 eq = strchr(arg, '=');
1958 if (eq)
1959 len = eq - arg;
1960 else
1961 len = strlen(arg);
1962 if (!len || strncmp(arg, arg_long, len))
1963 return 0;
1964 if (eq) {
1965 int n;
1966 char *end;
1967 if (!isdigit(*++eq))
1968 return 0;
1969 n = strtoul(eq, &end, 10);
1970 if (*end)
1971 return 0;
1972 *val = n;
1974 return 1;
1977 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1979 const char *arg = av[0];
1980 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1981 options->output_format |= DIFF_FORMAT_PATCH;
1982 else if (opt_arg(arg, 'U', "unified", &options->context))
1983 options->output_format |= DIFF_FORMAT_PATCH;
1984 else if (!strcmp(arg, "--raw"))
1985 options->output_format |= DIFF_FORMAT_RAW;
1986 else if (!strcmp(arg, "--patch-with-raw")) {
1987 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
1989 else if (!strcmp(arg, "--numstat")) {
1990 options->output_format |= DIFF_FORMAT_NUMSTAT;
1992 else if (!strcmp(arg, "--shortstat")) {
1993 options->output_format |= DIFF_FORMAT_SHORTSTAT;
1995 else if (!prefixcmp(arg, "--stat")) {
1996 char *end;
1997 int width = options->stat_width;
1998 int name_width = options->stat_name_width;
1999 arg += 6;
2000 end = (char *)arg;
2002 switch (*arg) {
2003 case '-':
2004 if (!prefixcmp(arg, "-width="))
2005 width = strtoul(arg + 7, &end, 10);
2006 else if (!prefixcmp(arg, "-name-width="))
2007 name_width = strtoul(arg + 12, &end, 10);
2008 break;
2009 case '=':
2010 width = strtoul(arg+1, &end, 10);
2011 if (*end == ',')
2012 name_width = strtoul(end+1, &end, 10);
2015 /* Important! This checks all the error cases! */
2016 if (*end)
2017 return 0;
2018 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2019 options->stat_name_width = name_width;
2020 options->stat_width = width;
2022 else if (!strcmp(arg, "--check"))
2023 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2024 else if (!strcmp(arg, "--summary"))
2025 options->output_format |= DIFF_FORMAT_SUMMARY;
2026 else if (!strcmp(arg, "--patch-with-stat")) {
2027 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2029 else if (!strcmp(arg, "-z"))
2030 options->line_termination = 0;
2031 else if (!prefixcmp(arg, "-l"))
2032 options->rename_limit = strtoul(arg+2, NULL, 10);
2033 else if (!strcmp(arg, "--full-index"))
2034 options->full_index = 1;
2035 else if (!strcmp(arg, "--binary")) {
2036 options->output_format |= DIFF_FORMAT_PATCH;
2037 options->binary = 1;
2039 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
2040 options->text = 1;
2042 else if (!strcmp(arg, "--name-only"))
2043 options->output_format |= DIFF_FORMAT_NAME;
2044 else if (!strcmp(arg, "--name-status"))
2045 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2046 else if (!strcmp(arg, "-R"))
2047 options->reverse_diff = 1;
2048 else if (!prefixcmp(arg, "-S"))
2049 options->pickaxe = arg + 2;
2050 else if (!strcmp(arg, "-s")) {
2051 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2053 else if (!prefixcmp(arg, "-O"))
2054 options->orderfile = arg + 2;
2055 else if (!prefixcmp(arg, "--diff-filter="))
2056 options->filter = arg + 14;
2057 else if (!strcmp(arg, "--pickaxe-all"))
2058 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2059 else if (!strcmp(arg, "--pickaxe-regex"))
2060 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2061 else if (!prefixcmp(arg, "-B")) {
2062 if ((options->break_opt =
2063 diff_scoreopt_parse(arg)) == -1)
2064 return -1;
2066 else if (!prefixcmp(arg, "-M")) {
2067 if ((options->rename_score =
2068 diff_scoreopt_parse(arg)) == -1)
2069 return -1;
2070 options->detect_rename = DIFF_DETECT_RENAME;
2072 else if (!prefixcmp(arg, "-C")) {
2073 if ((options->rename_score =
2074 diff_scoreopt_parse(arg)) == -1)
2075 return -1;
2076 options->detect_rename = DIFF_DETECT_COPY;
2078 else if (!strcmp(arg, "--find-copies-harder"))
2079 options->find_copies_harder = 1;
2080 else if (!strcmp(arg, "--abbrev"))
2081 options->abbrev = DEFAULT_ABBREV;
2082 else if (!prefixcmp(arg, "--abbrev=")) {
2083 options->abbrev = strtoul(arg + 9, NULL, 10);
2084 if (options->abbrev < MINIMUM_ABBREV)
2085 options->abbrev = MINIMUM_ABBREV;
2086 else if (40 < options->abbrev)
2087 options->abbrev = 40;
2089 else if (!strcmp(arg, "--color"))
2090 options->color_diff = 1;
2091 else if (!strcmp(arg, "--no-color"))
2092 options->color_diff = 0;
2093 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2094 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2095 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2096 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2097 else if (!strcmp(arg, "--ignore-space-at-eol"))
2098 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2099 else if (!strcmp(arg, "--color-words"))
2100 options->color_diff = options->color_diff_words = 1;
2101 else if (!strcmp(arg, "--no-renames"))
2102 options->detect_rename = 0;
2103 else
2104 return 0;
2105 return 1;
2108 static int parse_num(const char **cp_p)
2110 unsigned long num, scale;
2111 int ch, dot;
2112 const char *cp = *cp_p;
2114 num = 0;
2115 scale = 1;
2116 dot = 0;
2117 for(;;) {
2118 ch = *cp;
2119 if ( !dot && ch == '.' ) {
2120 scale = 1;
2121 dot = 1;
2122 } else if ( ch == '%' ) {
2123 scale = dot ? scale*100 : 100;
2124 cp++; /* % is always at the end */
2125 break;
2126 } else if ( ch >= '0' && ch <= '9' ) {
2127 if ( scale < 100000 ) {
2128 scale *= 10;
2129 num = (num*10) + (ch-'0');
2131 } else {
2132 break;
2134 cp++;
2136 *cp_p = cp;
2138 /* user says num divided by scale and we say internally that
2139 * is MAX_SCORE * num / scale.
2141 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
2144 int diff_scoreopt_parse(const char *opt)
2146 int opt1, opt2, cmd;
2148 if (*opt++ != '-')
2149 return -1;
2150 cmd = *opt++;
2151 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2152 return -1; /* that is not a -M, -C nor -B option */
2154 opt1 = parse_num(&opt);
2155 if (cmd != 'B')
2156 opt2 = 0;
2157 else {
2158 if (*opt == 0)
2159 opt2 = 0;
2160 else if (*opt != '/')
2161 return -1; /* we expect -B80/99 or -B80 */
2162 else {
2163 opt++;
2164 opt2 = parse_num(&opt);
2167 if (*opt != 0)
2168 return -1;
2169 return opt1 | (opt2 << 16);
2172 struct diff_queue_struct diff_queued_diff;
2174 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2176 if (queue->alloc <= queue->nr) {
2177 queue->alloc = alloc_nr(queue->alloc);
2178 queue->queue = xrealloc(queue->queue,
2179 sizeof(dp) * queue->alloc);
2181 queue->queue[queue->nr++] = dp;
2184 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2185 struct diff_filespec *one,
2186 struct diff_filespec *two)
2188 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2189 dp->one = one;
2190 dp->two = two;
2191 if (queue)
2192 diff_q(queue, dp);
2193 return dp;
2196 void diff_free_filepair(struct diff_filepair *p)
2198 diff_free_filespec_data(p->one);
2199 diff_free_filespec_data(p->two);
2200 free(p->one);
2201 free(p->two);
2202 free(p);
2205 /* This is different from find_unique_abbrev() in that
2206 * it stuffs the result with dots for alignment.
2208 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2210 int abblen;
2211 const char *abbrev;
2212 if (len == 40)
2213 return sha1_to_hex(sha1);
2215 abbrev = find_unique_abbrev(sha1, len);
2216 if (!abbrev)
2217 return sha1_to_hex(sha1);
2218 abblen = strlen(abbrev);
2219 if (abblen < 37) {
2220 static char hex[41];
2221 if (len < abblen && abblen <= len + 2)
2222 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2223 else
2224 sprintf(hex, "%s...", abbrev);
2225 return hex;
2227 return sha1_to_hex(sha1);
2230 static void diff_flush_raw(struct diff_filepair *p,
2231 struct diff_options *options)
2233 int two_paths;
2234 char status[10];
2235 int abbrev = options->abbrev;
2236 const char *path_one, *path_two;
2237 int inter_name_termination = '\t';
2238 int line_termination = options->line_termination;
2240 if (!line_termination)
2241 inter_name_termination = 0;
2243 path_one = p->one->path;
2244 path_two = p->two->path;
2245 if (line_termination) {
2246 path_one = quote_one(path_one);
2247 path_two = quote_one(path_two);
2250 if (p->score)
2251 sprintf(status, "%c%03d", p->status,
2252 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2253 else {
2254 status[0] = p->status;
2255 status[1] = 0;
2257 switch (p->status) {
2258 case DIFF_STATUS_COPIED:
2259 case DIFF_STATUS_RENAMED:
2260 two_paths = 1;
2261 break;
2262 case DIFF_STATUS_ADDED:
2263 case DIFF_STATUS_DELETED:
2264 two_paths = 0;
2265 break;
2266 default:
2267 two_paths = 0;
2268 break;
2270 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2271 printf(":%06o %06o %s ",
2272 p->one->mode, p->two->mode,
2273 diff_unique_abbrev(p->one->sha1, abbrev));
2274 printf("%s ",
2275 diff_unique_abbrev(p->two->sha1, abbrev));
2277 printf("%s%c%s", status, inter_name_termination, path_one);
2278 if (two_paths)
2279 printf("%c%s", inter_name_termination, path_two);
2280 putchar(line_termination);
2281 if (path_one != p->one->path)
2282 free((void*)path_one);
2283 if (path_two != p->two->path)
2284 free((void*)path_two);
2287 static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2289 char *path = p->two->path;
2291 if (opt->line_termination)
2292 path = quote_one(p->two->path);
2293 printf("%s%c", path, opt->line_termination);
2294 if (p->two->path != path)
2295 free(path);
2298 int diff_unmodified_pair(struct diff_filepair *p)
2300 /* This function is written stricter than necessary to support
2301 * the currently implemented transformers, but the idea is to
2302 * let transformers to produce diff_filepairs any way they want,
2303 * and filter and clean them up here before producing the output.
2305 struct diff_filespec *one, *two;
2307 if (DIFF_PAIR_UNMERGED(p))
2308 return 0; /* unmerged is interesting */
2310 one = p->one;
2311 two = p->two;
2313 /* deletion, addition, mode or type change
2314 * and rename are all interesting.
2316 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2317 DIFF_PAIR_MODE_CHANGED(p) ||
2318 strcmp(one->path, two->path))
2319 return 0;
2321 /* both are valid and point at the same path. that is, we are
2322 * dealing with a change.
2324 if (one->sha1_valid && two->sha1_valid &&
2325 !hashcmp(one->sha1, two->sha1))
2326 return 1; /* no change */
2327 if (!one->sha1_valid && !two->sha1_valid)
2328 return 1; /* both look at the same file on the filesystem. */
2329 return 0;
2332 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2334 if (diff_unmodified_pair(p))
2335 return;
2337 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2338 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2339 return; /* no tree diffs in patch format */
2341 run_diff(p, o);
2344 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2345 struct diffstat_t *diffstat)
2347 if (diff_unmodified_pair(p))
2348 return;
2350 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2351 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2352 return; /* no tree diffs in patch format */
2354 run_diffstat(p, o, diffstat);
2357 static void diff_flush_checkdiff(struct diff_filepair *p,
2358 struct diff_options *o)
2360 if (diff_unmodified_pair(p))
2361 return;
2363 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2364 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2365 return; /* no tree diffs in patch format */
2367 run_checkdiff(p, o);
2370 int diff_queue_is_empty(void)
2372 struct diff_queue_struct *q = &diff_queued_diff;
2373 int i;
2374 for (i = 0; i < q->nr; i++)
2375 if (!diff_unmodified_pair(q->queue[i]))
2376 return 0;
2377 return 1;
2380 #if DIFF_DEBUG
2381 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2383 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2384 x, one ? one : "",
2385 s->path,
2386 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2387 s->mode,
2388 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2389 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2390 x, one ? one : "",
2391 s->size, s->xfrm_flags);
2394 void diff_debug_filepair(const struct diff_filepair *p, int i)
2396 diff_debug_filespec(p->one, i, "one");
2397 diff_debug_filespec(p->two, i, "two");
2398 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2399 p->score, p->status ? p->status : '?',
2400 p->source_stays, p->broken_pair);
2403 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2405 int i;
2406 if (msg)
2407 fprintf(stderr, "%s\n", msg);
2408 fprintf(stderr, "q->nr = %d\n", q->nr);
2409 for (i = 0; i < q->nr; i++) {
2410 struct diff_filepair *p = q->queue[i];
2411 diff_debug_filepair(p, i);
2414 #endif
2416 static void diff_resolve_rename_copy(void)
2418 int i, j;
2419 struct diff_filepair *p, *pp;
2420 struct diff_queue_struct *q = &diff_queued_diff;
2422 diff_debug_queue("resolve-rename-copy", q);
2424 for (i = 0; i < q->nr; i++) {
2425 p = q->queue[i];
2426 p->status = 0; /* undecided */
2427 if (DIFF_PAIR_UNMERGED(p))
2428 p->status = DIFF_STATUS_UNMERGED;
2429 else if (!DIFF_FILE_VALID(p->one))
2430 p->status = DIFF_STATUS_ADDED;
2431 else if (!DIFF_FILE_VALID(p->two))
2432 p->status = DIFF_STATUS_DELETED;
2433 else if (DIFF_PAIR_TYPE_CHANGED(p))
2434 p->status = DIFF_STATUS_TYPE_CHANGED;
2436 /* from this point on, we are dealing with a pair
2437 * whose both sides are valid and of the same type, i.e.
2438 * either in-place edit or rename/copy edit.
2440 else if (DIFF_PAIR_RENAME(p)) {
2441 if (p->source_stays) {
2442 p->status = DIFF_STATUS_COPIED;
2443 continue;
2445 /* See if there is some other filepair that
2446 * copies from the same source as us. If so
2447 * we are a copy. Otherwise we are either a
2448 * copy if the path stays, or a rename if it
2449 * does not, but we already handled "stays" case.
2451 for (j = i + 1; j < q->nr; j++) {
2452 pp = q->queue[j];
2453 if (strcmp(pp->one->path, p->one->path))
2454 continue; /* not us */
2455 if (!DIFF_PAIR_RENAME(pp))
2456 continue; /* not a rename/copy */
2457 /* pp is a rename/copy from the same source */
2458 p->status = DIFF_STATUS_COPIED;
2459 break;
2461 if (!p->status)
2462 p->status = DIFF_STATUS_RENAMED;
2464 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2465 p->one->mode != p->two->mode ||
2466 is_null_sha1(p->one->sha1))
2467 p->status = DIFF_STATUS_MODIFIED;
2468 else {
2469 /* This is a "no-change" entry and should not
2470 * happen anymore, but prepare for broken callers.
2472 error("feeding unmodified %s to diffcore",
2473 p->one->path);
2474 p->status = DIFF_STATUS_UNKNOWN;
2477 diff_debug_queue("resolve-rename-copy done", q);
2480 static int check_pair_status(struct diff_filepair *p)
2482 switch (p->status) {
2483 case DIFF_STATUS_UNKNOWN:
2484 return 0;
2485 case 0:
2486 die("internal error in diff-resolve-rename-copy");
2487 default:
2488 return 1;
2492 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2494 int fmt = opt->output_format;
2496 if (fmt & DIFF_FORMAT_CHECKDIFF)
2497 diff_flush_checkdiff(p, opt);
2498 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2499 diff_flush_raw(p, opt);
2500 else if (fmt & DIFF_FORMAT_NAME)
2501 diff_flush_name(p, opt);
2504 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2506 char *name = quote_one(fs->path);
2507 if (fs->mode)
2508 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2509 else
2510 printf(" %s %s\n", newdelete, name);
2511 free(name);
2515 static void show_mode_change(struct diff_filepair *p, int show_name)
2517 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2518 if (show_name) {
2519 char *name = quote_one(p->two->path);
2520 printf(" mode change %06o => %06o %s\n",
2521 p->one->mode, p->two->mode, name);
2522 free(name);
2524 else
2525 printf(" mode change %06o => %06o\n",
2526 p->one->mode, p->two->mode);
2530 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2532 char *names = pprint_rename(p->one->path, p->two->path);
2534 printf(" %s %s (%d%%)\n", renamecopy, names,
2535 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2536 free(names);
2537 show_mode_change(p, 0);
2540 static void diff_summary(struct diff_filepair *p)
2542 switch(p->status) {
2543 case DIFF_STATUS_DELETED:
2544 show_file_mode_name("delete", p->one);
2545 break;
2546 case DIFF_STATUS_ADDED:
2547 show_file_mode_name("create", p->two);
2548 break;
2549 case DIFF_STATUS_COPIED:
2550 show_rename_copy("copy", p);
2551 break;
2552 case DIFF_STATUS_RENAMED:
2553 show_rename_copy("rename", p);
2554 break;
2555 default:
2556 if (p->score) {
2557 char *name = quote_one(p->two->path);
2558 printf(" rewrite %s (%d%%)\n", name,
2559 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2560 free(name);
2561 show_mode_change(p, 0);
2562 } else show_mode_change(p, 1);
2563 break;
2567 struct patch_id_t {
2568 struct xdiff_emit_state xm;
2569 SHA_CTX *ctx;
2570 int patchlen;
2573 static int remove_space(char *line, int len)
2575 int i;
2576 char *dst = line;
2577 unsigned char c;
2579 for (i = 0; i < len; i++)
2580 if (!isspace((c = line[i])))
2581 *dst++ = c;
2583 return dst - line;
2586 static void patch_id_consume(void *priv, char *line, unsigned long len)
2588 struct patch_id_t *data = priv;
2589 int new_len;
2591 /* Ignore line numbers when computing the SHA1 of the patch */
2592 if (!prefixcmp(line, "@@ -"))
2593 return;
2595 new_len = remove_space(line, len);
2597 SHA1_Update(data->ctx, line, new_len);
2598 data->patchlen += new_len;
2601 /* returns 0 upon success, and writes result into sha1 */
2602 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2604 struct diff_queue_struct *q = &diff_queued_diff;
2605 int i;
2606 SHA_CTX ctx;
2607 struct patch_id_t data;
2608 char buffer[PATH_MAX * 4 + 20];
2610 SHA1_Init(&ctx);
2611 memset(&data, 0, sizeof(struct patch_id_t));
2612 data.ctx = &ctx;
2613 data.xm.consume = patch_id_consume;
2615 for (i = 0; i < q->nr; i++) {
2616 xpparam_t xpp;
2617 xdemitconf_t xecfg;
2618 xdemitcb_t ecb;
2619 mmfile_t mf1, mf2;
2620 struct diff_filepair *p = q->queue[i];
2621 int len1, len2;
2623 if (p->status == 0)
2624 return error("internal diff status error");
2625 if (p->status == DIFF_STATUS_UNKNOWN)
2626 continue;
2627 if (diff_unmodified_pair(p))
2628 continue;
2629 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2630 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2631 continue;
2632 if (DIFF_PAIR_UNMERGED(p))
2633 continue;
2635 diff_fill_sha1_info(p->one);
2636 diff_fill_sha1_info(p->two);
2637 if (fill_mmfile(&mf1, p->one) < 0 ||
2638 fill_mmfile(&mf2, p->two) < 0)
2639 return error("unable to read files to diff");
2641 /* Maybe hash p->two? into the patch id? */
2642 if (mmfile_is_binary(&mf2))
2643 continue;
2645 len1 = remove_space(p->one->path, strlen(p->one->path));
2646 len2 = remove_space(p->two->path, strlen(p->two->path));
2647 if (p->one->mode == 0)
2648 len1 = snprintf(buffer, sizeof(buffer),
2649 "diff--gita/%.*sb/%.*s"
2650 "newfilemode%06o"
2651 "---/dev/null"
2652 "+++b/%.*s",
2653 len1, p->one->path,
2654 len2, p->two->path,
2655 p->two->mode,
2656 len2, p->two->path);
2657 else if (p->two->mode == 0)
2658 len1 = snprintf(buffer, sizeof(buffer),
2659 "diff--gita/%.*sb/%.*s"
2660 "deletedfilemode%06o"
2661 "---a/%.*s"
2662 "+++/dev/null",
2663 len1, p->one->path,
2664 len2, p->two->path,
2665 p->one->mode,
2666 len1, p->one->path);
2667 else
2668 len1 = snprintf(buffer, sizeof(buffer),
2669 "diff--gita/%.*sb/%.*s"
2670 "---a/%.*s"
2671 "+++b/%.*s",
2672 len1, p->one->path,
2673 len2, p->two->path,
2674 len1, p->one->path,
2675 len2, p->two->path);
2676 SHA1_Update(&ctx, buffer, len1);
2678 xpp.flags = XDF_NEED_MINIMAL;
2679 xecfg.ctxlen = 3;
2680 xecfg.flags = XDL_EMIT_FUNCNAMES;
2681 ecb.outf = xdiff_outf;
2682 ecb.priv = &data;
2683 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2686 SHA1_Final(sha1, &ctx);
2687 return 0;
2690 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2692 struct diff_queue_struct *q = &diff_queued_diff;
2693 int i;
2694 int result = diff_get_patch_id(options, sha1);
2696 for (i = 0; i < q->nr; i++)
2697 diff_free_filepair(q->queue[i]);
2699 free(q->queue);
2700 q->queue = NULL;
2701 q->nr = q->alloc = 0;
2703 return result;
2706 static int is_summary_empty(const struct diff_queue_struct *q)
2708 int i;
2710 for (i = 0; i < q->nr; i++) {
2711 const struct diff_filepair *p = q->queue[i];
2713 switch (p->status) {
2714 case DIFF_STATUS_DELETED:
2715 case DIFF_STATUS_ADDED:
2716 case DIFF_STATUS_COPIED:
2717 case DIFF_STATUS_RENAMED:
2718 return 0;
2719 default:
2720 if (p->score)
2721 return 0;
2722 if (p->one->mode && p->two->mode &&
2723 p->one->mode != p->two->mode)
2724 return 0;
2725 break;
2728 return 1;
2731 void diff_flush(struct diff_options *options)
2733 struct diff_queue_struct *q = &diff_queued_diff;
2734 int i, output_format = options->output_format;
2735 int separator = 0;
2738 * Order: raw, stat, summary, patch
2739 * or: name/name-status/checkdiff (other bits clear)
2741 if (!q->nr)
2742 goto free_queue;
2744 if (output_format & (DIFF_FORMAT_RAW |
2745 DIFF_FORMAT_NAME |
2746 DIFF_FORMAT_NAME_STATUS |
2747 DIFF_FORMAT_CHECKDIFF)) {
2748 for (i = 0; i < q->nr; i++) {
2749 struct diff_filepair *p = q->queue[i];
2750 if (check_pair_status(p))
2751 flush_one_pair(p, options);
2753 separator++;
2756 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
2757 struct diffstat_t diffstat;
2759 memset(&diffstat, 0, sizeof(struct diffstat_t));
2760 diffstat.xm.consume = diffstat_consume;
2761 for (i = 0; i < q->nr; i++) {
2762 struct diff_filepair *p = q->queue[i];
2763 if (check_pair_status(p))
2764 diff_flush_stat(p, options, &diffstat);
2766 if (output_format & DIFF_FORMAT_NUMSTAT)
2767 show_numstat(&diffstat, options);
2768 if (output_format & DIFF_FORMAT_DIFFSTAT)
2769 show_stats(&diffstat, options);
2770 else if (output_format & DIFF_FORMAT_SHORTSTAT)
2771 show_shortstats(&diffstat);
2772 separator++;
2775 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2776 for (i = 0; i < q->nr; i++)
2777 diff_summary(q->queue[i]);
2778 separator++;
2781 if (output_format & DIFF_FORMAT_PATCH) {
2782 if (separator) {
2783 if (options->stat_sep) {
2784 /* attach patch instead of inline */
2785 fputs(options->stat_sep, stdout);
2786 } else {
2787 putchar(options->line_termination);
2791 for (i = 0; i < q->nr; i++) {
2792 struct diff_filepair *p = q->queue[i];
2793 if (check_pair_status(p))
2794 diff_flush_patch(p, options);
2798 if (output_format & DIFF_FORMAT_CALLBACK)
2799 options->format_callback(q, options, options->format_callback_data);
2801 for (i = 0; i < q->nr; i++)
2802 diff_free_filepair(q->queue[i]);
2803 free_queue:
2804 free(q->queue);
2805 q->queue = NULL;
2806 q->nr = q->alloc = 0;
2809 static void diffcore_apply_filter(const char *filter)
2811 int i;
2812 struct diff_queue_struct *q = &diff_queued_diff;
2813 struct diff_queue_struct outq;
2814 outq.queue = NULL;
2815 outq.nr = outq.alloc = 0;
2817 if (!filter)
2818 return;
2820 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2821 int found;
2822 for (i = found = 0; !found && i < q->nr; i++) {
2823 struct diff_filepair *p = q->queue[i];
2824 if (((p->status == DIFF_STATUS_MODIFIED) &&
2825 ((p->score &&
2826 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2827 (!p->score &&
2828 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2829 ((p->status != DIFF_STATUS_MODIFIED) &&
2830 strchr(filter, p->status)))
2831 found++;
2833 if (found)
2834 return;
2836 /* otherwise we will clear the whole queue
2837 * by copying the empty outq at the end of this
2838 * function, but first clear the current entries
2839 * in the queue.
2841 for (i = 0; i < q->nr; i++)
2842 diff_free_filepair(q->queue[i]);
2844 else {
2845 /* Only the matching ones */
2846 for (i = 0; i < q->nr; i++) {
2847 struct diff_filepair *p = q->queue[i];
2849 if (((p->status == DIFF_STATUS_MODIFIED) &&
2850 ((p->score &&
2851 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2852 (!p->score &&
2853 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2854 ((p->status != DIFF_STATUS_MODIFIED) &&
2855 strchr(filter, p->status)))
2856 diff_q(&outq, p);
2857 else
2858 diff_free_filepair(p);
2861 free(q->queue);
2862 *q = outq;
2865 void diffcore_std(struct diff_options *options)
2867 if (options->break_opt != -1)
2868 diffcore_break(options->break_opt);
2869 if (options->detect_rename)
2870 diffcore_rename(options);
2871 if (options->break_opt != -1)
2872 diffcore_merge_broken();
2873 if (options->pickaxe)
2874 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2875 if (options->orderfile)
2876 diffcore_order(options->orderfile);
2877 diff_resolve_rename_copy();
2878 diffcore_apply_filter(options->filter);
2882 void diffcore_std_no_resolve(struct diff_options *options)
2884 if (options->pickaxe)
2885 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2886 if (options->orderfile)
2887 diffcore_order(options->orderfile);
2888 diffcore_apply_filter(options->filter);
2891 void diff_addremove(struct diff_options *options,
2892 int addremove, unsigned mode,
2893 const unsigned char *sha1,
2894 const char *base, const char *path)
2896 char concatpath[PATH_MAX];
2897 struct diff_filespec *one, *two;
2899 /* This may look odd, but it is a preparation for
2900 * feeding "there are unchanged files which should
2901 * not produce diffs, but when you are doing copy
2902 * detection you would need them, so here they are"
2903 * entries to the diff-core. They will be prefixed
2904 * with something like '=' or '*' (I haven't decided
2905 * which but should not make any difference).
2906 * Feeding the same new and old to diff_change()
2907 * also has the same effect.
2908 * Before the final output happens, they are pruned after
2909 * merged into rename/copy pairs as appropriate.
2911 if (options->reverse_diff)
2912 addremove = (addremove == '+' ? '-' :
2913 addremove == '-' ? '+' : addremove);
2915 if (!path) path = "";
2916 sprintf(concatpath, "%s%s", base, path);
2917 one = alloc_filespec(concatpath);
2918 two = alloc_filespec(concatpath);
2920 if (addremove != '+')
2921 fill_filespec(one, sha1, mode);
2922 if (addremove != '-')
2923 fill_filespec(two, sha1, mode);
2925 diff_queue(&diff_queued_diff, one, two);
2928 void diff_change(struct diff_options *options,
2929 unsigned old_mode, unsigned new_mode,
2930 const unsigned char *old_sha1,
2931 const unsigned char *new_sha1,
2932 const char *base, const char *path)
2934 char concatpath[PATH_MAX];
2935 struct diff_filespec *one, *two;
2937 if (options->reverse_diff) {
2938 unsigned tmp;
2939 const unsigned char *tmp_c;
2940 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2941 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2943 if (!path) path = "";
2944 sprintf(concatpath, "%s%s", base, path);
2945 one = alloc_filespec(concatpath);
2946 two = alloc_filespec(concatpath);
2947 fill_filespec(one, old_sha1, old_mode);
2948 fill_filespec(two, new_sha1, new_mode);
2950 diff_queue(&diff_queued_diff, one, two);
2953 void diff_unmerge(struct diff_options *options,
2954 const char *path,
2955 unsigned mode, const unsigned char *sha1)
2957 struct diff_filespec *one, *two;
2958 one = alloc_filespec(path);
2959 two = alloc_filespec(path);
2960 fill_filespec(one, sha1, mode);
2961 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;