status: show "-v" diff even for initial commit
[git/dscho.git] / diff.c
blob1918b73d5368d1ad89f501e63777e47763d0d0fe
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 switch (userdiff_config_porcelain(var, value)) {
97 case 0: break;
98 case -1: return -1;
99 default: return 0;
102 return git_diff_basic_config(var, value, cb);
105 int git_diff_basic_config(const char *var, const char *value, void *cb)
107 if (!strcmp(var, "diff.renamelimit")) {
108 diff_rename_limit_default = git_config_int(var, value);
109 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 switch (userdiff_config_basic(var, value)) {
127 case 0: break;
128 case -1: return -1;
129 default: return 0;
132 return git_color_default_config(var, value, cb);
135 static char *quote_two(const char *one, const char *two)
137 int need_one = quote_c_style(one, NULL, NULL, 1);
138 int need_two = quote_c_style(two, NULL, NULL, 1);
139 struct strbuf res = STRBUF_INIT;
141 if (need_one + need_two) {
142 strbuf_addch(&res, '"');
143 quote_c_style(one, &res, NULL, 1);
144 quote_c_style(two, &res, NULL, 1);
145 strbuf_addch(&res, '"');
146 } else {
147 strbuf_addstr(&res, one);
148 strbuf_addstr(&res, two);
150 return strbuf_detach(&res, NULL);
153 static const char *external_diff(void)
155 static const char *external_diff_cmd = NULL;
156 static int done_preparing = 0;
158 if (done_preparing)
159 return external_diff_cmd;
160 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
161 if (!external_diff_cmd)
162 external_diff_cmd = external_diff_cmd_cfg;
163 done_preparing = 1;
164 return external_diff_cmd;
167 static struct diff_tempfile {
168 const char *name; /* filename external diff should read from */
169 char hex[41];
170 char mode[10];
171 char tmp_path[PATH_MAX];
172 } diff_temp[2];
174 static int count_lines(const char *data, int size)
176 int count, ch, completely_empty = 1, nl_just_seen = 0;
177 count = 0;
178 while (0 < size--) {
179 ch = *data++;
180 if (ch == '\n') {
181 count++;
182 nl_just_seen = 1;
183 completely_empty = 0;
185 else {
186 nl_just_seen = 0;
187 completely_empty = 0;
190 if (completely_empty)
191 return 0;
192 if (!nl_just_seen)
193 count++; /* no trailing newline */
194 return count;
197 static void print_line_count(FILE *file, int count)
199 switch (count) {
200 case 0:
201 fprintf(file, "0,0");
202 break;
203 case 1:
204 fprintf(file, "1");
205 break;
206 default:
207 fprintf(file, "1,%d", count);
208 break;
212 static void copy_file_with_prefix(FILE *file,
213 int prefix, const char *data, int size,
214 const char *set, const char *reset)
216 int ch, nl_just_seen = 1;
217 while (0 < size--) {
218 ch = *data++;
219 if (nl_just_seen) {
220 fputs(set, file);
221 putc(prefix, file);
223 if (ch == '\n') {
224 nl_just_seen = 1;
225 fputs(reset, file);
226 } else
227 nl_just_seen = 0;
228 putc(ch, file);
230 if (!nl_just_seen)
231 fprintf(file, "%s\n\\ No newline at end of file\n", reset);
234 static void emit_rewrite_diff(const char *name_a,
235 const char *name_b,
236 struct diff_filespec *one,
237 struct diff_filespec *two,
238 struct diff_options *o)
240 int lc_a, lc_b;
241 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
242 const char *name_a_tab, *name_b_tab;
243 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
244 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
245 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
246 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
247 const char *reset = diff_get_color(color_diff, DIFF_RESET);
248 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
249 const char *a_prefix, *b_prefix;
251 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
252 a_prefix = o->b_prefix;
253 b_prefix = o->a_prefix;
254 } else {
255 a_prefix = o->a_prefix;
256 b_prefix = o->b_prefix;
259 name_a += (*name_a == '/');
260 name_b += (*name_b == '/');
261 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
262 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
264 strbuf_reset(&a_name);
265 strbuf_reset(&b_name);
266 quote_two_c_style(&a_name, a_prefix, name_a, 0);
267 quote_two_c_style(&b_name, b_prefix, name_b, 0);
269 diff_populate_filespec(one, 0);
270 diff_populate_filespec(two, 0);
271 lc_a = count_lines(one->data, one->size);
272 lc_b = count_lines(two->data, two->size);
273 fprintf(o->file,
274 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
275 metainfo, a_name.buf, name_a_tab, reset,
276 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
277 print_line_count(o->file, lc_a);
278 fprintf(o->file, " +");
279 print_line_count(o->file, lc_b);
280 fprintf(o->file, " @@%s\n", reset);
281 if (lc_a)
282 copy_file_with_prefix(o->file, '-', one->data, one->size, old, reset);
283 if (lc_b)
284 copy_file_with_prefix(o->file, '+', two->data, two->size, new, reset);
287 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
289 if (!DIFF_FILE_VALID(one)) {
290 mf->ptr = (char *)""; /* does not matter */
291 mf->size = 0;
292 return 0;
294 else if (diff_populate_filespec(one, 0))
295 return -1;
297 diff_filespec_load_driver(one);
298 if (one->driver->textconv) {
299 size_t size;
300 mf->ptr = run_textconv(one->driver->textconv, one, &size);
301 if (!mf->ptr)
302 return -1;
303 mf->size = size;
305 else {
306 mf->ptr = one->data;
307 mf->size = one->size;
309 return 0;
312 struct diff_words_buffer {
313 mmfile_t text;
314 long alloc;
315 long current; /* output pointer */
316 int suppressed_newline;
319 static void diff_words_append(char *line, unsigned long len,
320 struct diff_words_buffer *buffer)
322 if (buffer->text.size + len > buffer->alloc) {
323 buffer->alloc = (buffer->text.size + len) * 3 / 2;
324 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
326 line++;
327 len--;
328 memcpy(buffer->text.ptr + buffer->text.size, line, len);
329 buffer->text.size += len;
332 struct diff_words_data {
333 struct diff_words_buffer minus, plus;
334 FILE *file;
337 static void print_word(FILE *file, struct diff_words_buffer *buffer, int len, int color,
338 int suppress_newline)
340 const char *ptr;
341 int eol = 0;
343 if (len == 0)
344 return;
346 ptr = buffer->text.ptr + buffer->current;
347 buffer->current += len;
349 if (ptr[len - 1] == '\n') {
350 eol = 1;
351 len--;
354 fputs(diff_get_color(1, color), file);
355 fwrite(ptr, len, 1, file);
356 fputs(diff_get_color(1, DIFF_RESET), file);
358 if (eol) {
359 if (suppress_newline)
360 buffer->suppressed_newline = 1;
361 else
362 putc('\n', file);
366 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
368 struct diff_words_data *diff_words = priv;
370 if (diff_words->minus.suppressed_newline) {
371 if (line[0] != '+')
372 putc('\n', diff_words->file);
373 diff_words->minus.suppressed_newline = 0;
376 len--;
377 switch (line[0]) {
378 case '-':
379 print_word(diff_words->file,
380 &diff_words->minus, len, DIFF_FILE_OLD, 1);
381 break;
382 case '+':
383 print_word(diff_words->file,
384 &diff_words->plus, len, DIFF_FILE_NEW, 0);
385 break;
386 case ' ':
387 print_word(diff_words->file,
388 &diff_words->plus, len, DIFF_PLAIN, 0);
389 diff_words->minus.current += len;
390 break;
394 /* this executes the word diff on the accumulated buffers */
395 static void diff_words_show(struct diff_words_data *diff_words)
397 xpparam_t xpp;
398 xdemitconf_t xecfg;
399 xdemitcb_t ecb;
400 mmfile_t minus, plus;
401 int i;
403 memset(&xpp, 0, sizeof(xpp));
404 memset(&xecfg, 0, sizeof(xecfg));
405 minus.size = diff_words->minus.text.size;
406 minus.ptr = xmalloc(minus.size);
407 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
408 for (i = 0; i < minus.size; i++)
409 if (isspace(minus.ptr[i]))
410 minus.ptr[i] = '\n';
411 diff_words->minus.current = 0;
413 plus.size = diff_words->plus.text.size;
414 plus.ptr = xmalloc(plus.size);
415 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
416 for (i = 0; i < plus.size; i++)
417 if (isspace(plus.ptr[i]))
418 plus.ptr[i] = '\n';
419 diff_words->plus.current = 0;
421 xpp.flags = XDF_NEED_MINIMAL;
422 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
423 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
424 &xpp, &xecfg, &ecb);
425 free(minus.ptr);
426 free(plus.ptr);
427 diff_words->minus.text.size = diff_words->plus.text.size = 0;
429 if (diff_words->minus.suppressed_newline) {
430 putc('\n', diff_words->file);
431 diff_words->minus.suppressed_newline = 0;
435 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
437 struct emit_callback {
438 int nparents, color_diff;
439 unsigned ws_rule;
440 sane_truncate_fn truncate;
441 const char **label_path;
442 struct diff_words_data *diff_words;
443 int *found_changesp;
444 FILE *file;
447 static void free_diff_words_data(struct emit_callback *ecbdata)
449 if (ecbdata->diff_words) {
450 /* flush buffers */
451 if (ecbdata->diff_words->minus.text.size ||
452 ecbdata->diff_words->plus.text.size)
453 diff_words_show(ecbdata->diff_words);
455 free (ecbdata->diff_words->minus.text.ptr);
456 free (ecbdata->diff_words->plus.text.ptr);
457 free(ecbdata->diff_words);
458 ecbdata->diff_words = NULL;
462 const char *diff_get_color(int diff_use_color, enum color_diff ix)
464 if (diff_use_color)
465 return diff_colors[ix];
466 return "";
469 static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
471 int has_trailing_newline, has_trailing_carriage_return;
473 has_trailing_newline = (len > 0 && line[len-1] == '\n');
474 if (has_trailing_newline)
475 len--;
476 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
477 if (has_trailing_carriage_return)
478 len--;
480 fputs(set, file);
481 fwrite(line, len, 1, file);
482 fputs(reset, file);
483 if (has_trailing_carriage_return)
484 fputc('\r', file);
485 if (has_trailing_newline)
486 fputc('\n', file);
489 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
491 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
492 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
494 if (!*ws)
495 emit_line(ecbdata->file, set, reset, line, len);
496 else {
497 /* Emit just the prefix, then the rest. */
498 emit_line(ecbdata->file, set, reset, line, ecbdata->nparents);
499 ws_check_emit(line + ecbdata->nparents,
500 len - ecbdata->nparents, ecbdata->ws_rule,
501 ecbdata->file, set, reset, ws);
505 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
507 const char *cp;
508 unsigned long allot;
509 size_t l = len;
511 if (ecb->truncate)
512 return ecb->truncate(line, len);
513 cp = line;
514 allot = l;
515 while (0 < l) {
516 (void) utf8_width(&cp, &l);
517 if (!cp)
518 break; /* truncated in the middle? */
520 return allot - l;
523 static void fn_out_consume(void *priv, char *line, unsigned long len)
525 int i;
526 int color;
527 struct emit_callback *ecbdata = priv;
528 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
529 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
530 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
532 *(ecbdata->found_changesp) = 1;
534 if (ecbdata->label_path[0]) {
535 const char *name_a_tab, *name_b_tab;
537 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
538 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
540 fprintf(ecbdata->file, "%s--- %s%s%s\n",
541 meta, ecbdata->label_path[0], reset, name_a_tab);
542 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
543 meta, ecbdata->label_path[1], reset, name_b_tab);
544 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
547 if (diff_suppress_blank_empty
548 && len == 2 && line[0] == ' ' && line[1] == '\n') {
549 line[0] = '\n';
550 len = 1;
553 /* This is not really necessary for now because
554 * this codepath only deals with two-way diffs.
556 for (i = 0; i < len && line[i] == '@'; i++)
558 if (2 <= i && i < len && line[i] == ' ') {
559 ecbdata->nparents = i - 1;
560 len = sane_truncate_line(ecbdata, line, len);
561 emit_line(ecbdata->file,
562 diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
563 reset, line, len);
564 if (line[len-1] != '\n')
565 putc('\n', ecbdata->file);
566 return;
569 if (len < ecbdata->nparents) {
570 emit_line(ecbdata->file, reset, reset, line, len);
571 return;
574 color = DIFF_PLAIN;
575 if (ecbdata->diff_words && ecbdata->nparents != 1)
576 /* fall back to normal diff */
577 free_diff_words_data(ecbdata);
578 if (ecbdata->diff_words) {
579 if (line[0] == '-') {
580 diff_words_append(line, len,
581 &ecbdata->diff_words->minus);
582 return;
583 } else if (line[0] == '+') {
584 diff_words_append(line, len,
585 &ecbdata->diff_words->plus);
586 return;
588 if (ecbdata->diff_words->minus.text.size ||
589 ecbdata->diff_words->plus.text.size)
590 diff_words_show(ecbdata->diff_words);
591 line++;
592 len--;
593 emit_line(ecbdata->file, plain, reset, line, len);
594 return;
596 for (i = 0; i < ecbdata->nparents && len; i++) {
597 if (line[i] == '-')
598 color = DIFF_FILE_OLD;
599 else if (line[i] == '+')
600 color = DIFF_FILE_NEW;
603 if (color != DIFF_FILE_NEW) {
604 emit_line(ecbdata->file,
605 diff_get_color(ecbdata->color_diff, color),
606 reset, line, len);
607 return;
609 emit_add_line(reset, ecbdata, line, len);
612 static char *pprint_rename(const char *a, const char *b)
614 const char *old = a;
615 const char *new = b;
616 struct strbuf name = STRBUF_INIT;
617 int pfx_length, sfx_length;
618 int len_a = strlen(a);
619 int len_b = strlen(b);
620 int a_midlen, b_midlen;
621 int qlen_a = quote_c_style(a, NULL, NULL, 0);
622 int qlen_b = quote_c_style(b, NULL, NULL, 0);
624 if (qlen_a || qlen_b) {
625 quote_c_style(a, &name, NULL, 0);
626 strbuf_addstr(&name, " => ");
627 quote_c_style(b, &name, NULL, 0);
628 return strbuf_detach(&name, NULL);
631 /* Find common prefix */
632 pfx_length = 0;
633 while (*old && *new && *old == *new) {
634 if (*old == '/')
635 pfx_length = old - a + 1;
636 old++;
637 new++;
640 /* Find common suffix */
641 old = a + len_a;
642 new = b + len_b;
643 sfx_length = 0;
644 while (a <= old && b <= new && *old == *new) {
645 if (*old == '/')
646 sfx_length = len_a - (old - a);
647 old--;
648 new--;
652 * pfx{mid-a => mid-b}sfx
653 * {pfx-a => pfx-b}sfx
654 * pfx{sfx-a => sfx-b}
655 * name-a => name-b
657 a_midlen = len_a - pfx_length - sfx_length;
658 b_midlen = len_b - pfx_length - sfx_length;
659 if (a_midlen < 0)
660 a_midlen = 0;
661 if (b_midlen < 0)
662 b_midlen = 0;
664 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
665 if (pfx_length + sfx_length) {
666 strbuf_add(&name, a, pfx_length);
667 strbuf_addch(&name, '{');
669 strbuf_add(&name, a + pfx_length, a_midlen);
670 strbuf_addstr(&name, " => ");
671 strbuf_add(&name, b + pfx_length, b_midlen);
672 if (pfx_length + sfx_length) {
673 strbuf_addch(&name, '}');
674 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
676 return strbuf_detach(&name, NULL);
679 struct diffstat_t {
680 int nr;
681 int alloc;
682 struct diffstat_file {
683 char *from_name;
684 char *name;
685 char *print_name;
686 unsigned is_unmerged:1;
687 unsigned is_binary:1;
688 unsigned is_renamed:1;
689 unsigned int added, deleted;
690 } **files;
693 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
694 const char *name_a,
695 const char *name_b)
697 struct diffstat_file *x;
698 x = xcalloc(sizeof (*x), 1);
699 if (diffstat->nr == diffstat->alloc) {
700 diffstat->alloc = alloc_nr(diffstat->alloc);
701 diffstat->files = xrealloc(diffstat->files,
702 diffstat->alloc * sizeof(x));
704 diffstat->files[diffstat->nr++] = x;
705 if (name_b) {
706 x->from_name = xstrdup(name_a);
707 x->name = xstrdup(name_b);
708 x->is_renamed = 1;
710 else {
711 x->from_name = NULL;
712 x->name = xstrdup(name_a);
714 return x;
717 static void diffstat_consume(void *priv, char *line, unsigned long len)
719 struct diffstat_t *diffstat = priv;
720 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
722 if (line[0] == '+')
723 x->added++;
724 else if (line[0] == '-')
725 x->deleted++;
728 const char mime_boundary_leader[] = "------------";
730 static int scale_linear(int it, int width, int max_change)
733 * make sure that at least one '-' is printed if there were deletions,
734 * and likewise for '+'.
736 if (max_change < 2)
737 return it;
738 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
741 static void show_name(FILE *file,
742 const char *prefix, const char *name, int len,
743 const char *reset, const char *set)
745 fprintf(file, " %s%s%-*s%s |", set, prefix, len, name, reset);
748 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
750 if (cnt <= 0)
751 return;
752 fprintf(file, "%s", set);
753 while (cnt--)
754 putc(ch, file);
755 fprintf(file, "%s", reset);
758 static void fill_print_name(struct diffstat_file *file)
760 char *pname;
762 if (file->print_name)
763 return;
765 if (!file->is_renamed) {
766 struct strbuf buf = STRBUF_INIT;
767 if (quote_c_style(file->name, &buf, NULL, 0)) {
768 pname = strbuf_detach(&buf, NULL);
769 } else {
770 pname = file->name;
771 strbuf_release(&buf);
773 } else {
774 pname = pprint_rename(file->from_name, file->name);
776 file->print_name = pname;
779 static void show_stats(struct diffstat_t* data, struct diff_options *options)
781 int i, len, add, del, total, adds = 0, dels = 0;
782 int max_change = 0, max_len = 0;
783 int total_files = data->nr;
784 int width, name_width;
785 const char *reset, *set, *add_c, *del_c;
787 if (data->nr == 0)
788 return;
790 width = options->stat_width ? options->stat_width : 80;
791 name_width = options->stat_name_width ? options->stat_name_width : 50;
793 /* Sanity: give at least 5 columns to the graph,
794 * but leave at least 10 columns for the name.
796 if (width < 25)
797 width = 25;
798 if (name_width < 10)
799 name_width = 10;
800 else if (width < name_width + 15)
801 name_width = width - 15;
803 /* Find the longest filename and max number of changes */
804 reset = diff_get_color_opt(options, DIFF_RESET);
805 set = diff_get_color_opt(options, DIFF_PLAIN);
806 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
807 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
809 for (i = 0; i < data->nr; i++) {
810 struct diffstat_file *file = data->files[i];
811 int change = file->added + file->deleted;
812 fill_print_name(file);
813 len = strlen(file->print_name);
814 if (max_len < len)
815 max_len = len;
817 if (file->is_binary || file->is_unmerged)
818 continue;
819 if (max_change < change)
820 max_change = change;
823 /* Compute the width of the graph part;
824 * 10 is for one blank at the beginning of the line plus
825 * " | count " between the name and the graph.
827 * From here on, name_width is the width of the name area,
828 * and width is the width of the graph area.
830 name_width = (name_width < max_len) ? name_width : max_len;
831 if (width < (name_width + 10) + max_change)
832 width = width - (name_width + 10);
833 else
834 width = max_change;
836 for (i = 0; i < data->nr; i++) {
837 const char *prefix = "";
838 char *name = data->files[i]->print_name;
839 int added = data->files[i]->added;
840 int deleted = data->files[i]->deleted;
841 int name_len;
844 * "scale" the filename
846 len = name_width;
847 name_len = strlen(name);
848 if (name_width < name_len) {
849 char *slash;
850 prefix = "...";
851 len -= 3;
852 name += name_len - len;
853 slash = strchr(name, '/');
854 if (slash)
855 name = slash;
858 if (data->files[i]->is_binary) {
859 show_name(options->file, prefix, name, len, reset, set);
860 fprintf(options->file, " Bin ");
861 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
862 fprintf(options->file, " -> ");
863 fprintf(options->file, "%s%d%s", add_c, added, reset);
864 fprintf(options->file, " bytes");
865 fprintf(options->file, "\n");
866 continue;
868 else if (data->files[i]->is_unmerged) {
869 show_name(options->file, prefix, name, len, reset, set);
870 fprintf(options->file, " Unmerged\n");
871 continue;
873 else if (!data->files[i]->is_renamed &&
874 (added + deleted == 0)) {
875 total_files--;
876 continue;
880 * scale the add/delete
882 add = added;
883 del = deleted;
884 total = add + del;
885 adds += add;
886 dels += del;
888 if (width <= max_change) {
889 add = scale_linear(add, width, max_change);
890 del = scale_linear(del, width, max_change);
891 total = add + del;
893 show_name(options->file, prefix, name, len, reset, set);
894 fprintf(options->file, "%5d%s", added + deleted,
895 added + deleted ? " " : "");
896 show_graph(options->file, '+', add, add_c, reset);
897 show_graph(options->file, '-', del, del_c, reset);
898 fprintf(options->file, "\n");
900 fprintf(options->file,
901 "%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
902 set, total_files, adds, dels, reset);
905 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
907 int i, adds = 0, dels = 0, total_files = data->nr;
909 if (data->nr == 0)
910 return;
912 for (i = 0; i < data->nr; i++) {
913 if (!data->files[i]->is_binary &&
914 !data->files[i]->is_unmerged) {
915 int added = data->files[i]->added;
916 int deleted= data->files[i]->deleted;
917 if (!data->files[i]->is_renamed &&
918 (added + deleted == 0)) {
919 total_files--;
920 } else {
921 adds += added;
922 dels += deleted;
926 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
927 total_files, adds, dels);
930 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
932 int i;
934 if (data->nr == 0)
935 return;
937 for (i = 0; i < data->nr; i++) {
938 struct diffstat_file *file = data->files[i];
940 if (file->is_binary)
941 fprintf(options->file, "-\t-\t");
942 else
943 fprintf(options->file,
944 "%d\t%d\t", file->added, file->deleted);
945 if (options->line_termination) {
946 fill_print_name(file);
947 if (!file->is_renamed)
948 write_name_quoted(file->name, options->file,
949 options->line_termination);
950 else {
951 fputs(file->print_name, options->file);
952 putc(options->line_termination, options->file);
954 } else {
955 if (file->is_renamed) {
956 putc('\0', options->file);
957 write_name_quoted(file->from_name, options->file, '\0');
959 write_name_quoted(file->name, options->file, '\0');
964 struct dirstat_file {
965 const char *name;
966 unsigned long changed;
969 struct dirstat_dir {
970 struct dirstat_file *files;
971 int alloc, nr, percent, cumulative;
974 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
976 unsigned long this_dir = 0;
977 unsigned int sources = 0;
979 while (dir->nr) {
980 struct dirstat_file *f = dir->files;
981 int namelen = strlen(f->name);
982 unsigned long this;
983 char *slash;
985 if (namelen < baselen)
986 break;
987 if (memcmp(f->name, base, baselen))
988 break;
989 slash = strchr(f->name + baselen, '/');
990 if (slash) {
991 int newbaselen = slash + 1 - f->name;
992 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
993 sources++;
994 } else {
995 this = f->changed;
996 dir->files++;
997 dir->nr--;
998 sources += 2;
1000 this_dir += this;
1004 * We don't report dirstat's for
1005 * - the top level
1006 * - or cases where everything came from a single directory
1007 * under this directory (sources == 1).
1009 if (baselen && sources != 1) {
1010 int permille = this_dir * 1000 / changed;
1011 if (permille) {
1012 int percent = permille / 10;
1013 if (percent >= dir->percent) {
1014 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1015 if (!dir->cumulative)
1016 return 0;
1020 return this_dir;
1023 static int dirstat_compare(const void *_a, const void *_b)
1025 const struct dirstat_file *a = _a;
1026 const struct dirstat_file *b = _b;
1027 return strcmp(a->name, b->name);
1030 static void show_dirstat(struct diff_options *options)
1032 int i;
1033 unsigned long changed;
1034 struct dirstat_dir dir;
1035 struct diff_queue_struct *q = &diff_queued_diff;
1037 dir.files = NULL;
1038 dir.alloc = 0;
1039 dir.nr = 0;
1040 dir.percent = options->dirstat_percent;
1041 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1043 changed = 0;
1044 for (i = 0; i < q->nr; i++) {
1045 struct diff_filepair *p = q->queue[i];
1046 const char *name;
1047 unsigned long copied, added, damage;
1049 name = p->one->path ? p->one->path : p->two->path;
1051 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1052 diff_populate_filespec(p->one, 0);
1053 diff_populate_filespec(p->two, 0);
1054 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1055 &copied, &added);
1056 diff_free_filespec_data(p->one);
1057 diff_free_filespec_data(p->two);
1058 } else if (DIFF_FILE_VALID(p->one)) {
1059 diff_populate_filespec(p->one, 1);
1060 copied = added = 0;
1061 diff_free_filespec_data(p->one);
1062 } else if (DIFF_FILE_VALID(p->two)) {
1063 diff_populate_filespec(p->two, 1);
1064 copied = 0;
1065 added = p->two->size;
1066 diff_free_filespec_data(p->two);
1067 } else
1068 continue;
1071 * Original minus copied is the removed material,
1072 * added is the new material. They are both damages
1073 * made to the preimage. In --dirstat-by-file mode, count
1074 * damaged files, not damaged lines. This is done by
1075 * counting only a single damaged line per file.
1077 damage = (p->one->size - copied) + added;
1078 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1079 damage = 1;
1081 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1082 dir.files[dir.nr].name = name;
1083 dir.files[dir.nr].changed = damage;
1084 changed += damage;
1085 dir.nr++;
1088 /* This can happen even with many files, if everything was renames */
1089 if (!changed)
1090 return;
1092 /* Show all directories with more than x% of the changes */
1093 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1094 gather_dirstat(options->file, &dir, changed, "", 0);
1097 static void free_diffstat_info(struct diffstat_t *diffstat)
1099 int i;
1100 for (i = 0; i < diffstat->nr; i++) {
1101 struct diffstat_file *f = diffstat->files[i];
1102 if (f->name != f->print_name)
1103 free(f->print_name);
1104 free(f->name);
1105 free(f->from_name);
1106 free(f);
1108 free(diffstat->files);
1111 struct checkdiff_t {
1112 const char *filename;
1113 int lineno;
1114 struct diff_options *o;
1115 unsigned ws_rule;
1116 unsigned status;
1117 int trailing_blanks_start;
1120 static int is_conflict_marker(const char *line, unsigned long len)
1122 char firstchar;
1123 int cnt;
1125 if (len < 8)
1126 return 0;
1127 firstchar = line[0];
1128 switch (firstchar) {
1129 case '=': case '>': case '<':
1130 break;
1131 default:
1132 return 0;
1134 for (cnt = 1; cnt < 7; cnt++)
1135 if (line[cnt] != firstchar)
1136 return 0;
1137 /* line[0] thru line[6] are same as firstchar */
1138 if (firstchar == '=') {
1139 /* divider between ours and theirs? */
1140 if (len != 8 || line[7] != '\n')
1141 return 0;
1142 } else if (len < 8 || !isspace(line[7])) {
1143 /* not divider before ours nor after theirs */
1144 return 0;
1146 return 1;
1149 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1151 struct checkdiff_t *data = priv;
1152 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1153 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1154 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1155 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1156 char *err;
1158 if (line[0] == '+') {
1159 unsigned bad;
1160 data->lineno++;
1161 if (!ws_blank_line(line + 1, len - 1, data->ws_rule))
1162 data->trailing_blanks_start = 0;
1163 else if (!data->trailing_blanks_start)
1164 data->trailing_blanks_start = data->lineno;
1165 if (is_conflict_marker(line + 1, len - 1)) {
1166 data->status |= 1;
1167 fprintf(data->o->file,
1168 "%s:%d: leftover conflict marker\n",
1169 data->filename, data->lineno);
1171 bad = ws_check(line + 1, len - 1, data->ws_rule);
1172 if (!bad)
1173 return;
1174 data->status |= bad;
1175 err = whitespace_error_string(bad);
1176 fprintf(data->o->file, "%s:%d: %s.\n",
1177 data->filename, data->lineno, err);
1178 free(err);
1179 emit_line(data->o->file, set, reset, line, 1);
1180 ws_check_emit(line + 1, len - 1, data->ws_rule,
1181 data->o->file, set, reset, ws);
1182 } else if (line[0] == ' ') {
1183 data->lineno++;
1184 data->trailing_blanks_start = 0;
1185 } else if (line[0] == '@') {
1186 char *plus = strchr(line, '+');
1187 if (plus)
1188 data->lineno = strtol(plus, NULL, 10) - 1;
1189 else
1190 die("invalid diff");
1191 data->trailing_blanks_start = 0;
1195 static unsigned char *deflate_it(char *data,
1196 unsigned long size,
1197 unsigned long *result_size)
1199 int bound;
1200 unsigned char *deflated;
1201 z_stream stream;
1203 memset(&stream, 0, sizeof(stream));
1204 deflateInit(&stream, zlib_compression_level);
1205 bound = deflateBound(&stream, size);
1206 deflated = xmalloc(bound);
1207 stream.next_out = deflated;
1208 stream.avail_out = bound;
1210 stream.next_in = (unsigned char *)data;
1211 stream.avail_in = size;
1212 while (deflate(&stream, Z_FINISH) == Z_OK)
1213 ; /* nothing */
1214 deflateEnd(&stream);
1215 *result_size = stream.total_out;
1216 return deflated;
1219 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1221 void *cp;
1222 void *delta;
1223 void *deflated;
1224 void *data;
1225 unsigned long orig_size;
1226 unsigned long delta_size;
1227 unsigned long deflate_size;
1228 unsigned long data_size;
1230 /* We could do deflated delta, or we could do just deflated two,
1231 * whichever is smaller.
1233 delta = NULL;
1234 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1235 if (one->size && two->size) {
1236 delta = diff_delta(one->ptr, one->size,
1237 two->ptr, two->size,
1238 &delta_size, deflate_size);
1239 if (delta) {
1240 void *to_free = delta;
1241 orig_size = delta_size;
1242 delta = deflate_it(delta, delta_size, &delta_size);
1243 free(to_free);
1247 if (delta && delta_size < deflate_size) {
1248 fprintf(file, "delta %lu\n", orig_size);
1249 free(deflated);
1250 data = delta;
1251 data_size = delta_size;
1253 else {
1254 fprintf(file, "literal %lu\n", two->size);
1255 free(delta);
1256 data = deflated;
1257 data_size = deflate_size;
1260 /* emit data encoded in base85 */
1261 cp = data;
1262 while (data_size) {
1263 int bytes = (52 < data_size) ? 52 : data_size;
1264 char line[70];
1265 data_size -= bytes;
1266 if (bytes <= 26)
1267 line[0] = bytes + 'A' - 1;
1268 else
1269 line[0] = bytes - 26 + 'a' - 1;
1270 encode_85(line + 1, cp, bytes);
1271 cp = (char *) cp + bytes;
1272 fputs(line, file);
1273 fputc('\n', file);
1275 fprintf(file, "\n");
1276 free(data);
1279 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1281 fprintf(file, "GIT binary patch\n");
1282 emit_binary_diff_body(file, one, two);
1283 emit_binary_diff_body(file, two, one);
1286 void diff_filespec_load_driver(struct diff_filespec *one)
1288 if (!one->driver)
1289 one->driver = userdiff_find_by_path(one->path);
1290 if (!one->driver)
1291 one->driver = userdiff_find_by_name("default");
1294 int diff_filespec_is_binary(struct diff_filespec *one)
1296 if (one->is_binary == -1) {
1297 diff_filespec_load_driver(one);
1298 if (one->driver->binary != -1)
1299 one->is_binary = one->driver->binary;
1300 else {
1301 if (!one->data && DIFF_FILE_VALID(one))
1302 diff_populate_filespec(one, 0);
1303 if (one->data)
1304 one->is_binary = buffer_is_binary(one->data,
1305 one->size);
1306 if (one->is_binary == -1)
1307 one->is_binary = 0;
1310 return one->is_binary;
1313 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1315 diff_filespec_load_driver(one);
1316 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1319 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1321 if (!options->a_prefix)
1322 options->a_prefix = a;
1323 if (!options->b_prefix)
1324 options->b_prefix = b;
1327 static void builtin_diff(const char *name_a,
1328 const char *name_b,
1329 struct diff_filespec *one,
1330 struct diff_filespec *two,
1331 const char *xfrm_msg,
1332 struct diff_options *o,
1333 int complete_rewrite)
1335 mmfile_t mf1, mf2;
1336 const char *lbl[2];
1337 char *a_one, *b_two;
1338 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1339 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1340 const char *a_prefix, *b_prefix;
1342 diff_set_mnemonic_prefix(o, "a/", "b/");
1343 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1344 a_prefix = o->b_prefix;
1345 b_prefix = o->a_prefix;
1346 } else {
1347 a_prefix = o->a_prefix;
1348 b_prefix = o->b_prefix;
1351 /* Never use a non-valid filename anywhere if at all possible */
1352 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1353 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1355 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1356 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1357 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1358 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1359 fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1360 if (lbl[0][0] == '/') {
1361 /* /dev/null */
1362 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1363 if (xfrm_msg && xfrm_msg[0])
1364 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1366 else if (lbl[1][0] == '/') {
1367 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1368 if (xfrm_msg && xfrm_msg[0])
1369 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1371 else {
1372 if (one->mode != two->mode) {
1373 fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1374 fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1376 if (xfrm_msg && xfrm_msg[0])
1377 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1379 * we do not run diff between different kind
1380 * of objects.
1382 if ((one->mode ^ two->mode) & S_IFMT)
1383 goto free_ab_and_return;
1384 if (complete_rewrite) {
1385 emit_rewrite_diff(name_a, name_b, one, two, o);
1386 o->found_changes = 1;
1387 goto free_ab_and_return;
1391 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1392 die("unable to read files to diff");
1394 if (!DIFF_OPT_TST(o, TEXT) &&
1395 (diff_filespec_is_binary(one) || diff_filespec_is_binary(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 pe = diff_funcname_pattern(one);
1417 if (!pe)
1418 pe = diff_funcname_pattern(two);
1420 memset(&xpp, 0, sizeof(xpp));
1421 memset(&xecfg, 0, sizeof(xecfg));
1422 memset(&ecbdata, 0, sizeof(ecbdata));
1423 ecbdata.label_path = lbl;
1424 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1425 ecbdata.found_changesp = &o->found_changes;
1426 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1427 ecbdata.file = o->file;
1428 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1429 xecfg.ctxlen = o->context;
1430 xecfg.flags = XDL_EMIT_FUNCNAMES;
1431 if (pe)
1432 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1433 if (!diffopts)
1435 else if (!prefixcmp(diffopts, "--unified="))
1436 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1437 else if (!prefixcmp(diffopts, "-u"))
1438 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1439 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1440 ecbdata.diff_words =
1441 xcalloc(1, sizeof(struct diff_words_data));
1442 ecbdata.diff_words->file = o->file;
1444 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1445 &xpp, &xecfg, &ecb);
1446 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1447 free_diff_words_data(&ecbdata);
1450 free_ab_and_return:
1451 diff_free_filespec_data(one);
1452 diff_free_filespec_data(two);
1453 free(a_one);
1454 free(b_two);
1455 return;
1458 static void builtin_diffstat(const char *name_a, const char *name_b,
1459 struct diff_filespec *one,
1460 struct diff_filespec *two,
1461 struct diffstat_t *diffstat,
1462 struct diff_options *o,
1463 int complete_rewrite)
1465 mmfile_t mf1, mf2;
1466 struct diffstat_file *data;
1468 data = diffstat_add(diffstat, name_a, name_b);
1470 if (!one || !two) {
1471 data->is_unmerged = 1;
1472 return;
1474 if (complete_rewrite) {
1475 diff_populate_filespec(one, 0);
1476 diff_populate_filespec(two, 0);
1477 data->deleted = count_lines(one->data, one->size);
1478 data->added = count_lines(two->data, two->size);
1479 goto free_and_return;
1481 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1482 die("unable to read files to diff");
1484 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1485 data->is_binary = 1;
1486 data->added = mf2.size;
1487 data->deleted = mf1.size;
1488 } else {
1489 /* Crazy xdl interfaces.. */
1490 xpparam_t xpp;
1491 xdemitconf_t xecfg;
1492 xdemitcb_t ecb;
1494 memset(&xpp, 0, sizeof(xpp));
1495 memset(&xecfg, 0, sizeof(xecfg));
1496 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1497 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1498 &xpp, &xecfg, &ecb);
1501 free_and_return:
1502 diff_free_filespec_data(one);
1503 diff_free_filespec_data(two);
1506 static void builtin_checkdiff(const char *name_a, const char *name_b,
1507 const char *attr_path,
1508 struct diff_filespec *one,
1509 struct diff_filespec *two,
1510 struct diff_options *o)
1512 mmfile_t mf1, mf2;
1513 struct checkdiff_t data;
1515 if (!two)
1516 return;
1518 memset(&data, 0, sizeof(data));
1519 data.filename = name_b ? name_b : name_a;
1520 data.lineno = 0;
1521 data.o = o;
1522 data.ws_rule = whitespace_rule(attr_path);
1524 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1525 die("unable to read files to diff");
1528 * All the other codepaths check both sides, but not checking
1529 * the "old" side here is deliberate. We are checking the newly
1530 * introduced changes, and as long as the "new" side is text, we
1531 * can and should check what it introduces.
1533 if (diff_filespec_is_binary(two))
1534 goto free_and_return;
1535 else {
1536 /* Crazy xdl interfaces.. */
1537 xpparam_t xpp;
1538 xdemitconf_t xecfg;
1539 xdemitcb_t ecb;
1541 memset(&xpp, 0, sizeof(xpp));
1542 memset(&xecfg, 0, sizeof(xecfg));
1543 xecfg.ctxlen = 1; /* at least one context line */
1544 xpp.flags = XDF_NEED_MINIMAL;
1545 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1546 &xpp, &xecfg, &ecb);
1548 if ((data.ws_rule & WS_TRAILING_SPACE) &&
1549 data.trailing_blanks_start) {
1550 fprintf(o->file, "%s:%d: ends with blank lines.\n",
1551 data.filename, data.trailing_blanks_start);
1552 data.status = 1; /* report errors */
1555 free_and_return:
1556 diff_free_filespec_data(one);
1557 diff_free_filespec_data(two);
1558 if (data.status)
1559 DIFF_OPT_SET(o, CHECK_FAILED);
1562 struct diff_filespec *alloc_filespec(const char *path)
1564 int namelen = strlen(path);
1565 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1567 memset(spec, 0, sizeof(*spec));
1568 spec->path = (char *)(spec + 1);
1569 memcpy(spec->path, path, namelen+1);
1570 spec->count = 1;
1571 spec->is_binary = -1;
1572 return spec;
1575 void free_filespec(struct diff_filespec *spec)
1577 if (!--spec->count) {
1578 diff_free_filespec_data(spec);
1579 free(spec);
1583 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1584 unsigned short mode)
1586 if (mode) {
1587 spec->mode = canon_mode(mode);
1588 hashcpy(spec->sha1, sha1);
1589 spec->sha1_valid = !is_null_sha1(sha1);
1594 * Given a name and sha1 pair, if the index tells us the file in
1595 * the work tree has that object contents, return true, so that
1596 * prepare_temp_file() does not have to inflate and extract.
1598 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1600 struct cache_entry *ce;
1601 struct stat st;
1602 int pos, len;
1604 /* We do not read the cache ourselves here, because the
1605 * benchmark with my previous version that always reads cache
1606 * shows that it makes things worse for diff-tree comparing
1607 * two linux-2.6 kernel trees in an already checked out work
1608 * tree. This is because most diff-tree comparisons deal with
1609 * only a small number of files, while reading the cache is
1610 * expensive for a large project, and its cost outweighs the
1611 * savings we get by not inflating the object to a temporary
1612 * file. Practically, this code only helps when we are used
1613 * by diff-cache --cached, which does read the cache before
1614 * calling us.
1616 if (!active_cache)
1617 return 0;
1619 /* We want to avoid the working directory if our caller
1620 * doesn't need the data in a normal file, this system
1621 * is rather slow with its stat/open/mmap/close syscalls,
1622 * and the object is contained in a pack file. The pack
1623 * is probably already open and will be faster to obtain
1624 * the data through than the working directory. Loose
1625 * objects however would tend to be slower as they need
1626 * to be individually opened and inflated.
1628 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1629 return 0;
1631 len = strlen(name);
1632 pos = cache_name_pos(name, len);
1633 if (pos < 0)
1634 return 0;
1635 ce = active_cache[pos];
1638 * This is not the sha1 we are looking for, or
1639 * unreusable because it is not a regular file.
1641 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1642 return 0;
1645 * If ce matches the file in the work tree, we can reuse it.
1647 if (ce_uptodate(ce) ||
1648 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1649 return 1;
1651 return 0;
1654 static int populate_from_stdin(struct diff_filespec *s)
1656 struct strbuf buf = STRBUF_INIT;
1657 size_t size = 0;
1659 if (strbuf_read(&buf, 0, 0) < 0)
1660 return error("error while reading from stdin %s",
1661 strerror(errno));
1663 s->should_munmap = 0;
1664 s->data = strbuf_detach(&buf, &size);
1665 s->size = size;
1666 s->should_free = 1;
1667 return 0;
1670 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1672 int len;
1673 char *data = xmalloc(100);
1674 len = snprintf(data, 100,
1675 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1676 s->data = data;
1677 s->size = len;
1678 s->should_free = 1;
1679 if (size_only) {
1680 s->data = NULL;
1681 free(data);
1683 return 0;
1687 * While doing rename detection and pickaxe operation, we may need to
1688 * grab the data for the blob (or file) for our own in-core comparison.
1689 * diff_filespec has data and size fields for this purpose.
1691 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1693 int err = 0;
1694 if (!DIFF_FILE_VALID(s))
1695 die("internal error: asking to populate invalid file.");
1696 if (S_ISDIR(s->mode))
1697 return -1;
1699 if (s->data)
1700 return 0;
1702 if (size_only && 0 < s->size)
1703 return 0;
1705 if (S_ISGITLINK(s->mode))
1706 return diff_populate_gitlink(s, size_only);
1708 if (!s->sha1_valid ||
1709 reuse_worktree_file(s->path, s->sha1, 0)) {
1710 struct strbuf buf = STRBUF_INIT;
1711 struct stat st;
1712 int fd;
1714 if (!strcmp(s->path, "-"))
1715 return populate_from_stdin(s);
1717 if (lstat(s->path, &st) < 0) {
1718 if (errno == ENOENT) {
1719 err_empty:
1720 err = -1;
1721 empty:
1722 s->data = (char *)"";
1723 s->size = 0;
1724 return err;
1727 s->size = xsize_t(st.st_size);
1728 if (!s->size)
1729 goto empty;
1730 if (size_only)
1731 return 0;
1732 if (S_ISLNK(st.st_mode)) {
1733 int ret;
1734 s->data = xmalloc(s->size);
1735 s->should_free = 1;
1736 ret = readlink(s->path, s->data, s->size);
1737 if (ret < 0) {
1738 free(s->data);
1739 goto err_empty;
1741 return 0;
1743 fd = open(s->path, O_RDONLY);
1744 if (fd < 0)
1745 goto err_empty;
1746 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1747 close(fd);
1748 s->should_munmap = 1;
1751 * Convert from working tree format to canonical git format
1753 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
1754 size_t size = 0;
1755 munmap(s->data, s->size);
1756 s->should_munmap = 0;
1757 s->data = strbuf_detach(&buf, &size);
1758 s->size = size;
1759 s->should_free = 1;
1762 else {
1763 enum object_type type;
1764 if (size_only)
1765 type = sha1_object_info(s->sha1, &s->size);
1766 else {
1767 s->data = read_sha1_file(s->sha1, &type, &s->size);
1768 s->should_free = 1;
1771 return 0;
1774 void diff_free_filespec_blob(struct diff_filespec *s)
1776 if (s->should_free)
1777 free(s->data);
1778 else if (s->should_munmap)
1779 munmap(s->data, s->size);
1781 if (s->should_free || s->should_munmap) {
1782 s->should_free = s->should_munmap = 0;
1783 s->data = NULL;
1787 void diff_free_filespec_data(struct diff_filespec *s)
1789 diff_free_filespec_blob(s);
1790 free(s->cnt_data);
1791 s->cnt_data = NULL;
1794 static void prep_temp_blob(struct diff_tempfile *temp,
1795 void *blob,
1796 unsigned long size,
1797 const unsigned char *sha1,
1798 int mode)
1800 int fd;
1802 fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1803 if (fd < 0)
1804 die("unable to create temp-file: %s", strerror(errno));
1805 if (write_in_full(fd, blob, size) != size)
1806 die("unable to write temp-file");
1807 close(fd);
1808 temp->name = temp->tmp_path;
1809 strcpy(temp->hex, sha1_to_hex(sha1));
1810 temp->hex[40] = 0;
1811 sprintf(temp->mode, "%06o", mode);
1814 static void prepare_temp_file(const char *name,
1815 struct diff_tempfile *temp,
1816 struct diff_filespec *one)
1818 if (!DIFF_FILE_VALID(one)) {
1819 not_a_valid_file:
1820 /* A '-' entry produces this for file-2, and
1821 * a '+' entry produces this for file-1.
1823 temp->name = "/dev/null";
1824 strcpy(temp->hex, ".");
1825 strcpy(temp->mode, ".");
1826 return;
1829 if (!one->sha1_valid ||
1830 reuse_worktree_file(name, one->sha1, 1)) {
1831 struct stat st;
1832 if (lstat(name, &st) < 0) {
1833 if (errno == ENOENT)
1834 goto not_a_valid_file;
1835 die("stat(%s): %s", name, strerror(errno));
1837 if (S_ISLNK(st.st_mode)) {
1838 int ret;
1839 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1840 size_t sz = xsize_t(st.st_size);
1841 if (sizeof(buf) <= st.st_size)
1842 die("symlink too long: %s", name);
1843 ret = readlink(name, buf, sz);
1844 if (ret < 0)
1845 die("readlink(%s)", name);
1846 prep_temp_blob(temp, buf, sz,
1847 (one->sha1_valid ?
1848 one->sha1 : null_sha1),
1849 (one->sha1_valid ?
1850 one->mode : S_IFLNK));
1852 else {
1853 /* we can borrow from the file in the work tree */
1854 temp->name = name;
1855 if (!one->sha1_valid)
1856 strcpy(temp->hex, sha1_to_hex(null_sha1));
1857 else
1858 strcpy(temp->hex, sha1_to_hex(one->sha1));
1859 /* Even though we may sometimes borrow the
1860 * contents from the work tree, we always want
1861 * one->mode. mode is trustworthy even when
1862 * !(one->sha1_valid), as long as
1863 * DIFF_FILE_VALID(one).
1865 sprintf(temp->mode, "%06o", one->mode);
1867 return;
1869 else {
1870 if (diff_populate_filespec(one, 0))
1871 die("cannot read data blob for %s", one->path);
1872 prep_temp_blob(temp, one->data, one->size,
1873 one->sha1, one->mode);
1877 static void remove_tempfile(void)
1879 int i;
1881 for (i = 0; i < 2; i++)
1882 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1883 unlink(diff_temp[i].name);
1884 diff_temp[i].name = NULL;
1888 static void remove_tempfile_on_signal(int signo)
1890 remove_tempfile();
1891 signal(SIGINT, SIG_DFL);
1892 raise(signo);
1895 /* An external diff command takes:
1897 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1898 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1901 static void run_external_diff(const char *pgm,
1902 const char *name,
1903 const char *other,
1904 struct diff_filespec *one,
1905 struct diff_filespec *two,
1906 const char *xfrm_msg,
1907 int complete_rewrite)
1909 const char *spawn_arg[10];
1910 struct diff_tempfile *temp = diff_temp;
1911 int retval;
1912 static int atexit_asked = 0;
1913 const char *othername;
1914 const char **arg = &spawn_arg[0];
1916 othername = (other? other : name);
1917 if (one && two) {
1918 prepare_temp_file(name, &temp[0], one);
1919 prepare_temp_file(othername, &temp[1], two);
1920 if (! atexit_asked &&
1921 (temp[0].name == temp[0].tmp_path ||
1922 temp[1].name == temp[1].tmp_path)) {
1923 atexit_asked = 1;
1924 atexit(remove_tempfile);
1926 signal(SIGINT, remove_tempfile_on_signal);
1929 if (one && two) {
1930 *arg++ = pgm;
1931 *arg++ = name;
1932 *arg++ = temp[0].name;
1933 *arg++ = temp[0].hex;
1934 *arg++ = temp[0].mode;
1935 *arg++ = temp[1].name;
1936 *arg++ = temp[1].hex;
1937 *arg++ = temp[1].mode;
1938 if (other) {
1939 *arg++ = other;
1940 *arg++ = xfrm_msg;
1942 } else {
1943 *arg++ = pgm;
1944 *arg++ = name;
1946 *arg = NULL;
1947 fflush(NULL);
1948 retval = run_command_v_opt(spawn_arg, 0);
1949 remove_tempfile();
1950 if (retval) {
1951 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1952 exit(1);
1956 static void run_diff_cmd(const char *pgm,
1957 const char *name,
1958 const char *other,
1959 const char *attr_path,
1960 struct diff_filespec *one,
1961 struct diff_filespec *two,
1962 const char *xfrm_msg,
1963 struct diff_options *o,
1964 int complete_rewrite)
1966 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
1967 pgm = NULL;
1968 else {
1969 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
1970 if (drv && drv->external)
1971 pgm = drv->external;
1974 if (pgm) {
1975 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1976 complete_rewrite);
1977 return;
1979 if (one && two)
1980 builtin_diff(name, other ? other : name,
1981 one, two, xfrm_msg, o, complete_rewrite);
1982 else
1983 fprintf(o->file, "* Unmerged path %s\n", name);
1986 static void diff_fill_sha1_info(struct diff_filespec *one)
1988 if (DIFF_FILE_VALID(one)) {
1989 if (!one->sha1_valid) {
1990 struct stat st;
1991 if (!strcmp(one->path, "-")) {
1992 hashcpy(one->sha1, null_sha1);
1993 return;
1995 if (lstat(one->path, &st) < 0)
1996 die("stat %s", one->path);
1997 if (index_path(one->sha1, one->path, &st, 0))
1998 die("cannot hash %s\n", one->path);
2001 else
2002 hashclr(one->sha1);
2005 static int similarity_index(struct diff_filepair *p)
2007 return p->score * 100 / MAX_SCORE;
2010 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2012 /* Strip the prefix but do not molest /dev/null and absolute paths */
2013 if (*namep && **namep != '/')
2014 *namep += prefix_length;
2015 if (*otherp && **otherp != '/')
2016 *otherp += prefix_length;
2019 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2021 const char *pgm = external_diff();
2022 struct strbuf msg;
2023 char *xfrm_msg;
2024 struct diff_filespec *one = p->one;
2025 struct diff_filespec *two = p->two;
2026 const char *name;
2027 const char *other;
2028 const char *attr_path;
2029 int complete_rewrite = 0;
2031 name = p->one->path;
2032 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2033 attr_path = name;
2034 if (o->prefix_length)
2035 strip_prefix(o->prefix_length, &name, &other);
2037 if (DIFF_PAIR_UNMERGED(p)) {
2038 run_diff_cmd(pgm, name, NULL, attr_path,
2039 NULL, NULL, NULL, o, 0);
2040 return;
2043 diff_fill_sha1_info(one);
2044 diff_fill_sha1_info(two);
2046 strbuf_init(&msg, PATH_MAX * 2 + 300);
2047 switch (p->status) {
2048 case DIFF_STATUS_COPIED:
2049 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2050 strbuf_addstr(&msg, "\ncopy from ");
2051 quote_c_style(name, &msg, NULL, 0);
2052 strbuf_addstr(&msg, "\ncopy to ");
2053 quote_c_style(other, &msg, NULL, 0);
2054 strbuf_addch(&msg, '\n');
2055 break;
2056 case DIFF_STATUS_RENAMED:
2057 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2058 strbuf_addstr(&msg, "\nrename from ");
2059 quote_c_style(name, &msg, NULL, 0);
2060 strbuf_addstr(&msg, "\nrename to ");
2061 quote_c_style(other, &msg, NULL, 0);
2062 strbuf_addch(&msg, '\n');
2063 break;
2064 case DIFF_STATUS_MODIFIED:
2065 if (p->score) {
2066 strbuf_addf(&msg, "dissimilarity index %d%%\n",
2067 similarity_index(p));
2068 complete_rewrite = 1;
2069 break;
2071 /* fallthru */
2072 default:
2073 /* nothing */
2077 if (hashcmp(one->sha1, two->sha1)) {
2078 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2080 if (DIFF_OPT_TST(o, BINARY)) {
2081 mmfile_t mf;
2082 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2083 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2084 abbrev = 40;
2086 strbuf_addf(&msg, "index %.*s..%.*s",
2087 abbrev, sha1_to_hex(one->sha1),
2088 abbrev, sha1_to_hex(two->sha1));
2089 if (one->mode == two->mode)
2090 strbuf_addf(&msg, " %06o", one->mode);
2091 strbuf_addch(&msg, '\n');
2094 if (msg.len)
2095 strbuf_setlen(&msg, msg.len - 1);
2096 xfrm_msg = msg.len ? msg.buf : NULL;
2098 if (!pgm &&
2099 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2100 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2101 /* a filepair that changes between file and symlink
2102 * needs to be split into deletion and creation.
2104 struct diff_filespec *null = alloc_filespec(two->path);
2105 run_diff_cmd(NULL, name, other, attr_path,
2106 one, null, xfrm_msg, o, 0);
2107 free(null);
2108 null = alloc_filespec(one->path);
2109 run_diff_cmd(NULL, name, other, attr_path,
2110 null, two, xfrm_msg, o, 0);
2111 free(null);
2113 else
2114 run_diff_cmd(pgm, name, other, attr_path,
2115 one, two, xfrm_msg, o, complete_rewrite);
2117 strbuf_release(&msg);
2120 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2121 struct diffstat_t *diffstat)
2123 const char *name;
2124 const char *other;
2125 int complete_rewrite = 0;
2127 if (DIFF_PAIR_UNMERGED(p)) {
2128 /* unmerged */
2129 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2130 return;
2133 name = p->one->path;
2134 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2136 if (o->prefix_length)
2137 strip_prefix(o->prefix_length, &name, &other);
2139 diff_fill_sha1_info(p->one);
2140 diff_fill_sha1_info(p->two);
2142 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2143 complete_rewrite = 1;
2144 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2147 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2149 const char *name;
2150 const char *other;
2151 const char *attr_path;
2153 if (DIFF_PAIR_UNMERGED(p)) {
2154 /* unmerged */
2155 return;
2158 name = p->one->path;
2159 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2160 attr_path = other ? other : name;
2162 if (o->prefix_length)
2163 strip_prefix(o->prefix_length, &name, &other);
2165 diff_fill_sha1_info(p->one);
2166 diff_fill_sha1_info(p->two);
2168 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2171 void diff_setup(struct diff_options *options)
2173 memset(options, 0, sizeof(*options));
2175 options->file = stdout;
2177 options->line_termination = '\n';
2178 options->break_opt = -1;
2179 options->rename_limit = -1;
2180 options->dirstat_percent = 3;
2181 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
2182 options->context = 3;
2184 options->change = diff_change;
2185 options->add_remove = diff_addremove;
2186 if (diff_use_color_default > 0)
2187 DIFF_OPT_SET(options, COLOR_DIFF);
2188 else
2189 DIFF_OPT_CLR(options, COLOR_DIFF);
2190 options->detect_rename = diff_detect_rename_default;
2192 if (!diff_mnemonic_prefix) {
2193 options->a_prefix = "a/";
2194 options->b_prefix = "b/";
2198 int diff_setup_done(struct diff_options *options)
2200 int count = 0;
2202 if (options->output_format & DIFF_FORMAT_NAME)
2203 count++;
2204 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2205 count++;
2206 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2207 count++;
2208 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2209 count++;
2210 if (count > 1)
2211 die("--name-only, --name-status, --check and -s are mutually exclusive");
2213 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2214 options->detect_rename = DIFF_DETECT_COPY;
2216 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2217 options->prefix = NULL;
2218 if (options->prefix)
2219 options->prefix_length = strlen(options->prefix);
2220 else
2221 options->prefix_length = 0;
2223 if (options->output_format & (DIFF_FORMAT_NAME |
2224 DIFF_FORMAT_NAME_STATUS |
2225 DIFF_FORMAT_CHECKDIFF |
2226 DIFF_FORMAT_NO_OUTPUT))
2227 options->output_format &= ~(DIFF_FORMAT_RAW |
2228 DIFF_FORMAT_NUMSTAT |
2229 DIFF_FORMAT_DIFFSTAT |
2230 DIFF_FORMAT_SHORTSTAT |
2231 DIFF_FORMAT_DIRSTAT |
2232 DIFF_FORMAT_SUMMARY |
2233 DIFF_FORMAT_PATCH);
2236 * These cases always need recursive; we do not drop caller-supplied
2237 * recursive bits for other formats here.
2239 if (options->output_format & (DIFF_FORMAT_PATCH |
2240 DIFF_FORMAT_NUMSTAT |
2241 DIFF_FORMAT_DIFFSTAT |
2242 DIFF_FORMAT_SHORTSTAT |
2243 DIFF_FORMAT_DIRSTAT |
2244 DIFF_FORMAT_SUMMARY |
2245 DIFF_FORMAT_CHECKDIFF))
2246 DIFF_OPT_SET(options, RECURSIVE);
2248 * Also pickaxe would not work very well if you do not say recursive
2250 if (options->pickaxe)
2251 DIFF_OPT_SET(options, RECURSIVE);
2253 if (options->detect_rename && options->rename_limit < 0)
2254 options->rename_limit = diff_rename_limit_default;
2255 if (options->setup & DIFF_SETUP_USE_CACHE) {
2256 if (!active_cache)
2257 /* read-cache does not die even when it fails
2258 * so it is safe for us to do this here. Also
2259 * it does not smudge active_cache or active_nr
2260 * when it fails, so we do not have to worry about
2261 * cleaning it up ourselves either.
2263 read_cache();
2265 if (options->abbrev <= 0 || 40 < options->abbrev)
2266 options->abbrev = 40; /* full */
2269 * It does not make sense to show the first hit we happened
2270 * to have found. It does not make sense not to return with
2271 * exit code in such a case either.
2273 if (DIFF_OPT_TST(options, QUIET)) {
2274 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2275 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2278 return 0;
2281 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2283 char c, *eq;
2284 int len;
2286 if (*arg != '-')
2287 return 0;
2288 c = *++arg;
2289 if (!c)
2290 return 0;
2291 if (c == arg_short) {
2292 c = *++arg;
2293 if (!c)
2294 return 1;
2295 if (val && isdigit(c)) {
2296 char *end;
2297 int n = strtoul(arg, &end, 10);
2298 if (*end)
2299 return 0;
2300 *val = n;
2301 return 1;
2303 return 0;
2305 if (c != '-')
2306 return 0;
2307 arg++;
2308 eq = strchr(arg, '=');
2309 if (eq)
2310 len = eq - arg;
2311 else
2312 len = strlen(arg);
2313 if (!len || strncmp(arg, arg_long, len))
2314 return 0;
2315 if (eq) {
2316 int n;
2317 char *end;
2318 if (!isdigit(*++eq))
2319 return 0;
2320 n = strtoul(eq, &end, 10);
2321 if (*end)
2322 return 0;
2323 *val = n;
2325 return 1;
2328 static int diff_scoreopt_parse(const char *opt);
2330 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2332 const char *arg = av[0];
2334 /* Output format options */
2335 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2336 options->output_format |= DIFF_FORMAT_PATCH;
2337 else if (opt_arg(arg, 'U', "unified", &options->context))
2338 options->output_format |= DIFF_FORMAT_PATCH;
2339 else if (!strcmp(arg, "--raw"))
2340 options->output_format |= DIFF_FORMAT_RAW;
2341 else if (!strcmp(arg, "--patch-with-raw"))
2342 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2343 else if (!strcmp(arg, "--numstat"))
2344 options->output_format |= DIFF_FORMAT_NUMSTAT;
2345 else if (!strcmp(arg, "--shortstat"))
2346 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2347 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2348 options->output_format |= DIFF_FORMAT_DIRSTAT;
2349 else if (!strcmp(arg, "--cumulative")) {
2350 options->output_format |= DIFF_FORMAT_DIRSTAT;
2351 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2352 } else if (opt_arg(arg, 0, "dirstat-by-file",
2353 &options->dirstat_percent)) {
2354 options->output_format |= DIFF_FORMAT_DIRSTAT;
2355 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2357 else if (!strcmp(arg, "--check"))
2358 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2359 else if (!strcmp(arg, "--summary"))
2360 options->output_format |= DIFF_FORMAT_SUMMARY;
2361 else if (!strcmp(arg, "--patch-with-stat"))
2362 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2363 else if (!strcmp(arg, "--name-only"))
2364 options->output_format |= DIFF_FORMAT_NAME;
2365 else if (!strcmp(arg, "--name-status"))
2366 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2367 else if (!strcmp(arg, "-s"))
2368 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2369 else if (!prefixcmp(arg, "--stat")) {
2370 char *end;
2371 int width = options->stat_width;
2372 int name_width = options->stat_name_width;
2373 arg += 6;
2374 end = (char *)arg;
2376 switch (*arg) {
2377 case '-':
2378 if (!prefixcmp(arg, "-width="))
2379 width = strtoul(arg + 7, &end, 10);
2380 else if (!prefixcmp(arg, "-name-width="))
2381 name_width = strtoul(arg + 12, &end, 10);
2382 break;
2383 case '=':
2384 width = strtoul(arg+1, &end, 10);
2385 if (*end == ',')
2386 name_width = strtoul(end+1, &end, 10);
2389 /* Important! This checks all the error cases! */
2390 if (*end)
2391 return 0;
2392 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2393 options->stat_name_width = name_width;
2394 options->stat_width = width;
2397 /* renames options */
2398 else if (!prefixcmp(arg, "-B")) {
2399 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2400 return -1;
2402 else if (!prefixcmp(arg, "-M")) {
2403 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2404 return -1;
2405 options->detect_rename = DIFF_DETECT_RENAME;
2407 else if (!prefixcmp(arg, "-C")) {
2408 if (options->detect_rename == DIFF_DETECT_COPY)
2409 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2410 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2411 return -1;
2412 options->detect_rename = DIFF_DETECT_COPY;
2414 else if (!strcmp(arg, "--no-renames"))
2415 options->detect_rename = 0;
2416 else if (!strcmp(arg, "--relative"))
2417 DIFF_OPT_SET(options, RELATIVE_NAME);
2418 else if (!prefixcmp(arg, "--relative=")) {
2419 DIFF_OPT_SET(options, RELATIVE_NAME);
2420 options->prefix = arg + 11;
2423 /* xdiff options */
2424 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2425 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2426 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2427 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2428 else if (!strcmp(arg, "--ignore-space-at-eol"))
2429 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2431 /* flags options */
2432 else if (!strcmp(arg, "--binary")) {
2433 options->output_format |= DIFF_FORMAT_PATCH;
2434 DIFF_OPT_SET(options, BINARY);
2436 else if (!strcmp(arg, "--full-index"))
2437 DIFF_OPT_SET(options, FULL_INDEX);
2438 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2439 DIFF_OPT_SET(options, TEXT);
2440 else if (!strcmp(arg, "-R"))
2441 DIFF_OPT_SET(options, REVERSE_DIFF);
2442 else if (!strcmp(arg, "--find-copies-harder"))
2443 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2444 else if (!strcmp(arg, "--follow"))
2445 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2446 else if (!strcmp(arg, "--color"))
2447 DIFF_OPT_SET(options, COLOR_DIFF);
2448 else if (!strcmp(arg, "--no-color"))
2449 DIFF_OPT_CLR(options, COLOR_DIFF);
2450 else if (!strcmp(arg, "--color-words"))
2451 options->flags |= DIFF_OPT_COLOR_DIFF | DIFF_OPT_COLOR_DIFF_WORDS;
2452 else if (!strcmp(arg, "--exit-code"))
2453 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2454 else if (!strcmp(arg, "--quiet"))
2455 DIFF_OPT_SET(options, QUIET);
2456 else if (!strcmp(arg, "--ext-diff"))
2457 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2458 else if (!strcmp(arg, "--no-ext-diff"))
2459 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2460 else if (!strcmp(arg, "--ignore-submodules"))
2461 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2463 /* misc options */
2464 else if (!strcmp(arg, "-z"))
2465 options->line_termination = 0;
2466 else if (!prefixcmp(arg, "-l"))
2467 options->rename_limit = strtoul(arg+2, NULL, 10);
2468 else if (!prefixcmp(arg, "-S"))
2469 options->pickaxe = arg + 2;
2470 else if (!strcmp(arg, "--pickaxe-all"))
2471 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2472 else if (!strcmp(arg, "--pickaxe-regex"))
2473 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2474 else if (!prefixcmp(arg, "-O"))
2475 options->orderfile = arg + 2;
2476 else if (!prefixcmp(arg, "--diff-filter="))
2477 options->filter = arg + 14;
2478 else if (!strcmp(arg, "--abbrev"))
2479 options->abbrev = DEFAULT_ABBREV;
2480 else if (!prefixcmp(arg, "--abbrev=")) {
2481 options->abbrev = strtoul(arg + 9, NULL, 10);
2482 if (options->abbrev < MINIMUM_ABBREV)
2483 options->abbrev = MINIMUM_ABBREV;
2484 else if (40 < options->abbrev)
2485 options->abbrev = 40;
2487 else if (!prefixcmp(arg, "--src-prefix="))
2488 options->a_prefix = arg + 13;
2489 else if (!prefixcmp(arg, "--dst-prefix="))
2490 options->b_prefix = arg + 13;
2491 else if (!strcmp(arg, "--no-prefix"))
2492 options->a_prefix = options->b_prefix = "";
2493 else if (!prefixcmp(arg, "--output=")) {
2494 options->file = fopen(arg + strlen("--output="), "w");
2495 options->close_file = 1;
2496 } else
2497 return 0;
2498 return 1;
2501 static int parse_num(const char **cp_p)
2503 unsigned long num, scale;
2504 int ch, dot;
2505 const char *cp = *cp_p;
2507 num = 0;
2508 scale = 1;
2509 dot = 0;
2510 for(;;) {
2511 ch = *cp;
2512 if ( !dot && ch == '.' ) {
2513 scale = 1;
2514 dot = 1;
2515 } else if ( ch == '%' ) {
2516 scale = dot ? scale*100 : 100;
2517 cp++; /* % is always at the end */
2518 break;
2519 } else if ( ch >= '0' && ch <= '9' ) {
2520 if ( scale < 100000 ) {
2521 scale *= 10;
2522 num = (num*10) + (ch-'0');
2524 } else {
2525 break;
2527 cp++;
2529 *cp_p = cp;
2531 /* user says num divided by scale and we say internally that
2532 * is MAX_SCORE * num / scale.
2534 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2537 static int diff_scoreopt_parse(const char *opt)
2539 int opt1, opt2, cmd;
2541 if (*opt++ != '-')
2542 return -1;
2543 cmd = *opt++;
2544 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2545 return -1; /* that is not a -M, -C nor -B option */
2547 opt1 = parse_num(&opt);
2548 if (cmd != 'B')
2549 opt2 = 0;
2550 else {
2551 if (*opt == 0)
2552 opt2 = 0;
2553 else if (*opt != '/')
2554 return -1; /* we expect -B80/99 or -B80 */
2555 else {
2556 opt++;
2557 opt2 = parse_num(&opt);
2560 if (*opt != 0)
2561 return -1;
2562 return opt1 | (opt2 << 16);
2565 struct diff_queue_struct diff_queued_diff;
2567 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2569 if (queue->alloc <= queue->nr) {
2570 queue->alloc = alloc_nr(queue->alloc);
2571 queue->queue = xrealloc(queue->queue,
2572 sizeof(dp) * queue->alloc);
2574 queue->queue[queue->nr++] = dp;
2577 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2578 struct diff_filespec *one,
2579 struct diff_filespec *two)
2581 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2582 dp->one = one;
2583 dp->two = two;
2584 if (queue)
2585 diff_q(queue, dp);
2586 return dp;
2589 void diff_free_filepair(struct diff_filepair *p)
2591 free_filespec(p->one);
2592 free_filespec(p->two);
2593 free(p);
2596 /* This is different from find_unique_abbrev() in that
2597 * it stuffs the result with dots for alignment.
2599 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2601 int abblen;
2602 const char *abbrev;
2603 if (len == 40)
2604 return sha1_to_hex(sha1);
2606 abbrev = find_unique_abbrev(sha1, len);
2607 abblen = strlen(abbrev);
2608 if (abblen < 37) {
2609 static char hex[41];
2610 if (len < abblen && abblen <= len + 2)
2611 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2612 else
2613 sprintf(hex, "%s...", abbrev);
2614 return hex;
2616 return sha1_to_hex(sha1);
2619 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2621 int line_termination = opt->line_termination;
2622 int inter_name_termination = line_termination ? '\t' : '\0';
2624 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2625 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2626 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2627 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2629 if (p->score) {
2630 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2631 inter_name_termination);
2632 } else {
2633 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2636 if (p->status == DIFF_STATUS_COPIED ||
2637 p->status == DIFF_STATUS_RENAMED) {
2638 const char *name_a, *name_b;
2639 name_a = p->one->path;
2640 name_b = p->two->path;
2641 strip_prefix(opt->prefix_length, &name_a, &name_b);
2642 write_name_quoted(name_a, opt->file, inter_name_termination);
2643 write_name_quoted(name_b, opt->file, line_termination);
2644 } else {
2645 const char *name_a, *name_b;
2646 name_a = p->one->mode ? p->one->path : p->two->path;
2647 name_b = NULL;
2648 strip_prefix(opt->prefix_length, &name_a, &name_b);
2649 write_name_quoted(name_a, opt->file, line_termination);
2653 int diff_unmodified_pair(struct diff_filepair *p)
2655 /* This function is written stricter than necessary to support
2656 * the currently implemented transformers, but the idea is to
2657 * let transformers to produce diff_filepairs any way they want,
2658 * and filter and clean them up here before producing the output.
2660 struct diff_filespec *one = p->one, *two = p->two;
2662 if (DIFF_PAIR_UNMERGED(p))
2663 return 0; /* unmerged is interesting */
2665 /* deletion, addition, mode or type change
2666 * and rename are all interesting.
2668 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2669 DIFF_PAIR_MODE_CHANGED(p) ||
2670 strcmp(one->path, two->path))
2671 return 0;
2673 /* both are valid and point at the same path. that is, we are
2674 * dealing with a change.
2676 if (one->sha1_valid && two->sha1_valid &&
2677 !hashcmp(one->sha1, two->sha1))
2678 return 1; /* no change */
2679 if (!one->sha1_valid && !two->sha1_valid)
2680 return 1; /* both look at the same file on the filesystem. */
2681 return 0;
2684 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2686 if (diff_unmodified_pair(p))
2687 return;
2689 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2690 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2691 return; /* no tree diffs in patch format */
2693 run_diff(p, o);
2696 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2697 struct diffstat_t *diffstat)
2699 if (diff_unmodified_pair(p))
2700 return;
2702 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2703 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2704 return; /* no tree diffs in patch format */
2706 run_diffstat(p, o, diffstat);
2709 static void diff_flush_checkdiff(struct diff_filepair *p,
2710 struct diff_options *o)
2712 if (diff_unmodified_pair(p))
2713 return;
2715 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2716 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2717 return; /* no tree diffs in patch format */
2719 run_checkdiff(p, o);
2722 int diff_queue_is_empty(void)
2724 struct diff_queue_struct *q = &diff_queued_diff;
2725 int i;
2726 for (i = 0; i < q->nr; i++)
2727 if (!diff_unmodified_pair(q->queue[i]))
2728 return 0;
2729 return 1;
2732 #if DIFF_DEBUG
2733 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2735 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2736 x, one ? one : "",
2737 s->path,
2738 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2739 s->mode,
2740 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2741 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2742 x, one ? one : "",
2743 s->size, s->xfrm_flags);
2746 void diff_debug_filepair(const struct diff_filepair *p, int i)
2748 diff_debug_filespec(p->one, i, "one");
2749 diff_debug_filespec(p->two, i, "two");
2750 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2751 p->score, p->status ? p->status : '?',
2752 p->one->rename_used, p->broken_pair);
2755 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2757 int i;
2758 if (msg)
2759 fprintf(stderr, "%s\n", msg);
2760 fprintf(stderr, "q->nr = %d\n", q->nr);
2761 for (i = 0; i < q->nr; i++) {
2762 struct diff_filepair *p = q->queue[i];
2763 diff_debug_filepair(p, i);
2766 #endif
2768 static void diff_resolve_rename_copy(void)
2770 int i;
2771 struct diff_filepair *p;
2772 struct diff_queue_struct *q = &diff_queued_diff;
2774 diff_debug_queue("resolve-rename-copy", q);
2776 for (i = 0; i < q->nr; i++) {
2777 p = q->queue[i];
2778 p->status = 0; /* undecided */
2779 if (DIFF_PAIR_UNMERGED(p))
2780 p->status = DIFF_STATUS_UNMERGED;
2781 else if (!DIFF_FILE_VALID(p->one))
2782 p->status = DIFF_STATUS_ADDED;
2783 else if (!DIFF_FILE_VALID(p->two))
2784 p->status = DIFF_STATUS_DELETED;
2785 else if (DIFF_PAIR_TYPE_CHANGED(p))
2786 p->status = DIFF_STATUS_TYPE_CHANGED;
2788 /* from this point on, we are dealing with a pair
2789 * whose both sides are valid and of the same type, i.e.
2790 * either in-place edit or rename/copy edit.
2792 else if (DIFF_PAIR_RENAME(p)) {
2794 * A rename might have re-connected a broken
2795 * pair up, causing the pathnames to be the
2796 * same again. If so, that's not a rename at
2797 * all, just a modification..
2799 * Otherwise, see if this source was used for
2800 * multiple renames, in which case we decrement
2801 * the count, and call it a copy.
2803 if (!strcmp(p->one->path, p->two->path))
2804 p->status = DIFF_STATUS_MODIFIED;
2805 else if (--p->one->rename_used > 0)
2806 p->status = DIFF_STATUS_COPIED;
2807 else
2808 p->status = DIFF_STATUS_RENAMED;
2810 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2811 p->one->mode != p->two->mode ||
2812 is_null_sha1(p->one->sha1))
2813 p->status = DIFF_STATUS_MODIFIED;
2814 else {
2815 /* This is a "no-change" entry and should not
2816 * happen anymore, but prepare for broken callers.
2818 error("feeding unmodified %s to diffcore",
2819 p->one->path);
2820 p->status = DIFF_STATUS_UNKNOWN;
2823 diff_debug_queue("resolve-rename-copy done", q);
2826 static int check_pair_status(struct diff_filepair *p)
2828 switch (p->status) {
2829 case DIFF_STATUS_UNKNOWN:
2830 return 0;
2831 case 0:
2832 die("internal error in diff-resolve-rename-copy");
2833 default:
2834 return 1;
2838 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2840 int fmt = opt->output_format;
2842 if (fmt & DIFF_FORMAT_CHECKDIFF)
2843 diff_flush_checkdiff(p, opt);
2844 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2845 diff_flush_raw(p, opt);
2846 else if (fmt & DIFF_FORMAT_NAME) {
2847 const char *name_a, *name_b;
2848 name_a = p->two->path;
2849 name_b = NULL;
2850 strip_prefix(opt->prefix_length, &name_a, &name_b);
2851 write_name_quoted(name_a, opt->file, opt->line_termination);
2855 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
2857 if (fs->mode)
2858 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
2859 else
2860 fprintf(file, " %s ", newdelete);
2861 write_name_quoted(fs->path, file, '\n');
2865 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
2867 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2868 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
2869 show_name ? ' ' : '\n');
2870 if (show_name) {
2871 write_name_quoted(p->two->path, file, '\n');
2876 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
2878 char *names = pprint_rename(p->one->path, p->two->path);
2880 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2881 free(names);
2882 show_mode_change(file, p, 0);
2885 static void diff_summary(FILE *file, struct diff_filepair *p)
2887 switch(p->status) {
2888 case DIFF_STATUS_DELETED:
2889 show_file_mode_name(file, "delete", p->one);
2890 break;
2891 case DIFF_STATUS_ADDED:
2892 show_file_mode_name(file, "create", p->two);
2893 break;
2894 case DIFF_STATUS_COPIED:
2895 show_rename_copy(file, "copy", p);
2896 break;
2897 case DIFF_STATUS_RENAMED:
2898 show_rename_copy(file, "rename", p);
2899 break;
2900 default:
2901 if (p->score) {
2902 fputs(" rewrite ", file);
2903 write_name_quoted(p->two->path, file, ' ');
2904 fprintf(file, "(%d%%)\n", similarity_index(p));
2906 show_mode_change(file, p, !p->score);
2907 break;
2911 struct patch_id_t {
2912 git_SHA_CTX *ctx;
2913 int patchlen;
2916 static int remove_space(char *line, int len)
2918 int i;
2919 char *dst = line;
2920 unsigned char c;
2922 for (i = 0; i < len; i++)
2923 if (!isspace((c = line[i])))
2924 *dst++ = c;
2926 return dst - line;
2929 static void patch_id_consume(void *priv, char *line, unsigned long len)
2931 struct patch_id_t *data = priv;
2932 int new_len;
2934 /* Ignore line numbers when computing the SHA1 of the patch */
2935 if (!prefixcmp(line, "@@ -"))
2936 return;
2938 new_len = remove_space(line, len);
2940 git_SHA1_Update(data->ctx, line, new_len);
2941 data->patchlen += new_len;
2944 /* returns 0 upon success, and writes result into sha1 */
2945 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2947 struct diff_queue_struct *q = &diff_queued_diff;
2948 int i;
2949 git_SHA_CTX ctx;
2950 struct patch_id_t data;
2951 char buffer[PATH_MAX * 4 + 20];
2953 git_SHA1_Init(&ctx);
2954 memset(&data, 0, sizeof(struct patch_id_t));
2955 data.ctx = &ctx;
2957 for (i = 0; i < q->nr; i++) {
2958 xpparam_t xpp;
2959 xdemitconf_t xecfg;
2960 xdemitcb_t ecb;
2961 mmfile_t mf1, mf2;
2962 struct diff_filepair *p = q->queue[i];
2963 int len1, len2;
2965 memset(&xpp, 0, sizeof(xpp));
2966 memset(&xecfg, 0, sizeof(xecfg));
2967 if (p->status == 0)
2968 return error("internal diff status error");
2969 if (p->status == DIFF_STATUS_UNKNOWN)
2970 continue;
2971 if (diff_unmodified_pair(p))
2972 continue;
2973 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2974 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2975 continue;
2976 if (DIFF_PAIR_UNMERGED(p))
2977 continue;
2979 diff_fill_sha1_info(p->one);
2980 diff_fill_sha1_info(p->two);
2981 if (fill_mmfile(&mf1, p->one) < 0 ||
2982 fill_mmfile(&mf2, p->two) < 0)
2983 return error("unable to read files to diff");
2985 len1 = remove_space(p->one->path, strlen(p->one->path));
2986 len2 = remove_space(p->two->path, strlen(p->two->path));
2987 if (p->one->mode == 0)
2988 len1 = snprintf(buffer, sizeof(buffer),
2989 "diff--gita/%.*sb/%.*s"
2990 "newfilemode%06o"
2991 "---/dev/null"
2992 "+++b/%.*s",
2993 len1, p->one->path,
2994 len2, p->two->path,
2995 p->two->mode,
2996 len2, p->two->path);
2997 else if (p->two->mode == 0)
2998 len1 = snprintf(buffer, sizeof(buffer),
2999 "diff--gita/%.*sb/%.*s"
3000 "deletedfilemode%06o"
3001 "---a/%.*s"
3002 "+++/dev/null",
3003 len1, p->one->path,
3004 len2, p->two->path,
3005 p->one->mode,
3006 len1, p->one->path);
3007 else
3008 len1 = snprintf(buffer, sizeof(buffer),
3009 "diff--gita/%.*sb/%.*s"
3010 "---a/%.*s"
3011 "+++b/%.*s",
3012 len1, p->one->path,
3013 len2, p->two->path,
3014 len1, p->one->path,
3015 len2, p->two->path);
3016 git_SHA1_Update(&ctx, buffer, len1);
3018 xpp.flags = XDF_NEED_MINIMAL;
3019 xecfg.ctxlen = 3;
3020 xecfg.flags = XDL_EMIT_FUNCNAMES;
3021 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3022 &xpp, &xecfg, &ecb);
3025 git_SHA1_Final(sha1, &ctx);
3026 return 0;
3029 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3031 struct diff_queue_struct *q = &diff_queued_diff;
3032 int i;
3033 int result = diff_get_patch_id(options, sha1);
3035 for (i = 0; i < q->nr; i++)
3036 diff_free_filepair(q->queue[i]);
3038 free(q->queue);
3039 q->queue = NULL;
3040 q->nr = q->alloc = 0;
3042 return result;
3045 static int is_summary_empty(const struct diff_queue_struct *q)
3047 int i;
3049 for (i = 0; i < q->nr; i++) {
3050 const struct diff_filepair *p = q->queue[i];
3052 switch (p->status) {
3053 case DIFF_STATUS_DELETED:
3054 case DIFF_STATUS_ADDED:
3055 case DIFF_STATUS_COPIED:
3056 case DIFF_STATUS_RENAMED:
3057 return 0;
3058 default:
3059 if (p->score)
3060 return 0;
3061 if (p->one->mode && p->two->mode &&
3062 p->one->mode != p->two->mode)
3063 return 0;
3064 break;
3067 return 1;
3070 void diff_flush(struct diff_options *options)
3072 struct diff_queue_struct *q = &diff_queued_diff;
3073 int i, output_format = options->output_format;
3074 int separator = 0;
3077 * Order: raw, stat, summary, patch
3078 * or: name/name-status/checkdiff (other bits clear)
3080 if (!q->nr)
3081 goto free_queue;
3083 if (output_format & (DIFF_FORMAT_RAW |
3084 DIFF_FORMAT_NAME |
3085 DIFF_FORMAT_NAME_STATUS |
3086 DIFF_FORMAT_CHECKDIFF)) {
3087 for (i = 0; i < q->nr; i++) {
3088 struct diff_filepair *p = q->queue[i];
3089 if (check_pair_status(p))
3090 flush_one_pair(p, options);
3092 separator++;
3095 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3096 struct diffstat_t diffstat;
3098 memset(&diffstat, 0, sizeof(struct diffstat_t));
3099 for (i = 0; i < q->nr; i++) {
3100 struct diff_filepair *p = q->queue[i];
3101 if (check_pair_status(p))
3102 diff_flush_stat(p, options, &diffstat);
3104 if (output_format & DIFF_FORMAT_NUMSTAT)
3105 show_numstat(&diffstat, options);
3106 if (output_format & DIFF_FORMAT_DIFFSTAT)
3107 show_stats(&diffstat, options);
3108 if (output_format & DIFF_FORMAT_SHORTSTAT)
3109 show_shortstats(&diffstat, options);
3110 free_diffstat_info(&diffstat);
3111 separator++;
3113 if (output_format & DIFF_FORMAT_DIRSTAT)
3114 show_dirstat(options);
3116 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3117 for (i = 0; i < q->nr; i++)
3118 diff_summary(options->file, q->queue[i]);
3119 separator++;
3122 if (output_format & DIFF_FORMAT_PATCH) {
3123 if (separator) {
3124 putc(options->line_termination, options->file);
3125 if (options->stat_sep) {
3126 /* attach patch instead of inline */
3127 fputs(options->stat_sep, options->file);
3131 for (i = 0; i < q->nr; i++) {
3132 struct diff_filepair *p = q->queue[i];
3133 if (check_pair_status(p))
3134 diff_flush_patch(p, options);
3138 if (output_format & DIFF_FORMAT_CALLBACK)
3139 options->format_callback(q, options, options->format_callback_data);
3141 for (i = 0; i < q->nr; i++)
3142 diff_free_filepair(q->queue[i]);
3143 free_queue:
3144 free(q->queue);
3145 q->queue = NULL;
3146 q->nr = q->alloc = 0;
3147 if (options->close_file)
3148 fclose(options->file);
3151 static void diffcore_apply_filter(const char *filter)
3153 int i;
3154 struct diff_queue_struct *q = &diff_queued_diff;
3155 struct diff_queue_struct outq;
3156 outq.queue = NULL;
3157 outq.nr = outq.alloc = 0;
3159 if (!filter)
3160 return;
3162 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3163 int found;
3164 for (i = found = 0; !found && i < q->nr; i++) {
3165 struct diff_filepair *p = q->queue[i];
3166 if (((p->status == DIFF_STATUS_MODIFIED) &&
3167 ((p->score &&
3168 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3169 (!p->score &&
3170 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3171 ((p->status != DIFF_STATUS_MODIFIED) &&
3172 strchr(filter, p->status)))
3173 found++;
3175 if (found)
3176 return;
3178 /* otherwise we will clear the whole queue
3179 * by copying the empty outq at the end of this
3180 * function, but first clear the current entries
3181 * in the queue.
3183 for (i = 0; i < q->nr; i++)
3184 diff_free_filepair(q->queue[i]);
3186 else {
3187 /* Only the matching ones */
3188 for (i = 0; i < q->nr; i++) {
3189 struct diff_filepair *p = q->queue[i];
3191 if (((p->status == DIFF_STATUS_MODIFIED) &&
3192 ((p->score &&
3193 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3194 (!p->score &&
3195 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3196 ((p->status != DIFF_STATUS_MODIFIED) &&
3197 strchr(filter, p->status)))
3198 diff_q(&outq, p);
3199 else
3200 diff_free_filepair(p);
3203 free(q->queue);
3204 *q = outq;
3207 /* Check whether two filespecs with the same mode and size are identical */
3208 static int diff_filespec_is_identical(struct diff_filespec *one,
3209 struct diff_filespec *two)
3211 if (S_ISGITLINK(one->mode))
3212 return 0;
3213 if (diff_populate_filespec(one, 0))
3214 return 0;
3215 if (diff_populate_filespec(two, 0))
3216 return 0;
3217 return !memcmp(one->data, two->data, one->size);
3220 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3222 int i;
3223 struct diff_queue_struct *q = &diff_queued_diff;
3224 struct diff_queue_struct outq;
3225 outq.queue = NULL;
3226 outq.nr = outq.alloc = 0;
3228 for (i = 0; i < q->nr; i++) {
3229 struct diff_filepair *p = q->queue[i];
3232 * 1. Entries that come from stat info dirtyness
3233 * always have both sides (iow, not create/delete),
3234 * one side of the object name is unknown, with
3235 * the same mode and size. Keep the ones that
3236 * do not match these criteria. They have real
3237 * differences.
3239 * 2. At this point, the file is known to be modified,
3240 * with the same mode and size, and the object
3241 * name of one side is unknown. Need to inspect
3242 * the identical contents.
3244 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3245 !DIFF_FILE_VALID(p->two) ||
3246 (p->one->sha1_valid && p->two->sha1_valid) ||
3247 (p->one->mode != p->two->mode) ||
3248 diff_populate_filespec(p->one, 1) ||
3249 diff_populate_filespec(p->two, 1) ||
3250 (p->one->size != p->two->size) ||
3251 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3252 diff_q(&outq, p);
3253 else {
3255 * The caller can subtract 1 from skip_stat_unmatch
3256 * to determine how many paths were dirty only
3257 * due to stat info mismatch.
3259 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3260 diffopt->skip_stat_unmatch++;
3261 diff_free_filepair(p);
3264 free(q->queue);
3265 *q = outq;
3268 void diffcore_std(struct diff_options *options)
3270 if (options->skip_stat_unmatch)
3271 diffcore_skip_stat_unmatch(options);
3272 if (options->break_opt != -1)
3273 diffcore_break(options->break_opt);
3274 if (options->detect_rename)
3275 diffcore_rename(options);
3276 if (options->break_opt != -1)
3277 diffcore_merge_broken();
3278 if (options->pickaxe)
3279 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3280 if (options->orderfile)
3281 diffcore_order(options->orderfile);
3282 diff_resolve_rename_copy();
3283 diffcore_apply_filter(options->filter);
3285 if (diff_queued_diff.nr)
3286 DIFF_OPT_SET(options, HAS_CHANGES);
3287 else
3288 DIFF_OPT_CLR(options, HAS_CHANGES);
3291 int diff_result_code(struct diff_options *opt, int status)
3293 int result = 0;
3294 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3295 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3296 return status;
3297 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3298 DIFF_OPT_TST(opt, HAS_CHANGES))
3299 result |= 01;
3300 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3301 DIFF_OPT_TST(opt, CHECK_FAILED))
3302 result |= 02;
3303 return result;
3306 void diff_addremove(struct diff_options *options,
3307 int addremove, unsigned mode,
3308 const unsigned char *sha1,
3309 const char *concatpath)
3311 struct diff_filespec *one, *two;
3313 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3314 return;
3316 /* This may look odd, but it is a preparation for
3317 * feeding "there are unchanged files which should
3318 * not produce diffs, but when you are doing copy
3319 * detection you would need them, so here they are"
3320 * entries to the diff-core. They will be prefixed
3321 * with something like '=' or '*' (I haven't decided
3322 * which but should not make any difference).
3323 * Feeding the same new and old to diff_change()
3324 * also has the same effect.
3325 * Before the final output happens, they are pruned after
3326 * merged into rename/copy pairs as appropriate.
3328 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3329 addremove = (addremove == '+' ? '-' :
3330 addremove == '-' ? '+' : addremove);
3332 if (options->prefix &&
3333 strncmp(concatpath, options->prefix, options->prefix_length))
3334 return;
3336 one = alloc_filespec(concatpath);
3337 two = alloc_filespec(concatpath);
3339 if (addremove != '+')
3340 fill_filespec(one, sha1, mode);
3341 if (addremove != '-')
3342 fill_filespec(two, sha1, mode);
3344 diff_queue(&diff_queued_diff, one, two);
3345 DIFF_OPT_SET(options, HAS_CHANGES);
3348 void diff_change(struct diff_options *options,
3349 unsigned old_mode, unsigned new_mode,
3350 const unsigned char *old_sha1,
3351 const unsigned char *new_sha1,
3352 const char *concatpath)
3354 struct diff_filespec *one, *two;
3356 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3357 && S_ISGITLINK(new_mode))
3358 return;
3360 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3361 unsigned tmp;
3362 const unsigned char *tmp_c;
3363 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3364 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3367 if (options->prefix &&
3368 strncmp(concatpath, options->prefix, options->prefix_length))
3369 return;
3371 one = alloc_filespec(concatpath);
3372 two = alloc_filespec(concatpath);
3373 fill_filespec(one, old_sha1, old_mode);
3374 fill_filespec(two, new_sha1, new_mode);
3376 diff_queue(&diff_queued_diff, one, two);
3377 DIFF_OPT_SET(options, HAS_CHANGES);
3380 void diff_unmerge(struct diff_options *options,
3381 const char *path,
3382 unsigned mode, const unsigned char *sha1)
3384 struct diff_filespec *one, *two;
3386 if (options->prefix &&
3387 strncmp(path, options->prefix, options->prefix_length))
3388 return;
3390 one = alloc_filespec(path);
3391 two = alloc_filespec(path);
3392 fill_filespec(one, sha1, mode);
3393 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3396 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3397 size_t *outsize)
3399 struct diff_tempfile temp;
3400 const char *argv[3];
3401 const char **arg = argv;
3402 struct child_process child;
3403 struct strbuf buf = STRBUF_INIT;
3405 prepare_temp_file(spec->path, &temp, spec);
3406 *arg++ = pgm;
3407 *arg++ = temp.name;
3408 *arg = NULL;
3410 memset(&child, 0, sizeof(child));
3411 child.argv = argv;
3412 child.out = -1;
3413 if (start_command(&child) != 0 ||
3414 strbuf_read(&buf, child.out, 0) < 0 ||
3415 finish_command(&child) != 0) {
3416 if (temp.name == temp.tmp_path)
3417 unlink(temp.name);
3418 error("error running textconv command '%s'", pgm);
3419 return NULL;
3421 if (temp.name == temp.tmp_path)
3422 unlink(temp.name);
3424 return strbuf_detach(&buf, outsize);