git-merge(1): document diff-algorithm option to merge-recursive
[alt-git.git] / diff.c
blob0724fa6ff6c4312733e520d59f88ea12740d408d
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"
18 #include "string-list.h"
20 #ifdef NO_FAST_WORKING_DIRECTORY
21 #define FAST_WORKING_DIRECTORY 0
22 #else
23 #define FAST_WORKING_DIRECTORY 1
24 #endif
26 static int diff_detect_rename_default;
27 static int diff_rename_limit_default = 400;
28 static int diff_suppress_blank_empty;
29 static int diff_use_color_default = -1;
30 static int diff_context_default = 3;
31 static const char *diff_word_regex_cfg;
32 static const char *external_diff_cmd_cfg;
33 int diff_auto_refresh_index = 1;
34 static int diff_mnemonic_prefix;
35 static int diff_no_prefix;
36 static int diff_stat_graph_width;
37 static int diff_dirstat_permille_default = 30;
38 static struct diff_options default_diff_options;
39 static long diff_algorithm;
41 static char diff_colors[][COLOR_MAXLEN] = {
42 GIT_COLOR_RESET,
43 GIT_COLOR_NORMAL, /* PLAIN */
44 GIT_COLOR_BOLD, /* METAINFO */
45 GIT_COLOR_CYAN, /* FRAGINFO */
46 GIT_COLOR_RED, /* OLD */
47 GIT_COLOR_GREEN, /* NEW */
48 GIT_COLOR_YELLOW, /* COMMIT */
49 GIT_COLOR_BG_RED, /* WHITESPACE */
50 GIT_COLOR_NORMAL, /* FUNCINFO */
53 static int parse_diff_color_slot(const char *var, int ofs)
55 if (!strcasecmp(var+ofs, "plain"))
56 return DIFF_PLAIN;
57 if (!strcasecmp(var+ofs, "meta"))
58 return DIFF_METAINFO;
59 if (!strcasecmp(var+ofs, "frag"))
60 return DIFF_FRAGINFO;
61 if (!strcasecmp(var+ofs, "old"))
62 return DIFF_FILE_OLD;
63 if (!strcasecmp(var+ofs, "new"))
64 return DIFF_FILE_NEW;
65 if (!strcasecmp(var+ofs, "commit"))
66 return DIFF_COMMIT;
67 if (!strcasecmp(var+ofs, "whitespace"))
68 return DIFF_WHITESPACE;
69 if (!strcasecmp(var+ofs, "func"))
70 return DIFF_FUNCINFO;
71 return -1;
74 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
75 struct strbuf *errmsg)
77 char *params_copy = xstrdup(params_string);
78 struct string_list params = STRING_LIST_INIT_NODUP;
79 int ret = 0;
80 int i;
82 if (*params_copy)
83 string_list_split_in_place(&params, params_copy, ',', -1);
84 for (i = 0; i < params.nr; i++) {
85 const char *p = params.items[i].string;
86 if (!strcmp(p, "changes")) {
87 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
88 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
89 } else if (!strcmp(p, "lines")) {
90 DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
91 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
92 } else if (!strcmp(p, "files")) {
93 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
94 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
95 } else if (!strcmp(p, "noncumulative")) {
96 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
97 } else if (!strcmp(p, "cumulative")) {
98 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
99 } else if (isdigit(*p)) {
100 char *end;
101 int permille = strtoul(p, &end, 10) * 10;
102 if (*end == '.' && isdigit(*++end)) {
103 /* only use first digit */
104 permille += *end - '0';
105 /* .. and ignore any further digits */
106 while (isdigit(*++end))
107 ; /* nothing */
109 if (!*end)
110 options->dirstat_permille = permille;
111 else {
112 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
114 ret++;
116 } else {
117 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
118 ret++;
122 string_list_clear(&params, 0);
123 free(params_copy);
124 return ret;
127 static int parse_submodule_params(struct diff_options *options, const char *value)
129 if (!strcmp(value, "log"))
130 DIFF_OPT_SET(options, SUBMODULE_LOG);
131 else if (!strcmp(value, "short"))
132 DIFF_OPT_CLR(options, SUBMODULE_LOG);
133 else
134 return -1;
135 return 0;
138 static int git_config_rename(const char *var, const char *value)
140 if (!value)
141 return DIFF_DETECT_RENAME;
142 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
143 return DIFF_DETECT_COPY;
144 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
147 long parse_algorithm_value(const char *value)
149 if (!value)
150 return -1;
151 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
152 return 0;
153 else if (!strcasecmp(value, "minimal"))
154 return XDF_NEED_MINIMAL;
155 else if (!strcasecmp(value, "patience"))
156 return XDF_PATIENCE_DIFF;
157 else if (!strcasecmp(value, "histogram"))
158 return XDF_HISTOGRAM_DIFF;
159 return -1;
163 * These are to give UI layer defaults.
164 * The core-level commands such as git-diff-files should
165 * never be affected by the setting of diff.renames
166 * the user happens to have in the configuration file.
168 int git_diff_ui_config(const char *var, const char *value, void *cb)
170 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
171 diff_use_color_default = git_config_colorbool(var, value);
172 return 0;
174 if (!strcmp(var, "diff.context")) {
175 diff_context_default = git_config_int(var, value);
176 if (diff_context_default < 0)
177 return -1;
178 return 0;
180 if (!strcmp(var, "diff.renames")) {
181 diff_detect_rename_default = git_config_rename(var, value);
182 return 0;
184 if (!strcmp(var, "diff.autorefreshindex")) {
185 diff_auto_refresh_index = git_config_bool(var, value);
186 return 0;
188 if (!strcmp(var, "diff.mnemonicprefix")) {
189 diff_mnemonic_prefix = git_config_bool(var, value);
190 return 0;
192 if (!strcmp(var, "diff.noprefix")) {
193 diff_no_prefix = git_config_bool(var, value);
194 return 0;
196 if (!strcmp(var, "diff.statgraphwidth")) {
197 diff_stat_graph_width = git_config_int(var, value);
198 return 0;
200 if (!strcmp(var, "diff.external"))
201 return git_config_string(&external_diff_cmd_cfg, var, value);
202 if (!strcmp(var, "diff.wordregex"))
203 return git_config_string(&diff_word_regex_cfg, var, value);
205 if (!strcmp(var, "diff.ignoresubmodules"))
206 handle_ignore_submodules_arg(&default_diff_options, value);
208 if (!strcmp(var, "diff.submodule")) {
209 if (parse_submodule_params(&default_diff_options, value))
210 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
211 value);
212 return 0;
215 if (!strcmp(var, "diff.algorithm")) {
216 diff_algorithm = parse_algorithm_value(value);
217 if (diff_algorithm < 0)
218 return -1;
219 return 0;
222 if (git_color_config(var, value, cb) < 0)
223 return -1;
225 return git_diff_basic_config(var, value, cb);
228 int git_diff_basic_config(const char *var, const char *value, void *cb)
230 if (!strcmp(var, "diff.renamelimit")) {
231 diff_rename_limit_default = git_config_int(var, value);
232 return 0;
235 if (userdiff_config(var, value) < 0)
236 return -1;
238 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
239 int slot = parse_diff_color_slot(var, 11);
240 if (slot < 0)
241 return 0;
242 if (!value)
243 return config_error_nonbool(var);
244 color_parse(value, var, diff_colors[slot]);
245 return 0;
248 /* like GNU diff's --suppress-blank-empty option */
249 if (!strcmp(var, "diff.suppressblankempty") ||
250 /* for backwards compatibility */
251 !strcmp(var, "diff.suppress-blank-empty")) {
252 diff_suppress_blank_empty = git_config_bool(var, value);
253 return 0;
256 if (!strcmp(var, "diff.dirstat")) {
257 struct strbuf errmsg = STRBUF_INIT;
258 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
259 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
260 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
261 errmsg.buf);
262 strbuf_release(&errmsg);
263 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
264 return 0;
267 if (!prefixcmp(var, "submodule."))
268 return parse_submodule_config_option(var, value);
270 return git_default_config(var, value, cb);
273 static char *quote_two(const char *one, const char *two)
275 int need_one = quote_c_style(one, NULL, NULL, 1);
276 int need_two = quote_c_style(two, NULL, NULL, 1);
277 struct strbuf res = STRBUF_INIT;
279 if (need_one + need_two) {
280 strbuf_addch(&res, '"');
281 quote_c_style(one, &res, NULL, 1);
282 quote_c_style(two, &res, NULL, 1);
283 strbuf_addch(&res, '"');
284 } else {
285 strbuf_addstr(&res, one);
286 strbuf_addstr(&res, two);
288 return strbuf_detach(&res, NULL);
291 static const char *external_diff(void)
293 static const char *external_diff_cmd = NULL;
294 static int done_preparing = 0;
296 if (done_preparing)
297 return external_diff_cmd;
298 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
299 if (!external_diff_cmd)
300 external_diff_cmd = external_diff_cmd_cfg;
301 done_preparing = 1;
302 return external_diff_cmd;
305 static struct diff_tempfile {
306 const char *name; /* filename external diff should read from */
307 char hex[41];
308 char mode[10];
309 char tmp_path[PATH_MAX];
310 } diff_temp[2];
312 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
314 struct emit_callback {
315 int color_diff;
316 unsigned ws_rule;
317 int blank_at_eof_in_preimage;
318 int blank_at_eof_in_postimage;
319 int lno_in_preimage;
320 int lno_in_postimage;
321 sane_truncate_fn truncate;
322 const char **label_path;
323 struct diff_words_data *diff_words;
324 struct diff_options *opt;
325 int *found_changesp;
326 struct strbuf *header;
329 static int count_lines(const char *data, int size)
331 int count, ch, completely_empty = 1, nl_just_seen = 0;
332 count = 0;
333 while (0 < size--) {
334 ch = *data++;
335 if (ch == '\n') {
336 count++;
337 nl_just_seen = 1;
338 completely_empty = 0;
340 else {
341 nl_just_seen = 0;
342 completely_empty = 0;
345 if (completely_empty)
346 return 0;
347 if (!nl_just_seen)
348 count++; /* no trailing newline */
349 return count;
352 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
354 if (!DIFF_FILE_VALID(one)) {
355 mf->ptr = (char *)""; /* does not matter */
356 mf->size = 0;
357 return 0;
359 else if (diff_populate_filespec(one, 0))
360 return -1;
362 mf->ptr = one->data;
363 mf->size = one->size;
364 return 0;
367 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
368 static unsigned long diff_filespec_size(struct diff_filespec *one)
370 if (!DIFF_FILE_VALID(one))
371 return 0;
372 diff_populate_filespec(one, 1);
373 return one->size;
376 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
378 char *ptr = mf->ptr;
379 long size = mf->size;
380 int cnt = 0;
382 if (!size)
383 return cnt;
384 ptr += size - 1; /* pointing at the very end */
385 if (*ptr != '\n')
386 ; /* incomplete line */
387 else
388 ptr--; /* skip the last LF */
389 while (mf->ptr < ptr) {
390 char *prev_eol;
391 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
392 if (*prev_eol == '\n')
393 break;
394 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
395 break;
396 cnt++;
397 ptr = prev_eol - 1;
399 return cnt;
402 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
403 struct emit_callback *ecbdata)
405 int l1, l2, at;
406 unsigned ws_rule = ecbdata->ws_rule;
407 l1 = count_trailing_blank(mf1, ws_rule);
408 l2 = count_trailing_blank(mf2, ws_rule);
409 if (l2 <= l1) {
410 ecbdata->blank_at_eof_in_preimage = 0;
411 ecbdata->blank_at_eof_in_postimage = 0;
412 return;
414 at = count_lines(mf1->ptr, mf1->size);
415 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
417 at = count_lines(mf2->ptr, mf2->size);
418 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
421 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
422 int first, const char *line, int len)
424 int has_trailing_newline, has_trailing_carriage_return;
425 int nofirst;
426 FILE *file = o->file;
428 if (o->output_prefix) {
429 struct strbuf *msg = NULL;
430 msg = o->output_prefix(o, o->output_prefix_data);
431 assert(msg);
432 fwrite(msg->buf, msg->len, 1, file);
435 if (len == 0) {
436 has_trailing_newline = (first == '\n');
437 has_trailing_carriage_return = (!has_trailing_newline &&
438 (first == '\r'));
439 nofirst = has_trailing_newline || has_trailing_carriage_return;
440 } else {
441 has_trailing_newline = (len > 0 && line[len-1] == '\n');
442 if (has_trailing_newline)
443 len--;
444 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
445 if (has_trailing_carriage_return)
446 len--;
447 nofirst = 0;
450 if (len || !nofirst) {
451 fputs(set, file);
452 if (!nofirst)
453 fputc(first, file);
454 fwrite(line, len, 1, file);
455 fputs(reset, file);
457 if (has_trailing_carriage_return)
458 fputc('\r', file);
459 if (has_trailing_newline)
460 fputc('\n', file);
463 static void emit_line(struct diff_options *o, const char *set, const char *reset,
464 const char *line, int len)
466 emit_line_0(o, set, reset, line[0], line+1, len-1);
469 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
471 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
472 ecbdata->blank_at_eof_in_preimage &&
473 ecbdata->blank_at_eof_in_postimage &&
474 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
475 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
476 return 0;
477 return ws_blank_line(line, len, ecbdata->ws_rule);
480 static void emit_add_line(const char *reset,
481 struct emit_callback *ecbdata,
482 const char *line, int len)
484 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
485 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
487 if (!*ws)
488 emit_line_0(ecbdata->opt, set, reset, '+', line, len);
489 else if (new_blank_line_at_eof(ecbdata, line, len))
490 /* Blank line at EOF - paint '+' as well */
491 emit_line_0(ecbdata->opt, ws, reset, '+', line, len);
492 else {
493 /* Emit just the prefix, then the rest. */
494 emit_line_0(ecbdata->opt, set, reset, '+', "", 0);
495 ws_check_emit(line, len, ecbdata->ws_rule,
496 ecbdata->opt->file, set, reset, ws);
500 static void emit_hunk_header(struct emit_callback *ecbdata,
501 const char *line, int len)
503 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
504 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
505 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
506 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
507 static const char atat[2] = { '@', '@' };
508 const char *cp, *ep;
509 struct strbuf msgbuf = STRBUF_INIT;
510 int org_len = len;
511 int i = 1;
514 * As a hunk header must begin with "@@ -<old>, +<new> @@",
515 * it always is at least 10 bytes long.
517 if (len < 10 ||
518 memcmp(line, atat, 2) ||
519 !(ep = memmem(line + 2, len - 2, atat, 2))) {
520 emit_line(ecbdata->opt, plain, reset, line, len);
521 return;
523 ep += 2; /* skip over @@ */
525 /* The hunk header in fraginfo color */
526 strbuf_add(&msgbuf, frag, strlen(frag));
527 strbuf_add(&msgbuf, line, ep - line);
528 strbuf_add(&msgbuf, reset, strlen(reset));
531 * trailing "\r\n"
533 for ( ; i < 3; i++)
534 if (line[len - i] == '\r' || line[len - i] == '\n')
535 len--;
537 /* blank before the func header */
538 for (cp = ep; ep - line < len; ep++)
539 if (*ep != ' ' && *ep != '\t')
540 break;
541 if (ep != cp) {
542 strbuf_add(&msgbuf, plain, strlen(plain));
543 strbuf_add(&msgbuf, cp, ep - cp);
544 strbuf_add(&msgbuf, reset, strlen(reset));
547 if (ep < line + len) {
548 strbuf_add(&msgbuf, func, strlen(func));
549 strbuf_add(&msgbuf, ep, line + len - ep);
550 strbuf_add(&msgbuf, reset, strlen(reset));
553 strbuf_add(&msgbuf, line + len, org_len - len);
554 emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
555 strbuf_release(&msgbuf);
558 static struct diff_tempfile *claim_diff_tempfile(void) {
559 int i;
560 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
561 if (!diff_temp[i].name)
562 return diff_temp + i;
563 die("BUG: diff is failing to clean up its tempfiles");
566 static int remove_tempfile_installed;
568 static void remove_tempfile(void)
570 int i;
571 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
572 if (diff_temp[i].name == diff_temp[i].tmp_path)
573 unlink_or_warn(diff_temp[i].name);
574 diff_temp[i].name = NULL;
578 static void remove_tempfile_on_signal(int signo)
580 remove_tempfile();
581 sigchain_pop(signo);
582 raise(signo);
585 static void print_line_count(FILE *file, int count)
587 switch (count) {
588 case 0:
589 fprintf(file, "0,0");
590 break;
591 case 1:
592 fprintf(file, "1");
593 break;
594 default:
595 fprintf(file, "1,%d", count);
596 break;
600 static void emit_rewrite_lines(struct emit_callback *ecb,
601 int prefix, const char *data, int size)
603 const char *endp = NULL;
604 static const char *nneof = " No newline at end of file\n";
605 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
606 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
608 while (0 < size) {
609 int len;
611 endp = memchr(data, '\n', size);
612 len = endp ? (endp - data + 1) : size;
613 if (prefix != '+') {
614 ecb->lno_in_preimage++;
615 emit_line_0(ecb->opt, old, reset, '-',
616 data, len);
617 } else {
618 ecb->lno_in_postimage++;
619 emit_add_line(reset, ecb, data, len);
621 size -= len;
622 data += len;
624 if (!endp) {
625 const char *plain = diff_get_color(ecb->color_diff,
626 DIFF_PLAIN);
627 putc('\n', ecb->opt->file);
628 emit_line_0(ecb->opt, plain, reset, '\\',
629 nneof, strlen(nneof));
633 static void emit_rewrite_diff(const char *name_a,
634 const char *name_b,
635 struct diff_filespec *one,
636 struct diff_filespec *two,
637 struct userdiff_driver *textconv_one,
638 struct userdiff_driver *textconv_two,
639 struct diff_options *o)
641 int lc_a, lc_b;
642 const char *name_a_tab, *name_b_tab;
643 const char *metainfo = diff_get_color(o->use_color, DIFF_METAINFO);
644 const char *fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
645 const char *reset = diff_get_color(o->use_color, DIFF_RESET);
646 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
647 const char *a_prefix, *b_prefix;
648 char *data_one, *data_two;
649 size_t size_one, size_two;
650 struct emit_callback ecbdata;
651 char *line_prefix = "";
652 struct strbuf *msgbuf;
654 if (o && o->output_prefix) {
655 msgbuf = o->output_prefix(o, o->output_prefix_data);
656 line_prefix = msgbuf->buf;
659 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
660 a_prefix = o->b_prefix;
661 b_prefix = o->a_prefix;
662 } else {
663 a_prefix = o->a_prefix;
664 b_prefix = o->b_prefix;
667 name_a += (*name_a == '/');
668 name_b += (*name_b == '/');
669 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
670 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
672 strbuf_reset(&a_name);
673 strbuf_reset(&b_name);
674 quote_two_c_style(&a_name, a_prefix, name_a, 0);
675 quote_two_c_style(&b_name, b_prefix, name_b, 0);
677 size_one = fill_textconv(textconv_one, one, &data_one);
678 size_two = fill_textconv(textconv_two, two, &data_two);
680 memset(&ecbdata, 0, sizeof(ecbdata));
681 ecbdata.color_diff = want_color(o->use_color);
682 ecbdata.found_changesp = &o->found_changes;
683 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
684 ecbdata.opt = o;
685 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
686 mmfile_t mf1, mf2;
687 mf1.ptr = (char *)data_one;
688 mf2.ptr = (char *)data_two;
689 mf1.size = size_one;
690 mf2.size = size_two;
691 check_blank_at_eof(&mf1, &mf2, &ecbdata);
693 ecbdata.lno_in_preimage = 1;
694 ecbdata.lno_in_postimage = 1;
696 lc_a = count_lines(data_one, size_one);
697 lc_b = count_lines(data_two, size_two);
698 fprintf(o->file,
699 "%s%s--- %s%s%s\n%s%s+++ %s%s%s\n%s%s@@ -",
700 line_prefix, metainfo, a_name.buf, name_a_tab, reset,
701 line_prefix, metainfo, b_name.buf, name_b_tab, reset,
702 line_prefix, fraginfo);
703 if (!o->irreversible_delete)
704 print_line_count(o->file, lc_a);
705 else
706 fprintf(o->file, "?,?");
707 fprintf(o->file, " +");
708 print_line_count(o->file, lc_b);
709 fprintf(o->file, " @@%s\n", reset);
710 if (lc_a && !o->irreversible_delete)
711 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
712 if (lc_b)
713 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
714 if (textconv_one)
715 free((char *)data_one);
716 if (textconv_two)
717 free((char *)data_two);
720 struct diff_words_buffer {
721 mmfile_t text;
722 long alloc;
723 struct diff_words_orig {
724 const char *begin, *end;
725 } *orig;
726 int orig_nr, orig_alloc;
729 static void diff_words_append(char *line, unsigned long len,
730 struct diff_words_buffer *buffer)
732 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
733 line++;
734 len--;
735 memcpy(buffer->text.ptr + buffer->text.size, line, len);
736 buffer->text.size += len;
737 buffer->text.ptr[buffer->text.size] = '\0';
740 struct diff_words_style_elem {
741 const char *prefix;
742 const char *suffix;
743 const char *color; /* NULL; filled in by the setup code if
744 * color is enabled */
747 struct diff_words_style {
748 enum diff_words_type type;
749 struct diff_words_style_elem new, old, ctx;
750 const char *newline;
753 static struct diff_words_style diff_words_styles[] = {
754 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
755 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
756 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
759 struct diff_words_data {
760 struct diff_words_buffer minus, plus;
761 const char *current_plus;
762 int last_minus;
763 struct diff_options *opt;
764 regex_t *word_regex;
765 enum diff_words_type type;
766 struct diff_words_style *style;
769 static int fn_out_diff_words_write_helper(FILE *fp,
770 struct diff_words_style_elem *st_el,
771 const char *newline,
772 size_t count, const char *buf,
773 const char *line_prefix)
775 int print = 0;
777 while (count) {
778 char *p = memchr(buf, '\n', count);
779 if (print)
780 fputs(line_prefix, fp);
781 if (p != buf) {
782 if (st_el->color && fputs(st_el->color, fp) < 0)
783 return -1;
784 if (fputs(st_el->prefix, fp) < 0 ||
785 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
786 fputs(st_el->suffix, fp) < 0)
787 return -1;
788 if (st_el->color && *st_el->color
789 && fputs(GIT_COLOR_RESET, fp) < 0)
790 return -1;
792 if (!p)
793 return 0;
794 if (fputs(newline, fp) < 0)
795 return -1;
796 count -= p + 1 - buf;
797 buf = p + 1;
798 print = 1;
800 return 0;
804 * '--color-words' algorithm can be described as:
806 * 1. collect a the minus/plus lines of a diff hunk, divided into
807 * minus-lines and plus-lines;
809 * 2. break both minus-lines and plus-lines into words and
810 * place them into two mmfile_t with one word for each line;
812 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
814 * And for the common parts of the both file, we output the plus side text.
815 * diff_words->current_plus is used to trace the current position of the plus file
816 * which printed. diff_words->last_minus is used to trace the last minus word
817 * printed.
819 * For '--graph' to work with '--color-words', we need to output the graph prefix
820 * on each line of color words output. Generally, there are two conditions on
821 * which we should output the prefix.
823 * 1. diff_words->last_minus == 0 &&
824 * diff_words->current_plus == diff_words->plus.text.ptr
826 * that is: the plus text must start as a new line, and if there is no minus
827 * word printed, a graph prefix must be printed.
829 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
830 * *(diff_words->current_plus - 1) == '\n'
832 * that is: a graph prefix must be printed following a '\n'
834 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
836 if ((diff_words->last_minus == 0 &&
837 diff_words->current_plus == diff_words->plus.text.ptr) ||
838 (diff_words->current_plus > diff_words->plus.text.ptr &&
839 *(diff_words->current_plus - 1) == '\n')) {
840 return 1;
841 } else {
842 return 0;
846 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
848 struct diff_words_data *diff_words = priv;
849 struct diff_words_style *style = diff_words->style;
850 int minus_first, minus_len, plus_first, plus_len;
851 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
852 struct diff_options *opt = diff_words->opt;
853 struct strbuf *msgbuf;
854 char *line_prefix = "";
856 if (line[0] != '@' || parse_hunk_header(line, len,
857 &minus_first, &minus_len, &plus_first, &plus_len))
858 return;
860 assert(opt);
861 if (opt->output_prefix) {
862 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
863 line_prefix = msgbuf->buf;
866 /* POSIX requires that first be decremented by one if len == 0... */
867 if (minus_len) {
868 minus_begin = diff_words->minus.orig[minus_first].begin;
869 minus_end =
870 diff_words->minus.orig[minus_first + minus_len - 1].end;
871 } else
872 minus_begin = minus_end =
873 diff_words->minus.orig[minus_first].end;
875 if (plus_len) {
876 plus_begin = diff_words->plus.orig[plus_first].begin;
877 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
878 } else
879 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
881 if (color_words_output_graph_prefix(diff_words)) {
882 fputs(line_prefix, diff_words->opt->file);
884 if (diff_words->current_plus != plus_begin) {
885 fn_out_diff_words_write_helper(diff_words->opt->file,
886 &style->ctx, style->newline,
887 plus_begin - diff_words->current_plus,
888 diff_words->current_plus, line_prefix);
889 if (*(plus_begin - 1) == '\n')
890 fputs(line_prefix, diff_words->opt->file);
892 if (minus_begin != minus_end) {
893 fn_out_diff_words_write_helper(diff_words->opt->file,
894 &style->old, style->newline,
895 minus_end - minus_begin, minus_begin,
896 line_prefix);
898 if (plus_begin != plus_end) {
899 fn_out_diff_words_write_helper(diff_words->opt->file,
900 &style->new, style->newline,
901 plus_end - plus_begin, plus_begin,
902 line_prefix);
905 diff_words->current_plus = plus_end;
906 diff_words->last_minus = minus_first;
909 /* This function starts looking at *begin, and returns 0 iff a word was found. */
910 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
911 int *begin, int *end)
913 if (word_regex && *begin < buffer->size) {
914 regmatch_t match[1];
915 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
916 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
917 '\n', match[0].rm_eo - match[0].rm_so);
918 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
919 *begin += match[0].rm_so;
920 return *begin >= *end;
922 return -1;
925 /* find the next word */
926 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
927 (*begin)++;
928 if (*begin >= buffer->size)
929 return -1;
931 /* find the end of the word */
932 *end = *begin + 1;
933 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
934 (*end)++;
936 return 0;
940 * This function splits the words in buffer->text, stores the list with
941 * newline separator into out, and saves the offsets of the original words
942 * in buffer->orig.
944 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
945 regex_t *word_regex)
947 int i, j;
948 long alloc = 0;
950 out->size = 0;
951 out->ptr = NULL;
953 /* fake an empty "0th" word */
954 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
955 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
956 buffer->orig_nr = 1;
958 for (i = 0; i < buffer->text.size; i++) {
959 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
960 return;
962 /* store original boundaries */
963 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
964 buffer->orig_alloc);
965 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
966 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
967 buffer->orig_nr++;
969 /* store one word */
970 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
971 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
972 out->ptr[out->size + j - i] = '\n';
973 out->size += j - i + 1;
975 i = j - 1;
979 /* this executes the word diff on the accumulated buffers */
980 static void diff_words_show(struct diff_words_data *diff_words)
982 xpparam_t xpp;
983 xdemitconf_t xecfg;
984 mmfile_t minus, plus;
985 struct diff_words_style *style = diff_words->style;
987 struct diff_options *opt = diff_words->opt;
988 struct strbuf *msgbuf;
989 char *line_prefix = "";
991 assert(opt);
992 if (opt->output_prefix) {
993 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
994 line_prefix = msgbuf->buf;
997 /* special case: only removal */
998 if (!diff_words->plus.text.size) {
999 fputs(line_prefix, diff_words->opt->file);
1000 fn_out_diff_words_write_helper(diff_words->opt->file,
1001 &style->old, style->newline,
1002 diff_words->minus.text.size,
1003 diff_words->minus.text.ptr, line_prefix);
1004 diff_words->minus.text.size = 0;
1005 return;
1008 diff_words->current_plus = diff_words->plus.text.ptr;
1009 diff_words->last_minus = 0;
1011 memset(&xpp, 0, sizeof(xpp));
1012 memset(&xecfg, 0, sizeof(xecfg));
1013 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1014 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1015 xpp.flags = 0;
1016 /* as only the hunk header will be parsed, we need a 0-context */
1017 xecfg.ctxlen = 0;
1018 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1019 &xpp, &xecfg);
1020 free(minus.ptr);
1021 free(plus.ptr);
1022 if (diff_words->current_plus != diff_words->plus.text.ptr +
1023 diff_words->plus.text.size) {
1024 if (color_words_output_graph_prefix(diff_words))
1025 fputs(line_prefix, diff_words->opt->file);
1026 fn_out_diff_words_write_helper(diff_words->opt->file,
1027 &style->ctx, style->newline,
1028 diff_words->plus.text.ptr + diff_words->plus.text.size
1029 - diff_words->current_plus, diff_words->current_plus,
1030 line_prefix);
1032 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1035 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1036 static void diff_words_flush(struct emit_callback *ecbdata)
1038 if (ecbdata->diff_words->minus.text.size ||
1039 ecbdata->diff_words->plus.text.size)
1040 diff_words_show(ecbdata->diff_words);
1043 static void diff_filespec_load_driver(struct diff_filespec *one)
1045 /* Use already-loaded driver */
1046 if (one->driver)
1047 return;
1049 if (S_ISREG(one->mode))
1050 one->driver = userdiff_find_by_path(one->path);
1052 /* Fallback to default settings */
1053 if (!one->driver)
1054 one->driver = userdiff_find_by_name("default");
1057 static const char *userdiff_word_regex(struct diff_filespec *one)
1059 diff_filespec_load_driver(one);
1060 return one->driver->word_regex;
1063 static void init_diff_words_data(struct emit_callback *ecbdata,
1064 struct diff_options *orig_opts,
1065 struct diff_filespec *one,
1066 struct diff_filespec *two)
1068 int i;
1069 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1070 memcpy(o, orig_opts, sizeof(struct diff_options));
1072 ecbdata->diff_words =
1073 xcalloc(1, sizeof(struct diff_words_data));
1074 ecbdata->diff_words->type = o->word_diff;
1075 ecbdata->diff_words->opt = o;
1076 if (!o->word_regex)
1077 o->word_regex = userdiff_word_regex(one);
1078 if (!o->word_regex)
1079 o->word_regex = userdiff_word_regex(two);
1080 if (!o->word_regex)
1081 o->word_regex = diff_word_regex_cfg;
1082 if (o->word_regex) {
1083 ecbdata->diff_words->word_regex = (regex_t *)
1084 xmalloc(sizeof(regex_t));
1085 if (regcomp(ecbdata->diff_words->word_regex,
1086 o->word_regex,
1087 REG_EXTENDED | REG_NEWLINE))
1088 die ("Invalid regular expression: %s",
1089 o->word_regex);
1091 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1092 if (o->word_diff == diff_words_styles[i].type) {
1093 ecbdata->diff_words->style =
1094 &diff_words_styles[i];
1095 break;
1098 if (want_color(o->use_color)) {
1099 struct diff_words_style *st = ecbdata->diff_words->style;
1100 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1101 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1102 st->ctx.color = diff_get_color_opt(o, DIFF_PLAIN);
1106 static void free_diff_words_data(struct emit_callback *ecbdata)
1108 if (ecbdata->diff_words) {
1109 diff_words_flush(ecbdata);
1110 free (ecbdata->diff_words->opt);
1111 free (ecbdata->diff_words->minus.text.ptr);
1112 free (ecbdata->diff_words->minus.orig);
1113 free (ecbdata->diff_words->plus.text.ptr);
1114 free (ecbdata->diff_words->plus.orig);
1115 if (ecbdata->diff_words->word_regex) {
1116 regfree(ecbdata->diff_words->word_regex);
1117 free(ecbdata->diff_words->word_regex);
1119 free(ecbdata->diff_words);
1120 ecbdata->diff_words = NULL;
1124 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1126 if (want_color(diff_use_color))
1127 return diff_colors[ix];
1128 return "";
1131 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1133 const char *cp;
1134 unsigned long allot;
1135 size_t l = len;
1137 if (ecb->truncate)
1138 return ecb->truncate(line, len);
1139 cp = line;
1140 allot = l;
1141 while (0 < l) {
1142 (void) utf8_width(&cp, &l);
1143 if (!cp)
1144 break; /* truncated in the middle? */
1146 return allot - l;
1149 static void find_lno(const char *line, struct emit_callback *ecbdata)
1151 const char *p;
1152 ecbdata->lno_in_preimage = 0;
1153 ecbdata->lno_in_postimage = 0;
1154 p = strchr(line, '-');
1155 if (!p)
1156 return; /* cannot happen */
1157 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1158 p = strchr(p, '+');
1159 if (!p)
1160 return; /* cannot happen */
1161 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1164 static void fn_out_consume(void *priv, char *line, unsigned long len)
1166 struct emit_callback *ecbdata = priv;
1167 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
1168 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
1169 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1170 struct diff_options *o = ecbdata->opt;
1171 char *line_prefix = "";
1172 struct strbuf *msgbuf;
1174 if (o && o->output_prefix) {
1175 msgbuf = o->output_prefix(o, o->output_prefix_data);
1176 line_prefix = msgbuf->buf;
1179 if (ecbdata->header) {
1180 fprintf(ecbdata->opt->file, "%s", ecbdata->header->buf);
1181 strbuf_reset(ecbdata->header);
1182 ecbdata->header = NULL;
1184 *(ecbdata->found_changesp) = 1;
1186 if (ecbdata->label_path[0]) {
1187 const char *name_a_tab, *name_b_tab;
1189 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
1190 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
1192 fprintf(ecbdata->opt->file, "%s%s--- %s%s%s\n",
1193 line_prefix, meta, ecbdata->label_path[0], reset, name_a_tab);
1194 fprintf(ecbdata->opt->file, "%s%s+++ %s%s%s\n",
1195 line_prefix, meta, ecbdata->label_path[1], reset, name_b_tab);
1196 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1199 if (diff_suppress_blank_empty
1200 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1201 line[0] = '\n';
1202 len = 1;
1205 if (line[0] == '@') {
1206 if (ecbdata->diff_words)
1207 diff_words_flush(ecbdata);
1208 len = sane_truncate_line(ecbdata, line, len);
1209 find_lno(line, ecbdata);
1210 emit_hunk_header(ecbdata, line, len);
1211 if (line[len-1] != '\n')
1212 putc('\n', ecbdata->opt->file);
1213 return;
1216 if (len < 1) {
1217 emit_line(ecbdata->opt, reset, reset, line, len);
1218 if (ecbdata->diff_words
1219 && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
1220 fputs("~\n", ecbdata->opt->file);
1221 return;
1224 if (ecbdata->diff_words) {
1225 if (line[0] == '-') {
1226 diff_words_append(line, len,
1227 &ecbdata->diff_words->minus);
1228 return;
1229 } else if (line[0] == '+') {
1230 diff_words_append(line, len,
1231 &ecbdata->diff_words->plus);
1232 return;
1233 } else if (!prefixcmp(line, "\\ ")) {
1235 * Eat the "no newline at eof" marker as if we
1236 * saw a "+" or "-" line with nothing on it,
1237 * and return without diff_words_flush() to
1238 * defer processing. If this is the end of
1239 * preimage, more "+" lines may come after it.
1241 return;
1243 diff_words_flush(ecbdata);
1244 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
1245 emit_line(ecbdata->opt, plain, reset, line, len);
1246 fputs("~\n", ecbdata->opt->file);
1247 } else {
1249 * Skip the prefix character, if any. With
1250 * diff_suppress_blank_empty, there may be
1251 * none.
1253 if (line[0] != '\n') {
1254 line++;
1255 len--;
1257 emit_line(ecbdata->opt, plain, reset, line, len);
1259 return;
1262 if (line[0] != '+') {
1263 const char *color =
1264 diff_get_color(ecbdata->color_diff,
1265 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
1266 ecbdata->lno_in_preimage++;
1267 if (line[0] == ' ')
1268 ecbdata->lno_in_postimage++;
1269 emit_line(ecbdata->opt, color, reset, line, len);
1270 } else {
1271 ecbdata->lno_in_postimage++;
1272 emit_add_line(reset, ecbdata, line + 1, len - 1);
1276 static char *pprint_rename(const char *a, const char *b)
1278 const char *old = a;
1279 const char *new = b;
1280 struct strbuf name = STRBUF_INIT;
1281 int pfx_length, sfx_length;
1282 int len_a = strlen(a);
1283 int len_b = strlen(b);
1284 int a_midlen, b_midlen;
1285 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1286 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1288 if (qlen_a || qlen_b) {
1289 quote_c_style(a, &name, NULL, 0);
1290 strbuf_addstr(&name, " => ");
1291 quote_c_style(b, &name, NULL, 0);
1292 return strbuf_detach(&name, NULL);
1295 /* Find common prefix */
1296 pfx_length = 0;
1297 while (*old && *new && *old == *new) {
1298 if (*old == '/')
1299 pfx_length = old - a + 1;
1300 old++;
1301 new++;
1304 /* Find common suffix */
1305 old = a + len_a;
1306 new = b + len_b;
1307 sfx_length = 0;
1308 while (a <= old && b <= new && *old == *new) {
1309 if (*old == '/')
1310 sfx_length = len_a - (old - a);
1311 old--;
1312 new--;
1316 * pfx{mid-a => mid-b}sfx
1317 * {pfx-a => pfx-b}sfx
1318 * pfx{sfx-a => sfx-b}
1319 * name-a => name-b
1321 a_midlen = len_a - pfx_length - sfx_length;
1322 b_midlen = len_b - pfx_length - sfx_length;
1323 if (a_midlen < 0)
1324 a_midlen = 0;
1325 if (b_midlen < 0)
1326 b_midlen = 0;
1328 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1329 if (pfx_length + sfx_length) {
1330 strbuf_add(&name, a, pfx_length);
1331 strbuf_addch(&name, '{');
1333 strbuf_add(&name, a + pfx_length, a_midlen);
1334 strbuf_addstr(&name, " => ");
1335 strbuf_add(&name, b + pfx_length, b_midlen);
1336 if (pfx_length + sfx_length) {
1337 strbuf_addch(&name, '}');
1338 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1340 return strbuf_detach(&name, NULL);
1343 struct diffstat_t {
1344 int nr;
1345 int alloc;
1346 struct diffstat_file {
1347 char *from_name;
1348 char *name;
1349 char *print_name;
1350 unsigned is_unmerged:1;
1351 unsigned is_binary:1;
1352 unsigned is_renamed:1;
1353 unsigned is_interesting:1;
1354 uintmax_t added, deleted;
1355 } **files;
1358 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1359 const char *name_a,
1360 const char *name_b)
1362 struct diffstat_file *x;
1363 x = xcalloc(sizeof (*x), 1);
1364 if (diffstat->nr == diffstat->alloc) {
1365 diffstat->alloc = alloc_nr(diffstat->alloc);
1366 diffstat->files = xrealloc(diffstat->files,
1367 diffstat->alloc * sizeof(x));
1369 diffstat->files[diffstat->nr++] = x;
1370 if (name_b) {
1371 x->from_name = xstrdup(name_a);
1372 x->name = xstrdup(name_b);
1373 x->is_renamed = 1;
1375 else {
1376 x->from_name = NULL;
1377 x->name = xstrdup(name_a);
1379 return x;
1382 static void diffstat_consume(void *priv, char *line, unsigned long len)
1384 struct diffstat_t *diffstat = priv;
1385 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1387 if (line[0] == '+')
1388 x->added++;
1389 else if (line[0] == '-')
1390 x->deleted++;
1393 const char mime_boundary_leader[] = "------------";
1395 static int scale_linear(int it, int width, int max_change)
1397 if (!it)
1398 return 0;
1400 * make sure that at least one '-' or '+' is printed if
1401 * there is any change to this path. The easiest way is to
1402 * scale linearly as if the alloted width is one column shorter
1403 * than it is, and then add 1 to the result.
1405 return 1 + (it * (width - 1) / max_change);
1408 static void show_name(FILE *file,
1409 const char *prefix, const char *name, int len)
1411 fprintf(file, " %s%-*s |", prefix, len, name);
1414 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1416 if (cnt <= 0)
1417 return;
1418 fprintf(file, "%s", set);
1419 while (cnt--)
1420 putc(ch, file);
1421 fprintf(file, "%s", reset);
1424 static void fill_print_name(struct diffstat_file *file)
1426 char *pname;
1428 if (file->print_name)
1429 return;
1431 if (!file->is_renamed) {
1432 struct strbuf buf = STRBUF_INIT;
1433 if (quote_c_style(file->name, &buf, NULL, 0)) {
1434 pname = strbuf_detach(&buf, NULL);
1435 } else {
1436 pname = file->name;
1437 strbuf_release(&buf);
1439 } else {
1440 pname = pprint_rename(file->from_name, file->name);
1442 file->print_name = pname;
1445 int print_stat_summary(FILE *fp, int files, int insertions, int deletions)
1447 struct strbuf sb = STRBUF_INIT;
1448 int ret;
1450 if (!files) {
1451 assert(insertions == 0 && deletions == 0);
1452 return fprintf(fp, "%s\n", " 0 files changed");
1455 strbuf_addf(&sb,
1456 (files == 1) ? " %d file changed" : " %d files changed",
1457 files);
1460 * For binary diff, the caller may want to print "x files
1461 * changed" with insertions == 0 && deletions == 0.
1463 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
1464 * is probably less confusing (i.e skip over "2 files changed
1465 * but nothing about added/removed lines? Is this a bug in Git?").
1467 if (insertions || deletions == 0) {
1469 * TRANSLATORS: "+" in (+) is a line addition marker;
1470 * do not translate it.
1472 strbuf_addf(&sb,
1473 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
1474 insertions);
1477 if (deletions || insertions == 0) {
1479 * TRANSLATORS: "-" in (-) is a line removal marker;
1480 * do not translate it.
1482 strbuf_addf(&sb,
1483 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
1484 deletions);
1486 strbuf_addch(&sb, '\n');
1487 ret = fputs(sb.buf, fp);
1488 strbuf_release(&sb);
1489 return ret;
1492 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1494 int i, len, add, del, adds = 0, dels = 0;
1495 uintmax_t max_change = 0, max_len = 0;
1496 int total_files = data->nr, count;
1497 int width, name_width, graph_width, number_width = 0, bin_width = 0;
1498 const char *reset, *add_c, *del_c;
1499 const char *line_prefix = "";
1500 int extra_shown = 0;
1501 struct strbuf *msg = NULL;
1503 if (data->nr == 0)
1504 return;
1506 if (options->output_prefix) {
1507 msg = options->output_prefix(options, options->output_prefix_data);
1508 line_prefix = msg->buf;
1511 count = options->stat_count ? options->stat_count : data->nr;
1513 reset = diff_get_color_opt(options, DIFF_RESET);
1514 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1515 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1518 * Find the longest filename and max number of changes
1520 for (i = 0; (i < count) && (i < data->nr); i++) {
1521 struct diffstat_file *file = data->files[i];
1522 uintmax_t change = file->added + file->deleted;
1524 if (!file->is_interesting && (change == 0)) {
1525 count++; /* not shown == room for one more */
1526 continue;
1528 fill_print_name(file);
1529 len = strlen(file->print_name);
1530 if (max_len < len)
1531 max_len = len;
1533 if (file->is_unmerged) {
1534 /* "Unmerged" is 8 characters */
1535 bin_width = bin_width < 8 ? 8 : bin_width;
1536 continue;
1538 if (file->is_binary) {
1539 /* "Bin XXX -> YYY bytes" */
1540 int w = 14 + decimal_width(file->added)
1541 + decimal_width(file->deleted);
1542 bin_width = bin_width < w ? w : bin_width;
1543 /* Display change counts aligned with "Bin" */
1544 number_width = 3;
1545 continue;
1548 if (max_change < change)
1549 max_change = change;
1551 count = i; /* where we can stop scanning in data->files[] */
1554 * We have width = stat_width or term_columns() columns total.
1555 * We want a maximum of min(max_len, stat_name_width) for the name part.
1556 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1557 * We also need 1 for " " and 4 + decimal_width(max_change)
1558 * for " | NNNN " and one the empty column at the end, altogether
1559 * 6 + decimal_width(max_change).
1561 * If there's not enough space, we will use the smaller of
1562 * stat_name_width (if set) and 5/8*width for the filename,
1563 * and the rest for constant elements + graph part, but no more
1564 * than stat_graph_width for the graph part.
1565 * (5/8 gives 50 for filename and 30 for the constant parts + graph
1566 * for the standard terminal size).
1568 * In other words: stat_width limits the maximum width, and
1569 * stat_name_width fixes the maximum width of the filename,
1570 * and is also used to divide available columns if there
1571 * aren't enough.
1573 * Binary files are displayed with "Bin XXX -> YYY bytes"
1574 * instead of the change count and graph. This part is treated
1575 * similarly to the graph part, except that it is not
1576 * "scaled". If total width is too small to accomodate the
1577 * guaranteed minimum width of the filename part and the
1578 * separators and this message, this message will "overflow"
1579 * making the line longer than the maximum width.
1582 if (options->stat_width == -1)
1583 width = term_columns() - options->output_prefix_length;
1584 else
1585 width = options->stat_width ? options->stat_width : 80;
1586 number_width = decimal_width(max_change) > number_width ?
1587 decimal_width(max_change) : number_width;
1589 if (options->stat_graph_width == -1)
1590 options->stat_graph_width = diff_stat_graph_width;
1593 * Guarantee 3/8*16==6 for the graph part
1594 * and 5/8*16==10 for the filename part
1596 if (width < 16 + 6 + number_width)
1597 width = 16 + 6 + number_width;
1600 * First assign sizes that are wanted, ignoring available width.
1601 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
1602 * starting from "XXX" should fit in graph_width.
1604 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
1605 if (options->stat_graph_width &&
1606 options->stat_graph_width < graph_width)
1607 graph_width = options->stat_graph_width;
1609 name_width = (options->stat_name_width > 0 &&
1610 options->stat_name_width < max_len) ?
1611 options->stat_name_width : max_len;
1614 * Adjust adjustable widths not to exceed maximum width
1616 if (name_width + number_width + 6 + graph_width > width) {
1617 if (graph_width > width * 3/8 - number_width - 6) {
1618 graph_width = width * 3/8 - number_width - 6;
1619 if (graph_width < 6)
1620 graph_width = 6;
1623 if (options->stat_graph_width &&
1624 graph_width > options->stat_graph_width)
1625 graph_width = options->stat_graph_width;
1626 if (name_width > width - number_width - 6 - graph_width)
1627 name_width = width - number_width - 6 - graph_width;
1628 else
1629 graph_width = width - number_width - 6 - name_width;
1633 * From here name_width is the width of the name area,
1634 * and graph_width is the width of the graph area.
1635 * max_change is used to scale graph properly.
1637 for (i = 0; i < count; i++) {
1638 const char *prefix = "";
1639 struct diffstat_file *file = data->files[i];
1640 char *name = file->print_name;
1641 uintmax_t added = file->added;
1642 uintmax_t deleted = file->deleted;
1643 int name_len;
1645 if (!file->is_interesting && (added + deleted == 0))
1646 continue;
1649 * "scale" the filename
1651 len = name_width;
1652 name_len = strlen(name);
1653 if (name_width < name_len) {
1654 char *slash;
1655 prefix = "...";
1656 len -= 3;
1657 name += name_len - len;
1658 slash = strchr(name, '/');
1659 if (slash)
1660 name = slash;
1663 if (file->is_binary) {
1664 fprintf(options->file, "%s", line_prefix);
1665 show_name(options->file, prefix, name, len);
1666 fprintf(options->file, " %*s", number_width, "Bin");
1667 if (!added && !deleted) {
1668 putc('\n', options->file);
1669 continue;
1671 fprintf(options->file, " %s%"PRIuMAX"%s",
1672 del_c, deleted, reset);
1673 fprintf(options->file, " -> ");
1674 fprintf(options->file, "%s%"PRIuMAX"%s",
1675 add_c, added, reset);
1676 fprintf(options->file, " bytes");
1677 fprintf(options->file, "\n");
1678 continue;
1680 else if (file->is_unmerged) {
1681 fprintf(options->file, "%s", line_prefix);
1682 show_name(options->file, prefix, name, len);
1683 fprintf(options->file, " Unmerged\n");
1684 continue;
1688 * scale the add/delete
1690 add = added;
1691 del = deleted;
1693 if (graph_width <= max_change) {
1694 int total = add + del;
1696 total = scale_linear(add + del, graph_width, max_change);
1697 if (total < 2 && add && del)
1698 /* width >= 2 due to the sanity check */
1699 total = 2;
1700 if (add < del) {
1701 add = scale_linear(add, graph_width, max_change);
1702 del = total - add;
1703 } else {
1704 del = scale_linear(del, graph_width, max_change);
1705 add = total - del;
1708 fprintf(options->file, "%s", line_prefix);
1709 show_name(options->file, prefix, name, len);
1710 fprintf(options->file, " %*"PRIuMAX"%s",
1711 number_width, added + deleted,
1712 added + deleted ? " " : "");
1713 show_graph(options->file, '+', add, add_c, reset);
1714 show_graph(options->file, '-', del, del_c, reset);
1715 fprintf(options->file, "\n");
1718 for (i = 0; i < data->nr; i++) {
1719 struct diffstat_file *file = data->files[i];
1720 uintmax_t added = file->added;
1721 uintmax_t deleted = file->deleted;
1723 if (file->is_unmerged ||
1724 (!file->is_interesting && (added + deleted == 0))) {
1725 total_files--;
1726 continue;
1729 if (!file->is_binary) {
1730 adds += added;
1731 dels += deleted;
1733 if (i < count)
1734 continue;
1735 if (!extra_shown)
1736 fprintf(options->file, "%s ...\n", line_prefix);
1737 extra_shown = 1;
1739 fprintf(options->file, "%s", line_prefix);
1740 print_stat_summary(options->file, total_files, adds, dels);
1743 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1745 int i, adds = 0, dels = 0, total_files = data->nr;
1747 if (data->nr == 0)
1748 return;
1750 for (i = 0; i < data->nr; i++) {
1751 int added = data->files[i]->added;
1752 int deleted= data->files[i]->deleted;
1754 if (data->files[i]->is_unmerged ||
1755 (!data->files[i]->is_interesting && (added + deleted == 0))) {
1756 total_files--;
1757 } else if (!data->files[i]->is_binary) { /* don't count bytes */
1758 adds += added;
1759 dels += deleted;
1762 if (options->output_prefix) {
1763 struct strbuf *msg = NULL;
1764 msg = options->output_prefix(options,
1765 options->output_prefix_data);
1766 fprintf(options->file, "%s", msg->buf);
1768 print_stat_summary(options->file, total_files, adds, dels);
1771 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1773 int i;
1775 if (data->nr == 0)
1776 return;
1778 for (i = 0; i < data->nr; i++) {
1779 struct diffstat_file *file = data->files[i];
1781 if (options->output_prefix) {
1782 struct strbuf *msg = NULL;
1783 msg = options->output_prefix(options,
1784 options->output_prefix_data);
1785 fprintf(options->file, "%s", msg->buf);
1788 if (file->is_binary)
1789 fprintf(options->file, "-\t-\t");
1790 else
1791 fprintf(options->file,
1792 "%"PRIuMAX"\t%"PRIuMAX"\t",
1793 file->added, file->deleted);
1794 if (options->line_termination) {
1795 fill_print_name(file);
1796 if (!file->is_renamed)
1797 write_name_quoted(file->name, options->file,
1798 options->line_termination);
1799 else {
1800 fputs(file->print_name, options->file);
1801 putc(options->line_termination, options->file);
1803 } else {
1804 if (file->is_renamed) {
1805 putc('\0', options->file);
1806 write_name_quoted(file->from_name, options->file, '\0');
1808 write_name_quoted(file->name, options->file, '\0');
1813 struct dirstat_file {
1814 const char *name;
1815 unsigned long changed;
1818 struct dirstat_dir {
1819 struct dirstat_file *files;
1820 int alloc, nr, permille, cumulative;
1823 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
1824 unsigned long changed, const char *base, int baselen)
1826 unsigned long this_dir = 0;
1827 unsigned int sources = 0;
1828 const char *line_prefix = "";
1829 struct strbuf *msg = NULL;
1831 if (opt->output_prefix) {
1832 msg = opt->output_prefix(opt, opt->output_prefix_data);
1833 line_prefix = msg->buf;
1836 while (dir->nr) {
1837 struct dirstat_file *f = dir->files;
1838 int namelen = strlen(f->name);
1839 unsigned long this;
1840 char *slash;
1842 if (namelen < baselen)
1843 break;
1844 if (memcmp(f->name, base, baselen))
1845 break;
1846 slash = strchr(f->name + baselen, '/');
1847 if (slash) {
1848 int newbaselen = slash + 1 - f->name;
1849 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
1850 sources++;
1851 } else {
1852 this = f->changed;
1853 dir->files++;
1854 dir->nr--;
1855 sources += 2;
1857 this_dir += this;
1861 * We don't report dirstat's for
1862 * - the top level
1863 * - or cases where everything came from a single directory
1864 * under this directory (sources == 1).
1866 if (baselen && sources != 1) {
1867 if (this_dir) {
1868 int permille = this_dir * 1000 / changed;
1869 if (permille >= dir->permille) {
1870 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
1871 permille / 10, permille % 10, baselen, base);
1872 if (!dir->cumulative)
1873 return 0;
1877 return this_dir;
1880 static int dirstat_compare(const void *_a, const void *_b)
1882 const struct dirstat_file *a = _a;
1883 const struct dirstat_file *b = _b;
1884 return strcmp(a->name, b->name);
1887 static void show_dirstat(struct diff_options *options)
1889 int i;
1890 unsigned long changed;
1891 struct dirstat_dir dir;
1892 struct diff_queue_struct *q = &diff_queued_diff;
1894 dir.files = NULL;
1895 dir.alloc = 0;
1896 dir.nr = 0;
1897 dir.permille = options->dirstat_permille;
1898 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1900 changed = 0;
1901 for (i = 0; i < q->nr; i++) {
1902 struct diff_filepair *p = q->queue[i];
1903 const char *name;
1904 unsigned long copied, added, damage;
1905 int content_changed;
1907 name = p->two->path ? p->two->path : p->one->path;
1909 if (p->one->sha1_valid && p->two->sha1_valid)
1910 content_changed = hashcmp(p->one->sha1, p->two->sha1);
1911 else
1912 content_changed = 1;
1914 if (!content_changed) {
1916 * The SHA1 has not changed, so pre-/post-content is
1917 * identical. We can therefore skip looking at the
1918 * file contents altogether.
1920 damage = 0;
1921 goto found_damage;
1924 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
1926 * In --dirstat-by-file mode, we don't really need to
1927 * look at the actual file contents at all.
1928 * The fact that the SHA1 changed is enough for us to
1929 * add this file to the list of results
1930 * (with each file contributing equal damage).
1932 damage = 1;
1933 goto found_damage;
1936 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1937 diff_populate_filespec(p->one, 0);
1938 diff_populate_filespec(p->two, 0);
1939 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1940 &copied, &added);
1941 diff_free_filespec_data(p->one);
1942 diff_free_filespec_data(p->two);
1943 } else if (DIFF_FILE_VALID(p->one)) {
1944 diff_populate_filespec(p->one, 1);
1945 copied = added = 0;
1946 diff_free_filespec_data(p->one);
1947 } else if (DIFF_FILE_VALID(p->two)) {
1948 diff_populate_filespec(p->two, 1);
1949 copied = 0;
1950 added = p->two->size;
1951 diff_free_filespec_data(p->two);
1952 } else
1953 continue;
1956 * Original minus copied is the removed material,
1957 * added is the new material. They are both damages
1958 * made to the preimage.
1959 * If the resulting damage is zero, we know that
1960 * diffcore_count_changes() considers the two entries to
1961 * be identical, but since content_changed is true, we
1962 * know that there must have been _some_ kind of change,
1963 * so we force all entries to have damage > 0.
1965 damage = (p->one->size - copied) + added;
1966 if (!damage)
1967 damage = 1;
1969 found_damage:
1970 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1971 dir.files[dir.nr].name = name;
1972 dir.files[dir.nr].changed = damage;
1973 changed += damage;
1974 dir.nr++;
1977 /* This can happen even with many files, if everything was renames */
1978 if (!changed)
1979 return;
1981 /* Show all directories with more than x% of the changes */
1982 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1983 gather_dirstat(options, &dir, changed, "", 0);
1986 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
1988 int i;
1989 unsigned long changed;
1990 struct dirstat_dir dir;
1992 if (data->nr == 0)
1993 return;
1995 dir.files = NULL;
1996 dir.alloc = 0;
1997 dir.nr = 0;
1998 dir.permille = options->dirstat_permille;
1999 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2001 changed = 0;
2002 for (i = 0; i < data->nr; i++) {
2003 struct diffstat_file *file = data->files[i];
2004 unsigned long damage = file->added + file->deleted;
2005 if (file->is_binary)
2007 * binary files counts bytes, not lines. Must find some
2008 * way to normalize binary bytes vs. textual lines.
2009 * The following heuristic assumes that there are 64
2010 * bytes per "line".
2011 * This is stupid and ugly, but very cheap...
2013 damage = (damage + 63) / 64;
2014 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2015 dir.files[dir.nr].name = file->name;
2016 dir.files[dir.nr].changed = damage;
2017 changed += damage;
2018 dir.nr++;
2021 /* This can happen even with many files, if everything was renames */
2022 if (!changed)
2023 return;
2025 /* Show all directories with more than x% of the changes */
2026 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
2027 gather_dirstat(options, &dir, changed, "", 0);
2030 static void free_diffstat_info(struct diffstat_t *diffstat)
2032 int i;
2033 for (i = 0; i < diffstat->nr; i++) {
2034 struct diffstat_file *f = diffstat->files[i];
2035 if (f->name != f->print_name)
2036 free(f->print_name);
2037 free(f->name);
2038 free(f->from_name);
2039 free(f);
2041 free(diffstat->files);
2044 struct checkdiff_t {
2045 const char *filename;
2046 int lineno;
2047 int conflict_marker_size;
2048 struct diff_options *o;
2049 unsigned ws_rule;
2050 unsigned status;
2053 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2055 char firstchar;
2056 int cnt;
2058 if (len < marker_size + 1)
2059 return 0;
2060 firstchar = line[0];
2061 switch (firstchar) {
2062 case '=': case '>': case '<': case '|':
2063 break;
2064 default:
2065 return 0;
2067 for (cnt = 1; cnt < marker_size; cnt++)
2068 if (line[cnt] != firstchar)
2069 return 0;
2070 /* line[1] thru line[marker_size-1] are same as firstchar */
2071 if (len < marker_size + 1 || !isspace(line[marker_size]))
2072 return 0;
2073 return 1;
2076 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2078 struct checkdiff_t *data = priv;
2079 int marker_size = data->conflict_marker_size;
2080 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2081 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2082 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2083 char *err;
2084 char *line_prefix = "";
2085 struct strbuf *msgbuf;
2087 assert(data->o);
2088 if (data->o->output_prefix) {
2089 msgbuf = data->o->output_prefix(data->o,
2090 data->o->output_prefix_data);
2091 line_prefix = msgbuf->buf;
2094 if (line[0] == '+') {
2095 unsigned bad;
2096 data->lineno++;
2097 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2098 data->status |= 1;
2099 fprintf(data->o->file,
2100 "%s%s:%d: leftover conflict marker\n",
2101 line_prefix, data->filename, data->lineno);
2103 bad = ws_check(line + 1, len - 1, data->ws_rule);
2104 if (!bad)
2105 return;
2106 data->status |= bad;
2107 err = whitespace_error_string(bad);
2108 fprintf(data->o->file, "%s%s:%d: %s.\n",
2109 line_prefix, data->filename, data->lineno, err);
2110 free(err);
2111 emit_line(data->o, set, reset, line, 1);
2112 ws_check_emit(line + 1, len - 1, data->ws_rule,
2113 data->o->file, set, reset, ws);
2114 } else if (line[0] == ' ') {
2115 data->lineno++;
2116 } else if (line[0] == '@') {
2117 char *plus = strchr(line, '+');
2118 if (plus)
2119 data->lineno = strtol(plus, NULL, 10) - 1;
2120 else
2121 die("invalid diff");
2125 static unsigned char *deflate_it(char *data,
2126 unsigned long size,
2127 unsigned long *result_size)
2129 int bound;
2130 unsigned char *deflated;
2131 git_zstream stream;
2133 memset(&stream, 0, sizeof(stream));
2134 git_deflate_init(&stream, zlib_compression_level);
2135 bound = git_deflate_bound(&stream, size);
2136 deflated = xmalloc(bound);
2137 stream.next_out = deflated;
2138 stream.avail_out = bound;
2140 stream.next_in = (unsigned char *)data;
2141 stream.avail_in = size;
2142 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2143 ; /* nothing */
2144 git_deflate_end(&stream);
2145 *result_size = stream.total_out;
2146 return deflated;
2149 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two, char *prefix)
2151 void *cp;
2152 void *delta;
2153 void *deflated;
2154 void *data;
2155 unsigned long orig_size;
2156 unsigned long delta_size;
2157 unsigned long deflate_size;
2158 unsigned long data_size;
2160 /* We could do deflated delta, or we could do just deflated two,
2161 * whichever is smaller.
2163 delta = NULL;
2164 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2165 if (one->size && two->size) {
2166 delta = diff_delta(one->ptr, one->size,
2167 two->ptr, two->size,
2168 &delta_size, deflate_size);
2169 if (delta) {
2170 void *to_free = delta;
2171 orig_size = delta_size;
2172 delta = deflate_it(delta, delta_size, &delta_size);
2173 free(to_free);
2177 if (delta && delta_size < deflate_size) {
2178 fprintf(file, "%sdelta %lu\n", prefix, orig_size);
2179 free(deflated);
2180 data = delta;
2181 data_size = delta_size;
2183 else {
2184 fprintf(file, "%sliteral %lu\n", prefix, two->size);
2185 free(delta);
2186 data = deflated;
2187 data_size = deflate_size;
2190 /* emit data encoded in base85 */
2191 cp = data;
2192 while (data_size) {
2193 int bytes = (52 < data_size) ? 52 : data_size;
2194 char line[70];
2195 data_size -= bytes;
2196 if (bytes <= 26)
2197 line[0] = bytes + 'A' - 1;
2198 else
2199 line[0] = bytes - 26 + 'a' - 1;
2200 encode_85(line + 1, cp, bytes);
2201 cp = (char *) cp + bytes;
2202 fprintf(file, "%s", prefix);
2203 fputs(line, file);
2204 fputc('\n', file);
2206 fprintf(file, "%s\n", prefix);
2207 free(data);
2210 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two, char *prefix)
2212 fprintf(file, "%sGIT binary patch\n", prefix);
2213 emit_binary_diff_body(file, one, two, prefix);
2214 emit_binary_diff_body(file, two, one, prefix);
2217 int diff_filespec_is_binary(struct diff_filespec *one)
2219 if (one->is_binary == -1) {
2220 diff_filespec_load_driver(one);
2221 if (one->driver->binary != -1)
2222 one->is_binary = one->driver->binary;
2223 else {
2224 if (!one->data && DIFF_FILE_VALID(one))
2225 diff_populate_filespec(one, 0);
2226 if (one->data)
2227 one->is_binary = buffer_is_binary(one->data,
2228 one->size);
2229 if (one->is_binary == -1)
2230 one->is_binary = 0;
2233 return one->is_binary;
2236 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2238 diff_filespec_load_driver(one);
2239 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2242 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2244 if (!options->a_prefix)
2245 options->a_prefix = a;
2246 if (!options->b_prefix)
2247 options->b_prefix = b;
2250 struct userdiff_driver *get_textconv(struct diff_filespec *one)
2252 if (!DIFF_FILE_VALID(one))
2253 return NULL;
2255 diff_filespec_load_driver(one);
2256 return userdiff_get_textconv(one->driver);
2259 static void builtin_diff(const char *name_a,
2260 const char *name_b,
2261 struct diff_filespec *one,
2262 struct diff_filespec *two,
2263 const char *xfrm_msg,
2264 int must_show_header,
2265 struct diff_options *o,
2266 int complete_rewrite)
2268 mmfile_t mf1, mf2;
2269 const char *lbl[2];
2270 char *a_one, *b_two;
2271 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
2272 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2273 const char *a_prefix, *b_prefix;
2274 struct userdiff_driver *textconv_one = NULL;
2275 struct userdiff_driver *textconv_two = NULL;
2276 struct strbuf header = STRBUF_INIT;
2277 struct strbuf *msgbuf;
2278 char *line_prefix = "";
2280 if (o->output_prefix) {
2281 msgbuf = o->output_prefix(o, o->output_prefix_data);
2282 line_prefix = msgbuf->buf;
2285 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
2286 (!one->mode || S_ISGITLINK(one->mode)) &&
2287 (!two->mode || S_ISGITLINK(two->mode))) {
2288 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2289 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2290 show_submodule_summary(o->file, one ? one->path : two->path,
2291 one->sha1, two->sha1, two->dirty_submodule,
2292 meta, del, add, reset);
2293 return;
2296 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2297 textconv_one = get_textconv(one);
2298 textconv_two = get_textconv(two);
2301 diff_set_mnemonic_prefix(o, "a/", "b/");
2302 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2303 a_prefix = o->b_prefix;
2304 b_prefix = o->a_prefix;
2305 } else {
2306 a_prefix = o->a_prefix;
2307 b_prefix = o->b_prefix;
2310 /* Never use a non-valid filename anywhere if at all possible */
2311 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2312 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2314 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2315 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
2316 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2317 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
2318 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
2319 if (lbl[0][0] == '/') {
2320 /* /dev/null */
2321 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
2322 if (xfrm_msg)
2323 strbuf_addstr(&header, xfrm_msg);
2324 must_show_header = 1;
2326 else if (lbl[1][0] == '/') {
2327 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
2328 if (xfrm_msg)
2329 strbuf_addstr(&header, xfrm_msg);
2330 must_show_header = 1;
2332 else {
2333 if (one->mode != two->mode) {
2334 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
2335 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
2336 must_show_header = 1;
2338 if (xfrm_msg)
2339 strbuf_addstr(&header, xfrm_msg);
2342 * we do not run diff between different kind
2343 * of objects.
2345 if ((one->mode ^ two->mode) & S_IFMT)
2346 goto free_ab_and_return;
2347 if (complete_rewrite &&
2348 (textconv_one || !diff_filespec_is_binary(one)) &&
2349 (textconv_two || !diff_filespec_is_binary(two))) {
2350 fprintf(o->file, "%s", header.buf);
2351 strbuf_reset(&header);
2352 emit_rewrite_diff(name_a, name_b, one, two,
2353 textconv_one, textconv_two, o);
2354 o->found_changes = 1;
2355 goto free_ab_and_return;
2359 if (o->irreversible_delete && lbl[1][0] == '/') {
2360 fprintf(o->file, "%s", header.buf);
2361 strbuf_reset(&header);
2362 goto free_ab_and_return;
2363 } else if (!DIFF_OPT_TST(o, TEXT) &&
2364 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2365 (!textconv_two && diff_filespec_is_binary(two)) )) {
2366 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2367 die("unable to read files to diff");
2368 /* Quite common confusing case */
2369 if (mf1.size == mf2.size &&
2370 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2371 if (must_show_header)
2372 fprintf(o->file, "%s", header.buf);
2373 goto free_ab_and_return;
2375 fprintf(o->file, "%s", header.buf);
2376 strbuf_reset(&header);
2377 if (DIFF_OPT_TST(o, BINARY))
2378 emit_binary_diff(o->file, &mf1, &mf2, line_prefix);
2379 else
2380 fprintf(o->file, "%sBinary files %s and %s differ\n",
2381 line_prefix, lbl[0], lbl[1]);
2382 o->found_changes = 1;
2383 } else {
2384 /* Crazy xdl interfaces.. */
2385 const char *diffopts = getenv("GIT_DIFF_OPTS");
2386 xpparam_t xpp;
2387 xdemitconf_t xecfg;
2388 struct emit_callback ecbdata;
2389 const struct userdiff_funcname *pe;
2391 if (must_show_header) {
2392 fprintf(o->file, "%s", header.buf);
2393 strbuf_reset(&header);
2396 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2397 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
2399 pe = diff_funcname_pattern(one);
2400 if (!pe)
2401 pe = diff_funcname_pattern(two);
2403 memset(&xpp, 0, sizeof(xpp));
2404 memset(&xecfg, 0, sizeof(xecfg));
2405 memset(&ecbdata, 0, sizeof(ecbdata));
2406 ecbdata.label_path = lbl;
2407 ecbdata.color_diff = want_color(o->use_color);
2408 ecbdata.found_changesp = &o->found_changes;
2409 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
2410 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
2411 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2412 ecbdata.opt = o;
2413 ecbdata.header = header.len ? &header : NULL;
2414 xpp.flags = o->xdl_opts;
2415 xecfg.ctxlen = o->context;
2416 xecfg.interhunkctxlen = o->interhunkcontext;
2417 xecfg.flags = XDL_EMIT_FUNCNAMES;
2418 if (DIFF_OPT_TST(o, FUNCCONTEXT))
2419 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
2420 if (pe)
2421 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
2422 if (!diffopts)
2424 else if (!prefixcmp(diffopts, "--unified="))
2425 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
2426 else if (!prefixcmp(diffopts, "-u"))
2427 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
2428 if (o->word_diff)
2429 init_diff_words_data(&ecbdata, o, one, two);
2430 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2431 &xpp, &xecfg);
2432 if (o->word_diff)
2433 free_diff_words_data(&ecbdata);
2434 if (textconv_one)
2435 free(mf1.ptr);
2436 if (textconv_two)
2437 free(mf2.ptr);
2438 xdiff_clear_find_func(&xecfg);
2441 free_ab_and_return:
2442 strbuf_release(&header);
2443 diff_free_filespec_data(one);
2444 diff_free_filespec_data(two);
2445 free(a_one);
2446 free(b_two);
2447 return;
2450 static void builtin_diffstat(const char *name_a, const char *name_b,
2451 struct diff_filespec *one,
2452 struct diff_filespec *two,
2453 struct diffstat_t *diffstat,
2454 struct diff_options *o,
2455 struct diff_filepair *p)
2457 mmfile_t mf1, mf2;
2458 struct diffstat_file *data;
2459 int same_contents;
2460 int complete_rewrite = 0;
2462 if (!DIFF_PAIR_UNMERGED(p)) {
2463 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2464 complete_rewrite = 1;
2467 data = diffstat_add(diffstat, name_a, name_b);
2468 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
2470 if (!one || !two) {
2471 data->is_unmerged = 1;
2472 return;
2475 same_contents = !hashcmp(one->sha1, two->sha1);
2477 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2478 data->is_binary = 1;
2479 if (same_contents) {
2480 data->added = 0;
2481 data->deleted = 0;
2482 } else {
2483 data->added = diff_filespec_size(two);
2484 data->deleted = diff_filespec_size(one);
2488 else if (complete_rewrite) {
2489 diff_populate_filespec(one, 0);
2490 diff_populate_filespec(two, 0);
2491 data->deleted = count_lines(one->data, one->size);
2492 data->added = count_lines(two->data, two->size);
2495 else if (!same_contents) {
2496 /* Crazy xdl interfaces.. */
2497 xpparam_t xpp;
2498 xdemitconf_t xecfg;
2500 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2501 die("unable to read files to diff");
2503 memset(&xpp, 0, sizeof(xpp));
2504 memset(&xecfg, 0, sizeof(xecfg));
2505 xpp.flags = o->xdl_opts;
2506 xecfg.ctxlen = o->context;
2507 xecfg.interhunkctxlen = o->interhunkcontext;
2508 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2509 &xpp, &xecfg);
2512 diff_free_filespec_data(one);
2513 diff_free_filespec_data(two);
2516 static void builtin_checkdiff(const char *name_a, const char *name_b,
2517 const char *attr_path,
2518 struct diff_filespec *one,
2519 struct diff_filespec *two,
2520 struct diff_options *o)
2522 mmfile_t mf1, mf2;
2523 struct checkdiff_t data;
2525 if (!two)
2526 return;
2528 memset(&data, 0, sizeof(data));
2529 data.filename = name_b ? name_b : name_a;
2530 data.lineno = 0;
2531 data.o = o;
2532 data.ws_rule = whitespace_rule(attr_path);
2533 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2535 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2536 die("unable to read files to diff");
2539 * All the other codepaths check both sides, but not checking
2540 * the "old" side here is deliberate. We are checking the newly
2541 * introduced changes, and as long as the "new" side is text, we
2542 * can and should check what it introduces.
2544 if (diff_filespec_is_binary(two))
2545 goto free_and_return;
2546 else {
2547 /* Crazy xdl interfaces.. */
2548 xpparam_t xpp;
2549 xdemitconf_t xecfg;
2551 memset(&xpp, 0, sizeof(xpp));
2552 memset(&xecfg, 0, sizeof(xecfg));
2553 xecfg.ctxlen = 1; /* at least one context line */
2554 xpp.flags = 0;
2555 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2556 &xpp, &xecfg);
2558 if (data.ws_rule & WS_BLANK_AT_EOF) {
2559 struct emit_callback ecbdata;
2560 int blank_at_eof;
2562 ecbdata.ws_rule = data.ws_rule;
2563 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2564 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
2566 if (blank_at_eof) {
2567 static char *err;
2568 if (!err)
2569 err = whitespace_error_string(WS_BLANK_AT_EOF);
2570 fprintf(o->file, "%s:%d: %s.\n",
2571 data.filename, blank_at_eof, err);
2572 data.status = 1; /* report errors */
2576 free_and_return:
2577 diff_free_filespec_data(one);
2578 diff_free_filespec_data(two);
2579 if (data.status)
2580 DIFF_OPT_SET(o, CHECK_FAILED);
2583 struct diff_filespec *alloc_filespec(const char *path)
2585 int namelen = strlen(path);
2586 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
2588 memset(spec, 0, sizeof(*spec));
2589 spec->path = (char *)(spec + 1);
2590 memcpy(spec->path, path, namelen+1);
2591 spec->count = 1;
2592 spec->is_binary = -1;
2593 return spec;
2596 void free_filespec(struct diff_filespec *spec)
2598 if (!--spec->count) {
2599 diff_free_filespec_data(spec);
2600 free(spec);
2604 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
2605 int sha1_valid, unsigned short mode)
2607 if (mode) {
2608 spec->mode = canon_mode(mode);
2609 hashcpy(spec->sha1, sha1);
2610 spec->sha1_valid = sha1_valid;
2615 * Given a name and sha1 pair, if the index tells us the file in
2616 * the work tree has that object contents, return true, so that
2617 * prepare_temp_file() does not have to inflate and extract.
2619 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2621 struct cache_entry *ce;
2622 struct stat st;
2623 int pos, len;
2626 * We do not read the cache ourselves here, because the
2627 * benchmark with my previous version that always reads cache
2628 * shows that it makes things worse for diff-tree comparing
2629 * two linux-2.6 kernel trees in an already checked out work
2630 * tree. This is because most diff-tree comparisons deal with
2631 * only a small number of files, while reading the cache is
2632 * expensive for a large project, and its cost outweighs the
2633 * savings we get by not inflating the object to a temporary
2634 * file. Practically, this code only helps when we are used
2635 * by diff-cache --cached, which does read the cache before
2636 * calling us.
2638 if (!active_cache)
2639 return 0;
2641 /* We want to avoid the working directory if our caller
2642 * doesn't need the data in a normal file, this system
2643 * is rather slow with its stat/open/mmap/close syscalls,
2644 * and the object is contained in a pack file. The pack
2645 * is probably already open and will be faster to obtain
2646 * the data through than the working directory. Loose
2647 * objects however would tend to be slower as they need
2648 * to be individually opened and inflated.
2650 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2651 return 0;
2653 len = strlen(name);
2654 pos = cache_name_pos(name, len);
2655 if (pos < 0)
2656 return 0;
2657 ce = active_cache[pos];
2660 * This is not the sha1 we are looking for, or
2661 * unreusable because it is not a regular file.
2663 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
2664 return 0;
2667 * If ce is marked as "assume unchanged", there is no
2668 * guarantee that work tree matches what we are looking for.
2670 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2671 return 0;
2674 * If ce matches the file in the work tree, we can reuse it.
2676 if (ce_uptodate(ce) ||
2677 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2678 return 1;
2680 return 0;
2683 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2685 int len;
2686 char *data = xmalloc(100), *dirty = "";
2688 /* Are we looking at the work tree? */
2689 if (s->dirty_submodule)
2690 dirty = "-dirty";
2692 len = snprintf(data, 100,
2693 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2694 s->data = data;
2695 s->size = len;
2696 s->should_free = 1;
2697 if (size_only) {
2698 s->data = NULL;
2699 free(data);
2701 return 0;
2705 * While doing rename detection and pickaxe operation, we may need to
2706 * grab the data for the blob (or file) for our own in-core comparison.
2707 * diff_filespec has data and size fields for this purpose.
2709 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2711 int err = 0;
2712 if (!DIFF_FILE_VALID(s))
2713 die("internal error: asking to populate invalid file.");
2714 if (S_ISDIR(s->mode))
2715 return -1;
2717 if (s->data)
2718 return 0;
2720 if (size_only && 0 < s->size)
2721 return 0;
2723 if (S_ISGITLINK(s->mode))
2724 return diff_populate_gitlink(s, size_only);
2726 if (!s->sha1_valid ||
2727 reuse_worktree_file(s->path, s->sha1, 0)) {
2728 struct strbuf buf = STRBUF_INIT;
2729 struct stat st;
2730 int fd;
2732 if (lstat(s->path, &st) < 0) {
2733 if (errno == ENOENT) {
2734 err_empty:
2735 err = -1;
2736 empty:
2737 s->data = (char *)"";
2738 s->size = 0;
2739 return err;
2742 s->size = xsize_t(st.st_size);
2743 if (!s->size)
2744 goto empty;
2745 if (S_ISLNK(st.st_mode)) {
2746 struct strbuf sb = STRBUF_INIT;
2748 if (strbuf_readlink(&sb, s->path, s->size))
2749 goto err_empty;
2750 s->size = sb.len;
2751 s->data = strbuf_detach(&sb, NULL);
2752 s->should_free = 1;
2753 return 0;
2755 if (size_only)
2756 return 0;
2757 fd = open(s->path, O_RDONLY);
2758 if (fd < 0)
2759 goto err_empty;
2760 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2761 close(fd);
2762 s->should_munmap = 1;
2765 * Convert from working tree format to canonical git format
2767 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2768 size_t size = 0;
2769 munmap(s->data, s->size);
2770 s->should_munmap = 0;
2771 s->data = strbuf_detach(&buf, &size);
2772 s->size = size;
2773 s->should_free = 1;
2776 else {
2777 enum object_type type;
2778 if (size_only) {
2779 type = sha1_object_info(s->sha1, &s->size);
2780 if (type < 0)
2781 die("unable to read %s", sha1_to_hex(s->sha1));
2782 } else {
2783 s->data = read_sha1_file(s->sha1, &type, &s->size);
2784 if (!s->data)
2785 die("unable to read %s", sha1_to_hex(s->sha1));
2786 s->should_free = 1;
2789 return 0;
2792 void diff_free_filespec_blob(struct diff_filespec *s)
2794 if (s->should_free)
2795 free(s->data);
2796 else if (s->should_munmap)
2797 munmap(s->data, s->size);
2799 if (s->should_free || s->should_munmap) {
2800 s->should_free = s->should_munmap = 0;
2801 s->data = NULL;
2805 void diff_free_filespec_data(struct diff_filespec *s)
2807 diff_free_filespec_blob(s);
2808 free(s->cnt_data);
2809 s->cnt_data = NULL;
2812 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2813 void *blob,
2814 unsigned long size,
2815 const unsigned char *sha1,
2816 int mode)
2818 int fd;
2819 struct strbuf buf = STRBUF_INIT;
2820 struct strbuf template = STRBUF_INIT;
2821 char *path_dup = xstrdup(path);
2822 const char *base = basename(path_dup);
2824 /* Generate "XXXXXX_basename.ext" */
2825 strbuf_addstr(&template, "XXXXXX_");
2826 strbuf_addstr(&template, base);
2828 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2829 strlen(base) + 1);
2830 if (fd < 0)
2831 die_errno("unable to create temp-file");
2832 if (convert_to_working_tree(path,
2833 (const char *)blob, (size_t)size, &buf)) {
2834 blob = buf.buf;
2835 size = buf.len;
2837 if (write_in_full(fd, blob, size) != size)
2838 die_errno("unable to write temp-file");
2839 close(fd);
2840 temp->name = temp->tmp_path;
2841 strcpy(temp->hex, sha1_to_hex(sha1));
2842 temp->hex[40] = 0;
2843 sprintf(temp->mode, "%06o", mode);
2844 strbuf_release(&buf);
2845 strbuf_release(&template);
2846 free(path_dup);
2849 static struct diff_tempfile *prepare_temp_file(const char *name,
2850 struct diff_filespec *one)
2852 struct diff_tempfile *temp = claim_diff_tempfile();
2854 if (!DIFF_FILE_VALID(one)) {
2855 not_a_valid_file:
2856 /* A '-' entry produces this for file-2, and
2857 * a '+' entry produces this for file-1.
2859 temp->name = "/dev/null";
2860 strcpy(temp->hex, ".");
2861 strcpy(temp->mode, ".");
2862 return temp;
2865 if (!remove_tempfile_installed) {
2866 atexit(remove_tempfile);
2867 sigchain_push_common(remove_tempfile_on_signal);
2868 remove_tempfile_installed = 1;
2871 if (!one->sha1_valid ||
2872 reuse_worktree_file(name, one->sha1, 1)) {
2873 struct stat st;
2874 if (lstat(name, &st) < 0) {
2875 if (errno == ENOENT)
2876 goto not_a_valid_file;
2877 die_errno("stat(%s)", name);
2879 if (S_ISLNK(st.st_mode)) {
2880 struct strbuf sb = STRBUF_INIT;
2881 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2882 die_errno("readlink(%s)", name);
2883 prep_temp_blob(name, temp, sb.buf, sb.len,
2884 (one->sha1_valid ?
2885 one->sha1 : null_sha1),
2886 (one->sha1_valid ?
2887 one->mode : S_IFLNK));
2888 strbuf_release(&sb);
2890 else {
2891 /* we can borrow from the file in the work tree */
2892 temp->name = name;
2893 if (!one->sha1_valid)
2894 strcpy(temp->hex, sha1_to_hex(null_sha1));
2895 else
2896 strcpy(temp->hex, sha1_to_hex(one->sha1));
2897 /* Even though we may sometimes borrow the
2898 * contents from the work tree, we always want
2899 * one->mode. mode is trustworthy even when
2900 * !(one->sha1_valid), as long as
2901 * DIFF_FILE_VALID(one).
2903 sprintf(temp->mode, "%06o", one->mode);
2905 return temp;
2907 else {
2908 if (diff_populate_filespec(one, 0))
2909 die("cannot read data blob for %s", one->path);
2910 prep_temp_blob(name, temp, one->data, one->size,
2911 one->sha1, one->mode);
2913 return temp;
2916 /* An external diff command takes:
2918 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2919 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2922 static void run_external_diff(const char *pgm,
2923 const char *name,
2924 const char *other,
2925 struct diff_filespec *one,
2926 struct diff_filespec *two,
2927 const char *xfrm_msg,
2928 int complete_rewrite)
2930 const char *spawn_arg[10];
2931 int retval;
2932 const char **arg = &spawn_arg[0];
2934 if (one && two) {
2935 struct diff_tempfile *temp_one, *temp_two;
2936 const char *othername = (other ? other : name);
2937 temp_one = prepare_temp_file(name, one);
2938 temp_two = prepare_temp_file(othername, two);
2939 *arg++ = pgm;
2940 *arg++ = name;
2941 *arg++ = temp_one->name;
2942 *arg++ = temp_one->hex;
2943 *arg++ = temp_one->mode;
2944 *arg++ = temp_two->name;
2945 *arg++ = temp_two->hex;
2946 *arg++ = temp_two->mode;
2947 if (other) {
2948 *arg++ = other;
2949 *arg++ = xfrm_msg;
2951 } else {
2952 *arg++ = pgm;
2953 *arg++ = name;
2955 *arg = NULL;
2956 fflush(NULL);
2957 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2958 remove_tempfile();
2959 if (retval) {
2960 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2961 exit(1);
2965 static int similarity_index(struct diff_filepair *p)
2967 return p->score * 100 / MAX_SCORE;
2970 static void fill_metainfo(struct strbuf *msg,
2971 const char *name,
2972 const char *other,
2973 struct diff_filespec *one,
2974 struct diff_filespec *two,
2975 struct diff_options *o,
2976 struct diff_filepair *p,
2977 int *must_show_header,
2978 int use_color)
2980 const char *set = diff_get_color(use_color, DIFF_METAINFO);
2981 const char *reset = diff_get_color(use_color, DIFF_RESET);
2982 struct strbuf *msgbuf;
2983 char *line_prefix = "";
2985 *must_show_header = 1;
2986 if (o->output_prefix) {
2987 msgbuf = o->output_prefix(o, o->output_prefix_data);
2988 line_prefix = msgbuf->buf;
2990 strbuf_init(msg, PATH_MAX * 2 + 300);
2991 switch (p->status) {
2992 case DIFF_STATUS_COPIED:
2993 strbuf_addf(msg, "%s%ssimilarity index %d%%",
2994 line_prefix, set, similarity_index(p));
2995 strbuf_addf(msg, "%s\n%s%scopy from ",
2996 reset, line_prefix, set);
2997 quote_c_style(name, msg, NULL, 0);
2998 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
2999 quote_c_style(other, msg, NULL, 0);
3000 strbuf_addf(msg, "%s\n", reset);
3001 break;
3002 case DIFF_STATUS_RENAMED:
3003 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3004 line_prefix, set, similarity_index(p));
3005 strbuf_addf(msg, "%s\n%s%srename from ",
3006 reset, line_prefix, set);
3007 quote_c_style(name, msg, NULL, 0);
3008 strbuf_addf(msg, "%s\n%s%srename to ",
3009 reset, line_prefix, set);
3010 quote_c_style(other, msg, NULL, 0);
3011 strbuf_addf(msg, "%s\n", reset);
3012 break;
3013 case DIFF_STATUS_MODIFIED:
3014 if (p->score) {
3015 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3016 line_prefix,
3017 set, similarity_index(p), reset);
3018 break;
3020 /* fallthru */
3021 default:
3022 *must_show_header = 0;
3024 if (one && two && hashcmp(one->sha1, two->sha1)) {
3025 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3027 if (DIFF_OPT_TST(o, BINARY)) {
3028 mmfile_t mf;
3029 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3030 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3031 abbrev = 40;
3033 strbuf_addf(msg, "%s%sindex %s..", line_prefix, set,
3034 find_unique_abbrev(one->sha1, abbrev));
3035 strbuf_addstr(msg, find_unique_abbrev(two->sha1, abbrev));
3036 if (one->mode == two->mode)
3037 strbuf_addf(msg, " %06o", one->mode);
3038 strbuf_addf(msg, "%s\n", reset);
3042 static void run_diff_cmd(const char *pgm,
3043 const char *name,
3044 const char *other,
3045 const char *attr_path,
3046 struct diff_filespec *one,
3047 struct diff_filespec *two,
3048 struct strbuf *msg,
3049 struct diff_options *o,
3050 struct diff_filepair *p)
3052 const char *xfrm_msg = NULL;
3053 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3054 int must_show_header = 0;
3057 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3058 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3059 if (drv && drv->external)
3060 pgm = drv->external;
3063 if (msg) {
3065 * don't use colors when the header is intended for an
3066 * external diff driver
3068 fill_metainfo(msg, name, other, one, two, o, p,
3069 &must_show_header,
3070 want_color(o->use_color) && !pgm);
3071 xfrm_msg = msg->len ? msg->buf : NULL;
3074 if (pgm) {
3075 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3076 complete_rewrite);
3077 return;
3079 if (one && two)
3080 builtin_diff(name, other ? other : name,
3081 one, two, xfrm_msg, must_show_header,
3082 o, complete_rewrite);
3083 else
3084 fprintf(o->file, "* Unmerged path %s\n", name);
3087 static void diff_fill_sha1_info(struct diff_filespec *one)
3089 if (DIFF_FILE_VALID(one)) {
3090 if (!one->sha1_valid) {
3091 struct stat st;
3092 if (one->is_stdin) {
3093 hashcpy(one->sha1, null_sha1);
3094 return;
3096 if (lstat(one->path, &st) < 0)
3097 die_errno("stat '%s'", one->path);
3098 if (index_path(one->sha1, one->path, &st, 0))
3099 die("cannot hash %s", one->path);
3102 else
3103 hashclr(one->sha1);
3106 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3108 /* Strip the prefix but do not molest /dev/null and absolute paths */
3109 if (*namep && **namep != '/') {
3110 *namep += prefix_length;
3111 if (**namep == '/')
3112 ++*namep;
3114 if (*otherp && **otherp != '/') {
3115 *otherp += prefix_length;
3116 if (**otherp == '/')
3117 ++*otherp;
3121 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3123 const char *pgm = external_diff();
3124 struct strbuf msg;
3125 struct diff_filespec *one = p->one;
3126 struct diff_filespec *two = p->two;
3127 const char *name;
3128 const char *other;
3129 const char *attr_path;
3131 name = p->one->path;
3132 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3133 attr_path = name;
3134 if (o->prefix_length)
3135 strip_prefix(o->prefix_length, &name, &other);
3137 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3138 pgm = NULL;
3140 if (DIFF_PAIR_UNMERGED(p)) {
3141 run_diff_cmd(pgm, name, NULL, attr_path,
3142 NULL, NULL, NULL, o, p);
3143 return;
3146 diff_fill_sha1_info(one);
3147 diff_fill_sha1_info(two);
3149 if (!pgm &&
3150 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3151 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3153 * a filepair that changes between file and symlink
3154 * needs to be split into deletion and creation.
3156 struct diff_filespec *null = alloc_filespec(two->path);
3157 run_diff_cmd(NULL, name, other, attr_path,
3158 one, null, &msg, o, p);
3159 free(null);
3160 strbuf_release(&msg);
3162 null = alloc_filespec(one->path);
3163 run_diff_cmd(NULL, name, other, attr_path,
3164 null, two, &msg, o, p);
3165 free(null);
3167 else
3168 run_diff_cmd(pgm, name, other, attr_path,
3169 one, two, &msg, o, p);
3171 strbuf_release(&msg);
3174 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3175 struct diffstat_t *diffstat)
3177 const char *name;
3178 const char *other;
3180 if (DIFF_PAIR_UNMERGED(p)) {
3181 /* unmerged */
3182 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
3183 return;
3186 name = p->one->path;
3187 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3189 if (o->prefix_length)
3190 strip_prefix(o->prefix_length, &name, &other);
3192 diff_fill_sha1_info(p->one);
3193 diff_fill_sha1_info(p->two);
3195 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
3198 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3200 const char *name;
3201 const char *other;
3202 const char *attr_path;
3204 if (DIFF_PAIR_UNMERGED(p)) {
3205 /* unmerged */
3206 return;
3209 name = p->one->path;
3210 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3211 attr_path = other ? other : name;
3213 if (o->prefix_length)
3214 strip_prefix(o->prefix_length, &name, &other);
3216 diff_fill_sha1_info(p->one);
3217 diff_fill_sha1_info(p->two);
3219 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
3222 void diff_setup(struct diff_options *options)
3224 memcpy(options, &default_diff_options, sizeof(*options));
3226 options->file = stdout;
3228 options->line_termination = '\n';
3229 options->break_opt = -1;
3230 options->rename_limit = -1;
3231 options->dirstat_permille = diff_dirstat_permille_default;
3232 options->context = diff_context_default;
3233 DIFF_OPT_SET(options, RENAME_EMPTY);
3235 options->change = diff_change;
3236 options->add_remove = diff_addremove;
3237 options->use_color = diff_use_color_default;
3238 options->detect_rename = diff_detect_rename_default;
3239 options->xdl_opts |= diff_algorithm;
3241 if (diff_no_prefix) {
3242 options->a_prefix = options->b_prefix = "";
3243 } else if (!diff_mnemonic_prefix) {
3244 options->a_prefix = "a/";
3245 options->b_prefix = "b/";
3249 void diff_setup_done(struct diff_options *options)
3251 int count = 0;
3253 if (options->output_format & DIFF_FORMAT_NAME)
3254 count++;
3255 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3256 count++;
3257 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3258 count++;
3259 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3260 count++;
3261 if (count > 1)
3262 die("--name-only, --name-status, --check and -s are mutually exclusive");
3265 * Most of the time we can say "there are changes"
3266 * only by checking if there are changed paths, but
3267 * --ignore-whitespace* options force us to look
3268 * inside contents.
3271 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3272 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3273 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3274 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3275 else
3276 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3278 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3279 options->detect_rename = DIFF_DETECT_COPY;
3281 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3282 options->prefix = NULL;
3283 if (options->prefix)
3284 options->prefix_length = strlen(options->prefix);
3285 else
3286 options->prefix_length = 0;
3288 if (options->output_format & (DIFF_FORMAT_NAME |
3289 DIFF_FORMAT_NAME_STATUS |
3290 DIFF_FORMAT_CHECKDIFF |
3291 DIFF_FORMAT_NO_OUTPUT))
3292 options->output_format &= ~(DIFF_FORMAT_RAW |
3293 DIFF_FORMAT_NUMSTAT |
3294 DIFF_FORMAT_DIFFSTAT |
3295 DIFF_FORMAT_SHORTSTAT |
3296 DIFF_FORMAT_DIRSTAT |
3297 DIFF_FORMAT_SUMMARY |
3298 DIFF_FORMAT_PATCH);
3301 * These cases always need recursive; we do not drop caller-supplied
3302 * recursive bits for other formats here.
3304 if (options->output_format & (DIFF_FORMAT_PATCH |
3305 DIFF_FORMAT_NUMSTAT |
3306 DIFF_FORMAT_DIFFSTAT |
3307 DIFF_FORMAT_SHORTSTAT |
3308 DIFF_FORMAT_DIRSTAT |
3309 DIFF_FORMAT_SUMMARY |
3310 DIFF_FORMAT_CHECKDIFF))
3311 DIFF_OPT_SET(options, RECURSIVE);
3313 * Also pickaxe would not work very well if you do not say recursive
3315 if (options->pickaxe)
3316 DIFF_OPT_SET(options, RECURSIVE);
3318 * When patches are generated, submodules diffed against the work tree
3319 * must be checked for dirtiness too so it can be shown in the output
3321 if (options->output_format & DIFF_FORMAT_PATCH)
3322 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
3324 if (options->detect_rename && options->rename_limit < 0)
3325 options->rename_limit = diff_rename_limit_default;
3326 if (options->setup & DIFF_SETUP_USE_CACHE) {
3327 if (!active_cache)
3328 /* read-cache does not die even when it fails
3329 * so it is safe for us to do this here. Also
3330 * it does not smudge active_cache or active_nr
3331 * when it fails, so we do not have to worry about
3332 * cleaning it up ourselves either.
3334 read_cache();
3336 if (options->abbrev <= 0 || 40 < options->abbrev)
3337 options->abbrev = 40; /* full */
3340 * It does not make sense to show the first hit we happened
3341 * to have found. It does not make sense not to return with
3342 * exit code in such a case either.
3344 if (DIFF_OPT_TST(options, QUICK)) {
3345 options->output_format = DIFF_FORMAT_NO_OUTPUT;
3346 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3350 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
3352 char c, *eq;
3353 int len;
3355 if (*arg != '-')
3356 return 0;
3357 c = *++arg;
3358 if (!c)
3359 return 0;
3360 if (c == arg_short) {
3361 c = *++arg;
3362 if (!c)
3363 return 1;
3364 if (val && isdigit(c)) {
3365 char *end;
3366 int n = strtoul(arg, &end, 10);
3367 if (*end)
3368 return 0;
3369 *val = n;
3370 return 1;
3372 return 0;
3374 if (c != '-')
3375 return 0;
3376 arg++;
3377 eq = strchr(arg, '=');
3378 if (eq)
3379 len = eq - arg;
3380 else
3381 len = strlen(arg);
3382 if (!len || strncmp(arg, arg_long, len))
3383 return 0;
3384 if (eq) {
3385 int n;
3386 char *end;
3387 if (!isdigit(*++eq))
3388 return 0;
3389 n = strtoul(eq, &end, 10);
3390 if (*end)
3391 return 0;
3392 *val = n;
3394 return 1;
3397 static int diff_scoreopt_parse(const char *opt);
3399 static inline int short_opt(char opt, const char **argv,
3400 const char **optarg)
3402 const char *arg = argv[0];
3403 if (arg[0] != '-' || arg[1] != opt)
3404 return 0;
3405 if (arg[2] != '\0') {
3406 *optarg = arg + 2;
3407 return 1;
3409 if (!argv[1])
3410 die("Option '%c' requires a value", opt);
3411 *optarg = argv[1];
3412 return 2;
3415 int parse_long_opt(const char *opt, const char **argv,
3416 const char **optarg)
3418 const char *arg = argv[0];
3419 if (arg[0] != '-' || arg[1] != '-')
3420 return 0;
3421 arg += strlen("--");
3422 if (prefixcmp(arg, opt))
3423 return 0;
3424 arg += strlen(opt);
3425 if (*arg == '=') { /* sticked form: --option=value */
3426 *optarg = arg + 1;
3427 return 1;
3429 if (*arg != '\0')
3430 return 0;
3431 /* separate form: --option value */
3432 if (!argv[1])
3433 die("Option '--%s' requires a value", opt);
3434 *optarg = argv[1];
3435 return 2;
3438 static int stat_opt(struct diff_options *options, const char **av)
3440 const char *arg = av[0];
3441 char *end;
3442 int width = options->stat_width;
3443 int name_width = options->stat_name_width;
3444 int graph_width = options->stat_graph_width;
3445 int count = options->stat_count;
3446 int argcount = 1;
3448 arg += strlen("--stat");
3449 end = (char *)arg;
3451 switch (*arg) {
3452 case '-':
3453 if (!prefixcmp(arg, "-width")) {
3454 arg += strlen("-width");
3455 if (*arg == '=')
3456 width = strtoul(arg + 1, &end, 10);
3457 else if (!*arg && !av[1])
3458 die("Option '--stat-width' requires a value");
3459 else if (!*arg) {
3460 width = strtoul(av[1], &end, 10);
3461 argcount = 2;
3463 } else if (!prefixcmp(arg, "-name-width")) {
3464 arg += strlen("-name-width");
3465 if (*arg == '=')
3466 name_width = strtoul(arg + 1, &end, 10);
3467 else if (!*arg && !av[1])
3468 die("Option '--stat-name-width' requires a value");
3469 else if (!*arg) {
3470 name_width = strtoul(av[1], &end, 10);
3471 argcount = 2;
3473 } else if (!prefixcmp(arg, "-graph-width")) {
3474 arg += strlen("-graph-width");
3475 if (*arg == '=')
3476 graph_width = strtoul(arg + 1, &end, 10);
3477 else if (!*arg && !av[1])
3478 die("Option '--stat-graph-width' requires a value");
3479 else if (!*arg) {
3480 graph_width = strtoul(av[1], &end, 10);
3481 argcount = 2;
3483 } else if (!prefixcmp(arg, "-count")) {
3484 arg += strlen("-count");
3485 if (*arg == '=')
3486 count = strtoul(arg + 1, &end, 10);
3487 else if (!*arg && !av[1])
3488 die("Option '--stat-count' requires a value");
3489 else if (!*arg) {
3490 count = strtoul(av[1], &end, 10);
3491 argcount = 2;
3494 break;
3495 case '=':
3496 width = strtoul(arg+1, &end, 10);
3497 if (*end == ',')
3498 name_width = strtoul(end+1, &end, 10);
3499 if (*end == ',')
3500 count = strtoul(end+1, &end, 10);
3503 /* Important! This checks all the error cases! */
3504 if (*end)
3505 return 0;
3506 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3507 options->stat_name_width = name_width;
3508 options->stat_graph_width = graph_width;
3509 options->stat_width = width;
3510 options->stat_count = count;
3511 return argcount;
3514 static int parse_dirstat_opt(struct diff_options *options, const char *params)
3516 struct strbuf errmsg = STRBUF_INIT;
3517 if (parse_dirstat_params(options, params, &errmsg))
3518 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
3519 errmsg.buf);
3520 strbuf_release(&errmsg);
3522 * The caller knows a dirstat-related option is given from the command
3523 * line; allow it to say "return this_function();"
3525 options->output_format |= DIFF_FORMAT_DIRSTAT;
3526 return 1;
3529 static int parse_submodule_opt(struct diff_options *options, const char *value)
3531 if (parse_submodule_params(options, value))
3532 die(_("Failed to parse --submodule option parameter: '%s'"),
3533 value);
3534 return 1;
3537 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
3539 const char *arg = av[0];
3540 const char *optarg;
3541 int argcount;
3543 /* Output format options */
3544 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch"))
3545 options->output_format |= DIFF_FORMAT_PATCH;
3546 else if (opt_arg(arg, 'U', "unified", &options->context))
3547 options->output_format |= DIFF_FORMAT_PATCH;
3548 else if (!strcmp(arg, "--raw"))
3549 options->output_format |= DIFF_FORMAT_RAW;
3550 else if (!strcmp(arg, "--patch-with-raw"))
3551 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
3552 else if (!strcmp(arg, "--numstat"))
3553 options->output_format |= DIFF_FORMAT_NUMSTAT;
3554 else if (!strcmp(arg, "--shortstat"))
3555 options->output_format |= DIFF_FORMAT_SHORTSTAT;
3556 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
3557 return parse_dirstat_opt(options, "");
3558 else if (!prefixcmp(arg, "-X"))
3559 return parse_dirstat_opt(options, arg + 2);
3560 else if (!prefixcmp(arg, "--dirstat="))
3561 return parse_dirstat_opt(options, arg + 10);
3562 else if (!strcmp(arg, "--cumulative"))
3563 return parse_dirstat_opt(options, "cumulative");
3564 else if (!strcmp(arg, "--dirstat-by-file"))
3565 return parse_dirstat_opt(options, "files");
3566 else if (!prefixcmp(arg, "--dirstat-by-file=")) {
3567 parse_dirstat_opt(options, "files");
3568 return parse_dirstat_opt(options, arg + 18);
3570 else if (!strcmp(arg, "--check"))
3571 options->output_format |= DIFF_FORMAT_CHECKDIFF;
3572 else if (!strcmp(arg, "--summary"))
3573 options->output_format |= DIFF_FORMAT_SUMMARY;
3574 else if (!strcmp(arg, "--patch-with-stat"))
3575 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
3576 else if (!strcmp(arg, "--name-only"))
3577 options->output_format |= DIFF_FORMAT_NAME;
3578 else if (!strcmp(arg, "--name-status"))
3579 options->output_format |= DIFF_FORMAT_NAME_STATUS;
3580 else if (!strcmp(arg, "-s"))
3581 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
3582 else if (!prefixcmp(arg, "--stat"))
3583 /* --stat, --stat-width, --stat-name-width, or --stat-count */
3584 return stat_opt(options, av);
3586 /* renames options */
3587 else if (!prefixcmp(arg, "-B") || !prefixcmp(arg, "--break-rewrites=") ||
3588 !strcmp(arg, "--break-rewrites")) {
3589 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
3590 return error("invalid argument to -B: %s", arg+2);
3592 else if (!prefixcmp(arg, "-M") || !prefixcmp(arg, "--find-renames=") ||
3593 !strcmp(arg, "--find-renames")) {
3594 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3595 return error("invalid argument to -M: %s", arg+2);
3596 options->detect_rename = DIFF_DETECT_RENAME;
3598 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
3599 options->irreversible_delete = 1;
3601 else if (!prefixcmp(arg, "-C") || !prefixcmp(arg, "--find-copies=") ||
3602 !strcmp(arg, "--find-copies")) {
3603 if (options->detect_rename == DIFF_DETECT_COPY)
3604 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3605 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3606 return error("invalid argument to -C: %s", arg+2);
3607 options->detect_rename = DIFF_DETECT_COPY;
3609 else if (!strcmp(arg, "--no-renames"))
3610 options->detect_rename = 0;
3611 else if (!strcmp(arg, "--rename-empty"))
3612 DIFF_OPT_SET(options, RENAME_EMPTY);
3613 else if (!strcmp(arg, "--no-rename-empty"))
3614 DIFF_OPT_CLR(options, RENAME_EMPTY);
3615 else if (!strcmp(arg, "--relative"))
3616 DIFF_OPT_SET(options, RELATIVE_NAME);
3617 else if (!prefixcmp(arg, "--relative=")) {
3618 DIFF_OPT_SET(options, RELATIVE_NAME);
3619 options->prefix = arg + 11;
3622 /* xdiff options */
3623 else if (!strcmp(arg, "--minimal"))
3624 DIFF_XDL_SET(options, NEED_MINIMAL);
3625 else if (!strcmp(arg, "--no-minimal"))
3626 DIFF_XDL_CLR(options, NEED_MINIMAL);
3627 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
3628 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
3629 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
3630 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
3631 else if (!strcmp(arg, "--ignore-space-at-eol"))
3632 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
3633 else if (!strcmp(arg, "--patience"))
3634 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
3635 else if (!strcmp(arg, "--histogram"))
3636 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
3637 else if (!prefixcmp(arg, "--diff-algorithm=")) {
3638 long value = parse_algorithm_value(arg+17);
3639 if (value < 0)
3640 return error("option diff-algorithm accepts \"myers\", "
3641 "\"minimal\", \"patience\" and \"histogram\"");
3642 /* clear out previous settings */
3643 DIFF_XDL_CLR(options, NEED_MINIMAL);
3644 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3645 options->xdl_opts |= value;
3648 /* flags options */
3649 else if (!strcmp(arg, "--binary")) {
3650 options->output_format |= DIFF_FORMAT_PATCH;
3651 DIFF_OPT_SET(options, BINARY);
3653 else if (!strcmp(arg, "--full-index"))
3654 DIFF_OPT_SET(options, FULL_INDEX);
3655 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
3656 DIFF_OPT_SET(options, TEXT);
3657 else if (!strcmp(arg, "-R"))
3658 DIFF_OPT_SET(options, REVERSE_DIFF);
3659 else if (!strcmp(arg, "--find-copies-harder"))
3660 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3661 else if (!strcmp(arg, "--follow"))
3662 DIFF_OPT_SET(options, FOLLOW_RENAMES);
3663 else if (!strcmp(arg, "--color"))
3664 options->use_color = 1;
3665 else if (!prefixcmp(arg, "--color=")) {
3666 int value = git_config_colorbool(NULL, arg+8);
3667 if (value < 0)
3668 return error("option `color' expects \"always\", \"auto\", or \"never\"");
3669 options->use_color = value;
3671 else if (!strcmp(arg, "--no-color"))
3672 options->use_color = 0;
3673 else if (!strcmp(arg, "--color-words")) {
3674 options->use_color = 1;
3675 options->word_diff = DIFF_WORDS_COLOR;
3677 else if (!prefixcmp(arg, "--color-words=")) {
3678 options->use_color = 1;
3679 options->word_diff = DIFF_WORDS_COLOR;
3680 options->word_regex = arg + 14;
3682 else if (!strcmp(arg, "--word-diff")) {
3683 if (options->word_diff == DIFF_WORDS_NONE)
3684 options->word_diff = DIFF_WORDS_PLAIN;
3686 else if (!prefixcmp(arg, "--word-diff=")) {
3687 const char *type = arg + 12;
3688 if (!strcmp(type, "plain"))
3689 options->word_diff = DIFF_WORDS_PLAIN;
3690 else if (!strcmp(type, "color")) {
3691 options->use_color = 1;
3692 options->word_diff = DIFF_WORDS_COLOR;
3694 else if (!strcmp(type, "porcelain"))
3695 options->word_diff = DIFF_WORDS_PORCELAIN;
3696 else if (!strcmp(type, "none"))
3697 options->word_diff = DIFF_WORDS_NONE;
3698 else
3699 die("bad --word-diff argument: %s", type);
3701 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
3702 if (options->word_diff == DIFF_WORDS_NONE)
3703 options->word_diff = DIFF_WORDS_PLAIN;
3704 options->word_regex = optarg;
3705 return argcount;
3707 else if (!strcmp(arg, "--exit-code"))
3708 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3709 else if (!strcmp(arg, "--quiet"))
3710 DIFF_OPT_SET(options, QUICK);
3711 else if (!strcmp(arg, "--ext-diff"))
3712 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
3713 else if (!strcmp(arg, "--no-ext-diff"))
3714 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
3715 else if (!strcmp(arg, "--textconv"))
3716 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3717 else if (!strcmp(arg, "--no-textconv"))
3718 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
3719 else if (!strcmp(arg, "--ignore-submodules")) {
3720 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3721 handle_ignore_submodules_arg(options, "all");
3722 } else if (!prefixcmp(arg, "--ignore-submodules=")) {
3723 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3724 handle_ignore_submodules_arg(options, arg + 20);
3725 } else if (!strcmp(arg, "--submodule"))
3726 DIFF_OPT_SET(options, SUBMODULE_LOG);
3727 else if (!prefixcmp(arg, "--submodule="))
3728 return parse_submodule_opt(options, arg + 12);
3730 /* misc options */
3731 else if (!strcmp(arg, "-z"))
3732 options->line_termination = 0;
3733 else if ((argcount = short_opt('l', av, &optarg))) {
3734 options->rename_limit = strtoul(optarg, NULL, 10);
3735 return argcount;
3737 else if ((argcount = short_opt('S', av, &optarg))) {
3738 options->pickaxe = optarg;
3739 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
3740 return argcount;
3741 } else if ((argcount = short_opt('G', av, &optarg))) {
3742 options->pickaxe = optarg;
3743 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
3744 return argcount;
3746 else if (!strcmp(arg, "--pickaxe-all"))
3747 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
3748 else if (!strcmp(arg, "--pickaxe-regex"))
3749 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
3750 else if ((argcount = short_opt('O', av, &optarg))) {
3751 options->orderfile = optarg;
3752 return argcount;
3754 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
3755 options->filter = optarg;
3756 return argcount;
3758 else if (!strcmp(arg, "--abbrev"))
3759 options->abbrev = DEFAULT_ABBREV;
3760 else if (!prefixcmp(arg, "--abbrev=")) {
3761 options->abbrev = strtoul(arg + 9, NULL, 10);
3762 if (options->abbrev < MINIMUM_ABBREV)
3763 options->abbrev = MINIMUM_ABBREV;
3764 else if (40 < options->abbrev)
3765 options->abbrev = 40;
3767 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
3768 options->a_prefix = optarg;
3769 return argcount;
3771 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
3772 options->b_prefix = optarg;
3773 return argcount;
3775 else if (!strcmp(arg, "--no-prefix"))
3776 options->a_prefix = options->b_prefix = "";
3777 else if (opt_arg(arg, '\0', "inter-hunk-context",
3778 &options->interhunkcontext))
3780 else if (!strcmp(arg, "-W"))
3781 DIFF_OPT_SET(options, FUNCCONTEXT);
3782 else if (!strcmp(arg, "--function-context"))
3783 DIFF_OPT_SET(options, FUNCCONTEXT);
3784 else if (!strcmp(arg, "--no-function-context"))
3785 DIFF_OPT_CLR(options, FUNCCONTEXT);
3786 else if ((argcount = parse_long_opt("output", av, &optarg))) {
3787 options->file = fopen(optarg, "w");
3788 if (!options->file)
3789 die_errno("Could not open '%s'", optarg);
3790 options->close_file = 1;
3791 return argcount;
3792 } else
3793 return 0;
3794 return 1;
3797 int parse_rename_score(const char **cp_p)
3799 unsigned long num, scale;
3800 int ch, dot;
3801 const char *cp = *cp_p;
3803 num = 0;
3804 scale = 1;
3805 dot = 0;
3806 for (;;) {
3807 ch = *cp;
3808 if ( !dot && ch == '.' ) {
3809 scale = 1;
3810 dot = 1;
3811 } else if ( ch == '%' ) {
3812 scale = dot ? scale*100 : 100;
3813 cp++; /* % is always at the end */
3814 break;
3815 } else if ( ch >= '0' && ch <= '9' ) {
3816 if ( scale < 100000 ) {
3817 scale *= 10;
3818 num = (num*10) + (ch-'0');
3820 } else {
3821 break;
3823 cp++;
3825 *cp_p = cp;
3827 /* user says num divided by scale and we say internally that
3828 * is MAX_SCORE * num / scale.
3830 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3833 static int diff_scoreopt_parse(const char *opt)
3835 int opt1, opt2, cmd;
3837 if (*opt++ != '-')
3838 return -1;
3839 cmd = *opt++;
3840 if (cmd == '-') {
3841 /* convert the long-form arguments into short-form versions */
3842 if (!prefixcmp(opt, "break-rewrites")) {
3843 opt += strlen("break-rewrites");
3844 if (*opt == 0 || *opt++ == '=')
3845 cmd = 'B';
3846 } else if (!prefixcmp(opt, "find-copies")) {
3847 opt += strlen("find-copies");
3848 if (*opt == 0 || *opt++ == '=')
3849 cmd = 'C';
3850 } else if (!prefixcmp(opt, "find-renames")) {
3851 opt += strlen("find-renames");
3852 if (*opt == 0 || *opt++ == '=')
3853 cmd = 'M';
3856 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3857 return -1; /* that is not a -M, -C nor -B option */
3859 opt1 = parse_rename_score(&opt);
3860 if (cmd != 'B')
3861 opt2 = 0;
3862 else {
3863 if (*opt == 0)
3864 opt2 = 0;
3865 else if (*opt != '/')
3866 return -1; /* we expect -B80/99 or -B80 */
3867 else {
3868 opt++;
3869 opt2 = parse_rename_score(&opt);
3872 if (*opt != 0)
3873 return -1;
3874 return opt1 | (opt2 << 16);
3877 struct diff_queue_struct diff_queued_diff;
3879 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3881 if (queue->alloc <= queue->nr) {
3882 queue->alloc = alloc_nr(queue->alloc);
3883 queue->queue = xrealloc(queue->queue,
3884 sizeof(dp) * queue->alloc);
3886 queue->queue[queue->nr++] = dp;
3889 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3890 struct diff_filespec *one,
3891 struct diff_filespec *two)
3893 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3894 dp->one = one;
3895 dp->two = two;
3896 if (queue)
3897 diff_q(queue, dp);
3898 return dp;
3901 void diff_free_filepair(struct diff_filepair *p)
3903 free_filespec(p->one);
3904 free_filespec(p->two);
3905 free(p);
3908 /* This is different from find_unique_abbrev() in that
3909 * it stuffs the result with dots for alignment.
3911 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3913 int abblen;
3914 const char *abbrev;
3915 if (len == 40)
3916 return sha1_to_hex(sha1);
3918 abbrev = find_unique_abbrev(sha1, len);
3919 abblen = strlen(abbrev);
3920 if (abblen < 37) {
3921 static char hex[41];
3922 if (len < abblen && abblen <= len + 2)
3923 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3924 else
3925 sprintf(hex, "%s...", abbrev);
3926 return hex;
3928 return sha1_to_hex(sha1);
3931 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3933 int line_termination = opt->line_termination;
3934 int inter_name_termination = line_termination ? '\t' : '\0';
3935 if (opt->output_prefix) {
3936 struct strbuf *msg = NULL;
3937 msg = opt->output_prefix(opt, opt->output_prefix_data);
3938 fprintf(opt->file, "%s", msg->buf);
3941 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3942 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3943 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3944 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3946 if (p->score) {
3947 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3948 inter_name_termination);
3949 } else {
3950 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3953 if (p->status == DIFF_STATUS_COPIED ||
3954 p->status == DIFF_STATUS_RENAMED) {
3955 const char *name_a, *name_b;
3956 name_a = p->one->path;
3957 name_b = p->two->path;
3958 strip_prefix(opt->prefix_length, &name_a, &name_b);
3959 write_name_quoted(name_a, opt->file, inter_name_termination);
3960 write_name_quoted(name_b, opt->file, line_termination);
3961 } else {
3962 const char *name_a, *name_b;
3963 name_a = p->one->mode ? p->one->path : p->two->path;
3964 name_b = NULL;
3965 strip_prefix(opt->prefix_length, &name_a, &name_b);
3966 write_name_quoted(name_a, opt->file, line_termination);
3970 int diff_unmodified_pair(struct diff_filepair *p)
3972 /* This function is written stricter than necessary to support
3973 * the currently implemented transformers, but the idea is to
3974 * let transformers to produce diff_filepairs any way they want,
3975 * and filter and clean them up here before producing the output.
3977 struct diff_filespec *one = p->one, *two = p->two;
3979 if (DIFF_PAIR_UNMERGED(p))
3980 return 0; /* unmerged is interesting */
3982 /* deletion, addition, mode or type change
3983 * and rename are all interesting.
3985 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3986 DIFF_PAIR_MODE_CHANGED(p) ||
3987 strcmp(one->path, two->path))
3988 return 0;
3990 /* both are valid and point at the same path. that is, we are
3991 * dealing with a change.
3993 if (one->sha1_valid && two->sha1_valid &&
3994 !hashcmp(one->sha1, two->sha1) &&
3995 !one->dirty_submodule && !two->dirty_submodule)
3996 return 1; /* no change */
3997 if (!one->sha1_valid && !two->sha1_valid)
3998 return 1; /* both look at the same file on the filesystem. */
3999 return 0;
4002 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
4004 if (diff_unmodified_pair(p))
4005 return;
4007 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4008 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4009 return; /* no tree diffs in patch format */
4011 run_diff(p, o);
4014 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
4015 struct diffstat_t *diffstat)
4017 if (diff_unmodified_pair(p))
4018 return;
4020 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4021 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4022 return; /* no useful stat for tree diffs */
4024 run_diffstat(p, o, diffstat);
4027 static void diff_flush_checkdiff(struct diff_filepair *p,
4028 struct diff_options *o)
4030 if (diff_unmodified_pair(p))
4031 return;
4033 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4034 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4035 return; /* nothing to check in tree diffs */
4037 run_checkdiff(p, o);
4040 int diff_queue_is_empty(void)
4042 struct diff_queue_struct *q = &diff_queued_diff;
4043 int i;
4044 for (i = 0; i < q->nr; i++)
4045 if (!diff_unmodified_pair(q->queue[i]))
4046 return 0;
4047 return 1;
4050 #if DIFF_DEBUG
4051 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
4053 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
4054 x, one ? one : "",
4055 s->path,
4056 DIFF_FILE_VALID(s) ? "valid" : "invalid",
4057 s->mode,
4058 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
4059 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
4060 x, one ? one : "",
4061 s->size, s->xfrm_flags);
4064 void diff_debug_filepair(const struct diff_filepair *p, int i)
4066 diff_debug_filespec(p->one, i, "one");
4067 diff_debug_filespec(p->two, i, "two");
4068 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
4069 p->score, p->status ? p->status : '?',
4070 p->one->rename_used, p->broken_pair);
4073 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
4075 int i;
4076 if (msg)
4077 fprintf(stderr, "%s\n", msg);
4078 fprintf(stderr, "q->nr = %d\n", q->nr);
4079 for (i = 0; i < q->nr; i++) {
4080 struct diff_filepair *p = q->queue[i];
4081 diff_debug_filepair(p, i);
4084 #endif
4086 static void diff_resolve_rename_copy(void)
4088 int i;
4089 struct diff_filepair *p;
4090 struct diff_queue_struct *q = &diff_queued_diff;
4092 diff_debug_queue("resolve-rename-copy", q);
4094 for (i = 0; i < q->nr; i++) {
4095 p = q->queue[i];
4096 p->status = 0; /* undecided */
4097 if (DIFF_PAIR_UNMERGED(p))
4098 p->status = DIFF_STATUS_UNMERGED;
4099 else if (!DIFF_FILE_VALID(p->one))
4100 p->status = DIFF_STATUS_ADDED;
4101 else if (!DIFF_FILE_VALID(p->two))
4102 p->status = DIFF_STATUS_DELETED;
4103 else if (DIFF_PAIR_TYPE_CHANGED(p))
4104 p->status = DIFF_STATUS_TYPE_CHANGED;
4106 /* from this point on, we are dealing with a pair
4107 * whose both sides are valid and of the same type, i.e.
4108 * either in-place edit or rename/copy edit.
4110 else if (DIFF_PAIR_RENAME(p)) {
4112 * A rename might have re-connected a broken
4113 * pair up, causing the pathnames to be the
4114 * same again. If so, that's not a rename at
4115 * all, just a modification..
4117 * Otherwise, see if this source was used for
4118 * multiple renames, in which case we decrement
4119 * the count, and call it a copy.
4121 if (!strcmp(p->one->path, p->two->path))
4122 p->status = DIFF_STATUS_MODIFIED;
4123 else if (--p->one->rename_used > 0)
4124 p->status = DIFF_STATUS_COPIED;
4125 else
4126 p->status = DIFF_STATUS_RENAMED;
4128 else if (hashcmp(p->one->sha1, p->two->sha1) ||
4129 p->one->mode != p->two->mode ||
4130 p->one->dirty_submodule ||
4131 p->two->dirty_submodule ||
4132 is_null_sha1(p->one->sha1))
4133 p->status = DIFF_STATUS_MODIFIED;
4134 else {
4135 /* This is a "no-change" entry and should not
4136 * happen anymore, but prepare for broken callers.
4138 error("feeding unmodified %s to diffcore",
4139 p->one->path);
4140 p->status = DIFF_STATUS_UNKNOWN;
4143 diff_debug_queue("resolve-rename-copy done", q);
4146 static int check_pair_status(struct diff_filepair *p)
4148 switch (p->status) {
4149 case DIFF_STATUS_UNKNOWN:
4150 return 0;
4151 case 0:
4152 die("internal error in diff-resolve-rename-copy");
4153 default:
4154 return 1;
4158 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4160 int fmt = opt->output_format;
4162 if (fmt & DIFF_FORMAT_CHECKDIFF)
4163 diff_flush_checkdiff(p, opt);
4164 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4165 diff_flush_raw(p, opt);
4166 else if (fmt & DIFF_FORMAT_NAME) {
4167 const char *name_a, *name_b;
4168 name_a = p->two->path;
4169 name_b = NULL;
4170 strip_prefix(opt->prefix_length, &name_a, &name_b);
4171 write_name_quoted(name_a, opt->file, opt->line_termination);
4175 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4177 if (fs->mode)
4178 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4179 else
4180 fprintf(file, " %s ", newdelete);
4181 write_name_quoted(fs->path, file, '\n');
4185 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
4186 const char *line_prefix)
4188 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
4189 fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
4190 p->two->mode, show_name ? ' ' : '\n');
4191 if (show_name) {
4192 write_name_quoted(p->two->path, file, '\n');
4197 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
4198 const char *line_prefix)
4200 char *names = pprint_rename(p->one->path, p->two->path);
4202 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
4203 free(names);
4204 show_mode_change(file, p, 0, line_prefix);
4207 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4209 FILE *file = opt->file;
4210 char *line_prefix = "";
4212 if (opt->output_prefix) {
4213 struct strbuf *buf = opt->output_prefix(opt, opt->output_prefix_data);
4214 line_prefix = buf->buf;
4217 switch(p->status) {
4218 case DIFF_STATUS_DELETED:
4219 fputs(line_prefix, file);
4220 show_file_mode_name(file, "delete", p->one);
4221 break;
4222 case DIFF_STATUS_ADDED:
4223 fputs(line_prefix, file);
4224 show_file_mode_name(file, "create", p->two);
4225 break;
4226 case DIFF_STATUS_COPIED:
4227 fputs(line_prefix, file);
4228 show_rename_copy(file, "copy", p, line_prefix);
4229 break;
4230 case DIFF_STATUS_RENAMED:
4231 fputs(line_prefix, file);
4232 show_rename_copy(file, "rename", p, line_prefix);
4233 break;
4234 default:
4235 if (p->score) {
4236 fprintf(file, "%s rewrite ", line_prefix);
4237 write_name_quoted(p->two->path, file, ' ');
4238 fprintf(file, "(%d%%)\n", similarity_index(p));
4240 show_mode_change(file, p, !p->score, line_prefix);
4241 break;
4245 struct patch_id_t {
4246 git_SHA_CTX *ctx;
4247 int patchlen;
4250 static int remove_space(char *line, int len)
4252 int i;
4253 char *dst = line;
4254 unsigned char c;
4256 for (i = 0; i < len; i++)
4257 if (!isspace((c = line[i])))
4258 *dst++ = c;
4260 return dst - line;
4263 static void patch_id_consume(void *priv, char *line, unsigned long len)
4265 struct patch_id_t *data = priv;
4266 int new_len;
4268 /* Ignore line numbers when computing the SHA1 of the patch */
4269 if (!prefixcmp(line, "@@ -"))
4270 return;
4272 new_len = remove_space(line, len);
4274 git_SHA1_Update(data->ctx, line, new_len);
4275 data->patchlen += new_len;
4278 /* returns 0 upon success, and writes result into sha1 */
4279 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
4281 struct diff_queue_struct *q = &diff_queued_diff;
4282 int i;
4283 git_SHA_CTX ctx;
4284 struct patch_id_t data;
4285 char buffer[PATH_MAX * 4 + 20];
4287 git_SHA1_Init(&ctx);
4288 memset(&data, 0, sizeof(struct patch_id_t));
4289 data.ctx = &ctx;
4291 for (i = 0; i < q->nr; i++) {
4292 xpparam_t xpp;
4293 xdemitconf_t xecfg;
4294 mmfile_t mf1, mf2;
4295 struct diff_filepair *p = q->queue[i];
4296 int len1, len2;
4298 memset(&xpp, 0, sizeof(xpp));
4299 memset(&xecfg, 0, sizeof(xecfg));
4300 if (p->status == 0)
4301 return error("internal diff status error");
4302 if (p->status == DIFF_STATUS_UNKNOWN)
4303 continue;
4304 if (diff_unmodified_pair(p))
4305 continue;
4306 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4307 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4308 continue;
4309 if (DIFF_PAIR_UNMERGED(p))
4310 continue;
4312 diff_fill_sha1_info(p->one);
4313 diff_fill_sha1_info(p->two);
4314 if (fill_mmfile(&mf1, p->one) < 0 ||
4315 fill_mmfile(&mf2, p->two) < 0)
4316 return error("unable to read files to diff");
4318 len1 = remove_space(p->one->path, strlen(p->one->path));
4319 len2 = remove_space(p->two->path, strlen(p->two->path));
4320 if (p->one->mode == 0)
4321 len1 = snprintf(buffer, sizeof(buffer),
4322 "diff--gita/%.*sb/%.*s"
4323 "newfilemode%06o"
4324 "---/dev/null"
4325 "+++b/%.*s",
4326 len1, p->one->path,
4327 len2, p->two->path,
4328 p->two->mode,
4329 len2, p->two->path);
4330 else if (p->two->mode == 0)
4331 len1 = snprintf(buffer, sizeof(buffer),
4332 "diff--gita/%.*sb/%.*s"
4333 "deletedfilemode%06o"
4334 "---a/%.*s"
4335 "+++/dev/null",
4336 len1, p->one->path,
4337 len2, p->two->path,
4338 p->one->mode,
4339 len1, p->one->path);
4340 else
4341 len1 = snprintf(buffer, sizeof(buffer),
4342 "diff--gita/%.*sb/%.*s"
4343 "---a/%.*s"
4344 "+++b/%.*s",
4345 len1, p->one->path,
4346 len2, p->two->path,
4347 len1, p->one->path,
4348 len2, p->two->path);
4349 git_SHA1_Update(&ctx, buffer, len1);
4351 if (diff_filespec_is_binary(p->one) ||
4352 diff_filespec_is_binary(p->two)) {
4353 git_SHA1_Update(&ctx, sha1_to_hex(p->one->sha1), 40);
4354 git_SHA1_Update(&ctx, sha1_to_hex(p->two->sha1), 40);
4355 continue;
4358 xpp.flags = 0;
4359 xecfg.ctxlen = 3;
4360 xecfg.flags = 0;
4361 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
4362 &xpp, &xecfg);
4365 git_SHA1_Final(sha1, &ctx);
4366 return 0;
4369 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
4371 struct diff_queue_struct *q = &diff_queued_diff;
4372 int i;
4373 int result = diff_get_patch_id(options, sha1);
4375 for (i = 0; i < q->nr; i++)
4376 diff_free_filepair(q->queue[i]);
4378 free(q->queue);
4379 DIFF_QUEUE_CLEAR(q);
4381 return result;
4384 static int is_summary_empty(const struct diff_queue_struct *q)
4386 int i;
4388 for (i = 0; i < q->nr; i++) {
4389 const struct diff_filepair *p = q->queue[i];
4391 switch (p->status) {
4392 case DIFF_STATUS_DELETED:
4393 case DIFF_STATUS_ADDED:
4394 case DIFF_STATUS_COPIED:
4395 case DIFF_STATUS_RENAMED:
4396 return 0;
4397 default:
4398 if (p->score)
4399 return 0;
4400 if (p->one->mode && p->two->mode &&
4401 p->one->mode != p->two->mode)
4402 return 0;
4403 break;
4406 return 1;
4409 static const char rename_limit_warning[] =
4410 "inexact rename detection was skipped due to too many files.";
4412 static const char degrade_cc_to_c_warning[] =
4413 "only found copies from modified paths due to too many files.";
4415 static const char rename_limit_advice[] =
4416 "you may want to set your %s variable to at least "
4417 "%d and retry the command.";
4419 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4421 if (degraded_cc)
4422 warning(degrade_cc_to_c_warning);
4423 else if (needed)
4424 warning(rename_limit_warning);
4425 else
4426 return;
4427 if (0 < needed && needed < 32767)
4428 warning(rename_limit_advice, varname, needed);
4431 void diff_flush(struct diff_options *options)
4433 struct diff_queue_struct *q = &diff_queued_diff;
4434 int i, output_format = options->output_format;
4435 int separator = 0;
4436 int dirstat_by_line = 0;
4439 * Order: raw, stat, summary, patch
4440 * or: name/name-status/checkdiff (other bits clear)
4442 if (!q->nr)
4443 goto free_queue;
4445 if (output_format & (DIFF_FORMAT_RAW |
4446 DIFF_FORMAT_NAME |
4447 DIFF_FORMAT_NAME_STATUS |
4448 DIFF_FORMAT_CHECKDIFF)) {
4449 for (i = 0; i < q->nr; i++) {
4450 struct diff_filepair *p = q->queue[i];
4451 if (check_pair_status(p))
4452 flush_one_pair(p, options);
4454 separator++;
4457 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
4458 dirstat_by_line = 1;
4460 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
4461 dirstat_by_line) {
4462 struct diffstat_t diffstat;
4464 memset(&diffstat, 0, sizeof(struct diffstat_t));
4465 for (i = 0; i < q->nr; i++) {
4466 struct diff_filepair *p = q->queue[i];
4467 if (check_pair_status(p))
4468 diff_flush_stat(p, options, &diffstat);
4470 if (output_format & DIFF_FORMAT_NUMSTAT)
4471 show_numstat(&diffstat, options);
4472 if (output_format & DIFF_FORMAT_DIFFSTAT)
4473 show_stats(&diffstat, options);
4474 if (output_format & DIFF_FORMAT_SHORTSTAT)
4475 show_shortstats(&diffstat, options);
4476 if (output_format & DIFF_FORMAT_DIRSTAT)
4477 show_dirstat_by_line(&diffstat, options);
4478 free_diffstat_info(&diffstat);
4479 separator++;
4481 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
4482 show_dirstat(options);
4484 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
4485 for (i = 0; i < q->nr; i++) {
4486 diff_summary(options, q->queue[i]);
4488 separator++;
4491 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
4492 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
4493 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4495 * run diff_flush_patch for the exit status. setting
4496 * options->file to /dev/null should be safe, becaue we
4497 * aren't supposed to produce any output anyway.
4499 if (options->close_file)
4500 fclose(options->file);
4501 options->file = fopen("/dev/null", "w");
4502 if (!options->file)
4503 die_errno("Could not open /dev/null");
4504 options->close_file = 1;
4505 for (i = 0; i < q->nr; i++) {
4506 struct diff_filepair *p = q->queue[i];
4507 if (check_pair_status(p))
4508 diff_flush_patch(p, options);
4509 if (options->found_changes)
4510 break;
4514 if (output_format & DIFF_FORMAT_PATCH) {
4515 if (separator) {
4516 if (options->output_prefix) {
4517 struct strbuf *msg = NULL;
4518 msg = options->output_prefix(options,
4519 options->output_prefix_data);
4520 fwrite(msg->buf, msg->len, 1, stdout);
4522 putc(options->line_termination, options->file);
4523 if (options->stat_sep) {
4524 /* attach patch instead of inline */
4525 fputs(options->stat_sep, options->file);
4529 for (i = 0; i < q->nr; i++) {
4530 struct diff_filepair *p = q->queue[i];
4531 if (check_pair_status(p))
4532 diff_flush_patch(p, options);
4536 if (output_format & DIFF_FORMAT_CALLBACK)
4537 options->format_callback(q, options, options->format_callback_data);
4539 for (i = 0; i < q->nr; i++)
4540 diff_free_filepair(q->queue[i]);
4541 free_queue:
4542 free(q->queue);
4543 DIFF_QUEUE_CLEAR(q);
4544 if (options->close_file)
4545 fclose(options->file);
4548 * Report the content-level differences with HAS_CHANGES;
4549 * diff_addremove/diff_change does not set the bit when
4550 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
4552 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4553 if (options->found_changes)
4554 DIFF_OPT_SET(options, HAS_CHANGES);
4555 else
4556 DIFF_OPT_CLR(options, HAS_CHANGES);
4560 static void diffcore_apply_filter(const char *filter)
4562 int i;
4563 struct diff_queue_struct *q = &diff_queued_diff;
4564 struct diff_queue_struct outq;
4565 DIFF_QUEUE_CLEAR(&outq);
4567 if (!filter)
4568 return;
4570 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
4571 int found;
4572 for (i = found = 0; !found && i < q->nr; i++) {
4573 struct diff_filepair *p = q->queue[i];
4574 if (((p->status == DIFF_STATUS_MODIFIED) &&
4575 ((p->score &&
4576 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4577 (!p->score &&
4578 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4579 ((p->status != DIFF_STATUS_MODIFIED) &&
4580 strchr(filter, p->status)))
4581 found++;
4583 if (found)
4584 return;
4586 /* otherwise we will clear the whole queue
4587 * by copying the empty outq at the end of this
4588 * function, but first clear the current entries
4589 * in the queue.
4591 for (i = 0; i < q->nr; i++)
4592 diff_free_filepair(q->queue[i]);
4594 else {
4595 /* Only the matching ones */
4596 for (i = 0; i < q->nr; i++) {
4597 struct diff_filepair *p = q->queue[i];
4599 if (((p->status == DIFF_STATUS_MODIFIED) &&
4600 ((p->score &&
4601 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4602 (!p->score &&
4603 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4604 ((p->status != DIFF_STATUS_MODIFIED) &&
4605 strchr(filter, p->status)))
4606 diff_q(&outq, p);
4607 else
4608 diff_free_filepair(p);
4611 free(q->queue);
4612 *q = outq;
4615 /* Check whether two filespecs with the same mode and size are identical */
4616 static int diff_filespec_is_identical(struct diff_filespec *one,
4617 struct diff_filespec *two)
4619 if (S_ISGITLINK(one->mode))
4620 return 0;
4621 if (diff_populate_filespec(one, 0))
4622 return 0;
4623 if (diff_populate_filespec(two, 0))
4624 return 0;
4625 return !memcmp(one->data, two->data, one->size);
4628 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
4630 int i;
4631 struct diff_queue_struct *q = &diff_queued_diff;
4632 struct diff_queue_struct outq;
4633 DIFF_QUEUE_CLEAR(&outq);
4635 for (i = 0; i < q->nr; i++) {
4636 struct diff_filepair *p = q->queue[i];
4639 * 1. Entries that come from stat info dirtiness
4640 * always have both sides (iow, not create/delete),
4641 * one side of the object name is unknown, with
4642 * the same mode and size. Keep the ones that
4643 * do not match these criteria. They have real
4644 * differences.
4646 * 2. At this point, the file is known to be modified,
4647 * with the same mode and size, and the object
4648 * name of one side is unknown. Need to inspect
4649 * the identical contents.
4651 if (!DIFF_FILE_VALID(p->one) || /* (1) */
4652 !DIFF_FILE_VALID(p->two) ||
4653 (p->one->sha1_valid && p->two->sha1_valid) ||
4654 (p->one->mode != p->two->mode) ||
4655 diff_populate_filespec(p->one, 1) ||
4656 diff_populate_filespec(p->two, 1) ||
4657 (p->one->size != p->two->size) ||
4658 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
4659 diff_q(&outq, p);
4660 else {
4662 * The caller can subtract 1 from skip_stat_unmatch
4663 * to determine how many paths were dirty only
4664 * due to stat info mismatch.
4666 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
4667 diffopt->skip_stat_unmatch++;
4668 diff_free_filepair(p);
4671 free(q->queue);
4672 *q = outq;
4675 static int diffnamecmp(const void *a_, const void *b_)
4677 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4678 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4679 const char *name_a, *name_b;
4681 name_a = a->one ? a->one->path : a->two->path;
4682 name_b = b->one ? b->one->path : b->two->path;
4683 return strcmp(name_a, name_b);
4686 void diffcore_fix_diff_index(struct diff_options *options)
4688 struct diff_queue_struct *q = &diff_queued_diff;
4689 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
4692 void diffcore_std(struct diff_options *options)
4694 if (options->skip_stat_unmatch)
4695 diffcore_skip_stat_unmatch(options);
4696 if (!options->found_follow) {
4697 /* See try_to_follow_renames() in tree-diff.c */
4698 if (options->break_opt != -1)
4699 diffcore_break(options->break_opt);
4700 if (options->detect_rename)
4701 diffcore_rename(options);
4702 if (options->break_opt != -1)
4703 diffcore_merge_broken();
4705 if (options->pickaxe)
4706 diffcore_pickaxe(options);
4707 if (options->orderfile)
4708 diffcore_order(options->orderfile);
4709 if (!options->found_follow)
4710 /* See try_to_follow_renames() in tree-diff.c */
4711 diff_resolve_rename_copy();
4712 diffcore_apply_filter(options->filter);
4714 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4715 DIFF_OPT_SET(options, HAS_CHANGES);
4716 else
4717 DIFF_OPT_CLR(options, HAS_CHANGES);
4719 options->found_follow = 0;
4722 int diff_result_code(struct diff_options *opt, int status)
4724 int result = 0;
4726 diff_warn_rename_limit("diff.renamelimit",
4727 opt->needed_rename_limit,
4728 opt->degraded_cc_to_c);
4729 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4730 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
4731 return status;
4732 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4733 DIFF_OPT_TST(opt, HAS_CHANGES))
4734 result |= 01;
4735 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4736 DIFF_OPT_TST(opt, CHECK_FAILED))
4737 result |= 02;
4738 return result;
4741 int diff_can_quit_early(struct diff_options *opt)
4743 return (DIFF_OPT_TST(opt, QUICK) &&
4744 !opt->filter &&
4745 DIFF_OPT_TST(opt, HAS_CHANGES));
4749 * Shall changes to this submodule be ignored?
4751 * Submodule changes can be configured to be ignored separately for each path,
4752 * but that configuration can be overridden from the command line.
4754 static int is_submodule_ignored(const char *path, struct diff_options *options)
4756 int ignored = 0;
4757 unsigned orig_flags = options->flags;
4758 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
4759 set_diffopt_flags_from_submodule_config(options, path);
4760 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
4761 ignored = 1;
4762 options->flags = orig_flags;
4763 return ignored;
4766 void diff_addremove(struct diff_options *options,
4767 int addremove, unsigned mode,
4768 const unsigned char *sha1,
4769 int sha1_valid,
4770 const char *concatpath, unsigned dirty_submodule)
4772 struct diff_filespec *one, *two;
4774 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
4775 return;
4777 /* This may look odd, but it is a preparation for
4778 * feeding "there are unchanged files which should
4779 * not produce diffs, but when you are doing copy
4780 * detection you would need them, so here they are"
4781 * entries to the diff-core. They will be prefixed
4782 * with something like '=' or '*' (I haven't decided
4783 * which but should not make any difference).
4784 * Feeding the same new and old to diff_change()
4785 * also has the same effect.
4786 * Before the final output happens, they are pruned after
4787 * merged into rename/copy pairs as appropriate.
4789 if (DIFF_OPT_TST(options, REVERSE_DIFF))
4790 addremove = (addremove == '+' ? '-' :
4791 addremove == '-' ? '+' : addremove);
4793 if (options->prefix &&
4794 strncmp(concatpath, options->prefix, options->prefix_length))
4795 return;
4797 one = alloc_filespec(concatpath);
4798 two = alloc_filespec(concatpath);
4800 if (addremove != '+')
4801 fill_filespec(one, sha1, sha1_valid, mode);
4802 if (addremove != '-') {
4803 fill_filespec(two, sha1, sha1_valid, mode);
4804 two->dirty_submodule = dirty_submodule;
4807 diff_queue(&diff_queued_diff, one, two);
4808 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4809 DIFF_OPT_SET(options, HAS_CHANGES);
4812 void diff_change(struct diff_options *options,
4813 unsigned old_mode, unsigned new_mode,
4814 const unsigned char *old_sha1,
4815 const unsigned char *new_sha1,
4816 int old_sha1_valid, int new_sha1_valid,
4817 const char *concatpath,
4818 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
4820 struct diff_filespec *one, *two;
4822 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
4823 is_submodule_ignored(concatpath, options))
4824 return;
4826 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
4827 unsigned tmp;
4828 const unsigned char *tmp_c;
4829 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
4830 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
4831 tmp = old_sha1_valid; old_sha1_valid = new_sha1_valid;
4832 new_sha1_valid = tmp;
4833 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
4834 new_dirty_submodule = tmp;
4837 if (options->prefix &&
4838 strncmp(concatpath, options->prefix, options->prefix_length))
4839 return;
4841 one = alloc_filespec(concatpath);
4842 two = alloc_filespec(concatpath);
4843 fill_filespec(one, old_sha1, old_sha1_valid, old_mode);
4844 fill_filespec(two, new_sha1, new_sha1_valid, new_mode);
4845 one->dirty_submodule = old_dirty_submodule;
4846 two->dirty_submodule = new_dirty_submodule;
4848 diff_queue(&diff_queued_diff, one, two);
4849 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4850 DIFF_OPT_SET(options, HAS_CHANGES);
4853 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
4855 struct diff_filepair *pair;
4856 struct diff_filespec *one, *two;
4858 if (options->prefix &&
4859 strncmp(path, options->prefix, options->prefix_length))
4860 return NULL;
4862 one = alloc_filespec(path);
4863 two = alloc_filespec(path);
4864 pair = diff_queue(&diff_queued_diff, one, two);
4865 pair->is_unmerged = 1;
4866 return pair;
4869 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
4870 size_t *outsize)
4872 struct diff_tempfile *temp;
4873 const char *argv[3];
4874 const char **arg = argv;
4875 struct child_process child;
4876 struct strbuf buf = STRBUF_INIT;
4877 int err = 0;
4879 temp = prepare_temp_file(spec->path, spec);
4880 *arg++ = pgm;
4881 *arg++ = temp->name;
4882 *arg = NULL;
4884 memset(&child, 0, sizeof(child));
4885 child.use_shell = 1;
4886 child.argv = argv;
4887 child.out = -1;
4888 if (start_command(&child)) {
4889 remove_tempfile();
4890 return NULL;
4893 if (strbuf_read(&buf, child.out, 0) < 0)
4894 err = error("error reading from textconv command '%s'", pgm);
4895 close(child.out);
4897 if (finish_command(&child) || err) {
4898 strbuf_release(&buf);
4899 remove_tempfile();
4900 return NULL;
4902 remove_tempfile();
4904 return strbuf_detach(&buf, outsize);
4907 size_t fill_textconv(struct userdiff_driver *driver,
4908 struct diff_filespec *df,
4909 char **outbuf)
4911 size_t size;
4913 if (!driver || !driver->textconv) {
4914 if (!DIFF_FILE_VALID(df)) {
4915 *outbuf = "";
4916 return 0;
4918 if (diff_populate_filespec(df, 0))
4919 die("unable to read files to diff");
4920 *outbuf = df->data;
4921 return df->size;
4924 if (driver->textconv_cache && df->sha1_valid) {
4925 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4926 &size);
4927 if (*outbuf)
4928 return size;
4931 *outbuf = run_textconv(driver->textconv, df, &size);
4932 if (!*outbuf)
4933 die("unable to read files to diff");
4935 if (driver->textconv_cache && df->sha1_valid) {
4936 /* ignore errors, as we might be in a readonly repository */
4937 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4938 size);
4940 * we could save up changes and flush them all at the end,
4941 * but we would need an extra call after all diffing is done.
4942 * Since generating a cache entry is the slow path anyway,
4943 * this extra overhead probably isn't a big deal.
4945 notes_cache_write(driver->textconv_cache);
4948 return size;
4951 void setup_diff_pager(struct diff_options *opt)
4954 * If the user asked for our exit code, then either they want --quiet
4955 * or --exit-code. We should definitely not bother with a pager in the
4956 * former case, as we will generate no output. Since we still properly
4957 * report our exit code even when a pager is run, we _could_ run a
4958 * pager with --exit-code. But since we have not done so historically,
4959 * and because it is easy to find people oneline advising "git diff
4960 * --exit-code" in hooks and other scripts, we do not do so.
4962 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4963 check_pager_config("diff") != 0)
4964 setup_pager();