New --dirstat=lines mode, doing dirstat analysis based on diffstat
[git.git] / diff.c
blob919a16d89e83bdd256fc0bb43e7e22d34036627b
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 = 400;
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;
34 static int diff_dirstat_permille_default = 30;
35 static struct diff_options default_diff_options;
37 static char diff_colors[][COLOR_MAXLEN] = {
38 GIT_COLOR_RESET,
39 GIT_COLOR_NORMAL, /* PLAIN */
40 GIT_COLOR_BOLD, /* METAINFO */
41 GIT_COLOR_CYAN, /* FRAGINFO */
42 GIT_COLOR_RED, /* OLD */
43 GIT_COLOR_GREEN, /* NEW */
44 GIT_COLOR_YELLOW, /* COMMIT */
45 GIT_COLOR_BG_RED, /* WHITESPACE */
46 GIT_COLOR_NORMAL, /* FUNCINFO */
49 static int parse_diff_color_slot(const char *var, int ofs)
51 if (!strcasecmp(var+ofs, "plain"))
52 return DIFF_PLAIN;
53 if (!strcasecmp(var+ofs, "meta"))
54 return DIFF_METAINFO;
55 if (!strcasecmp(var+ofs, "frag"))
56 return DIFF_FRAGINFO;
57 if (!strcasecmp(var+ofs, "old"))
58 return DIFF_FILE_OLD;
59 if (!strcasecmp(var+ofs, "new"))
60 return DIFF_FILE_NEW;
61 if (!strcasecmp(var+ofs, "commit"))
62 return DIFF_COMMIT;
63 if (!strcasecmp(var+ofs, "whitespace"))
64 return DIFF_WHITESPACE;
65 if (!strcasecmp(var+ofs, "func"))
66 return DIFF_FUNCINFO;
67 return -1;
70 static int parse_dirstat_params(struct diff_options *options, const char *params)
72 const char *p = params;
73 while (*p) {
74 if (!prefixcmp(p, "changes")) {
75 p += 7;
76 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
77 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
78 } else if (!prefixcmp(p, "lines")) {
79 p += 5;
80 DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
81 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
82 } else if (!prefixcmp(p, "files")) {
83 p += 5;
84 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
85 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
86 } else if (!prefixcmp(p, "noncumulative")) {
87 p += 13;
88 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
89 } else if (!prefixcmp(p, "cumulative")) {
90 p += 10;
91 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
92 } else if (isdigit(*p)) {
93 char *end;
94 options->dirstat_permille = strtoul(p, &end, 10) * 10;
95 p = end;
96 if (*p == '.' && isdigit(*++p)) {
97 /* only use first digit */
98 options->dirstat_permille += *p - '0';
99 /* .. and ignore any further digits */
100 while (isdigit(*++p))
101 ; /* nothing */
103 } else
104 return error("Unknown --dirstat parameter '%s'", p);
106 if (*p) {
107 /* more parameters, swallow separator */
108 if (*p != ',')
109 return error("Missing comma separator at char "
110 "%"PRIuMAX" of '%s'",
111 (uintmax_t) (p - params), params);
112 p++;
115 return 0;
118 static int git_config_rename(const char *var, const char *value)
120 if (!value)
121 return DIFF_DETECT_RENAME;
122 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
123 return DIFF_DETECT_COPY;
124 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
128 * These are to give UI layer defaults.
129 * The core-level commands such as git-diff-files should
130 * never be affected by the setting of diff.renames
131 * the user happens to have in the configuration file.
133 int git_diff_ui_config(const char *var, const char *value, void *cb)
135 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
136 diff_use_color_default = git_config_colorbool(var, value, -1);
137 return 0;
139 if (!strcmp(var, "diff.renames")) {
140 diff_detect_rename_default = git_config_rename(var, value);
141 return 0;
143 if (!strcmp(var, "diff.autorefreshindex")) {
144 diff_auto_refresh_index = git_config_bool(var, value);
145 return 0;
147 if (!strcmp(var, "diff.mnemonicprefix")) {
148 diff_mnemonic_prefix = git_config_bool(var, value);
149 return 0;
151 if (!strcmp(var, "diff.noprefix")) {
152 diff_no_prefix = git_config_bool(var, value);
153 return 0;
155 if (!strcmp(var, "diff.external"))
156 return git_config_string(&external_diff_cmd_cfg, var, value);
157 if (!strcmp(var, "diff.wordregex"))
158 return git_config_string(&diff_word_regex_cfg, var, value);
160 if (!strcmp(var, "diff.ignoresubmodules"))
161 handle_ignore_submodules_arg(&default_diff_options, value);
163 return git_diff_basic_config(var, value, cb);
166 int git_diff_basic_config(const char *var, const char *value, void *cb)
168 if (!strcmp(var, "diff.renamelimit")) {
169 diff_rename_limit_default = git_config_int(var, value);
170 return 0;
173 switch (userdiff_config(var, value)) {
174 case 0: break;
175 case -1: return -1;
176 default: return 0;
179 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
180 int slot = parse_diff_color_slot(var, 11);
181 if (slot < 0)
182 return 0;
183 if (!value)
184 return config_error_nonbool(var);
185 color_parse(value, var, diff_colors[slot]);
186 return 0;
189 /* like GNU diff's --suppress-blank-empty option */
190 if (!strcmp(var, "diff.suppressblankempty") ||
191 /* for backwards compatibility */
192 !strcmp(var, "diff.suppress-blank-empty")) {
193 diff_suppress_blank_empty = git_config_bool(var, value);
194 return 0;
197 if (!strcmp(var, "diff.dirstat")) {
198 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
199 (void) parse_dirstat_params(&default_diff_options, value);
200 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
201 return 0;
204 if (!prefixcmp(var, "submodule."))
205 return parse_submodule_config_option(var, value);
207 return git_color_default_config(var, value, cb);
210 static char *quote_two(const char *one, const char *two)
212 int need_one = quote_c_style(one, NULL, NULL, 1);
213 int need_two = quote_c_style(two, NULL, NULL, 1);
214 struct strbuf res = STRBUF_INIT;
216 if (need_one + need_two) {
217 strbuf_addch(&res, '"');
218 quote_c_style(one, &res, NULL, 1);
219 quote_c_style(two, &res, NULL, 1);
220 strbuf_addch(&res, '"');
221 } else {
222 strbuf_addstr(&res, one);
223 strbuf_addstr(&res, two);
225 return strbuf_detach(&res, NULL);
228 static const char *external_diff(void)
230 static const char *external_diff_cmd = NULL;
231 static int done_preparing = 0;
233 if (done_preparing)
234 return external_diff_cmd;
235 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
236 if (!external_diff_cmd)
237 external_diff_cmd = external_diff_cmd_cfg;
238 done_preparing = 1;
239 return external_diff_cmd;
242 static struct diff_tempfile {
243 const char *name; /* filename external diff should read from */
244 char hex[41];
245 char mode[10];
246 char tmp_path[PATH_MAX];
247 } diff_temp[2];
249 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
251 struct emit_callback {
252 int color_diff;
253 unsigned ws_rule;
254 int blank_at_eof_in_preimage;
255 int blank_at_eof_in_postimage;
256 int lno_in_preimage;
257 int lno_in_postimage;
258 sane_truncate_fn truncate;
259 const char **label_path;
260 struct diff_words_data *diff_words;
261 struct diff_options *opt;
262 int *found_changesp;
263 struct strbuf *header;
266 static int count_lines(const char *data, int size)
268 int count, ch, completely_empty = 1, nl_just_seen = 0;
269 count = 0;
270 while (0 < size--) {
271 ch = *data++;
272 if (ch == '\n') {
273 count++;
274 nl_just_seen = 1;
275 completely_empty = 0;
277 else {
278 nl_just_seen = 0;
279 completely_empty = 0;
282 if (completely_empty)
283 return 0;
284 if (!nl_just_seen)
285 count++; /* no trailing newline */
286 return count;
289 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
291 if (!DIFF_FILE_VALID(one)) {
292 mf->ptr = (char *)""; /* does not matter */
293 mf->size = 0;
294 return 0;
296 else if (diff_populate_filespec(one, 0))
297 return -1;
299 mf->ptr = one->data;
300 mf->size = one->size;
301 return 0;
304 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
305 static unsigned long diff_filespec_size(struct diff_filespec *one)
307 if (!DIFF_FILE_VALID(one))
308 return 0;
309 diff_populate_filespec(one, 1);
310 return one->size;
313 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
315 char *ptr = mf->ptr;
316 long size = mf->size;
317 int cnt = 0;
319 if (!size)
320 return cnt;
321 ptr += size - 1; /* pointing at the very end */
322 if (*ptr != '\n')
323 ; /* incomplete line */
324 else
325 ptr--; /* skip the last LF */
326 while (mf->ptr < ptr) {
327 char *prev_eol;
328 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
329 if (*prev_eol == '\n')
330 break;
331 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
332 break;
333 cnt++;
334 ptr = prev_eol - 1;
336 return cnt;
339 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
340 struct emit_callback *ecbdata)
342 int l1, l2, at;
343 unsigned ws_rule = ecbdata->ws_rule;
344 l1 = count_trailing_blank(mf1, ws_rule);
345 l2 = count_trailing_blank(mf2, ws_rule);
346 if (l2 <= l1) {
347 ecbdata->blank_at_eof_in_preimage = 0;
348 ecbdata->blank_at_eof_in_postimage = 0;
349 return;
351 at = count_lines(mf1->ptr, mf1->size);
352 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
354 at = count_lines(mf2->ptr, mf2->size);
355 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
358 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
359 int first, const char *line, int len)
361 int has_trailing_newline, has_trailing_carriage_return;
362 int nofirst;
363 FILE *file = o->file;
365 if (o->output_prefix) {
366 struct strbuf *msg = NULL;
367 msg = o->output_prefix(o, o->output_prefix_data);
368 assert(msg);
369 fwrite(msg->buf, msg->len, 1, file);
372 if (len == 0) {
373 has_trailing_newline = (first == '\n');
374 has_trailing_carriage_return = (!has_trailing_newline &&
375 (first == '\r'));
376 nofirst = has_trailing_newline || has_trailing_carriage_return;
377 } else {
378 has_trailing_newline = (len > 0 && line[len-1] == '\n');
379 if (has_trailing_newline)
380 len--;
381 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
382 if (has_trailing_carriage_return)
383 len--;
384 nofirst = 0;
387 if (len || !nofirst) {
388 fputs(set, file);
389 if (!nofirst)
390 fputc(first, file);
391 fwrite(line, len, 1, file);
392 fputs(reset, file);
394 if (has_trailing_carriage_return)
395 fputc('\r', file);
396 if (has_trailing_newline)
397 fputc('\n', file);
400 static void emit_line(struct diff_options *o, const char *set, const char *reset,
401 const char *line, int len)
403 emit_line_0(o, set, reset, line[0], line+1, len-1);
406 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
408 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
409 ecbdata->blank_at_eof_in_preimage &&
410 ecbdata->blank_at_eof_in_postimage &&
411 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
412 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
413 return 0;
414 return ws_blank_line(line, len, ecbdata->ws_rule);
417 static void emit_add_line(const char *reset,
418 struct emit_callback *ecbdata,
419 const char *line, int len)
421 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
422 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
424 if (!*ws)
425 emit_line_0(ecbdata->opt, set, reset, '+', line, len);
426 else if (new_blank_line_at_eof(ecbdata, line, len))
427 /* Blank line at EOF - paint '+' as well */
428 emit_line_0(ecbdata->opt, ws, reset, '+', line, len);
429 else {
430 /* Emit just the prefix, then the rest. */
431 emit_line_0(ecbdata->opt, set, reset, '+', "", 0);
432 ws_check_emit(line, len, ecbdata->ws_rule,
433 ecbdata->opt->file, set, reset, ws);
437 static void emit_hunk_header(struct emit_callback *ecbdata,
438 const char *line, int len)
440 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
441 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
442 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
443 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
444 static const char atat[2] = { '@', '@' };
445 const char *cp, *ep;
446 struct strbuf msgbuf = STRBUF_INIT;
447 int org_len = len;
448 int i = 1;
451 * As a hunk header must begin with "@@ -<old>, +<new> @@",
452 * it always is at least 10 bytes long.
454 if (len < 10 ||
455 memcmp(line, atat, 2) ||
456 !(ep = memmem(line + 2, len - 2, atat, 2))) {
457 emit_line(ecbdata->opt, plain, reset, line, len);
458 return;
460 ep += 2; /* skip over @@ */
462 /* The hunk header in fraginfo color */
463 strbuf_add(&msgbuf, frag, strlen(frag));
464 strbuf_add(&msgbuf, line, ep - line);
465 strbuf_add(&msgbuf, reset, strlen(reset));
468 * trailing "\r\n"
470 for ( ; i < 3; i++)
471 if (line[len - i] == '\r' || line[len - i] == '\n')
472 len--;
474 /* blank before the func header */
475 for (cp = ep; ep - line < len; ep++)
476 if (*ep != ' ' && *ep != '\t')
477 break;
478 if (ep != cp) {
479 strbuf_add(&msgbuf, plain, strlen(plain));
480 strbuf_add(&msgbuf, cp, ep - cp);
481 strbuf_add(&msgbuf, reset, strlen(reset));
484 if (ep < line + len) {
485 strbuf_add(&msgbuf, func, strlen(func));
486 strbuf_add(&msgbuf, ep, line + len - ep);
487 strbuf_add(&msgbuf, reset, strlen(reset));
490 strbuf_add(&msgbuf, line + len, org_len - len);
491 emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
492 strbuf_release(&msgbuf);
495 static struct diff_tempfile *claim_diff_tempfile(void) {
496 int i;
497 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
498 if (!diff_temp[i].name)
499 return diff_temp + i;
500 die("BUG: diff is failing to clean up its tempfiles");
503 static int remove_tempfile_installed;
505 static void remove_tempfile(void)
507 int i;
508 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
509 if (diff_temp[i].name == diff_temp[i].tmp_path)
510 unlink_or_warn(diff_temp[i].name);
511 diff_temp[i].name = NULL;
515 static void remove_tempfile_on_signal(int signo)
517 remove_tempfile();
518 sigchain_pop(signo);
519 raise(signo);
522 static void print_line_count(FILE *file, int count)
524 switch (count) {
525 case 0:
526 fprintf(file, "0,0");
527 break;
528 case 1:
529 fprintf(file, "1");
530 break;
531 default:
532 fprintf(file, "1,%d", count);
533 break;
537 static void emit_rewrite_lines(struct emit_callback *ecb,
538 int prefix, const char *data, int size)
540 const char *endp = NULL;
541 static const char *nneof = " No newline at end of file\n";
542 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
543 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
545 while (0 < size) {
546 int len;
548 endp = memchr(data, '\n', size);
549 len = endp ? (endp - data + 1) : size;
550 if (prefix != '+') {
551 ecb->lno_in_preimage++;
552 emit_line_0(ecb->opt, old, reset, '-',
553 data, len);
554 } else {
555 ecb->lno_in_postimage++;
556 emit_add_line(reset, ecb, data, len);
558 size -= len;
559 data += len;
561 if (!endp) {
562 const char *plain = diff_get_color(ecb->color_diff,
563 DIFF_PLAIN);
564 emit_line_0(ecb->opt, plain, reset, '\\',
565 nneof, strlen(nneof));
569 static void emit_rewrite_diff(const char *name_a,
570 const char *name_b,
571 struct diff_filespec *one,
572 struct diff_filespec *two,
573 struct userdiff_driver *textconv_one,
574 struct userdiff_driver *textconv_two,
575 struct diff_options *o)
577 int lc_a, lc_b;
578 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
579 const char *name_a_tab, *name_b_tab;
580 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
581 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
582 const char *reset = diff_get_color(color_diff, DIFF_RESET);
583 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
584 const char *a_prefix, *b_prefix;
585 char *data_one, *data_two;
586 size_t size_one, size_two;
587 struct emit_callback ecbdata;
588 char *line_prefix = "";
589 struct strbuf *msgbuf;
591 if (o && o->output_prefix) {
592 msgbuf = o->output_prefix(o, o->output_prefix_data);
593 line_prefix = msgbuf->buf;
596 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
597 a_prefix = o->b_prefix;
598 b_prefix = o->a_prefix;
599 } else {
600 a_prefix = o->a_prefix;
601 b_prefix = o->b_prefix;
604 name_a += (*name_a == '/');
605 name_b += (*name_b == '/');
606 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
607 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
609 strbuf_reset(&a_name);
610 strbuf_reset(&b_name);
611 quote_two_c_style(&a_name, a_prefix, name_a, 0);
612 quote_two_c_style(&b_name, b_prefix, name_b, 0);
614 size_one = fill_textconv(textconv_one, one, &data_one);
615 size_two = fill_textconv(textconv_two, two, &data_two);
617 memset(&ecbdata, 0, sizeof(ecbdata));
618 ecbdata.color_diff = color_diff;
619 ecbdata.found_changesp = &o->found_changes;
620 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
621 ecbdata.opt = o;
622 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
623 mmfile_t mf1, mf2;
624 mf1.ptr = (char *)data_one;
625 mf2.ptr = (char *)data_two;
626 mf1.size = size_one;
627 mf2.size = size_two;
628 check_blank_at_eof(&mf1, &mf2, &ecbdata);
630 ecbdata.lno_in_preimage = 1;
631 ecbdata.lno_in_postimage = 1;
633 lc_a = count_lines(data_one, size_one);
634 lc_b = count_lines(data_two, size_two);
635 fprintf(o->file,
636 "%s%s--- %s%s%s\n%s%s+++ %s%s%s\n%s%s@@ -",
637 line_prefix, metainfo, a_name.buf, name_a_tab, reset,
638 line_prefix, metainfo, b_name.buf, name_b_tab, reset,
639 line_prefix, fraginfo);
640 if (!o->irreversible_delete)
641 print_line_count(o->file, lc_a);
642 else
643 fprintf(o->file, "?,?");
644 fprintf(o->file, " +");
645 print_line_count(o->file, lc_b);
646 fprintf(o->file, " @@%s\n", reset);
647 if (lc_a && !o->irreversible_delete)
648 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
649 if (lc_b)
650 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
651 if (textconv_one)
652 free((char *)data_one);
653 if (textconv_two)
654 free((char *)data_two);
657 struct diff_words_buffer {
658 mmfile_t text;
659 long alloc;
660 struct diff_words_orig {
661 const char *begin, *end;
662 } *orig;
663 int orig_nr, orig_alloc;
666 static void diff_words_append(char *line, unsigned long len,
667 struct diff_words_buffer *buffer)
669 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
670 line++;
671 len--;
672 memcpy(buffer->text.ptr + buffer->text.size, line, len);
673 buffer->text.size += len;
674 buffer->text.ptr[buffer->text.size] = '\0';
677 struct diff_words_style_elem {
678 const char *prefix;
679 const char *suffix;
680 const char *color; /* NULL; filled in by the setup code if
681 * color is enabled */
684 struct diff_words_style {
685 enum diff_words_type type;
686 struct diff_words_style_elem new, old, ctx;
687 const char *newline;
690 static struct diff_words_style diff_words_styles[] = {
691 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
692 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
693 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
696 struct diff_words_data {
697 struct diff_words_buffer minus, plus;
698 const char *current_plus;
699 int last_minus;
700 struct diff_options *opt;
701 regex_t *word_regex;
702 enum diff_words_type type;
703 struct diff_words_style *style;
706 static int fn_out_diff_words_write_helper(FILE *fp,
707 struct diff_words_style_elem *st_el,
708 const char *newline,
709 size_t count, const char *buf,
710 const char *line_prefix)
712 int print = 0;
714 while (count) {
715 char *p = memchr(buf, '\n', count);
716 if (print)
717 fputs(line_prefix, fp);
718 if (p != buf) {
719 if (st_el->color && fputs(st_el->color, fp) < 0)
720 return -1;
721 if (fputs(st_el->prefix, fp) < 0 ||
722 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
723 fputs(st_el->suffix, fp) < 0)
724 return -1;
725 if (st_el->color && *st_el->color
726 && fputs(GIT_COLOR_RESET, fp) < 0)
727 return -1;
729 if (!p)
730 return 0;
731 if (fputs(newline, fp) < 0)
732 return -1;
733 count -= p + 1 - buf;
734 buf = p + 1;
735 print = 1;
737 return 0;
741 * '--color-words' algorithm can be described as:
743 * 1. collect a the minus/plus lines of a diff hunk, divided into
744 * minus-lines and plus-lines;
746 * 2. break both minus-lines and plus-lines into words and
747 * place them into two mmfile_t with one word for each line;
749 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
751 * And for the common parts of the both file, we output the plus side text.
752 * diff_words->current_plus is used to trace the current position of the plus file
753 * which printed. diff_words->last_minus is used to trace the last minus word
754 * printed.
756 * For '--graph' to work with '--color-words', we need to output the graph prefix
757 * on each line of color words output. Generally, there are two conditions on
758 * which we should output the prefix.
760 * 1. diff_words->last_minus == 0 &&
761 * diff_words->current_plus == diff_words->plus.text.ptr
763 * that is: the plus text must start as a new line, and if there is no minus
764 * word printed, a graph prefix must be printed.
766 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
767 * *(diff_words->current_plus - 1) == '\n'
769 * that is: a graph prefix must be printed following a '\n'
771 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
773 if ((diff_words->last_minus == 0 &&
774 diff_words->current_plus == diff_words->plus.text.ptr) ||
775 (diff_words->current_plus > diff_words->plus.text.ptr &&
776 *(diff_words->current_plus - 1) == '\n')) {
777 return 1;
778 } else {
779 return 0;
783 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
785 struct diff_words_data *diff_words = priv;
786 struct diff_words_style *style = diff_words->style;
787 int minus_first, minus_len, plus_first, plus_len;
788 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
789 struct diff_options *opt = diff_words->opt;
790 struct strbuf *msgbuf;
791 char *line_prefix = "";
793 if (line[0] != '@' || parse_hunk_header(line, len,
794 &minus_first, &minus_len, &plus_first, &plus_len))
795 return;
797 assert(opt);
798 if (opt->output_prefix) {
799 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
800 line_prefix = msgbuf->buf;
803 /* POSIX requires that first be decremented by one if len == 0... */
804 if (minus_len) {
805 minus_begin = diff_words->minus.orig[minus_first].begin;
806 minus_end =
807 diff_words->minus.orig[minus_first + minus_len - 1].end;
808 } else
809 minus_begin = minus_end =
810 diff_words->minus.orig[minus_first].end;
812 if (plus_len) {
813 plus_begin = diff_words->plus.orig[plus_first].begin;
814 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
815 } else
816 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
818 if (color_words_output_graph_prefix(diff_words)) {
819 fputs(line_prefix, diff_words->opt->file);
821 if (diff_words->current_plus != plus_begin) {
822 fn_out_diff_words_write_helper(diff_words->opt->file,
823 &style->ctx, style->newline,
824 plus_begin - diff_words->current_plus,
825 diff_words->current_plus, line_prefix);
826 if (*(plus_begin - 1) == '\n')
827 fputs(line_prefix, diff_words->opt->file);
829 if (minus_begin != minus_end) {
830 fn_out_diff_words_write_helper(diff_words->opt->file,
831 &style->old, style->newline,
832 minus_end - minus_begin, minus_begin,
833 line_prefix);
835 if (plus_begin != plus_end) {
836 fn_out_diff_words_write_helper(diff_words->opt->file,
837 &style->new, style->newline,
838 plus_end - plus_begin, plus_begin,
839 line_prefix);
842 diff_words->current_plus = plus_end;
843 diff_words->last_minus = minus_first;
846 /* This function starts looking at *begin, and returns 0 iff a word was found. */
847 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
848 int *begin, int *end)
850 if (word_regex && *begin < buffer->size) {
851 regmatch_t match[1];
852 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
853 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
854 '\n', match[0].rm_eo - match[0].rm_so);
855 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
856 *begin += match[0].rm_so;
857 return *begin >= *end;
859 return -1;
862 /* find the next word */
863 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
864 (*begin)++;
865 if (*begin >= buffer->size)
866 return -1;
868 /* find the end of the word */
869 *end = *begin + 1;
870 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
871 (*end)++;
873 return 0;
877 * This function splits the words in buffer->text, stores the list with
878 * newline separator into out, and saves the offsets of the original words
879 * in buffer->orig.
881 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
882 regex_t *word_regex)
884 int i, j;
885 long alloc = 0;
887 out->size = 0;
888 out->ptr = NULL;
890 /* fake an empty "0th" word */
891 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
892 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
893 buffer->orig_nr = 1;
895 for (i = 0; i < buffer->text.size; i++) {
896 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
897 return;
899 /* store original boundaries */
900 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
901 buffer->orig_alloc);
902 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
903 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
904 buffer->orig_nr++;
906 /* store one word */
907 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
908 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
909 out->ptr[out->size + j - i] = '\n';
910 out->size += j - i + 1;
912 i = j - 1;
916 /* this executes the word diff on the accumulated buffers */
917 static void diff_words_show(struct diff_words_data *diff_words)
919 xpparam_t xpp;
920 xdemitconf_t xecfg;
921 mmfile_t minus, plus;
922 struct diff_words_style *style = diff_words->style;
924 struct diff_options *opt = diff_words->opt;
925 struct strbuf *msgbuf;
926 char *line_prefix = "";
928 assert(opt);
929 if (opt->output_prefix) {
930 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
931 line_prefix = msgbuf->buf;
934 /* special case: only removal */
935 if (!diff_words->plus.text.size) {
936 fputs(line_prefix, diff_words->opt->file);
937 fn_out_diff_words_write_helper(diff_words->opt->file,
938 &style->old, style->newline,
939 diff_words->minus.text.size,
940 diff_words->minus.text.ptr, line_prefix);
941 diff_words->minus.text.size = 0;
942 return;
945 diff_words->current_plus = diff_words->plus.text.ptr;
946 diff_words->last_minus = 0;
948 memset(&xpp, 0, sizeof(xpp));
949 memset(&xecfg, 0, sizeof(xecfg));
950 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
951 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
952 xpp.flags = 0;
953 /* as only the hunk header will be parsed, we need a 0-context */
954 xecfg.ctxlen = 0;
955 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
956 &xpp, &xecfg);
957 free(minus.ptr);
958 free(plus.ptr);
959 if (diff_words->current_plus != diff_words->plus.text.ptr +
960 diff_words->plus.text.size) {
961 if (color_words_output_graph_prefix(diff_words))
962 fputs(line_prefix, diff_words->opt->file);
963 fn_out_diff_words_write_helper(diff_words->opt->file,
964 &style->ctx, style->newline,
965 diff_words->plus.text.ptr + diff_words->plus.text.size
966 - diff_words->current_plus, diff_words->current_plus,
967 line_prefix);
969 diff_words->minus.text.size = diff_words->plus.text.size = 0;
972 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
973 static void diff_words_flush(struct emit_callback *ecbdata)
975 if (ecbdata->diff_words->minus.text.size ||
976 ecbdata->diff_words->plus.text.size)
977 diff_words_show(ecbdata->diff_words);
980 static void free_diff_words_data(struct emit_callback *ecbdata)
982 if (ecbdata->diff_words) {
983 diff_words_flush(ecbdata);
984 free (ecbdata->diff_words->minus.text.ptr);
985 free (ecbdata->diff_words->minus.orig);
986 free (ecbdata->diff_words->plus.text.ptr);
987 free (ecbdata->diff_words->plus.orig);
988 if (ecbdata->diff_words->word_regex) {
989 regfree(ecbdata->diff_words->word_regex);
990 free(ecbdata->diff_words->word_regex);
992 free(ecbdata->diff_words);
993 ecbdata->diff_words = NULL;
997 const char *diff_get_color(int diff_use_color, enum color_diff ix)
999 if (diff_use_color)
1000 return diff_colors[ix];
1001 return "";
1004 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1006 const char *cp;
1007 unsigned long allot;
1008 size_t l = len;
1010 if (ecb->truncate)
1011 return ecb->truncate(line, len);
1012 cp = line;
1013 allot = l;
1014 while (0 < l) {
1015 (void) utf8_width(&cp, &l);
1016 if (!cp)
1017 break; /* truncated in the middle? */
1019 return allot - l;
1022 static void find_lno(const char *line, struct emit_callback *ecbdata)
1024 const char *p;
1025 ecbdata->lno_in_preimage = 0;
1026 ecbdata->lno_in_postimage = 0;
1027 p = strchr(line, '-');
1028 if (!p)
1029 return; /* cannot happen */
1030 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1031 p = strchr(p, '+');
1032 if (!p)
1033 return; /* cannot happen */
1034 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1037 static void fn_out_consume(void *priv, char *line, unsigned long len)
1039 struct emit_callback *ecbdata = priv;
1040 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
1041 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
1042 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1043 struct diff_options *o = ecbdata->opt;
1044 char *line_prefix = "";
1045 struct strbuf *msgbuf;
1047 if (o && o->output_prefix) {
1048 msgbuf = o->output_prefix(o, o->output_prefix_data);
1049 line_prefix = msgbuf->buf;
1052 if (ecbdata->header) {
1053 fprintf(ecbdata->opt->file, "%s", ecbdata->header->buf);
1054 strbuf_reset(ecbdata->header);
1055 ecbdata->header = NULL;
1057 *(ecbdata->found_changesp) = 1;
1059 if (ecbdata->label_path[0]) {
1060 const char *name_a_tab, *name_b_tab;
1062 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
1063 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
1065 fprintf(ecbdata->opt->file, "%s%s--- %s%s%s\n",
1066 line_prefix, meta, ecbdata->label_path[0], reset, name_a_tab);
1067 fprintf(ecbdata->opt->file, "%s%s+++ %s%s%s\n",
1068 line_prefix, meta, ecbdata->label_path[1], reset, name_b_tab);
1069 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1072 if (diff_suppress_blank_empty
1073 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1074 line[0] = '\n';
1075 len = 1;
1078 if (line[0] == '@') {
1079 if (ecbdata->diff_words)
1080 diff_words_flush(ecbdata);
1081 len = sane_truncate_line(ecbdata, line, len);
1082 find_lno(line, ecbdata);
1083 emit_hunk_header(ecbdata, line, len);
1084 if (line[len-1] != '\n')
1085 putc('\n', ecbdata->opt->file);
1086 return;
1089 if (len < 1) {
1090 emit_line(ecbdata->opt, reset, reset, line, len);
1091 if (ecbdata->diff_words
1092 && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
1093 fputs("~\n", ecbdata->opt->file);
1094 return;
1097 if (ecbdata->diff_words) {
1098 if (line[0] == '-') {
1099 diff_words_append(line, len,
1100 &ecbdata->diff_words->minus);
1101 return;
1102 } else if (line[0] == '+') {
1103 diff_words_append(line, len,
1104 &ecbdata->diff_words->plus);
1105 return;
1107 diff_words_flush(ecbdata);
1108 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
1109 emit_line(ecbdata->opt, plain, reset, line, len);
1110 fputs("~\n", ecbdata->opt->file);
1111 } else {
1112 /* don't print the prefix character */
1113 emit_line(ecbdata->opt, plain, reset, line+1, len-1);
1115 return;
1118 if (line[0] != '+') {
1119 const char *color =
1120 diff_get_color(ecbdata->color_diff,
1121 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
1122 ecbdata->lno_in_preimage++;
1123 if (line[0] == ' ')
1124 ecbdata->lno_in_postimage++;
1125 emit_line(ecbdata->opt, color, reset, line, len);
1126 } else {
1127 ecbdata->lno_in_postimage++;
1128 emit_add_line(reset, ecbdata, line + 1, len - 1);
1132 static char *pprint_rename(const char *a, const char *b)
1134 const char *old = a;
1135 const char *new = b;
1136 struct strbuf name = STRBUF_INIT;
1137 int pfx_length, sfx_length;
1138 int len_a = strlen(a);
1139 int len_b = strlen(b);
1140 int a_midlen, b_midlen;
1141 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1142 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1144 if (qlen_a || qlen_b) {
1145 quote_c_style(a, &name, NULL, 0);
1146 strbuf_addstr(&name, " => ");
1147 quote_c_style(b, &name, NULL, 0);
1148 return strbuf_detach(&name, NULL);
1151 /* Find common prefix */
1152 pfx_length = 0;
1153 while (*old && *new && *old == *new) {
1154 if (*old == '/')
1155 pfx_length = old - a + 1;
1156 old++;
1157 new++;
1160 /* Find common suffix */
1161 old = a + len_a;
1162 new = b + len_b;
1163 sfx_length = 0;
1164 while (a <= old && b <= new && *old == *new) {
1165 if (*old == '/')
1166 sfx_length = len_a - (old - a);
1167 old--;
1168 new--;
1172 * pfx{mid-a => mid-b}sfx
1173 * {pfx-a => pfx-b}sfx
1174 * pfx{sfx-a => sfx-b}
1175 * name-a => name-b
1177 a_midlen = len_a - pfx_length - sfx_length;
1178 b_midlen = len_b - pfx_length - sfx_length;
1179 if (a_midlen < 0)
1180 a_midlen = 0;
1181 if (b_midlen < 0)
1182 b_midlen = 0;
1184 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1185 if (pfx_length + sfx_length) {
1186 strbuf_add(&name, a, pfx_length);
1187 strbuf_addch(&name, '{');
1189 strbuf_add(&name, a + pfx_length, a_midlen);
1190 strbuf_addstr(&name, " => ");
1191 strbuf_add(&name, b + pfx_length, b_midlen);
1192 if (pfx_length + sfx_length) {
1193 strbuf_addch(&name, '}');
1194 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1196 return strbuf_detach(&name, NULL);
1199 struct diffstat_t {
1200 int nr;
1201 int alloc;
1202 struct diffstat_file {
1203 char *from_name;
1204 char *name;
1205 char *print_name;
1206 unsigned is_unmerged:1;
1207 unsigned is_binary:1;
1208 unsigned is_renamed:1;
1209 uintmax_t added, deleted;
1210 } **files;
1213 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1214 const char *name_a,
1215 const char *name_b)
1217 struct diffstat_file *x;
1218 x = xcalloc(sizeof (*x), 1);
1219 if (diffstat->nr == diffstat->alloc) {
1220 diffstat->alloc = alloc_nr(diffstat->alloc);
1221 diffstat->files = xrealloc(diffstat->files,
1222 diffstat->alloc * sizeof(x));
1224 diffstat->files[diffstat->nr++] = x;
1225 if (name_b) {
1226 x->from_name = xstrdup(name_a);
1227 x->name = xstrdup(name_b);
1228 x->is_renamed = 1;
1230 else {
1231 x->from_name = NULL;
1232 x->name = xstrdup(name_a);
1234 return x;
1237 static void diffstat_consume(void *priv, char *line, unsigned long len)
1239 struct diffstat_t *diffstat = priv;
1240 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1242 if (line[0] == '+')
1243 x->added++;
1244 else if (line[0] == '-')
1245 x->deleted++;
1248 const char mime_boundary_leader[] = "------------";
1250 static int scale_linear(int it, int width, int max_change)
1253 * make sure that at least one '-' is printed if there were deletions,
1254 * and likewise for '+'.
1256 if (max_change < 2)
1257 return it;
1258 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
1261 static void show_name(FILE *file,
1262 const char *prefix, const char *name, int len)
1264 fprintf(file, " %s%-*s |", prefix, len, name);
1267 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1269 if (cnt <= 0)
1270 return;
1271 fprintf(file, "%s", set);
1272 while (cnt--)
1273 putc(ch, file);
1274 fprintf(file, "%s", reset);
1277 static void fill_print_name(struct diffstat_file *file)
1279 char *pname;
1281 if (file->print_name)
1282 return;
1284 if (!file->is_renamed) {
1285 struct strbuf buf = STRBUF_INIT;
1286 if (quote_c_style(file->name, &buf, NULL, 0)) {
1287 pname = strbuf_detach(&buf, NULL);
1288 } else {
1289 pname = file->name;
1290 strbuf_release(&buf);
1292 } else {
1293 pname = pprint_rename(file->from_name, file->name);
1295 file->print_name = pname;
1298 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1300 int i, len, add, del, adds = 0, dels = 0;
1301 uintmax_t max_change = 0, max_len = 0;
1302 int total_files = data->nr;
1303 int width, name_width;
1304 const char *reset, *add_c, *del_c;
1305 const char *line_prefix = "";
1306 struct strbuf *msg = NULL;
1308 if (data->nr == 0)
1309 return;
1311 if (options->output_prefix) {
1312 msg = options->output_prefix(options, options->output_prefix_data);
1313 line_prefix = msg->buf;
1316 width = options->stat_width ? options->stat_width : 80;
1317 name_width = options->stat_name_width ? options->stat_name_width : 50;
1319 /* Sanity: give at least 5 columns to the graph,
1320 * but leave at least 10 columns for the name.
1322 if (width < 25)
1323 width = 25;
1324 if (name_width < 10)
1325 name_width = 10;
1326 else if (width < name_width + 15)
1327 name_width = width - 15;
1329 /* Find the longest filename and max number of changes */
1330 reset = diff_get_color_opt(options, DIFF_RESET);
1331 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1332 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1334 for (i = 0; i < data->nr; i++) {
1335 struct diffstat_file *file = data->files[i];
1336 uintmax_t change = file->added + file->deleted;
1337 fill_print_name(file);
1338 len = strlen(file->print_name);
1339 if (max_len < len)
1340 max_len = len;
1342 if (file->is_binary || file->is_unmerged)
1343 continue;
1344 if (max_change < change)
1345 max_change = change;
1348 /* Compute the width of the graph part;
1349 * 10 is for one blank at the beginning of the line plus
1350 * " | count " between the name and the graph.
1352 * From here on, name_width is the width of the name area,
1353 * and width is the width of the graph area.
1355 name_width = (name_width < max_len) ? name_width : max_len;
1356 if (width < (name_width + 10) + max_change)
1357 width = width - (name_width + 10);
1358 else
1359 width = max_change;
1361 for (i = 0; i < data->nr; i++) {
1362 const char *prefix = "";
1363 char *name = data->files[i]->print_name;
1364 uintmax_t added = data->files[i]->added;
1365 uintmax_t deleted = data->files[i]->deleted;
1366 int name_len;
1369 * "scale" the filename
1371 len = name_width;
1372 name_len = strlen(name);
1373 if (name_width < name_len) {
1374 char *slash;
1375 prefix = "...";
1376 len -= 3;
1377 name += name_len - len;
1378 slash = strchr(name, '/');
1379 if (slash)
1380 name = slash;
1383 if (data->files[i]->is_binary) {
1384 fprintf(options->file, "%s", line_prefix);
1385 show_name(options->file, prefix, name, len);
1386 fprintf(options->file, " Bin ");
1387 fprintf(options->file, "%s%"PRIuMAX"%s",
1388 del_c, deleted, reset);
1389 fprintf(options->file, " -> ");
1390 fprintf(options->file, "%s%"PRIuMAX"%s",
1391 add_c, added, reset);
1392 fprintf(options->file, " bytes");
1393 fprintf(options->file, "\n");
1394 continue;
1396 else if (data->files[i]->is_unmerged) {
1397 fprintf(options->file, "%s", line_prefix);
1398 show_name(options->file, prefix, name, len);
1399 fprintf(options->file, " Unmerged\n");
1400 continue;
1402 else if (!data->files[i]->is_renamed &&
1403 (added + deleted == 0)) {
1404 total_files--;
1405 continue;
1409 * scale the add/delete
1411 add = added;
1412 del = deleted;
1413 adds += add;
1414 dels += del;
1416 if (width <= max_change) {
1417 add = scale_linear(add, width, max_change);
1418 del = scale_linear(del, width, max_change);
1420 fprintf(options->file, "%s", line_prefix);
1421 show_name(options->file, prefix, name, len);
1422 fprintf(options->file, "%5"PRIuMAX"%s", added + deleted,
1423 added + deleted ? " " : "");
1424 show_graph(options->file, '+', add, add_c, reset);
1425 show_graph(options->file, '-', del, del_c, reset);
1426 fprintf(options->file, "\n");
1428 fprintf(options->file, "%s", line_prefix);
1429 fprintf(options->file,
1430 " %d files changed, %d insertions(+), %d deletions(-)\n",
1431 total_files, adds, dels);
1434 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1436 int i, adds = 0, dels = 0, total_files = data->nr;
1438 if (data->nr == 0)
1439 return;
1441 for (i = 0; i < data->nr; i++) {
1442 if (!data->files[i]->is_binary &&
1443 !data->files[i]->is_unmerged) {
1444 int added = data->files[i]->added;
1445 int deleted= data->files[i]->deleted;
1446 if (!data->files[i]->is_renamed &&
1447 (added + deleted == 0)) {
1448 total_files--;
1449 } else {
1450 adds += added;
1451 dels += deleted;
1455 if (options->output_prefix) {
1456 struct strbuf *msg = NULL;
1457 msg = options->output_prefix(options,
1458 options->output_prefix_data);
1459 fprintf(options->file, "%s", msg->buf);
1461 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1462 total_files, adds, dels);
1465 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1467 int i;
1469 if (data->nr == 0)
1470 return;
1472 for (i = 0; i < data->nr; i++) {
1473 struct diffstat_file *file = data->files[i];
1475 if (options->output_prefix) {
1476 struct strbuf *msg = NULL;
1477 msg = options->output_prefix(options,
1478 options->output_prefix_data);
1479 fprintf(options->file, "%s", msg->buf);
1482 if (file->is_binary)
1483 fprintf(options->file, "-\t-\t");
1484 else
1485 fprintf(options->file,
1486 "%"PRIuMAX"\t%"PRIuMAX"\t",
1487 file->added, file->deleted);
1488 if (options->line_termination) {
1489 fill_print_name(file);
1490 if (!file->is_renamed)
1491 write_name_quoted(file->name, options->file,
1492 options->line_termination);
1493 else {
1494 fputs(file->print_name, options->file);
1495 putc(options->line_termination, options->file);
1497 } else {
1498 if (file->is_renamed) {
1499 putc('\0', options->file);
1500 write_name_quoted(file->from_name, options->file, '\0');
1502 write_name_quoted(file->name, options->file, '\0');
1507 struct dirstat_file {
1508 const char *name;
1509 unsigned long changed;
1512 struct dirstat_dir {
1513 struct dirstat_file *files;
1514 int alloc, nr, permille, cumulative;
1517 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
1518 unsigned long changed, const char *base, int baselen)
1520 unsigned long this_dir = 0;
1521 unsigned int sources = 0;
1522 const char *line_prefix = "";
1523 struct strbuf *msg = NULL;
1525 if (opt->output_prefix) {
1526 msg = opt->output_prefix(opt, opt->output_prefix_data);
1527 line_prefix = msg->buf;
1530 while (dir->nr) {
1531 struct dirstat_file *f = dir->files;
1532 int namelen = strlen(f->name);
1533 unsigned long this;
1534 char *slash;
1536 if (namelen < baselen)
1537 break;
1538 if (memcmp(f->name, base, baselen))
1539 break;
1540 slash = strchr(f->name + baselen, '/');
1541 if (slash) {
1542 int newbaselen = slash + 1 - f->name;
1543 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
1544 sources++;
1545 } else {
1546 this = f->changed;
1547 dir->files++;
1548 dir->nr--;
1549 sources += 2;
1551 this_dir += this;
1555 * We don't report dirstat's for
1556 * - the top level
1557 * - or cases where everything came from a single directory
1558 * under this directory (sources == 1).
1560 if (baselen && sources != 1) {
1561 if (this_dir) {
1562 int permille = this_dir * 1000 / changed;
1563 if (permille >= dir->permille) {
1564 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
1565 permille / 10, permille % 10, baselen, base);
1566 if (!dir->cumulative)
1567 return 0;
1571 return this_dir;
1574 static int dirstat_compare(const void *_a, const void *_b)
1576 const struct dirstat_file *a = _a;
1577 const struct dirstat_file *b = _b;
1578 return strcmp(a->name, b->name);
1581 static void show_dirstat(struct diff_options *options)
1583 int i;
1584 unsigned long changed;
1585 struct dirstat_dir dir;
1586 struct diff_queue_struct *q = &diff_queued_diff;
1588 dir.files = NULL;
1589 dir.alloc = 0;
1590 dir.nr = 0;
1591 dir.permille = options->dirstat_permille;
1592 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1594 changed = 0;
1595 for (i = 0; i < q->nr; i++) {
1596 struct diff_filepair *p = q->queue[i];
1597 const char *name;
1598 unsigned long copied, added, damage;
1599 int content_changed;
1601 name = p->two->path ? p->two->path : p->one->path;
1603 if (p->one->sha1_valid && p->two->sha1_valid)
1604 content_changed = hashcmp(p->one->sha1, p->two->sha1);
1605 else
1606 content_changed = 1;
1608 if (!content_changed) {
1610 * The SHA1 has not changed, so pre-/post-content is
1611 * identical. We can therefore skip looking at the
1612 * file contents altogether.
1614 damage = 0;
1615 goto found_damage;
1618 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
1620 * In --dirstat-by-file mode, we don't really need to
1621 * look at the actual file contents at all.
1622 * The fact that the SHA1 changed is enough for us to
1623 * add this file to the list of results
1624 * (with each file contributing equal damage).
1626 damage = 1;
1627 goto found_damage;
1630 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1631 diff_populate_filespec(p->one, 0);
1632 diff_populate_filespec(p->two, 0);
1633 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1634 &copied, &added);
1635 diff_free_filespec_data(p->one);
1636 diff_free_filespec_data(p->two);
1637 } else if (DIFF_FILE_VALID(p->one)) {
1638 diff_populate_filespec(p->one, 1);
1639 copied = added = 0;
1640 diff_free_filespec_data(p->one);
1641 } else if (DIFF_FILE_VALID(p->two)) {
1642 diff_populate_filespec(p->two, 1);
1643 copied = 0;
1644 added = p->two->size;
1645 diff_free_filespec_data(p->two);
1646 } else
1647 continue;
1650 * Original minus copied is the removed material,
1651 * added is the new material. They are both damages
1652 * made to the preimage.
1653 * If the resulting damage is zero, we know that
1654 * diffcore_count_changes() considers the two entries to
1655 * be identical, but since content_changed is true, we
1656 * know that there must have been _some_ kind of change,
1657 * so we force all entries to have damage > 0.
1659 damage = (p->one->size - copied) + added;
1660 if (!damage)
1661 damage = 1;
1663 found_damage:
1664 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1665 dir.files[dir.nr].name = name;
1666 dir.files[dir.nr].changed = damage;
1667 changed += damage;
1668 dir.nr++;
1671 /* This can happen even with many files, if everything was renames */
1672 if (!changed)
1673 return;
1675 /* Show all directories with more than x% of the changes */
1676 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1677 gather_dirstat(options, &dir, changed, "", 0);
1680 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
1682 int i;
1683 unsigned long changed;
1684 struct dirstat_dir dir;
1686 if (data->nr == 0)
1687 return;
1689 dir.files = NULL;
1690 dir.alloc = 0;
1691 dir.nr = 0;
1692 dir.permille = options->dirstat_permille;
1693 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1695 changed = 0;
1696 for (i = 0; i < data->nr; i++) {
1697 struct diffstat_file *file = data->files[i];
1698 unsigned long damage = file->added + file->deleted;
1699 if (file->is_binary)
1701 * binary files counts bytes, not lines. Must find some
1702 * way to normalize binary bytes vs. textual lines.
1703 * The following heuristic assumes that there are 64
1704 * bytes per "line".
1705 * This is stupid and ugly, but very cheap...
1707 damage = (damage + 63) / 64;
1708 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1709 dir.files[dir.nr].name = file->name;
1710 dir.files[dir.nr].changed = damage;
1711 changed += damage;
1712 dir.nr++;
1715 /* This can happen even with many files, if everything was renames */
1716 if (!changed)
1717 return;
1719 /* Show all directories with more than x% of the changes */
1720 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1721 gather_dirstat(options, &dir, changed, "", 0);
1724 static void free_diffstat_info(struct diffstat_t *diffstat)
1726 int i;
1727 for (i = 0; i < diffstat->nr; i++) {
1728 struct diffstat_file *f = diffstat->files[i];
1729 if (f->name != f->print_name)
1730 free(f->print_name);
1731 free(f->name);
1732 free(f->from_name);
1733 free(f);
1735 free(diffstat->files);
1738 struct checkdiff_t {
1739 const char *filename;
1740 int lineno;
1741 int conflict_marker_size;
1742 struct diff_options *o;
1743 unsigned ws_rule;
1744 unsigned status;
1747 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
1749 char firstchar;
1750 int cnt;
1752 if (len < marker_size + 1)
1753 return 0;
1754 firstchar = line[0];
1755 switch (firstchar) {
1756 case '=': case '>': case '<': case '|':
1757 break;
1758 default:
1759 return 0;
1761 for (cnt = 1; cnt < marker_size; cnt++)
1762 if (line[cnt] != firstchar)
1763 return 0;
1764 /* line[1] thru line[marker_size-1] are same as firstchar */
1765 if (len < marker_size + 1 || !isspace(line[marker_size]))
1766 return 0;
1767 return 1;
1770 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1772 struct checkdiff_t *data = priv;
1773 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1774 int marker_size = data->conflict_marker_size;
1775 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1776 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1777 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1778 char *err;
1779 char *line_prefix = "";
1780 struct strbuf *msgbuf;
1782 assert(data->o);
1783 if (data->o->output_prefix) {
1784 msgbuf = data->o->output_prefix(data->o,
1785 data->o->output_prefix_data);
1786 line_prefix = msgbuf->buf;
1789 if (line[0] == '+') {
1790 unsigned bad;
1791 data->lineno++;
1792 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
1793 data->status |= 1;
1794 fprintf(data->o->file,
1795 "%s%s:%d: leftover conflict marker\n",
1796 line_prefix, data->filename, data->lineno);
1798 bad = ws_check(line + 1, len - 1, data->ws_rule);
1799 if (!bad)
1800 return;
1801 data->status |= bad;
1802 err = whitespace_error_string(bad);
1803 fprintf(data->o->file, "%s%s:%d: %s.\n",
1804 line_prefix, data->filename, data->lineno, err);
1805 free(err);
1806 emit_line(data->o, set, reset, line, 1);
1807 ws_check_emit(line + 1, len - 1, data->ws_rule,
1808 data->o->file, set, reset, ws);
1809 } else if (line[0] == ' ') {
1810 data->lineno++;
1811 } else if (line[0] == '@') {
1812 char *plus = strchr(line, '+');
1813 if (plus)
1814 data->lineno = strtol(plus, NULL, 10) - 1;
1815 else
1816 die("invalid diff");
1820 static unsigned char *deflate_it(char *data,
1821 unsigned long size,
1822 unsigned long *result_size)
1824 int bound;
1825 unsigned char *deflated;
1826 z_stream stream;
1828 memset(&stream, 0, sizeof(stream));
1829 deflateInit(&stream, zlib_compression_level);
1830 bound = deflateBound(&stream, size);
1831 deflated = xmalloc(bound);
1832 stream.next_out = deflated;
1833 stream.avail_out = bound;
1835 stream.next_in = (unsigned char *)data;
1836 stream.avail_in = size;
1837 while (deflate(&stream, Z_FINISH) == Z_OK)
1838 ; /* nothing */
1839 deflateEnd(&stream);
1840 *result_size = stream.total_out;
1841 return deflated;
1844 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two, char *prefix)
1846 void *cp;
1847 void *delta;
1848 void *deflated;
1849 void *data;
1850 unsigned long orig_size;
1851 unsigned long delta_size;
1852 unsigned long deflate_size;
1853 unsigned long data_size;
1855 /* We could do deflated delta, or we could do just deflated two,
1856 * whichever is smaller.
1858 delta = NULL;
1859 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1860 if (one->size && two->size) {
1861 delta = diff_delta(one->ptr, one->size,
1862 two->ptr, two->size,
1863 &delta_size, deflate_size);
1864 if (delta) {
1865 void *to_free = delta;
1866 orig_size = delta_size;
1867 delta = deflate_it(delta, delta_size, &delta_size);
1868 free(to_free);
1872 if (delta && delta_size < deflate_size) {
1873 fprintf(file, "%sdelta %lu\n", prefix, orig_size);
1874 free(deflated);
1875 data = delta;
1876 data_size = delta_size;
1878 else {
1879 fprintf(file, "%sliteral %lu\n", prefix, two->size);
1880 free(delta);
1881 data = deflated;
1882 data_size = deflate_size;
1885 /* emit data encoded in base85 */
1886 cp = data;
1887 while (data_size) {
1888 int bytes = (52 < data_size) ? 52 : data_size;
1889 char line[70];
1890 data_size -= bytes;
1891 if (bytes <= 26)
1892 line[0] = bytes + 'A' - 1;
1893 else
1894 line[0] = bytes - 26 + 'a' - 1;
1895 encode_85(line + 1, cp, bytes);
1896 cp = (char *) cp + bytes;
1897 fprintf(file, "%s", prefix);
1898 fputs(line, file);
1899 fputc('\n', file);
1901 fprintf(file, "%s\n", prefix);
1902 free(data);
1905 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two, char *prefix)
1907 fprintf(file, "%sGIT binary patch\n", prefix);
1908 emit_binary_diff_body(file, one, two, prefix);
1909 emit_binary_diff_body(file, two, one, prefix);
1912 static void diff_filespec_load_driver(struct diff_filespec *one)
1914 /* Use already-loaded driver */
1915 if (one->driver)
1916 return;
1918 if (S_ISREG(one->mode))
1919 one->driver = userdiff_find_by_path(one->path);
1921 /* Fallback to default settings */
1922 if (!one->driver)
1923 one->driver = userdiff_find_by_name("default");
1926 int diff_filespec_is_binary(struct diff_filespec *one)
1928 if (one->is_binary == -1) {
1929 diff_filespec_load_driver(one);
1930 if (one->driver->binary != -1)
1931 one->is_binary = one->driver->binary;
1932 else {
1933 if (!one->data && DIFF_FILE_VALID(one))
1934 diff_populate_filespec(one, 0);
1935 if (one->data)
1936 one->is_binary = buffer_is_binary(one->data,
1937 one->size);
1938 if (one->is_binary == -1)
1939 one->is_binary = 0;
1942 return one->is_binary;
1945 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1947 diff_filespec_load_driver(one);
1948 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1951 static const char *userdiff_word_regex(struct diff_filespec *one)
1953 diff_filespec_load_driver(one);
1954 return one->driver->word_regex;
1957 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1959 if (!options->a_prefix)
1960 options->a_prefix = a;
1961 if (!options->b_prefix)
1962 options->b_prefix = b;
1965 struct userdiff_driver *get_textconv(struct diff_filespec *one)
1967 if (!DIFF_FILE_VALID(one))
1968 return NULL;
1970 diff_filespec_load_driver(one);
1971 if (!one->driver->textconv)
1972 return NULL;
1974 if (one->driver->textconv_want_cache && !one->driver->textconv_cache) {
1975 struct notes_cache *c = xmalloc(sizeof(*c));
1976 struct strbuf name = STRBUF_INIT;
1978 strbuf_addf(&name, "textconv/%s", one->driver->name);
1979 notes_cache_init(c, name.buf, one->driver->textconv);
1980 one->driver->textconv_cache = c;
1983 return one->driver;
1986 static void builtin_diff(const char *name_a,
1987 const char *name_b,
1988 struct diff_filespec *one,
1989 struct diff_filespec *two,
1990 const char *xfrm_msg,
1991 int must_show_header,
1992 struct diff_options *o,
1993 int complete_rewrite)
1995 mmfile_t mf1, mf2;
1996 const char *lbl[2];
1997 char *a_one, *b_two;
1998 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1999 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2000 const char *a_prefix, *b_prefix;
2001 struct userdiff_driver *textconv_one = NULL;
2002 struct userdiff_driver *textconv_two = NULL;
2003 struct strbuf header = STRBUF_INIT;
2004 struct strbuf *msgbuf;
2005 char *line_prefix = "";
2007 if (o->output_prefix) {
2008 msgbuf = o->output_prefix(o, o->output_prefix_data);
2009 line_prefix = msgbuf->buf;
2012 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
2013 (!one->mode || S_ISGITLINK(one->mode)) &&
2014 (!two->mode || S_ISGITLINK(two->mode))) {
2015 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2016 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2017 show_submodule_summary(o->file, one ? one->path : two->path,
2018 one->sha1, two->sha1, two->dirty_submodule,
2019 del, add, reset);
2020 return;
2023 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2024 textconv_one = get_textconv(one);
2025 textconv_two = get_textconv(two);
2028 diff_set_mnemonic_prefix(o, "a/", "b/");
2029 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2030 a_prefix = o->b_prefix;
2031 b_prefix = o->a_prefix;
2032 } else {
2033 a_prefix = o->a_prefix;
2034 b_prefix = o->b_prefix;
2037 /* Never use a non-valid filename anywhere if at all possible */
2038 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2039 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2041 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2042 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
2043 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2044 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
2045 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, set, a_one, b_two, reset);
2046 if (lbl[0][0] == '/') {
2047 /* /dev/null */
2048 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, set, two->mode, reset);
2049 if (xfrm_msg)
2050 strbuf_addstr(&header, xfrm_msg);
2051 must_show_header = 1;
2053 else if (lbl[1][0] == '/') {
2054 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, set, one->mode, reset);
2055 if (xfrm_msg)
2056 strbuf_addstr(&header, xfrm_msg);
2057 must_show_header = 1;
2059 else {
2060 if (one->mode != two->mode) {
2061 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, set, one->mode, reset);
2062 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, set, two->mode, reset);
2063 must_show_header = 1;
2065 if (xfrm_msg)
2066 strbuf_addstr(&header, xfrm_msg);
2069 * we do not run diff between different kind
2070 * of objects.
2072 if ((one->mode ^ two->mode) & S_IFMT)
2073 goto free_ab_and_return;
2074 if (complete_rewrite &&
2075 (textconv_one || !diff_filespec_is_binary(one)) &&
2076 (textconv_two || !diff_filespec_is_binary(two))) {
2077 fprintf(o->file, "%s", header.buf);
2078 strbuf_reset(&header);
2079 emit_rewrite_diff(name_a, name_b, one, two,
2080 textconv_one, textconv_two, o);
2081 o->found_changes = 1;
2082 goto free_ab_and_return;
2086 if (o->irreversible_delete && lbl[1][0] == '/') {
2087 fprintf(o->file, "%s", header.buf);
2088 strbuf_reset(&header);
2089 goto free_ab_and_return;
2090 } else if (!DIFF_OPT_TST(o, TEXT) &&
2091 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2092 (!textconv_two && diff_filespec_is_binary(two)) )) {
2093 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2094 die("unable to read files to diff");
2095 /* Quite common confusing case */
2096 if (mf1.size == mf2.size &&
2097 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2098 if (must_show_header)
2099 fprintf(o->file, "%s", header.buf);
2100 goto free_ab_and_return;
2102 fprintf(o->file, "%s", header.buf);
2103 strbuf_reset(&header);
2104 if (DIFF_OPT_TST(o, BINARY))
2105 emit_binary_diff(o->file, &mf1, &mf2, line_prefix);
2106 else
2107 fprintf(o->file, "%sBinary files %s and %s differ\n",
2108 line_prefix, lbl[0], lbl[1]);
2109 o->found_changes = 1;
2110 } else {
2111 /* Crazy xdl interfaces.. */
2112 const char *diffopts = getenv("GIT_DIFF_OPTS");
2113 xpparam_t xpp;
2114 xdemitconf_t xecfg;
2115 struct emit_callback ecbdata;
2116 const struct userdiff_funcname *pe;
2118 if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS) || must_show_header) {
2119 fprintf(o->file, "%s", header.buf);
2120 strbuf_reset(&header);
2123 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2124 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
2126 pe = diff_funcname_pattern(one);
2127 if (!pe)
2128 pe = diff_funcname_pattern(two);
2130 memset(&xpp, 0, sizeof(xpp));
2131 memset(&xecfg, 0, sizeof(xecfg));
2132 memset(&ecbdata, 0, sizeof(ecbdata));
2133 ecbdata.label_path = lbl;
2134 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
2135 ecbdata.found_changesp = &o->found_changes;
2136 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
2137 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
2138 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2139 ecbdata.opt = o;
2140 ecbdata.header = header.len ? &header : NULL;
2141 xpp.flags = o->xdl_opts;
2142 xecfg.ctxlen = o->context;
2143 xecfg.interhunkctxlen = o->interhunkcontext;
2144 xecfg.flags = XDL_EMIT_FUNCNAMES;
2145 if (pe)
2146 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
2147 if (!diffopts)
2149 else if (!prefixcmp(diffopts, "--unified="))
2150 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
2151 else if (!prefixcmp(diffopts, "-u"))
2152 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
2153 if (o->word_diff) {
2154 int i;
2156 ecbdata.diff_words =
2157 xcalloc(1, sizeof(struct diff_words_data));
2158 ecbdata.diff_words->type = o->word_diff;
2159 ecbdata.diff_words->opt = o;
2160 if (!o->word_regex)
2161 o->word_regex = userdiff_word_regex(one);
2162 if (!o->word_regex)
2163 o->word_regex = userdiff_word_regex(two);
2164 if (!o->word_regex)
2165 o->word_regex = diff_word_regex_cfg;
2166 if (o->word_regex) {
2167 ecbdata.diff_words->word_regex = (regex_t *)
2168 xmalloc(sizeof(regex_t));
2169 if (regcomp(ecbdata.diff_words->word_regex,
2170 o->word_regex,
2171 REG_EXTENDED | REG_NEWLINE))
2172 die ("Invalid regular expression: %s",
2173 o->word_regex);
2175 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2176 if (o->word_diff == diff_words_styles[i].type) {
2177 ecbdata.diff_words->style =
2178 &diff_words_styles[i];
2179 break;
2182 if (DIFF_OPT_TST(o, COLOR_DIFF)) {
2183 struct diff_words_style *st = ecbdata.diff_words->style;
2184 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2185 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2186 st->ctx.color = diff_get_color_opt(o, DIFF_PLAIN);
2189 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2190 &xpp, &xecfg);
2191 if (o->word_diff)
2192 free_diff_words_data(&ecbdata);
2193 if (textconv_one)
2194 free(mf1.ptr);
2195 if (textconv_two)
2196 free(mf2.ptr);
2197 xdiff_clear_find_func(&xecfg);
2200 free_ab_and_return:
2201 strbuf_release(&header);
2202 diff_free_filespec_data(one);
2203 diff_free_filespec_data(two);
2204 free(a_one);
2205 free(b_two);
2206 return;
2209 static void builtin_diffstat(const char *name_a, const char *name_b,
2210 struct diff_filespec *one,
2211 struct diff_filespec *two,
2212 struct diffstat_t *diffstat,
2213 struct diff_options *o,
2214 int complete_rewrite)
2216 mmfile_t mf1, mf2;
2217 struct diffstat_file *data;
2219 data = diffstat_add(diffstat, name_a, name_b);
2221 if (!one || !two) {
2222 data->is_unmerged = 1;
2223 return;
2226 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2227 data->is_binary = 1;
2228 data->added = diff_filespec_size(two);
2229 data->deleted = diff_filespec_size(one);
2232 else if (complete_rewrite) {
2233 diff_populate_filespec(one, 0);
2234 diff_populate_filespec(two, 0);
2235 data->deleted = count_lines(one->data, one->size);
2236 data->added = count_lines(two->data, two->size);
2239 else {
2240 /* Crazy xdl interfaces.. */
2241 xpparam_t xpp;
2242 xdemitconf_t xecfg;
2244 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2245 die("unable to read files to diff");
2247 memset(&xpp, 0, sizeof(xpp));
2248 memset(&xecfg, 0, sizeof(xecfg));
2249 xpp.flags = o->xdl_opts;
2250 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2251 &xpp, &xecfg);
2254 diff_free_filespec_data(one);
2255 diff_free_filespec_data(two);
2258 static void builtin_checkdiff(const char *name_a, const char *name_b,
2259 const char *attr_path,
2260 struct diff_filespec *one,
2261 struct diff_filespec *two,
2262 struct diff_options *o)
2264 mmfile_t mf1, mf2;
2265 struct checkdiff_t data;
2267 if (!two)
2268 return;
2270 memset(&data, 0, sizeof(data));
2271 data.filename = name_b ? name_b : name_a;
2272 data.lineno = 0;
2273 data.o = o;
2274 data.ws_rule = whitespace_rule(attr_path);
2275 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2277 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2278 die("unable to read files to diff");
2281 * All the other codepaths check both sides, but not checking
2282 * the "old" side here is deliberate. We are checking the newly
2283 * introduced changes, and as long as the "new" side is text, we
2284 * can and should check what it introduces.
2286 if (diff_filespec_is_binary(two))
2287 goto free_and_return;
2288 else {
2289 /* Crazy xdl interfaces.. */
2290 xpparam_t xpp;
2291 xdemitconf_t xecfg;
2293 memset(&xpp, 0, sizeof(xpp));
2294 memset(&xecfg, 0, sizeof(xecfg));
2295 xecfg.ctxlen = 1; /* at least one context line */
2296 xpp.flags = 0;
2297 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2298 &xpp, &xecfg);
2300 if (data.ws_rule & WS_BLANK_AT_EOF) {
2301 struct emit_callback ecbdata;
2302 int blank_at_eof;
2304 ecbdata.ws_rule = data.ws_rule;
2305 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2306 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
2308 if (blank_at_eof) {
2309 static char *err;
2310 if (!err)
2311 err = whitespace_error_string(WS_BLANK_AT_EOF);
2312 fprintf(o->file, "%s:%d: %s.\n",
2313 data.filename, blank_at_eof, err);
2314 data.status = 1; /* report errors */
2318 free_and_return:
2319 diff_free_filespec_data(one);
2320 diff_free_filespec_data(two);
2321 if (data.status)
2322 DIFF_OPT_SET(o, CHECK_FAILED);
2325 struct diff_filespec *alloc_filespec(const char *path)
2327 int namelen = strlen(path);
2328 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
2330 memset(spec, 0, sizeof(*spec));
2331 spec->path = (char *)(spec + 1);
2332 memcpy(spec->path, path, namelen+1);
2333 spec->count = 1;
2334 spec->is_binary = -1;
2335 return spec;
2338 void free_filespec(struct diff_filespec *spec)
2340 if (!--spec->count) {
2341 diff_free_filespec_data(spec);
2342 free(spec);
2346 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
2347 unsigned short mode)
2349 if (mode) {
2350 spec->mode = canon_mode(mode);
2351 hashcpy(spec->sha1, sha1);
2352 spec->sha1_valid = !is_null_sha1(sha1);
2357 * Given a name and sha1 pair, if the index tells us the file in
2358 * the work tree has that object contents, return true, so that
2359 * prepare_temp_file() does not have to inflate and extract.
2361 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2363 struct cache_entry *ce;
2364 struct stat st;
2365 int pos, len;
2368 * We do not read the cache ourselves here, because the
2369 * benchmark with my previous version that always reads cache
2370 * shows that it makes things worse for diff-tree comparing
2371 * two linux-2.6 kernel trees in an already checked out work
2372 * tree. This is because most diff-tree comparisons deal with
2373 * only a small number of files, while reading the cache is
2374 * expensive for a large project, and its cost outweighs the
2375 * savings we get by not inflating the object to a temporary
2376 * file. Practically, this code only helps when we are used
2377 * by diff-cache --cached, which does read the cache before
2378 * calling us.
2380 if (!active_cache)
2381 return 0;
2383 /* We want to avoid the working directory if our caller
2384 * doesn't need the data in a normal file, this system
2385 * is rather slow with its stat/open/mmap/close syscalls,
2386 * and the object is contained in a pack file. The pack
2387 * is probably already open and will be faster to obtain
2388 * the data through than the working directory. Loose
2389 * objects however would tend to be slower as they need
2390 * to be individually opened and inflated.
2392 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2393 return 0;
2395 len = strlen(name);
2396 pos = cache_name_pos(name, len);
2397 if (pos < 0)
2398 return 0;
2399 ce = active_cache[pos];
2402 * This is not the sha1 we are looking for, or
2403 * unreusable because it is not a regular file.
2405 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
2406 return 0;
2409 * If ce is marked as "assume unchanged", there is no
2410 * guarantee that work tree matches what we are looking for.
2412 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2413 return 0;
2416 * If ce matches the file in the work tree, we can reuse it.
2418 if (ce_uptodate(ce) ||
2419 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2420 return 1;
2422 return 0;
2425 static int populate_from_stdin(struct diff_filespec *s)
2427 struct strbuf buf = STRBUF_INIT;
2428 size_t size = 0;
2430 if (strbuf_read(&buf, 0, 0) < 0)
2431 return error("error while reading from stdin %s",
2432 strerror(errno));
2434 s->should_munmap = 0;
2435 s->data = strbuf_detach(&buf, &size);
2436 s->size = size;
2437 s->should_free = 1;
2438 return 0;
2441 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2443 int len;
2444 char *data = xmalloc(100), *dirty = "";
2446 /* Are we looking at the work tree? */
2447 if (s->dirty_submodule)
2448 dirty = "-dirty";
2450 len = snprintf(data, 100,
2451 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2452 s->data = data;
2453 s->size = len;
2454 s->should_free = 1;
2455 if (size_only) {
2456 s->data = NULL;
2457 free(data);
2459 return 0;
2463 * While doing rename detection and pickaxe operation, we may need to
2464 * grab the data for the blob (or file) for our own in-core comparison.
2465 * diff_filespec has data and size fields for this purpose.
2467 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2469 int err = 0;
2470 if (!DIFF_FILE_VALID(s))
2471 die("internal error: asking to populate invalid file.");
2472 if (S_ISDIR(s->mode))
2473 return -1;
2475 if (s->data)
2476 return 0;
2478 if (size_only && 0 < s->size)
2479 return 0;
2481 if (S_ISGITLINK(s->mode))
2482 return diff_populate_gitlink(s, size_only);
2484 if (!s->sha1_valid ||
2485 reuse_worktree_file(s->path, s->sha1, 0)) {
2486 struct strbuf buf = STRBUF_INIT;
2487 struct stat st;
2488 int fd;
2490 if (!strcmp(s->path, "-"))
2491 return populate_from_stdin(s);
2493 if (lstat(s->path, &st) < 0) {
2494 if (errno == ENOENT) {
2495 err_empty:
2496 err = -1;
2497 empty:
2498 s->data = (char *)"";
2499 s->size = 0;
2500 return err;
2503 s->size = xsize_t(st.st_size);
2504 if (!s->size)
2505 goto empty;
2506 if (S_ISLNK(st.st_mode)) {
2507 struct strbuf sb = STRBUF_INIT;
2509 if (strbuf_readlink(&sb, s->path, s->size))
2510 goto err_empty;
2511 s->size = sb.len;
2512 s->data = strbuf_detach(&sb, NULL);
2513 s->should_free = 1;
2514 return 0;
2516 if (size_only)
2517 return 0;
2518 fd = open(s->path, O_RDONLY);
2519 if (fd < 0)
2520 goto err_empty;
2521 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2522 close(fd);
2523 s->should_munmap = 1;
2526 * Convert from working tree format to canonical git format
2528 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2529 size_t size = 0;
2530 munmap(s->data, s->size);
2531 s->should_munmap = 0;
2532 s->data = strbuf_detach(&buf, &size);
2533 s->size = size;
2534 s->should_free = 1;
2537 else {
2538 enum object_type type;
2539 if (size_only) {
2540 type = sha1_object_info(s->sha1, &s->size);
2541 if (type < 0)
2542 die("unable to read %s", sha1_to_hex(s->sha1));
2543 } else {
2544 s->data = read_sha1_file(s->sha1, &type, &s->size);
2545 if (!s->data)
2546 die("unable to read %s", sha1_to_hex(s->sha1));
2547 s->should_free = 1;
2550 return 0;
2553 void diff_free_filespec_blob(struct diff_filespec *s)
2555 if (s->should_free)
2556 free(s->data);
2557 else if (s->should_munmap)
2558 munmap(s->data, s->size);
2560 if (s->should_free || s->should_munmap) {
2561 s->should_free = s->should_munmap = 0;
2562 s->data = NULL;
2566 void diff_free_filespec_data(struct diff_filespec *s)
2568 diff_free_filespec_blob(s);
2569 free(s->cnt_data);
2570 s->cnt_data = NULL;
2573 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2574 void *blob,
2575 unsigned long size,
2576 const unsigned char *sha1,
2577 int mode)
2579 int fd;
2580 struct strbuf buf = STRBUF_INIT;
2581 struct strbuf template = STRBUF_INIT;
2582 char *path_dup = xstrdup(path);
2583 const char *base = basename(path_dup);
2585 /* Generate "XXXXXX_basename.ext" */
2586 strbuf_addstr(&template, "XXXXXX_");
2587 strbuf_addstr(&template, base);
2589 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2590 strlen(base) + 1);
2591 if (fd < 0)
2592 die_errno("unable to create temp-file");
2593 if (convert_to_working_tree(path,
2594 (const char *)blob, (size_t)size, &buf)) {
2595 blob = buf.buf;
2596 size = buf.len;
2598 if (write_in_full(fd, blob, size) != size)
2599 die_errno("unable to write temp-file");
2600 close(fd);
2601 temp->name = temp->tmp_path;
2602 strcpy(temp->hex, sha1_to_hex(sha1));
2603 temp->hex[40] = 0;
2604 sprintf(temp->mode, "%06o", mode);
2605 strbuf_release(&buf);
2606 strbuf_release(&template);
2607 free(path_dup);
2610 static struct diff_tempfile *prepare_temp_file(const char *name,
2611 struct diff_filespec *one)
2613 struct diff_tempfile *temp = claim_diff_tempfile();
2615 if (!DIFF_FILE_VALID(one)) {
2616 not_a_valid_file:
2617 /* A '-' entry produces this for file-2, and
2618 * a '+' entry produces this for file-1.
2620 temp->name = "/dev/null";
2621 strcpy(temp->hex, ".");
2622 strcpy(temp->mode, ".");
2623 return temp;
2626 if (!remove_tempfile_installed) {
2627 atexit(remove_tempfile);
2628 sigchain_push_common(remove_tempfile_on_signal);
2629 remove_tempfile_installed = 1;
2632 if (!one->sha1_valid ||
2633 reuse_worktree_file(name, one->sha1, 1)) {
2634 struct stat st;
2635 if (lstat(name, &st) < 0) {
2636 if (errno == ENOENT)
2637 goto not_a_valid_file;
2638 die_errno("stat(%s)", name);
2640 if (S_ISLNK(st.st_mode)) {
2641 struct strbuf sb = STRBUF_INIT;
2642 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2643 die_errno("readlink(%s)", name);
2644 prep_temp_blob(name, temp, sb.buf, sb.len,
2645 (one->sha1_valid ?
2646 one->sha1 : null_sha1),
2647 (one->sha1_valid ?
2648 one->mode : S_IFLNK));
2649 strbuf_release(&sb);
2651 else {
2652 /* we can borrow from the file in the work tree */
2653 temp->name = name;
2654 if (!one->sha1_valid)
2655 strcpy(temp->hex, sha1_to_hex(null_sha1));
2656 else
2657 strcpy(temp->hex, sha1_to_hex(one->sha1));
2658 /* Even though we may sometimes borrow the
2659 * contents from the work tree, we always want
2660 * one->mode. mode is trustworthy even when
2661 * !(one->sha1_valid), as long as
2662 * DIFF_FILE_VALID(one).
2664 sprintf(temp->mode, "%06o", one->mode);
2666 return temp;
2668 else {
2669 if (diff_populate_filespec(one, 0))
2670 die("cannot read data blob for %s", one->path);
2671 prep_temp_blob(name, temp, one->data, one->size,
2672 one->sha1, one->mode);
2674 return temp;
2677 /* An external diff command takes:
2679 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2680 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2683 static void run_external_diff(const char *pgm,
2684 const char *name,
2685 const char *other,
2686 struct diff_filespec *one,
2687 struct diff_filespec *two,
2688 const char *xfrm_msg,
2689 int complete_rewrite)
2691 const char *spawn_arg[10];
2692 int retval;
2693 const char **arg = &spawn_arg[0];
2695 if (one && two) {
2696 struct diff_tempfile *temp_one, *temp_two;
2697 const char *othername = (other ? other : name);
2698 temp_one = prepare_temp_file(name, one);
2699 temp_two = prepare_temp_file(othername, two);
2700 *arg++ = pgm;
2701 *arg++ = name;
2702 *arg++ = temp_one->name;
2703 *arg++ = temp_one->hex;
2704 *arg++ = temp_one->mode;
2705 *arg++ = temp_two->name;
2706 *arg++ = temp_two->hex;
2707 *arg++ = temp_two->mode;
2708 if (other) {
2709 *arg++ = other;
2710 *arg++ = xfrm_msg;
2712 } else {
2713 *arg++ = pgm;
2714 *arg++ = name;
2716 *arg = NULL;
2717 fflush(NULL);
2718 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2719 remove_tempfile();
2720 if (retval) {
2721 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2722 exit(1);
2726 static int similarity_index(struct diff_filepair *p)
2728 return p->score * 100 / MAX_SCORE;
2731 static void fill_metainfo(struct strbuf *msg,
2732 const char *name,
2733 const char *other,
2734 struct diff_filespec *one,
2735 struct diff_filespec *two,
2736 struct diff_options *o,
2737 struct diff_filepair *p,
2738 int *must_show_header,
2739 int use_color)
2741 const char *set = diff_get_color(use_color, DIFF_METAINFO);
2742 const char *reset = diff_get_color(use_color, DIFF_RESET);
2743 struct strbuf *msgbuf;
2744 char *line_prefix = "";
2746 *must_show_header = 1;
2747 if (o->output_prefix) {
2748 msgbuf = o->output_prefix(o, o->output_prefix_data);
2749 line_prefix = msgbuf->buf;
2751 strbuf_init(msg, PATH_MAX * 2 + 300);
2752 switch (p->status) {
2753 case DIFF_STATUS_COPIED:
2754 strbuf_addf(msg, "%s%ssimilarity index %d%%",
2755 line_prefix, set, similarity_index(p));
2756 strbuf_addf(msg, "%s\n%s%scopy from ",
2757 reset, line_prefix, set);
2758 quote_c_style(name, msg, NULL, 0);
2759 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
2760 quote_c_style(other, msg, NULL, 0);
2761 strbuf_addf(msg, "%s\n", reset);
2762 break;
2763 case DIFF_STATUS_RENAMED:
2764 strbuf_addf(msg, "%s%ssimilarity index %d%%",
2765 line_prefix, set, similarity_index(p));
2766 strbuf_addf(msg, "%s\n%s%srename from ",
2767 reset, line_prefix, set);
2768 quote_c_style(name, msg, NULL, 0);
2769 strbuf_addf(msg, "%s\n%s%srename to ",
2770 reset, line_prefix, set);
2771 quote_c_style(other, msg, NULL, 0);
2772 strbuf_addf(msg, "%s\n", reset);
2773 break;
2774 case DIFF_STATUS_MODIFIED:
2775 if (p->score) {
2776 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
2777 line_prefix,
2778 set, similarity_index(p), reset);
2779 break;
2781 /* fallthru */
2782 default:
2783 *must_show_header = 0;
2785 if (one && two && hashcmp(one->sha1, two->sha1)) {
2786 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2788 if (DIFF_OPT_TST(o, BINARY)) {
2789 mmfile_t mf;
2790 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2791 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2792 abbrev = 40;
2794 strbuf_addf(msg, "%s%sindex %s..", line_prefix, set,
2795 find_unique_abbrev(one->sha1, abbrev));
2796 strbuf_addstr(msg, find_unique_abbrev(two->sha1, abbrev));
2797 if (one->mode == two->mode)
2798 strbuf_addf(msg, " %06o", one->mode);
2799 strbuf_addf(msg, "%s\n", reset);
2803 static void run_diff_cmd(const char *pgm,
2804 const char *name,
2805 const char *other,
2806 const char *attr_path,
2807 struct diff_filespec *one,
2808 struct diff_filespec *two,
2809 struct strbuf *msg,
2810 struct diff_options *o,
2811 struct diff_filepair *p)
2813 const char *xfrm_msg = NULL;
2814 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2815 int must_show_header = 0;
2817 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2818 pgm = NULL;
2819 else {
2820 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2821 if (drv && drv->external)
2822 pgm = drv->external;
2825 if (msg) {
2827 * don't use colors when the header is intended for an
2828 * external diff driver
2830 fill_metainfo(msg, name, other, one, two, o, p,
2831 &must_show_header,
2832 DIFF_OPT_TST(o, COLOR_DIFF) && !pgm);
2833 xfrm_msg = msg->len ? msg->buf : NULL;
2836 if (pgm) {
2837 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2838 complete_rewrite);
2839 return;
2841 if (one && two)
2842 builtin_diff(name, other ? other : name,
2843 one, two, xfrm_msg, must_show_header,
2844 o, complete_rewrite);
2845 else
2846 fprintf(o->file, "* Unmerged path %s\n", name);
2849 static void diff_fill_sha1_info(struct diff_filespec *one)
2851 if (DIFF_FILE_VALID(one)) {
2852 if (!one->sha1_valid) {
2853 struct stat st;
2854 if (!strcmp(one->path, "-")) {
2855 hashcpy(one->sha1, null_sha1);
2856 return;
2858 if (lstat(one->path, &st) < 0)
2859 die_errno("stat '%s'", one->path);
2860 if (index_path(one->sha1, one->path, &st, 0))
2861 die("cannot hash %s", one->path);
2864 else
2865 hashclr(one->sha1);
2868 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2870 /* Strip the prefix but do not molest /dev/null and absolute paths */
2871 if (*namep && **namep != '/') {
2872 *namep += prefix_length;
2873 if (**namep == '/')
2874 ++*namep;
2876 if (*otherp && **otherp != '/') {
2877 *otherp += prefix_length;
2878 if (**otherp == '/')
2879 ++*otherp;
2883 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2885 const char *pgm = external_diff();
2886 struct strbuf msg;
2887 struct diff_filespec *one = p->one;
2888 struct diff_filespec *two = p->two;
2889 const char *name;
2890 const char *other;
2891 const char *attr_path;
2893 name = p->one->path;
2894 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2895 attr_path = name;
2896 if (o->prefix_length)
2897 strip_prefix(o->prefix_length, &name, &other);
2899 if (DIFF_PAIR_UNMERGED(p)) {
2900 run_diff_cmd(pgm, name, NULL, attr_path,
2901 NULL, NULL, NULL, o, p);
2902 return;
2905 diff_fill_sha1_info(one);
2906 diff_fill_sha1_info(two);
2908 if (!pgm &&
2909 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2910 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2912 * a filepair that changes between file and symlink
2913 * needs to be split into deletion and creation.
2915 struct diff_filespec *null = alloc_filespec(two->path);
2916 run_diff_cmd(NULL, name, other, attr_path,
2917 one, null, &msg, o, p);
2918 free(null);
2919 strbuf_release(&msg);
2921 null = alloc_filespec(one->path);
2922 run_diff_cmd(NULL, name, other, attr_path,
2923 null, two, &msg, o, p);
2924 free(null);
2926 else
2927 run_diff_cmd(pgm, name, other, attr_path,
2928 one, two, &msg, o, p);
2930 strbuf_release(&msg);
2933 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2934 struct diffstat_t *diffstat)
2936 const char *name;
2937 const char *other;
2938 int complete_rewrite = 0;
2940 if (DIFF_PAIR_UNMERGED(p)) {
2941 /* unmerged */
2942 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2943 return;
2946 name = p->one->path;
2947 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2949 if (o->prefix_length)
2950 strip_prefix(o->prefix_length, &name, &other);
2952 diff_fill_sha1_info(p->one);
2953 diff_fill_sha1_info(p->two);
2955 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2956 complete_rewrite = 1;
2957 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2960 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2962 const char *name;
2963 const char *other;
2964 const char *attr_path;
2966 if (DIFF_PAIR_UNMERGED(p)) {
2967 /* unmerged */
2968 return;
2971 name = p->one->path;
2972 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2973 attr_path = other ? other : name;
2975 if (o->prefix_length)
2976 strip_prefix(o->prefix_length, &name, &other);
2978 diff_fill_sha1_info(p->one);
2979 diff_fill_sha1_info(p->two);
2981 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2984 void diff_setup(struct diff_options *options)
2986 memcpy(options, &default_diff_options, sizeof(*options));
2988 options->file = stdout;
2990 options->line_termination = '\n';
2991 options->break_opt = -1;
2992 options->rename_limit = -1;
2993 options->dirstat_permille = diff_dirstat_permille_default;
2994 options->context = 3;
2996 options->change = diff_change;
2997 options->add_remove = diff_addremove;
2998 if (diff_use_color_default > 0)
2999 DIFF_OPT_SET(options, COLOR_DIFF);
3000 options->detect_rename = diff_detect_rename_default;
3002 if (diff_no_prefix) {
3003 options->a_prefix = options->b_prefix = "";
3004 } else if (!diff_mnemonic_prefix) {
3005 options->a_prefix = "a/";
3006 options->b_prefix = "b/";
3010 int diff_setup_done(struct diff_options *options)
3012 int count = 0;
3014 if (options->output_format & DIFF_FORMAT_NAME)
3015 count++;
3016 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3017 count++;
3018 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3019 count++;
3020 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3021 count++;
3022 if (count > 1)
3023 die("--name-only, --name-status, --check and -s are mutually exclusive");
3026 * Most of the time we can say "there are changes"
3027 * only by checking if there are changed paths, but
3028 * --ignore-whitespace* options force us to look
3029 * inside contents.
3032 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3033 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3034 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3035 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3036 else
3037 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3039 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3040 options->detect_rename = DIFF_DETECT_COPY;
3042 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3043 options->prefix = NULL;
3044 if (options->prefix)
3045 options->prefix_length = strlen(options->prefix);
3046 else
3047 options->prefix_length = 0;
3049 if (options->output_format & (DIFF_FORMAT_NAME |
3050 DIFF_FORMAT_NAME_STATUS |
3051 DIFF_FORMAT_CHECKDIFF |
3052 DIFF_FORMAT_NO_OUTPUT))
3053 options->output_format &= ~(DIFF_FORMAT_RAW |
3054 DIFF_FORMAT_NUMSTAT |
3055 DIFF_FORMAT_DIFFSTAT |
3056 DIFF_FORMAT_SHORTSTAT |
3057 DIFF_FORMAT_DIRSTAT |
3058 DIFF_FORMAT_SUMMARY |
3059 DIFF_FORMAT_PATCH);
3062 * These cases always need recursive; we do not drop caller-supplied
3063 * recursive bits for other formats here.
3065 if (options->output_format & (DIFF_FORMAT_PATCH |
3066 DIFF_FORMAT_NUMSTAT |
3067 DIFF_FORMAT_DIFFSTAT |
3068 DIFF_FORMAT_SHORTSTAT |
3069 DIFF_FORMAT_DIRSTAT |
3070 DIFF_FORMAT_SUMMARY |
3071 DIFF_FORMAT_CHECKDIFF))
3072 DIFF_OPT_SET(options, RECURSIVE);
3074 * Also pickaxe would not work very well if you do not say recursive
3076 if (options->pickaxe)
3077 DIFF_OPT_SET(options, RECURSIVE);
3079 * When patches are generated, submodules diffed against the work tree
3080 * must be checked for dirtiness too so it can be shown in the output
3082 if (options->output_format & DIFF_FORMAT_PATCH)
3083 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
3085 if (options->detect_rename && options->rename_limit < 0)
3086 options->rename_limit = diff_rename_limit_default;
3087 if (options->setup & DIFF_SETUP_USE_CACHE) {
3088 if (!active_cache)
3089 /* read-cache does not die even when it fails
3090 * so it is safe for us to do this here. Also
3091 * it does not smudge active_cache or active_nr
3092 * when it fails, so we do not have to worry about
3093 * cleaning it up ourselves either.
3095 read_cache();
3097 if (options->abbrev <= 0 || 40 < options->abbrev)
3098 options->abbrev = 40; /* full */
3101 * It does not make sense to show the first hit we happened
3102 * to have found. It does not make sense not to return with
3103 * exit code in such a case either.
3105 if (DIFF_OPT_TST(options, QUICK)) {
3106 options->output_format = DIFF_FORMAT_NO_OUTPUT;
3107 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3110 return 0;
3113 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
3115 char c, *eq;
3116 int len;
3118 if (*arg != '-')
3119 return 0;
3120 c = *++arg;
3121 if (!c)
3122 return 0;
3123 if (c == arg_short) {
3124 c = *++arg;
3125 if (!c)
3126 return 1;
3127 if (val && isdigit(c)) {
3128 char *end;
3129 int n = strtoul(arg, &end, 10);
3130 if (*end)
3131 return 0;
3132 *val = n;
3133 return 1;
3135 return 0;
3137 if (c != '-')
3138 return 0;
3139 arg++;
3140 eq = strchr(arg, '=');
3141 if (eq)
3142 len = eq - arg;
3143 else
3144 len = strlen(arg);
3145 if (!len || strncmp(arg, arg_long, len))
3146 return 0;
3147 if (eq) {
3148 int n;
3149 char *end;
3150 if (!isdigit(*++eq))
3151 return 0;
3152 n = strtoul(eq, &end, 10);
3153 if (*end)
3154 return 0;
3155 *val = n;
3157 return 1;
3160 static int diff_scoreopt_parse(const char *opt);
3162 static inline int short_opt(char opt, const char **argv,
3163 const char **optarg)
3165 const char *arg = argv[0];
3166 if (arg[0] != '-' || arg[1] != opt)
3167 return 0;
3168 if (arg[2] != '\0') {
3169 *optarg = arg + 2;
3170 return 1;
3172 if (!argv[1])
3173 die("Option '%c' requires a value", opt);
3174 *optarg = argv[1];
3175 return 2;
3178 int parse_long_opt(const char *opt, const char **argv,
3179 const char **optarg)
3181 const char *arg = argv[0];
3182 if (arg[0] != '-' || arg[1] != '-')
3183 return 0;
3184 arg += strlen("--");
3185 if (prefixcmp(arg, opt))
3186 return 0;
3187 arg += strlen(opt);
3188 if (*arg == '=') { /* sticked form: --option=value */
3189 *optarg = arg + 1;
3190 return 1;
3192 if (*arg != '\0')
3193 return 0;
3194 /* separate form: --option value */
3195 if (!argv[1])
3196 die("Option '--%s' requires a value", opt);
3197 *optarg = argv[1];
3198 return 2;
3201 static int stat_opt(struct diff_options *options, const char **av)
3203 const char *arg = av[0];
3204 char *end;
3205 int width = options->stat_width;
3206 int name_width = options->stat_name_width;
3207 int argcount = 1;
3209 arg += strlen("--stat");
3210 end = (char *)arg;
3212 switch (*arg) {
3213 case '-':
3214 if (!prefixcmp(arg, "-width")) {
3215 arg += strlen("-width");
3216 if (*arg == '=')
3217 width = strtoul(arg + 1, &end, 10);
3218 else if (!*arg && !av[1])
3219 die("Option '--stat-width' requires a value");
3220 else if (!*arg) {
3221 width = strtoul(av[1], &end, 10);
3222 argcount = 2;
3224 } else if (!prefixcmp(arg, "-name-width")) {
3225 arg += strlen("-name-width");
3226 if (*arg == '=')
3227 name_width = strtoul(arg + 1, &end, 10);
3228 else if (!*arg && !av[1])
3229 die("Option '--stat-name-width' requires a value");
3230 else if (!*arg) {
3231 name_width = strtoul(av[1], &end, 10);
3232 argcount = 2;
3235 break;
3236 case '=':
3237 width = strtoul(arg+1, &end, 10);
3238 if (*end == ',')
3239 name_width = strtoul(end+1, &end, 10);
3242 /* Important! This checks all the error cases! */
3243 if (*end)
3244 return 0;
3245 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3246 options->stat_name_width = name_width;
3247 options->stat_width = width;
3248 return argcount;
3251 static int parse_dirstat_opt(struct diff_options *options, const char *params)
3253 if (parse_dirstat_params(options, params))
3254 die("Failed to parse --dirstat/-X option parameter");
3256 * The caller knows a dirstat-related option is given from the command
3257 * line; allow it to say "return this_function();"
3259 options->output_format |= DIFF_FORMAT_DIRSTAT;
3260 return 1;
3263 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
3265 const char *arg = av[0];
3266 const char *optarg;
3267 int argcount;
3269 /* Output format options */
3270 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch"))
3271 options->output_format |= DIFF_FORMAT_PATCH;
3272 else if (opt_arg(arg, 'U', "unified", &options->context))
3273 options->output_format |= DIFF_FORMAT_PATCH;
3274 else if (!strcmp(arg, "--raw"))
3275 options->output_format |= DIFF_FORMAT_RAW;
3276 else if (!strcmp(arg, "--patch-with-raw"))
3277 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
3278 else if (!strcmp(arg, "--numstat"))
3279 options->output_format |= DIFF_FORMAT_NUMSTAT;
3280 else if (!strcmp(arg, "--shortstat"))
3281 options->output_format |= DIFF_FORMAT_SHORTSTAT;
3282 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
3283 return parse_dirstat_opt(options, "");
3284 else if (!prefixcmp(arg, "-X"))
3285 return parse_dirstat_opt(options, arg + 2);
3286 else if (!prefixcmp(arg, "--dirstat="))
3287 return parse_dirstat_opt(options, arg + 10);
3288 else if (!strcmp(arg, "--cumulative"))
3289 return parse_dirstat_opt(options, "cumulative");
3290 else if (!strcmp(arg, "--dirstat-by-file"))
3291 return parse_dirstat_opt(options, "files");
3292 else if (!prefixcmp(arg, "--dirstat-by-file=")) {
3293 parse_dirstat_opt(options, "files");
3294 return parse_dirstat_opt(options, arg + 18);
3296 else if (!strcmp(arg, "--check"))
3297 options->output_format |= DIFF_FORMAT_CHECKDIFF;
3298 else if (!strcmp(arg, "--summary"))
3299 options->output_format |= DIFF_FORMAT_SUMMARY;
3300 else if (!strcmp(arg, "--patch-with-stat"))
3301 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
3302 else if (!strcmp(arg, "--name-only"))
3303 options->output_format |= DIFF_FORMAT_NAME;
3304 else if (!strcmp(arg, "--name-status"))
3305 options->output_format |= DIFF_FORMAT_NAME_STATUS;
3306 else if (!strcmp(arg, "-s"))
3307 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
3308 else if (!prefixcmp(arg, "--stat"))
3309 /* --stat, --stat-width, or --stat-name-width */
3310 return stat_opt(options, av);
3312 /* renames options */
3313 else if (!prefixcmp(arg, "-B") || !prefixcmp(arg, "--break-rewrites=") ||
3314 !strcmp(arg, "--break-rewrites")) {
3315 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
3316 return error("invalid argument to -B: %s", arg+2);
3318 else if (!prefixcmp(arg, "-M") || !prefixcmp(arg, "--find-renames=") ||
3319 !strcmp(arg, "--find-renames")) {
3320 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3321 return error("invalid argument to -M: %s", arg+2);
3322 options->detect_rename = DIFF_DETECT_RENAME;
3324 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
3325 options->irreversible_delete = 1;
3327 else if (!prefixcmp(arg, "-C") || !prefixcmp(arg, "--find-copies=") ||
3328 !strcmp(arg, "--find-copies")) {
3329 if (options->detect_rename == DIFF_DETECT_COPY)
3330 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3331 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3332 return error("invalid argument to -C: %s", arg+2);
3333 options->detect_rename = DIFF_DETECT_COPY;
3335 else if (!strcmp(arg, "--no-renames"))
3336 options->detect_rename = 0;
3337 else if (!strcmp(arg, "--relative"))
3338 DIFF_OPT_SET(options, RELATIVE_NAME);
3339 else if (!prefixcmp(arg, "--relative=")) {
3340 DIFF_OPT_SET(options, RELATIVE_NAME);
3341 options->prefix = arg + 11;
3344 /* xdiff options */
3345 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
3346 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
3347 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
3348 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
3349 else if (!strcmp(arg, "--ignore-space-at-eol"))
3350 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
3351 else if (!strcmp(arg, "--patience"))
3352 DIFF_XDL_SET(options, PATIENCE_DIFF);
3354 /* flags options */
3355 else if (!strcmp(arg, "--binary")) {
3356 options->output_format |= DIFF_FORMAT_PATCH;
3357 DIFF_OPT_SET(options, BINARY);
3359 else if (!strcmp(arg, "--full-index"))
3360 DIFF_OPT_SET(options, FULL_INDEX);
3361 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
3362 DIFF_OPT_SET(options, TEXT);
3363 else if (!strcmp(arg, "-R"))
3364 DIFF_OPT_SET(options, REVERSE_DIFF);
3365 else if (!strcmp(arg, "--find-copies-harder"))
3366 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3367 else if (!strcmp(arg, "--follow"))
3368 DIFF_OPT_SET(options, FOLLOW_RENAMES);
3369 else if (!strcmp(arg, "--color"))
3370 DIFF_OPT_SET(options, COLOR_DIFF);
3371 else if (!prefixcmp(arg, "--color=")) {
3372 int value = git_config_colorbool(NULL, arg+8, -1);
3373 if (value == 0)
3374 DIFF_OPT_CLR(options, COLOR_DIFF);
3375 else if (value > 0)
3376 DIFF_OPT_SET(options, COLOR_DIFF);
3377 else
3378 return error("option `color' expects \"always\", \"auto\", or \"never\"");
3380 else if (!strcmp(arg, "--no-color"))
3381 DIFF_OPT_CLR(options, COLOR_DIFF);
3382 else if (!strcmp(arg, "--color-words")) {
3383 DIFF_OPT_SET(options, COLOR_DIFF);
3384 options->word_diff = DIFF_WORDS_COLOR;
3386 else if (!prefixcmp(arg, "--color-words=")) {
3387 DIFF_OPT_SET(options, COLOR_DIFF);
3388 options->word_diff = DIFF_WORDS_COLOR;
3389 options->word_regex = arg + 14;
3391 else if (!strcmp(arg, "--word-diff")) {
3392 if (options->word_diff == DIFF_WORDS_NONE)
3393 options->word_diff = DIFF_WORDS_PLAIN;
3395 else if (!prefixcmp(arg, "--word-diff=")) {
3396 const char *type = arg + 12;
3397 if (!strcmp(type, "plain"))
3398 options->word_diff = DIFF_WORDS_PLAIN;
3399 else if (!strcmp(type, "color")) {
3400 DIFF_OPT_SET(options, COLOR_DIFF);
3401 options->word_diff = DIFF_WORDS_COLOR;
3403 else if (!strcmp(type, "porcelain"))
3404 options->word_diff = DIFF_WORDS_PORCELAIN;
3405 else if (!strcmp(type, "none"))
3406 options->word_diff = DIFF_WORDS_NONE;
3407 else
3408 die("bad --word-diff argument: %s", type);
3410 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
3411 if (options->word_diff == DIFF_WORDS_NONE)
3412 options->word_diff = DIFF_WORDS_PLAIN;
3413 options->word_regex = optarg;
3414 return argcount;
3416 else if (!strcmp(arg, "--exit-code"))
3417 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3418 else if (!strcmp(arg, "--quiet"))
3419 DIFF_OPT_SET(options, QUICK);
3420 else if (!strcmp(arg, "--ext-diff"))
3421 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
3422 else if (!strcmp(arg, "--no-ext-diff"))
3423 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
3424 else if (!strcmp(arg, "--textconv"))
3425 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3426 else if (!strcmp(arg, "--no-textconv"))
3427 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
3428 else if (!strcmp(arg, "--ignore-submodules")) {
3429 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3430 handle_ignore_submodules_arg(options, "all");
3431 } else if (!prefixcmp(arg, "--ignore-submodules=")) {
3432 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3433 handle_ignore_submodules_arg(options, arg + 20);
3434 } else if (!strcmp(arg, "--submodule"))
3435 DIFF_OPT_SET(options, SUBMODULE_LOG);
3436 else if (!prefixcmp(arg, "--submodule=")) {
3437 if (!strcmp(arg + 12, "log"))
3438 DIFF_OPT_SET(options, SUBMODULE_LOG);
3441 /* misc options */
3442 else if (!strcmp(arg, "-z"))
3443 options->line_termination = 0;
3444 else if ((argcount = short_opt('l', av, &optarg))) {
3445 options->rename_limit = strtoul(optarg, NULL, 10);
3446 return argcount;
3448 else if ((argcount = short_opt('S', av, &optarg))) {
3449 options->pickaxe = optarg;
3450 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
3451 return argcount;
3452 } else if ((argcount = short_opt('G', av, &optarg))) {
3453 options->pickaxe = optarg;
3454 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
3455 return argcount;
3457 else if (!strcmp(arg, "--pickaxe-all"))
3458 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
3459 else if (!strcmp(arg, "--pickaxe-regex"))
3460 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
3461 else if ((argcount = short_opt('O', av, &optarg))) {
3462 options->orderfile = optarg;
3463 return argcount;
3465 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
3466 options->filter = optarg;
3467 return argcount;
3469 else if (!strcmp(arg, "--abbrev"))
3470 options->abbrev = DEFAULT_ABBREV;
3471 else if (!prefixcmp(arg, "--abbrev=")) {
3472 options->abbrev = strtoul(arg + 9, NULL, 10);
3473 if (options->abbrev < MINIMUM_ABBREV)
3474 options->abbrev = MINIMUM_ABBREV;
3475 else if (40 < options->abbrev)
3476 options->abbrev = 40;
3478 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
3479 options->a_prefix = optarg;
3480 return argcount;
3482 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
3483 options->b_prefix = optarg;
3484 return argcount;
3486 else if (!strcmp(arg, "--no-prefix"))
3487 options->a_prefix = options->b_prefix = "";
3488 else if (opt_arg(arg, '\0', "inter-hunk-context",
3489 &options->interhunkcontext))
3491 else if ((argcount = parse_long_opt("output", av, &optarg))) {
3492 options->file = fopen(optarg, "w");
3493 if (!options->file)
3494 die_errno("Could not open '%s'", optarg);
3495 options->close_file = 1;
3496 return argcount;
3497 } else
3498 return 0;
3499 return 1;
3502 int parse_rename_score(const char **cp_p)
3504 unsigned long num, scale;
3505 int ch, dot;
3506 const char *cp = *cp_p;
3508 num = 0;
3509 scale = 1;
3510 dot = 0;
3511 for (;;) {
3512 ch = *cp;
3513 if ( !dot && ch == '.' ) {
3514 scale = 1;
3515 dot = 1;
3516 } else if ( ch == '%' ) {
3517 scale = dot ? scale*100 : 100;
3518 cp++; /* % is always at the end */
3519 break;
3520 } else if ( ch >= '0' && ch <= '9' ) {
3521 if ( scale < 100000 ) {
3522 scale *= 10;
3523 num = (num*10) + (ch-'0');
3525 } else {
3526 break;
3528 cp++;
3530 *cp_p = cp;
3532 /* user says num divided by scale and we say internally that
3533 * is MAX_SCORE * num / scale.
3535 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3538 static int diff_scoreopt_parse(const char *opt)
3540 int opt1, opt2, cmd;
3542 if (*opt++ != '-')
3543 return -1;
3544 cmd = *opt++;
3545 if (cmd == '-') {
3546 /* convert the long-form arguments into short-form versions */
3547 if (!prefixcmp(opt, "break-rewrites")) {
3548 opt += strlen("break-rewrites");
3549 if (*opt == 0 || *opt++ == '=')
3550 cmd = 'B';
3551 } else if (!prefixcmp(opt, "find-copies")) {
3552 opt += strlen("find-copies");
3553 if (*opt == 0 || *opt++ == '=')
3554 cmd = 'C';
3555 } else if (!prefixcmp(opt, "find-renames")) {
3556 opt += strlen("find-renames");
3557 if (*opt == 0 || *opt++ == '=')
3558 cmd = 'M';
3561 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3562 return -1; /* that is not a -M, -C nor -B option */
3564 opt1 = parse_rename_score(&opt);
3565 if (cmd != 'B')
3566 opt2 = 0;
3567 else {
3568 if (*opt == 0)
3569 opt2 = 0;
3570 else if (*opt != '/')
3571 return -1; /* we expect -B80/99 or -B80 */
3572 else {
3573 opt++;
3574 opt2 = parse_rename_score(&opt);
3577 if (*opt != 0)
3578 return -1;
3579 return opt1 | (opt2 << 16);
3582 struct diff_queue_struct diff_queued_diff;
3584 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3586 if (queue->alloc <= queue->nr) {
3587 queue->alloc = alloc_nr(queue->alloc);
3588 queue->queue = xrealloc(queue->queue,
3589 sizeof(dp) * queue->alloc);
3591 queue->queue[queue->nr++] = dp;
3594 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3595 struct diff_filespec *one,
3596 struct diff_filespec *two)
3598 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3599 dp->one = one;
3600 dp->two = two;
3601 if (queue)
3602 diff_q(queue, dp);
3603 return dp;
3606 void diff_free_filepair(struct diff_filepair *p)
3608 free_filespec(p->one);
3609 free_filespec(p->two);
3610 free(p);
3613 /* This is different from find_unique_abbrev() in that
3614 * it stuffs the result with dots for alignment.
3616 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3618 int abblen;
3619 const char *abbrev;
3620 if (len == 40)
3621 return sha1_to_hex(sha1);
3623 abbrev = find_unique_abbrev(sha1, len);
3624 abblen = strlen(abbrev);
3625 if (abblen < 37) {
3626 static char hex[41];
3627 if (len < abblen && abblen <= len + 2)
3628 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3629 else
3630 sprintf(hex, "%s...", abbrev);
3631 return hex;
3633 return sha1_to_hex(sha1);
3636 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3638 int line_termination = opt->line_termination;
3639 int inter_name_termination = line_termination ? '\t' : '\0';
3640 if (opt->output_prefix) {
3641 struct strbuf *msg = NULL;
3642 msg = opt->output_prefix(opt, opt->output_prefix_data);
3643 fprintf(opt->file, "%s", msg->buf);
3646 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3647 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3648 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3649 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3651 if (p->score) {
3652 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3653 inter_name_termination);
3654 } else {
3655 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3658 if (p->status == DIFF_STATUS_COPIED ||
3659 p->status == DIFF_STATUS_RENAMED) {
3660 const char *name_a, *name_b;
3661 name_a = p->one->path;
3662 name_b = p->two->path;
3663 strip_prefix(opt->prefix_length, &name_a, &name_b);
3664 write_name_quoted(name_a, opt->file, inter_name_termination);
3665 write_name_quoted(name_b, opt->file, line_termination);
3666 } else {
3667 const char *name_a, *name_b;
3668 name_a = p->one->mode ? p->one->path : p->two->path;
3669 name_b = NULL;
3670 strip_prefix(opt->prefix_length, &name_a, &name_b);
3671 write_name_quoted(name_a, opt->file, line_termination);
3675 int diff_unmodified_pair(struct diff_filepair *p)
3677 /* This function is written stricter than necessary to support
3678 * the currently implemented transformers, but the idea is to
3679 * let transformers to produce diff_filepairs any way they want,
3680 * and filter and clean them up here before producing the output.
3682 struct diff_filespec *one = p->one, *two = p->two;
3684 if (DIFF_PAIR_UNMERGED(p))
3685 return 0; /* unmerged is interesting */
3687 /* deletion, addition, mode or type change
3688 * and rename are all interesting.
3690 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3691 DIFF_PAIR_MODE_CHANGED(p) ||
3692 strcmp(one->path, two->path))
3693 return 0;
3695 /* both are valid and point at the same path. that is, we are
3696 * dealing with a change.
3698 if (one->sha1_valid && two->sha1_valid &&
3699 !hashcmp(one->sha1, two->sha1) &&
3700 !one->dirty_submodule && !two->dirty_submodule)
3701 return 1; /* no change */
3702 if (!one->sha1_valid && !two->sha1_valid)
3703 return 1; /* both look at the same file on the filesystem. */
3704 return 0;
3707 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3709 if (diff_unmodified_pair(p))
3710 return;
3712 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3713 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3714 return; /* no tree diffs in patch format */
3716 run_diff(p, o);
3719 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3720 struct diffstat_t *diffstat)
3722 if (diff_unmodified_pair(p))
3723 return;
3725 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3726 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3727 return; /* no useful stat for tree diffs */
3729 run_diffstat(p, o, diffstat);
3732 static void diff_flush_checkdiff(struct diff_filepair *p,
3733 struct diff_options *o)
3735 if (diff_unmodified_pair(p))
3736 return;
3738 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3739 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3740 return; /* nothing to check in tree diffs */
3742 run_checkdiff(p, o);
3745 int diff_queue_is_empty(void)
3747 struct diff_queue_struct *q = &diff_queued_diff;
3748 int i;
3749 for (i = 0; i < q->nr; i++)
3750 if (!diff_unmodified_pair(q->queue[i]))
3751 return 0;
3752 return 1;
3755 #if DIFF_DEBUG
3756 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3758 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3759 x, one ? one : "",
3760 s->path,
3761 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3762 s->mode,
3763 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3764 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3765 x, one ? one : "",
3766 s->size, s->xfrm_flags);
3769 void diff_debug_filepair(const struct diff_filepair *p, int i)
3771 diff_debug_filespec(p->one, i, "one");
3772 diff_debug_filespec(p->two, i, "two");
3773 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3774 p->score, p->status ? p->status : '?',
3775 p->one->rename_used, p->broken_pair);
3778 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3780 int i;
3781 if (msg)
3782 fprintf(stderr, "%s\n", msg);
3783 fprintf(stderr, "q->nr = %d\n", q->nr);
3784 for (i = 0; i < q->nr; i++) {
3785 struct diff_filepair *p = q->queue[i];
3786 diff_debug_filepair(p, i);
3789 #endif
3791 static void diff_resolve_rename_copy(void)
3793 int i;
3794 struct diff_filepair *p;
3795 struct diff_queue_struct *q = &diff_queued_diff;
3797 diff_debug_queue("resolve-rename-copy", q);
3799 for (i = 0; i < q->nr; i++) {
3800 p = q->queue[i];
3801 p->status = 0; /* undecided */
3802 if (DIFF_PAIR_UNMERGED(p))
3803 p->status = DIFF_STATUS_UNMERGED;
3804 else if (!DIFF_FILE_VALID(p->one))
3805 p->status = DIFF_STATUS_ADDED;
3806 else if (!DIFF_FILE_VALID(p->two))
3807 p->status = DIFF_STATUS_DELETED;
3808 else if (DIFF_PAIR_TYPE_CHANGED(p))
3809 p->status = DIFF_STATUS_TYPE_CHANGED;
3811 /* from this point on, we are dealing with a pair
3812 * whose both sides are valid and of the same type, i.e.
3813 * either in-place edit or rename/copy edit.
3815 else if (DIFF_PAIR_RENAME(p)) {
3817 * A rename might have re-connected a broken
3818 * pair up, causing the pathnames to be the
3819 * same again. If so, that's not a rename at
3820 * all, just a modification..
3822 * Otherwise, see if this source was used for
3823 * multiple renames, in which case we decrement
3824 * the count, and call it a copy.
3826 if (!strcmp(p->one->path, p->two->path))
3827 p->status = DIFF_STATUS_MODIFIED;
3828 else if (--p->one->rename_used > 0)
3829 p->status = DIFF_STATUS_COPIED;
3830 else
3831 p->status = DIFF_STATUS_RENAMED;
3833 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3834 p->one->mode != p->two->mode ||
3835 p->one->dirty_submodule ||
3836 p->two->dirty_submodule ||
3837 is_null_sha1(p->one->sha1))
3838 p->status = DIFF_STATUS_MODIFIED;
3839 else {
3840 /* This is a "no-change" entry and should not
3841 * happen anymore, but prepare for broken callers.
3843 error("feeding unmodified %s to diffcore",
3844 p->one->path);
3845 p->status = DIFF_STATUS_UNKNOWN;
3848 diff_debug_queue("resolve-rename-copy done", q);
3851 static int check_pair_status(struct diff_filepair *p)
3853 switch (p->status) {
3854 case DIFF_STATUS_UNKNOWN:
3855 return 0;
3856 case 0:
3857 die("internal error in diff-resolve-rename-copy");
3858 default:
3859 return 1;
3863 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3865 int fmt = opt->output_format;
3867 if (fmt & DIFF_FORMAT_CHECKDIFF)
3868 diff_flush_checkdiff(p, opt);
3869 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3870 diff_flush_raw(p, opt);
3871 else if (fmt & DIFF_FORMAT_NAME) {
3872 const char *name_a, *name_b;
3873 name_a = p->two->path;
3874 name_b = NULL;
3875 strip_prefix(opt->prefix_length, &name_a, &name_b);
3876 write_name_quoted(name_a, opt->file, opt->line_termination);
3880 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3882 if (fs->mode)
3883 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3884 else
3885 fprintf(file, " %s ", newdelete);
3886 write_name_quoted(fs->path, file, '\n');
3890 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
3891 const char *line_prefix)
3893 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3894 fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
3895 p->two->mode, show_name ? ' ' : '\n');
3896 if (show_name) {
3897 write_name_quoted(p->two->path, file, '\n');
3902 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
3903 const char *line_prefix)
3905 char *names = pprint_rename(p->one->path, p->two->path);
3907 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3908 free(names);
3909 show_mode_change(file, p, 0, line_prefix);
3912 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
3914 FILE *file = opt->file;
3915 char *line_prefix = "";
3917 if (opt->output_prefix) {
3918 struct strbuf *buf = opt->output_prefix(opt, opt->output_prefix_data);
3919 line_prefix = buf->buf;
3922 switch(p->status) {
3923 case DIFF_STATUS_DELETED:
3924 fputs(line_prefix, file);
3925 show_file_mode_name(file, "delete", p->one);
3926 break;
3927 case DIFF_STATUS_ADDED:
3928 fputs(line_prefix, file);
3929 show_file_mode_name(file, "create", p->two);
3930 break;
3931 case DIFF_STATUS_COPIED:
3932 fputs(line_prefix, file);
3933 show_rename_copy(file, "copy", p, line_prefix);
3934 break;
3935 case DIFF_STATUS_RENAMED:
3936 fputs(line_prefix, file);
3937 show_rename_copy(file, "rename", p, line_prefix);
3938 break;
3939 default:
3940 if (p->score) {
3941 fprintf(file, "%s rewrite ", line_prefix);
3942 write_name_quoted(p->two->path, file, ' ');
3943 fprintf(file, "(%d%%)\n", similarity_index(p));
3945 show_mode_change(file, p, !p->score, line_prefix);
3946 break;
3950 struct patch_id_t {
3951 git_SHA_CTX *ctx;
3952 int patchlen;
3955 static int remove_space(char *line, int len)
3957 int i;
3958 char *dst = line;
3959 unsigned char c;
3961 for (i = 0; i < len; i++)
3962 if (!isspace((c = line[i])))
3963 *dst++ = c;
3965 return dst - line;
3968 static void patch_id_consume(void *priv, char *line, unsigned long len)
3970 struct patch_id_t *data = priv;
3971 int new_len;
3973 /* Ignore line numbers when computing the SHA1 of the patch */
3974 if (!prefixcmp(line, "@@ -"))
3975 return;
3977 new_len = remove_space(line, len);
3979 git_SHA1_Update(data->ctx, line, new_len);
3980 data->patchlen += new_len;
3983 /* returns 0 upon success, and writes result into sha1 */
3984 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3986 struct diff_queue_struct *q = &diff_queued_diff;
3987 int i;
3988 git_SHA_CTX ctx;
3989 struct patch_id_t data;
3990 char buffer[PATH_MAX * 4 + 20];
3992 git_SHA1_Init(&ctx);
3993 memset(&data, 0, sizeof(struct patch_id_t));
3994 data.ctx = &ctx;
3996 for (i = 0; i < q->nr; i++) {
3997 xpparam_t xpp;
3998 xdemitconf_t xecfg;
3999 mmfile_t mf1, mf2;
4000 struct diff_filepair *p = q->queue[i];
4001 int len1, len2;
4003 memset(&xpp, 0, sizeof(xpp));
4004 memset(&xecfg, 0, sizeof(xecfg));
4005 if (p->status == 0)
4006 return error("internal diff status error");
4007 if (p->status == DIFF_STATUS_UNKNOWN)
4008 continue;
4009 if (diff_unmodified_pair(p))
4010 continue;
4011 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4012 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4013 continue;
4014 if (DIFF_PAIR_UNMERGED(p))
4015 continue;
4017 diff_fill_sha1_info(p->one);
4018 diff_fill_sha1_info(p->two);
4019 if (fill_mmfile(&mf1, p->one) < 0 ||
4020 fill_mmfile(&mf2, p->two) < 0)
4021 return error("unable to read files to diff");
4023 len1 = remove_space(p->one->path, strlen(p->one->path));
4024 len2 = remove_space(p->two->path, strlen(p->two->path));
4025 if (p->one->mode == 0)
4026 len1 = snprintf(buffer, sizeof(buffer),
4027 "diff--gita/%.*sb/%.*s"
4028 "newfilemode%06o"
4029 "---/dev/null"
4030 "+++b/%.*s",
4031 len1, p->one->path,
4032 len2, p->two->path,
4033 p->two->mode,
4034 len2, p->two->path);
4035 else if (p->two->mode == 0)
4036 len1 = snprintf(buffer, sizeof(buffer),
4037 "diff--gita/%.*sb/%.*s"
4038 "deletedfilemode%06o"
4039 "---a/%.*s"
4040 "+++/dev/null",
4041 len1, p->one->path,
4042 len2, p->two->path,
4043 p->one->mode,
4044 len1, p->one->path);
4045 else
4046 len1 = snprintf(buffer, sizeof(buffer),
4047 "diff--gita/%.*sb/%.*s"
4048 "---a/%.*s"
4049 "+++b/%.*s",
4050 len1, p->one->path,
4051 len2, p->two->path,
4052 len1, p->one->path,
4053 len2, p->two->path);
4054 git_SHA1_Update(&ctx, buffer, len1);
4056 if (diff_filespec_is_binary(p->one) ||
4057 diff_filespec_is_binary(p->two)) {
4058 git_SHA1_Update(&ctx, sha1_to_hex(p->one->sha1), 40);
4059 git_SHA1_Update(&ctx, sha1_to_hex(p->two->sha1), 40);
4060 continue;
4063 xpp.flags = 0;
4064 xecfg.ctxlen = 3;
4065 xecfg.flags = 0;
4066 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
4067 &xpp, &xecfg);
4070 git_SHA1_Final(sha1, &ctx);
4071 return 0;
4074 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
4076 struct diff_queue_struct *q = &diff_queued_diff;
4077 int i;
4078 int result = diff_get_patch_id(options, sha1);
4080 for (i = 0; i < q->nr; i++)
4081 diff_free_filepair(q->queue[i]);
4083 free(q->queue);
4084 DIFF_QUEUE_CLEAR(q);
4086 return result;
4089 static int is_summary_empty(const struct diff_queue_struct *q)
4091 int i;
4093 for (i = 0; i < q->nr; i++) {
4094 const struct diff_filepair *p = q->queue[i];
4096 switch (p->status) {
4097 case DIFF_STATUS_DELETED:
4098 case DIFF_STATUS_ADDED:
4099 case DIFF_STATUS_COPIED:
4100 case DIFF_STATUS_RENAMED:
4101 return 0;
4102 default:
4103 if (p->score)
4104 return 0;
4105 if (p->one->mode && p->two->mode &&
4106 p->one->mode != p->two->mode)
4107 return 0;
4108 break;
4111 return 1;
4114 static const char rename_limit_warning[] =
4115 "inexact rename detection was skipped due to too many files.";
4117 static const char degrade_cc_to_c_warning[] =
4118 "only found copies from modified paths due to too many files.";
4120 static const char rename_limit_advice[] =
4121 "you may want to set your %s variable to at least "
4122 "%d and retry the command.";
4124 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4126 if (degraded_cc)
4127 warning(degrade_cc_to_c_warning);
4128 else if (needed)
4129 warning(rename_limit_warning);
4130 else
4131 return;
4132 if (0 < needed && needed < 32767)
4133 warning(rename_limit_advice, varname, needed);
4136 void diff_flush(struct diff_options *options)
4138 struct diff_queue_struct *q = &diff_queued_diff;
4139 int i, output_format = options->output_format;
4140 int separator = 0;
4141 int dirstat_by_line = 0;
4144 * Order: raw, stat, summary, patch
4145 * or: name/name-status/checkdiff (other bits clear)
4147 if (!q->nr)
4148 goto free_queue;
4150 if (output_format & (DIFF_FORMAT_RAW |
4151 DIFF_FORMAT_NAME |
4152 DIFF_FORMAT_NAME_STATUS |
4153 DIFF_FORMAT_CHECKDIFF)) {
4154 for (i = 0; i < q->nr; i++) {
4155 struct diff_filepair *p = q->queue[i];
4156 if (check_pair_status(p))
4157 flush_one_pair(p, options);
4159 separator++;
4162 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
4163 dirstat_by_line = 1;
4165 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
4166 dirstat_by_line) {
4167 struct diffstat_t diffstat;
4169 memset(&diffstat, 0, sizeof(struct diffstat_t));
4170 for (i = 0; i < q->nr; i++) {
4171 struct diff_filepair *p = q->queue[i];
4172 if (check_pair_status(p))
4173 diff_flush_stat(p, options, &diffstat);
4175 if (output_format & DIFF_FORMAT_NUMSTAT)
4176 show_numstat(&diffstat, options);
4177 if (output_format & DIFF_FORMAT_DIFFSTAT)
4178 show_stats(&diffstat, options);
4179 if (output_format & DIFF_FORMAT_SHORTSTAT)
4180 show_shortstats(&diffstat, options);
4181 if (output_format & DIFF_FORMAT_DIRSTAT)
4182 show_dirstat_by_line(&diffstat, options);
4183 free_diffstat_info(&diffstat);
4184 separator++;
4186 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
4187 show_dirstat(options);
4189 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
4190 for (i = 0; i < q->nr; i++) {
4191 diff_summary(options, q->queue[i]);
4193 separator++;
4196 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
4197 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
4198 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4200 * run diff_flush_patch for the exit status. setting
4201 * options->file to /dev/null should be safe, becaue we
4202 * aren't supposed to produce any output anyway.
4204 if (options->close_file)
4205 fclose(options->file);
4206 options->file = fopen("/dev/null", "w");
4207 if (!options->file)
4208 die_errno("Could not open /dev/null");
4209 options->close_file = 1;
4210 for (i = 0; i < q->nr; i++) {
4211 struct diff_filepair *p = q->queue[i];
4212 if (check_pair_status(p))
4213 diff_flush_patch(p, options);
4214 if (options->found_changes)
4215 break;
4219 if (output_format & DIFF_FORMAT_PATCH) {
4220 if (separator) {
4221 putc(options->line_termination, options->file);
4222 if (options->stat_sep) {
4223 /* attach patch instead of inline */
4224 fputs(options->stat_sep, options->file);
4228 for (i = 0; i < q->nr; i++) {
4229 struct diff_filepair *p = q->queue[i];
4230 if (check_pair_status(p))
4231 diff_flush_patch(p, options);
4235 if (output_format & DIFF_FORMAT_CALLBACK)
4236 options->format_callback(q, options, options->format_callback_data);
4238 for (i = 0; i < q->nr; i++)
4239 diff_free_filepair(q->queue[i]);
4240 free_queue:
4241 free(q->queue);
4242 DIFF_QUEUE_CLEAR(q);
4243 if (options->close_file)
4244 fclose(options->file);
4247 * Report the content-level differences with HAS_CHANGES;
4248 * diff_addremove/diff_change does not set the bit when
4249 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
4251 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4252 if (options->found_changes)
4253 DIFF_OPT_SET(options, HAS_CHANGES);
4254 else
4255 DIFF_OPT_CLR(options, HAS_CHANGES);
4259 static void diffcore_apply_filter(const char *filter)
4261 int i;
4262 struct diff_queue_struct *q = &diff_queued_diff;
4263 struct diff_queue_struct outq;
4264 DIFF_QUEUE_CLEAR(&outq);
4266 if (!filter)
4267 return;
4269 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
4270 int found;
4271 for (i = found = 0; !found && i < q->nr; i++) {
4272 struct diff_filepair *p = q->queue[i];
4273 if (((p->status == DIFF_STATUS_MODIFIED) &&
4274 ((p->score &&
4275 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4276 (!p->score &&
4277 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4278 ((p->status != DIFF_STATUS_MODIFIED) &&
4279 strchr(filter, p->status)))
4280 found++;
4282 if (found)
4283 return;
4285 /* otherwise we will clear the whole queue
4286 * by copying the empty outq at the end of this
4287 * function, but first clear the current entries
4288 * in the queue.
4290 for (i = 0; i < q->nr; i++)
4291 diff_free_filepair(q->queue[i]);
4293 else {
4294 /* Only the matching ones */
4295 for (i = 0; i < q->nr; i++) {
4296 struct diff_filepair *p = q->queue[i];
4298 if (((p->status == DIFF_STATUS_MODIFIED) &&
4299 ((p->score &&
4300 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4301 (!p->score &&
4302 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4303 ((p->status != DIFF_STATUS_MODIFIED) &&
4304 strchr(filter, p->status)))
4305 diff_q(&outq, p);
4306 else
4307 diff_free_filepair(p);
4310 free(q->queue);
4311 *q = outq;
4314 /* Check whether two filespecs with the same mode and size are identical */
4315 static int diff_filespec_is_identical(struct diff_filespec *one,
4316 struct diff_filespec *two)
4318 if (S_ISGITLINK(one->mode))
4319 return 0;
4320 if (diff_populate_filespec(one, 0))
4321 return 0;
4322 if (diff_populate_filespec(two, 0))
4323 return 0;
4324 return !memcmp(one->data, two->data, one->size);
4327 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
4329 int i;
4330 struct diff_queue_struct *q = &diff_queued_diff;
4331 struct diff_queue_struct outq;
4332 DIFF_QUEUE_CLEAR(&outq);
4334 for (i = 0; i < q->nr; i++) {
4335 struct diff_filepair *p = q->queue[i];
4338 * 1. Entries that come from stat info dirtiness
4339 * always have both sides (iow, not create/delete),
4340 * one side of the object name is unknown, with
4341 * the same mode and size. Keep the ones that
4342 * do not match these criteria. They have real
4343 * differences.
4345 * 2. At this point, the file is known to be modified,
4346 * with the same mode and size, and the object
4347 * name of one side is unknown. Need to inspect
4348 * the identical contents.
4350 if (!DIFF_FILE_VALID(p->one) || /* (1) */
4351 !DIFF_FILE_VALID(p->two) ||
4352 (p->one->sha1_valid && p->two->sha1_valid) ||
4353 (p->one->mode != p->two->mode) ||
4354 diff_populate_filespec(p->one, 1) ||
4355 diff_populate_filespec(p->two, 1) ||
4356 (p->one->size != p->two->size) ||
4357 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
4358 diff_q(&outq, p);
4359 else {
4361 * The caller can subtract 1 from skip_stat_unmatch
4362 * to determine how many paths were dirty only
4363 * due to stat info mismatch.
4365 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
4366 diffopt->skip_stat_unmatch++;
4367 diff_free_filepair(p);
4370 free(q->queue);
4371 *q = outq;
4374 static int diffnamecmp(const void *a_, const void *b_)
4376 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4377 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4378 const char *name_a, *name_b;
4380 name_a = a->one ? a->one->path : a->two->path;
4381 name_b = b->one ? b->one->path : b->two->path;
4382 return strcmp(name_a, name_b);
4385 void diffcore_fix_diff_index(struct diff_options *options)
4387 struct diff_queue_struct *q = &diff_queued_diff;
4388 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
4391 void diffcore_std(struct diff_options *options)
4393 if (options->skip_stat_unmatch)
4394 diffcore_skip_stat_unmatch(options);
4395 if (!options->found_follow) {
4396 /* See try_to_follow_renames() in tree-diff.c */
4397 if (options->break_opt != -1)
4398 diffcore_break(options->break_opt);
4399 if (options->detect_rename)
4400 diffcore_rename(options);
4401 if (options->break_opt != -1)
4402 diffcore_merge_broken();
4404 if (options->pickaxe)
4405 diffcore_pickaxe(options);
4406 if (options->orderfile)
4407 diffcore_order(options->orderfile);
4408 if (!options->found_follow)
4409 /* See try_to_follow_renames() in tree-diff.c */
4410 diff_resolve_rename_copy();
4411 diffcore_apply_filter(options->filter);
4413 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4414 DIFF_OPT_SET(options, HAS_CHANGES);
4415 else
4416 DIFF_OPT_CLR(options, HAS_CHANGES);
4418 options->found_follow = 0;
4421 int diff_result_code(struct diff_options *opt, int status)
4423 int result = 0;
4425 diff_warn_rename_limit("diff.renamelimit",
4426 opt->needed_rename_limit,
4427 opt->degraded_cc_to_c);
4428 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4429 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
4430 return status;
4431 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4432 DIFF_OPT_TST(opt, HAS_CHANGES))
4433 result |= 01;
4434 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4435 DIFF_OPT_TST(opt, CHECK_FAILED))
4436 result |= 02;
4437 return result;
4441 * Shall changes to this submodule be ignored?
4443 * Submodule changes can be configured to be ignored separately for each path,
4444 * but that configuration can be overridden from the command line.
4446 static int is_submodule_ignored(const char *path, struct diff_options *options)
4448 int ignored = 0;
4449 unsigned orig_flags = options->flags;
4450 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
4451 set_diffopt_flags_from_submodule_config(options, path);
4452 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
4453 ignored = 1;
4454 options->flags = orig_flags;
4455 return ignored;
4458 void diff_addremove(struct diff_options *options,
4459 int addremove, unsigned mode,
4460 const unsigned char *sha1,
4461 const char *concatpath, unsigned dirty_submodule)
4463 struct diff_filespec *one, *two;
4465 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
4466 return;
4468 /* This may look odd, but it is a preparation for
4469 * feeding "there are unchanged files which should
4470 * not produce diffs, but when you are doing copy
4471 * detection you would need them, so here they are"
4472 * entries to the diff-core. They will be prefixed
4473 * with something like '=' or '*' (I haven't decided
4474 * which but should not make any difference).
4475 * Feeding the same new and old to diff_change()
4476 * also has the same effect.
4477 * Before the final output happens, they are pruned after
4478 * merged into rename/copy pairs as appropriate.
4480 if (DIFF_OPT_TST(options, REVERSE_DIFF))
4481 addremove = (addremove == '+' ? '-' :
4482 addremove == '-' ? '+' : addremove);
4484 if (options->prefix &&
4485 strncmp(concatpath, options->prefix, options->prefix_length))
4486 return;
4488 one = alloc_filespec(concatpath);
4489 two = alloc_filespec(concatpath);
4491 if (addremove != '+')
4492 fill_filespec(one, sha1, mode);
4493 if (addremove != '-') {
4494 fill_filespec(two, sha1, mode);
4495 two->dirty_submodule = dirty_submodule;
4498 diff_queue(&diff_queued_diff, one, two);
4499 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4500 DIFF_OPT_SET(options, HAS_CHANGES);
4503 void diff_change(struct diff_options *options,
4504 unsigned old_mode, unsigned new_mode,
4505 const unsigned char *old_sha1,
4506 const unsigned char *new_sha1,
4507 const char *concatpath,
4508 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
4510 struct diff_filespec *one, *two;
4512 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
4513 is_submodule_ignored(concatpath, options))
4514 return;
4516 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
4517 unsigned tmp;
4518 const unsigned char *tmp_c;
4519 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
4520 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
4521 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
4522 new_dirty_submodule = tmp;
4525 if (options->prefix &&
4526 strncmp(concatpath, options->prefix, options->prefix_length))
4527 return;
4529 one = alloc_filespec(concatpath);
4530 two = alloc_filespec(concatpath);
4531 fill_filespec(one, old_sha1, old_mode);
4532 fill_filespec(two, new_sha1, new_mode);
4533 one->dirty_submodule = old_dirty_submodule;
4534 two->dirty_submodule = new_dirty_submodule;
4536 diff_queue(&diff_queued_diff, one, two);
4537 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4538 DIFF_OPT_SET(options, HAS_CHANGES);
4541 void diff_unmerge(struct diff_options *options,
4542 const char *path,
4543 unsigned mode, const unsigned char *sha1)
4545 struct diff_filespec *one, *two;
4547 if (options->prefix &&
4548 strncmp(path, options->prefix, options->prefix_length))
4549 return;
4551 one = alloc_filespec(path);
4552 two = alloc_filespec(path);
4553 fill_filespec(one, sha1, mode);
4554 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
4557 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
4558 size_t *outsize)
4560 struct diff_tempfile *temp;
4561 const char *argv[3];
4562 const char **arg = argv;
4563 struct child_process child;
4564 struct strbuf buf = STRBUF_INIT;
4565 int err = 0;
4567 temp = prepare_temp_file(spec->path, spec);
4568 *arg++ = pgm;
4569 *arg++ = temp->name;
4570 *arg = NULL;
4572 memset(&child, 0, sizeof(child));
4573 child.use_shell = 1;
4574 child.argv = argv;
4575 child.out = -1;
4576 if (start_command(&child)) {
4577 remove_tempfile();
4578 return NULL;
4581 if (strbuf_read(&buf, child.out, 0) < 0)
4582 err = error("error reading from textconv command '%s'", pgm);
4583 close(child.out);
4585 if (finish_command(&child) || err) {
4586 strbuf_release(&buf);
4587 remove_tempfile();
4588 return NULL;
4590 remove_tempfile();
4592 return strbuf_detach(&buf, outsize);
4595 size_t fill_textconv(struct userdiff_driver *driver,
4596 struct diff_filespec *df,
4597 char **outbuf)
4599 size_t size;
4601 if (!driver || !driver->textconv) {
4602 if (!DIFF_FILE_VALID(df)) {
4603 *outbuf = "";
4604 return 0;
4606 if (diff_populate_filespec(df, 0))
4607 die("unable to read files to diff");
4608 *outbuf = df->data;
4609 return df->size;
4612 if (driver->textconv_cache && df->sha1_valid) {
4613 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4614 &size);
4615 if (*outbuf)
4616 return size;
4619 *outbuf = run_textconv(driver->textconv, df, &size);
4620 if (!*outbuf)
4621 die("unable to read files to diff");
4623 if (driver->textconv_cache && df->sha1_valid) {
4624 /* ignore errors, as we might be in a readonly repository */
4625 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4626 size);
4628 * we could save up changes and flush them all at the end,
4629 * but we would need an extra call after all diffing is done.
4630 * Since generating a cache entry is the slow path anyway,
4631 * this extra overhead probably isn't a big deal.
4633 notes_cache_write(driver->textconv_cache);
4636 return size;