patch: strip all dirs if patch_level is -1
[git/pclouds.git] / diff.c
blob62961eca6a85ca3ce727eaec77da515402f8a223
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"
12 #include "spawn-pipe.h"
14 #ifdef NO_FAST_WORKING_DIRECTORY
15 #define FAST_WORKING_DIRECTORY 0
16 #else
17 #define FAST_WORKING_DIRECTORY 1
18 #endif
20 static int diff_detect_rename_default;
21 static int diff_rename_limit_default = -1;
22 static int diff_use_color_default;
24 static char diff_colors[][COLOR_MAXLEN] = {
25 "\033[m", /* reset */
26 "", /* PLAIN (normal) */
27 "\033[1m", /* METAINFO (bold) */
28 "\033[36m", /* FRAGINFO (cyan) */
29 "\033[31m", /* OLD (red) */
30 "\033[32m", /* NEW (green) */
31 "\033[33m", /* COMMIT (yellow) */
32 "\033[41m", /* WHITESPACE (red background) */
35 static int parse_diff_color_slot(const char *var, int ofs)
37 if (!strcasecmp(var+ofs, "plain"))
38 return DIFF_PLAIN;
39 if (!strcasecmp(var+ofs, "meta"))
40 return DIFF_METAINFO;
41 if (!strcasecmp(var+ofs, "frag"))
42 return DIFF_FRAGINFO;
43 if (!strcasecmp(var+ofs, "old"))
44 return DIFF_FILE_OLD;
45 if (!strcasecmp(var+ofs, "new"))
46 return DIFF_FILE_NEW;
47 if (!strcasecmp(var+ofs, "commit"))
48 return DIFF_COMMIT;
49 if (!strcasecmp(var+ofs, "whitespace"))
50 return DIFF_WHITESPACE;
51 die("bad config variable '%s'", var);
54 static struct ll_diff_driver {
55 const char *name;
56 struct ll_diff_driver *next;
57 char *cmd;
58 } *user_diff, **user_diff_tail;
60 static void read_config_if_needed(void)
62 if (!user_diff_tail) {
63 user_diff_tail = &user_diff;
64 git_config(git_diff_ui_config);
69 * Currently there is only "diff.<drivername>.command" variable;
70 * because there are "diff.color.<slot>" variables, we are parsing
71 * this in a bit convoluted way to allow low level diff driver
72 * called "color".
74 static int parse_lldiff_command(const char *var, const char *ep, const char *value)
76 const char *name;
77 int namelen;
78 struct ll_diff_driver *drv;
80 name = var + 5;
81 namelen = ep - name;
82 for (drv = user_diff; drv; drv = drv->next)
83 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
84 break;
85 if (!drv) {
86 char *namebuf;
87 drv = xcalloc(1, sizeof(struct ll_diff_driver));
88 namebuf = xmalloc(namelen + 1);
89 memcpy(namebuf, name, namelen);
90 namebuf[namelen] = 0;
91 drv->name = namebuf;
92 drv->next = NULL;
93 if (!user_diff_tail)
94 user_diff_tail = &user_diff;
95 *user_diff_tail = drv;
96 user_diff_tail = &(drv->next);
99 if (!value)
100 return error("%s: lacks value", var);
101 drv->cmd = strdup(value);
102 return 0;
106 * 'diff.<what>.funcname' attribute can be specified in the configuration
107 * to define a customized regexp to find the beginning of a function to
108 * be used for hunk header lines of "diff -p" style output.
110 static struct funcname_pattern {
111 char *name;
112 char *pattern;
113 struct funcname_pattern *next;
114 } *funcname_pattern_list;
116 static int parse_funcname_pattern(const char *var, const char *ep, const char *value)
118 const char *name;
119 int namelen;
120 struct funcname_pattern *pp;
122 name = var + 5; /* "diff." */
123 namelen = ep - name;
125 for (pp = funcname_pattern_list; pp; pp = pp->next)
126 if (!strncmp(pp->name, name, namelen) && !pp->name[namelen])
127 break;
128 if (!pp) {
129 char *namebuf;
130 pp = xcalloc(1, sizeof(*pp));
131 namebuf = xmalloc(namelen + 1);
132 memcpy(namebuf, name, namelen);
133 namebuf[namelen] = 0;
134 pp->name = namebuf;
135 pp->next = funcname_pattern_list;
136 funcname_pattern_list = pp;
138 if (pp->pattern)
139 free(pp->pattern);
140 pp->pattern = xstrdup(value);
141 return 0;
145 * These are to give UI layer defaults.
146 * The core-level commands such as git-diff-files should
147 * never be affected by the setting of diff.renames
148 * the user happens to have in the configuration file.
150 int git_diff_ui_config(const char *var, const char *value)
152 if (!strcmp(var, "diff.renamelimit")) {
153 diff_rename_limit_default = git_config_int(var, value);
154 return 0;
156 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
157 diff_use_color_default = git_config_colorbool(var, value);
158 return 0;
160 if (!strcmp(var, "diff.renames")) {
161 if (!value)
162 diff_detect_rename_default = DIFF_DETECT_RENAME;
163 else if (!strcasecmp(value, "copies") ||
164 !strcasecmp(value, "copy"))
165 diff_detect_rename_default = DIFF_DETECT_COPY;
166 else if (git_config_bool(var,value))
167 diff_detect_rename_default = DIFF_DETECT_RENAME;
168 return 0;
170 if (!prefixcmp(var, "diff.")) {
171 const char *ep = strrchr(var, '.');
173 if (ep != var + 4) {
174 if (!strcmp(ep, ".command"))
175 return parse_lldiff_command(var, ep, value);
176 if (!strcmp(ep, ".funcname"))
177 return parse_funcname_pattern(var, ep, value);
180 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
181 int slot = parse_diff_color_slot(var, 11);
182 color_parse(value, var, diff_colors[slot]);
183 return 0;
186 return git_default_config(var, value);
189 static char *quote_one(const char *str)
191 int needlen;
192 char *xp;
194 if (!str)
195 return NULL;
196 needlen = quote_c_style(str, NULL, NULL, 0);
197 if (!needlen)
198 return xstrdup(str);
199 xp = xmalloc(needlen + 1);
200 quote_c_style(str, xp, NULL, 0);
201 return xp;
204 static char *quote_two(const char *one, const char *two)
206 int need_one = quote_c_style(one, NULL, NULL, 1);
207 int need_two = quote_c_style(two, NULL, NULL, 1);
208 char *xp;
210 if (need_one + need_two) {
211 if (!need_one) need_one = strlen(one);
212 if (!need_two) need_one = strlen(two);
214 xp = xmalloc(need_one + need_two + 3);
215 xp[0] = '"';
216 quote_c_style(one, xp + 1, NULL, 1);
217 quote_c_style(two, xp + need_one + 1, NULL, 1);
218 strcpy(xp + need_one + need_two + 1, "\"");
219 return xp;
221 need_one = strlen(one);
222 need_two = strlen(two);
223 xp = xmalloc(need_one + need_two + 1);
224 strcpy(xp, one);
225 strcpy(xp + need_one, two);
226 return xp;
229 static const char *external_diff(void)
231 static const char *external_diff_cmd = NULL;
232 static int done_preparing = 0;
234 if (done_preparing)
235 return external_diff_cmd;
236 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
237 done_preparing = 1;
238 return external_diff_cmd;
241 static struct diff_tempfile {
242 const char *name; /* filename external diff should read from */
243 char hex[41];
244 char mode[10];
245 char tmp_path[PATH_MAX];
246 } diff_temp[2];
248 static int count_lines(const char *data, int size)
250 int count, ch, completely_empty = 1, nl_just_seen = 0;
251 count = 0;
252 while (0 < size--) {
253 ch = *data++;
254 if (ch == '\n') {
255 count++;
256 nl_just_seen = 1;
257 completely_empty = 0;
259 else {
260 nl_just_seen = 0;
261 completely_empty = 0;
264 if (completely_empty)
265 return 0;
266 if (!nl_just_seen)
267 count++; /* no trailing newline */
268 return count;
271 static void print_line_count(int count)
273 switch (count) {
274 case 0:
275 printf("0,0");
276 break;
277 case 1:
278 printf("1");
279 break;
280 default:
281 printf("1,%d", count);
282 break;
286 static void copy_file(int prefix, const char *data, int size,
287 const char *set, const char *reset)
289 int ch, nl_just_seen = 1;
290 while (0 < size--) {
291 ch = *data++;
292 if (nl_just_seen) {
293 fputs(set, stdout);
294 putchar(prefix);
296 if (ch == '\n') {
297 nl_just_seen = 1;
298 fputs(reset, stdout);
299 } else
300 nl_just_seen = 0;
301 putchar(ch);
303 if (!nl_just_seen)
304 printf("%s\n\\ No newline at end of file\n", reset);
307 static void emit_rewrite_diff(const char *name_a,
308 const char *name_b,
309 struct diff_filespec *one,
310 struct diff_filespec *two,
311 int color_diff)
313 int lc_a, lc_b;
314 const char *name_a_tab, *name_b_tab;
315 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
316 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
317 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
318 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
319 const char *reset = diff_get_color(color_diff, DIFF_RESET);
321 name_a += (*name_a == '/');
322 name_b += (*name_b == '/');
323 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
324 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
326 diff_populate_filespec(one, 0);
327 diff_populate_filespec(two, 0);
328 lc_a = count_lines(one->data, one->size);
329 lc_b = count_lines(two->data, two->size);
330 printf("%s--- a/%s%s%s\n%s+++ b/%s%s%s\n%s@@ -",
331 metainfo, name_a, name_a_tab, reset,
332 metainfo, name_b, name_b_tab, reset, fraginfo);
333 print_line_count(lc_a);
334 printf(" +");
335 print_line_count(lc_b);
336 printf(" @@%s\n", reset);
337 if (lc_a)
338 copy_file('-', one->data, one->size, old, reset);
339 if (lc_b)
340 copy_file('+', two->data, two->size, new, reset);
343 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
345 if (!DIFF_FILE_VALID(one)) {
346 mf->ptr = (char *)""; /* does not matter */
347 mf->size = 0;
348 return 0;
350 else if (diff_populate_filespec(one, 0))
351 return -1;
352 mf->ptr = one->data;
353 mf->size = one->size;
354 return 0;
357 struct diff_words_buffer {
358 mmfile_t text;
359 long alloc;
360 long current; /* output pointer */
361 int suppressed_newline;
364 static void diff_words_append(char *line, unsigned long len,
365 struct diff_words_buffer *buffer)
367 if (buffer->text.size + len > buffer->alloc) {
368 buffer->alloc = (buffer->text.size + len) * 3 / 2;
369 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
371 line++;
372 len--;
373 memcpy(buffer->text.ptr + buffer->text.size, line, len);
374 buffer->text.size += len;
377 struct diff_words_data {
378 struct xdiff_emit_state xm;
379 struct diff_words_buffer minus, plus;
382 static void print_word(struct diff_words_buffer *buffer, int len, int color,
383 int suppress_newline)
385 const char *ptr;
386 int eol = 0;
388 if (len == 0)
389 return;
391 ptr = buffer->text.ptr + buffer->current;
392 buffer->current += len;
394 if (ptr[len - 1] == '\n') {
395 eol = 1;
396 len--;
399 fputs(diff_get_color(1, color), stdout);
400 fwrite(ptr, len, 1, stdout);
401 fputs(diff_get_color(1, DIFF_RESET), stdout);
403 if (eol) {
404 if (suppress_newline)
405 buffer->suppressed_newline = 1;
406 else
407 putchar('\n');
411 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
413 struct diff_words_data *diff_words = priv;
415 if (diff_words->minus.suppressed_newline) {
416 if (line[0] != '+')
417 putchar('\n');
418 diff_words->minus.suppressed_newline = 0;
421 len--;
422 switch (line[0]) {
423 case '-':
424 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
425 break;
426 case '+':
427 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
428 break;
429 case ' ':
430 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
431 diff_words->minus.current += len;
432 break;
436 /* this executes the word diff on the accumulated buffers */
437 static void diff_words_show(struct diff_words_data *diff_words)
439 xpparam_t xpp;
440 xdemitconf_t xecfg;
441 xdemitcb_t ecb;
442 mmfile_t minus, plus;
443 int i;
445 memset(&xecfg, 0, sizeof(xecfg));
446 minus.size = diff_words->minus.text.size;
447 minus.ptr = xmalloc(minus.size);
448 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
449 for (i = 0; i < minus.size; i++)
450 if (isspace(minus.ptr[i]))
451 minus.ptr[i] = '\n';
452 diff_words->minus.current = 0;
454 plus.size = diff_words->plus.text.size;
455 plus.ptr = xmalloc(plus.size);
456 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
457 for (i = 0; i < plus.size; i++)
458 if (isspace(plus.ptr[i]))
459 plus.ptr[i] = '\n';
460 diff_words->plus.current = 0;
462 xpp.flags = XDF_NEED_MINIMAL;
463 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
464 ecb.outf = xdiff_outf;
465 ecb.priv = diff_words;
466 diff_words->xm.consume = fn_out_diff_words_aux;
467 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
469 free(minus.ptr);
470 free(plus.ptr);
471 diff_words->minus.text.size = diff_words->plus.text.size = 0;
473 if (diff_words->minus.suppressed_newline) {
474 putchar('\n');
475 diff_words->minus.suppressed_newline = 0;
479 struct emit_callback {
480 struct xdiff_emit_state xm;
481 int nparents, color_diff;
482 const char **label_path;
483 struct diff_words_data *diff_words;
484 int *found_changesp;
487 static void free_diff_words_data(struct emit_callback *ecbdata)
489 if (ecbdata->diff_words) {
490 /* flush buffers */
491 if (ecbdata->diff_words->minus.text.size ||
492 ecbdata->diff_words->plus.text.size)
493 diff_words_show(ecbdata->diff_words);
495 if (ecbdata->diff_words->minus.text.ptr)
496 free (ecbdata->diff_words->minus.text.ptr);
497 if (ecbdata->diff_words->plus.text.ptr)
498 free (ecbdata->diff_words->plus.text.ptr);
499 free(ecbdata->diff_words);
500 ecbdata->diff_words = NULL;
504 const char *diff_get_color(int diff_use_color, enum color_diff ix)
506 if (diff_use_color)
507 return diff_colors[ix];
508 return "";
511 static void emit_line(const char *set, const char *reset, const char *line, int len)
513 if (len > 0 && line[len-1] == '\n')
514 len--;
515 fputs(set, stdout);
516 fwrite(line, len, 1, stdout);
517 puts(reset);
520 static void emit_line_with_ws(int nparents,
521 const char *set, const char *reset, const char *ws,
522 const char *line, int len)
524 int col0 = nparents;
525 int last_tab_in_indent = -1;
526 int last_space_in_indent = -1;
527 int i;
528 int tail = len;
529 int need_highlight_leading_space = 0;
530 /* The line is a newly added line. Does it have funny leading
531 * whitespaces? In indent, SP should never precede a TAB.
533 for (i = col0; i < len; i++) {
534 if (line[i] == '\t') {
535 last_tab_in_indent = i;
536 if (0 <= last_space_in_indent)
537 need_highlight_leading_space = 1;
539 else if (line[i] == ' ')
540 last_space_in_indent = i;
541 else
542 break;
544 fputs(set, stdout);
545 fwrite(line, col0, 1, stdout);
546 fputs(reset, stdout);
547 if (((i == len) || line[i] == '\n') && i != col0) {
548 /* The whole line was indent */
549 emit_line(ws, reset, line + col0, len - col0);
550 return;
552 i = col0;
553 if (need_highlight_leading_space) {
554 while (i < last_tab_in_indent) {
555 if (line[i] == ' ') {
556 fputs(ws, stdout);
557 putchar(' ');
558 fputs(reset, stdout);
560 else
561 putchar(line[i]);
562 i++;
565 tail = len - 1;
566 if (line[tail] == '\n' && i < tail)
567 tail--;
568 while (i < tail) {
569 if (!isspace(line[tail]))
570 break;
571 tail--;
573 if ((i < tail && line[tail + 1] != '\n')) {
574 /* This has whitespace between tail+1..len */
575 fputs(set, stdout);
576 fwrite(line + i, tail - i + 1, 1, stdout);
577 fputs(reset, stdout);
578 emit_line(ws, reset, line + tail + 1, len - tail - 1);
580 else
581 emit_line(set, reset, line + i, len - i);
584 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
586 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
587 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
589 if (!*ws)
590 emit_line(set, reset, line, len);
591 else
592 emit_line_with_ws(ecbdata->nparents, set, reset, ws,
593 line, len);
596 static void fn_out_consume(void *priv, char *line, unsigned long len)
598 int i;
599 int color;
600 struct emit_callback *ecbdata = priv;
601 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
602 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
604 *(ecbdata->found_changesp) = 1;
606 if (ecbdata->label_path[0]) {
607 const char *name_a_tab, *name_b_tab;
609 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
610 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
612 printf("%s--- %s%s%s\n",
613 set, ecbdata->label_path[0], reset, name_a_tab);
614 printf("%s+++ %s%s%s\n",
615 set, ecbdata->label_path[1], reset, name_b_tab);
616 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
619 /* This is not really necessary for now because
620 * this codepath only deals with two-way diffs.
622 for (i = 0; i < len && line[i] == '@'; i++)
624 if (2 <= i && i < len && line[i] == ' ') {
625 ecbdata->nparents = i - 1;
626 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
627 reset, line, len);
628 return;
631 if (len < ecbdata->nparents) {
632 set = reset;
633 emit_line(reset, reset, line, len);
634 return;
637 color = DIFF_PLAIN;
638 if (ecbdata->diff_words && ecbdata->nparents != 1)
639 /* fall back to normal diff */
640 free_diff_words_data(ecbdata);
641 if (ecbdata->diff_words) {
642 if (line[0] == '-') {
643 diff_words_append(line, len,
644 &ecbdata->diff_words->minus);
645 return;
646 } else if (line[0] == '+') {
647 diff_words_append(line, len,
648 &ecbdata->diff_words->plus);
649 return;
651 if (ecbdata->diff_words->minus.text.size ||
652 ecbdata->diff_words->plus.text.size)
653 diff_words_show(ecbdata->diff_words);
654 line++;
655 len--;
656 emit_line(set, reset, line, len);
657 return;
659 for (i = 0; i < ecbdata->nparents && len; i++) {
660 if (line[i] == '-')
661 color = DIFF_FILE_OLD;
662 else if (line[i] == '+')
663 color = DIFF_FILE_NEW;
666 if (color != DIFF_FILE_NEW) {
667 emit_line(diff_get_color(ecbdata->color_diff, color),
668 reset, line, len);
669 return;
671 emit_add_line(reset, ecbdata, line, len);
674 static char *pprint_rename(const char *a, const char *b)
676 const char *old = a;
677 const char *new = b;
678 char *name = NULL;
679 int pfx_length, sfx_length;
680 int len_a = strlen(a);
681 int len_b = strlen(b);
682 int qlen_a = quote_c_style(a, NULL, NULL, 0);
683 int qlen_b = quote_c_style(b, NULL, NULL, 0);
685 if (qlen_a || qlen_b) {
686 if (qlen_a) len_a = qlen_a;
687 if (qlen_b) len_b = qlen_b;
688 name = xmalloc( len_a + len_b + 5 );
689 if (qlen_a)
690 quote_c_style(a, name, NULL, 0);
691 else
692 memcpy(name, a, len_a);
693 memcpy(name + len_a, " => ", 4);
694 if (qlen_b)
695 quote_c_style(b, name + len_a + 4, NULL, 0);
696 else
697 memcpy(name + len_a + 4, b, len_b + 1);
698 return name;
701 /* Find common prefix */
702 pfx_length = 0;
703 while (*old && *new && *old == *new) {
704 if (*old == '/')
705 pfx_length = old - a + 1;
706 old++;
707 new++;
710 /* Find common suffix */
711 old = a + len_a;
712 new = b + len_b;
713 sfx_length = 0;
714 while (a <= old && b <= new && *old == *new) {
715 if (*old == '/')
716 sfx_length = len_a - (old - a);
717 old--;
718 new--;
722 * pfx{mid-a => mid-b}sfx
723 * {pfx-a => pfx-b}sfx
724 * pfx{sfx-a => sfx-b}
725 * name-a => name-b
727 if (pfx_length + sfx_length) {
728 int a_midlen = len_a - pfx_length - sfx_length;
729 int b_midlen = len_b - pfx_length - sfx_length;
730 if (a_midlen < 0) a_midlen = 0;
731 if (b_midlen < 0) b_midlen = 0;
733 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
734 sprintf(name, "%.*s{%.*s => %.*s}%s",
735 pfx_length, a,
736 a_midlen, a + pfx_length,
737 b_midlen, b + pfx_length,
738 a + len_a - sfx_length);
740 else {
741 name = xmalloc(len_a + len_b + 5);
742 sprintf(name, "%s => %s", a, b);
744 return name;
747 struct diffstat_t {
748 struct xdiff_emit_state xm;
750 int nr;
751 int alloc;
752 struct diffstat_file {
753 char *name;
754 unsigned is_unmerged:1;
755 unsigned is_binary:1;
756 unsigned is_renamed:1;
757 unsigned int added, deleted;
758 } **files;
761 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
762 const char *name_a,
763 const char *name_b)
765 struct diffstat_file *x;
766 x = xcalloc(sizeof (*x), 1);
767 if (diffstat->nr == diffstat->alloc) {
768 diffstat->alloc = alloc_nr(diffstat->alloc);
769 diffstat->files = xrealloc(diffstat->files,
770 diffstat->alloc * sizeof(x));
772 diffstat->files[diffstat->nr++] = x;
773 if (name_b) {
774 x->name = pprint_rename(name_a, name_b);
775 x->is_renamed = 1;
777 else
778 x->name = xstrdup(name_a);
779 return x;
782 static void diffstat_consume(void *priv, char *line, unsigned long len)
784 struct diffstat_t *diffstat = priv;
785 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
787 if (line[0] == '+')
788 x->added++;
789 else if (line[0] == '-')
790 x->deleted++;
793 const char mime_boundary_leader[] = "------------";
795 static int scale_linear(int it, int width, int max_change)
798 * make sure that at least one '-' is printed if there were deletions,
799 * and likewise for '+'.
801 if (max_change < 2)
802 return it;
803 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
806 static void show_name(const char *prefix, const char *name, int len,
807 const char *reset, const char *set)
809 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
812 static void show_graph(char ch, int cnt, const char *set, const char *reset)
814 if (cnt <= 0)
815 return;
816 printf("%s", set);
817 while (cnt--)
818 putchar(ch);
819 printf("%s", reset);
822 static void show_stats(struct diffstat_t* data, struct diff_options *options)
824 int i, len, add, del, total, adds = 0, dels = 0;
825 int max_change = 0, max_len = 0;
826 int total_files = data->nr;
827 int width, name_width;
828 const char *reset, *set, *add_c, *del_c;
830 if (data->nr == 0)
831 return;
833 width = options->stat_width ? options->stat_width : 80;
834 name_width = options->stat_name_width ? options->stat_name_width : 50;
836 /* Sanity: give at least 5 columns to the graph,
837 * but leave at least 10 columns for the name.
839 if (width < name_width + 15) {
840 if (name_width <= 25)
841 width = name_width + 15;
842 else
843 name_width = width - 15;
846 /* Find the longest filename and max number of changes */
847 reset = diff_get_color(options->color_diff, DIFF_RESET);
848 set = diff_get_color(options->color_diff, DIFF_PLAIN);
849 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
850 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
852 for (i = 0; i < data->nr; i++) {
853 struct diffstat_file *file = data->files[i];
854 int change = file->added + file->deleted;
856 if (!file->is_renamed) { /* renames are already quoted by pprint_rename */
857 len = quote_c_style(file->name, NULL, NULL, 0);
858 if (len) {
859 char *qname = xmalloc(len + 1);
860 quote_c_style(file->name, qname, NULL, 0);
861 free(file->name);
862 file->name = qname;
866 len = strlen(file->name);
867 if (max_len < len)
868 max_len = len;
870 if (file->is_binary || file->is_unmerged)
871 continue;
872 if (max_change < change)
873 max_change = change;
876 /* Compute the width of the graph part;
877 * 10 is for one blank at the beginning of the line plus
878 * " | count " between the name and the graph.
880 * From here on, name_width is the width of the name area,
881 * and width is the width of the graph area.
883 name_width = (name_width < max_len) ? name_width : max_len;
884 if (width < (name_width + 10) + max_change)
885 width = width - (name_width + 10);
886 else
887 width = max_change;
889 for (i = 0; i < data->nr; i++) {
890 const char *prefix = "";
891 char *name = data->files[i]->name;
892 int added = data->files[i]->added;
893 int deleted = data->files[i]->deleted;
894 int name_len;
897 * "scale" the filename
899 len = name_width;
900 name_len = strlen(name);
901 if (name_width < name_len) {
902 char *slash;
903 prefix = "...";
904 len -= 3;
905 name += name_len - len;
906 slash = strchr(name, '/');
907 if (slash)
908 name = slash;
911 if (data->files[i]->is_binary) {
912 show_name(prefix, name, len, reset, set);
913 printf(" Bin ");
914 printf("%s%d%s", del_c, deleted, reset);
915 printf(" -> ");
916 printf("%s%d%s", add_c, added, reset);
917 printf(" bytes");
918 printf("\n");
919 goto free_diffstat_file;
921 else if (data->files[i]->is_unmerged) {
922 show_name(prefix, name, len, reset, set);
923 printf(" Unmerged\n");
924 goto free_diffstat_file;
926 else if (!data->files[i]->is_renamed &&
927 (added + deleted == 0)) {
928 total_files--;
929 goto free_diffstat_file;
933 * scale the add/delete
935 add = added;
936 del = deleted;
937 total = add + del;
938 adds += add;
939 dels += del;
941 if (width <= max_change) {
942 add = scale_linear(add, width, max_change);
943 del = scale_linear(del, width, max_change);
944 total = add + del;
946 show_name(prefix, name, len, reset, set);
947 printf("%5d ", added + deleted);
948 show_graph('+', add, add_c, reset);
949 show_graph('-', del, del_c, reset);
950 putchar('\n');
951 free_diffstat_file:
952 free(data->files[i]->name);
953 free(data->files[i]);
955 free(data->files);
956 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
957 set, total_files, adds, dels, reset);
960 static void show_shortstats(struct diffstat_t* data)
962 int i, adds = 0, dels = 0, total_files = data->nr;
964 if (data->nr == 0)
965 return;
967 for (i = 0; i < data->nr; i++) {
968 if (!data->files[i]->is_binary &&
969 !data->files[i]->is_unmerged) {
970 int added = data->files[i]->added;
971 int deleted= data->files[i]->deleted;
972 if (!data->files[i]->is_renamed &&
973 (added + deleted == 0)) {
974 total_files--;
975 } else {
976 adds += added;
977 dels += deleted;
980 free(data->files[i]->name);
981 free(data->files[i]);
983 free(data->files);
985 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
986 total_files, adds, dels);
989 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
991 int i;
993 for (i = 0; i < data->nr; i++) {
994 struct diffstat_file *file = data->files[i];
996 if (file->is_binary)
997 printf("-\t-\t");
998 else
999 printf("%d\t%d\t", file->added, file->deleted);
1000 if (options->line_termination && !file->is_renamed &&
1001 quote_c_style(file->name, NULL, NULL, 0))
1002 quote_c_style(file->name, NULL, stdout, 0);
1003 else
1004 fputs(file->name, stdout);
1005 putchar(options->line_termination);
1009 struct checkdiff_t {
1010 struct xdiff_emit_state xm;
1011 const char *filename;
1012 int lineno, color_diff;
1015 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1017 struct checkdiff_t *data = priv;
1018 const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
1019 const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
1020 const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
1022 if (line[0] == '+') {
1023 int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
1025 /* check space before tab */
1026 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
1027 if (line[i] == ' ')
1028 spaces++;
1029 if (line[i - 1] == '\t' && spaces)
1030 space_before_tab = 1;
1032 /* check white space at line end */
1033 if (line[len - 1] == '\n')
1034 len--;
1035 if (isspace(line[len - 1]))
1036 white_space_at_end = 1;
1038 if (space_before_tab || white_space_at_end) {
1039 printf("%s:%d: %s", data->filename, data->lineno, ws);
1040 if (space_before_tab) {
1041 printf("space before tab");
1042 if (white_space_at_end)
1043 putchar(',');
1045 if (white_space_at_end)
1046 printf("white space at end");
1047 printf(":%s ", reset);
1048 emit_line_with_ws(1, set, reset, ws, line, len);
1051 data->lineno++;
1052 } else if (line[0] == ' ')
1053 data->lineno++;
1054 else if (line[0] == '@') {
1055 char *plus = strchr(line, '+');
1056 if (plus)
1057 data->lineno = strtol(plus, NULL, 10);
1058 else
1059 die("invalid diff");
1063 static unsigned char *deflate_it(char *data,
1064 unsigned long size,
1065 unsigned long *result_size)
1067 int bound;
1068 unsigned char *deflated;
1069 z_stream stream;
1071 memset(&stream, 0, sizeof(stream));
1072 deflateInit(&stream, zlib_compression_level);
1073 bound = deflateBound(&stream, size);
1074 deflated = xmalloc(bound);
1075 stream.next_out = deflated;
1076 stream.avail_out = bound;
1078 stream.next_in = (unsigned char *)data;
1079 stream.avail_in = size;
1080 while (deflate(&stream, Z_FINISH) == Z_OK)
1081 ; /* nothing */
1082 deflateEnd(&stream);
1083 *result_size = stream.total_out;
1084 return deflated;
1087 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
1089 void *cp;
1090 void *delta;
1091 void *deflated;
1092 void *data;
1093 unsigned long orig_size;
1094 unsigned long delta_size;
1095 unsigned long deflate_size;
1096 unsigned long data_size;
1098 /* We could do deflated delta, or we could do just deflated two,
1099 * whichever is smaller.
1101 delta = NULL;
1102 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1103 if (one->size && two->size) {
1104 delta = diff_delta(one->ptr, one->size,
1105 two->ptr, two->size,
1106 &delta_size, deflate_size);
1107 if (delta) {
1108 void *to_free = delta;
1109 orig_size = delta_size;
1110 delta = deflate_it(delta, delta_size, &delta_size);
1111 free(to_free);
1115 if (delta && delta_size < deflate_size) {
1116 printf("delta %lu\n", orig_size);
1117 free(deflated);
1118 data = delta;
1119 data_size = delta_size;
1121 else {
1122 printf("literal %lu\n", two->size);
1123 free(delta);
1124 data = deflated;
1125 data_size = deflate_size;
1128 /* emit data encoded in base85 */
1129 cp = data;
1130 while (data_size) {
1131 int bytes = (52 < data_size) ? 52 : data_size;
1132 char line[70];
1133 data_size -= bytes;
1134 if (bytes <= 26)
1135 line[0] = bytes + 'A' - 1;
1136 else
1137 line[0] = bytes - 26 + 'a' - 1;
1138 encode_85(line + 1, cp, bytes);
1139 cp = (char *) cp + bytes;
1140 puts(line);
1142 printf("\n");
1143 free(data);
1146 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1148 printf("GIT binary patch\n");
1149 emit_binary_diff_body(one, two);
1150 emit_binary_diff_body(two, one);
1153 static void setup_diff_attr_check(struct git_attr_check *check)
1155 static struct git_attr *attr_diff;
1157 if (!attr_diff) {
1158 attr_diff = git_attr("diff", 4);
1160 check[0].attr = attr_diff;
1163 static void diff_filespec_check_attr(struct diff_filespec *one)
1165 struct git_attr_check attr_diff_check;
1166 int check_from_data = 0;
1168 if (one->checked_attr)
1169 return;
1171 setup_diff_attr_check(&attr_diff_check);
1172 one->is_binary = 0;
1173 one->funcname_pattern_ident = NULL;
1175 if (!git_checkattr(one->path, 1, &attr_diff_check)) {
1176 const char *value;
1178 /* binaryness */
1179 value = attr_diff_check.value;
1180 if (ATTR_TRUE(value))
1182 else if (ATTR_FALSE(value))
1183 one->is_binary = 1;
1184 else
1185 check_from_data = 1;
1187 /* funcname pattern ident */
1188 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1190 else
1191 one->funcname_pattern_ident = value;
1194 if (check_from_data) {
1195 if (!one->data && DIFF_FILE_VALID(one))
1196 diff_populate_filespec(one, 0);
1198 if (one->data)
1199 one->is_binary = buffer_is_binary(one->data, one->size);
1203 int diff_filespec_is_binary(struct diff_filespec *one)
1205 diff_filespec_check_attr(one);
1206 return one->is_binary;
1209 static const char *funcname_pattern(const char *ident)
1211 struct funcname_pattern *pp;
1213 read_config_if_needed();
1214 for (pp = funcname_pattern_list; pp; pp = pp->next)
1215 if (!strcmp(ident, pp->name))
1216 return pp->pattern;
1217 return NULL;
1220 static struct builtin_funcname_pattern {
1221 const char *name;
1222 const char *pattern;
1223 } builtin_funcname_pattern[] = {
1224 { "java", "!^[ ]*\\(catch\\|do\\|for\\|if\\|instanceof\\|"
1225 "new\\|return\\|switch\\|throw\\|while\\)\n"
1226 "^[ ]*\\(\\([ ]*"
1227 "[A-Za-z_][A-Za-z_0-9]*\\)\\{2,\\}"
1228 "[ ]*([^;]*$\\)" },
1229 { "tex", "^\\(\\\\\\(sub\\)*section{.*\\)$" },
1232 static const char *diff_funcname_pattern(struct diff_filespec *one)
1234 const char *ident, *pattern;
1235 int i;
1237 diff_filespec_check_attr(one);
1238 ident = one->funcname_pattern_ident;
1240 if (!ident)
1242 * If the config file has "funcname.default" defined, that
1243 * regexp is used; otherwise NULL is returned and xemit uses
1244 * the built-in default.
1246 return funcname_pattern("default");
1248 /* Look up custom "funcname.$ident" regexp from config. */
1249 pattern = funcname_pattern(ident);
1250 if (pattern)
1251 return pattern;
1254 * And define built-in fallback patterns here. Note that
1255 * these can be overriden by the user's config settings.
1257 for (i = 0; i < ARRAY_SIZE(builtin_funcname_pattern); i++)
1258 if (!strcmp(ident, builtin_funcname_pattern[i].name))
1259 return builtin_funcname_pattern[i].pattern;
1261 return NULL;
1264 static void builtin_diff(const char *name_a,
1265 const char *name_b,
1266 struct diff_filespec *one,
1267 struct diff_filespec *two,
1268 const char *xfrm_msg,
1269 struct diff_options *o,
1270 int complete_rewrite)
1272 mmfile_t mf1, mf2;
1273 const char *lbl[2];
1274 char *a_one, *b_two;
1275 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1276 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1278 a_one = quote_two("a/", name_a + (*name_a == '/'));
1279 b_two = quote_two("b/", name_b + (*name_b == '/'));
1280 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1281 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1282 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1283 if (lbl[0][0] == '/') {
1284 /* /dev/null */
1285 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1286 if (xfrm_msg && xfrm_msg[0])
1287 printf("%s%s%s\n", set, xfrm_msg, reset);
1289 else if (lbl[1][0] == '/') {
1290 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1291 if (xfrm_msg && xfrm_msg[0])
1292 printf("%s%s%s\n", set, xfrm_msg, reset);
1294 else {
1295 if (one->mode != two->mode) {
1296 printf("%sold mode %06o%s\n", set, one->mode, reset);
1297 printf("%snew mode %06o%s\n", set, two->mode, reset);
1299 if (xfrm_msg && xfrm_msg[0])
1300 printf("%s%s%s\n", set, xfrm_msg, reset);
1302 * we do not run diff between different kind
1303 * of objects.
1305 if ((one->mode ^ two->mode) & S_IFMT)
1306 goto free_ab_and_return;
1307 if (complete_rewrite) {
1308 emit_rewrite_diff(name_a, name_b, one, two,
1309 o->color_diff);
1310 o->found_changes = 1;
1311 goto free_ab_and_return;
1315 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1316 die("unable to read files to diff");
1318 if (!o->text &&
1319 (diff_filespec_is_binary(one) || diff_filespec_is_binary(two))) {
1320 /* Quite common confusing case */
1321 if (mf1.size == mf2.size &&
1322 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1323 goto free_ab_and_return;
1324 if (o->binary)
1325 emit_binary_diff(&mf1, &mf2);
1326 else
1327 printf("Binary files %s and %s differ\n",
1328 lbl[0], lbl[1]);
1329 o->found_changes = 1;
1331 else {
1332 /* Crazy xdl interfaces.. */
1333 const char *diffopts = getenv("GIT_DIFF_OPTS");
1334 xpparam_t xpp;
1335 xdemitconf_t xecfg;
1336 xdemitcb_t ecb;
1337 struct emit_callback ecbdata;
1338 const char *funcname_pattern;
1340 funcname_pattern = diff_funcname_pattern(one);
1341 if (!funcname_pattern)
1342 funcname_pattern = diff_funcname_pattern(two);
1344 memset(&xecfg, 0, sizeof(xecfg));
1345 memset(&ecbdata, 0, sizeof(ecbdata));
1346 ecbdata.label_path = lbl;
1347 ecbdata.color_diff = o->color_diff;
1348 ecbdata.found_changesp = &o->found_changes;
1349 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1350 xecfg.ctxlen = o->context;
1351 xecfg.flags = XDL_EMIT_FUNCNAMES;
1352 if (funcname_pattern)
1353 xdiff_set_find_func(&xecfg, funcname_pattern);
1354 if (!diffopts)
1356 else if (!prefixcmp(diffopts, "--unified="))
1357 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1358 else if (!prefixcmp(diffopts, "-u"))
1359 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1360 ecb.outf = xdiff_outf;
1361 ecb.priv = &ecbdata;
1362 ecbdata.xm.consume = fn_out_consume;
1363 if (o->color_diff_words)
1364 ecbdata.diff_words =
1365 xcalloc(1, sizeof(struct diff_words_data));
1366 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1367 if (o->color_diff_words)
1368 free_diff_words_data(&ecbdata);
1371 free_ab_and_return:
1372 diff_free_filespec_data(one);
1373 diff_free_filespec_data(two);
1374 free(a_one);
1375 free(b_two);
1376 return;
1379 static void builtin_diffstat(const char *name_a, const char *name_b,
1380 struct diff_filespec *one,
1381 struct diff_filespec *two,
1382 struct diffstat_t *diffstat,
1383 struct diff_options *o,
1384 int complete_rewrite)
1386 mmfile_t mf1, mf2;
1387 struct diffstat_file *data;
1389 data = diffstat_add(diffstat, name_a, name_b);
1391 if (!one || !two) {
1392 data->is_unmerged = 1;
1393 return;
1395 if (complete_rewrite) {
1396 diff_populate_filespec(one, 0);
1397 diff_populate_filespec(two, 0);
1398 data->deleted = count_lines(one->data, one->size);
1399 data->added = count_lines(two->data, two->size);
1400 goto free_and_return;
1402 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1403 die("unable to read files to diff");
1405 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1406 data->is_binary = 1;
1407 data->added = mf2.size;
1408 data->deleted = mf1.size;
1409 } else {
1410 /* Crazy xdl interfaces.. */
1411 xpparam_t xpp;
1412 xdemitconf_t xecfg;
1413 xdemitcb_t ecb;
1415 memset(&xecfg, 0, sizeof(xecfg));
1416 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1417 ecb.outf = xdiff_outf;
1418 ecb.priv = diffstat;
1419 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1422 free_and_return:
1423 diff_free_filespec_data(one);
1424 diff_free_filespec_data(two);
1427 static void builtin_checkdiff(const char *name_a, const char *name_b,
1428 struct diff_filespec *one,
1429 struct diff_filespec *two, struct diff_options *o)
1431 mmfile_t mf1, mf2;
1432 struct checkdiff_t data;
1434 if (!two)
1435 return;
1437 memset(&data, 0, sizeof(data));
1438 data.xm.consume = checkdiff_consume;
1439 data.filename = name_b ? name_b : name_a;
1440 data.lineno = 0;
1441 data.color_diff = o->color_diff;
1443 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1444 die("unable to read files to diff");
1446 if (diff_filespec_is_binary(two))
1447 goto free_and_return;
1448 else {
1449 /* Crazy xdl interfaces.. */
1450 xpparam_t xpp;
1451 xdemitconf_t xecfg;
1452 xdemitcb_t ecb;
1454 memset(&xecfg, 0, sizeof(xecfg));
1455 xpp.flags = XDF_NEED_MINIMAL;
1456 ecb.outf = xdiff_outf;
1457 ecb.priv = &data;
1458 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1460 free_and_return:
1461 diff_free_filespec_data(one);
1462 diff_free_filespec_data(two);
1465 struct diff_filespec *alloc_filespec(const char *path)
1467 int namelen = strlen(path);
1468 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1470 memset(spec, 0, sizeof(*spec));
1471 spec->path = (char *)(spec + 1);
1472 memcpy(spec->path, path, namelen+1);
1473 return spec;
1476 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1477 unsigned short mode)
1479 if (mode) {
1480 spec->mode = canon_mode(mode);
1481 hashcpy(spec->sha1, sha1);
1482 spec->sha1_valid = !is_null_sha1(sha1);
1487 * Given a name and sha1 pair, if the index tells us the file in
1488 * the work tree has that object contents, return true, so that
1489 * prepare_temp_file() does not have to inflate and extract.
1491 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1493 struct cache_entry *ce;
1494 struct stat st;
1495 int pos, len;
1497 /* We do not read the cache ourselves here, because the
1498 * benchmark with my previous version that always reads cache
1499 * shows that it makes things worse for diff-tree comparing
1500 * two linux-2.6 kernel trees in an already checked out work
1501 * tree. This is because most diff-tree comparisons deal with
1502 * only a small number of files, while reading the cache is
1503 * expensive for a large project, and its cost outweighs the
1504 * savings we get by not inflating the object to a temporary
1505 * file. Practically, this code only helps when we are used
1506 * by diff-cache --cached, which does read the cache before
1507 * calling us.
1509 if (!active_cache)
1510 return 0;
1512 /* We want to avoid the working directory if our caller
1513 * doesn't need the data in a normal file, this system
1514 * is rather slow with its stat/open/mmap/close syscalls,
1515 * and the object is contained in a pack file. The pack
1516 * is probably already open and will be faster to obtain
1517 * the data through than the working directory. Loose
1518 * objects however would tend to be slower as they need
1519 * to be individually opened and inflated.
1521 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1522 return 0;
1524 len = strlen(name);
1525 pos = cache_name_pos(name, len);
1526 if (pos < 0)
1527 return 0;
1528 ce = active_cache[pos];
1529 if ((lstat(name, &st) < 0) ||
1530 !S_ISREG(st.st_mode) || /* careful! */
1531 ce_match_stat(ce, &st, 0) ||
1532 hashcmp(sha1, ce->sha1))
1533 return 0;
1534 /* we return 1 only when we can stat, it is a regular file,
1535 * stat information matches, and sha1 recorded in the cache
1536 * matches. I.e. we know the file in the work tree really is
1537 * the same as the <name, sha1> pair.
1539 return 1;
1542 static int populate_from_stdin(struct diff_filespec *s)
1544 #define INCREMENT 1024
1545 char *buf;
1546 unsigned long size;
1547 ssize_t got;
1549 size = 0;
1550 buf = NULL;
1551 while (1) {
1552 buf = xrealloc(buf, size + INCREMENT);
1553 got = xread(0, buf + size, INCREMENT);
1554 if (!got)
1555 break; /* EOF */
1556 if (got < 0)
1557 return error("error while reading from stdin %s",
1558 strerror(errno));
1559 size += got;
1561 s->should_munmap = 0;
1562 s->data = buf;
1563 s->size = size;
1564 s->should_free = 1;
1565 return 0;
1568 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1570 int len;
1571 char *data = xmalloc(100);
1572 len = snprintf(data, 100,
1573 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1574 s->data = data;
1575 s->size = len;
1576 s->should_free = 1;
1577 if (size_only) {
1578 s->data = NULL;
1579 free(data);
1581 return 0;
1585 * While doing rename detection and pickaxe operation, we may need to
1586 * grab the data for the blob (or file) for our own in-core comparison.
1587 * diff_filespec has data and size fields for this purpose.
1589 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1591 int err = 0;
1592 if (!DIFF_FILE_VALID(s))
1593 die("internal error: asking to populate invalid file.");
1594 if (S_ISDIR(s->mode))
1595 return -1;
1597 if (s->data)
1598 return 0;
1600 if (size_only && 0 < s->size)
1601 return 0;
1603 if (S_ISGITLINK(s->mode))
1604 return diff_populate_gitlink(s, size_only);
1606 if (!s->sha1_valid ||
1607 reuse_worktree_file(s->path, s->sha1, 0)) {
1608 struct stat st;
1609 int fd;
1610 char *buf;
1611 unsigned long size;
1613 if (!strcmp(s->path, "-"))
1614 return populate_from_stdin(s);
1616 if (lstat(s->path, &st) < 0) {
1617 if (errno == ENOENT) {
1618 err_empty:
1619 err = -1;
1620 empty:
1621 s->data = (char *)"";
1622 s->size = 0;
1623 return err;
1626 s->size = xsize_t(st.st_size);
1627 if (!s->size)
1628 goto empty;
1629 if (size_only)
1630 return 0;
1631 if (S_ISLNK(st.st_mode)) {
1632 int ret;
1633 s->data = xmalloc(s->size);
1634 s->should_free = 1;
1635 ret = readlink(s->path, s->data, s->size);
1636 if (ret < 0) {
1637 free(s->data);
1638 goto err_empty;
1640 return 0;
1642 fd = open(s->path, O_RDONLY);
1643 if (fd < 0)
1644 goto err_empty;
1645 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1646 close(fd);
1647 s->should_munmap = 1;
1650 * Convert from working tree format to canonical git format
1652 size = s->size;
1653 buf = convert_to_git(s->path, s->data, &size);
1654 if (buf) {
1655 munmap(s->data, s->size);
1656 s->should_munmap = 0;
1657 s->data = buf;
1658 s->size = size;
1659 s->should_free = 1;
1662 else {
1663 enum object_type type;
1664 if (size_only)
1665 type = sha1_object_info(s->sha1, &s->size);
1666 else {
1667 s->data = read_sha1_file(s->sha1, &type, &s->size);
1668 s->should_free = 1;
1671 return 0;
1674 void diff_free_filespec_data(struct diff_filespec *s)
1676 if (s->should_free)
1677 free(s->data);
1678 else if (s->should_munmap)
1679 munmap(s->data, s->size);
1681 if (s->should_free || s->should_munmap) {
1682 s->should_free = s->should_munmap = 0;
1683 s->data = NULL;
1685 free(s->cnt_data);
1686 s->cnt_data = NULL;
1689 static void prep_temp_blob(struct diff_tempfile *temp,
1690 void *blob,
1691 unsigned long size,
1692 const unsigned char *sha1,
1693 int mode)
1695 int fd;
1697 fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1698 if (fd < 0)
1699 die("unable to create temp-file");
1700 if (write_in_full(fd, blob, size) != size)
1701 die("unable to write temp-file");
1702 close(fd);
1703 temp->name = temp->tmp_path;
1704 strcpy(temp->hex, sha1_to_hex(sha1));
1705 temp->hex[40] = 0;
1706 sprintf(temp->mode, "%06o", mode);
1709 static void prepare_temp_file(const char *name,
1710 struct diff_tempfile *temp,
1711 struct diff_filespec *one)
1713 if (!DIFF_FILE_VALID(one)) {
1714 not_a_valid_file:
1715 /* A '-' entry produces this for file-2, and
1716 * a '+' entry produces this for file-1.
1718 temp->name = "/dev/null";
1719 strcpy(temp->hex, ".");
1720 strcpy(temp->mode, ".");
1721 return;
1724 if (!one->sha1_valid ||
1725 reuse_worktree_file(name, one->sha1, 1)) {
1726 struct stat st;
1727 if (lstat(name, &st) < 0) {
1728 if (errno == ENOENT)
1729 goto not_a_valid_file;
1730 die("stat(%s): %s", name, strerror(errno));
1732 if (S_ISLNK(st.st_mode)) {
1733 int ret;
1734 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1735 size_t sz = xsize_t(st.st_size);
1736 if (sizeof(buf) <= st.st_size)
1737 die("symlink too long: %s", name);
1738 ret = readlink(name, buf, sz);
1739 if (ret < 0)
1740 die("readlink(%s)", name);
1741 prep_temp_blob(temp, buf, sz,
1742 (one->sha1_valid ?
1743 one->sha1 : null_sha1),
1744 (one->sha1_valid ?
1745 one->mode : S_IFLNK));
1747 else {
1748 /* we can borrow from the file in the work tree */
1749 temp->name = name;
1750 if (!one->sha1_valid)
1751 strcpy(temp->hex, sha1_to_hex(null_sha1));
1752 else
1753 strcpy(temp->hex, sha1_to_hex(one->sha1));
1754 /* Even though we may sometimes borrow the
1755 * contents from the work tree, we always want
1756 * one->mode. mode is trustworthy even when
1757 * !(one->sha1_valid), as long as
1758 * DIFF_FILE_VALID(one).
1760 sprintf(temp->mode, "%06o", one->mode);
1762 return;
1764 else {
1765 if (diff_populate_filespec(one, 0))
1766 die("cannot read data blob for %s", one->path);
1767 prep_temp_blob(temp, one->data, one->size,
1768 one->sha1, one->mode);
1772 static void remove_tempfile(void)
1774 int i;
1776 for (i = 0; i < 2; i++)
1777 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1778 unlink(diff_temp[i].name);
1779 diff_temp[i].name = NULL;
1783 static void remove_tempfile_on_signal(int signo)
1785 remove_tempfile();
1786 signal(SIGINT, SIG_DFL);
1787 raise(signo);
1790 static int spawn_prog(const char *pgm, const char **arg)
1792 pid_t pid;
1793 int status;
1795 fflush(NULL);
1796 pid = spawnvpe_pipe(pgm, arg, environ, NULL, NULL);
1797 if (pid < 0)
1798 die("unable to fork");
1800 while (waitpid(pid, &status, 0) < 0) {
1801 if (errno == EINTR)
1802 continue;
1803 return -1;
1806 /* Earlier we did not check the exit status because
1807 * diff exits non-zero if files are different, and
1808 * we are not interested in knowing that. It was a
1809 * mistake which made it harder to quit a diff-*
1810 * session that uses the git-apply-patch-script as
1811 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1812 * should also exit non-zero only when it wants to
1813 * abort the entire diff-* session.
1815 if (WIFEXITED(status) && !WEXITSTATUS(status))
1816 return 0;
1817 return -1;
1820 /* An external diff command takes:
1822 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1823 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1826 static void run_external_diff(const char *pgm,
1827 const char *name,
1828 const char *other,
1829 struct diff_filespec *one,
1830 struct diff_filespec *two,
1831 const char *xfrm_msg,
1832 int complete_rewrite)
1834 const char *spawn_arg[10];
1835 struct diff_tempfile *temp = diff_temp;
1836 int retval;
1837 static int atexit_asked = 0;
1838 const char *othername;
1839 const char **arg = &spawn_arg[1];
1841 othername = (other? other : name);
1842 if (one && two) {
1843 prepare_temp_file(name, &temp[0], one);
1844 prepare_temp_file(othername, &temp[1], two);
1845 if (! atexit_asked &&
1846 (temp[0].name == temp[0].tmp_path ||
1847 temp[1].name == temp[1].tmp_path)) {
1848 atexit_asked = 1;
1849 atexit(remove_tempfile);
1851 signal(SIGINT, remove_tempfile_on_signal);
1854 if (one && two) {
1855 *arg++ = name;
1856 *arg++ = temp[0].name;
1857 *arg++ = temp[0].hex;
1858 *arg++ = temp[0].mode;
1859 *arg++ = temp[1].name;
1860 *arg++ = temp[1].hex;
1861 *arg++ = temp[1].mode;
1862 if (other) {
1863 *arg++ = other;
1864 *arg++ = xfrm_msg;
1866 } else {
1867 *arg++ = name;
1869 *arg = NULL;
1870 retval = spawn_prog(pgm, spawn_arg);
1871 remove_tempfile();
1872 if (retval) {
1873 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1874 exit(1);
1878 static const char *external_diff_attr(const char *name)
1880 struct git_attr_check attr_diff_check;
1882 setup_diff_attr_check(&attr_diff_check);
1883 if (!git_checkattr(name, 1, &attr_diff_check)) {
1884 const char *value = attr_diff_check.value;
1885 if (!ATTR_TRUE(value) &&
1886 !ATTR_FALSE(value) &&
1887 !ATTR_UNSET(value)) {
1888 struct ll_diff_driver *drv;
1890 read_config_if_needed();
1891 for (drv = user_diff; drv; drv = drv->next)
1892 if (!strcmp(drv->name, value))
1893 return drv->cmd;
1896 return NULL;
1899 static void run_diff_cmd(const char *pgm,
1900 const char *name,
1901 const char *other,
1902 struct diff_filespec *one,
1903 struct diff_filespec *two,
1904 const char *xfrm_msg,
1905 struct diff_options *o,
1906 int complete_rewrite)
1908 if (!o->allow_external)
1909 pgm = NULL;
1910 else {
1911 const char *cmd = external_diff_attr(name);
1912 if (cmd)
1913 pgm = cmd;
1916 if (pgm) {
1917 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1918 complete_rewrite);
1919 return;
1921 if (one && two)
1922 builtin_diff(name, other ? other : name,
1923 one, two, xfrm_msg, o, complete_rewrite);
1924 else
1925 printf("* Unmerged path %s\n", name);
1928 static void diff_fill_sha1_info(struct diff_filespec *one)
1930 if (DIFF_FILE_VALID(one)) {
1931 if (!one->sha1_valid) {
1932 struct stat st;
1933 if (!strcmp(one->path, "-")) {
1934 hashcpy(one->sha1, null_sha1);
1935 return;
1937 if (lstat(one->path, &st) < 0)
1938 die("stat %s", one->path);
1939 if (index_path(one->sha1, one->path, &st, 0))
1940 die("cannot hash %s\n", one->path);
1943 else
1944 hashclr(one->sha1);
1947 static int similarity_index(struct diff_filepair *p)
1949 return p->score * 100 / MAX_SCORE;
1952 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1954 const char *pgm = external_diff();
1955 char msg[PATH_MAX*2+300], *xfrm_msg;
1956 struct diff_filespec *one;
1957 struct diff_filespec *two;
1958 const char *name;
1959 const char *other;
1960 char *name_munged, *other_munged;
1961 int complete_rewrite = 0;
1962 int len;
1964 if (DIFF_PAIR_UNMERGED(p)) {
1965 /* unmerged */
1966 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1967 return;
1970 name = p->one->path;
1971 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1972 name_munged = quote_one(name);
1973 other_munged = quote_one(other);
1974 one = p->one; two = p->two;
1976 diff_fill_sha1_info(one);
1977 diff_fill_sha1_info(two);
1979 len = 0;
1980 switch (p->status) {
1981 case DIFF_STATUS_COPIED:
1982 len += snprintf(msg + len, sizeof(msg) - len,
1983 "similarity index %d%%\n"
1984 "copy from %s\n"
1985 "copy to %s\n",
1986 similarity_index(p), name_munged, other_munged);
1987 break;
1988 case DIFF_STATUS_RENAMED:
1989 len += snprintf(msg + len, sizeof(msg) - len,
1990 "similarity index %d%%\n"
1991 "rename from %s\n"
1992 "rename to %s\n",
1993 similarity_index(p), name_munged, other_munged);
1994 break;
1995 case DIFF_STATUS_MODIFIED:
1996 if (p->score) {
1997 len += snprintf(msg + len, sizeof(msg) - len,
1998 "dissimilarity index %d%%\n",
1999 similarity_index(p));
2000 complete_rewrite = 1;
2001 break;
2003 /* fallthru */
2004 default:
2005 /* nothing */
2009 if (hashcmp(one->sha1, two->sha1)) {
2010 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
2012 if (o->binary) {
2013 mmfile_t mf;
2014 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2015 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2016 abbrev = 40;
2018 len += snprintf(msg + len, sizeof(msg) - len,
2019 "index %.*s..%.*s",
2020 abbrev, sha1_to_hex(one->sha1),
2021 abbrev, sha1_to_hex(two->sha1));
2022 if (one->mode == two->mode)
2023 len += snprintf(msg + len, sizeof(msg) - len,
2024 " %06o", one->mode);
2025 len += snprintf(msg + len, sizeof(msg) - len, "\n");
2028 if (len)
2029 msg[--len] = 0;
2030 xfrm_msg = len ? msg : NULL;
2032 if (!pgm &&
2033 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2034 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2035 /* a filepair that changes between file and symlink
2036 * needs to be split into deletion and creation.
2038 struct diff_filespec *null = alloc_filespec(two->path);
2039 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
2040 free(null);
2041 null = alloc_filespec(one->path);
2042 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
2043 free(null);
2045 else
2046 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
2047 complete_rewrite);
2049 free(name_munged);
2050 free(other_munged);
2053 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2054 struct diffstat_t *diffstat)
2056 const char *name;
2057 const char *other;
2058 int complete_rewrite = 0;
2060 if (DIFF_PAIR_UNMERGED(p)) {
2061 /* unmerged */
2062 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2063 return;
2066 name = p->one->path;
2067 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2069 diff_fill_sha1_info(p->one);
2070 diff_fill_sha1_info(p->two);
2072 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2073 complete_rewrite = 1;
2074 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2077 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2079 const char *name;
2080 const char *other;
2082 if (DIFF_PAIR_UNMERGED(p)) {
2083 /* unmerged */
2084 return;
2087 name = p->one->path;
2088 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2090 diff_fill_sha1_info(p->one);
2091 diff_fill_sha1_info(p->two);
2093 builtin_checkdiff(name, other, p->one, p->two, o);
2096 void diff_setup(struct diff_options *options)
2098 memset(options, 0, sizeof(*options));
2099 options->line_termination = '\n';
2100 options->break_opt = -1;
2101 options->rename_limit = -1;
2102 options->context = 3;
2103 options->msg_sep = "";
2105 options->change = diff_change;
2106 options->add_remove = diff_addremove;
2107 options->color_diff = diff_use_color_default;
2108 options->detect_rename = diff_detect_rename_default;
2111 int diff_setup_done(struct diff_options *options)
2113 int count = 0;
2115 if (options->output_format & DIFF_FORMAT_NAME)
2116 count++;
2117 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2118 count++;
2119 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2120 count++;
2121 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2122 count++;
2123 if (count > 1)
2124 die("--name-only, --name-status, --check and -s are mutually exclusive");
2126 if (options->find_copies_harder)
2127 options->detect_rename = DIFF_DETECT_COPY;
2129 if (options->output_format & (DIFF_FORMAT_NAME |
2130 DIFF_FORMAT_NAME_STATUS |
2131 DIFF_FORMAT_CHECKDIFF |
2132 DIFF_FORMAT_NO_OUTPUT))
2133 options->output_format &= ~(DIFF_FORMAT_RAW |
2134 DIFF_FORMAT_NUMSTAT |
2135 DIFF_FORMAT_DIFFSTAT |
2136 DIFF_FORMAT_SHORTSTAT |
2137 DIFF_FORMAT_SUMMARY |
2138 DIFF_FORMAT_PATCH);
2141 * These cases always need recursive; we do not drop caller-supplied
2142 * recursive bits for other formats here.
2144 if (options->output_format & (DIFF_FORMAT_PATCH |
2145 DIFF_FORMAT_NUMSTAT |
2146 DIFF_FORMAT_DIFFSTAT |
2147 DIFF_FORMAT_SHORTSTAT |
2148 DIFF_FORMAT_SUMMARY |
2149 DIFF_FORMAT_CHECKDIFF))
2150 options->recursive = 1;
2152 * Also pickaxe would not work very well if you do not say recursive
2154 if (options->pickaxe)
2155 options->recursive = 1;
2157 if (options->detect_rename && options->rename_limit < 0)
2158 options->rename_limit = diff_rename_limit_default;
2159 if (options->setup & DIFF_SETUP_USE_CACHE) {
2160 if (!active_cache)
2161 /* read-cache does not die even when it fails
2162 * so it is safe for us to do this here. Also
2163 * it does not smudge active_cache or active_nr
2164 * when it fails, so we do not have to worry about
2165 * cleaning it up ourselves either.
2167 read_cache();
2169 if (options->abbrev <= 0 || 40 < options->abbrev)
2170 options->abbrev = 40; /* full */
2173 * It does not make sense to show the first hit we happened
2174 * to have found. It does not make sense not to return with
2175 * exit code in such a case either.
2177 if (options->quiet) {
2178 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2179 options->exit_with_status = 1;
2183 * If we postprocess in diffcore, we cannot simply return
2184 * upon the first hit. We need to run diff as usual.
2186 if (options->pickaxe || options->filter)
2187 options->quiet = 0;
2189 return 0;
2192 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2194 char c, *eq;
2195 int len;
2197 if (*arg != '-')
2198 return 0;
2199 c = *++arg;
2200 if (!c)
2201 return 0;
2202 if (c == arg_short) {
2203 c = *++arg;
2204 if (!c)
2205 return 1;
2206 if (val && isdigit(c)) {
2207 char *end;
2208 int n = strtoul(arg, &end, 10);
2209 if (*end)
2210 return 0;
2211 *val = n;
2212 return 1;
2214 return 0;
2216 if (c != '-')
2217 return 0;
2218 arg++;
2219 eq = strchr(arg, '=');
2220 if (eq)
2221 len = eq - arg;
2222 else
2223 len = strlen(arg);
2224 if (!len || strncmp(arg, arg_long, len))
2225 return 0;
2226 if (eq) {
2227 int n;
2228 char *end;
2229 if (!isdigit(*++eq))
2230 return 0;
2231 n = strtoul(eq, &end, 10);
2232 if (*end)
2233 return 0;
2234 *val = n;
2236 return 1;
2239 static int diff_scoreopt_parse(const char *opt);
2241 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2243 const char *arg = av[0];
2244 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2245 options->output_format |= DIFF_FORMAT_PATCH;
2246 else if (opt_arg(arg, 'U', "unified", &options->context))
2247 options->output_format |= DIFF_FORMAT_PATCH;
2248 else if (!strcmp(arg, "--raw"))
2249 options->output_format |= DIFF_FORMAT_RAW;
2250 else if (!strcmp(arg, "--patch-with-raw")) {
2251 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2253 else if (!strcmp(arg, "--numstat")) {
2254 options->output_format |= DIFF_FORMAT_NUMSTAT;
2256 else if (!strcmp(arg, "--shortstat")) {
2257 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2259 else if (!prefixcmp(arg, "--stat")) {
2260 char *end;
2261 int width = options->stat_width;
2262 int name_width = options->stat_name_width;
2263 arg += 6;
2264 end = (char *)arg;
2266 switch (*arg) {
2267 case '-':
2268 if (!prefixcmp(arg, "-width="))
2269 width = strtoul(arg + 7, &end, 10);
2270 else if (!prefixcmp(arg, "-name-width="))
2271 name_width = strtoul(arg + 12, &end, 10);
2272 break;
2273 case '=':
2274 width = strtoul(arg+1, &end, 10);
2275 if (*end == ',')
2276 name_width = strtoul(end+1, &end, 10);
2279 /* Important! This checks all the error cases! */
2280 if (*end)
2281 return 0;
2282 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2283 options->stat_name_width = name_width;
2284 options->stat_width = width;
2286 else if (!strcmp(arg, "--check"))
2287 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2288 else if (!strcmp(arg, "--summary"))
2289 options->output_format |= DIFF_FORMAT_SUMMARY;
2290 else if (!strcmp(arg, "--patch-with-stat")) {
2291 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2293 else if (!strcmp(arg, "-z"))
2294 options->line_termination = 0;
2295 else if (!prefixcmp(arg, "-l"))
2296 options->rename_limit = strtoul(arg+2, NULL, 10);
2297 else if (!strcmp(arg, "--full-index"))
2298 options->full_index = 1;
2299 else if (!strcmp(arg, "--binary")) {
2300 options->output_format |= DIFF_FORMAT_PATCH;
2301 options->binary = 1;
2303 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
2304 options->text = 1;
2306 else if (!strcmp(arg, "--name-only"))
2307 options->output_format |= DIFF_FORMAT_NAME;
2308 else if (!strcmp(arg, "--name-status"))
2309 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2310 else if (!strcmp(arg, "-R"))
2311 options->reverse_diff = 1;
2312 else if (!prefixcmp(arg, "-S"))
2313 options->pickaxe = arg + 2;
2314 else if (!strcmp(arg, "-s")) {
2315 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2317 else if (!prefixcmp(arg, "-O"))
2318 options->orderfile = arg + 2;
2319 else if (!prefixcmp(arg, "--diff-filter="))
2320 options->filter = arg + 14;
2321 else if (!strcmp(arg, "--pickaxe-all"))
2322 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2323 else if (!strcmp(arg, "--pickaxe-regex"))
2324 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2325 else if (!prefixcmp(arg, "-B")) {
2326 if ((options->break_opt =
2327 diff_scoreopt_parse(arg)) == -1)
2328 return -1;
2330 else if (!prefixcmp(arg, "-M")) {
2331 if ((options->rename_score =
2332 diff_scoreopt_parse(arg)) == -1)
2333 return -1;
2334 options->detect_rename = DIFF_DETECT_RENAME;
2336 else if (!prefixcmp(arg, "-C")) {
2337 if (options->detect_rename == DIFF_DETECT_COPY)
2338 options->find_copies_harder = 1;
2339 if ((options->rename_score =
2340 diff_scoreopt_parse(arg)) == -1)
2341 return -1;
2342 options->detect_rename = DIFF_DETECT_COPY;
2344 else if (!strcmp(arg, "--find-copies-harder"))
2345 options->find_copies_harder = 1;
2346 else if (!strcmp(arg, "--follow"))
2347 options->follow_renames = 1;
2348 else if (!strcmp(arg, "--abbrev"))
2349 options->abbrev = DEFAULT_ABBREV;
2350 else if (!prefixcmp(arg, "--abbrev=")) {
2351 options->abbrev = strtoul(arg + 9, NULL, 10);
2352 if (options->abbrev < MINIMUM_ABBREV)
2353 options->abbrev = MINIMUM_ABBREV;
2354 else if (40 < options->abbrev)
2355 options->abbrev = 40;
2357 else if (!strcmp(arg, "--color"))
2358 options->color_diff = 1;
2359 else if (!strcmp(arg, "--no-color"))
2360 options->color_diff = 0;
2361 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2362 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2363 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2364 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2365 else if (!strcmp(arg, "--ignore-space-at-eol"))
2366 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2367 else if (!strcmp(arg, "--color-words"))
2368 options->color_diff = options->color_diff_words = 1;
2369 else if (!strcmp(arg, "--no-renames"))
2370 options->detect_rename = 0;
2371 else if (!strcmp(arg, "--exit-code"))
2372 options->exit_with_status = 1;
2373 else if (!strcmp(arg, "--quiet"))
2374 options->quiet = 1;
2375 else if (!strcmp(arg, "--ext-diff"))
2376 options->allow_external = 1;
2377 else if (!strcmp(arg, "--no-ext-diff"))
2378 options->allow_external = 0;
2379 else
2380 return 0;
2381 return 1;
2384 static int parse_num(const char **cp_p)
2386 unsigned long num, scale;
2387 int ch, dot;
2388 const char *cp = *cp_p;
2390 num = 0;
2391 scale = 1;
2392 dot = 0;
2393 for(;;) {
2394 ch = *cp;
2395 if ( !dot && ch == '.' ) {
2396 scale = 1;
2397 dot = 1;
2398 } else if ( ch == '%' ) {
2399 scale = dot ? scale*100 : 100;
2400 cp++; /* % is always at the end */
2401 break;
2402 } else if ( ch >= '0' && ch <= '9' ) {
2403 if ( scale < 100000 ) {
2404 scale *= 10;
2405 num = (num*10) + (ch-'0');
2407 } else {
2408 break;
2410 cp++;
2412 *cp_p = cp;
2414 /* user says num divided by scale and we say internally that
2415 * is MAX_SCORE * num / scale.
2417 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2420 static int diff_scoreopt_parse(const char *opt)
2422 int opt1, opt2, cmd;
2424 if (*opt++ != '-')
2425 return -1;
2426 cmd = *opt++;
2427 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2428 return -1; /* that is not a -M, -C nor -B option */
2430 opt1 = parse_num(&opt);
2431 if (cmd != 'B')
2432 opt2 = 0;
2433 else {
2434 if (*opt == 0)
2435 opt2 = 0;
2436 else if (*opt != '/')
2437 return -1; /* we expect -B80/99 or -B80 */
2438 else {
2439 opt++;
2440 opt2 = parse_num(&opt);
2443 if (*opt != 0)
2444 return -1;
2445 return opt1 | (opt2 << 16);
2448 struct diff_queue_struct diff_queued_diff;
2450 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2452 if (queue->alloc <= queue->nr) {
2453 queue->alloc = alloc_nr(queue->alloc);
2454 queue->queue = xrealloc(queue->queue,
2455 sizeof(dp) * queue->alloc);
2457 queue->queue[queue->nr++] = dp;
2460 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2461 struct diff_filespec *one,
2462 struct diff_filespec *two)
2464 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2465 dp->one = one;
2466 dp->two = two;
2467 if (queue)
2468 diff_q(queue, dp);
2469 return dp;
2472 void diff_free_filepair(struct diff_filepair *p)
2474 diff_free_filespec_data(p->one);
2475 diff_free_filespec_data(p->two);
2476 free(p->one);
2477 free(p->two);
2478 free(p);
2481 /* This is different from find_unique_abbrev() in that
2482 * it stuffs the result with dots for alignment.
2484 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2486 int abblen;
2487 const char *abbrev;
2488 if (len == 40)
2489 return sha1_to_hex(sha1);
2491 abbrev = find_unique_abbrev(sha1, len);
2492 if (!abbrev)
2493 return sha1_to_hex(sha1);
2494 abblen = strlen(abbrev);
2495 if (abblen < 37) {
2496 static char hex[41];
2497 if (len < abblen && abblen <= len + 2)
2498 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2499 else
2500 sprintf(hex, "%s...", abbrev);
2501 return hex;
2503 return sha1_to_hex(sha1);
2506 static void diff_flush_raw(struct diff_filepair *p,
2507 struct diff_options *options)
2509 int two_paths;
2510 char status[10];
2511 int abbrev = options->abbrev;
2512 const char *path_one, *path_two;
2513 int inter_name_termination = '\t';
2514 int line_termination = options->line_termination;
2516 if (!line_termination)
2517 inter_name_termination = 0;
2519 path_one = p->one->path;
2520 path_two = p->two->path;
2521 if (line_termination) {
2522 path_one = quote_one(path_one);
2523 path_two = quote_one(path_two);
2526 if (p->score)
2527 sprintf(status, "%c%03d", p->status, similarity_index(p));
2528 else {
2529 status[0] = p->status;
2530 status[1] = 0;
2532 switch (p->status) {
2533 case DIFF_STATUS_COPIED:
2534 case DIFF_STATUS_RENAMED:
2535 two_paths = 1;
2536 break;
2537 case DIFF_STATUS_ADDED:
2538 case DIFF_STATUS_DELETED:
2539 two_paths = 0;
2540 break;
2541 default:
2542 two_paths = 0;
2543 break;
2545 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2546 printf(":%06o %06o %s ",
2547 p->one->mode, p->two->mode,
2548 diff_unique_abbrev(p->one->sha1, abbrev));
2549 printf("%s ",
2550 diff_unique_abbrev(p->two->sha1, abbrev));
2552 printf("%s%c%s", status, inter_name_termination,
2553 two_paths || p->one->mode ? path_one : path_two);
2554 if (two_paths)
2555 printf("%c%s", inter_name_termination, path_two);
2556 putchar(line_termination);
2557 if (path_one != p->one->path)
2558 free((void*)path_one);
2559 if (path_two != p->two->path)
2560 free((void*)path_two);
2563 static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2565 char *path = p->two->path;
2567 if (opt->line_termination)
2568 path = quote_one(p->two->path);
2569 printf("%s%c", path, opt->line_termination);
2570 if (p->two->path != path)
2571 free(path);
2574 int diff_unmodified_pair(struct diff_filepair *p)
2576 /* This function is written stricter than necessary to support
2577 * the currently implemented transformers, but the idea is to
2578 * let transformers to produce diff_filepairs any way they want,
2579 * and filter and clean them up here before producing the output.
2581 struct diff_filespec *one, *two;
2583 if (DIFF_PAIR_UNMERGED(p))
2584 return 0; /* unmerged is interesting */
2586 one = p->one;
2587 two = p->two;
2589 /* deletion, addition, mode or type change
2590 * and rename are all interesting.
2592 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2593 DIFF_PAIR_MODE_CHANGED(p) ||
2594 strcmp(one->path, two->path))
2595 return 0;
2597 /* both are valid and point at the same path. that is, we are
2598 * dealing with a change.
2600 if (one->sha1_valid && two->sha1_valid &&
2601 !hashcmp(one->sha1, two->sha1))
2602 return 1; /* no change */
2603 if (!one->sha1_valid && !two->sha1_valid)
2604 return 1; /* both look at the same file on the filesystem. */
2605 return 0;
2608 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2610 if (diff_unmodified_pair(p))
2611 return;
2613 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2614 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2615 return; /* no tree diffs in patch format */
2617 run_diff(p, o);
2620 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2621 struct diffstat_t *diffstat)
2623 if (diff_unmodified_pair(p))
2624 return;
2626 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2627 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2628 return; /* no tree diffs in patch format */
2630 run_diffstat(p, o, diffstat);
2633 static void diff_flush_checkdiff(struct diff_filepair *p,
2634 struct diff_options *o)
2636 if (diff_unmodified_pair(p))
2637 return;
2639 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2640 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2641 return; /* no tree diffs in patch format */
2643 run_checkdiff(p, o);
2646 int diff_queue_is_empty(void)
2648 struct diff_queue_struct *q = &diff_queued_diff;
2649 int i;
2650 for (i = 0; i < q->nr; i++)
2651 if (!diff_unmodified_pair(q->queue[i]))
2652 return 0;
2653 return 1;
2656 #if DIFF_DEBUG
2657 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2659 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2660 x, one ? one : "",
2661 s->path,
2662 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2663 s->mode,
2664 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2665 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2666 x, one ? one : "",
2667 s->size, s->xfrm_flags);
2670 void diff_debug_filepair(const struct diff_filepair *p, int i)
2672 diff_debug_filespec(p->one, i, "one");
2673 diff_debug_filespec(p->two, i, "two");
2674 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2675 p->score, p->status ? p->status : '?',
2676 p->source_stays, p->broken_pair);
2679 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2681 int i;
2682 if (msg)
2683 fprintf(stderr, "%s\n", msg);
2684 fprintf(stderr, "q->nr = %d\n", q->nr);
2685 for (i = 0; i < q->nr; i++) {
2686 struct diff_filepair *p = q->queue[i];
2687 diff_debug_filepair(p, i);
2690 #endif
2692 static void diff_resolve_rename_copy(void)
2694 int i, j;
2695 struct diff_filepair *p, *pp;
2696 struct diff_queue_struct *q = &diff_queued_diff;
2698 diff_debug_queue("resolve-rename-copy", q);
2700 for (i = 0; i < q->nr; i++) {
2701 p = q->queue[i];
2702 p->status = 0; /* undecided */
2703 if (DIFF_PAIR_UNMERGED(p))
2704 p->status = DIFF_STATUS_UNMERGED;
2705 else if (!DIFF_FILE_VALID(p->one))
2706 p->status = DIFF_STATUS_ADDED;
2707 else if (!DIFF_FILE_VALID(p->two))
2708 p->status = DIFF_STATUS_DELETED;
2709 else if (DIFF_PAIR_TYPE_CHANGED(p))
2710 p->status = DIFF_STATUS_TYPE_CHANGED;
2712 /* from this point on, we are dealing with a pair
2713 * whose both sides are valid and of the same type, i.e.
2714 * either in-place edit or rename/copy edit.
2716 else if (DIFF_PAIR_RENAME(p)) {
2717 if (p->source_stays) {
2718 p->status = DIFF_STATUS_COPIED;
2719 continue;
2721 /* See if there is some other filepair that
2722 * copies from the same source as us. If so
2723 * we are a copy. Otherwise we are either a
2724 * copy if the path stays, or a rename if it
2725 * does not, but we already handled "stays" case.
2727 for (j = i + 1; j < q->nr; j++) {
2728 pp = q->queue[j];
2729 if (strcmp(pp->one->path, p->one->path))
2730 continue; /* not us */
2731 if (!DIFF_PAIR_RENAME(pp))
2732 continue; /* not a rename/copy */
2733 /* pp is a rename/copy from the same source */
2734 p->status = DIFF_STATUS_COPIED;
2735 break;
2737 if (!p->status)
2738 p->status = DIFF_STATUS_RENAMED;
2740 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2741 p->one->mode != p->two->mode ||
2742 is_null_sha1(p->one->sha1))
2743 p->status = DIFF_STATUS_MODIFIED;
2744 else {
2745 /* This is a "no-change" entry and should not
2746 * happen anymore, but prepare for broken callers.
2748 error("feeding unmodified %s to diffcore",
2749 p->one->path);
2750 p->status = DIFF_STATUS_UNKNOWN;
2753 diff_debug_queue("resolve-rename-copy done", q);
2756 static int check_pair_status(struct diff_filepair *p)
2758 switch (p->status) {
2759 case DIFF_STATUS_UNKNOWN:
2760 return 0;
2761 case 0:
2762 die("internal error in diff-resolve-rename-copy");
2763 default:
2764 return 1;
2768 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2770 int fmt = opt->output_format;
2772 if (fmt & DIFF_FORMAT_CHECKDIFF)
2773 diff_flush_checkdiff(p, opt);
2774 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2775 diff_flush_raw(p, opt);
2776 else if (fmt & DIFF_FORMAT_NAME)
2777 diff_flush_name(p, opt);
2780 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2782 char *name = quote_one(fs->path);
2783 if (fs->mode)
2784 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2785 else
2786 printf(" %s %s\n", newdelete, name);
2787 free(name);
2791 static void show_mode_change(struct diff_filepair *p, int show_name)
2793 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2794 if (show_name) {
2795 char *name = quote_one(p->two->path);
2796 printf(" mode change %06o => %06o %s\n",
2797 p->one->mode, p->two->mode, name);
2798 free(name);
2800 else
2801 printf(" mode change %06o => %06o\n",
2802 p->one->mode, p->two->mode);
2806 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2808 char *names = pprint_rename(p->one->path, p->two->path);
2810 printf(" %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2811 free(names);
2812 show_mode_change(p, 0);
2815 static void diff_summary(struct diff_filepair *p)
2817 switch(p->status) {
2818 case DIFF_STATUS_DELETED:
2819 show_file_mode_name("delete", p->one);
2820 break;
2821 case DIFF_STATUS_ADDED:
2822 show_file_mode_name("create", p->two);
2823 break;
2824 case DIFF_STATUS_COPIED:
2825 show_rename_copy("copy", p);
2826 break;
2827 case DIFF_STATUS_RENAMED:
2828 show_rename_copy("rename", p);
2829 break;
2830 default:
2831 if (p->score) {
2832 char *name = quote_one(p->two->path);
2833 printf(" rewrite %s (%d%%)\n", name,
2834 similarity_index(p));
2835 free(name);
2836 show_mode_change(p, 0);
2837 } else show_mode_change(p, 1);
2838 break;
2842 struct patch_id_t {
2843 struct xdiff_emit_state xm;
2844 SHA_CTX *ctx;
2845 int patchlen;
2848 static int remove_space(char *line, int len)
2850 int i;
2851 char *dst = line;
2852 unsigned char c;
2854 for (i = 0; i < len; i++)
2855 if (!isspace((c = line[i])))
2856 *dst++ = c;
2858 return dst - line;
2861 static void patch_id_consume(void *priv, char *line, unsigned long len)
2863 struct patch_id_t *data = priv;
2864 int new_len;
2866 /* Ignore line numbers when computing the SHA1 of the patch */
2867 if (!prefixcmp(line, "@@ -"))
2868 return;
2870 new_len = remove_space(line, len);
2872 SHA1_Update(data->ctx, line, new_len);
2873 data->patchlen += new_len;
2876 /* returns 0 upon success, and writes result into sha1 */
2877 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2879 struct diff_queue_struct *q = &diff_queued_diff;
2880 int i;
2881 SHA_CTX ctx;
2882 struct patch_id_t data;
2883 char buffer[PATH_MAX * 4 + 20];
2885 SHA1_Init(&ctx);
2886 memset(&data, 0, sizeof(struct patch_id_t));
2887 data.ctx = &ctx;
2888 data.xm.consume = patch_id_consume;
2890 for (i = 0; i < q->nr; i++) {
2891 xpparam_t xpp;
2892 xdemitconf_t xecfg;
2893 xdemitcb_t ecb;
2894 mmfile_t mf1, mf2;
2895 struct diff_filepair *p = q->queue[i];
2896 int len1, len2;
2898 memset(&xecfg, 0, sizeof(xecfg));
2899 if (p->status == 0)
2900 return error("internal diff status error");
2901 if (p->status == DIFF_STATUS_UNKNOWN)
2902 continue;
2903 if (diff_unmodified_pair(p))
2904 continue;
2905 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2906 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2907 continue;
2908 if (DIFF_PAIR_UNMERGED(p))
2909 continue;
2911 diff_fill_sha1_info(p->one);
2912 diff_fill_sha1_info(p->two);
2913 if (fill_mmfile(&mf1, p->one) < 0 ||
2914 fill_mmfile(&mf2, p->two) < 0)
2915 return error("unable to read files to diff");
2917 /* Maybe hash p->two? into the patch id? */
2918 if (diff_filespec_is_binary(p->two))
2919 continue;
2921 len1 = remove_space(p->one->path, strlen(p->one->path));
2922 len2 = remove_space(p->two->path, strlen(p->two->path));
2923 if (p->one->mode == 0)
2924 len1 = snprintf(buffer, sizeof(buffer),
2925 "diff--gita/%.*sb/%.*s"
2926 "newfilemode%06o"
2927 "---/dev/null"
2928 "+++b/%.*s",
2929 len1, p->one->path,
2930 len2, p->two->path,
2931 p->two->mode,
2932 len2, p->two->path);
2933 else if (p->two->mode == 0)
2934 len1 = snprintf(buffer, sizeof(buffer),
2935 "diff--gita/%.*sb/%.*s"
2936 "deletedfilemode%06o"
2937 "---a/%.*s"
2938 "+++/dev/null",
2939 len1, p->one->path,
2940 len2, p->two->path,
2941 p->one->mode,
2942 len1, p->one->path);
2943 else
2944 len1 = snprintf(buffer, sizeof(buffer),
2945 "diff--gita/%.*sb/%.*s"
2946 "---a/%.*s"
2947 "+++b/%.*s",
2948 len1, p->one->path,
2949 len2, p->two->path,
2950 len1, p->one->path,
2951 len2, p->two->path);
2952 SHA1_Update(&ctx, buffer, len1);
2954 xpp.flags = XDF_NEED_MINIMAL;
2955 xecfg.ctxlen = 3;
2956 xecfg.flags = XDL_EMIT_FUNCNAMES;
2957 ecb.outf = xdiff_outf;
2958 ecb.priv = &data;
2959 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2962 SHA1_Final(sha1, &ctx);
2963 return 0;
2966 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2968 struct diff_queue_struct *q = &diff_queued_diff;
2969 int i;
2970 int result = diff_get_patch_id(options, sha1);
2972 for (i = 0; i < q->nr; i++)
2973 diff_free_filepair(q->queue[i]);
2975 free(q->queue);
2976 q->queue = NULL;
2977 q->nr = q->alloc = 0;
2979 return result;
2982 static int is_summary_empty(const struct diff_queue_struct *q)
2984 int i;
2986 for (i = 0; i < q->nr; i++) {
2987 const struct diff_filepair *p = q->queue[i];
2989 switch (p->status) {
2990 case DIFF_STATUS_DELETED:
2991 case DIFF_STATUS_ADDED:
2992 case DIFF_STATUS_COPIED:
2993 case DIFF_STATUS_RENAMED:
2994 return 0;
2995 default:
2996 if (p->score)
2997 return 0;
2998 if (p->one->mode && p->two->mode &&
2999 p->one->mode != p->two->mode)
3000 return 0;
3001 break;
3004 return 1;
3007 void diff_flush(struct diff_options *options)
3009 struct diff_queue_struct *q = &diff_queued_diff;
3010 int i, output_format = options->output_format;
3011 int separator = 0;
3014 * Order: raw, stat, summary, patch
3015 * or: name/name-status/checkdiff (other bits clear)
3017 if (!q->nr)
3018 goto free_queue;
3020 if (output_format & (DIFF_FORMAT_RAW |
3021 DIFF_FORMAT_NAME |
3022 DIFF_FORMAT_NAME_STATUS |
3023 DIFF_FORMAT_CHECKDIFF)) {
3024 for (i = 0; i < q->nr; i++) {
3025 struct diff_filepair *p = q->queue[i];
3026 if (check_pair_status(p))
3027 flush_one_pair(p, options);
3029 separator++;
3032 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3033 struct diffstat_t diffstat;
3035 memset(&diffstat, 0, sizeof(struct diffstat_t));
3036 diffstat.xm.consume = diffstat_consume;
3037 for (i = 0; i < q->nr; i++) {
3038 struct diff_filepair *p = q->queue[i];
3039 if (check_pair_status(p))
3040 diff_flush_stat(p, options, &diffstat);
3042 if (output_format & DIFF_FORMAT_NUMSTAT)
3043 show_numstat(&diffstat, options);
3044 if (output_format & DIFF_FORMAT_DIFFSTAT)
3045 show_stats(&diffstat, options);
3046 else if (output_format & DIFF_FORMAT_SHORTSTAT)
3047 show_shortstats(&diffstat);
3048 separator++;
3051 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3052 for (i = 0; i < q->nr; i++)
3053 diff_summary(q->queue[i]);
3054 separator++;
3057 if (output_format & DIFF_FORMAT_PATCH) {
3058 if (separator) {
3059 if (options->stat_sep) {
3060 /* attach patch instead of inline */
3061 fputs(options->stat_sep, stdout);
3062 } else {
3063 putchar(options->line_termination);
3067 for (i = 0; i < q->nr; i++) {
3068 struct diff_filepair *p = q->queue[i];
3069 if (check_pair_status(p))
3070 diff_flush_patch(p, options);
3074 if (output_format & DIFF_FORMAT_CALLBACK)
3075 options->format_callback(q, options, options->format_callback_data);
3077 for (i = 0; i < q->nr; i++)
3078 diff_free_filepair(q->queue[i]);
3079 free_queue:
3080 free(q->queue);
3081 q->queue = NULL;
3082 q->nr = q->alloc = 0;
3085 static void diffcore_apply_filter(const char *filter)
3087 int i;
3088 struct diff_queue_struct *q = &diff_queued_diff;
3089 struct diff_queue_struct outq;
3090 outq.queue = NULL;
3091 outq.nr = outq.alloc = 0;
3093 if (!filter)
3094 return;
3096 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3097 int found;
3098 for (i = found = 0; !found && i < q->nr; i++) {
3099 struct diff_filepair *p = q->queue[i];
3100 if (((p->status == DIFF_STATUS_MODIFIED) &&
3101 ((p->score &&
3102 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3103 (!p->score &&
3104 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3105 ((p->status != DIFF_STATUS_MODIFIED) &&
3106 strchr(filter, p->status)))
3107 found++;
3109 if (found)
3110 return;
3112 /* otherwise we will clear the whole queue
3113 * by copying the empty outq at the end of this
3114 * function, but first clear the current entries
3115 * in the queue.
3117 for (i = 0; i < q->nr; i++)
3118 diff_free_filepair(q->queue[i]);
3120 else {
3121 /* Only the matching ones */
3122 for (i = 0; i < q->nr; i++) {
3123 struct diff_filepair *p = q->queue[i];
3125 if (((p->status == DIFF_STATUS_MODIFIED) &&
3126 ((p->score &&
3127 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3128 (!p->score &&
3129 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3130 ((p->status != DIFF_STATUS_MODIFIED) &&
3131 strchr(filter, p->status)))
3132 diff_q(&outq, p);
3133 else
3134 diff_free_filepair(p);
3137 free(q->queue);
3138 *q = outq;
3141 void diffcore_std(struct diff_options *options)
3143 if (options->quiet)
3144 return;
3146 if (options->break_opt != -1)
3147 diffcore_break(options->break_opt);
3148 if (options->detect_rename)
3149 diffcore_rename(options);
3150 if (options->break_opt != -1)
3151 diffcore_merge_broken();
3152 if (options->pickaxe)
3153 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3154 if (options->orderfile)
3155 diffcore_order(options->orderfile);
3156 diff_resolve_rename_copy();
3157 diffcore_apply_filter(options->filter);
3159 options->has_changes = !!diff_queued_diff.nr;
3163 void diff_addremove(struct diff_options *options,
3164 int addremove, unsigned mode,
3165 const unsigned char *sha1,
3166 const char *base, const char *path)
3168 char concatpath[PATH_MAX];
3169 struct diff_filespec *one, *two;
3171 /* This may look odd, but it is a preparation for
3172 * feeding "there are unchanged files which should
3173 * not produce diffs, but when you are doing copy
3174 * detection you would need them, so here they are"
3175 * entries to the diff-core. They will be prefixed
3176 * with something like '=' or '*' (I haven't decided
3177 * which but should not make any difference).
3178 * Feeding the same new and old to diff_change()
3179 * also has the same effect.
3180 * Before the final output happens, they are pruned after
3181 * merged into rename/copy pairs as appropriate.
3183 if (options->reverse_diff)
3184 addremove = (addremove == '+' ? '-' :
3185 addremove == '-' ? '+' : addremove);
3187 if (!path) path = "";
3188 sprintf(concatpath, "%s%s", base, path);
3189 one = alloc_filespec(concatpath);
3190 two = alloc_filespec(concatpath);
3192 if (addremove != '+')
3193 fill_filespec(one, sha1, mode);
3194 if (addremove != '-')
3195 fill_filespec(two, sha1, mode);
3197 diff_queue(&diff_queued_diff, one, two);
3198 options->has_changes = 1;
3201 void diff_change(struct diff_options *options,
3202 unsigned old_mode, unsigned new_mode,
3203 const unsigned char *old_sha1,
3204 const unsigned char *new_sha1,
3205 const char *base, const char *path)
3207 char concatpath[PATH_MAX];
3208 struct diff_filespec *one, *two;
3210 if (options->reverse_diff) {
3211 unsigned tmp;
3212 const unsigned char *tmp_c;
3213 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3214 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3216 if (!path) path = "";
3217 sprintf(concatpath, "%s%s", base, path);
3218 one = alloc_filespec(concatpath);
3219 two = alloc_filespec(concatpath);
3220 fill_filespec(one, old_sha1, old_mode);
3221 fill_filespec(two, new_sha1, new_mode);
3223 diff_queue(&diff_queued_diff, one, two);
3224 options->has_changes = 1;
3227 void diff_unmerge(struct diff_options *options,
3228 const char *path,
3229 unsigned mode, const unsigned char *sha1)
3231 struct diff_filespec *one, *two;
3232 one = alloc_filespec(path);
3233 two = alloc_filespec(path);
3234 fill_filespec(one, sha1, mode);
3235 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;