diff: Make numstat machine fritndly also for renames
[git/jnareb-git.git] / diff.c
blob568c59b38fdc2e4c229883e8ace42935fbec87b6
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"
11 #include "attr.h"
13 #ifdef NO_FAST_WORKING_DIRECTORY
14 #define FAST_WORKING_DIRECTORY 0
15 #else
16 #define FAST_WORKING_DIRECTORY 1
17 #endif
19 static int use_size_cache;
21 static int diff_detect_rename_default;
22 static int diff_rename_limit_default = -1;
23 static int diff_use_color_default;
25 static char diff_colors[][COLOR_MAXLEN] = {
26 "\033[m", /* reset */
27 "", /* PLAIN (normal) */
28 "\033[1m", /* METAINFO (bold) */
29 "\033[36m", /* FRAGINFO (cyan) */
30 "\033[31m", /* OLD (red) */
31 "\033[32m", /* NEW (green) */
32 "\033[33m", /* COMMIT (yellow) */
33 "\033[41m", /* WHITESPACE (red background) */
36 static int parse_diff_color_slot(const char *var, int ofs)
38 if (!strcasecmp(var+ofs, "plain"))
39 return DIFF_PLAIN;
40 if (!strcasecmp(var+ofs, "meta"))
41 return DIFF_METAINFO;
42 if (!strcasecmp(var+ofs, "frag"))
43 return DIFF_FRAGINFO;
44 if (!strcasecmp(var+ofs, "old"))
45 return DIFF_FILE_OLD;
46 if (!strcasecmp(var+ofs, "new"))
47 return DIFF_FILE_NEW;
48 if (!strcasecmp(var+ofs, "commit"))
49 return DIFF_COMMIT;
50 if (!strcasecmp(var+ofs, "whitespace"))
51 return DIFF_WHITESPACE;
52 die("bad config variable '%s'", var);
55 static struct ll_diff_driver {
56 const char *name;
57 struct ll_diff_driver *next;
58 char *cmd;
59 } *user_diff, **user_diff_tail;
62 * Currently there is only "diff.<drivername>.command" variable;
63 * because there are "diff.color.<slot>" variables, we are parsing
64 * this in a bit convoluted way to allow low level diff driver
65 * called "color".
67 static int parse_lldiff_command(const char *var, const char *ep, const char *value)
69 const char *name;
70 int namelen;
71 struct ll_diff_driver *drv;
73 name = var + 5;
74 namelen = ep - name;
75 for (drv = user_diff; drv; drv = drv->next)
76 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
77 break;
78 if (!drv) {
79 char *namebuf;
80 drv = xcalloc(1, sizeof(struct ll_diff_driver));
81 namebuf = xmalloc(namelen + 1);
82 memcpy(namebuf, name, namelen);
83 namebuf[namelen] = 0;
84 drv->name = namebuf;
85 drv->next = NULL;
86 if (!user_diff_tail)
87 user_diff_tail = &user_diff;
88 *user_diff_tail = drv;
89 user_diff_tail = &(drv->next);
92 if (!value)
93 return error("%s: lacks value", var);
94 drv->cmd = strdup(value);
95 return 0;
99 * These are to give UI layer defaults.
100 * The core-level commands such as git-diff-files should
101 * never be affected by the setting of diff.renames
102 * the user happens to have in the configuration file.
104 int git_diff_ui_config(const char *var, const char *value)
106 if (!strcmp(var, "diff.renamelimit")) {
107 diff_rename_limit_default = git_config_int(var, value);
108 return 0;
110 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
111 diff_use_color_default = git_config_colorbool(var, value);
112 return 0;
114 if (!strcmp(var, "diff.renames")) {
115 if (!value)
116 diff_detect_rename_default = DIFF_DETECT_RENAME;
117 else if (!strcasecmp(value, "copies") ||
118 !strcasecmp(value, "copy"))
119 diff_detect_rename_default = DIFF_DETECT_COPY;
120 else if (git_config_bool(var,value))
121 diff_detect_rename_default = DIFF_DETECT_RENAME;
122 return 0;
124 if (!prefixcmp(var, "diff.")) {
125 const char *ep = strrchr(var, '.');
127 if (ep != var + 4 && !strcmp(ep, ".command"))
128 return parse_lldiff_command(var, ep, value);
130 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
131 int slot = parse_diff_color_slot(var, 11);
132 color_parse(value, var, diff_colors[slot]);
133 return 0;
136 return git_default_config(var, value);
139 static char *quote_one(const char *str)
141 int needlen;
142 char *xp;
144 if (!str)
145 return NULL;
146 needlen = quote_c_style(str, NULL, NULL, 0);
147 if (!needlen)
148 return xstrdup(str);
149 xp = xmalloc(needlen + 1);
150 quote_c_style(str, xp, NULL, 0);
151 return xp;
154 static char *quote_two(const char *one, const char *two)
156 int need_one = quote_c_style(one, NULL, NULL, 1);
157 int need_two = quote_c_style(two, NULL, NULL, 1);
158 char *xp;
160 if (need_one + need_two) {
161 if (!need_one) need_one = strlen(one);
162 if (!need_two) need_one = strlen(two);
164 xp = xmalloc(need_one + need_two + 3);
165 xp[0] = '"';
166 quote_c_style(one, xp + 1, NULL, 1);
167 quote_c_style(two, xp + need_one + 1, NULL, 1);
168 strcpy(xp + need_one + need_two + 1, "\"");
169 return xp;
171 need_one = strlen(one);
172 need_two = strlen(two);
173 xp = xmalloc(need_one + need_two + 1);
174 strcpy(xp, one);
175 strcpy(xp + need_one, two);
176 return xp;
179 static const char *external_diff(void)
181 static const char *external_diff_cmd = NULL;
182 static int done_preparing = 0;
184 if (done_preparing)
185 return external_diff_cmd;
186 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
187 done_preparing = 1;
188 return external_diff_cmd;
191 #define TEMPFILE_PATH_LEN 50
193 static struct diff_tempfile {
194 const char *name; /* filename external diff should read from */
195 char hex[41];
196 char mode[10];
197 char tmp_path[TEMPFILE_PATH_LEN];
198 } diff_temp[2];
200 static int count_lines(const char *data, int size)
202 int count, ch, completely_empty = 1, nl_just_seen = 0;
203 count = 0;
204 while (0 < size--) {
205 ch = *data++;
206 if (ch == '\n') {
207 count++;
208 nl_just_seen = 1;
209 completely_empty = 0;
211 else {
212 nl_just_seen = 0;
213 completely_empty = 0;
216 if (completely_empty)
217 return 0;
218 if (!nl_just_seen)
219 count++; /* no trailing newline */
220 return count;
223 static void print_line_count(int count)
225 switch (count) {
226 case 0:
227 printf("0,0");
228 break;
229 case 1:
230 printf("1");
231 break;
232 default:
233 printf("1,%d", count);
234 break;
238 static void copy_file(int prefix, const char *data, int size,
239 const char *set, const char *reset)
241 int ch, nl_just_seen = 1;
242 while (0 < size--) {
243 ch = *data++;
244 if (nl_just_seen) {
245 fputs(set, stdout);
246 putchar(prefix);
248 if (ch == '\n') {
249 nl_just_seen = 1;
250 fputs(reset, stdout);
251 } else
252 nl_just_seen = 0;
253 putchar(ch);
255 if (!nl_just_seen)
256 printf("%s\n\\ No newline at end of file\n", reset);
259 static void emit_rewrite_diff(const char *name_a,
260 const char *name_b,
261 struct diff_filespec *one,
262 struct diff_filespec *two,
263 int color_diff)
265 int lc_a, lc_b;
266 const char *name_a_tab, *name_b_tab;
267 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
268 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
269 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
270 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
271 const char *reset = diff_get_color(color_diff, DIFF_RESET);
273 name_a += (*name_a == '/');
274 name_b += (*name_b == '/');
275 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
276 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
278 diff_populate_filespec(one, 0);
279 diff_populate_filespec(two, 0);
280 lc_a = count_lines(one->data, one->size);
281 lc_b = count_lines(two->data, two->size);
282 printf("%s--- a/%s%s%s\n%s+++ b/%s%s%s\n%s@@ -",
283 metainfo, name_a, name_a_tab, reset,
284 metainfo, name_b, name_b_tab, reset, fraginfo);
285 print_line_count(lc_a);
286 printf(" +");
287 print_line_count(lc_b);
288 printf(" @@%s\n", reset);
289 if (lc_a)
290 copy_file('-', one->data, one->size, old, reset);
291 if (lc_b)
292 copy_file('+', two->data, two->size, new, reset);
295 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
297 if (!DIFF_FILE_VALID(one)) {
298 mf->ptr = (char *)""; /* does not matter */
299 mf->size = 0;
300 return 0;
302 else if (diff_populate_filespec(one, 0))
303 return -1;
304 mf->ptr = one->data;
305 mf->size = one->size;
306 return 0;
309 struct diff_words_buffer {
310 mmfile_t text;
311 long alloc;
312 long current; /* output pointer */
313 int suppressed_newline;
316 static void diff_words_append(char *line, unsigned long len,
317 struct diff_words_buffer *buffer)
319 if (buffer->text.size + len > buffer->alloc) {
320 buffer->alloc = (buffer->text.size + len) * 3 / 2;
321 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
323 line++;
324 len--;
325 memcpy(buffer->text.ptr + buffer->text.size, line, len);
326 buffer->text.size += len;
329 struct diff_words_data {
330 struct xdiff_emit_state xm;
331 struct diff_words_buffer minus, plus;
334 static void print_word(struct diff_words_buffer *buffer, int len, int color,
335 int suppress_newline)
337 const char *ptr;
338 int eol = 0;
340 if (len == 0)
341 return;
343 ptr = buffer->text.ptr + buffer->current;
344 buffer->current += len;
346 if (ptr[len - 1] == '\n') {
347 eol = 1;
348 len--;
351 fputs(diff_get_color(1, color), stdout);
352 fwrite(ptr, len, 1, stdout);
353 fputs(diff_get_color(1, DIFF_RESET), stdout);
355 if (eol) {
356 if (suppress_newline)
357 buffer->suppressed_newline = 1;
358 else
359 putchar('\n');
363 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
365 struct diff_words_data *diff_words = priv;
367 if (diff_words->minus.suppressed_newline) {
368 if (line[0] != '+')
369 putchar('\n');
370 diff_words->minus.suppressed_newline = 0;
373 len--;
374 switch (line[0]) {
375 case '-':
376 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
377 break;
378 case '+':
379 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
380 break;
381 case ' ':
382 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
383 diff_words->minus.current += len;
384 break;
388 /* this executes the word diff on the accumulated buffers */
389 static void diff_words_show(struct diff_words_data *diff_words)
391 xpparam_t xpp;
392 xdemitconf_t xecfg;
393 xdemitcb_t ecb;
394 mmfile_t minus, plus;
395 int i;
397 minus.size = diff_words->minus.text.size;
398 minus.ptr = xmalloc(minus.size);
399 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
400 for (i = 0; i < minus.size; i++)
401 if (isspace(minus.ptr[i]))
402 minus.ptr[i] = '\n';
403 diff_words->minus.current = 0;
405 plus.size = diff_words->plus.text.size;
406 plus.ptr = xmalloc(plus.size);
407 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
408 for (i = 0; i < plus.size; i++)
409 if (isspace(plus.ptr[i]))
410 plus.ptr[i] = '\n';
411 diff_words->plus.current = 0;
413 xpp.flags = XDF_NEED_MINIMAL;
414 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
415 xecfg.flags = 0;
416 ecb.outf = xdiff_outf;
417 ecb.priv = diff_words;
418 diff_words->xm.consume = fn_out_diff_words_aux;
419 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
421 free(minus.ptr);
422 free(plus.ptr);
423 diff_words->minus.text.size = diff_words->plus.text.size = 0;
425 if (diff_words->minus.suppressed_newline) {
426 putchar('\n');
427 diff_words->minus.suppressed_newline = 0;
431 struct emit_callback {
432 struct xdiff_emit_state xm;
433 int nparents, color_diff;
434 const char **label_path;
435 struct diff_words_data *diff_words;
436 int *found_changesp;
439 static void free_diff_words_data(struct emit_callback *ecbdata)
441 if (ecbdata->diff_words) {
442 /* flush buffers */
443 if (ecbdata->diff_words->minus.text.size ||
444 ecbdata->diff_words->plus.text.size)
445 diff_words_show(ecbdata->diff_words);
447 if (ecbdata->diff_words->minus.text.ptr)
448 free (ecbdata->diff_words->minus.text.ptr);
449 if (ecbdata->diff_words->plus.text.ptr)
450 free (ecbdata->diff_words->plus.text.ptr);
451 free(ecbdata->diff_words);
452 ecbdata->diff_words = NULL;
456 const char *diff_get_color(int diff_use_color, enum color_diff ix)
458 if (diff_use_color)
459 return diff_colors[ix];
460 return "";
463 static void emit_line(const char *set, const char *reset, const char *line, int len)
465 if (len > 0 && line[len-1] == '\n')
466 len--;
467 fputs(set, stdout);
468 fwrite(line, len, 1, stdout);
469 puts(reset);
472 static void emit_line_with_ws(int nparents,
473 const char *set, const char *reset, const char *ws,
474 const char *line, int len)
476 int col0 = nparents;
477 int last_tab_in_indent = -1;
478 int last_space_in_indent = -1;
479 int i;
480 int tail = len;
481 int need_highlight_leading_space = 0;
482 /* The line is a newly added line. Does it have funny leading
483 * whitespaces? In indent, SP should never precede a TAB.
485 for (i = col0; i < len; i++) {
486 if (line[i] == '\t') {
487 last_tab_in_indent = i;
488 if (0 <= last_space_in_indent)
489 need_highlight_leading_space = 1;
491 else if (line[i] == ' ')
492 last_space_in_indent = i;
493 else
494 break;
496 fputs(set, stdout);
497 fwrite(line, col0, 1, stdout);
498 fputs(reset, stdout);
499 if (((i == len) || line[i] == '\n') && i != col0) {
500 /* The whole line was indent */
501 emit_line(ws, reset, line + col0, len - col0);
502 return;
504 i = col0;
505 if (need_highlight_leading_space) {
506 while (i < last_tab_in_indent) {
507 if (line[i] == ' ') {
508 fputs(ws, stdout);
509 putchar(' ');
510 fputs(reset, stdout);
512 else
513 putchar(line[i]);
514 i++;
517 tail = len - 1;
518 if (line[tail] == '\n' && i < tail)
519 tail--;
520 while (i < tail) {
521 if (!isspace(line[tail]))
522 break;
523 tail--;
525 if ((i < tail && line[tail + 1] != '\n')) {
526 /* This has whitespace between tail+1..len */
527 fputs(set, stdout);
528 fwrite(line + i, tail - i + 1, 1, stdout);
529 fputs(reset, stdout);
530 emit_line(ws, reset, line + tail + 1, len - tail - 1);
532 else
533 emit_line(set, reset, line + i, len - i);
536 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
538 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
539 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
541 if (!*ws)
542 emit_line(set, reset, line, len);
543 else
544 emit_line_with_ws(ecbdata->nparents, set, reset, ws,
545 line, len);
548 static void fn_out_consume(void *priv, char *line, unsigned long len)
550 int i;
551 int color;
552 struct emit_callback *ecbdata = priv;
553 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
554 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
556 *(ecbdata->found_changesp) = 1;
558 if (ecbdata->label_path[0]) {
559 const char *name_a_tab, *name_b_tab;
561 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
562 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
564 printf("%s--- %s%s%s\n",
565 set, ecbdata->label_path[0], reset, name_a_tab);
566 printf("%s+++ %s%s%s\n",
567 set, ecbdata->label_path[1], reset, name_b_tab);
568 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
571 /* This is not really necessary for now because
572 * this codepath only deals with two-way diffs.
574 for (i = 0; i < len && line[i] == '@'; i++)
576 if (2 <= i && i < len && line[i] == ' ') {
577 ecbdata->nparents = i - 1;
578 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
579 reset, line, len);
580 return;
583 if (len < ecbdata->nparents) {
584 set = reset;
585 emit_line(reset, reset, line, len);
586 return;
589 color = DIFF_PLAIN;
590 if (ecbdata->diff_words && ecbdata->nparents != 1)
591 /* fall back to normal diff */
592 free_diff_words_data(ecbdata);
593 if (ecbdata->diff_words) {
594 if (line[0] == '-') {
595 diff_words_append(line, len,
596 &ecbdata->diff_words->minus);
597 return;
598 } else if (line[0] == '+') {
599 diff_words_append(line, len,
600 &ecbdata->diff_words->plus);
601 return;
603 if (ecbdata->diff_words->minus.text.size ||
604 ecbdata->diff_words->plus.text.size)
605 diff_words_show(ecbdata->diff_words);
606 line++;
607 len--;
608 emit_line(set, reset, line, len);
609 return;
611 for (i = 0; i < ecbdata->nparents && len; i++) {
612 if (line[i] == '-')
613 color = DIFF_FILE_OLD;
614 else if (line[i] == '+')
615 color = DIFF_FILE_NEW;
618 if (color != DIFF_FILE_NEW) {
619 emit_line(diff_get_color(ecbdata->color_diff, color),
620 reset, line, len);
621 return;
623 emit_add_line(reset, ecbdata, line, len);
626 static char *pprint_rename(const char *a, const char *b)
628 const char *old = a;
629 const char *new = b;
630 char *name = NULL;
631 int pfx_length, sfx_length;
632 int len_a = strlen(a);
633 int len_b = strlen(b);
634 int qlen_a = quote_c_style(a, NULL, NULL, 0);
635 int qlen_b = quote_c_style(b, NULL, NULL, 0);
637 if (qlen_a || qlen_b) {
638 if (qlen_a) len_a = qlen_a;
639 if (qlen_b) len_b = qlen_b;
640 name = xmalloc( len_a + len_b + 5 );
641 if (qlen_a)
642 quote_c_style(a, name, NULL, 0);
643 else
644 memcpy(name, a, len_a);
645 memcpy(name + len_a, " => ", 4);
646 if (qlen_b)
647 quote_c_style(b, name + len_a + 4, NULL, 0);
648 else
649 memcpy(name + len_a + 4, b, len_b + 1);
650 return name;
653 /* Find common prefix */
654 pfx_length = 0;
655 while (*old && *new && *old == *new) {
656 if (*old == '/')
657 pfx_length = old - a + 1;
658 old++;
659 new++;
662 /* Find common suffix */
663 old = a + len_a;
664 new = b + len_b;
665 sfx_length = 0;
666 while (a <= old && b <= new && *old == *new) {
667 if (*old == '/')
668 sfx_length = len_a - (old - a);
669 old--;
670 new--;
674 * pfx{mid-a => mid-b}sfx
675 * {pfx-a => pfx-b}sfx
676 * pfx{sfx-a => sfx-b}
677 * name-a => name-b
679 if (pfx_length + sfx_length) {
680 int a_midlen = len_a - pfx_length - sfx_length;
681 int b_midlen = len_b - pfx_length - sfx_length;
682 if (a_midlen < 0) a_midlen = 0;
683 if (b_midlen < 0) b_midlen = 0;
685 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
686 sprintf(name, "%.*s{%.*s => %.*s}%s",
687 pfx_length, a,
688 a_midlen, a + pfx_length,
689 b_midlen, b + pfx_length,
690 a + len_a - sfx_length);
692 else {
693 name = xmalloc(len_a + len_b + 5);
694 sprintf(name, "%s => %s", a, b);
696 return name;
699 struct diffstat_t {
700 struct xdiff_emit_state xm;
702 int nr;
703 int alloc;
704 struct diffstat_file {
705 char *name;
706 char *from_name;
707 unsigned is_unmerged:1;
708 unsigned is_binary:1;
709 unsigned is_renamed:1;
710 unsigned int added, deleted;
711 } **files;
714 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
715 const char *name_a,
716 const char *name_b)
718 struct diffstat_file *x;
719 x = xcalloc(sizeof (*x), 1);
720 if (diffstat->nr == diffstat->alloc) {
721 diffstat->alloc = alloc_nr(diffstat->alloc);
722 diffstat->files = xrealloc(diffstat->files,
723 diffstat->alloc * sizeof(x));
725 diffstat->files[diffstat->nr++] = x;
726 x->name = xstrdup(name_a);
727 if (name_b) {
728 x->from_name = xstrdup(name_b);
729 x->is_renamed = 1;
731 else
732 x->from_name = NULL;
733 return x;
736 static void diffstat_consume(void *priv, char *line, unsigned long len)
738 struct diffstat_t *diffstat = priv;
739 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
741 if (line[0] == '+')
742 x->added++;
743 else if (line[0] == '-')
744 x->deleted++;
747 const char mime_boundary_leader[] = "------------";
749 static int scale_linear(int it, int width, int max_change)
752 * make sure that at least one '-' is printed if there were deletions,
753 * and likewise for '+'.
755 if (max_change < 2)
756 return it;
757 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
760 static void show_name(const char *prefix, const char *name, int len,
761 const char *reset, const char *set)
763 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
766 static void show_graph(char ch, int cnt, const char *set, const char *reset)
768 if (cnt <= 0)
769 return;
770 printf("%s", set);
771 while (cnt--)
772 putchar(ch);
773 printf("%s", reset);
776 static void show_stats(struct diffstat_t* data, struct diff_options *options)
778 int i, len, add, del, total, adds = 0, dels = 0;
779 int max_change = 0, max_len = 0;
780 int total_files = data->nr;
781 int width, name_width;
782 const char *reset, *set, *add_c, *del_c;
784 if (data->nr == 0)
785 return;
787 width = options->stat_width ? options->stat_width : 80;
788 name_width = options->stat_name_width ? options->stat_name_width : 50;
790 /* Sanity: give at least 5 columns to the graph,
791 * but leave at least 10 columns for the name.
793 if (width < name_width + 15) {
794 if (name_width <= 25)
795 width = name_width + 15;
796 else
797 name_width = width - 15;
800 /* Find the longest filename and max number of changes */
801 reset = diff_get_color(options->color_diff, DIFF_RESET);
802 set = diff_get_color(options->color_diff, DIFF_PLAIN);
803 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
804 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
806 for (i = 0; i < data->nr; i++) {
807 struct diffstat_file *file = data->files[i];
808 int change = file->added + file->deleted;
810 if (!file->is_renamed) { /* renames are quoted by pprint_rename */
811 len = quote_c_style(file->name, NULL, NULL, 0);
812 if (len) {
813 char *qname = xmalloc(len + 1);
814 quote_c_style(file->name, qname, NULL, 0);
815 free(file->name);
816 file->name = qname;
818 } else {
819 char *qname = pprint_rename(file->name, file->from_name);
820 free(file->name);
821 file->name = qname;
824 len = strlen(file->name);
825 if (max_len < len)
826 max_len = len;
828 if (file->is_binary || file->is_unmerged)
829 continue;
830 if (max_change < change)
831 max_change = change;
834 /* Compute the width of the graph part;
835 * 10 is for one blank at the beginning of the line plus
836 * " | count " between the name and the graph.
838 * From here on, name_width is the width of the name area,
839 * and width is the width of the graph area.
841 name_width = (name_width < max_len) ? name_width : max_len;
842 if (width < (name_width + 10) + max_change)
843 width = width - (name_width + 10);
844 else
845 width = max_change;
847 for (i = 0; i < data->nr; i++) {
848 const char *prefix = "";
849 char *name = data->files[i]->name;
850 int added = data->files[i]->added;
851 int deleted = data->files[i]->deleted;
852 int name_len;
855 * "scale" the filename
857 len = name_width;
858 name_len = strlen(name);
859 if (name_width < name_len) {
860 char *slash;
861 prefix = "...";
862 len -= 3;
863 name += name_len - len;
864 slash = strchr(name, '/');
865 if (slash)
866 name = slash;
869 if (data->files[i]->is_binary) {
870 show_name(prefix, name, len, reset, set);
871 printf(" Bin ");
872 printf("%s%d%s", del_c, deleted, reset);
873 printf(" -> ");
874 printf("%s%d%s", add_c, added, reset);
875 printf(" bytes");
876 printf("\n");
877 goto free_diffstat_file;
879 else if (data->files[i]->is_unmerged) {
880 show_name(prefix, name, len, reset, set);
881 printf(" Unmerged\n");
882 goto free_diffstat_file;
884 else if (!data->files[i]->is_renamed &&
885 (added + deleted == 0)) {
886 total_files--;
887 goto free_diffstat_file;
891 * scale the add/delete
893 add = added;
894 del = deleted;
895 total = add + del;
896 adds += add;
897 dels += del;
899 if (width <= max_change) {
900 add = scale_linear(add, width, max_change);
901 del = scale_linear(del, width, max_change);
902 total = add + del;
904 show_name(prefix, name, len, reset, set);
905 printf("%5d ", added + deleted);
906 show_graph('+', add, add_c, reset);
907 show_graph('-', del, del_c, reset);
908 putchar('\n');
909 free_diffstat_file:
910 free(data->files[i]->name);
911 free(data->files[i]);
913 free(data->files);
914 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
915 set, total_files, adds, dels, reset);
918 static void show_shortstats(struct diffstat_t* data)
920 int i, adds = 0, dels = 0, total_files = data->nr;
922 if (data->nr == 0)
923 return;
925 for (i = 0; i < data->nr; i++) {
926 if (!data->files[i]->is_binary &&
927 !data->files[i]->is_unmerged) {
928 int added = data->files[i]->added;
929 int deleted= data->files[i]->deleted;
930 if (!data->files[i]->is_renamed &&
931 (added + deleted == 0)) {
932 total_files--;
933 } else {
934 adds += added;
935 dels += deleted;
938 free(data->files[i]->name);
939 free(data->files[i]);
941 free(data->files);
943 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
944 total_files, adds, dels);
947 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
949 int i;
951 for (i = 0; i < data->nr; i++) {
952 struct diffstat_file *file = data->files[i];
954 if (file->is_binary)
955 printf("-\t-\t");
956 else
957 printf("%d\t%d\t", file->added, file->deleted);
958 if (options->line_termination &&
959 quote_c_style(file->name, NULL, NULL, 0))
960 quote_c_style(file->name, NULL, stdout, 0);
961 else
962 fputs(file->name, stdout);
963 if (file->is_renamed) {
964 printf("%s", options->line_termination ? "\t" : "\0\0");
965 if (options->line_termination &&
966 quote_c_style(file->from_name, NULL, NULL, 0))
967 quote_c_style(file->from_name, NULL, stdout, 0);
968 else
969 fputs(file->from_name, stdout);
971 putchar(options->line_termination);
975 struct checkdiff_t {
976 struct xdiff_emit_state xm;
977 const char *filename;
978 int lineno, color_diff;
981 static void checkdiff_consume(void *priv, char *line, unsigned long len)
983 struct checkdiff_t *data = priv;
984 const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
985 const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
986 const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
988 if (line[0] == '+') {
989 int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
991 /* check space before tab */
992 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
993 if (line[i] == ' ')
994 spaces++;
995 if (line[i - 1] == '\t' && spaces)
996 space_before_tab = 1;
998 /* check white space at line end */
999 if (line[len - 1] == '\n')
1000 len--;
1001 if (isspace(line[len - 1]))
1002 white_space_at_end = 1;
1004 if (space_before_tab || white_space_at_end) {
1005 printf("%s:%d: %s", data->filename, data->lineno, ws);
1006 if (space_before_tab) {
1007 printf("space before tab");
1008 if (white_space_at_end)
1009 putchar(',');
1011 if (white_space_at_end)
1012 printf("white space at end");
1013 printf(":%s ", reset);
1014 emit_line_with_ws(1, set, reset, ws, line, len);
1017 data->lineno++;
1018 } else if (line[0] == ' ')
1019 data->lineno++;
1020 else if (line[0] == '@') {
1021 char *plus = strchr(line, '+');
1022 if (plus)
1023 data->lineno = strtol(plus, NULL, 10);
1024 else
1025 die("invalid diff");
1029 static unsigned char *deflate_it(char *data,
1030 unsigned long size,
1031 unsigned long *result_size)
1033 int bound;
1034 unsigned char *deflated;
1035 z_stream stream;
1037 memset(&stream, 0, sizeof(stream));
1038 deflateInit(&stream, zlib_compression_level);
1039 bound = deflateBound(&stream, size);
1040 deflated = xmalloc(bound);
1041 stream.next_out = deflated;
1042 stream.avail_out = bound;
1044 stream.next_in = (unsigned char *)data;
1045 stream.avail_in = size;
1046 while (deflate(&stream, Z_FINISH) == Z_OK)
1047 ; /* nothing */
1048 deflateEnd(&stream);
1049 *result_size = stream.total_out;
1050 return deflated;
1053 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
1055 void *cp;
1056 void *delta;
1057 void *deflated;
1058 void *data;
1059 unsigned long orig_size;
1060 unsigned long delta_size;
1061 unsigned long deflate_size;
1062 unsigned long data_size;
1064 /* We could do deflated delta, or we could do just deflated two,
1065 * whichever is smaller.
1067 delta = NULL;
1068 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1069 if (one->size && two->size) {
1070 delta = diff_delta(one->ptr, one->size,
1071 two->ptr, two->size,
1072 &delta_size, deflate_size);
1073 if (delta) {
1074 void *to_free = delta;
1075 orig_size = delta_size;
1076 delta = deflate_it(delta, delta_size, &delta_size);
1077 free(to_free);
1081 if (delta && delta_size < deflate_size) {
1082 printf("delta %lu\n", orig_size);
1083 free(deflated);
1084 data = delta;
1085 data_size = delta_size;
1087 else {
1088 printf("literal %lu\n", two->size);
1089 free(delta);
1090 data = deflated;
1091 data_size = deflate_size;
1094 /* emit data encoded in base85 */
1095 cp = data;
1096 while (data_size) {
1097 int bytes = (52 < data_size) ? 52 : data_size;
1098 char line[70];
1099 data_size -= bytes;
1100 if (bytes <= 26)
1101 line[0] = bytes + 'A' - 1;
1102 else
1103 line[0] = bytes - 26 + 'a' - 1;
1104 encode_85(line + 1, cp, bytes);
1105 cp = (char *) cp + bytes;
1106 puts(line);
1108 printf("\n");
1109 free(data);
1112 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1114 printf("GIT binary patch\n");
1115 emit_binary_diff_body(one, two);
1116 emit_binary_diff_body(two, one);
1119 static void setup_diff_attr_check(struct git_attr_check *check)
1121 static struct git_attr *attr_diff;
1123 if (!attr_diff)
1124 attr_diff = git_attr("diff", 4);
1125 check->attr = attr_diff;
1128 #define FIRST_FEW_BYTES 8000
1129 static int file_is_binary(struct diff_filespec *one)
1131 unsigned long sz;
1132 struct git_attr_check attr_diff_check;
1134 setup_diff_attr_check(&attr_diff_check);
1135 if (!git_checkattr(one->path, 1, &attr_diff_check)) {
1136 const char *value = attr_diff_check.value;
1137 if (ATTR_TRUE(value))
1138 return 0;
1139 else if (ATTR_FALSE(value))
1140 return 1;
1143 if (!one->data) {
1144 if (!DIFF_FILE_VALID(one))
1145 return 0;
1146 diff_populate_filespec(one, 0);
1148 sz = one->size;
1149 if (FIRST_FEW_BYTES < sz)
1150 sz = FIRST_FEW_BYTES;
1151 return !!memchr(one->data, 0, sz);
1154 static void builtin_diff(const char *name_a,
1155 const char *name_b,
1156 struct diff_filespec *one,
1157 struct diff_filespec *two,
1158 const char *xfrm_msg,
1159 struct diff_options *o,
1160 int complete_rewrite)
1162 mmfile_t mf1, mf2;
1163 const char *lbl[2];
1164 char *a_one, *b_two;
1165 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1166 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1168 a_one = quote_two("a/", name_a + (*name_a == '/'));
1169 b_two = quote_two("b/", name_b + (*name_b == '/'));
1170 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1171 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1172 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1173 if (lbl[0][0] == '/') {
1174 /* /dev/null */
1175 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1176 if (xfrm_msg && xfrm_msg[0])
1177 printf("%s%s%s\n", set, xfrm_msg, reset);
1179 else if (lbl[1][0] == '/') {
1180 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1181 if (xfrm_msg && xfrm_msg[0])
1182 printf("%s%s%s\n", set, xfrm_msg, reset);
1184 else {
1185 if (one->mode != two->mode) {
1186 printf("%sold mode %06o%s\n", set, one->mode, reset);
1187 printf("%snew mode %06o%s\n", set, two->mode, reset);
1189 if (xfrm_msg && xfrm_msg[0])
1190 printf("%s%s%s\n", set, xfrm_msg, reset);
1192 * we do not run diff between different kind
1193 * of objects.
1195 if ((one->mode ^ two->mode) & S_IFMT)
1196 goto free_ab_and_return;
1197 if (complete_rewrite) {
1198 emit_rewrite_diff(name_a, name_b, one, two,
1199 o->color_diff);
1200 o->found_changes = 1;
1201 goto free_ab_and_return;
1205 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1206 die("unable to read files to diff");
1208 if (!o->text && (file_is_binary(one) || file_is_binary(two))) {
1209 /* Quite common confusing case */
1210 if (mf1.size == mf2.size &&
1211 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1212 goto free_ab_and_return;
1213 if (o->binary)
1214 emit_binary_diff(&mf1, &mf2);
1215 else
1216 printf("Binary files %s and %s differ\n",
1217 lbl[0], lbl[1]);
1218 o->found_changes = 1;
1220 else {
1221 /* Crazy xdl interfaces.. */
1222 const char *diffopts = getenv("GIT_DIFF_OPTS");
1223 xpparam_t xpp;
1224 xdemitconf_t xecfg;
1225 xdemitcb_t ecb;
1226 struct emit_callback ecbdata;
1228 memset(&ecbdata, 0, sizeof(ecbdata));
1229 ecbdata.label_path = lbl;
1230 ecbdata.color_diff = o->color_diff;
1231 ecbdata.found_changesp = &o->found_changes;
1232 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1233 xecfg.ctxlen = o->context;
1234 xecfg.flags = XDL_EMIT_FUNCNAMES;
1235 if (!diffopts)
1237 else if (!prefixcmp(diffopts, "--unified="))
1238 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1239 else if (!prefixcmp(diffopts, "-u"))
1240 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1241 ecb.outf = xdiff_outf;
1242 ecb.priv = &ecbdata;
1243 ecbdata.xm.consume = fn_out_consume;
1244 if (o->color_diff_words)
1245 ecbdata.diff_words =
1246 xcalloc(1, sizeof(struct diff_words_data));
1247 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1248 if (o->color_diff_words)
1249 free_diff_words_data(&ecbdata);
1252 free_ab_and_return:
1253 free(a_one);
1254 free(b_two);
1255 return;
1258 static void builtin_diffstat(const char *name_a, const char *name_b,
1259 struct diff_filespec *one,
1260 struct diff_filespec *two,
1261 struct diffstat_t *diffstat,
1262 struct diff_options *o,
1263 int complete_rewrite)
1265 mmfile_t mf1, mf2;
1266 struct diffstat_file *data;
1268 data = diffstat_add(diffstat, name_a, name_b);
1270 if (!one || !two) {
1271 data->is_unmerged = 1;
1272 return;
1274 if (complete_rewrite) {
1275 diff_populate_filespec(one, 0);
1276 diff_populate_filespec(two, 0);
1277 data->deleted = count_lines(one->data, one->size);
1278 data->added = count_lines(two->data, two->size);
1279 return;
1281 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1282 die("unable to read files to diff");
1284 if (file_is_binary(one) || file_is_binary(two)) {
1285 data->is_binary = 1;
1286 data->added = mf2.size;
1287 data->deleted = mf1.size;
1288 } else {
1289 /* Crazy xdl interfaces.. */
1290 xpparam_t xpp;
1291 xdemitconf_t xecfg;
1292 xdemitcb_t ecb;
1294 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1295 xecfg.ctxlen = 0;
1296 xecfg.flags = 0;
1297 ecb.outf = xdiff_outf;
1298 ecb.priv = diffstat;
1299 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1303 static void builtin_checkdiff(const char *name_a, const char *name_b,
1304 struct diff_filespec *one,
1305 struct diff_filespec *two, struct diff_options *o)
1307 mmfile_t mf1, mf2;
1308 struct checkdiff_t data;
1310 if (!two)
1311 return;
1313 memset(&data, 0, sizeof(data));
1314 data.xm.consume = checkdiff_consume;
1315 data.filename = name_b ? name_b : name_a;
1316 data.lineno = 0;
1317 data.color_diff = o->color_diff;
1319 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1320 die("unable to read files to diff");
1322 if (file_is_binary(two))
1323 return;
1324 else {
1325 /* Crazy xdl interfaces.. */
1326 xpparam_t xpp;
1327 xdemitconf_t xecfg;
1328 xdemitcb_t ecb;
1330 xpp.flags = XDF_NEED_MINIMAL;
1331 xecfg.ctxlen = 0;
1332 xecfg.flags = 0;
1333 ecb.outf = xdiff_outf;
1334 ecb.priv = &data;
1335 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1339 struct diff_filespec *alloc_filespec(const char *path)
1341 int namelen = strlen(path);
1342 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1344 memset(spec, 0, sizeof(*spec));
1345 spec->path = (char *)(spec + 1);
1346 memcpy(spec->path, path, namelen+1);
1347 return spec;
1350 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1351 unsigned short mode)
1353 if (mode) {
1354 spec->mode = canon_mode(mode);
1355 hashcpy(spec->sha1, sha1);
1356 spec->sha1_valid = !is_null_sha1(sha1);
1361 * Given a name and sha1 pair, if the dircache tells us the file in
1362 * the work tree has that object contents, return true, so that
1363 * prepare_temp_file() does not have to inflate and extract.
1365 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1367 struct cache_entry *ce;
1368 struct stat st;
1369 int pos, len;
1371 /* We do not read the cache ourselves here, because the
1372 * benchmark with my previous version that always reads cache
1373 * shows that it makes things worse for diff-tree comparing
1374 * two linux-2.6 kernel trees in an already checked out work
1375 * tree. This is because most diff-tree comparisons deal with
1376 * only a small number of files, while reading the cache is
1377 * expensive for a large project, and its cost outweighs the
1378 * savings we get by not inflating the object to a temporary
1379 * file. Practically, this code only helps when we are used
1380 * by diff-cache --cached, which does read the cache before
1381 * calling us.
1383 if (!active_cache)
1384 return 0;
1386 /* We want to avoid the working directory if our caller
1387 * doesn't need the data in a normal file, this system
1388 * is rather slow with its stat/open/mmap/close syscalls,
1389 * and the object is contained in a pack file. The pack
1390 * is probably already open and will be faster to obtain
1391 * the data through than the working directory. Loose
1392 * objects however would tend to be slower as they need
1393 * to be individually opened and inflated.
1395 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1396 return 0;
1398 len = strlen(name);
1399 pos = cache_name_pos(name, len);
1400 if (pos < 0)
1401 return 0;
1402 ce = active_cache[pos];
1403 if ((lstat(name, &st) < 0) ||
1404 !S_ISREG(st.st_mode) || /* careful! */
1405 ce_match_stat(ce, &st, 0) ||
1406 hashcmp(sha1, ce->sha1))
1407 return 0;
1408 /* we return 1 only when we can stat, it is a regular file,
1409 * stat information matches, and sha1 recorded in the cache
1410 * matches. I.e. we know the file in the work tree really is
1411 * the same as the <name, sha1> pair.
1413 return 1;
1416 static struct sha1_size_cache {
1417 unsigned char sha1[20];
1418 unsigned long size;
1419 } **sha1_size_cache;
1420 static int sha1_size_cache_nr, sha1_size_cache_alloc;
1422 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
1423 int find_only,
1424 unsigned long size)
1426 int first, last;
1427 struct sha1_size_cache *e;
1429 first = 0;
1430 last = sha1_size_cache_nr;
1431 while (last > first) {
1432 int cmp, next = (last + first) >> 1;
1433 e = sha1_size_cache[next];
1434 cmp = hashcmp(e->sha1, sha1);
1435 if (!cmp)
1436 return e;
1437 if (cmp < 0) {
1438 last = next;
1439 continue;
1441 first = next+1;
1443 /* not found */
1444 if (find_only)
1445 return NULL;
1446 /* insert to make it at "first" */
1447 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
1448 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
1449 sha1_size_cache = xrealloc(sha1_size_cache,
1450 sha1_size_cache_alloc *
1451 sizeof(*sha1_size_cache));
1453 sha1_size_cache_nr++;
1454 if (first < sha1_size_cache_nr)
1455 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
1456 (sha1_size_cache_nr - first - 1) *
1457 sizeof(*sha1_size_cache));
1458 e = xmalloc(sizeof(struct sha1_size_cache));
1459 sha1_size_cache[first] = e;
1460 hashcpy(e->sha1, sha1);
1461 e->size = size;
1462 return e;
1465 static int populate_from_stdin(struct diff_filespec *s)
1467 #define INCREMENT 1024
1468 char *buf;
1469 unsigned long size;
1470 int got;
1472 size = 0;
1473 buf = NULL;
1474 while (1) {
1475 buf = xrealloc(buf, size + INCREMENT);
1476 got = xread(0, buf + size, INCREMENT);
1477 if (!got)
1478 break; /* EOF */
1479 if (got < 0)
1480 return error("error while reading from stdin %s",
1481 strerror(errno));
1482 size += got;
1484 s->should_munmap = 0;
1485 s->data = buf;
1486 s->size = size;
1487 s->should_free = 1;
1488 return 0;
1491 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1493 int len;
1494 char *data = xmalloc(100);
1495 len = snprintf(data, 100,
1496 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1497 s->data = data;
1498 s->size = len;
1499 s->should_free = 1;
1500 if (size_only) {
1501 s->data = NULL;
1502 free(data);
1504 return 0;
1508 * While doing rename detection and pickaxe operation, we may need to
1509 * grab the data for the blob (or file) for our own in-core comparison.
1510 * diff_filespec has data and size fields for this purpose.
1512 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1514 int err = 0;
1515 if (!DIFF_FILE_VALID(s))
1516 die("internal error: asking to populate invalid file.");
1517 if (S_ISDIR(s->mode))
1518 return -1;
1520 if (!use_size_cache)
1521 size_only = 0;
1523 if (s->data)
1524 return err;
1526 if (S_ISDIRLNK(s->mode))
1527 return diff_populate_gitlink(s, size_only);
1529 if (!s->sha1_valid ||
1530 reuse_worktree_file(s->path, s->sha1, 0)) {
1531 struct stat st;
1532 int fd;
1533 char *buf;
1534 unsigned long size;
1536 if (!strcmp(s->path, "-"))
1537 return populate_from_stdin(s);
1539 if (lstat(s->path, &st) < 0) {
1540 if (errno == ENOENT) {
1541 err_empty:
1542 err = -1;
1543 empty:
1544 s->data = (char *)"";
1545 s->size = 0;
1546 return err;
1549 s->size = xsize_t(st.st_size);
1550 if (!s->size)
1551 goto empty;
1552 if (size_only)
1553 return 0;
1554 if (S_ISLNK(st.st_mode)) {
1555 int ret;
1556 s->data = xmalloc(s->size);
1557 s->should_free = 1;
1558 ret = readlink(s->path, s->data, s->size);
1559 if (ret < 0) {
1560 free(s->data);
1561 goto err_empty;
1563 return 0;
1565 fd = open(s->path, O_RDONLY);
1566 if (fd < 0)
1567 goto err_empty;
1568 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1569 close(fd);
1570 s->should_munmap = 1;
1573 * Convert from working tree format to canonical git format
1575 size = s->size;
1576 buf = convert_to_git(s->path, s->data, &size);
1577 if (buf) {
1578 munmap(s->data, s->size);
1579 s->should_munmap = 0;
1580 s->data = buf;
1581 s->size = size;
1582 s->should_free = 1;
1585 else {
1586 enum object_type type;
1587 struct sha1_size_cache *e;
1589 if (size_only && use_size_cache &&
1590 (e = locate_size_cache(s->sha1, 1, 0)) != NULL) {
1591 s->size = e->size;
1592 return 0;
1595 if (size_only) {
1596 type = sha1_object_info(s->sha1, &s->size);
1597 if (use_size_cache && 0 < type)
1598 locate_size_cache(s->sha1, 0, s->size);
1600 else {
1601 s->data = read_sha1_file(s->sha1, &type, &s->size);
1602 s->should_free = 1;
1605 return 0;
1608 void diff_free_filespec_data(struct diff_filespec *s)
1610 if (s->should_free)
1611 free(s->data);
1612 else if (s->should_munmap)
1613 munmap(s->data, s->size);
1614 s->should_free = s->should_munmap = 0;
1615 s->data = NULL;
1616 free(s->cnt_data);
1617 s->cnt_data = NULL;
1620 static void prep_temp_blob(struct diff_tempfile *temp,
1621 void *blob,
1622 unsigned long size,
1623 const unsigned char *sha1,
1624 int mode)
1626 int fd;
1628 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1629 if (fd < 0)
1630 die("unable to create temp-file");
1631 if (write_in_full(fd, blob, size) != size)
1632 die("unable to write temp-file");
1633 close(fd);
1634 temp->name = temp->tmp_path;
1635 strcpy(temp->hex, sha1_to_hex(sha1));
1636 temp->hex[40] = 0;
1637 sprintf(temp->mode, "%06o", mode);
1640 static void prepare_temp_file(const char *name,
1641 struct diff_tempfile *temp,
1642 struct diff_filespec *one)
1644 if (!DIFF_FILE_VALID(one)) {
1645 not_a_valid_file:
1646 /* A '-' entry produces this for file-2, and
1647 * a '+' entry produces this for file-1.
1649 temp->name = "/dev/null";
1650 strcpy(temp->hex, ".");
1651 strcpy(temp->mode, ".");
1652 return;
1655 if (!one->sha1_valid ||
1656 reuse_worktree_file(name, one->sha1, 1)) {
1657 struct stat st;
1658 if (lstat(name, &st) < 0) {
1659 if (errno == ENOENT)
1660 goto not_a_valid_file;
1661 die("stat(%s): %s", name, strerror(errno));
1663 if (S_ISLNK(st.st_mode)) {
1664 int ret;
1665 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1666 size_t sz = xsize_t(st.st_size);
1667 if (sizeof(buf) <= st.st_size)
1668 die("symlink too long: %s", name);
1669 ret = readlink(name, buf, sz);
1670 if (ret < 0)
1671 die("readlink(%s)", name);
1672 prep_temp_blob(temp, buf, sz,
1673 (one->sha1_valid ?
1674 one->sha1 : null_sha1),
1675 (one->sha1_valid ?
1676 one->mode : S_IFLNK));
1678 else {
1679 /* we can borrow from the file in the work tree */
1680 temp->name = name;
1681 if (!one->sha1_valid)
1682 strcpy(temp->hex, sha1_to_hex(null_sha1));
1683 else
1684 strcpy(temp->hex, sha1_to_hex(one->sha1));
1685 /* Even though we may sometimes borrow the
1686 * contents from the work tree, we always want
1687 * one->mode. mode is trustworthy even when
1688 * !(one->sha1_valid), as long as
1689 * DIFF_FILE_VALID(one).
1691 sprintf(temp->mode, "%06o", one->mode);
1693 return;
1695 else {
1696 if (diff_populate_filespec(one, 0))
1697 die("cannot read data blob for %s", one->path);
1698 prep_temp_blob(temp, one->data, one->size,
1699 one->sha1, one->mode);
1703 static void remove_tempfile(void)
1705 int i;
1707 for (i = 0; i < 2; i++)
1708 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1709 unlink(diff_temp[i].name);
1710 diff_temp[i].name = NULL;
1714 static void remove_tempfile_on_signal(int signo)
1716 remove_tempfile();
1717 signal(SIGINT, SIG_DFL);
1718 raise(signo);
1721 static int spawn_prog(const char *pgm, const char **arg)
1723 pid_t pid;
1724 int status;
1726 fflush(NULL);
1727 pid = fork();
1728 if (pid < 0)
1729 die("unable to fork");
1730 if (!pid) {
1731 execvp(pgm, (char *const*) arg);
1732 exit(255);
1735 while (waitpid(pid, &status, 0) < 0) {
1736 if (errno == EINTR)
1737 continue;
1738 return -1;
1741 /* Earlier we did not check the exit status because
1742 * diff exits non-zero if files are different, and
1743 * we are not interested in knowing that. It was a
1744 * mistake which made it harder to quit a diff-*
1745 * session that uses the git-apply-patch-script as
1746 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1747 * should also exit non-zero only when it wants to
1748 * abort the entire diff-* session.
1750 if (WIFEXITED(status) && !WEXITSTATUS(status))
1751 return 0;
1752 return -1;
1755 /* An external diff command takes:
1757 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1758 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1761 static void run_external_diff(const char *pgm,
1762 const char *name,
1763 const char *other,
1764 struct diff_filespec *one,
1765 struct diff_filespec *two,
1766 const char *xfrm_msg,
1767 int complete_rewrite)
1769 const char *spawn_arg[10];
1770 struct diff_tempfile *temp = diff_temp;
1771 int retval;
1772 static int atexit_asked = 0;
1773 const char *othername;
1774 const char **arg = &spawn_arg[0];
1776 othername = (other? other : name);
1777 if (one && two) {
1778 prepare_temp_file(name, &temp[0], one);
1779 prepare_temp_file(othername, &temp[1], two);
1780 if (! atexit_asked &&
1781 (temp[0].name == temp[0].tmp_path ||
1782 temp[1].name == temp[1].tmp_path)) {
1783 atexit_asked = 1;
1784 atexit(remove_tempfile);
1786 signal(SIGINT, remove_tempfile_on_signal);
1789 if (one && two) {
1790 *arg++ = pgm;
1791 *arg++ = name;
1792 *arg++ = temp[0].name;
1793 *arg++ = temp[0].hex;
1794 *arg++ = temp[0].mode;
1795 *arg++ = temp[1].name;
1796 *arg++ = temp[1].hex;
1797 *arg++ = temp[1].mode;
1798 if (other) {
1799 *arg++ = other;
1800 *arg++ = xfrm_msg;
1802 } else {
1803 *arg++ = pgm;
1804 *arg++ = name;
1806 *arg = NULL;
1807 retval = spawn_prog(pgm, spawn_arg);
1808 remove_tempfile();
1809 if (retval) {
1810 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1811 exit(1);
1815 static const char *external_diff_attr(const char *name)
1817 struct git_attr_check attr_diff_check;
1819 setup_diff_attr_check(&attr_diff_check);
1820 if (!git_checkattr(name, 1, &attr_diff_check)) {
1821 const char *value = attr_diff_check.value;
1822 if (!ATTR_TRUE(value) &&
1823 !ATTR_FALSE(value) &&
1824 !ATTR_UNSET(value)) {
1825 struct ll_diff_driver *drv;
1827 if (!user_diff_tail) {
1828 user_diff_tail = &user_diff;
1829 git_config(git_diff_ui_config);
1831 for (drv = user_diff; drv; drv = drv->next)
1832 if (!strcmp(drv->name, value))
1833 return drv->cmd;
1836 return NULL;
1839 static void run_diff_cmd(const char *pgm,
1840 const char *name,
1841 const char *other,
1842 struct diff_filespec *one,
1843 struct diff_filespec *two,
1844 const char *xfrm_msg,
1845 struct diff_options *o,
1846 int complete_rewrite)
1848 if (!o->allow_external)
1849 pgm = NULL;
1850 else {
1851 const char *cmd = external_diff_attr(name);
1852 if (cmd)
1853 pgm = cmd;
1856 if (pgm) {
1857 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1858 complete_rewrite);
1859 return;
1861 if (one && two)
1862 builtin_diff(name, other ? other : name,
1863 one, two, xfrm_msg, o, complete_rewrite);
1864 else
1865 printf("* Unmerged path %s\n", name);
1868 static void diff_fill_sha1_info(struct diff_filespec *one)
1870 if (DIFF_FILE_VALID(one)) {
1871 if (!one->sha1_valid) {
1872 struct stat st;
1873 if (!strcmp(one->path, "-")) {
1874 hashcpy(one->sha1, null_sha1);
1875 return;
1877 if (lstat(one->path, &st) < 0)
1878 die("stat %s", one->path);
1879 if (index_path(one->sha1, one->path, &st, 0))
1880 die("cannot hash %s\n", one->path);
1883 else
1884 hashclr(one->sha1);
1887 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1889 const char *pgm = external_diff();
1890 char msg[PATH_MAX*2+300], *xfrm_msg;
1891 struct diff_filespec *one;
1892 struct diff_filespec *two;
1893 const char *name;
1894 const char *other;
1895 char *name_munged, *other_munged;
1896 int complete_rewrite = 0;
1897 int len;
1899 if (DIFF_PAIR_UNMERGED(p)) {
1900 /* unmerged */
1901 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1902 return;
1905 name = p->one->path;
1906 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1907 name_munged = quote_one(name);
1908 other_munged = quote_one(other);
1909 one = p->one; two = p->two;
1911 diff_fill_sha1_info(one);
1912 diff_fill_sha1_info(two);
1914 len = 0;
1915 switch (p->status) {
1916 case DIFF_STATUS_COPIED:
1917 len += snprintf(msg + len, sizeof(msg) - len,
1918 "similarity index %d%%\n"
1919 "copy from %s\n"
1920 "copy to %s\n",
1921 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1922 name_munged, other_munged);
1923 break;
1924 case DIFF_STATUS_RENAMED:
1925 len += snprintf(msg + len, sizeof(msg) - len,
1926 "similarity index %d%%\n"
1927 "rename from %s\n"
1928 "rename to %s\n",
1929 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1930 name_munged, other_munged);
1931 break;
1932 case DIFF_STATUS_MODIFIED:
1933 if (p->score) {
1934 len += snprintf(msg + len, sizeof(msg) - len,
1935 "dissimilarity index %d%%\n",
1936 (int)(0.5 + p->score *
1937 100.0/MAX_SCORE));
1938 complete_rewrite = 1;
1939 break;
1941 /* fallthru */
1942 default:
1943 /* nothing */
1947 if (hashcmp(one->sha1, two->sha1)) {
1948 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1950 if (o->binary) {
1951 mmfile_t mf;
1952 if ((!fill_mmfile(&mf, one) && file_is_binary(one)) ||
1953 (!fill_mmfile(&mf, two) && file_is_binary(two)))
1954 abbrev = 40;
1956 len += snprintf(msg + len, sizeof(msg) - len,
1957 "index %.*s..%.*s",
1958 abbrev, sha1_to_hex(one->sha1),
1959 abbrev, sha1_to_hex(two->sha1));
1960 if (one->mode == two->mode)
1961 len += snprintf(msg + len, sizeof(msg) - len,
1962 " %06o", one->mode);
1963 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1966 if (len)
1967 msg[--len] = 0;
1968 xfrm_msg = len ? msg : NULL;
1970 if (!pgm &&
1971 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1972 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1973 /* a filepair that changes between file and symlink
1974 * needs to be split into deletion and creation.
1976 struct diff_filespec *null = alloc_filespec(two->path);
1977 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1978 free(null);
1979 null = alloc_filespec(one->path);
1980 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1981 free(null);
1983 else
1984 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1985 complete_rewrite);
1987 free(name_munged);
1988 free(other_munged);
1991 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1992 struct diffstat_t *diffstat)
1994 const char *name;
1995 const char *other;
1996 int complete_rewrite = 0;
1998 if (DIFF_PAIR_UNMERGED(p)) {
1999 /* unmerged */
2000 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2001 return;
2004 name = p->one->path;
2005 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2007 diff_fill_sha1_info(p->one);
2008 diff_fill_sha1_info(p->two);
2010 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2011 complete_rewrite = 1;
2012 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2015 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2017 const char *name;
2018 const char *other;
2020 if (DIFF_PAIR_UNMERGED(p)) {
2021 /* unmerged */
2022 return;
2025 name = p->one->path;
2026 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2028 diff_fill_sha1_info(p->one);
2029 diff_fill_sha1_info(p->two);
2031 builtin_checkdiff(name, other, p->one, p->two, o);
2034 void diff_setup(struct diff_options *options)
2036 memset(options, 0, sizeof(*options));
2037 options->line_termination = '\n';
2038 options->break_opt = -1;
2039 options->rename_limit = -1;
2040 options->context = 3;
2041 options->msg_sep = "";
2043 options->change = diff_change;
2044 options->add_remove = diff_addremove;
2045 options->color_diff = diff_use_color_default;
2046 options->detect_rename = diff_detect_rename_default;
2049 int diff_setup_done(struct diff_options *options)
2051 int count = 0;
2053 if (options->output_format & DIFF_FORMAT_NAME)
2054 count++;
2055 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2056 count++;
2057 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2058 count++;
2059 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2060 count++;
2061 if (count > 1)
2062 die("--name-only, --name-status, --check and -s are mutually exclusive");
2064 if (options->find_copies_harder)
2065 options->detect_rename = DIFF_DETECT_COPY;
2067 if (options->output_format & (DIFF_FORMAT_NAME |
2068 DIFF_FORMAT_NAME_STATUS |
2069 DIFF_FORMAT_CHECKDIFF |
2070 DIFF_FORMAT_NO_OUTPUT))
2071 options->output_format &= ~(DIFF_FORMAT_RAW |
2072 DIFF_FORMAT_NUMSTAT |
2073 DIFF_FORMAT_DIFFSTAT |
2074 DIFF_FORMAT_SHORTSTAT |
2075 DIFF_FORMAT_SUMMARY |
2076 DIFF_FORMAT_PATCH);
2079 * These cases always need recursive; we do not drop caller-supplied
2080 * recursive bits for other formats here.
2082 if (options->output_format & (DIFF_FORMAT_PATCH |
2083 DIFF_FORMAT_NUMSTAT |
2084 DIFF_FORMAT_DIFFSTAT |
2085 DIFF_FORMAT_SHORTSTAT |
2086 DIFF_FORMAT_SUMMARY |
2087 DIFF_FORMAT_CHECKDIFF))
2088 options->recursive = 1;
2090 * Also pickaxe would not work very well if you do not say recursive
2092 if (options->pickaxe)
2093 options->recursive = 1;
2095 if (options->detect_rename && options->rename_limit < 0)
2096 options->rename_limit = diff_rename_limit_default;
2097 if (options->setup & DIFF_SETUP_USE_CACHE) {
2098 if (!active_cache)
2099 /* read-cache does not die even when it fails
2100 * so it is safe for us to do this here. Also
2101 * it does not smudge active_cache or active_nr
2102 * when it fails, so we do not have to worry about
2103 * cleaning it up ourselves either.
2105 read_cache();
2107 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
2108 use_size_cache = 1;
2109 if (options->abbrev <= 0 || 40 < options->abbrev)
2110 options->abbrev = 40; /* full */
2113 * It does not make sense to show the first hit we happened
2114 * to have found. It does not make sense not to return with
2115 * exit code in such a case either.
2117 if (options->quiet) {
2118 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2119 options->exit_with_status = 1;
2123 * If we postprocess in diffcore, we cannot simply return
2124 * upon the first hit. We need to run diff as usual.
2126 if (options->pickaxe || options->filter)
2127 options->quiet = 0;
2129 return 0;
2132 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2134 char c, *eq;
2135 int len;
2137 if (*arg != '-')
2138 return 0;
2139 c = *++arg;
2140 if (!c)
2141 return 0;
2142 if (c == arg_short) {
2143 c = *++arg;
2144 if (!c)
2145 return 1;
2146 if (val && isdigit(c)) {
2147 char *end;
2148 int n = strtoul(arg, &end, 10);
2149 if (*end)
2150 return 0;
2151 *val = n;
2152 return 1;
2154 return 0;
2156 if (c != '-')
2157 return 0;
2158 arg++;
2159 eq = strchr(arg, '=');
2160 if (eq)
2161 len = eq - arg;
2162 else
2163 len = strlen(arg);
2164 if (!len || strncmp(arg, arg_long, len))
2165 return 0;
2166 if (eq) {
2167 int n;
2168 char *end;
2169 if (!isdigit(*++eq))
2170 return 0;
2171 n = strtoul(eq, &end, 10);
2172 if (*end)
2173 return 0;
2174 *val = n;
2176 return 1;
2179 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2181 const char *arg = av[0];
2182 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2183 options->output_format |= DIFF_FORMAT_PATCH;
2184 else if (opt_arg(arg, 'U', "unified", &options->context))
2185 options->output_format |= DIFF_FORMAT_PATCH;
2186 else if (!strcmp(arg, "--raw"))
2187 options->output_format |= DIFF_FORMAT_RAW;
2188 else if (!strcmp(arg, "--patch-with-raw")) {
2189 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2191 else if (!strcmp(arg, "--numstat")) {
2192 options->output_format |= DIFF_FORMAT_NUMSTAT;
2194 else if (!strcmp(arg, "--shortstat")) {
2195 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2197 else if (!prefixcmp(arg, "--stat")) {
2198 char *end;
2199 int width = options->stat_width;
2200 int name_width = options->stat_name_width;
2201 arg += 6;
2202 end = (char *)arg;
2204 switch (*arg) {
2205 case '-':
2206 if (!prefixcmp(arg, "-width="))
2207 width = strtoul(arg + 7, &end, 10);
2208 else if (!prefixcmp(arg, "-name-width="))
2209 name_width = strtoul(arg + 12, &end, 10);
2210 break;
2211 case '=':
2212 width = strtoul(arg+1, &end, 10);
2213 if (*end == ',')
2214 name_width = strtoul(end+1, &end, 10);
2217 /* Important! This checks all the error cases! */
2218 if (*end)
2219 return 0;
2220 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2221 options->stat_name_width = name_width;
2222 options->stat_width = width;
2224 else if (!strcmp(arg, "--check"))
2225 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2226 else if (!strcmp(arg, "--summary"))
2227 options->output_format |= DIFF_FORMAT_SUMMARY;
2228 else if (!strcmp(arg, "--patch-with-stat")) {
2229 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2231 else if (!strcmp(arg, "-z"))
2232 options->line_termination = 0;
2233 else if (!prefixcmp(arg, "-l"))
2234 options->rename_limit = strtoul(arg+2, NULL, 10);
2235 else if (!strcmp(arg, "--full-index"))
2236 options->full_index = 1;
2237 else if (!strcmp(arg, "--binary")) {
2238 options->output_format |= DIFF_FORMAT_PATCH;
2239 options->binary = 1;
2241 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
2242 options->text = 1;
2244 else if (!strcmp(arg, "--name-only"))
2245 options->output_format |= DIFF_FORMAT_NAME;
2246 else if (!strcmp(arg, "--name-status"))
2247 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2248 else if (!strcmp(arg, "-R"))
2249 options->reverse_diff = 1;
2250 else if (!prefixcmp(arg, "-S"))
2251 options->pickaxe = arg + 2;
2252 else if (!strcmp(arg, "-s")) {
2253 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2255 else if (!prefixcmp(arg, "-O"))
2256 options->orderfile = arg + 2;
2257 else if (!prefixcmp(arg, "--diff-filter="))
2258 options->filter = arg + 14;
2259 else if (!strcmp(arg, "--pickaxe-all"))
2260 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2261 else if (!strcmp(arg, "--pickaxe-regex"))
2262 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2263 else if (!prefixcmp(arg, "-B")) {
2264 if ((options->break_opt =
2265 diff_scoreopt_parse(arg)) == -1)
2266 return -1;
2268 else if (!prefixcmp(arg, "-M")) {
2269 if ((options->rename_score =
2270 diff_scoreopt_parse(arg)) == -1)
2271 return -1;
2272 options->detect_rename = DIFF_DETECT_RENAME;
2274 else if (!prefixcmp(arg, "-C")) {
2275 if ((options->rename_score =
2276 diff_scoreopt_parse(arg)) == -1)
2277 return -1;
2278 options->detect_rename = DIFF_DETECT_COPY;
2280 else if (!strcmp(arg, "--find-copies-harder"))
2281 options->find_copies_harder = 1;
2282 else if (!strcmp(arg, "--abbrev"))
2283 options->abbrev = DEFAULT_ABBREV;
2284 else if (!prefixcmp(arg, "--abbrev=")) {
2285 options->abbrev = strtoul(arg + 9, NULL, 10);
2286 if (options->abbrev < MINIMUM_ABBREV)
2287 options->abbrev = MINIMUM_ABBREV;
2288 else if (40 < options->abbrev)
2289 options->abbrev = 40;
2291 else if (!strcmp(arg, "--color"))
2292 options->color_diff = 1;
2293 else if (!strcmp(arg, "--no-color"))
2294 options->color_diff = 0;
2295 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2296 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2297 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2298 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2299 else if (!strcmp(arg, "--ignore-space-at-eol"))
2300 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2301 else if (!strcmp(arg, "--color-words"))
2302 options->color_diff = options->color_diff_words = 1;
2303 else if (!strcmp(arg, "--no-renames"))
2304 options->detect_rename = 0;
2305 else if (!strcmp(arg, "--exit-code"))
2306 options->exit_with_status = 1;
2307 else if (!strcmp(arg, "--quiet"))
2308 options->quiet = 1;
2309 else
2310 return 0;
2311 return 1;
2314 static int parse_num(const char **cp_p)
2316 unsigned long num, scale;
2317 int ch, dot;
2318 const char *cp = *cp_p;
2320 num = 0;
2321 scale = 1;
2322 dot = 0;
2323 for(;;) {
2324 ch = *cp;
2325 if ( !dot && ch == '.' ) {
2326 scale = 1;
2327 dot = 1;
2328 } else if ( ch == '%' ) {
2329 scale = dot ? scale*100 : 100;
2330 cp++; /* % is always at the end */
2331 break;
2332 } else if ( ch >= '0' && ch <= '9' ) {
2333 if ( scale < 100000 ) {
2334 scale *= 10;
2335 num = (num*10) + (ch-'0');
2337 } else {
2338 break;
2340 cp++;
2342 *cp_p = cp;
2344 /* user says num divided by scale and we say internally that
2345 * is MAX_SCORE * num / scale.
2347 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2350 int diff_scoreopt_parse(const char *opt)
2352 int opt1, opt2, cmd;
2354 if (*opt++ != '-')
2355 return -1;
2356 cmd = *opt++;
2357 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2358 return -1; /* that is not a -M, -C nor -B option */
2360 opt1 = parse_num(&opt);
2361 if (cmd != 'B')
2362 opt2 = 0;
2363 else {
2364 if (*opt == 0)
2365 opt2 = 0;
2366 else if (*opt != '/')
2367 return -1; /* we expect -B80/99 or -B80 */
2368 else {
2369 opt++;
2370 opt2 = parse_num(&opt);
2373 if (*opt != 0)
2374 return -1;
2375 return opt1 | (opt2 << 16);
2378 struct diff_queue_struct diff_queued_diff;
2380 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2382 if (queue->alloc <= queue->nr) {
2383 queue->alloc = alloc_nr(queue->alloc);
2384 queue->queue = xrealloc(queue->queue,
2385 sizeof(dp) * queue->alloc);
2387 queue->queue[queue->nr++] = dp;
2390 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2391 struct diff_filespec *one,
2392 struct diff_filespec *two)
2394 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2395 dp->one = one;
2396 dp->two = two;
2397 if (queue)
2398 diff_q(queue, dp);
2399 return dp;
2402 void diff_free_filepair(struct diff_filepair *p)
2404 diff_free_filespec_data(p->one);
2405 diff_free_filespec_data(p->two);
2406 free(p->one);
2407 free(p->two);
2408 free(p);
2411 /* This is different from find_unique_abbrev() in that
2412 * it stuffs the result with dots for alignment.
2414 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2416 int abblen;
2417 const char *abbrev;
2418 if (len == 40)
2419 return sha1_to_hex(sha1);
2421 abbrev = find_unique_abbrev(sha1, len);
2422 if (!abbrev)
2423 return sha1_to_hex(sha1);
2424 abblen = strlen(abbrev);
2425 if (abblen < 37) {
2426 static char hex[41];
2427 if (len < abblen && abblen <= len + 2)
2428 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2429 else
2430 sprintf(hex, "%s...", abbrev);
2431 return hex;
2433 return sha1_to_hex(sha1);
2436 static void diff_flush_raw(struct diff_filepair *p,
2437 struct diff_options *options)
2439 int two_paths;
2440 char status[10];
2441 int abbrev = options->abbrev;
2442 const char *path_one, *path_two;
2443 int inter_name_termination = '\t';
2444 int line_termination = options->line_termination;
2446 if (!line_termination)
2447 inter_name_termination = 0;
2449 path_one = p->one->path;
2450 path_two = p->two->path;
2451 if (line_termination) {
2452 path_one = quote_one(path_one);
2453 path_two = quote_one(path_two);
2456 if (p->score)
2457 sprintf(status, "%c%03d", p->status,
2458 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2459 else {
2460 status[0] = p->status;
2461 status[1] = 0;
2463 switch (p->status) {
2464 case DIFF_STATUS_COPIED:
2465 case DIFF_STATUS_RENAMED:
2466 two_paths = 1;
2467 break;
2468 case DIFF_STATUS_ADDED:
2469 case DIFF_STATUS_DELETED:
2470 two_paths = 0;
2471 break;
2472 default:
2473 two_paths = 0;
2474 break;
2476 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2477 printf(":%06o %06o %s ",
2478 p->one->mode, p->two->mode,
2479 diff_unique_abbrev(p->one->sha1, abbrev));
2480 printf("%s ",
2481 diff_unique_abbrev(p->two->sha1, abbrev));
2483 printf("%s%c%s", status, inter_name_termination, path_one);
2484 if (two_paths)
2485 printf("%c%s", inter_name_termination, path_two);
2486 putchar(line_termination);
2487 if (path_one != p->one->path)
2488 free((void*)path_one);
2489 if (path_two != p->two->path)
2490 free((void*)path_two);
2493 static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2495 char *path = p->two->path;
2497 if (opt->line_termination)
2498 path = quote_one(p->two->path);
2499 printf("%s%c", path, opt->line_termination);
2500 if (p->two->path != path)
2501 free(path);
2504 int diff_unmodified_pair(struct diff_filepair *p)
2506 /* This function is written stricter than necessary to support
2507 * the currently implemented transformers, but the idea is to
2508 * let transformers to produce diff_filepairs any way they want,
2509 * and filter and clean them up here before producing the output.
2511 struct diff_filespec *one, *two;
2513 if (DIFF_PAIR_UNMERGED(p))
2514 return 0; /* unmerged is interesting */
2516 one = p->one;
2517 two = p->two;
2519 /* deletion, addition, mode or type change
2520 * and rename are all interesting.
2522 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2523 DIFF_PAIR_MODE_CHANGED(p) ||
2524 strcmp(one->path, two->path))
2525 return 0;
2527 /* both are valid and point at the same path. that is, we are
2528 * dealing with a change.
2530 if (one->sha1_valid && two->sha1_valid &&
2531 !hashcmp(one->sha1, two->sha1))
2532 return 1; /* no change */
2533 if (!one->sha1_valid && !two->sha1_valid)
2534 return 1; /* both look at the same file on the filesystem. */
2535 return 0;
2538 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2540 if (diff_unmodified_pair(p))
2541 return;
2543 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2544 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2545 return; /* no tree diffs in patch format */
2547 run_diff(p, o);
2550 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2551 struct diffstat_t *diffstat)
2553 if (diff_unmodified_pair(p))
2554 return;
2556 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2557 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2558 return; /* no tree diffs in patch format */
2560 run_diffstat(p, o, diffstat);
2563 static void diff_flush_checkdiff(struct diff_filepair *p,
2564 struct diff_options *o)
2566 if (diff_unmodified_pair(p))
2567 return;
2569 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2570 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2571 return; /* no tree diffs in patch format */
2573 run_checkdiff(p, o);
2576 int diff_queue_is_empty(void)
2578 struct diff_queue_struct *q = &diff_queued_diff;
2579 int i;
2580 for (i = 0; i < q->nr; i++)
2581 if (!diff_unmodified_pair(q->queue[i]))
2582 return 0;
2583 return 1;
2586 #if DIFF_DEBUG
2587 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2589 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2590 x, one ? one : "",
2591 s->path,
2592 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2593 s->mode,
2594 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2595 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2596 x, one ? one : "",
2597 s->size, s->xfrm_flags);
2600 void diff_debug_filepair(const struct diff_filepair *p, int i)
2602 diff_debug_filespec(p->one, i, "one");
2603 diff_debug_filespec(p->two, i, "two");
2604 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2605 p->score, p->status ? p->status : '?',
2606 p->source_stays, p->broken_pair);
2609 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2611 int i;
2612 if (msg)
2613 fprintf(stderr, "%s\n", msg);
2614 fprintf(stderr, "q->nr = %d\n", q->nr);
2615 for (i = 0; i < q->nr; i++) {
2616 struct diff_filepair *p = q->queue[i];
2617 diff_debug_filepair(p, i);
2620 #endif
2622 static void diff_resolve_rename_copy(void)
2624 int i, j;
2625 struct diff_filepair *p, *pp;
2626 struct diff_queue_struct *q = &diff_queued_diff;
2628 diff_debug_queue("resolve-rename-copy", q);
2630 for (i = 0; i < q->nr; i++) {
2631 p = q->queue[i];
2632 p->status = 0; /* undecided */
2633 if (DIFF_PAIR_UNMERGED(p))
2634 p->status = DIFF_STATUS_UNMERGED;
2635 else if (!DIFF_FILE_VALID(p->one))
2636 p->status = DIFF_STATUS_ADDED;
2637 else if (!DIFF_FILE_VALID(p->two))
2638 p->status = DIFF_STATUS_DELETED;
2639 else if (DIFF_PAIR_TYPE_CHANGED(p))
2640 p->status = DIFF_STATUS_TYPE_CHANGED;
2642 /* from this point on, we are dealing with a pair
2643 * whose both sides are valid and of the same type, i.e.
2644 * either in-place edit or rename/copy edit.
2646 else if (DIFF_PAIR_RENAME(p)) {
2647 if (p->source_stays) {
2648 p->status = DIFF_STATUS_COPIED;
2649 continue;
2651 /* See if there is some other filepair that
2652 * copies from the same source as us. If so
2653 * we are a copy. Otherwise we are either a
2654 * copy if the path stays, or a rename if it
2655 * does not, but we already handled "stays" case.
2657 for (j = i + 1; j < q->nr; j++) {
2658 pp = q->queue[j];
2659 if (strcmp(pp->one->path, p->one->path))
2660 continue; /* not us */
2661 if (!DIFF_PAIR_RENAME(pp))
2662 continue; /* not a rename/copy */
2663 /* pp is a rename/copy from the same source */
2664 p->status = DIFF_STATUS_COPIED;
2665 break;
2667 if (!p->status)
2668 p->status = DIFF_STATUS_RENAMED;
2670 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2671 p->one->mode != p->two->mode ||
2672 is_null_sha1(p->one->sha1))
2673 p->status = DIFF_STATUS_MODIFIED;
2674 else {
2675 /* This is a "no-change" entry and should not
2676 * happen anymore, but prepare for broken callers.
2678 error("feeding unmodified %s to diffcore",
2679 p->one->path);
2680 p->status = DIFF_STATUS_UNKNOWN;
2683 diff_debug_queue("resolve-rename-copy done", q);
2686 static int check_pair_status(struct diff_filepair *p)
2688 switch (p->status) {
2689 case DIFF_STATUS_UNKNOWN:
2690 return 0;
2691 case 0:
2692 die("internal error in diff-resolve-rename-copy");
2693 default:
2694 return 1;
2698 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2700 int fmt = opt->output_format;
2702 if (fmt & DIFF_FORMAT_CHECKDIFF)
2703 diff_flush_checkdiff(p, opt);
2704 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2705 diff_flush_raw(p, opt);
2706 else if (fmt & DIFF_FORMAT_NAME)
2707 diff_flush_name(p, opt);
2710 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2712 char *name = quote_one(fs->path);
2713 if (fs->mode)
2714 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2715 else
2716 printf(" %s %s\n", newdelete, name);
2717 free(name);
2721 static void show_mode_change(struct diff_filepair *p, int show_name)
2723 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2724 if (show_name) {
2725 char *name = quote_one(p->two->path);
2726 printf(" mode change %06o => %06o %s\n",
2727 p->one->mode, p->two->mode, name);
2728 free(name);
2730 else
2731 printf(" mode change %06o => %06o\n",
2732 p->one->mode, p->two->mode);
2736 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2738 char *names = pprint_rename(p->one->path, p->two->path);
2740 printf(" %s %s (%d%%)\n", renamecopy, names,
2741 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2742 free(names);
2743 show_mode_change(p, 0);
2746 static void diff_summary(struct diff_filepair *p)
2748 switch(p->status) {
2749 case DIFF_STATUS_DELETED:
2750 show_file_mode_name("delete", p->one);
2751 break;
2752 case DIFF_STATUS_ADDED:
2753 show_file_mode_name("create", p->two);
2754 break;
2755 case DIFF_STATUS_COPIED:
2756 show_rename_copy("copy", p);
2757 break;
2758 case DIFF_STATUS_RENAMED:
2759 show_rename_copy("rename", p);
2760 break;
2761 default:
2762 if (p->score) {
2763 char *name = quote_one(p->two->path);
2764 printf(" rewrite %s (%d%%)\n", name,
2765 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2766 free(name);
2767 show_mode_change(p, 0);
2768 } else show_mode_change(p, 1);
2769 break;
2773 struct patch_id_t {
2774 struct xdiff_emit_state xm;
2775 SHA_CTX *ctx;
2776 int patchlen;
2779 static int remove_space(char *line, int len)
2781 int i;
2782 char *dst = line;
2783 unsigned char c;
2785 for (i = 0; i < len; i++)
2786 if (!isspace((c = line[i])))
2787 *dst++ = c;
2789 return dst - line;
2792 static void patch_id_consume(void *priv, char *line, unsigned long len)
2794 struct patch_id_t *data = priv;
2795 int new_len;
2797 /* Ignore line numbers when computing the SHA1 of the patch */
2798 if (!prefixcmp(line, "@@ -"))
2799 return;
2801 new_len = remove_space(line, len);
2803 SHA1_Update(data->ctx, line, new_len);
2804 data->patchlen += new_len;
2807 /* returns 0 upon success, and writes result into sha1 */
2808 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2810 struct diff_queue_struct *q = &diff_queued_diff;
2811 int i;
2812 SHA_CTX ctx;
2813 struct patch_id_t data;
2814 char buffer[PATH_MAX * 4 + 20];
2816 SHA1_Init(&ctx);
2817 memset(&data, 0, sizeof(struct patch_id_t));
2818 data.ctx = &ctx;
2819 data.xm.consume = patch_id_consume;
2821 for (i = 0; i < q->nr; i++) {
2822 xpparam_t xpp;
2823 xdemitconf_t xecfg;
2824 xdemitcb_t ecb;
2825 mmfile_t mf1, mf2;
2826 struct diff_filepair *p = q->queue[i];
2827 int len1, len2;
2829 if (p->status == 0)
2830 return error("internal diff status error");
2831 if (p->status == DIFF_STATUS_UNKNOWN)
2832 continue;
2833 if (diff_unmodified_pair(p))
2834 continue;
2835 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2836 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2837 continue;
2838 if (DIFF_PAIR_UNMERGED(p))
2839 continue;
2841 diff_fill_sha1_info(p->one);
2842 diff_fill_sha1_info(p->two);
2843 if (fill_mmfile(&mf1, p->one) < 0 ||
2844 fill_mmfile(&mf2, p->two) < 0)
2845 return error("unable to read files to diff");
2847 /* Maybe hash p->two? into the patch id? */
2848 if (file_is_binary(p->two))
2849 continue;
2851 len1 = remove_space(p->one->path, strlen(p->one->path));
2852 len2 = remove_space(p->two->path, strlen(p->two->path));
2853 if (p->one->mode == 0)
2854 len1 = snprintf(buffer, sizeof(buffer),
2855 "diff--gita/%.*sb/%.*s"
2856 "newfilemode%06o"
2857 "---/dev/null"
2858 "+++b/%.*s",
2859 len1, p->one->path,
2860 len2, p->two->path,
2861 p->two->mode,
2862 len2, p->two->path);
2863 else if (p->two->mode == 0)
2864 len1 = snprintf(buffer, sizeof(buffer),
2865 "diff--gita/%.*sb/%.*s"
2866 "deletedfilemode%06o"
2867 "---a/%.*s"
2868 "+++/dev/null",
2869 len1, p->one->path,
2870 len2, p->two->path,
2871 p->one->mode,
2872 len1, p->one->path);
2873 else
2874 len1 = snprintf(buffer, sizeof(buffer),
2875 "diff--gita/%.*sb/%.*s"
2876 "---a/%.*s"
2877 "+++b/%.*s",
2878 len1, p->one->path,
2879 len2, p->two->path,
2880 len1, p->one->path,
2881 len2, p->two->path);
2882 SHA1_Update(&ctx, buffer, len1);
2884 xpp.flags = XDF_NEED_MINIMAL;
2885 xecfg.ctxlen = 3;
2886 xecfg.flags = XDL_EMIT_FUNCNAMES;
2887 ecb.outf = xdiff_outf;
2888 ecb.priv = &data;
2889 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2892 SHA1_Final(sha1, &ctx);
2893 return 0;
2896 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2898 struct diff_queue_struct *q = &diff_queued_diff;
2899 int i;
2900 int result = diff_get_patch_id(options, sha1);
2902 for (i = 0; i < q->nr; i++)
2903 diff_free_filepair(q->queue[i]);
2905 free(q->queue);
2906 q->queue = NULL;
2907 q->nr = q->alloc = 0;
2909 return result;
2912 static int is_summary_empty(const struct diff_queue_struct *q)
2914 int i;
2916 for (i = 0; i < q->nr; i++) {
2917 const struct diff_filepair *p = q->queue[i];
2919 switch (p->status) {
2920 case DIFF_STATUS_DELETED:
2921 case DIFF_STATUS_ADDED:
2922 case DIFF_STATUS_COPIED:
2923 case DIFF_STATUS_RENAMED:
2924 return 0;
2925 default:
2926 if (p->score)
2927 return 0;
2928 if (p->one->mode && p->two->mode &&
2929 p->one->mode != p->two->mode)
2930 return 0;
2931 break;
2934 return 1;
2937 void diff_flush(struct diff_options *options)
2939 struct diff_queue_struct *q = &diff_queued_diff;
2940 int i, output_format = options->output_format;
2941 int separator = 0;
2944 * Order: raw, stat, summary, patch
2945 * or: name/name-status/checkdiff (other bits clear)
2947 if (!q->nr)
2948 goto free_queue;
2950 if (output_format & (DIFF_FORMAT_RAW |
2951 DIFF_FORMAT_NAME |
2952 DIFF_FORMAT_NAME_STATUS |
2953 DIFF_FORMAT_CHECKDIFF)) {
2954 for (i = 0; i < q->nr; i++) {
2955 struct diff_filepair *p = q->queue[i];
2956 if (check_pair_status(p))
2957 flush_one_pair(p, options);
2959 separator++;
2962 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
2963 struct diffstat_t diffstat;
2965 memset(&diffstat, 0, sizeof(struct diffstat_t));
2966 diffstat.xm.consume = diffstat_consume;
2967 for (i = 0; i < q->nr; i++) {
2968 struct diff_filepair *p = q->queue[i];
2969 if (check_pair_status(p))
2970 diff_flush_stat(p, options, &diffstat);
2972 if (output_format & DIFF_FORMAT_NUMSTAT)
2973 show_numstat(&diffstat, options);
2974 if (output_format & DIFF_FORMAT_DIFFSTAT)
2975 show_stats(&diffstat, options);
2976 else if (output_format & DIFF_FORMAT_SHORTSTAT)
2977 show_shortstats(&diffstat);
2978 separator++;
2981 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2982 for (i = 0; i < q->nr; i++)
2983 diff_summary(q->queue[i]);
2984 separator++;
2987 if (output_format & DIFF_FORMAT_PATCH) {
2988 if (separator) {
2989 if (options->stat_sep) {
2990 /* attach patch instead of inline */
2991 fputs(options->stat_sep, stdout);
2992 } else {
2993 putchar(options->line_termination);
2997 for (i = 0; i < q->nr; i++) {
2998 struct diff_filepair *p = q->queue[i];
2999 if (check_pair_status(p))
3000 diff_flush_patch(p, options);
3004 if (output_format & DIFF_FORMAT_CALLBACK)
3005 options->format_callback(q, options, options->format_callback_data);
3007 for (i = 0; i < q->nr; i++)
3008 diff_free_filepair(q->queue[i]);
3009 free_queue:
3010 free(q->queue);
3011 q->queue = NULL;
3012 q->nr = q->alloc = 0;
3015 static void diffcore_apply_filter(const char *filter)
3017 int i;
3018 struct diff_queue_struct *q = &diff_queued_diff;
3019 struct diff_queue_struct outq;
3020 outq.queue = NULL;
3021 outq.nr = outq.alloc = 0;
3023 if (!filter)
3024 return;
3026 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3027 int found;
3028 for (i = found = 0; !found && i < q->nr; i++) {
3029 struct diff_filepair *p = q->queue[i];
3030 if (((p->status == DIFF_STATUS_MODIFIED) &&
3031 ((p->score &&
3032 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3033 (!p->score &&
3034 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3035 ((p->status != DIFF_STATUS_MODIFIED) &&
3036 strchr(filter, p->status)))
3037 found++;
3039 if (found)
3040 return;
3042 /* otherwise we will clear the whole queue
3043 * by copying the empty outq at the end of this
3044 * function, but first clear the current entries
3045 * in the queue.
3047 for (i = 0; i < q->nr; i++)
3048 diff_free_filepair(q->queue[i]);
3050 else {
3051 /* Only the matching ones */
3052 for (i = 0; i < q->nr; i++) {
3053 struct diff_filepair *p = q->queue[i];
3055 if (((p->status == DIFF_STATUS_MODIFIED) &&
3056 ((p->score &&
3057 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3058 (!p->score &&
3059 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3060 ((p->status != DIFF_STATUS_MODIFIED) &&
3061 strchr(filter, p->status)))
3062 diff_q(&outq, p);
3063 else
3064 diff_free_filepair(p);
3067 free(q->queue);
3068 *q = outq;
3071 void diffcore_std(struct diff_options *options)
3073 if (options->quiet)
3074 return;
3075 if (options->break_opt != -1)
3076 diffcore_break(options->break_opt);
3077 if (options->detect_rename)
3078 diffcore_rename(options);
3079 if (options->break_opt != -1)
3080 diffcore_merge_broken();
3081 if (options->pickaxe)
3082 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3083 if (options->orderfile)
3084 diffcore_order(options->orderfile);
3085 diff_resolve_rename_copy();
3086 diffcore_apply_filter(options->filter);
3088 options->has_changes = !!diff_queued_diff.nr;
3092 void diff_addremove(struct diff_options *options,
3093 int addremove, unsigned mode,
3094 const unsigned char *sha1,
3095 const char *base, const char *path)
3097 char concatpath[PATH_MAX];
3098 struct diff_filespec *one, *two;
3100 /* This may look odd, but it is a preparation for
3101 * feeding "there are unchanged files which should
3102 * not produce diffs, but when you are doing copy
3103 * detection you would need them, so here they are"
3104 * entries to the diff-core. They will be prefixed
3105 * with something like '=' or '*' (I haven't decided
3106 * which but should not make any difference).
3107 * Feeding the same new and old to diff_change()
3108 * also has the same effect.
3109 * Before the final output happens, they are pruned after
3110 * merged into rename/copy pairs as appropriate.
3112 if (options->reverse_diff)
3113 addremove = (addremove == '+' ? '-' :
3114 addremove == '-' ? '+' : addremove);
3116 if (!path) path = "";
3117 sprintf(concatpath, "%s%s", base, path);
3118 one = alloc_filespec(concatpath);
3119 two = alloc_filespec(concatpath);
3121 if (addremove != '+')
3122 fill_filespec(one, sha1, mode);
3123 if (addremove != '-')
3124 fill_filespec(two, sha1, mode);
3126 diff_queue(&diff_queued_diff, one, two);
3127 options->has_changes = 1;
3130 void diff_change(struct diff_options *options,
3131 unsigned old_mode, unsigned new_mode,
3132 const unsigned char *old_sha1,
3133 const unsigned char *new_sha1,
3134 const char *base, const char *path)
3136 char concatpath[PATH_MAX];
3137 struct diff_filespec *one, *two;
3139 if (options->reverse_diff) {
3140 unsigned tmp;
3141 const unsigned char *tmp_c;
3142 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3143 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3145 if (!path) path = "";
3146 sprintf(concatpath, "%s%s", base, path);
3147 one = alloc_filespec(concatpath);
3148 two = alloc_filespec(concatpath);
3149 fill_filespec(one, old_sha1, old_mode);
3150 fill_filespec(two, new_sha1, new_mode);
3152 diff_queue(&diff_queued_diff, one, two);
3153 options->has_changes = 1;
3156 void diff_unmerge(struct diff_options *options,
3157 const char *path,
3158 unsigned mode, const unsigned char *sha1)
3160 struct diff_filespec *one, *two;
3161 one = alloc_filespec(path);
3162 two = alloc_filespec(path);
3163 fill_filespec(one, sha1, mode);
3164 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;