blame: use xdi_diff_hunks(), get rid of struct patch
[git/wpalmer.git] / diff.c
blobf141e7c8ff661733c2be6652709cc60c3340100e
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "quote.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "delta.h"
9 #include "xdiff-interface.h"
10 #include "color.h"
11 #include "attr.h"
12 #include "run-command.h"
13 #include "utf8.h"
15 #ifdef NO_FAST_WORKING_DIRECTORY
16 #define FAST_WORKING_DIRECTORY 0
17 #else
18 #define FAST_WORKING_DIRECTORY 1
19 #endif
21 static int diff_detect_rename_default;
22 static int diff_rename_limit_default = 200;
23 static int diff_suppress_blank_empty;
24 int diff_use_color_default = -1;
25 static const char *external_diff_cmd_cfg;
26 int diff_auto_refresh_index = 1;
27 static int diff_mnemonic_prefix;
29 static char diff_colors[][COLOR_MAXLEN] = {
30 "\033[m", /* reset */
31 "", /* PLAIN (normal) */
32 "\033[1m", /* METAINFO (bold) */
33 "\033[36m", /* FRAGINFO (cyan) */
34 "\033[31m", /* OLD (red) */
35 "\033[32m", /* NEW (green) */
36 "\033[33m", /* COMMIT (yellow) */
37 "\033[41m", /* WHITESPACE (red background) */
40 static int parse_diff_color_slot(const char *var, int ofs)
42 if (!strcasecmp(var+ofs, "plain"))
43 return DIFF_PLAIN;
44 if (!strcasecmp(var+ofs, "meta"))
45 return DIFF_METAINFO;
46 if (!strcasecmp(var+ofs, "frag"))
47 return DIFF_FRAGINFO;
48 if (!strcasecmp(var+ofs, "old"))
49 return DIFF_FILE_OLD;
50 if (!strcasecmp(var+ofs, "new"))
51 return DIFF_FILE_NEW;
52 if (!strcasecmp(var+ofs, "commit"))
53 return DIFF_COMMIT;
54 if (!strcasecmp(var+ofs, "whitespace"))
55 return DIFF_WHITESPACE;
56 die("bad config variable '%s'", var);
59 static struct ll_diff_driver {
60 const char *name;
61 struct ll_diff_driver *next;
62 const char *cmd;
63 } *user_diff, **user_diff_tail;
66 * Currently there is only "diff.<drivername>.command" variable;
67 * because there are "diff.color.<slot>" variables, we are parsing
68 * this in a bit convoluted way to allow low level diff driver
69 * called "color".
71 static int parse_lldiff_command(const char *var, const char *ep, const char *value)
73 const char *name;
74 int namelen;
75 struct ll_diff_driver *drv;
77 name = var + 5;
78 namelen = ep - name;
79 for (drv = user_diff; drv; drv = drv->next)
80 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
81 break;
82 if (!drv) {
83 drv = xcalloc(1, sizeof(struct ll_diff_driver));
84 drv->name = xmemdupz(name, namelen);
85 if (!user_diff_tail)
86 user_diff_tail = &user_diff;
87 *user_diff_tail = drv;
88 user_diff_tail = &(drv->next);
91 return git_config_string(&(drv->cmd), var, value);
95 * 'diff.<what>.funcname' attribute can be specified in the configuration
96 * to define a customized regexp to find the beginning of a function to
97 * be used for hunk header lines of "diff -p" style output.
99 struct funcname_pattern_entry {
100 char *name;
101 char *pattern;
102 int cflags;
104 static struct funcname_pattern_list {
105 struct funcname_pattern_list *next;
106 struct funcname_pattern_entry e;
107 } *funcname_pattern_list;
109 static int parse_funcname_pattern(const char *var, const char *ep, const char *value, int cflags)
111 const char *name;
112 int namelen;
113 struct funcname_pattern_list *pp;
115 name = var + 5; /* "diff." */
116 namelen = ep - name;
118 for (pp = funcname_pattern_list; pp; pp = pp->next)
119 if (!strncmp(pp->e.name, name, namelen) && !pp->e.name[namelen])
120 break;
121 if (!pp) {
122 pp = xcalloc(1, sizeof(*pp));
123 pp->e.name = xmemdupz(name, namelen);
124 pp->next = funcname_pattern_list;
125 funcname_pattern_list = pp;
127 free(pp->e.pattern);
128 pp->e.pattern = xstrdup(value);
129 pp->e.cflags = cflags;
130 return 0;
134 * These are to give UI layer defaults.
135 * The core-level commands such as git-diff-files should
136 * never be affected by the setting of diff.renames
137 * the user happens to have in the configuration file.
139 int git_diff_ui_config(const char *var, const char *value, void *cb)
141 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
142 diff_use_color_default = git_config_colorbool(var, value, -1);
143 return 0;
145 if (!strcmp(var, "diff.renames")) {
146 if (!value)
147 diff_detect_rename_default = DIFF_DETECT_RENAME;
148 else if (!strcasecmp(value, "copies") ||
149 !strcasecmp(value, "copy"))
150 diff_detect_rename_default = DIFF_DETECT_COPY;
151 else if (git_config_bool(var,value))
152 diff_detect_rename_default = DIFF_DETECT_RENAME;
153 return 0;
155 if (!strcmp(var, "diff.autorefreshindex")) {
156 diff_auto_refresh_index = git_config_bool(var, value);
157 return 0;
159 if (!strcmp(var, "diff.mnemonicprefix")) {
160 diff_mnemonic_prefix = git_config_bool(var, value);
161 return 0;
163 if (!strcmp(var, "diff.external"))
164 return git_config_string(&external_diff_cmd_cfg, var, value);
165 if (!prefixcmp(var, "diff.")) {
166 const char *ep = strrchr(var, '.');
168 if (ep != var + 4 && !strcmp(ep, ".command"))
169 return parse_lldiff_command(var, ep, value);
172 return git_diff_basic_config(var, value, cb);
175 int git_diff_basic_config(const char *var, const char *value, void *cb)
177 if (!strcmp(var, "diff.renamelimit")) {
178 diff_rename_limit_default = git_config_int(var, value);
179 return 0;
182 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
183 int slot = parse_diff_color_slot(var, 11);
184 if (!value)
185 return config_error_nonbool(var);
186 color_parse(value, var, diff_colors[slot]);
187 return 0;
190 /* like GNU diff's --suppress-blank-empty option */
191 if (!strcmp(var, "diff.suppress-blank-empty")) {
192 diff_suppress_blank_empty = git_config_bool(var, value);
193 return 0;
196 if (!prefixcmp(var, "diff.")) {
197 const char *ep = strrchr(var, '.');
198 if (ep != var + 4) {
199 if (!strcmp(ep, ".funcname")) {
200 if (!value)
201 return config_error_nonbool(var);
202 return parse_funcname_pattern(var, ep, value,
204 } else if (!strcmp(ep, ".xfuncname")) {
205 if (!value)
206 return config_error_nonbool(var);
207 return parse_funcname_pattern(var, ep, value,
208 REG_EXTENDED);
213 return git_color_default_config(var, value, cb);
216 static char *quote_two(const char *one, const char *two)
218 int need_one = quote_c_style(one, NULL, NULL, 1);
219 int need_two = quote_c_style(two, NULL, NULL, 1);
220 struct strbuf res = STRBUF_INIT;
222 if (need_one + need_two) {
223 strbuf_addch(&res, '"');
224 quote_c_style(one, &res, NULL, 1);
225 quote_c_style(two, &res, NULL, 1);
226 strbuf_addch(&res, '"');
227 } else {
228 strbuf_addstr(&res, one);
229 strbuf_addstr(&res, two);
231 return strbuf_detach(&res, NULL);
234 static const char *external_diff(void)
236 static const char *external_diff_cmd = NULL;
237 static int done_preparing = 0;
239 if (done_preparing)
240 return external_diff_cmd;
241 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
242 if (!external_diff_cmd)
243 external_diff_cmd = external_diff_cmd_cfg;
244 done_preparing = 1;
245 return external_diff_cmd;
248 static struct diff_tempfile {
249 const char *name; /* filename external diff should read from */
250 char hex[41];
251 char mode[10];
252 char tmp_path[PATH_MAX];
253 } diff_temp[2];
255 static int count_lines(const char *data, int size)
257 int count, ch, completely_empty = 1, nl_just_seen = 0;
258 count = 0;
259 while (0 < size--) {
260 ch = *data++;
261 if (ch == '\n') {
262 count++;
263 nl_just_seen = 1;
264 completely_empty = 0;
266 else {
267 nl_just_seen = 0;
268 completely_empty = 0;
271 if (completely_empty)
272 return 0;
273 if (!nl_just_seen)
274 count++; /* no trailing newline */
275 return count;
278 static void print_line_count(FILE *file, int count)
280 switch (count) {
281 case 0:
282 fprintf(file, "0,0");
283 break;
284 case 1:
285 fprintf(file, "1");
286 break;
287 default:
288 fprintf(file, "1,%d", count);
289 break;
293 static void copy_file_with_prefix(FILE *file,
294 int prefix, const char *data, int size,
295 const char *set, const char *reset)
297 int ch, nl_just_seen = 1;
298 while (0 < size--) {
299 ch = *data++;
300 if (nl_just_seen) {
301 fputs(set, file);
302 putc(prefix, file);
304 if (ch == '\n') {
305 nl_just_seen = 1;
306 fputs(reset, file);
307 } else
308 nl_just_seen = 0;
309 putc(ch, file);
311 if (!nl_just_seen)
312 fprintf(file, "%s\n\\ No newline at end of file\n", reset);
315 static void emit_rewrite_diff(const char *name_a,
316 const char *name_b,
317 struct diff_filespec *one,
318 struct diff_filespec *two,
319 struct diff_options *o)
321 int lc_a, lc_b;
322 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
323 const char *name_a_tab, *name_b_tab;
324 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
325 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
326 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
327 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
328 const char *reset = diff_get_color(color_diff, DIFF_RESET);
329 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
330 const char *a_prefix, *b_prefix;
332 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
333 a_prefix = o->b_prefix;
334 b_prefix = o->a_prefix;
335 } else {
336 a_prefix = o->a_prefix;
337 b_prefix = o->b_prefix;
340 name_a += (*name_a == '/');
341 name_b += (*name_b == '/');
342 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
343 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
345 strbuf_reset(&a_name);
346 strbuf_reset(&b_name);
347 quote_two_c_style(&a_name, a_prefix, name_a, 0);
348 quote_two_c_style(&b_name, b_prefix, name_b, 0);
350 diff_populate_filespec(one, 0);
351 diff_populate_filespec(two, 0);
352 lc_a = count_lines(one->data, one->size);
353 lc_b = count_lines(two->data, two->size);
354 fprintf(o->file,
355 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
356 metainfo, a_name.buf, name_a_tab, reset,
357 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
358 print_line_count(o->file, lc_a);
359 fprintf(o->file, " +");
360 print_line_count(o->file, lc_b);
361 fprintf(o->file, " @@%s\n", reset);
362 if (lc_a)
363 copy_file_with_prefix(o->file, '-', one->data, one->size, old, reset);
364 if (lc_b)
365 copy_file_with_prefix(o->file, '+', two->data, two->size, new, reset);
368 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
370 if (!DIFF_FILE_VALID(one)) {
371 mf->ptr = (char *)""; /* does not matter */
372 mf->size = 0;
373 return 0;
375 else if (diff_populate_filespec(one, 0))
376 return -1;
377 mf->ptr = one->data;
378 mf->size = one->size;
379 return 0;
382 struct diff_words_buffer {
383 mmfile_t text;
384 long alloc;
385 long current; /* output pointer */
386 int suppressed_newline;
389 static void diff_words_append(char *line, unsigned long len,
390 struct diff_words_buffer *buffer)
392 if (buffer->text.size + len > buffer->alloc) {
393 buffer->alloc = (buffer->text.size + len) * 3 / 2;
394 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
396 line++;
397 len--;
398 memcpy(buffer->text.ptr + buffer->text.size, line, len);
399 buffer->text.size += len;
402 struct diff_words_data {
403 struct diff_words_buffer minus, plus;
404 FILE *file;
407 static void print_word(FILE *file, struct diff_words_buffer *buffer, int len, int color,
408 int suppress_newline)
410 const char *ptr;
411 int eol = 0;
413 if (len == 0)
414 return;
416 ptr = buffer->text.ptr + buffer->current;
417 buffer->current += len;
419 if (ptr[len - 1] == '\n') {
420 eol = 1;
421 len--;
424 fputs(diff_get_color(1, color), file);
425 fwrite(ptr, len, 1, file);
426 fputs(diff_get_color(1, DIFF_RESET), file);
428 if (eol) {
429 if (suppress_newline)
430 buffer->suppressed_newline = 1;
431 else
432 putc('\n', file);
436 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
438 struct diff_words_data *diff_words = priv;
440 if (diff_words->minus.suppressed_newline) {
441 if (line[0] != '+')
442 putc('\n', diff_words->file);
443 diff_words->minus.suppressed_newline = 0;
446 len--;
447 switch (line[0]) {
448 case '-':
449 print_word(diff_words->file,
450 &diff_words->minus, len, DIFF_FILE_OLD, 1);
451 break;
452 case '+':
453 print_word(diff_words->file,
454 &diff_words->plus, len, DIFF_FILE_NEW, 0);
455 break;
456 case ' ':
457 print_word(diff_words->file,
458 &diff_words->plus, len, DIFF_PLAIN, 0);
459 diff_words->minus.current += len;
460 break;
464 /* this executes the word diff on the accumulated buffers */
465 static void diff_words_show(struct diff_words_data *diff_words)
467 xpparam_t xpp;
468 xdemitconf_t xecfg;
469 xdemitcb_t ecb;
470 mmfile_t minus, plus;
471 int i;
473 memset(&xpp, 0, sizeof(xpp));
474 memset(&xecfg, 0, sizeof(xecfg));
475 minus.size = diff_words->minus.text.size;
476 minus.ptr = xmalloc(minus.size);
477 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
478 for (i = 0; i < minus.size; i++)
479 if (isspace(minus.ptr[i]))
480 minus.ptr[i] = '\n';
481 diff_words->minus.current = 0;
483 plus.size = diff_words->plus.text.size;
484 plus.ptr = xmalloc(plus.size);
485 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
486 for (i = 0; i < plus.size; i++)
487 if (isspace(plus.ptr[i]))
488 plus.ptr[i] = '\n';
489 diff_words->plus.current = 0;
491 xpp.flags = XDF_NEED_MINIMAL;
492 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
493 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
494 &xpp, &xecfg, &ecb);
495 free(minus.ptr);
496 free(plus.ptr);
497 diff_words->minus.text.size = diff_words->plus.text.size = 0;
499 if (diff_words->minus.suppressed_newline) {
500 putc('\n', diff_words->file);
501 diff_words->minus.suppressed_newline = 0;
505 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
507 struct emit_callback {
508 int nparents, color_diff;
509 unsigned ws_rule;
510 sane_truncate_fn truncate;
511 const char **label_path;
512 struct diff_words_data *diff_words;
513 int *found_changesp;
514 FILE *file;
517 static void free_diff_words_data(struct emit_callback *ecbdata)
519 if (ecbdata->diff_words) {
520 /* flush buffers */
521 if (ecbdata->diff_words->minus.text.size ||
522 ecbdata->diff_words->plus.text.size)
523 diff_words_show(ecbdata->diff_words);
525 free (ecbdata->diff_words->minus.text.ptr);
526 free (ecbdata->diff_words->plus.text.ptr);
527 free(ecbdata->diff_words);
528 ecbdata->diff_words = NULL;
532 const char *diff_get_color(int diff_use_color, enum color_diff ix)
534 if (diff_use_color)
535 return diff_colors[ix];
536 return "";
539 static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
541 int has_trailing_newline, has_trailing_carriage_return;
543 has_trailing_newline = (len > 0 && line[len-1] == '\n');
544 if (has_trailing_newline)
545 len--;
546 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
547 if (has_trailing_carriage_return)
548 len--;
550 fputs(set, file);
551 fwrite(line, len, 1, file);
552 fputs(reset, file);
553 if (has_trailing_carriage_return)
554 fputc('\r', file);
555 if (has_trailing_newline)
556 fputc('\n', file);
559 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
561 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
562 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
564 if (!*ws)
565 emit_line(ecbdata->file, set, reset, line, len);
566 else {
567 /* Emit just the prefix, then the rest. */
568 emit_line(ecbdata->file, set, reset, line, ecbdata->nparents);
569 ws_check_emit(line + ecbdata->nparents,
570 len - ecbdata->nparents, ecbdata->ws_rule,
571 ecbdata->file, set, reset, ws);
575 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
577 const char *cp;
578 unsigned long allot;
579 size_t l = len;
581 if (ecb->truncate)
582 return ecb->truncate(line, len);
583 cp = line;
584 allot = l;
585 while (0 < l) {
586 (void) utf8_width(&cp, &l);
587 if (!cp)
588 break; /* truncated in the middle? */
590 return allot - l;
593 static void fn_out_consume(void *priv, char *line, unsigned long len)
595 int i;
596 int color;
597 struct emit_callback *ecbdata = priv;
598 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
599 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
600 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
602 *(ecbdata->found_changesp) = 1;
604 if (ecbdata->label_path[0]) {
605 const char *name_a_tab, *name_b_tab;
607 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
608 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
610 fprintf(ecbdata->file, "%s--- %s%s%s\n",
611 meta, ecbdata->label_path[0], reset, name_a_tab);
612 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
613 meta, ecbdata->label_path[1], reset, name_b_tab);
614 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
617 if (diff_suppress_blank_empty
618 && len == 2 && line[0] == ' ' && line[1] == '\n') {
619 line[0] = '\n';
620 len = 1;
623 /* This is not really necessary for now because
624 * this codepath only deals with two-way diffs.
626 for (i = 0; i < len && line[i] == '@'; i++)
628 if (2 <= i && i < len && line[i] == ' ') {
629 ecbdata->nparents = i - 1;
630 len = sane_truncate_line(ecbdata, line, len);
631 emit_line(ecbdata->file,
632 diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
633 reset, line, len);
634 if (line[len-1] != '\n')
635 putc('\n', ecbdata->file);
636 return;
639 if (len < ecbdata->nparents) {
640 emit_line(ecbdata->file, reset, reset, line, len);
641 return;
644 color = DIFF_PLAIN;
645 if (ecbdata->diff_words && ecbdata->nparents != 1)
646 /* fall back to normal diff */
647 free_diff_words_data(ecbdata);
648 if (ecbdata->diff_words) {
649 if (line[0] == '-') {
650 diff_words_append(line, len,
651 &ecbdata->diff_words->minus);
652 return;
653 } else if (line[0] == '+') {
654 diff_words_append(line, len,
655 &ecbdata->diff_words->plus);
656 return;
658 if (ecbdata->diff_words->minus.text.size ||
659 ecbdata->diff_words->plus.text.size)
660 diff_words_show(ecbdata->diff_words);
661 line++;
662 len--;
663 emit_line(ecbdata->file, plain, reset, line, len);
664 return;
666 for (i = 0; i < ecbdata->nparents && len; i++) {
667 if (line[i] == '-')
668 color = DIFF_FILE_OLD;
669 else if (line[i] == '+')
670 color = DIFF_FILE_NEW;
673 if (color != DIFF_FILE_NEW) {
674 emit_line(ecbdata->file,
675 diff_get_color(ecbdata->color_diff, color),
676 reset, line, len);
677 return;
679 emit_add_line(reset, ecbdata, line, len);
682 static char *pprint_rename(const char *a, const char *b)
684 const char *old = a;
685 const char *new = b;
686 struct strbuf name = STRBUF_INIT;
687 int pfx_length, sfx_length;
688 int len_a = strlen(a);
689 int len_b = strlen(b);
690 int a_midlen, b_midlen;
691 int qlen_a = quote_c_style(a, NULL, NULL, 0);
692 int qlen_b = quote_c_style(b, NULL, NULL, 0);
694 if (qlen_a || qlen_b) {
695 quote_c_style(a, &name, NULL, 0);
696 strbuf_addstr(&name, " => ");
697 quote_c_style(b, &name, NULL, 0);
698 return strbuf_detach(&name, NULL);
701 /* Find common prefix */
702 pfx_length = 0;
703 while (*old && *new && *old == *new) {
704 if (*old == '/')
705 pfx_length = old - a + 1;
706 old++;
707 new++;
710 /* Find common suffix */
711 old = a + len_a;
712 new = b + len_b;
713 sfx_length = 0;
714 while (a <= old && b <= new && *old == *new) {
715 if (*old == '/')
716 sfx_length = len_a - (old - a);
717 old--;
718 new--;
722 * pfx{mid-a => mid-b}sfx
723 * {pfx-a => pfx-b}sfx
724 * pfx{sfx-a => sfx-b}
725 * name-a => name-b
727 a_midlen = len_a - pfx_length - sfx_length;
728 b_midlen = len_b - pfx_length - sfx_length;
729 if (a_midlen < 0)
730 a_midlen = 0;
731 if (b_midlen < 0)
732 b_midlen = 0;
734 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
735 if (pfx_length + sfx_length) {
736 strbuf_add(&name, a, pfx_length);
737 strbuf_addch(&name, '{');
739 strbuf_add(&name, a + pfx_length, a_midlen);
740 strbuf_addstr(&name, " => ");
741 strbuf_add(&name, b + pfx_length, b_midlen);
742 if (pfx_length + sfx_length) {
743 strbuf_addch(&name, '}');
744 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
746 return strbuf_detach(&name, NULL);
749 struct diffstat_t {
750 int nr;
751 int alloc;
752 struct diffstat_file {
753 char *from_name;
754 char *name;
755 char *print_name;
756 unsigned is_unmerged:1;
757 unsigned is_binary:1;
758 unsigned is_renamed:1;
759 unsigned int added, deleted;
760 } **files;
763 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
764 const char *name_a,
765 const char *name_b)
767 struct diffstat_file *x;
768 x = xcalloc(sizeof (*x), 1);
769 if (diffstat->nr == diffstat->alloc) {
770 diffstat->alloc = alloc_nr(diffstat->alloc);
771 diffstat->files = xrealloc(diffstat->files,
772 diffstat->alloc * sizeof(x));
774 diffstat->files[diffstat->nr++] = x;
775 if (name_b) {
776 x->from_name = xstrdup(name_a);
777 x->name = xstrdup(name_b);
778 x->is_renamed = 1;
780 else {
781 x->from_name = NULL;
782 x->name = xstrdup(name_a);
784 return x;
787 static void diffstat_consume(void *priv, char *line, unsigned long len)
789 struct diffstat_t *diffstat = priv;
790 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
792 if (line[0] == '+')
793 x->added++;
794 else if (line[0] == '-')
795 x->deleted++;
798 const char mime_boundary_leader[] = "------------";
800 static int scale_linear(int it, int width, int max_change)
803 * make sure that at least one '-' is printed if there were deletions,
804 * and likewise for '+'.
806 if (max_change < 2)
807 return it;
808 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
811 static void show_name(FILE *file,
812 const char *prefix, const char *name, int len,
813 const char *reset, const char *set)
815 fprintf(file, " %s%s%-*s%s |", set, prefix, len, name, reset);
818 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
820 if (cnt <= 0)
821 return;
822 fprintf(file, "%s", set);
823 while (cnt--)
824 putc(ch, file);
825 fprintf(file, "%s", reset);
828 static void fill_print_name(struct diffstat_file *file)
830 char *pname;
832 if (file->print_name)
833 return;
835 if (!file->is_renamed) {
836 struct strbuf buf = STRBUF_INIT;
837 if (quote_c_style(file->name, &buf, NULL, 0)) {
838 pname = strbuf_detach(&buf, NULL);
839 } else {
840 pname = file->name;
841 strbuf_release(&buf);
843 } else {
844 pname = pprint_rename(file->from_name, file->name);
846 file->print_name = pname;
849 static void show_stats(struct diffstat_t* data, struct diff_options *options)
851 int i, len, add, del, total, adds = 0, dels = 0;
852 int max_change = 0, max_len = 0;
853 int total_files = data->nr;
854 int width, name_width;
855 const char *reset, *set, *add_c, *del_c;
857 if (data->nr == 0)
858 return;
860 width = options->stat_width ? options->stat_width : 80;
861 name_width = options->stat_name_width ? options->stat_name_width : 50;
863 /* Sanity: give at least 5 columns to the graph,
864 * but leave at least 10 columns for the name.
866 if (width < 25)
867 width = 25;
868 if (name_width < 10)
869 name_width = 10;
870 else if (width < name_width + 15)
871 name_width = width - 15;
873 /* Find the longest filename and max number of changes */
874 reset = diff_get_color_opt(options, DIFF_RESET);
875 set = diff_get_color_opt(options, DIFF_PLAIN);
876 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
877 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
879 for (i = 0; i < data->nr; i++) {
880 struct diffstat_file *file = data->files[i];
881 int change = file->added + file->deleted;
882 fill_print_name(file);
883 len = strlen(file->print_name);
884 if (max_len < len)
885 max_len = len;
887 if (file->is_binary || file->is_unmerged)
888 continue;
889 if (max_change < change)
890 max_change = change;
893 /* Compute the width of the graph part;
894 * 10 is for one blank at the beginning of the line plus
895 * " | count " between the name and the graph.
897 * From here on, name_width is the width of the name area,
898 * and width is the width of the graph area.
900 name_width = (name_width < max_len) ? name_width : max_len;
901 if (width < (name_width + 10) + max_change)
902 width = width - (name_width + 10);
903 else
904 width = max_change;
906 for (i = 0; i < data->nr; i++) {
907 const char *prefix = "";
908 char *name = data->files[i]->print_name;
909 int added = data->files[i]->added;
910 int deleted = data->files[i]->deleted;
911 int name_len;
914 * "scale" the filename
916 len = name_width;
917 name_len = strlen(name);
918 if (name_width < name_len) {
919 char *slash;
920 prefix = "...";
921 len -= 3;
922 name += name_len - len;
923 slash = strchr(name, '/');
924 if (slash)
925 name = slash;
928 if (data->files[i]->is_binary) {
929 show_name(options->file, prefix, name, len, reset, set);
930 fprintf(options->file, " Bin ");
931 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
932 fprintf(options->file, " -> ");
933 fprintf(options->file, "%s%d%s", add_c, added, reset);
934 fprintf(options->file, " bytes");
935 fprintf(options->file, "\n");
936 continue;
938 else if (data->files[i]->is_unmerged) {
939 show_name(options->file, prefix, name, len, reset, set);
940 fprintf(options->file, " Unmerged\n");
941 continue;
943 else if (!data->files[i]->is_renamed &&
944 (added + deleted == 0)) {
945 total_files--;
946 continue;
950 * scale the add/delete
952 add = added;
953 del = deleted;
954 total = add + del;
955 adds += add;
956 dels += del;
958 if (width <= max_change) {
959 add = scale_linear(add, width, max_change);
960 del = scale_linear(del, width, max_change);
961 total = add + del;
963 show_name(options->file, prefix, name, len, reset, set);
964 fprintf(options->file, "%5d%s", added + deleted,
965 added + deleted ? " " : "");
966 show_graph(options->file, '+', add, add_c, reset);
967 show_graph(options->file, '-', del, del_c, reset);
968 fprintf(options->file, "\n");
970 fprintf(options->file,
971 "%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
972 set, total_files, adds, dels, reset);
975 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
977 int i, adds = 0, dels = 0, total_files = data->nr;
979 if (data->nr == 0)
980 return;
982 for (i = 0; i < data->nr; i++) {
983 if (!data->files[i]->is_binary &&
984 !data->files[i]->is_unmerged) {
985 int added = data->files[i]->added;
986 int deleted= data->files[i]->deleted;
987 if (!data->files[i]->is_renamed &&
988 (added + deleted == 0)) {
989 total_files--;
990 } else {
991 adds += added;
992 dels += deleted;
996 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
997 total_files, adds, dels);
1000 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
1002 int i;
1004 if (data->nr == 0)
1005 return;
1007 for (i = 0; i < data->nr; i++) {
1008 struct diffstat_file *file = data->files[i];
1010 if (file->is_binary)
1011 fprintf(options->file, "-\t-\t");
1012 else
1013 fprintf(options->file,
1014 "%d\t%d\t", file->added, file->deleted);
1015 if (options->line_termination) {
1016 fill_print_name(file);
1017 if (!file->is_renamed)
1018 write_name_quoted(file->name, options->file,
1019 options->line_termination);
1020 else {
1021 fputs(file->print_name, options->file);
1022 putc(options->line_termination, options->file);
1024 } else {
1025 if (file->is_renamed) {
1026 putc('\0', options->file);
1027 write_name_quoted(file->from_name, options->file, '\0');
1029 write_name_quoted(file->name, options->file, '\0');
1034 struct dirstat_file {
1035 const char *name;
1036 unsigned long changed;
1039 struct dirstat_dir {
1040 struct dirstat_file *files;
1041 int alloc, nr, percent, cumulative;
1044 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1046 unsigned long this_dir = 0;
1047 unsigned int sources = 0;
1049 while (dir->nr) {
1050 struct dirstat_file *f = dir->files;
1051 int namelen = strlen(f->name);
1052 unsigned long this;
1053 char *slash;
1055 if (namelen < baselen)
1056 break;
1057 if (memcmp(f->name, base, baselen))
1058 break;
1059 slash = strchr(f->name + baselen, '/');
1060 if (slash) {
1061 int newbaselen = slash + 1 - f->name;
1062 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1063 sources++;
1064 } else {
1065 this = f->changed;
1066 dir->files++;
1067 dir->nr--;
1068 sources += 2;
1070 this_dir += this;
1074 * We don't report dirstat's for
1075 * - the top level
1076 * - or cases where everything came from a single directory
1077 * under this directory (sources == 1).
1079 if (baselen && sources != 1) {
1080 int permille = this_dir * 1000 / changed;
1081 if (permille) {
1082 int percent = permille / 10;
1083 if (percent >= dir->percent) {
1084 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1085 if (!dir->cumulative)
1086 return 0;
1090 return this_dir;
1093 static int dirstat_compare(const void *_a, const void *_b)
1095 const struct dirstat_file *a = _a;
1096 const struct dirstat_file *b = _b;
1097 return strcmp(a->name, b->name);
1100 static void show_dirstat(struct diff_options *options)
1102 int i;
1103 unsigned long changed;
1104 struct dirstat_dir dir;
1105 struct diff_queue_struct *q = &diff_queued_diff;
1107 dir.files = NULL;
1108 dir.alloc = 0;
1109 dir.nr = 0;
1110 dir.percent = options->dirstat_percent;
1111 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1113 changed = 0;
1114 for (i = 0; i < q->nr; i++) {
1115 struct diff_filepair *p = q->queue[i];
1116 const char *name;
1117 unsigned long copied, added, damage;
1119 name = p->one->path ? p->one->path : p->two->path;
1121 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1122 diff_populate_filespec(p->one, 0);
1123 diff_populate_filespec(p->two, 0);
1124 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1125 &copied, &added);
1126 diff_free_filespec_data(p->one);
1127 diff_free_filespec_data(p->two);
1128 } else if (DIFF_FILE_VALID(p->one)) {
1129 diff_populate_filespec(p->one, 1);
1130 copied = added = 0;
1131 diff_free_filespec_data(p->one);
1132 } else if (DIFF_FILE_VALID(p->two)) {
1133 diff_populate_filespec(p->two, 1);
1134 copied = 0;
1135 added = p->two->size;
1136 diff_free_filespec_data(p->two);
1137 } else
1138 continue;
1141 * Original minus copied is the removed material,
1142 * added is the new material. They are both damages
1143 * made to the preimage. In --dirstat-by-file mode, count
1144 * damaged files, not damaged lines. This is done by
1145 * counting only a single damaged line per file.
1147 damage = (p->one->size - copied) + added;
1148 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1149 damage = 1;
1151 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1152 dir.files[dir.nr].name = name;
1153 dir.files[dir.nr].changed = damage;
1154 changed += damage;
1155 dir.nr++;
1158 /* This can happen even with many files, if everything was renames */
1159 if (!changed)
1160 return;
1162 /* Show all directories with more than x% of the changes */
1163 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1164 gather_dirstat(options->file, &dir, changed, "", 0);
1167 static void free_diffstat_info(struct diffstat_t *diffstat)
1169 int i;
1170 for (i = 0; i < diffstat->nr; i++) {
1171 struct diffstat_file *f = diffstat->files[i];
1172 if (f->name != f->print_name)
1173 free(f->print_name);
1174 free(f->name);
1175 free(f->from_name);
1176 free(f);
1178 free(diffstat->files);
1181 struct checkdiff_t {
1182 const char *filename;
1183 int lineno;
1184 struct diff_options *o;
1185 unsigned ws_rule;
1186 unsigned status;
1187 int trailing_blanks_start;
1190 static int is_conflict_marker(const char *line, unsigned long len)
1192 char firstchar;
1193 int cnt;
1195 if (len < 8)
1196 return 0;
1197 firstchar = line[0];
1198 switch (firstchar) {
1199 case '=': case '>': case '<':
1200 break;
1201 default:
1202 return 0;
1204 for (cnt = 1; cnt < 7; cnt++)
1205 if (line[cnt] != firstchar)
1206 return 0;
1207 /* line[0] thru line[6] are same as firstchar */
1208 if (firstchar == '=') {
1209 /* divider between ours and theirs? */
1210 if (len != 8 || line[7] != '\n')
1211 return 0;
1212 } else if (len < 8 || !isspace(line[7])) {
1213 /* not divider before ours nor after theirs */
1214 return 0;
1216 return 1;
1219 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1221 struct checkdiff_t *data = priv;
1222 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1223 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1224 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1225 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1226 char *err;
1228 if (line[0] == '+') {
1229 unsigned bad;
1230 data->lineno++;
1231 if (!ws_blank_line(line + 1, len - 1, data->ws_rule))
1232 data->trailing_blanks_start = 0;
1233 else if (!data->trailing_blanks_start)
1234 data->trailing_blanks_start = data->lineno;
1235 if (is_conflict_marker(line + 1, len - 1)) {
1236 data->status |= 1;
1237 fprintf(data->o->file,
1238 "%s:%d: leftover conflict marker\n",
1239 data->filename, data->lineno);
1241 bad = ws_check(line + 1, len - 1, data->ws_rule);
1242 if (!bad)
1243 return;
1244 data->status |= bad;
1245 err = whitespace_error_string(bad);
1246 fprintf(data->o->file, "%s:%d: %s.\n",
1247 data->filename, data->lineno, err);
1248 free(err);
1249 emit_line(data->o->file, set, reset, line, 1);
1250 ws_check_emit(line + 1, len - 1, data->ws_rule,
1251 data->o->file, set, reset, ws);
1252 } else if (line[0] == ' ') {
1253 data->lineno++;
1254 data->trailing_blanks_start = 0;
1255 } else if (line[0] == '@') {
1256 char *plus = strchr(line, '+');
1257 if (plus)
1258 data->lineno = strtol(plus, NULL, 10) - 1;
1259 else
1260 die("invalid diff");
1261 data->trailing_blanks_start = 0;
1265 static unsigned char *deflate_it(char *data,
1266 unsigned long size,
1267 unsigned long *result_size)
1269 int bound;
1270 unsigned char *deflated;
1271 z_stream stream;
1273 memset(&stream, 0, sizeof(stream));
1274 deflateInit(&stream, zlib_compression_level);
1275 bound = deflateBound(&stream, size);
1276 deflated = xmalloc(bound);
1277 stream.next_out = deflated;
1278 stream.avail_out = bound;
1280 stream.next_in = (unsigned char *)data;
1281 stream.avail_in = size;
1282 while (deflate(&stream, Z_FINISH) == Z_OK)
1283 ; /* nothing */
1284 deflateEnd(&stream);
1285 *result_size = stream.total_out;
1286 return deflated;
1289 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1291 void *cp;
1292 void *delta;
1293 void *deflated;
1294 void *data;
1295 unsigned long orig_size;
1296 unsigned long delta_size;
1297 unsigned long deflate_size;
1298 unsigned long data_size;
1300 /* We could do deflated delta, or we could do just deflated two,
1301 * whichever is smaller.
1303 delta = NULL;
1304 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1305 if (one->size && two->size) {
1306 delta = diff_delta(one->ptr, one->size,
1307 two->ptr, two->size,
1308 &delta_size, deflate_size);
1309 if (delta) {
1310 void *to_free = delta;
1311 orig_size = delta_size;
1312 delta = deflate_it(delta, delta_size, &delta_size);
1313 free(to_free);
1317 if (delta && delta_size < deflate_size) {
1318 fprintf(file, "delta %lu\n", orig_size);
1319 free(deflated);
1320 data = delta;
1321 data_size = delta_size;
1323 else {
1324 fprintf(file, "literal %lu\n", two->size);
1325 free(delta);
1326 data = deflated;
1327 data_size = deflate_size;
1330 /* emit data encoded in base85 */
1331 cp = data;
1332 while (data_size) {
1333 int bytes = (52 < data_size) ? 52 : data_size;
1334 char line[70];
1335 data_size -= bytes;
1336 if (bytes <= 26)
1337 line[0] = bytes + 'A' - 1;
1338 else
1339 line[0] = bytes - 26 + 'a' - 1;
1340 encode_85(line + 1, cp, bytes);
1341 cp = (char *) cp + bytes;
1342 fputs(line, file);
1343 fputc('\n', file);
1345 fprintf(file, "\n");
1346 free(data);
1349 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1351 fprintf(file, "GIT binary patch\n");
1352 emit_binary_diff_body(file, one, two);
1353 emit_binary_diff_body(file, two, one);
1356 static void setup_diff_attr_check(struct git_attr_check *check)
1358 static struct git_attr *attr_diff;
1360 if (!attr_diff) {
1361 attr_diff = git_attr("diff", 4);
1363 check[0].attr = attr_diff;
1366 static void diff_filespec_check_attr(struct diff_filespec *one)
1368 struct git_attr_check attr_diff_check;
1369 int check_from_data = 0;
1371 if (one->checked_attr)
1372 return;
1374 setup_diff_attr_check(&attr_diff_check);
1375 one->is_binary = 0;
1376 one->funcname_pattern_ident = NULL;
1378 if (!git_checkattr(one->path, 1, &attr_diff_check)) {
1379 const char *value;
1381 /* binaryness */
1382 value = attr_diff_check.value;
1383 if (ATTR_TRUE(value))
1385 else if (ATTR_FALSE(value))
1386 one->is_binary = 1;
1387 else
1388 check_from_data = 1;
1390 /* funcname pattern ident */
1391 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1393 else
1394 one->funcname_pattern_ident = value;
1397 if (check_from_data) {
1398 if (!one->data && DIFF_FILE_VALID(one))
1399 diff_populate_filespec(one, 0);
1401 if (one->data)
1402 one->is_binary = buffer_is_binary(one->data, one->size);
1406 int diff_filespec_is_binary(struct diff_filespec *one)
1408 diff_filespec_check_attr(one);
1409 return one->is_binary;
1412 static const struct funcname_pattern_entry *funcname_pattern(const char *ident)
1414 struct funcname_pattern_list *pp;
1416 for (pp = funcname_pattern_list; pp; pp = pp->next)
1417 if (!strcmp(ident, pp->e.name))
1418 return &pp->e;
1419 return NULL;
1422 static const struct funcname_pattern_entry builtin_funcname_pattern[] = {
1423 { "bibtex", "(@[a-zA-Z]{1,}[ \t]*\\{{0,1}[ \t]*[^ \t\"@',\\#}{~%]*).*$",
1424 REG_EXTENDED },
1425 { "html", "^[ \t]*(<[Hh][1-6][ \t].*>.*)$", REG_EXTENDED },
1426 { "java",
1427 "!^[ \t]*(catch|do|for|if|instanceof|new|return|switch|throw|while)\n"
1428 "^[ \t]*(([ \t]*[A-Za-z_][A-Za-z_0-9]*){2,}[ \t]*\\([^;]*)$",
1429 REG_EXTENDED },
1430 { "objc",
1431 /* Negate C statements that can look like functions */
1432 "!^[ \t]*(do|for|if|else|return|switch|while)\n"
1433 /* Objective-C methods */
1434 "^[ \t]*([-+][ \t]*\\([ \t]*[A-Za-z_][A-Za-z_0-9* \t]*\\)[ \t]*[A-Za-z_].*)$\n"
1435 /* C functions */
1436 "^[ \t]*(([ \t]*[A-Za-z_][A-Za-z_0-9]*){2,}[ \t]*\\([^;]*)$\n"
1437 /* Objective-C class/protocol definitions */
1438 "^(@(implementation|interface|protocol)[ \t].*)$",
1439 REG_EXTENDED },
1440 { "pascal",
1441 "^((procedure|function|constructor|destructor|interface|"
1442 "implementation|initialization|finalization)[ \t]*.*)$"
1443 "\n"
1444 "^(.*=[ \t]*(class|record).*)$",
1445 REG_EXTENDED },
1446 { "php", "^[\t ]*((function|class).*)", REG_EXTENDED },
1447 { "python", "^[ \t]*((class|def)[ \t].*)$", REG_EXTENDED },
1448 { "ruby", "^[ \t]*((class|module|def)[ \t].*)$",
1449 REG_EXTENDED },
1450 { "tex",
1451 "^(\\\\((sub)*section|chapter|part)\\*{0,1}\\{.*)$",
1452 REG_EXTENDED },
1455 static const struct funcname_pattern_entry *diff_funcname_pattern(struct diff_filespec *one)
1457 const char *ident;
1458 const struct funcname_pattern_entry *pe;
1459 int i;
1461 diff_filespec_check_attr(one);
1462 ident = one->funcname_pattern_ident;
1464 if (!ident)
1466 * If the config file has "funcname.default" defined, that
1467 * regexp is used; otherwise NULL is returned and xemit uses
1468 * the built-in default.
1470 return funcname_pattern("default");
1472 /* Look up custom "funcname.$ident" regexp from config. */
1473 pe = funcname_pattern(ident);
1474 if (pe)
1475 return pe;
1478 * And define built-in fallback patterns here. Note that
1479 * these can be overridden by the user's config settings.
1481 for (i = 0; i < ARRAY_SIZE(builtin_funcname_pattern); i++)
1482 if (!strcmp(ident, builtin_funcname_pattern[i].name))
1483 return &builtin_funcname_pattern[i];
1485 return NULL;
1488 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1490 if (!options->a_prefix)
1491 options->a_prefix = a;
1492 if (!options->b_prefix)
1493 options->b_prefix = b;
1496 static void builtin_diff(const char *name_a,
1497 const char *name_b,
1498 struct diff_filespec *one,
1499 struct diff_filespec *two,
1500 const char *xfrm_msg,
1501 struct diff_options *o,
1502 int complete_rewrite)
1504 mmfile_t mf1, mf2;
1505 const char *lbl[2];
1506 char *a_one, *b_two;
1507 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1508 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1509 const char *a_prefix, *b_prefix;
1511 diff_set_mnemonic_prefix(o, "a/", "b/");
1512 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1513 a_prefix = o->b_prefix;
1514 b_prefix = o->a_prefix;
1515 } else {
1516 a_prefix = o->a_prefix;
1517 b_prefix = o->b_prefix;
1520 /* Never use a non-valid filename anywhere if at all possible */
1521 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1522 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1524 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1525 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1526 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1527 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1528 fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1529 if (lbl[0][0] == '/') {
1530 /* /dev/null */
1531 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1532 if (xfrm_msg && xfrm_msg[0])
1533 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1535 else if (lbl[1][0] == '/') {
1536 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1537 if (xfrm_msg && xfrm_msg[0])
1538 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1540 else {
1541 if (one->mode != two->mode) {
1542 fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1543 fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1545 if (xfrm_msg && xfrm_msg[0])
1546 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1548 * we do not run diff between different kind
1549 * of objects.
1551 if ((one->mode ^ two->mode) & S_IFMT)
1552 goto free_ab_and_return;
1553 if (complete_rewrite) {
1554 emit_rewrite_diff(name_a, name_b, one, two, o);
1555 o->found_changes = 1;
1556 goto free_ab_and_return;
1560 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1561 die("unable to read files to diff");
1563 if (!DIFF_OPT_TST(o, TEXT) &&
1564 (diff_filespec_is_binary(one) || diff_filespec_is_binary(two))) {
1565 /* Quite common confusing case */
1566 if (mf1.size == mf2.size &&
1567 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1568 goto free_ab_and_return;
1569 if (DIFF_OPT_TST(o, BINARY))
1570 emit_binary_diff(o->file, &mf1, &mf2);
1571 else
1572 fprintf(o->file, "Binary files %s and %s differ\n",
1573 lbl[0], lbl[1]);
1574 o->found_changes = 1;
1576 else {
1577 /* Crazy xdl interfaces.. */
1578 const char *diffopts = getenv("GIT_DIFF_OPTS");
1579 xpparam_t xpp;
1580 xdemitconf_t xecfg;
1581 xdemitcb_t ecb;
1582 struct emit_callback ecbdata;
1583 const struct funcname_pattern_entry *pe;
1585 pe = diff_funcname_pattern(one);
1586 if (!pe)
1587 pe = diff_funcname_pattern(two);
1589 memset(&xpp, 0, sizeof(xpp));
1590 memset(&xecfg, 0, sizeof(xecfg));
1591 memset(&ecbdata, 0, sizeof(ecbdata));
1592 ecbdata.label_path = lbl;
1593 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1594 ecbdata.found_changesp = &o->found_changes;
1595 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1596 ecbdata.file = o->file;
1597 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1598 xecfg.ctxlen = o->context;
1599 xecfg.flags = XDL_EMIT_FUNCNAMES;
1600 if (pe)
1601 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1602 if (!diffopts)
1604 else if (!prefixcmp(diffopts, "--unified="))
1605 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1606 else if (!prefixcmp(diffopts, "-u"))
1607 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1608 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1609 ecbdata.diff_words =
1610 xcalloc(1, sizeof(struct diff_words_data));
1611 ecbdata.diff_words->file = o->file;
1613 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1614 &xpp, &xecfg, &ecb);
1615 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1616 free_diff_words_data(&ecbdata);
1619 free_ab_and_return:
1620 diff_free_filespec_data(one);
1621 diff_free_filespec_data(two);
1622 free(a_one);
1623 free(b_two);
1624 return;
1627 static void builtin_diffstat(const char *name_a, const char *name_b,
1628 struct diff_filespec *one,
1629 struct diff_filespec *two,
1630 struct diffstat_t *diffstat,
1631 struct diff_options *o,
1632 int complete_rewrite)
1634 mmfile_t mf1, mf2;
1635 struct diffstat_file *data;
1637 data = diffstat_add(diffstat, name_a, name_b);
1639 if (!one || !two) {
1640 data->is_unmerged = 1;
1641 return;
1643 if (complete_rewrite) {
1644 diff_populate_filespec(one, 0);
1645 diff_populate_filespec(two, 0);
1646 data->deleted = count_lines(one->data, one->size);
1647 data->added = count_lines(two->data, two->size);
1648 goto free_and_return;
1650 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1651 die("unable to read files to diff");
1653 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1654 data->is_binary = 1;
1655 data->added = mf2.size;
1656 data->deleted = mf1.size;
1657 } else {
1658 /* Crazy xdl interfaces.. */
1659 xpparam_t xpp;
1660 xdemitconf_t xecfg;
1661 xdemitcb_t ecb;
1663 memset(&xpp, 0, sizeof(xpp));
1664 memset(&xecfg, 0, sizeof(xecfg));
1665 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1666 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1667 &xpp, &xecfg, &ecb);
1670 free_and_return:
1671 diff_free_filespec_data(one);
1672 diff_free_filespec_data(two);
1675 static void builtin_checkdiff(const char *name_a, const char *name_b,
1676 const char *attr_path,
1677 struct diff_filespec *one,
1678 struct diff_filespec *two,
1679 struct diff_options *o)
1681 mmfile_t mf1, mf2;
1682 struct checkdiff_t data;
1684 if (!two)
1685 return;
1687 memset(&data, 0, sizeof(data));
1688 data.filename = name_b ? name_b : name_a;
1689 data.lineno = 0;
1690 data.o = o;
1691 data.ws_rule = whitespace_rule(attr_path);
1693 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1694 die("unable to read files to diff");
1697 * All the other codepaths check both sides, but not checking
1698 * the "old" side here is deliberate. We are checking the newly
1699 * introduced changes, and as long as the "new" side is text, we
1700 * can and should check what it introduces.
1702 if (diff_filespec_is_binary(two))
1703 goto free_and_return;
1704 else {
1705 /* Crazy xdl interfaces.. */
1706 xpparam_t xpp;
1707 xdemitconf_t xecfg;
1708 xdemitcb_t ecb;
1710 memset(&xpp, 0, sizeof(xpp));
1711 memset(&xecfg, 0, sizeof(xecfg));
1712 xecfg.ctxlen = 1; /* at least one context line */
1713 xpp.flags = XDF_NEED_MINIMAL;
1714 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1715 &xpp, &xecfg, &ecb);
1717 if ((data.ws_rule & WS_TRAILING_SPACE) &&
1718 data.trailing_blanks_start) {
1719 fprintf(o->file, "%s:%d: ends with blank lines.\n",
1720 data.filename, data.trailing_blanks_start);
1721 data.status = 1; /* report errors */
1724 free_and_return:
1725 diff_free_filespec_data(one);
1726 diff_free_filespec_data(two);
1727 if (data.status)
1728 DIFF_OPT_SET(o, CHECK_FAILED);
1731 struct diff_filespec *alloc_filespec(const char *path)
1733 int namelen = strlen(path);
1734 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1736 memset(spec, 0, sizeof(*spec));
1737 spec->path = (char *)(spec + 1);
1738 memcpy(spec->path, path, namelen+1);
1739 spec->count = 1;
1740 return spec;
1743 void free_filespec(struct diff_filespec *spec)
1745 if (!--spec->count) {
1746 diff_free_filespec_data(spec);
1747 free(spec);
1751 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1752 unsigned short mode)
1754 if (mode) {
1755 spec->mode = canon_mode(mode);
1756 hashcpy(spec->sha1, sha1);
1757 spec->sha1_valid = !is_null_sha1(sha1);
1762 * Given a name and sha1 pair, if the index tells us the file in
1763 * the work tree has that object contents, return true, so that
1764 * prepare_temp_file() does not have to inflate and extract.
1766 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1768 struct cache_entry *ce;
1769 struct stat st;
1770 int pos, len;
1772 /* We do not read the cache ourselves here, because the
1773 * benchmark with my previous version that always reads cache
1774 * shows that it makes things worse for diff-tree comparing
1775 * two linux-2.6 kernel trees in an already checked out work
1776 * tree. This is because most diff-tree comparisons deal with
1777 * only a small number of files, while reading the cache is
1778 * expensive for a large project, and its cost outweighs the
1779 * savings we get by not inflating the object to a temporary
1780 * file. Practically, this code only helps when we are used
1781 * by diff-cache --cached, which does read the cache before
1782 * calling us.
1784 if (!active_cache)
1785 return 0;
1787 /* We want to avoid the working directory if our caller
1788 * doesn't need the data in a normal file, this system
1789 * is rather slow with its stat/open/mmap/close syscalls,
1790 * and the object is contained in a pack file. The pack
1791 * is probably already open and will be faster to obtain
1792 * the data through than the working directory. Loose
1793 * objects however would tend to be slower as they need
1794 * to be individually opened and inflated.
1796 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1797 return 0;
1799 len = strlen(name);
1800 pos = cache_name_pos(name, len);
1801 if (pos < 0)
1802 return 0;
1803 ce = active_cache[pos];
1806 * This is not the sha1 we are looking for, or
1807 * unreusable because it is not a regular file.
1809 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1810 return 0;
1813 * If ce matches the file in the work tree, we can reuse it.
1815 if (ce_uptodate(ce) ||
1816 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1817 return 1;
1819 return 0;
1822 static int populate_from_stdin(struct diff_filespec *s)
1824 struct strbuf buf = STRBUF_INIT;
1825 size_t size = 0;
1827 if (strbuf_read(&buf, 0, 0) < 0)
1828 return error("error while reading from stdin %s",
1829 strerror(errno));
1831 s->should_munmap = 0;
1832 s->data = strbuf_detach(&buf, &size);
1833 s->size = size;
1834 s->should_free = 1;
1835 return 0;
1838 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1840 int len;
1841 char *data = xmalloc(100);
1842 len = snprintf(data, 100,
1843 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1844 s->data = data;
1845 s->size = len;
1846 s->should_free = 1;
1847 if (size_only) {
1848 s->data = NULL;
1849 free(data);
1851 return 0;
1855 * While doing rename detection and pickaxe operation, we may need to
1856 * grab the data for the blob (or file) for our own in-core comparison.
1857 * diff_filespec has data and size fields for this purpose.
1859 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1861 int err = 0;
1862 if (!DIFF_FILE_VALID(s))
1863 die("internal error: asking to populate invalid file.");
1864 if (S_ISDIR(s->mode))
1865 return -1;
1867 if (s->data)
1868 return 0;
1870 if (size_only && 0 < s->size)
1871 return 0;
1873 if (S_ISGITLINK(s->mode))
1874 return diff_populate_gitlink(s, size_only);
1876 if (!s->sha1_valid ||
1877 reuse_worktree_file(s->path, s->sha1, 0)) {
1878 struct strbuf buf = STRBUF_INIT;
1879 struct stat st;
1880 int fd;
1882 if (!strcmp(s->path, "-"))
1883 return populate_from_stdin(s);
1885 if (lstat(s->path, &st) < 0) {
1886 if (errno == ENOENT) {
1887 err_empty:
1888 err = -1;
1889 empty:
1890 s->data = (char *)"";
1891 s->size = 0;
1892 return err;
1895 s->size = xsize_t(st.st_size);
1896 if (!s->size)
1897 goto empty;
1898 if (size_only)
1899 return 0;
1900 if (S_ISLNK(st.st_mode)) {
1901 int ret;
1902 s->data = xmalloc(s->size);
1903 s->should_free = 1;
1904 ret = readlink(s->path, s->data, s->size);
1905 if (ret < 0) {
1906 free(s->data);
1907 goto err_empty;
1909 return 0;
1911 fd = open(s->path, O_RDONLY);
1912 if (fd < 0)
1913 goto err_empty;
1914 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1915 close(fd);
1916 s->should_munmap = 1;
1919 * Convert from working tree format to canonical git format
1921 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
1922 size_t size = 0;
1923 munmap(s->data, s->size);
1924 s->should_munmap = 0;
1925 s->data = strbuf_detach(&buf, &size);
1926 s->size = size;
1927 s->should_free = 1;
1930 else {
1931 enum object_type type;
1932 if (size_only)
1933 type = sha1_object_info(s->sha1, &s->size);
1934 else {
1935 s->data = read_sha1_file(s->sha1, &type, &s->size);
1936 s->should_free = 1;
1939 return 0;
1942 void diff_free_filespec_blob(struct diff_filespec *s)
1944 if (s->should_free)
1945 free(s->data);
1946 else if (s->should_munmap)
1947 munmap(s->data, s->size);
1949 if (s->should_free || s->should_munmap) {
1950 s->should_free = s->should_munmap = 0;
1951 s->data = NULL;
1955 void diff_free_filespec_data(struct diff_filespec *s)
1957 diff_free_filespec_blob(s);
1958 free(s->cnt_data);
1959 s->cnt_data = NULL;
1962 static void prep_temp_blob(struct diff_tempfile *temp,
1963 void *blob,
1964 unsigned long size,
1965 const unsigned char *sha1,
1966 int mode)
1968 int fd;
1970 fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1971 if (fd < 0)
1972 die("unable to create temp-file: %s", strerror(errno));
1973 if (write_in_full(fd, blob, size) != size)
1974 die("unable to write temp-file");
1975 close(fd);
1976 temp->name = temp->tmp_path;
1977 strcpy(temp->hex, sha1_to_hex(sha1));
1978 temp->hex[40] = 0;
1979 sprintf(temp->mode, "%06o", mode);
1982 static void prepare_temp_file(const char *name,
1983 struct diff_tempfile *temp,
1984 struct diff_filespec *one)
1986 if (!DIFF_FILE_VALID(one)) {
1987 not_a_valid_file:
1988 /* A '-' entry produces this for file-2, and
1989 * a '+' entry produces this for file-1.
1991 temp->name = "/dev/null";
1992 strcpy(temp->hex, ".");
1993 strcpy(temp->mode, ".");
1994 return;
1997 if (!one->sha1_valid ||
1998 reuse_worktree_file(name, one->sha1, 1)) {
1999 struct stat st;
2000 if (lstat(name, &st) < 0) {
2001 if (errno == ENOENT)
2002 goto not_a_valid_file;
2003 die("stat(%s): %s", name, strerror(errno));
2005 if (S_ISLNK(st.st_mode)) {
2006 int ret;
2007 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
2008 size_t sz = xsize_t(st.st_size);
2009 if (sizeof(buf) <= st.st_size)
2010 die("symlink too long: %s", name);
2011 ret = readlink(name, buf, sz);
2012 if (ret < 0)
2013 die("readlink(%s)", name);
2014 prep_temp_blob(temp, buf, sz,
2015 (one->sha1_valid ?
2016 one->sha1 : null_sha1),
2017 (one->sha1_valid ?
2018 one->mode : S_IFLNK));
2020 else {
2021 /* we can borrow from the file in the work tree */
2022 temp->name = name;
2023 if (!one->sha1_valid)
2024 strcpy(temp->hex, sha1_to_hex(null_sha1));
2025 else
2026 strcpy(temp->hex, sha1_to_hex(one->sha1));
2027 /* Even though we may sometimes borrow the
2028 * contents from the work tree, we always want
2029 * one->mode. mode is trustworthy even when
2030 * !(one->sha1_valid), as long as
2031 * DIFF_FILE_VALID(one).
2033 sprintf(temp->mode, "%06o", one->mode);
2035 return;
2037 else {
2038 if (diff_populate_filespec(one, 0))
2039 die("cannot read data blob for %s", one->path);
2040 prep_temp_blob(temp, one->data, one->size,
2041 one->sha1, one->mode);
2045 static void remove_tempfile(void)
2047 int i;
2049 for (i = 0; i < 2; i++)
2050 if (diff_temp[i].name == diff_temp[i].tmp_path) {
2051 unlink(diff_temp[i].name);
2052 diff_temp[i].name = NULL;
2056 static void remove_tempfile_on_signal(int signo)
2058 remove_tempfile();
2059 signal(SIGINT, SIG_DFL);
2060 raise(signo);
2063 /* An external diff command takes:
2065 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2066 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2069 static void run_external_diff(const char *pgm,
2070 const char *name,
2071 const char *other,
2072 struct diff_filespec *one,
2073 struct diff_filespec *two,
2074 const char *xfrm_msg,
2075 int complete_rewrite)
2077 const char *spawn_arg[10];
2078 struct diff_tempfile *temp = diff_temp;
2079 int retval;
2080 static int atexit_asked = 0;
2081 const char *othername;
2082 const char **arg = &spawn_arg[0];
2084 othername = (other? other : name);
2085 if (one && two) {
2086 prepare_temp_file(name, &temp[0], one);
2087 prepare_temp_file(othername, &temp[1], two);
2088 if (! atexit_asked &&
2089 (temp[0].name == temp[0].tmp_path ||
2090 temp[1].name == temp[1].tmp_path)) {
2091 atexit_asked = 1;
2092 atexit(remove_tempfile);
2094 signal(SIGINT, remove_tempfile_on_signal);
2097 if (one && two) {
2098 *arg++ = pgm;
2099 *arg++ = name;
2100 *arg++ = temp[0].name;
2101 *arg++ = temp[0].hex;
2102 *arg++ = temp[0].mode;
2103 *arg++ = temp[1].name;
2104 *arg++ = temp[1].hex;
2105 *arg++ = temp[1].mode;
2106 if (other) {
2107 *arg++ = other;
2108 *arg++ = xfrm_msg;
2110 } else {
2111 *arg++ = pgm;
2112 *arg++ = name;
2114 *arg = NULL;
2115 fflush(NULL);
2116 retval = run_command_v_opt(spawn_arg, 0);
2117 remove_tempfile();
2118 if (retval) {
2119 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2120 exit(1);
2124 static const char *external_diff_attr(const char *name)
2126 struct git_attr_check attr_diff_check;
2128 if (!name)
2129 return NULL;
2131 setup_diff_attr_check(&attr_diff_check);
2132 if (!git_checkattr(name, 1, &attr_diff_check)) {
2133 const char *value = attr_diff_check.value;
2134 if (!ATTR_TRUE(value) &&
2135 !ATTR_FALSE(value) &&
2136 !ATTR_UNSET(value)) {
2137 struct ll_diff_driver *drv;
2139 for (drv = user_diff; drv; drv = drv->next)
2140 if (!strcmp(drv->name, value))
2141 return drv->cmd;
2144 return NULL;
2147 static void run_diff_cmd(const char *pgm,
2148 const char *name,
2149 const char *other,
2150 const char *attr_path,
2151 struct diff_filespec *one,
2152 struct diff_filespec *two,
2153 const char *xfrm_msg,
2154 struct diff_options *o,
2155 int complete_rewrite)
2157 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2158 pgm = NULL;
2159 else {
2160 const char *cmd = external_diff_attr(attr_path);
2161 if (cmd)
2162 pgm = cmd;
2165 if (pgm) {
2166 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2167 complete_rewrite);
2168 return;
2170 if (one && two)
2171 builtin_diff(name, other ? other : name,
2172 one, two, xfrm_msg, o, complete_rewrite);
2173 else
2174 fprintf(o->file, "* Unmerged path %s\n", name);
2177 static void diff_fill_sha1_info(struct diff_filespec *one)
2179 if (DIFF_FILE_VALID(one)) {
2180 if (!one->sha1_valid) {
2181 struct stat st;
2182 if (!strcmp(one->path, "-")) {
2183 hashcpy(one->sha1, null_sha1);
2184 return;
2186 if (lstat(one->path, &st) < 0)
2187 die("stat %s", one->path);
2188 if (index_path(one->sha1, one->path, &st, 0))
2189 die("cannot hash %s\n", one->path);
2192 else
2193 hashclr(one->sha1);
2196 static int similarity_index(struct diff_filepair *p)
2198 return p->score * 100 / MAX_SCORE;
2201 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2203 /* Strip the prefix but do not molest /dev/null and absolute paths */
2204 if (*namep && **namep != '/')
2205 *namep += prefix_length;
2206 if (*otherp && **otherp != '/')
2207 *otherp += prefix_length;
2210 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2212 const char *pgm = external_diff();
2213 struct strbuf msg;
2214 char *xfrm_msg;
2215 struct diff_filespec *one = p->one;
2216 struct diff_filespec *two = p->two;
2217 const char *name;
2218 const char *other;
2219 const char *attr_path;
2220 int complete_rewrite = 0;
2222 name = p->one->path;
2223 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2224 attr_path = name;
2225 if (o->prefix_length)
2226 strip_prefix(o->prefix_length, &name, &other);
2228 if (DIFF_PAIR_UNMERGED(p)) {
2229 run_diff_cmd(pgm, name, NULL, attr_path,
2230 NULL, NULL, NULL, o, 0);
2231 return;
2234 diff_fill_sha1_info(one);
2235 diff_fill_sha1_info(two);
2237 strbuf_init(&msg, PATH_MAX * 2 + 300);
2238 switch (p->status) {
2239 case DIFF_STATUS_COPIED:
2240 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2241 strbuf_addstr(&msg, "\ncopy from ");
2242 quote_c_style(name, &msg, NULL, 0);
2243 strbuf_addstr(&msg, "\ncopy to ");
2244 quote_c_style(other, &msg, NULL, 0);
2245 strbuf_addch(&msg, '\n');
2246 break;
2247 case DIFF_STATUS_RENAMED:
2248 strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
2249 strbuf_addstr(&msg, "\nrename from ");
2250 quote_c_style(name, &msg, NULL, 0);
2251 strbuf_addstr(&msg, "\nrename to ");
2252 quote_c_style(other, &msg, NULL, 0);
2253 strbuf_addch(&msg, '\n');
2254 break;
2255 case DIFF_STATUS_MODIFIED:
2256 if (p->score) {
2257 strbuf_addf(&msg, "dissimilarity index %d%%\n",
2258 similarity_index(p));
2259 complete_rewrite = 1;
2260 break;
2262 /* fallthru */
2263 default:
2264 /* nothing */
2268 if (hashcmp(one->sha1, two->sha1)) {
2269 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2271 if (DIFF_OPT_TST(o, BINARY)) {
2272 mmfile_t mf;
2273 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2274 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2275 abbrev = 40;
2277 strbuf_addf(&msg, "index %.*s..%.*s",
2278 abbrev, sha1_to_hex(one->sha1),
2279 abbrev, sha1_to_hex(two->sha1));
2280 if (one->mode == two->mode)
2281 strbuf_addf(&msg, " %06o", one->mode);
2282 strbuf_addch(&msg, '\n');
2285 if (msg.len)
2286 strbuf_setlen(&msg, msg.len - 1);
2287 xfrm_msg = msg.len ? msg.buf : NULL;
2289 if (!pgm &&
2290 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2291 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2292 /* a filepair that changes between file and symlink
2293 * needs to be split into deletion and creation.
2295 struct diff_filespec *null = alloc_filespec(two->path);
2296 run_diff_cmd(NULL, name, other, attr_path,
2297 one, null, xfrm_msg, o, 0);
2298 free(null);
2299 null = alloc_filespec(one->path);
2300 run_diff_cmd(NULL, name, other, attr_path,
2301 null, two, xfrm_msg, o, 0);
2302 free(null);
2304 else
2305 run_diff_cmd(pgm, name, other, attr_path,
2306 one, two, xfrm_msg, o, complete_rewrite);
2308 strbuf_release(&msg);
2311 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2312 struct diffstat_t *diffstat)
2314 const char *name;
2315 const char *other;
2316 int complete_rewrite = 0;
2318 if (DIFF_PAIR_UNMERGED(p)) {
2319 /* unmerged */
2320 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2321 return;
2324 name = p->one->path;
2325 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2327 if (o->prefix_length)
2328 strip_prefix(o->prefix_length, &name, &other);
2330 diff_fill_sha1_info(p->one);
2331 diff_fill_sha1_info(p->two);
2333 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2334 complete_rewrite = 1;
2335 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2338 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2340 const char *name;
2341 const char *other;
2342 const char *attr_path;
2344 if (DIFF_PAIR_UNMERGED(p)) {
2345 /* unmerged */
2346 return;
2349 name = p->one->path;
2350 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2351 attr_path = other ? other : name;
2353 if (o->prefix_length)
2354 strip_prefix(o->prefix_length, &name, &other);
2356 diff_fill_sha1_info(p->one);
2357 diff_fill_sha1_info(p->two);
2359 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2362 void diff_setup(struct diff_options *options)
2364 memset(options, 0, sizeof(*options));
2366 options->file = stdout;
2368 options->line_termination = '\n';
2369 options->break_opt = -1;
2370 options->rename_limit = -1;
2371 options->dirstat_percent = 3;
2372 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
2373 options->context = 3;
2375 options->change = diff_change;
2376 options->add_remove = diff_addremove;
2377 if (diff_use_color_default > 0)
2378 DIFF_OPT_SET(options, COLOR_DIFF);
2379 else
2380 DIFF_OPT_CLR(options, COLOR_DIFF);
2381 options->detect_rename = diff_detect_rename_default;
2383 if (!diff_mnemonic_prefix) {
2384 options->a_prefix = "a/";
2385 options->b_prefix = "b/";
2389 int diff_setup_done(struct diff_options *options)
2391 int count = 0;
2393 if (options->output_format & DIFF_FORMAT_NAME)
2394 count++;
2395 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2396 count++;
2397 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2398 count++;
2399 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2400 count++;
2401 if (count > 1)
2402 die("--name-only, --name-status, --check and -s are mutually exclusive");
2404 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2405 options->detect_rename = DIFF_DETECT_COPY;
2407 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2408 options->prefix = NULL;
2409 if (options->prefix)
2410 options->prefix_length = strlen(options->prefix);
2411 else
2412 options->prefix_length = 0;
2414 if (options->output_format & (DIFF_FORMAT_NAME |
2415 DIFF_FORMAT_NAME_STATUS |
2416 DIFF_FORMAT_CHECKDIFF |
2417 DIFF_FORMAT_NO_OUTPUT))
2418 options->output_format &= ~(DIFF_FORMAT_RAW |
2419 DIFF_FORMAT_NUMSTAT |
2420 DIFF_FORMAT_DIFFSTAT |
2421 DIFF_FORMAT_SHORTSTAT |
2422 DIFF_FORMAT_DIRSTAT |
2423 DIFF_FORMAT_SUMMARY |
2424 DIFF_FORMAT_PATCH);
2427 * These cases always need recursive; we do not drop caller-supplied
2428 * recursive bits for other formats here.
2430 if (options->output_format & (DIFF_FORMAT_PATCH |
2431 DIFF_FORMAT_NUMSTAT |
2432 DIFF_FORMAT_DIFFSTAT |
2433 DIFF_FORMAT_SHORTSTAT |
2434 DIFF_FORMAT_DIRSTAT |
2435 DIFF_FORMAT_SUMMARY |
2436 DIFF_FORMAT_CHECKDIFF))
2437 DIFF_OPT_SET(options, RECURSIVE);
2439 * Also pickaxe would not work very well if you do not say recursive
2441 if (options->pickaxe)
2442 DIFF_OPT_SET(options, RECURSIVE);
2444 if (options->detect_rename && options->rename_limit < 0)
2445 options->rename_limit = diff_rename_limit_default;
2446 if (options->setup & DIFF_SETUP_USE_CACHE) {
2447 if (!active_cache)
2448 /* read-cache does not die even when it fails
2449 * so it is safe for us to do this here. Also
2450 * it does not smudge active_cache or active_nr
2451 * when it fails, so we do not have to worry about
2452 * cleaning it up ourselves either.
2454 read_cache();
2456 if (options->abbrev <= 0 || 40 < options->abbrev)
2457 options->abbrev = 40; /* full */
2460 * It does not make sense to show the first hit we happened
2461 * to have found. It does not make sense not to return with
2462 * exit code in such a case either.
2464 if (DIFF_OPT_TST(options, QUIET)) {
2465 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2466 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2469 return 0;
2472 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2474 char c, *eq;
2475 int len;
2477 if (*arg != '-')
2478 return 0;
2479 c = *++arg;
2480 if (!c)
2481 return 0;
2482 if (c == arg_short) {
2483 c = *++arg;
2484 if (!c)
2485 return 1;
2486 if (val && isdigit(c)) {
2487 char *end;
2488 int n = strtoul(arg, &end, 10);
2489 if (*end)
2490 return 0;
2491 *val = n;
2492 return 1;
2494 return 0;
2496 if (c != '-')
2497 return 0;
2498 arg++;
2499 eq = strchr(arg, '=');
2500 if (eq)
2501 len = eq - arg;
2502 else
2503 len = strlen(arg);
2504 if (!len || strncmp(arg, arg_long, len))
2505 return 0;
2506 if (eq) {
2507 int n;
2508 char *end;
2509 if (!isdigit(*++eq))
2510 return 0;
2511 n = strtoul(eq, &end, 10);
2512 if (*end)
2513 return 0;
2514 *val = n;
2516 return 1;
2519 static int diff_scoreopt_parse(const char *opt);
2521 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2523 const char *arg = av[0];
2525 /* Output format options */
2526 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2527 options->output_format |= DIFF_FORMAT_PATCH;
2528 else if (opt_arg(arg, 'U', "unified", &options->context))
2529 options->output_format |= DIFF_FORMAT_PATCH;
2530 else if (!strcmp(arg, "--raw"))
2531 options->output_format |= DIFF_FORMAT_RAW;
2532 else if (!strcmp(arg, "--patch-with-raw"))
2533 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2534 else if (!strcmp(arg, "--numstat"))
2535 options->output_format |= DIFF_FORMAT_NUMSTAT;
2536 else if (!strcmp(arg, "--shortstat"))
2537 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2538 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2539 options->output_format |= DIFF_FORMAT_DIRSTAT;
2540 else if (!strcmp(arg, "--cumulative")) {
2541 options->output_format |= DIFF_FORMAT_DIRSTAT;
2542 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2543 } else if (opt_arg(arg, 0, "dirstat-by-file",
2544 &options->dirstat_percent)) {
2545 options->output_format |= DIFF_FORMAT_DIRSTAT;
2546 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2548 else if (!strcmp(arg, "--check"))
2549 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2550 else if (!strcmp(arg, "--summary"))
2551 options->output_format |= DIFF_FORMAT_SUMMARY;
2552 else if (!strcmp(arg, "--patch-with-stat"))
2553 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2554 else if (!strcmp(arg, "--name-only"))
2555 options->output_format |= DIFF_FORMAT_NAME;
2556 else if (!strcmp(arg, "--name-status"))
2557 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2558 else if (!strcmp(arg, "-s"))
2559 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2560 else if (!prefixcmp(arg, "--stat")) {
2561 char *end;
2562 int width = options->stat_width;
2563 int name_width = options->stat_name_width;
2564 arg += 6;
2565 end = (char *)arg;
2567 switch (*arg) {
2568 case '-':
2569 if (!prefixcmp(arg, "-width="))
2570 width = strtoul(arg + 7, &end, 10);
2571 else if (!prefixcmp(arg, "-name-width="))
2572 name_width = strtoul(arg + 12, &end, 10);
2573 break;
2574 case '=':
2575 width = strtoul(arg+1, &end, 10);
2576 if (*end == ',')
2577 name_width = strtoul(end+1, &end, 10);
2580 /* Important! This checks all the error cases! */
2581 if (*end)
2582 return 0;
2583 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2584 options->stat_name_width = name_width;
2585 options->stat_width = width;
2588 /* renames options */
2589 else if (!prefixcmp(arg, "-B")) {
2590 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2591 return -1;
2593 else if (!prefixcmp(arg, "-M")) {
2594 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2595 return -1;
2596 options->detect_rename = DIFF_DETECT_RENAME;
2598 else if (!prefixcmp(arg, "-C")) {
2599 if (options->detect_rename == DIFF_DETECT_COPY)
2600 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2601 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2602 return -1;
2603 options->detect_rename = DIFF_DETECT_COPY;
2605 else if (!strcmp(arg, "--no-renames"))
2606 options->detect_rename = 0;
2607 else if (!strcmp(arg, "--relative"))
2608 DIFF_OPT_SET(options, RELATIVE_NAME);
2609 else if (!prefixcmp(arg, "--relative=")) {
2610 DIFF_OPT_SET(options, RELATIVE_NAME);
2611 options->prefix = arg + 11;
2614 /* xdiff options */
2615 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2616 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2617 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2618 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2619 else if (!strcmp(arg, "--ignore-space-at-eol"))
2620 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2622 /* flags options */
2623 else if (!strcmp(arg, "--binary")) {
2624 options->output_format |= DIFF_FORMAT_PATCH;
2625 DIFF_OPT_SET(options, BINARY);
2627 else if (!strcmp(arg, "--full-index"))
2628 DIFF_OPT_SET(options, FULL_INDEX);
2629 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2630 DIFF_OPT_SET(options, TEXT);
2631 else if (!strcmp(arg, "-R"))
2632 DIFF_OPT_SET(options, REVERSE_DIFF);
2633 else if (!strcmp(arg, "--find-copies-harder"))
2634 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2635 else if (!strcmp(arg, "--follow"))
2636 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2637 else if (!strcmp(arg, "--color"))
2638 DIFF_OPT_SET(options, COLOR_DIFF);
2639 else if (!strcmp(arg, "--no-color"))
2640 DIFF_OPT_CLR(options, COLOR_DIFF);
2641 else if (!strcmp(arg, "--color-words"))
2642 options->flags |= DIFF_OPT_COLOR_DIFF | DIFF_OPT_COLOR_DIFF_WORDS;
2643 else if (!strcmp(arg, "--exit-code"))
2644 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2645 else if (!strcmp(arg, "--quiet"))
2646 DIFF_OPT_SET(options, QUIET);
2647 else if (!strcmp(arg, "--ext-diff"))
2648 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2649 else if (!strcmp(arg, "--no-ext-diff"))
2650 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2651 else if (!strcmp(arg, "--ignore-submodules"))
2652 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2654 /* misc options */
2655 else if (!strcmp(arg, "-z"))
2656 options->line_termination = 0;
2657 else if (!prefixcmp(arg, "-l"))
2658 options->rename_limit = strtoul(arg+2, NULL, 10);
2659 else if (!prefixcmp(arg, "-S"))
2660 options->pickaxe = arg + 2;
2661 else if (!strcmp(arg, "--pickaxe-all"))
2662 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2663 else if (!strcmp(arg, "--pickaxe-regex"))
2664 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2665 else if (!prefixcmp(arg, "-O"))
2666 options->orderfile = arg + 2;
2667 else if (!prefixcmp(arg, "--diff-filter="))
2668 options->filter = arg + 14;
2669 else if (!strcmp(arg, "--abbrev"))
2670 options->abbrev = DEFAULT_ABBREV;
2671 else if (!prefixcmp(arg, "--abbrev=")) {
2672 options->abbrev = strtoul(arg + 9, NULL, 10);
2673 if (options->abbrev < MINIMUM_ABBREV)
2674 options->abbrev = MINIMUM_ABBREV;
2675 else if (40 < options->abbrev)
2676 options->abbrev = 40;
2678 else if (!prefixcmp(arg, "--src-prefix="))
2679 options->a_prefix = arg + 13;
2680 else if (!prefixcmp(arg, "--dst-prefix="))
2681 options->b_prefix = arg + 13;
2682 else if (!strcmp(arg, "--no-prefix"))
2683 options->a_prefix = options->b_prefix = "";
2684 else if (!prefixcmp(arg, "--output=")) {
2685 options->file = fopen(arg + strlen("--output="), "w");
2686 options->close_file = 1;
2687 } else
2688 return 0;
2689 return 1;
2692 static int parse_num(const char **cp_p)
2694 unsigned long num, scale;
2695 int ch, dot;
2696 const char *cp = *cp_p;
2698 num = 0;
2699 scale = 1;
2700 dot = 0;
2701 for(;;) {
2702 ch = *cp;
2703 if ( !dot && ch == '.' ) {
2704 scale = 1;
2705 dot = 1;
2706 } else if ( ch == '%' ) {
2707 scale = dot ? scale*100 : 100;
2708 cp++; /* % is always at the end */
2709 break;
2710 } else if ( ch >= '0' && ch <= '9' ) {
2711 if ( scale < 100000 ) {
2712 scale *= 10;
2713 num = (num*10) + (ch-'0');
2715 } else {
2716 break;
2718 cp++;
2720 *cp_p = cp;
2722 /* user says num divided by scale and we say internally that
2723 * is MAX_SCORE * num / scale.
2725 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2728 static int diff_scoreopt_parse(const char *opt)
2730 int opt1, opt2, cmd;
2732 if (*opt++ != '-')
2733 return -1;
2734 cmd = *opt++;
2735 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2736 return -1; /* that is not a -M, -C nor -B option */
2738 opt1 = parse_num(&opt);
2739 if (cmd != 'B')
2740 opt2 = 0;
2741 else {
2742 if (*opt == 0)
2743 opt2 = 0;
2744 else if (*opt != '/')
2745 return -1; /* we expect -B80/99 or -B80 */
2746 else {
2747 opt++;
2748 opt2 = parse_num(&opt);
2751 if (*opt != 0)
2752 return -1;
2753 return opt1 | (opt2 << 16);
2756 struct diff_queue_struct diff_queued_diff;
2758 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2760 if (queue->alloc <= queue->nr) {
2761 queue->alloc = alloc_nr(queue->alloc);
2762 queue->queue = xrealloc(queue->queue,
2763 sizeof(dp) * queue->alloc);
2765 queue->queue[queue->nr++] = dp;
2768 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2769 struct diff_filespec *one,
2770 struct diff_filespec *two)
2772 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2773 dp->one = one;
2774 dp->two = two;
2775 if (queue)
2776 diff_q(queue, dp);
2777 return dp;
2780 void diff_free_filepair(struct diff_filepair *p)
2782 free_filespec(p->one);
2783 free_filespec(p->two);
2784 free(p);
2787 /* This is different from find_unique_abbrev() in that
2788 * it stuffs the result with dots for alignment.
2790 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2792 int abblen;
2793 const char *abbrev;
2794 if (len == 40)
2795 return sha1_to_hex(sha1);
2797 abbrev = find_unique_abbrev(sha1, len);
2798 abblen = strlen(abbrev);
2799 if (abblen < 37) {
2800 static char hex[41];
2801 if (len < abblen && abblen <= len + 2)
2802 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2803 else
2804 sprintf(hex, "%s...", abbrev);
2805 return hex;
2807 return sha1_to_hex(sha1);
2810 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2812 int line_termination = opt->line_termination;
2813 int inter_name_termination = line_termination ? '\t' : '\0';
2815 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2816 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2817 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2818 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2820 if (p->score) {
2821 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2822 inter_name_termination);
2823 } else {
2824 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2827 if (p->status == DIFF_STATUS_COPIED ||
2828 p->status == DIFF_STATUS_RENAMED) {
2829 const char *name_a, *name_b;
2830 name_a = p->one->path;
2831 name_b = p->two->path;
2832 strip_prefix(opt->prefix_length, &name_a, &name_b);
2833 write_name_quoted(name_a, opt->file, inter_name_termination);
2834 write_name_quoted(name_b, opt->file, line_termination);
2835 } else {
2836 const char *name_a, *name_b;
2837 name_a = p->one->mode ? p->one->path : p->two->path;
2838 name_b = NULL;
2839 strip_prefix(opt->prefix_length, &name_a, &name_b);
2840 write_name_quoted(name_a, opt->file, line_termination);
2844 int diff_unmodified_pair(struct diff_filepair *p)
2846 /* This function is written stricter than necessary to support
2847 * the currently implemented transformers, but the idea is to
2848 * let transformers to produce diff_filepairs any way they want,
2849 * and filter and clean them up here before producing the output.
2851 struct diff_filespec *one = p->one, *two = p->two;
2853 if (DIFF_PAIR_UNMERGED(p))
2854 return 0; /* unmerged is interesting */
2856 /* deletion, addition, mode or type change
2857 * and rename are all interesting.
2859 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2860 DIFF_PAIR_MODE_CHANGED(p) ||
2861 strcmp(one->path, two->path))
2862 return 0;
2864 /* both are valid and point at the same path. that is, we are
2865 * dealing with a change.
2867 if (one->sha1_valid && two->sha1_valid &&
2868 !hashcmp(one->sha1, two->sha1))
2869 return 1; /* no change */
2870 if (!one->sha1_valid && !two->sha1_valid)
2871 return 1; /* both look at the same file on the filesystem. */
2872 return 0;
2875 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2877 if (diff_unmodified_pair(p))
2878 return;
2880 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2881 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2882 return; /* no tree diffs in patch format */
2884 run_diff(p, o);
2887 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2888 struct diffstat_t *diffstat)
2890 if (diff_unmodified_pair(p))
2891 return;
2893 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2894 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2895 return; /* no tree diffs in patch format */
2897 run_diffstat(p, o, diffstat);
2900 static void diff_flush_checkdiff(struct diff_filepair *p,
2901 struct diff_options *o)
2903 if (diff_unmodified_pair(p))
2904 return;
2906 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2907 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2908 return; /* no tree diffs in patch format */
2910 run_checkdiff(p, o);
2913 int diff_queue_is_empty(void)
2915 struct diff_queue_struct *q = &diff_queued_diff;
2916 int i;
2917 for (i = 0; i < q->nr; i++)
2918 if (!diff_unmodified_pair(q->queue[i]))
2919 return 0;
2920 return 1;
2923 #if DIFF_DEBUG
2924 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2926 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2927 x, one ? one : "",
2928 s->path,
2929 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2930 s->mode,
2931 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2932 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2933 x, one ? one : "",
2934 s->size, s->xfrm_flags);
2937 void diff_debug_filepair(const struct diff_filepair *p, int i)
2939 diff_debug_filespec(p->one, i, "one");
2940 diff_debug_filespec(p->two, i, "two");
2941 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
2942 p->score, p->status ? p->status : '?',
2943 p->one->rename_used, p->broken_pair);
2946 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2948 int i;
2949 if (msg)
2950 fprintf(stderr, "%s\n", msg);
2951 fprintf(stderr, "q->nr = %d\n", q->nr);
2952 for (i = 0; i < q->nr; i++) {
2953 struct diff_filepair *p = q->queue[i];
2954 diff_debug_filepair(p, i);
2957 #endif
2959 static void diff_resolve_rename_copy(void)
2961 int i;
2962 struct diff_filepair *p;
2963 struct diff_queue_struct *q = &diff_queued_diff;
2965 diff_debug_queue("resolve-rename-copy", q);
2967 for (i = 0; i < q->nr; i++) {
2968 p = q->queue[i];
2969 p->status = 0; /* undecided */
2970 if (DIFF_PAIR_UNMERGED(p))
2971 p->status = DIFF_STATUS_UNMERGED;
2972 else if (!DIFF_FILE_VALID(p->one))
2973 p->status = DIFF_STATUS_ADDED;
2974 else if (!DIFF_FILE_VALID(p->two))
2975 p->status = DIFF_STATUS_DELETED;
2976 else if (DIFF_PAIR_TYPE_CHANGED(p))
2977 p->status = DIFF_STATUS_TYPE_CHANGED;
2979 /* from this point on, we are dealing with a pair
2980 * whose both sides are valid and of the same type, i.e.
2981 * either in-place edit or rename/copy edit.
2983 else if (DIFF_PAIR_RENAME(p)) {
2985 * A rename might have re-connected a broken
2986 * pair up, causing the pathnames to be the
2987 * same again. If so, that's not a rename at
2988 * all, just a modification..
2990 * Otherwise, see if this source was used for
2991 * multiple renames, in which case we decrement
2992 * the count, and call it a copy.
2994 if (!strcmp(p->one->path, p->two->path))
2995 p->status = DIFF_STATUS_MODIFIED;
2996 else if (--p->one->rename_used > 0)
2997 p->status = DIFF_STATUS_COPIED;
2998 else
2999 p->status = DIFF_STATUS_RENAMED;
3001 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3002 p->one->mode != p->two->mode ||
3003 is_null_sha1(p->one->sha1))
3004 p->status = DIFF_STATUS_MODIFIED;
3005 else {
3006 /* This is a "no-change" entry and should not
3007 * happen anymore, but prepare for broken callers.
3009 error("feeding unmodified %s to diffcore",
3010 p->one->path);
3011 p->status = DIFF_STATUS_UNKNOWN;
3014 diff_debug_queue("resolve-rename-copy done", q);
3017 static int check_pair_status(struct diff_filepair *p)
3019 switch (p->status) {
3020 case DIFF_STATUS_UNKNOWN:
3021 return 0;
3022 case 0:
3023 die("internal error in diff-resolve-rename-copy");
3024 default:
3025 return 1;
3029 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3031 int fmt = opt->output_format;
3033 if (fmt & DIFF_FORMAT_CHECKDIFF)
3034 diff_flush_checkdiff(p, opt);
3035 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3036 diff_flush_raw(p, opt);
3037 else if (fmt & DIFF_FORMAT_NAME) {
3038 const char *name_a, *name_b;
3039 name_a = p->two->path;
3040 name_b = NULL;
3041 strip_prefix(opt->prefix_length, &name_a, &name_b);
3042 write_name_quoted(name_a, opt->file, opt->line_termination);
3046 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3048 if (fs->mode)
3049 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3050 else
3051 fprintf(file, " %s ", newdelete);
3052 write_name_quoted(fs->path, file, '\n');
3056 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3058 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3059 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3060 show_name ? ' ' : '\n');
3061 if (show_name) {
3062 write_name_quoted(p->two->path, file, '\n');
3067 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3069 char *names = pprint_rename(p->one->path, p->two->path);
3071 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3072 free(names);
3073 show_mode_change(file, p, 0);
3076 static void diff_summary(FILE *file, struct diff_filepair *p)
3078 switch(p->status) {
3079 case DIFF_STATUS_DELETED:
3080 show_file_mode_name(file, "delete", p->one);
3081 break;
3082 case DIFF_STATUS_ADDED:
3083 show_file_mode_name(file, "create", p->two);
3084 break;
3085 case DIFF_STATUS_COPIED:
3086 show_rename_copy(file, "copy", p);
3087 break;
3088 case DIFF_STATUS_RENAMED:
3089 show_rename_copy(file, "rename", p);
3090 break;
3091 default:
3092 if (p->score) {
3093 fputs(" rewrite ", file);
3094 write_name_quoted(p->two->path, file, ' ');
3095 fprintf(file, "(%d%%)\n", similarity_index(p));
3097 show_mode_change(file, p, !p->score);
3098 break;
3102 struct patch_id_t {
3103 git_SHA_CTX *ctx;
3104 int patchlen;
3107 static int remove_space(char *line, int len)
3109 int i;
3110 char *dst = line;
3111 unsigned char c;
3113 for (i = 0; i < len; i++)
3114 if (!isspace((c = line[i])))
3115 *dst++ = c;
3117 return dst - line;
3120 static void patch_id_consume(void *priv, char *line, unsigned long len)
3122 struct patch_id_t *data = priv;
3123 int new_len;
3125 /* Ignore line numbers when computing the SHA1 of the patch */
3126 if (!prefixcmp(line, "@@ -"))
3127 return;
3129 new_len = remove_space(line, len);
3131 git_SHA1_Update(data->ctx, line, new_len);
3132 data->patchlen += new_len;
3135 /* returns 0 upon success, and writes result into sha1 */
3136 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3138 struct diff_queue_struct *q = &diff_queued_diff;
3139 int i;
3140 git_SHA_CTX ctx;
3141 struct patch_id_t data;
3142 char buffer[PATH_MAX * 4 + 20];
3144 git_SHA1_Init(&ctx);
3145 memset(&data, 0, sizeof(struct patch_id_t));
3146 data.ctx = &ctx;
3148 for (i = 0; i < q->nr; i++) {
3149 xpparam_t xpp;
3150 xdemitconf_t xecfg;
3151 xdemitcb_t ecb;
3152 mmfile_t mf1, mf2;
3153 struct diff_filepair *p = q->queue[i];
3154 int len1, len2;
3156 memset(&xpp, 0, sizeof(xpp));
3157 memset(&xecfg, 0, sizeof(xecfg));
3158 if (p->status == 0)
3159 return error("internal diff status error");
3160 if (p->status == DIFF_STATUS_UNKNOWN)
3161 continue;
3162 if (diff_unmodified_pair(p))
3163 continue;
3164 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3165 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3166 continue;
3167 if (DIFF_PAIR_UNMERGED(p))
3168 continue;
3170 diff_fill_sha1_info(p->one);
3171 diff_fill_sha1_info(p->two);
3172 if (fill_mmfile(&mf1, p->one) < 0 ||
3173 fill_mmfile(&mf2, p->two) < 0)
3174 return error("unable to read files to diff");
3176 len1 = remove_space(p->one->path, strlen(p->one->path));
3177 len2 = remove_space(p->two->path, strlen(p->two->path));
3178 if (p->one->mode == 0)
3179 len1 = snprintf(buffer, sizeof(buffer),
3180 "diff--gita/%.*sb/%.*s"
3181 "newfilemode%06o"
3182 "---/dev/null"
3183 "+++b/%.*s",
3184 len1, p->one->path,
3185 len2, p->two->path,
3186 p->two->mode,
3187 len2, p->two->path);
3188 else if (p->two->mode == 0)
3189 len1 = snprintf(buffer, sizeof(buffer),
3190 "diff--gita/%.*sb/%.*s"
3191 "deletedfilemode%06o"
3192 "---a/%.*s"
3193 "+++/dev/null",
3194 len1, p->one->path,
3195 len2, p->two->path,
3196 p->one->mode,
3197 len1, p->one->path);
3198 else
3199 len1 = snprintf(buffer, sizeof(buffer),
3200 "diff--gita/%.*sb/%.*s"
3201 "---a/%.*s"
3202 "+++b/%.*s",
3203 len1, p->one->path,
3204 len2, p->two->path,
3205 len1, p->one->path,
3206 len2, p->two->path);
3207 git_SHA1_Update(&ctx, buffer, len1);
3209 xpp.flags = XDF_NEED_MINIMAL;
3210 xecfg.ctxlen = 3;
3211 xecfg.flags = XDL_EMIT_FUNCNAMES;
3212 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3213 &xpp, &xecfg, &ecb);
3216 git_SHA1_Final(sha1, &ctx);
3217 return 0;
3220 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3222 struct diff_queue_struct *q = &diff_queued_diff;
3223 int i;
3224 int result = diff_get_patch_id(options, sha1);
3226 for (i = 0; i < q->nr; i++)
3227 diff_free_filepair(q->queue[i]);
3229 free(q->queue);
3230 q->queue = NULL;
3231 q->nr = q->alloc = 0;
3233 return result;
3236 static int is_summary_empty(const struct diff_queue_struct *q)
3238 int i;
3240 for (i = 0; i < q->nr; i++) {
3241 const struct diff_filepair *p = q->queue[i];
3243 switch (p->status) {
3244 case DIFF_STATUS_DELETED:
3245 case DIFF_STATUS_ADDED:
3246 case DIFF_STATUS_COPIED:
3247 case DIFF_STATUS_RENAMED:
3248 return 0;
3249 default:
3250 if (p->score)
3251 return 0;
3252 if (p->one->mode && p->two->mode &&
3253 p->one->mode != p->two->mode)
3254 return 0;
3255 break;
3258 return 1;
3261 void diff_flush(struct diff_options *options)
3263 struct diff_queue_struct *q = &diff_queued_diff;
3264 int i, output_format = options->output_format;
3265 int separator = 0;
3268 * Order: raw, stat, summary, patch
3269 * or: name/name-status/checkdiff (other bits clear)
3271 if (!q->nr)
3272 goto free_queue;
3274 if (output_format & (DIFF_FORMAT_RAW |
3275 DIFF_FORMAT_NAME |
3276 DIFF_FORMAT_NAME_STATUS |
3277 DIFF_FORMAT_CHECKDIFF)) {
3278 for (i = 0; i < q->nr; i++) {
3279 struct diff_filepair *p = q->queue[i];
3280 if (check_pair_status(p))
3281 flush_one_pair(p, options);
3283 separator++;
3286 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3287 struct diffstat_t diffstat;
3289 memset(&diffstat, 0, sizeof(struct diffstat_t));
3290 for (i = 0; i < q->nr; i++) {
3291 struct diff_filepair *p = q->queue[i];
3292 if (check_pair_status(p))
3293 diff_flush_stat(p, options, &diffstat);
3295 if (output_format & DIFF_FORMAT_NUMSTAT)
3296 show_numstat(&diffstat, options);
3297 if (output_format & DIFF_FORMAT_DIFFSTAT)
3298 show_stats(&diffstat, options);
3299 if (output_format & DIFF_FORMAT_SHORTSTAT)
3300 show_shortstats(&diffstat, options);
3301 free_diffstat_info(&diffstat);
3302 separator++;
3304 if (output_format & DIFF_FORMAT_DIRSTAT)
3305 show_dirstat(options);
3307 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3308 for (i = 0; i < q->nr; i++)
3309 diff_summary(options->file, q->queue[i]);
3310 separator++;
3313 if (output_format & DIFF_FORMAT_PATCH) {
3314 if (separator) {
3315 putc(options->line_termination, options->file);
3316 if (options->stat_sep) {
3317 /* attach patch instead of inline */
3318 fputs(options->stat_sep, options->file);
3322 for (i = 0; i < q->nr; i++) {
3323 struct diff_filepair *p = q->queue[i];
3324 if (check_pair_status(p))
3325 diff_flush_patch(p, options);
3329 if (output_format & DIFF_FORMAT_CALLBACK)
3330 options->format_callback(q, options, options->format_callback_data);
3332 for (i = 0; i < q->nr; i++)
3333 diff_free_filepair(q->queue[i]);
3334 free_queue:
3335 free(q->queue);
3336 q->queue = NULL;
3337 q->nr = q->alloc = 0;
3338 if (options->close_file)
3339 fclose(options->file);
3342 static void diffcore_apply_filter(const char *filter)
3344 int i;
3345 struct diff_queue_struct *q = &diff_queued_diff;
3346 struct diff_queue_struct outq;
3347 outq.queue = NULL;
3348 outq.nr = outq.alloc = 0;
3350 if (!filter)
3351 return;
3353 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3354 int found;
3355 for (i = found = 0; !found && i < q->nr; i++) {
3356 struct diff_filepair *p = q->queue[i];
3357 if (((p->status == DIFF_STATUS_MODIFIED) &&
3358 ((p->score &&
3359 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3360 (!p->score &&
3361 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3362 ((p->status != DIFF_STATUS_MODIFIED) &&
3363 strchr(filter, p->status)))
3364 found++;
3366 if (found)
3367 return;
3369 /* otherwise we will clear the whole queue
3370 * by copying the empty outq at the end of this
3371 * function, but first clear the current entries
3372 * in the queue.
3374 for (i = 0; i < q->nr; i++)
3375 diff_free_filepair(q->queue[i]);
3377 else {
3378 /* Only the matching ones */
3379 for (i = 0; i < q->nr; i++) {
3380 struct diff_filepair *p = q->queue[i];
3382 if (((p->status == DIFF_STATUS_MODIFIED) &&
3383 ((p->score &&
3384 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3385 (!p->score &&
3386 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3387 ((p->status != DIFF_STATUS_MODIFIED) &&
3388 strchr(filter, p->status)))
3389 diff_q(&outq, p);
3390 else
3391 diff_free_filepair(p);
3394 free(q->queue);
3395 *q = outq;
3398 /* Check whether two filespecs with the same mode and size are identical */
3399 static int diff_filespec_is_identical(struct diff_filespec *one,
3400 struct diff_filespec *two)
3402 if (S_ISGITLINK(one->mode))
3403 return 0;
3404 if (diff_populate_filespec(one, 0))
3405 return 0;
3406 if (diff_populate_filespec(two, 0))
3407 return 0;
3408 return !memcmp(one->data, two->data, one->size);
3411 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3413 int i;
3414 struct diff_queue_struct *q = &diff_queued_diff;
3415 struct diff_queue_struct outq;
3416 outq.queue = NULL;
3417 outq.nr = outq.alloc = 0;
3419 for (i = 0; i < q->nr; i++) {
3420 struct diff_filepair *p = q->queue[i];
3423 * 1. Entries that come from stat info dirtyness
3424 * always have both sides (iow, not create/delete),
3425 * one side of the object name is unknown, with
3426 * the same mode and size. Keep the ones that
3427 * do not match these criteria. They have real
3428 * differences.
3430 * 2. At this point, the file is known to be modified,
3431 * with the same mode and size, and the object
3432 * name of one side is unknown. Need to inspect
3433 * the identical contents.
3435 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3436 !DIFF_FILE_VALID(p->two) ||
3437 (p->one->sha1_valid && p->two->sha1_valid) ||
3438 (p->one->mode != p->two->mode) ||
3439 diff_populate_filespec(p->one, 1) ||
3440 diff_populate_filespec(p->two, 1) ||
3441 (p->one->size != p->two->size) ||
3442 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3443 diff_q(&outq, p);
3444 else {
3446 * The caller can subtract 1 from skip_stat_unmatch
3447 * to determine how many paths were dirty only
3448 * due to stat info mismatch.
3450 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3451 diffopt->skip_stat_unmatch++;
3452 diff_free_filepair(p);
3455 free(q->queue);
3456 *q = outq;
3459 void diffcore_std(struct diff_options *options)
3461 if (options->skip_stat_unmatch)
3462 diffcore_skip_stat_unmatch(options);
3463 if (options->break_opt != -1)
3464 diffcore_break(options->break_opt);
3465 if (options->detect_rename)
3466 diffcore_rename(options);
3467 if (options->break_opt != -1)
3468 diffcore_merge_broken();
3469 if (options->pickaxe)
3470 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3471 if (options->orderfile)
3472 diffcore_order(options->orderfile);
3473 diff_resolve_rename_copy();
3474 diffcore_apply_filter(options->filter);
3476 if (diff_queued_diff.nr)
3477 DIFF_OPT_SET(options, HAS_CHANGES);
3478 else
3479 DIFF_OPT_CLR(options, HAS_CHANGES);
3482 int diff_result_code(struct diff_options *opt, int status)
3484 int result = 0;
3485 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3486 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3487 return status;
3488 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3489 DIFF_OPT_TST(opt, HAS_CHANGES))
3490 result |= 01;
3491 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3492 DIFF_OPT_TST(opt, CHECK_FAILED))
3493 result |= 02;
3494 return result;
3497 void diff_addremove(struct diff_options *options,
3498 int addremove, unsigned mode,
3499 const unsigned char *sha1,
3500 const char *concatpath)
3502 struct diff_filespec *one, *two;
3504 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3505 return;
3507 /* This may look odd, but it is a preparation for
3508 * feeding "there are unchanged files which should
3509 * not produce diffs, but when you are doing copy
3510 * detection you would need them, so here they are"
3511 * entries to the diff-core. They will be prefixed
3512 * with something like '=' or '*' (I haven't decided
3513 * which but should not make any difference).
3514 * Feeding the same new and old to diff_change()
3515 * also has the same effect.
3516 * Before the final output happens, they are pruned after
3517 * merged into rename/copy pairs as appropriate.
3519 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3520 addremove = (addremove == '+' ? '-' :
3521 addremove == '-' ? '+' : addremove);
3523 if (options->prefix &&
3524 strncmp(concatpath, options->prefix, options->prefix_length))
3525 return;
3527 one = alloc_filespec(concatpath);
3528 two = alloc_filespec(concatpath);
3530 if (addremove != '+')
3531 fill_filespec(one, sha1, mode);
3532 if (addremove != '-')
3533 fill_filespec(two, sha1, mode);
3535 diff_queue(&diff_queued_diff, one, two);
3536 DIFF_OPT_SET(options, HAS_CHANGES);
3539 void diff_change(struct diff_options *options,
3540 unsigned old_mode, unsigned new_mode,
3541 const unsigned char *old_sha1,
3542 const unsigned char *new_sha1,
3543 const char *concatpath)
3545 struct diff_filespec *one, *two;
3547 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3548 && S_ISGITLINK(new_mode))
3549 return;
3551 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3552 unsigned tmp;
3553 const unsigned char *tmp_c;
3554 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3555 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3558 if (options->prefix &&
3559 strncmp(concatpath, options->prefix, options->prefix_length))
3560 return;
3562 one = alloc_filespec(concatpath);
3563 two = alloc_filespec(concatpath);
3564 fill_filespec(one, old_sha1, old_mode);
3565 fill_filespec(two, new_sha1, new_mode);
3567 diff_queue(&diff_queued_diff, one, two);
3568 DIFF_OPT_SET(options, HAS_CHANGES);
3571 void diff_unmerge(struct diff_options *options,
3572 const char *path,
3573 unsigned mode, const unsigned char *sha1)
3575 struct diff_filespec *one, *two;
3577 if (options->prefix &&
3578 strncmp(path, options->prefix, options->prefix_length))
3579 return;
3581 one = alloc_filespec(path);
3582 two = alloc_filespec(path);
3583 fill_filespec(one, sha1, mode);
3584 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;