gitweb: Add git_merge sub
[git/gsoc2010-gitweb.git] / diff.c
bloba8ed740848ab9938cba8a99509b93422910a48b6
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "quote.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "delta.h"
9 #include "xdiff-interface.h"
10 #include "color.h"
11 #include "attr.h"
12 #include "run-command.h"
13 #include "utf8.h"
14 #include "userdiff.h"
15 #include "sigchain.h"
16 #include "submodule.h"
17 #include "ll-merge.h"
19 #ifdef NO_FAST_WORKING_DIRECTORY
20 #define FAST_WORKING_DIRECTORY 0
21 #else
22 #define FAST_WORKING_DIRECTORY 1
23 #endif
25 static int diff_detect_rename_default;
26 static int diff_rename_limit_default = 200;
27 static int diff_suppress_blank_empty;
28 int diff_use_color_default = -1;
29 static const char *diff_word_regex_cfg;
30 static const char *external_diff_cmd_cfg;
31 int diff_auto_refresh_index = 1;
32 static int diff_mnemonic_prefix;
33 static int diff_no_prefix;
35 static char diff_colors[][COLOR_MAXLEN] = {
36 GIT_COLOR_RESET,
37 GIT_COLOR_NORMAL, /* PLAIN */
38 GIT_COLOR_BOLD, /* METAINFO */
39 GIT_COLOR_CYAN, /* FRAGINFO */
40 GIT_COLOR_RED, /* OLD */
41 GIT_COLOR_GREEN, /* NEW */
42 GIT_COLOR_YELLOW, /* COMMIT */
43 GIT_COLOR_BG_RED, /* WHITESPACE */
44 GIT_COLOR_NORMAL, /* FUNCINFO */
47 static void diff_filespec_load_driver(struct diff_filespec *one);
48 static size_t fill_textconv(struct userdiff_driver *driver,
49 struct diff_filespec *df, char **outbuf);
51 static int parse_diff_color_slot(const char *var, int ofs)
53 if (!strcasecmp(var+ofs, "plain"))
54 return DIFF_PLAIN;
55 if (!strcasecmp(var+ofs, "meta"))
56 return DIFF_METAINFO;
57 if (!strcasecmp(var+ofs, "frag"))
58 return DIFF_FRAGINFO;
59 if (!strcasecmp(var+ofs, "old"))
60 return DIFF_FILE_OLD;
61 if (!strcasecmp(var+ofs, "new"))
62 return DIFF_FILE_NEW;
63 if (!strcasecmp(var+ofs, "commit"))
64 return DIFF_COMMIT;
65 if (!strcasecmp(var+ofs, "whitespace"))
66 return DIFF_WHITESPACE;
67 if (!strcasecmp(var+ofs, "func"))
68 return DIFF_FUNCINFO;
69 return -1;
72 static int git_config_rename(const char *var, const char *value)
74 if (!value)
75 return DIFF_DETECT_RENAME;
76 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
77 return DIFF_DETECT_COPY;
78 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
82 * These are to give UI layer defaults.
83 * The core-level commands such as git-diff-files should
84 * never be affected by the setting of diff.renames
85 * the user happens to have in the configuration file.
87 int git_diff_ui_config(const char *var, const char *value, void *cb)
89 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
90 diff_use_color_default = git_config_colorbool(var, value, -1);
91 return 0;
93 if (!strcmp(var, "diff.renames")) {
94 diff_detect_rename_default = git_config_rename(var, value);
95 return 0;
97 if (!strcmp(var, "diff.autorefreshindex")) {
98 diff_auto_refresh_index = git_config_bool(var, value);
99 return 0;
101 if (!strcmp(var, "diff.mnemonicprefix")) {
102 diff_mnemonic_prefix = git_config_bool(var, value);
103 return 0;
105 if (!strcmp(var, "diff.noprefix")) {
106 diff_no_prefix = git_config_bool(var, value);
107 return 0;
109 if (!strcmp(var, "diff.external"))
110 return git_config_string(&external_diff_cmd_cfg, var, value);
111 if (!strcmp(var, "diff.wordregex"))
112 return git_config_string(&diff_word_regex_cfg, var, value);
114 return git_diff_basic_config(var, value, cb);
117 int git_diff_basic_config(const char *var, const char *value, void *cb)
119 if (!strcmp(var, "diff.renamelimit")) {
120 diff_rename_limit_default = git_config_int(var, value);
121 return 0;
124 switch (userdiff_config(var, value)) {
125 case 0: break;
126 case -1: return -1;
127 default: return 0;
130 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
131 int slot = parse_diff_color_slot(var, 11);
132 if (slot < 0)
133 return 0;
134 if (!value)
135 return config_error_nonbool(var);
136 color_parse(value, var, diff_colors[slot]);
137 return 0;
140 /* like GNU diff's --suppress-blank-empty option */
141 if (!strcmp(var, "diff.suppressblankempty") ||
142 /* for backwards compatibility */
143 !strcmp(var, "diff.suppress-blank-empty")) {
144 diff_suppress_blank_empty = git_config_bool(var, value);
145 return 0;
148 return git_color_default_config(var, value, cb);
151 static char *quote_two(const char *one, const char *two)
153 int need_one = quote_c_style(one, NULL, NULL, 1);
154 int need_two = quote_c_style(two, NULL, NULL, 1);
155 struct strbuf res = STRBUF_INIT;
157 if (need_one + need_two) {
158 strbuf_addch(&res, '"');
159 quote_c_style(one, &res, NULL, 1);
160 quote_c_style(two, &res, NULL, 1);
161 strbuf_addch(&res, '"');
162 } else {
163 strbuf_addstr(&res, one);
164 strbuf_addstr(&res, two);
166 return strbuf_detach(&res, NULL);
169 static const char *external_diff(void)
171 static const char *external_diff_cmd = NULL;
172 static int done_preparing = 0;
174 if (done_preparing)
175 return external_diff_cmd;
176 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
177 if (!external_diff_cmd)
178 external_diff_cmd = external_diff_cmd_cfg;
179 done_preparing = 1;
180 return external_diff_cmd;
183 static struct diff_tempfile {
184 const char *name; /* filename external diff should read from */
185 char hex[41];
186 char mode[10];
187 char tmp_path[PATH_MAX];
188 } diff_temp[2];
190 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
192 struct emit_callback {
193 int color_diff;
194 unsigned ws_rule;
195 int blank_at_eof_in_preimage;
196 int blank_at_eof_in_postimage;
197 int lno_in_preimage;
198 int lno_in_postimage;
199 sane_truncate_fn truncate;
200 const char **label_path;
201 struct diff_words_data *diff_words;
202 struct diff_options *opt;
203 int *found_changesp;
204 struct strbuf *header;
207 static int count_lines(const char *data, int size)
209 int count, ch, completely_empty = 1, nl_just_seen = 0;
210 count = 0;
211 while (0 < size--) {
212 ch = *data++;
213 if (ch == '\n') {
214 count++;
215 nl_just_seen = 1;
216 completely_empty = 0;
218 else {
219 nl_just_seen = 0;
220 completely_empty = 0;
223 if (completely_empty)
224 return 0;
225 if (!nl_just_seen)
226 count++; /* no trailing newline */
227 return count;
230 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
232 if (!DIFF_FILE_VALID(one)) {
233 mf->ptr = (char *)""; /* does not matter */
234 mf->size = 0;
235 return 0;
237 else if (diff_populate_filespec(one, 0))
238 return -1;
240 mf->ptr = one->data;
241 mf->size = one->size;
242 return 0;
245 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
247 char *ptr = mf->ptr;
248 long size = mf->size;
249 int cnt = 0;
251 if (!size)
252 return cnt;
253 ptr += size - 1; /* pointing at the very end */
254 if (*ptr != '\n')
255 ; /* incomplete line */
256 else
257 ptr--; /* skip the last LF */
258 while (mf->ptr < ptr) {
259 char *prev_eol;
260 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
261 if (*prev_eol == '\n')
262 break;
263 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
264 break;
265 cnt++;
266 ptr = prev_eol - 1;
268 return cnt;
271 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
272 struct emit_callback *ecbdata)
274 int l1, l2, at;
275 unsigned ws_rule = ecbdata->ws_rule;
276 l1 = count_trailing_blank(mf1, ws_rule);
277 l2 = count_trailing_blank(mf2, ws_rule);
278 if (l2 <= l1) {
279 ecbdata->blank_at_eof_in_preimage = 0;
280 ecbdata->blank_at_eof_in_postimage = 0;
281 return;
283 at = count_lines(mf1->ptr, mf1->size);
284 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
286 at = count_lines(mf2->ptr, mf2->size);
287 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
290 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
291 int first, const char *line, int len)
293 int has_trailing_newline, has_trailing_carriage_return;
294 int nofirst;
295 FILE *file = o->file;
297 if (o->output_prefix) {
298 struct strbuf *msg = NULL;
299 msg = o->output_prefix(o, o->output_prefix_data);
300 assert(msg);
301 fwrite(msg->buf, msg->len, 1, file);
304 if (len == 0) {
305 has_trailing_newline = (first == '\n');
306 has_trailing_carriage_return = (!has_trailing_newline &&
307 (first == '\r'));
308 nofirst = has_trailing_newline || has_trailing_carriage_return;
309 } else {
310 has_trailing_newline = (len > 0 && line[len-1] == '\n');
311 if (has_trailing_newline)
312 len--;
313 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
314 if (has_trailing_carriage_return)
315 len--;
316 nofirst = 0;
319 if (len || !nofirst) {
320 fputs(set, file);
321 if (!nofirst)
322 fputc(first, file);
323 fwrite(line, len, 1, file);
324 fputs(reset, file);
326 if (has_trailing_carriage_return)
327 fputc('\r', file);
328 if (has_trailing_newline)
329 fputc('\n', file);
332 static void emit_line(struct diff_options *o, const char *set, const char *reset,
333 const char *line, int len)
335 emit_line_0(o, set, reset, line[0], line+1, len-1);
338 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
340 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
341 ecbdata->blank_at_eof_in_preimage &&
342 ecbdata->blank_at_eof_in_postimage &&
343 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
344 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
345 return 0;
346 return ws_blank_line(line, len, ecbdata->ws_rule);
349 static void emit_add_line(const char *reset,
350 struct emit_callback *ecbdata,
351 const char *line, int len)
353 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
354 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
356 if (!*ws)
357 emit_line_0(ecbdata->opt, set, reset, '+', line, len);
358 else if (new_blank_line_at_eof(ecbdata, line, len))
359 /* Blank line at EOF - paint '+' as well */
360 emit_line_0(ecbdata->opt, ws, reset, '+', line, len);
361 else {
362 /* Emit just the prefix, then the rest. */
363 emit_line_0(ecbdata->opt, set, reset, '+', "", 0);
364 ws_check_emit(line, len, ecbdata->ws_rule,
365 ecbdata->opt->file, set, reset, ws);
369 static void emit_hunk_header(struct emit_callback *ecbdata,
370 const char *line, int len)
372 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
373 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
374 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
375 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
376 static const char atat[2] = { '@', '@' };
377 const char *cp, *ep;
378 struct strbuf msgbuf = STRBUF_INIT;
379 int org_len = len;
380 int i = 1;
383 * As a hunk header must begin with "@@ -<old>, +<new> @@",
384 * it always is at least 10 bytes long.
386 if (len < 10 ||
387 memcmp(line, atat, 2) ||
388 !(ep = memmem(line + 2, len - 2, atat, 2))) {
389 emit_line(ecbdata->opt, plain, reset, line, len);
390 return;
392 ep += 2; /* skip over @@ */
394 /* The hunk header in fraginfo color */
395 strbuf_add(&msgbuf, frag, strlen(frag));
396 strbuf_add(&msgbuf, line, ep - line);
397 strbuf_add(&msgbuf, reset, strlen(reset));
400 * trailing "\r\n"
402 for ( ; i < 3; i++)
403 if (line[len - i] == '\r' || line[len - i] == '\n')
404 len--;
406 /* blank before the func header */
407 for (cp = ep; ep - line < len; ep++)
408 if (*ep != ' ' && *ep != '\t')
409 break;
410 if (ep != cp) {
411 strbuf_add(&msgbuf, plain, strlen(plain));
412 strbuf_add(&msgbuf, cp, ep - cp);
413 strbuf_add(&msgbuf, reset, strlen(reset));
416 if (ep < line + len) {
417 strbuf_add(&msgbuf, func, strlen(func));
418 strbuf_add(&msgbuf, ep, line + len - ep);
419 strbuf_add(&msgbuf, reset, strlen(reset));
422 strbuf_add(&msgbuf, line + len, org_len - len);
423 emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
424 strbuf_release(&msgbuf);
427 static struct diff_tempfile *claim_diff_tempfile(void) {
428 int i;
429 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
430 if (!diff_temp[i].name)
431 return diff_temp + i;
432 die("BUG: diff is failing to clean up its tempfiles");
435 static int remove_tempfile_installed;
437 static void remove_tempfile(void)
439 int i;
440 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
441 if (diff_temp[i].name == diff_temp[i].tmp_path)
442 unlink_or_warn(diff_temp[i].name);
443 diff_temp[i].name = NULL;
447 static void remove_tempfile_on_signal(int signo)
449 remove_tempfile();
450 sigchain_pop(signo);
451 raise(signo);
454 static void print_line_count(FILE *file, int count)
456 switch (count) {
457 case 0:
458 fprintf(file, "0,0");
459 break;
460 case 1:
461 fprintf(file, "1");
462 break;
463 default:
464 fprintf(file, "1,%d", count);
465 break;
469 static void emit_rewrite_lines(struct emit_callback *ecb,
470 int prefix, const char *data, int size)
472 const char *endp = NULL;
473 static const char *nneof = " No newline at end of file\n";
474 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
475 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
477 while (0 < size) {
478 int len;
480 endp = memchr(data, '\n', size);
481 len = endp ? (endp - data + 1) : size;
482 if (prefix != '+') {
483 ecb->lno_in_preimage++;
484 emit_line_0(ecb->opt, old, reset, '-',
485 data, len);
486 } else {
487 ecb->lno_in_postimage++;
488 emit_add_line(reset, ecb, data, len);
490 size -= len;
491 data += len;
493 if (!endp) {
494 const char *plain = diff_get_color(ecb->color_diff,
495 DIFF_PLAIN);
496 emit_line_0(ecb->opt, plain, reset, '\\',
497 nneof, strlen(nneof));
501 static void emit_rewrite_diff(const char *name_a,
502 const char *name_b,
503 struct diff_filespec *one,
504 struct diff_filespec *two,
505 struct userdiff_driver *textconv_one,
506 struct userdiff_driver *textconv_two,
507 struct diff_options *o)
509 int lc_a, lc_b;
510 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
511 const char *name_a_tab, *name_b_tab;
512 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
513 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
514 const char *reset = diff_get_color(color_diff, DIFF_RESET);
515 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
516 const char *a_prefix, *b_prefix;
517 char *data_one, *data_two;
518 size_t size_one, size_two;
519 struct emit_callback ecbdata;
521 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
522 a_prefix = o->b_prefix;
523 b_prefix = o->a_prefix;
524 } else {
525 a_prefix = o->a_prefix;
526 b_prefix = o->b_prefix;
529 name_a += (*name_a == '/');
530 name_b += (*name_b == '/');
531 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
532 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
534 strbuf_reset(&a_name);
535 strbuf_reset(&b_name);
536 quote_two_c_style(&a_name, a_prefix, name_a, 0);
537 quote_two_c_style(&b_name, b_prefix, name_b, 0);
539 size_one = fill_textconv(textconv_one, one, &data_one);
540 size_two = fill_textconv(textconv_two, two, &data_two);
542 memset(&ecbdata, 0, sizeof(ecbdata));
543 ecbdata.color_diff = color_diff;
544 ecbdata.found_changesp = &o->found_changes;
545 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
546 ecbdata.opt = o;
547 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
548 mmfile_t mf1, mf2;
549 mf1.ptr = (char *)data_one;
550 mf2.ptr = (char *)data_two;
551 mf1.size = size_one;
552 mf2.size = size_two;
553 check_blank_at_eof(&mf1, &mf2, &ecbdata);
555 ecbdata.lno_in_preimage = 1;
556 ecbdata.lno_in_postimage = 1;
558 lc_a = count_lines(data_one, size_one);
559 lc_b = count_lines(data_two, size_two);
560 fprintf(o->file,
561 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
562 metainfo, a_name.buf, name_a_tab, reset,
563 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
564 print_line_count(o->file, lc_a);
565 fprintf(o->file, " +");
566 print_line_count(o->file, lc_b);
567 fprintf(o->file, " @@%s\n", reset);
568 if (lc_a)
569 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
570 if (lc_b)
571 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
572 if (textconv_one)
573 free((char *)data_one);
574 if (textconv_two)
575 free((char *)data_two);
578 struct diff_words_buffer {
579 mmfile_t text;
580 long alloc;
581 struct diff_words_orig {
582 const char *begin, *end;
583 } *orig;
584 int orig_nr, orig_alloc;
587 static void diff_words_append(char *line, unsigned long len,
588 struct diff_words_buffer *buffer)
590 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
591 line++;
592 len--;
593 memcpy(buffer->text.ptr + buffer->text.size, line, len);
594 buffer->text.size += len;
595 buffer->text.ptr[buffer->text.size] = '\0';
598 struct diff_words_style_elem
600 const char *prefix;
601 const char *suffix;
602 const char *color; /* NULL; filled in by the setup code if
603 * color is enabled */
606 struct diff_words_style
608 enum diff_words_type type;
609 struct diff_words_style_elem new, old, ctx;
610 const char *newline;
613 struct diff_words_style diff_words_styles[] = {
614 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
615 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
616 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
619 struct diff_words_data {
620 struct diff_words_buffer minus, plus;
621 const char *current_plus;
622 int last_minus;
623 struct diff_options *opt;
624 regex_t *word_regex;
625 enum diff_words_type type;
626 struct diff_words_style *style;
629 static int fn_out_diff_words_write_helper(FILE *fp,
630 struct diff_words_style_elem *st_el,
631 const char *newline,
632 size_t count, const char *buf,
633 const char *line_prefix)
635 int print = 0;
637 while (count) {
638 char *p = memchr(buf, '\n', count);
639 if (print)
640 fputs(line_prefix, fp);
641 if (p != buf) {
642 if (st_el->color && fputs(st_el->color, fp) < 0)
643 return -1;
644 if (fputs(st_el->prefix, fp) < 0 ||
645 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
646 fputs(st_el->suffix, fp) < 0)
647 return -1;
648 if (st_el->color && *st_el->color
649 && fputs(GIT_COLOR_RESET, fp) < 0)
650 return -1;
652 if (!p)
653 return 0;
654 if (fputs(newline, fp) < 0)
655 return -1;
656 count -= p + 1 - buf;
657 buf = p + 1;
658 print = 1;
660 return 0;
664 * '--color-words' algorithm can be described as:
666 * 1. collect a the minus/plus lines of a diff hunk, divided into
667 * minus-lines and plus-lines;
669 * 2. break both minus-lines and plus-lines into words and
670 * place them into two mmfile_t with one word for each line;
672 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
674 * And for the common parts of the both file, we output the plus side text.
675 * diff_words->current_plus is used to trace the current position of the plus file
676 * which printed. diff_words->last_minus is used to trace the last minus word
677 * printed.
679 * For '--graph' to work with '--color-words', we need to output the graph prefix
680 * on each line of color words output. Generally, there are two conditions on
681 * which we should output the prefix.
683 * 1. diff_words->last_minus == 0 &&
684 * diff_words->current_plus == diff_words->plus.text.ptr
686 * that is: the plus text must start as a new line, and if there is no minus
687 * word printed, a graph prefix must be printed.
689 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
690 * *(diff_words->current_plus - 1) == '\n'
692 * that is: a graph prefix must be printed following a '\n'
694 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
696 if ((diff_words->last_minus == 0 &&
697 diff_words->current_plus == diff_words->plus.text.ptr) ||
698 (diff_words->current_plus > diff_words->plus.text.ptr &&
699 *(diff_words->current_plus - 1) == '\n')) {
700 return 1;
701 } else {
702 return 0;
706 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
708 struct diff_words_data *diff_words = priv;
709 struct diff_words_style *style = diff_words->style;
710 int minus_first, minus_len, plus_first, plus_len;
711 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
712 struct diff_options *opt = diff_words->opt;
713 struct strbuf *msgbuf;
714 char *line_prefix = "";
716 if (line[0] != '@' || parse_hunk_header(line, len,
717 &minus_first, &minus_len, &plus_first, &plus_len))
718 return;
720 assert(opt);
721 if (opt->output_prefix) {
722 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
723 line_prefix = msgbuf->buf;
726 /* POSIX requires that first be decremented by one if len == 0... */
727 if (minus_len) {
728 minus_begin = diff_words->minus.orig[minus_first].begin;
729 minus_end =
730 diff_words->minus.orig[minus_first + minus_len - 1].end;
731 } else
732 minus_begin = minus_end =
733 diff_words->minus.orig[minus_first].end;
735 if (plus_len) {
736 plus_begin = diff_words->plus.orig[plus_first].begin;
737 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
738 } else
739 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
741 if (color_words_output_graph_prefix(diff_words)) {
742 fputs(line_prefix, diff_words->opt->file);
744 if (diff_words->current_plus != plus_begin) {
745 fn_out_diff_words_write_helper(diff_words->opt->file,
746 &style->ctx, style->newline,
747 plus_begin - diff_words->current_plus,
748 diff_words->current_plus, line_prefix);
749 if (*(plus_begin - 1) == '\n')
750 fputs(line_prefix, diff_words->opt->file);
752 if (minus_begin != minus_end) {
753 fn_out_diff_words_write_helper(diff_words->opt->file,
754 &style->old, style->newline,
755 minus_end - minus_begin, minus_begin,
756 line_prefix);
758 if (plus_begin != plus_end) {
759 fn_out_diff_words_write_helper(diff_words->opt->file,
760 &style->new, style->newline,
761 plus_end - plus_begin, plus_begin,
762 line_prefix);
765 diff_words->current_plus = plus_end;
766 diff_words->last_minus = minus_first;
769 /* This function starts looking at *begin, and returns 0 iff a word was found. */
770 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
771 int *begin, int *end)
773 if (word_regex && *begin < buffer->size) {
774 regmatch_t match[1];
775 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
776 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
777 '\n', match[0].rm_eo - match[0].rm_so);
778 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
779 *begin += match[0].rm_so;
780 return *begin >= *end;
782 return -1;
785 /* find the next word */
786 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
787 (*begin)++;
788 if (*begin >= buffer->size)
789 return -1;
791 /* find the end of the word */
792 *end = *begin + 1;
793 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
794 (*end)++;
796 return 0;
800 * This function splits the words in buffer->text, stores the list with
801 * newline separator into out, and saves the offsets of the original words
802 * in buffer->orig.
804 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
805 regex_t *word_regex)
807 int i, j;
808 long alloc = 0;
810 out->size = 0;
811 out->ptr = NULL;
813 /* fake an empty "0th" word */
814 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
815 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
816 buffer->orig_nr = 1;
818 for (i = 0; i < buffer->text.size; i++) {
819 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
820 return;
822 /* store original boundaries */
823 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
824 buffer->orig_alloc);
825 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
826 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
827 buffer->orig_nr++;
829 /* store one word */
830 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
831 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
832 out->ptr[out->size + j - i] = '\n';
833 out->size += j - i + 1;
835 i = j - 1;
839 /* this executes the word diff on the accumulated buffers */
840 static void diff_words_show(struct diff_words_data *diff_words)
842 xpparam_t xpp;
843 xdemitconf_t xecfg;
844 mmfile_t minus, plus;
845 struct diff_words_style *style = diff_words->style;
847 struct diff_options *opt = diff_words->opt;
848 struct strbuf *msgbuf;
849 char *line_prefix = "";
851 assert(opt);
852 if (opt->output_prefix) {
853 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
854 line_prefix = msgbuf->buf;
857 /* special case: only removal */
858 if (!diff_words->plus.text.size) {
859 fputs(line_prefix, diff_words->opt->file);
860 fn_out_diff_words_write_helper(diff_words->opt->file,
861 &style->old, style->newline,
862 diff_words->minus.text.size,
863 diff_words->minus.text.ptr, line_prefix);
864 diff_words->minus.text.size = 0;
865 return;
868 diff_words->current_plus = diff_words->plus.text.ptr;
869 diff_words->last_minus = 0;
871 memset(&xpp, 0, sizeof(xpp));
872 memset(&xecfg, 0, sizeof(xecfg));
873 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
874 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
875 xpp.flags = 0;
876 /* as only the hunk header will be parsed, we need a 0-context */
877 xecfg.ctxlen = 0;
878 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
879 &xpp, &xecfg);
880 free(minus.ptr);
881 free(plus.ptr);
882 if (diff_words->current_plus != diff_words->plus.text.ptr +
883 diff_words->plus.text.size) {
884 if (color_words_output_graph_prefix(diff_words))
885 fputs(line_prefix, diff_words->opt->file);
886 fn_out_diff_words_write_helper(diff_words->opt->file,
887 &style->ctx, style->newline,
888 diff_words->plus.text.ptr + diff_words->plus.text.size
889 - diff_words->current_plus, diff_words->current_plus,
890 line_prefix);
892 diff_words->minus.text.size = diff_words->plus.text.size = 0;
895 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
896 static void diff_words_flush(struct emit_callback *ecbdata)
898 if (ecbdata->diff_words->minus.text.size ||
899 ecbdata->diff_words->plus.text.size)
900 diff_words_show(ecbdata->diff_words);
903 static void free_diff_words_data(struct emit_callback *ecbdata)
905 if (ecbdata->diff_words) {
906 diff_words_flush(ecbdata);
907 free (ecbdata->diff_words->minus.text.ptr);
908 free (ecbdata->diff_words->minus.orig);
909 free (ecbdata->diff_words->plus.text.ptr);
910 free (ecbdata->diff_words->plus.orig);
911 free(ecbdata->diff_words->word_regex);
912 free(ecbdata->diff_words);
913 ecbdata->diff_words = NULL;
917 const char *diff_get_color(int diff_use_color, enum color_diff ix)
919 if (diff_use_color)
920 return diff_colors[ix];
921 return "";
924 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
926 const char *cp;
927 unsigned long allot;
928 size_t l = len;
930 if (ecb->truncate)
931 return ecb->truncate(line, len);
932 cp = line;
933 allot = l;
934 while (0 < l) {
935 (void) utf8_width(&cp, &l);
936 if (!cp)
937 break; /* truncated in the middle? */
939 return allot - l;
942 static void find_lno(const char *line, struct emit_callback *ecbdata)
944 const char *p;
945 ecbdata->lno_in_preimage = 0;
946 ecbdata->lno_in_postimage = 0;
947 p = strchr(line, '-');
948 if (!p)
949 return; /* cannot happen */
950 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
951 p = strchr(p, '+');
952 if (!p)
953 return; /* cannot happen */
954 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
957 static void fn_out_consume(void *priv, char *line, unsigned long len)
959 struct emit_callback *ecbdata = priv;
960 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
961 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
962 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
964 if (ecbdata->header) {
965 fprintf(ecbdata->opt->file, "%s", ecbdata->header->buf);
966 strbuf_reset(ecbdata->header);
967 ecbdata->header = NULL;
969 *(ecbdata->found_changesp) = 1;
971 if (ecbdata->label_path[0]) {
972 const char *name_a_tab, *name_b_tab;
974 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
975 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
977 fprintf(ecbdata->opt->file, "%s--- %s%s%s\n",
978 meta, ecbdata->label_path[0], reset, name_a_tab);
979 fprintf(ecbdata->opt->file, "%s+++ %s%s%s\n",
980 meta, ecbdata->label_path[1], reset, name_b_tab);
981 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
984 if (diff_suppress_blank_empty
985 && len == 2 && line[0] == ' ' && line[1] == '\n') {
986 line[0] = '\n';
987 len = 1;
990 if (line[0] == '@') {
991 if (ecbdata->diff_words)
992 diff_words_flush(ecbdata);
993 len = sane_truncate_line(ecbdata, line, len);
994 find_lno(line, ecbdata);
995 emit_hunk_header(ecbdata, line, len);
996 if (line[len-1] != '\n')
997 putc('\n', ecbdata->opt->file);
998 return;
1001 if (len < 1) {
1002 emit_line(ecbdata->opt, reset, reset, line, len);
1003 if (ecbdata->diff_words
1004 && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
1005 fputs("~\n", ecbdata->opt->file);
1006 return;
1009 if (ecbdata->diff_words) {
1010 if (line[0] == '-') {
1011 diff_words_append(line, len,
1012 &ecbdata->diff_words->minus);
1013 return;
1014 } else if (line[0] == '+') {
1015 diff_words_append(line, len,
1016 &ecbdata->diff_words->plus);
1017 return;
1019 diff_words_flush(ecbdata);
1020 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
1021 emit_line(ecbdata->opt, plain, reset, line, len);
1022 fputs("~\n", ecbdata->opt->file);
1023 } else {
1024 /* don't print the prefix character */
1025 emit_line(ecbdata->opt, plain, reset, line+1, len-1);
1027 return;
1030 if (line[0] != '+') {
1031 const char *color =
1032 diff_get_color(ecbdata->color_diff,
1033 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
1034 ecbdata->lno_in_preimage++;
1035 if (line[0] == ' ')
1036 ecbdata->lno_in_postimage++;
1037 emit_line(ecbdata->opt, color, reset, line, len);
1038 } else {
1039 ecbdata->lno_in_postimage++;
1040 emit_add_line(reset, ecbdata, line + 1, len - 1);
1044 static char *pprint_rename(const char *a, const char *b)
1046 const char *old = a;
1047 const char *new = b;
1048 struct strbuf name = STRBUF_INIT;
1049 int pfx_length, sfx_length;
1050 int len_a = strlen(a);
1051 int len_b = strlen(b);
1052 int a_midlen, b_midlen;
1053 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1054 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1056 if (qlen_a || qlen_b) {
1057 quote_c_style(a, &name, NULL, 0);
1058 strbuf_addstr(&name, " => ");
1059 quote_c_style(b, &name, NULL, 0);
1060 return strbuf_detach(&name, NULL);
1063 /* Find common prefix */
1064 pfx_length = 0;
1065 while (*old && *new && *old == *new) {
1066 if (*old == '/')
1067 pfx_length = old - a + 1;
1068 old++;
1069 new++;
1072 /* Find common suffix */
1073 old = a + len_a;
1074 new = b + len_b;
1075 sfx_length = 0;
1076 while (a <= old && b <= new && *old == *new) {
1077 if (*old == '/')
1078 sfx_length = len_a - (old - a);
1079 old--;
1080 new--;
1084 * pfx{mid-a => mid-b}sfx
1085 * {pfx-a => pfx-b}sfx
1086 * pfx{sfx-a => sfx-b}
1087 * name-a => name-b
1089 a_midlen = len_a - pfx_length - sfx_length;
1090 b_midlen = len_b - pfx_length - sfx_length;
1091 if (a_midlen < 0)
1092 a_midlen = 0;
1093 if (b_midlen < 0)
1094 b_midlen = 0;
1096 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1097 if (pfx_length + sfx_length) {
1098 strbuf_add(&name, a, pfx_length);
1099 strbuf_addch(&name, '{');
1101 strbuf_add(&name, a + pfx_length, a_midlen);
1102 strbuf_addstr(&name, " => ");
1103 strbuf_add(&name, b + pfx_length, b_midlen);
1104 if (pfx_length + sfx_length) {
1105 strbuf_addch(&name, '}');
1106 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1108 return strbuf_detach(&name, NULL);
1111 struct diffstat_t {
1112 int nr;
1113 int alloc;
1114 struct diffstat_file {
1115 char *from_name;
1116 char *name;
1117 char *print_name;
1118 unsigned is_unmerged:1;
1119 unsigned is_binary:1;
1120 unsigned is_renamed:1;
1121 uintmax_t added, deleted;
1122 } **files;
1125 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1126 const char *name_a,
1127 const char *name_b)
1129 struct diffstat_file *x;
1130 x = xcalloc(sizeof (*x), 1);
1131 if (diffstat->nr == diffstat->alloc) {
1132 diffstat->alloc = alloc_nr(diffstat->alloc);
1133 diffstat->files = xrealloc(diffstat->files,
1134 diffstat->alloc * sizeof(x));
1136 diffstat->files[diffstat->nr++] = x;
1137 if (name_b) {
1138 x->from_name = xstrdup(name_a);
1139 x->name = xstrdup(name_b);
1140 x->is_renamed = 1;
1142 else {
1143 x->from_name = NULL;
1144 x->name = xstrdup(name_a);
1146 return x;
1149 static void diffstat_consume(void *priv, char *line, unsigned long len)
1151 struct diffstat_t *diffstat = priv;
1152 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1154 if (line[0] == '+')
1155 x->added++;
1156 else if (line[0] == '-')
1157 x->deleted++;
1160 const char mime_boundary_leader[] = "------------";
1162 static int scale_linear(int it, int width, int max_change)
1165 * make sure that at least one '-' is printed if there were deletions,
1166 * and likewise for '+'.
1168 if (max_change < 2)
1169 return it;
1170 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
1173 static void show_name(FILE *file,
1174 const char *prefix, const char *name, int len)
1176 fprintf(file, " %s%-*s |", prefix, len, name);
1179 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1181 if (cnt <= 0)
1182 return;
1183 fprintf(file, "%s", set);
1184 while (cnt--)
1185 putc(ch, file);
1186 fprintf(file, "%s", reset);
1189 static void fill_print_name(struct diffstat_file *file)
1191 char *pname;
1193 if (file->print_name)
1194 return;
1196 if (!file->is_renamed) {
1197 struct strbuf buf = STRBUF_INIT;
1198 if (quote_c_style(file->name, &buf, NULL, 0)) {
1199 pname = strbuf_detach(&buf, NULL);
1200 } else {
1201 pname = file->name;
1202 strbuf_release(&buf);
1204 } else {
1205 pname = pprint_rename(file->from_name, file->name);
1207 file->print_name = pname;
1210 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1212 int i, len, add, del, adds = 0, dels = 0;
1213 uintmax_t max_change = 0, max_len = 0;
1214 int total_files = data->nr;
1215 int width, name_width;
1216 const char *reset, *set, *add_c, *del_c;
1218 if (data->nr == 0)
1219 return;
1221 width = options->stat_width ? options->stat_width : 80;
1222 name_width = options->stat_name_width ? options->stat_name_width : 50;
1224 /* Sanity: give at least 5 columns to the graph,
1225 * but leave at least 10 columns for the name.
1227 if (width < 25)
1228 width = 25;
1229 if (name_width < 10)
1230 name_width = 10;
1231 else if (width < name_width + 15)
1232 name_width = width - 15;
1234 /* Find the longest filename and max number of changes */
1235 reset = diff_get_color_opt(options, DIFF_RESET);
1236 set = diff_get_color_opt(options, DIFF_PLAIN);
1237 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1238 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1240 for (i = 0; i < data->nr; i++) {
1241 struct diffstat_file *file = data->files[i];
1242 uintmax_t change = file->added + file->deleted;
1243 fill_print_name(file);
1244 len = strlen(file->print_name);
1245 if (max_len < len)
1246 max_len = len;
1248 if (file->is_binary || file->is_unmerged)
1249 continue;
1250 if (max_change < change)
1251 max_change = change;
1254 /* Compute the width of the graph part;
1255 * 10 is for one blank at the beginning of the line plus
1256 * " | count " between the name and the graph.
1258 * From here on, name_width is the width of the name area,
1259 * and width is the width of the graph area.
1261 name_width = (name_width < max_len) ? name_width : max_len;
1262 if (width < (name_width + 10) + max_change)
1263 width = width - (name_width + 10);
1264 else
1265 width = max_change;
1267 for (i = 0; i < data->nr; i++) {
1268 const char *prefix = "";
1269 char *name = data->files[i]->print_name;
1270 uintmax_t added = data->files[i]->added;
1271 uintmax_t deleted = data->files[i]->deleted;
1272 int name_len;
1275 * "scale" the filename
1277 len = name_width;
1278 name_len = strlen(name);
1279 if (name_width < name_len) {
1280 char *slash;
1281 prefix = "...";
1282 len -= 3;
1283 name += name_len - len;
1284 slash = strchr(name, '/');
1285 if (slash)
1286 name = slash;
1289 if (data->files[i]->is_binary) {
1290 show_name(options->file, prefix, name, len);
1291 fprintf(options->file, " Bin ");
1292 fprintf(options->file, "%s%"PRIuMAX"%s",
1293 del_c, deleted, reset);
1294 fprintf(options->file, " -> ");
1295 fprintf(options->file, "%s%"PRIuMAX"%s",
1296 add_c, added, reset);
1297 fprintf(options->file, " bytes");
1298 fprintf(options->file, "\n");
1299 continue;
1301 else if (data->files[i]->is_unmerged) {
1302 show_name(options->file, prefix, name, len);
1303 fprintf(options->file, " Unmerged\n");
1304 continue;
1306 else if (!data->files[i]->is_renamed &&
1307 (added + deleted == 0)) {
1308 total_files--;
1309 continue;
1313 * scale the add/delete
1315 add = added;
1316 del = deleted;
1317 adds += add;
1318 dels += del;
1320 if (width <= max_change) {
1321 add = scale_linear(add, width, max_change);
1322 del = scale_linear(del, width, max_change);
1324 show_name(options->file, prefix, name, len);
1325 fprintf(options->file, "%5"PRIuMAX"%s", added + deleted,
1326 added + deleted ? " " : "");
1327 show_graph(options->file, '+', add, add_c, reset);
1328 show_graph(options->file, '-', del, del_c, reset);
1329 fprintf(options->file, "\n");
1331 fprintf(options->file,
1332 " %d files changed, %d insertions(+), %d deletions(-)\n",
1333 total_files, adds, dels);
1336 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1338 int i, adds = 0, dels = 0, total_files = data->nr;
1340 if (data->nr == 0)
1341 return;
1343 for (i = 0; i < data->nr; i++) {
1344 if (!data->files[i]->is_binary &&
1345 !data->files[i]->is_unmerged) {
1346 int added = data->files[i]->added;
1347 int deleted= data->files[i]->deleted;
1348 if (!data->files[i]->is_renamed &&
1349 (added + deleted == 0)) {
1350 total_files--;
1351 } else {
1352 adds += added;
1353 dels += deleted;
1357 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1358 total_files, adds, dels);
1361 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1363 int i;
1365 if (data->nr == 0)
1366 return;
1368 for (i = 0; i < data->nr; i++) {
1369 struct diffstat_file *file = data->files[i];
1371 if (file->is_binary)
1372 fprintf(options->file, "-\t-\t");
1373 else
1374 fprintf(options->file,
1375 "%"PRIuMAX"\t%"PRIuMAX"\t",
1376 file->added, file->deleted);
1377 if (options->line_termination) {
1378 fill_print_name(file);
1379 if (!file->is_renamed)
1380 write_name_quoted(file->name, options->file,
1381 options->line_termination);
1382 else {
1383 fputs(file->print_name, options->file);
1384 putc(options->line_termination, options->file);
1386 } else {
1387 if (file->is_renamed) {
1388 putc('\0', options->file);
1389 write_name_quoted(file->from_name, options->file, '\0');
1391 write_name_quoted(file->name, options->file, '\0');
1396 struct dirstat_file {
1397 const char *name;
1398 unsigned long changed;
1401 struct dirstat_dir {
1402 struct dirstat_file *files;
1403 int alloc, nr, percent, cumulative;
1406 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1408 unsigned long this_dir = 0;
1409 unsigned int sources = 0;
1411 while (dir->nr) {
1412 struct dirstat_file *f = dir->files;
1413 int namelen = strlen(f->name);
1414 unsigned long this;
1415 char *slash;
1417 if (namelen < baselen)
1418 break;
1419 if (memcmp(f->name, base, baselen))
1420 break;
1421 slash = strchr(f->name + baselen, '/');
1422 if (slash) {
1423 int newbaselen = slash + 1 - f->name;
1424 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1425 sources++;
1426 } else {
1427 this = f->changed;
1428 dir->files++;
1429 dir->nr--;
1430 sources += 2;
1432 this_dir += this;
1436 * We don't report dirstat's for
1437 * - the top level
1438 * - or cases where everything came from a single directory
1439 * under this directory (sources == 1).
1441 if (baselen && sources != 1) {
1442 int permille = this_dir * 1000 / changed;
1443 if (permille) {
1444 int percent = permille / 10;
1445 if (percent >= dir->percent) {
1446 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1447 if (!dir->cumulative)
1448 return 0;
1452 return this_dir;
1455 static int dirstat_compare(const void *_a, const void *_b)
1457 const struct dirstat_file *a = _a;
1458 const struct dirstat_file *b = _b;
1459 return strcmp(a->name, b->name);
1462 static void show_dirstat(struct diff_options *options)
1464 int i;
1465 unsigned long changed;
1466 struct dirstat_dir dir;
1467 struct diff_queue_struct *q = &diff_queued_diff;
1469 dir.files = NULL;
1470 dir.alloc = 0;
1471 dir.nr = 0;
1472 dir.percent = options->dirstat_percent;
1473 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1475 changed = 0;
1476 for (i = 0; i < q->nr; i++) {
1477 struct diff_filepair *p = q->queue[i];
1478 const char *name;
1479 unsigned long copied, added, damage;
1481 name = p->one->path ? p->one->path : p->two->path;
1483 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1484 diff_populate_filespec(p->one, 0);
1485 diff_populate_filespec(p->two, 0);
1486 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1487 &copied, &added);
1488 diff_free_filespec_data(p->one);
1489 diff_free_filespec_data(p->two);
1490 } else if (DIFF_FILE_VALID(p->one)) {
1491 diff_populate_filespec(p->one, 1);
1492 copied = added = 0;
1493 diff_free_filespec_data(p->one);
1494 } else if (DIFF_FILE_VALID(p->two)) {
1495 diff_populate_filespec(p->two, 1);
1496 copied = 0;
1497 added = p->two->size;
1498 diff_free_filespec_data(p->two);
1499 } else
1500 continue;
1503 * Original minus copied is the removed material,
1504 * added is the new material. They are both damages
1505 * made to the preimage. In --dirstat-by-file mode, count
1506 * damaged files, not damaged lines. This is done by
1507 * counting only a single damaged line per file.
1509 damage = (p->one->size - copied) + added;
1510 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1511 damage = 1;
1513 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1514 dir.files[dir.nr].name = name;
1515 dir.files[dir.nr].changed = damage;
1516 changed += damage;
1517 dir.nr++;
1520 /* This can happen even with many files, if everything was renames */
1521 if (!changed)
1522 return;
1524 /* Show all directories with more than x% of the changes */
1525 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1526 gather_dirstat(options->file, &dir, changed, "", 0);
1529 static void free_diffstat_info(struct diffstat_t *diffstat)
1531 int i;
1532 for (i = 0; i < diffstat->nr; i++) {
1533 struct diffstat_file *f = diffstat->files[i];
1534 if (f->name != f->print_name)
1535 free(f->print_name);
1536 free(f->name);
1537 free(f->from_name);
1538 free(f);
1540 free(diffstat->files);
1543 struct checkdiff_t {
1544 const char *filename;
1545 int lineno;
1546 int conflict_marker_size;
1547 struct diff_options *o;
1548 unsigned ws_rule;
1549 unsigned status;
1552 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
1554 char firstchar;
1555 int cnt;
1557 if (len < marker_size + 1)
1558 return 0;
1559 firstchar = line[0];
1560 switch (firstchar) {
1561 case '=': case '>': case '<': case '|':
1562 break;
1563 default:
1564 return 0;
1566 for (cnt = 1; cnt < marker_size; cnt++)
1567 if (line[cnt] != firstchar)
1568 return 0;
1569 /* line[1] thru line[marker_size-1] are same as firstchar */
1570 if (len < marker_size + 1 || !isspace(line[marker_size]))
1571 return 0;
1572 return 1;
1575 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1577 struct checkdiff_t *data = priv;
1578 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1579 int marker_size = data->conflict_marker_size;
1580 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1581 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1582 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1583 char *err;
1585 if (line[0] == '+') {
1586 unsigned bad;
1587 data->lineno++;
1588 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
1589 data->status |= 1;
1590 fprintf(data->o->file,
1591 "%s:%d: leftover conflict marker\n",
1592 data->filename, data->lineno);
1594 bad = ws_check(line + 1, len - 1, data->ws_rule);
1595 if (!bad)
1596 return;
1597 data->status |= bad;
1598 err = whitespace_error_string(bad);
1599 fprintf(data->o->file, "%s:%d: %s.\n",
1600 data->filename, data->lineno, err);
1601 free(err);
1602 emit_line(data->o, set, reset, line, 1);
1603 ws_check_emit(line + 1, len - 1, data->ws_rule,
1604 data->o->file, set, reset, ws);
1605 } else if (line[0] == ' ') {
1606 data->lineno++;
1607 } else if (line[0] == '@') {
1608 char *plus = strchr(line, '+');
1609 if (plus)
1610 data->lineno = strtol(plus, NULL, 10) - 1;
1611 else
1612 die("invalid diff");
1616 static unsigned char *deflate_it(char *data,
1617 unsigned long size,
1618 unsigned long *result_size)
1620 int bound;
1621 unsigned char *deflated;
1622 z_stream stream;
1624 memset(&stream, 0, sizeof(stream));
1625 deflateInit(&stream, zlib_compression_level);
1626 bound = deflateBound(&stream, size);
1627 deflated = xmalloc(bound);
1628 stream.next_out = deflated;
1629 stream.avail_out = bound;
1631 stream.next_in = (unsigned char *)data;
1632 stream.avail_in = size;
1633 while (deflate(&stream, Z_FINISH) == Z_OK)
1634 ; /* nothing */
1635 deflateEnd(&stream);
1636 *result_size = stream.total_out;
1637 return deflated;
1640 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1642 void *cp;
1643 void *delta;
1644 void *deflated;
1645 void *data;
1646 unsigned long orig_size;
1647 unsigned long delta_size;
1648 unsigned long deflate_size;
1649 unsigned long data_size;
1651 /* We could do deflated delta, or we could do just deflated two,
1652 * whichever is smaller.
1654 delta = NULL;
1655 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1656 if (one->size && two->size) {
1657 delta = diff_delta(one->ptr, one->size,
1658 two->ptr, two->size,
1659 &delta_size, deflate_size);
1660 if (delta) {
1661 void *to_free = delta;
1662 orig_size = delta_size;
1663 delta = deflate_it(delta, delta_size, &delta_size);
1664 free(to_free);
1668 if (delta && delta_size < deflate_size) {
1669 fprintf(file, "delta %lu\n", orig_size);
1670 free(deflated);
1671 data = delta;
1672 data_size = delta_size;
1674 else {
1675 fprintf(file, "literal %lu\n", two->size);
1676 free(delta);
1677 data = deflated;
1678 data_size = deflate_size;
1681 /* emit data encoded in base85 */
1682 cp = data;
1683 while (data_size) {
1684 int bytes = (52 < data_size) ? 52 : data_size;
1685 char line[70];
1686 data_size -= bytes;
1687 if (bytes <= 26)
1688 line[0] = bytes + 'A' - 1;
1689 else
1690 line[0] = bytes - 26 + 'a' - 1;
1691 encode_85(line + 1, cp, bytes);
1692 cp = (char *) cp + bytes;
1693 fputs(line, file);
1694 fputc('\n', file);
1696 fprintf(file, "\n");
1697 free(data);
1700 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1702 fprintf(file, "GIT binary patch\n");
1703 emit_binary_diff_body(file, one, two);
1704 emit_binary_diff_body(file, two, one);
1707 static void diff_filespec_load_driver(struct diff_filespec *one)
1709 if (!one->driver)
1710 one->driver = userdiff_find_by_path(one->path);
1711 if (!one->driver)
1712 one->driver = userdiff_find_by_name("default");
1715 int diff_filespec_is_binary(struct diff_filespec *one)
1717 if (one->is_binary == -1) {
1718 diff_filespec_load_driver(one);
1719 if (one->driver->binary != -1)
1720 one->is_binary = one->driver->binary;
1721 else {
1722 if (!one->data && DIFF_FILE_VALID(one))
1723 diff_populate_filespec(one, 0);
1724 if (one->data)
1725 one->is_binary = buffer_is_binary(one->data,
1726 one->size);
1727 if (one->is_binary == -1)
1728 one->is_binary = 0;
1731 return one->is_binary;
1734 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1736 diff_filespec_load_driver(one);
1737 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1740 static const char *userdiff_word_regex(struct diff_filespec *one)
1742 diff_filespec_load_driver(one);
1743 return one->driver->word_regex;
1746 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1748 if (!options->a_prefix)
1749 options->a_prefix = a;
1750 if (!options->b_prefix)
1751 options->b_prefix = b;
1754 static struct userdiff_driver *get_textconv(struct diff_filespec *one)
1756 if (!DIFF_FILE_VALID(one))
1757 return NULL;
1758 if (!S_ISREG(one->mode))
1759 return NULL;
1760 diff_filespec_load_driver(one);
1761 if (!one->driver->textconv)
1762 return NULL;
1764 if (one->driver->textconv_want_cache && !one->driver->textconv_cache) {
1765 struct notes_cache *c = xmalloc(sizeof(*c));
1766 struct strbuf name = STRBUF_INIT;
1768 strbuf_addf(&name, "textconv/%s", one->driver->name);
1769 notes_cache_init(c, name.buf, one->driver->textconv);
1770 one->driver->textconv_cache = c;
1773 return one->driver;
1776 static void builtin_diff(const char *name_a,
1777 const char *name_b,
1778 struct diff_filespec *one,
1779 struct diff_filespec *two,
1780 const char *xfrm_msg,
1781 struct diff_options *o,
1782 int complete_rewrite)
1784 mmfile_t mf1, mf2;
1785 const char *lbl[2];
1786 char *a_one, *b_two;
1787 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1788 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1789 const char *a_prefix, *b_prefix;
1790 struct userdiff_driver *textconv_one = NULL;
1791 struct userdiff_driver *textconv_two = NULL;
1792 struct strbuf header = STRBUF_INIT;
1794 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
1795 (!one->mode || S_ISGITLINK(one->mode)) &&
1796 (!two->mode || S_ISGITLINK(two->mode))) {
1797 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1798 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1799 show_submodule_summary(o->file, one ? one->path : two->path,
1800 one->sha1, two->sha1, two->dirty_submodule,
1801 del, add, reset);
1802 return;
1805 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1806 textconv_one = get_textconv(one);
1807 textconv_two = get_textconv(two);
1810 diff_set_mnemonic_prefix(o, "a/", "b/");
1811 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1812 a_prefix = o->b_prefix;
1813 b_prefix = o->a_prefix;
1814 } else {
1815 a_prefix = o->a_prefix;
1816 b_prefix = o->b_prefix;
1819 /* Never use a non-valid filename anywhere if at all possible */
1820 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1821 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1823 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1824 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1825 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1826 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1827 strbuf_addf(&header, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1828 if (lbl[0][0] == '/') {
1829 /* /dev/null */
1830 strbuf_addf(&header, "%snew file mode %06o%s\n", set, two->mode, reset);
1831 if (xfrm_msg)
1832 strbuf_addstr(&header, xfrm_msg);
1834 else if (lbl[1][0] == '/') {
1835 strbuf_addf(&header, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1836 if (xfrm_msg)
1837 strbuf_addstr(&header, xfrm_msg);
1839 else {
1840 if (one->mode != two->mode) {
1841 strbuf_addf(&header, "%sold mode %06o%s\n", set, one->mode, reset);
1842 strbuf_addf(&header, "%snew mode %06o%s\n", set, two->mode, reset);
1844 if (xfrm_msg)
1845 strbuf_addstr(&header, xfrm_msg);
1848 * we do not run diff between different kind
1849 * of objects.
1851 if ((one->mode ^ two->mode) & S_IFMT)
1852 goto free_ab_and_return;
1853 if (complete_rewrite &&
1854 (textconv_one || !diff_filespec_is_binary(one)) &&
1855 (textconv_two || !diff_filespec_is_binary(two))) {
1856 fprintf(o->file, "%s", header.buf);
1857 strbuf_reset(&header);
1858 emit_rewrite_diff(name_a, name_b, one, two,
1859 textconv_one, textconv_two, o);
1860 o->found_changes = 1;
1861 goto free_ab_and_return;
1862 } else if (diff_filespec_is_binary(one) &&
1863 diff_filespec_is_binary(two)) {
1864 fprintf(o->file, "%s", header.buf);
1865 strbuf_reset(&header);
1869 if (!DIFF_OPT_TST(o, TEXT) &&
1870 ( (!textconv_one && diff_filespec_is_binary(one)) ||
1871 (!textconv_two && diff_filespec_is_binary(two)) )) {
1872 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1873 die("unable to read files to diff");
1874 /* Quite common confusing case */
1875 if (mf1.size == mf2.size &&
1876 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1877 goto free_ab_and_return;
1878 fprintf(o->file, "%s", header.buf);
1879 strbuf_reset(&header);
1880 if (DIFF_OPT_TST(o, BINARY))
1881 emit_binary_diff(o->file, &mf1, &mf2);
1882 else
1883 fprintf(o->file, "Binary files %s and %s differ\n",
1884 lbl[0], lbl[1]);
1885 o->found_changes = 1;
1887 else {
1888 /* Crazy xdl interfaces.. */
1889 const char *diffopts = getenv("GIT_DIFF_OPTS");
1890 xpparam_t xpp;
1891 xdemitconf_t xecfg;
1892 struct emit_callback ecbdata;
1893 const struct userdiff_funcname *pe;
1895 if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS)) {
1896 fprintf(o->file, "%s", header.buf);
1897 strbuf_reset(&header);
1900 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
1901 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
1903 pe = diff_funcname_pattern(one);
1904 if (!pe)
1905 pe = diff_funcname_pattern(two);
1907 memset(&xpp, 0, sizeof(xpp));
1908 memset(&xecfg, 0, sizeof(xecfg));
1909 memset(&ecbdata, 0, sizeof(ecbdata));
1910 ecbdata.label_path = lbl;
1911 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1912 ecbdata.found_changesp = &o->found_changes;
1913 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1914 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1915 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1916 ecbdata.opt = o;
1917 ecbdata.header = header.len ? &header : NULL;
1918 xpp.flags = o->xdl_opts;
1919 xecfg.ctxlen = o->context;
1920 xecfg.interhunkctxlen = o->interhunkcontext;
1921 xecfg.flags = XDL_EMIT_FUNCNAMES;
1922 if (pe)
1923 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1924 if (!diffopts)
1926 else if (!prefixcmp(diffopts, "--unified="))
1927 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1928 else if (!prefixcmp(diffopts, "-u"))
1929 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1930 if (o->word_diff) {
1931 int i;
1933 ecbdata.diff_words =
1934 xcalloc(1, sizeof(struct diff_words_data));
1935 ecbdata.diff_words->type = o->word_diff;
1936 ecbdata.diff_words->opt = o;
1937 if (!o->word_regex)
1938 o->word_regex = userdiff_word_regex(one);
1939 if (!o->word_regex)
1940 o->word_regex = userdiff_word_regex(two);
1941 if (!o->word_regex)
1942 o->word_regex = diff_word_regex_cfg;
1943 if (o->word_regex) {
1944 ecbdata.diff_words->word_regex = (regex_t *)
1945 xmalloc(sizeof(regex_t));
1946 if (regcomp(ecbdata.diff_words->word_regex,
1947 o->word_regex,
1948 REG_EXTENDED | REG_NEWLINE))
1949 die ("Invalid regular expression: %s",
1950 o->word_regex);
1952 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1953 if (o->word_diff == diff_words_styles[i].type) {
1954 ecbdata.diff_words->style =
1955 &diff_words_styles[i];
1956 break;
1959 if (DIFF_OPT_TST(o, COLOR_DIFF)) {
1960 struct diff_words_style *st = ecbdata.diff_words->style;
1961 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1962 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1963 st->ctx.color = diff_get_color_opt(o, DIFF_PLAIN);
1966 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1967 &xpp, &xecfg);
1968 if (o->word_diff)
1969 free_diff_words_data(&ecbdata);
1970 if (textconv_one)
1971 free(mf1.ptr);
1972 if (textconv_two)
1973 free(mf2.ptr);
1974 xdiff_clear_find_func(&xecfg);
1977 free_ab_and_return:
1978 strbuf_release(&header);
1979 diff_free_filespec_data(one);
1980 diff_free_filespec_data(two);
1981 free(a_one);
1982 free(b_two);
1983 return;
1986 static void builtin_diffstat(const char *name_a, const char *name_b,
1987 struct diff_filespec *one,
1988 struct diff_filespec *two,
1989 struct diffstat_t *diffstat,
1990 struct diff_options *o,
1991 int complete_rewrite)
1993 mmfile_t mf1, mf2;
1994 struct diffstat_file *data;
1996 data = diffstat_add(diffstat, name_a, name_b);
1998 if (!one || !two) {
1999 data->is_unmerged = 1;
2000 return;
2002 if (complete_rewrite) {
2003 diff_populate_filespec(one, 0);
2004 diff_populate_filespec(two, 0);
2005 data->deleted = count_lines(one->data, one->size);
2006 data->added = count_lines(two->data, two->size);
2007 goto free_and_return;
2009 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2010 die("unable to read files to diff");
2012 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2013 data->is_binary = 1;
2014 data->added = mf2.size;
2015 data->deleted = mf1.size;
2016 } else {
2017 /* Crazy xdl interfaces.. */
2018 xpparam_t xpp;
2019 xdemitconf_t xecfg;
2021 memset(&xpp, 0, sizeof(xpp));
2022 memset(&xecfg, 0, sizeof(xecfg));
2023 xpp.flags = o->xdl_opts;
2024 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2025 &xpp, &xecfg);
2028 free_and_return:
2029 diff_free_filespec_data(one);
2030 diff_free_filespec_data(two);
2033 static void builtin_checkdiff(const char *name_a, const char *name_b,
2034 const char *attr_path,
2035 struct diff_filespec *one,
2036 struct diff_filespec *two,
2037 struct diff_options *o)
2039 mmfile_t mf1, mf2;
2040 struct checkdiff_t data;
2042 if (!two)
2043 return;
2045 memset(&data, 0, sizeof(data));
2046 data.filename = name_b ? name_b : name_a;
2047 data.lineno = 0;
2048 data.o = o;
2049 data.ws_rule = whitespace_rule(attr_path);
2050 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2052 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2053 die("unable to read files to diff");
2056 * All the other codepaths check both sides, but not checking
2057 * the "old" side here is deliberate. We are checking the newly
2058 * introduced changes, and as long as the "new" side is text, we
2059 * can and should check what it introduces.
2061 if (diff_filespec_is_binary(two))
2062 goto free_and_return;
2063 else {
2064 /* Crazy xdl interfaces.. */
2065 xpparam_t xpp;
2066 xdemitconf_t xecfg;
2068 memset(&xpp, 0, sizeof(xpp));
2069 memset(&xecfg, 0, sizeof(xecfg));
2070 xecfg.ctxlen = 1; /* at least one context line */
2071 xpp.flags = 0;
2072 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2073 &xpp, &xecfg);
2075 if (data.ws_rule & WS_BLANK_AT_EOF) {
2076 struct emit_callback ecbdata;
2077 int blank_at_eof;
2079 ecbdata.ws_rule = data.ws_rule;
2080 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2081 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
2083 if (blank_at_eof) {
2084 static char *err;
2085 if (!err)
2086 err = whitespace_error_string(WS_BLANK_AT_EOF);
2087 fprintf(o->file, "%s:%d: %s.\n",
2088 data.filename, blank_at_eof, err);
2089 data.status = 1; /* report errors */
2093 free_and_return:
2094 diff_free_filespec_data(one);
2095 diff_free_filespec_data(two);
2096 if (data.status)
2097 DIFF_OPT_SET(o, CHECK_FAILED);
2100 struct diff_filespec *alloc_filespec(const char *path)
2102 int namelen = strlen(path);
2103 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
2105 memset(spec, 0, sizeof(*spec));
2106 spec->path = (char *)(spec + 1);
2107 memcpy(spec->path, path, namelen+1);
2108 spec->count = 1;
2109 spec->is_binary = -1;
2110 return spec;
2113 void free_filespec(struct diff_filespec *spec)
2115 if (!--spec->count) {
2116 diff_free_filespec_data(spec);
2117 free(spec);
2121 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
2122 unsigned short mode)
2124 if (mode) {
2125 spec->mode = canon_mode(mode);
2126 hashcpy(spec->sha1, sha1);
2127 spec->sha1_valid = !is_null_sha1(sha1);
2132 * Given a name and sha1 pair, if the index tells us the file in
2133 * the work tree has that object contents, return true, so that
2134 * prepare_temp_file() does not have to inflate and extract.
2136 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2138 struct cache_entry *ce;
2139 struct stat st;
2140 int pos, len;
2143 * We do not read the cache ourselves here, because the
2144 * benchmark with my previous version that always reads cache
2145 * shows that it makes things worse for diff-tree comparing
2146 * two linux-2.6 kernel trees in an already checked out work
2147 * tree. This is because most diff-tree comparisons deal with
2148 * only a small number of files, while reading the cache is
2149 * expensive for a large project, and its cost outweighs the
2150 * savings we get by not inflating the object to a temporary
2151 * file. Practically, this code only helps when we are used
2152 * by diff-cache --cached, which does read the cache before
2153 * calling us.
2155 if (!active_cache)
2156 return 0;
2158 /* We want to avoid the working directory if our caller
2159 * doesn't need the data in a normal file, this system
2160 * is rather slow with its stat/open/mmap/close syscalls,
2161 * and the object is contained in a pack file. The pack
2162 * is probably already open and will be faster to obtain
2163 * the data through than the working directory. Loose
2164 * objects however would tend to be slower as they need
2165 * to be individually opened and inflated.
2167 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2168 return 0;
2170 len = strlen(name);
2171 pos = cache_name_pos(name, len);
2172 if (pos < 0)
2173 return 0;
2174 ce = active_cache[pos];
2177 * This is not the sha1 we are looking for, or
2178 * unreusable because it is not a regular file.
2180 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
2181 return 0;
2184 * If ce is marked as "assume unchanged", there is no
2185 * guarantee that work tree matches what we are looking for.
2187 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2188 return 0;
2191 * If ce matches the file in the work tree, we can reuse it.
2193 if (ce_uptodate(ce) ||
2194 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2195 return 1;
2197 return 0;
2200 static int populate_from_stdin(struct diff_filespec *s)
2202 struct strbuf buf = STRBUF_INIT;
2203 size_t size = 0;
2205 if (strbuf_read(&buf, 0, 0) < 0)
2206 return error("error while reading from stdin %s",
2207 strerror(errno));
2209 s->should_munmap = 0;
2210 s->data = strbuf_detach(&buf, &size);
2211 s->size = size;
2212 s->should_free = 1;
2213 return 0;
2216 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2218 int len;
2219 char *data = xmalloc(100), *dirty = "";
2221 /* Are we looking at the work tree? */
2222 if (s->dirty_submodule)
2223 dirty = "-dirty";
2225 len = snprintf(data, 100,
2226 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2227 s->data = data;
2228 s->size = len;
2229 s->should_free = 1;
2230 if (size_only) {
2231 s->data = NULL;
2232 free(data);
2234 return 0;
2238 * While doing rename detection and pickaxe operation, we may need to
2239 * grab the data for the blob (or file) for our own in-core comparison.
2240 * diff_filespec has data and size fields for this purpose.
2242 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2244 int err = 0;
2245 if (!DIFF_FILE_VALID(s))
2246 die("internal error: asking to populate invalid file.");
2247 if (S_ISDIR(s->mode))
2248 return -1;
2250 if (s->data)
2251 return 0;
2253 if (size_only && 0 < s->size)
2254 return 0;
2256 if (S_ISGITLINK(s->mode))
2257 return diff_populate_gitlink(s, size_only);
2259 if (!s->sha1_valid ||
2260 reuse_worktree_file(s->path, s->sha1, 0)) {
2261 struct strbuf buf = STRBUF_INIT;
2262 struct stat st;
2263 int fd;
2265 if (!strcmp(s->path, "-"))
2266 return populate_from_stdin(s);
2268 if (lstat(s->path, &st) < 0) {
2269 if (errno == ENOENT) {
2270 err_empty:
2271 err = -1;
2272 empty:
2273 s->data = (char *)"";
2274 s->size = 0;
2275 return err;
2278 s->size = xsize_t(st.st_size);
2279 if (!s->size)
2280 goto empty;
2281 if (S_ISLNK(st.st_mode)) {
2282 struct strbuf sb = STRBUF_INIT;
2284 if (strbuf_readlink(&sb, s->path, s->size))
2285 goto err_empty;
2286 s->size = sb.len;
2287 s->data = strbuf_detach(&sb, NULL);
2288 s->should_free = 1;
2289 return 0;
2291 if (size_only)
2292 return 0;
2293 fd = open(s->path, O_RDONLY);
2294 if (fd < 0)
2295 goto err_empty;
2296 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2297 close(fd);
2298 s->should_munmap = 1;
2301 * Convert from working tree format to canonical git format
2303 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2304 size_t size = 0;
2305 munmap(s->data, s->size);
2306 s->should_munmap = 0;
2307 s->data = strbuf_detach(&buf, &size);
2308 s->size = size;
2309 s->should_free = 1;
2312 else {
2313 enum object_type type;
2314 if (size_only)
2315 type = sha1_object_info(s->sha1, &s->size);
2316 else {
2317 s->data = read_sha1_file(s->sha1, &type, &s->size);
2318 s->should_free = 1;
2321 return 0;
2324 void diff_free_filespec_blob(struct diff_filespec *s)
2326 if (s->should_free)
2327 free(s->data);
2328 else if (s->should_munmap)
2329 munmap(s->data, s->size);
2331 if (s->should_free || s->should_munmap) {
2332 s->should_free = s->should_munmap = 0;
2333 s->data = NULL;
2337 void diff_free_filespec_data(struct diff_filespec *s)
2339 diff_free_filespec_blob(s);
2340 free(s->cnt_data);
2341 s->cnt_data = NULL;
2344 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2345 void *blob,
2346 unsigned long size,
2347 const unsigned char *sha1,
2348 int mode)
2350 int fd;
2351 struct strbuf buf = STRBUF_INIT;
2352 struct strbuf template = STRBUF_INIT;
2353 char *path_dup = xstrdup(path);
2354 const char *base = basename(path_dup);
2356 /* Generate "XXXXXX_basename.ext" */
2357 strbuf_addstr(&template, "XXXXXX_");
2358 strbuf_addstr(&template, base);
2360 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2361 strlen(base) + 1);
2362 if (fd < 0)
2363 die_errno("unable to create temp-file");
2364 if (convert_to_working_tree(path,
2365 (const char *)blob, (size_t)size, &buf)) {
2366 blob = buf.buf;
2367 size = buf.len;
2369 if (write_in_full(fd, blob, size) != size)
2370 die_errno("unable to write temp-file");
2371 close(fd);
2372 temp->name = temp->tmp_path;
2373 strcpy(temp->hex, sha1_to_hex(sha1));
2374 temp->hex[40] = 0;
2375 sprintf(temp->mode, "%06o", mode);
2376 strbuf_release(&buf);
2377 strbuf_release(&template);
2378 free(path_dup);
2381 static struct diff_tempfile *prepare_temp_file(const char *name,
2382 struct diff_filespec *one)
2384 struct diff_tempfile *temp = claim_diff_tempfile();
2386 if (!DIFF_FILE_VALID(one)) {
2387 not_a_valid_file:
2388 /* A '-' entry produces this for file-2, and
2389 * a '+' entry produces this for file-1.
2391 temp->name = "/dev/null";
2392 strcpy(temp->hex, ".");
2393 strcpy(temp->mode, ".");
2394 return temp;
2397 if (!remove_tempfile_installed) {
2398 atexit(remove_tempfile);
2399 sigchain_push_common(remove_tempfile_on_signal);
2400 remove_tempfile_installed = 1;
2403 if (!one->sha1_valid ||
2404 reuse_worktree_file(name, one->sha1, 1)) {
2405 struct stat st;
2406 if (lstat(name, &st) < 0) {
2407 if (errno == ENOENT)
2408 goto not_a_valid_file;
2409 die_errno("stat(%s)", name);
2411 if (S_ISLNK(st.st_mode)) {
2412 struct strbuf sb = STRBUF_INIT;
2413 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2414 die_errno("readlink(%s)", name);
2415 prep_temp_blob(name, temp, sb.buf, sb.len,
2416 (one->sha1_valid ?
2417 one->sha1 : null_sha1),
2418 (one->sha1_valid ?
2419 one->mode : S_IFLNK));
2420 strbuf_release(&sb);
2422 else {
2423 /* we can borrow from the file in the work tree */
2424 temp->name = name;
2425 if (!one->sha1_valid)
2426 strcpy(temp->hex, sha1_to_hex(null_sha1));
2427 else
2428 strcpy(temp->hex, sha1_to_hex(one->sha1));
2429 /* Even though we may sometimes borrow the
2430 * contents from the work tree, we always want
2431 * one->mode. mode is trustworthy even when
2432 * !(one->sha1_valid), as long as
2433 * DIFF_FILE_VALID(one).
2435 sprintf(temp->mode, "%06o", one->mode);
2437 return temp;
2439 else {
2440 if (diff_populate_filespec(one, 0))
2441 die("cannot read data blob for %s", one->path);
2442 prep_temp_blob(name, temp, one->data, one->size,
2443 one->sha1, one->mode);
2445 return temp;
2448 /* An external diff command takes:
2450 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2451 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2454 static void run_external_diff(const char *pgm,
2455 const char *name,
2456 const char *other,
2457 struct diff_filespec *one,
2458 struct diff_filespec *two,
2459 const char *xfrm_msg,
2460 int complete_rewrite)
2462 const char *spawn_arg[10];
2463 int retval;
2464 const char **arg = &spawn_arg[0];
2466 if (one && two) {
2467 struct diff_tempfile *temp_one, *temp_two;
2468 const char *othername = (other ? other : name);
2469 temp_one = prepare_temp_file(name, one);
2470 temp_two = prepare_temp_file(othername, two);
2471 *arg++ = pgm;
2472 *arg++ = name;
2473 *arg++ = temp_one->name;
2474 *arg++ = temp_one->hex;
2475 *arg++ = temp_one->mode;
2476 *arg++ = temp_two->name;
2477 *arg++ = temp_two->hex;
2478 *arg++ = temp_two->mode;
2479 if (other) {
2480 *arg++ = other;
2481 *arg++ = xfrm_msg;
2483 } else {
2484 *arg++ = pgm;
2485 *arg++ = name;
2487 *arg = NULL;
2488 fflush(NULL);
2489 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2490 remove_tempfile();
2491 if (retval) {
2492 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2493 exit(1);
2497 static int similarity_index(struct diff_filepair *p)
2499 return p->score * 100 / MAX_SCORE;
2502 static void fill_metainfo(struct strbuf *msg,
2503 const char *name,
2504 const char *other,
2505 struct diff_filespec *one,
2506 struct diff_filespec *two,
2507 struct diff_options *o,
2508 struct diff_filepair *p,
2509 int use_color)
2511 const char *set = diff_get_color(use_color, DIFF_METAINFO);
2512 const char *reset = diff_get_color(use_color, DIFF_RESET);
2514 strbuf_init(msg, PATH_MAX * 2 + 300);
2515 switch (p->status) {
2516 case DIFF_STATUS_COPIED:
2517 strbuf_addf(msg, "%ssimilarity index %d%%",
2518 set, similarity_index(p));
2519 strbuf_addf(msg, "%s\n%scopy from ", reset, set);
2520 quote_c_style(name, msg, NULL, 0);
2521 strbuf_addf(msg, "%s\n%scopy to ", reset, set);
2522 quote_c_style(other, msg, NULL, 0);
2523 strbuf_addf(msg, "%s\n", reset);
2524 break;
2525 case DIFF_STATUS_RENAMED:
2526 strbuf_addf(msg, "%ssimilarity index %d%%",
2527 set, similarity_index(p));
2528 strbuf_addf(msg, "%s\n%srename from ", reset, set);
2529 quote_c_style(name, msg, NULL, 0);
2530 strbuf_addf(msg, "%s\n%srename to ", reset, set);
2531 quote_c_style(other, msg, NULL, 0);
2532 strbuf_addf(msg, "%s\n", reset);
2533 break;
2534 case DIFF_STATUS_MODIFIED:
2535 if (p->score) {
2536 strbuf_addf(msg, "%sdissimilarity index %d%%%s\n",
2537 set, similarity_index(p), reset);
2538 break;
2540 /* fallthru */
2541 default:
2542 /* nothing */
2545 if (one && two && hashcmp(one->sha1, two->sha1)) {
2546 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2548 if (DIFF_OPT_TST(o, BINARY)) {
2549 mmfile_t mf;
2550 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2551 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2552 abbrev = 40;
2554 strbuf_addf(msg, "%sindex %s..", set,
2555 find_unique_abbrev(one->sha1, abbrev));
2556 strbuf_addstr(msg, find_unique_abbrev(two->sha1, abbrev));
2557 if (one->mode == two->mode)
2558 strbuf_addf(msg, " %06o", one->mode);
2559 strbuf_addf(msg, "%s\n", reset);
2563 static void run_diff_cmd(const char *pgm,
2564 const char *name,
2565 const char *other,
2566 const char *attr_path,
2567 struct diff_filespec *one,
2568 struct diff_filespec *two,
2569 struct strbuf *msg,
2570 struct diff_options *o,
2571 struct diff_filepair *p)
2573 const char *xfrm_msg = NULL;
2574 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2576 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2577 pgm = NULL;
2578 else {
2579 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2580 if (drv && drv->external)
2581 pgm = drv->external;
2584 if (msg) {
2586 * don't use colors when the header is intended for an
2587 * external diff driver
2589 fill_metainfo(msg, name, other, one, two, o, p,
2590 DIFF_OPT_TST(o, COLOR_DIFF) && !pgm);
2591 xfrm_msg = msg->len ? msg->buf : NULL;
2594 if (pgm) {
2595 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2596 complete_rewrite);
2597 return;
2599 if (one && two)
2600 builtin_diff(name, other ? other : name,
2601 one, two, xfrm_msg, o, complete_rewrite);
2602 else
2603 fprintf(o->file, "* Unmerged path %s\n", name);
2606 static void diff_fill_sha1_info(struct diff_filespec *one)
2608 if (DIFF_FILE_VALID(one)) {
2609 if (!one->sha1_valid) {
2610 struct stat st;
2611 if (!strcmp(one->path, "-")) {
2612 hashcpy(one->sha1, null_sha1);
2613 return;
2615 if (lstat(one->path, &st) < 0)
2616 die_errno("stat '%s'", one->path);
2617 if (index_path(one->sha1, one->path, &st, 0))
2618 die("cannot hash %s", one->path);
2621 else
2622 hashclr(one->sha1);
2625 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2627 /* Strip the prefix but do not molest /dev/null and absolute paths */
2628 if (*namep && **namep != '/')
2629 *namep += prefix_length;
2630 if (*otherp && **otherp != '/')
2631 *otherp += prefix_length;
2634 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2636 const char *pgm = external_diff();
2637 struct strbuf msg;
2638 struct diff_filespec *one = p->one;
2639 struct diff_filespec *two = p->two;
2640 const char *name;
2641 const char *other;
2642 const char *attr_path;
2644 name = p->one->path;
2645 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2646 attr_path = name;
2647 if (o->prefix_length)
2648 strip_prefix(o->prefix_length, &name, &other);
2650 if (DIFF_PAIR_UNMERGED(p)) {
2651 run_diff_cmd(pgm, name, NULL, attr_path,
2652 NULL, NULL, NULL, o, p);
2653 return;
2656 diff_fill_sha1_info(one);
2657 diff_fill_sha1_info(two);
2659 if (!pgm &&
2660 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2661 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2663 * a filepair that changes between file and symlink
2664 * needs to be split into deletion and creation.
2666 struct diff_filespec *null = alloc_filespec(two->path);
2667 run_diff_cmd(NULL, name, other, attr_path,
2668 one, null, &msg, o, p);
2669 free(null);
2670 strbuf_release(&msg);
2672 null = alloc_filespec(one->path);
2673 run_diff_cmd(NULL, name, other, attr_path,
2674 null, two, &msg, o, p);
2675 free(null);
2677 else
2678 run_diff_cmd(pgm, name, other, attr_path,
2679 one, two, &msg, o, p);
2681 strbuf_release(&msg);
2684 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2685 struct diffstat_t *diffstat)
2687 const char *name;
2688 const char *other;
2689 int complete_rewrite = 0;
2691 if (DIFF_PAIR_UNMERGED(p)) {
2692 /* unmerged */
2693 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2694 return;
2697 name = p->one->path;
2698 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2700 if (o->prefix_length)
2701 strip_prefix(o->prefix_length, &name, &other);
2703 diff_fill_sha1_info(p->one);
2704 diff_fill_sha1_info(p->two);
2706 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2707 complete_rewrite = 1;
2708 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2711 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2713 const char *name;
2714 const char *other;
2715 const char *attr_path;
2717 if (DIFF_PAIR_UNMERGED(p)) {
2718 /* unmerged */
2719 return;
2722 name = p->one->path;
2723 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2724 attr_path = other ? other : name;
2726 if (o->prefix_length)
2727 strip_prefix(o->prefix_length, &name, &other);
2729 diff_fill_sha1_info(p->one);
2730 diff_fill_sha1_info(p->two);
2732 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2735 void diff_setup(struct diff_options *options)
2737 memset(options, 0, sizeof(*options));
2738 memset(&diff_queued_diff, 0, sizeof(diff_queued_diff));
2740 options->file = stdout;
2742 options->line_termination = '\n';
2743 options->break_opt = -1;
2744 options->rename_limit = -1;
2745 options->dirstat_percent = 3;
2746 options->context = 3;
2748 options->change = diff_change;
2749 options->add_remove = diff_addremove;
2750 if (diff_use_color_default > 0)
2751 DIFF_OPT_SET(options, COLOR_DIFF);
2752 options->detect_rename = diff_detect_rename_default;
2754 if (diff_no_prefix) {
2755 options->a_prefix = options->b_prefix = "";
2756 } else if (!diff_mnemonic_prefix) {
2757 options->a_prefix = "a/";
2758 options->b_prefix = "b/";
2762 int diff_setup_done(struct diff_options *options)
2764 int count = 0;
2766 if (options->output_format & DIFF_FORMAT_NAME)
2767 count++;
2768 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2769 count++;
2770 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2771 count++;
2772 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2773 count++;
2774 if (count > 1)
2775 die("--name-only, --name-status, --check and -s are mutually exclusive");
2778 * Most of the time we can say "there are changes"
2779 * only by checking if there are changed paths, but
2780 * --ignore-whitespace* options force us to look
2781 * inside contents.
2784 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2785 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2786 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2787 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2788 else
2789 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2791 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2792 options->detect_rename = DIFF_DETECT_COPY;
2794 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2795 options->prefix = NULL;
2796 if (options->prefix)
2797 options->prefix_length = strlen(options->prefix);
2798 else
2799 options->prefix_length = 0;
2801 if (options->output_format & (DIFF_FORMAT_NAME |
2802 DIFF_FORMAT_NAME_STATUS |
2803 DIFF_FORMAT_CHECKDIFF |
2804 DIFF_FORMAT_NO_OUTPUT))
2805 options->output_format &= ~(DIFF_FORMAT_RAW |
2806 DIFF_FORMAT_NUMSTAT |
2807 DIFF_FORMAT_DIFFSTAT |
2808 DIFF_FORMAT_SHORTSTAT |
2809 DIFF_FORMAT_DIRSTAT |
2810 DIFF_FORMAT_SUMMARY |
2811 DIFF_FORMAT_PATCH);
2814 * These cases always need recursive; we do not drop caller-supplied
2815 * recursive bits for other formats here.
2817 if (options->output_format & (DIFF_FORMAT_PATCH |
2818 DIFF_FORMAT_NUMSTAT |
2819 DIFF_FORMAT_DIFFSTAT |
2820 DIFF_FORMAT_SHORTSTAT |
2821 DIFF_FORMAT_DIRSTAT |
2822 DIFF_FORMAT_SUMMARY |
2823 DIFF_FORMAT_CHECKDIFF))
2824 DIFF_OPT_SET(options, RECURSIVE);
2826 * Also pickaxe would not work very well if you do not say recursive
2828 if (options->pickaxe)
2829 DIFF_OPT_SET(options, RECURSIVE);
2831 * When patches are generated, submodules diffed against the work tree
2832 * must be checked for dirtiness too so it can be shown in the output
2834 if (options->output_format & DIFF_FORMAT_PATCH)
2835 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
2837 if (options->detect_rename && options->rename_limit < 0)
2838 options->rename_limit = diff_rename_limit_default;
2839 if (options->setup & DIFF_SETUP_USE_CACHE) {
2840 if (!active_cache)
2841 /* read-cache does not die even when it fails
2842 * so it is safe for us to do this here. Also
2843 * it does not smudge active_cache or active_nr
2844 * when it fails, so we do not have to worry about
2845 * cleaning it up ourselves either.
2847 read_cache();
2849 if (options->abbrev <= 0 || 40 < options->abbrev)
2850 options->abbrev = 40; /* full */
2853 * It does not make sense to show the first hit we happened
2854 * to have found. It does not make sense not to return with
2855 * exit code in such a case either.
2857 if (DIFF_OPT_TST(options, QUICK)) {
2858 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2859 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2862 return 0;
2865 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2867 char c, *eq;
2868 int len;
2870 if (*arg != '-')
2871 return 0;
2872 c = *++arg;
2873 if (!c)
2874 return 0;
2875 if (c == arg_short) {
2876 c = *++arg;
2877 if (!c)
2878 return 1;
2879 if (val && isdigit(c)) {
2880 char *end;
2881 int n = strtoul(arg, &end, 10);
2882 if (*end)
2883 return 0;
2884 *val = n;
2885 return 1;
2887 return 0;
2889 if (c != '-')
2890 return 0;
2891 arg++;
2892 eq = strchr(arg, '=');
2893 if (eq)
2894 len = eq - arg;
2895 else
2896 len = strlen(arg);
2897 if (!len || strncmp(arg, arg_long, len))
2898 return 0;
2899 if (eq) {
2900 int n;
2901 char *end;
2902 if (!isdigit(*++eq))
2903 return 0;
2904 n = strtoul(eq, &end, 10);
2905 if (*end)
2906 return 0;
2907 *val = n;
2909 return 1;
2912 static int diff_scoreopt_parse(const char *opt);
2914 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2916 const char *arg = av[0];
2918 /* Output format options */
2919 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch"))
2920 options->output_format |= DIFF_FORMAT_PATCH;
2921 else if (opt_arg(arg, 'U', "unified", &options->context))
2922 options->output_format |= DIFF_FORMAT_PATCH;
2923 else if (!strcmp(arg, "--raw"))
2924 options->output_format |= DIFF_FORMAT_RAW;
2925 else if (!strcmp(arg, "--patch-with-raw"))
2926 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2927 else if (!strcmp(arg, "--numstat"))
2928 options->output_format |= DIFF_FORMAT_NUMSTAT;
2929 else if (!strcmp(arg, "--shortstat"))
2930 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2931 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2932 options->output_format |= DIFF_FORMAT_DIRSTAT;
2933 else if (!strcmp(arg, "--cumulative")) {
2934 options->output_format |= DIFF_FORMAT_DIRSTAT;
2935 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2936 } else if (opt_arg(arg, 0, "dirstat-by-file",
2937 &options->dirstat_percent)) {
2938 options->output_format |= DIFF_FORMAT_DIRSTAT;
2939 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2941 else if (!strcmp(arg, "--check"))
2942 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2943 else if (!strcmp(arg, "--summary"))
2944 options->output_format |= DIFF_FORMAT_SUMMARY;
2945 else if (!strcmp(arg, "--patch-with-stat"))
2946 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2947 else if (!strcmp(arg, "--name-only"))
2948 options->output_format |= DIFF_FORMAT_NAME;
2949 else if (!strcmp(arg, "--name-status"))
2950 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2951 else if (!strcmp(arg, "-s"))
2952 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2953 else if (!prefixcmp(arg, "--stat")) {
2954 char *end;
2955 int width = options->stat_width;
2956 int name_width = options->stat_name_width;
2957 arg += 6;
2958 end = (char *)arg;
2960 switch (*arg) {
2961 case '-':
2962 if (!prefixcmp(arg, "-width="))
2963 width = strtoul(arg + 7, &end, 10);
2964 else if (!prefixcmp(arg, "-name-width="))
2965 name_width = strtoul(arg + 12, &end, 10);
2966 break;
2967 case '=':
2968 width = strtoul(arg+1, &end, 10);
2969 if (*end == ',')
2970 name_width = strtoul(end+1, &end, 10);
2973 /* Important! This checks all the error cases! */
2974 if (*end)
2975 return 0;
2976 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2977 options->stat_name_width = name_width;
2978 options->stat_width = width;
2981 /* renames options */
2982 else if (!prefixcmp(arg, "-B")) {
2983 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2984 return -1;
2986 else if (!prefixcmp(arg, "-M")) {
2987 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2988 return -1;
2989 options->detect_rename = DIFF_DETECT_RENAME;
2991 else if (!prefixcmp(arg, "-C")) {
2992 if (options->detect_rename == DIFF_DETECT_COPY)
2993 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2994 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2995 return -1;
2996 options->detect_rename = DIFF_DETECT_COPY;
2998 else if (!strcmp(arg, "--no-renames"))
2999 options->detect_rename = 0;
3000 else if (!strcmp(arg, "--relative"))
3001 DIFF_OPT_SET(options, RELATIVE_NAME);
3002 else if (!prefixcmp(arg, "--relative=")) {
3003 DIFF_OPT_SET(options, RELATIVE_NAME);
3004 options->prefix = arg + 11;
3007 /* xdiff options */
3008 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
3009 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
3010 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
3011 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
3012 else if (!strcmp(arg, "--ignore-space-at-eol"))
3013 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
3014 else if (!strcmp(arg, "--patience"))
3015 DIFF_XDL_SET(options, PATIENCE_DIFF);
3017 /* flags options */
3018 else if (!strcmp(arg, "--binary")) {
3019 options->output_format |= DIFF_FORMAT_PATCH;
3020 DIFF_OPT_SET(options, BINARY);
3022 else if (!strcmp(arg, "--full-index"))
3023 DIFF_OPT_SET(options, FULL_INDEX);
3024 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
3025 DIFF_OPT_SET(options, TEXT);
3026 else if (!strcmp(arg, "-R"))
3027 DIFF_OPT_SET(options, REVERSE_DIFF);
3028 else if (!strcmp(arg, "--find-copies-harder"))
3029 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3030 else if (!strcmp(arg, "--follow"))
3031 DIFF_OPT_SET(options, FOLLOW_RENAMES);
3032 else if (!strcmp(arg, "--color"))
3033 DIFF_OPT_SET(options, COLOR_DIFF);
3034 else if (!prefixcmp(arg, "--color=")) {
3035 int value = git_config_colorbool(NULL, arg+8, -1);
3036 if (value == 0)
3037 DIFF_OPT_CLR(options, COLOR_DIFF);
3038 else if (value > 0)
3039 DIFF_OPT_SET(options, COLOR_DIFF);
3040 else
3041 return error("option `color' expects \"always\", \"auto\", or \"never\"");
3043 else if (!strcmp(arg, "--no-color"))
3044 DIFF_OPT_CLR(options, COLOR_DIFF);
3045 else if (!strcmp(arg, "--color-words")) {
3046 DIFF_OPT_SET(options, COLOR_DIFF);
3047 options->word_diff = DIFF_WORDS_COLOR;
3049 else if (!prefixcmp(arg, "--color-words=")) {
3050 DIFF_OPT_SET(options, COLOR_DIFF);
3051 options->word_diff = DIFF_WORDS_COLOR;
3052 options->word_regex = arg + 14;
3054 else if (!strcmp(arg, "--word-diff")) {
3055 if (options->word_diff == DIFF_WORDS_NONE)
3056 options->word_diff = DIFF_WORDS_PLAIN;
3058 else if (!prefixcmp(arg, "--word-diff=")) {
3059 const char *type = arg + 12;
3060 if (!strcmp(type, "plain"))
3061 options->word_diff = DIFF_WORDS_PLAIN;
3062 else if (!strcmp(type, "color")) {
3063 DIFF_OPT_SET(options, COLOR_DIFF);
3064 options->word_diff = DIFF_WORDS_COLOR;
3066 else if (!strcmp(type, "porcelain"))
3067 options->word_diff = DIFF_WORDS_PORCELAIN;
3068 else if (!strcmp(type, "none"))
3069 options->word_diff = DIFF_WORDS_NONE;
3070 else
3071 die("bad --word-diff argument: %s", type);
3073 else if (!prefixcmp(arg, "--word-diff-regex=")) {
3074 if (options->word_diff == DIFF_WORDS_NONE)
3075 options->word_diff = DIFF_WORDS_PLAIN;
3076 options->word_regex = arg + 18;
3078 else if (!strcmp(arg, "--exit-code"))
3079 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3080 else if (!strcmp(arg, "--quiet"))
3081 DIFF_OPT_SET(options, QUICK);
3082 else if (!strcmp(arg, "--ext-diff"))
3083 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
3084 else if (!strcmp(arg, "--no-ext-diff"))
3085 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
3086 else if (!strcmp(arg, "--textconv"))
3087 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3088 else if (!strcmp(arg, "--no-textconv"))
3089 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
3090 else if (!strcmp(arg, "--ignore-submodules"))
3091 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
3092 else if (!strcmp(arg, "--submodule"))
3093 DIFF_OPT_SET(options, SUBMODULE_LOG);
3094 else if (!prefixcmp(arg, "--submodule=")) {
3095 if (!strcmp(arg + 12, "log"))
3096 DIFF_OPT_SET(options, SUBMODULE_LOG);
3099 /* misc options */
3100 else if (!strcmp(arg, "-z"))
3101 options->line_termination = 0;
3102 else if (!prefixcmp(arg, "-l"))
3103 options->rename_limit = strtoul(arg+2, NULL, 10);
3104 else if (!prefixcmp(arg, "-S"))
3105 options->pickaxe = arg + 2;
3106 else if (!strcmp(arg, "--pickaxe-all"))
3107 options->pickaxe_opts = DIFF_PICKAXE_ALL;
3108 else if (!strcmp(arg, "--pickaxe-regex"))
3109 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
3110 else if (!prefixcmp(arg, "-O"))
3111 options->orderfile = arg + 2;
3112 else if (!prefixcmp(arg, "--diff-filter="))
3113 options->filter = arg + 14;
3114 else if (!strcmp(arg, "--abbrev"))
3115 options->abbrev = DEFAULT_ABBREV;
3116 else if (!prefixcmp(arg, "--abbrev=")) {
3117 options->abbrev = strtoul(arg + 9, NULL, 10);
3118 if (options->abbrev < MINIMUM_ABBREV)
3119 options->abbrev = MINIMUM_ABBREV;
3120 else if (40 < options->abbrev)
3121 options->abbrev = 40;
3123 else if (!prefixcmp(arg, "--src-prefix="))
3124 options->a_prefix = arg + 13;
3125 else if (!prefixcmp(arg, "--dst-prefix="))
3126 options->b_prefix = arg + 13;
3127 else if (!strcmp(arg, "--no-prefix"))
3128 options->a_prefix = options->b_prefix = "";
3129 else if (opt_arg(arg, '\0', "inter-hunk-context",
3130 &options->interhunkcontext))
3132 else if (!prefixcmp(arg, "--output=")) {
3133 options->file = fopen(arg + strlen("--output="), "w");
3134 if (!options->file)
3135 die_errno("Could not open '%s'", arg + strlen("--output="));
3136 options->close_file = 1;
3137 } else
3138 return 0;
3139 return 1;
3142 static int parse_num(const char **cp_p)
3144 unsigned long num, scale;
3145 int ch, dot;
3146 const char *cp = *cp_p;
3148 num = 0;
3149 scale = 1;
3150 dot = 0;
3151 for (;;) {
3152 ch = *cp;
3153 if ( !dot && ch == '.' ) {
3154 scale = 1;
3155 dot = 1;
3156 } else if ( ch == '%' ) {
3157 scale = dot ? scale*100 : 100;
3158 cp++; /* % is always at the end */
3159 break;
3160 } else if ( ch >= '0' && ch <= '9' ) {
3161 if ( scale < 100000 ) {
3162 scale *= 10;
3163 num = (num*10) + (ch-'0');
3165 } else {
3166 break;
3168 cp++;
3170 *cp_p = cp;
3172 /* user says num divided by scale and we say internally that
3173 * is MAX_SCORE * num / scale.
3175 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3178 static int diff_scoreopt_parse(const char *opt)
3180 int opt1, opt2, cmd;
3182 if (*opt++ != '-')
3183 return -1;
3184 cmd = *opt++;
3185 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3186 return -1; /* that is not a -M, -C nor -B option */
3188 opt1 = parse_num(&opt);
3189 if (cmd != 'B')
3190 opt2 = 0;
3191 else {
3192 if (*opt == 0)
3193 opt2 = 0;
3194 else if (*opt != '/')
3195 return -1; /* we expect -B80/99 or -B80 */
3196 else {
3197 opt++;
3198 opt2 = parse_num(&opt);
3201 if (*opt != 0)
3202 return -1;
3203 return opt1 | (opt2 << 16);
3206 struct diff_queue_struct diff_queued_diff;
3208 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3210 if (queue->alloc <= queue->nr) {
3211 queue->alloc = alloc_nr(queue->alloc);
3212 queue->queue = xrealloc(queue->queue,
3213 sizeof(dp) * queue->alloc);
3215 queue->queue[queue->nr++] = dp;
3218 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3219 struct diff_filespec *one,
3220 struct diff_filespec *two)
3222 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3223 dp->one = one;
3224 dp->two = two;
3225 if (queue)
3226 diff_q(queue, dp);
3227 return dp;
3230 void diff_free_filepair(struct diff_filepair *p)
3232 free_filespec(p->one);
3233 free_filespec(p->two);
3234 free(p);
3237 /* This is different from find_unique_abbrev() in that
3238 * it stuffs the result with dots for alignment.
3240 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3242 int abblen;
3243 const char *abbrev;
3244 if (len == 40)
3245 return sha1_to_hex(sha1);
3247 abbrev = find_unique_abbrev(sha1, len);
3248 abblen = strlen(abbrev);
3249 if (abblen < 37) {
3250 static char hex[41];
3251 if (len < abblen && abblen <= len + 2)
3252 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3253 else
3254 sprintf(hex, "%s...", abbrev);
3255 return hex;
3257 return sha1_to_hex(sha1);
3260 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3262 int line_termination = opt->line_termination;
3263 int inter_name_termination = line_termination ? '\t' : '\0';
3265 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3266 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3267 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3268 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3270 if (p->score) {
3271 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3272 inter_name_termination);
3273 } else {
3274 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3277 if (p->status == DIFF_STATUS_COPIED ||
3278 p->status == DIFF_STATUS_RENAMED) {
3279 const char *name_a, *name_b;
3280 name_a = p->one->path;
3281 name_b = p->two->path;
3282 strip_prefix(opt->prefix_length, &name_a, &name_b);
3283 write_name_quoted(name_a, opt->file, inter_name_termination);
3284 write_name_quoted(name_b, opt->file, line_termination);
3285 } else {
3286 const char *name_a, *name_b;
3287 name_a = p->one->mode ? p->one->path : p->two->path;
3288 name_b = NULL;
3289 strip_prefix(opt->prefix_length, &name_a, &name_b);
3290 write_name_quoted(name_a, opt->file, line_termination);
3294 int diff_unmodified_pair(struct diff_filepair *p)
3296 /* This function is written stricter than necessary to support
3297 * the currently implemented transformers, but the idea is to
3298 * let transformers to produce diff_filepairs any way they want,
3299 * and filter and clean them up here before producing the output.
3301 struct diff_filespec *one = p->one, *two = p->two;
3303 if (DIFF_PAIR_UNMERGED(p))
3304 return 0; /* unmerged is interesting */
3306 /* deletion, addition, mode or type change
3307 * and rename are all interesting.
3309 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3310 DIFF_PAIR_MODE_CHANGED(p) ||
3311 strcmp(one->path, two->path))
3312 return 0;
3314 /* both are valid and point at the same path. that is, we are
3315 * dealing with a change.
3317 if (one->sha1_valid && two->sha1_valid &&
3318 !hashcmp(one->sha1, two->sha1) &&
3319 !one->dirty_submodule && !two->dirty_submodule)
3320 return 1; /* no change */
3321 if (!one->sha1_valid && !two->sha1_valid)
3322 return 1; /* both look at the same file on the filesystem. */
3323 return 0;
3326 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3328 if (diff_unmodified_pair(p))
3329 return;
3331 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3332 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3333 return; /* no tree diffs in patch format */
3335 run_diff(p, o);
3338 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3339 struct diffstat_t *diffstat)
3341 if (diff_unmodified_pair(p))
3342 return;
3344 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3345 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3346 return; /* no tree diffs in patch format */
3348 run_diffstat(p, o, diffstat);
3351 static void diff_flush_checkdiff(struct diff_filepair *p,
3352 struct diff_options *o)
3354 if (diff_unmodified_pair(p))
3355 return;
3357 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3358 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3359 return; /* no tree diffs in patch format */
3361 run_checkdiff(p, o);
3364 int diff_queue_is_empty(void)
3366 struct diff_queue_struct *q = &diff_queued_diff;
3367 int i;
3368 for (i = 0; i < q->nr; i++)
3369 if (!diff_unmodified_pair(q->queue[i]))
3370 return 0;
3371 return 1;
3374 #if DIFF_DEBUG
3375 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3377 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3378 x, one ? one : "",
3379 s->path,
3380 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3381 s->mode,
3382 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3383 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3384 x, one ? one : "",
3385 s->size, s->xfrm_flags);
3388 void diff_debug_filepair(const struct diff_filepair *p, int i)
3390 diff_debug_filespec(p->one, i, "one");
3391 diff_debug_filespec(p->two, i, "two");
3392 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3393 p->score, p->status ? p->status : '?',
3394 p->one->rename_used, p->broken_pair);
3397 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3399 int i;
3400 if (msg)
3401 fprintf(stderr, "%s\n", msg);
3402 fprintf(stderr, "q->nr = %d\n", q->nr);
3403 for (i = 0; i < q->nr; i++) {
3404 struct diff_filepair *p = q->queue[i];
3405 diff_debug_filepair(p, i);
3408 #endif
3410 static void diff_resolve_rename_copy(void)
3412 int i;
3413 struct diff_filepair *p;
3414 struct diff_queue_struct *q = &diff_queued_diff;
3416 diff_debug_queue("resolve-rename-copy", q);
3418 for (i = 0; i < q->nr; i++) {
3419 p = q->queue[i];
3420 p->status = 0; /* undecided */
3421 if (DIFF_PAIR_UNMERGED(p))
3422 p->status = DIFF_STATUS_UNMERGED;
3423 else if (!DIFF_FILE_VALID(p->one))
3424 p->status = DIFF_STATUS_ADDED;
3425 else if (!DIFF_FILE_VALID(p->two))
3426 p->status = DIFF_STATUS_DELETED;
3427 else if (DIFF_PAIR_TYPE_CHANGED(p))
3428 p->status = DIFF_STATUS_TYPE_CHANGED;
3430 /* from this point on, we are dealing with a pair
3431 * whose both sides are valid and of the same type, i.e.
3432 * either in-place edit or rename/copy edit.
3434 else if (DIFF_PAIR_RENAME(p)) {
3436 * A rename might have re-connected a broken
3437 * pair up, causing the pathnames to be the
3438 * same again. If so, that's not a rename at
3439 * all, just a modification..
3441 * Otherwise, see if this source was used for
3442 * multiple renames, in which case we decrement
3443 * the count, and call it a copy.
3445 if (!strcmp(p->one->path, p->two->path))
3446 p->status = DIFF_STATUS_MODIFIED;
3447 else if (--p->one->rename_used > 0)
3448 p->status = DIFF_STATUS_COPIED;
3449 else
3450 p->status = DIFF_STATUS_RENAMED;
3452 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3453 p->one->mode != p->two->mode ||
3454 p->one->dirty_submodule ||
3455 p->two->dirty_submodule ||
3456 is_null_sha1(p->one->sha1))
3457 p->status = DIFF_STATUS_MODIFIED;
3458 else {
3459 /* This is a "no-change" entry and should not
3460 * happen anymore, but prepare for broken callers.
3462 error("feeding unmodified %s to diffcore",
3463 p->one->path);
3464 p->status = DIFF_STATUS_UNKNOWN;
3467 diff_debug_queue("resolve-rename-copy done", q);
3470 static int check_pair_status(struct diff_filepair *p)
3472 switch (p->status) {
3473 case DIFF_STATUS_UNKNOWN:
3474 return 0;
3475 case 0:
3476 die("internal error in diff-resolve-rename-copy");
3477 default:
3478 return 1;
3482 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3484 int fmt = opt->output_format;
3486 if (fmt & DIFF_FORMAT_CHECKDIFF)
3487 diff_flush_checkdiff(p, opt);
3488 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3489 diff_flush_raw(p, opt);
3490 else if (fmt & DIFF_FORMAT_NAME) {
3491 const char *name_a, *name_b;
3492 name_a = p->two->path;
3493 name_b = NULL;
3494 strip_prefix(opt->prefix_length, &name_a, &name_b);
3495 write_name_quoted(name_a, opt->file, opt->line_termination);
3499 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3501 if (fs->mode)
3502 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3503 else
3504 fprintf(file, " %s ", newdelete);
3505 write_name_quoted(fs->path, file, '\n');
3509 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3511 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3512 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3513 show_name ? ' ' : '\n');
3514 if (show_name) {
3515 write_name_quoted(p->two->path, file, '\n');
3520 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3522 char *names = pprint_rename(p->one->path, p->two->path);
3524 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3525 free(names);
3526 show_mode_change(file, p, 0);
3529 static void diff_summary(FILE *file, struct diff_filepair *p)
3531 switch(p->status) {
3532 case DIFF_STATUS_DELETED:
3533 show_file_mode_name(file, "delete", p->one);
3534 break;
3535 case DIFF_STATUS_ADDED:
3536 show_file_mode_name(file, "create", p->two);
3537 break;
3538 case DIFF_STATUS_COPIED:
3539 show_rename_copy(file, "copy", p);
3540 break;
3541 case DIFF_STATUS_RENAMED:
3542 show_rename_copy(file, "rename", p);
3543 break;
3544 default:
3545 if (p->score) {
3546 fputs(" rewrite ", file);
3547 write_name_quoted(p->two->path, file, ' ');
3548 fprintf(file, "(%d%%)\n", similarity_index(p));
3550 show_mode_change(file, p, !p->score);
3551 break;
3555 struct patch_id_t {
3556 git_SHA_CTX *ctx;
3557 int patchlen;
3560 static int remove_space(char *line, int len)
3562 int i;
3563 char *dst = line;
3564 unsigned char c;
3566 for (i = 0; i < len; i++)
3567 if (!isspace((c = line[i])))
3568 *dst++ = c;
3570 return dst - line;
3573 static void patch_id_consume(void *priv, char *line, unsigned long len)
3575 struct patch_id_t *data = priv;
3576 int new_len;
3578 /* Ignore line numbers when computing the SHA1 of the patch */
3579 if (!prefixcmp(line, "@@ -"))
3580 return;
3582 new_len = remove_space(line, len);
3584 git_SHA1_Update(data->ctx, line, new_len);
3585 data->patchlen += new_len;
3588 /* returns 0 upon success, and writes result into sha1 */
3589 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3591 struct diff_queue_struct *q = &diff_queued_diff;
3592 int i;
3593 git_SHA_CTX ctx;
3594 struct patch_id_t data;
3595 char buffer[PATH_MAX * 4 + 20];
3597 git_SHA1_Init(&ctx);
3598 memset(&data, 0, sizeof(struct patch_id_t));
3599 data.ctx = &ctx;
3601 for (i = 0; i < q->nr; i++) {
3602 xpparam_t xpp;
3603 xdemitconf_t xecfg;
3604 mmfile_t mf1, mf2;
3605 struct diff_filepair *p = q->queue[i];
3606 int len1, len2;
3608 memset(&xpp, 0, sizeof(xpp));
3609 memset(&xecfg, 0, sizeof(xecfg));
3610 if (p->status == 0)
3611 return error("internal diff status error");
3612 if (p->status == DIFF_STATUS_UNKNOWN)
3613 continue;
3614 if (diff_unmodified_pair(p))
3615 continue;
3616 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3617 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3618 continue;
3619 if (DIFF_PAIR_UNMERGED(p))
3620 continue;
3622 diff_fill_sha1_info(p->one);
3623 diff_fill_sha1_info(p->two);
3624 if (fill_mmfile(&mf1, p->one) < 0 ||
3625 fill_mmfile(&mf2, p->two) < 0)
3626 return error("unable to read files to diff");
3628 len1 = remove_space(p->one->path, strlen(p->one->path));
3629 len2 = remove_space(p->two->path, strlen(p->two->path));
3630 if (p->one->mode == 0)
3631 len1 = snprintf(buffer, sizeof(buffer),
3632 "diff--gita/%.*sb/%.*s"
3633 "newfilemode%06o"
3634 "---/dev/null"
3635 "+++b/%.*s",
3636 len1, p->one->path,
3637 len2, p->two->path,
3638 p->two->mode,
3639 len2, p->two->path);
3640 else if (p->two->mode == 0)
3641 len1 = snprintf(buffer, sizeof(buffer),
3642 "diff--gita/%.*sb/%.*s"
3643 "deletedfilemode%06o"
3644 "---a/%.*s"
3645 "+++/dev/null",
3646 len1, p->one->path,
3647 len2, p->two->path,
3648 p->one->mode,
3649 len1, p->one->path);
3650 else
3651 len1 = snprintf(buffer, sizeof(buffer),
3652 "diff--gita/%.*sb/%.*s"
3653 "---a/%.*s"
3654 "+++b/%.*s",
3655 len1, p->one->path,
3656 len2, p->two->path,
3657 len1, p->one->path,
3658 len2, p->two->path);
3659 git_SHA1_Update(&ctx, buffer, len1);
3661 xpp.flags = 0;
3662 xecfg.ctxlen = 3;
3663 xecfg.flags = XDL_EMIT_FUNCNAMES;
3664 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3665 &xpp, &xecfg);
3668 git_SHA1_Final(sha1, &ctx);
3669 return 0;
3672 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3674 struct diff_queue_struct *q = &diff_queued_diff;
3675 int i;
3676 int result = diff_get_patch_id(options, sha1);
3678 for (i = 0; i < q->nr; i++)
3679 diff_free_filepair(q->queue[i]);
3681 free(q->queue);
3682 DIFF_QUEUE_CLEAR(q);
3684 return result;
3687 static int is_summary_empty(const struct diff_queue_struct *q)
3689 int i;
3691 for (i = 0; i < q->nr; i++) {
3692 const struct diff_filepair *p = q->queue[i];
3694 switch (p->status) {
3695 case DIFF_STATUS_DELETED:
3696 case DIFF_STATUS_ADDED:
3697 case DIFF_STATUS_COPIED:
3698 case DIFF_STATUS_RENAMED:
3699 return 0;
3700 default:
3701 if (p->score)
3702 return 0;
3703 if (p->one->mode && p->two->mode &&
3704 p->one->mode != p->two->mode)
3705 return 0;
3706 break;
3709 return 1;
3712 void diff_flush(struct diff_options *options)
3714 struct diff_queue_struct *q = &diff_queued_diff;
3715 int i, output_format = options->output_format;
3716 int separator = 0;
3719 * Order: raw, stat, summary, patch
3720 * or: name/name-status/checkdiff (other bits clear)
3722 if (!q->nr)
3723 goto free_queue;
3725 if (output_format & (DIFF_FORMAT_RAW |
3726 DIFF_FORMAT_NAME |
3727 DIFF_FORMAT_NAME_STATUS |
3728 DIFF_FORMAT_CHECKDIFF)) {
3729 for (i = 0; i < q->nr; i++) {
3730 struct diff_filepair *p = q->queue[i];
3731 if (check_pair_status(p))
3732 flush_one_pair(p, options);
3734 separator++;
3737 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3738 struct diffstat_t diffstat;
3740 memset(&diffstat, 0, sizeof(struct diffstat_t));
3741 for (i = 0; i < q->nr; i++) {
3742 struct diff_filepair *p = q->queue[i];
3743 if (check_pair_status(p))
3744 diff_flush_stat(p, options, &diffstat);
3746 if (output_format & DIFF_FORMAT_NUMSTAT)
3747 show_numstat(&diffstat, options);
3748 if (output_format & DIFF_FORMAT_DIFFSTAT)
3749 show_stats(&diffstat, options);
3750 if (output_format & DIFF_FORMAT_SHORTSTAT)
3751 show_shortstats(&diffstat, options);
3752 free_diffstat_info(&diffstat);
3753 separator++;
3755 if (output_format & DIFF_FORMAT_DIRSTAT)
3756 show_dirstat(options);
3758 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3759 for (i = 0; i < q->nr; i++)
3760 diff_summary(options->file, q->queue[i]);
3761 separator++;
3764 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
3765 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
3766 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3768 * run diff_flush_patch for the exit status. setting
3769 * options->file to /dev/null should be safe, becaue we
3770 * aren't supposed to produce any output anyway.
3772 if (options->close_file)
3773 fclose(options->file);
3774 options->file = fopen("/dev/null", "w");
3775 if (!options->file)
3776 die_errno("Could not open /dev/null");
3777 options->close_file = 1;
3778 for (i = 0; i < q->nr; i++) {
3779 struct diff_filepair *p = q->queue[i];
3780 if (check_pair_status(p))
3781 diff_flush_patch(p, options);
3782 if (options->found_changes)
3783 break;
3787 if (output_format & DIFF_FORMAT_PATCH) {
3788 if (separator) {
3789 putc(options->line_termination, options->file);
3790 if (options->stat_sep) {
3791 /* attach patch instead of inline */
3792 fputs(options->stat_sep, options->file);
3796 for (i = 0; i < q->nr; i++) {
3797 struct diff_filepair *p = q->queue[i];
3798 if (check_pair_status(p))
3799 diff_flush_patch(p, options);
3803 if (output_format & DIFF_FORMAT_CALLBACK)
3804 options->format_callback(q, options, options->format_callback_data);
3806 for (i = 0; i < q->nr; i++)
3807 diff_free_filepair(q->queue[i]);
3808 free_queue:
3809 free(q->queue);
3810 DIFF_QUEUE_CLEAR(q);
3811 if (options->close_file)
3812 fclose(options->file);
3815 * Report the content-level differences with HAS_CHANGES;
3816 * diff_addremove/diff_change does not set the bit when
3817 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3819 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3820 if (options->found_changes)
3821 DIFF_OPT_SET(options, HAS_CHANGES);
3822 else
3823 DIFF_OPT_CLR(options, HAS_CHANGES);
3827 static void diffcore_apply_filter(const char *filter)
3829 int i;
3830 struct diff_queue_struct *q = &diff_queued_diff;
3831 struct diff_queue_struct outq;
3832 DIFF_QUEUE_CLEAR(&outq);
3834 if (!filter)
3835 return;
3837 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3838 int found;
3839 for (i = found = 0; !found && i < q->nr; i++) {
3840 struct diff_filepair *p = q->queue[i];
3841 if (((p->status == DIFF_STATUS_MODIFIED) &&
3842 ((p->score &&
3843 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3844 (!p->score &&
3845 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3846 ((p->status != DIFF_STATUS_MODIFIED) &&
3847 strchr(filter, p->status)))
3848 found++;
3850 if (found)
3851 return;
3853 /* otherwise we will clear the whole queue
3854 * by copying the empty outq at the end of this
3855 * function, but first clear the current entries
3856 * in the queue.
3858 for (i = 0; i < q->nr; i++)
3859 diff_free_filepair(q->queue[i]);
3861 else {
3862 /* Only the matching ones */
3863 for (i = 0; i < q->nr; i++) {
3864 struct diff_filepair *p = q->queue[i];
3866 if (((p->status == DIFF_STATUS_MODIFIED) &&
3867 ((p->score &&
3868 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3869 (!p->score &&
3870 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3871 ((p->status != DIFF_STATUS_MODIFIED) &&
3872 strchr(filter, p->status)))
3873 diff_q(&outq, p);
3874 else
3875 diff_free_filepair(p);
3878 free(q->queue);
3879 *q = outq;
3882 /* Check whether two filespecs with the same mode and size are identical */
3883 static int diff_filespec_is_identical(struct diff_filespec *one,
3884 struct diff_filespec *two)
3886 if (S_ISGITLINK(one->mode))
3887 return 0;
3888 if (diff_populate_filespec(one, 0))
3889 return 0;
3890 if (diff_populate_filespec(two, 0))
3891 return 0;
3892 return !memcmp(one->data, two->data, one->size);
3895 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3897 int i;
3898 struct diff_queue_struct *q = &diff_queued_diff;
3899 struct diff_queue_struct outq;
3900 DIFF_QUEUE_CLEAR(&outq);
3902 for (i = 0; i < q->nr; i++) {
3903 struct diff_filepair *p = q->queue[i];
3906 * 1. Entries that come from stat info dirtiness
3907 * always have both sides (iow, not create/delete),
3908 * one side of the object name is unknown, with
3909 * the same mode and size. Keep the ones that
3910 * do not match these criteria. They have real
3911 * differences.
3913 * 2. At this point, the file is known to be modified,
3914 * with the same mode and size, and the object
3915 * name of one side is unknown. Need to inspect
3916 * the identical contents.
3918 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3919 !DIFF_FILE_VALID(p->two) ||
3920 (p->one->sha1_valid && p->two->sha1_valid) ||
3921 (p->one->mode != p->two->mode) ||
3922 diff_populate_filespec(p->one, 1) ||
3923 diff_populate_filespec(p->two, 1) ||
3924 (p->one->size != p->two->size) ||
3925 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3926 diff_q(&outq, p);
3927 else {
3929 * The caller can subtract 1 from skip_stat_unmatch
3930 * to determine how many paths were dirty only
3931 * due to stat info mismatch.
3933 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3934 diffopt->skip_stat_unmatch++;
3935 diff_free_filepair(p);
3938 free(q->queue);
3939 *q = outq;
3942 static int diffnamecmp(const void *a_, const void *b_)
3944 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
3945 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
3946 const char *name_a, *name_b;
3948 name_a = a->one ? a->one->path : a->two->path;
3949 name_b = b->one ? b->one->path : b->two->path;
3950 return strcmp(name_a, name_b);
3953 void diffcore_fix_diff_index(struct diff_options *options)
3955 struct diff_queue_struct *q = &diff_queued_diff;
3956 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
3959 void diffcore_std(struct diff_options *options)
3961 /* We never run this function more than one time, because the
3962 * rename/copy detection logic can only run once.
3964 if (diff_queued_diff.run)
3965 return;
3967 if (options->skip_stat_unmatch)
3968 diffcore_skip_stat_unmatch(options);
3969 if (options->break_opt != -1)
3970 diffcore_break(options->break_opt);
3971 if (options->detect_rename)
3972 diffcore_rename(options);
3973 if (options->break_opt != -1)
3974 diffcore_merge_broken();
3975 if (options->pickaxe)
3976 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3977 if (options->orderfile)
3978 diffcore_order(options->orderfile);
3979 diff_resolve_rename_copy();
3980 diffcore_apply_filter(options->filter);
3982 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3983 DIFF_OPT_SET(options, HAS_CHANGES);
3984 else
3985 DIFF_OPT_CLR(options, HAS_CHANGES);
3987 diff_queued_diff.run = 1;
3990 int diff_result_code(struct diff_options *opt, int status)
3992 int result = 0;
3993 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3994 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3995 return status;
3996 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3997 DIFF_OPT_TST(opt, HAS_CHANGES))
3998 result |= 01;
3999 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4000 DIFF_OPT_TST(opt, CHECK_FAILED))
4001 result |= 02;
4002 return result;
4005 void diff_addremove(struct diff_options *options,
4006 int addremove, unsigned mode,
4007 const unsigned char *sha1,
4008 const char *concatpath, unsigned dirty_submodule)
4010 struct diff_filespec *one, *two;
4012 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
4013 return;
4015 /* This may look odd, but it is a preparation for
4016 * feeding "there are unchanged files which should
4017 * not produce diffs, but when you are doing copy
4018 * detection you would need them, so here they are"
4019 * entries to the diff-core. They will be prefixed
4020 * with something like '=' or '*' (I haven't decided
4021 * which but should not make any difference).
4022 * Feeding the same new and old to diff_change()
4023 * also has the same effect.
4024 * Before the final output happens, they are pruned after
4025 * merged into rename/copy pairs as appropriate.
4027 if (DIFF_OPT_TST(options, REVERSE_DIFF))
4028 addremove = (addremove == '+' ? '-' :
4029 addremove == '-' ? '+' : addremove);
4031 if (options->prefix &&
4032 strncmp(concatpath, options->prefix, options->prefix_length))
4033 return;
4035 one = alloc_filespec(concatpath);
4036 two = alloc_filespec(concatpath);
4038 if (addremove != '+')
4039 fill_filespec(one, sha1, mode);
4040 if (addremove != '-') {
4041 fill_filespec(two, sha1, mode);
4042 two->dirty_submodule = dirty_submodule;
4045 diff_queue(&diff_queued_diff, one, two);
4046 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4047 DIFF_OPT_SET(options, HAS_CHANGES);
4050 void diff_change(struct diff_options *options,
4051 unsigned old_mode, unsigned new_mode,
4052 const unsigned char *old_sha1,
4053 const unsigned char *new_sha1,
4054 const char *concatpath,
4055 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
4057 struct diff_filespec *one, *two;
4059 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
4060 && S_ISGITLINK(new_mode))
4061 return;
4063 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
4064 unsigned tmp;
4065 const unsigned char *tmp_c;
4066 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
4067 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
4068 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
4069 new_dirty_submodule = tmp;
4072 if (options->prefix &&
4073 strncmp(concatpath, options->prefix, options->prefix_length))
4074 return;
4076 one = alloc_filespec(concatpath);
4077 two = alloc_filespec(concatpath);
4078 fill_filespec(one, old_sha1, old_mode);
4079 fill_filespec(two, new_sha1, new_mode);
4080 one->dirty_submodule = old_dirty_submodule;
4081 two->dirty_submodule = new_dirty_submodule;
4083 diff_queue(&diff_queued_diff, one, two);
4084 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4085 DIFF_OPT_SET(options, HAS_CHANGES);
4088 void diff_unmerge(struct diff_options *options,
4089 const char *path,
4090 unsigned mode, const unsigned char *sha1)
4092 struct diff_filespec *one, *two;
4094 if (options->prefix &&
4095 strncmp(path, options->prefix, options->prefix_length))
4096 return;
4098 one = alloc_filespec(path);
4099 two = alloc_filespec(path);
4100 fill_filespec(one, sha1, mode);
4101 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
4104 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
4105 size_t *outsize)
4107 struct diff_tempfile *temp;
4108 const char *argv[3];
4109 const char **arg = argv;
4110 struct child_process child;
4111 struct strbuf buf = STRBUF_INIT;
4112 int err = 0;
4114 temp = prepare_temp_file(spec->path, spec);
4115 *arg++ = pgm;
4116 *arg++ = temp->name;
4117 *arg = NULL;
4119 memset(&child, 0, sizeof(child));
4120 child.use_shell = 1;
4121 child.argv = argv;
4122 child.out = -1;
4123 if (start_command(&child)) {
4124 remove_tempfile();
4125 return NULL;
4128 if (strbuf_read(&buf, child.out, 0) < 0)
4129 err = error("error reading from textconv command '%s'", pgm);
4130 close(child.out);
4132 if (finish_command(&child) || err) {
4133 strbuf_release(&buf);
4134 remove_tempfile();
4135 return NULL;
4137 remove_tempfile();
4139 return strbuf_detach(&buf, outsize);
4142 static size_t fill_textconv(struct userdiff_driver *driver,
4143 struct diff_filespec *df,
4144 char **outbuf)
4146 size_t size;
4148 if (!driver || !driver->textconv) {
4149 if (!DIFF_FILE_VALID(df)) {
4150 *outbuf = "";
4151 return 0;
4153 if (diff_populate_filespec(df, 0))
4154 die("unable to read files to diff");
4155 *outbuf = df->data;
4156 return df->size;
4159 if (driver->textconv_cache) {
4160 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4161 &size);
4162 if (*outbuf)
4163 return size;
4166 *outbuf = run_textconv(driver->textconv, df, &size);
4167 if (!*outbuf)
4168 die("unable to read files to diff");
4170 if (driver->textconv_cache) {
4171 /* ignore errors, as we might be in a readonly repository */
4172 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4173 size);
4175 * we could save up changes and flush them all at the end,
4176 * but we would need an extra call after all diffing is done.
4177 * Since generating a cache entry is the slow path anyway,
4178 * this extra overhead probably isn't a big deal.
4180 notes_cache_write(driver->textconv_cache);
4183 return size;