git.el: Never clear the status buffer, only update the files.
[git/dscho.git] / diff.c
blobf644947c823e824a294414a660beac02b4182fe4
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"
14 #include "userdiff.h"
16 #ifdef NO_FAST_WORKING_DIRECTORY
17 #define FAST_WORKING_DIRECTORY 0
18 #else
19 #define FAST_WORKING_DIRECTORY 1
20 #endif
22 static int diff_detect_rename_default;
23 static int diff_rename_limit_default = 200;
24 static int diff_suppress_blank_empty;
25 int diff_use_color_default = -1;
26 static const char *external_diff_cmd_cfg;
27 int diff_auto_refresh_index = 1;
28 static int diff_mnemonic_prefix;
30 static char diff_colors[][COLOR_MAXLEN] = {
31 "\033[m", /* reset */
32 "", /* PLAIN (normal) */
33 "\033[1m", /* METAINFO (bold) */
34 "\033[36m", /* FRAGINFO (cyan) */
35 "\033[31m", /* OLD (red) */
36 "\033[32m", /* NEW (green) */
37 "\033[33m", /* COMMIT (yellow) */
38 "\033[41m", /* WHITESPACE (red background) */
41 static void diff_filespec_load_driver(struct diff_filespec *one);
42 static char *run_textconv(const char *, struct diff_filespec *, size_t *);
44 static int parse_diff_color_slot(const char *var, int ofs)
46 if (!strcasecmp(var+ofs, "plain"))
47 return DIFF_PLAIN;
48 if (!strcasecmp(var+ofs, "meta"))
49 return DIFF_METAINFO;
50 if (!strcasecmp(var+ofs, "frag"))
51 return DIFF_FRAGINFO;
52 if (!strcasecmp(var+ofs, "old"))
53 return DIFF_FILE_OLD;
54 if (!strcasecmp(var+ofs, "new"))
55 return DIFF_FILE_NEW;
56 if (!strcasecmp(var+ofs, "commit"))
57 return DIFF_COMMIT;
58 if (!strcasecmp(var+ofs, "whitespace"))
59 return DIFF_WHITESPACE;
60 die("bad config variable '%s'", var);
64 * These are to give UI layer defaults.
65 * The core-level commands such as git-diff-files should
66 * never be affected by the setting of diff.renames
67 * the user happens to have in the configuration file.
69 int git_diff_ui_config(const char *var, const char *value, void *cb)
71 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
72 diff_use_color_default = git_config_colorbool(var, value, -1);
73 return 0;
75 if (!strcmp(var, "diff.renames")) {
76 if (!value)
77 diff_detect_rename_default = DIFF_DETECT_RENAME;
78 else if (!strcasecmp(value, "copies") ||
79 !strcasecmp(value, "copy"))
80 diff_detect_rename_default = DIFF_DETECT_COPY;
81 else if (git_config_bool(var,value))
82 diff_detect_rename_default = DIFF_DETECT_RENAME;
83 return 0;
85 if (!strcmp(var, "diff.autorefreshindex")) {
86 diff_auto_refresh_index = git_config_bool(var, value);
87 return 0;
89 if (!strcmp(var, "diff.mnemonicprefix")) {
90 diff_mnemonic_prefix = git_config_bool(var, value);
91 return 0;
93 if (!strcmp(var, "diff.external"))
94 return git_config_string(&external_diff_cmd_cfg, var, value);
96 return git_diff_basic_config(var, value, cb);
99 int git_diff_basic_config(const char *var, const char *value, void *cb)
101 if (!strcmp(var, "diff.renamelimit")) {
102 diff_rename_limit_default = git_config_int(var, value);
103 return 0;
106 switch (userdiff_config(var, value)) {
107 case 0: break;
108 case -1: return -1;
109 default: return 0;
112 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
113 int slot = parse_diff_color_slot(var, 11);
114 if (!value)
115 return config_error_nonbool(var);
116 color_parse(value, var, diff_colors[slot]);
117 return 0;
120 /* like GNU diff's --suppress-blank-empty option */
121 if (!strcmp(var, "diff.suppress-blank-empty")) {
122 diff_suppress_blank_empty = git_config_bool(var, value);
123 return 0;
126 return git_color_default_config(var, value, cb);
129 static char *quote_two(const char *one, const char *two)
131 int need_one = quote_c_style(one, NULL, NULL, 1);
132 int need_two = quote_c_style(two, NULL, NULL, 1);
133 struct strbuf res = STRBUF_INIT;
135 if (need_one + need_two) {
136 strbuf_addch(&res, '"');
137 quote_c_style(one, &res, NULL, 1);
138 quote_c_style(two, &res, NULL, 1);
139 strbuf_addch(&res, '"');
140 } else {
141 strbuf_addstr(&res, one);
142 strbuf_addstr(&res, two);
144 return strbuf_detach(&res, NULL);
147 static const char *external_diff(void)
149 static const char *external_diff_cmd = NULL;
150 static int done_preparing = 0;
152 if (done_preparing)
153 return external_diff_cmd;
154 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
155 if (!external_diff_cmd)
156 external_diff_cmd = external_diff_cmd_cfg;
157 done_preparing = 1;
158 return external_diff_cmd;
161 static struct diff_tempfile {
162 const char *name; /* filename external diff should read from */
163 char hex[41];
164 char mode[10];
165 char tmp_path[PATH_MAX];
166 } diff_temp[2];
168 static int count_lines(const char *data, int size)
170 int count, ch, completely_empty = 1, nl_just_seen = 0;
171 count = 0;
172 while (0 < size--) {
173 ch = *data++;
174 if (ch == '\n') {
175 count++;
176 nl_just_seen = 1;
177 completely_empty = 0;
179 else {
180 nl_just_seen = 0;
181 completely_empty = 0;
184 if (completely_empty)
185 return 0;
186 if (!nl_just_seen)
187 count++; /* no trailing newline */
188 return count;
191 static void print_line_count(FILE *file, int count)
193 switch (count) {
194 case 0:
195 fprintf(file, "0,0");
196 break;
197 case 1:
198 fprintf(file, "1");
199 break;
200 default:
201 fprintf(file, "1,%d", count);
202 break;
206 static void copy_file_with_prefix(FILE *file,
207 int prefix, const char *data, int size,
208 const char *set, const char *reset)
210 int ch, nl_just_seen = 1;
211 while (0 < size--) {
212 ch = *data++;
213 if (nl_just_seen) {
214 fputs(set, file);
215 putc(prefix, file);
217 if (ch == '\n') {
218 nl_just_seen = 1;
219 fputs(reset, file);
220 } else
221 nl_just_seen = 0;
222 putc(ch, file);
224 if (!nl_just_seen)
225 fprintf(file, "%s\n\\ No newline at end of file\n", reset);
228 static void emit_rewrite_diff(const char *name_a,
229 const char *name_b,
230 struct diff_filespec *one,
231 struct diff_filespec *two,
232 struct diff_options *o)
234 int lc_a, lc_b;
235 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
236 const char *name_a_tab, *name_b_tab;
237 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
238 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
239 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
240 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
241 const char *reset = diff_get_color(color_diff, DIFF_RESET);
242 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
243 const char *a_prefix, *b_prefix;
245 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
246 a_prefix = o->b_prefix;
247 b_prefix = o->a_prefix;
248 } else {
249 a_prefix = o->a_prefix;
250 b_prefix = o->b_prefix;
253 name_a += (*name_a == '/');
254 name_b += (*name_b == '/');
255 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
256 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
258 strbuf_reset(&a_name);
259 strbuf_reset(&b_name);
260 quote_two_c_style(&a_name, a_prefix, name_a, 0);
261 quote_two_c_style(&b_name, b_prefix, name_b, 0);
263 diff_populate_filespec(one, 0);
264 diff_populate_filespec(two, 0);
265 lc_a = count_lines(one->data, one->size);
266 lc_b = count_lines(two->data, two->size);
267 fprintf(o->file,
268 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
269 metainfo, a_name.buf, name_a_tab, reset,
270 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
271 print_line_count(o->file, lc_a);
272 fprintf(o->file, " +");
273 print_line_count(o->file, lc_b);
274 fprintf(o->file, " @@%s\n", reset);
275 if (lc_a)
276 copy_file_with_prefix(o->file, '-', one->data, one->size, old, reset);
277 if (lc_b)
278 copy_file_with_prefix(o->file, '+', two->data, two->size, new, reset);
281 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
283 if (!DIFF_FILE_VALID(one)) {
284 mf->ptr = (char *)""; /* does not matter */
285 mf->size = 0;
286 return 0;
288 else if (diff_populate_filespec(one, 0))
289 return -1;
291 mf->ptr = one->data;
292 mf->size = one->size;
293 return 0;
296 struct diff_words_buffer {
297 mmfile_t text;
298 long alloc;
299 long current; /* output pointer */
300 int suppressed_newline;
303 static void diff_words_append(char *line, unsigned long len,
304 struct diff_words_buffer *buffer)
306 if (buffer->text.size + len > buffer->alloc) {
307 buffer->alloc = (buffer->text.size + len) * 3 / 2;
308 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
310 line++;
311 len--;
312 memcpy(buffer->text.ptr + buffer->text.size, line, len);
313 buffer->text.size += len;
316 struct diff_words_data {
317 struct diff_words_buffer minus, plus;
318 FILE *file;
321 static void print_word(FILE *file, struct diff_words_buffer *buffer, int len, int color,
322 int suppress_newline)
324 const char *ptr;
325 int eol = 0;
327 if (len == 0)
328 return;
330 ptr = buffer->text.ptr + buffer->current;
331 buffer->current += len;
333 if (ptr[len - 1] == '\n') {
334 eol = 1;
335 len--;
338 fputs(diff_get_color(1, color), file);
339 fwrite(ptr, len, 1, file);
340 fputs(diff_get_color(1, DIFF_RESET), file);
342 if (eol) {
343 if (suppress_newline)
344 buffer->suppressed_newline = 1;
345 else
346 putc('\n', file);
350 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
352 struct diff_words_data *diff_words = priv;
354 if (diff_words->minus.suppressed_newline) {
355 if (line[0] != '+')
356 putc('\n', diff_words->file);
357 diff_words->minus.suppressed_newline = 0;
360 len--;
361 switch (line[0]) {
362 case '-':
363 print_word(diff_words->file,
364 &diff_words->minus, len, DIFF_FILE_OLD, 1);
365 break;
366 case '+':
367 print_word(diff_words->file,
368 &diff_words->plus, len, DIFF_FILE_NEW, 0);
369 break;
370 case ' ':
371 print_word(diff_words->file,
372 &diff_words->plus, len, DIFF_PLAIN, 0);
373 diff_words->minus.current += len;
374 break;
378 /* this executes the word diff on the accumulated buffers */
379 static void diff_words_show(struct diff_words_data *diff_words)
381 xpparam_t xpp;
382 xdemitconf_t xecfg;
383 xdemitcb_t ecb;
384 mmfile_t minus, plus;
385 int i;
387 memset(&xpp, 0, sizeof(xpp));
388 memset(&xecfg, 0, sizeof(xecfg));
389 minus.size = diff_words->minus.text.size;
390 minus.ptr = xmalloc(minus.size);
391 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
392 for (i = 0; i < minus.size; i++)
393 if (isspace(minus.ptr[i]))
394 minus.ptr[i] = '\n';
395 diff_words->minus.current = 0;
397 plus.size = diff_words->plus.text.size;
398 plus.ptr = xmalloc(plus.size);
399 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
400 for (i = 0; i < plus.size; i++)
401 if (isspace(plus.ptr[i]))
402 plus.ptr[i] = '\n';
403 diff_words->plus.current = 0;
405 xpp.flags = XDF_NEED_MINIMAL;
406 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
407 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
408 &xpp, &xecfg, &ecb);
409 free(minus.ptr);
410 free(plus.ptr);
411 diff_words->minus.text.size = diff_words->plus.text.size = 0;
413 if (diff_words->minus.suppressed_newline) {
414 putc('\n', diff_words->file);
415 diff_words->minus.suppressed_newline = 0;
419 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
421 struct emit_callback {
422 int nparents, color_diff;
423 unsigned ws_rule;
424 sane_truncate_fn truncate;
425 const char **label_path;
426 struct diff_words_data *diff_words;
427 int *found_changesp;
428 FILE *file;
431 static void free_diff_words_data(struct emit_callback *ecbdata)
433 if (ecbdata->diff_words) {
434 /* flush buffers */
435 if (ecbdata->diff_words->minus.text.size ||
436 ecbdata->diff_words->plus.text.size)
437 diff_words_show(ecbdata->diff_words);
439 free (ecbdata->diff_words->minus.text.ptr);
440 free (ecbdata->diff_words->plus.text.ptr);
441 free(ecbdata->diff_words);
442 ecbdata->diff_words = NULL;
446 const char *diff_get_color(int diff_use_color, enum color_diff ix)
448 if (diff_use_color)
449 return diff_colors[ix];
450 return "";
453 static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
455 int has_trailing_newline, has_trailing_carriage_return;
457 has_trailing_newline = (len > 0 && line[len-1] == '\n');
458 if (has_trailing_newline)
459 len--;
460 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
461 if (has_trailing_carriage_return)
462 len--;
464 fputs(set, file);
465 fwrite(line, len, 1, file);
466 fputs(reset, file);
467 if (has_trailing_carriage_return)
468 fputc('\r', file);
469 if (has_trailing_newline)
470 fputc('\n', file);
473 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
475 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
476 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
478 if (!*ws)
479 emit_line(ecbdata->file, set, reset, line, len);
480 else {
481 /* Emit just the prefix, then the rest. */
482 emit_line(ecbdata->file, set, reset, line, ecbdata->nparents);
483 ws_check_emit(line + ecbdata->nparents,
484 len - ecbdata->nparents, ecbdata->ws_rule,
485 ecbdata->file, set, reset, ws);
489 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
491 const char *cp;
492 unsigned long allot;
493 size_t l = len;
495 if (ecb->truncate)
496 return ecb->truncate(line, len);
497 cp = line;
498 allot = l;
499 while (0 < l) {
500 (void) utf8_width(&cp, &l);
501 if (!cp)
502 break; /* truncated in the middle? */
504 return allot - l;
507 static void fn_out_consume(void *priv, char *line, unsigned long len)
509 int i;
510 int color;
511 struct emit_callback *ecbdata = priv;
512 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
513 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
514 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
516 *(ecbdata->found_changesp) = 1;
518 if (ecbdata->label_path[0]) {
519 const char *name_a_tab, *name_b_tab;
521 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
522 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
524 fprintf(ecbdata->file, "%s--- %s%s%s\n",
525 meta, ecbdata->label_path[0], reset, name_a_tab);
526 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
527 meta, ecbdata->label_path[1], reset, name_b_tab);
528 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
531 if (diff_suppress_blank_empty
532 && len == 2 && line[0] == ' ' && line[1] == '\n') {
533 line[0] = '\n';
534 len = 1;
537 /* This is not really necessary for now because
538 * this codepath only deals with two-way diffs.
540 for (i = 0; i < len && line[i] == '@'; i++)
542 if (2 <= i && i < len && line[i] == ' ') {
543 ecbdata->nparents = i - 1;
544 len = sane_truncate_line(ecbdata, line, len);
545 emit_line(ecbdata->file,
546 diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
547 reset, line, len);
548 if (line[len-1] != '\n')
549 putc('\n', ecbdata->file);
550 return;
553 if (len < ecbdata->nparents) {
554 emit_line(ecbdata->file, reset, reset, line, len);
555 return;
558 color = DIFF_PLAIN;
559 if (ecbdata->diff_words && ecbdata->nparents != 1)
560 /* fall back to normal diff */
561 free_diff_words_data(ecbdata);
562 if (ecbdata->diff_words) {
563 if (line[0] == '-') {
564 diff_words_append(line, len,
565 &ecbdata->diff_words->minus);
566 return;
567 } else if (line[0] == '+') {
568 diff_words_append(line, len,
569 &ecbdata->diff_words->plus);
570 return;
572 if (ecbdata->diff_words->minus.text.size ||
573 ecbdata->diff_words->plus.text.size)
574 diff_words_show(ecbdata->diff_words);
575 line++;
576 len--;
577 emit_line(ecbdata->file, plain, reset, line, len);
578 return;
580 for (i = 0; i < ecbdata->nparents && len; i++) {
581 if (line[i] == '-')
582 color = DIFF_FILE_OLD;
583 else if (line[i] == '+')
584 color = DIFF_FILE_NEW;
587 if (color != DIFF_FILE_NEW) {
588 emit_line(ecbdata->file,
589 diff_get_color(ecbdata->color_diff, color),
590 reset, line, len);
591 return;
593 emit_add_line(reset, ecbdata, line, len);
596 static char *pprint_rename(const char *a, const char *b)
598 const char *old = a;
599 const char *new = b;
600 struct strbuf name = STRBUF_INIT;
601 int pfx_length, sfx_length;
602 int len_a = strlen(a);
603 int len_b = strlen(b);
604 int a_midlen, b_midlen;
605 int qlen_a = quote_c_style(a, NULL, NULL, 0);
606 int qlen_b = quote_c_style(b, NULL, NULL, 0);
608 if (qlen_a || qlen_b) {
609 quote_c_style(a, &name, NULL, 0);
610 strbuf_addstr(&name, " => ");
611 quote_c_style(b, &name, NULL, 0);
612 return strbuf_detach(&name, NULL);
615 /* Find common prefix */
616 pfx_length = 0;
617 while (*old && *new && *old == *new) {
618 if (*old == '/')
619 pfx_length = old - a + 1;
620 old++;
621 new++;
624 /* Find common suffix */
625 old = a + len_a;
626 new = b + len_b;
627 sfx_length = 0;
628 while (a <= old && b <= new && *old == *new) {
629 if (*old == '/')
630 sfx_length = len_a - (old - a);
631 old--;
632 new--;
636 * pfx{mid-a => mid-b}sfx
637 * {pfx-a => pfx-b}sfx
638 * pfx{sfx-a => sfx-b}
639 * name-a => name-b
641 a_midlen = len_a - pfx_length - sfx_length;
642 b_midlen = len_b - pfx_length - sfx_length;
643 if (a_midlen < 0)
644 a_midlen = 0;
645 if (b_midlen < 0)
646 b_midlen = 0;
648 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
649 if (pfx_length + sfx_length) {
650 strbuf_add(&name, a, pfx_length);
651 strbuf_addch(&name, '{');
653 strbuf_add(&name, a + pfx_length, a_midlen);
654 strbuf_addstr(&name, " => ");
655 strbuf_add(&name, b + pfx_length, b_midlen);
656 if (pfx_length + sfx_length) {
657 strbuf_addch(&name, '}');
658 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
660 return strbuf_detach(&name, NULL);
663 struct diffstat_t {
664 int nr;
665 int alloc;
666 struct diffstat_file {
667 char *from_name;
668 char *name;
669 char *print_name;
670 unsigned is_unmerged:1;
671 unsigned is_binary:1;
672 unsigned is_renamed:1;
673 unsigned int added, deleted;
674 } **files;
677 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
678 const char *name_a,
679 const char *name_b)
681 struct diffstat_file *x;
682 x = xcalloc(sizeof (*x), 1);
683 if (diffstat->nr == diffstat->alloc) {
684 diffstat->alloc = alloc_nr(diffstat->alloc);
685 diffstat->files = xrealloc(diffstat->files,
686 diffstat->alloc * sizeof(x));
688 diffstat->files[diffstat->nr++] = x;
689 if (name_b) {
690 x->from_name = xstrdup(name_a);
691 x->name = xstrdup(name_b);
692 x->is_renamed = 1;
694 else {
695 x->from_name = NULL;
696 x->name = xstrdup(name_a);
698 return x;
701 static void diffstat_consume(void *priv, char *line, unsigned long len)
703 struct diffstat_t *diffstat = priv;
704 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
706 if (line[0] == '+')
707 x->added++;
708 else if (line[0] == '-')
709 x->deleted++;
712 const char mime_boundary_leader[] = "------------";
714 static int scale_linear(int it, int width, int max_change)
717 * make sure that at least one '-' is printed if there were deletions,
718 * and likewise for '+'.
720 if (max_change < 2)
721 return it;
722 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
725 static void show_name(FILE *file,
726 const char *prefix, const char *name, int len,
727 const char *reset, const char *set)
729 fprintf(file, " %s%s%-*s%s |", set, prefix, len, name, reset);
732 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
734 if (cnt <= 0)
735 return;
736 fprintf(file, "%s", set);
737 while (cnt--)
738 putc(ch, file);
739 fprintf(file, "%s", reset);
742 static void fill_print_name(struct diffstat_file *file)
744 char *pname;
746 if (file->print_name)
747 return;
749 if (!file->is_renamed) {
750 struct strbuf buf = STRBUF_INIT;
751 if (quote_c_style(file->name, &buf, NULL, 0)) {
752 pname = strbuf_detach(&buf, NULL);
753 } else {
754 pname = file->name;
755 strbuf_release(&buf);
757 } else {
758 pname = pprint_rename(file->from_name, file->name);
760 file->print_name = pname;
763 static void show_stats(struct diffstat_t* data, struct diff_options *options)
765 int i, len, add, del, total, adds = 0, dels = 0;
766 int max_change = 0, max_len = 0;
767 int total_files = data->nr;
768 int width, name_width;
769 const char *reset, *set, *add_c, *del_c;
771 if (data->nr == 0)
772 return;
774 width = options->stat_width ? options->stat_width : 80;
775 name_width = options->stat_name_width ? options->stat_name_width : 50;
777 /* Sanity: give at least 5 columns to the graph,
778 * but leave at least 10 columns for the name.
780 if (width < 25)
781 width = 25;
782 if (name_width < 10)
783 name_width = 10;
784 else if (width < name_width + 15)
785 name_width = width - 15;
787 /* Find the longest filename and max number of changes */
788 reset = diff_get_color_opt(options, DIFF_RESET);
789 set = diff_get_color_opt(options, DIFF_PLAIN);
790 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
791 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
793 for (i = 0; i < data->nr; i++) {
794 struct diffstat_file *file = data->files[i];
795 int change = file->added + file->deleted;
796 fill_print_name(file);
797 len = strlen(file->print_name);
798 if (max_len < len)
799 max_len = len;
801 if (file->is_binary || file->is_unmerged)
802 continue;
803 if (max_change < change)
804 max_change = change;
807 /* Compute the width of the graph part;
808 * 10 is for one blank at the beginning of the line plus
809 * " | count " between the name and the graph.
811 * From here on, name_width is the width of the name area,
812 * and width is the width of the graph area.
814 name_width = (name_width < max_len) ? name_width : max_len;
815 if (width < (name_width + 10) + max_change)
816 width = width - (name_width + 10);
817 else
818 width = max_change;
820 for (i = 0; i < data->nr; i++) {
821 const char *prefix = "";
822 char *name = data->files[i]->print_name;
823 int added = data->files[i]->added;
824 int deleted = data->files[i]->deleted;
825 int name_len;
828 * "scale" the filename
830 len = name_width;
831 name_len = strlen(name);
832 if (name_width < name_len) {
833 char *slash;
834 prefix = "...";
835 len -= 3;
836 name += name_len - len;
837 slash = strchr(name, '/');
838 if (slash)
839 name = slash;
842 if (data->files[i]->is_binary) {
843 show_name(options->file, prefix, name, len, reset, set);
844 fprintf(options->file, " Bin ");
845 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
846 fprintf(options->file, " -> ");
847 fprintf(options->file, "%s%d%s", add_c, added, reset);
848 fprintf(options->file, " bytes");
849 fprintf(options->file, "\n");
850 continue;
852 else if (data->files[i]->is_unmerged) {
853 show_name(options->file, prefix, name, len, reset, set);
854 fprintf(options->file, " Unmerged\n");
855 continue;
857 else if (!data->files[i]->is_renamed &&
858 (added + deleted == 0)) {
859 total_files--;
860 continue;
864 * scale the add/delete
866 add = added;
867 del = deleted;
868 total = add + del;
869 adds += add;
870 dels += del;
872 if (width <= max_change) {
873 add = scale_linear(add, width, max_change);
874 del = scale_linear(del, width, max_change);
875 total = add + del;
877 show_name(options->file, prefix, name, len, reset, set);
878 fprintf(options->file, "%5d%s", added + deleted,
879 added + deleted ? " " : "");
880 show_graph(options->file, '+', add, add_c, reset);
881 show_graph(options->file, '-', del, del_c, reset);
882 fprintf(options->file, "\n");
884 fprintf(options->file,
885 "%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
886 set, total_files, adds, dels, reset);
889 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
891 int i, adds = 0, dels = 0, total_files = data->nr;
893 if (data->nr == 0)
894 return;
896 for (i = 0; i < data->nr; i++) {
897 if (!data->files[i]->is_binary &&
898 !data->files[i]->is_unmerged) {
899 int added = data->files[i]->added;
900 int deleted= data->files[i]->deleted;
901 if (!data->files[i]->is_renamed &&
902 (added + deleted == 0)) {
903 total_files--;
904 } else {
905 adds += added;
906 dels += deleted;
910 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
911 total_files, adds, dels);
914 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
916 int i;
918 if (data->nr == 0)
919 return;
921 for (i = 0; i < data->nr; i++) {
922 struct diffstat_file *file = data->files[i];
924 if (file->is_binary)
925 fprintf(options->file, "-\t-\t");
926 else
927 fprintf(options->file,
928 "%d\t%d\t", file->added, file->deleted);
929 if (options->line_termination) {
930 fill_print_name(file);
931 if (!file->is_renamed)
932 write_name_quoted(file->name, options->file,
933 options->line_termination);
934 else {
935 fputs(file->print_name, options->file);
936 putc(options->line_termination, options->file);
938 } else {
939 if (file->is_renamed) {
940 putc('\0', options->file);
941 write_name_quoted(file->from_name, options->file, '\0');
943 write_name_quoted(file->name, options->file, '\0');
948 struct dirstat_file {
949 const char *name;
950 unsigned long changed;
953 struct dirstat_dir {
954 struct dirstat_file *files;
955 int alloc, nr, percent, cumulative;
958 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
960 unsigned long this_dir = 0;
961 unsigned int sources = 0;
963 while (dir->nr) {
964 struct dirstat_file *f = dir->files;
965 int namelen = strlen(f->name);
966 unsigned long this;
967 char *slash;
969 if (namelen < baselen)
970 break;
971 if (memcmp(f->name, base, baselen))
972 break;
973 slash = strchr(f->name + baselen, '/');
974 if (slash) {
975 int newbaselen = slash + 1 - f->name;
976 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
977 sources++;
978 } else {
979 this = f->changed;
980 dir->files++;
981 dir->nr--;
982 sources += 2;
984 this_dir += this;
988 * We don't report dirstat's for
989 * - the top level
990 * - or cases where everything came from a single directory
991 * under this directory (sources == 1).
993 if (baselen && sources != 1) {
994 int permille = this_dir * 1000 / changed;
995 if (permille) {
996 int percent = permille / 10;
997 if (percent >= dir->percent) {
998 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
999 if (!dir->cumulative)
1000 return 0;
1004 return this_dir;
1007 static int dirstat_compare(const void *_a, const void *_b)
1009 const struct dirstat_file *a = _a;
1010 const struct dirstat_file *b = _b;
1011 return strcmp(a->name, b->name);
1014 static void show_dirstat(struct diff_options *options)
1016 int i;
1017 unsigned long changed;
1018 struct dirstat_dir dir;
1019 struct diff_queue_struct *q = &diff_queued_diff;
1021 dir.files = NULL;
1022 dir.alloc = 0;
1023 dir.nr = 0;
1024 dir.percent = options->dirstat_percent;
1025 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1027 changed = 0;
1028 for (i = 0; i < q->nr; i++) {
1029 struct diff_filepair *p = q->queue[i];
1030 const char *name;
1031 unsigned long copied, added, damage;
1033 name = p->one->path ? p->one->path : p->two->path;
1035 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1036 diff_populate_filespec(p->one, 0);
1037 diff_populate_filespec(p->two, 0);
1038 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1039 &copied, &added);
1040 diff_free_filespec_data(p->one);
1041 diff_free_filespec_data(p->two);
1042 } else if (DIFF_FILE_VALID(p->one)) {
1043 diff_populate_filespec(p->one, 1);
1044 copied = added = 0;
1045 diff_free_filespec_data(p->one);
1046 } else if (DIFF_FILE_VALID(p->two)) {
1047 diff_populate_filespec(p->two, 1);
1048 copied = 0;
1049 added = p->two->size;
1050 diff_free_filespec_data(p->two);
1051 } else
1052 continue;
1055 * Original minus copied is the removed material,
1056 * added is the new material. They are both damages
1057 * made to the preimage. In --dirstat-by-file mode, count
1058 * damaged files, not damaged lines. This is done by
1059 * counting only a single damaged line per file.
1061 damage = (p->one->size - copied) + added;
1062 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1063 damage = 1;
1065 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1066 dir.files[dir.nr].name = name;
1067 dir.files[dir.nr].changed = damage;
1068 changed += damage;
1069 dir.nr++;
1072 /* This can happen even with many files, if everything was renames */
1073 if (!changed)
1074 return;
1076 /* Show all directories with more than x% of the changes */
1077 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1078 gather_dirstat(options->file, &dir, changed, "", 0);
1081 static void free_diffstat_info(struct diffstat_t *diffstat)
1083 int i;
1084 for (i = 0; i < diffstat->nr; i++) {
1085 struct diffstat_file *f = diffstat->files[i];
1086 if (f->name != f->print_name)
1087 free(f->print_name);
1088 free(f->name);
1089 free(f->from_name);
1090 free(f);
1092 free(diffstat->files);
1095 struct checkdiff_t {
1096 const char *filename;
1097 int lineno;
1098 struct diff_options *o;
1099 unsigned ws_rule;
1100 unsigned status;
1101 int trailing_blanks_start;
1104 static int is_conflict_marker(const char *line, unsigned long len)
1106 char firstchar;
1107 int cnt;
1109 if (len < 8)
1110 return 0;
1111 firstchar = line[0];
1112 switch (firstchar) {
1113 case '=': case '>': case '<':
1114 break;
1115 default:
1116 return 0;
1118 for (cnt = 1; cnt < 7; cnt++)
1119 if (line[cnt] != firstchar)
1120 return 0;
1121 /* line[0] thru line[6] are same as firstchar */
1122 if (firstchar == '=') {
1123 /* divider between ours and theirs? */
1124 if (len != 8 || line[7] != '\n')
1125 return 0;
1126 } else if (len < 8 || !isspace(line[7])) {
1127 /* not divider before ours nor after theirs */
1128 return 0;
1130 return 1;
1133 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1135 struct checkdiff_t *data = priv;
1136 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1137 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1138 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1139 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1140 char *err;
1142 if (line[0] == '+') {
1143 unsigned bad;
1144 data->lineno++;
1145 if (!ws_blank_line(line + 1, len - 1, data->ws_rule))
1146 data->trailing_blanks_start = 0;
1147 else if (!data->trailing_blanks_start)
1148 data->trailing_blanks_start = data->lineno;
1149 if (is_conflict_marker(line + 1, len - 1)) {
1150 data->status |= 1;
1151 fprintf(data->o->file,
1152 "%s:%d: leftover conflict marker\n",
1153 data->filename, data->lineno);
1155 bad = ws_check(line + 1, len - 1, data->ws_rule);
1156 if (!bad)
1157 return;
1158 data->status |= bad;
1159 err = whitespace_error_string(bad);
1160 fprintf(data->o->file, "%s:%d: %s.\n",
1161 data->filename, data->lineno, err);
1162 free(err);
1163 emit_line(data->o->file, set, reset, line, 1);
1164 ws_check_emit(line + 1, len - 1, data->ws_rule,
1165 data->o->file, set, reset, ws);
1166 } else if (line[0] == ' ') {
1167 data->lineno++;
1168 data->trailing_blanks_start = 0;
1169 } else if (line[0] == '@') {
1170 char *plus = strchr(line, '+');
1171 if (plus)
1172 data->lineno = strtol(plus, NULL, 10) - 1;
1173 else
1174 die("invalid diff");
1175 data->trailing_blanks_start = 0;
1179 static unsigned char *deflate_it(char *data,
1180 unsigned long size,
1181 unsigned long *result_size)
1183 int bound;
1184 unsigned char *deflated;
1185 z_stream stream;
1187 memset(&stream, 0, sizeof(stream));
1188 deflateInit(&stream, zlib_compression_level);
1189 bound = deflateBound(&stream, size);
1190 deflated = xmalloc(bound);
1191 stream.next_out = deflated;
1192 stream.avail_out = bound;
1194 stream.next_in = (unsigned char *)data;
1195 stream.avail_in = size;
1196 while (deflate(&stream, Z_FINISH) == Z_OK)
1197 ; /* nothing */
1198 deflateEnd(&stream);
1199 *result_size = stream.total_out;
1200 return deflated;
1203 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1205 void *cp;
1206 void *delta;
1207 void *deflated;
1208 void *data;
1209 unsigned long orig_size;
1210 unsigned long delta_size;
1211 unsigned long deflate_size;
1212 unsigned long data_size;
1214 /* We could do deflated delta, or we could do just deflated two,
1215 * whichever is smaller.
1217 delta = NULL;
1218 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1219 if (one->size && two->size) {
1220 delta = diff_delta(one->ptr, one->size,
1221 two->ptr, two->size,
1222 &delta_size, deflate_size);
1223 if (delta) {
1224 void *to_free = delta;
1225 orig_size = delta_size;
1226 delta = deflate_it(delta, delta_size, &delta_size);
1227 free(to_free);
1231 if (delta && delta_size < deflate_size) {
1232 fprintf(file, "delta %lu\n", orig_size);
1233 free(deflated);
1234 data = delta;
1235 data_size = delta_size;
1237 else {
1238 fprintf(file, "literal %lu\n", two->size);
1239 free(delta);
1240 data = deflated;
1241 data_size = deflate_size;
1244 /* emit data encoded in base85 */
1245 cp = data;
1246 while (data_size) {
1247 int bytes = (52 < data_size) ? 52 : data_size;
1248 char line[70];
1249 data_size -= bytes;
1250 if (bytes <= 26)
1251 line[0] = bytes + 'A' - 1;
1252 else
1253 line[0] = bytes - 26 + 'a' - 1;
1254 encode_85(line + 1, cp, bytes);
1255 cp = (char *) cp + bytes;
1256 fputs(line, file);
1257 fputc('\n', file);
1259 fprintf(file, "\n");
1260 free(data);
1263 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1265 fprintf(file, "GIT binary patch\n");
1266 emit_binary_diff_body(file, one, two);
1267 emit_binary_diff_body(file, two, one);
1270 static void diff_filespec_load_driver(struct diff_filespec *one)
1272 if (!one->driver)
1273 one->driver = userdiff_find_by_path(one->path);
1274 if (!one->driver)
1275 one->driver = userdiff_find_by_name("default");
1278 int diff_filespec_is_binary(struct diff_filespec *one)
1280 if (one->is_binary == -1) {
1281 diff_filespec_load_driver(one);
1282 if (one->driver->binary != -1)
1283 one->is_binary = one->driver->binary;
1284 else {
1285 if (!one->data && DIFF_FILE_VALID(one))
1286 diff_populate_filespec(one, 0);
1287 if (one->data)
1288 one->is_binary = buffer_is_binary(one->data,
1289 one->size);
1290 if (one->is_binary == -1)
1291 one->is_binary = 0;
1294 return one->is_binary;
1297 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1299 diff_filespec_load_driver(one);
1300 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1303 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1305 if (!options->a_prefix)
1306 options->a_prefix = a;
1307 if (!options->b_prefix)
1308 options->b_prefix = b;
1311 static const char *get_textconv(struct diff_filespec *one)
1313 if (!DIFF_FILE_VALID(one))
1314 return NULL;
1315 if (!S_ISREG(one->mode))
1316 return NULL;
1317 diff_filespec_load_driver(one);
1318 return one->driver->textconv;
1321 static void builtin_diff(const char *name_a,
1322 const char *name_b,
1323 struct diff_filespec *one,
1324 struct diff_filespec *two,
1325 const char *xfrm_msg,
1326 struct diff_options *o,
1327 int complete_rewrite)
1329 mmfile_t mf1, mf2;
1330 const char *lbl[2];
1331 char *a_one, *b_two;
1332 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1333 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1334 const char *a_prefix, *b_prefix;
1335 const char *textconv_one = NULL, *textconv_two = NULL;
1337 diff_set_mnemonic_prefix(o, "a/", "b/");
1338 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1339 a_prefix = o->b_prefix;
1340 b_prefix = o->a_prefix;
1341 } else {
1342 a_prefix = o->a_prefix;
1343 b_prefix = o->b_prefix;
1346 /* Never use a non-valid filename anywhere if at all possible */
1347 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1348 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1350 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1351 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1352 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1353 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1354 fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1355 if (lbl[0][0] == '/') {
1356 /* /dev/null */
1357 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1358 if (xfrm_msg && xfrm_msg[0])
1359 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1361 else if (lbl[1][0] == '/') {
1362 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1363 if (xfrm_msg && xfrm_msg[0])
1364 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1366 else {
1367 if (one->mode != two->mode) {
1368 fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1369 fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1371 if (xfrm_msg && xfrm_msg[0])
1372 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1374 * we do not run diff between different kind
1375 * of objects.
1377 if ((one->mode ^ two->mode) & S_IFMT)
1378 goto free_ab_and_return;
1379 if (complete_rewrite) {
1380 emit_rewrite_diff(name_a, name_b, one, two, o);
1381 o->found_changes = 1;
1382 goto free_ab_and_return;
1386 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1387 die("unable to read files to diff");
1389 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1390 textconv_one = get_textconv(one);
1391 textconv_two = get_textconv(two);
1394 if (!DIFF_OPT_TST(o, TEXT) &&
1395 ( (diff_filespec_is_binary(one) && !textconv_one) ||
1396 (diff_filespec_is_binary(two) && !textconv_two) )) {
1397 /* Quite common confusing case */
1398 if (mf1.size == mf2.size &&
1399 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1400 goto free_ab_and_return;
1401 if (DIFF_OPT_TST(o, BINARY))
1402 emit_binary_diff(o->file, &mf1, &mf2);
1403 else
1404 fprintf(o->file, "Binary files %s and %s differ\n",
1405 lbl[0], lbl[1]);
1406 o->found_changes = 1;
1408 else {
1409 /* Crazy xdl interfaces.. */
1410 const char *diffopts = getenv("GIT_DIFF_OPTS");
1411 xpparam_t xpp;
1412 xdemitconf_t xecfg;
1413 xdemitcb_t ecb;
1414 struct emit_callback ecbdata;
1415 const struct userdiff_funcname *pe;
1417 if (textconv_one) {
1418 size_t size;
1419 mf1.ptr = run_textconv(textconv_one, one, &size);
1420 if (!mf1.ptr)
1421 die("unable to read files to diff");
1422 mf1.size = size;
1424 if (textconv_two) {
1425 size_t size;
1426 mf2.ptr = run_textconv(textconv_two, two, &size);
1427 if (!mf2.ptr)
1428 die("unable to read files to diff");
1429 mf2.size = size;
1432 pe = diff_funcname_pattern(one);
1433 if (!pe)
1434 pe = diff_funcname_pattern(two);
1436 memset(&xpp, 0, sizeof(xpp));
1437 memset(&xecfg, 0, sizeof(xecfg));
1438 memset(&ecbdata, 0, sizeof(ecbdata));
1439 ecbdata.label_path = lbl;
1440 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1441 ecbdata.found_changesp = &o->found_changes;
1442 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1443 ecbdata.file = o->file;
1444 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1445 xecfg.ctxlen = o->context;
1446 xecfg.flags = XDL_EMIT_FUNCNAMES;
1447 if (pe)
1448 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1449 if (!diffopts)
1451 else if (!prefixcmp(diffopts, "--unified="))
1452 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1453 else if (!prefixcmp(diffopts, "-u"))
1454 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1455 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1456 ecbdata.diff_words =
1457 xcalloc(1, sizeof(struct diff_words_data));
1458 ecbdata.diff_words->file = o->file;
1460 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1461 &xpp, &xecfg, &ecb);
1462 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1463 free_diff_words_data(&ecbdata);
1464 if (textconv_one)
1465 free(mf1.ptr);
1466 if (textconv_two)
1467 free(mf2.ptr);
1470 free_ab_and_return:
1471 diff_free_filespec_data(one);
1472 diff_free_filespec_data(two);
1473 free(a_one);
1474 free(b_two);
1475 return;
1478 static void builtin_diffstat(const char *name_a, const char *name_b,
1479 struct diff_filespec *one,
1480 struct diff_filespec *two,
1481 struct diffstat_t *diffstat,
1482 struct diff_options *o,
1483 int complete_rewrite)
1485 mmfile_t mf1, mf2;
1486 struct diffstat_file *data;
1488 data = diffstat_add(diffstat, name_a, name_b);
1490 if (!one || !two) {
1491 data->is_unmerged = 1;
1492 return;
1494 if (complete_rewrite) {
1495 diff_populate_filespec(one, 0);
1496 diff_populate_filespec(two, 0);
1497 data->deleted = count_lines(one->data, one->size);
1498 data->added = count_lines(two->data, two->size);
1499 goto free_and_return;
1501 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1502 die("unable to read files to diff");
1504 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1505 data->is_binary = 1;
1506 data->added = mf2.size;
1507 data->deleted = mf1.size;
1508 } else {
1509 /* Crazy xdl interfaces.. */
1510 xpparam_t xpp;
1511 xdemitconf_t xecfg;
1512 xdemitcb_t ecb;
1514 memset(&xpp, 0, sizeof(xpp));
1515 memset(&xecfg, 0, sizeof(xecfg));
1516 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1517 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1518 &xpp, &xecfg, &ecb);
1521 free_and_return:
1522 diff_free_filespec_data(one);
1523 diff_free_filespec_data(two);
1526 static void builtin_checkdiff(const char *name_a, const char *name_b,
1527 const char *attr_path,
1528 struct diff_filespec *one,
1529 struct diff_filespec *two,
1530 struct diff_options *o)
1532 mmfile_t mf1, mf2;
1533 struct checkdiff_t data;
1535 if (!two)
1536 return;
1538 memset(&data, 0, sizeof(data));
1539 data.filename = name_b ? name_b : name_a;
1540 data.lineno = 0;
1541 data.o = o;
1542 data.ws_rule = whitespace_rule(attr_path);
1544 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1545 die("unable to read files to diff");
1548 * All the other codepaths check both sides, but not checking
1549 * the "old" side here is deliberate. We are checking the newly
1550 * introduced changes, and as long as the "new" side is text, we
1551 * can and should check what it introduces.
1553 if (diff_filespec_is_binary(two))
1554 goto free_and_return;
1555 else {
1556 /* Crazy xdl interfaces.. */
1557 xpparam_t xpp;
1558 xdemitconf_t xecfg;
1559 xdemitcb_t ecb;
1561 memset(&xpp, 0, sizeof(xpp));
1562 memset(&xecfg, 0, sizeof(xecfg));
1563 xecfg.ctxlen = 1; /* at least one context line */
1564 xpp.flags = XDF_NEED_MINIMAL;
1565 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1566 &xpp, &xecfg, &ecb);
1568 if ((data.ws_rule & WS_TRAILING_SPACE) &&
1569 data.trailing_blanks_start) {
1570 fprintf(o->file, "%s:%d: ends with blank lines.\n",
1571 data.filename, data.trailing_blanks_start);
1572 data.status = 1; /* report errors */
1575 free_and_return:
1576 diff_free_filespec_data(one);
1577 diff_free_filespec_data(two);
1578 if (data.status)
1579 DIFF_OPT_SET(o, CHECK_FAILED);
1582 struct diff_filespec *alloc_filespec(const char *path)
1584 int namelen = strlen(path);
1585 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1587 memset(spec, 0, sizeof(*spec));
1588 spec->path = (char *)(spec + 1);
1589 memcpy(spec->path, path, namelen+1);
1590 spec->count = 1;
1591 spec->is_binary = -1;
1592 return spec;
1595 void free_filespec(struct diff_filespec *spec)
1597 if (!--spec->count) {
1598 diff_free_filespec_data(spec);
1599 free(spec);
1603 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1604 unsigned short mode)
1606 if (mode) {
1607 spec->mode = canon_mode(mode);
1608 hashcpy(spec->sha1, sha1);
1609 spec->sha1_valid = !is_null_sha1(sha1);
1614 * Given a name and sha1 pair, if the index tells us the file in
1615 * the work tree has that object contents, return true, so that
1616 * prepare_temp_file() does not have to inflate and extract.
1618 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1620 struct cache_entry *ce;
1621 struct stat st;
1622 int pos, len;
1624 /* We do not read the cache ourselves here, because the
1625 * benchmark with my previous version that always reads cache
1626 * shows that it makes things worse for diff-tree comparing
1627 * two linux-2.6 kernel trees in an already checked out work
1628 * tree. This is because most diff-tree comparisons deal with
1629 * only a small number of files, while reading the cache is
1630 * expensive for a large project, and its cost outweighs the
1631 * savings we get by not inflating the object to a temporary
1632 * file. Practically, this code only helps when we are used
1633 * by diff-cache --cached, which does read the cache before
1634 * calling us.
1636 if (!active_cache)
1637 return 0;
1639 /* We want to avoid the working directory if our caller
1640 * doesn't need the data in a normal file, this system
1641 * is rather slow with its stat/open/mmap/close syscalls,
1642 * and the object is contained in a pack file. The pack
1643 * is probably already open and will be faster to obtain
1644 * the data through than the working directory. Loose
1645 * objects however would tend to be slower as they need
1646 * to be individually opened and inflated.
1648 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1649 return 0;
1651 len = strlen(name);
1652 pos = cache_name_pos(name, len);
1653 if (pos < 0)
1654 return 0;
1655 ce = active_cache[pos];
1658 * This is not the sha1 we are looking for, or
1659 * unreusable because it is not a regular file.
1661 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1662 return 0;
1665 * If ce matches the file in the work tree, we can reuse it.
1667 if (ce_uptodate(ce) ||
1668 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1669 return 1;
1671 return 0;
1674 static int populate_from_stdin(struct diff_filespec *s)
1676 struct strbuf buf = STRBUF_INIT;
1677 size_t size = 0;
1679 if (strbuf_read(&buf, 0, 0) < 0)
1680 return error("error while reading from stdin %s",
1681 strerror(errno));
1683 s->should_munmap = 0;
1684 s->data = strbuf_detach(&buf, &size);
1685 s->size = size;
1686 s->should_free = 1;
1687 return 0;
1690 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1692 int len;
1693 char *data = xmalloc(100);
1694 len = snprintf(data, 100,
1695 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1696 s->data = data;
1697 s->size = len;
1698 s->should_free = 1;
1699 if (size_only) {
1700 s->data = NULL;
1701 free(data);
1703 return 0;
1707 * While doing rename detection and pickaxe operation, we may need to
1708 * grab the data for the blob (or file) for our own in-core comparison.
1709 * diff_filespec has data and size fields for this purpose.
1711 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1713 int err = 0;
1714 if (!DIFF_FILE_VALID(s))
1715 die("internal error: asking to populate invalid file.");
1716 if (S_ISDIR(s->mode))
1717 return -1;
1719 if (s->data)
1720 return 0;
1722 if (size_only && 0 < s->size)
1723 return 0;
1725 if (S_ISGITLINK(s->mode))
1726 return diff_populate_gitlink(s, size_only);
1728 if (!s->sha1_valid ||
1729 reuse_worktree_file(s->path, s->sha1, 0)) {
1730 struct strbuf buf = STRBUF_INIT;
1731 struct stat st;
1732 int fd;
1734 if (!strcmp(s->path, "-"))
1735 return populate_from_stdin(s);
1737 if (lstat(s->path, &st) < 0) {
1738 if (errno == ENOENT) {
1739 err_empty:
1740 err = -1;
1741 empty:
1742 s->data = (char *)"";
1743 s->size = 0;
1744 return err;
1747 s->size = xsize_t(st.st_size);
1748 if (!s->size)
1749 goto empty;
1750 if (size_only)
1751 return 0;
1752 if (S_ISLNK(st.st_mode)) {
1753 int ret;
1754 s->data = xmalloc(s->size);
1755 s->should_free = 1;
1756 ret = readlink(s->path, s->data, s->size);
1757 if (ret < 0) {
1758 free(s->data);
1759 goto err_empty;
1761 return 0;
1763 fd = open(s->path, O_RDONLY);
1764 if (fd < 0)
1765 goto err_empty;
1766 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1767 close(fd);
1768 s->should_munmap = 1;
1771 * Convert from working tree format to canonical git format
1773 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
1774 size_t size = 0;
1775 munmap(s->data, s->size);
1776 s->should_munmap = 0;
1777 s->data = strbuf_detach(&buf, &size);
1778 s->size = size;
1779 s->should_free = 1;
1782 else {
1783 enum object_type type;
1784 if (size_only)
1785 type = sha1_object_info(s->sha1, &s->size);
1786 else {
1787 s->data = read_sha1_file(s->sha1, &type, &s->size);
1788 s->should_free = 1;
1791 return 0;
1794 void diff_free_filespec_blob(struct diff_filespec *s)
1796 if (s->should_free)
1797 free(s->data);
1798 else if (s->should_munmap)
1799 munmap(s->data, s->size);
1801 if (s->should_free || s->should_munmap) {
1802 s->should_free = s->should_munmap = 0;
1803 s->data = NULL;
1807 void diff_free_filespec_data(struct diff_filespec *s)
1809 diff_free_filespec_blob(s);
1810 free(s->cnt_data);
1811 s->cnt_data = NULL;
1814 static void prep_temp_blob(struct diff_tempfile *temp,
1815 void *blob,
1816 unsigned long size,
1817 const unsigned char *sha1,
1818 int mode)
1820 int fd;
1822 fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1823 if (fd < 0)
1824 die("unable to create temp-file: %s", strerror(errno));
1825 if (write_in_full(fd, blob, size) != size)
1826 die("unable to write temp-file");
1827 close(fd);
1828 temp->name = temp->tmp_path;
1829 strcpy(temp->hex, sha1_to_hex(sha1));
1830 temp->hex[40] = 0;
1831 sprintf(temp->mode, "%06o", mode);
1834 static void prepare_temp_file(const char *name,
1835 struct diff_tempfile *temp,
1836 struct diff_filespec *one)
1838 if (!DIFF_FILE_VALID(one)) {
1839 not_a_valid_file:
1840 /* A '-' entry produces this for file-2, and
1841 * a '+' entry produces this for file-1.
1843 temp->name = "/dev/null";
1844 strcpy(temp->hex, ".");
1845 strcpy(temp->mode, ".");
1846 return;
1849 if (!one->sha1_valid ||
1850 reuse_worktree_file(name, one->sha1, 1)) {
1851 struct stat st;
1852 if (lstat(name, &st) < 0) {
1853 if (errno == ENOENT)
1854 goto not_a_valid_file;
1855 die("stat(%s): %s", name, strerror(errno));
1857 if (S_ISLNK(st.st_mode)) {
1858 int ret;
1859 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1860 size_t sz = xsize_t(st.st_size);
1861 if (sizeof(buf) <= st.st_size)
1862 die("symlink too long: %s", name);
1863 ret = readlink(name, buf, sz);
1864 if (ret < 0)
1865 die("readlink(%s)", name);
1866 prep_temp_blob(temp, buf, sz,
1867 (one->sha1_valid ?
1868 one->sha1 : null_sha1),
1869 (one->sha1_valid ?
1870 one->mode : S_IFLNK));
1872 else {
1873 /* we can borrow from the file in the work tree */
1874 temp->name = name;
1875 if (!one->sha1_valid)
1876 strcpy(temp->hex, sha1_to_hex(null_sha1));
1877 else
1878 strcpy(temp->hex, sha1_to_hex(one->sha1));
1879 /* Even though we may sometimes borrow the
1880 * contents from the work tree, we always want
1881 * one->mode. mode is trustworthy even when
1882 * !(one->sha1_valid), as long as
1883 * DIFF_FILE_VALID(one).
1885 sprintf(temp->mode, "%06o", one->mode);
1887 return;
1889 else {
1890 if (diff_populate_filespec(one, 0))
1891 die("cannot read data blob for %s", one->path);
1892 prep_temp_blob(temp, one->data, one->size,
1893 one->sha1, one->mode);
1897 static void remove_tempfile(void)
1899 int i;
1901 for (i = 0; i < 2; i++)
1902 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1903 unlink(diff_temp[i].name);
1904 diff_temp[i].name = NULL;
1908 static void remove_tempfile_on_signal(int signo)
1910 remove_tempfile();
1911 signal(SIGINT, SIG_DFL);
1912 raise(signo);
1915 /* An external diff command takes:
1917 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1918 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1921 static void run_external_diff(const char *pgm,
1922 const char *name,
1923 const char *other,
1924 struct diff_filespec *one,
1925 struct diff_filespec *two,
1926 const char *xfrm_msg,
1927 int complete_rewrite)
1929 const char *spawn_arg[10];
1930 struct diff_tempfile *temp = diff_temp;
1931 int retval;
1932 static int atexit_asked = 0;
1933 const char *othername;
1934 const char **arg = &spawn_arg[0];
1936 othername = (other? other : name);
1937 if (one && two) {
1938 prepare_temp_file(name, &temp[0], one);
1939 prepare_temp_file(othername, &temp[1], two);
1940 if (! atexit_asked &&
1941 (temp[0].name == temp[0].tmp_path ||
1942 temp[1].name == temp[1].tmp_path)) {
1943 atexit_asked = 1;
1944 atexit(remove_tempfile);
1946 signal(SIGINT, remove_tempfile_on_signal);
1949 if (one && two) {
1950 *arg++ = pgm;
1951 *arg++ = name;
1952 *arg++ = temp[0].name;
1953 *arg++ = temp[0].hex;
1954 *arg++ = temp[0].mode;
1955 *arg++ = temp[1].name;
1956 *arg++ = temp[1].hex;
1957 *arg++ = temp[1].mode;
1958 if (other) {
1959 *arg++ = other;
1960 *arg++ = xfrm_msg;
1962 } else {
1963 *arg++ = pgm;
1964 *arg++ = name;
1966 *arg = NULL;
1967 fflush(NULL);
1968 retval = run_command_v_opt(spawn_arg, 0);
1969 remove_tempfile();
1970 if (retval) {
1971 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1972 exit(1);
1976 static void run_diff_cmd(const char *pgm,
1977 const char *name,
1978 const char *other,
1979 const char *attr_path,
1980 struct diff_filespec *one,
1981 struct diff_filespec *two,
1982 const char *xfrm_msg,
1983 struct diff_options *o,
1984 int complete_rewrite)
1986 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
1987 pgm = NULL;
1988 else {
1989 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
1990 if (drv && drv->external)
1991 pgm = drv->external;
1994 if (pgm) {
1995 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1996 complete_rewrite);
1997 return;
1999 if (one && two)
2000 builtin_diff(name, other ? other : name,
2001 one, two, xfrm_msg, o, complete_rewrite);
2002 else
2003 fprintf(o->file, "* Unmerged path %s\n", name);
2006 static void diff_fill_sha1_info(struct diff_filespec *one)
2008 if (DIFF_FILE_VALID(one)) {
2009 if (!one->sha1_valid) {
2010 struct stat st;
2011 if (!strcmp(one->path, "-")) {
2012 hashcpy(one->sha1, null_sha1);
2013 return;
2015 if (lstat(one->path, &st) < 0)
2016 die("stat %s", one->path);
2017 if (index_path(one->sha1, one->path, &st, 0))
2018 die("cannot hash %s\n", one->path);
2021 else
2022 hashclr(one->sha1);
2025 static int similarity_index(struct diff_filepair *p)
2027 return p->score * 100 / MAX_SCORE;
2030 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2032 /* Strip the prefix but do not molest /dev/null and absolute paths */
2033 if (*namep && **namep != '/')
2034 *namep += prefix_length;
2035 if (*otherp && **otherp != '/')
2036 *otherp += prefix_length;
2039 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2041 const char *pgm = external_diff();
2042 struct strbuf msg;
2043 char *xfrm_msg;
2044 struct diff_filespec *one = p->one;
2045 struct diff_filespec *two = p->two;
2046 const char *name;
2047 const char *other;
2048 const char *attr_path;
2049 int complete_rewrite = 0;
2051 name = p->one->path;
2052 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2053 attr_path = name;
2054 if (o->prefix_length)
2055 strip_prefix(o->prefix_length, &name, &other);
2057 if (DIFF_PAIR_UNMERGED(p)) {
2058 run_diff_cmd(pgm, name, NULL, attr_path,
2059 NULL, NULL, NULL, o, 0);
2060 return;
2063 diff_fill_sha1_info(one);
2064 diff_fill_sha1_info(two);
2066 strbuf_init(&msg, PATH_MAX * 2 + 300);
2067 switch (p->status) {
2068 case DIFF_STATUS_COPIED:
2069 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2070 strbuf_addstr(&msg, "\ncopy from ");
2071 quote_c_style(name, &msg, NULL, 0);
2072 strbuf_addstr(&msg, "\ncopy to ");
2073 quote_c_style(other, &msg, NULL, 0);
2074 strbuf_addch(&msg, '\n');
2075 break;
2076 case DIFF_STATUS_RENAMED:
2077 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2078 strbuf_addstr(&msg, "\nrename from ");
2079 quote_c_style(name, &msg, NULL, 0);
2080 strbuf_addstr(&msg, "\nrename to ");
2081 quote_c_style(other, &msg, NULL, 0);
2082 strbuf_addch(&msg, '\n');
2083 break;
2084 case DIFF_STATUS_MODIFIED:
2085 if (p->score) {
2086 strbuf_addf(&msg, "dissimilarity index %d%%\n",
2087 similarity_index(p));
2088 complete_rewrite = 1;
2089 break;
2091 /* fallthru */
2092 default:
2093 /* nothing */
2097 if (hashcmp(one->sha1, two->sha1)) {
2098 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2100 if (DIFF_OPT_TST(o, BINARY)) {
2101 mmfile_t mf;
2102 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2103 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2104 abbrev = 40;
2106 strbuf_addf(&msg, "index %.*s..%.*s",
2107 abbrev, sha1_to_hex(one->sha1),
2108 abbrev, sha1_to_hex(two->sha1));
2109 if (one->mode == two->mode)
2110 strbuf_addf(&msg, " %06o", one->mode);
2111 strbuf_addch(&msg, '\n');
2114 if (msg.len)
2115 strbuf_setlen(&msg, msg.len - 1);
2116 xfrm_msg = msg.len ? msg.buf : NULL;
2118 if (!pgm &&
2119 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2120 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2121 /* a filepair that changes between file and symlink
2122 * needs to be split into deletion and creation.
2124 struct diff_filespec *null = alloc_filespec(two->path);
2125 run_diff_cmd(NULL, name, other, attr_path,
2126 one, null, xfrm_msg, o, 0);
2127 free(null);
2128 null = alloc_filespec(one->path);
2129 run_diff_cmd(NULL, name, other, attr_path,
2130 null, two, xfrm_msg, o, 0);
2131 free(null);
2133 else
2134 run_diff_cmd(pgm, name, other, attr_path,
2135 one, two, xfrm_msg, o, complete_rewrite);
2137 strbuf_release(&msg);
2140 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2141 struct diffstat_t *diffstat)
2143 const char *name;
2144 const char *other;
2145 int complete_rewrite = 0;
2147 if (DIFF_PAIR_UNMERGED(p)) {
2148 /* unmerged */
2149 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2150 return;
2153 name = p->one->path;
2154 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2156 if (o->prefix_length)
2157 strip_prefix(o->prefix_length, &name, &other);
2159 diff_fill_sha1_info(p->one);
2160 diff_fill_sha1_info(p->two);
2162 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2163 complete_rewrite = 1;
2164 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2167 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2169 const char *name;
2170 const char *other;
2171 const char *attr_path;
2173 if (DIFF_PAIR_UNMERGED(p)) {
2174 /* unmerged */
2175 return;
2178 name = p->one->path;
2179 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2180 attr_path = other ? other : name;
2182 if (o->prefix_length)
2183 strip_prefix(o->prefix_length, &name, &other);
2185 diff_fill_sha1_info(p->one);
2186 diff_fill_sha1_info(p->two);
2188 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2191 void diff_setup(struct diff_options *options)
2193 memset(options, 0, sizeof(*options));
2195 options->file = stdout;
2197 options->line_termination = '\n';
2198 options->break_opt = -1;
2199 options->rename_limit = -1;
2200 options->dirstat_percent = 3;
2201 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
2202 options->context = 3;
2204 options->change = diff_change;
2205 options->add_remove = diff_addremove;
2206 if (diff_use_color_default > 0)
2207 DIFF_OPT_SET(options, COLOR_DIFF);
2208 else
2209 DIFF_OPT_CLR(options, COLOR_DIFF);
2210 options->detect_rename = diff_detect_rename_default;
2212 if (!diff_mnemonic_prefix) {
2213 options->a_prefix = "a/";
2214 options->b_prefix = "b/";
2218 int diff_setup_done(struct diff_options *options)
2220 int count = 0;
2222 if (options->output_format & DIFF_FORMAT_NAME)
2223 count++;
2224 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2225 count++;
2226 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2227 count++;
2228 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2229 count++;
2230 if (count > 1)
2231 die("--name-only, --name-status, --check and -s are mutually exclusive");
2233 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2234 options->detect_rename = DIFF_DETECT_COPY;
2236 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2237 options->prefix = NULL;
2238 if (options->prefix)
2239 options->prefix_length = strlen(options->prefix);
2240 else
2241 options->prefix_length = 0;
2243 if (options->output_format & (DIFF_FORMAT_NAME |
2244 DIFF_FORMAT_NAME_STATUS |
2245 DIFF_FORMAT_CHECKDIFF |
2246 DIFF_FORMAT_NO_OUTPUT))
2247 options->output_format &= ~(DIFF_FORMAT_RAW |
2248 DIFF_FORMAT_NUMSTAT |
2249 DIFF_FORMAT_DIFFSTAT |
2250 DIFF_FORMAT_SHORTSTAT |
2251 DIFF_FORMAT_DIRSTAT |
2252 DIFF_FORMAT_SUMMARY |
2253 DIFF_FORMAT_PATCH);
2256 * These cases always need recursive; we do not drop caller-supplied
2257 * recursive bits for other formats here.
2259 if (options->output_format & (DIFF_FORMAT_PATCH |
2260 DIFF_FORMAT_NUMSTAT |
2261 DIFF_FORMAT_DIFFSTAT |
2262 DIFF_FORMAT_SHORTSTAT |
2263 DIFF_FORMAT_DIRSTAT |
2264 DIFF_FORMAT_SUMMARY |
2265 DIFF_FORMAT_CHECKDIFF))
2266 DIFF_OPT_SET(options, RECURSIVE);
2268 * Also pickaxe would not work very well if you do not say recursive
2270 if (options->pickaxe)
2271 DIFF_OPT_SET(options, RECURSIVE);
2273 if (options->detect_rename && options->rename_limit < 0)
2274 options->rename_limit = diff_rename_limit_default;
2275 if (options->setup & DIFF_SETUP_USE_CACHE) {
2276 if (!active_cache)
2277 /* read-cache does not die even when it fails
2278 * so it is safe for us to do this here. Also
2279 * it does not smudge active_cache or active_nr
2280 * when it fails, so we do not have to worry about
2281 * cleaning it up ourselves either.
2283 read_cache();
2285 if (options->abbrev <= 0 || 40 < options->abbrev)
2286 options->abbrev = 40; /* full */
2289 * It does not make sense to show the first hit we happened
2290 * to have found. It does not make sense not to return with
2291 * exit code in such a case either.
2293 if (DIFF_OPT_TST(options, QUIET)) {
2294 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2295 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2298 return 0;
2301 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2303 char c, *eq;
2304 int len;
2306 if (*arg != '-')
2307 return 0;
2308 c = *++arg;
2309 if (!c)
2310 return 0;
2311 if (c == arg_short) {
2312 c = *++arg;
2313 if (!c)
2314 return 1;
2315 if (val && isdigit(c)) {
2316 char *end;
2317 int n = strtoul(arg, &end, 10);
2318 if (*end)
2319 return 0;
2320 *val = n;
2321 return 1;
2323 return 0;
2325 if (c != '-')
2326 return 0;
2327 arg++;
2328 eq = strchr(arg, '=');
2329 if (eq)
2330 len = eq - arg;
2331 else
2332 len = strlen(arg);
2333 if (!len || strncmp(arg, arg_long, len))
2334 return 0;
2335 if (eq) {
2336 int n;
2337 char *end;
2338 if (!isdigit(*++eq))
2339 return 0;
2340 n = strtoul(eq, &end, 10);
2341 if (*end)
2342 return 0;
2343 *val = n;
2345 return 1;
2348 static int diff_scoreopt_parse(const char *opt);
2350 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2352 const char *arg = av[0];
2354 /* Output format options */
2355 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2356 options->output_format |= DIFF_FORMAT_PATCH;
2357 else if (opt_arg(arg, 'U', "unified", &options->context))
2358 options->output_format |= DIFF_FORMAT_PATCH;
2359 else if (!strcmp(arg, "--raw"))
2360 options->output_format |= DIFF_FORMAT_RAW;
2361 else if (!strcmp(arg, "--patch-with-raw"))
2362 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2363 else if (!strcmp(arg, "--numstat"))
2364 options->output_format |= DIFF_FORMAT_NUMSTAT;
2365 else if (!strcmp(arg, "--shortstat"))
2366 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2367 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2368 options->output_format |= DIFF_FORMAT_DIRSTAT;
2369 else if (!strcmp(arg, "--cumulative")) {
2370 options->output_format |= DIFF_FORMAT_DIRSTAT;
2371 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2372 } else if (opt_arg(arg, 0, "dirstat-by-file",
2373 &options->dirstat_percent)) {
2374 options->output_format |= DIFF_FORMAT_DIRSTAT;
2375 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2377 else if (!strcmp(arg, "--check"))
2378 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2379 else if (!strcmp(arg, "--summary"))
2380 options->output_format |= DIFF_FORMAT_SUMMARY;
2381 else if (!strcmp(arg, "--patch-with-stat"))
2382 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2383 else if (!strcmp(arg, "--name-only"))
2384 options->output_format |= DIFF_FORMAT_NAME;
2385 else if (!strcmp(arg, "--name-status"))
2386 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2387 else if (!strcmp(arg, "-s"))
2388 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2389 else if (!prefixcmp(arg, "--stat")) {
2390 char *end;
2391 int width = options->stat_width;
2392 int name_width = options->stat_name_width;
2393 arg += 6;
2394 end = (char *)arg;
2396 switch (*arg) {
2397 case '-':
2398 if (!prefixcmp(arg, "-width="))
2399 width = strtoul(arg + 7, &end, 10);
2400 else if (!prefixcmp(arg, "-name-width="))
2401 name_width = strtoul(arg + 12, &end, 10);
2402 break;
2403 case '=':
2404 width = strtoul(arg+1, &end, 10);
2405 if (*end == ',')
2406 name_width = strtoul(end+1, &end, 10);
2409 /* Important! This checks all the error cases! */
2410 if (*end)
2411 return 0;
2412 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2413 options->stat_name_width = name_width;
2414 options->stat_width = width;
2417 /* renames options */
2418 else if (!prefixcmp(arg, "-B")) {
2419 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2420 return -1;
2422 else if (!prefixcmp(arg, "-M")) {
2423 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2424 return -1;
2425 options->detect_rename = DIFF_DETECT_RENAME;
2427 else if (!prefixcmp(arg, "-C")) {
2428 if (options->detect_rename == DIFF_DETECT_COPY)
2429 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2430 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2431 return -1;
2432 options->detect_rename = DIFF_DETECT_COPY;
2434 else if (!strcmp(arg, "--no-renames"))
2435 options->detect_rename = 0;
2436 else if (!strcmp(arg, "--relative"))
2437 DIFF_OPT_SET(options, RELATIVE_NAME);
2438 else if (!prefixcmp(arg, "--relative=")) {
2439 DIFF_OPT_SET(options, RELATIVE_NAME);
2440 options->prefix = arg + 11;
2443 /* xdiff options */
2444 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2445 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2446 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2447 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2448 else if (!strcmp(arg, "--ignore-space-at-eol"))
2449 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2451 /* flags options */
2452 else if (!strcmp(arg, "--binary")) {
2453 options->output_format |= DIFF_FORMAT_PATCH;
2454 DIFF_OPT_SET(options, BINARY);
2456 else if (!strcmp(arg, "--full-index"))
2457 DIFF_OPT_SET(options, FULL_INDEX);
2458 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2459 DIFF_OPT_SET(options, TEXT);
2460 else if (!strcmp(arg, "-R"))
2461 DIFF_OPT_SET(options, REVERSE_DIFF);
2462 else if (!strcmp(arg, "--find-copies-harder"))
2463 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2464 else if (!strcmp(arg, "--follow"))
2465 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2466 else if (!strcmp(arg, "--color"))
2467 DIFF_OPT_SET(options, COLOR_DIFF);
2468 else if (!strcmp(arg, "--no-color"))
2469 DIFF_OPT_CLR(options, COLOR_DIFF);
2470 else if (!strcmp(arg, "--color-words"))
2471 options->flags |= DIFF_OPT_COLOR_DIFF | DIFF_OPT_COLOR_DIFF_WORDS;
2472 else if (!strcmp(arg, "--exit-code"))
2473 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2474 else if (!strcmp(arg, "--quiet"))
2475 DIFF_OPT_SET(options, QUIET);
2476 else if (!strcmp(arg, "--ext-diff"))
2477 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2478 else if (!strcmp(arg, "--no-ext-diff"))
2479 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2480 else if (!strcmp(arg, "--ignore-submodules"))
2481 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2483 /* misc options */
2484 else if (!strcmp(arg, "-z"))
2485 options->line_termination = 0;
2486 else if (!prefixcmp(arg, "-l"))
2487 options->rename_limit = strtoul(arg+2, NULL, 10);
2488 else if (!prefixcmp(arg, "-S"))
2489 options->pickaxe = arg + 2;
2490 else if (!strcmp(arg, "--pickaxe-all"))
2491 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2492 else if (!strcmp(arg, "--pickaxe-regex"))
2493 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2494 else if (!prefixcmp(arg, "-O"))
2495 options->orderfile = arg + 2;
2496 else if (!prefixcmp(arg, "--diff-filter="))
2497 options->filter = arg + 14;
2498 else if (!strcmp(arg, "--abbrev"))
2499 options->abbrev = DEFAULT_ABBREV;
2500 else if (!prefixcmp(arg, "--abbrev=")) {
2501 options->abbrev = strtoul(arg + 9, NULL, 10);
2502 if (options->abbrev < MINIMUM_ABBREV)
2503 options->abbrev = MINIMUM_ABBREV;
2504 else if (40 < options->abbrev)
2505 options->abbrev = 40;
2507 else if (!prefixcmp(arg, "--src-prefix="))
2508 options->a_prefix = arg + 13;
2509 else if (!prefixcmp(arg, "--dst-prefix="))
2510 options->b_prefix = arg + 13;
2511 else if (!strcmp(arg, "--no-prefix"))
2512 options->a_prefix = options->b_prefix = "";
2513 else if (!prefixcmp(arg, "--output=")) {
2514 options->file = fopen(arg + strlen("--output="), "w");
2515 options->close_file = 1;
2516 } else
2517 return 0;
2518 return 1;
2521 static int parse_num(const char **cp_p)
2523 unsigned long num, scale;
2524 int ch, dot;
2525 const char *cp = *cp_p;
2527 num = 0;
2528 scale = 1;
2529 dot = 0;
2530 for(;;) {
2531 ch = *cp;
2532 if ( !dot && ch == '.' ) {
2533 scale = 1;
2534 dot = 1;
2535 } else if ( ch == '%' ) {
2536 scale = dot ? scale*100 : 100;
2537 cp++; /* % is always at the end */
2538 break;
2539 } else if ( ch >= '0' && ch <= '9' ) {
2540 if ( scale < 100000 ) {
2541 scale *= 10;
2542 num = (num*10) + (ch-'0');
2544 } else {
2545 break;
2547 cp++;
2549 *cp_p = cp;
2551 /* user says num divided by scale and we say internally that
2552 * is MAX_SCORE * num / scale.
2554 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2557 static int diff_scoreopt_parse(const char *opt)
2559 int opt1, opt2, cmd;
2561 if (*opt++ != '-')
2562 return -1;
2563 cmd = *opt++;
2564 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2565 return -1; /* that is not a -M, -C nor -B option */
2567 opt1 = parse_num(&opt);
2568 if (cmd != 'B')
2569 opt2 = 0;
2570 else {
2571 if (*opt == 0)
2572 opt2 = 0;
2573 else if (*opt != '/')
2574 return -1; /* we expect -B80/99 or -B80 */
2575 else {
2576 opt++;
2577 opt2 = parse_num(&opt);
2580 if (*opt != 0)
2581 return -1;
2582 return opt1 | (opt2 << 16);
2585 struct diff_queue_struct diff_queued_diff;
2587 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2589 if (queue->alloc <= queue->nr) {
2590 queue->alloc = alloc_nr(queue->alloc);
2591 queue->queue = xrealloc(queue->queue,
2592 sizeof(dp) * queue->alloc);
2594 queue->queue[queue->nr++] = dp;
2597 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2598 struct diff_filespec *one,
2599 struct diff_filespec *two)
2601 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2602 dp->one = one;
2603 dp->two = two;
2604 if (queue)
2605 diff_q(queue, dp);
2606 return dp;
2609 void diff_free_filepair(struct diff_filepair *p)
2611 free_filespec(p->one);
2612 free_filespec(p->two);
2613 free(p);
2616 /* This is different from find_unique_abbrev() in that
2617 * it stuffs the result with dots for alignment.
2619 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2621 int abblen;
2622 const char *abbrev;
2623 if (len == 40)
2624 return sha1_to_hex(sha1);
2626 abbrev = find_unique_abbrev(sha1, len);
2627 abblen = strlen(abbrev);
2628 if (abblen < 37) {
2629 static char hex[41];
2630 if (len < abblen && abblen <= len + 2)
2631 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2632 else
2633 sprintf(hex, "%s...", abbrev);
2634 return hex;
2636 return sha1_to_hex(sha1);
2639 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2641 int line_termination = opt->line_termination;
2642 int inter_name_termination = line_termination ? '\t' : '\0';
2644 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2645 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2646 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2647 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2649 if (p->score) {
2650 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2651 inter_name_termination);
2652 } else {
2653 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2656 if (p->status == DIFF_STATUS_COPIED ||
2657 p->status == DIFF_STATUS_RENAMED) {
2658 const char *name_a, *name_b;
2659 name_a = p->one->path;
2660 name_b = p->two->path;
2661 strip_prefix(opt->prefix_length, &name_a, &name_b);
2662 write_name_quoted(name_a, opt->file, inter_name_termination);
2663 write_name_quoted(name_b, opt->file, line_termination);
2664 } else {
2665 const char *name_a, *name_b;
2666 name_a = p->one->mode ? p->one->path : p->two->path;
2667 name_b = NULL;
2668 strip_prefix(opt->prefix_length, &name_a, &name_b);
2669 write_name_quoted(name_a, opt->file, line_termination);
2673 int diff_unmodified_pair(struct diff_filepair *p)
2675 /* This function is written stricter than necessary to support
2676 * the currently implemented transformers, but the idea is to
2677 * let transformers to produce diff_filepairs any way they want,
2678 * and filter and clean them up here before producing the output.
2680 struct diff_filespec *one = p->one, *two = p->two;
2682 if (DIFF_PAIR_UNMERGED(p))
2683 return 0; /* unmerged is interesting */
2685 /* deletion, addition, mode or type change
2686 * and rename are all interesting.
2688 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2689 DIFF_PAIR_MODE_CHANGED(p) ||
2690 strcmp(one->path, two->path))
2691 return 0;
2693 /* both are valid and point at the same path. that is, we are
2694 * dealing with a change.
2696 if (one->sha1_valid && two->sha1_valid &&
2697 !hashcmp(one->sha1, two->sha1))
2698 return 1; /* no change */
2699 if (!one->sha1_valid && !two->sha1_valid)
2700 return 1; /* both look at the same file on the filesystem. */
2701 return 0;
2704 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2706 if (diff_unmodified_pair(p))
2707 return;
2709 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2710 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2711 return; /* no tree diffs in patch format */
2713 run_diff(p, o);
2716 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2717 struct diffstat_t *diffstat)
2719 if (diff_unmodified_pair(p))
2720 return;
2722 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2723 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2724 return; /* no tree diffs in patch format */
2726 run_diffstat(p, o, diffstat);
2729 static void diff_flush_checkdiff(struct diff_filepair *p,
2730 struct diff_options *o)
2732 if (diff_unmodified_pair(p))
2733 return;
2735 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2736 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2737 return; /* no tree diffs in patch format */
2739 run_checkdiff(p, o);
2742 int diff_queue_is_empty(void)
2744 struct diff_queue_struct *q = &diff_queued_diff;
2745 int i;
2746 for (i = 0; i < q->nr; i++)
2747 if (!diff_unmodified_pair(q->queue[i]))
2748 return 0;
2749 return 1;
2752 #if DIFF_DEBUG
2753 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2755 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2756 x, one ? one : "",
2757 s->path,
2758 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2759 s->mode,
2760 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2761 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2762 x, one ? one : "",
2763 s->size, s->xfrm_flags);
2766 void diff_debug_filepair(const struct diff_filepair *p, int i)
2768 diff_debug_filespec(p->one, i, "one");
2769 diff_debug_filespec(p->two, i, "two");
2770 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2771 p->score, p->status ? p->status : '?',
2772 p->one->rename_used, p->broken_pair);
2775 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2777 int i;
2778 if (msg)
2779 fprintf(stderr, "%s\n", msg);
2780 fprintf(stderr, "q->nr = %d\n", q->nr);
2781 for (i = 0; i < q->nr; i++) {
2782 struct diff_filepair *p = q->queue[i];
2783 diff_debug_filepair(p, i);
2786 #endif
2788 static void diff_resolve_rename_copy(void)
2790 int i;
2791 struct diff_filepair *p;
2792 struct diff_queue_struct *q = &diff_queued_diff;
2794 diff_debug_queue("resolve-rename-copy", q);
2796 for (i = 0; i < q->nr; i++) {
2797 p = q->queue[i];
2798 p->status = 0; /* undecided */
2799 if (DIFF_PAIR_UNMERGED(p))
2800 p->status = DIFF_STATUS_UNMERGED;
2801 else if (!DIFF_FILE_VALID(p->one))
2802 p->status = DIFF_STATUS_ADDED;
2803 else if (!DIFF_FILE_VALID(p->two))
2804 p->status = DIFF_STATUS_DELETED;
2805 else if (DIFF_PAIR_TYPE_CHANGED(p))
2806 p->status = DIFF_STATUS_TYPE_CHANGED;
2808 /* from this point on, we are dealing with a pair
2809 * whose both sides are valid and of the same type, i.e.
2810 * either in-place edit or rename/copy edit.
2812 else if (DIFF_PAIR_RENAME(p)) {
2814 * A rename might have re-connected a broken
2815 * pair up, causing the pathnames to be the
2816 * same again. If so, that's not a rename at
2817 * all, just a modification..
2819 * Otherwise, see if this source was used for
2820 * multiple renames, in which case we decrement
2821 * the count, and call it a copy.
2823 if (!strcmp(p->one->path, p->two->path))
2824 p->status = DIFF_STATUS_MODIFIED;
2825 else if (--p->one->rename_used > 0)
2826 p->status = DIFF_STATUS_COPIED;
2827 else
2828 p->status = DIFF_STATUS_RENAMED;
2830 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2831 p->one->mode != p->two->mode ||
2832 is_null_sha1(p->one->sha1))
2833 p->status = DIFF_STATUS_MODIFIED;
2834 else {
2835 /* This is a "no-change" entry and should not
2836 * happen anymore, but prepare for broken callers.
2838 error("feeding unmodified %s to diffcore",
2839 p->one->path);
2840 p->status = DIFF_STATUS_UNKNOWN;
2843 diff_debug_queue("resolve-rename-copy done", q);
2846 static int check_pair_status(struct diff_filepair *p)
2848 switch (p->status) {
2849 case DIFF_STATUS_UNKNOWN:
2850 return 0;
2851 case 0:
2852 die("internal error in diff-resolve-rename-copy");
2853 default:
2854 return 1;
2858 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2860 int fmt = opt->output_format;
2862 if (fmt & DIFF_FORMAT_CHECKDIFF)
2863 diff_flush_checkdiff(p, opt);
2864 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2865 diff_flush_raw(p, opt);
2866 else if (fmt & DIFF_FORMAT_NAME) {
2867 const char *name_a, *name_b;
2868 name_a = p->two->path;
2869 name_b = NULL;
2870 strip_prefix(opt->prefix_length, &name_a, &name_b);
2871 write_name_quoted(name_a, opt->file, opt->line_termination);
2875 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
2877 if (fs->mode)
2878 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
2879 else
2880 fprintf(file, " %s ", newdelete);
2881 write_name_quoted(fs->path, file, '\n');
2885 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
2887 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2888 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
2889 show_name ? ' ' : '\n');
2890 if (show_name) {
2891 write_name_quoted(p->two->path, file, '\n');
2896 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
2898 char *names = pprint_rename(p->one->path, p->two->path);
2900 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2901 free(names);
2902 show_mode_change(file, p, 0);
2905 static void diff_summary(FILE *file, struct diff_filepair *p)
2907 switch(p->status) {
2908 case DIFF_STATUS_DELETED:
2909 show_file_mode_name(file, "delete", p->one);
2910 break;
2911 case DIFF_STATUS_ADDED:
2912 show_file_mode_name(file, "create", p->two);
2913 break;
2914 case DIFF_STATUS_COPIED:
2915 show_rename_copy(file, "copy", p);
2916 break;
2917 case DIFF_STATUS_RENAMED:
2918 show_rename_copy(file, "rename", p);
2919 break;
2920 default:
2921 if (p->score) {
2922 fputs(" rewrite ", file);
2923 write_name_quoted(p->two->path, file, ' ');
2924 fprintf(file, "(%d%%)\n", similarity_index(p));
2926 show_mode_change(file, p, !p->score);
2927 break;
2931 struct patch_id_t {
2932 git_SHA_CTX *ctx;
2933 int patchlen;
2936 static int remove_space(char *line, int len)
2938 int i;
2939 char *dst = line;
2940 unsigned char c;
2942 for (i = 0; i < len; i++)
2943 if (!isspace((c = line[i])))
2944 *dst++ = c;
2946 return dst - line;
2949 static void patch_id_consume(void *priv, char *line, unsigned long len)
2951 struct patch_id_t *data = priv;
2952 int new_len;
2954 /* Ignore line numbers when computing the SHA1 of the patch */
2955 if (!prefixcmp(line, "@@ -"))
2956 return;
2958 new_len = remove_space(line, len);
2960 git_SHA1_Update(data->ctx, line, new_len);
2961 data->patchlen += new_len;
2964 /* returns 0 upon success, and writes result into sha1 */
2965 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2967 struct diff_queue_struct *q = &diff_queued_diff;
2968 int i;
2969 git_SHA_CTX ctx;
2970 struct patch_id_t data;
2971 char buffer[PATH_MAX * 4 + 20];
2973 git_SHA1_Init(&ctx);
2974 memset(&data, 0, sizeof(struct patch_id_t));
2975 data.ctx = &ctx;
2977 for (i = 0; i < q->nr; i++) {
2978 xpparam_t xpp;
2979 xdemitconf_t xecfg;
2980 xdemitcb_t ecb;
2981 mmfile_t mf1, mf2;
2982 struct diff_filepair *p = q->queue[i];
2983 int len1, len2;
2985 memset(&xpp, 0, sizeof(xpp));
2986 memset(&xecfg, 0, sizeof(xecfg));
2987 if (p->status == 0)
2988 return error("internal diff status error");
2989 if (p->status == DIFF_STATUS_UNKNOWN)
2990 continue;
2991 if (diff_unmodified_pair(p))
2992 continue;
2993 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2994 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2995 continue;
2996 if (DIFF_PAIR_UNMERGED(p))
2997 continue;
2999 diff_fill_sha1_info(p->one);
3000 diff_fill_sha1_info(p->two);
3001 if (fill_mmfile(&mf1, p->one) < 0 ||
3002 fill_mmfile(&mf2, p->two) < 0)
3003 return error("unable to read files to diff");
3005 len1 = remove_space(p->one->path, strlen(p->one->path));
3006 len2 = remove_space(p->two->path, strlen(p->two->path));
3007 if (p->one->mode == 0)
3008 len1 = snprintf(buffer, sizeof(buffer),
3009 "diff--gita/%.*sb/%.*s"
3010 "newfilemode%06o"
3011 "---/dev/null"
3012 "+++b/%.*s",
3013 len1, p->one->path,
3014 len2, p->two->path,
3015 p->two->mode,
3016 len2, p->two->path);
3017 else if (p->two->mode == 0)
3018 len1 = snprintf(buffer, sizeof(buffer),
3019 "diff--gita/%.*sb/%.*s"
3020 "deletedfilemode%06o"
3021 "---a/%.*s"
3022 "+++/dev/null",
3023 len1, p->one->path,
3024 len2, p->two->path,
3025 p->one->mode,
3026 len1, p->one->path);
3027 else
3028 len1 = snprintf(buffer, sizeof(buffer),
3029 "diff--gita/%.*sb/%.*s"
3030 "---a/%.*s"
3031 "+++b/%.*s",
3032 len1, p->one->path,
3033 len2, p->two->path,
3034 len1, p->one->path,
3035 len2, p->two->path);
3036 git_SHA1_Update(&ctx, buffer, len1);
3038 xpp.flags = XDF_NEED_MINIMAL;
3039 xecfg.ctxlen = 3;
3040 xecfg.flags = XDL_EMIT_FUNCNAMES;
3041 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3042 &xpp, &xecfg, &ecb);
3045 git_SHA1_Final(sha1, &ctx);
3046 return 0;
3049 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3051 struct diff_queue_struct *q = &diff_queued_diff;
3052 int i;
3053 int result = diff_get_patch_id(options, sha1);
3055 for (i = 0; i < q->nr; i++)
3056 diff_free_filepair(q->queue[i]);
3058 free(q->queue);
3059 q->queue = NULL;
3060 q->nr = q->alloc = 0;
3062 return result;
3065 static int is_summary_empty(const struct diff_queue_struct *q)
3067 int i;
3069 for (i = 0; i < q->nr; i++) {
3070 const struct diff_filepair *p = q->queue[i];
3072 switch (p->status) {
3073 case DIFF_STATUS_DELETED:
3074 case DIFF_STATUS_ADDED:
3075 case DIFF_STATUS_COPIED:
3076 case DIFF_STATUS_RENAMED:
3077 return 0;
3078 default:
3079 if (p->score)
3080 return 0;
3081 if (p->one->mode && p->two->mode &&
3082 p->one->mode != p->two->mode)
3083 return 0;
3084 break;
3087 return 1;
3090 void diff_flush(struct diff_options *options)
3092 struct diff_queue_struct *q = &diff_queued_diff;
3093 int i, output_format = options->output_format;
3094 int separator = 0;
3097 * Order: raw, stat, summary, patch
3098 * or: name/name-status/checkdiff (other bits clear)
3100 if (!q->nr)
3101 goto free_queue;
3103 if (output_format & (DIFF_FORMAT_RAW |
3104 DIFF_FORMAT_NAME |
3105 DIFF_FORMAT_NAME_STATUS |
3106 DIFF_FORMAT_CHECKDIFF)) {
3107 for (i = 0; i < q->nr; i++) {
3108 struct diff_filepair *p = q->queue[i];
3109 if (check_pair_status(p))
3110 flush_one_pair(p, options);
3112 separator++;
3115 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3116 struct diffstat_t diffstat;
3118 memset(&diffstat, 0, sizeof(struct diffstat_t));
3119 for (i = 0; i < q->nr; i++) {
3120 struct diff_filepair *p = q->queue[i];
3121 if (check_pair_status(p))
3122 diff_flush_stat(p, options, &diffstat);
3124 if (output_format & DIFF_FORMAT_NUMSTAT)
3125 show_numstat(&diffstat, options);
3126 if (output_format & DIFF_FORMAT_DIFFSTAT)
3127 show_stats(&diffstat, options);
3128 if (output_format & DIFF_FORMAT_SHORTSTAT)
3129 show_shortstats(&diffstat, options);
3130 free_diffstat_info(&diffstat);
3131 separator++;
3133 if (output_format & DIFF_FORMAT_DIRSTAT)
3134 show_dirstat(options);
3136 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3137 for (i = 0; i < q->nr; i++)
3138 diff_summary(options->file, q->queue[i]);
3139 separator++;
3142 if (output_format & DIFF_FORMAT_PATCH) {
3143 if (separator) {
3144 putc(options->line_termination, options->file);
3145 if (options->stat_sep) {
3146 /* attach patch instead of inline */
3147 fputs(options->stat_sep, options->file);
3151 for (i = 0; i < q->nr; i++) {
3152 struct diff_filepair *p = q->queue[i];
3153 if (check_pair_status(p))
3154 diff_flush_patch(p, options);
3158 if (output_format & DIFF_FORMAT_CALLBACK)
3159 options->format_callback(q, options, options->format_callback_data);
3161 for (i = 0; i < q->nr; i++)
3162 diff_free_filepair(q->queue[i]);
3163 free_queue:
3164 free(q->queue);
3165 q->queue = NULL;
3166 q->nr = q->alloc = 0;
3167 if (options->close_file)
3168 fclose(options->file);
3171 static void diffcore_apply_filter(const char *filter)
3173 int i;
3174 struct diff_queue_struct *q = &diff_queued_diff;
3175 struct diff_queue_struct outq;
3176 outq.queue = NULL;
3177 outq.nr = outq.alloc = 0;
3179 if (!filter)
3180 return;
3182 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3183 int found;
3184 for (i = found = 0; !found && i < q->nr; i++) {
3185 struct diff_filepair *p = q->queue[i];
3186 if (((p->status == DIFF_STATUS_MODIFIED) &&
3187 ((p->score &&
3188 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3189 (!p->score &&
3190 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3191 ((p->status != DIFF_STATUS_MODIFIED) &&
3192 strchr(filter, p->status)))
3193 found++;
3195 if (found)
3196 return;
3198 /* otherwise we will clear the whole queue
3199 * by copying the empty outq at the end of this
3200 * function, but first clear the current entries
3201 * in the queue.
3203 for (i = 0; i < q->nr; i++)
3204 diff_free_filepair(q->queue[i]);
3206 else {
3207 /* Only the matching ones */
3208 for (i = 0; i < q->nr; i++) {
3209 struct diff_filepair *p = q->queue[i];
3211 if (((p->status == DIFF_STATUS_MODIFIED) &&
3212 ((p->score &&
3213 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3214 (!p->score &&
3215 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3216 ((p->status != DIFF_STATUS_MODIFIED) &&
3217 strchr(filter, p->status)))
3218 diff_q(&outq, p);
3219 else
3220 diff_free_filepair(p);
3223 free(q->queue);
3224 *q = outq;
3227 /* Check whether two filespecs with the same mode and size are identical */
3228 static int diff_filespec_is_identical(struct diff_filespec *one,
3229 struct diff_filespec *two)
3231 if (S_ISGITLINK(one->mode))
3232 return 0;
3233 if (diff_populate_filespec(one, 0))
3234 return 0;
3235 if (diff_populate_filespec(two, 0))
3236 return 0;
3237 return !memcmp(one->data, two->data, one->size);
3240 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3242 int i;
3243 struct diff_queue_struct *q = &diff_queued_diff;
3244 struct diff_queue_struct outq;
3245 outq.queue = NULL;
3246 outq.nr = outq.alloc = 0;
3248 for (i = 0; i < q->nr; i++) {
3249 struct diff_filepair *p = q->queue[i];
3252 * 1. Entries that come from stat info dirtyness
3253 * always have both sides (iow, not create/delete),
3254 * one side of the object name is unknown, with
3255 * the same mode and size. Keep the ones that
3256 * do not match these criteria. They have real
3257 * differences.
3259 * 2. At this point, the file is known to be modified,
3260 * with the same mode and size, and the object
3261 * name of one side is unknown. Need to inspect
3262 * the identical contents.
3264 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3265 !DIFF_FILE_VALID(p->two) ||
3266 (p->one->sha1_valid && p->two->sha1_valid) ||
3267 (p->one->mode != p->two->mode) ||
3268 diff_populate_filespec(p->one, 1) ||
3269 diff_populate_filespec(p->two, 1) ||
3270 (p->one->size != p->two->size) ||
3271 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3272 diff_q(&outq, p);
3273 else {
3275 * The caller can subtract 1 from skip_stat_unmatch
3276 * to determine how many paths were dirty only
3277 * due to stat info mismatch.
3279 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3280 diffopt->skip_stat_unmatch++;
3281 diff_free_filepair(p);
3284 free(q->queue);
3285 *q = outq;
3288 void diffcore_std(struct diff_options *options)
3290 if (options->skip_stat_unmatch)
3291 diffcore_skip_stat_unmatch(options);
3292 if (options->break_opt != -1)
3293 diffcore_break(options->break_opt);
3294 if (options->detect_rename)
3295 diffcore_rename(options);
3296 if (options->break_opt != -1)
3297 diffcore_merge_broken();
3298 if (options->pickaxe)
3299 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3300 if (options->orderfile)
3301 diffcore_order(options->orderfile);
3302 diff_resolve_rename_copy();
3303 diffcore_apply_filter(options->filter);
3305 if (diff_queued_diff.nr)
3306 DIFF_OPT_SET(options, HAS_CHANGES);
3307 else
3308 DIFF_OPT_CLR(options, HAS_CHANGES);
3311 int diff_result_code(struct diff_options *opt, int status)
3313 int result = 0;
3314 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3315 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3316 return status;
3317 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3318 DIFF_OPT_TST(opt, HAS_CHANGES))
3319 result |= 01;
3320 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3321 DIFF_OPT_TST(opt, CHECK_FAILED))
3322 result |= 02;
3323 return result;
3326 void diff_addremove(struct diff_options *options,
3327 int addremove, unsigned mode,
3328 const unsigned char *sha1,
3329 const char *concatpath)
3331 struct diff_filespec *one, *two;
3333 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3334 return;
3336 /* This may look odd, but it is a preparation for
3337 * feeding "there are unchanged files which should
3338 * not produce diffs, but when you are doing copy
3339 * detection you would need them, so here they are"
3340 * entries to the diff-core. They will be prefixed
3341 * with something like '=' or '*' (I haven't decided
3342 * which but should not make any difference).
3343 * Feeding the same new and old to diff_change()
3344 * also has the same effect.
3345 * Before the final output happens, they are pruned after
3346 * merged into rename/copy pairs as appropriate.
3348 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3349 addremove = (addremove == '+' ? '-' :
3350 addremove == '-' ? '+' : addremove);
3352 if (options->prefix &&
3353 strncmp(concatpath, options->prefix, options->prefix_length))
3354 return;
3356 one = alloc_filespec(concatpath);
3357 two = alloc_filespec(concatpath);
3359 if (addremove != '+')
3360 fill_filespec(one, sha1, mode);
3361 if (addremove != '-')
3362 fill_filespec(two, sha1, mode);
3364 diff_queue(&diff_queued_diff, one, two);
3365 DIFF_OPT_SET(options, HAS_CHANGES);
3368 void diff_change(struct diff_options *options,
3369 unsigned old_mode, unsigned new_mode,
3370 const unsigned char *old_sha1,
3371 const unsigned char *new_sha1,
3372 const char *concatpath)
3374 struct diff_filespec *one, *two;
3376 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3377 && S_ISGITLINK(new_mode))
3378 return;
3380 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3381 unsigned tmp;
3382 const unsigned char *tmp_c;
3383 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3384 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3387 if (options->prefix &&
3388 strncmp(concatpath, options->prefix, options->prefix_length))
3389 return;
3391 one = alloc_filespec(concatpath);
3392 two = alloc_filespec(concatpath);
3393 fill_filespec(one, old_sha1, old_mode);
3394 fill_filespec(two, new_sha1, new_mode);
3396 diff_queue(&diff_queued_diff, one, two);
3397 DIFF_OPT_SET(options, HAS_CHANGES);
3400 void diff_unmerge(struct diff_options *options,
3401 const char *path,
3402 unsigned mode, const unsigned char *sha1)
3404 struct diff_filespec *one, *two;
3406 if (options->prefix &&
3407 strncmp(path, options->prefix, options->prefix_length))
3408 return;
3410 one = alloc_filespec(path);
3411 two = alloc_filespec(path);
3412 fill_filespec(one, sha1, mode);
3413 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3416 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3417 size_t *outsize)
3419 struct diff_tempfile temp;
3420 const char *argv[3];
3421 const char **arg = argv;
3422 struct child_process child;
3423 struct strbuf buf = STRBUF_INIT;
3425 prepare_temp_file(spec->path, &temp, spec);
3426 *arg++ = pgm;
3427 *arg++ = temp.name;
3428 *arg = NULL;
3430 memset(&child, 0, sizeof(child));
3431 child.argv = argv;
3432 child.out = -1;
3433 if (start_command(&child) != 0 ||
3434 strbuf_read(&buf, child.out, 0) < 0 ||
3435 finish_command(&child) != 0) {
3436 if (temp.name == temp.tmp_path)
3437 unlink(temp.name);
3438 error("error running textconv command '%s'", pgm);
3439 return NULL;
3441 if (temp.name == temp.tmp_path)
3442 unlink(temp.name);
3444 return strbuf_detach(&buf, outsize);