enable textconv for diff in verbose status/commit
[git/trast.git] / diff.c
blob23d454e71d4d22165d995d8fd321c86d2eeb84e4
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(&xecfg, 0, sizeof(xecfg));
388 minus.size = diff_words->minus.text.size;
389 minus.ptr = xmalloc(minus.size);
390 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
391 for (i = 0; i < minus.size; i++)
392 if (isspace(minus.ptr[i]))
393 minus.ptr[i] = '\n';
394 diff_words->minus.current = 0;
396 plus.size = diff_words->plus.text.size;
397 plus.ptr = xmalloc(plus.size);
398 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
399 for (i = 0; i < plus.size; i++)
400 if (isspace(plus.ptr[i]))
401 plus.ptr[i] = '\n';
402 diff_words->plus.current = 0;
404 xpp.flags = XDF_NEED_MINIMAL;
405 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
406 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
407 &xpp, &xecfg, &ecb);
408 free(minus.ptr);
409 free(plus.ptr);
410 diff_words->minus.text.size = diff_words->plus.text.size = 0;
412 if (diff_words->minus.suppressed_newline) {
413 putc('\n', diff_words->file);
414 diff_words->minus.suppressed_newline = 0;
418 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
420 struct emit_callback {
421 int nparents, color_diff;
422 unsigned ws_rule;
423 sane_truncate_fn truncate;
424 const char **label_path;
425 struct diff_words_data *diff_words;
426 int *found_changesp;
427 FILE *file;
430 static void free_diff_words_data(struct emit_callback *ecbdata)
432 if (ecbdata->diff_words) {
433 /* flush buffers */
434 if (ecbdata->diff_words->minus.text.size ||
435 ecbdata->diff_words->plus.text.size)
436 diff_words_show(ecbdata->diff_words);
438 free (ecbdata->diff_words->minus.text.ptr);
439 free (ecbdata->diff_words->plus.text.ptr);
440 free(ecbdata->diff_words);
441 ecbdata->diff_words = NULL;
445 const char *diff_get_color(int diff_use_color, enum color_diff ix)
447 if (diff_use_color)
448 return diff_colors[ix];
449 return "";
452 static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
454 int has_trailing_newline, has_trailing_carriage_return;
456 has_trailing_newline = (len > 0 && line[len-1] == '\n');
457 if (has_trailing_newline)
458 len--;
459 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
460 if (has_trailing_carriage_return)
461 len--;
463 fputs(set, file);
464 fwrite(line, len, 1, file);
465 fputs(reset, file);
466 if (has_trailing_carriage_return)
467 fputc('\r', file);
468 if (has_trailing_newline)
469 fputc('\n', file);
472 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
474 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
475 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
477 if (!*ws)
478 emit_line(ecbdata->file, set, reset, line, len);
479 else {
480 /* Emit just the prefix, then the rest. */
481 emit_line(ecbdata->file, set, reset, line, ecbdata->nparents);
482 ws_check_emit(line + ecbdata->nparents,
483 len - ecbdata->nparents, ecbdata->ws_rule,
484 ecbdata->file, set, reset, ws);
488 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
490 const char *cp;
491 unsigned long allot;
492 size_t l = len;
494 if (ecb->truncate)
495 return ecb->truncate(line, len);
496 cp = line;
497 allot = l;
498 while (0 < l) {
499 (void) utf8_width(&cp, &l);
500 if (!cp)
501 break; /* truncated in the middle? */
503 return allot - l;
506 static void fn_out_consume(void *priv, char *line, unsigned long len)
508 int i;
509 int color;
510 struct emit_callback *ecbdata = priv;
511 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
512 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
513 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
515 *(ecbdata->found_changesp) = 1;
517 if (ecbdata->label_path[0]) {
518 const char *name_a_tab, *name_b_tab;
520 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
521 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
523 fprintf(ecbdata->file, "%s--- %s%s%s\n",
524 meta, ecbdata->label_path[0], reset, name_a_tab);
525 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
526 meta, ecbdata->label_path[1], reset, name_b_tab);
527 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
530 if (diff_suppress_blank_empty
531 && len == 2 && line[0] == ' ' && line[1] == '\n') {
532 line[0] = '\n';
533 len = 1;
536 /* This is not really necessary for now because
537 * this codepath only deals with two-way diffs.
539 for (i = 0; i < len && line[i] == '@'; i++)
541 if (2 <= i && i < len && line[i] == ' ') {
542 ecbdata->nparents = i - 1;
543 len = sane_truncate_line(ecbdata, line, len);
544 emit_line(ecbdata->file,
545 diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
546 reset, line, len);
547 if (line[len-1] != '\n')
548 putc('\n', ecbdata->file);
549 return;
552 if (len < ecbdata->nparents) {
553 emit_line(ecbdata->file, reset, reset, line, len);
554 return;
557 color = DIFF_PLAIN;
558 if (ecbdata->diff_words && ecbdata->nparents != 1)
559 /* fall back to normal diff */
560 free_diff_words_data(ecbdata);
561 if (ecbdata->diff_words) {
562 if (line[0] == '-') {
563 diff_words_append(line, len,
564 &ecbdata->diff_words->minus);
565 return;
566 } else if (line[0] == '+') {
567 diff_words_append(line, len,
568 &ecbdata->diff_words->plus);
569 return;
571 if (ecbdata->diff_words->minus.text.size ||
572 ecbdata->diff_words->plus.text.size)
573 diff_words_show(ecbdata->diff_words);
574 line++;
575 len--;
576 emit_line(ecbdata->file, plain, reset, line, len);
577 return;
579 for (i = 0; i < ecbdata->nparents && len; i++) {
580 if (line[i] == '-')
581 color = DIFF_FILE_OLD;
582 else if (line[i] == '+')
583 color = DIFF_FILE_NEW;
586 if (color != DIFF_FILE_NEW) {
587 emit_line(ecbdata->file,
588 diff_get_color(ecbdata->color_diff, color),
589 reset, line, len);
590 return;
592 emit_add_line(reset, ecbdata, line, len);
595 static char *pprint_rename(const char *a, const char *b)
597 const char *old = a;
598 const char *new = b;
599 struct strbuf name = STRBUF_INIT;
600 int pfx_length, sfx_length;
601 int len_a = strlen(a);
602 int len_b = strlen(b);
603 int a_midlen, b_midlen;
604 int qlen_a = quote_c_style(a, NULL, NULL, 0);
605 int qlen_b = quote_c_style(b, NULL, NULL, 0);
607 if (qlen_a || qlen_b) {
608 quote_c_style(a, &name, NULL, 0);
609 strbuf_addstr(&name, " => ");
610 quote_c_style(b, &name, NULL, 0);
611 return strbuf_detach(&name, NULL);
614 /* Find common prefix */
615 pfx_length = 0;
616 while (*old && *new && *old == *new) {
617 if (*old == '/')
618 pfx_length = old - a + 1;
619 old++;
620 new++;
623 /* Find common suffix */
624 old = a + len_a;
625 new = b + len_b;
626 sfx_length = 0;
627 while (a <= old && b <= new && *old == *new) {
628 if (*old == '/')
629 sfx_length = len_a - (old - a);
630 old--;
631 new--;
635 * pfx{mid-a => mid-b}sfx
636 * {pfx-a => pfx-b}sfx
637 * pfx{sfx-a => sfx-b}
638 * name-a => name-b
640 a_midlen = len_a - pfx_length - sfx_length;
641 b_midlen = len_b - pfx_length - sfx_length;
642 if (a_midlen < 0)
643 a_midlen = 0;
644 if (b_midlen < 0)
645 b_midlen = 0;
647 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
648 if (pfx_length + sfx_length) {
649 strbuf_add(&name, a, pfx_length);
650 strbuf_addch(&name, '{');
652 strbuf_add(&name, a + pfx_length, a_midlen);
653 strbuf_addstr(&name, " => ");
654 strbuf_add(&name, b + pfx_length, b_midlen);
655 if (pfx_length + sfx_length) {
656 strbuf_addch(&name, '}');
657 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
659 return strbuf_detach(&name, NULL);
662 struct diffstat_t {
663 int nr;
664 int alloc;
665 struct diffstat_file {
666 char *from_name;
667 char *name;
668 char *print_name;
669 unsigned is_unmerged:1;
670 unsigned is_binary:1;
671 unsigned is_renamed:1;
672 unsigned int added, deleted;
673 } **files;
676 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
677 const char *name_a,
678 const char *name_b)
680 struct diffstat_file *x;
681 x = xcalloc(sizeof (*x), 1);
682 if (diffstat->nr == diffstat->alloc) {
683 diffstat->alloc = alloc_nr(diffstat->alloc);
684 diffstat->files = xrealloc(diffstat->files,
685 diffstat->alloc * sizeof(x));
687 diffstat->files[diffstat->nr++] = x;
688 if (name_b) {
689 x->from_name = xstrdup(name_a);
690 x->name = xstrdup(name_b);
691 x->is_renamed = 1;
693 else {
694 x->from_name = NULL;
695 x->name = xstrdup(name_a);
697 return x;
700 static void diffstat_consume(void *priv, char *line, unsigned long len)
702 struct diffstat_t *diffstat = priv;
703 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
705 if (line[0] == '+')
706 x->added++;
707 else if (line[0] == '-')
708 x->deleted++;
711 const char mime_boundary_leader[] = "------------";
713 static int scale_linear(int it, int width, int max_change)
716 * make sure that at least one '-' is printed if there were deletions,
717 * and likewise for '+'.
719 if (max_change < 2)
720 return it;
721 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
724 static void show_name(FILE *file,
725 const char *prefix, const char *name, int len,
726 const char *reset, const char *set)
728 fprintf(file, " %s%s%-*s%s |", set, prefix, len, name, reset);
731 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
733 if (cnt <= 0)
734 return;
735 fprintf(file, "%s", set);
736 while (cnt--)
737 putc(ch, file);
738 fprintf(file, "%s", reset);
741 static void fill_print_name(struct diffstat_file *file)
743 char *pname;
745 if (file->print_name)
746 return;
748 if (!file->is_renamed) {
749 struct strbuf buf = STRBUF_INIT;
750 if (quote_c_style(file->name, &buf, NULL, 0)) {
751 pname = strbuf_detach(&buf, NULL);
752 } else {
753 pname = file->name;
754 strbuf_release(&buf);
756 } else {
757 pname = pprint_rename(file->from_name, file->name);
759 file->print_name = pname;
762 static void show_stats(struct diffstat_t* data, struct diff_options *options)
764 int i, len, add, del, total, adds = 0, dels = 0;
765 int max_change = 0, max_len = 0;
766 int total_files = data->nr;
767 int width, name_width;
768 const char *reset, *set, *add_c, *del_c;
770 if (data->nr == 0)
771 return;
773 width = options->stat_width ? options->stat_width : 80;
774 name_width = options->stat_name_width ? options->stat_name_width : 50;
776 /* Sanity: give at least 5 columns to the graph,
777 * but leave at least 10 columns for the name.
779 if (width < 25)
780 width = 25;
781 if (name_width < 10)
782 name_width = 10;
783 else if (width < name_width + 15)
784 name_width = width - 15;
786 /* Find the longest filename and max number of changes */
787 reset = diff_get_color_opt(options, DIFF_RESET);
788 set = diff_get_color_opt(options, DIFF_PLAIN);
789 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
790 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
792 for (i = 0; i < data->nr; i++) {
793 struct diffstat_file *file = data->files[i];
794 int change = file->added + file->deleted;
795 fill_print_name(file);
796 len = strlen(file->print_name);
797 if (max_len < len)
798 max_len = len;
800 if (file->is_binary || file->is_unmerged)
801 continue;
802 if (max_change < change)
803 max_change = change;
806 /* Compute the width of the graph part;
807 * 10 is for one blank at the beginning of the line plus
808 * " | count " between the name and the graph.
810 * From here on, name_width is the width of the name area,
811 * and width is the width of the graph area.
813 name_width = (name_width < max_len) ? name_width : max_len;
814 if (width < (name_width + 10) + max_change)
815 width = width - (name_width + 10);
816 else
817 width = max_change;
819 for (i = 0; i < data->nr; i++) {
820 const char *prefix = "";
821 char *name = data->files[i]->print_name;
822 int added = data->files[i]->added;
823 int deleted = data->files[i]->deleted;
824 int name_len;
827 * "scale" the filename
829 len = name_width;
830 name_len = strlen(name);
831 if (name_width < name_len) {
832 char *slash;
833 prefix = "...";
834 len -= 3;
835 name += name_len - len;
836 slash = strchr(name, '/');
837 if (slash)
838 name = slash;
841 if (data->files[i]->is_binary) {
842 show_name(options->file, prefix, name, len, reset, set);
843 fprintf(options->file, " Bin ");
844 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
845 fprintf(options->file, " -> ");
846 fprintf(options->file, "%s%d%s", add_c, added, reset);
847 fprintf(options->file, " bytes");
848 fprintf(options->file, "\n");
849 continue;
851 else if (data->files[i]->is_unmerged) {
852 show_name(options->file, prefix, name, len, reset, set);
853 fprintf(options->file, " Unmerged\n");
854 continue;
856 else if (!data->files[i]->is_renamed &&
857 (added + deleted == 0)) {
858 total_files--;
859 continue;
863 * scale the add/delete
865 add = added;
866 del = deleted;
867 total = add + del;
868 adds += add;
869 dels += del;
871 if (width <= max_change) {
872 add = scale_linear(add, width, max_change);
873 del = scale_linear(del, width, max_change);
874 total = add + del;
876 show_name(options->file, prefix, name, len, reset, set);
877 fprintf(options->file, "%5d%s", added + deleted,
878 added + deleted ? " " : "");
879 show_graph(options->file, '+', add, add_c, reset);
880 show_graph(options->file, '-', del, del_c, reset);
881 fprintf(options->file, "\n");
883 fprintf(options->file,
884 "%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
885 set, total_files, adds, dels, reset);
888 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
890 int i, adds = 0, dels = 0, total_files = data->nr;
892 if (data->nr == 0)
893 return;
895 for (i = 0; i < data->nr; i++) {
896 if (!data->files[i]->is_binary &&
897 !data->files[i]->is_unmerged) {
898 int added = data->files[i]->added;
899 int deleted= data->files[i]->deleted;
900 if (!data->files[i]->is_renamed &&
901 (added + deleted == 0)) {
902 total_files--;
903 } else {
904 adds += added;
905 dels += deleted;
909 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
910 total_files, adds, dels);
913 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
915 int i;
917 if (data->nr == 0)
918 return;
920 for (i = 0; i < data->nr; i++) {
921 struct diffstat_file *file = data->files[i];
923 if (file->is_binary)
924 fprintf(options->file, "-\t-\t");
925 else
926 fprintf(options->file,
927 "%d\t%d\t", file->added, file->deleted);
928 if (options->line_termination) {
929 fill_print_name(file);
930 if (!file->is_renamed)
931 write_name_quoted(file->name, options->file,
932 options->line_termination);
933 else {
934 fputs(file->print_name, options->file);
935 putc(options->line_termination, options->file);
937 } else {
938 if (file->is_renamed) {
939 putc('\0', options->file);
940 write_name_quoted(file->from_name, options->file, '\0');
942 write_name_quoted(file->name, options->file, '\0');
947 struct dirstat_file {
948 const char *name;
949 unsigned long changed;
952 struct dirstat_dir {
953 struct dirstat_file *files;
954 int alloc, nr, percent, cumulative;
957 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
959 unsigned long this_dir = 0;
960 unsigned int sources = 0;
962 while (dir->nr) {
963 struct dirstat_file *f = dir->files;
964 int namelen = strlen(f->name);
965 unsigned long this;
966 char *slash;
968 if (namelen < baselen)
969 break;
970 if (memcmp(f->name, base, baselen))
971 break;
972 slash = strchr(f->name + baselen, '/');
973 if (slash) {
974 int newbaselen = slash + 1 - f->name;
975 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
976 sources++;
977 } else {
978 this = f->changed;
979 dir->files++;
980 dir->nr--;
981 sources += 2;
983 this_dir += this;
987 * We don't report dirstat's for
988 * - the top level
989 * - or cases where everything came from a single directory
990 * under this directory (sources == 1).
992 if (baselen && sources != 1) {
993 int permille = this_dir * 1000 / changed;
994 if (permille) {
995 int percent = permille / 10;
996 if (percent >= dir->percent) {
997 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
998 if (!dir->cumulative)
999 return 0;
1003 return this_dir;
1006 static int dirstat_compare(const void *_a, const void *_b)
1008 const struct dirstat_file *a = _a;
1009 const struct dirstat_file *b = _b;
1010 return strcmp(a->name, b->name);
1013 static void show_dirstat(struct diff_options *options)
1015 int i;
1016 unsigned long changed;
1017 struct dirstat_dir dir;
1018 struct diff_queue_struct *q = &diff_queued_diff;
1020 dir.files = NULL;
1021 dir.alloc = 0;
1022 dir.nr = 0;
1023 dir.percent = options->dirstat_percent;
1024 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1026 changed = 0;
1027 for (i = 0; i < q->nr; i++) {
1028 struct diff_filepair *p = q->queue[i];
1029 const char *name;
1030 unsigned long copied, added, damage;
1032 name = p->one->path ? p->one->path : p->two->path;
1034 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1035 diff_populate_filespec(p->one, 0);
1036 diff_populate_filespec(p->two, 0);
1037 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1038 &copied, &added);
1039 diff_free_filespec_data(p->one);
1040 diff_free_filespec_data(p->two);
1041 } else if (DIFF_FILE_VALID(p->one)) {
1042 diff_populate_filespec(p->one, 1);
1043 copied = added = 0;
1044 diff_free_filespec_data(p->one);
1045 } else if (DIFF_FILE_VALID(p->two)) {
1046 diff_populate_filespec(p->two, 1);
1047 copied = 0;
1048 added = p->two->size;
1049 diff_free_filespec_data(p->two);
1050 } else
1051 continue;
1054 * Original minus copied is the removed material,
1055 * added is the new material. They are both damages
1056 * made to the preimage. In --dirstat-by-file mode, count
1057 * damaged files, not damaged lines. This is done by
1058 * counting only a single damaged line per file.
1060 damage = (p->one->size - copied) + added;
1061 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1062 damage = 1;
1064 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1065 dir.files[dir.nr].name = name;
1066 dir.files[dir.nr].changed = damage;
1067 changed += damage;
1068 dir.nr++;
1071 /* This can happen even with many files, if everything was renames */
1072 if (!changed)
1073 return;
1075 /* Show all directories with more than x% of the changes */
1076 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1077 gather_dirstat(options->file, &dir, changed, "", 0);
1080 static void free_diffstat_info(struct diffstat_t *diffstat)
1082 int i;
1083 for (i = 0; i < diffstat->nr; i++) {
1084 struct diffstat_file *f = diffstat->files[i];
1085 if (f->name != f->print_name)
1086 free(f->print_name);
1087 free(f->name);
1088 free(f->from_name);
1089 free(f);
1091 free(diffstat->files);
1094 struct checkdiff_t {
1095 const char *filename;
1096 int lineno;
1097 struct diff_options *o;
1098 unsigned ws_rule;
1099 unsigned status;
1100 int trailing_blanks_start;
1103 static int is_conflict_marker(const char *line, unsigned long len)
1105 char firstchar;
1106 int cnt;
1108 if (len < 8)
1109 return 0;
1110 firstchar = line[0];
1111 switch (firstchar) {
1112 case '=': case '>': case '<':
1113 break;
1114 default:
1115 return 0;
1117 for (cnt = 1; cnt < 7; cnt++)
1118 if (line[cnt] != firstchar)
1119 return 0;
1120 /* line[0] thru line[6] are same as firstchar */
1121 if (firstchar == '=') {
1122 /* divider between ours and theirs? */
1123 if (len != 8 || line[7] != '\n')
1124 return 0;
1125 } else if (len < 8 || !isspace(line[7])) {
1126 /* not divider before ours nor after theirs */
1127 return 0;
1129 return 1;
1132 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1134 struct checkdiff_t *data = priv;
1135 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1136 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1137 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1138 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1139 char *err;
1141 if (line[0] == '+') {
1142 unsigned bad;
1143 data->lineno++;
1144 if (!ws_blank_line(line + 1, len - 1, data->ws_rule))
1145 data->trailing_blanks_start = 0;
1146 else if (!data->trailing_blanks_start)
1147 data->trailing_blanks_start = data->lineno;
1148 if (is_conflict_marker(line + 1, len - 1)) {
1149 data->status |= 1;
1150 fprintf(data->o->file,
1151 "%s:%d: leftover conflict marker\n",
1152 data->filename, data->lineno);
1154 bad = ws_check(line + 1, len - 1, data->ws_rule);
1155 if (!bad)
1156 return;
1157 data->status |= bad;
1158 err = whitespace_error_string(bad);
1159 fprintf(data->o->file, "%s:%d: %s.\n",
1160 data->filename, data->lineno, err);
1161 free(err);
1162 emit_line(data->o->file, set, reset, line, 1);
1163 ws_check_emit(line + 1, len - 1, data->ws_rule,
1164 data->o->file, set, reset, ws);
1165 } else if (line[0] == ' ') {
1166 data->lineno++;
1167 data->trailing_blanks_start = 0;
1168 } else if (line[0] == '@') {
1169 char *plus = strchr(line, '+');
1170 if (plus)
1171 data->lineno = strtol(plus, NULL, 10) - 1;
1172 else
1173 die("invalid diff");
1174 data->trailing_blanks_start = 0;
1178 static unsigned char *deflate_it(char *data,
1179 unsigned long size,
1180 unsigned long *result_size)
1182 int bound;
1183 unsigned char *deflated;
1184 z_stream stream;
1186 memset(&stream, 0, sizeof(stream));
1187 deflateInit(&stream, zlib_compression_level);
1188 bound = deflateBound(&stream, size);
1189 deflated = xmalloc(bound);
1190 stream.next_out = deflated;
1191 stream.avail_out = bound;
1193 stream.next_in = (unsigned char *)data;
1194 stream.avail_in = size;
1195 while (deflate(&stream, Z_FINISH) == Z_OK)
1196 ; /* nothing */
1197 deflateEnd(&stream);
1198 *result_size = stream.total_out;
1199 return deflated;
1202 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1204 void *cp;
1205 void *delta;
1206 void *deflated;
1207 void *data;
1208 unsigned long orig_size;
1209 unsigned long delta_size;
1210 unsigned long deflate_size;
1211 unsigned long data_size;
1213 /* We could do deflated delta, or we could do just deflated two,
1214 * whichever is smaller.
1216 delta = NULL;
1217 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1218 if (one->size && two->size) {
1219 delta = diff_delta(one->ptr, one->size,
1220 two->ptr, two->size,
1221 &delta_size, deflate_size);
1222 if (delta) {
1223 void *to_free = delta;
1224 orig_size = delta_size;
1225 delta = deflate_it(delta, delta_size, &delta_size);
1226 free(to_free);
1230 if (delta && delta_size < deflate_size) {
1231 fprintf(file, "delta %lu\n", orig_size);
1232 free(deflated);
1233 data = delta;
1234 data_size = delta_size;
1236 else {
1237 fprintf(file, "literal %lu\n", two->size);
1238 free(delta);
1239 data = deflated;
1240 data_size = deflate_size;
1243 /* emit data encoded in base85 */
1244 cp = data;
1245 while (data_size) {
1246 int bytes = (52 < data_size) ? 52 : data_size;
1247 char line[70];
1248 data_size -= bytes;
1249 if (bytes <= 26)
1250 line[0] = bytes + 'A' - 1;
1251 else
1252 line[0] = bytes - 26 + 'a' - 1;
1253 encode_85(line + 1, cp, bytes);
1254 cp = (char *) cp + bytes;
1255 fputs(line, file);
1256 fputc('\n', file);
1258 fprintf(file, "\n");
1259 free(data);
1262 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1264 fprintf(file, "GIT binary patch\n");
1265 emit_binary_diff_body(file, one, two);
1266 emit_binary_diff_body(file, two, one);
1269 static void diff_filespec_load_driver(struct diff_filespec *one)
1271 if (!one->driver)
1272 one->driver = userdiff_find_by_path(one->path);
1273 if (!one->driver)
1274 one->driver = userdiff_find_by_name("default");
1277 int diff_filespec_is_binary(struct diff_filespec *one)
1279 if (one->is_binary == -1) {
1280 diff_filespec_load_driver(one);
1281 if (one->driver->binary != -1)
1282 one->is_binary = one->driver->binary;
1283 else {
1284 if (!one->data && DIFF_FILE_VALID(one))
1285 diff_populate_filespec(one, 0);
1286 if (one->data)
1287 one->is_binary = buffer_is_binary(one->data,
1288 one->size);
1289 if (one->is_binary == -1)
1290 one->is_binary = 0;
1293 return one->is_binary;
1296 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1298 diff_filespec_load_driver(one);
1299 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1302 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1304 if (!options->a_prefix)
1305 options->a_prefix = a;
1306 if (!options->b_prefix)
1307 options->b_prefix = b;
1310 static const char *get_textconv(struct diff_filespec *one)
1312 if (!DIFF_FILE_VALID(one))
1313 return NULL;
1314 if (!S_ISREG(one->mode))
1315 return NULL;
1316 diff_filespec_load_driver(one);
1317 return one->driver->textconv;
1320 static void builtin_diff(const char *name_a,
1321 const char *name_b,
1322 struct diff_filespec *one,
1323 struct diff_filespec *two,
1324 const char *xfrm_msg,
1325 struct diff_options *o,
1326 int complete_rewrite)
1328 mmfile_t mf1, mf2;
1329 const char *lbl[2];
1330 char *a_one, *b_two;
1331 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1332 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1333 const char *a_prefix, *b_prefix;
1334 const char *textconv_one = NULL, *textconv_two = NULL;
1336 diff_set_mnemonic_prefix(o, "a/", "b/");
1337 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1338 a_prefix = o->b_prefix;
1339 b_prefix = o->a_prefix;
1340 } else {
1341 a_prefix = o->a_prefix;
1342 b_prefix = o->b_prefix;
1345 /* Never use a non-valid filename anywhere if at all possible */
1346 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1347 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1349 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1350 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1351 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1352 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1353 fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1354 if (lbl[0][0] == '/') {
1355 /* /dev/null */
1356 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1357 if (xfrm_msg && xfrm_msg[0])
1358 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1360 else if (lbl[1][0] == '/') {
1361 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1362 if (xfrm_msg && xfrm_msg[0])
1363 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1365 else {
1366 if (one->mode != two->mode) {
1367 fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1368 fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1370 if (xfrm_msg && xfrm_msg[0])
1371 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1373 * we do not run diff between different kind
1374 * of objects.
1376 if ((one->mode ^ two->mode) & S_IFMT)
1377 goto free_ab_and_return;
1378 if (complete_rewrite) {
1379 emit_rewrite_diff(name_a, name_b, one, two, o);
1380 o->found_changes = 1;
1381 goto free_ab_and_return;
1385 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1386 die("unable to read files to diff");
1388 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1389 textconv_one = get_textconv(one);
1390 textconv_two = get_textconv(two);
1393 if (!DIFF_OPT_TST(o, TEXT) &&
1394 ( (diff_filespec_is_binary(one) && !textconv_one) ||
1395 (diff_filespec_is_binary(two) && !textconv_two) )) {
1396 /* Quite common confusing case */
1397 if (mf1.size == mf2.size &&
1398 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1399 goto free_ab_and_return;
1400 if (DIFF_OPT_TST(o, BINARY))
1401 emit_binary_diff(o->file, &mf1, &mf2);
1402 else
1403 fprintf(o->file, "Binary files %s and %s differ\n",
1404 lbl[0], lbl[1]);
1405 o->found_changes = 1;
1407 else {
1408 /* Crazy xdl interfaces.. */
1409 const char *diffopts = getenv("GIT_DIFF_OPTS");
1410 xpparam_t xpp;
1411 xdemitconf_t xecfg;
1412 xdemitcb_t ecb;
1413 struct emit_callback ecbdata;
1414 const struct userdiff_funcname *pe;
1416 if (textconv_one) {
1417 size_t size;
1418 mf1.ptr = run_textconv(textconv_one, one, &size);
1419 if (!mf1.ptr)
1420 die("unable to read files to diff");
1421 mf1.size = size;
1423 if (textconv_two) {
1424 size_t size;
1425 mf2.ptr = run_textconv(textconv_two, two, &size);
1426 if (!mf2.ptr)
1427 die("unable to read files to diff");
1428 mf2.size = size;
1431 pe = diff_funcname_pattern(one);
1432 if (!pe)
1433 pe = diff_funcname_pattern(two);
1435 memset(&xecfg, 0, sizeof(xecfg));
1436 memset(&ecbdata, 0, sizeof(ecbdata));
1437 ecbdata.label_path = lbl;
1438 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1439 ecbdata.found_changesp = &o->found_changes;
1440 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1441 ecbdata.file = o->file;
1442 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1443 xecfg.ctxlen = o->context;
1444 xecfg.flags = XDL_EMIT_FUNCNAMES;
1445 if (pe)
1446 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1447 if (!diffopts)
1449 else if (!prefixcmp(diffopts, "--unified="))
1450 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1451 else if (!prefixcmp(diffopts, "-u"))
1452 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1453 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1454 ecbdata.diff_words =
1455 xcalloc(1, sizeof(struct diff_words_data));
1456 ecbdata.diff_words->file = o->file;
1458 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1459 &xpp, &xecfg, &ecb);
1460 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1461 free_diff_words_data(&ecbdata);
1462 if (textconv_one)
1463 free(mf1.ptr);
1464 if (textconv_two)
1465 free(mf2.ptr);
1468 free_ab_and_return:
1469 diff_free_filespec_data(one);
1470 diff_free_filespec_data(two);
1471 free(a_one);
1472 free(b_two);
1473 return;
1476 static void builtin_diffstat(const char *name_a, const char *name_b,
1477 struct diff_filespec *one,
1478 struct diff_filespec *two,
1479 struct diffstat_t *diffstat,
1480 struct diff_options *o,
1481 int complete_rewrite)
1483 mmfile_t mf1, mf2;
1484 struct diffstat_file *data;
1486 data = diffstat_add(diffstat, name_a, name_b);
1488 if (!one || !two) {
1489 data->is_unmerged = 1;
1490 return;
1492 if (complete_rewrite) {
1493 diff_populate_filespec(one, 0);
1494 diff_populate_filespec(two, 0);
1495 data->deleted = count_lines(one->data, one->size);
1496 data->added = count_lines(two->data, two->size);
1497 goto free_and_return;
1499 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1500 die("unable to read files to diff");
1502 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1503 data->is_binary = 1;
1504 data->added = mf2.size;
1505 data->deleted = mf1.size;
1506 } else {
1507 /* Crazy xdl interfaces.. */
1508 xpparam_t xpp;
1509 xdemitconf_t xecfg;
1510 xdemitcb_t ecb;
1512 memset(&xecfg, 0, sizeof(xecfg));
1513 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1514 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1515 &xpp, &xecfg, &ecb);
1518 free_and_return:
1519 diff_free_filespec_data(one);
1520 diff_free_filespec_data(two);
1523 static void builtin_checkdiff(const char *name_a, const char *name_b,
1524 const char *attr_path,
1525 struct diff_filespec *one,
1526 struct diff_filespec *two,
1527 struct diff_options *o)
1529 mmfile_t mf1, mf2;
1530 struct checkdiff_t data;
1532 if (!two)
1533 return;
1535 memset(&data, 0, sizeof(data));
1536 data.filename = name_b ? name_b : name_a;
1537 data.lineno = 0;
1538 data.o = o;
1539 data.ws_rule = whitespace_rule(attr_path);
1541 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1542 die("unable to read files to diff");
1545 * All the other codepaths check both sides, but not checking
1546 * the "old" side here is deliberate. We are checking the newly
1547 * introduced changes, and as long as the "new" side is text, we
1548 * can and should check what it introduces.
1550 if (diff_filespec_is_binary(two))
1551 goto free_and_return;
1552 else {
1553 /* Crazy xdl interfaces.. */
1554 xpparam_t xpp;
1555 xdemitconf_t xecfg;
1556 xdemitcb_t ecb;
1558 memset(&xecfg, 0, sizeof(xecfg));
1559 xecfg.ctxlen = 1; /* at least one context line */
1560 xpp.flags = XDF_NEED_MINIMAL;
1561 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1562 &xpp, &xecfg, &ecb);
1564 if ((data.ws_rule & WS_TRAILING_SPACE) &&
1565 data.trailing_blanks_start) {
1566 fprintf(o->file, "%s:%d: ends with blank lines.\n",
1567 data.filename, data.trailing_blanks_start);
1568 data.status = 1; /* report errors */
1571 free_and_return:
1572 diff_free_filespec_data(one);
1573 diff_free_filespec_data(two);
1574 if (data.status)
1575 DIFF_OPT_SET(o, CHECK_FAILED);
1578 struct diff_filespec *alloc_filespec(const char *path)
1580 int namelen = strlen(path);
1581 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1583 memset(spec, 0, sizeof(*spec));
1584 spec->path = (char *)(spec + 1);
1585 memcpy(spec->path, path, namelen+1);
1586 spec->count = 1;
1587 spec->is_binary = -1;
1588 return spec;
1591 void free_filespec(struct diff_filespec *spec)
1593 if (!--spec->count) {
1594 diff_free_filespec_data(spec);
1595 free(spec);
1599 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1600 unsigned short mode)
1602 if (mode) {
1603 spec->mode = canon_mode(mode);
1604 hashcpy(spec->sha1, sha1);
1605 spec->sha1_valid = !is_null_sha1(sha1);
1610 * Given a name and sha1 pair, if the index tells us the file in
1611 * the work tree has that object contents, return true, so that
1612 * prepare_temp_file() does not have to inflate and extract.
1614 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1616 struct cache_entry *ce;
1617 struct stat st;
1618 int pos, len;
1620 /* We do not read the cache ourselves here, because the
1621 * benchmark with my previous version that always reads cache
1622 * shows that it makes things worse for diff-tree comparing
1623 * two linux-2.6 kernel trees in an already checked out work
1624 * tree. This is because most diff-tree comparisons deal with
1625 * only a small number of files, while reading the cache is
1626 * expensive for a large project, and its cost outweighs the
1627 * savings we get by not inflating the object to a temporary
1628 * file. Practically, this code only helps when we are used
1629 * by diff-cache --cached, which does read the cache before
1630 * calling us.
1632 if (!active_cache)
1633 return 0;
1635 /* We want to avoid the working directory if our caller
1636 * doesn't need the data in a normal file, this system
1637 * is rather slow with its stat/open/mmap/close syscalls,
1638 * and the object is contained in a pack file. The pack
1639 * is probably already open and will be faster to obtain
1640 * the data through than the working directory. Loose
1641 * objects however would tend to be slower as they need
1642 * to be individually opened and inflated.
1644 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1645 return 0;
1647 len = strlen(name);
1648 pos = cache_name_pos(name, len);
1649 if (pos < 0)
1650 return 0;
1651 ce = active_cache[pos];
1654 * This is not the sha1 we are looking for, or
1655 * unreusable because it is not a regular file.
1657 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1658 return 0;
1661 * If ce matches the file in the work tree, we can reuse it.
1663 if (ce_uptodate(ce) ||
1664 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1665 return 1;
1667 return 0;
1670 static int populate_from_stdin(struct diff_filespec *s)
1672 struct strbuf buf = STRBUF_INIT;
1673 size_t size = 0;
1675 if (strbuf_read(&buf, 0, 0) < 0)
1676 return error("error while reading from stdin %s",
1677 strerror(errno));
1679 s->should_munmap = 0;
1680 s->data = strbuf_detach(&buf, &size);
1681 s->size = size;
1682 s->should_free = 1;
1683 return 0;
1686 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1688 int len;
1689 char *data = xmalloc(100);
1690 len = snprintf(data, 100,
1691 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1692 s->data = data;
1693 s->size = len;
1694 s->should_free = 1;
1695 if (size_only) {
1696 s->data = NULL;
1697 free(data);
1699 return 0;
1703 * While doing rename detection and pickaxe operation, we may need to
1704 * grab the data for the blob (or file) for our own in-core comparison.
1705 * diff_filespec has data and size fields for this purpose.
1707 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1709 int err = 0;
1710 if (!DIFF_FILE_VALID(s))
1711 die("internal error: asking to populate invalid file.");
1712 if (S_ISDIR(s->mode))
1713 return -1;
1715 if (s->data)
1716 return 0;
1718 if (size_only && 0 < s->size)
1719 return 0;
1721 if (S_ISGITLINK(s->mode))
1722 return diff_populate_gitlink(s, size_only);
1724 if (!s->sha1_valid ||
1725 reuse_worktree_file(s->path, s->sha1, 0)) {
1726 struct strbuf buf = STRBUF_INIT;
1727 struct stat st;
1728 int fd;
1730 if (!strcmp(s->path, "-"))
1731 return populate_from_stdin(s);
1733 if (lstat(s->path, &st) < 0) {
1734 if (errno == ENOENT) {
1735 err_empty:
1736 err = -1;
1737 empty:
1738 s->data = (char *)"";
1739 s->size = 0;
1740 return err;
1743 s->size = xsize_t(st.st_size);
1744 if (!s->size)
1745 goto empty;
1746 if (size_only)
1747 return 0;
1748 if (S_ISLNK(st.st_mode)) {
1749 int ret;
1750 s->data = xmalloc(s->size);
1751 s->should_free = 1;
1752 ret = readlink(s->path, s->data, s->size);
1753 if (ret < 0) {
1754 free(s->data);
1755 goto err_empty;
1757 return 0;
1759 fd = open(s->path, O_RDONLY);
1760 if (fd < 0)
1761 goto err_empty;
1762 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1763 close(fd);
1764 s->should_munmap = 1;
1767 * Convert from working tree format to canonical git format
1769 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
1770 size_t size = 0;
1771 munmap(s->data, s->size);
1772 s->should_munmap = 0;
1773 s->data = strbuf_detach(&buf, &size);
1774 s->size = size;
1775 s->should_free = 1;
1778 else {
1779 enum object_type type;
1780 if (size_only)
1781 type = sha1_object_info(s->sha1, &s->size);
1782 else {
1783 s->data = read_sha1_file(s->sha1, &type, &s->size);
1784 s->should_free = 1;
1787 return 0;
1790 void diff_free_filespec_blob(struct diff_filespec *s)
1792 if (s->should_free)
1793 free(s->data);
1794 else if (s->should_munmap)
1795 munmap(s->data, s->size);
1797 if (s->should_free || s->should_munmap) {
1798 s->should_free = s->should_munmap = 0;
1799 s->data = NULL;
1803 void diff_free_filespec_data(struct diff_filespec *s)
1805 diff_free_filespec_blob(s);
1806 free(s->cnt_data);
1807 s->cnt_data = NULL;
1810 static void prep_temp_blob(struct diff_tempfile *temp,
1811 void *blob,
1812 unsigned long size,
1813 const unsigned char *sha1,
1814 int mode)
1816 int fd;
1818 fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1819 if (fd < 0)
1820 die("unable to create temp-file: %s", strerror(errno));
1821 if (write_in_full(fd, blob, size) != size)
1822 die("unable to write temp-file");
1823 close(fd);
1824 temp->name = temp->tmp_path;
1825 strcpy(temp->hex, sha1_to_hex(sha1));
1826 temp->hex[40] = 0;
1827 sprintf(temp->mode, "%06o", mode);
1830 static void prepare_temp_file(const char *name,
1831 struct diff_tempfile *temp,
1832 struct diff_filespec *one)
1834 if (!DIFF_FILE_VALID(one)) {
1835 not_a_valid_file:
1836 /* A '-' entry produces this for file-2, and
1837 * a '+' entry produces this for file-1.
1839 temp->name = "/dev/null";
1840 strcpy(temp->hex, ".");
1841 strcpy(temp->mode, ".");
1842 return;
1845 if (!one->sha1_valid ||
1846 reuse_worktree_file(name, one->sha1, 1)) {
1847 struct stat st;
1848 if (lstat(name, &st) < 0) {
1849 if (errno == ENOENT)
1850 goto not_a_valid_file;
1851 die("stat(%s): %s", name, strerror(errno));
1853 if (S_ISLNK(st.st_mode)) {
1854 int ret;
1855 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1856 size_t sz = xsize_t(st.st_size);
1857 if (sizeof(buf) <= st.st_size)
1858 die("symlink too long: %s", name);
1859 ret = readlink(name, buf, sz);
1860 if (ret < 0)
1861 die("readlink(%s)", name);
1862 prep_temp_blob(temp, buf, sz,
1863 (one->sha1_valid ?
1864 one->sha1 : null_sha1),
1865 (one->sha1_valid ?
1866 one->mode : S_IFLNK));
1868 else {
1869 /* we can borrow from the file in the work tree */
1870 temp->name = name;
1871 if (!one->sha1_valid)
1872 strcpy(temp->hex, sha1_to_hex(null_sha1));
1873 else
1874 strcpy(temp->hex, sha1_to_hex(one->sha1));
1875 /* Even though we may sometimes borrow the
1876 * contents from the work tree, we always want
1877 * one->mode. mode is trustworthy even when
1878 * !(one->sha1_valid), as long as
1879 * DIFF_FILE_VALID(one).
1881 sprintf(temp->mode, "%06o", one->mode);
1883 return;
1885 else {
1886 if (diff_populate_filespec(one, 0))
1887 die("cannot read data blob for %s", one->path);
1888 prep_temp_blob(temp, one->data, one->size,
1889 one->sha1, one->mode);
1893 static void remove_tempfile(void)
1895 int i;
1897 for (i = 0; i < 2; i++)
1898 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1899 unlink(diff_temp[i].name);
1900 diff_temp[i].name = NULL;
1904 static void remove_tempfile_on_signal(int signo)
1906 remove_tempfile();
1907 signal(SIGINT, SIG_DFL);
1908 raise(signo);
1911 /* An external diff command takes:
1913 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1914 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1917 static void run_external_diff(const char *pgm,
1918 const char *name,
1919 const char *other,
1920 struct diff_filespec *one,
1921 struct diff_filespec *two,
1922 const char *xfrm_msg,
1923 int complete_rewrite)
1925 const char *spawn_arg[10];
1926 struct diff_tempfile *temp = diff_temp;
1927 int retval;
1928 static int atexit_asked = 0;
1929 const char *othername;
1930 const char **arg = &spawn_arg[0];
1932 othername = (other? other : name);
1933 if (one && two) {
1934 prepare_temp_file(name, &temp[0], one);
1935 prepare_temp_file(othername, &temp[1], two);
1936 if (! atexit_asked &&
1937 (temp[0].name == temp[0].tmp_path ||
1938 temp[1].name == temp[1].tmp_path)) {
1939 atexit_asked = 1;
1940 atexit(remove_tempfile);
1942 signal(SIGINT, remove_tempfile_on_signal);
1945 if (one && two) {
1946 *arg++ = pgm;
1947 *arg++ = name;
1948 *arg++ = temp[0].name;
1949 *arg++ = temp[0].hex;
1950 *arg++ = temp[0].mode;
1951 *arg++ = temp[1].name;
1952 *arg++ = temp[1].hex;
1953 *arg++ = temp[1].mode;
1954 if (other) {
1955 *arg++ = other;
1956 *arg++ = xfrm_msg;
1958 } else {
1959 *arg++ = pgm;
1960 *arg++ = name;
1962 *arg = NULL;
1963 fflush(NULL);
1964 retval = run_command_v_opt(spawn_arg, 0);
1965 remove_tempfile();
1966 if (retval) {
1967 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1968 exit(1);
1972 static void run_diff_cmd(const char *pgm,
1973 const char *name,
1974 const char *other,
1975 const char *attr_path,
1976 struct diff_filespec *one,
1977 struct diff_filespec *two,
1978 const char *xfrm_msg,
1979 struct diff_options *o,
1980 int complete_rewrite)
1982 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
1983 pgm = NULL;
1984 else {
1985 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
1986 if (drv && drv->external)
1987 pgm = drv->external;
1990 if (pgm) {
1991 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1992 complete_rewrite);
1993 return;
1995 if (one && two)
1996 builtin_diff(name, other ? other : name,
1997 one, two, xfrm_msg, o, complete_rewrite);
1998 else
1999 fprintf(o->file, "* Unmerged path %s\n", name);
2002 static void diff_fill_sha1_info(struct diff_filespec *one)
2004 if (DIFF_FILE_VALID(one)) {
2005 if (!one->sha1_valid) {
2006 struct stat st;
2007 if (!strcmp(one->path, "-")) {
2008 hashcpy(one->sha1, null_sha1);
2009 return;
2011 if (lstat(one->path, &st) < 0)
2012 die("stat %s", one->path);
2013 if (index_path(one->sha1, one->path, &st, 0))
2014 die("cannot hash %s\n", one->path);
2017 else
2018 hashclr(one->sha1);
2021 static int similarity_index(struct diff_filepair *p)
2023 return p->score * 100 / MAX_SCORE;
2026 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2028 /* Strip the prefix but do not molest /dev/null and absolute paths */
2029 if (*namep && **namep != '/')
2030 *namep += prefix_length;
2031 if (*otherp && **otherp != '/')
2032 *otherp += prefix_length;
2035 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2037 const char *pgm = external_diff();
2038 struct strbuf msg;
2039 char *xfrm_msg;
2040 struct diff_filespec *one = p->one;
2041 struct diff_filespec *two = p->two;
2042 const char *name;
2043 const char *other;
2044 const char *attr_path;
2045 int complete_rewrite = 0;
2047 name = p->one->path;
2048 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2049 attr_path = name;
2050 if (o->prefix_length)
2051 strip_prefix(o->prefix_length, &name, &other);
2053 if (DIFF_PAIR_UNMERGED(p)) {
2054 run_diff_cmd(pgm, name, NULL, attr_path,
2055 NULL, NULL, NULL, o, 0);
2056 return;
2059 diff_fill_sha1_info(one);
2060 diff_fill_sha1_info(two);
2062 strbuf_init(&msg, PATH_MAX * 2 + 300);
2063 switch (p->status) {
2064 case DIFF_STATUS_COPIED:
2065 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2066 strbuf_addstr(&msg, "\ncopy from ");
2067 quote_c_style(name, &msg, NULL, 0);
2068 strbuf_addstr(&msg, "\ncopy to ");
2069 quote_c_style(other, &msg, NULL, 0);
2070 strbuf_addch(&msg, '\n');
2071 break;
2072 case DIFF_STATUS_RENAMED:
2073 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2074 strbuf_addstr(&msg, "\nrename from ");
2075 quote_c_style(name, &msg, NULL, 0);
2076 strbuf_addstr(&msg, "\nrename to ");
2077 quote_c_style(other, &msg, NULL, 0);
2078 strbuf_addch(&msg, '\n');
2079 break;
2080 case DIFF_STATUS_MODIFIED:
2081 if (p->score) {
2082 strbuf_addf(&msg, "dissimilarity index %d%%\n",
2083 similarity_index(p));
2084 complete_rewrite = 1;
2085 break;
2087 /* fallthru */
2088 default:
2089 /* nothing */
2093 if (hashcmp(one->sha1, two->sha1)) {
2094 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2096 if (DIFF_OPT_TST(o, BINARY)) {
2097 mmfile_t mf;
2098 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2099 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2100 abbrev = 40;
2102 strbuf_addf(&msg, "index %.*s..%.*s",
2103 abbrev, sha1_to_hex(one->sha1),
2104 abbrev, sha1_to_hex(two->sha1));
2105 if (one->mode == two->mode)
2106 strbuf_addf(&msg, " %06o", one->mode);
2107 strbuf_addch(&msg, '\n');
2110 if (msg.len)
2111 strbuf_setlen(&msg, msg.len - 1);
2112 xfrm_msg = msg.len ? msg.buf : NULL;
2114 if (!pgm &&
2115 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2116 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2117 /* a filepair that changes between file and symlink
2118 * needs to be split into deletion and creation.
2120 struct diff_filespec *null = alloc_filespec(two->path);
2121 run_diff_cmd(NULL, name, other, attr_path,
2122 one, null, xfrm_msg, o, 0);
2123 free(null);
2124 null = alloc_filespec(one->path);
2125 run_diff_cmd(NULL, name, other, attr_path,
2126 null, two, xfrm_msg, o, 0);
2127 free(null);
2129 else
2130 run_diff_cmd(pgm, name, other, attr_path,
2131 one, two, xfrm_msg, o, complete_rewrite);
2133 strbuf_release(&msg);
2136 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2137 struct diffstat_t *diffstat)
2139 const char *name;
2140 const char *other;
2141 int complete_rewrite = 0;
2143 if (DIFF_PAIR_UNMERGED(p)) {
2144 /* unmerged */
2145 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2146 return;
2149 name = p->one->path;
2150 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2152 if (o->prefix_length)
2153 strip_prefix(o->prefix_length, &name, &other);
2155 diff_fill_sha1_info(p->one);
2156 diff_fill_sha1_info(p->two);
2158 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2159 complete_rewrite = 1;
2160 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2163 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2165 const char *name;
2166 const char *other;
2167 const char *attr_path;
2169 if (DIFF_PAIR_UNMERGED(p)) {
2170 /* unmerged */
2171 return;
2174 name = p->one->path;
2175 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2176 attr_path = other ? other : name;
2178 if (o->prefix_length)
2179 strip_prefix(o->prefix_length, &name, &other);
2181 diff_fill_sha1_info(p->one);
2182 diff_fill_sha1_info(p->two);
2184 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2187 void diff_setup(struct diff_options *options)
2189 memset(options, 0, sizeof(*options));
2191 options->file = stdout;
2193 options->line_termination = '\n';
2194 options->break_opt = -1;
2195 options->rename_limit = -1;
2196 options->dirstat_percent = 3;
2197 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
2198 options->context = 3;
2200 options->change = diff_change;
2201 options->add_remove = diff_addremove;
2202 if (diff_use_color_default > 0)
2203 DIFF_OPT_SET(options, COLOR_DIFF);
2204 else
2205 DIFF_OPT_CLR(options, COLOR_DIFF);
2206 options->detect_rename = diff_detect_rename_default;
2208 if (!diff_mnemonic_prefix) {
2209 options->a_prefix = "a/";
2210 options->b_prefix = "b/";
2214 int diff_setup_done(struct diff_options *options)
2216 int count = 0;
2218 if (options->output_format & DIFF_FORMAT_NAME)
2219 count++;
2220 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2221 count++;
2222 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2223 count++;
2224 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2225 count++;
2226 if (count > 1)
2227 die("--name-only, --name-status, --check and -s are mutually exclusive");
2229 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2230 options->detect_rename = DIFF_DETECT_COPY;
2232 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2233 options->prefix = NULL;
2234 if (options->prefix)
2235 options->prefix_length = strlen(options->prefix);
2236 else
2237 options->prefix_length = 0;
2239 if (options->output_format & (DIFF_FORMAT_NAME |
2240 DIFF_FORMAT_NAME_STATUS |
2241 DIFF_FORMAT_CHECKDIFF |
2242 DIFF_FORMAT_NO_OUTPUT))
2243 options->output_format &= ~(DIFF_FORMAT_RAW |
2244 DIFF_FORMAT_NUMSTAT |
2245 DIFF_FORMAT_DIFFSTAT |
2246 DIFF_FORMAT_SHORTSTAT |
2247 DIFF_FORMAT_DIRSTAT |
2248 DIFF_FORMAT_SUMMARY |
2249 DIFF_FORMAT_PATCH);
2252 * These cases always need recursive; we do not drop caller-supplied
2253 * recursive bits for other formats here.
2255 if (options->output_format & (DIFF_FORMAT_PATCH |
2256 DIFF_FORMAT_NUMSTAT |
2257 DIFF_FORMAT_DIFFSTAT |
2258 DIFF_FORMAT_SHORTSTAT |
2259 DIFF_FORMAT_DIRSTAT |
2260 DIFF_FORMAT_SUMMARY |
2261 DIFF_FORMAT_CHECKDIFF))
2262 DIFF_OPT_SET(options, RECURSIVE);
2264 * Also pickaxe would not work very well if you do not say recursive
2266 if (options->pickaxe)
2267 DIFF_OPT_SET(options, RECURSIVE);
2269 if (options->detect_rename && options->rename_limit < 0)
2270 options->rename_limit = diff_rename_limit_default;
2271 if (options->setup & DIFF_SETUP_USE_CACHE) {
2272 if (!active_cache)
2273 /* read-cache does not die even when it fails
2274 * so it is safe for us to do this here. Also
2275 * it does not smudge active_cache or active_nr
2276 * when it fails, so we do not have to worry about
2277 * cleaning it up ourselves either.
2279 read_cache();
2281 if (options->abbrev <= 0 || 40 < options->abbrev)
2282 options->abbrev = 40; /* full */
2285 * It does not make sense to show the first hit we happened
2286 * to have found. It does not make sense not to return with
2287 * exit code in such a case either.
2289 if (DIFF_OPT_TST(options, QUIET)) {
2290 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2291 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2294 return 0;
2297 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2299 char c, *eq;
2300 int len;
2302 if (*arg != '-')
2303 return 0;
2304 c = *++arg;
2305 if (!c)
2306 return 0;
2307 if (c == arg_short) {
2308 c = *++arg;
2309 if (!c)
2310 return 1;
2311 if (val && isdigit(c)) {
2312 char *end;
2313 int n = strtoul(arg, &end, 10);
2314 if (*end)
2315 return 0;
2316 *val = n;
2317 return 1;
2319 return 0;
2321 if (c != '-')
2322 return 0;
2323 arg++;
2324 eq = strchr(arg, '=');
2325 if (eq)
2326 len = eq - arg;
2327 else
2328 len = strlen(arg);
2329 if (!len || strncmp(arg, arg_long, len))
2330 return 0;
2331 if (eq) {
2332 int n;
2333 char *end;
2334 if (!isdigit(*++eq))
2335 return 0;
2336 n = strtoul(eq, &end, 10);
2337 if (*end)
2338 return 0;
2339 *val = n;
2341 return 1;
2344 static int diff_scoreopt_parse(const char *opt);
2346 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2348 const char *arg = av[0];
2350 /* Output format options */
2351 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2352 options->output_format |= DIFF_FORMAT_PATCH;
2353 else if (opt_arg(arg, 'U', "unified", &options->context))
2354 options->output_format |= DIFF_FORMAT_PATCH;
2355 else if (!strcmp(arg, "--raw"))
2356 options->output_format |= DIFF_FORMAT_RAW;
2357 else if (!strcmp(arg, "--patch-with-raw"))
2358 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2359 else if (!strcmp(arg, "--numstat"))
2360 options->output_format |= DIFF_FORMAT_NUMSTAT;
2361 else if (!strcmp(arg, "--shortstat"))
2362 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2363 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2364 options->output_format |= DIFF_FORMAT_DIRSTAT;
2365 else if (!strcmp(arg, "--cumulative")) {
2366 options->output_format |= DIFF_FORMAT_DIRSTAT;
2367 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2368 } else if (opt_arg(arg, 0, "dirstat-by-file",
2369 &options->dirstat_percent)) {
2370 options->output_format |= DIFF_FORMAT_DIRSTAT;
2371 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2373 else if (!strcmp(arg, "--check"))
2374 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2375 else if (!strcmp(arg, "--summary"))
2376 options->output_format |= DIFF_FORMAT_SUMMARY;
2377 else if (!strcmp(arg, "--patch-with-stat"))
2378 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2379 else if (!strcmp(arg, "--name-only"))
2380 options->output_format |= DIFF_FORMAT_NAME;
2381 else if (!strcmp(arg, "--name-status"))
2382 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2383 else if (!strcmp(arg, "-s"))
2384 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2385 else if (!prefixcmp(arg, "--stat")) {
2386 char *end;
2387 int width = options->stat_width;
2388 int name_width = options->stat_name_width;
2389 arg += 6;
2390 end = (char *)arg;
2392 switch (*arg) {
2393 case '-':
2394 if (!prefixcmp(arg, "-width="))
2395 width = strtoul(arg + 7, &end, 10);
2396 else if (!prefixcmp(arg, "-name-width="))
2397 name_width = strtoul(arg + 12, &end, 10);
2398 break;
2399 case '=':
2400 width = strtoul(arg+1, &end, 10);
2401 if (*end == ',')
2402 name_width = strtoul(end+1, &end, 10);
2405 /* Important! This checks all the error cases! */
2406 if (*end)
2407 return 0;
2408 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2409 options->stat_name_width = name_width;
2410 options->stat_width = width;
2413 /* renames options */
2414 else if (!prefixcmp(arg, "-B")) {
2415 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2416 return -1;
2418 else if (!prefixcmp(arg, "-M")) {
2419 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2420 return -1;
2421 options->detect_rename = DIFF_DETECT_RENAME;
2423 else if (!prefixcmp(arg, "-C")) {
2424 if (options->detect_rename == DIFF_DETECT_COPY)
2425 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2426 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2427 return -1;
2428 options->detect_rename = DIFF_DETECT_COPY;
2430 else if (!strcmp(arg, "--no-renames"))
2431 options->detect_rename = 0;
2432 else if (!strcmp(arg, "--relative"))
2433 DIFF_OPT_SET(options, RELATIVE_NAME);
2434 else if (!prefixcmp(arg, "--relative=")) {
2435 DIFF_OPT_SET(options, RELATIVE_NAME);
2436 options->prefix = arg + 11;
2439 /* xdiff options */
2440 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2441 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2442 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2443 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2444 else if (!strcmp(arg, "--ignore-space-at-eol"))
2445 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2447 /* flags options */
2448 else if (!strcmp(arg, "--binary")) {
2449 options->output_format |= DIFF_FORMAT_PATCH;
2450 DIFF_OPT_SET(options, BINARY);
2452 else if (!strcmp(arg, "--full-index"))
2453 DIFF_OPT_SET(options, FULL_INDEX);
2454 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2455 DIFF_OPT_SET(options, TEXT);
2456 else if (!strcmp(arg, "-R"))
2457 DIFF_OPT_SET(options, REVERSE_DIFF);
2458 else if (!strcmp(arg, "--find-copies-harder"))
2459 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2460 else if (!strcmp(arg, "--follow"))
2461 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2462 else if (!strcmp(arg, "--color"))
2463 DIFF_OPT_SET(options, COLOR_DIFF);
2464 else if (!strcmp(arg, "--no-color"))
2465 DIFF_OPT_CLR(options, COLOR_DIFF);
2466 else if (!strcmp(arg, "--color-words"))
2467 options->flags |= DIFF_OPT_COLOR_DIFF | DIFF_OPT_COLOR_DIFF_WORDS;
2468 else if (!strcmp(arg, "--exit-code"))
2469 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2470 else if (!strcmp(arg, "--quiet"))
2471 DIFF_OPT_SET(options, QUIET);
2472 else if (!strcmp(arg, "--ext-diff"))
2473 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2474 else if (!strcmp(arg, "--no-ext-diff"))
2475 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2476 else if (!strcmp(arg, "--ignore-submodules"))
2477 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2479 /* misc options */
2480 else if (!strcmp(arg, "-z"))
2481 options->line_termination = 0;
2482 else if (!prefixcmp(arg, "-l"))
2483 options->rename_limit = strtoul(arg+2, NULL, 10);
2484 else if (!prefixcmp(arg, "-S"))
2485 options->pickaxe = arg + 2;
2486 else if (!strcmp(arg, "--pickaxe-all"))
2487 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2488 else if (!strcmp(arg, "--pickaxe-regex"))
2489 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2490 else if (!prefixcmp(arg, "-O"))
2491 options->orderfile = arg + 2;
2492 else if (!prefixcmp(arg, "--diff-filter="))
2493 options->filter = arg + 14;
2494 else if (!strcmp(arg, "--abbrev"))
2495 options->abbrev = DEFAULT_ABBREV;
2496 else if (!prefixcmp(arg, "--abbrev=")) {
2497 options->abbrev = strtoul(arg + 9, NULL, 10);
2498 if (options->abbrev < MINIMUM_ABBREV)
2499 options->abbrev = MINIMUM_ABBREV;
2500 else if (40 < options->abbrev)
2501 options->abbrev = 40;
2503 else if (!prefixcmp(arg, "--src-prefix="))
2504 options->a_prefix = arg + 13;
2505 else if (!prefixcmp(arg, "--dst-prefix="))
2506 options->b_prefix = arg + 13;
2507 else if (!strcmp(arg, "--no-prefix"))
2508 options->a_prefix = options->b_prefix = "";
2509 else if (!prefixcmp(arg, "--output=")) {
2510 options->file = fopen(arg + strlen("--output="), "w");
2511 options->close_file = 1;
2512 } else
2513 return 0;
2514 return 1;
2517 static int parse_num(const char **cp_p)
2519 unsigned long num, scale;
2520 int ch, dot;
2521 const char *cp = *cp_p;
2523 num = 0;
2524 scale = 1;
2525 dot = 0;
2526 for(;;) {
2527 ch = *cp;
2528 if ( !dot && ch == '.' ) {
2529 scale = 1;
2530 dot = 1;
2531 } else if ( ch == '%' ) {
2532 scale = dot ? scale*100 : 100;
2533 cp++; /* % is always at the end */
2534 break;
2535 } else if ( ch >= '0' && ch <= '9' ) {
2536 if ( scale < 100000 ) {
2537 scale *= 10;
2538 num = (num*10) + (ch-'0');
2540 } else {
2541 break;
2543 cp++;
2545 *cp_p = cp;
2547 /* user says num divided by scale and we say internally that
2548 * is MAX_SCORE * num / scale.
2550 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2553 static int diff_scoreopt_parse(const char *opt)
2555 int opt1, opt2, cmd;
2557 if (*opt++ != '-')
2558 return -1;
2559 cmd = *opt++;
2560 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2561 return -1; /* that is not a -M, -C nor -B option */
2563 opt1 = parse_num(&opt);
2564 if (cmd != 'B')
2565 opt2 = 0;
2566 else {
2567 if (*opt == 0)
2568 opt2 = 0;
2569 else if (*opt != '/')
2570 return -1; /* we expect -B80/99 or -B80 */
2571 else {
2572 opt++;
2573 opt2 = parse_num(&opt);
2576 if (*opt != 0)
2577 return -1;
2578 return opt1 | (opt2 << 16);
2581 struct diff_queue_struct diff_queued_diff;
2583 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2585 if (queue->alloc <= queue->nr) {
2586 queue->alloc = alloc_nr(queue->alloc);
2587 queue->queue = xrealloc(queue->queue,
2588 sizeof(dp) * queue->alloc);
2590 queue->queue[queue->nr++] = dp;
2593 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2594 struct diff_filespec *one,
2595 struct diff_filespec *two)
2597 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2598 dp->one = one;
2599 dp->two = two;
2600 if (queue)
2601 diff_q(queue, dp);
2602 return dp;
2605 void diff_free_filepair(struct diff_filepair *p)
2607 free_filespec(p->one);
2608 free_filespec(p->two);
2609 free(p);
2612 /* This is different from find_unique_abbrev() in that
2613 * it stuffs the result with dots for alignment.
2615 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2617 int abblen;
2618 const char *abbrev;
2619 if (len == 40)
2620 return sha1_to_hex(sha1);
2622 abbrev = find_unique_abbrev(sha1, len);
2623 abblen = strlen(abbrev);
2624 if (abblen < 37) {
2625 static char hex[41];
2626 if (len < abblen && abblen <= len + 2)
2627 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2628 else
2629 sprintf(hex, "%s...", abbrev);
2630 return hex;
2632 return sha1_to_hex(sha1);
2635 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2637 int line_termination = opt->line_termination;
2638 int inter_name_termination = line_termination ? '\t' : '\0';
2640 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2641 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2642 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2643 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2645 if (p->score) {
2646 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2647 inter_name_termination);
2648 } else {
2649 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2652 if (p->status == DIFF_STATUS_COPIED ||
2653 p->status == DIFF_STATUS_RENAMED) {
2654 const char *name_a, *name_b;
2655 name_a = p->one->path;
2656 name_b = p->two->path;
2657 strip_prefix(opt->prefix_length, &name_a, &name_b);
2658 write_name_quoted(name_a, opt->file, inter_name_termination);
2659 write_name_quoted(name_b, opt->file, line_termination);
2660 } else {
2661 const char *name_a, *name_b;
2662 name_a = p->one->mode ? p->one->path : p->two->path;
2663 name_b = NULL;
2664 strip_prefix(opt->prefix_length, &name_a, &name_b);
2665 write_name_quoted(name_a, opt->file, line_termination);
2669 int diff_unmodified_pair(struct diff_filepair *p)
2671 /* This function is written stricter than necessary to support
2672 * the currently implemented transformers, but the idea is to
2673 * let transformers to produce diff_filepairs any way they want,
2674 * and filter and clean them up here before producing the output.
2676 struct diff_filespec *one = p->one, *two = p->two;
2678 if (DIFF_PAIR_UNMERGED(p))
2679 return 0; /* unmerged is interesting */
2681 /* deletion, addition, mode or type change
2682 * and rename are all interesting.
2684 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2685 DIFF_PAIR_MODE_CHANGED(p) ||
2686 strcmp(one->path, two->path))
2687 return 0;
2689 /* both are valid and point at the same path. that is, we are
2690 * dealing with a change.
2692 if (one->sha1_valid && two->sha1_valid &&
2693 !hashcmp(one->sha1, two->sha1))
2694 return 1; /* no change */
2695 if (!one->sha1_valid && !two->sha1_valid)
2696 return 1; /* both look at the same file on the filesystem. */
2697 return 0;
2700 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2702 if (diff_unmodified_pair(p))
2703 return;
2705 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2706 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2707 return; /* no tree diffs in patch format */
2709 run_diff(p, o);
2712 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2713 struct diffstat_t *diffstat)
2715 if (diff_unmodified_pair(p))
2716 return;
2718 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2719 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2720 return; /* no tree diffs in patch format */
2722 run_diffstat(p, o, diffstat);
2725 static void diff_flush_checkdiff(struct diff_filepair *p,
2726 struct diff_options *o)
2728 if (diff_unmodified_pair(p))
2729 return;
2731 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2732 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2733 return; /* no tree diffs in patch format */
2735 run_checkdiff(p, o);
2738 int diff_queue_is_empty(void)
2740 struct diff_queue_struct *q = &diff_queued_diff;
2741 int i;
2742 for (i = 0; i < q->nr; i++)
2743 if (!diff_unmodified_pair(q->queue[i]))
2744 return 0;
2745 return 1;
2748 #if DIFF_DEBUG
2749 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2751 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2752 x, one ? one : "",
2753 s->path,
2754 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2755 s->mode,
2756 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2757 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2758 x, one ? one : "",
2759 s->size, s->xfrm_flags);
2762 void diff_debug_filepair(const struct diff_filepair *p, int i)
2764 diff_debug_filespec(p->one, i, "one");
2765 diff_debug_filespec(p->two, i, "two");
2766 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2767 p->score, p->status ? p->status : '?',
2768 p->one->rename_used, p->broken_pair);
2771 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2773 int i;
2774 if (msg)
2775 fprintf(stderr, "%s\n", msg);
2776 fprintf(stderr, "q->nr = %d\n", q->nr);
2777 for (i = 0; i < q->nr; i++) {
2778 struct diff_filepair *p = q->queue[i];
2779 diff_debug_filepair(p, i);
2782 #endif
2784 static void diff_resolve_rename_copy(void)
2786 int i;
2787 struct diff_filepair *p;
2788 struct diff_queue_struct *q = &diff_queued_diff;
2790 diff_debug_queue("resolve-rename-copy", q);
2792 for (i = 0; i < q->nr; i++) {
2793 p = q->queue[i];
2794 p->status = 0; /* undecided */
2795 if (DIFF_PAIR_UNMERGED(p))
2796 p->status = DIFF_STATUS_UNMERGED;
2797 else if (!DIFF_FILE_VALID(p->one))
2798 p->status = DIFF_STATUS_ADDED;
2799 else if (!DIFF_FILE_VALID(p->two))
2800 p->status = DIFF_STATUS_DELETED;
2801 else if (DIFF_PAIR_TYPE_CHANGED(p))
2802 p->status = DIFF_STATUS_TYPE_CHANGED;
2804 /* from this point on, we are dealing with a pair
2805 * whose both sides are valid and of the same type, i.e.
2806 * either in-place edit or rename/copy edit.
2808 else if (DIFF_PAIR_RENAME(p)) {
2810 * A rename might have re-connected a broken
2811 * pair up, causing the pathnames to be the
2812 * same again. If so, that's not a rename at
2813 * all, just a modification..
2815 * Otherwise, see if this source was used for
2816 * multiple renames, in which case we decrement
2817 * the count, and call it a copy.
2819 if (!strcmp(p->one->path, p->two->path))
2820 p->status = DIFF_STATUS_MODIFIED;
2821 else if (--p->one->rename_used > 0)
2822 p->status = DIFF_STATUS_COPIED;
2823 else
2824 p->status = DIFF_STATUS_RENAMED;
2826 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2827 p->one->mode != p->two->mode ||
2828 is_null_sha1(p->one->sha1))
2829 p->status = DIFF_STATUS_MODIFIED;
2830 else {
2831 /* This is a "no-change" entry and should not
2832 * happen anymore, but prepare for broken callers.
2834 error("feeding unmodified %s to diffcore",
2835 p->one->path);
2836 p->status = DIFF_STATUS_UNKNOWN;
2839 diff_debug_queue("resolve-rename-copy done", q);
2842 static int check_pair_status(struct diff_filepair *p)
2844 switch (p->status) {
2845 case DIFF_STATUS_UNKNOWN:
2846 return 0;
2847 case 0:
2848 die("internal error in diff-resolve-rename-copy");
2849 default:
2850 return 1;
2854 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2856 int fmt = opt->output_format;
2858 if (fmt & DIFF_FORMAT_CHECKDIFF)
2859 diff_flush_checkdiff(p, opt);
2860 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2861 diff_flush_raw(p, opt);
2862 else if (fmt & DIFF_FORMAT_NAME) {
2863 const char *name_a, *name_b;
2864 name_a = p->two->path;
2865 name_b = NULL;
2866 strip_prefix(opt->prefix_length, &name_a, &name_b);
2867 write_name_quoted(name_a, opt->file, opt->line_termination);
2871 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
2873 if (fs->mode)
2874 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
2875 else
2876 fprintf(file, " %s ", newdelete);
2877 write_name_quoted(fs->path, file, '\n');
2881 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
2883 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2884 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
2885 show_name ? ' ' : '\n');
2886 if (show_name) {
2887 write_name_quoted(p->two->path, file, '\n');
2892 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
2894 char *names = pprint_rename(p->one->path, p->two->path);
2896 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2897 free(names);
2898 show_mode_change(file, p, 0);
2901 static void diff_summary(FILE *file, struct diff_filepair *p)
2903 switch(p->status) {
2904 case DIFF_STATUS_DELETED:
2905 show_file_mode_name(file, "delete", p->one);
2906 break;
2907 case DIFF_STATUS_ADDED:
2908 show_file_mode_name(file, "create", p->two);
2909 break;
2910 case DIFF_STATUS_COPIED:
2911 show_rename_copy(file, "copy", p);
2912 break;
2913 case DIFF_STATUS_RENAMED:
2914 show_rename_copy(file, "rename", p);
2915 break;
2916 default:
2917 if (p->score) {
2918 fputs(" rewrite ", file);
2919 write_name_quoted(p->two->path, file, ' ');
2920 fprintf(file, "(%d%%)\n", similarity_index(p));
2922 show_mode_change(file, p, !p->score);
2923 break;
2927 struct patch_id_t {
2928 git_SHA_CTX *ctx;
2929 int patchlen;
2932 static int remove_space(char *line, int len)
2934 int i;
2935 char *dst = line;
2936 unsigned char c;
2938 for (i = 0; i < len; i++)
2939 if (!isspace((c = line[i])))
2940 *dst++ = c;
2942 return dst - line;
2945 static void patch_id_consume(void *priv, char *line, unsigned long len)
2947 struct patch_id_t *data = priv;
2948 int new_len;
2950 /* Ignore line numbers when computing the SHA1 of the patch */
2951 if (!prefixcmp(line, "@@ -"))
2952 return;
2954 new_len = remove_space(line, len);
2956 git_SHA1_Update(data->ctx, line, new_len);
2957 data->patchlen += new_len;
2960 /* returns 0 upon success, and writes result into sha1 */
2961 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2963 struct diff_queue_struct *q = &diff_queued_diff;
2964 int i;
2965 git_SHA_CTX ctx;
2966 struct patch_id_t data;
2967 char buffer[PATH_MAX * 4 + 20];
2969 git_SHA1_Init(&ctx);
2970 memset(&data, 0, sizeof(struct patch_id_t));
2971 data.ctx = &ctx;
2973 for (i = 0; i < q->nr; i++) {
2974 xpparam_t xpp;
2975 xdemitconf_t xecfg;
2976 xdemitcb_t ecb;
2977 mmfile_t mf1, mf2;
2978 struct diff_filepair *p = q->queue[i];
2979 int len1, len2;
2981 memset(&xecfg, 0, sizeof(xecfg));
2982 if (p->status == 0)
2983 return error("internal diff status error");
2984 if (p->status == DIFF_STATUS_UNKNOWN)
2985 continue;
2986 if (diff_unmodified_pair(p))
2987 continue;
2988 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2989 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2990 continue;
2991 if (DIFF_PAIR_UNMERGED(p))
2992 continue;
2994 diff_fill_sha1_info(p->one);
2995 diff_fill_sha1_info(p->two);
2996 if (fill_mmfile(&mf1, p->one) < 0 ||
2997 fill_mmfile(&mf2, p->two) < 0)
2998 return error("unable to read files to diff");
3000 len1 = remove_space(p->one->path, strlen(p->one->path));
3001 len2 = remove_space(p->two->path, strlen(p->two->path));
3002 if (p->one->mode == 0)
3003 len1 = snprintf(buffer, sizeof(buffer),
3004 "diff--gita/%.*sb/%.*s"
3005 "newfilemode%06o"
3006 "---/dev/null"
3007 "+++b/%.*s",
3008 len1, p->one->path,
3009 len2, p->two->path,
3010 p->two->mode,
3011 len2, p->two->path);
3012 else if (p->two->mode == 0)
3013 len1 = snprintf(buffer, sizeof(buffer),
3014 "diff--gita/%.*sb/%.*s"
3015 "deletedfilemode%06o"
3016 "---a/%.*s"
3017 "+++/dev/null",
3018 len1, p->one->path,
3019 len2, p->two->path,
3020 p->one->mode,
3021 len1, p->one->path);
3022 else
3023 len1 = snprintf(buffer, sizeof(buffer),
3024 "diff--gita/%.*sb/%.*s"
3025 "---a/%.*s"
3026 "+++b/%.*s",
3027 len1, p->one->path,
3028 len2, p->two->path,
3029 len1, p->one->path,
3030 len2, p->two->path);
3031 git_SHA1_Update(&ctx, buffer, len1);
3033 xpp.flags = XDF_NEED_MINIMAL;
3034 xecfg.ctxlen = 3;
3035 xecfg.flags = XDL_EMIT_FUNCNAMES;
3036 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3037 &xpp, &xecfg, &ecb);
3040 git_SHA1_Final(sha1, &ctx);
3041 return 0;
3044 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3046 struct diff_queue_struct *q = &diff_queued_diff;
3047 int i;
3048 int result = diff_get_patch_id(options, sha1);
3050 for (i = 0; i < q->nr; i++)
3051 diff_free_filepair(q->queue[i]);
3053 free(q->queue);
3054 q->queue = NULL;
3055 q->nr = q->alloc = 0;
3057 return result;
3060 static int is_summary_empty(const struct diff_queue_struct *q)
3062 int i;
3064 for (i = 0; i < q->nr; i++) {
3065 const struct diff_filepair *p = q->queue[i];
3067 switch (p->status) {
3068 case DIFF_STATUS_DELETED:
3069 case DIFF_STATUS_ADDED:
3070 case DIFF_STATUS_COPIED:
3071 case DIFF_STATUS_RENAMED:
3072 return 0;
3073 default:
3074 if (p->score)
3075 return 0;
3076 if (p->one->mode && p->two->mode &&
3077 p->one->mode != p->two->mode)
3078 return 0;
3079 break;
3082 return 1;
3085 void diff_flush(struct diff_options *options)
3087 struct diff_queue_struct *q = &diff_queued_diff;
3088 int i, output_format = options->output_format;
3089 int separator = 0;
3092 * Order: raw, stat, summary, patch
3093 * or: name/name-status/checkdiff (other bits clear)
3095 if (!q->nr)
3096 goto free_queue;
3098 if (output_format & (DIFF_FORMAT_RAW |
3099 DIFF_FORMAT_NAME |
3100 DIFF_FORMAT_NAME_STATUS |
3101 DIFF_FORMAT_CHECKDIFF)) {
3102 for (i = 0; i < q->nr; i++) {
3103 struct diff_filepair *p = q->queue[i];
3104 if (check_pair_status(p))
3105 flush_one_pair(p, options);
3107 separator++;
3110 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3111 struct diffstat_t diffstat;
3113 memset(&diffstat, 0, sizeof(struct diffstat_t));
3114 for (i = 0; i < q->nr; i++) {
3115 struct diff_filepair *p = q->queue[i];
3116 if (check_pair_status(p))
3117 diff_flush_stat(p, options, &diffstat);
3119 if (output_format & DIFF_FORMAT_NUMSTAT)
3120 show_numstat(&diffstat, options);
3121 if (output_format & DIFF_FORMAT_DIFFSTAT)
3122 show_stats(&diffstat, options);
3123 if (output_format & DIFF_FORMAT_SHORTSTAT)
3124 show_shortstats(&diffstat, options);
3125 free_diffstat_info(&diffstat);
3126 separator++;
3128 if (output_format & DIFF_FORMAT_DIRSTAT)
3129 show_dirstat(options);
3131 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3132 for (i = 0; i < q->nr; i++)
3133 diff_summary(options->file, q->queue[i]);
3134 separator++;
3137 if (output_format & DIFF_FORMAT_PATCH) {
3138 if (separator) {
3139 putc(options->line_termination, options->file);
3140 if (options->stat_sep) {
3141 /* attach patch instead of inline */
3142 fputs(options->stat_sep, options->file);
3146 for (i = 0; i < q->nr; i++) {
3147 struct diff_filepair *p = q->queue[i];
3148 if (check_pair_status(p))
3149 diff_flush_patch(p, options);
3153 if (output_format & DIFF_FORMAT_CALLBACK)
3154 options->format_callback(q, options, options->format_callback_data);
3156 for (i = 0; i < q->nr; i++)
3157 diff_free_filepair(q->queue[i]);
3158 free_queue:
3159 free(q->queue);
3160 q->queue = NULL;
3161 q->nr = q->alloc = 0;
3162 if (options->close_file)
3163 fclose(options->file);
3166 static void diffcore_apply_filter(const char *filter)
3168 int i;
3169 struct diff_queue_struct *q = &diff_queued_diff;
3170 struct diff_queue_struct outq;
3171 outq.queue = NULL;
3172 outq.nr = outq.alloc = 0;
3174 if (!filter)
3175 return;
3177 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3178 int found;
3179 for (i = found = 0; !found && i < q->nr; i++) {
3180 struct diff_filepair *p = q->queue[i];
3181 if (((p->status == DIFF_STATUS_MODIFIED) &&
3182 ((p->score &&
3183 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3184 (!p->score &&
3185 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3186 ((p->status != DIFF_STATUS_MODIFIED) &&
3187 strchr(filter, p->status)))
3188 found++;
3190 if (found)
3191 return;
3193 /* otherwise we will clear the whole queue
3194 * by copying the empty outq at the end of this
3195 * function, but first clear the current entries
3196 * in the queue.
3198 for (i = 0; i < q->nr; i++)
3199 diff_free_filepair(q->queue[i]);
3201 else {
3202 /* Only the matching ones */
3203 for (i = 0; i < q->nr; i++) {
3204 struct diff_filepair *p = q->queue[i];
3206 if (((p->status == DIFF_STATUS_MODIFIED) &&
3207 ((p->score &&
3208 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3209 (!p->score &&
3210 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3211 ((p->status != DIFF_STATUS_MODIFIED) &&
3212 strchr(filter, p->status)))
3213 diff_q(&outq, p);
3214 else
3215 diff_free_filepair(p);
3218 free(q->queue);
3219 *q = outq;
3222 /* Check whether two filespecs with the same mode and size are identical */
3223 static int diff_filespec_is_identical(struct diff_filespec *one,
3224 struct diff_filespec *two)
3226 if (S_ISGITLINK(one->mode))
3227 return 0;
3228 if (diff_populate_filespec(one, 0))
3229 return 0;
3230 if (diff_populate_filespec(two, 0))
3231 return 0;
3232 return !memcmp(one->data, two->data, one->size);
3235 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3237 int i;
3238 struct diff_queue_struct *q = &diff_queued_diff;
3239 struct diff_queue_struct outq;
3240 outq.queue = NULL;
3241 outq.nr = outq.alloc = 0;
3243 for (i = 0; i < q->nr; i++) {
3244 struct diff_filepair *p = q->queue[i];
3247 * 1. Entries that come from stat info dirtyness
3248 * always have both sides (iow, not create/delete),
3249 * one side of the object name is unknown, with
3250 * the same mode and size. Keep the ones that
3251 * do not match these criteria. They have real
3252 * differences.
3254 * 2. At this point, the file is known to be modified,
3255 * with the same mode and size, and the object
3256 * name of one side is unknown. Need to inspect
3257 * the identical contents.
3259 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3260 !DIFF_FILE_VALID(p->two) ||
3261 (p->one->sha1_valid && p->two->sha1_valid) ||
3262 (p->one->mode != p->two->mode) ||
3263 diff_populate_filespec(p->one, 1) ||
3264 diff_populate_filespec(p->two, 1) ||
3265 (p->one->size != p->two->size) ||
3266 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3267 diff_q(&outq, p);
3268 else {
3270 * The caller can subtract 1 from skip_stat_unmatch
3271 * to determine how many paths were dirty only
3272 * due to stat info mismatch.
3274 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3275 diffopt->skip_stat_unmatch++;
3276 diff_free_filepair(p);
3279 free(q->queue);
3280 *q = outq;
3283 void diffcore_std(struct diff_options *options)
3285 if (options->skip_stat_unmatch)
3286 diffcore_skip_stat_unmatch(options);
3287 if (options->break_opt != -1)
3288 diffcore_break(options->break_opt);
3289 if (options->detect_rename)
3290 diffcore_rename(options);
3291 if (options->break_opt != -1)
3292 diffcore_merge_broken();
3293 if (options->pickaxe)
3294 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3295 if (options->orderfile)
3296 diffcore_order(options->orderfile);
3297 diff_resolve_rename_copy();
3298 diffcore_apply_filter(options->filter);
3300 if (diff_queued_diff.nr)
3301 DIFF_OPT_SET(options, HAS_CHANGES);
3302 else
3303 DIFF_OPT_CLR(options, HAS_CHANGES);
3306 int diff_result_code(struct diff_options *opt, int status)
3308 int result = 0;
3309 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3310 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3311 return status;
3312 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3313 DIFF_OPT_TST(opt, HAS_CHANGES))
3314 result |= 01;
3315 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3316 DIFF_OPT_TST(opt, CHECK_FAILED))
3317 result |= 02;
3318 return result;
3321 void diff_addremove(struct diff_options *options,
3322 int addremove, unsigned mode,
3323 const unsigned char *sha1,
3324 const char *concatpath)
3326 struct diff_filespec *one, *two;
3328 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3329 return;
3331 /* This may look odd, but it is a preparation for
3332 * feeding "there are unchanged files which should
3333 * not produce diffs, but when you are doing copy
3334 * detection you would need them, so here they are"
3335 * entries to the diff-core. They will be prefixed
3336 * with something like '=' or '*' (I haven't decided
3337 * which but should not make any difference).
3338 * Feeding the same new and old to diff_change()
3339 * also has the same effect.
3340 * Before the final output happens, they are pruned after
3341 * merged into rename/copy pairs as appropriate.
3343 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3344 addremove = (addremove == '+' ? '-' :
3345 addremove == '-' ? '+' : addremove);
3347 if (options->prefix &&
3348 strncmp(concatpath, options->prefix, options->prefix_length))
3349 return;
3351 one = alloc_filespec(concatpath);
3352 two = alloc_filespec(concatpath);
3354 if (addremove != '+')
3355 fill_filespec(one, sha1, mode);
3356 if (addremove != '-')
3357 fill_filespec(two, sha1, mode);
3359 diff_queue(&diff_queued_diff, one, two);
3360 DIFF_OPT_SET(options, HAS_CHANGES);
3363 void diff_change(struct diff_options *options,
3364 unsigned old_mode, unsigned new_mode,
3365 const unsigned char *old_sha1,
3366 const unsigned char *new_sha1,
3367 const char *concatpath)
3369 struct diff_filespec *one, *two;
3371 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3372 && S_ISGITLINK(new_mode))
3373 return;
3375 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3376 unsigned tmp;
3377 const unsigned char *tmp_c;
3378 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3379 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3382 if (options->prefix &&
3383 strncmp(concatpath, options->prefix, options->prefix_length))
3384 return;
3386 one = alloc_filespec(concatpath);
3387 two = alloc_filespec(concatpath);
3388 fill_filespec(one, old_sha1, old_mode);
3389 fill_filespec(two, new_sha1, new_mode);
3391 diff_queue(&diff_queued_diff, one, two);
3392 DIFF_OPT_SET(options, HAS_CHANGES);
3395 void diff_unmerge(struct diff_options *options,
3396 const char *path,
3397 unsigned mode, const unsigned char *sha1)
3399 struct diff_filespec *one, *two;
3401 if (options->prefix &&
3402 strncmp(path, options->prefix, options->prefix_length))
3403 return;
3405 one = alloc_filespec(path);
3406 two = alloc_filespec(path);
3407 fill_filespec(one, sha1, mode);
3408 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3411 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3412 size_t *outsize)
3414 struct diff_tempfile temp;
3415 const char *argv[3];
3416 const char **arg = argv;
3417 struct child_process child;
3418 struct strbuf buf = STRBUF_INIT;
3420 prepare_temp_file(spec->path, &temp, spec);
3421 *arg++ = pgm;
3422 *arg++ = temp.name;
3423 *arg = NULL;
3425 memset(&child, 0, sizeof(child));
3426 child.argv = argv;
3427 child.out = -1;
3428 if (start_command(&child) != 0 ||
3429 strbuf_read(&buf, child.out, 0) < 0 ||
3430 finish_command(&child) != 0) {
3431 if (temp.name == temp.tmp_path)
3432 unlink(temp.name);
3433 error("error running textconv command '%s'", pgm);
3434 return NULL;
3436 if (temp.name == temp.tmp_path)
3437 unlink(temp.name);
3439 return strbuf_detach(&buf, outsize);