Merge branch 'mz/push-verbose' into next
[git/gitweb-caching.git] / diff.c
bloba6c143251c8cd7da84400b960cb153b6f24c2ae6
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"
13 #include "utf8.h"
15 #ifdef NO_FAST_WORKING_DIRECTORY
16 #define FAST_WORKING_DIRECTORY 0
17 #else
18 #define FAST_WORKING_DIRECTORY 1
19 #endif
21 static int diff_detect_rename_default;
22 static int diff_rename_limit_default = 200;
23 int diff_use_color_default = -1;
24 static const char *external_diff_cmd_cfg;
25 int diff_auto_refresh_index = 1;
27 static char diff_colors[][COLOR_MAXLEN] = {
28 "\033[m", /* reset */
29 "", /* PLAIN (normal) */
30 "\033[1m", /* METAINFO (bold) */
31 "\033[36m", /* FRAGINFO (cyan) */
32 "\033[31m", /* OLD (red) */
33 "\033[32m", /* NEW (green) */
34 "\033[33m", /* COMMIT (yellow) */
35 "\033[41m", /* WHITESPACE (red background) */
38 static int parse_diff_color_slot(const char *var, int ofs)
40 if (!strcasecmp(var+ofs, "plain"))
41 return DIFF_PLAIN;
42 if (!strcasecmp(var+ofs, "meta"))
43 return DIFF_METAINFO;
44 if (!strcasecmp(var+ofs, "frag"))
45 return DIFF_FRAGINFO;
46 if (!strcasecmp(var+ofs, "old"))
47 return DIFF_FILE_OLD;
48 if (!strcasecmp(var+ofs, "new"))
49 return DIFF_FILE_NEW;
50 if (!strcasecmp(var+ofs, "commit"))
51 return DIFF_COMMIT;
52 if (!strcasecmp(var+ofs, "whitespace"))
53 return DIFF_WHITESPACE;
54 die("bad config variable '%s'", var);
57 static struct ll_diff_driver {
58 const char *name;
59 struct ll_diff_driver *next;
60 const char *cmd;
61 } *user_diff, **user_diff_tail;
64 * Currently there is only "diff.<drivername>.command" variable;
65 * because there are "diff.color.<slot>" variables, we are parsing
66 * this in a bit convoluted way to allow low level diff driver
67 * called "color".
69 static int parse_lldiff_command(const char *var, const char *ep, const char *value)
71 const char *name;
72 int namelen;
73 struct ll_diff_driver *drv;
75 name = var + 5;
76 namelen = ep - name;
77 for (drv = user_diff; drv; drv = drv->next)
78 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
79 break;
80 if (!drv) {
81 drv = xcalloc(1, sizeof(struct ll_diff_driver));
82 drv->name = xmemdupz(name, namelen);
83 if (!user_diff_tail)
84 user_diff_tail = &user_diff;
85 *user_diff_tail = drv;
86 user_diff_tail = &(drv->next);
89 return git_config_string(&(drv->cmd), var, value);
93 * 'diff.<what>.funcname' attribute can be specified in the configuration
94 * to define a customized regexp to find the beginning of a function to
95 * be used for hunk header lines of "diff -p" style output.
97 static struct funcname_pattern {
98 char *name;
99 char *pattern;
100 struct funcname_pattern *next;
101 } *funcname_pattern_list;
103 static int parse_funcname_pattern(const char *var, const char *ep, const char *value)
105 const char *name;
106 int namelen;
107 struct funcname_pattern *pp;
109 name = var + 5; /* "diff." */
110 namelen = ep - name;
112 for (pp = funcname_pattern_list; pp; pp = pp->next)
113 if (!strncmp(pp->name, name, namelen) && !pp->name[namelen])
114 break;
115 if (!pp) {
116 pp = xcalloc(1, sizeof(*pp));
117 pp->name = xmemdupz(name, namelen);
118 pp->next = funcname_pattern_list;
119 funcname_pattern_list = pp;
121 free(pp->pattern);
122 pp->pattern = xstrdup(value);
123 return 0;
127 * These are to give UI layer defaults.
128 * The core-level commands such as git-diff-files should
129 * never be affected by the setting of diff.renames
130 * the user happens to have in the configuration file.
132 int git_diff_ui_config(const char *var, const char *value, void *cb)
134 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
135 diff_use_color_default = git_config_colorbool(var, value, -1);
136 return 0;
138 if (!strcmp(var, "diff.renames")) {
139 if (!value)
140 diff_detect_rename_default = DIFF_DETECT_RENAME;
141 else if (!strcasecmp(value, "copies") ||
142 !strcasecmp(value, "copy"))
143 diff_detect_rename_default = DIFF_DETECT_COPY;
144 else if (git_config_bool(var,value))
145 diff_detect_rename_default = DIFF_DETECT_RENAME;
146 return 0;
148 if (!strcmp(var, "diff.autorefreshindex")) {
149 diff_auto_refresh_index = git_config_bool(var, value);
150 return 0;
152 if (!strcmp(var, "diff.external"))
153 return git_config_string(&external_diff_cmd_cfg, var, value);
154 if (!prefixcmp(var, "diff.")) {
155 const char *ep = strrchr(var, '.');
157 if (ep != var + 4 && !strcmp(ep, ".command"))
158 return parse_lldiff_command(var, ep, value);
161 return git_diff_basic_config(var, value, cb);
164 int git_diff_basic_config(const char *var, const char *value, void *cb)
166 if (!strcmp(var, "diff.renamelimit")) {
167 diff_rename_limit_default = git_config_int(var, value);
168 return 0;
171 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
172 int slot = parse_diff_color_slot(var, 11);
173 if (!value)
174 return config_error_nonbool(var);
175 color_parse(value, var, diff_colors[slot]);
176 return 0;
179 if (!prefixcmp(var, "diff.")) {
180 const char *ep = strrchr(var, '.');
181 if (ep != var + 4) {
182 if (!strcmp(ep, ".funcname")) {
183 if (!value)
184 return config_error_nonbool(var);
185 return parse_funcname_pattern(var, ep, value);
190 return git_color_default_config(var, value, cb);
193 static char *quote_two(const char *one, const char *two)
195 int need_one = quote_c_style(one, NULL, NULL, 1);
196 int need_two = quote_c_style(two, NULL, NULL, 1);
197 struct strbuf res;
199 strbuf_init(&res, 0);
200 if (need_one + need_two) {
201 strbuf_addch(&res, '"');
202 quote_c_style(one, &res, NULL, 1);
203 quote_c_style(two, &res, NULL, 1);
204 strbuf_addch(&res, '"');
205 } else {
206 strbuf_addstr(&res, one);
207 strbuf_addstr(&res, two);
209 return strbuf_detach(&res, NULL);
212 static const char *external_diff(void)
214 static const char *external_diff_cmd = NULL;
215 static int done_preparing = 0;
217 if (done_preparing)
218 return external_diff_cmd;
219 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
220 if (!external_diff_cmd)
221 external_diff_cmd = external_diff_cmd_cfg;
222 done_preparing = 1;
223 return external_diff_cmd;
226 static struct diff_tempfile {
227 const char *name; /* filename external diff should read from */
228 char hex[41];
229 char mode[10];
230 char tmp_path[PATH_MAX];
231 } diff_temp[2];
233 static int count_lines(const char *data, int size)
235 int count, ch, completely_empty = 1, nl_just_seen = 0;
236 count = 0;
237 while (0 < size--) {
238 ch = *data++;
239 if (ch == '\n') {
240 count++;
241 nl_just_seen = 1;
242 completely_empty = 0;
244 else {
245 nl_just_seen = 0;
246 completely_empty = 0;
249 if (completely_empty)
250 return 0;
251 if (!nl_just_seen)
252 count++; /* no trailing newline */
253 return count;
256 static void print_line_count(FILE *file, int count)
258 switch (count) {
259 case 0:
260 fprintf(file, "0,0");
261 break;
262 case 1:
263 fprintf(file, "1");
264 break;
265 default:
266 fprintf(file, "1,%d", count);
267 break;
271 static void copy_file_with_prefix(FILE *file,
272 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, file);
280 putc(prefix, file);
282 if (ch == '\n') {
283 nl_just_seen = 1;
284 fputs(reset, file);
285 } else
286 nl_just_seen = 0;
287 putc(ch, file);
289 if (!nl_just_seen)
290 fprintf(file, "%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 fprintf(o->file,
324 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
325 metainfo, a_name.buf, name_a_tab, reset,
326 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
327 print_line_count(o->file, lc_a);
328 fprintf(o->file, " +");
329 print_line_count(o->file, lc_b);
330 fprintf(o->file, " @@%s\n", reset);
331 if (lc_a)
332 copy_file_with_prefix(o->file, '-', one->data, one->size, old, reset);
333 if (lc_b)
334 copy_file_with_prefix(o->file, '+', two->data, two->size, new, reset);
337 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
339 if (!DIFF_FILE_VALID(one)) {
340 mf->ptr = (char *)""; /* does not matter */
341 mf->size = 0;
342 return 0;
344 else if (diff_populate_filespec(one, 0))
345 return -1;
346 mf->ptr = one->data;
347 mf->size = one->size;
348 return 0;
351 struct diff_words_buffer {
352 mmfile_t text;
353 long alloc;
354 long current; /* output pointer */
355 int suppressed_newline;
358 static void diff_words_append(char *line, unsigned long len,
359 struct diff_words_buffer *buffer)
361 if (buffer->text.size + len > buffer->alloc) {
362 buffer->alloc = (buffer->text.size + len) * 3 / 2;
363 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
365 line++;
366 len--;
367 memcpy(buffer->text.ptr + buffer->text.size, line, len);
368 buffer->text.size += len;
371 struct diff_words_data {
372 struct diff_words_buffer minus, plus;
373 FILE *file;
376 static void print_word(FILE *file, struct diff_words_buffer *buffer, int len, int color,
377 int suppress_newline)
379 const char *ptr;
380 int eol = 0;
382 if (len == 0)
383 return;
385 ptr = buffer->text.ptr + buffer->current;
386 buffer->current += len;
388 if (ptr[len - 1] == '\n') {
389 eol = 1;
390 len--;
393 fputs(diff_get_color(1, color), file);
394 fwrite(ptr, len, 1, file);
395 fputs(diff_get_color(1, DIFF_RESET), file);
397 if (eol) {
398 if (suppress_newline)
399 buffer->suppressed_newline = 1;
400 else
401 putc('\n', file);
405 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
407 struct diff_words_data *diff_words = priv;
409 if (diff_words->minus.suppressed_newline) {
410 if (line[0] != '+')
411 putc('\n', diff_words->file);
412 diff_words->minus.suppressed_newline = 0;
415 len--;
416 switch (line[0]) {
417 case '-':
418 print_word(diff_words->file,
419 &diff_words->minus, len, DIFF_FILE_OLD, 1);
420 break;
421 case '+':
422 print_word(diff_words->file,
423 &diff_words->plus, len, DIFF_FILE_NEW, 0);
424 break;
425 case ' ':
426 print_word(diff_words->file,
427 &diff_words->plus, len, DIFF_PLAIN, 0);
428 diff_words->minus.current += len;
429 break;
433 /* this executes the word diff on the accumulated buffers */
434 static void diff_words_show(struct diff_words_data *diff_words)
436 xpparam_t xpp;
437 xdemitconf_t xecfg;
438 xdemitcb_t ecb;
439 mmfile_t minus, plus;
440 int i;
442 memset(&xecfg, 0, sizeof(xecfg));
443 minus.size = diff_words->minus.text.size;
444 minus.ptr = xmalloc(minus.size);
445 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
446 for (i = 0; i < minus.size; i++)
447 if (isspace(minus.ptr[i]))
448 minus.ptr[i] = '\n';
449 diff_words->minus.current = 0;
451 plus.size = diff_words->plus.text.size;
452 plus.ptr = xmalloc(plus.size);
453 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
454 for (i = 0; i < plus.size; i++)
455 if (isspace(plus.ptr[i]))
456 plus.ptr[i] = '\n';
457 diff_words->plus.current = 0;
459 xpp.flags = XDF_NEED_MINIMAL;
460 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
461 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
462 &xpp, &xecfg, &ecb);
463 free(minus.ptr);
464 free(plus.ptr);
465 diff_words->minus.text.size = diff_words->plus.text.size = 0;
467 if (diff_words->minus.suppressed_newline) {
468 putc('\n', diff_words->file);
469 diff_words->minus.suppressed_newline = 0;
473 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
475 struct emit_callback {
476 int nparents, color_diff;
477 unsigned ws_rule;
478 sane_truncate_fn truncate;
479 const char **label_path;
480 struct diff_words_data *diff_words;
481 int *found_changesp;
482 FILE *file;
485 static void free_diff_words_data(struct emit_callback *ecbdata)
487 if (ecbdata->diff_words) {
488 /* flush buffers */
489 if (ecbdata->diff_words->minus.text.size ||
490 ecbdata->diff_words->plus.text.size)
491 diff_words_show(ecbdata->diff_words);
493 free (ecbdata->diff_words->minus.text.ptr);
494 free (ecbdata->diff_words->plus.text.ptr);
495 free(ecbdata->diff_words);
496 ecbdata->diff_words = NULL;
500 const char *diff_get_color(int diff_use_color, enum color_diff ix)
502 if (diff_use_color)
503 return diff_colors[ix];
504 return "";
507 static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
509 int has_trailing_newline = (len > 0 && line[len-1] == '\n');
510 if (has_trailing_newline)
511 len--;
513 fputs(set, file);
514 fwrite(line, len, 1, file);
515 fputs(reset, file);
516 if (has_trailing_newline)
517 fputc('\n', file);
520 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
522 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
523 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
525 if (!*ws)
526 emit_line(ecbdata->file, set, reset, line, len);
527 else {
528 /* Emit just the prefix, then the rest. */
529 emit_line(ecbdata->file, set, reset, line, ecbdata->nparents);
530 ws_check_emit(line + ecbdata->nparents,
531 len - ecbdata->nparents, ecbdata->ws_rule,
532 ecbdata->file, set, reset, ws);
536 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
538 const char *cp;
539 unsigned long allot;
540 size_t l = len;
542 if (ecb->truncate)
543 return ecb->truncate(line, len);
544 cp = line;
545 allot = l;
546 while (0 < l) {
547 (void) utf8_width(&cp, &l);
548 if (!cp)
549 break; /* truncated in the middle? */
551 return allot - l;
554 static void fn_out_consume(void *priv, char *line, unsigned long len)
556 int i;
557 int color;
558 struct emit_callback *ecbdata = priv;
559 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
560 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
561 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
563 *(ecbdata->found_changesp) = 1;
565 if (ecbdata->label_path[0]) {
566 const char *name_a_tab, *name_b_tab;
568 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
569 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
571 fprintf(ecbdata->file, "%s--- %s%s%s\n",
572 meta, ecbdata->label_path[0], reset, name_a_tab);
573 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
574 meta, ecbdata->label_path[1], reset, name_b_tab);
575 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
578 /* This is not really necessary for now because
579 * this codepath only deals with two-way diffs.
581 for (i = 0; i < len && line[i] == '@'; i++)
583 if (2 <= i && i < len && line[i] == ' ') {
584 ecbdata->nparents = i - 1;
585 len = sane_truncate_line(ecbdata, line, len);
586 emit_line(ecbdata->file,
587 diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
588 reset, line, len);
589 if (line[len-1] != '\n')
590 putc('\n', ecbdata->file);
591 return;
594 if (len < ecbdata->nparents) {
595 emit_line(ecbdata->file, reset, reset, line, len);
596 return;
599 color = DIFF_PLAIN;
600 if (ecbdata->diff_words && ecbdata->nparents != 1)
601 /* fall back to normal diff */
602 free_diff_words_data(ecbdata);
603 if (ecbdata->diff_words) {
604 if (line[0] == '-') {
605 diff_words_append(line, len,
606 &ecbdata->diff_words->minus);
607 return;
608 } else if (line[0] == '+') {
609 diff_words_append(line, len,
610 &ecbdata->diff_words->plus);
611 return;
613 if (ecbdata->diff_words->minus.text.size ||
614 ecbdata->diff_words->plus.text.size)
615 diff_words_show(ecbdata->diff_words);
616 line++;
617 len--;
618 emit_line(ecbdata->file, plain, reset, line, len);
619 return;
621 for (i = 0; i < ecbdata->nparents && len; i++) {
622 if (line[i] == '-')
623 color = DIFF_FILE_OLD;
624 else if (line[i] == '+')
625 color = DIFF_FILE_NEW;
628 if (color != DIFF_FILE_NEW) {
629 emit_line(ecbdata->file,
630 diff_get_color(ecbdata->color_diff, color),
631 reset, line, len);
632 return;
634 emit_add_line(reset, ecbdata, line, len);
637 static char *pprint_rename(const char *a, const char *b)
639 const char *old = a;
640 const char *new = b;
641 struct strbuf name;
642 int pfx_length, sfx_length;
643 int len_a = strlen(a);
644 int len_b = strlen(b);
645 int a_midlen, b_midlen;
646 int qlen_a = quote_c_style(a, NULL, NULL, 0);
647 int qlen_b = quote_c_style(b, NULL, NULL, 0);
649 strbuf_init(&name, 0);
650 if (qlen_a || qlen_b) {
651 quote_c_style(a, &name, NULL, 0);
652 strbuf_addstr(&name, " => ");
653 quote_c_style(b, &name, NULL, 0);
654 return strbuf_detach(&name, NULL);
657 /* Find common prefix */
658 pfx_length = 0;
659 while (*old && *new && *old == *new) {
660 if (*old == '/')
661 pfx_length = old - a + 1;
662 old++;
663 new++;
666 /* Find common suffix */
667 old = a + len_a;
668 new = b + len_b;
669 sfx_length = 0;
670 while (a <= old && b <= new && *old == *new) {
671 if (*old == '/')
672 sfx_length = len_a - (old - a);
673 old--;
674 new--;
678 * pfx{mid-a => mid-b}sfx
679 * {pfx-a => pfx-b}sfx
680 * pfx{sfx-a => sfx-b}
681 * name-a => name-b
683 a_midlen = len_a - pfx_length - sfx_length;
684 b_midlen = len_b - pfx_length - sfx_length;
685 if (a_midlen < 0)
686 a_midlen = 0;
687 if (b_midlen < 0)
688 b_midlen = 0;
690 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
691 if (pfx_length + sfx_length) {
692 strbuf_add(&name, a, pfx_length);
693 strbuf_addch(&name, '{');
695 strbuf_add(&name, a + pfx_length, a_midlen);
696 strbuf_addstr(&name, " => ");
697 strbuf_add(&name, b + pfx_length, b_midlen);
698 if (pfx_length + sfx_length) {
699 strbuf_addch(&name, '}');
700 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
702 return strbuf_detach(&name, NULL);
705 struct diffstat_t {
706 int nr;
707 int alloc;
708 struct diffstat_file {
709 char *from_name;
710 char *name;
711 char *print_name;
712 unsigned is_unmerged:1;
713 unsigned is_binary:1;
714 unsigned is_renamed:1;
715 unsigned int added, deleted;
716 } **files;
719 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
720 const char *name_a,
721 const char *name_b)
723 struct diffstat_file *x;
724 x = xcalloc(sizeof (*x), 1);
725 if (diffstat->nr == diffstat->alloc) {
726 diffstat->alloc = alloc_nr(diffstat->alloc);
727 diffstat->files = xrealloc(diffstat->files,
728 diffstat->alloc * sizeof(x));
730 diffstat->files[diffstat->nr++] = x;
731 if (name_b) {
732 x->from_name = xstrdup(name_a);
733 x->name = xstrdup(name_b);
734 x->is_renamed = 1;
736 else {
737 x->from_name = NULL;
738 x->name = xstrdup(name_a);
740 return x;
743 static void diffstat_consume(void *priv, char *line, unsigned long len)
745 struct diffstat_t *diffstat = priv;
746 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
748 if (line[0] == '+')
749 x->added++;
750 else if (line[0] == '-')
751 x->deleted++;
754 const char mime_boundary_leader[] = "------------";
756 static int scale_linear(int it, int width, int max_change)
759 * make sure that at least one '-' is printed if there were deletions,
760 * and likewise for '+'.
762 if (max_change < 2)
763 return it;
764 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
767 static void show_name(FILE *file,
768 const char *prefix, const char *name, int len,
769 const char *reset, const char *set)
771 fprintf(file, " %s%s%-*s%s |", set, prefix, len, name, reset);
774 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
776 if (cnt <= 0)
777 return;
778 fprintf(file, "%s", set);
779 while (cnt--)
780 putc(ch, file);
781 fprintf(file, "%s", reset);
784 static void fill_print_name(struct diffstat_file *file)
786 char *pname;
788 if (file->print_name)
789 return;
791 if (!file->is_renamed) {
792 struct strbuf buf;
793 strbuf_init(&buf, 0);
794 if (quote_c_style(file->name, &buf, NULL, 0)) {
795 pname = strbuf_detach(&buf, NULL);
796 } else {
797 pname = file->name;
798 strbuf_release(&buf);
800 } else {
801 pname = pprint_rename(file->from_name, file->name);
803 file->print_name = pname;
806 static void show_stats(struct diffstat_t* data, struct diff_options *options)
808 int i, len, add, del, total, adds = 0, dels = 0;
809 int max_change = 0, max_len = 0;
810 int total_files = data->nr;
811 int width, name_width;
812 const char *reset, *set, *add_c, *del_c;
814 if (data->nr == 0)
815 return;
817 width = options->stat_width ? options->stat_width : 80;
818 name_width = options->stat_name_width ? options->stat_name_width : 50;
820 /* Sanity: give at least 5 columns to the graph,
821 * but leave at least 10 columns for the name.
823 if (width < 25)
824 width = 25;
825 if (name_width < 10)
826 name_width = 10;
827 else if (width < name_width + 15)
828 name_width = width - 15;
830 /* Find the longest filename and max number of changes */
831 reset = diff_get_color_opt(options, DIFF_RESET);
832 set = diff_get_color_opt(options, DIFF_PLAIN);
833 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
834 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
836 for (i = 0; i < data->nr; i++) {
837 struct diffstat_file *file = data->files[i];
838 int change = file->added + file->deleted;
839 fill_print_name(file);
840 len = strlen(file->print_name);
841 if (max_len < len)
842 max_len = len;
844 if (file->is_binary || file->is_unmerged)
845 continue;
846 if (max_change < change)
847 max_change = change;
850 /* Compute the width of the graph part;
851 * 10 is for one blank at the beginning of the line plus
852 * " | count " between the name and the graph.
854 * From here on, name_width is the width of the name area,
855 * and width is the width of the graph area.
857 name_width = (name_width < max_len) ? name_width : max_len;
858 if (width < (name_width + 10) + max_change)
859 width = width - (name_width + 10);
860 else
861 width = max_change;
863 for (i = 0; i < data->nr; i++) {
864 const char *prefix = "";
865 char *name = data->files[i]->print_name;
866 int added = data->files[i]->added;
867 int deleted = data->files[i]->deleted;
868 int name_len;
871 * "scale" the filename
873 len = name_width;
874 name_len = strlen(name);
875 if (name_width < name_len) {
876 char *slash;
877 prefix = "...";
878 len -= 3;
879 name += name_len - len;
880 slash = strchr(name, '/');
881 if (slash)
882 name = slash;
885 if (data->files[i]->is_binary) {
886 show_name(options->file, prefix, name, len, reset, set);
887 fprintf(options->file, " Bin ");
888 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
889 fprintf(options->file, " -> ");
890 fprintf(options->file, "%s%d%s", add_c, added, reset);
891 fprintf(options->file, " bytes");
892 fprintf(options->file, "\n");
893 continue;
895 else if (data->files[i]->is_unmerged) {
896 show_name(options->file, prefix, name, len, reset, set);
897 fprintf(options->file, " Unmerged\n");
898 continue;
900 else if (!data->files[i]->is_renamed &&
901 (added + deleted == 0)) {
902 total_files--;
903 continue;
907 * scale the add/delete
909 add = added;
910 del = deleted;
911 total = add + del;
912 adds += add;
913 dels += del;
915 if (width <= max_change) {
916 add = scale_linear(add, width, max_change);
917 del = scale_linear(del, width, max_change);
918 total = add + del;
920 show_name(options->file, prefix, name, len, reset, set);
921 fprintf(options->file, "%5d%s", added + deleted,
922 added + deleted ? " " : "");
923 show_graph(options->file, '+', add, add_c, reset);
924 show_graph(options->file, '-', del, del_c, reset);
925 fprintf(options->file, "\n");
927 fprintf(options->file,
928 "%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
929 set, total_files, adds, dels, reset);
932 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
934 int i, adds = 0, dels = 0, total_files = data->nr;
936 if (data->nr == 0)
937 return;
939 for (i = 0; i < data->nr; i++) {
940 if (!data->files[i]->is_binary &&
941 !data->files[i]->is_unmerged) {
942 int added = data->files[i]->added;
943 int deleted= data->files[i]->deleted;
944 if (!data->files[i]->is_renamed &&
945 (added + deleted == 0)) {
946 total_files--;
947 } else {
948 adds += added;
949 dels += deleted;
953 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
954 total_files, adds, dels);
957 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
959 int i;
961 if (data->nr == 0)
962 return;
964 for (i = 0; i < data->nr; i++) {
965 struct diffstat_file *file = data->files[i];
967 if (file->is_binary)
968 fprintf(options->file, "-\t-\t");
969 else
970 fprintf(options->file,
971 "%d\t%d\t", file->added, file->deleted);
972 if (options->line_termination) {
973 fill_print_name(file);
974 if (!file->is_renamed)
975 write_name_quoted(file->name, options->file,
976 options->line_termination);
977 else {
978 fputs(file->print_name, options->file);
979 putc(options->line_termination, options->file);
981 } else {
982 if (file->is_renamed) {
983 putc('\0', options->file);
984 write_name_quoted(file->from_name, options->file, '\0');
986 write_name_quoted(file->name, options->file, '\0');
991 struct dirstat_file {
992 const char *name;
993 unsigned long changed;
996 struct dirstat_dir {
997 struct dirstat_file *files;
998 int alloc, nr, percent, cumulative;
1001 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1003 unsigned long this_dir = 0;
1004 unsigned int sources = 0;
1006 while (dir->nr) {
1007 struct dirstat_file *f = dir->files;
1008 int namelen = strlen(f->name);
1009 unsigned long this;
1010 char *slash;
1012 if (namelen < baselen)
1013 break;
1014 if (memcmp(f->name, base, baselen))
1015 break;
1016 slash = strchr(f->name + baselen, '/');
1017 if (slash) {
1018 int newbaselen = slash + 1 - f->name;
1019 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1020 sources++;
1021 } else {
1022 this = f->changed;
1023 dir->files++;
1024 dir->nr--;
1025 sources += 2;
1027 this_dir += this;
1031 * We don't report dirstat's for
1032 * - the top level
1033 * - or cases where everything came from a single directory
1034 * under this directory (sources == 1).
1036 if (baselen && sources != 1) {
1037 int permille = this_dir * 1000 / changed;
1038 if (permille) {
1039 int percent = permille / 10;
1040 if (percent >= dir->percent) {
1041 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1042 if (!dir->cumulative)
1043 return 0;
1047 return this_dir;
1050 static void show_dirstat(struct diff_options *options)
1052 int i;
1053 unsigned long changed;
1054 struct dirstat_dir dir;
1055 struct diff_queue_struct *q = &diff_queued_diff;
1057 dir.files = NULL;
1058 dir.alloc = 0;
1059 dir.nr = 0;
1060 dir.percent = options->dirstat_percent;
1061 dir.cumulative = options->output_format & DIFF_FORMAT_CUMULATIVE;
1063 changed = 0;
1064 for (i = 0; i < q->nr; i++) {
1065 struct diff_filepair *p = q->queue[i];
1066 const char *name;
1067 unsigned long copied, added, damage;
1069 name = p->one->path ? p->one->path : p->two->path;
1071 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1072 diff_populate_filespec(p->one, 0);
1073 diff_populate_filespec(p->two, 0);
1074 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1075 &copied, &added);
1076 diff_free_filespec_data(p->one);
1077 diff_free_filespec_data(p->two);
1078 } else if (DIFF_FILE_VALID(p->one)) {
1079 diff_populate_filespec(p->one, 1);
1080 copied = added = 0;
1081 diff_free_filespec_data(p->one);
1082 } else if (DIFF_FILE_VALID(p->two)) {
1083 diff_populate_filespec(p->two, 1);
1084 copied = 0;
1085 added = p->two->size;
1086 diff_free_filespec_data(p->two);
1087 } else
1088 continue;
1091 * Original minus copied is the removed material,
1092 * added is the new material. They are both damages
1093 * made to the preimage.
1095 damage = (p->one->size - copied) + added;
1097 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1098 dir.files[dir.nr].name = name;
1099 dir.files[dir.nr].changed = damage;
1100 changed += damage;
1101 dir.nr++;
1104 /* This can happen even with many files, if everything was renames */
1105 if (!changed)
1106 return;
1108 /* Show all directories with more than x% of the changes */
1109 gather_dirstat(options->file, &dir, changed, "", 0);
1112 static void free_diffstat_info(struct diffstat_t *diffstat)
1114 int i;
1115 for (i = 0; i < diffstat->nr; i++) {
1116 struct diffstat_file *f = diffstat->files[i];
1117 if (f->name != f->print_name)
1118 free(f->print_name);
1119 free(f->name);
1120 free(f->from_name);
1121 free(f);
1123 free(diffstat->files);
1126 struct checkdiff_t {
1127 const char *filename;
1128 int lineno;
1129 struct diff_options *o;
1130 unsigned ws_rule;
1131 unsigned status;
1132 int trailing_blanks_start;
1135 static int is_conflict_marker(const char *line, unsigned long len)
1137 char firstchar;
1138 int cnt;
1140 if (len < 8)
1141 return 0;
1142 firstchar = line[0];
1143 switch (firstchar) {
1144 case '=': case '>': case '<':
1145 break;
1146 default:
1147 return 0;
1149 for (cnt = 1; cnt < 7; cnt++)
1150 if (line[cnt] != firstchar)
1151 return 0;
1152 /* line[0] thru line[6] are same as firstchar */
1153 if (firstchar == '=') {
1154 /* divider between ours and theirs? */
1155 if (len != 8 || line[7] != '\n')
1156 return 0;
1157 } else if (len < 8 || !isspace(line[7])) {
1158 /* not divider before ours nor after theirs */
1159 return 0;
1161 return 1;
1164 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1166 struct checkdiff_t *data = priv;
1167 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1168 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1169 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1170 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1171 char *err;
1173 if (line[0] == '+') {
1174 unsigned bad;
1175 data->lineno++;
1176 if (!ws_blank_line(line + 1, len - 1, data->ws_rule))
1177 data->trailing_blanks_start = 0;
1178 else if (!data->trailing_blanks_start)
1179 data->trailing_blanks_start = data->lineno;
1180 if (is_conflict_marker(line + 1, len - 1)) {
1181 data->status |= 1;
1182 fprintf(data->o->file,
1183 "%s:%d: leftover conflict marker\n",
1184 data->filename, data->lineno);
1186 bad = ws_check(line + 1, len - 1, data->ws_rule);
1187 if (!bad)
1188 return;
1189 data->status |= bad;
1190 err = whitespace_error_string(bad);
1191 fprintf(data->o->file, "%s:%d: %s.\n",
1192 data->filename, data->lineno, err);
1193 free(err);
1194 emit_line(data->o->file, set, reset, line, 1);
1195 ws_check_emit(line + 1, len - 1, data->ws_rule,
1196 data->o->file, set, reset, ws);
1197 } else if (line[0] == ' ') {
1198 data->lineno++;
1199 data->trailing_blanks_start = 0;
1200 } else if (line[0] == '@') {
1201 char *plus = strchr(line, '+');
1202 if (plus)
1203 data->lineno = strtol(plus, NULL, 10) - 1;
1204 else
1205 die("invalid diff");
1206 data->trailing_blanks_start = 0;
1210 static unsigned char *deflate_it(char *data,
1211 unsigned long size,
1212 unsigned long *result_size)
1214 int bound;
1215 unsigned char *deflated;
1216 z_stream stream;
1218 memset(&stream, 0, sizeof(stream));
1219 deflateInit(&stream, zlib_compression_level);
1220 bound = deflateBound(&stream, size);
1221 deflated = xmalloc(bound);
1222 stream.next_out = deflated;
1223 stream.avail_out = bound;
1225 stream.next_in = (unsigned char *)data;
1226 stream.avail_in = size;
1227 while (deflate(&stream, Z_FINISH) == Z_OK)
1228 ; /* nothing */
1229 deflateEnd(&stream);
1230 *result_size = stream.total_out;
1231 return deflated;
1234 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1236 void *cp;
1237 void *delta;
1238 void *deflated;
1239 void *data;
1240 unsigned long orig_size;
1241 unsigned long delta_size;
1242 unsigned long deflate_size;
1243 unsigned long data_size;
1245 /* We could do deflated delta, or we could do just deflated two,
1246 * whichever is smaller.
1248 delta = NULL;
1249 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1250 if (one->size && two->size) {
1251 delta = diff_delta(one->ptr, one->size,
1252 two->ptr, two->size,
1253 &delta_size, deflate_size);
1254 if (delta) {
1255 void *to_free = delta;
1256 orig_size = delta_size;
1257 delta = deflate_it(delta, delta_size, &delta_size);
1258 free(to_free);
1262 if (delta && delta_size < deflate_size) {
1263 fprintf(file, "delta %lu\n", orig_size);
1264 free(deflated);
1265 data = delta;
1266 data_size = delta_size;
1268 else {
1269 fprintf(file, "literal %lu\n", two->size);
1270 free(delta);
1271 data = deflated;
1272 data_size = deflate_size;
1275 /* emit data encoded in base85 */
1276 cp = data;
1277 while (data_size) {
1278 int bytes = (52 < data_size) ? 52 : data_size;
1279 char line[70];
1280 data_size -= bytes;
1281 if (bytes <= 26)
1282 line[0] = bytes + 'A' - 1;
1283 else
1284 line[0] = bytes - 26 + 'a' - 1;
1285 encode_85(line + 1, cp, bytes);
1286 cp = (char *) cp + bytes;
1287 fputs(line, file);
1288 fputc('\n', file);
1290 fprintf(file, "\n");
1291 free(data);
1294 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1296 fprintf(file, "GIT binary patch\n");
1297 emit_binary_diff_body(file, one, two);
1298 emit_binary_diff_body(file, two, one);
1301 static void setup_diff_attr_check(struct git_attr_check *check)
1303 static struct git_attr *attr_diff;
1305 if (!attr_diff) {
1306 attr_diff = git_attr("diff", 4);
1308 check[0].attr = attr_diff;
1311 static void diff_filespec_check_attr(struct diff_filespec *one)
1313 struct git_attr_check attr_diff_check;
1314 int check_from_data = 0;
1316 if (one->checked_attr)
1317 return;
1319 setup_diff_attr_check(&attr_diff_check);
1320 one->is_binary = 0;
1321 one->funcname_pattern_ident = NULL;
1323 if (!git_checkattr(one->path, 1, &attr_diff_check)) {
1324 const char *value;
1326 /* binaryness */
1327 value = attr_diff_check.value;
1328 if (ATTR_TRUE(value))
1330 else if (ATTR_FALSE(value))
1331 one->is_binary = 1;
1332 else
1333 check_from_data = 1;
1335 /* funcname pattern ident */
1336 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1338 else
1339 one->funcname_pattern_ident = value;
1342 if (check_from_data) {
1343 if (!one->data && DIFF_FILE_VALID(one))
1344 diff_populate_filespec(one, 0);
1346 if (one->data)
1347 one->is_binary = buffer_is_binary(one->data, one->size);
1351 int diff_filespec_is_binary(struct diff_filespec *one)
1353 diff_filespec_check_attr(one);
1354 return one->is_binary;
1357 static const char *funcname_pattern(const char *ident)
1359 struct funcname_pattern *pp;
1361 for (pp = funcname_pattern_list; pp; pp = pp->next)
1362 if (!strcmp(ident, pp->name))
1363 return pp->pattern;
1364 return NULL;
1367 static struct builtin_funcname_pattern {
1368 const char *name;
1369 const char *pattern;
1370 } builtin_funcname_pattern[] = {
1371 { "java", "!^[ ]*\\(catch\\|do\\|for\\|if\\|instanceof\\|"
1372 "new\\|return\\|switch\\|throw\\|while\\)\n"
1373 "^[ ]*\\(\\([ ]*"
1374 "[A-Za-z_][A-Za-z_0-9]*\\)\\{2,\\}"
1375 "[ ]*([^;]*\\)$" },
1376 { "pascal", "^\\(\\(procedure\\|function\\|constructor\\|"
1377 "destructor\\|interface\\|implementation\\|"
1378 "initialization\\|finalization\\)[ \t]*.*\\)$"
1379 "\\|"
1380 "^\\(.*=[ \t]*\\(class\\|record\\).*\\)$"
1382 { "bibtex", "\\(@[a-zA-Z]\\{1,\\}[ \t]*{\\{0,1\\}[ \t]*[^ \t\"@',\\#}{~%]*\\).*$" },
1383 { "tex", "^\\(\\\\\\(\\(sub\\)*section\\|chapter\\|part\\)\\*\\{0,1\\}{.*\\)$" },
1384 { "ruby", "^\\s*\\(\\(class\\|module\\|def\\)\\s.*\\)$" },
1387 static const char *diff_funcname_pattern(struct diff_filespec *one)
1389 const char *ident, *pattern;
1390 int i;
1392 diff_filespec_check_attr(one);
1393 ident = one->funcname_pattern_ident;
1395 if (!ident)
1397 * If the config file has "funcname.default" defined, that
1398 * regexp is used; otherwise NULL is returned and xemit uses
1399 * the built-in default.
1401 return funcname_pattern("default");
1403 /* Look up custom "funcname.$ident" regexp from config. */
1404 pattern = funcname_pattern(ident);
1405 if (pattern)
1406 return pattern;
1409 * And define built-in fallback patterns here. Note that
1410 * these can be overridden by the user's config settings.
1412 for (i = 0; i < ARRAY_SIZE(builtin_funcname_pattern); i++)
1413 if (!strcmp(ident, builtin_funcname_pattern[i].name))
1414 return builtin_funcname_pattern[i].pattern;
1416 return NULL;
1419 static void builtin_diff(const char *name_a,
1420 const char *name_b,
1421 struct diff_filespec *one,
1422 struct diff_filespec *two,
1423 const char *xfrm_msg,
1424 struct diff_options *o,
1425 int complete_rewrite)
1427 mmfile_t mf1, mf2;
1428 const char *lbl[2];
1429 char *a_one, *b_two;
1430 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1431 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1433 a_one = quote_two(o->a_prefix, name_a + (*name_a == '/'));
1434 b_two = quote_two(o->b_prefix, name_b + (*name_b == '/'));
1435 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1436 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1437 fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1438 if (lbl[0][0] == '/') {
1439 /* /dev/null */
1440 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1441 if (xfrm_msg && xfrm_msg[0])
1442 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1444 else if (lbl[1][0] == '/') {
1445 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1446 if (xfrm_msg && xfrm_msg[0])
1447 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1449 else {
1450 if (one->mode != two->mode) {
1451 fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1452 fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1454 if (xfrm_msg && xfrm_msg[0])
1455 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1457 * we do not run diff between different kind
1458 * of objects.
1460 if ((one->mode ^ two->mode) & S_IFMT)
1461 goto free_ab_and_return;
1462 if (complete_rewrite) {
1463 emit_rewrite_diff(name_a, name_b, one, two, o);
1464 o->found_changes = 1;
1465 goto free_ab_and_return;
1469 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1470 die("unable to read files to diff");
1472 if (!DIFF_OPT_TST(o, TEXT) &&
1473 (diff_filespec_is_binary(one) || diff_filespec_is_binary(two))) {
1474 /* Quite common confusing case */
1475 if (mf1.size == mf2.size &&
1476 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1477 goto free_ab_and_return;
1478 if (DIFF_OPT_TST(o, BINARY))
1479 emit_binary_diff(o->file, &mf1, &mf2);
1480 else
1481 fprintf(o->file, "Binary files %s and %s differ\n",
1482 lbl[0], lbl[1]);
1483 o->found_changes = 1;
1485 else {
1486 /* Crazy xdl interfaces.. */
1487 const char *diffopts = getenv("GIT_DIFF_OPTS");
1488 xpparam_t xpp;
1489 xdemitconf_t xecfg;
1490 xdemitcb_t ecb;
1491 struct emit_callback ecbdata;
1492 const char *funcname_pattern;
1494 funcname_pattern = diff_funcname_pattern(one);
1495 if (!funcname_pattern)
1496 funcname_pattern = diff_funcname_pattern(two);
1498 memset(&xecfg, 0, sizeof(xecfg));
1499 memset(&ecbdata, 0, sizeof(ecbdata));
1500 ecbdata.label_path = lbl;
1501 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1502 ecbdata.found_changesp = &o->found_changes;
1503 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1504 ecbdata.file = o->file;
1505 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1506 xecfg.ctxlen = o->context;
1507 xecfg.flags = XDL_EMIT_FUNCNAMES;
1508 if (funcname_pattern)
1509 xdiff_set_find_func(&xecfg, funcname_pattern);
1510 if (!diffopts)
1512 else if (!prefixcmp(diffopts, "--unified="))
1513 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1514 else if (!prefixcmp(diffopts, "-u"))
1515 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1516 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1517 ecbdata.diff_words =
1518 xcalloc(1, sizeof(struct diff_words_data));
1519 ecbdata.diff_words->file = o->file;
1521 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1522 &xpp, &xecfg, &ecb);
1523 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1524 free_diff_words_data(&ecbdata);
1527 free_ab_and_return:
1528 diff_free_filespec_data(one);
1529 diff_free_filespec_data(two);
1530 free(a_one);
1531 free(b_two);
1532 return;
1535 static void builtin_diffstat(const char *name_a, const char *name_b,
1536 struct diff_filespec *one,
1537 struct diff_filespec *two,
1538 struct diffstat_t *diffstat,
1539 struct diff_options *o,
1540 int complete_rewrite)
1542 mmfile_t mf1, mf2;
1543 struct diffstat_file *data;
1545 data = diffstat_add(diffstat, name_a, name_b);
1547 if (!one || !two) {
1548 data->is_unmerged = 1;
1549 return;
1551 if (complete_rewrite) {
1552 diff_populate_filespec(one, 0);
1553 diff_populate_filespec(two, 0);
1554 data->deleted = count_lines(one->data, one->size);
1555 data->added = count_lines(two->data, two->size);
1556 goto free_and_return;
1558 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1559 die("unable to read files to diff");
1561 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1562 data->is_binary = 1;
1563 data->added = mf2.size;
1564 data->deleted = mf1.size;
1565 } else {
1566 /* Crazy xdl interfaces.. */
1567 xpparam_t xpp;
1568 xdemitconf_t xecfg;
1569 xdemitcb_t ecb;
1571 memset(&xecfg, 0, sizeof(xecfg));
1572 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1573 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1574 &xpp, &xecfg, &ecb);
1577 free_and_return:
1578 diff_free_filespec_data(one);
1579 diff_free_filespec_data(two);
1582 static void builtin_checkdiff(const char *name_a, const char *name_b,
1583 const char *attr_path,
1584 struct diff_filespec *one,
1585 struct diff_filespec *two,
1586 struct diff_options *o)
1588 mmfile_t mf1, mf2;
1589 struct checkdiff_t data;
1591 if (!two)
1592 return;
1594 memset(&data, 0, sizeof(data));
1595 data.filename = name_b ? name_b : name_a;
1596 data.lineno = 0;
1597 data.o = o;
1598 data.ws_rule = whitespace_rule(attr_path);
1600 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1601 die("unable to read files to diff");
1604 * All the other codepaths check both sides, but not checking
1605 * the "old" side here is deliberate. We are checking the newly
1606 * introduced changes, and as long as the "new" side is text, we
1607 * can and should check what it introduces.
1609 if (diff_filespec_is_binary(two))
1610 goto free_and_return;
1611 else {
1612 /* Crazy xdl interfaces.. */
1613 xpparam_t xpp;
1614 xdemitconf_t xecfg;
1615 xdemitcb_t ecb;
1617 memset(&xecfg, 0, sizeof(xecfg));
1618 xpp.flags = XDF_NEED_MINIMAL;
1619 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1620 &xpp, &xecfg, &ecb);
1622 if ((data.ws_rule & WS_TRAILING_SPACE) &&
1623 data.trailing_blanks_start) {
1624 fprintf(o->file, "%s:%d: ends with blank lines.\n",
1625 data.filename, data.trailing_blanks_start);
1626 data.status = 1; /* report errors */
1629 free_and_return:
1630 diff_free_filespec_data(one);
1631 diff_free_filespec_data(two);
1632 if (data.status)
1633 DIFF_OPT_SET(o, CHECK_FAILED);
1636 struct diff_filespec *alloc_filespec(const char *path)
1638 int namelen = strlen(path);
1639 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1641 memset(spec, 0, sizeof(*spec));
1642 spec->path = (char *)(spec + 1);
1643 memcpy(spec->path, path, namelen+1);
1644 spec->count = 1;
1645 return spec;
1648 void free_filespec(struct diff_filespec *spec)
1650 if (!--spec->count) {
1651 diff_free_filespec_data(spec);
1652 free(spec);
1656 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1657 unsigned short mode)
1659 if (mode) {
1660 spec->mode = canon_mode(mode);
1661 hashcpy(spec->sha1, sha1);
1662 spec->sha1_valid = !is_null_sha1(sha1);
1667 * Given a name and sha1 pair, if the index tells us the file in
1668 * the work tree has that object contents, return true, so that
1669 * prepare_temp_file() does not have to inflate and extract.
1671 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1673 struct cache_entry *ce;
1674 struct stat st;
1675 int pos, len;
1677 /* We do not read the cache ourselves here, because the
1678 * benchmark with my previous version that always reads cache
1679 * shows that it makes things worse for diff-tree comparing
1680 * two linux-2.6 kernel trees in an already checked out work
1681 * tree. This is because most diff-tree comparisons deal with
1682 * only a small number of files, while reading the cache is
1683 * expensive for a large project, and its cost outweighs the
1684 * savings we get by not inflating the object to a temporary
1685 * file. Practically, this code only helps when we are used
1686 * by diff-cache --cached, which does read the cache before
1687 * calling us.
1689 if (!active_cache)
1690 return 0;
1692 /* We want to avoid the working directory if our caller
1693 * doesn't need the data in a normal file, this system
1694 * is rather slow with its stat/open/mmap/close syscalls,
1695 * and the object is contained in a pack file. The pack
1696 * is probably already open and will be faster to obtain
1697 * the data through than the working directory. Loose
1698 * objects however would tend to be slower as they need
1699 * to be individually opened and inflated.
1701 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1702 return 0;
1704 len = strlen(name);
1705 pos = cache_name_pos(name, len);
1706 if (pos < 0)
1707 return 0;
1708 ce = active_cache[pos];
1711 * This is not the sha1 we are looking for, or
1712 * unreusable because it is not a regular file.
1714 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1715 return 0;
1718 * If ce matches the file in the work tree, we can reuse it.
1720 if (ce_uptodate(ce) ||
1721 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1722 return 1;
1724 return 0;
1727 static int populate_from_stdin(struct diff_filespec *s)
1729 struct strbuf buf;
1730 size_t size = 0;
1732 strbuf_init(&buf, 0);
1733 if (strbuf_read(&buf, 0, 0) < 0)
1734 return error("error while reading from stdin %s",
1735 strerror(errno));
1737 s->should_munmap = 0;
1738 s->data = strbuf_detach(&buf, &size);
1739 s->size = size;
1740 s->should_free = 1;
1741 return 0;
1744 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1746 int len;
1747 char *data = xmalloc(100);
1748 len = snprintf(data, 100,
1749 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1750 s->data = data;
1751 s->size = len;
1752 s->should_free = 1;
1753 if (size_only) {
1754 s->data = NULL;
1755 free(data);
1757 return 0;
1761 * While doing rename detection and pickaxe operation, we may need to
1762 * grab the data for the blob (or file) for our own in-core comparison.
1763 * diff_filespec has data and size fields for this purpose.
1765 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1767 int err = 0;
1768 if (!DIFF_FILE_VALID(s))
1769 die("internal error: asking to populate invalid file.");
1770 if (S_ISDIR(s->mode))
1771 return -1;
1773 if (s->data)
1774 return 0;
1776 if (size_only && 0 < s->size)
1777 return 0;
1779 if (S_ISGITLINK(s->mode))
1780 return diff_populate_gitlink(s, size_only);
1782 if (!s->sha1_valid ||
1783 reuse_worktree_file(s->path, s->sha1, 0)) {
1784 struct strbuf buf;
1785 struct stat st;
1786 int fd;
1788 if (!strcmp(s->path, "-"))
1789 return populate_from_stdin(s);
1791 if (lstat(s->path, &st) < 0) {
1792 if (errno == ENOENT) {
1793 err_empty:
1794 err = -1;
1795 empty:
1796 s->data = (char *)"";
1797 s->size = 0;
1798 return err;
1801 s->size = xsize_t(st.st_size);
1802 if (!s->size)
1803 goto empty;
1804 if (size_only)
1805 return 0;
1806 if (S_ISLNK(st.st_mode)) {
1807 int ret;
1808 s->data = xmalloc(s->size);
1809 s->should_free = 1;
1810 ret = readlink(s->path, s->data, s->size);
1811 if (ret < 0) {
1812 free(s->data);
1813 goto err_empty;
1815 return 0;
1817 fd = open(s->path, O_RDONLY);
1818 if (fd < 0)
1819 goto err_empty;
1820 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1821 close(fd);
1822 s->should_munmap = 1;
1825 * Convert from working tree format to canonical git format
1827 strbuf_init(&buf, 0);
1828 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
1829 size_t size = 0;
1830 munmap(s->data, s->size);
1831 s->should_munmap = 0;
1832 s->data = strbuf_detach(&buf, &size);
1833 s->size = size;
1834 s->should_free = 1;
1837 else {
1838 enum object_type type;
1839 if (size_only)
1840 type = sha1_object_info(s->sha1, &s->size);
1841 else {
1842 s->data = read_sha1_file(s->sha1, &type, &s->size);
1843 s->should_free = 1;
1846 return 0;
1849 void diff_free_filespec_blob(struct diff_filespec *s)
1851 if (s->should_free)
1852 free(s->data);
1853 else if (s->should_munmap)
1854 munmap(s->data, s->size);
1856 if (s->should_free || s->should_munmap) {
1857 s->should_free = s->should_munmap = 0;
1858 s->data = NULL;
1862 void diff_free_filespec_data(struct diff_filespec *s)
1864 diff_free_filespec_blob(s);
1865 free(s->cnt_data);
1866 s->cnt_data = NULL;
1869 static void prep_temp_blob(struct diff_tempfile *temp,
1870 void *blob,
1871 unsigned long size,
1872 const unsigned char *sha1,
1873 int mode)
1875 int fd;
1877 fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1878 if (fd < 0)
1879 die("unable to create temp-file: %s", strerror(errno));
1880 if (write_in_full(fd, blob, size) != size)
1881 die("unable to write temp-file");
1882 close(fd);
1883 temp->name = temp->tmp_path;
1884 strcpy(temp->hex, sha1_to_hex(sha1));
1885 temp->hex[40] = 0;
1886 sprintf(temp->mode, "%06o", mode);
1889 static void prepare_temp_file(const char *name,
1890 struct diff_tempfile *temp,
1891 struct diff_filespec *one)
1893 if (!DIFF_FILE_VALID(one)) {
1894 not_a_valid_file:
1895 /* A '-' entry produces this for file-2, and
1896 * a '+' entry produces this for file-1.
1898 temp->name = "/dev/null";
1899 strcpy(temp->hex, ".");
1900 strcpy(temp->mode, ".");
1901 return;
1904 if (!one->sha1_valid ||
1905 reuse_worktree_file(name, one->sha1, 1)) {
1906 struct stat st;
1907 if (lstat(name, &st) < 0) {
1908 if (errno == ENOENT)
1909 goto not_a_valid_file;
1910 die("stat(%s): %s", name, strerror(errno));
1912 if (S_ISLNK(st.st_mode)) {
1913 int ret;
1914 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1915 size_t sz = xsize_t(st.st_size);
1916 if (sizeof(buf) <= st.st_size)
1917 die("symlink too long: %s", name);
1918 ret = readlink(name, buf, sz);
1919 if (ret < 0)
1920 die("readlink(%s)", name);
1921 prep_temp_blob(temp, buf, sz,
1922 (one->sha1_valid ?
1923 one->sha1 : null_sha1),
1924 (one->sha1_valid ?
1925 one->mode : S_IFLNK));
1927 else {
1928 /* we can borrow from the file in the work tree */
1929 temp->name = name;
1930 if (!one->sha1_valid)
1931 strcpy(temp->hex, sha1_to_hex(null_sha1));
1932 else
1933 strcpy(temp->hex, sha1_to_hex(one->sha1));
1934 /* Even though we may sometimes borrow the
1935 * contents from the work tree, we always want
1936 * one->mode. mode is trustworthy even when
1937 * !(one->sha1_valid), as long as
1938 * DIFF_FILE_VALID(one).
1940 sprintf(temp->mode, "%06o", one->mode);
1942 return;
1944 else {
1945 if (diff_populate_filespec(one, 0))
1946 die("cannot read data blob for %s", one->path);
1947 prep_temp_blob(temp, one->data, one->size,
1948 one->sha1, one->mode);
1952 static void remove_tempfile(void)
1954 int i;
1956 for (i = 0; i < 2; i++)
1957 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1958 unlink(diff_temp[i].name);
1959 diff_temp[i].name = NULL;
1963 static void remove_tempfile_on_signal(int signo)
1965 remove_tempfile();
1966 signal(SIGINT, SIG_DFL);
1967 raise(signo);
1970 /* An external diff command takes:
1972 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1973 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1976 static void run_external_diff(const char *pgm,
1977 const char *name,
1978 const char *other,
1979 struct diff_filespec *one,
1980 struct diff_filespec *two,
1981 const char *xfrm_msg,
1982 int complete_rewrite)
1984 const char *spawn_arg[10];
1985 struct diff_tempfile *temp = diff_temp;
1986 int retval;
1987 static int atexit_asked = 0;
1988 const char *othername;
1989 const char **arg = &spawn_arg[0];
1991 othername = (other? other : name);
1992 if (one && two) {
1993 prepare_temp_file(name, &temp[0], one);
1994 prepare_temp_file(othername, &temp[1], two);
1995 if (! atexit_asked &&
1996 (temp[0].name == temp[0].tmp_path ||
1997 temp[1].name == temp[1].tmp_path)) {
1998 atexit_asked = 1;
1999 atexit(remove_tempfile);
2001 signal(SIGINT, remove_tempfile_on_signal);
2004 if (one && two) {
2005 *arg++ = pgm;
2006 *arg++ = name;
2007 *arg++ = temp[0].name;
2008 *arg++ = temp[0].hex;
2009 *arg++ = temp[0].mode;
2010 *arg++ = temp[1].name;
2011 *arg++ = temp[1].hex;
2012 *arg++ = temp[1].mode;
2013 if (other) {
2014 *arg++ = other;
2015 *arg++ = xfrm_msg;
2017 } else {
2018 *arg++ = pgm;
2019 *arg++ = name;
2021 *arg = NULL;
2022 fflush(NULL);
2023 retval = run_command_v_opt(spawn_arg, 0);
2024 remove_tempfile();
2025 if (retval) {
2026 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2027 exit(1);
2031 static const char *external_diff_attr(const char *name)
2033 struct git_attr_check attr_diff_check;
2035 if (!name)
2036 return NULL;
2038 setup_diff_attr_check(&attr_diff_check);
2039 if (!git_checkattr(name, 1, &attr_diff_check)) {
2040 const char *value = attr_diff_check.value;
2041 if (!ATTR_TRUE(value) &&
2042 !ATTR_FALSE(value) &&
2043 !ATTR_UNSET(value)) {
2044 struct ll_diff_driver *drv;
2046 for (drv = user_diff; drv; drv = drv->next)
2047 if (!strcmp(drv->name, value))
2048 return drv->cmd;
2051 return NULL;
2054 static void run_diff_cmd(const char *pgm,
2055 const char *name,
2056 const char *other,
2057 const char *attr_path,
2058 struct diff_filespec *one,
2059 struct diff_filespec *two,
2060 const char *xfrm_msg,
2061 struct diff_options *o,
2062 int complete_rewrite)
2064 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2065 pgm = NULL;
2066 else {
2067 const char *cmd = external_diff_attr(attr_path);
2068 if (cmd)
2069 pgm = cmd;
2072 if (pgm) {
2073 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2074 complete_rewrite);
2075 return;
2077 if (one && two)
2078 builtin_diff(name, other ? other : name,
2079 one, two, xfrm_msg, o, complete_rewrite);
2080 else
2081 fprintf(o->file, "* Unmerged path %s\n", name);
2084 static void diff_fill_sha1_info(struct diff_filespec *one)
2086 if (DIFF_FILE_VALID(one)) {
2087 if (!one->sha1_valid) {
2088 struct stat st;
2089 if (!strcmp(one->path, "-")) {
2090 hashcpy(one->sha1, null_sha1);
2091 return;
2093 if (lstat(one->path, &st) < 0)
2094 die("stat %s", one->path);
2095 if (index_path(one->sha1, one->path, &st, 0))
2096 die("cannot hash %s\n", one->path);
2099 else
2100 hashclr(one->sha1);
2103 static int similarity_index(struct diff_filepair *p)
2105 return p->score * 100 / MAX_SCORE;
2108 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2110 /* Strip the prefix but do not molest /dev/null and absolute paths */
2111 if (*namep && **namep != '/')
2112 *namep += prefix_length;
2113 if (*otherp && **otherp != '/')
2114 *otherp += prefix_length;
2117 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2119 const char *pgm = external_diff();
2120 struct strbuf msg;
2121 char *xfrm_msg;
2122 struct diff_filespec *one = p->one;
2123 struct diff_filespec *two = p->two;
2124 const char *name;
2125 const char *other;
2126 const char *attr_path;
2127 int complete_rewrite = 0;
2129 name = p->one->path;
2130 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2131 attr_path = name;
2132 if (o->prefix_length)
2133 strip_prefix(o->prefix_length, &name, &other);
2135 if (DIFF_PAIR_UNMERGED(p)) {
2136 run_diff_cmd(pgm, name, NULL, attr_path,
2137 NULL, NULL, NULL, o, 0);
2138 return;
2141 diff_fill_sha1_info(one);
2142 diff_fill_sha1_info(two);
2144 strbuf_init(&msg, PATH_MAX * 2 + 300);
2145 switch (p->status) {
2146 case DIFF_STATUS_COPIED:
2147 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2148 strbuf_addstr(&msg, "\ncopy from ");
2149 quote_c_style(name, &msg, NULL, 0);
2150 strbuf_addstr(&msg, "\ncopy to ");
2151 quote_c_style(other, &msg, NULL, 0);
2152 strbuf_addch(&msg, '\n');
2153 break;
2154 case DIFF_STATUS_RENAMED:
2155 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2156 strbuf_addstr(&msg, "\nrename from ");
2157 quote_c_style(name, &msg, NULL, 0);
2158 strbuf_addstr(&msg, "\nrename to ");
2159 quote_c_style(other, &msg, NULL, 0);
2160 strbuf_addch(&msg, '\n');
2161 break;
2162 case DIFF_STATUS_MODIFIED:
2163 if (p->score) {
2164 strbuf_addf(&msg, "dissimilarity index %d%%\n",
2165 similarity_index(p));
2166 complete_rewrite = 1;
2167 break;
2169 /* fallthru */
2170 default:
2171 /* nothing */
2175 if (hashcmp(one->sha1, two->sha1)) {
2176 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2178 if (DIFF_OPT_TST(o, BINARY)) {
2179 mmfile_t mf;
2180 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2181 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2182 abbrev = 40;
2184 strbuf_addf(&msg, "index %.*s..%.*s",
2185 abbrev, sha1_to_hex(one->sha1),
2186 abbrev, sha1_to_hex(two->sha1));
2187 if (one->mode == two->mode)
2188 strbuf_addf(&msg, " %06o", one->mode);
2189 strbuf_addch(&msg, '\n');
2192 if (msg.len)
2193 strbuf_setlen(&msg, msg.len - 1);
2194 xfrm_msg = msg.len ? msg.buf : NULL;
2196 if (!pgm &&
2197 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2198 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2199 /* a filepair that changes between file and symlink
2200 * needs to be split into deletion and creation.
2202 struct diff_filespec *null = alloc_filespec(two->path);
2203 run_diff_cmd(NULL, name, other, attr_path,
2204 one, null, xfrm_msg, o, 0);
2205 free(null);
2206 null = alloc_filespec(one->path);
2207 run_diff_cmd(NULL, name, other, attr_path,
2208 null, two, xfrm_msg, o, 0);
2209 free(null);
2211 else
2212 run_diff_cmd(pgm, name, other, attr_path,
2213 one, two, xfrm_msg, o, complete_rewrite);
2215 strbuf_release(&msg);
2218 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2219 struct diffstat_t *diffstat)
2221 const char *name;
2222 const char *other;
2223 int complete_rewrite = 0;
2225 if (DIFF_PAIR_UNMERGED(p)) {
2226 /* unmerged */
2227 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2228 return;
2231 name = p->one->path;
2232 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2234 if (o->prefix_length)
2235 strip_prefix(o->prefix_length, &name, &other);
2237 diff_fill_sha1_info(p->one);
2238 diff_fill_sha1_info(p->two);
2240 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2241 complete_rewrite = 1;
2242 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2245 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2247 const char *name;
2248 const char *other;
2249 const char *attr_path;
2251 if (DIFF_PAIR_UNMERGED(p)) {
2252 /* unmerged */
2253 return;
2256 name = p->one->path;
2257 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2258 attr_path = other ? other : name;
2260 if (o->prefix_length)
2261 strip_prefix(o->prefix_length, &name, &other);
2263 diff_fill_sha1_info(p->one);
2264 diff_fill_sha1_info(p->two);
2266 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2269 void diff_setup(struct diff_options *options)
2271 memset(options, 0, sizeof(*options));
2273 options->file = stdout;
2275 options->line_termination = '\n';
2276 options->break_opt = -1;
2277 options->rename_limit = -1;
2278 options->dirstat_percent = 3;
2279 options->context = 3;
2281 options->change = diff_change;
2282 options->add_remove = diff_addremove;
2283 if (diff_use_color_default > 0)
2284 DIFF_OPT_SET(options, COLOR_DIFF);
2285 else
2286 DIFF_OPT_CLR(options, COLOR_DIFF);
2287 options->detect_rename = diff_detect_rename_default;
2289 options->a_prefix = "a/";
2290 options->b_prefix = "b/";
2293 int diff_setup_done(struct diff_options *options)
2295 int count = 0;
2297 if (options->output_format & DIFF_FORMAT_NAME)
2298 count++;
2299 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2300 count++;
2301 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2302 count++;
2303 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2304 count++;
2305 if (count > 1)
2306 die("--name-only, --name-status, --check and -s are mutually exclusive");
2308 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2309 options->detect_rename = DIFF_DETECT_COPY;
2311 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2312 options->prefix = NULL;
2313 if (options->prefix)
2314 options->prefix_length = strlen(options->prefix);
2315 else
2316 options->prefix_length = 0;
2318 if (options->output_format & (DIFF_FORMAT_NAME |
2319 DIFF_FORMAT_NAME_STATUS |
2320 DIFF_FORMAT_CHECKDIFF |
2321 DIFF_FORMAT_NO_OUTPUT))
2322 options->output_format &= ~(DIFF_FORMAT_RAW |
2323 DIFF_FORMAT_NUMSTAT |
2324 DIFF_FORMAT_DIFFSTAT |
2325 DIFF_FORMAT_SHORTSTAT |
2326 DIFF_FORMAT_DIRSTAT |
2327 DIFF_FORMAT_SUMMARY |
2328 DIFF_FORMAT_PATCH);
2331 * These cases always need recursive; we do not drop caller-supplied
2332 * recursive bits for other formats here.
2334 if (options->output_format & (DIFF_FORMAT_PATCH |
2335 DIFF_FORMAT_NUMSTAT |
2336 DIFF_FORMAT_DIFFSTAT |
2337 DIFF_FORMAT_SHORTSTAT |
2338 DIFF_FORMAT_DIRSTAT |
2339 DIFF_FORMAT_SUMMARY |
2340 DIFF_FORMAT_CHECKDIFF))
2341 DIFF_OPT_SET(options, RECURSIVE);
2343 * Also pickaxe would not work very well if you do not say recursive
2345 if (options->pickaxe)
2346 DIFF_OPT_SET(options, RECURSIVE);
2348 if (options->detect_rename && options->rename_limit < 0)
2349 options->rename_limit = diff_rename_limit_default;
2350 if (options->setup & DIFF_SETUP_USE_CACHE) {
2351 if (!active_cache)
2352 /* read-cache does not die even when it fails
2353 * so it is safe for us to do this here. Also
2354 * it does not smudge active_cache or active_nr
2355 * when it fails, so we do not have to worry about
2356 * cleaning it up ourselves either.
2358 read_cache();
2360 if (options->abbrev <= 0 || 40 < options->abbrev)
2361 options->abbrev = 40; /* full */
2364 * It does not make sense to show the first hit we happened
2365 * to have found. It does not make sense not to return with
2366 * exit code in such a case either.
2368 if (DIFF_OPT_TST(options, QUIET)) {
2369 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2370 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2374 * If we postprocess in diffcore, we cannot simply return
2375 * upon the first hit. We need to run diff as usual.
2377 if (options->pickaxe || options->filter)
2378 DIFF_OPT_CLR(options, QUIET);
2380 return 0;
2383 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2385 char c, *eq;
2386 int len;
2388 if (*arg != '-')
2389 return 0;
2390 c = *++arg;
2391 if (!c)
2392 return 0;
2393 if (c == arg_short) {
2394 c = *++arg;
2395 if (!c)
2396 return 1;
2397 if (val && isdigit(c)) {
2398 char *end;
2399 int n = strtoul(arg, &end, 10);
2400 if (*end)
2401 return 0;
2402 *val = n;
2403 return 1;
2405 return 0;
2407 if (c != '-')
2408 return 0;
2409 arg++;
2410 eq = strchr(arg, '=');
2411 if (eq)
2412 len = eq - arg;
2413 else
2414 len = strlen(arg);
2415 if (!len || strncmp(arg, arg_long, len))
2416 return 0;
2417 if (eq) {
2418 int n;
2419 char *end;
2420 if (!isdigit(*++eq))
2421 return 0;
2422 n = strtoul(eq, &end, 10);
2423 if (*end)
2424 return 0;
2425 *val = n;
2427 return 1;
2430 static int diff_scoreopt_parse(const char *opt);
2432 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2434 const char *arg = av[0];
2436 /* Output format options */
2437 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2438 options->output_format |= DIFF_FORMAT_PATCH;
2439 else if (opt_arg(arg, 'U', "unified", &options->context))
2440 options->output_format |= DIFF_FORMAT_PATCH;
2441 else if (!strcmp(arg, "--raw"))
2442 options->output_format |= DIFF_FORMAT_RAW;
2443 else if (!strcmp(arg, "--patch-with-raw"))
2444 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2445 else if (!strcmp(arg, "--numstat"))
2446 options->output_format |= DIFF_FORMAT_NUMSTAT;
2447 else if (!strcmp(arg, "--shortstat"))
2448 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2449 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2450 options->output_format |= DIFF_FORMAT_DIRSTAT;
2451 else if (!strcmp(arg, "--cumulative"))
2452 options->output_format |= DIFF_FORMAT_CUMULATIVE;
2453 else if (!strcmp(arg, "--check"))
2454 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2455 else if (!strcmp(arg, "--summary"))
2456 options->output_format |= DIFF_FORMAT_SUMMARY;
2457 else if (!strcmp(arg, "--patch-with-stat"))
2458 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2459 else if (!strcmp(arg, "--name-only"))
2460 options->output_format |= DIFF_FORMAT_NAME;
2461 else if (!strcmp(arg, "--name-status"))
2462 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2463 else if (!strcmp(arg, "-s"))
2464 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2465 else if (!prefixcmp(arg, "--stat")) {
2466 char *end;
2467 int width = options->stat_width;
2468 int name_width = options->stat_name_width;
2469 arg += 6;
2470 end = (char *)arg;
2472 switch (*arg) {
2473 case '-':
2474 if (!prefixcmp(arg, "-width="))
2475 width = strtoul(arg + 7, &end, 10);
2476 else if (!prefixcmp(arg, "-name-width="))
2477 name_width = strtoul(arg + 12, &end, 10);
2478 break;
2479 case '=':
2480 width = strtoul(arg+1, &end, 10);
2481 if (*end == ',')
2482 name_width = strtoul(end+1, &end, 10);
2485 /* Important! This checks all the error cases! */
2486 if (*end)
2487 return 0;
2488 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2489 options->stat_name_width = name_width;
2490 options->stat_width = width;
2493 /* renames options */
2494 else if (!prefixcmp(arg, "-B")) {
2495 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2496 return -1;
2498 else if (!prefixcmp(arg, "-M")) {
2499 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2500 return -1;
2501 options->detect_rename = DIFF_DETECT_RENAME;
2503 else if (!prefixcmp(arg, "-C")) {
2504 if (options->detect_rename == DIFF_DETECT_COPY)
2505 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2506 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2507 return -1;
2508 options->detect_rename = DIFF_DETECT_COPY;
2510 else if (!strcmp(arg, "--no-renames"))
2511 options->detect_rename = 0;
2512 else if (!strcmp(arg, "--relative"))
2513 DIFF_OPT_SET(options, RELATIVE_NAME);
2514 else if (!prefixcmp(arg, "--relative=")) {
2515 DIFF_OPT_SET(options, RELATIVE_NAME);
2516 options->prefix = arg + 11;
2519 /* xdiff options */
2520 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2521 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2522 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2523 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2524 else if (!strcmp(arg, "--ignore-space-at-eol"))
2525 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2527 /* flags options */
2528 else if (!strcmp(arg, "--binary")) {
2529 options->output_format |= DIFF_FORMAT_PATCH;
2530 DIFF_OPT_SET(options, BINARY);
2532 else if (!strcmp(arg, "--full-index"))
2533 DIFF_OPT_SET(options, FULL_INDEX);
2534 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2535 DIFF_OPT_SET(options, TEXT);
2536 else if (!strcmp(arg, "-R"))
2537 DIFF_OPT_SET(options, REVERSE_DIFF);
2538 else if (!strcmp(arg, "--find-copies-harder"))
2539 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2540 else if (!strcmp(arg, "--follow"))
2541 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2542 else if (!strcmp(arg, "--color"))
2543 DIFF_OPT_SET(options, COLOR_DIFF);
2544 else if (!strcmp(arg, "--no-color"))
2545 DIFF_OPT_CLR(options, COLOR_DIFF);
2546 else if (!strcmp(arg, "--color-words"))
2547 options->flags |= DIFF_OPT_COLOR_DIFF | DIFF_OPT_COLOR_DIFF_WORDS;
2548 else if (!strcmp(arg, "--exit-code"))
2549 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2550 else if (!strcmp(arg, "--quiet"))
2551 DIFF_OPT_SET(options, QUIET);
2552 else if (!strcmp(arg, "--ext-diff"))
2553 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2554 else if (!strcmp(arg, "--no-ext-diff"))
2555 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2556 else if (!strcmp(arg, "--ignore-submodules"))
2557 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2559 /* misc options */
2560 else if (!strcmp(arg, "-z"))
2561 options->line_termination = 0;
2562 else if (!prefixcmp(arg, "-l"))
2563 options->rename_limit = strtoul(arg+2, NULL, 10);
2564 else if (!prefixcmp(arg, "-S"))
2565 options->pickaxe = arg + 2;
2566 else if (!strcmp(arg, "--pickaxe-all"))
2567 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2568 else if (!strcmp(arg, "--pickaxe-regex"))
2569 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2570 else if (!prefixcmp(arg, "-O"))
2571 options->orderfile = arg + 2;
2572 else if (!prefixcmp(arg, "--diff-filter="))
2573 options->filter = arg + 14;
2574 else if (!strcmp(arg, "--abbrev"))
2575 options->abbrev = DEFAULT_ABBREV;
2576 else if (!prefixcmp(arg, "--abbrev=")) {
2577 options->abbrev = strtoul(arg + 9, NULL, 10);
2578 if (options->abbrev < MINIMUM_ABBREV)
2579 options->abbrev = MINIMUM_ABBREV;
2580 else if (40 < options->abbrev)
2581 options->abbrev = 40;
2583 else if (!prefixcmp(arg, "--src-prefix="))
2584 options->a_prefix = arg + 13;
2585 else if (!prefixcmp(arg, "--dst-prefix="))
2586 options->b_prefix = arg + 13;
2587 else if (!strcmp(arg, "--no-prefix"))
2588 options->a_prefix = options->b_prefix = "";
2589 else if (!prefixcmp(arg, "--output=")) {
2590 options->file = fopen(arg + strlen("--output="), "w");
2591 options->close_file = 1;
2592 } else
2593 return 0;
2594 return 1;
2597 static int parse_num(const char **cp_p)
2599 unsigned long num, scale;
2600 int ch, dot;
2601 const char *cp = *cp_p;
2603 num = 0;
2604 scale = 1;
2605 dot = 0;
2606 for(;;) {
2607 ch = *cp;
2608 if ( !dot && ch == '.' ) {
2609 scale = 1;
2610 dot = 1;
2611 } else if ( ch == '%' ) {
2612 scale = dot ? scale*100 : 100;
2613 cp++; /* % is always at the end */
2614 break;
2615 } else if ( ch >= '0' && ch <= '9' ) {
2616 if ( scale < 100000 ) {
2617 scale *= 10;
2618 num = (num*10) + (ch-'0');
2620 } else {
2621 break;
2623 cp++;
2625 *cp_p = cp;
2627 /* user says num divided by scale and we say internally that
2628 * is MAX_SCORE * num / scale.
2630 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2633 static int diff_scoreopt_parse(const char *opt)
2635 int opt1, opt2, cmd;
2637 if (*opt++ != '-')
2638 return -1;
2639 cmd = *opt++;
2640 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2641 return -1; /* that is not a -M, -C nor -B option */
2643 opt1 = parse_num(&opt);
2644 if (cmd != 'B')
2645 opt2 = 0;
2646 else {
2647 if (*opt == 0)
2648 opt2 = 0;
2649 else if (*opt != '/')
2650 return -1; /* we expect -B80/99 or -B80 */
2651 else {
2652 opt++;
2653 opt2 = parse_num(&opt);
2656 if (*opt != 0)
2657 return -1;
2658 return opt1 | (opt2 << 16);
2661 struct diff_queue_struct diff_queued_diff;
2663 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2665 if (queue->alloc <= queue->nr) {
2666 queue->alloc = alloc_nr(queue->alloc);
2667 queue->queue = xrealloc(queue->queue,
2668 sizeof(dp) * queue->alloc);
2670 queue->queue[queue->nr++] = dp;
2673 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2674 struct diff_filespec *one,
2675 struct diff_filespec *two)
2677 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2678 dp->one = one;
2679 dp->two = two;
2680 if (queue)
2681 diff_q(queue, dp);
2682 return dp;
2685 void diff_free_filepair(struct diff_filepair *p)
2687 free_filespec(p->one);
2688 free_filespec(p->two);
2689 free(p);
2692 /* This is different from find_unique_abbrev() in that
2693 * it stuffs the result with dots for alignment.
2695 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2697 int abblen;
2698 const char *abbrev;
2699 if (len == 40)
2700 return sha1_to_hex(sha1);
2702 abbrev = find_unique_abbrev(sha1, len);
2703 abblen = strlen(abbrev);
2704 if (abblen < 37) {
2705 static char hex[41];
2706 if (len < abblen && abblen <= len + 2)
2707 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2708 else
2709 sprintf(hex, "%s...", abbrev);
2710 return hex;
2712 return sha1_to_hex(sha1);
2715 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2717 int line_termination = opt->line_termination;
2718 int inter_name_termination = line_termination ? '\t' : '\0';
2720 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2721 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2722 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2723 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2725 if (p->score) {
2726 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2727 inter_name_termination);
2728 } else {
2729 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2732 if (p->status == DIFF_STATUS_COPIED ||
2733 p->status == DIFF_STATUS_RENAMED) {
2734 const char *name_a, *name_b;
2735 name_a = p->one->path;
2736 name_b = p->two->path;
2737 strip_prefix(opt->prefix_length, &name_a, &name_b);
2738 write_name_quoted(name_a, opt->file, inter_name_termination);
2739 write_name_quoted(name_b, opt->file, line_termination);
2740 } else {
2741 const char *name_a, *name_b;
2742 name_a = p->one->mode ? p->one->path : p->two->path;
2743 name_b = NULL;
2744 strip_prefix(opt->prefix_length, &name_a, &name_b);
2745 write_name_quoted(name_a, opt->file, line_termination);
2749 int diff_unmodified_pair(struct diff_filepair *p)
2751 /* This function is written stricter than necessary to support
2752 * the currently implemented transformers, but the idea is to
2753 * let transformers to produce diff_filepairs any way they want,
2754 * and filter and clean them up here before producing the output.
2756 struct diff_filespec *one = p->one, *two = p->two;
2758 if (DIFF_PAIR_UNMERGED(p))
2759 return 0; /* unmerged is interesting */
2761 /* deletion, addition, mode or type change
2762 * and rename are all interesting.
2764 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2765 DIFF_PAIR_MODE_CHANGED(p) ||
2766 strcmp(one->path, two->path))
2767 return 0;
2769 /* both are valid and point at the same path. that is, we are
2770 * dealing with a change.
2772 if (one->sha1_valid && two->sha1_valid &&
2773 !hashcmp(one->sha1, two->sha1))
2774 return 1; /* no change */
2775 if (!one->sha1_valid && !two->sha1_valid)
2776 return 1; /* both look at the same file on the filesystem. */
2777 return 0;
2780 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2782 if (diff_unmodified_pair(p))
2783 return;
2785 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2786 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2787 return; /* no tree diffs in patch format */
2789 run_diff(p, o);
2792 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2793 struct diffstat_t *diffstat)
2795 if (diff_unmodified_pair(p))
2796 return;
2798 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2799 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2800 return; /* no tree diffs in patch format */
2802 run_diffstat(p, o, diffstat);
2805 static void diff_flush_checkdiff(struct diff_filepair *p,
2806 struct diff_options *o)
2808 if (diff_unmodified_pair(p))
2809 return;
2811 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2812 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2813 return; /* no tree diffs in patch format */
2815 run_checkdiff(p, o);
2818 int diff_queue_is_empty(void)
2820 struct diff_queue_struct *q = &diff_queued_diff;
2821 int i;
2822 for (i = 0; i < q->nr; i++)
2823 if (!diff_unmodified_pair(q->queue[i]))
2824 return 0;
2825 return 1;
2828 #if DIFF_DEBUG
2829 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2831 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2832 x, one ? one : "",
2833 s->path,
2834 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2835 s->mode,
2836 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2837 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2838 x, one ? one : "",
2839 s->size, s->xfrm_flags);
2842 void diff_debug_filepair(const struct diff_filepair *p, int i)
2844 diff_debug_filespec(p->one, i, "one");
2845 diff_debug_filespec(p->two, i, "two");
2846 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2847 p->score, p->status ? p->status : '?',
2848 p->one->rename_used, p->broken_pair);
2851 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2853 int i;
2854 if (msg)
2855 fprintf(stderr, "%s\n", msg);
2856 fprintf(stderr, "q->nr = %d\n", q->nr);
2857 for (i = 0; i < q->nr; i++) {
2858 struct diff_filepair *p = q->queue[i];
2859 diff_debug_filepair(p, i);
2862 #endif
2864 static void diff_resolve_rename_copy(void)
2866 int i;
2867 struct diff_filepair *p;
2868 struct diff_queue_struct *q = &diff_queued_diff;
2870 diff_debug_queue("resolve-rename-copy", q);
2872 for (i = 0; i < q->nr; i++) {
2873 p = q->queue[i];
2874 p->status = 0; /* undecided */
2875 if (DIFF_PAIR_UNMERGED(p))
2876 p->status = DIFF_STATUS_UNMERGED;
2877 else if (!DIFF_FILE_VALID(p->one))
2878 p->status = DIFF_STATUS_ADDED;
2879 else if (!DIFF_FILE_VALID(p->two))
2880 p->status = DIFF_STATUS_DELETED;
2881 else if (DIFF_PAIR_TYPE_CHANGED(p))
2882 p->status = DIFF_STATUS_TYPE_CHANGED;
2884 /* from this point on, we are dealing with a pair
2885 * whose both sides are valid and of the same type, i.e.
2886 * either in-place edit or rename/copy edit.
2888 else if (DIFF_PAIR_RENAME(p)) {
2890 * A rename might have re-connected a broken
2891 * pair up, causing the pathnames to be the
2892 * same again. If so, that's not a rename at
2893 * all, just a modification..
2895 * Otherwise, see if this source was used for
2896 * multiple renames, in which case we decrement
2897 * the count, and call it a copy.
2899 if (!strcmp(p->one->path, p->two->path))
2900 p->status = DIFF_STATUS_MODIFIED;
2901 else if (--p->one->rename_used > 0)
2902 p->status = DIFF_STATUS_COPIED;
2903 else
2904 p->status = DIFF_STATUS_RENAMED;
2906 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2907 p->one->mode != p->two->mode ||
2908 is_null_sha1(p->one->sha1))
2909 p->status = DIFF_STATUS_MODIFIED;
2910 else {
2911 /* This is a "no-change" entry and should not
2912 * happen anymore, but prepare for broken callers.
2914 error("feeding unmodified %s to diffcore",
2915 p->one->path);
2916 p->status = DIFF_STATUS_UNKNOWN;
2919 diff_debug_queue("resolve-rename-copy done", q);
2922 static int check_pair_status(struct diff_filepair *p)
2924 switch (p->status) {
2925 case DIFF_STATUS_UNKNOWN:
2926 return 0;
2927 case 0:
2928 die("internal error in diff-resolve-rename-copy");
2929 default:
2930 return 1;
2934 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2936 int fmt = opt->output_format;
2938 if (fmt & DIFF_FORMAT_CHECKDIFF)
2939 diff_flush_checkdiff(p, opt);
2940 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2941 diff_flush_raw(p, opt);
2942 else if (fmt & DIFF_FORMAT_NAME) {
2943 const char *name_a, *name_b;
2944 name_a = p->two->path;
2945 name_b = NULL;
2946 strip_prefix(opt->prefix_length, &name_a, &name_b);
2947 write_name_quoted(name_a, opt->file, opt->line_termination);
2951 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
2953 if (fs->mode)
2954 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
2955 else
2956 fprintf(file, " %s ", newdelete);
2957 write_name_quoted(fs->path, file, '\n');
2961 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
2963 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2964 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
2965 show_name ? ' ' : '\n');
2966 if (show_name) {
2967 write_name_quoted(p->two->path, file, '\n');
2972 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
2974 char *names = pprint_rename(p->one->path, p->two->path);
2976 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2977 free(names);
2978 show_mode_change(file, p, 0);
2981 static void diff_summary(FILE *file, struct diff_filepair *p)
2983 switch(p->status) {
2984 case DIFF_STATUS_DELETED:
2985 show_file_mode_name(file, "delete", p->one);
2986 break;
2987 case DIFF_STATUS_ADDED:
2988 show_file_mode_name(file, "create", p->two);
2989 break;
2990 case DIFF_STATUS_COPIED:
2991 show_rename_copy(file, "copy", p);
2992 break;
2993 case DIFF_STATUS_RENAMED:
2994 show_rename_copy(file, "rename", p);
2995 break;
2996 default:
2997 if (p->score) {
2998 fputs(" rewrite ", file);
2999 write_name_quoted(p->two->path, file, ' ');
3000 fprintf(file, "(%d%%)\n", similarity_index(p));
3002 show_mode_change(file, p, !p->score);
3003 break;
3007 struct patch_id_t {
3008 SHA_CTX *ctx;
3009 int patchlen;
3012 static int remove_space(char *line, int len)
3014 int i;
3015 char *dst = line;
3016 unsigned char c;
3018 for (i = 0; i < len; i++)
3019 if (!isspace((c = line[i])))
3020 *dst++ = c;
3022 return dst - line;
3025 static void patch_id_consume(void *priv, char *line, unsigned long len)
3027 struct patch_id_t *data = priv;
3028 int new_len;
3030 /* Ignore line numbers when computing the SHA1 of the patch */
3031 if (!prefixcmp(line, "@@ -"))
3032 return;
3034 new_len = remove_space(line, len);
3036 SHA1_Update(data->ctx, line, new_len);
3037 data->patchlen += new_len;
3040 /* returns 0 upon success, and writes result into sha1 */
3041 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3043 struct diff_queue_struct *q = &diff_queued_diff;
3044 int i;
3045 SHA_CTX ctx;
3046 struct patch_id_t data;
3047 char buffer[PATH_MAX * 4 + 20];
3049 SHA1_Init(&ctx);
3050 memset(&data, 0, sizeof(struct patch_id_t));
3051 data.ctx = &ctx;
3053 for (i = 0; i < q->nr; i++) {
3054 xpparam_t xpp;
3055 xdemitconf_t xecfg;
3056 xdemitcb_t ecb;
3057 mmfile_t mf1, mf2;
3058 struct diff_filepair *p = q->queue[i];
3059 int len1, len2;
3061 memset(&xecfg, 0, sizeof(xecfg));
3062 if (p->status == 0)
3063 return error("internal diff status error");
3064 if (p->status == DIFF_STATUS_UNKNOWN)
3065 continue;
3066 if (diff_unmodified_pair(p))
3067 continue;
3068 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3069 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3070 continue;
3071 if (DIFF_PAIR_UNMERGED(p))
3072 continue;
3074 diff_fill_sha1_info(p->one);
3075 diff_fill_sha1_info(p->two);
3076 if (fill_mmfile(&mf1, p->one) < 0 ||
3077 fill_mmfile(&mf2, p->two) < 0)
3078 return error("unable to read files to diff");
3080 len1 = remove_space(p->one->path, strlen(p->one->path));
3081 len2 = remove_space(p->two->path, strlen(p->two->path));
3082 if (p->one->mode == 0)
3083 len1 = snprintf(buffer, sizeof(buffer),
3084 "diff--gita/%.*sb/%.*s"
3085 "newfilemode%06o"
3086 "---/dev/null"
3087 "+++b/%.*s",
3088 len1, p->one->path,
3089 len2, p->two->path,
3090 p->two->mode,
3091 len2, p->two->path);
3092 else if (p->two->mode == 0)
3093 len1 = snprintf(buffer, sizeof(buffer),
3094 "diff--gita/%.*sb/%.*s"
3095 "deletedfilemode%06o"
3096 "---a/%.*s"
3097 "+++/dev/null",
3098 len1, p->one->path,
3099 len2, p->two->path,
3100 p->one->mode,
3101 len1, p->one->path);
3102 else
3103 len1 = snprintf(buffer, sizeof(buffer),
3104 "diff--gita/%.*sb/%.*s"
3105 "---a/%.*s"
3106 "+++b/%.*s",
3107 len1, p->one->path,
3108 len2, p->two->path,
3109 len1, p->one->path,
3110 len2, p->two->path);
3111 SHA1_Update(&ctx, buffer, len1);
3113 xpp.flags = XDF_NEED_MINIMAL;
3114 xecfg.ctxlen = 3;
3115 xecfg.flags = XDL_EMIT_FUNCNAMES;
3116 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3117 &xpp, &xecfg, &ecb);
3120 SHA1_Final(sha1, &ctx);
3121 return 0;
3124 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3126 struct diff_queue_struct *q = &diff_queued_diff;
3127 int i;
3128 int result = diff_get_patch_id(options, sha1);
3130 for (i = 0; i < q->nr; i++)
3131 diff_free_filepair(q->queue[i]);
3133 free(q->queue);
3134 q->queue = NULL;
3135 q->nr = q->alloc = 0;
3137 return result;
3140 static int is_summary_empty(const struct diff_queue_struct *q)
3142 int i;
3144 for (i = 0; i < q->nr; i++) {
3145 const struct diff_filepair *p = q->queue[i];
3147 switch (p->status) {
3148 case DIFF_STATUS_DELETED:
3149 case DIFF_STATUS_ADDED:
3150 case DIFF_STATUS_COPIED:
3151 case DIFF_STATUS_RENAMED:
3152 return 0;
3153 default:
3154 if (p->score)
3155 return 0;
3156 if (p->one->mode && p->two->mode &&
3157 p->one->mode != p->two->mode)
3158 return 0;
3159 break;
3162 return 1;
3165 void diff_flush(struct diff_options *options)
3167 struct diff_queue_struct *q = &diff_queued_diff;
3168 int i, output_format = options->output_format;
3169 int separator = 0;
3172 * Order: raw, stat, summary, patch
3173 * or: name/name-status/checkdiff (other bits clear)
3175 if (!q->nr)
3176 goto free_queue;
3178 if (output_format & (DIFF_FORMAT_RAW |
3179 DIFF_FORMAT_NAME |
3180 DIFF_FORMAT_NAME_STATUS |
3181 DIFF_FORMAT_CHECKDIFF)) {
3182 for (i = 0; i < q->nr; i++) {
3183 struct diff_filepair *p = q->queue[i];
3184 if (check_pair_status(p))
3185 flush_one_pair(p, options);
3187 separator++;
3190 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3191 struct diffstat_t diffstat;
3193 memset(&diffstat, 0, sizeof(struct diffstat_t));
3194 for (i = 0; i < q->nr; i++) {
3195 struct diff_filepair *p = q->queue[i];
3196 if (check_pair_status(p))
3197 diff_flush_stat(p, options, &diffstat);
3199 if (output_format & DIFF_FORMAT_NUMSTAT)
3200 show_numstat(&diffstat, options);
3201 if (output_format & DIFF_FORMAT_DIFFSTAT)
3202 show_stats(&diffstat, options);
3203 if (output_format & DIFF_FORMAT_SHORTSTAT)
3204 show_shortstats(&diffstat, options);
3205 free_diffstat_info(&diffstat);
3206 separator++;
3208 if (output_format & DIFF_FORMAT_DIRSTAT)
3209 show_dirstat(options);
3211 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3212 for (i = 0; i < q->nr; i++)
3213 diff_summary(options->file, q->queue[i]);
3214 separator++;
3217 if (output_format & DIFF_FORMAT_PATCH) {
3218 if (separator) {
3219 putc(options->line_termination, options->file);
3220 if (options->stat_sep) {
3221 /* attach patch instead of inline */
3222 fputs(options->stat_sep, options->file);
3226 for (i = 0; i < q->nr; i++) {
3227 struct diff_filepair *p = q->queue[i];
3228 if (check_pair_status(p))
3229 diff_flush_patch(p, options);
3233 if (output_format & DIFF_FORMAT_CALLBACK)
3234 options->format_callback(q, options, options->format_callback_data);
3236 for (i = 0; i < q->nr; i++)
3237 diff_free_filepair(q->queue[i]);
3238 free_queue:
3239 free(q->queue);
3240 q->queue = NULL;
3241 q->nr = q->alloc = 0;
3242 if (options->close_file)
3243 fclose(options->file);
3246 static void diffcore_apply_filter(const char *filter)
3248 int i;
3249 struct diff_queue_struct *q = &diff_queued_diff;
3250 struct diff_queue_struct outq;
3251 outq.queue = NULL;
3252 outq.nr = outq.alloc = 0;
3254 if (!filter)
3255 return;
3257 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3258 int found;
3259 for (i = found = 0; !found && i < q->nr; i++) {
3260 struct diff_filepair *p = q->queue[i];
3261 if (((p->status == DIFF_STATUS_MODIFIED) &&
3262 ((p->score &&
3263 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3264 (!p->score &&
3265 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3266 ((p->status != DIFF_STATUS_MODIFIED) &&
3267 strchr(filter, p->status)))
3268 found++;
3270 if (found)
3271 return;
3273 /* otherwise we will clear the whole queue
3274 * by copying the empty outq at the end of this
3275 * function, but first clear the current entries
3276 * in the queue.
3278 for (i = 0; i < q->nr; i++)
3279 diff_free_filepair(q->queue[i]);
3281 else {
3282 /* Only the matching ones */
3283 for (i = 0; i < q->nr; i++) {
3284 struct diff_filepair *p = q->queue[i];
3286 if (((p->status == DIFF_STATUS_MODIFIED) &&
3287 ((p->score &&
3288 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3289 (!p->score &&
3290 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3291 ((p->status != DIFF_STATUS_MODIFIED) &&
3292 strchr(filter, p->status)))
3293 diff_q(&outq, p);
3294 else
3295 diff_free_filepair(p);
3298 free(q->queue);
3299 *q = outq;
3302 /* Check whether two filespecs with the same mode and size are identical */
3303 static int diff_filespec_is_identical(struct diff_filespec *one,
3304 struct diff_filespec *two)
3306 if (S_ISGITLINK(one->mode))
3307 return 0;
3308 if (diff_populate_filespec(one, 0))
3309 return 0;
3310 if (diff_populate_filespec(two, 0))
3311 return 0;
3312 return !memcmp(one->data, two->data, one->size);
3315 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3317 int i;
3318 struct diff_queue_struct *q = &diff_queued_diff;
3319 struct diff_queue_struct outq;
3320 outq.queue = NULL;
3321 outq.nr = outq.alloc = 0;
3323 for (i = 0; i < q->nr; i++) {
3324 struct diff_filepair *p = q->queue[i];
3327 * 1. Entries that come from stat info dirtyness
3328 * always have both sides (iow, not create/delete),
3329 * one side of the object name is unknown, with
3330 * the same mode and size. Keep the ones that
3331 * do not match these criteria. They have real
3332 * differences.
3334 * 2. At this point, the file is known to be modified,
3335 * with the same mode and size, and the object
3336 * name of one side is unknown. Need to inspect
3337 * the identical contents.
3339 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3340 !DIFF_FILE_VALID(p->two) ||
3341 (p->one->sha1_valid && p->two->sha1_valid) ||
3342 (p->one->mode != p->two->mode) ||
3343 diff_populate_filespec(p->one, 1) ||
3344 diff_populate_filespec(p->two, 1) ||
3345 (p->one->size != p->two->size) ||
3346 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3347 diff_q(&outq, p);
3348 else {
3350 * The caller can subtract 1 from skip_stat_unmatch
3351 * to determine how many paths were dirty only
3352 * due to stat info mismatch.
3354 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3355 diffopt->skip_stat_unmatch++;
3356 diff_free_filepair(p);
3359 free(q->queue);
3360 *q = outq;
3363 void diffcore_std(struct diff_options *options)
3365 if (DIFF_OPT_TST(options, QUIET))
3366 return;
3368 if (options->skip_stat_unmatch && !DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3369 diffcore_skip_stat_unmatch(options);
3370 if (options->break_opt != -1)
3371 diffcore_break(options->break_opt);
3372 if (options->detect_rename)
3373 diffcore_rename(options);
3374 if (options->break_opt != -1)
3375 diffcore_merge_broken();
3376 if (options->pickaxe)
3377 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3378 if (options->orderfile)
3379 diffcore_order(options->orderfile);
3380 diff_resolve_rename_copy();
3381 diffcore_apply_filter(options->filter);
3383 if (diff_queued_diff.nr)
3384 DIFF_OPT_SET(options, HAS_CHANGES);
3385 else
3386 DIFF_OPT_CLR(options, HAS_CHANGES);
3389 int diff_result_code(struct diff_options *opt, int status)
3391 int result = 0;
3392 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3393 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3394 return status;
3395 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3396 DIFF_OPT_TST(opt, HAS_CHANGES))
3397 result |= 01;
3398 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3399 DIFF_OPT_TST(opt, CHECK_FAILED))
3400 result |= 02;
3401 return result;
3404 void diff_addremove(struct diff_options *options,
3405 int addremove, unsigned mode,
3406 const unsigned char *sha1,
3407 const char *concatpath)
3409 struct diff_filespec *one, *two;
3411 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3412 return;
3414 /* This may look odd, but it is a preparation for
3415 * feeding "there are unchanged files which should
3416 * not produce diffs, but when you are doing copy
3417 * detection you would need them, so here they are"
3418 * entries to the diff-core. They will be prefixed
3419 * with something like '=' or '*' (I haven't decided
3420 * which but should not make any difference).
3421 * Feeding the same new and old to diff_change()
3422 * also has the same effect.
3423 * Before the final output happens, they are pruned after
3424 * merged into rename/copy pairs as appropriate.
3426 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3427 addremove = (addremove == '+' ? '-' :
3428 addremove == '-' ? '+' : addremove);
3430 if (options->prefix &&
3431 strncmp(concatpath, options->prefix, options->prefix_length))
3432 return;
3434 one = alloc_filespec(concatpath);
3435 two = alloc_filespec(concatpath);
3437 if (addremove != '+')
3438 fill_filespec(one, sha1, mode);
3439 if (addremove != '-')
3440 fill_filespec(two, sha1, mode);
3442 diff_queue(&diff_queued_diff, one, two);
3443 DIFF_OPT_SET(options, HAS_CHANGES);
3446 void diff_change(struct diff_options *options,
3447 unsigned old_mode, unsigned new_mode,
3448 const unsigned char *old_sha1,
3449 const unsigned char *new_sha1,
3450 const char *concatpath)
3452 struct diff_filespec *one, *two;
3454 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3455 && S_ISGITLINK(new_mode))
3456 return;
3458 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3459 unsigned tmp;
3460 const unsigned char *tmp_c;
3461 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3462 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3465 if (options->prefix &&
3466 strncmp(concatpath, options->prefix, options->prefix_length))
3467 return;
3469 one = alloc_filespec(concatpath);
3470 two = alloc_filespec(concatpath);
3471 fill_filespec(one, old_sha1, old_mode);
3472 fill_filespec(two, new_sha1, new_mode);
3474 diff_queue(&diff_queued_diff, one, two);
3475 DIFF_OPT_SET(options, HAS_CHANGES);
3478 void diff_unmerge(struct diff_options *options,
3479 const char *path,
3480 unsigned mode, const unsigned char *sha1)
3482 struct diff_filespec *one, *two;
3484 if (options->prefix &&
3485 strncmp(path, options->prefix, options->prefix_length))
3486 return;
3488 one = alloc_filespec(path);
3489 two = alloc_filespec(path);
3490 fill_filespec(one, sha1, mode);
3491 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;