diff: add ruby funcname pattern
[git/spearce.git] / diff.c
blobc253015c5d612a6715485031adc840658ffaf9c0
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.renamelimit")) {
135 diff_rename_limit_default = git_config_int(var, value);
136 return 0;
138 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
139 diff_use_color_default = git_config_colorbool(var, value, -1);
140 return 0;
142 if (!strcmp(var, "diff.renames")) {
143 if (!value)
144 diff_detect_rename_default = DIFF_DETECT_RENAME;
145 else if (!strcasecmp(value, "copies") ||
146 !strcasecmp(value, "copy"))
147 diff_detect_rename_default = DIFF_DETECT_COPY;
148 else if (git_config_bool(var,value))
149 diff_detect_rename_default = DIFF_DETECT_RENAME;
150 return 0;
152 if (!strcmp(var, "diff.autorefreshindex")) {
153 diff_auto_refresh_index = git_config_bool(var, value);
154 return 0;
156 if (!strcmp(var, "diff.external"))
157 return git_config_string(&external_diff_cmd_cfg, var, value);
158 if (!prefixcmp(var, "diff.")) {
159 const char *ep = strrchr(var, '.');
161 if (ep != var + 4 && !strcmp(ep, ".command"))
162 return parse_lldiff_command(var, ep, value);
165 return git_diff_basic_config(var, value, cb);
168 int git_diff_basic_config(const char *var, const char *value, void *cb)
170 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
171 int slot = parse_diff_color_slot(var, 11);
172 if (!value)
173 return config_error_nonbool(var);
174 color_parse(value, var, diff_colors[slot]);
175 return 0;
178 if (!prefixcmp(var, "diff.")) {
179 const char *ep = strrchr(var, '.');
180 if (ep != var + 4) {
181 if (!strcmp(ep, ".funcname")) {
182 if (!value)
183 return config_error_nonbool(var);
184 return parse_funcname_pattern(var, ep, value);
189 return git_color_default_config(var, value, cb);
192 static char *quote_two(const char *one, const char *two)
194 int need_one = quote_c_style(one, NULL, NULL, 1);
195 int need_two = quote_c_style(two, NULL, NULL, 1);
196 struct strbuf res;
198 strbuf_init(&res, 0);
199 if (need_one + need_two) {
200 strbuf_addch(&res, '"');
201 quote_c_style(one, &res, NULL, 1);
202 quote_c_style(two, &res, NULL, 1);
203 strbuf_addch(&res, '"');
204 } else {
205 strbuf_addstr(&res, one);
206 strbuf_addstr(&res, two);
208 return strbuf_detach(&res, NULL);
211 static const char *external_diff(void)
213 static const char *external_diff_cmd = NULL;
214 static int done_preparing = 0;
216 if (done_preparing)
217 return external_diff_cmd;
218 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
219 if (!external_diff_cmd)
220 external_diff_cmd = external_diff_cmd_cfg;
221 done_preparing = 1;
222 return external_diff_cmd;
225 static struct diff_tempfile {
226 const char *name; /* filename external diff should read from */
227 char hex[41];
228 char mode[10];
229 char tmp_path[PATH_MAX];
230 } diff_temp[2];
232 static int count_lines(const char *data, int size)
234 int count, ch, completely_empty = 1, nl_just_seen = 0;
235 count = 0;
236 while (0 < size--) {
237 ch = *data++;
238 if (ch == '\n') {
239 count++;
240 nl_just_seen = 1;
241 completely_empty = 0;
243 else {
244 nl_just_seen = 0;
245 completely_empty = 0;
248 if (completely_empty)
249 return 0;
250 if (!nl_just_seen)
251 count++; /* no trailing newline */
252 return count;
255 static void print_line_count(FILE *file, int count)
257 switch (count) {
258 case 0:
259 fprintf(file, "0,0");
260 break;
261 case 1:
262 fprintf(file, "1");
263 break;
264 default:
265 fprintf(file, "1,%d", count);
266 break;
270 static void copy_file_with_prefix(FILE *file,
271 int prefix, const char *data, int size,
272 const char *set, const char *reset)
274 int ch, nl_just_seen = 1;
275 while (0 < size--) {
276 ch = *data++;
277 if (nl_just_seen) {
278 fputs(set, file);
279 putc(prefix, file);
281 if (ch == '\n') {
282 nl_just_seen = 1;
283 fputs(reset, file);
284 } else
285 nl_just_seen = 0;
286 putc(ch, file);
288 if (!nl_just_seen)
289 fprintf(file, "%s\n\\ No newline at end of file\n", reset);
292 static void emit_rewrite_diff(const char *name_a,
293 const char *name_b,
294 struct diff_filespec *one,
295 struct diff_filespec *two,
296 struct diff_options *o)
298 int lc_a, lc_b;
299 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
300 const char *name_a_tab, *name_b_tab;
301 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
302 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
303 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
304 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
305 const char *reset = diff_get_color(color_diff, DIFF_RESET);
306 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
308 name_a += (*name_a == '/');
309 name_b += (*name_b == '/');
310 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
311 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
313 strbuf_reset(&a_name);
314 strbuf_reset(&b_name);
315 quote_two_c_style(&a_name, o->a_prefix, name_a, 0);
316 quote_two_c_style(&b_name, o->b_prefix, name_b, 0);
318 diff_populate_filespec(one, 0);
319 diff_populate_filespec(two, 0);
320 lc_a = count_lines(one->data, one->size);
321 lc_b = count_lines(two->data, two->size);
322 fprintf(o->file,
323 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
324 metainfo, a_name.buf, name_a_tab, reset,
325 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
326 print_line_count(o->file, lc_a);
327 fprintf(o->file, " +");
328 print_line_count(o->file, lc_b);
329 fprintf(o->file, " @@%s\n", reset);
330 if (lc_a)
331 copy_file_with_prefix(o->file, '-', one->data, one->size, old, reset);
332 if (lc_b)
333 copy_file_with_prefix(o->file, '+', two->data, two->size, new, reset);
336 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
338 if (!DIFF_FILE_VALID(one)) {
339 mf->ptr = (char *)""; /* does not matter */
340 mf->size = 0;
341 return 0;
343 else if (diff_populate_filespec(one, 0))
344 return -1;
345 mf->ptr = one->data;
346 mf->size = one->size;
347 return 0;
350 struct diff_words_buffer {
351 mmfile_t text;
352 long alloc;
353 long current; /* output pointer */
354 int suppressed_newline;
357 static void diff_words_append(char *line, unsigned long len,
358 struct diff_words_buffer *buffer)
360 if (buffer->text.size + len > buffer->alloc) {
361 buffer->alloc = (buffer->text.size + len) * 3 / 2;
362 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
364 line++;
365 len--;
366 memcpy(buffer->text.ptr + buffer->text.size, line, len);
367 buffer->text.size += len;
370 struct diff_words_data {
371 struct xdiff_emit_state xm;
372 struct diff_words_buffer minus, plus;
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 ecb.outf = xdiff_outf;
462 ecb.priv = diff_words;
463 diff_words->xm.consume = fn_out_diff_words_aux;
464 xdi_diff(&minus, &plus, &xpp, &xecfg, &ecb);
466 free(minus.ptr);
467 free(plus.ptr);
468 diff_words->minus.text.size = diff_words->plus.text.size = 0;
470 if (diff_words->minus.suppressed_newline) {
471 putc('\n', diff_words->file);
472 diff_words->minus.suppressed_newline = 0;
476 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
478 struct emit_callback {
479 struct xdiff_emit_state xm;
480 int nparents, color_diff;
481 unsigned ws_rule;
482 sane_truncate_fn truncate;
483 const char **label_path;
484 struct diff_words_data *diff_words;
485 int *found_changesp;
486 FILE *file;
489 static void free_diff_words_data(struct emit_callback *ecbdata)
491 if (ecbdata->diff_words) {
492 /* flush buffers */
493 if (ecbdata->diff_words->minus.text.size ||
494 ecbdata->diff_words->plus.text.size)
495 diff_words_show(ecbdata->diff_words);
497 free (ecbdata->diff_words->minus.text.ptr);
498 free (ecbdata->diff_words->plus.text.ptr);
499 free(ecbdata->diff_words);
500 ecbdata->diff_words = NULL;
504 const char *diff_get_color(int diff_use_color, enum color_diff ix)
506 if (diff_use_color)
507 return diff_colors[ix];
508 return "";
511 static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
513 int has_trailing_newline = (len > 0 && line[len-1] == '\n');
514 if (has_trailing_newline)
515 len--;
517 fputs(set, file);
518 fwrite(line, len, 1, file);
519 fputs(reset, file);
520 if (has_trailing_newline)
521 fputc('\n', file);
524 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
526 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
527 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
529 if (!*ws)
530 emit_line(ecbdata->file, set, reset, line, len);
531 else {
532 /* Emit just the prefix, then the rest. */
533 emit_line(ecbdata->file, set, reset, line, ecbdata->nparents);
534 ws_check_emit(line + ecbdata->nparents,
535 len - ecbdata->nparents, ecbdata->ws_rule,
536 ecbdata->file, set, reset, ws);
540 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
542 const char *cp;
543 unsigned long allot;
544 size_t l = len;
546 if (ecb->truncate)
547 return ecb->truncate(line, len);
548 cp = line;
549 allot = l;
550 while (0 < l) {
551 (void) utf8_width(&cp, &l);
552 if (!cp)
553 break; /* truncated in the middle? */
555 return allot - l;
558 static void fn_out_consume(void *priv, char *line, unsigned long len)
560 int i;
561 int color;
562 struct emit_callback *ecbdata = priv;
563 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
564 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
565 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
567 *(ecbdata->found_changesp) = 1;
569 if (ecbdata->label_path[0]) {
570 const char *name_a_tab, *name_b_tab;
572 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
573 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
575 fprintf(ecbdata->file, "%s--- %s%s%s\n",
576 meta, ecbdata->label_path[0], reset, name_a_tab);
577 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
578 meta, ecbdata->label_path[1], reset, name_b_tab);
579 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
582 /* This is not really necessary for now because
583 * this codepath only deals with two-way diffs.
585 for (i = 0; i < len && line[i] == '@'; i++)
587 if (2 <= i && i < len && line[i] == ' ') {
588 ecbdata->nparents = i - 1;
589 len = sane_truncate_line(ecbdata, line, len);
590 emit_line(ecbdata->file,
591 diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
592 reset, line, len);
593 if (line[len-1] != '\n')
594 putc('\n', ecbdata->file);
595 return;
598 if (len < ecbdata->nparents) {
599 emit_line(ecbdata->file, reset, reset, line, len);
600 return;
603 color = DIFF_PLAIN;
604 if (ecbdata->diff_words && ecbdata->nparents != 1)
605 /* fall back to normal diff */
606 free_diff_words_data(ecbdata);
607 if (ecbdata->diff_words) {
608 if (line[0] == '-') {
609 diff_words_append(line, len,
610 &ecbdata->diff_words->minus);
611 return;
612 } else if (line[0] == '+') {
613 diff_words_append(line, len,
614 &ecbdata->diff_words->plus);
615 return;
617 if (ecbdata->diff_words->minus.text.size ||
618 ecbdata->diff_words->plus.text.size)
619 diff_words_show(ecbdata->diff_words);
620 line++;
621 len--;
622 emit_line(ecbdata->file, plain, reset, line, len);
623 return;
625 for (i = 0; i < ecbdata->nparents && len; i++) {
626 if (line[i] == '-')
627 color = DIFF_FILE_OLD;
628 else if (line[i] == '+')
629 color = DIFF_FILE_NEW;
632 if (color != DIFF_FILE_NEW) {
633 emit_line(ecbdata->file,
634 diff_get_color(ecbdata->color_diff, color),
635 reset, line, len);
636 return;
638 emit_add_line(reset, ecbdata, line, len);
641 static char *pprint_rename(const char *a, const char *b)
643 const char *old = a;
644 const char *new = b;
645 struct strbuf name;
646 int pfx_length, sfx_length;
647 int len_a = strlen(a);
648 int len_b = strlen(b);
649 int a_midlen, b_midlen;
650 int qlen_a = quote_c_style(a, NULL, NULL, 0);
651 int qlen_b = quote_c_style(b, NULL, NULL, 0);
653 strbuf_init(&name, 0);
654 if (qlen_a || qlen_b) {
655 quote_c_style(a, &name, NULL, 0);
656 strbuf_addstr(&name, " => ");
657 quote_c_style(b, &name, NULL, 0);
658 return strbuf_detach(&name, NULL);
661 /* Find common prefix */
662 pfx_length = 0;
663 while (*old && *new && *old == *new) {
664 if (*old == '/')
665 pfx_length = old - a + 1;
666 old++;
667 new++;
670 /* Find common suffix */
671 old = a + len_a;
672 new = b + len_b;
673 sfx_length = 0;
674 while (a <= old && b <= new && *old == *new) {
675 if (*old == '/')
676 sfx_length = len_a - (old - a);
677 old--;
678 new--;
682 * pfx{mid-a => mid-b}sfx
683 * {pfx-a => pfx-b}sfx
684 * pfx{sfx-a => sfx-b}
685 * name-a => name-b
687 a_midlen = len_a - pfx_length - sfx_length;
688 b_midlen = len_b - pfx_length - sfx_length;
689 if (a_midlen < 0)
690 a_midlen = 0;
691 if (b_midlen < 0)
692 b_midlen = 0;
694 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
695 if (pfx_length + sfx_length) {
696 strbuf_add(&name, a, pfx_length);
697 strbuf_addch(&name, '{');
699 strbuf_add(&name, a + pfx_length, a_midlen);
700 strbuf_addstr(&name, " => ");
701 strbuf_add(&name, b + pfx_length, b_midlen);
702 if (pfx_length + sfx_length) {
703 strbuf_addch(&name, '}');
704 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
706 return strbuf_detach(&name, NULL);
709 struct diffstat_t {
710 struct xdiff_emit_state xm;
712 int nr;
713 int alloc;
714 struct diffstat_file {
715 char *from_name;
716 char *name;
717 char *print_name;
718 unsigned is_unmerged:1;
719 unsigned is_binary:1;
720 unsigned is_renamed:1;
721 unsigned int added, deleted;
722 } **files;
725 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
726 const char *name_a,
727 const char *name_b)
729 struct diffstat_file *x;
730 x = xcalloc(sizeof (*x), 1);
731 if (diffstat->nr == diffstat->alloc) {
732 diffstat->alloc = alloc_nr(diffstat->alloc);
733 diffstat->files = xrealloc(diffstat->files,
734 diffstat->alloc * sizeof(x));
736 diffstat->files[diffstat->nr++] = x;
737 if (name_b) {
738 x->from_name = xstrdup(name_a);
739 x->name = xstrdup(name_b);
740 x->is_renamed = 1;
742 else {
743 x->from_name = NULL;
744 x->name = xstrdup(name_a);
746 return x;
749 static void diffstat_consume(void *priv, char *line, unsigned long len)
751 struct diffstat_t *diffstat = priv;
752 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
754 if (line[0] == '+')
755 x->added++;
756 else if (line[0] == '-')
757 x->deleted++;
760 const char mime_boundary_leader[] = "------------";
762 static int scale_linear(int it, int width, int max_change)
765 * make sure that at least one '-' is printed if there were deletions,
766 * and likewise for '+'.
768 if (max_change < 2)
769 return it;
770 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
773 static void show_name(FILE *file,
774 const char *prefix, const char *name, int len,
775 const char *reset, const char *set)
777 fprintf(file, " %s%s%-*s%s |", set, prefix, len, name, reset);
780 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
782 if (cnt <= 0)
783 return;
784 fprintf(file, "%s", set);
785 while (cnt--)
786 putc(ch, file);
787 fprintf(file, "%s", reset);
790 static void fill_print_name(struct diffstat_file *file)
792 char *pname;
794 if (file->print_name)
795 return;
797 if (!file->is_renamed) {
798 struct strbuf buf;
799 strbuf_init(&buf, 0);
800 if (quote_c_style(file->name, &buf, NULL, 0)) {
801 pname = strbuf_detach(&buf, NULL);
802 } else {
803 pname = file->name;
804 strbuf_release(&buf);
806 } else {
807 pname = pprint_rename(file->from_name, file->name);
809 file->print_name = pname;
812 static void show_stats(struct diffstat_t* data, struct diff_options *options)
814 int i, len, add, del, total, adds = 0, dels = 0;
815 int max_change = 0, max_len = 0;
816 int total_files = data->nr;
817 int width, name_width;
818 const char *reset, *set, *add_c, *del_c;
820 if (data->nr == 0)
821 return;
823 width = options->stat_width ? options->stat_width : 80;
824 name_width = options->stat_name_width ? options->stat_name_width : 50;
826 /* Sanity: give at least 5 columns to the graph,
827 * but leave at least 10 columns for the name.
829 if (width < 25)
830 width = 25;
831 if (name_width < 10)
832 name_width = 10;
833 else if (width < name_width + 15)
834 name_width = width - 15;
836 /* Find the longest filename and max number of changes */
837 reset = diff_get_color_opt(options, DIFF_RESET);
838 set = diff_get_color_opt(options, DIFF_PLAIN);
839 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
840 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
842 for (i = 0; i < data->nr; i++) {
843 struct diffstat_file *file = data->files[i];
844 int change = file->added + file->deleted;
845 fill_print_name(file);
846 len = strlen(file->print_name);
847 if (max_len < len)
848 max_len = len;
850 if (file->is_binary || file->is_unmerged)
851 continue;
852 if (max_change < change)
853 max_change = change;
856 /* Compute the width of the graph part;
857 * 10 is for one blank at the beginning of the line plus
858 * " | count " between the name and the graph.
860 * From here on, name_width is the width of the name area,
861 * and width is the width of the graph area.
863 name_width = (name_width < max_len) ? name_width : max_len;
864 if (width < (name_width + 10) + max_change)
865 width = width - (name_width + 10);
866 else
867 width = max_change;
869 for (i = 0; i < data->nr; i++) {
870 const char *prefix = "";
871 char *name = data->files[i]->print_name;
872 int added = data->files[i]->added;
873 int deleted = data->files[i]->deleted;
874 int name_len;
877 * "scale" the filename
879 len = name_width;
880 name_len = strlen(name);
881 if (name_width < name_len) {
882 char *slash;
883 prefix = "...";
884 len -= 3;
885 name += name_len - len;
886 slash = strchr(name, '/');
887 if (slash)
888 name = slash;
891 if (data->files[i]->is_binary) {
892 show_name(options->file, prefix, name, len, reset, set);
893 fprintf(options->file, " Bin ");
894 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
895 fprintf(options->file, " -> ");
896 fprintf(options->file, "%s%d%s", add_c, added, reset);
897 fprintf(options->file, " bytes");
898 fprintf(options->file, "\n");
899 continue;
901 else if (data->files[i]->is_unmerged) {
902 show_name(options->file, prefix, name, len, reset, set);
903 fprintf(options->file, " Unmerged\n");
904 continue;
906 else if (!data->files[i]->is_renamed &&
907 (added + deleted == 0)) {
908 total_files--;
909 continue;
913 * scale the add/delete
915 add = added;
916 del = deleted;
917 total = add + del;
918 adds += add;
919 dels += del;
921 if (width <= max_change) {
922 add = scale_linear(add, width, max_change);
923 del = scale_linear(del, width, max_change);
924 total = add + del;
926 show_name(options->file, prefix, name, len, reset, set);
927 fprintf(options->file, "%5d%s", added + deleted,
928 added + deleted ? " " : "");
929 show_graph(options->file, '+', add, add_c, reset);
930 show_graph(options->file, '-', del, del_c, reset);
931 fprintf(options->file, "\n");
933 fprintf(options->file,
934 "%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
935 set, total_files, adds, dels, reset);
938 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
940 int i, adds = 0, dels = 0, total_files = data->nr;
942 if (data->nr == 0)
943 return;
945 for (i = 0; i < data->nr; i++) {
946 if (!data->files[i]->is_binary &&
947 !data->files[i]->is_unmerged) {
948 int added = data->files[i]->added;
949 int deleted= data->files[i]->deleted;
950 if (!data->files[i]->is_renamed &&
951 (added + deleted == 0)) {
952 total_files--;
953 } else {
954 adds += added;
955 dels += deleted;
959 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
960 total_files, adds, dels);
963 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
965 int i;
967 if (data->nr == 0)
968 return;
970 for (i = 0; i < data->nr; i++) {
971 struct diffstat_file *file = data->files[i];
973 if (file->is_binary)
974 fprintf(options->file, "-\t-\t");
975 else
976 fprintf(options->file,
977 "%d\t%d\t", file->added, file->deleted);
978 if (options->line_termination) {
979 fill_print_name(file);
980 if (!file->is_renamed)
981 write_name_quoted(file->name, options->file,
982 options->line_termination);
983 else {
984 fputs(file->print_name, options->file);
985 putc(options->line_termination, options->file);
987 } else {
988 if (file->is_renamed) {
989 putc('\0', options->file);
990 write_name_quoted(file->from_name, options->file, '\0');
992 write_name_quoted(file->name, options->file, '\0');
997 struct dirstat_file {
998 const char *name;
999 unsigned long changed;
1002 struct dirstat_dir {
1003 struct dirstat_file *files;
1004 int alloc, nr, percent, cumulative;
1007 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1009 unsigned long this_dir = 0;
1010 unsigned int sources = 0;
1012 while (dir->nr) {
1013 struct dirstat_file *f = dir->files;
1014 int namelen = strlen(f->name);
1015 unsigned long this;
1016 char *slash;
1018 if (namelen < baselen)
1019 break;
1020 if (memcmp(f->name, base, baselen))
1021 break;
1022 slash = strchr(f->name + baselen, '/');
1023 if (slash) {
1024 int newbaselen = slash + 1 - f->name;
1025 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1026 sources++;
1027 } else {
1028 this = f->changed;
1029 dir->files++;
1030 dir->nr--;
1031 sources += 2;
1033 this_dir += this;
1037 * We don't report dirstat's for
1038 * - the top level
1039 * - or cases where everything came from a single directory
1040 * under this directory (sources == 1).
1042 if (baselen && sources != 1) {
1043 int permille = this_dir * 1000 / changed;
1044 if (permille) {
1045 int percent = permille / 10;
1046 if (percent >= dir->percent) {
1047 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1048 if (!dir->cumulative)
1049 return 0;
1053 return this_dir;
1056 static void show_dirstat(struct diff_options *options)
1058 int i;
1059 unsigned long changed;
1060 struct dirstat_dir dir;
1061 struct diff_queue_struct *q = &diff_queued_diff;
1063 dir.files = NULL;
1064 dir.alloc = 0;
1065 dir.nr = 0;
1066 dir.percent = options->dirstat_percent;
1067 dir.cumulative = options->output_format & DIFF_FORMAT_CUMULATIVE;
1069 changed = 0;
1070 for (i = 0; i < q->nr; i++) {
1071 struct diff_filepair *p = q->queue[i];
1072 const char *name;
1073 unsigned long copied, added, damage;
1075 name = p->one->path ? p->one->path : p->two->path;
1077 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1078 diff_populate_filespec(p->one, 0);
1079 diff_populate_filespec(p->two, 0);
1080 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1081 &copied, &added);
1082 diff_free_filespec_data(p->one);
1083 diff_free_filespec_data(p->two);
1084 } else if (DIFF_FILE_VALID(p->one)) {
1085 diff_populate_filespec(p->one, 1);
1086 copied = added = 0;
1087 diff_free_filespec_data(p->one);
1088 } else if (DIFF_FILE_VALID(p->two)) {
1089 diff_populate_filespec(p->two, 1);
1090 copied = 0;
1091 added = p->two->size;
1092 diff_free_filespec_data(p->two);
1093 } else
1094 continue;
1097 * Original minus copied is the removed material,
1098 * added is the new material. They are both damages
1099 * made to the preimage.
1101 damage = (p->one->size - copied) + added;
1103 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1104 dir.files[dir.nr].name = name;
1105 dir.files[dir.nr].changed = damage;
1106 changed += damage;
1107 dir.nr++;
1110 /* This can happen even with many files, if everything was renames */
1111 if (!changed)
1112 return;
1114 /* Show all directories with more than x% of the changes */
1115 gather_dirstat(options->file, &dir, changed, "", 0);
1118 static void free_diffstat_info(struct diffstat_t *diffstat)
1120 int i;
1121 for (i = 0; i < diffstat->nr; i++) {
1122 struct diffstat_file *f = diffstat->files[i];
1123 if (f->name != f->print_name)
1124 free(f->print_name);
1125 free(f->name);
1126 free(f->from_name);
1127 free(f);
1129 free(diffstat->files);
1132 struct checkdiff_t {
1133 struct xdiff_emit_state xm;
1134 const char *filename;
1135 int lineno;
1136 struct diff_options *o;
1137 unsigned ws_rule;
1138 unsigned status;
1139 int trailing_blanks_start;
1142 static int is_conflict_marker(const char *line, unsigned long len)
1144 char firstchar;
1145 int cnt;
1147 if (len < 8)
1148 return 0;
1149 firstchar = line[0];
1150 switch (firstchar) {
1151 case '=': case '>': case '<':
1152 break;
1153 default:
1154 return 0;
1156 for (cnt = 1; cnt < 7; cnt++)
1157 if (line[cnt] != firstchar)
1158 return 0;
1159 /* line[0] thru line[6] are same as firstchar */
1160 if (firstchar == '=') {
1161 /* divider between ours and theirs? */
1162 if (len != 8 || line[7] != '\n')
1163 return 0;
1164 } else if (len < 8 || !isspace(line[7])) {
1165 /* not divider before ours nor after theirs */
1166 return 0;
1168 return 1;
1171 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1173 struct checkdiff_t *data = priv;
1174 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1175 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1176 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1177 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1178 char *err;
1180 if (line[0] == '+') {
1181 unsigned bad;
1182 data->lineno++;
1183 if (!ws_blank_line(line + 1, len - 1, data->ws_rule))
1184 data->trailing_blanks_start = 0;
1185 else if (!data->trailing_blanks_start)
1186 data->trailing_blanks_start = data->lineno;
1187 if (is_conflict_marker(line + 1, len - 1)) {
1188 data->status |= 1;
1189 fprintf(data->o->file,
1190 "%s:%d: leftover conflict marker\n",
1191 data->filename, data->lineno);
1193 bad = ws_check(line + 1, len - 1, data->ws_rule);
1194 if (!bad)
1195 return;
1196 data->status |= bad;
1197 err = whitespace_error_string(bad);
1198 fprintf(data->o->file, "%s:%d: %s.\n",
1199 data->filename, data->lineno, err);
1200 free(err);
1201 emit_line(data->o->file, set, reset, line, 1);
1202 ws_check_emit(line + 1, len - 1, data->ws_rule,
1203 data->o->file, set, reset, ws);
1204 } else if (line[0] == ' ') {
1205 data->lineno++;
1206 data->trailing_blanks_start = 0;
1207 } else if (line[0] == '@') {
1208 char *plus = strchr(line, '+');
1209 if (plus)
1210 data->lineno = strtol(plus, NULL, 10) - 1;
1211 else
1212 die("invalid diff");
1213 data->trailing_blanks_start = 0;
1217 static unsigned char *deflate_it(char *data,
1218 unsigned long size,
1219 unsigned long *result_size)
1221 int bound;
1222 unsigned char *deflated;
1223 z_stream stream;
1225 memset(&stream, 0, sizeof(stream));
1226 deflateInit(&stream, zlib_compression_level);
1227 bound = deflateBound(&stream, size);
1228 deflated = xmalloc(bound);
1229 stream.next_out = deflated;
1230 stream.avail_out = bound;
1232 stream.next_in = (unsigned char *)data;
1233 stream.avail_in = size;
1234 while (deflate(&stream, Z_FINISH) == Z_OK)
1235 ; /* nothing */
1236 deflateEnd(&stream);
1237 *result_size = stream.total_out;
1238 return deflated;
1241 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1243 void *cp;
1244 void *delta;
1245 void *deflated;
1246 void *data;
1247 unsigned long orig_size;
1248 unsigned long delta_size;
1249 unsigned long deflate_size;
1250 unsigned long data_size;
1252 /* We could do deflated delta, or we could do just deflated two,
1253 * whichever is smaller.
1255 delta = NULL;
1256 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1257 if (one->size && two->size) {
1258 delta = diff_delta(one->ptr, one->size,
1259 two->ptr, two->size,
1260 &delta_size, deflate_size);
1261 if (delta) {
1262 void *to_free = delta;
1263 orig_size = delta_size;
1264 delta = deflate_it(delta, delta_size, &delta_size);
1265 free(to_free);
1269 if (delta && delta_size < deflate_size) {
1270 fprintf(file, "delta %lu\n", orig_size);
1271 free(deflated);
1272 data = delta;
1273 data_size = delta_size;
1275 else {
1276 fprintf(file, "literal %lu\n", two->size);
1277 free(delta);
1278 data = deflated;
1279 data_size = deflate_size;
1282 /* emit data encoded in base85 */
1283 cp = data;
1284 while (data_size) {
1285 int bytes = (52 < data_size) ? 52 : data_size;
1286 char line[70];
1287 data_size -= bytes;
1288 if (bytes <= 26)
1289 line[0] = bytes + 'A' - 1;
1290 else
1291 line[0] = bytes - 26 + 'a' - 1;
1292 encode_85(line + 1, cp, bytes);
1293 cp = (char *) cp + bytes;
1294 fputs(line, file);
1295 fputc('\n', file);
1297 fprintf(file, "\n");
1298 free(data);
1301 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1303 fprintf(file, "GIT binary patch\n");
1304 emit_binary_diff_body(file, one, two);
1305 emit_binary_diff_body(file, two, one);
1308 static void setup_diff_attr_check(struct git_attr_check *check)
1310 static struct git_attr *attr_diff;
1312 if (!attr_diff) {
1313 attr_diff = git_attr("diff", 4);
1315 check[0].attr = attr_diff;
1318 static void diff_filespec_check_attr(struct diff_filespec *one)
1320 struct git_attr_check attr_diff_check;
1321 int check_from_data = 0;
1323 if (one->checked_attr)
1324 return;
1326 setup_diff_attr_check(&attr_diff_check);
1327 one->is_binary = 0;
1328 one->funcname_pattern_ident = NULL;
1330 if (!git_checkattr(one->path, 1, &attr_diff_check)) {
1331 const char *value;
1333 /* binaryness */
1334 value = attr_diff_check.value;
1335 if (ATTR_TRUE(value))
1337 else if (ATTR_FALSE(value))
1338 one->is_binary = 1;
1339 else
1340 check_from_data = 1;
1342 /* funcname pattern ident */
1343 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1345 else
1346 one->funcname_pattern_ident = value;
1349 if (check_from_data) {
1350 if (!one->data && DIFF_FILE_VALID(one))
1351 diff_populate_filespec(one, 0);
1353 if (one->data)
1354 one->is_binary = buffer_is_binary(one->data, one->size);
1358 int diff_filespec_is_binary(struct diff_filespec *one)
1360 diff_filespec_check_attr(one);
1361 return one->is_binary;
1364 static const char *funcname_pattern(const char *ident)
1366 struct funcname_pattern *pp;
1368 for (pp = funcname_pattern_list; pp; pp = pp->next)
1369 if (!strcmp(ident, pp->name))
1370 return pp->pattern;
1371 return NULL;
1374 static struct builtin_funcname_pattern {
1375 const char *name;
1376 const char *pattern;
1377 } builtin_funcname_pattern[] = {
1378 { "java", "!^[ ]*\\(catch\\|do\\|for\\|if\\|instanceof\\|"
1379 "new\\|return\\|switch\\|throw\\|while\\)\n"
1380 "^[ ]*\\(\\([ ]*"
1381 "[A-Za-z_][A-Za-z_0-9]*\\)\\{2,\\}"
1382 "[ ]*([^;]*\\)$" },
1383 { "tex", "^\\(\\\\\\(sub\\)*section{.*\\)$" },
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 ecb.outf = xdiff_outf;
1517 ecb.priv = &ecbdata;
1518 ecbdata.xm.consume = fn_out_consume;
1519 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1520 ecbdata.diff_words =
1521 xcalloc(1, sizeof(struct diff_words_data));
1522 ecbdata.diff_words->file = o->file;
1524 xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1525 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1526 free_diff_words_data(&ecbdata);
1529 free_ab_and_return:
1530 diff_free_filespec_data(one);
1531 diff_free_filespec_data(two);
1532 free(a_one);
1533 free(b_two);
1534 return;
1537 static void builtin_diffstat(const char *name_a, const char *name_b,
1538 struct diff_filespec *one,
1539 struct diff_filespec *two,
1540 struct diffstat_t *diffstat,
1541 struct diff_options *o,
1542 int complete_rewrite)
1544 mmfile_t mf1, mf2;
1545 struct diffstat_file *data;
1547 data = diffstat_add(diffstat, name_a, name_b);
1549 if (!one || !two) {
1550 data->is_unmerged = 1;
1551 return;
1553 if (complete_rewrite) {
1554 diff_populate_filespec(one, 0);
1555 diff_populate_filespec(two, 0);
1556 data->deleted = count_lines(one->data, one->size);
1557 data->added = count_lines(two->data, two->size);
1558 goto free_and_return;
1560 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1561 die("unable to read files to diff");
1563 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1564 data->is_binary = 1;
1565 data->added = mf2.size;
1566 data->deleted = mf1.size;
1567 } else {
1568 /* Crazy xdl interfaces.. */
1569 xpparam_t xpp;
1570 xdemitconf_t xecfg;
1571 xdemitcb_t ecb;
1573 memset(&xecfg, 0, sizeof(xecfg));
1574 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1575 ecb.outf = xdiff_outf;
1576 ecb.priv = diffstat;
1577 xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1580 free_and_return:
1581 diff_free_filespec_data(one);
1582 diff_free_filespec_data(two);
1585 static void builtin_checkdiff(const char *name_a, const char *name_b,
1586 const char *attr_path,
1587 struct diff_filespec *one,
1588 struct diff_filespec *two,
1589 struct diff_options *o)
1591 mmfile_t mf1, mf2;
1592 struct checkdiff_t data;
1594 if (!two)
1595 return;
1597 memset(&data, 0, sizeof(data));
1598 data.xm.consume = checkdiff_consume;
1599 data.filename = name_b ? name_b : name_a;
1600 data.lineno = 0;
1601 data.o = o;
1602 data.ws_rule = whitespace_rule(attr_path);
1604 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1605 die("unable to read files to diff");
1608 * All the other codepaths check both sides, but not checking
1609 * the "old" side here is deliberate. We are checking the newly
1610 * introduced changes, and as long as the "new" side is text, we
1611 * can and should check what it introduces.
1613 if (diff_filespec_is_binary(two))
1614 goto free_and_return;
1615 else {
1616 /* Crazy xdl interfaces.. */
1617 xpparam_t xpp;
1618 xdemitconf_t xecfg;
1619 xdemitcb_t ecb;
1621 memset(&xecfg, 0, sizeof(xecfg));
1622 xpp.flags = XDF_NEED_MINIMAL;
1623 ecb.outf = xdiff_outf;
1624 ecb.priv = &data;
1625 xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1627 if (data.trailing_blanks_start) {
1628 fprintf(o->file, "%s:%d: ends with blank lines.\n",
1629 data.filename, data.trailing_blanks_start);
1630 data.status = 1; /* report errors */
1633 free_and_return:
1634 diff_free_filespec_data(one);
1635 diff_free_filespec_data(two);
1636 if (data.status)
1637 DIFF_OPT_SET(o, CHECK_FAILED);
1640 struct diff_filespec *alloc_filespec(const char *path)
1642 int namelen = strlen(path);
1643 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1645 memset(spec, 0, sizeof(*spec));
1646 spec->path = (char *)(spec + 1);
1647 memcpy(spec->path, path, namelen+1);
1648 spec->count = 1;
1649 return spec;
1652 void free_filespec(struct diff_filespec *spec)
1654 if (!--spec->count) {
1655 diff_free_filespec_data(spec);
1656 free(spec);
1660 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1661 unsigned short mode)
1663 if (mode) {
1664 spec->mode = canon_mode(mode);
1665 hashcpy(spec->sha1, sha1);
1666 spec->sha1_valid = !is_null_sha1(sha1);
1671 * Given a name and sha1 pair, if the index tells us the file in
1672 * the work tree has that object contents, return true, so that
1673 * prepare_temp_file() does not have to inflate and extract.
1675 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1677 struct cache_entry *ce;
1678 struct stat st;
1679 int pos, len;
1681 /* We do not read the cache ourselves here, because the
1682 * benchmark with my previous version that always reads cache
1683 * shows that it makes things worse for diff-tree comparing
1684 * two linux-2.6 kernel trees in an already checked out work
1685 * tree. This is because most diff-tree comparisons deal with
1686 * only a small number of files, while reading the cache is
1687 * expensive for a large project, and its cost outweighs the
1688 * savings we get by not inflating the object to a temporary
1689 * file. Practically, this code only helps when we are used
1690 * by diff-cache --cached, which does read the cache before
1691 * calling us.
1693 if (!active_cache)
1694 return 0;
1696 /* We want to avoid the working directory if our caller
1697 * doesn't need the data in a normal file, this system
1698 * is rather slow with its stat/open/mmap/close syscalls,
1699 * and the object is contained in a pack file. The pack
1700 * is probably already open and will be faster to obtain
1701 * the data through than the working directory. Loose
1702 * objects however would tend to be slower as they need
1703 * to be individually opened and inflated.
1705 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1706 return 0;
1708 len = strlen(name);
1709 pos = cache_name_pos(name, len);
1710 if (pos < 0)
1711 return 0;
1712 ce = active_cache[pos];
1715 * This is not the sha1 we are looking for, or
1716 * unreusable because it is not a regular file.
1718 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1719 return 0;
1722 * If ce matches the file in the work tree, we can reuse it.
1724 if (ce_uptodate(ce) ||
1725 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1726 return 1;
1728 return 0;
1731 static int populate_from_stdin(struct diff_filespec *s)
1733 struct strbuf buf;
1734 size_t size = 0;
1736 strbuf_init(&buf, 0);
1737 if (strbuf_read(&buf, 0, 0) < 0)
1738 return error("error while reading from stdin %s",
1739 strerror(errno));
1741 s->should_munmap = 0;
1742 s->data = strbuf_detach(&buf, &size);
1743 s->size = size;
1744 s->should_free = 1;
1745 return 0;
1748 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1750 int len;
1751 char *data = xmalloc(100);
1752 len = snprintf(data, 100,
1753 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1754 s->data = data;
1755 s->size = len;
1756 s->should_free = 1;
1757 if (size_only) {
1758 s->data = NULL;
1759 free(data);
1761 return 0;
1765 * While doing rename detection and pickaxe operation, we may need to
1766 * grab the data for the blob (or file) for our own in-core comparison.
1767 * diff_filespec has data and size fields for this purpose.
1769 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1771 int err = 0;
1772 if (!DIFF_FILE_VALID(s))
1773 die("internal error: asking to populate invalid file.");
1774 if (S_ISDIR(s->mode))
1775 return -1;
1777 if (s->data)
1778 return 0;
1780 if (size_only && 0 < s->size)
1781 return 0;
1783 if (S_ISGITLINK(s->mode))
1784 return diff_populate_gitlink(s, size_only);
1786 if (!s->sha1_valid ||
1787 reuse_worktree_file(s->path, s->sha1, 0)) {
1788 struct strbuf buf;
1789 struct stat st;
1790 int fd;
1792 if (!strcmp(s->path, "-"))
1793 return populate_from_stdin(s);
1795 if (lstat(s->path, &st) < 0) {
1796 if (errno == ENOENT) {
1797 err_empty:
1798 err = -1;
1799 empty:
1800 s->data = (char *)"";
1801 s->size = 0;
1802 return err;
1805 s->size = xsize_t(st.st_size);
1806 if (!s->size)
1807 goto empty;
1808 if (size_only)
1809 return 0;
1810 if (S_ISLNK(st.st_mode)) {
1811 int ret;
1812 s->data = xmalloc(s->size);
1813 s->should_free = 1;
1814 ret = readlink(s->path, s->data, s->size);
1815 if (ret < 0) {
1816 free(s->data);
1817 goto err_empty;
1819 return 0;
1821 fd = open(s->path, O_RDONLY);
1822 if (fd < 0)
1823 goto err_empty;
1824 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1825 close(fd);
1826 s->should_munmap = 1;
1829 * Convert from working tree format to canonical git format
1831 strbuf_init(&buf, 0);
1832 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
1833 size_t size = 0;
1834 munmap(s->data, s->size);
1835 s->should_munmap = 0;
1836 s->data = strbuf_detach(&buf, &size);
1837 s->size = size;
1838 s->should_free = 1;
1841 else {
1842 enum object_type type;
1843 if (size_only)
1844 type = sha1_object_info(s->sha1, &s->size);
1845 else {
1846 s->data = read_sha1_file(s->sha1, &type, &s->size);
1847 s->should_free = 1;
1850 return 0;
1853 void diff_free_filespec_blob(struct diff_filespec *s)
1855 if (s->should_free)
1856 free(s->data);
1857 else if (s->should_munmap)
1858 munmap(s->data, s->size);
1860 if (s->should_free || s->should_munmap) {
1861 s->should_free = s->should_munmap = 0;
1862 s->data = NULL;
1866 void diff_free_filespec_data(struct diff_filespec *s)
1868 diff_free_filespec_blob(s);
1869 free(s->cnt_data);
1870 s->cnt_data = NULL;
1873 static void prep_temp_blob(struct diff_tempfile *temp,
1874 void *blob,
1875 unsigned long size,
1876 const unsigned char *sha1,
1877 int mode)
1879 int fd;
1881 fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1882 if (fd < 0)
1883 die("unable to create temp-file: %s", strerror(errno));
1884 if (write_in_full(fd, blob, size) != size)
1885 die("unable to write temp-file");
1886 close(fd);
1887 temp->name = temp->tmp_path;
1888 strcpy(temp->hex, sha1_to_hex(sha1));
1889 temp->hex[40] = 0;
1890 sprintf(temp->mode, "%06o", mode);
1893 static void prepare_temp_file(const char *name,
1894 struct diff_tempfile *temp,
1895 struct diff_filespec *one)
1897 if (!DIFF_FILE_VALID(one)) {
1898 not_a_valid_file:
1899 /* A '-' entry produces this for file-2, and
1900 * a '+' entry produces this for file-1.
1902 temp->name = "/dev/null";
1903 strcpy(temp->hex, ".");
1904 strcpy(temp->mode, ".");
1905 return;
1908 if (!one->sha1_valid ||
1909 reuse_worktree_file(name, one->sha1, 1)) {
1910 struct stat st;
1911 if (lstat(name, &st) < 0) {
1912 if (errno == ENOENT)
1913 goto not_a_valid_file;
1914 die("stat(%s): %s", name, strerror(errno));
1916 if (S_ISLNK(st.st_mode)) {
1917 int ret;
1918 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1919 size_t sz = xsize_t(st.st_size);
1920 if (sizeof(buf) <= st.st_size)
1921 die("symlink too long: %s", name);
1922 ret = readlink(name, buf, sz);
1923 if (ret < 0)
1924 die("readlink(%s)", name);
1925 prep_temp_blob(temp, buf, sz,
1926 (one->sha1_valid ?
1927 one->sha1 : null_sha1),
1928 (one->sha1_valid ?
1929 one->mode : S_IFLNK));
1931 else {
1932 /* we can borrow from the file in the work tree */
1933 temp->name = name;
1934 if (!one->sha1_valid)
1935 strcpy(temp->hex, sha1_to_hex(null_sha1));
1936 else
1937 strcpy(temp->hex, sha1_to_hex(one->sha1));
1938 /* Even though we may sometimes borrow the
1939 * contents from the work tree, we always want
1940 * one->mode. mode is trustworthy even when
1941 * !(one->sha1_valid), as long as
1942 * DIFF_FILE_VALID(one).
1944 sprintf(temp->mode, "%06o", one->mode);
1946 return;
1948 else {
1949 if (diff_populate_filespec(one, 0))
1950 die("cannot read data blob for %s", one->path);
1951 prep_temp_blob(temp, one->data, one->size,
1952 one->sha1, one->mode);
1956 static void remove_tempfile(void)
1958 int i;
1960 for (i = 0; i < 2; i++)
1961 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1962 unlink(diff_temp[i].name);
1963 diff_temp[i].name = NULL;
1967 static void remove_tempfile_on_signal(int signo)
1969 remove_tempfile();
1970 signal(SIGINT, SIG_DFL);
1971 raise(signo);
1974 /* An external diff command takes:
1976 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1977 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1980 static void run_external_diff(const char *pgm,
1981 const char *name,
1982 const char *other,
1983 struct diff_filespec *one,
1984 struct diff_filespec *two,
1985 const char *xfrm_msg,
1986 int complete_rewrite)
1988 const char *spawn_arg[10];
1989 struct diff_tempfile *temp = diff_temp;
1990 int retval;
1991 static int atexit_asked = 0;
1992 const char *othername;
1993 const char **arg = &spawn_arg[0];
1995 othername = (other? other : name);
1996 if (one && two) {
1997 prepare_temp_file(name, &temp[0], one);
1998 prepare_temp_file(othername, &temp[1], two);
1999 if (! atexit_asked &&
2000 (temp[0].name == temp[0].tmp_path ||
2001 temp[1].name == temp[1].tmp_path)) {
2002 atexit_asked = 1;
2003 atexit(remove_tempfile);
2005 signal(SIGINT, remove_tempfile_on_signal);
2008 if (one && two) {
2009 *arg++ = pgm;
2010 *arg++ = name;
2011 *arg++ = temp[0].name;
2012 *arg++ = temp[0].hex;
2013 *arg++ = temp[0].mode;
2014 *arg++ = temp[1].name;
2015 *arg++ = temp[1].hex;
2016 *arg++ = temp[1].mode;
2017 if (other) {
2018 *arg++ = other;
2019 *arg++ = xfrm_msg;
2021 } else {
2022 *arg++ = pgm;
2023 *arg++ = name;
2025 *arg = NULL;
2026 fflush(NULL);
2027 retval = run_command_v_opt(spawn_arg, 0);
2028 remove_tempfile();
2029 if (retval) {
2030 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2031 exit(1);
2035 static const char *external_diff_attr(const char *name)
2037 struct git_attr_check attr_diff_check;
2039 if (!name)
2040 return NULL;
2042 setup_diff_attr_check(&attr_diff_check);
2043 if (!git_checkattr(name, 1, &attr_diff_check)) {
2044 const char *value = attr_diff_check.value;
2045 if (!ATTR_TRUE(value) &&
2046 !ATTR_FALSE(value) &&
2047 !ATTR_UNSET(value)) {
2048 struct ll_diff_driver *drv;
2050 for (drv = user_diff; drv; drv = drv->next)
2051 if (!strcmp(drv->name, value))
2052 return drv->cmd;
2055 return NULL;
2058 static void run_diff_cmd(const char *pgm,
2059 const char *name,
2060 const char *other,
2061 const char *attr_path,
2062 struct diff_filespec *one,
2063 struct diff_filespec *two,
2064 const char *xfrm_msg,
2065 struct diff_options *o,
2066 int complete_rewrite)
2068 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2069 pgm = NULL;
2070 else {
2071 const char *cmd = external_diff_attr(attr_path);
2072 if (cmd)
2073 pgm = cmd;
2076 if (pgm) {
2077 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2078 complete_rewrite);
2079 return;
2081 if (one && two)
2082 builtin_diff(name, other ? other : name,
2083 one, two, xfrm_msg, o, complete_rewrite);
2084 else
2085 fprintf(o->file, "* Unmerged path %s\n", name);
2088 static void diff_fill_sha1_info(struct diff_filespec *one)
2090 if (DIFF_FILE_VALID(one)) {
2091 if (!one->sha1_valid) {
2092 struct stat st;
2093 if (!strcmp(one->path, "-")) {
2094 hashcpy(one->sha1, null_sha1);
2095 return;
2097 if (lstat(one->path, &st) < 0)
2098 die("stat %s", one->path);
2099 if (index_path(one->sha1, one->path, &st, 0))
2100 die("cannot hash %s\n", one->path);
2103 else
2104 hashclr(one->sha1);
2107 static int similarity_index(struct diff_filepair *p)
2109 return p->score * 100 / MAX_SCORE;
2112 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2114 /* Strip the prefix but do not molest /dev/null and absolute paths */
2115 if (*namep && **namep != '/')
2116 *namep += prefix_length;
2117 if (*otherp && **otherp != '/')
2118 *otherp += prefix_length;
2121 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2123 const char *pgm = external_diff();
2124 struct strbuf msg;
2125 char *xfrm_msg;
2126 struct diff_filespec *one = p->one;
2127 struct diff_filespec *two = p->two;
2128 const char *name;
2129 const char *other;
2130 const char *attr_path;
2131 int complete_rewrite = 0;
2133 name = p->one->path;
2134 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2135 attr_path = name;
2136 if (o->prefix_length)
2137 strip_prefix(o->prefix_length, &name, &other);
2139 if (DIFF_PAIR_UNMERGED(p)) {
2140 run_diff_cmd(pgm, name, NULL, attr_path,
2141 NULL, NULL, NULL, o, 0);
2142 return;
2145 diff_fill_sha1_info(one);
2146 diff_fill_sha1_info(two);
2148 strbuf_init(&msg, PATH_MAX * 2 + 300);
2149 switch (p->status) {
2150 case DIFF_STATUS_COPIED:
2151 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2152 strbuf_addstr(&msg, "\ncopy from ");
2153 quote_c_style(name, &msg, NULL, 0);
2154 strbuf_addstr(&msg, "\ncopy to ");
2155 quote_c_style(other, &msg, NULL, 0);
2156 strbuf_addch(&msg, '\n');
2157 break;
2158 case DIFF_STATUS_RENAMED:
2159 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2160 strbuf_addstr(&msg, "\nrename from ");
2161 quote_c_style(name, &msg, NULL, 0);
2162 strbuf_addstr(&msg, "\nrename to ");
2163 quote_c_style(other, &msg, NULL, 0);
2164 strbuf_addch(&msg, '\n');
2165 break;
2166 case DIFF_STATUS_MODIFIED:
2167 if (p->score) {
2168 strbuf_addf(&msg, "dissimilarity index %d%%\n",
2169 similarity_index(p));
2170 complete_rewrite = 1;
2171 break;
2173 /* fallthru */
2174 default:
2175 /* nothing */
2179 if (hashcmp(one->sha1, two->sha1)) {
2180 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2182 if (DIFF_OPT_TST(o, BINARY)) {
2183 mmfile_t mf;
2184 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2185 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2186 abbrev = 40;
2188 strbuf_addf(&msg, "index %.*s..%.*s",
2189 abbrev, sha1_to_hex(one->sha1),
2190 abbrev, sha1_to_hex(two->sha1));
2191 if (one->mode == two->mode)
2192 strbuf_addf(&msg, " %06o", one->mode);
2193 strbuf_addch(&msg, '\n');
2196 if (msg.len)
2197 strbuf_setlen(&msg, msg.len - 1);
2198 xfrm_msg = msg.len ? msg.buf : NULL;
2200 if (!pgm &&
2201 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2202 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2203 /* a filepair that changes between file and symlink
2204 * needs to be split into deletion and creation.
2206 struct diff_filespec *null = alloc_filespec(two->path);
2207 run_diff_cmd(NULL, name, other, attr_path,
2208 one, null, xfrm_msg, o, 0);
2209 free(null);
2210 null = alloc_filespec(one->path);
2211 run_diff_cmd(NULL, name, other, attr_path,
2212 null, two, xfrm_msg, o, 0);
2213 free(null);
2215 else
2216 run_diff_cmd(pgm, name, other, attr_path,
2217 one, two, xfrm_msg, o, complete_rewrite);
2219 strbuf_release(&msg);
2222 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2223 struct diffstat_t *diffstat)
2225 const char *name;
2226 const char *other;
2227 int complete_rewrite = 0;
2229 if (DIFF_PAIR_UNMERGED(p)) {
2230 /* unmerged */
2231 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2232 return;
2235 name = p->one->path;
2236 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2238 if (o->prefix_length)
2239 strip_prefix(o->prefix_length, &name, &other);
2241 diff_fill_sha1_info(p->one);
2242 diff_fill_sha1_info(p->two);
2244 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2245 complete_rewrite = 1;
2246 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2249 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2251 const char *name;
2252 const char *other;
2253 const char *attr_path;
2255 if (DIFF_PAIR_UNMERGED(p)) {
2256 /* unmerged */
2257 return;
2260 name = p->one->path;
2261 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2262 attr_path = other ? other : name;
2264 if (o->prefix_length)
2265 strip_prefix(o->prefix_length, &name, &other);
2267 diff_fill_sha1_info(p->one);
2268 diff_fill_sha1_info(p->two);
2270 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2273 void diff_setup(struct diff_options *options)
2275 memset(options, 0, sizeof(*options));
2277 options->file = stdout;
2279 options->line_termination = '\n';
2280 options->break_opt = -1;
2281 options->rename_limit = -1;
2282 options->dirstat_percent = 3;
2283 options->context = 3;
2285 options->change = diff_change;
2286 options->add_remove = diff_addremove;
2287 if (diff_use_color_default > 0)
2288 DIFF_OPT_SET(options, COLOR_DIFF);
2289 else
2290 DIFF_OPT_CLR(options, COLOR_DIFF);
2291 options->detect_rename = diff_detect_rename_default;
2293 options->a_prefix = "a/";
2294 options->b_prefix = "b/";
2297 int diff_setup_done(struct diff_options *options)
2299 int count = 0;
2301 if (options->output_format & DIFF_FORMAT_NAME)
2302 count++;
2303 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2304 count++;
2305 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2306 count++;
2307 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2308 count++;
2309 if (count > 1)
2310 die("--name-only, --name-status, --check and -s are mutually exclusive");
2312 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2313 options->detect_rename = DIFF_DETECT_COPY;
2315 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2316 options->prefix = NULL;
2317 if (options->prefix)
2318 options->prefix_length = strlen(options->prefix);
2319 else
2320 options->prefix_length = 0;
2322 if (options->output_format & (DIFF_FORMAT_NAME |
2323 DIFF_FORMAT_NAME_STATUS |
2324 DIFF_FORMAT_CHECKDIFF |
2325 DIFF_FORMAT_NO_OUTPUT))
2326 options->output_format &= ~(DIFF_FORMAT_RAW |
2327 DIFF_FORMAT_NUMSTAT |
2328 DIFF_FORMAT_DIFFSTAT |
2329 DIFF_FORMAT_SHORTSTAT |
2330 DIFF_FORMAT_DIRSTAT |
2331 DIFF_FORMAT_SUMMARY |
2332 DIFF_FORMAT_PATCH);
2335 * These cases always need recursive; we do not drop caller-supplied
2336 * recursive bits for other formats here.
2338 if (options->output_format & (DIFF_FORMAT_PATCH |
2339 DIFF_FORMAT_NUMSTAT |
2340 DIFF_FORMAT_DIFFSTAT |
2341 DIFF_FORMAT_SHORTSTAT |
2342 DIFF_FORMAT_DIRSTAT |
2343 DIFF_FORMAT_SUMMARY |
2344 DIFF_FORMAT_CHECKDIFF))
2345 DIFF_OPT_SET(options, RECURSIVE);
2347 * Also pickaxe would not work very well if you do not say recursive
2349 if (options->pickaxe)
2350 DIFF_OPT_SET(options, RECURSIVE);
2352 if (options->detect_rename && options->rename_limit < 0)
2353 options->rename_limit = diff_rename_limit_default;
2354 if (options->setup & DIFF_SETUP_USE_CACHE) {
2355 if (!active_cache)
2356 /* read-cache does not die even when it fails
2357 * so it is safe for us to do this here. Also
2358 * it does not smudge active_cache or active_nr
2359 * when it fails, so we do not have to worry about
2360 * cleaning it up ourselves either.
2362 read_cache();
2364 if (options->abbrev <= 0 || 40 < options->abbrev)
2365 options->abbrev = 40; /* full */
2368 * It does not make sense to show the first hit we happened
2369 * to have found. It does not make sense not to return with
2370 * exit code in such a case either.
2372 if (DIFF_OPT_TST(options, QUIET)) {
2373 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2374 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2378 * If we postprocess in diffcore, we cannot simply return
2379 * upon the first hit. We need to run diff as usual.
2381 if (options->pickaxe || options->filter)
2382 DIFF_OPT_CLR(options, QUIET);
2384 return 0;
2387 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2389 char c, *eq;
2390 int len;
2392 if (*arg != '-')
2393 return 0;
2394 c = *++arg;
2395 if (!c)
2396 return 0;
2397 if (c == arg_short) {
2398 c = *++arg;
2399 if (!c)
2400 return 1;
2401 if (val && isdigit(c)) {
2402 char *end;
2403 int n = strtoul(arg, &end, 10);
2404 if (*end)
2405 return 0;
2406 *val = n;
2407 return 1;
2409 return 0;
2411 if (c != '-')
2412 return 0;
2413 arg++;
2414 eq = strchr(arg, '=');
2415 if (eq)
2416 len = eq - arg;
2417 else
2418 len = strlen(arg);
2419 if (!len || strncmp(arg, arg_long, len))
2420 return 0;
2421 if (eq) {
2422 int n;
2423 char *end;
2424 if (!isdigit(*++eq))
2425 return 0;
2426 n = strtoul(eq, &end, 10);
2427 if (*end)
2428 return 0;
2429 *val = n;
2431 return 1;
2434 static int diff_scoreopt_parse(const char *opt);
2436 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2438 const char *arg = av[0];
2440 /* Output format options */
2441 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2442 options->output_format |= DIFF_FORMAT_PATCH;
2443 else if (opt_arg(arg, 'U', "unified", &options->context))
2444 options->output_format |= DIFF_FORMAT_PATCH;
2445 else if (!strcmp(arg, "--raw"))
2446 options->output_format |= DIFF_FORMAT_RAW;
2447 else if (!strcmp(arg, "--patch-with-raw"))
2448 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2449 else if (!strcmp(arg, "--numstat"))
2450 options->output_format |= DIFF_FORMAT_NUMSTAT;
2451 else if (!strcmp(arg, "--shortstat"))
2452 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2453 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2454 options->output_format |= DIFF_FORMAT_DIRSTAT;
2455 else if (!strcmp(arg, "--cumulative"))
2456 options->output_format |= DIFF_FORMAT_CUMULATIVE;
2457 else if (!strcmp(arg, "--check"))
2458 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2459 else if (!strcmp(arg, "--summary"))
2460 options->output_format |= DIFF_FORMAT_SUMMARY;
2461 else if (!strcmp(arg, "--patch-with-stat"))
2462 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2463 else if (!strcmp(arg, "--name-only"))
2464 options->output_format |= DIFF_FORMAT_NAME;
2465 else if (!strcmp(arg, "--name-status"))
2466 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2467 else if (!strcmp(arg, "-s"))
2468 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2469 else if (!prefixcmp(arg, "--stat")) {
2470 char *end;
2471 int width = options->stat_width;
2472 int name_width = options->stat_name_width;
2473 arg += 6;
2474 end = (char *)arg;
2476 switch (*arg) {
2477 case '-':
2478 if (!prefixcmp(arg, "-width="))
2479 width = strtoul(arg + 7, &end, 10);
2480 else if (!prefixcmp(arg, "-name-width="))
2481 name_width = strtoul(arg + 12, &end, 10);
2482 break;
2483 case '=':
2484 width = strtoul(arg+1, &end, 10);
2485 if (*end == ',')
2486 name_width = strtoul(end+1, &end, 10);
2489 /* Important! This checks all the error cases! */
2490 if (*end)
2491 return 0;
2492 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2493 options->stat_name_width = name_width;
2494 options->stat_width = width;
2497 /* renames options */
2498 else if (!prefixcmp(arg, "-B")) {
2499 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2500 return -1;
2502 else if (!prefixcmp(arg, "-M")) {
2503 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2504 return -1;
2505 options->detect_rename = DIFF_DETECT_RENAME;
2507 else if (!prefixcmp(arg, "-C")) {
2508 if (options->detect_rename == DIFF_DETECT_COPY)
2509 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2510 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2511 return -1;
2512 options->detect_rename = DIFF_DETECT_COPY;
2514 else if (!strcmp(arg, "--no-renames"))
2515 options->detect_rename = 0;
2516 else if (!strcmp(arg, "--relative"))
2517 DIFF_OPT_SET(options, RELATIVE_NAME);
2518 else if (!prefixcmp(arg, "--relative=")) {
2519 DIFF_OPT_SET(options, RELATIVE_NAME);
2520 options->prefix = arg + 11;
2523 /* xdiff options */
2524 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2525 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2526 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2527 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2528 else if (!strcmp(arg, "--ignore-space-at-eol"))
2529 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2531 /* flags options */
2532 else if (!strcmp(arg, "--binary")) {
2533 options->output_format |= DIFF_FORMAT_PATCH;
2534 DIFF_OPT_SET(options, BINARY);
2536 else if (!strcmp(arg, "--full-index"))
2537 DIFF_OPT_SET(options, FULL_INDEX);
2538 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2539 DIFF_OPT_SET(options, TEXT);
2540 else if (!strcmp(arg, "-R"))
2541 DIFF_OPT_SET(options, REVERSE_DIFF);
2542 else if (!strcmp(arg, "--find-copies-harder"))
2543 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2544 else if (!strcmp(arg, "--follow"))
2545 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2546 else if (!strcmp(arg, "--color"))
2547 DIFF_OPT_SET(options, COLOR_DIFF);
2548 else if (!strcmp(arg, "--no-color"))
2549 DIFF_OPT_CLR(options, COLOR_DIFF);
2550 else if (!strcmp(arg, "--color-words"))
2551 options->flags |= DIFF_OPT_COLOR_DIFF | DIFF_OPT_COLOR_DIFF_WORDS;
2552 else if (!strcmp(arg, "--exit-code"))
2553 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2554 else if (!strcmp(arg, "--quiet"))
2555 DIFF_OPT_SET(options, QUIET);
2556 else if (!strcmp(arg, "--ext-diff"))
2557 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2558 else if (!strcmp(arg, "--no-ext-diff"))
2559 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2560 else if (!strcmp(arg, "--ignore-submodules"))
2561 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2563 /* misc options */
2564 else if (!strcmp(arg, "-z"))
2565 options->line_termination = 0;
2566 else if (!prefixcmp(arg, "-l"))
2567 options->rename_limit = strtoul(arg+2, NULL, 10);
2568 else if (!prefixcmp(arg, "-S"))
2569 options->pickaxe = arg + 2;
2570 else if (!strcmp(arg, "--pickaxe-all"))
2571 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2572 else if (!strcmp(arg, "--pickaxe-regex"))
2573 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2574 else if (!prefixcmp(arg, "-O"))
2575 options->orderfile = arg + 2;
2576 else if (!prefixcmp(arg, "--diff-filter="))
2577 options->filter = arg + 14;
2578 else if (!strcmp(arg, "--abbrev"))
2579 options->abbrev = DEFAULT_ABBREV;
2580 else if (!prefixcmp(arg, "--abbrev=")) {
2581 options->abbrev = strtoul(arg + 9, NULL, 10);
2582 if (options->abbrev < MINIMUM_ABBREV)
2583 options->abbrev = MINIMUM_ABBREV;
2584 else if (40 < options->abbrev)
2585 options->abbrev = 40;
2587 else if (!prefixcmp(arg, "--src-prefix="))
2588 options->a_prefix = arg + 13;
2589 else if (!prefixcmp(arg, "--dst-prefix="))
2590 options->b_prefix = arg + 13;
2591 else if (!strcmp(arg, "--no-prefix"))
2592 options->a_prefix = options->b_prefix = "";
2593 else if (!prefixcmp(arg, "--output=")) {
2594 options->file = fopen(arg + strlen("--output="), "w");
2595 options->close_file = 1;
2596 } else
2597 return 0;
2598 return 1;
2601 static int parse_num(const char **cp_p)
2603 unsigned long num, scale;
2604 int ch, dot;
2605 const char *cp = *cp_p;
2607 num = 0;
2608 scale = 1;
2609 dot = 0;
2610 for(;;) {
2611 ch = *cp;
2612 if ( !dot && ch == '.' ) {
2613 scale = 1;
2614 dot = 1;
2615 } else if ( ch == '%' ) {
2616 scale = dot ? scale*100 : 100;
2617 cp++; /* % is always at the end */
2618 break;
2619 } else if ( ch >= '0' && ch <= '9' ) {
2620 if ( scale < 100000 ) {
2621 scale *= 10;
2622 num = (num*10) + (ch-'0');
2624 } else {
2625 break;
2627 cp++;
2629 *cp_p = cp;
2631 /* user says num divided by scale and we say internally that
2632 * is MAX_SCORE * num / scale.
2634 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2637 static int diff_scoreopt_parse(const char *opt)
2639 int opt1, opt2, cmd;
2641 if (*opt++ != '-')
2642 return -1;
2643 cmd = *opt++;
2644 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2645 return -1; /* that is not a -M, -C nor -B option */
2647 opt1 = parse_num(&opt);
2648 if (cmd != 'B')
2649 opt2 = 0;
2650 else {
2651 if (*opt == 0)
2652 opt2 = 0;
2653 else if (*opt != '/')
2654 return -1; /* we expect -B80/99 or -B80 */
2655 else {
2656 opt++;
2657 opt2 = parse_num(&opt);
2660 if (*opt != 0)
2661 return -1;
2662 return opt1 | (opt2 << 16);
2665 struct diff_queue_struct diff_queued_diff;
2667 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2669 if (queue->alloc <= queue->nr) {
2670 queue->alloc = alloc_nr(queue->alloc);
2671 queue->queue = xrealloc(queue->queue,
2672 sizeof(dp) * queue->alloc);
2674 queue->queue[queue->nr++] = dp;
2677 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2678 struct diff_filespec *one,
2679 struct diff_filespec *two)
2681 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2682 dp->one = one;
2683 dp->two = two;
2684 if (queue)
2685 diff_q(queue, dp);
2686 return dp;
2689 void diff_free_filepair(struct diff_filepair *p)
2691 free_filespec(p->one);
2692 free_filespec(p->two);
2693 free(p);
2696 /* This is different from find_unique_abbrev() in that
2697 * it stuffs the result with dots for alignment.
2699 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2701 int abblen;
2702 const char *abbrev;
2703 if (len == 40)
2704 return sha1_to_hex(sha1);
2706 abbrev = find_unique_abbrev(sha1, len);
2707 abblen = strlen(abbrev);
2708 if (abblen < 37) {
2709 static char hex[41];
2710 if (len < abblen && abblen <= len + 2)
2711 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2712 else
2713 sprintf(hex, "%s...", abbrev);
2714 return hex;
2716 return sha1_to_hex(sha1);
2719 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2721 int line_termination = opt->line_termination;
2722 int inter_name_termination = line_termination ? '\t' : '\0';
2724 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2725 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2726 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2727 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2729 if (p->score) {
2730 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2731 inter_name_termination);
2732 } else {
2733 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2736 if (p->status == DIFF_STATUS_COPIED ||
2737 p->status == DIFF_STATUS_RENAMED) {
2738 const char *name_a, *name_b;
2739 name_a = p->one->path;
2740 name_b = p->two->path;
2741 strip_prefix(opt->prefix_length, &name_a, &name_b);
2742 write_name_quoted(name_a, opt->file, inter_name_termination);
2743 write_name_quoted(name_b, opt->file, line_termination);
2744 } else {
2745 const char *name_a, *name_b;
2746 name_a = p->one->mode ? p->one->path : p->two->path;
2747 name_b = NULL;
2748 strip_prefix(opt->prefix_length, &name_a, &name_b);
2749 write_name_quoted(name_a, opt->file, line_termination);
2753 int diff_unmodified_pair(struct diff_filepair *p)
2755 /* This function is written stricter than necessary to support
2756 * the currently implemented transformers, but the idea is to
2757 * let transformers to produce diff_filepairs any way they want,
2758 * and filter and clean them up here before producing the output.
2760 struct diff_filespec *one = p->one, *two = p->two;
2762 if (DIFF_PAIR_UNMERGED(p))
2763 return 0; /* unmerged is interesting */
2765 /* deletion, addition, mode or type change
2766 * and rename are all interesting.
2768 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2769 DIFF_PAIR_MODE_CHANGED(p) ||
2770 strcmp(one->path, two->path))
2771 return 0;
2773 /* both are valid and point at the same path. that is, we are
2774 * dealing with a change.
2776 if (one->sha1_valid && two->sha1_valid &&
2777 !hashcmp(one->sha1, two->sha1))
2778 return 1; /* no change */
2779 if (!one->sha1_valid && !two->sha1_valid)
2780 return 1; /* both look at the same file on the filesystem. */
2781 return 0;
2784 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2786 if (diff_unmodified_pair(p))
2787 return;
2789 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2790 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2791 return; /* no tree diffs in patch format */
2793 run_diff(p, o);
2796 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2797 struct diffstat_t *diffstat)
2799 if (diff_unmodified_pair(p))
2800 return;
2802 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2803 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2804 return; /* no tree diffs in patch format */
2806 run_diffstat(p, o, diffstat);
2809 static void diff_flush_checkdiff(struct diff_filepair *p,
2810 struct diff_options *o)
2812 if (diff_unmodified_pair(p))
2813 return;
2815 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2816 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2817 return; /* no tree diffs in patch format */
2819 run_checkdiff(p, o);
2822 int diff_queue_is_empty(void)
2824 struct diff_queue_struct *q = &diff_queued_diff;
2825 int i;
2826 for (i = 0; i < q->nr; i++)
2827 if (!diff_unmodified_pair(q->queue[i]))
2828 return 0;
2829 return 1;
2832 #if DIFF_DEBUG
2833 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2835 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2836 x, one ? one : "",
2837 s->path,
2838 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2839 s->mode,
2840 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2841 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2842 x, one ? one : "",
2843 s->size, s->xfrm_flags);
2846 void diff_debug_filepair(const struct diff_filepair *p, int i)
2848 diff_debug_filespec(p->one, i, "one");
2849 diff_debug_filespec(p->two, i, "two");
2850 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2851 p->score, p->status ? p->status : '?',
2852 p->one->rename_used, p->broken_pair);
2855 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2857 int i;
2858 if (msg)
2859 fprintf(stderr, "%s\n", msg);
2860 fprintf(stderr, "q->nr = %d\n", q->nr);
2861 for (i = 0; i < q->nr; i++) {
2862 struct diff_filepair *p = q->queue[i];
2863 diff_debug_filepair(p, i);
2866 #endif
2868 static void diff_resolve_rename_copy(void)
2870 int i;
2871 struct diff_filepair *p;
2872 struct diff_queue_struct *q = &diff_queued_diff;
2874 diff_debug_queue("resolve-rename-copy", q);
2876 for (i = 0; i < q->nr; i++) {
2877 p = q->queue[i];
2878 p->status = 0; /* undecided */
2879 if (DIFF_PAIR_UNMERGED(p))
2880 p->status = DIFF_STATUS_UNMERGED;
2881 else if (!DIFF_FILE_VALID(p->one))
2882 p->status = DIFF_STATUS_ADDED;
2883 else if (!DIFF_FILE_VALID(p->two))
2884 p->status = DIFF_STATUS_DELETED;
2885 else if (DIFF_PAIR_TYPE_CHANGED(p))
2886 p->status = DIFF_STATUS_TYPE_CHANGED;
2888 /* from this point on, we are dealing with a pair
2889 * whose both sides are valid and of the same type, i.e.
2890 * either in-place edit or rename/copy edit.
2892 else if (DIFF_PAIR_RENAME(p)) {
2894 * A rename might have re-connected a broken
2895 * pair up, causing the pathnames to be the
2896 * same again. If so, that's not a rename at
2897 * all, just a modification..
2899 * Otherwise, see if this source was used for
2900 * multiple renames, in which case we decrement
2901 * the count, and call it a copy.
2903 if (!strcmp(p->one->path, p->two->path))
2904 p->status = DIFF_STATUS_MODIFIED;
2905 else if (--p->one->rename_used > 0)
2906 p->status = DIFF_STATUS_COPIED;
2907 else
2908 p->status = DIFF_STATUS_RENAMED;
2910 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2911 p->one->mode != p->two->mode ||
2912 is_null_sha1(p->one->sha1))
2913 p->status = DIFF_STATUS_MODIFIED;
2914 else {
2915 /* This is a "no-change" entry and should not
2916 * happen anymore, but prepare for broken callers.
2918 error("feeding unmodified %s to diffcore",
2919 p->one->path);
2920 p->status = DIFF_STATUS_UNKNOWN;
2923 diff_debug_queue("resolve-rename-copy done", q);
2926 static int check_pair_status(struct diff_filepair *p)
2928 switch (p->status) {
2929 case DIFF_STATUS_UNKNOWN:
2930 return 0;
2931 case 0:
2932 die("internal error in diff-resolve-rename-copy");
2933 default:
2934 return 1;
2938 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2940 int fmt = opt->output_format;
2942 if (fmt & DIFF_FORMAT_CHECKDIFF)
2943 diff_flush_checkdiff(p, opt);
2944 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2945 diff_flush_raw(p, opt);
2946 else if (fmt & DIFF_FORMAT_NAME) {
2947 const char *name_a, *name_b;
2948 name_a = p->two->path;
2949 name_b = NULL;
2950 strip_prefix(opt->prefix_length, &name_a, &name_b);
2951 write_name_quoted(name_a, opt->file, opt->line_termination);
2955 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
2957 if (fs->mode)
2958 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
2959 else
2960 fprintf(file, " %s ", newdelete);
2961 write_name_quoted(fs->path, file, '\n');
2965 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
2967 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2968 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
2969 show_name ? ' ' : '\n');
2970 if (show_name) {
2971 write_name_quoted(p->two->path, file, '\n');
2976 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
2978 char *names = pprint_rename(p->one->path, p->two->path);
2980 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2981 free(names);
2982 show_mode_change(file, p, 0);
2985 static void diff_summary(FILE *file, struct diff_filepair *p)
2987 switch(p->status) {
2988 case DIFF_STATUS_DELETED:
2989 show_file_mode_name(file, "delete", p->one);
2990 break;
2991 case DIFF_STATUS_ADDED:
2992 show_file_mode_name(file, "create", p->two);
2993 break;
2994 case DIFF_STATUS_COPIED:
2995 show_rename_copy(file, "copy", p);
2996 break;
2997 case DIFF_STATUS_RENAMED:
2998 show_rename_copy(file, "rename", p);
2999 break;
3000 default:
3001 if (p->score) {
3002 fputs(" rewrite ", file);
3003 write_name_quoted(p->two->path, file, ' ');
3004 fprintf(file, "(%d%%)\n", similarity_index(p));
3006 show_mode_change(file, p, !p->score);
3007 break;
3011 struct patch_id_t {
3012 struct xdiff_emit_state xm;
3013 SHA_CTX *ctx;
3014 int patchlen;
3017 static int remove_space(char *line, int len)
3019 int i;
3020 char *dst = line;
3021 unsigned char c;
3023 for (i = 0; i < len; i++)
3024 if (!isspace((c = line[i])))
3025 *dst++ = c;
3027 return dst - line;
3030 static void patch_id_consume(void *priv, char *line, unsigned long len)
3032 struct patch_id_t *data = priv;
3033 int new_len;
3035 /* Ignore line numbers when computing the SHA1 of the patch */
3036 if (!prefixcmp(line, "@@ -"))
3037 return;
3039 new_len = remove_space(line, len);
3041 SHA1_Update(data->ctx, line, new_len);
3042 data->patchlen += new_len;
3045 /* returns 0 upon success, and writes result into sha1 */
3046 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3048 struct diff_queue_struct *q = &diff_queued_diff;
3049 int i;
3050 SHA_CTX ctx;
3051 struct patch_id_t data;
3052 char buffer[PATH_MAX * 4 + 20];
3054 SHA1_Init(&ctx);
3055 memset(&data, 0, sizeof(struct patch_id_t));
3056 data.ctx = &ctx;
3057 data.xm.consume = patch_id_consume;
3059 for (i = 0; i < q->nr; i++) {
3060 xpparam_t xpp;
3061 xdemitconf_t xecfg;
3062 xdemitcb_t ecb;
3063 mmfile_t mf1, mf2;
3064 struct diff_filepair *p = q->queue[i];
3065 int len1, len2;
3067 memset(&xecfg, 0, sizeof(xecfg));
3068 if (p->status == 0)
3069 return error("internal diff status error");
3070 if (p->status == DIFF_STATUS_UNKNOWN)
3071 continue;
3072 if (diff_unmodified_pair(p))
3073 continue;
3074 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3075 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3076 continue;
3077 if (DIFF_PAIR_UNMERGED(p))
3078 continue;
3080 diff_fill_sha1_info(p->one);
3081 diff_fill_sha1_info(p->two);
3082 if (fill_mmfile(&mf1, p->one) < 0 ||
3083 fill_mmfile(&mf2, p->two) < 0)
3084 return error("unable to read files to diff");
3086 len1 = remove_space(p->one->path, strlen(p->one->path));
3087 len2 = remove_space(p->two->path, strlen(p->two->path));
3088 if (p->one->mode == 0)
3089 len1 = snprintf(buffer, sizeof(buffer),
3090 "diff--gita/%.*sb/%.*s"
3091 "newfilemode%06o"
3092 "---/dev/null"
3093 "+++b/%.*s",
3094 len1, p->one->path,
3095 len2, p->two->path,
3096 p->two->mode,
3097 len2, p->two->path);
3098 else if (p->two->mode == 0)
3099 len1 = snprintf(buffer, sizeof(buffer),
3100 "diff--gita/%.*sb/%.*s"
3101 "deletedfilemode%06o"
3102 "---a/%.*s"
3103 "+++/dev/null",
3104 len1, p->one->path,
3105 len2, p->two->path,
3106 p->one->mode,
3107 len1, p->one->path);
3108 else
3109 len1 = snprintf(buffer, sizeof(buffer),
3110 "diff--gita/%.*sb/%.*s"
3111 "---a/%.*s"
3112 "+++b/%.*s",
3113 len1, p->one->path,
3114 len2, p->two->path,
3115 len1, p->one->path,
3116 len2, p->two->path);
3117 SHA1_Update(&ctx, buffer, len1);
3119 xpp.flags = XDF_NEED_MINIMAL;
3120 xecfg.ctxlen = 3;
3121 xecfg.flags = XDL_EMIT_FUNCNAMES;
3122 ecb.outf = xdiff_outf;
3123 ecb.priv = &data;
3124 xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
3127 SHA1_Final(sha1, &ctx);
3128 return 0;
3131 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3133 struct diff_queue_struct *q = &diff_queued_diff;
3134 int i;
3135 int result = diff_get_patch_id(options, sha1);
3137 for (i = 0; i < q->nr; i++)
3138 diff_free_filepair(q->queue[i]);
3140 free(q->queue);
3141 q->queue = NULL;
3142 q->nr = q->alloc = 0;
3144 return result;
3147 static int is_summary_empty(const struct diff_queue_struct *q)
3149 int i;
3151 for (i = 0; i < q->nr; i++) {
3152 const struct diff_filepair *p = q->queue[i];
3154 switch (p->status) {
3155 case DIFF_STATUS_DELETED:
3156 case DIFF_STATUS_ADDED:
3157 case DIFF_STATUS_COPIED:
3158 case DIFF_STATUS_RENAMED:
3159 return 0;
3160 default:
3161 if (p->score)
3162 return 0;
3163 if (p->one->mode && p->two->mode &&
3164 p->one->mode != p->two->mode)
3165 return 0;
3166 break;
3169 return 1;
3172 void diff_flush(struct diff_options *options)
3174 struct diff_queue_struct *q = &diff_queued_diff;
3175 int i, output_format = options->output_format;
3176 int separator = 0;
3179 * Order: raw, stat, summary, patch
3180 * or: name/name-status/checkdiff (other bits clear)
3182 if (!q->nr)
3183 goto free_queue;
3185 if (output_format & (DIFF_FORMAT_RAW |
3186 DIFF_FORMAT_NAME |
3187 DIFF_FORMAT_NAME_STATUS |
3188 DIFF_FORMAT_CHECKDIFF)) {
3189 for (i = 0; i < q->nr; i++) {
3190 struct diff_filepair *p = q->queue[i];
3191 if (check_pair_status(p))
3192 flush_one_pair(p, options);
3194 separator++;
3197 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3198 struct diffstat_t diffstat;
3200 memset(&diffstat, 0, sizeof(struct diffstat_t));
3201 diffstat.xm.consume = diffstat_consume;
3202 for (i = 0; i < q->nr; i++) {
3203 struct diff_filepair *p = q->queue[i];
3204 if (check_pair_status(p))
3205 diff_flush_stat(p, options, &diffstat);
3207 if (output_format & DIFF_FORMAT_NUMSTAT)
3208 show_numstat(&diffstat, options);
3209 if (output_format & DIFF_FORMAT_DIFFSTAT)
3210 show_stats(&diffstat, options);
3211 if (output_format & DIFF_FORMAT_SHORTSTAT)
3212 show_shortstats(&diffstat, options);
3213 free_diffstat_info(&diffstat);
3214 separator++;
3216 if (output_format & DIFF_FORMAT_DIRSTAT)
3217 show_dirstat(options);
3219 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3220 for (i = 0; i < q->nr; i++)
3221 diff_summary(options->file, q->queue[i]);
3222 separator++;
3225 if (output_format & DIFF_FORMAT_PATCH) {
3226 if (separator) {
3227 putc(options->line_termination, options->file);
3228 if (options->stat_sep) {
3229 /* attach patch instead of inline */
3230 fputs(options->stat_sep, options->file);
3234 for (i = 0; i < q->nr; i++) {
3235 struct diff_filepair *p = q->queue[i];
3236 if (check_pair_status(p))
3237 diff_flush_patch(p, options);
3241 if (output_format & DIFF_FORMAT_CALLBACK)
3242 options->format_callback(q, options, options->format_callback_data);
3244 for (i = 0; i < q->nr; i++)
3245 diff_free_filepair(q->queue[i]);
3246 free_queue:
3247 free(q->queue);
3248 q->queue = NULL;
3249 q->nr = q->alloc = 0;
3250 if (options->close_file)
3251 fclose(options->file);
3254 static void diffcore_apply_filter(const char *filter)
3256 int i;
3257 struct diff_queue_struct *q = &diff_queued_diff;
3258 struct diff_queue_struct outq;
3259 outq.queue = NULL;
3260 outq.nr = outq.alloc = 0;
3262 if (!filter)
3263 return;
3265 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3266 int found;
3267 for (i = found = 0; !found && i < q->nr; i++) {
3268 struct diff_filepair *p = q->queue[i];
3269 if (((p->status == DIFF_STATUS_MODIFIED) &&
3270 ((p->score &&
3271 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3272 (!p->score &&
3273 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3274 ((p->status != DIFF_STATUS_MODIFIED) &&
3275 strchr(filter, p->status)))
3276 found++;
3278 if (found)
3279 return;
3281 /* otherwise we will clear the whole queue
3282 * by copying the empty outq at the end of this
3283 * function, but first clear the current entries
3284 * in the queue.
3286 for (i = 0; i < q->nr; i++)
3287 diff_free_filepair(q->queue[i]);
3289 else {
3290 /* Only the matching ones */
3291 for (i = 0; i < q->nr; i++) {
3292 struct diff_filepair *p = q->queue[i];
3294 if (((p->status == DIFF_STATUS_MODIFIED) &&
3295 ((p->score &&
3296 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3297 (!p->score &&
3298 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3299 ((p->status != DIFF_STATUS_MODIFIED) &&
3300 strchr(filter, p->status)))
3301 diff_q(&outq, p);
3302 else
3303 diff_free_filepair(p);
3306 free(q->queue);
3307 *q = outq;
3310 /* Check whether two filespecs with the same mode and size are identical */
3311 static int diff_filespec_is_identical(struct diff_filespec *one,
3312 struct diff_filespec *two)
3314 if (S_ISGITLINK(one->mode))
3315 return 0;
3316 if (diff_populate_filespec(one, 0))
3317 return 0;
3318 if (diff_populate_filespec(two, 0))
3319 return 0;
3320 return !memcmp(one->data, two->data, one->size);
3323 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3325 int i;
3326 struct diff_queue_struct *q = &diff_queued_diff;
3327 struct diff_queue_struct outq;
3328 outq.queue = NULL;
3329 outq.nr = outq.alloc = 0;
3331 for (i = 0; i < q->nr; i++) {
3332 struct diff_filepair *p = q->queue[i];
3335 * 1. Entries that come from stat info dirtyness
3336 * always have both sides (iow, not create/delete),
3337 * one side of the object name is unknown, with
3338 * the same mode and size. Keep the ones that
3339 * do not match these criteria. They have real
3340 * differences.
3342 * 2. At this point, the file is known to be modified,
3343 * with the same mode and size, and the object
3344 * name of one side is unknown. Need to inspect
3345 * the identical contents.
3347 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3348 !DIFF_FILE_VALID(p->two) ||
3349 (p->one->sha1_valid && p->two->sha1_valid) ||
3350 (p->one->mode != p->two->mode) ||
3351 diff_populate_filespec(p->one, 1) ||
3352 diff_populate_filespec(p->two, 1) ||
3353 (p->one->size != p->two->size) ||
3354 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3355 diff_q(&outq, p);
3356 else {
3358 * The caller can subtract 1 from skip_stat_unmatch
3359 * to determine how many paths were dirty only
3360 * due to stat info mismatch.
3362 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3363 diffopt->skip_stat_unmatch++;
3364 diff_free_filepair(p);
3367 free(q->queue);
3368 *q = outq;
3371 void diffcore_std(struct diff_options *options)
3373 if (DIFF_OPT_TST(options, QUIET))
3374 return;
3376 if (options->skip_stat_unmatch && !DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3377 diffcore_skip_stat_unmatch(options);
3378 if (options->break_opt != -1)
3379 diffcore_break(options->break_opt);
3380 if (options->detect_rename)
3381 diffcore_rename(options);
3382 if (options->break_opt != -1)
3383 diffcore_merge_broken();
3384 if (options->pickaxe)
3385 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3386 if (options->orderfile)
3387 diffcore_order(options->orderfile);
3388 diff_resolve_rename_copy();
3389 diffcore_apply_filter(options->filter);
3391 if (diff_queued_diff.nr)
3392 DIFF_OPT_SET(options, HAS_CHANGES);
3393 else
3394 DIFF_OPT_CLR(options, HAS_CHANGES);
3397 int diff_result_code(struct diff_options *opt, int status)
3399 int result = 0;
3400 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3401 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3402 return status;
3403 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3404 DIFF_OPT_TST(opt, HAS_CHANGES))
3405 result |= 01;
3406 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3407 DIFF_OPT_TST(opt, CHECK_FAILED))
3408 result |= 02;
3409 return result;
3412 void diff_addremove(struct diff_options *options,
3413 int addremove, unsigned mode,
3414 const unsigned char *sha1,
3415 const char *concatpath)
3417 struct diff_filespec *one, *two;
3419 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3420 return;
3422 /* This may look odd, but it is a preparation for
3423 * feeding "there are unchanged files which should
3424 * not produce diffs, but when you are doing copy
3425 * detection you would need them, so here they are"
3426 * entries to the diff-core. They will be prefixed
3427 * with something like '=' or '*' (I haven't decided
3428 * which but should not make any difference).
3429 * Feeding the same new and old to diff_change()
3430 * also has the same effect.
3431 * Before the final output happens, they are pruned after
3432 * merged into rename/copy pairs as appropriate.
3434 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3435 addremove = (addremove == '+' ? '-' :
3436 addremove == '-' ? '+' : addremove);
3438 if (options->prefix &&
3439 strncmp(concatpath, options->prefix, options->prefix_length))
3440 return;
3442 one = alloc_filespec(concatpath);
3443 two = alloc_filespec(concatpath);
3445 if (addremove != '+')
3446 fill_filespec(one, sha1, mode);
3447 if (addremove != '-')
3448 fill_filespec(two, sha1, mode);
3450 diff_queue(&diff_queued_diff, one, two);
3451 DIFF_OPT_SET(options, HAS_CHANGES);
3454 void diff_change(struct diff_options *options,
3455 unsigned old_mode, unsigned new_mode,
3456 const unsigned char *old_sha1,
3457 const unsigned char *new_sha1,
3458 const char *concatpath)
3460 struct diff_filespec *one, *two;
3462 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3463 && S_ISGITLINK(new_mode))
3464 return;
3466 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3467 unsigned tmp;
3468 const unsigned char *tmp_c;
3469 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3470 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3473 if (options->prefix &&
3474 strncmp(concatpath, options->prefix, options->prefix_length))
3475 return;
3477 one = alloc_filespec(concatpath);
3478 two = alloc_filespec(concatpath);
3479 fill_filespec(one, old_sha1, old_mode);
3480 fill_filespec(two, new_sha1, new_mode);
3482 diff_queue(&diff_queued_diff, one, two);
3483 DIFF_OPT_SET(options, HAS_CHANGES);
3486 void diff_unmerge(struct diff_options *options,
3487 const char *path,
3488 unsigned mode, const unsigned char *sha1)
3490 struct diff_filespec *one, *two;
3492 if (options->prefix &&
3493 strncmp(path, options->prefix, options->prefix_length))
3494 return;
3496 one = alloc_filespec(path);
3497 two = alloc_filespec(path);
3498 fill_filespec(one, sha1, mode);
3499 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;