git.el: Display file types and type changes.
[git/jrn.git] / diff.c
blob2c78d74a427aa04aba1403661c899083488e46f2
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 "run-command.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 = 100;
22 static int diff_use_color_default;
23 static const char *external_diff_cmd_cfg;
24 int diff_auto_refresh_index = 1;
26 static char diff_colors[][COLOR_MAXLEN] = {
27 "\033[m", /* reset */
28 "", /* PLAIN (normal) */
29 "\033[1m", /* METAINFO (bold) */
30 "\033[36m", /* FRAGINFO (cyan) */
31 "\033[31m", /* OLD (red) */
32 "\033[32m", /* NEW (green) */
33 "\033[33m", /* COMMIT (yellow) */
34 "\033[41m", /* WHITESPACE (red background) */
37 static int parse_diff_color_slot(const char *var, int ofs)
39 if (!strcasecmp(var+ofs, "plain"))
40 return DIFF_PLAIN;
41 if (!strcasecmp(var+ofs, "meta"))
42 return DIFF_METAINFO;
43 if (!strcasecmp(var+ofs, "frag"))
44 return DIFF_FRAGINFO;
45 if (!strcasecmp(var+ofs, "old"))
46 return DIFF_FILE_OLD;
47 if (!strcasecmp(var+ofs, "new"))
48 return DIFF_FILE_NEW;
49 if (!strcasecmp(var+ofs, "commit"))
50 return DIFF_COMMIT;
51 if (!strcasecmp(var+ofs, "whitespace"))
52 return DIFF_WHITESPACE;
53 die("bad config variable '%s'", var);
56 static struct ll_diff_driver {
57 const char *name;
58 struct ll_diff_driver *next;
59 char *cmd;
60 } *user_diff, **user_diff_tail;
63 * Currently there is only "diff.<drivername>.command" variable;
64 * because there are "diff.color.<slot>" variables, we are parsing
65 * this in a bit convoluted way to allow low level diff driver
66 * called "color".
68 static int parse_lldiff_command(const char *var, const char *ep, const char *value)
70 const char *name;
71 int namelen;
72 struct ll_diff_driver *drv;
74 name = var + 5;
75 namelen = ep - name;
76 for (drv = user_diff; drv; drv = drv->next)
77 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
78 break;
79 if (!drv) {
80 drv = xcalloc(1, sizeof(struct ll_diff_driver));
81 drv->name = xmemdupz(name, namelen);
82 if (!user_diff_tail)
83 user_diff_tail = &user_diff;
84 *user_diff_tail = drv;
85 user_diff_tail = &(drv->next);
88 if (!value)
89 return error("%s: lacks value", var);
90 drv->cmd = strdup(value);
91 return 0;
95 * 'diff.<what>.funcname' attribute can be specified in the configuration
96 * to define a customized regexp to find the beginning of a function to
97 * be used for hunk header lines of "diff -p" style output.
99 static struct funcname_pattern {
100 char *name;
101 char *pattern;
102 struct funcname_pattern *next;
103 } *funcname_pattern_list;
105 static int parse_funcname_pattern(const char *var, const char *ep, const char *value)
107 const char *name;
108 int namelen;
109 struct funcname_pattern *pp;
111 name = var + 5; /* "diff." */
112 namelen = ep - name;
114 for (pp = funcname_pattern_list; pp; pp = pp->next)
115 if (!strncmp(pp->name, name, namelen) && !pp->name[namelen])
116 break;
117 if (!pp) {
118 pp = xcalloc(1, sizeof(*pp));
119 pp->name = xmemdupz(name, namelen);
120 pp->next = funcname_pattern_list;
121 funcname_pattern_list = pp;
123 if (pp->pattern)
124 free(pp->pattern);
125 pp->pattern = xstrdup(value);
126 return 0;
130 * These are to give UI layer defaults.
131 * The core-level commands such as git-diff-files should
132 * never be affected by the setting of diff.renames
133 * the user happens to have in the configuration file.
135 int git_diff_ui_config(const char *var, const char *value)
137 if (!strcmp(var, "diff.renamelimit")) {
138 diff_rename_limit_default = git_config_int(var, value);
139 return 0;
141 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
142 diff_use_color_default = git_config_colorbool(var, value, -1);
143 return 0;
145 if (!strcmp(var, "diff.renames")) {
146 if (!value)
147 diff_detect_rename_default = DIFF_DETECT_RENAME;
148 else if (!strcasecmp(value, "copies") ||
149 !strcasecmp(value, "copy"))
150 diff_detect_rename_default = DIFF_DETECT_COPY;
151 else if (git_config_bool(var,value))
152 diff_detect_rename_default = DIFF_DETECT_RENAME;
153 return 0;
155 if (!strcmp(var, "diff.autorefreshindex")) {
156 diff_auto_refresh_index = git_config_bool(var, value);
157 return 0;
159 if (!strcmp(var, "diff.external")) {
160 external_diff_cmd_cfg = xstrdup(value);
161 return 0;
163 if (!prefixcmp(var, "diff.")) {
164 const char *ep = strrchr(var, '.');
166 if (ep != var + 4) {
167 if (!strcmp(ep, ".command"))
168 return parse_lldiff_command(var, ep, value);
172 return git_diff_basic_config(var, value);
175 int git_diff_basic_config(const char *var, const char *value)
177 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
178 int slot = parse_diff_color_slot(var, 11);
179 color_parse(value, var, diff_colors[slot]);
180 return 0;
183 if (!prefixcmp(var, "diff.")) {
184 const char *ep = strrchr(var, '.');
185 if (ep != var + 4) {
186 if (!strcmp(ep, ".funcname"))
187 return parse_funcname_pattern(var, ep, value);
191 return git_default_config(var, value);
194 static char *quote_two(const char *one, const char *two)
196 int need_one = quote_c_style(one, NULL, NULL, 1);
197 int need_two = quote_c_style(two, NULL, NULL, 1);
198 struct strbuf res;
200 strbuf_init(&res, 0);
201 if (need_one + need_two) {
202 strbuf_addch(&res, '"');
203 quote_c_style(one, &res, NULL, 1);
204 quote_c_style(two, &res, NULL, 1);
205 strbuf_addch(&res, '"');
206 } else {
207 strbuf_addstr(&res, one);
208 strbuf_addstr(&res, two);
210 return strbuf_detach(&res, NULL);
213 static const char *external_diff(void)
215 static const char *external_diff_cmd = NULL;
216 static int done_preparing = 0;
218 if (done_preparing)
219 return external_diff_cmd;
220 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
221 if (!external_diff_cmd)
222 external_diff_cmd = external_diff_cmd_cfg;
223 done_preparing = 1;
224 return external_diff_cmd;
227 static struct diff_tempfile {
228 const char *name; /* filename external diff should read from */
229 char hex[41];
230 char mode[10];
231 char tmp_path[PATH_MAX];
232 } diff_temp[2];
234 static int count_lines(const char *data, int size)
236 int count, ch, completely_empty = 1, nl_just_seen = 0;
237 count = 0;
238 while (0 < size--) {
239 ch = *data++;
240 if (ch == '\n') {
241 count++;
242 nl_just_seen = 1;
243 completely_empty = 0;
245 else {
246 nl_just_seen = 0;
247 completely_empty = 0;
250 if (completely_empty)
251 return 0;
252 if (!nl_just_seen)
253 count++; /* no trailing newline */
254 return count;
257 static void print_line_count(int count)
259 switch (count) {
260 case 0:
261 printf("0,0");
262 break;
263 case 1:
264 printf("1");
265 break;
266 default:
267 printf("1,%d", count);
268 break;
272 static void copy_file(int prefix, const char *data, int size,
273 const char *set, const char *reset)
275 int ch, nl_just_seen = 1;
276 while (0 < size--) {
277 ch = *data++;
278 if (nl_just_seen) {
279 fputs(set, stdout);
280 putchar(prefix);
282 if (ch == '\n') {
283 nl_just_seen = 1;
284 fputs(reset, stdout);
285 } else
286 nl_just_seen = 0;
287 putchar(ch);
289 if (!nl_just_seen)
290 printf("%s\n\\ No newline at end of file\n", reset);
293 static void emit_rewrite_diff(const char *name_a,
294 const char *name_b,
295 struct diff_filespec *one,
296 struct diff_filespec *two,
297 struct diff_options *o)
299 int lc_a, lc_b;
300 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
301 const char *name_a_tab, *name_b_tab;
302 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
303 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
304 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
305 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
306 const char *reset = diff_get_color(color_diff, DIFF_RESET);
307 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
309 name_a += (*name_a == '/');
310 name_b += (*name_b == '/');
311 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
312 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
314 strbuf_reset(&a_name);
315 strbuf_reset(&b_name);
316 quote_two_c_style(&a_name, o->a_prefix, name_a, 0);
317 quote_two_c_style(&b_name, o->b_prefix, name_b, 0);
319 diff_populate_filespec(one, 0);
320 diff_populate_filespec(two, 0);
321 lc_a = count_lines(one->data, one->size);
322 lc_b = count_lines(two->data, two->size);
323 printf("%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
324 metainfo, a_name.buf, name_a_tab, reset,
325 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
326 print_line_count(lc_a);
327 printf(" +");
328 print_line_count(lc_b);
329 printf(" @@%s\n", reset);
330 if (lc_a)
331 copy_file('-', one->data, one->size, old, reset);
332 if (lc_b)
333 copy_file('+', two->data, two->size, new, reset);
336 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
338 if (!DIFF_FILE_VALID(one)) {
339 mf->ptr = (char *)""; /* does not matter */
340 mf->size = 0;
341 return 0;
343 else if (diff_populate_filespec(one, 0))
344 return -1;
345 mf->ptr = one->data;
346 mf->size = one->size;
347 return 0;
350 struct diff_words_buffer {
351 mmfile_t text;
352 long alloc;
353 long current; /* output pointer */
354 int suppressed_newline;
357 static void diff_words_append(char *line, unsigned long len,
358 struct diff_words_buffer *buffer)
360 if (buffer->text.size + len > buffer->alloc) {
361 buffer->alloc = (buffer->text.size + len) * 3 / 2;
362 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
364 line++;
365 len--;
366 memcpy(buffer->text.ptr + buffer->text.size, line, len);
367 buffer->text.size += len;
370 struct diff_words_data {
371 struct xdiff_emit_state xm;
372 struct diff_words_buffer minus, plus;
375 static void print_word(struct diff_words_buffer *buffer, int len, int color,
376 int suppress_newline)
378 const char *ptr;
379 int eol = 0;
381 if (len == 0)
382 return;
384 ptr = buffer->text.ptr + buffer->current;
385 buffer->current += len;
387 if (ptr[len - 1] == '\n') {
388 eol = 1;
389 len--;
392 fputs(diff_get_color(1, color), stdout);
393 fwrite(ptr, len, 1, stdout);
394 fputs(diff_get_color(1, DIFF_RESET), stdout);
396 if (eol) {
397 if (suppress_newline)
398 buffer->suppressed_newline = 1;
399 else
400 putchar('\n');
404 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
406 struct diff_words_data *diff_words = priv;
408 if (diff_words->minus.suppressed_newline) {
409 if (line[0] != '+')
410 putchar('\n');
411 diff_words->minus.suppressed_newline = 0;
414 len--;
415 switch (line[0]) {
416 case '-':
417 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
418 break;
419 case '+':
420 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
421 break;
422 case ' ':
423 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
424 diff_words->minus.current += len;
425 break;
429 /* this executes the word diff on the accumulated buffers */
430 static void diff_words_show(struct diff_words_data *diff_words)
432 xpparam_t xpp;
433 xdemitconf_t xecfg;
434 xdemitcb_t ecb;
435 mmfile_t minus, plus;
436 int i;
438 memset(&xecfg, 0, sizeof(xecfg));
439 minus.size = diff_words->minus.text.size;
440 minus.ptr = xmalloc(minus.size);
441 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
442 for (i = 0; i < minus.size; i++)
443 if (isspace(minus.ptr[i]))
444 minus.ptr[i] = '\n';
445 diff_words->minus.current = 0;
447 plus.size = diff_words->plus.text.size;
448 plus.ptr = xmalloc(plus.size);
449 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
450 for (i = 0; i < plus.size; i++)
451 if (isspace(plus.ptr[i]))
452 plus.ptr[i] = '\n';
453 diff_words->plus.current = 0;
455 xpp.flags = XDF_NEED_MINIMAL;
456 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
457 ecb.outf = xdiff_outf;
458 ecb.priv = diff_words;
459 diff_words->xm.consume = fn_out_diff_words_aux;
460 xdi_diff(&minus, &plus, &xpp, &xecfg, &ecb);
462 free(minus.ptr);
463 free(plus.ptr);
464 diff_words->minus.text.size = diff_words->plus.text.size = 0;
466 if (diff_words->minus.suppressed_newline) {
467 putchar('\n');
468 diff_words->minus.suppressed_newline = 0;
472 struct emit_callback {
473 struct xdiff_emit_state xm;
474 int nparents, color_diff;
475 unsigned ws_rule;
476 const char **label_path;
477 struct diff_words_data *diff_words;
478 int *found_changesp;
481 static void free_diff_words_data(struct emit_callback *ecbdata)
483 if (ecbdata->diff_words) {
484 /* flush buffers */
485 if (ecbdata->diff_words->minus.text.size ||
486 ecbdata->diff_words->plus.text.size)
487 diff_words_show(ecbdata->diff_words);
489 if (ecbdata->diff_words->minus.text.ptr)
490 free (ecbdata->diff_words->minus.text.ptr);
491 if (ecbdata->diff_words->plus.text.ptr)
492 free (ecbdata->diff_words->plus.text.ptr);
493 free(ecbdata->diff_words);
494 ecbdata->diff_words = NULL;
498 const char *diff_get_color(int diff_use_color, enum color_diff ix)
500 if (diff_use_color)
501 return diff_colors[ix];
502 return "";
505 static void emit_line(const char *set, const char *reset, const char *line, int len)
507 fputs(set, stdout);
508 fwrite(line, len, 1, stdout);
509 fputs(reset, stdout);
512 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
514 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
515 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
517 if (!*ws)
518 emit_line(set, reset, line, len);
519 else {
520 /* Emit just the prefix, then the rest. */
521 emit_line(set, reset, line, ecbdata->nparents);
522 (void)check_and_emit_line(line + ecbdata->nparents,
523 len - ecbdata->nparents, ecbdata->ws_rule,
524 stdout, set, reset, ws);
528 static void fn_out_consume(void *priv, char *line, unsigned long len)
530 int i;
531 int color;
532 struct emit_callback *ecbdata = priv;
533 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
534 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
536 *(ecbdata->found_changesp) = 1;
538 if (ecbdata->label_path[0]) {
539 const char *name_a_tab, *name_b_tab;
541 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
542 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
544 printf("%s--- %s%s%s\n",
545 set, ecbdata->label_path[0], reset, name_a_tab);
546 printf("%s+++ %s%s%s\n",
547 set, ecbdata->label_path[1], reset, name_b_tab);
548 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
551 /* This is not really necessary for now because
552 * this codepath only deals with two-way diffs.
554 for (i = 0; i < len && line[i] == '@'; i++)
556 if (2 <= i && i < len && line[i] == ' ') {
557 ecbdata->nparents = i - 1;
558 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
559 reset, line, len);
560 return;
563 if (len < ecbdata->nparents) {
564 set = reset;
565 emit_line(reset, reset, line, len);
566 return;
569 color = DIFF_PLAIN;
570 if (ecbdata->diff_words && ecbdata->nparents != 1)
571 /* fall back to normal diff */
572 free_diff_words_data(ecbdata);
573 if (ecbdata->diff_words) {
574 if (line[0] == '-') {
575 diff_words_append(line, len,
576 &ecbdata->diff_words->minus);
577 return;
578 } else if (line[0] == '+') {
579 diff_words_append(line, len,
580 &ecbdata->diff_words->plus);
581 return;
583 if (ecbdata->diff_words->minus.text.size ||
584 ecbdata->diff_words->plus.text.size)
585 diff_words_show(ecbdata->diff_words);
586 line++;
587 len--;
588 emit_line(set, reset, line, len);
589 return;
591 for (i = 0; i < ecbdata->nparents && len; i++) {
592 if (line[i] == '-')
593 color = DIFF_FILE_OLD;
594 else if (line[i] == '+')
595 color = DIFF_FILE_NEW;
598 if (color != DIFF_FILE_NEW) {
599 emit_line(diff_get_color(ecbdata->color_diff, color),
600 reset, line, len);
601 return;
603 emit_add_line(reset, ecbdata, line, len);
606 static char *pprint_rename(const char *a, const char *b)
608 const char *old = a;
609 const char *new = b;
610 struct strbuf name;
611 int pfx_length, sfx_length;
612 int len_a = strlen(a);
613 int len_b = strlen(b);
614 int a_midlen, b_midlen;
615 int qlen_a = quote_c_style(a, NULL, NULL, 0);
616 int qlen_b = quote_c_style(b, NULL, NULL, 0);
618 strbuf_init(&name, 0);
619 if (qlen_a || qlen_b) {
620 quote_c_style(a, &name, NULL, 0);
621 strbuf_addstr(&name, " => ");
622 quote_c_style(b, &name, NULL, 0);
623 return strbuf_detach(&name, NULL);
626 /* Find common prefix */
627 pfx_length = 0;
628 while (*old && *new && *old == *new) {
629 if (*old == '/')
630 pfx_length = old - a + 1;
631 old++;
632 new++;
635 /* Find common suffix */
636 old = a + len_a;
637 new = b + len_b;
638 sfx_length = 0;
639 while (a <= old && b <= new && *old == *new) {
640 if (*old == '/')
641 sfx_length = len_a - (old - a);
642 old--;
643 new--;
647 * pfx{mid-a => mid-b}sfx
648 * {pfx-a => pfx-b}sfx
649 * pfx{sfx-a => sfx-b}
650 * name-a => name-b
652 a_midlen = len_a - pfx_length - sfx_length;
653 b_midlen = len_b - pfx_length - sfx_length;
654 if (a_midlen < 0)
655 a_midlen = 0;
656 if (b_midlen < 0)
657 b_midlen = 0;
659 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
660 if (pfx_length + sfx_length) {
661 strbuf_add(&name, a, pfx_length);
662 strbuf_addch(&name, '{');
664 strbuf_add(&name, a + pfx_length, a_midlen);
665 strbuf_addstr(&name, " => ");
666 strbuf_add(&name, b + pfx_length, b_midlen);
667 if (pfx_length + sfx_length) {
668 strbuf_addch(&name, '}');
669 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
671 return strbuf_detach(&name, NULL);
674 struct diffstat_t {
675 struct xdiff_emit_state xm;
677 int nr;
678 int alloc;
679 struct diffstat_file {
680 char *from_name;
681 char *name;
682 char *print_name;
683 unsigned is_unmerged:1;
684 unsigned is_binary:1;
685 unsigned is_renamed:1;
686 unsigned int added, deleted;
687 } **files;
690 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
691 const char *name_a,
692 const char *name_b)
694 struct diffstat_file *x;
695 x = xcalloc(sizeof (*x), 1);
696 if (diffstat->nr == diffstat->alloc) {
697 diffstat->alloc = alloc_nr(diffstat->alloc);
698 diffstat->files = xrealloc(diffstat->files,
699 diffstat->alloc * sizeof(x));
701 diffstat->files[diffstat->nr++] = x;
702 if (name_b) {
703 x->from_name = xstrdup(name_a);
704 x->name = xstrdup(name_b);
705 x->is_renamed = 1;
707 else {
708 x->from_name = NULL;
709 x->name = xstrdup(name_a);
711 return x;
714 static void diffstat_consume(void *priv, char *line, unsigned long len)
716 struct diffstat_t *diffstat = priv;
717 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
719 if (line[0] == '+')
720 x->added++;
721 else if (line[0] == '-')
722 x->deleted++;
725 const char mime_boundary_leader[] = "------------";
727 static int scale_linear(int it, int width, int max_change)
730 * make sure that at least one '-' is printed if there were deletions,
731 * and likewise for '+'.
733 if (max_change < 2)
734 return it;
735 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
738 static void show_name(const char *prefix, const char *name, int len,
739 const char *reset, const char *set)
741 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
744 static void show_graph(char ch, int cnt, const char *set, const char *reset)
746 if (cnt <= 0)
747 return;
748 printf("%s", set);
749 while (cnt--)
750 putchar(ch);
751 printf("%s", reset);
754 static void fill_print_name(struct diffstat_file *file)
756 char *pname;
758 if (file->print_name)
759 return;
761 if (!file->is_renamed) {
762 struct strbuf buf;
763 strbuf_init(&buf, 0);
764 if (quote_c_style(file->name, &buf, NULL, 0)) {
765 pname = strbuf_detach(&buf, NULL);
766 } else {
767 pname = file->name;
768 strbuf_release(&buf);
770 } else {
771 pname = pprint_rename(file->from_name, file->name);
773 file->print_name = pname;
776 static void show_stats(struct diffstat_t* data, struct diff_options *options)
778 int i, len, add, del, total, adds = 0, dels = 0;
779 int max_change = 0, max_len = 0;
780 int total_files = data->nr;
781 int width, name_width;
782 const char *reset, *set, *add_c, *del_c;
784 if (data->nr == 0)
785 return;
787 width = options->stat_width ? options->stat_width : 80;
788 name_width = options->stat_name_width ? options->stat_name_width : 50;
790 /* Sanity: give at least 5 columns to the graph,
791 * but leave at least 10 columns for the name.
793 if (width < name_width + 15) {
794 if (name_width <= 25)
795 width = name_width + 15;
796 else
797 name_width = width - 15;
800 /* Find the longest filename and max number of changes */
801 reset = diff_get_color_opt(options, DIFF_RESET);
802 set = diff_get_color_opt(options, DIFF_PLAIN);
803 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
804 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
806 for (i = 0; i < data->nr; i++) {
807 struct diffstat_file *file = data->files[i];
808 int change = file->added + file->deleted;
809 fill_print_name(file);
810 len = strlen(file->print_name);
811 if (max_len < len)
812 max_len = len;
814 if (file->is_binary || file->is_unmerged)
815 continue;
816 if (max_change < change)
817 max_change = change;
820 /* Compute the width of the graph part;
821 * 10 is for one blank at the beginning of the line plus
822 * " | count " between the name and the graph.
824 * From here on, name_width is the width of the name area,
825 * and width is the width of the graph area.
827 name_width = (name_width < max_len) ? name_width : max_len;
828 if (width < (name_width + 10) + max_change)
829 width = width - (name_width + 10);
830 else
831 width = max_change;
833 for (i = 0; i < data->nr; i++) {
834 const char *prefix = "";
835 char *name = data->files[i]->print_name;
836 int added = data->files[i]->added;
837 int deleted = data->files[i]->deleted;
838 int name_len;
841 * "scale" the filename
843 len = name_width;
844 name_len = strlen(name);
845 if (name_width < name_len) {
846 char *slash;
847 prefix = "...";
848 len -= 3;
849 name += name_len - len;
850 slash = strchr(name, '/');
851 if (slash)
852 name = slash;
855 if (data->files[i]->is_binary) {
856 show_name(prefix, name, len, reset, set);
857 printf(" Bin ");
858 printf("%s%d%s", del_c, deleted, reset);
859 printf(" -> ");
860 printf("%s%d%s", add_c, added, reset);
861 printf(" bytes");
862 printf("\n");
863 continue;
865 else if (data->files[i]->is_unmerged) {
866 show_name(prefix, name, len, reset, set);
867 printf(" Unmerged\n");
868 continue;
870 else if (!data->files[i]->is_renamed &&
871 (added + deleted == 0)) {
872 total_files--;
873 continue;
877 * scale the add/delete
879 add = added;
880 del = deleted;
881 total = add + del;
882 adds += add;
883 dels += del;
885 if (width <= max_change) {
886 add = scale_linear(add, width, max_change);
887 del = scale_linear(del, width, max_change);
888 total = add + del;
890 show_name(prefix, name, len, reset, set);
891 printf("%5d ", added + deleted);
892 show_graph('+', add, add_c, reset);
893 show_graph('-', del, del_c, reset);
894 putchar('\n');
896 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
897 set, total_files, adds, dels, reset);
900 static void show_shortstats(struct diffstat_t* data)
902 int i, adds = 0, dels = 0, total_files = data->nr;
904 if (data->nr == 0)
905 return;
907 for (i = 0; i < data->nr; i++) {
908 if (!data->files[i]->is_binary &&
909 !data->files[i]->is_unmerged) {
910 int added = data->files[i]->added;
911 int deleted= data->files[i]->deleted;
912 if (!data->files[i]->is_renamed &&
913 (added + deleted == 0)) {
914 total_files--;
915 } else {
916 adds += added;
917 dels += deleted;
921 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
922 total_files, adds, dels);
925 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
927 int i;
929 if (data->nr == 0)
930 return;
932 for (i = 0; i < data->nr; i++) {
933 struct diffstat_file *file = data->files[i];
935 if (file->is_binary)
936 printf("-\t-\t");
937 else
938 printf("%d\t%d\t", file->added, file->deleted);
939 if (options->line_termination) {
940 fill_print_name(file);
941 if (!file->is_renamed)
942 write_name_quoted(file->name, stdout,
943 options->line_termination);
944 else {
945 fputs(file->print_name, stdout);
946 putchar(options->line_termination);
948 } else {
949 if (file->is_renamed) {
950 putchar('\0');
951 write_name_quoted(file->from_name, stdout, '\0');
953 write_name_quoted(file->name, stdout, '\0');
958 static void free_diffstat_info(struct diffstat_t *diffstat)
960 int i;
961 for (i = 0; i < diffstat->nr; i++) {
962 struct diffstat_file *f = diffstat->files[i];
963 if (f->name != f->print_name)
964 free(f->print_name);
965 free(f->name);
966 free(f->from_name);
967 free(f);
969 free(diffstat->files);
972 struct checkdiff_t {
973 struct xdiff_emit_state xm;
974 const char *filename;
975 int lineno, color_diff;
976 unsigned ws_rule;
977 unsigned status;
980 static void checkdiff_consume(void *priv, char *line, unsigned long len)
982 struct checkdiff_t *data = priv;
983 const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
984 const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
985 const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
986 char *err;
988 if (line[0] == '+') {
989 data->status = check_and_emit_line(line + 1, len - 1,
990 data->ws_rule, NULL, NULL, NULL, NULL);
991 if (!data->status)
992 return;
993 err = whitespace_error_string(data->status);
994 printf("%s:%d: %s.\n", data->filename, data->lineno, err);
995 free(err);
996 emit_line(set, reset, line, 1);
997 (void)check_and_emit_line(line + 1, len - 1, data->ws_rule,
998 stdout, set, reset, ws);
999 data->lineno++;
1000 } else if (line[0] == ' ')
1001 data->lineno++;
1002 else if (line[0] == '@') {
1003 char *plus = strchr(line, '+');
1004 if (plus)
1005 data->lineno = strtol(plus, NULL, 10);
1006 else
1007 die("invalid diff");
1011 static unsigned char *deflate_it(char *data,
1012 unsigned long size,
1013 unsigned long *result_size)
1015 int bound;
1016 unsigned char *deflated;
1017 z_stream stream;
1019 memset(&stream, 0, sizeof(stream));
1020 deflateInit(&stream, zlib_compression_level);
1021 bound = deflateBound(&stream, size);
1022 deflated = xmalloc(bound);
1023 stream.next_out = deflated;
1024 stream.avail_out = bound;
1026 stream.next_in = (unsigned char *)data;
1027 stream.avail_in = size;
1028 while (deflate(&stream, Z_FINISH) == Z_OK)
1029 ; /* nothing */
1030 deflateEnd(&stream);
1031 *result_size = stream.total_out;
1032 return deflated;
1035 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
1037 void *cp;
1038 void *delta;
1039 void *deflated;
1040 void *data;
1041 unsigned long orig_size;
1042 unsigned long delta_size;
1043 unsigned long deflate_size;
1044 unsigned long data_size;
1046 /* We could do deflated delta, or we could do just deflated two,
1047 * whichever is smaller.
1049 delta = NULL;
1050 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1051 if (one->size && two->size) {
1052 delta = diff_delta(one->ptr, one->size,
1053 two->ptr, two->size,
1054 &delta_size, deflate_size);
1055 if (delta) {
1056 void *to_free = delta;
1057 orig_size = delta_size;
1058 delta = deflate_it(delta, delta_size, &delta_size);
1059 free(to_free);
1063 if (delta && delta_size < deflate_size) {
1064 printf("delta %lu\n", orig_size);
1065 free(deflated);
1066 data = delta;
1067 data_size = delta_size;
1069 else {
1070 printf("literal %lu\n", two->size);
1071 free(delta);
1072 data = deflated;
1073 data_size = deflate_size;
1076 /* emit data encoded in base85 */
1077 cp = data;
1078 while (data_size) {
1079 int bytes = (52 < data_size) ? 52 : data_size;
1080 char line[70];
1081 data_size -= bytes;
1082 if (bytes <= 26)
1083 line[0] = bytes + 'A' - 1;
1084 else
1085 line[0] = bytes - 26 + 'a' - 1;
1086 encode_85(line + 1, cp, bytes);
1087 cp = (char *) cp + bytes;
1088 puts(line);
1090 printf("\n");
1091 free(data);
1094 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1096 printf("GIT binary patch\n");
1097 emit_binary_diff_body(one, two);
1098 emit_binary_diff_body(two, one);
1101 static void setup_diff_attr_check(struct git_attr_check *check)
1103 static struct git_attr *attr_diff;
1105 if (!attr_diff) {
1106 attr_diff = git_attr("diff", 4);
1108 check[0].attr = attr_diff;
1111 static void diff_filespec_check_attr(struct diff_filespec *one)
1113 struct git_attr_check attr_diff_check;
1114 int check_from_data = 0;
1116 if (one->checked_attr)
1117 return;
1119 setup_diff_attr_check(&attr_diff_check);
1120 one->is_binary = 0;
1121 one->funcname_pattern_ident = NULL;
1123 if (!git_checkattr(one->path, 1, &attr_diff_check)) {
1124 const char *value;
1126 /* binaryness */
1127 value = attr_diff_check.value;
1128 if (ATTR_TRUE(value))
1130 else if (ATTR_FALSE(value))
1131 one->is_binary = 1;
1132 else
1133 check_from_data = 1;
1135 /* funcname pattern ident */
1136 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1138 else
1139 one->funcname_pattern_ident = value;
1142 if (check_from_data) {
1143 if (!one->data && DIFF_FILE_VALID(one))
1144 diff_populate_filespec(one, 0);
1146 if (one->data)
1147 one->is_binary = buffer_is_binary(one->data, one->size);
1151 int diff_filespec_is_binary(struct diff_filespec *one)
1153 diff_filespec_check_attr(one);
1154 return one->is_binary;
1157 static const char *funcname_pattern(const char *ident)
1159 struct funcname_pattern *pp;
1161 for (pp = funcname_pattern_list; pp; pp = pp->next)
1162 if (!strcmp(ident, pp->name))
1163 return pp->pattern;
1164 return NULL;
1167 static struct builtin_funcname_pattern {
1168 const char *name;
1169 const char *pattern;
1170 } builtin_funcname_pattern[] = {
1171 { "java", "!^[ ]*\\(catch\\|do\\|for\\|if\\|instanceof\\|"
1172 "new\\|return\\|switch\\|throw\\|while\\)\n"
1173 "^[ ]*\\(\\([ ]*"
1174 "[A-Za-z_][A-Za-z_0-9]*\\)\\{2,\\}"
1175 "[ ]*([^;]*$\\)" },
1176 { "tex", "^\\(\\\\\\(sub\\)*section{.*\\)$" },
1179 static const char *diff_funcname_pattern(struct diff_filespec *one)
1181 const char *ident, *pattern;
1182 int i;
1184 diff_filespec_check_attr(one);
1185 ident = one->funcname_pattern_ident;
1187 if (!ident)
1189 * If the config file has "funcname.default" defined, that
1190 * regexp is used; otherwise NULL is returned and xemit uses
1191 * the built-in default.
1193 return funcname_pattern("default");
1195 /* Look up custom "funcname.$ident" regexp from config. */
1196 pattern = funcname_pattern(ident);
1197 if (pattern)
1198 return pattern;
1201 * And define built-in fallback patterns here. Note that
1202 * these can be overriden by the user's config settings.
1204 for (i = 0; i < ARRAY_SIZE(builtin_funcname_pattern); i++)
1205 if (!strcmp(ident, builtin_funcname_pattern[i].name))
1206 return builtin_funcname_pattern[i].pattern;
1208 return NULL;
1211 static void builtin_diff(const char *name_a,
1212 const char *name_b,
1213 struct diff_filespec *one,
1214 struct diff_filespec *two,
1215 const char *xfrm_msg,
1216 struct diff_options *o,
1217 int complete_rewrite)
1219 mmfile_t mf1, mf2;
1220 const char *lbl[2];
1221 char *a_one, *b_two;
1222 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1223 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1225 a_one = quote_two(o->a_prefix, name_a + (*name_a == '/'));
1226 b_two = quote_two(o->b_prefix, name_b + (*name_b == '/'));
1227 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1228 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1229 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1230 if (lbl[0][0] == '/') {
1231 /* /dev/null */
1232 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1233 if (xfrm_msg && xfrm_msg[0])
1234 printf("%s%s%s\n", set, xfrm_msg, reset);
1236 else if (lbl[1][0] == '/') {
1237 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1238 if (xfrm_msg && xfrm_msg[0])
1239 printf("%s%s%s\n", set, xfrm_msg, reset);
1241 else {
1242 if (one->mode != two->mode) {
1243 printf("%sold mode %06o%s\n", set, one->mode, reset);
1244 printf("%snew mode %06o%s\n", set, two->mode, reset);
1246 if (xfrm_msg && xfrm_msg[0])
1247 printf("%s%s%s\n", set, xfrm_msg, reset);
1249 * we do not run diff between different kind
1250 * of objects.
1252 if ((one->mode ^ two->mode) & S_IFMT)
1253 goto free_ab_and_return;
1254 if (complete_rewrite) {
1255 emit_rewrite_diff(name_a, name_b, one, two, o);
1256 o->found_changes = 1;
1257 goto free_ab_and_return;
1261 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1262 die("unable to read files to diff");
1264 if (!DIFF_OPT_TST(o, TEXT) &&
1265 (diff_filespec_is_binary(one) || diff_filespec_is_binary(two))) {
1266 /* Quite common confusing case */
1267 if (mf1.size == mf2.size &&
1268 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1269 goto free_ab_and_return;
1270 if (DIFF_OPT_TST(o, BINARY))
1271 emit_binary_diff(&mf1, &mf2);
1272 else
1273 printf("Binary files %s and %s differ\n",
1274 lbl[0], lbl[1]);
1275 o->found_changes = 1;
1277 else {
1278 /* Crazy xdl interfaces.. */
1279 const char *diffopts = getenv("GIT_DIFF_OPTS");
1280 xpparam_t xpp;
1281 xdemitconf_t xecfg;
1282 xdemitcb_t ecb;
1283 struct emit_callback ecbdata;
1284 const char *funcname_pattern;
1286 funcname_pattern = diff_funcname_pattern(one);
1287 if (!funcname_pattern)
1288 funcname_pattern = diff_funcname_pattern(two);
1290 memset(&xecfg, 0, sizeof(xecfg));
1291 memset(&ecbdata, 0, sizeof(ecbdata));
1292 ecbdata.label_path = lbl;
1293 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1294 ecbdata.found_changesp = &o->found_changes;
1295 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1296 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1297 xecfg.ctxlen = o->context;
1298 xecfg.flags = XDL_EMIT_FUNCNAMES;
1299 if (funcname_pattern)
1300 xdiff_set_find_func(&xecfg, funcname_pattern);
1301 if (!diffopts)
1303 else if (!prefixcmp(diffopts, "--unified="))
1304 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1305 else if (!prefixcmp(diffopts, "-u"))
1306 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1307 ecb.outf = xdiff_outf;
1308 ecb.priv = &ecbdata;
1309 ecbdata.xm.consume = fn_out_consume;
1310 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1311 ecbdata.diff_words =
1312 xcalloc(1, sizeof(struct diff_words_data));
1313 xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1314 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1315 free_diff_words_data(&ecbdata);
1318 free_ab_and_return:
1319 diff_free_filespec_data(one);
1320 diff_free_filespec_data(two);
1321 free(a_one);
1322 free(b_two);
1323 return;
1326 static void builtin_diffstat(const char *name_a, const char *name_b,
1327 struct diff_filespec *one,
1328 struct diff_filespec *two,
1329 struct diffstat_t *diffstat,
1330 struct diff_options *o,
1331 int complete_rewrite)
1333 mmfile_t mf1, mf2;
1334 struct diffstat_file *data;
1336 data = diffstat_add(diffstat, name_a, name_b);
1338 if (!one || !two) {
1339 data->is_unmerged = 1;
1340 return;
1342 if (complete_rewrite) {
1343 diff_populate_filespec(one, 0);
1344 diff_populate_filespec(two, 0);
1345 data->deleted = count_lines(one->data, one->size);
1346 data->added = count_lines(two->data, two->size);
1347 goto free_and_return;
1349 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1350 die("unable to read files to diff");
1352 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1353 data->is_binary = 1;
1354 data->added = mf2.size;
1355 data->deleted = mf1.size;
1356 } else {
1357 /* Crazy xdl interfaces.. */
1358 xpparam_t xpp;
1359 xdemitconf_t xecfg;
1360 xdemitcb_t ecb;
1362 memset(&xecfg, 0, sizeof(xecfg));
1363 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1364 ecb.outf = xdiff_outf;
1365 ecb.priv = diffstat;
1366 xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1369 free_and_return:
1370 diff_free_filespec_data(one);
1371 diff_free_filespec_data(two);
1374 static void builtin_checkdiff(const char *name_a, const char *name_b,
1375 struct diff_filespec *one,
1376 struct diff_filespec *two, struct diff_options *o)
1378 mmfile_t mf1, mf2;
1379 struct checkdiff_t data;
1381 if (!two)
1382 return;
1384 memset(&data, 0, sizeof(data));
1385 data.xm.consume = checkdiff_consume;
1386 data.filename = name_b ? name_b : name_a;
1387 data.lineno = 0;
1388 data.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1389 data.ws_rule = whitespace_rule(data.filename);
1391 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1392 die("unable to read files to diff");
1394 if (diff_filespec_is_binary(two))
1395 goto free_and_return;
1396 else {
1397 /* Crazy xdl interfaces.. */
1398 xpparam_t xpp;
1399 xdemitconf_t xecfg;
1400 xdemitcb_t ecb;
1402 memset(&xecfg, 0, sizeof(xecfg));
1403 xpp.flags = XDF_NEED_MINIMAL;
1404 ecb.outf = xdiff_outf;
1405 ecb.priv = &data;
1406 xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1408 free_and_return:
1409 diff_free_filespec_data(one);
1410 diff_free_filespec_data(two);
1411 if (data.status)
1412 DIFF_OPT_SET(o, CHECK_FAILED);
1415 struct diff_filespec *alloc_filespec(const char *path)
1417 int namelen = strlen(path);
1418 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1420 memset(spec, 0, sizeof(*spec));
1421 spec->path = (char *)(spec + 1);
1422 memcpy(spec->path, path, namelen+1);
1423 spec->count = 1;
1424 return spec;
1427 void free_filespec(struct diff_filespec *spec)
1429 if (!--spec->count) {
1430 diff_free_filespec_data(spec);
1431 free(spec);
1435 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1436 unsigned short mode)
1438 if (mode) {
1439 spec->mode = canon_mode(mode);
1440 hashcpy(spec->sha1, sha1);
1441 spec->sha1_valid = !is_null_sha1(sha1);
1446 * Given a name and sha1 pair, if the index tells us the file in
1447 * the work tree has that object contents, return true, so that
1448 * prepare_temp_file() does not have to inflate and extract.
1450 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1452 struct cache_entry *ce;
1453 struct stat st;
1454 int pos, len;
1456 /* We do not read the cache ourselves here, because the
1457 * benchmark with my previous version that always reads cache
1458 * shows that it makes things worse for diff-tree comparing
1459 * two linux-2.6 kernel trees in an already checked out work
1460 * tree. This is because most diff-tree comparisons deal with
1461 * only a small number of files, while reading the cache is
1462 * expensive for a large project, and its cost outweighs the
1463 * savings we get by not inflating the object to a temporary
1464 * file. Practically, this code only helps when we are used
1465 * by diff-cache --cached, which does read the cache before
1466 * calling us.
1468 if (!active_cache)
1469 return 0;
1471 /* We want to avoid the working directory if our caller
1472 * doesn't need the data in a normal file, this system
1473 * is rather slow with its stat/open/mmap/close syscalls,
1474 * and the object is contained in a pack file. The pack
1475 * is probably already open and will be faster to obtain
1476 * the data through than the working directory. Loose
1477 * objects however would tend to be slower as they need
1478 * to be individually opened and inflated.
1480 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1481 return 0;
1483 len = strlen(name);
1484 pos = cache_name_pos(name, len);
1485 if (pos < 0)
1486 return 0;
1487 ce = active_cache[pos];
1488 if ((lstat(name, &st) < 0) ||
1489 !S_ISREG(st.st_mode) || /* careful! */
1490 ce_match_stat(ce, &st, 0) ||
1491 hashcmp(sha1, ce->sha1))
1492 return 0;
1493 /* we return 1 only when we can stat, it is a regular file,
1494 * stat information matches, and sha1 recorded in the cache
1495 * matches. I.e. we know the file in the work tree really is
1496 * the same as the <name, sha1> pair.
1498 return 1;
1501 static int populate_from_stdin(struct diff_filespec *s)
1503 struct strbuf buf;
1504 size_t size = 0;
1506 strbuf_init(&buf, 0);
1507 if (strbuf_read(&buf, 0, 0) < 0)
1508 return error("error while reading from stdin %s",
1509 strerror(errno));
1511 s->should_munmap = 0;
1512 s->data = strbuf_detach(&buf, &size);
1513 s->size = size;
1514 s->should_free = 1;
1515 return 0;
1518 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1520 int len;
1521 char *data = xmalloc(100);
1522 len = snprintf(data, 100,
1523 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1524 s->data = data;
1525 s->size = len;
1526 s->should_free = 1;
1527 if (size_only) {
1528 s->data = NULL;
1529 free(data);
1531 return 0;
1535 * While doing rename detection and pickaxe operation, we may need to
1536 * grab the data for the blob (or file) for our own in-core comparison.
1537 * diff_filespec has data and size fields for this purpose.
1539 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1541 int err = 0;
1542 if (!DIFF_FILE_VALID(s))
1543 die("internal error: asking to populate invalid file.");
1544 if (S_ISDIR(s->mode))
1545 return -1;
1547 if (s->data)
1548 return 0;
1550 if (size_only && 0 < s->size)
1551 return 0;
1553 if (S_ISGITLINK(s->mode))
1554 return diff_populate_gitlink(s, size_only);
1556 if (!s->sha1_valid ||
1557 reuse_worktree_file(s->path, s->sha1, 0)) {
1558 struct strbuf buf;
1559 struct stat st;
1560 int fd;
1562 if (!strcmp(s->path, "-"))
1563 return populate_from_stdin(s);
1565 if (lstat(s->path, &st) < 0) {
1566 if (errno == ENOENT) {
1567 err_empty:
1568 err = -1;
1569 empty:
1570 s->data = (char *)"";
1571 s->size = 0;
1572 return err;
1575 s->size = xsize_t(st.st_size);
1576 if (!s->size)
1577 goto empty;
1578 if (size_only)
1579 return 0;
1580 if (S_ISLNK(st.st_mode)) {
1581 int ret;
1582 s->data = xmalloc(s->size);
1583 s->should_free = 1;
1584 ret = readlink(s->path, s->data, s->size);
1585 if (ret < 0) {
1586 free(s->data);
1587 goto err_empty;
1589 return 0;
1591 fd = open(s->path, O_RDONLY);
1592 if (fd < 0)
1593 goto err_empty;
1594 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1595 close(fd);
1596 s->should_munmap = 1;
1599 * Convert from working tree format to canonical git format
1601 strbuf_init(&buf, 0);
1602 if (convert_to_git(s->path, s->data, s->size, &buf)) {
1603 size_t size = 0;
1604 munmap(s->data, s->size);
1605 s->should_munmap = 0;
1606 s->data = strbuf_detach(&buf, &size);
1607 s->size = size;
1608 s->should_free = 1;
1611 else {
1612 enum object_type type;
1613 if (size_only)
1614 type = sha1_object_info(s->sha1, &s->size);
1615 else {
1616 s->data = read_sha1_file(s->sha1, &type, &s->size);
1617 s->should_free = 1;
1620 return 0;
1623 void diff_free_filespec_blob(struct diff_filespec *s)
1625 if (s->should_free)
1626 free(s->data);
1627 else if (s->should_munmap)
1628 munmap(s->data, s->size);
1630 if (s->should_free || s->should_munmap) {
1631 s->should_free = s->should_munmap = 0;
1632 s->data = NULL;
1636 void diff_free_filespec_data(struct diff_filespec *s)
1638 diff_free_filespec_blob(s);
1639 free(s->cnt_data);
1640 s->cnt_data = NULL;
1643 static void prep_temp_blob(struct diff_tempfile *temp,
1644 void *blob,
1645 unsigned long size,
1646 const unsigned char *sha1,
1647 int mode)
1649 int fd;
1651 fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1652 if (fd < 0)
1653 die("unable to create temp-file: %s", strerror(errno));
1654 if (write_in_full(fd, blob, size) != size)
1655 die("unable to write temp-file");
1656 close(fd);
1657 temp->name = temp->tmp_path;
1658 strcpy(temp->hex, sha1_to_hex(sha1));
1659 temp->hex[40] = 0;
1660 sprintf(temp->mode, "%06o", mode);
1663 static void prepare_temp_file(const char *name,
1664 struct diff_tempfile *temp,
1665 struct diff_filespec *one)
1667 if (!DIFF_FILE_VALID(one)) {
1668 not_a_valid_file:
1669 /* A '-' entry produces this for file-2, and
1670 * a '+' entry produces this for file-1.
1672 temp->name = "/dev/null";
1673 strcpy(temp->hex, ".");
1674 strcpy(temp->mode, ".");
1675 return;
1678 if (!one->sha1_valid ||
1679 reuse_worktree_file(name, one->sha1, 1)) {
1680 struct stat st;
1681 if (lstat(name, &st) < 0) {
1682 if (errno == ENOENT)
1683 goto not_a_valid_file;
1684 die("stat(%s): %s", name, strerror(errno));
1686 if (S_ISLNK(st.st_mode)) {
1687 int ret;
1688 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1689 size_t sz = xsize_t(st.st_size);
1690 if (sizeof(buf) <= st.st_size)
1691 die("symlink too long: %s", name);
1692 ret = readlink(name, buf, sz);
1693 if (ret < 0)
1694 die("readlink(%s)", name);
1695 prep_temp_blob(temp, buf, sz,
1696 (one->sha1_valid ?
1697 one->sha1 : null_sha1),
1698 (one->sha1_valid ?
1699 one->mode : S_IFLNK));
1701 else {
1702 /* we can borrow from the file in the work tree */
1703 temp->name = name;
1704 if (!one->sha1_valid)
1705 strcpy(temp->hex, sha1_to_hex(null_sha1));
1706 else
1707 strcpy(temp->hex, sha1_to_hex(one->sha1));
1708 /* Even though we may sometimes borrow the
1709 * contents from the work tree, we always want
1710 * one->mode. mode is trustworthy even when
1711 * !(one->sha1_valid), as long as
1712 * DIFF_FILE_VALID(one).
1714 sprintf(temp->mode, "%06o", one->mode);
1716 return;
1718 else {
1719 if (diff_populate_filespec(one, 0))
1720 die("cannot read data blob for %s", one->path);
1721 prep_temp_blob(temp, one->data, one->size,
1722 one->sha1, one->mode);
1726 static void remove_tempfile(void)
1728 int i;
1730 for (i = 0; i < 2; i++)
1731 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1732 unlink(diff_temp[i].name);
1733 diff_temp[i].name = NULL;
1737 static void remove_tempfile_on_signal(int signo)
1739 remove_tempfile();
1740 signal(SIGINT, SIG_DFL);
1741 raise(signo);
1744 /* An external diff command takes:
1746 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1747 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1750 static void run_external_diff(const char *pgm,
1751 const char *name,
1752 const char *other,
1753 struct diff_filespec *one,
1754 struct diff_filespec *two,
1755 const char *xfrm_msg,
1756 int complete_rewrite)
1758 const char *spawn_arg[10];
1759 struct diff_tempfile *temp = diff_temp;
1760 int retval;
1761 static int atexit_asked = 0;
1762 const char *othername;
1763 const char **arg = &spawn_arg[0];
1765 othername = (other? other : name);
1766 if (one && two) {
1767 prepare_temp_file(name, &temp[0], one);
1768 prepare_temp_file(othername, &temp[1], two);
1769 if (! atexit_asked &&
1770 (temp[0].name == temp[0].tmp_path ||
1771 temp[1].name == temp[1].tmp_path)) {
1772 atexit_asked = 1;
1773 atexit(remove_tempfile);
1775 signal(SIGINT, remove_tempfile_on_signal);
1778 if (one && two) {
1779 *arg++ = pgm;
1780 *arg++ = name;
1781 *arg++ = temp[0].name;
1782 *arg++ = temp[0].hex;
1783 *arg++ = temp[0].mode;
1784 *arg++ = temp[1].name;
1785 *arg++ = temp[1].hex;
1786 *arg++ = temp[1].mode;
1787 if (other) {
1788 *arg++ = other;
1789 *arg++ = xfrm_msg;
1791 } else {
1792 *arg++ = pgm;
1793 *arg++ = name;
1795 *arg = NULL;
1796 fflush(NULL);
1797 retval = run_command_v_opt(spawn_arg, 0);
1798 remove_tempfile();
1799 if (retval) {
1800 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1801 exit(1);
1805 static const char *external_diff_attr(const char *name)
1807 struct git_attr_check attr_diff_check;
1809 setup_diff_attr_check(&attr_diff_check);
1810 if (!git_checkattr(name, 1, &attr_diff_check)) {
1811 const char *value = attr_diff_check.value;
1812 if (!ATTR_TRUE(value) &&
1813 !ATTR_FALSE(value) &&
1814 !ATTR_UNSET(value)) {
1815 struct ll_diff_driver *drv;
1817 for (drv = user_diff; drv; drv = drv->next)
1818 if (!strcmp(drv->name, value))
1819 return drv->cmd;
1822 return NULL;
1825 static void run_diff_cmd(const char *pgm,
1826 const char *name,
1827 const char *other,
1828 struct diff_filespec *one,
1829 struct diff_filespec *two,
1830 const char *xfrm_msg,
1831 struct diff_options *o,
1832 int complete_rewrite)
1834 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
1835 pgm = NULL;
1836 else {
1837 const char *cmd = external_diff_attr(name);
1838 if (cmd)
1839 pgm = cmd;
1842 if (pgm) {
1843 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1844 complete_rewrite);
1845 return;
1847 if (one && two)
1848 builtin_diff(name, other ? other : name,
1849 one, two, xfrm_msg, o, complete_rewrite);
1850 else
1851 printf("* Unmerged path %s\n", name);
1854 static void diff_fill_sha1_info(struct diff_filespec *one)
1856 if (DIFF_FILE_VALID(one)) {
1857 if (!one->sha1_valid) {
1858 struct stat st;
1859 if (!strcmp(one->path, "-")) {
1860 hashcpy(one->sha1, null_sha1);
1861 return;
1863 if (lstat(one->path, &st) < 0)
1864 die("stat %s", one->path);
1865 if (index_path(one->sha1, one->path, &st, 0))
1866 die("cannot hash %s\n", one->path);
1869 else
1870 hashclr(one->sha1);
1873 static int similarity_index(struct diff_filepair *p)
1875 return p->score * 100 / MAX_SCORE;
1878 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1880 const char *pgm = external_diff();
1881 struct strbuf msg;
1882 char *xfrm_msg;
1883 struct diff_filespec *one = p->one;
1884 struct diff_filespec *two = p->two;
1885 const char *name;
1886 const char *other;
1887 int complete_rewrite = 0;
1890 if (DIFF_PAIR_UNMERGED(p)) {
1891 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1892 return;
1895 name = p->one->path;
1896 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1897 diff_fill_sha1_info(one);
1898 diff_fill_sha1_info(two);
1900 strbuf_init(&msg, PATH_MAX * 2 + 300);
1901 switch (p->status) {
1902 case DIFF_STATUS_COPIED:
1903 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
1904 strbuf_addstr(&msg, "\ncopy from ");
1905 quote_c_style(name, &msg, NULL, 0);
1906 strbuf_addstr(&msg, "\ncopy to ");
1907 quote_c_style(other, &msg, NULL, 0);
1908 strbuf_addch(&msg, '\n');
1909 break;
1910 case DIFF_STATUS_RENAMED:
1911 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
1912 strbuf_addstr(&msg, "\nrename from ");
1913 quote_c_style(name, &msg, NULL, 0);
1914 strbuf_addstr(&msg, "\nrename to ");
1915 quote_c_style(other, &msg, NULL, 0);
1916 strbuf_addch(&msg, '\n');
1917 break;
1918 case DIFF_STATUS_MODIFIED:
1919 if (p->score) {
1920 strbuf_addf(&msg, "dissimilarity index %d%%\n",
1921 similarity_index(p));
1922 complete_rewrite = 1;
1923 break;
1925 /* fallthru */
1926 default:
1927 /* nothing */
1931 if (hashcmp(one->sha1, two->sha1)) {
1932 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
1934 if (DIFF_OPT_TST(o, BINARY)) {
1935 mmfile_t mf;
1936 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
1937 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
1938 abbrev = 40;
1940 strbuf_addf(&msg, "index %.*s..%.*s",
1941 abbrev, sha1_to_hex(one->sha1),
1942 abbrev, sha1_to_hex(two->sha1));
1943 if (one->mode == two->mode)
1944 strbuf_addf(&msg, " %06o", one->mode);
1945 strbuf_addch(&msg, '\n');
1948 if (msg.len)
1949 strbuf_setlen(&msg, msg.len - 1);
1950 xfrm_msg = msg.len ? msg.buf : NULL;
1952 if (!pgm &&
1953 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1954 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1955 /* a filepair that changes between file and symlink
1956 * needs to be split into deletion and creation.
1958 struct diff_filespec *null = alloc_filespec(two->path);
1959 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1960 free(null);
1961 null = alloc_filespec(one->path);
1962 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1963 free(null);
1965 else
1966 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1967 complete_rewrite);
1969 strbuf_release(&msg);
1972 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1973 struct diffstat_t *diffstat)
1975 const char *name;
1976 const char *other;
1977 int complete_rewrite = 0;
1979 if (DIFF_PAIR_UNMERGED(p)) {
1980 /* unmerged */
1981 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1982 return;
1985 name = p->one->path;
1986 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1988 diff_fill_sha1_info(p->one);
1989 diff_fill_sha1_info(p->two);
1991 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1992 complete_rewrite = 1;
1993 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1996 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1998 const char *name;
1999 const char *other;
2001 if (DIFF_PAIR_UNMERGED(p)) {
2002 /* unmerged */
2003 return;
2006 name = p->one->path;
2007 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2009 diff_fill_sha1_info(p->one);
2010 diff_fill_sha1_info(p->two);
2012 builtin_checkdiff(name, other, p->one, p->two, o);
2015 void diff_setup(struct diff_options *options)
2017 memset(options, 0, sizeof(*options));
2018 options->line_termination = '\n';
2019 options->break_opt = -1;
2020 options->rename_limit = -1;
2021 options->context = 3;
2022 options->msg_sep = "";
2024 options->change = diff_change;
2025 options->add_remove = diff_addremove;
2026 if (diff_use_color_default)
2027 DIFF_OPT_SET(options, COLOR_DIFF);
2028 else
2029 DIFF_OPT_CLR(options, COLOR_DIFF);
2030 options->detect_rename = diff_detect_rename_default;
2032 options->a_prefix = "a/";
2033 options->b_prefix = "b/";
2036 int diff_setup_done(struct diff_options *options)
2038 int count = 0;
2040 if (options->output_format & DIFF_FORMAT_NAME)
2041 count++;
2042 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2043 count++;
2044 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2045 count++;
2046 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2047 count++;
2048 if (count > 1)
2049 die("--name-only, --name-status, --check and -s are mutually exclusive");
2051 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2052 options->detect_rename = DIFF_DETECT_COPY;
2054 if (options->output_format & (DIFF_FORMAT_NAME |
2055 DIFF_FORMAT_NAME_STATUS |
2056 DIFF_FORMAT_CHECKDIFF |
2057 DIFF_FORMAT_NO_OUTPUT))
2058 options->output_format &= ~(DIFF_FORMAT_RAW |
2059 DIFF_FORMAT_NUMSTAT |
2060 DIFF_FORMAT_DIFFSTAT |
2061 DIFF_FORMAT_SHORTSTAT |
2062 DIFF_FORMAT_SUMMARY |
2063 DIFF_FORMAT_PATCH);
2066 * These cases always need recursive; we do not drop caller-supplied
2067 * recursive bits for other formats here.
2069 if (options->output_format & (DIFF_FORMAT_PATCH |
2070 DIFF_FORMAT_NUMSTAT |
2071 DIFF_FORMAT_DIFFSTAT |
2072 DIFF_FORMAT_SHORTSTAT |
2073 DIFF_FORMAT_SUMMARY |
2074 DIFF_FORMAT_CHECKDIFF))
2075 DIFF_OPT_SET(options, RECURSIVE);
2077 * Also pickaxe would not work very well if you do not say recursive
2079 if (options->pickaxe)
2080 DIFF_OPT_SET(options, RECURSIVE);
2082 if (options->detect_rename && options->rename_limit < 0)
2083 options->rename_limit = diff_rename_limit_default;
2084 if (options->setup & DIFF_SETUP_USE_CACHE) {
2085 if (!active_cache)
2086 /* read-cache does not die even when it fails
2087 * so it is safe for us to do this here. Also
2088 * it does not smudge active_cache or active_nr
2089 * when it fails, so we do not have to worry about
2090 * cleaning it up ourselves either.
2092 read_cache();
2094 if (options->abbrev <= 0 || 40 < options->abbrev)
2095 options->abbrev = 40; /* full */
2098 * It does not make sense to show the first hit we happened
2099 * to have found. It does not make sense not to return with
2100 * exit code in such a case either.
2102 if (DIFF_OPT_TST(options, QUIET)) {
2103 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2104 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2108 * If we postprocess in diffcore, we cannot simply return
2109 * upon the first hit. We need to run diff as usual.
2111 if (options->pickaxe || options->filter)
2112 DIFF_OPT_CLR(options, QUIET);
2114 return 0;
2117 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2119 char c, *eq;
2120 int len;
2122 if (*arg != '-')
2123 return 0;
2124 c = *++arg;
2125 if (!c)
2126 return 0;
2127 if (c == arg_short) {
2128 c = *++arg;
2129 if (!c)
2130 return 1;
2131 if (val && isdigit(c)) {
2132 char *end;
2133 int n = strtoul(arg, &end, 10);
2134 if (*end)
2135 return 0;
2136 *val = n;
2137 return 1;
2139 return 0;
2141 if (c != '-')
2142 return 0;
2143 arg++;
2144 eq = strchr(arg, '=');
2145 if (eq)
2146 len = eq - arg;
2147 else
2148 len = strlen(arg);
2149 if (!len || strncmp(arg, arg_long, len))
2150 return 0;
2151 if (eq) {
2152 int n;
2153 char *end;
2154 if (!isdigit(*++eq))
2155 return 0;
2156 n = strtoul(eq, &end, 10);
2157 if (*end)
2158 return 0;
2159 *val = n;
2161 return 1;
2164 static int diff_scoreopt_parse(const char *opt);
2166 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2168 const char *arg = av[0];
2170 /* Output format options */
2171 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2172 options->output_format |= DIFF_FORMAT_PATCH;
2173 else if (opt_arg(arg, 'U', "unified", &options->context))
2174 options->output_format |= DIFF_FORMAT_PATCH;
2175 else if (!strcmp(arg, "--raw"))
2176 options->output_format |= DIFF_FORMAT_RAW;
2177 else if (!strcmp(arg, "--patch-with-raw"))
2178 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2179 else if (!strcmp(arg, "--numstat"))
2180 options->output_format |= DIFF_FORMAT_NUMSTAT;
2181 else if (!strcmp(arg, "--shortstat"))
2182 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2183 else if (!strcmp(arg, "--check"))
2184 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2185 else if (!strcmp(arg, "--summary"))
2186 options->output_format |= DIFF_FORMAT_SUMMARY;
2187 else if (!strcmp(arg, "--patch-with-stat"))
2188 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2189 else if (!strcmp(arg, "--name-only"))
2190 options->output_format |= DIFF_FORMAT_NAME;
2191 else if (!strcmp(arg, "--name-status"))
2192 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2193 else if (!strcmp(arg, "-s"))
2194 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2195 else if (!prefixcmp(arg, "--stat")) {
2196 char *end;
2197 int width = options->stat_width;
2198 int name_width = options->stat_name_width;
2199 arg += 6;
2200 end = (char *)arg;
2202 switch (*arg) {
2203 case '-':
2204 if (!prefixcmp(arg, "-width="))
2205 width = strtoul(arg + 7, &end, 10);
2206 else if (!prefixcmp(arg, "-name-width="))
2207 name_width = strtoul(arg + 12, &end, 10);
2208 break;
2209 case '=':
2210 width = strtoul(arg+1, &end, 10);
2211 if (*end == ',')
2212 name_width = strtoul(end+1, &end, 10);
2215 /* Important! This checks all the error cases! */
2216 if (*end)
2217 return 0;
2218 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2219 options->stat_name_width = name_width;
2220 options->stat_width = width;
2223 /* renames options */
2224 else if (!prefixcmp(arg, "-B")) {
2225 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2226 return -1;
2228 else if (!prefixcmp(arg, "-M")) {
2229 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2230 return -1;
2231 options->detect_rename = DIFF_DETECT_RENAME;
2233 else if (!prefixcmp(arg, "-C")) {
2234 if (options->detect_rename == DIFF_DETECT_COPY)
2235 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2236 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2237 return -1;
2238 options->detect_rename = DIFF_DETECT_COPY;
2240 else if (!strcmp(arg, "--no-renames"))
2241 options->detect_rename = 0;
2243 /* xdiff options */
2244 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2245 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2246 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2247 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2248 else if (!strcmp(arg, "--ignore-space-at-eol"))
2249 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2251 /* flags options */
2252 else if (!strcmp(arg, "--binary")) {
2253 options->output_format |= DIFF_FORMAT_PATCH;
2254 DIFF_OPT_SET(options, BINARY);
2256 else if (!strcmp(arg, "--full-index"))
2257 DIFF_OPT_SET(options, FULL_INDEX);
2258 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2259 DIFF_OPT_SET(options, TEXT);
2260 else if (!strcmp(arg, "-R"))
2261 DIFF_OPT_SET(options, REVERSE_DIFF);
2262 else if (!strcmp(arg, "--find-copies-harder"))
2263 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2264 else if (!strcmp(arg, "--follow"))
2265 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2266 else if (!strcmp(arg, "--color"))
2267 DIFF_OPT_SET(options, COLOR_DIFF);
2268 else if (!strcmp(arg, "--no-color"))
2269 DIFF_OPT_CLR(options, COLOR_DIFF);
2270 else if (!strcmp(arg, "--color-words"))
2271 options->flags |= DIFF_OPT_COLOR_DIFF | DIFF_OPT_COLOR_DIFF_WORDS;
2272 else if (!strcmp(arg, "--exit-code"))
2273 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2274 else if (!strcmp(arg, "--quiet"))
2275 DIFF_OPT_SET(options, QUIET);
2276 else if (!strcmp(arg, "--ext-diff"))
2277 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2278 else if (!strcmp(arg, "--no-ext-diff"))
2279 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2281 /* misc options */
2282 else if (!strcmp(arg, "-z"))
2283 options->line_termination = 0;
2284 else if (!prefixcmp(arg, "-l"))
2285 options->rename_limit = strtoul(arg+2, NULL, 10);
2286 else if (!prefixcmp(arg, "-S"))
2287 options->pickaxe = arg + 2;
2288 else if (!strcmp(arg, "--pickaxe-all"))
2289 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2290 else if (!strcmp(arg, "--pickaxe-regex"))
2291 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2292 else if (!prefixcmp(arg, "-O"))
2293 options->orderfile = arg + 2;
2294 else if (!prefixcmp(arg, "--diff-filter="))
2295 options->filter = arg + 14;
2296 else if (!strcmp(arg, "--abbrev"))
2297 options->abbrev = DEFAULT_ABBREV;
2298 else if (!prefixcmp(arg, "--abbrev=")) {
2299 options->abbrev = strtoul(arg + 9, NULL, 10);
2300 if (options->abbrev < MINIMUM_ABBREV)
2301 options->abbrev = MINIMUM_ABBREV;
2302 else if (40 < options->abbrev)
2303 options->abbrev = 40;
2305 else if (!prefixcmp(arg, "--src-prefix="))
2306 options->a_prefix = arg + 13;
2307 else if (!prefixcmp(arg, "--dst-prefix="))
2308 options->b_prefix = arg + 13;
2309 else if (!strcmp(arg, "--no-prefix"))
2310 options->a_prefix = options->b_prefix = "";
2311 else
2312 return 0;
2313 return 1;
2316 static int parse_num(const char **cp_p)
2318 unsigned long num, scale;
2319 int ch, dot;
2320 const char *cp = *cp_p;
2322 num = 0;
2323 scale = 1;
2324 dot = 0;
2325 for(;;) {
2326 ch = *cp;
2327 if ( !dot && ch == '.' ) {
2328 scale = 1;
2329 dot = 1;
2330 } else if ( ch == '%' ) {
2331 scale = dot ? scale*100 : 100;
2332 cp++; /* % is always at the end */
2333 break;
2334 } else if ( ch >= '0' && ch <= '9' ) {
2335 if ( scale < 100000 ) {
2336 scale *= 10;
2337 num = (num*10) + (ch-'0');
2339 } else {
2340 break;
2342 cp++;
2344 *cp_p = cp;
2346 /* user says num divided by scale and we say internally that
2347 * is MAX_SCORE * num / scale.
2349 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2352 static int diff_scoreopt_parse(const char *opt)
2354 int opt1, opt2, cmd;
2356 if (*opt++ != '-')
2357 return -1;
2358 cmd = *opt++;
2359 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2360 return -1; /* that is not a -M, -C nor -B option */
2362 opt1 = parse_num(&opt);
2363 if (cmd != 'B')
2364 opt2 = 0;
2365 else {
2366 if (*opt == 0)
2367 opt2 = 0;
2368 else if (*opt != '/')
2369 return -1; /* we expect -B80/99 or -B80 */
2370 else {
2371 opt++;
2372 opt2 = parse_num(&opt);
2375 if (*opt != 0)
2376 return -1;
2377 return opt1 | (opt2 << 16);
2380 struct diff_queue_struct diff_queued_diff;
2382 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2384 if (queue->alloc <= queue->nr) {
2385 queue->alloc = alloc_nr(queue->alloc);
2386 queue->queue = xrealloc(queue->queue,
2387 sizeof(dp) * queue->alloc);
2389 queue->queue[queue->nr++] = dp;
2392 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2393 struct diff_filespec *one,
2394 struct diff_filespec *two)
2396 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2397 dp->one = one;
2398 dp->two = two;
2399 if (queue)
2400 diff_q(queue, dp);
2401 return dp;
2404 void diff_free_filepair(struct diff_filepair *p)
2406 free_filespec(p->one);
2407 free_filespec(p->two);
2408 free(p);
2411 /* This is different from find_unique_abbrev() in that
2412 * it stuffs the result with dots for alignment.
2414 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2416 int abblen;
2417 const char *abbrev;
2418 if (len == 40)
2419 return sha1_to_hex(sha1);
2421 abbrev = find_unique_abbrev(sha1, len);
2422 if (!abbrev)
2423 return sha1_to_hex(sha1);
2424 abblen = strlen(abbrev);
2425 if (abblen < 37) {
2426 static char hex[41];
2427 if (len < abblen && abblen <= len + 2)
2428 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2429 else
2430 sprintf(hex, "%s...", abbrev);
2431 return hex;
2433 return sha1_to_hex(sha1);
2436 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2438 int line_termination = opt->line_termination;
2439 int inter_name_termination = line_termination ? '\t' : '\0';
2441 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2442 printf(":%06o %06o %s ", p->one->mode, p->two->mode,
2443 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2444 printf("%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2446 if (p->score) {
2447 printf("%c%03d%c", p->status, similarity_index(p),
2448 inter_name_termination);
2449 } else {
2450 printf("%c%c", p->status, inter_name_termination);
2453 if (p->status == DIFF_STATUS_COPIED || p->status == DIFF_STATUS_RENAMED) {
2454 write_name_quoted(p->one->path, stdout, inter_name_termination);
2455 write_name_quoted(p->two->path, stdout, line_termination);
2456 } else {
2457 const char *path = p->one->mode ? p->one->path : p->two->path;
2458 write_name_quoted(path, stdout, line_termination);
2462 int diff_unmodified_pair(struct diff_filepair *p)
2464 /* This function is written stricter than necessary to support
2465 * the currently implemented transformers, but the idea is to
2466 * let transformers to produce diff_filepairs any way they want,
2467 * and filter and clean them up here before producing the output.
2469 struct diff_filespec *one = p->one, *two = p->two;
2471 if (DIFF_PAIR_UNMERGED(p))
2472 return 0; /* unmerged is interesting */
2474 /* deletion, addition, mode or type change
2475 * and rename are all interesting.
2477 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2478 DIFF_PAIR_MODE_CHANGED(p) ||
2479 strcmp(one->path, two->path))
2480 return 0;
2482 /* both are valid and point at the same path. that is, we are
2483 * dealing with a change.
2485 if (one->sha1_valid && two->sha1_valid &&
2486 !hashcmp(one->sha1, two->sha1))
2487 return 1; /* no change */
2488 if (!one->sha1_valid && !two->sha1_valid)
2489 return 1; /* both look at the same file on the filesystem. */
2490 return 0;
2493 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2495 if (diff_unmodified_pair(p))
2496 return;
2498 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2499 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2500 return; /* no tree diffs in patch format */
2502 run_diff(p, o);
2505 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2506 struct diffstat_t *diffstat)
2508 if (diff_unmodified_pair(p))
2509 return;
2511 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2512 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2513 return; /* no tree diffs in patch format */
2515 run_diffstat(p, o, diffstat);
2518 static void diff_flush_checkdiff(struct diff_filepair *p,
2519 struct diff_options *o)
2521 if (diff_unmodified_pair(p))
2522 return;
2524 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2525 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2526 return; /* no tree diffs in patch format */
2528 run_checkdiff(p, o);
2531 int diff_queue_is_empty(void)
2533 struct diff_queue_struct *q = &diff_queued_diff;
2534 int i;
2535 for (i = 0; i < q->nr; i++)
2536 if (!diff_unmodified_pair(q->queue[i]))
2537 return 0;
2538 return 1;
2541 #if DIFF_DEBUG
2542 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2544 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2545 x, one ? one : "",
2546 s->path,
2547 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2548 s->mode,
2549 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2550 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2551 x, one ? one : "",
2552 s->size, s->xfrm_flags);
2555 void diff_debug_filepair(const struct diff_filepair *p, int i)
2557 diff_debug_filespec(p->one, i, "one");
2558 diff_debug_filespec(p->two, i, "two");
2559 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2560 p->score, p->status ? p->status : '?',
2561 p->one->rename_used, p->broken_pair);
2564 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2566 int i;
2567 if (msg)
2568 fprintf(stderr, "%s\n", msg);
2569 fprintf(stderr, "q->nr = %d\n", q->nr);
2570 for (i = 0; i < q->nr; i++) {
2571 struct diff_filepair *p = q->queue[i];
2572 diff_debug_filepair(p, i);
2575 #endif
2577 static void diff_resolve_rename_copy(void)
2579 int i;
2580 struct diff_filepair *p;
2581 struct diff_queue_struct *q = &diff_queued_diff;
2583 diff_debug_queue("resolve-rename-copy", q);
2585 for (i = 0; i < q->nr; i++) {
2586 p = q->queue[i];
2587 p->status = 0; /* undecided */
2588 if (DIFF_PAIR_UNMERGED(p))
2589 p->status = DIFF_STATUS_UNMERGED;
2590 else if (!DIFF_FILE_VALID(p->one))
2591 p->status = DIFF_STATUS_ADDED;
2592 else if (!DIFF_FILE_VALID(p->two))
2593 p->status = DIFF_STATUS_DELETED;
2594 else if (DIFF_PAIR_TYPE_CHANGED(p))
2595 p->status = DIFF_STATUS_TYPE_CHANGED;
2597 /* from this point on, we are dealing with a pair
2598 * whose both sides are valid and of the same type, i.e.
2599 * either in-place edit or rename/copy edit.
2601 else if (DIFF_PAIR_RENAME(p)) {
2603 * A rename might have re-connected a broken
2604 * pair up, causing the pathnames to be the
2605 * same again. If so, that's not a rename at
2606 * all, just a modification..
2608 * Otherwise, see if this source was used for
2609 * multiple renames, in which case we decrement
2610 * the count, and call it a copy.
2612 if (!strcmp(p->one->path, p->two->path))
2613 p->status = DIFF_STATUS_MODIFIED;
2614 else if (--p->one->rename_used > 0)
2615 p->status = DIFF_STATUS_COPIED;
2616 else
2617 p->status = DIFF_STATUS_RENAMED;
2619 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2620 p->one->mode != p->two->mode ||
2621 is_null_sha1(p->one->sha1))
2622 p->status = DIFF_STATUS_MODIFIED;
2623 else {
2624 /* This is a "no-change" entry and should not
2625 * happen anymore, but prepare for broken callers.
2627 error("feeding unmodified %s to diffcore",
2628 p->one->path);
2629 p->status = DIFF_STATUS_UNKNOWN;
2632 diff_debug_queue("resolve-rename-copy done", q);
2635 static int check_pair_status(struct diff_filepair *p)
2637 switch (p->status) {
2638 case DIFF_STATUS_UNKNOWN:
2639 return 0;
2640 case 0:
2641 die("internal error in diff-resolve-rename-copy");
2642 default:
2643 return 1;
2647 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2649 int fmt = opt->output_format;
2651 if (fmt & DIFF_FORMAT_CHECKDIFF)
2652 diff_flush_checkdiff(p, opt);
2653 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2654 diff_flush_raw(p, opt);
2655 else if (fmt & DIFF_FORMAT_NAME)
2656 write_name_quoted(p->two->path, stdout, opt->line_termination);
2659 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2661 if (fs->mode)
2662 printf(" %s mode %06o ", newdelete, fs->mode);
2663 else
2664 printf(" %s ", newdelete);
2665 write_name_quoted(fs->path, stdout, '\n');
2669 static void show_mode_change(struct diff_filepair *p, int show_name)
2671 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2672 printf(" mode change %06o => %06o%c", p->one->mode, p->two->mode,
2673 show_name ? ' ' : '\n');
2674 if (show_name) {
2675 write_name_quoted(p->two->path, stdout, '\n');
2680 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2682 char *names = pprint_rename(p->one->path, p->two->path);
2684 printf(" %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2685 free(names);
2686 show_mode_change(p, 0);
2689 static void diff_summary(struct diff_filepair *p)
2691 switch(p->status) {
2692 case DIFF_STATUS_DELETED:
2693 show_file_mode_name("delete", p->one);
2694 break;
2695 case DIFF_STATUS_ADDED:
2696 show_file_mode_name("create", p->two);
2697 break;
2698 case DIFF_STATUS_COPIED:
2699 show_rename_copy("copy", p);
2700 break;
2701 case DIFF_STATUS_RENAMED:
2702 show_rename_copy("rename", p);
2703 break;
2704 default:
2705 if (p->score) {
2706 fputs(" rewrite ", stdout);
2707 write_name_quoted(p->two->path, stdout, ' ');
2708 printf("(%d%%)\n", similarity_index(p));
2710 show_mode_change(p, !p->score);
2711 break;
2715 struct patch_id_t {
2716 struct xdiff_emit_state xm;
2717 SHA_CTX *ctx;
2718 int patchlen;
2721 static int remove_space(char *line, int len)
2723 int i;
2724 char *dst = line;
2725 unsigned char c;
2727 for (i = 0; i < len; i++)
2728 if (!isspace((c = line[i])))
2729 *dst++ = c;
2731 return dst - line;
2734 static void patch_id_consume(void *priv, char *line, unsigned long len)
2736 struct patch_id_t *data = priv;
2737 int new_len;
2739 /* Ignore line numbers when computing the SHA1 of the patch */
2740 if (!prefixcmp(line, "@@ -"))
2741 return;
2743 new_len = remove_space(line, len);
2745 SHA1_Update(data->ctx, line, new_len);
2746 data->patchlen += new_len;
2749 /* returns 0 upon success, and writes result into sha1 */
2750 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2752 struct diff_queue_struct *q = &diff_queued_diff;
2753 int i;
2754 SHA_CTX ctx;
2755 struct patch_id_t data;
2756 char buffer[PATH_MAX * 4 + 20];
2758 SHA1_Init(&ctx);
2759 memset(&data, 0, sizeof(struct patch_id_t));
2760 data.ctx = &ctx;
2761 data.xm.consume = patch_id_consume;
2763 for (i = 0; i < q->nr; i++) {
2764 xpparam_t xpp;
2765 xdemitconf_t xecfg;
2766 xdemitcb_t ecb;
2767 mmfile_t mf1, mf2;
2768 struct diff_filepair *p = q->queue[i];
2769 int len1, len2;
2771 memset(&xecfg, 0, sizeof(xecfg));
2772 if (p->status == 0)
2773 return error("internal diff status error");
2774 if (p->status == DIFF_STATUS_UNKNOWN)
2775 continue;
2776 if (diff_unmodified_pair(p))
2777 continue;
2778 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2779 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2780 continue;
2781 if (DIFF_PAIR_UNMERGED(p))
2782 continue;
2784 diff_fill_sha1_info(p->one);
2785 diff_fill_sha1_info(p->two);
2786 if (fill_mmfile(&mf1, p->one) < 0 ||
2787 fill_mmfile(&mf2, p->two) < 0)
2788 return error("unable to read files to diff");
2790 len1 = remove_space(p->one->path, strlen(p->one->path));
2791 len2 = remove_space(p->two->path, strlen(p->two->path));
2792 if (p->one->mode == 0)
2793 len1 = snprintf(buffer, sizeof(buffer),
2794 "diff--gita/%.*sb/%.*s"
2795 "newfilemode%06o"
2796 "---/dev/null"
2797 "+++b/%.*s",
2798 len1, p->one->path,
2799 len2, p->two->path,
2800 p->two->mode,
2801 len2, p->two->path);
2802 else if (p->two->mode == 0)
2803 len1 = snprintf(buffer, sizeof(buffer),
2804 "diff--gita/%.*sb/%.*s"
2805 "deletedfilemode%06o"
2806 "---a/%.*s"
2807 "+++/dev/null",
2808 len1, p->one->path,
2809 len2, p->two->path,
2810 p->one->mode,
2811 len1, p->one->path);
2812 else
2813 len1 = snprintf(buffer, sizeof(buffer),
2814 "diff--gita/%.*sb/%.*s"
2815 "---a/%.*s"
2816 "+++b/%.*s",
2817 len1, p->one->path,
2818 len2, p->two->path,
2819 len1, p->one->path,
2820 len2, p->two->path);
2821 SHA1_Update(&ctx, buffer, len1);
2823 xpp.flags = XDF_NEED_MINIMAL;
2824 xecfg.ctxlen = 3;
2825 xecfg.flags = XDL_EMIT_FUNCNAMES;
2826 ecb.outf = xdiff_outf;
2827 ecb.priv = &data;
2828 xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2831 SHA1_Final(sha1, &ctx);
2832 return 0;
2835 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2837 struct diff_queue_struct *q = &diff_queued_diff;
2838 int i;
2839 int result = diff_get_patch_id(options, sha1);
2841 for (i = 0; i < q->nr; i++)
2842 diff_free_filepair(q->queue[i]);
2844 free(q->queue);
2845 q->queue = NULL;
2846 q->nr = q->alloc = 0;
2848 return result;
2851 static int is_summary_empty(const struct diff_queue_struct *q)
2853 int i;
2855 for (i = 0; i < q->nr; i++) {
2856 const struct diff_filepair *p = q->queue[i];
2858 switch (p->status) {
2859 case DIFF_STATUS_DELETED:
2860 case DIFF_STATUS_ADDED:
2861 case DIFF_STATUS_COPIED:
2862 case DIFF_STATUS_RENAMED:
2863 return 0;
2864 default:
2865 if (p->score)
2866 return 0;
2867 if (p->one->mode && p->two->mode &&
2868 p->one->mode != p->two->mode)
2869 return 0;
2870 break;
2873 return 1;
2876 void diff_flush(struct diff_options *options)
2878 struct diff_queue_struct *q = &diff_queued_diff;
2879 int i, output_format = options->output_format;
2880 int separator = 0;
2883 * Order: raw, stat, summary, patch
2884 * or: name/name-status/checkdiff (other bits clear)
2886 if (!q->nr)
2887 goto free_queue;
2889 if (output_format & (DIFF_FORMAT_RAW |
2890 DIFF_FORMAT_NAME |
2891 DIFF_FORMAT_NAME_STATUS |
2892 DIFF_FORMAT_CHECKDIFF)) {
2893 for (i = 0; i < q->nr; i++) {
2894 struct diff_filepair *p = q->queue[i];
2895 if (check_pair_status(p))
2896 flush_one_pair(p, options);
2898 separator++;
2901 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
2902 struct diffstat_t diffstat;
2904 memset(&diffstat, 0, sizeof(struct diffstat_t));
2905 diffstat.xm.consume = diffstat_consume;
2906 for (i = 0; i < q->nr; i++) {
2907 struct diff_filepair *p = q->queue[i];
2908 if (check_pair_status(p))
2909 diff_flush_stat(p, options, &diffstat);
2911 if (output_format & DIFF_FORMAT_NUMSTAT)
2912 show_numstat(&diffstat, options);
2913 if (output_format & DIFF_FORMAT_DIFFSTAT)
2914 show_stats(&diffstat, options);
2915 if (output_format & DIFF_FORMAT_SHORTSTAT)
2916 show_shortstats(&diffstat);
2917 free_diffstat_info(&diffstat);
2918 separator++;
2921 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2922 for (i = 0; i < q->nr; i++)
2923 diff_summary(q->queue[i]);
2924 separator++;
2927 if (output_format & DIFF_FORMAT_PATCH) {
2928 if (separator) {
2929 if (options->stat_sep) {
2930 /* attach patch instead of inline */
2931 fputs(options->stat_sep, stdout);
2932 } else {
2933 putchar(options->line_termination);
2937 for (i = 0; i < q->nr; i++) {
2938 struct diff_filepair *p = q->queue[i];
2939 if (check_pair_status(p))
2940 diff_flush_patch(p, options);
2944 if (output_format & DIFF_FORMAT_CALLBACK)
2945 options->format_callback(q, options, options->format_callback_data);
2947 for (i = 0; i < q->nr; i++)
2948 diff_free_filepair(q->queue[i]);
2949 free_queue:
2950 free(q->queue);
2951 q->queue = NULL;
2952 q->nr = q->alloc = 0;
2955 static void diffcore_apply_filter(const char *filter)
2957 int i;
2958 struct diff_queue_struct *q = &diff_queued_diff;
2959 struct diff_queue_struct outq;
2960 outq.queue = NULL;
2961 outq.nr = outq.alloc = 0;
2963 if (!filter)
2964 return;
2966 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2967 int found;
2968 for (i = found = 0; !found && i < q->nr; i++) {
2969 struct diff_filepair *p = q->queue[i];
2970 if (((p->status == DIFF_STATUS_MODIFIED) &&
2971 ((p->score &&
2972 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2973 (!p->score &&
2974 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2975 ((p->status != DIFF_STATUS_MODIFIED) &&
2976 strchr(filter, p->status)))
2977 found++;
2979 if (found)
2980 return;
2982 /* otherwise we will clear the whole queue
2983 * by copying the empty outq at the end of this
2984 * function, but first clear the current entries
2985 * in the queue.
2987 for (i = 0; i < q->nr; i++)
2988 diff_free_filepair(q->queue[i]);
2990 else {
2991 /* Only the matching ones */
2992 for (i = 0; i < q->nr; i++) {
2993 struct diff_filepair *p = q->queue[i];
2995 if (((p->status == DIFF_STATUS_MODIFIED) &&
2996 ((p->score &&
2997 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2998 (!p->score &&
2999 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3000 ((p->status != DIFF_STATUS_MODIFIED) &&
3001 strchr(filter, p->status)))
3002 diff_q(&outq, p);
3003 else
3004 diff_free_filepair(p);
3007 free(q->queue);
3008 *q = outq;
3011 /* Check whether two filespecs with the same mode and size are identical */
3012 static int diff_filespec_is_identical(struct diff_filespec *one,
3013 struct diff_filespec *two)
3015 if (S_ISGITLINK(one->mode)) {
3016 diff_fill_sha1_info(one);
3017 diff_fill_sha1_info(two);
3018 return !hashcmp(one->sha1, two->sha1);
3020 if (diff_populate_filespec(one, 0))
3021 return 0;
3022 if (diff_populate_filespec(two, 0))
3023 return 0;
3024 return !memcmp(one->data, two->data, one->size);
3027 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3029 int i;
3030 struct diff_queue_struct *q = &diff_queued_diff;
3031 struct diff_queue_struct outq;
3032 outq.queue = NULL;
3033 outq.nr = outq.alloc = 0;
3035 for (i = 0; i < q->nr; i++) {
3036 struct diff_filepair *p = q->queue[i];
3039 * 1. Entries that come from stat info dirtyness
3040 * always have both sides (iow, not create/delete),
3041 * one side of the object name is unknown, with
3042 * the same mode and size. Keep the ones that
3043 * do not match these criteria. They have real
3044 * differences.
3046 * 2. At this point, the file is known to be modified,
3047 * with the same mode and size, and the object
3048 * name of one side is unknown. Need to inspect
3049 * the identical contents.
3051 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3052 !DIFF_FILE_VALID(p->two) ||
3053 (p->one->sha1_valid && p->two->sha1_valid) ||
3054 (p->one->mode != p->two->mode) ||
3055 diff_populate_filespec(p->one, 1) ||
3056 diff_populate_filespec(p->two, 1) ||
3057 (p->one->size != p->two->size) ||
3058 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3059 diff_q(&outq, p);
3060 else {
3062 * The caller can subtract 1 from skip_stat_unmatch
3063 * to determine how many paths were dirty only
3064 * due to stat info mismatch.
3066 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3067 diffopt->skip_stat_unmatch++;
3068 diff_free_filepair(p);
3071 free(q->queue);
3072 *q = outq;
3075 void diffcore_std(struct diff_options *options)
3077 if (DIFF_OPT_TST(options, QUIET))
3078 return;
3080 if (options->skip_stat_unmatch && !DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3081 diffcore_skip_stat_unmatch(options);
3082 if (options->break_opt != -1)
3083 diffcore_break(options->break_opt);
3084 if (options->detect_rename)
3085 diffcore_rename(options);
3086 if (options->break_opt != -1)
3087 diffcore_merge_broken();
3088 if (options->pickaxe)
3089 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3090 if (options->orderfile)
3091 diffcore_order(options->orderfile);
3092 diff_resolve_rename_copy();
3093 diffcore_apply_filter(options->filter);
3095 if (diff_queued_diff.nr)
3096 DIFF_OPT_SET(options, HAS_CHANGES);
3097 else
3098 DIFF_OPT_CLR(options, HAS_CHANGES);
3101 int diff_result_code(struct diff_options *opt, int status)
3103 int result = 0;
3104 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3105 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3106 return status;
3107 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3108 DIFF_OPT_TST(opt, HAS_CHANGES))
3109 result |= 01;
3110 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3111 DIFF_OPT_TST(opt, CHECK_FAILED))
3112 result |= 02;
3113 return result;
3116 void diff_addremove(struct diff_options *options,
3117 int addremove, unsigned mode,
3118 const unsigned char *sha1,
3119 const char *base, const char *path)
3121 char concatpath[PATH_MAX];
3122 struct diff_filespec *one, *two;
3124 /* This may look odd, but it is a preparation for
3125 * feeding "there are unchanged files which should
3126 * not produce diffs, but when you are doing copy
3127 * detection you would need them, so here they are"
3128 * entries to the diff-core. They will be prefixed
3129 * with something like '=' or '*' (I haven't decided
3130 * which but should not make any difference).
3131 * Feeding the same new and old to diff_change()
3132 * also has the same effect.
3133 * Before the final output happens, they are pruned after
3134 * merged into rename/copy pairs as appropriate.
3136 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3137 addremove = (addremove == '+' ? '-' :
3138 addremove == '-' ? '+' : addremove);
3140 if (!path) path = "";
3141 sprintf(concatpath, "%s%s", base, path);
3142 one = alloc_filespec(concatpath);
3143 two = alloc_filespec(concatpath);
3145 if (addremove != '+')
3146 fill_filespec(one, sha1, mode);
3147 if (addremove != '-')
3148 fill_filespec(two, sha1, mode);
3150 diff_queue(&diff_queued_diff, one, two);
3151 DIFF_OPT_SET(options, HAS_CHANGES);
3154 void diff_change(struct diff_options *options,
3155 unsigned old_mode, unsigned new_mode,
3156 const unsigned char *old_sha1,
3157 const unsigned char *new_sha1,
3158 const char *base, const char *path)
3160 char concatpath[PATH_MAX];
3161 struct diff_filespec *one, *two;
3163 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3164 unsigned tmp;
3165 const unsigned char *tmp_c;
3166 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3167 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3169 if (!path) path = "";
3170 sprintf(concatpath, "%s%s", base, path);
3171 one = alloc_filespec(concatpath);
3172 two = alloc_filespec(concatpath);
3173 fill_filespec(one, old_sha1, old_mode);
3174 fill_filespec(two, new_sha1, new_mode);
3176 diff_queue(&diff_queued_diff, one, two);
3177 DIFF_OPT_SET(options, HAS_CHANGES);
3180 void diff_unmerge(struct diff_options *options,
3181 const char *path,
3182 unsigned mode, const unsigned char *sha1)
3184 struct diff_filespec *one, *two;
3185 one = alloc_filespec(path);
3186 two = alloc_filespec(path);
3187 fill_filespec(one, sha1, mode);
3188 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;