Fix configuration syntax to specify customized hunk header patterns.
[git/platforms/storm.git] / diff.c
blob21e61af265570f2795a45a7c87cff49094f45b1d
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 diff_detect_rename_default;
20 static int diff_rename_limit_default = -1;
21 static int diff_use_color_default;
23 static char diff_colors[][COLOR_MAXLEN] = {
24 "\033[m", /* reset */
25 "", /* PLAIN (normal) */
26 "\033[1m", /* METAINFO (bold) */
27 "\033[36m", /* FRAGINFO (cyan) */
28 "\033[31m", /* OLD (red) */
29 "\033[32m", /* NEW (green) */
30 "\033[33m", /* COMMIT (yellow) */
31 "\033[41m", /* WHITESPACE (red background) */
34 static int parse_diff_color_slot(const char *var, int ofs)
36 if (!strcasecmp(var+ofs, "plain"))
37 return DIFF_PLAIN;
38 if (!strcasecmp(var+ofs, "meta"))
39 return DIFF_METAINFO;
40 if (!strcasecmp(var+ofs, "frag"))
41 return DIFF_FRAGINFO;
42 if (!strcasecmp(var+ofs, "old"))
43 return DIFF_FILE_OLD;
44 if (!strcasecmp(var+ofs, "new"))
45 return DIFF_FILE_NEW;
46 if (!strcasecmp(var+ofs, "commit"))
47 return DIFF_COMMIT;
48 if (!strcasecmp(var+ofs, "whitespace"))
49 return DIFF_WHITESPACE;
50 die("bad config variable '%s'", var);
53 static struct ll_diff_driver {
54 const char *name;
55 struct ll_diff_driver *next;
56 char *cmd;
57 } *user_diff, **user_diff_tail;
59 static void read_config_if_needed(void)
61 if (!user_diff_tail) {
62 user_diff_tail = &user_diff;
63 git_config(git_diff_ui_config);
68 * Currently there is only "diff.<drivername>.command" variable;
69 * because there are "diff.color.<slot>" variables, we are parsing
70 * this in a bit convoluted way to allow low level diff driver
71 * called "color".
73 static int parse_lldiff_command(const char *var, const char *ep, const char *value)
75 const char *name;
76 int namelen;
77 struct ll_diff_driver *drv;
79 name = var + 5;
80 namelen = ep - name;
81 for (drv = user_diff; drv; drv = drv->next)
82 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
83 break;
84 if (!drv) {
85 char *namebuf;
86 drv = xcalloc(1, sizeof(struct ll_diff_driver));
87 namebuf = xmalloc(namelen + 1);
88 memcpy(namebuf, name, namelen);
89 namebuf[namelen] = 0;
90 drv->name = namebuf;
91 drv->next = NULL;
92 if (!user_diff_tail)
93 user_diff_tail = &user_diff;
94 *user_diff_tail = drv;
95 user_diff_tail = &(drv->next);
98 if (!value)
99 return error("%s: lacks value", var);
100 drv->cmd = strdup(value);
101 return 0;
105 * 'diff.<what>.funcname' attribute can be specified in the configuration
106 * to define a customized regexp to find the beginning of a function to
107 * be used for hunk header lines of "diff -p" style output.
109 static struct funcname_pattern {
110 char *name;
111 char *pattern;
112 struct funcname_pattern *next;
113 } *funcname_pattern_list;
115 static int parse_funcname_pattern(const char *var, const char *ep, const char *value)
117 const char *name;
118 int namelen;
119 struct funcname_pattern *pp;
121 name = var + 5; /* "diff." */
122 namelen = ep - name;
124 for (pp = funcname_pattern_list; pp; pp = pp->next)
125 if (!strncmp(pp->name, name, namelen) && !pp->name[namelen])
126 break;
127 if (!pp) {
128 char *namebuf;
129 pp = xcalloc(1, sizeof(*pp));
130 namebuf = xmalloc(namelen + 1);
131 memcpy(namebuf, name, namelen);
132 namebuf[namelen] = 0;
133 pp->name = namebuf;
134 pp->next = funcname_pattern_list;
135 funcname_pattern_list = pp;
137 if (pp->pattern)
138 free(pp->pattern);
139 pp->pattern = xstrdup(value);
140 return 0;
144 * These are to give UI layer defaults.
145 * The core-level commands such as git-diff-files should
146 * never be affected by the setting of diff.renames
147 * the user happens to have in the configuration file.
149 int git_diff_ui_config(const char *var, const char *value)
151 if (!strcmp(var, "diff.renamelimit")) {
152 diff_rename_limit_default = git_config_int(var, value);
153 return 0;
155 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
156 diff_use_color_default = git_config_colorbool(var, value);
157 return 0;
159 if (!strcmp(var, "diff.renames")) {
160 if (!value)
161 diff_detect_rename_default = DIFF_DETECT_RENAME;
162 else if (!strcasecmp(value, "copies") ||
163 !strcasecmp(value, "copy"))
164 diff_detect_rename_default = DIFF_DETECT_COPY;
165 else if (git_config_bool(var,value))
166 diff_detect_rename_default = DIFF_DETECT_RENAME;
167 return 0;
169 if (!prefixcmp(var, "diff.")) {
170 const char *ep = strrchr(var, '.');
172 if (ep != var + 4) {
173 if (!strcmp(ep, ".command"))
174 return parse_lldiff_command(var, ep, value);
175 if (!strcmp(ep, ".funcname"))
176 return parse_funcname_pattern(var, ep, value);
179 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
180 int slot = parse_diff_color_slot(var, 11);
181 color_parse(value, var, diff_colors[slot]);
182 return 0;
185 return git_default_config(var, value);
188 static char *quote_one(const char *str)
190 int needlen;
191 char *xp;
193 if (!str)
194 return NULL;
195 needlen = quote_c_style(str, NULL, NULL, 0);
196 if (!needlen)
197 return xstrdup(str);
198 xp = xmalloc(needlen + 1);
199 quote_c_style(str, xp, NULL, 0);
200 return xp;
203 static char *quote_two(const char *one, const char *two)
205 int need_one = quote_c_style(one, NULL, NULL, 1);
206 int need_two = quote_c_style(two, NULL, NULL, 1);
207 char *xp;
209 if (need_one + need_two) {
210 if (!need_one) need_one = strlen(one);
211 if (!need_two) need_one = strlen(two);
213 xp = xmalloc(need_one + need_two + 3);
214 xp[0] = '"';
215 quote_c_style(one, xp + 1, NULL, 1);
216 quote_c_style(two, xp + need_one + 1, NULL, 1);
217 strcpy(xp + need_one + need_two + 1, "\"");
218 return xp;
220 need_one = strlen(one);
221 need_two = strlen(two);
222 xp = xmalloc(need_one + need_two + 1);
223 strcpy(xp, one);
224 strcpy(xp + need_one, two);
225 return xp;
228 static const char *external_diff(void)
230 static const char *external_diff_cmd = NULL;
231 static int done_preparing = 0;
233 if (done_preparing)
234 return external_diff_cmd;
235 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
236 done_preparing = 1;
237 return external_diff_cmd;
240 static struct diff_tempfile {
241 const char *name; /* filename external diff should read from */
242 char hex[41];
243 char mode[10];
244 char tmp_path[PATH_MAX];
245 } diff_temp[2];
247 static int count_lines(const char *data, int size)
249 int count, ch, completely_empty = 1, nl_just_seen = 0;
250 count = 0;
251 while (0 < size--) {
252 ch = *data++;
253 if (ch == '\n') {
254 count++;
255 nl_just_seen = 1;
256 completely_empty = 0;
258 else {
259 nl_just_seen = 0;
260 completely_empty = 0;
263 if (completely_empty)
264 return 0;
265 if (!nl_just_seen)
266 count++; /* no trailing newline */
267 return count;
270 static void print_line_count(int count)
272 switch (count) {
273 case 0:
274 printf("0,0");
275 break;
276 case 1:
277 printf("1");
278 break;
279 default:
280 printf("1,%d", count);
281 break;
285 static void copy_file(int prefix, const char *data, int size,
286 const char *set, const char *reset)
288 int ch, nl_just_seen = 1;
289 while (0 < size--) {
290 ch = *data++;
291 if (nl_just_seen) {
292 fputs(set, stdout);
293 putchar(prefix);
295 if (ch == '\n') {
296 nl_just_seen = 1;
297 fputs(reset, stdout);
298 } else
299 nl_just_seen = 0;
300 putchar(ch);
302 if (!nl_just_seen)
303 printf("%s\n\\ No newline at end of file\n", reset);
306 static void emit_rewrite_diff(const char *name_a,
307 const char *name_b,
308 struct diff_filespec *one,
309 struct diff_filespec *two,
310 int color_diff)
312 int lc_a, lc_b;
313 const char *name_a_tab, *name_b_tab;
314 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
315 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
316 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
317 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
318 const char *reset = diff_get_color(color_diff, DIFF_RESET);
320 name_a += (*name_a == '/');
321 name_b += (*name_b == '/');
322 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
323 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
325 diff_populate_filespec(one, 0);
326 diff_populate_filespec(two, 0);
327 lc_a = count_lines(one->data, one->size);
328 lc_b = count_lines(two->data, two->size);
329 printf("%s--- a/%s%s%s\n%s+++ b/%s%s%s\n%s@@ -",
330 metainfo, name_a, name_a_tab, reset,
331 metainfo, name_b, name_b_tab, reset, fraginfo);
332 print_line_count(lc_a);
333 printf(" +");
334 print_line_count(lc_b);
335 printf(" @@%s\n", reset);
336 if (lc_a)
337 copy_file('-', one->data, one->size, old, reset);
338 if (lc_b)
339 copy_file('+', two->data, two->size, new, reset);
342 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
344 if (!DIFF_FILE_VALID(one)) {
345 mf->ptr = (char *)""; /* does not matter */
346 mf->size = 0;
347 return 0;
349 else if (diff_populate_filespec(one, 0))
350 return -1;
351 mf->ptr = one->data;
352 mf->size = one->size;
353 return 0;
356 struct diff_words_buffer {
357 mmfile_t text;
358 long alloc;
359 long current; /* output pointer */
360 int suppressed_newline;
363 static void diff_words_append(char *line, unsigned long len,
364 struct diff_words_buffer *buffer)
366 if (buffer->text.size + len > buffer->alloc) {
367 buffer->alloc = (buffer->text.size + len) * 3 / 2;
368 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
370 line++;
371 len--;
372 memcpy(buffer->text.ptr + buffer->text.size, line, len);
373 buffer->text.size += len;
376 struct diff_words_data {
377 struct xdiff_emit_state xm;
378 struct diff_words_buffer minus, plus;
381 static void print_word(struct diff_words_buffer *buffer, int len, int color,
382 int suppress_newline)
384 const char *ptr;
385 int eol = 0;
387 if (len == 0)
388 return;
390 ptr = buffer->text.ptr + buffer->current;
391 buffer->current += len;
393 if (ptr[len - 1] == '\n') {
394 eol = 1;
395 len--;
398 fputs(diff_get_color(1, color), stdout);
399 fwrite(ptr, len, 1, stdout);
400 fputs(diff_get_color(1, DIFF_RESET), stdout);
402 if (eol) {
403 if (suppress_newline)
404 buffer->suppressed_newline = 1;
405 else
406 putchar('\n');
410 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
412 struct diff_words_data *diff_words = priv;
414 if (diff_words->minus.suppressed_newline) {
415 if (line[0] != '+')
416 putchar('\n');
417 diff_words->minus.suppressed_newline = 0;
420 len--;
421 switch (line[0]) {
422 case '-':
423 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
424 break;
425 case '+':
426 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
427 break;
428 case ' ':
429 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
430 diff_words->minus.current += len;
431 break;
435 /* this executes the word diff on the accumulated buffers */
436 static void diff_words_show(struct diff_words_data *diff_words)
438 xpparam_t xpp;
439 xdemitconf_t xecfg;
440 xdemitcb_t ecb;
441 mmfile_t minus, plus;
442 int i;
444 memset(&xecfg, 0, sizeof(xecfg));
445 minus.size = diff_words->minus.text.size;
446 minus.ptr = xmalloc(minus.size);
447 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
448 for (i = 0; i < minus.size; i++)
449 if (isspace(minus.ptr[i]))
450 minus.ptr[i] = '\n';
451 diff_words->minus.current = 0;
453 plus.size = diff_words->plus.text.size;
454 plus.ptr = xmalloc(plus.size);
455 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
456 for (i = 0; i < plus.size; i++)
457 if (isspace(plus.ptr[i]))
458 plus.ptr[i] = '\n';
459 diff_words->plus.current = 0;
461 xpp.flags = XDF_NEED_MINIMAL;
462 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
463 ecb.outf = xdiff_outf;
464 ecb.priv = diff_words;
465 diff_words->xm.consume = fn_out_diff_words_aux;
466 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
468 free(minus.ptr);
469 free(plus.ptr);
470 diff_words->minus.text.size = diff_words->plus.text.size = 0;
472 if (diff_words->minus.suppressed_newline) {
473 putchar('\n');
474 diff_words->minus.suppressed_newline = 0;
478 struct emit_callback {
479 struct xdiff_emit_state xm;
480 int nparents, color_diff;
481 const char **label_path;
482 struct diff_words_data *diff_words;
483 int *found_changesp;
486 static void free_diff_words_data(struct emit_callback *ecbdata)
488 if (ecbdata->diff_words) {
489 /* flush buffers */
490 if (ecbdata->diff_words->minus.text.size ||
491 ecbdata->diff_words->plus.text.size)
492 diff_words_show(ecbdata->diff_words);
494 if (ecbdata->diff_words->minus.text.ptr)
495 free (ecbdata->diff_words->minus.text.ptr);
496 if (ecbdata->diff_words->plus.text.ptr)
497 free (ecbdata->diff_words->plus.text.ptr);
498 free(ecbdata->diff_words);
499 ecbdata->diff_words = NULL;
503 const char *diff_get_color(int diff_use_color, enum color_diff ix)
505 if (diff_use_color)
506 return diff_colors[ix];
507 return "";
510 static void emit_line(const char *set, const char *reset, const char *line, int len)
512 if (len > 0 && line[len-1] == '\n')
513 len--;
514 fputs(set, stdout);
515 fwrite(line, len, 1, stdout);
516 puts(reset);
519 static void emit_line_with_ws(int nparents,
520 const char *set, const char *reset, const char *ws,
521 const char *line, int len)
523 int col0 = nparents;
524 int last_tab_in_indent = -1;
525 int last_space_in_indent = -1;
526 int i;
527 int tail = len;
528 int need_highlight_leading_space = 0;
529 /* The line is a newly added line. Does it have funny leading
530 * whitespaces? In indent, SP should never precede a TAB.
532 for (i = col0; i < len; i++) {
533 if (line[i] == '\t') {
534 last_tab_in_indent = i;
535 if (0 <= last_space_in_indent)
536 need_highlight_leading_space = 1;
538 else if (line[i] == ' ')
539 last_space_in_indent = i;
540 else
541 break;
543 fputs(set, stdout);
544 fwrite(line, col0, 1, stdout);
545 fputs(reset, stdout);
546 if (((i == len) || line[i] == '\n') && i != col0) {
547 /* The whole line was indent */
548 emit_line(ws, reset, line + col0, len - col0);
549 return;
551 i = col0;
552 if (need_highlight_leading_space) {
553 while (i < last_tab_in_indent) {
554 if (line[i] == ' ') {
555 fputs(ws, stdout);
556 putchar(' ');
557 fputs(reset, stdout);
559 else
560 putchar(line[i]);
561 i++;
564 tail = len - 1;
565 if (line[tail] == '\n' && i < tail)
566 tail--;
567 while (i < tail) {
568 if (!isspace(line[tail]))
569 break;
570 tail--;
572 if ((i < tail && line[tail + 1] != '\n')) {
573 /* This has whitespace between tail+1..len */
574 fputs(set, stdout);
575 fwrite(line + i, tail - i + 1, 1, stdout);
576 fputs(reset, stdout);
577 emit_line(ws, reset, line + tail + 1, len - tail - 1);
579 else
580 emit_line(set, reset, line + i, len - i);
583 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
585 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
586 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
588 if (!*ws)
589 emit_line(set, reset, line, len);
590 else
591 emit_line_with_ws(ecbdata->nparents, set, reset, ws,
592 line, len);
595 static void fn_out_consume(void *priv, char *line, unsigned long len)
597 int i;
598 int color;
599 struct emit_callback *ecbdata = priv;
600 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
601 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
603 *(ecbdata->found_changesp) = 1;
605 if (ecbdata->label_path[0]) {
606 const char *name_a_tab, *name_b_tab;
608 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
609 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
611 printf("%s--- %s%s%s\n",
612 set, ecbdata->label_path[0], reset, name_a_tab);
613 printf("%s+++ %s%s%s\n",
614 set, ecbdata->label_path[1], reset, name_b_tab);
615 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
618 /* This is not really necessary for now because
619 * this codepath only deals with two-way diffs.
621 for (i = 0; i < len && line[i] == '@'; i++)
623 if (2 <= i && i < len && line[i] == ' ') {
624 ecbdata->nparents = i - 1;
625 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
626 reset, line, len);
627 return;
630 if (len < ecbdata->nparents) {
631 set = reset;
632 emit_line(reset, reset, line, len);
633 return;
636 color = DIFF_PLAIN;
637 if (ecbdata->diff_words && ecbdata->nparents != 1)
638 /* fall back to normal diff */
639 free_diff_words_data(ecbdata);
640 if (ecbdata->diff_words) {
641 if (line[0] == '-') {
642 diff_words_append(line, len,
643 &ecbdata->diff_words->minus);
644 return;
645 } else if (line[0] == '+') {
646 diff_words_append(line, len,
647 &ecbdata->diff_words->plus);
648 return;
650 if (ecbdata->diff_words->minus.text.size ||
651 ecbdata->diff_words->plus.text.size)
652 diff_words_show(ecbdata->diff_words);
653 line++;
654 len--;
655 emit_line(set, reset, line, len);
656 return;
658 for (i = 0; i < ecbdata->nparents && len; i++) {
659 if (line[i] == '-')
660 color = DIFF_FILE_OLD;
661 else if (line[i] == '+')
662 color = DIFF_FILE_NEW;
665 if (color != DIFF_FILE_NEW) {
666 emit_line(diff_get_color(ecbdata->color_diff, color),
667 reset, line, len);
668 return;
670 emit_add_line(reset, ecbdata, line, len);
673 static char *pprint_rename(const char *a, const char *b)
675 const char *old = a;
676 const char *new = b;
677 char *name = NULL;
678 int pfx_length, sfx_length;
679 int len_a = strlen(a);
680 int len_b = strlen(b);
681 int qlen_a = quote_c_style(a, NULL, NULL, 0);
682 int qlen_b = quote_c_style(b, NULL, NULL, 0);
684 if (qlen_a || qlen_b) {
685 if (qlen_a) len_a = qlen_a;
686 if (qlen_b) len_b = qlen_b;
687 name = xmalloc( len_a + len_b + 5 );
688 if (qlen_a)
689 quote_c_style(a, name, NULL, 0);
690 else
691 memcpy(name, a, len_a);
692 memcpy(name + len_a, " => ", 4);
693 if (qlen_b)
694 quote_c_style(b, name + len_a + 4, NULL, 0);
695 else
696 memcpy(name + len_a + 4, b, len_b + 1);
697 return name;
700 /* Find common prefix */
701 pfx_length = 0;
702 while (*old && *new && *old == *new) {
703 if (*old == '/')
704 pfx_length = old - a + 1;
705 old++;
706 new++;
709 /* Find common suffix */
710 old = a + len_a;
711 new = b + len_b;
712 sfx_length = 0;
713 while (a <= old && b <= new && *old == *new) {
714 if (*old == '/')
715 sfx_length = len_a - (old - a);
716 old--;
717 new--;
721 * pfx{mid-a => mid-b}sfx
722 * {pfx-a => pfx-b}sfx
723 * pfx{sfx-a => sfx-b}
724 * name-a => name-b
726 if (pfx_length + sfx_length) {
727 int a_midlen = len_a - pfx_length - sfx_length;
728 int b_midlen = len_b - pfx_length - sfx_length;
729 if (a_midlen < 0) a_midlen = 0;
730 if (b_midlen < 0) b_midlen = 0;
732 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
733 sprintf(name, "%.*s{%.*s => %.*s}%s",
734 pfx_length, a,
735 a_midlen, a + pfx_length,
736 b_midlen, b + pfx_length,
737 a + len_a - sfx_length);
739 else {
740 name = xmalloc(len_a + len_b + 5);
741 sprintf(name, "%s => %s", a, b);
743 return name;
746 struct diffstat_t {
747 struct xdiff_emit_state xm;
749 int nr;
750 int alloc;
751 struct diffstat_file {
752 char *name;
753 unsigned is_unmerged:1;
754 unsigned is_binary:1;
755 unsigned is_renamed:1;
756 unsigned int added, deleted;
757 } **files;
760 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
761 const char *name_a,
762 const char *name_b)
764 struct diffstat_file *x;
765 x = xcalloc(sizeof (*x), 1);
766 if (diffstat->nr == diffstat->alloc) {
767 diffstat->alloc = alloc_nr(diffstat->alloc);
768 diffstat->files = xrealloc(diffstat->files,
769 diffstat->alloc * sizeof(x));
771 diffstat->files[diffstat->nr++] = x;
772 if (name_b) {
773 x->name = pprint_rename(name_a, name_b);
774 x->is_renamed = 1;
776 else
777 x->name = xstrdup(name_a);
778 return x;
781 static void diffstat_consume(void *priv, char *line, unsigned long len)
783 struct diffstat_t *diffstat = priv;
784 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
786 if (line[0] == '+')
787 x->added++;
788 else if (line[0] == '-')
789 x->deleted++;
792 const char mime_boundary_leader[] = "------------";
794 static int scale_linear(int it, int width, int max_change)
797 * make sure that at least one '-' is printed if there were deletions,
798 * and likewise for '+'.
800 if (max_change < 2)
801 return it;
802 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
805 static void show_name(const char *prefix, const char *name, int len,
806 const char *reset, const char *set)
808 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
811 static void show_graph(char ch, int cnt, const char *set, const char *reset)
813 if (cnt <= 0)
814 return;
815 printf("%s", set);
816 while (cnt--)
817 putchar(ch);
818 printf("%s", reset);
821 static void show_stats(struct diffstat_t* data, struct diff_options *options)
823 int i, len, add, del, total, adds = 0, dels = 0;
824 int max_change = 0, max_len = 0;
825 int total_files = data->nr;
826 int width, name_width;
827 const char *reset, *set, *add_c, *del_c;
829 if (data->nr == 0)
830 return;
832 width = options->stat_width ? options->stat_width : 80;
833 name_width = options->stat_name_width ? options->stat_name_width : 50;
835 /* Sanity: give at least 5 columns to the graph,
836 * but leave at least 10 columns for the name.
838 if (width < name_width + 15) {
839 if (name_width <= 25)
840 width = name_width + 15;
841 else
842 name_width = width - 15;
845 /* Find the longest filename and max number of changes */
846 reset = diff_get_color(options->color_diff, DIFF_RESET);
847 set = diff_get_color(options->color_diff, DIFF_PLAIN);
848 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
849 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
851 for (i = 0; i < data->nr; i++) {
852 struct diffstat_file *file = data->files[i];
853 int change = file->added + file->deleted;
855 if (!file->is_renamed) { /* renames are already quoted by pprint_rename */
856 len = quote_c_style(file->name, NULL, NULL, 0);
857 if (len) {
858 char *qname = xmalloc(len + 1);
859 quote_c_style(file->name, qname, NULL, 0);
860 free(file->name);
861 file->name = qname;
865 len = strlen(file->name);
866 if (max_len < len)
867 max_len = len;
869 if (file->is_binary || file->is_unmerged)
870 continue;
871 if (max_change < change)
872 max_change = change;
875 /* Compute the width of the graph part;
876 * 10 is for one blank at the beginning of the line plus
877 * " | count " between the name and the graph.
879 * From here on, name_width is the width of the name area,
880 * and width is the width of the graph area.
882 name_width = (name_width < max_len) ? name_width : max_len;
883 if (width < (name_width + 10) + max_change)
884 width = width - (name_width + 10);
885 else
886 width = max_change;
888 for (i = 0; i < data->nr; i++) {
889 const char *prefix = "";
890 char *name = data->files[i]->name;
891 int added = data->files[i]->added;
892 int deleted = data->files[i]->deleted;
893 int name_len;
896 * "scale" the filename
898 len = name_width;
899 name_len = strlen(name);
900 if (name_width < name_len) {
901 char *slash;
902 prefix = "...";
903 len -= 3;
904 name += name_len - len;
905 slash = strchr(name, '/');
906 if (slash)
907 name = slash;
910 if (data->files[i]->is_binary) {
911 show_name(prefix, name, len, reset, set);
912 printf(" Bin ");
913 printf("%s%d%s", del_c, deleted, reset);
914 printf(" -> ");
915 printf("%s%d%s", add_c, added, reset);
916 printf(" bytes");
917 printf("\n");
918 goto free_diffstat_file;
920 else if (data->files[i]->is_unmerged) {
921 show_name(prefix, name, len, reset, set);
922 printf(" Unmerged\n");
923 goto free_diffstat_file;
925 else if (!data->files[i]->is_renamed &&
926 (added + deleted == 0)) {
927 total_files--;
928 goto free_diffstat_file;
932 * scale the add/delete
934 add = added;
935 del = deleted;
936 total = add + del;
937 adds += add;
938 dels += del;
940 if (width <= max_change) {
941 add = scale_linear(add, width, max_change);
942 del = scale_linear(del, width, max_change);
943 total = add + del;
945 show_name(prefix, name, len, reset, set);
946 printf("%5d ", added + deleted);
947 show_graph('+', add, add_c, reset);
948 show_graph('-', del, del_c, reset);
949 putchar('\n');
950 free_diffstat_file:
951 free(data->files[i]->name);
952 free(data->files[i]);
954 free(data->files);
955 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
956 set, total_files, adds, dels, reset);
959 static void show_shortstats(struct diffstat_t* data)
961 int i, adds = 0, dels = 0, total_files = data->nr;
963 if (data->nr == 0)
964 return;
966 for (i = 0; i < data->nr; i++) {
967 if (!data->files[i]->is_binary &&
968 !data->files[i]->is_unmerged) {
969 int added = data->files[i]->added;
970 int deleted= data->files[i]->deleted;
971 if (!data->files[i]->is_renamed &&
972 (added + deleted == 0)) {
973 total_files--;
974 } else {
975 adds += added;
976 dels += deleted;
979 free(data->files[i]->name);
980 free(data->files[i]);
982 free(data->files);
984 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
985 total_files, adds, dels);
988 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
990 int i;
992 for (i = 0; i < data->nr; i++) {
993 struct diffstat_file *file = data->files[i];
995 if (file->is_binary)
996 printf("-\t-\t");
997 else
998 printf("%d\t%d\t", file->added, file->deleted);
999 if (options->line_termination && !file->is_renamed &&
1000 quote_c_style(file->name, NULL, NULL, 0))
1001 quote_c_style(file->name, NULL, stdout, 0);
1002 else
1003 fputs(file->name, stdout);
1004 putchar(options->line_termination);
1008 struct checkdiff_t {
1009 struct xdiff_emit_state xm;
1010 const char *filename;
1011 int lineno, color_diff;
1014 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1016 struct checkdiff_t *data = priv;
1017 const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
1018 const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
1019 const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
1021 if (line[0] == '+') {
1022 int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
1024 /* check space before tab */
1025 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
1026 if (line[i] == ' ')
1027 spaces++;
1028 if (line[i - 1] == '\t' && spaces)
1029 space_before_tab = 1;
1031 /* check white space at line end */
1032 if (line[len - 1] == '\n')
1033 len--;
1034 if (isspace(line[len - 1]))
1035 white_space_at_end = 1;
1037 if (space_before_tab || white_space_at_end) {
1038 printf("%s:%d: %s", data->filename, data->lineno, ws);
1039 if (space_before_tab) {
1040 printf("space before tab");
1041 if (white_space_at_end)
1042 putchar(',');
1044 if (white_space_at_end)
1045 printf("white space at end");
1046 printf(":%s ", reset);
1047 emit_line_with_ws(1, set, reset, ws, line, len);
1050 data->lineno++;
1051 } else if (line[0] == ' ')
1052 data->lineno++;
1053 else if (line[0] == '@') {
1054 char *plus = strchr(line, '+');
1055 if (plus)
1056 data->lineno = strtol(plus, NULL, 10);
1057 else
1058 die("invalid diff");
1062 static unsigned char *deflate_it(char *data,
1063 unsigned long size,
1064 unsigned long *result_size)
1066 int bound;
1067 unsigned char *deflated;
1068 z_stream stream;
1070 memset(&stream, 0, sizeof(stream));
1071 deflateInit(&stream, zlib_compression_level);
1072 bound = deflateBound(&stream, size);
1073 deflated = xmalloc(bound);
1074 stream.next_out = deflated;
1075 stream.avail_out = bound;
1077 stream.next_in = (unsigned char *)data;
1078 stream.avail_in = size;
1079 while (deflate(&stream, Z_FINISH) == Z_OK)
1080 ; /* nothing */
1081 deflateEnd(&stream);
1082 *result_size = stream.total_out;
1083 return deflated;
1086 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
1088 void *cp;
1089 void *delta;
1090 void *deflated;
1091 void *data;
1092 unsigned long orig_size;
1093 unsigned long delta_size;
1094 unsigned long deflate_size;
1095 unsigned long data_size;
1097 /* We could do deflated delta, or we could do just deflated two,
1098 * whichever is smaller.
1100 delta = NULL;
1101 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1102 if (one->size && two->size) {
1103 delta = diff_delta(one->ptr, one->size,
1104 two->ptr, two->size,
1105 &delta_size, deflate_size);
1106 if (delta) {
1107 void *to_free = delta;
1108 orig_size = delta_size;
1109 delta = deflate_it(delta, delta_size, &delta_size);
1110 free(to_free);
1114 if (delta && delta_size < deflate_size) {
1115 printf("delta %lu\n", orig_size);
1116 free(deflated);
1117 data = delta;
1118 data_size = delta_size;
1120 else {
1121 printf("literal %lu\n", two->size);
1122 free(delta);
1123 data = deflated;
1124 data_size = deflate_size;
1127 /* emit data encoded in base85 */
1128 cp = data;
1129 while (data_size) {
1130 int bytes = (52 < data_size) ? 52 : data_size;
1131 char line[70];
1132 data_size -= bytes;
1133 if (bytes <= 26)
1134 line[0] = bytes + 'A' - 1;
1135 else
1136 line[0] = bytes - 26 + 'a' - 1;
1137 encode_85(line + 1, cp, bytes);
1138 cp = (char *) cp + bytes;
1139 puts(line);
1141 printf("\n");
1142 free(data);
1145 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1147 printf("GIT binary patch\n");
1148 emit_binary_diff_body(one, two);
1149 emit_binary_diff_body(two, one);
1152 static void setup_diff_attr_check(struct git_attr_check *check)
1154 static struct git_attr *attr_diff;
1156 if (!attr_diff) {
1157 attr_diff = git_attr("diff", 4);
1159 check[0].attr = attr_diff;
1162 static void diff_filespec_check_attr(struct diff_filespec *one)
1164 struct git_attr_check attr_diff_check;
1166 if (one->checked_attr)
1167 return;
1169 setup_diff_attr_check(&attr_diff_check);
1170 one->is_binary = 0;
1171 one->funcname_pattern_ident = NULL;
1173 if (!git_checkattr(one->path, 1, &attr_diff_check)) {
1174 const char *value;
1176 /* binaryness */
1177 value = attr_diff_check.value;
1178 if (ATTR_TRUE(value))
1180 else if (ATTR_FALSE(value))
1181 one->is_binary = 1;
1183 /* funcname pattern ident */
1184 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1186 else
1187 one->funcname_pattern_ident = value;
1190 if (!one->data && DIFF_FILE_VALID(one))
1191 diff_populate_filespec(one, 0);
1193 if (one->data)
1194 one->is_binary = buffer_is_binary(one->data, one->size);
1198 int diff_filespec_is_binary(struct diff_filespec *one)
1200 diff_filespec_check_attr(one);
1201 return one->is_binary;
1204 static const char *funcname_pattern(const char *ident)
1206 struct funcname_pattern *pp;
1208 read_config_if_needed();
1209 for (pp = funcname_pattern_list; pp; pp = pp->next)
1210 if (!strcmp(ident, pp->name))
1211 return pp->pattern;
1212 return NULL;
1215 static const char *diff_funcname_pattern(struct diff_filespec *one)
1217 const char *ident, *pattern;
1219 diff_filespec_check_attr(one);
1220 ident = one->funcname_pattern_ident;
1222 if (!ident)
1224 * If the config file has "funcname.default" defined, that
1225 * regexp is used; otherwise NULL is returned and xemit uses
1226 * the built-in default.
1228 return funcname_pattern("default");
1230 /* Look up custom "funcname.$ident" regexp from config. */
1231 pattern = funcname_pattern(ident);
1232 if (pattern)
1233 return pattern;
1236 * And define built-in fallback patterns here. Note that
1237 * these can be overriden by the user's config settings.
1239 if (!strcmp(ident, "java"))
1240 return "!^[ ]*\\(catch\\|do\\|for\\|if\\|instanceof\\|"
1241 "new\\|return\\|switch\\|throw\\|while\\)\n"
1242 "^[ ]*\\(\\([ ]*"
1243 "[A-Za-z_][A-Za-z_0-9]*\\)\\{2,\\}"
1244 "[ ]*([^;]*$\\)";
1246 return NULL;
1249 static void builtin_diff(const char *name_a,
1250 const char *name_b,
1251 struct diff_filespec *one,
1252 struct diff_filespec *two,
1253 const char *xfrm_msg,
1254 struct diff_options *o,
1255 int complete_rewrite)
1257 mmfile_t mf1, mf2;
1258 const char *lbl[2];
1259 char *a_one, *b_two;
1260 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1261 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1263 a_one = quote_two("a/", name_a + (*name_a == '/'));
1264 b_two = quote_two("b/", name_b + (*name_b == '/'));
1265 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1266 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1267 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1268 if (lbl[0][0] == '/') {
1269 /* /dev/null */
1270 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1271 if (xfrm_msg && xfrm_msg[0])
1272 printf("%s%s%s\n", set, xfrm_msg, reset);
1274 else if (lbl[1][0] == '/') {
1275 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1276 if (xfrm_msg && xfrm_msg[0])
1277 printf("%s%s%s\n", set, xfrm_msg, reset);
1279 else {
1280 if (one->mode != two->mode) {
1281 printf("%sold mode %06o%s\n", set, one->mode, reset);
1282 printf("%snew mode %06o%s\n", set, two->mode, reset);
1284 if (xfrm_msg && xfrm_msg[0])
1285 printf("%s%s%s\n", set, xfrm_msg, reset);
1287 * we do not run diff between different kind
1288 * of objects.
1290 if ((one->mode ^ two->mode) & S_IFMT)
1291 goto free_ab_and_return;
1292 if (complete_rewrite) {
1293 emit_rewrite_diff(name_a, name_b, one, two,
1294 o->color_diff);
1295 o->found_changes = 1;
1296 goto free_ab_and_return;
1300 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1301 die("unable to read files to diff");
1303 if (!o->text &&
1304 (diff_filespec_is_binary(one) || diff_filespec_is_binary(two))) {
1305 /* Quite common confusing case */
1306 if (mf1.size == mf2.size &&
1307 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1308 goto free_ab_and_return;
1309 if (o->binary)
1310 emit_binary_diff(&mf1, &mf2);
1311 else
1312 printf("Binary files %s and %s differ\n",
1313 lbl[0], lbl[1]);
1314 o->found_changes = 1;
1316 else {
1317 /* Crazy xdl interfaces.. */
1318 const char *diffopts = getenv("GIT_DIFF_OPTS");
1319 xpparam_t xpp;
1320 xdemitconf_t xecfg;
1321 xdemitcb_t ecb;
1322 struct emit_callback ecbdata;
1323 const char *funcname_pattern;
1325 funcname_pattern = diff_funcname_pattern(one);
1326 if (!funcname_pattern)
1327 funcname_pattern = diff_funcname_pattern(two);
1329 memset(&xecfg, 0, sizeof(xecfg));
1330 memset(&ecbdata, 0, sizeof(ecbdata));
1331 ecbdata.label_path = lbl;
1332 ecbdata.color_diff = o->color_diff;
1333 ecbdata.found_changesp = &o->found_changes;
1334 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1335 xecfg.ctxlen = o->context;
1336 xecfg.flags = XDL_EMIT_FUNCNAMES;
1337 if (funcname_pattern)
1338 xdiff_set_find_func(&xecfg, funcname_pattern);
1339 if (!diffopts)
1341 else if (!prefixcmp(diffopts, "--unified="))
1342 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1343 else if (!prefixcmp(diffopts, "-u"))
1344 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1345 ecb.outf = xdiff_outf;
1346 ecb.priv = &ecbdata;
1347 ecbdata.xm.consume = fn_out_consume;
1348 if (o->color_diff_words)
1349 ecbdata.diff_words =
1350 xcalloc(1, sizeof(struct diff_words_data));
1351 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1352 if (o->color_diff_words)
1353 free_diff_words_data(&ecbdata);
1356 free_ab_and_return:
1357 diff_free_filespec_data(one);
1358 diff_free_filespec_data(two);
1359 free(a_one);
1360 free(b_two);
1361 return;
1364 static void builtin_diffstat(const char *name_a, const char *name_b,
1365 struct diff_filespec *one,
1366 struct diff_filespec *two,
1367 struct diffstat_t *diffstat,
1368 struct diff_options *o,
1369 int complete_rewrite)
1371 mmfile_t mf1, mf2;
1372 struct diffstat_file *data;
1374 data = diffstat_add(diffstat, name_a, name_b);
1376 if (!one || !two) {
1377 data->is_unmerged = 1;
1378 return;
1380 if (complete_rewrite) {
1381 diff_populate_filespec(one, 0);
1382 diff_populate_filespec(two, 0);
1383 data->deleted = count_lines(one->data, one->size);
1384 data->added = count_lines(two->data, two->size);
1385 goto free_and_return;
1387 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1388 die("unable to read files to diff");
1390 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1391 data->is_binary = 1;
1392 data->added = mf2.size;
1393 data->deleted = mf1.size;
1394 } else {
1395 /* Crazy xdl interfaces.. */
1396 xpparam_t xpp;
1397 xdemitconf_t xecfg;
1398 xdemitcb_t ecb;
1400 memset(&xecfg, 0, sizeof(xecfg));
1401 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1402 ecb.outf = xdiff_outf;
1403 ecb.priv = diffstat;
1404 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1407 free_and_return:
1408 diff_free_filespec_data(one);
1409 diff_free_filespec_data(two);
1412 static void builtin_checkdiff(const char *name_a, const char *name_b,
1413 struct diff_filespec *one,
1414 struct diff_filespec *two, struct diff_options *o)
1416 mmfile_t mf1, mf2;
1417 struct checkdiff_t data;
1419 if (!two)
1420 return;
1422 memset(&data, 0, sizeof(data));
1423 data.xm.consume = checkdiff_consume;
1424 data.filename = name_b ? name_b : name_a;
1425 data.lineno = 0;
1426 data.color_diff = o->color_diff;
1428 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1429 die("unable to read files to diff");
1431 if (diff_filespec_is_binary(two))
1432 goto free_and_return;
1433 else {
1434 /* Crazy xdl interfaces.. */
1435 xpparam_t xpp;
1436 xdemitconf_t xecfg;
1437 xdemitcb_t ecb;
1439 memset(&xecfg, 0, sizeof(xecfg));
1440 xpp.flags = XDF_NEED_MINIMAL;
1441 ecb.outf = xdiff_outf;
1442 ecb.priv = &data;
1443 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1445 free_and_return:
1446 diff_free_filespec_data(one);
1447 diff_free_filespec_data(two);
1450 struct diff_filespec *alloc_filespec(const char *path)
1452 int namelen = strlen(path);
1453 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1455 memset(spec, 0, sizeof(*spec));
1456 spec->path = (char *)(spec + 1);
1457 memcpy(spec->path, path, namelen+1);
1458 return spec;
1461 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1462 unsigned short mode)
1464 if (mode) {
1465 spec->mode = canon_mode(mode);
1466 hashcpy(spec->sha1, sha1);
1467 spec->sha1_valid = !is_null_sha1(sha1);
1472 * Given a name and sha1 pair, if the index tells us the file in
1473 * the work tree has that object contents, return true, so that
1474 * prepare_temp_file() does not have to inflate and extract.
1476 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1478 struct cache_entry *ce;
1479 struct stat st;
1480 int pos, len;
1482 /* We do not read the cache ourselves here, because the
1483 * benchmark with my previous version that always reads cache
1484 * shows that it makes things worse for diff-tree comparing
1485 * two linux-2.6 kernel trees in an already checked out work
1486 * tree. This is because most diff-tree comparisons deal with
1487 * only a small number of files, while reading the cache is
1488 * expensive for a large project, and its cost outweighs the
1489 * savings we get by not inflating the object to a temporary
1490 * file. Practically, this code only helps when we are used
1491 * by diff-cache --cached, which does read the cache before
1492 * calling us.
1494 if (!active_cache)
1495 return 0;
1497 /* We want to avoid the working directory if our caller
1498 * doesn't need the data in a normal file, this system
1499 * is rather slow with its stat/open/mmap/close syscalls,
1500 * and the object is contained in a pack file. The pack
1501 * is probably already open and will be faster to obtain
1502 * the data through than the working directory. Loose
1503 * objects however would tend to be slower as they need
1504 * to be individually opened and inflated.
1506 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1507 return 0;
1509 len = strlen(name);
1510 pos = cache_name_pos(name, len);
1511 if (pos < 0)
1512 return 0;
1513 ce = active_cache[pos];
1514 if ((lstat(name, &st) < 0) ||
1515 !S_ISREG(st.st_mode) || /* careful! */
1516 ce_match_stat(ce, &st, 0) ||
1517 hashcmp(sha1, ce->sha1))
1518 return 0;
1519 /* we return 1 only when we can stat, it is a regular file,
1520 * stat information matches, and sha1 recorded in the cache
1521 * matches. I.e. we know the file in the work tree really is
1522 * the same as the <name, sha1> pair.
1524 return 1;
1527 static int populate_from_stdin(struct diff_filespec *s)
1529 #define INCREMENT 1024
1530 char *buf;
1531 unsigned long size;
1532 ssize_t got;
1534 size = 0;
1535 buf = NULL;
1536 while (1) {
1537 buf = xrealloc(buf, size + INCREMENT);
1538 got = xread(0, buf + size, INCREMENT);
1539 if (!got)
1540 break; /* EOF */
1541 if (got < 0)
1542 return error("error while reading from stdin %s",
1543 strerror(errno));
1544 size += got;
1546 s->should_munmap = 0;
1547 s->data = buf;
1548 s->size = size;
1549 s->should_free = 1;
1550 return 0;
1553 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1555 int len;
1556 char *data = xmalloc(100);
1557 len = snprintf(data, 100,
1558 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1559 s->data = data;
1560 s->size = len;
1561 s->should_free = 1;
1562 if (size_only) {
1563 s->data = NULL;
1564 free(data);
1566 return 0;
1570 * While doing rename detection and pickaxe operation, we may need to
1571 * grab the data for the blob (or file) for our own in-core comparison.
1572 * diff_filespec has data and size fields for this purpose.
1574 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1576 int err = 0;
1577 if (!DIFF_FILE_VALID(s))
1578 die("internal error: asking to populate invalid file.");
1579 if (S_ISDIR(s->mode))
1580 return -1;
1582 if (s->data)
1583 return 0;
1585 if (size_only && 0 < s->size)
1586 return 0;
1588 if (S_ISGITLINK(s->mode))
1589 return diff_populate_gitlink(s, size_only);
1591 if (!s->sha1_valid ||
1592 reuse_worktree_file(s->path, s->sha1, 0)) {
1593 struct stat st;
1594 int fd;
1595 char *buf;
1596 unsigned long size;
1598 if (!strcmp(s->path, "-"))
1599 return populate_from_stdin(s);
1601 if (lstat(s->path, &st) < 0) {
1602 if (errno == ENOENT) {
1603 err_empty:
1604 err = -1;
1605 empty:
1606 s->data = (char *)"";
1607 s->size = 0;
1608 return err;
1611 s->size = xsize_t(st.st_size);
1612 if (!s->size)
1613 goto empty;
1614 if (size_only)
1615 return 0;
1616 if (S_ISLNK(st.st_mode)) {
1617 int ret;
1618 s->data = xmalloc(s->size);
1619 s->should_free = 1;
1620 ret = readlink(s->path, s->data, s->size);
1621 if (ret < 0) {
1622 free(s->data);
1623 goto err_empty;
1625 return 0;
1627 fd = open(s->path, O_RDONLY);
1628 if (fd < 0)
1629 goto err_empty;
1630 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1631 close(fd);
1632 s->should_munmap = 1;
1635 * Convert from working tree format to canonical git format
1637 size = s->size;
1638 buf = convert_to_git(s->path, s->data, &size);
1639 if (buf) {
1640 munmap(s->data, s->size);
1641 s->should_munmap = 0;
1642 s->data = buf;
1643 s->size = size;
1644 s->should_free = 1;
1647 else {
1648 enum object_type type;
1649 if (size_only)
1650 type = sha1_object_info(s->sha1, &s->size);
1651 else {
1652 s->data = read_sha1_file(s->sha1, &type, &s->size);
1653 s->should_free = 1;
1656 return 0;
1659 void diff_free_filespec_data(struct diff_filespec *s)
1661 if (s->should_free)
1662 free(s->data);
1663 else if (s->should_munmap)
1664 munmap(s->data, s->size);
1666 if (s->should_free || s->should_munmap) {
1667 s->should_free = s->should_munmap = 0;
1668 s->data = NULL;
1670 free(s->cnt_data);
1671 s->cnt_data = NULL;
1674 static void prep_temp_blob(struct diff_tempfile *temp,
1675 void *blob,
1676 unsigned long size,
1677 const unsigned char *sha1,
1678 int mode)
1680 int fd;
1682 fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1683 if (fd < 0)
1684 die("unable to create temp-file");
1685 if (write_in_full(fd, blob, size) != size)
1686 die("unable to write temp-file");
1687 close(fd);
1688 temp->name = temp->tmp_path;
1689 strcpy(temp->hex, sha1_to_hex(sha1));
1690 temp->hex[40] = 0;
1691 sprintf(temp->mode, "%06o", mode);
1694 static void prepare_temp_file(const char *name,
1695 struct diff_tempfile *temp,
1696 struct diff_filespec *one)
1698 if (!DIFF_FILE_VALID(one)) {
1699 not_a_valid_file:
1700 /* A '-' entry produces this for file-2, and
1701 * a '+' entry produces this for file-1.
1703 temp->name = "/dev/null";
1704 strcpy(temp->hex, ".");
1705 strcpy(temp->mode, ".");
1706 return;
1709 if (!one->sha1_valid ||
1710 reuse_worktree_file(name, one->sha1, 1)) {
1711 struct stat st;
1712 if (lstat(name, &st) < 0) {
1713 if (errno == ENOENT)
1714 goto not_a_valid_file;
1715 die("stat(%s): %s", name, strerror(errno));
1717 if (S_ISLNK(st.st_mode)) {
1718 int ret;
1719 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1720 size_t sz = xsize_t(st.st_size);
1721 if (sizeof(buf) <= st.st_size)
1722 die("symlink too long: %s", name);
1723 ret = readlink(name, buf, sz);
1724 if (ret < 0)
1725 die("readlink(%s)", name);
1726 prep_temp_blob(temp, buf, sz,
1727 (one->sha1_valid ?
1728 one->sha1 : null_sha1),
1729 (one->sha1_valid ?
1730 one->mode : S_IFLNK));
1732 else {
1733 /* we can borrow from the file in the work tree */
1734 temp->name = name;
1735 if (!one->sha1_valid)
1736 strcpy(temp->hex, sha1_to_hex(null_sha1));
1737 else
1738 strcpy(temp->hex, sha1_to_hex(one->sha1));
1739 /* Even though we may sometimes borrow the
1740 * contents from the work tree, we always want
1741 * one->mode. mode is trustworthy even when
1742 * !(one->sha1_valid), as long as
1743 * DIFF_FILE_VALID(one).
1745 sprintf(temp->mode, "%06o", one->mode);
1747 return;
1749 else {
1750 if (diff_populate_filespec(one, 0))
1751 die("cannot read data blob for %s", one->path);
1752 prep_temp_blob(temp, one->data, one->size,
1753 one->sha1, one->mode);
1757 static void remove_tempfile(void)
1759 int i;
1761 for (i = 0; i < 2; i++)
1762 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1763 unlink(diff_temp[i].name);
1764 diff_temp[i].name = NULL;
1768 static void remove_tempfile_on_signal(int signo)
1770 remove_tempfile();
1771 signal(SIGINT, SIG_DFL);
1772 raise(signo);
1775 static int spawn_prog(const char *pgm, const char **arg)
1777 pid_t pid;
1778 int status;
1780 fflush(NULL);
1781 pid = fork();
1782 if (pid < 0)
1783 die("unable to fork");
1784 if (!pid) {
1785 execvp(pgm, (char *const*) arg);
1786 exit(255);
1789 while (waitpid(pid, &status, 0) < 0) {
1790 if (errno == EINTR)
1791 continue;
1792 return -1;
1795 /* Earlier we did not check the exit status because
1796 * diff exits non-zero if files are different, and
1797 * we are not interested in knowing that. It was a
1798 * mistake which made it harder to quit a diff-*
1799 * session that uses the git-apply-patch-script as
1800 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1801 * should also exit non-zero only when it wants to
1802 * abort the entire diff-* session.
1804 if (WIFEXITED(status) && !WEXITSTATUS(status))
1805 return 0;
1806 return -1;
1809 /* An external diff command takes:
1811 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1812 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1815 static void run_external_diff(const char *pgm,
1816 const char *name,
1817 const char *other,
1818 struct diff_filespec *one,
1819 struct diff_filespec *two,
1820 const char *xfrm_msg,
1821 int complete_rewrite)
1823 const char *spawn_arg[10];
1824 struct diff_tempfile *temp = diff_temp;
1825 int retval;
1826 static int atexit_asked = 0;
1827 const char *othername;
1828 const char **arg = &spawn_arg[0];
1830 othername = (other? other : name);
1831 if (one && two) {
1832 prepare_temp_file(name, &temp[0], one);
1833 prepare_temp_file(othername, &temp[1], two);
1834 if (! atexit_asked &&
1835 (temp[0].name == temp[0].tmp_path ||
1836 temp[1].name == temp[1].tmp_path)) {
1837 atexit_asked = 1;
1838 atexit(remove_tempfile);
1840 signal(SIGINT, remove_tempfile_on_signal);
1843 if (one && two) {
1844 *arg++ = pgm;
1845 *arg++ = name;
1846 *arg++ = temp[0].name;
1847 *arg++ = temp[0].hex;
1848 *arg++ = temp[0].mode;
1849 *arg++ = temp[1].name;
1850 *arg++ = temp[1].hex;
1851 *arg++ = temp[1].mode;
1852 if (other) {
1853 *arg++ = other;
1854 *arg++ = xfrm_msg;
1856 } else {
1857 *arg++ = pgm;
1858 *arg++ = name;
1860 *arg = NULL;
1861 retval = spawn_prog(pgm, spawn_arg);
1862 remove_tempfile();
1863 if (retval) {
1864 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1865 exit(1);
1869 static const char *external_diff_attr(const char *name)
1871 struct git_attr_check attr_diff_check;
1873 setup_diff_attr_check(&attr_diff_check);
1874 if (!git_checkattr(name, 1, &attr_diff_check)) {
1875 const char *value = attr_diff_check.value;
1876 if (!ATTR_TRUE(value) &&
1877 !ATTR_FALSE(value) &&
1878 !ATTR_UNSET(value)) {
1879 struct ll_diff_driver *drv;
1881 read_config_if_needed();
1882 for (drv = user_diff; drv; drv = drv->next)
1883 if (!strcmp(drv->name, value))
1884 return drv->cmd;
1887 return NULL;
1890 static void run_diff_cmd(const char *pgm,
1891 const char *name,
1892 const char *other,
1893 struct diff_filespec *one,
1894 struct diff_filespec *two,
1895 const char *xfrm_msg,
1896 struct diff_options *o,
1897 int complete_rewrite)
1899 if (!o->allow_external)
1900 pgm = NULL;
1901 else {
1902 const char *cmd = external_diff_attr(name);
1903 if (cmd)
1904 pgm = cmd;
1907 if (pgm) {
1908 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1909 complete_rewrite);
1910 return;
1912 if (one && two)
1913 builtin_diff(name, other ? other : name,
1914 one, two, xfrm_msg, o, complete_rewrite);
1915 else
1916 printf("* Unmerged path %s\n", name);
1919 static void diff_fill_sha1_info(struct diff_filespec *one)
1921 if (DIFF_FILE_VALID(one)) {
1922 if (!one->sha1_valid) {
1923 struct stat st;
1924 if (!strcmp(one->path, "-")) {
1925 hashcpy(one->sha1, null_sha1);
1926 return;
1928 if (lstat(one->path, &st) < 0)
1929 die("stat %s", one->path);
1930 if (index_path(one->sha1, one->path, &st, 0))
1931 die("cannot hash %s\n", one->path);
1934 else
1935 hashclr(one->sha1);
1938 static int similarity_index(struct diff_filepair *p)
1940 return p->score * 100 / MAX_SCORE;
1943 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1945 const char *pgm = external_diff();
1946 char msg[PATH_MAX*2+300], *xfrm_msg;
1947 struct diff_filespec *one;
1948 struct diff_filespec *two;
1949 const char *name;
1950 const char *other;
1951 char *name_munged, *other_munged;
1952 int complete_rewrite = 0;
1953 int len;
1955 if (DIFF_PAIR_UNMERGED(p)) {
1956 /* unmerged */
1957 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1958 return;
1961 name = p->one->path;
1962 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1963 name_munged = quote_one(name);
1964 other_munged = quote_one(other);
1965 one = p->one; two = p->two;
1967 diff_fill_sha1_info(one);
1968 diff_fill_sha1_info(two);
1970 len = 0;
1971 switch (p->status) {
1972 case DIFF_STATUS_COPIED:
1973 len += snprintf(msg + len, sizeof(msg) - len,
1974 "similarity index %d%%\n"
1975 "copy from %s\n"
1976 "copy to %s\n",
1977 similarity_index(p), name_munged, other_munged);
1978 break;
1979 case DIFF_STATUS_RENAMED:
1980 len += snprintf(msg + len, sizeof(msg) - len,
1981 "similarity index %d%%\n"
1982 "rename from %s\n"
1983 "rename to %s\n",
1984 similarity_index(p), name_munged, other_munged);
1985 break;
1986 case DIFF_STATUS_MODIFIED:
1987 if (p->score) {
1988 len += snprintf(msg + len, sizeof(msg) - len,
1989 "dissimilarity index %d%%\n",
1990 similarity_index(p));
1991 complete_rewrite = 1;
1992 break;
1994 /* fallthru */
1995 default:
1996 /* nothing */
2000 if (hashcmp(one->sha1, two->sha1)) {
2001 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
2003 if (o->binary) {
2004 mmfile_t mf;
2005 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2006 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2007 abbrev = 40;
2009 len += snprintf(msg + len, sizeof(msg) - len,
2010 "index %.*s..%.*s",
2011 abbrev, sha1_to_hex(one->sha1),
2012 abbrev, sha1_to_hex(two->sha1));
2013 if (one->mode == two->mode)
2014 len += snprintf(msg + len, sizeof(msg) - len,
2015 " %06o", one->mode);
2016 len += snprintf(msg + len, sizeof(msg) - len, "\n");
2019 if (len)
2020 msg[--len] = 0;
2021 xfrm_msg = len ? msg : NULL;
2023 if (!pgm &&
2024 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2025 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2026 /* a filepair that changes between file and symlink
2027 * needs to be split into deletion and creation.
2029 struct diff_filespec *null = alloc_filespec(two->path);
2030 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
2031 free(null);
2032 null = alloc_filespec(one->path);
2033 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
2034 free(null);
2036 else
2037 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
2038 complete_rewrite);
2040 free(name_munged);
2041 free(other_munged);
2044 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2045 struct diffstat_t *diffstat)
2047 const char *name;
2048 const char *other;
2049 int complete_rewrite = 0;
2051 if (DIFF_PAIR_UNMERGED(p)) {
2052 /* unmerged */
2053 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2054 return;
2057 name = p->one->path;
2058 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2060 diff_fill_sha1_info(p->one);
2061 diff_fill_sha1_info(p->two);
2063 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2064 complete_rewrite = 1;
2065 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2068 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2070 const char *name;
2071 const char *other;
2073 if (DIFF_PAIR_UNMERGED(p)) {
2074 /* unmerged */
2075 return;
2078 name = p->one->path;
2079 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2081 diff_fill_sha1_info(p->one);
2082 diff_fill_sha1_info(p->two);
2084 builtin_checkdiff(name, other, p->one, p->two, o);
2087 void diff_setup(struct diff_options *options)
2089 memset(options, 0, sizeof(*options));
2090 options->line_termination = '\n';
2091 options->break_opt = -1;
2092 options->rename_limit = -1;
2093 options->context = 3;
2094 options->msg_sep = "";
2096 options->change = diff_change;
2097 options->add_remove = diff_addremove;
2098 options->color_diff = diff_use_color_default;
2099 options->detect_rename = diff_detect_rename_default;
2102 int diff_setup_done(struct diff_options *options)
2104 int count = 0;
2106 if (options->output_format & DIFF_FORMAT_NAME)
2107 count++;
2108 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2109 count++;
2110 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2111 count++;
2112 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2113 count++;
2114 if (count > 1)
2115 die("--name-only, --name-status, --check and -s are mutually exclusive");
2117 if (options->find_copies_harder)
2118 options->detect_rename = DIFF_DETECT_COPY;
2120 if (options->output_format & (DIFF_FORMAT_NAME |
2121 DIFF_FORMAT_NAME_STATUS |
2122 DIFF_FORMAT_CHECKDIFF |
2123 DIFF_FORMAT_NO_OUTPUT))
2124 options->output_format &= ~(DIFF_FORMAT_RAW |
2125 DIFF_FORMAT_NUMSTAT |
2126 DIFF_FORMAT_DIFFSTAT |
2127 DIFF_FORMAT_SHORTSTAT |
2128 DIFF_FORMAT_SUMMARY |
2129 DIFF_FORMAT_PATCH);
2132 * These cases always need recursive; we do not drop caller-supplied
2133 * recursive bits for other formats here.
2135 if (options->output_format & (DIFF_FORMAT_PATCH |
2136 DIFF_FORMAT_NUMSTAT |
2137 DIFF_FORMAT_DIFFSTAT |
2138 DIFF_FORMAT_SHORTSTAT |
2139 DIFF_FORMAT_SUMMARY |
2140 DIFF_FORMAT_CHECKDIFF))
2141 options->recursive = 1;
2143 * Also pickaxe would not work very well if you do not say recursive
2145 if (options->pickaxe)
2146 options->recursive = 1;
2148 if (options->detect_rename && options->rename_limit < 0)
2149 options->rename_limit = diff_rename_limit_default;
2150 if (options->setup & DIFF_SETUP_USE_CACHE) {
2151 if (!active_cache)
2152 /* read-cache does not die even when it fails
2153 * so it is safe for us to do this here. Also
2154 * it does not smudge active_cache or active_nr
2155 * when it fails, so we do not have to worry about
2156 * cleaning it up ourselves either.
2158 read_cache();
2160 if (options->abbrev <= 0 || 40 < options->abbrev)
2161 options->abbrev = 40; /* full */
2164 * It does not make sense to show the first hit we happened
2165 * to have found. It does not make sense not to return with
2166 * exit code in such a case either.
2168 if (options->quiet) {
2169 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2170 options->exit_with_status = 1;
2174 * If we postprocess in diffcore, we cannot simply return
2175 * upon the first hit. We need to run diff as usual.
2177 if (options->pickaxe || options->filter)
2178 options->quiet = 0;
2180 return 0;
2183 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2185 char c, *eq;
2186 int len;
2188 if (*arg != '-')
2189 return 0;
2190 c = *++arg;
2191 if (!c)
2192 return 0;
2193 if (c == arg_short) {
2194 c = *++arg;
2195 if (!c)
2196 return 1;
2197 if (val && isdigit(c)) {
2198 char *end;
2199 int n = strtoul(arg, &end, 10);
2200 if (*end)
2201 return 0;
2202 *val = n;
2203 return 1;
2205 return 0;
2207 if (c != '-')
2208 return 0;
2209 arg++;
2210 eq = strchr(arg, '=');
2211 if (eq)
2212 len = eq - arg;
2213 else
2214 len = strlen(arg);
2215 if (!len || strncmp(arg, arg_long, len))
2216 return 0;
2217 if (eq) {
2218 int n;
2219 char *end;
2220 if (!isdigit(*++eq))
2221 return 0;
2222 n = strtoul(eq, &end, 10);
2223 if (*end)
2224 return 0;
2225 *val = n;
2227 return 1;
2230 static int diff_scoreopt_parse(const char *opt);
2232 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2234 const char *arg = av[0];
2235 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2236 options->output_format |= DIFF_FORMAT_PATCH;
2237 else if (opt_arg(arg, 'U', "unified", &options->context))
2238 options->output_format |= DIFF_FORMAT_PATCH;
2239 else if (!strcmp(arg, "--raw"))
2240 options->output_format |= DIFF_FORMAT_RAW;
2241 else if (!strcmp(arg, "--patch-with-raw")) {
2242 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2244 else if (!strcmp(arg, "--numstat")) {
2245 options->output_format |= DIFF_FORMAT_NUMSTAT;
2247 else if (!strcmp(arg, "--shortstat")) {
2248 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2250 else if (!prefixcmp(arg, "--stat")) {
2251 char *end;
2252 int width = options->stat_width;
2253 int name_width = options->stat_name_width;
2254 arg += 6;
2255 end = (char *)arg;
2257 switch (*arg) {
2258 case '-':
2259 if (!prefixcmp(arg, "-width="))
2260 width = strtoul(arg + 7, &end, 10);
2261 else if (!prefixcmp(arg, "-name-width="))
2262 name_width = strtoul(arg + 12, &end, 10);
2263 break;
2264 case '=':
2265 width = strtoul(arg+1, &end, 10);
2266 if (*end == ',')
2267 name_width = strtoul(end+1, &end, 10);
2270 /* Important! This checks all the error cases! */
2271 if (*end)
2272 return 0;
2273 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2274 options->stat_name_width = name_width;
2275 options->stat_width = width;
2277 else if (!strcmp(arg, "--check"))
2278 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2279 else if (!strcmp(arg, "--summary"))
2280 options->output_format |= DIFF_FORMAT_SUMMARY;
2281 else if (!strcmp(arg, "--patch-with-stat")) {
2282 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2284 else if (!strcmp(arg, "-z"))
2285 options->line_termination = 0;
2286 else if (!prefixcmp(arg, "-l"))
2287 options->rename_limit = strtoul(arg+2, NULL, 10);
2288 else if (!strcmp(arg, "--full-index"))
2289 options->full_index = 1;
2290 else if (!strcmp(arg, "--binary")) {
2291 options->output_format |= DIFF_FORMAT_PATCH;
2292 options->binary = 1;
2294 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
2295 options->text = 1;
2297 else if (!strcmp(arg, "--name-only"))
2298 options->output_format |= DIFF_FORMAT_NAME;
2299 else if (!strcmp(arg, "--name-status"))
2300 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2301 else if (!strcmp(arg, "-R"))
2302 options->reverse_diff = 1;
2303 else if (!prefixcmp(arg, "-S"))
2304 options->pickaxe = arg + 2;
2305 else if (!strcmp(arg, "-s")) {
2306 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2308 else if (!prefixcmp(arg, "-O"))
2309 options->orderfile = arg + 2;
2310 else if (!prefixcmp(arg, "--diff-filter="))
2311 options->filter = arg + 14;
2312 else if (!strcmp(arg, "--pickaxe-all"))
2313 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2314 else if (!strcmp(arg, "--pickaxe-regex"))
2315 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2316 else if (!prefixcmp(arg, "-B")) {
2317 if ((options->break_opt =
2318 diff_scoreopt_parse(arg)) == -1)
2319 return -1;
2321 else if (!prefixcmp(arg, "-M")) {
2322 if ((options->rename_score =
2323 diff_scoreopt_parse(arg)) == -1)
2324 return -1;
2325 options->detect_rename = DIFF_DETECT_RENAME;
2327 else if (!prefixcmp(arg, "-C")) {
2328 if (options->detect_rename == DIFF_DETECT_COPY)
2329 options->find_copies_harder = 1;
2330 if ((options->rename_score =
2331 diff_scoreopt_parse(arg)) == -1)
2332 return -1;
2333 options->detect_rename = DIFF_DETECT_COPY;
2335 else if (!strcmp(arg, "--find-copies-harder"))
2336 options->find_copies_harder = 1;
2337 else if (!strcmp(arg, "--follow"))
2338 options->follow_renames = 1;
2339 else if (!strcmp(arg, "--abbrev"))
2340 options->abbrev = DEFAULT_ABBREV;
2341 else if (!prefixcmp(arg, "--abbrev=")) {
2342 options->abbrev = strtoul(arg + 9, NULL, 10);
2343 if (options->abbrev < MINIMUM_ABBREV)
2344 options->abbrev = MINIMUM_ABBREV;
2345 else if (40 < options->abbrev)
2346 options->abbrev = 40;
2348 else if (!strcmp(arg, "--color"))
2349 options->color_diff = 1;
2350 else if (!strcmp(arg, "--no-color"))
2351 options->color_diff = 0;
2352 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2353 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2354 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2355 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2356 else if (!strcmp(arg, "--ignore-space-at-eol"))
2357 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2358 else if (!strcmp(arg, "--color-words"))
2359 options->color_diff = options->color_diff_words = 1;
2360 else if (!strcmp(arg, "--no-renames"))
2361 options->detect_rename = 0;
2362 else if (!strcmp(arg, "--exit-code"))
2363 options->exit_with_status = 1;
2364 else if (!strcmp(arg, "--quiet"))
2365 options->quiet = 1;
2366 else if (!strcmp(arg, "--ext-diff"))
2367 options->allow_external = 1;
2368 else if (!strcmp(arg, "--no-ext-diff"))
2369 options->allow_external = 0;
2370 else
2371 return 0;
2372 return 1;
2375 static int parse_num(const char **cp_p)
2377 unsigned long num, scale;
2378 int ch, dot;
2379 const char *cp = *cp_p;
2381 num = 0;
2382 scale = 1;
2383 dot = 0;
2384 for(;;) {
2385 ch = *cp;
2386 if ( !dot && ch == '.' ) {
2387 scale = 1;
2388 dot = 1;
2389 } else if ( ch == '%' ) {
2390 scale = dot ? scale*100 : 100;
2391 cp++; /* % is always at the end */
2392 break;
2393 } else if ( ch >= '0' && ch <= '9' ) {
2394 if ( scale < 100000 ) {
2395 scale *= 10;
2396 num = (num*10) + (ch-'0');
2398 } else {
2399 break;
2401 cp++;
2403 *cp_p = cp;
2405 /* user says num divided by scale and we say internally that
2406 * is MAX_SCORE * num / scale.
2408 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2411 static int diff_scoreopt_parse(const char *opt)
2413 int opt1, opt2, cmd;
2415 if (*opt++ != '-')
2416 return -1;
2417 cmd = *opt++;
2418 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2419 return -1; /* that is not a -M, -C nor -B option */
2421 opt1 = parse_num(&opt);
2422 if (cmd != 'B')
2423 opt2 = 0;
2424 else {
2425 if (*opt == 0)
2426 opt2 = 0;
2427 else if (*opt != '/')
2428 return -1; /* we expect -B80/99 or -B80 */
2429 else {
2430 opt++;
2431 opt2 = parse_num(&opt);
2434 if (*opt != 0)
2435 return -1;
2436 return opt1 | (opt2 << 16);
2439 struct diff_queue_struct diff_queued_diff;
2441 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2443 if (queue->alloc <= queue->nr) {
2444 queue->alloc = alloc_nr(queue->alloc);
2445 queue->queue = xrealloc(queue->queue,
2446 sizeof(dp) * queue->alloc);
2448 queue->queue[queue->nr++] = dp;
2451 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2452 struct diff_filespec *one,
2453 struct diff_filespec *two)
2455 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2456 dp->one = one;
2457 dp->two = two;
2458 if (queue)
2459 diff_q(queue, dp);
2460 return dp;
2463 void diff_free_filepair(struct diff_filepair *p)
2465 diff_free_filespec_data(p->one);
2466 diff_free_filespec_data(p->two);
2467 free(p->one);
2468 free(p->two);
2469 free(p);
2472 /* This is different from find_unique_abbrev() in that
2473 * it stuffs the result with dots for alignment.
2475 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2477 int abblen;
2478 const char *abbrev;
2479 if (len == 40)
2480 return sha1_to_hex(sha1);
2482 abbrev = find_unique_abbrev(sha1, len);
2483 if (!abbrev)
2484 return sha1_to_hex(sha1);
2485 abblen = strlen(abbrev);
2486 if (abblen < 37) {
2487 static char hex[41];
2488 if (len < abblen && abblen <= len + 2)
2489 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2490 else
2491 sprintf(hex, "%s...", abbrev);
2492 return hex;
2494 return sha1_to_hex(sha1);
2497 static void diff_flush_raw(struct diff_filepair *p,
2498 struct diff_options *options)
2500 int two_paths;
2501 char status[10];
2502 int abbrev = options->abbrev;
2503 const char *path_one, *path_two;
2504 int inter_name_termination = '\t';
2505 int line_termination = options->line_termination;
2507 if (!line_termination)
2508 inter_name_termination = 0;
2510 path_one = p->one->path;
2511 path_two = p->two->path;
2512 if (line_termination) {
2513 path_one = quote_one(path_one);
2514 path_two = quote_one(path_two);
2517 if (p->score)
2518 sprintf(status, "%c%03d", p->status, similarity_index(p));
2519 else {
2520 status[0] = p->status;
2521 status[1] = 0;
2523 switch (p->status) {
2524 case DIFF_STATUS_COPIED:
2525 case DIFF_STATUS_RENAMED:
2526 two_paths = 1;
2527 break;
2528 case DIFF_STATUS_ADDED:
2529 case DIFF_STATUS_DELETED:
2530 two_paths = 0;
2531 break;
2532 default:
2533 two_paths = 0;
2534 break;
2536 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2537 printf(":%06o %06o %s ",
2538 p->one->mode, p->two->mode,
2539 diff_unique_abbrev(p->one->sha1, abbrev));
2540 printf("%s ",
2541 diff_unique_abbrev(p->two->sha1, abbrev));
2543 printf("%s%c%s", status, inter_name_termination,
2544 two_paths || p->one->mode ? path_one : path_two);
2545 if (two_paths)
2546 printf("%c%s", inter_name_termination, path_two);
2547 putchar(line_termination);
2548 if (path_one != p->one->path)
2549 free((void*)path_one);
2550 if (path_two != p->two->path)
2551 free((void*)path_two);
2554 static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2556 char *path = p->two->path;
2558 if (opt->line_termination)
2559 path = quote_one(p->two->path);
2560 printf("%s%c", path, opt->line_termination);
2561 if (p->two->path != path)
2562 free(path);
2565 int diff_unmodified_pair(struct diff_filepair *p)
2567 /* This function is written stricter than necessary to support
2568 * the currently implemented transformers, but the idea is to
2569 * let transformers to produce diff_filepairs any way they want,
2570 * and filter and clean them up here before producing the output.
2572 struct diff_filespec *one, *two;
2574 if (DIFF_PAIR_UNMERGED(p))
2575 return 0; /* unmerged is interesting */
2577 one = p->one;
2578 two = p->two;
2580 /* deletion, addition, mode or type change
2581 * and rename are all interesting.
2583 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2584 DIFF_PAIR_MODE_CHANGED(p) ||
2585 strcmp(one->path, two->path))
2586 return 0;
2588 /* both are valid and point at the same path. that is, we are
2589 * dealing with a change.
2591 if (one->sha1_valid && two->sha1_valid &&
2592 !hashcmp(one->sha1, two->sha1))
2593 return 1; /* no change */
2594 if (!one->sha1_valid && !two->sha1_valid)
2595 return 1; /* both look at the same file on the filesystem. */
2596 return 0;
2599 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2601 if (diff_unmodified_pair(p))
2602 return;
2604 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2605 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2606 return; /* no tree diffs in patch format */
2608 run_diff(p, o);
2611 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2612 struct diffstat_t *diffstat)
2614 if (diff_unmodified_pair(p))
2615 return;
2617 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2618 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2619 return; /* no tree diffs in patch format */
2621 run_diffstat(p, o, diffstat);
2624 static void diff_flush_checkdiff(struct diff_filepair *p,
2625 struct diff_options *o)
2627 if (diff_unmodified_pair(p))
2628 return;
2630 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2631 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2632 return; /* no tree diffs in patch format */
2634 run_checkdiff(p, o);
2637 int diff_queue_is_empty(void)
2639 struct diff_queue_struct *q = &diff_queued_diff;
2640 int i;
2641 for (i = 0; i < q->nr; i++)
2642 if (!diff_unmodified_pair(q->queue[i]))
2643 return 0;
2644 return 1;
2647 #if DIFF_DEBUG
2648 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2650 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2651 x, one ? one : "",
2652 s->path,
2653 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2654 s->mode,
2655 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2656 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2657 x, one ? one : "",
2658 s->size, s->xfrm_flags);
2661 void diff_debug_filepair(const struct diff_filepair *p, int i)
2663 diff_debug_filespec(p->one, i, "one");
2664 diff_debug_filespec(p->two, i, "two");
2665 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2666 p->score, p->status ? p->status : '?',
2667 p->source_stays, p->broken_pair);
2670 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2672 int i;
2673 if (msg)
2674 fprintf(stderr, "%s\n", msg);
2675 fprintf(stderr, "q->nr = %d\n", q->nr);
2676 for (i = 0; i < q->nr; i++) {
2677 struct diff_filepair *p = q->queue[i];
2678 diff_debug_filepair(p, i);
2681 #endif
2683 static void diff_resolve_rename_copy(void)
2685 int i, j;
2686 struct diff_filepair *p, *pp;
2687 struct diff_queue_struct *q = &diff_queued_diff;
2689 diff_debug_queue("resolve-rename-copy", q);
2691 for (i = 0; i < q->nr; i++) {
2692 p = q->queue[i];
2693 p->status = 0; /* undecided */
2694 if (DIFF_PAIR_UNMERGED(p))
2695 p->status = DIFF_STATUS_UNMERGED;
2696 else if (!DIFF_FILE_VALID(p->one))
2697 p->status = DIFF_STATUS_ADDED;
2698 else if (!DIFF_FILE_VALID(p->two))
2699 p->status = DIFF_STATUS_DELETED;
2700 else if (DIFF_PAIR_TYPE_CHANGED(p))
2701 p->status = DIFF_STATUS_TYPE_CHANGED;
2703 /* from this point on, we are dealing with a pair
2704 * whose both sides are valid and of the same type, i.e.
2705 * either in-place edit or rename/copy edit.
2707 else if (DIFF_PAIR_RENAME(p)) {
2708 if (p->source_stays) {
2709 p->status = DIFF_STATUS_COPIED;
2710 continue;
2712 /* See if there is some other filepair that
2713 * copies from the same source as us. If so
2714 * we are a copy. Otherwise we are either a
2715 * copy if the path stays, or a rename if it
2716 * does not, but we already handled "stays" case.
2718 for (j = i + 1; j < q->nr; j++) {
2719 pp = q->queue[j];
2720 if (strcmp(pp->one->path, p->one->path))
2721 continue; /* not us */
2722 if (!DIFF_PAIR_RENAME(pp))
2723 continue; /* not a rename/copy */
2724 /* pp is a rename/copy from the same source */
2725 p->status = DIFF_STATUS_COPIED;
2726 break;
2728 if (!p->status)
2729 p->status = DIFF_STATUS_RENAMED;
2731 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2732 p->one->mode != p->two->mode ||
2733 is_null_sha1(p->one->sha1))
2734 p->status = DIFF_STATUS_MODIFIED;
2735 else {
2736 /* This is a "no-change" entry and should not
2737 * happen anymore, but prepare for broken callers.
2739 error("feeding unmodified %s to diffcore",
2740 p->one->path);
2741 p->status = DIFF_STATUS_UNKNOWN;
2744 diff_debug_queue("resolve-rename-copy done", q);
2747 static int check_pair_status(struct diff_filepair *p)
2749 switch (p->status) {
2750 case DIFF_STATUS_UNKNOWN:
2751 return 0;
2752 case 0:
2753 die("internal error in diff-resolve-rename-copy");
2754 default:
2755 return 1;
2759 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2761 int fmt = opt->output_format;
2763 if (fmt & DIFF_FORMAT_CHECKDIFF)
2764 diff_flush_checkdiff(p, opt);
2765 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2766 diff_flush_raw(p, opt);
2767 else if (fmt & DIFF_FORMAT_NAME)
2768 diff_flush_name(p, opt);
2771 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2773 char *name = quote_one(fs->path);
2774 if (fs->mode)
2775 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2776 else
2777 printf(" %s %s\n", newdelete, name);
2778 free(name);
2782 static void show_mode_change(struct diff_filepair *p, int show_name)
2784 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2785 if (show_name) {
2786 char *name = quote_one(p->two->path);
2787 printf(" mode change %06o => %06o %s\n",
2788 p->one->mode, p->two->mode, name);
2789 free(name);
2791 else
2792 printf(" mode change %06o => %06o\n",
2793 p->one->mode, p->two->mode);
2797 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2799 char *names = pprint_rename(p->one->path, p->two->path);
2801 printf(" %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2802 free(names);
2803 show_mode_change(p, 0);
2806 static void diff_summary(struct diff_filepair *p)
2808 switch(p->status) {
2809 case DIFF_STATUS_DELETED:
2810 show_file_mode_name("delete", p->one);
2811 break;
2812 case DIFF_STATUS_ADDED:
2813 show_file_mode_name("create", p->two);
2814 break;
2815 case DIFF_STATUS_COPIED:
2816 show_rename_copy("copy", p);
2817 break;
2818 case DIFF_STATUS_RENAMED:
2819 show_rename_copy("rename", p);
2820 break;
2821 default:
2822 if (p->score) {
2823 char *name = quote_one(p->two->path);
2824 printf(" rewrite %s (%d%%)\n", name,
2825 similarity_index(p));
2826 free(name);
2827 show_mode_change(p, 0);
2828 } else show_mode_change(p, 1);
2829 break;
2833 struct patch_id_t {
2834 struct xdiff_emit_state xm;
2835 SHA_CTX *ctx;
2836 int patchlen;
2839 static int remove_space(char *line, int len)
2841 int i;
2842 char *dst = line;
2843 unsigned char c;
2845 for (i = 0; i < len; i++)
2846 if (!isspace((c = line[i])))
2847 *dst++ = c;
2849 return dst - line;
2852 static void patch_id_consume(void *priv, char *line, unsigned long len)
2854 struct patch_id_t *data = priv;
2855 int new_len;
2857 /* Ignore line numbers when computing the SHA1 of the patch */
2858 if (!prefixcmp(line, "@@ -"))
2859 return;
2861 new_len = remove_space(line, len);
2863 SHA1_Update(data->ctx, line, new_len);
2864 data->patchlen += new_len;
2867 /* returns 0 upon success, and writes result into sha1 */
2868 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2870 struct diff_queue_struct *q = &diff_queued_diff;
2871 int i;
2872 SHA_CTX ctx;
2873 struct patch_id_t data;
2874 char buffer[PATH_MAX * 4 + 20];
2876 SHA1_Init(&ctx);
2877 memset(&data, 0, sizeof(struct patch_id_t));
2878 data.ctx = &ctx;
2879 data.xm.consume = patch_id_consume;
2881 for (i = 0; i < q->nr; i++) {
2882 xpparam_t xpp;
2883 xdemitconf_t xecfg;
2884 xdemitcb_t ecb;
2885 mmfile_t mf1, mf2;
2886 struct diff_filepair *p = q->queue[i];
2887 int len1, len2;
2889 memset(&xecfg, 0, sizeof(xecfg));
2890 if (p->status == 0)
2891 return error("internal diff status error");
2892 if (p->status == DIFF_STATUS_UNKNOWN)
2893 continue;
2894 if (diff_unmodified_pair(p))
2895 continue;
2896 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2897 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2898 continue;
2899 if (DIFF_PAIR_UNMERGED(p))
2900 continue;
2902 diff_fill_sha1_info(p->one);
2903 diff_fill_sha1_info(p->two);
2904 if (fill_mmfile(&mf1, p->one) < 0 ||
2905 fill_mmfile(&mf2, p->two) < 0)
2906 return error("unable to read files to diff");
2908 /* Maybe hash p->two? into the patch id? */
2909 if (diff_filespec_is_binary(p->two))
2910 continue;
2912 len1 = remove_space(p->one->path, strlen(p->one->path));
2913 len2 = remove_space(p->two->path, strlen(p->two->path));
2914 if (p->one->mode == 0)
2915 len1 = snprintf(buffer, sizeof(buffer),
2916 "diff--gita/%.*sb/%.*s"
2917 "newfilemode%06o"
2918 "---/dev/null"
2919 "+++b/%.*s",
2920 len1, p->one->path,
2921 len2, p->two->path,
2922 p->two->mode,
2923 len2, p->two->path);
2924 else if (p->two->mode == 0)
2925 len1 = snprintf(buffer, sizeof(buffer),
2926 "diff--gita/%.*sb/%.*s"
2927 "deletedfilemode%06o"
2928 "---a/%.*s"
2929 "+++/dev/null",
2930 len1, p->one->path,
2931 len2, p->two->path,
2932 p->one->mode,
2933 len1, p->one->path);
2934 else
2935 len1 = snprintf(buffer, sizeof(buffer),
2936 "diff--gita/%.*sb/%.*s"
2937 "---a/%.*s"
2938 "+++b/%.*s",
2939 len1, p->one->path,
2940 len2, p->two->path,
2941 len1, p->one->path,
2942 len2, p->two->path);
2943 SHA1_Update(&ctx, buffer, len1);
2945 xpp.flags = XDF_NEED_MINIMAL;
2946 xecfg.ctxlen = 3;
2947 xecfg.flags = XDL_EMIT_FUNCNAMES;
2948 ecb.outf = xdiff_outf;
2949 ecb.priv = &data;
2950 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2953 SHA1_Final(sha1, &ctx);
2954 return 0;
2957 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2959 struct diff_queue_struct *q = &diff_queued_diff;
2960 int i;
2961 int result = diff_get_patch_id(options, sha1);
2963 for (i = 0; i < q->nr; i++)
2964 diff_free_filepair(q->queue[i]);
2966 free(q->queue);
2967 q->queue = NULL;
2968 q->nr = q->alloc = 0;
2970 return result;
2973 static int is_summary_empty(const struct diff_queue_struct *q)
2975 int i;
2977 for (i = 0; i < q->nr; i++) {
2978 const struct diff_filepair *p = q->queue[i];
2980 switch (p->status) {
2981 case DIFF_STATUS_DELETED:
2982 case DIFF_STATUS_ADDED:
2983 case DIFF_STATUS_COPIED:
2984 case DIFF_STATUS_RENAMED:
2985 return 0;
2986 default:
2987 if (p->score)
2988 return 0;
2989 if (p->one->mode && p->two->mode &&
2990 p->one->mode != p->two->mode)
2991 return 0;
2992 break;
2995 return 1;
2998 void diff_flush(struct diff_options *options)
3000 struct diff_queue_struct *q = &diff_queued_diff;
3001 int i, output_format = options->output_format;
3002 int separator = 0;
3005 * Order: raw, stat, summary, patch
3006 * or: name/name-status/checkdiff (other bits clear)
3008 if (!q->nr)
3009 goto free_queue;
3011 if (output_format & (DIFF_FORMAT_RAW |
3012 DIFF_FORMAT_NAME |
3013 DIFF_FORMAT_NAME_STATUS |
3014 DIFF_FORMAT_CHECKDIFF)) {
3015 for (i = 0; i < q->nr; i++) {
3016 struct diff_filepair *p = q->queue[i];
3017 if (check_pair_status(p))
3018 flush_one_pair(p, options);
3020 separator++;
3023 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3024 struct diffstat_t diffstat;
3026 memset(&diffstat, 0, sizeof(struct diffstat_t));
3027 diffstat.xm.consume = diffstat_consume;
3028 for (i = 0; i < q->nr; i++) {
3029 struct diff_filepair *p = q->queue[i];
3030 if (check_pair_status(p))
3031 diff_flush_stat(p, options, &diffstat);
3033 if (output_format & DIFF_FORMAT_NUMSTAT)
3034 show_numstat(&diffstat, options);
3035 if (output_format & DIFF_FORMAT_DIFFSTAT)
3036 show_stats(&diffstat, options);
3037 else if (output_format & DIFF_FORMAT_SHORTSTAT)
3038 show_shortstats(&diffstat);
3039 separator++;
3042 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3043 for (i = 0; i < q->nr; i++)
3044 diff_summary(q->queue[i]);
3045 separator++;
3048 if (output_format & DIFF_FORMAT_PATCH) {
3049 if (separator) {
3050 if (options->stat_sep) {
3051 /* attach patch instead of inline */
3052 fputs(options->stat_sep, stdout);
3053 } else {
3054 putchar(options->line_termination);
3058 for (i = 0; i < q->nr; i++) {
3059 struct diff_filepair *p = q->queue[i];
3060 if (check_pair_status(p))
3061 diff_flush_patch(p, options);
3065 if (output_format & DIFF_FORMAT_CALLBACK)
3066 options->format_callback(q, options, options->format_callback_data);
3068 for (i = 0; i < q->nr; i++)
3069 diff_free_filepair(q->queue[i]);
3070 free_queue:
3071 free(q->queue);
3072 q->queue = NULL;
3073 q->nr = q->alloc = 0;
3076 static void diffcore_apply_filter(const char *filter)
3078 int i;
3079 struct diff_queue_struct *q = &diff_queued_diff;
3080 struct diff_queue_struct outq;
3081 outq.queue = NULL;
3082 outq.nr = outq.alloc = 0;
3084 if (!filter)
3085 return;
3087 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3088 int found;
3089 for (i = found = 0; !found && i < q->nr; i++) {
3090 struct diff_filepair *p = q->queue[i];
3091 if (((p->status == DIFF_STATUS_MODIFIED) &&
3092 ((p->score &&
3093 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3094 (!p->score &&
3095 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3096 ((p->status != DIFF_STATUS_MODIFIED) &&
3097 strchr(filter, p->status)))
3098 found++;
3100 if (found)
3101 return;
3103 /* otherwise we will clear the whole queue
3104 * by copying the empty outq at the end of this
3105 * function, but first clear the current entries
3106 * in the queue.
3108 for (i = 0; i < q->nr; i++)
3109 diff_free_filepair(q->queue[i]);
3111 else {
3112 /* Only the matching ones */
3113 for (i = 0; i < q->nr; i++) {
3114 struct diff_filepair *p = q->queue[i];
3116 if (((p->status == DIFF_STATUS_MODIFIED) &&
3117 ((p->score &&
3118 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3119 (!p->score &&
3120 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3121 ((p->status != DIFF_STATUS_MODIFIED) &&
3122 strchr(filter, p->status)))
3123 diff_q(&outq, p);
3124 else
3125 diff_free_filepair(p);
3128 free(q->queue);
3129 *q = outq;
3132 void diffcore_std(struct diff_options *options)
3134 if (options->quiet)
3135 return;
3137 if (options->break_opt != -1)
3138 diffcore_break(options->break_opt);
3139 if (options->detect_rename)
3140 diffcore_rename(options);
3141 if (options->break_opt != -1)
3142 diffcore_merge_broken();
3143 if (options->pickaxe)
3144 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3145 if (options->orderfile)
3146 diffcore_order(options->orderfile);
3147 diff_resolve_rename_copy();
3148 diffcore_apply_filter(options->filter);
3150 options->has_changes = !!diff_queued_diff.nr;
3154 void diff_addremove(struct diff_options *options,
3155 int addremove, unsigned mode,
3156 const unsigned char *sha1,
3157 const char *base, const char *path)
3159 char concatpath[PATH_MAX];
3160 struct diff_filespec *one, *two;
3162 /* This may look odd, but it is a preparation for
3163 * feeding "there are unchanged files which should
3164 * not produce diffs, but when you are doing copy
3165 * detection you would need them, so here they are"
3166 * entries to the diff-core. They will be prefixed
3167 * with something like '=' or '*' (I haven't decided
3168 * which but should not make any difference).
3169 * Feeding the same new and old to diff_change()
3170 * also has the same effect.
3171 * Before the final output happens, they are pruned after
3172 * merged into rename/copy pairs as appropriate.
3174 if (options->reverse_diff)
3175 addremove = (addremove == '+' ? '-' :
3176 addremove == '-' ? '+' : addremove);
3178 if (!path) path = "";
3179 sprintf(concatpath, "%s%s", base, path);
3180 one = alloc_filespec(concatpath);
3181 two = alloc_filespec(concatpath);
3183 if (addremove != '+')
3184 fill_filespec(one, sha1, mode);
3185 if (addremove != '-')
3186 fill_filespec(two, sha1, mode);
3188 diff_queue(&diff_queued_diff, one, two);
3189 options->has_changes = 1;
3192 void diff_change(struct diff_options *options,
3193 unsigned old_mode, unsigned new_mode,
3194 const unsigned char *old_sha1,
3195 const unsigned char *new_sha1,
3196 const char *base, const char *path)
3198 char concatpath[PATH_MAX];
3199 struct diff_filespec *one, *two;
3201 if (options->reverse_diff) {
3202 unsigned tmp;
3203 const unsigned char *tmp_c;
3204 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3205 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3207 if (!path) path = "";
3208 sprintf(concatpath, "%s%s", base, path);
3209 one = alloc_filespec(concatpath);
3210 two = alloc_filespec(concatpath);
3211 fill_filespec(one, old_sha1, old_mode);
3212 fill_filespec(two, new_sha1, new_mode);
3214 diff_queue(&diff_queued_diff, one, two);
3215 options->has_changes = 1;
3218 void diff_unmerge(struct diff_options *options,
3219 const char *path,
3220 unsigned mode, const unsigned char *sha1)
3222 struct diff_filespec *one, *two;
3223 one = alloc_filespec(path);
3224 two = alloc_filespec(path);
3225 fill_filespec(one, sha1, mode);
3226 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;