transport: compute summary-width dynamically
[git.git] / diff.c
blobcefc13eb8e811a5a5021fcd9573d5fd3c9a37bae
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "tempfile.h"
6 #include "quote.h"
7 #include "diff.h"
8 #include "diffcore.h"
9 #include "delta.h"
10 #include "xdiff-interface.h"
11 #include "color.h"
12 #include "attr.h"
13 #include "run-command.h"
14 #include "utf8.h"
15 #include "userdiff.h"
16 #include "submodule-config.h"
17 #include "submodule.h"
18 #include "ll-merge.h"
19 #include "string-list.h"
20 #include "argv-array.h"
21 #include "graph.h"
23 #ifdef NO_FAST_WORKING_DIRECTORY
24 #define FAST_WORKING_DIRECTORY 0
25 #else
26 #define FAST_WORKING_DIRECTORY 1
27 #endif
29 static int diff_detect_rename_default;
30 static int diff_compaction_heuristic; /* experimental */
31 static int diff_rename_limit_default = 400;
32 static int diff_suppress_blank_empty;
33 static int diff_use_color_default = -1;
34 static int diff_context_default = 3;
35 static const char *diff_word_regex_cfg;
36 static const char *external_diff_cmd_cfg;
37 static const char *diff_order_file_cfg;
38 int diff_auto_refresh_index = 1;
39 static int diff_mnemonic_prefix;
40 static int diff_no_prefix;
41 static int diff_stat_graph_width;
42 static int diff_dirstat_permille_default = 30;
43 static struct diff_options default_diff_options;
44 static long diff_algorithm;
46 static char diff_colors[][COLOR_MAXLEN] = {
47 GIT_COLOR_RESET,
48 GIT_COLOR_NORMAL, /* CONTEXT */
49 GIT_COLOR_BOLD, /* METAINFO */
50 GIT_COLOR_CYAN, /* FRAGINFO */
51 GIT_COLOR_RED, /* OLD */
52 GIT_COLOR_GREEN, /* NEW */
53 GIT_COLOR_YELLOW, /* COMMIT */
54 GIT_COLOR_BG_RED, /* WHITESPACE */
55 GIT_COLOR_NORMAL, /* FUNCINFO */
58 static int parse_diff_color_slot(const char *var)
60 if (!strcasecmp(var, "context") || !strcasecmp(var, "plain"))
61 return DIFF_CONTEXT;
62 if (!strcasecmp(var, "meta"))
63 return DIFF_METAINFO;
64 if (!strcasecmp(var, "frag"))
65 return DIFF_FRAGINFO;
66 if (!strcasecmp(var, "old"))
67 return DIFF_FILE_OLD;
68 if (!strcasecmp(var, "new"))
69 return DIFF_FILE_NEW;
70 if (!strcasecmp(var, "commit"))
71 return DIFF_COMMIT;
72 if (!strcasecmp(var, "whitespace"))
73 return DIFF_WHITESPACE;
74 if (!strcasecmp(var, "func"))
75 return DIFF_FUNCINFO;
76 return -1;
79 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
80 struct strbuf *errmsg)
82 char *params_copy = xstrdup(params_string);
83 struct string_list params = STRING_LIST_INIT_NODUP;
84 int ret = 0;
85 int i;
87 if (*params_copy)
88 string_list_split_in_place(&params, params_copy, ',', -1);
89 for (i = 0; i < params.nr; i++) {
90 const char *p = params.items[i].string;
91 if (!strcmp(p, "changes")) {
92 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
93 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
94 } else if (!strcmp(p, "lines")) {
95 DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
96 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
97 } else if (!strcmp(p, "files")) {
98 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
99 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
100 } else if (!strcmp(p, "noncumulative")) {
101 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
102 } else if (!strcmp(p, "cumulative")) {
103 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
104 } else if (isdigit(*p)) {
105 char *end;
106 int permille = strtoul(p, &end, 10) * 10;
107 if (*end == '.' && isdigit(*++end)) {
108 /* only use first digit */
109 permille += *end - '0';
110 /* .. and ignore any further digits */
111 while (isdigit(*++end))
112 ; /* nothing */
114 if (!*end)
115 options->dirstat_permille = permille;
116 else {
117 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
119 ret++;
121 } else {
122 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
123 ret++;
127 string_list_clear(&params, 0);
128 free(params_copy);
129 return ret;
132 static int parse_submodule_params(struct diff_options *options, const char *value)
134 if (!strcmp(value, "log"))
135 options->submodule_format = DIFF_SUBMODULE_LOG;
136 else if (!strcmp(value, "short"))
137 options->submodule_format = DIFF_SUBMODULE_SHORT;
138 else if (!strcmp(value, "diff"))
139 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
140 else
141 return -1;
142 return 0;
145 static int git_config_rename(const char *var, const char *value)
147 if (!value)
148 return DIFF_DETECT_RENAME;
149 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
150 return DIFF_DETECT_COPY;
151 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
154 long parse_algorithm_value(const char *value)
156 if (!value)
157 return -1;
158 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
159 return 0;
160 else if (!strcasecmp(value, "minimal"))
161 return XDF_NEED_MINIMAL;
162 else if (!strcasecmp(value, "patience"))
163 return XDF_PATIENCE_DIFF;
164 else if (!strcasecmp(value, "histogram"))
165 return XDF_HISTOGRAM_DIFF;
166 return -1;
170 * These are to give UI layer defaults.
171 * The core-level commands such as git-diff-files should
172 * never be affected by the setting of diff.renames
173 * the user happens to have in the configuration file.
175 void init_diff_ui_defaults(void)
177 diff_detect_rename_default = 1;
180 int git_diff_ui_config(const char *var, const char *value, void *cb)
182 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
183 diff_use_color_default = git_config_colorbool(var, value);
184 return 0;
186 if (!strcmp(var, "diff.context")) {
187 diff_context_default = git_config_int(var, value);
188 if (diff_context_default < 0)
189 return -1;
190 return 0;
192 if (!strcmp(var, "diff.renames")) {
193 diff_detect_rename_default = git_config_rename(var, value);
194 return 0;
196 if (!strcmp(var, "diff.compactionheuristic")) {
197 diff_compaction_heuristic = git_config_bool(var, value);
198 return 0;
200 if (!strcmp(var, "diff.autorefreshindex")) {
201 diff_auto_refresh_index = git_config_bool(var, value);
202 return 0;
204 if (!strcmp(var, "diff.mnemonicprefix")) {
205 diff_mnemonic_prefix = git_config_bool(var, value);
206 return 0;
208 if (!strcmp(var, "diff.noprefix")) {
209 diff_no_prefix = git_config_bool(var, value);
210 return 0;
212 if (!strcmp(var, "diff.statgraphwidth")) {
213 diff_stat_graph_width = git_config_int(var, value);
214 return 0;
216 if (!strcmp(var, "diff.external"))
217 return git_config_string(&external_diff_cmd_cfg, var, value);
218 if (!strcmp(var, "diff.wordregex"))
219 return git_config_string(&diff_word_regex_cfg, var, value);
220 if (!strcmp(var, "diff.orderfile"))
221 return git_config_pathname(&diff_order_file_cfg, var, value);
223 if (!strcmp(var, "diff.ignoresubmodules"))
224 handle_ignore_submodules_arg(&default_diff_options, value);
226 if (!strcmp(var, "diff.submodule")) {
227 if (parse_submodule_params(&default_diff_options, value))
228 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
229 value);
230 return 0;
233 if (!strcmp(var, "diff.algorithm")) {
234 diff_algorithm = parse_algorithm_value(value);
235 if (diff_algorithm < 0)
236 return -1;
237 return 0;
240 if (git_color_config(var, value, cb) < 0)
241 return -1;
243 return git_diff_basic_config(var, value, cb);
246 int git_diff_basic_config(const char *var, const char *value, void *cb)
248 const char *name;
250 if (!strcmp(var, "diff.renamelimit")) {
251 diff_rename_limit_default = git_config_int(var, value);
252 return 0;
255 if (userdiff_config(var, value) < 0)
256 return -1;
258 if (skip_prefix(var, "diff.color.", &name) ||
259 skip_prefix(var, "color.diff.", &name)) {
260 int slot = parse_diff_color_slot(name);
261 if (slot < 0)
262 return 0;
263 if (!value)
264 return config_error_nonbool(var);
265 return color_parse(value, diff_colors[slot]);
268 /* like GNU diff's --suppress-blank-empty option */
269 if (!strcmp(var, "diff.suppressblankempty") ||
270 /* for backwards compatibility */
271 !strcmp(var, "diff.suppress-blank-empty")) {
272 diff_suppress_blank_empty = git_config_bool(var, value);
273 return 0;
276 if (!strcmp(var, "diff.dirstat")) {
277 struct strbuf errmsg = STRBUF_INIT;
278 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
279 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
280 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
281 errmsg.buf);
282 strbuf_release(&errmsg);
283 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
284 return 0;
287 if (starts_with(var, "submodule."))
288 return parse_submodule_config_option(var, value);
290 return git_default_config(var, value, cb);
293 static char *quote_two(const char *one, const char *two)
295 int need_one = quote_c_style(one, NULL, NULL, 1);
296 int need_two = quote_c_style(two, NULL, NULL, 1);
297 struct strbuf res = STRBUF_INIT;
299 if (need_one + need_two) {
300 strbuf_addch(&res, '"');
301 quote_c_style(one, &res, NULL, 1);
302 quote_c_style(two, &res, NULL, 1);
303 strbuf_addch(&res, '"');
304 } else {
305 strbuf_addstr(&res, one);
306 strbuf_addstr(&res, two);
308 return strbuf_detach(&res, NULL);
311 static const char *external_diff(void)
313 static const char *external_diff_cmd = NULL;
314 static int done_preparing = 0;
316 if (done_preparing)
317 return external_diff_cmd;
318 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
319 if (!external_diff_cmd)
320 external_diff_cmd = external_diff_cmd_cfg;
321 done_preparing = 1;
322 return external_diff_cmd;
326 * Keep track of files used for diffing. Sometimes such an entry
327 * refers to a temporary file, sometimes to an existing file, and
328 * sometimes to "/dev/null".
330 static struct diff_tempfile {
332 * filename external diff should read from, or NULL if this
333 * entry is currently not in use:
335 const char *name;
337 char hex[GIT_SHA1_HEXSZ + 1];
338 char mode[10];
341 * If this diff_tempfile instance refers to a temporary file,
342 * this tempfile object is used to manage its lifetime.
344 struct tempfile tempfile;
345 } diff_temp[2];
347 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
349 struct emit_callback {
350 int color_diff;
351 unsigned ws_rule;
352 int blank_at_eof_in_preimage;
353 int blank_at_eof_in_postimage;
354 int lno_in_preimage;
355 int lno_in_postimage;
356 sane_truncate_fn truncate;
357 const char **label_path;
358 struct diff_words_data *diff_words;
359 struct diff_options *opt;
360 struct strbuf *header;
363 static int count_lines(const char *data, int size)
365 int count, ch, completely_empty = 1, nl_just_seen = 0;
366 count = 0;
367 while (0 < size--) {
368 ch = *data++;
369 if (ch == '\n') {
370 count++;
371 nl_just_seen = 1;
372 completely_empty = 0;
374 else {
375 nl_just_seen = 0;
376 completely_empty = 0;
379 if (completely_empty)
380 return 0;
381 if (!nl_just_seen)
382 count++; /* no trailing newline */
383 return count;
386 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
388 if (!DIFF_FILE_VALID(one)) {
389 mf->ptr = (char *)""; /* does not matter */
390 mf->size = 0;
391 return 0;
393 else if (diff_populate_filespec(one, 0))
394 return -1;
396 mf->ptr = one->data;
397 mf->size = one->size;
398 return 0;
401 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
402 static unsigned long diff_filespec_size(struct diff_filespec *one)
404 if (!DIFF_FILE_VALID(one))
405 return 0;
406 diff_populate_filespec(one, CHECK_SIZE_ONLY);
407 return one->size;
410 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
412 char *ptr = mf->ptr;
413 long size = mf->size;
414 int cnt = 0;
416 if (!size)
417 return cnt;
418 ptr += size - 1; /* pointing at the very end */
419 if (*ptr != '\n')
420 ; /* incomplete line */
421 else
422 ptr--; /* skip the last LF */
423 while (mf->ptr < ptr) {
424 char *prev_eol;
425 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
426 if (*prev_eol == '\n')
427 break;
428 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
429 break;
430 cnt++;
431 ptr = prev_eol - 1;
433 return cnt;
436 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
437 struct emit_callback *ecbdata)
439 int l1, l2, at;
440 unsigned ws_rule = ecbdata->ws_rule;
441 l1 = count_trailing_blank(mf1, ws_rule);
442 l2 = count_trailing_blank(mf2, ws_rule);
443 if (l2 <= l1) {
444 ecbdata->blank_at_eof_in_preimage = 0;
445 ecbdata->blank_at_eof_in_postimage = 0;
446 return;
448 at = count_lines(mf1->ptr, mf1->size);
449 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
451 at = count_lines(mf2->ptr, mf2->size);
452 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
455 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
456 int first, const char *line, int len)
458 int has_trailing_newline, has_trailing_carriage_return;
459 int nofirst;
460 FILE *file = o->file;
462 fputs(diff_line_prefix(o), file);
464 if (len == 0) {
465 has_trailing_newline = (first == '\n');
466 has_trailing_carriage_return = (!has_trailing_newline &&
467 (first == '\r'));
468 nofirst = has_trailing_newline || has_trailing_carriage_return;
469 } else {
470 has_trailing_newline = (len > 0 && line[len-1] == '\n');
471 if (has_trailing_newline)
472 len--;
473 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
474 if (has_trailing_carriage_return)
475 len--;
476 nofirst = 0;
479 if (len || !nofirst) {
480 fputs(set, file);
481 if (!nofirst)
482 fputc(first, file);
483 fwrite(line, len, 1, file);
484 fputs(reset, file);
486 if (has_trailing_carriage_return)
487 fputc('\r', file);
488 if (has_trailing_newline)
489 fputc('\n', file);
492 static void emit_line(struct diff_options *o, const char *set, const char *reset,
493 const char *line, int len)
495 emit_line_0(o, set, reset, line[0], line+1, len-1);
498 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
500 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
501 ecbdata->blank_at_eof_in_preimage &&
502 ecbdata->blank_at_eof_in_postimage &&
503 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
504 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
505 return 0;
506 return ws_blank_line(line, len, ecbdata->ws_rule);
509 static void emit_line_checked(const char *reset,
510 struct emit_callback *ecbdata,
511 const char *line, int len,
512 enum color_diff color,
513 unsigned ws_error_highlight,
514 char sign)
516 const char *set = diff_get_color(ecbdata->color_diff, color);
517 const char *ws = NULL;
519 if (ecbdata->opt->ws_error_highlight & ws_error_highlight) {
520 ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
521 if (!*ws)
522 ws = NULL;
525 if (!ws)
526 emit_line_0(ecbdata->opt, set, reset, sign, line, len);
527 else if (sign == '+' && new_blank_line_at_eof(ecbdata, line, len))
528 /* Blank line at EOF - paint '+' as well */
529 emit_line_0(ecbdata->opt, ws, reset, sign, line, len);
530 else {
531 /* Emit just the prefix, then the rest. */
532 emit_line_0(ecbdata->opt, set, reset, sign, "", 0);
533 ws_check_emit(line, len, ecbdata->ws_rule,
534 ecbdata->opt->file, set, reset, ws);
538 static void emit_add_line(const char *reset,
539 struct emit_callback *ecbdata,
540 const char *line, int len)
542 emit_line_checked(reset, ecbdata, line, len,
543 DIFF_FILE_NEW, WSEH_NEW, '+');
546 static void emit_del_line(const char *reset,
547 struct emit_callback *ecbdata,
548 const char *line, int len)
550 emit_line_checked(reset, ecbdata, line, len,
551 DIFF_FILE_OLD, WSEH_OLD, '-');
554 static void emit_context_line(const char *reset,
555 struct emit_callback *ecbdata,
556 const char *line, int len)
558 emit_line_checked(reset, ecbdata, line, len,
559 DIFF_CONTEXT, WSEH_CONTEXT, ' ');
562 static void emit_hunk_header(struct emit_callback *ecbdata,
563 const char *line, int len)
565 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
566 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
567 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
568 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
569 static const char atat[2] = { '@', '@' };
570 const char *cp, *ep;
571 struct strbuf msgbuf = STRBUF_INIT;
572 int org_len = len;
573 int i = 1;
576 * As a hunk header must begin with "@@ -<old>, +<new> @@",
577 * it always is at least 10 bytes long.
579 if (len < 10 ||
580 memcmp(line, atat, 2) ||
581 !(ep = memmem(line + 2, len - 2, atat, 2))) {
582 emit_line(ecbdata->opt, context, reset, line, len);
583 return;
585 ep += 2; /* skip over @@ */
587 /* The hunk header in fraginfo color */
588 strbuf_addstr(&msgbuf, frag);
589 strbuf_add(&msgbuf, line, ep - line);
590 strbuf_addstr(&msgbuf, reset);
593 * trailing "\r\n"
595 for ( ; i < 3; i++)
596 if (line[len - i] == '\r' || line[len - i] == '\n')
597 len--;
599 /* blank before the func header */
600 for (cp = ep; ep - line < len; ep++)
601 if (*ep != ' ' && *ep != '\t')
602 break;
603 if (ep != cp) {
604 strbuf_addstr(&msgbuf, context);
605 strbuf_add(&msgbuf, cp, ep - cp);
606 strbuf_addstr(&msgbuf, reset);
609 if (ep < line + len) {
610 strbuf_addstr(&msgbuf, func);
611 strbuf_add(&msgbuf, ep, line + len - ep);
612 strbuf_addstr(&msgbuf, reset);
615 strbuf_add(&msgbuf, line + len, org_len - len);
616 emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
617 strbuf_release(&msgbuf);
620 static struct diff_tempfile *claim_diff_tempfile(void) {
621 int i;
622 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
623 if (!diff_temp[i].name)
624 return diff_temp + i;
625 die("BUG: diff is failing to clean up its tempfiles");
628 static void remove_tempfile(void)
630 int i;
631 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
632 if (is_tempfile_active(&diff_temp[i].tempfile))
633 delete_tempfile(&diff_temp[i].tempfile);
634 diff_temp[i].name = NULL;
638 static void print_line_count(FILE *file, int count)
640 switch (count) {
641 case 0:
642 fprintf(file, "0,0");
643 break;
644 case 1:
645 fprintf(file, "1");
646 break;
647 default:
648 fprintf(file, "1,%d", count);
649 break;
653 static void emit_rewrite_lines(struct emit_callback *ecb,
654 int prefix, const char *data, int size)
656 const char *endp = NULL;
657 static const char *nneof = " No newline at end of file\n";
658 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
660 while (0 < size) {
661 int len;
663 endp = memchr(data, '\n', size);
664 len = endp ? (endp - data + 1) : size;
665 if (prefix != '+') {
666 ecb->lno_in_preimage++;
667 emit_del_line(reset, ecb, data, len);
668 } else {
669 ecb->lno_in_postimage++;
670 emit_add_line(reset, ecb, data, len);
672 size -= len;
673 data += len;
675 if (!endp) {
676 const char *context = diff_get_color(ecb->color_diff,
677 DIFF_CONTEXT);
678 putc('\n', ecb->opt->file);
679 emit_line_0(ecb->opt, context, reset, '\\',
680 nneof, strlen(nneof));
684 static void emit_rewrite_diff(const char *name_a,
685 const char *name_b,
686 struct diff_filespec *one,
687 struct diff_filespec *two,
688 struct userdiff_driver *textconv_one,
689 struct userdiff_driver *textconv_two,
690 struct diff_options *o)
692 int lc_a, lc_b;
693 const char *name_a_tab, *name_b_tab;
694 const char *metainfo = diff_get_color(o->use_color, DIFF_METAINFO);
695 const char *fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
696 const char *reset = diff_get_color(o->use_color, DIFF_RESET);
697 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
698 const char *a_prefix, *b_prefix;
699 char *data_one, *data_two;
700 size_t size_one, size_two;
701 struct emit_callback ecbdata;
702 const char *line_prefix = diff_line_prefix(o);
704 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
705 a_prefix = o->b_prefix;
706 b_prefix = o->a_prefix;
707 } else {
708 a_prefix = o->a_prefix;
709 b_prefix = o->b_prefix;
712 name_a += (*name_a == '/');
713 name_b += (*name_b == '/');
714 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
715 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
717 strbuf_reset(&a_name);
718 strbuf_reset(&b_name);
719 quote_two_c_style(&a_name, a_prefix, name_a, 0);
720 quote_two_c_style(&b_name, b_prefix, name_b, 0);
722 size_one = fill_textconv(textconv_one, one, &data_one);
723 size_two = fill_textconv(textconv_two, two, &data_two);
725 memset(&ecbdata, 0, sizeof(ecbdata));
726 ecbdata.color_diff = want_color(o->use_color);
727 ecbdata.ws_rule = whitespace_rule(name_b);
728 ecbdata.opt = o;
729 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
730 mmfile_t mf1, mf2;
731 mf1.ptr = (char *)data_one;
732 mf2.ptr = (char *)data_two;
733 mf1.size = size_one;
734 mf2.size = size_two;
735 check_blank_at_eof(&mf1, &mf2, &ecbdata);
737 ecbdata.lno_in_preimage = 1;
738 ecbdata.lno_in_postimage = 1;
740 lc_a = count_lines(data_one, size_one);
741 lc_b = count_lines(data_two, size_two);
742 fprintf(o->file,
743 "%s%s--- %s%s%s\n%s%s+++ %s%s%s\n%s%s@@ -",
744 line_prefix, metainfo, a_name.buf, name_a_tab, reset,
745 line_prefix, metainfo, b_name.buf, name_b_tab, reset,
746 line_prefix, fraginfo);
747 if (!o->irreversible_delete)
748 print_line_count(o->file, lc_a);
749 else
750 fprintf(o->file, "?,?");
751 fprintf(o->file, " +");
752 print_line_count(o->file, lc_b);
753 fprintf(o->file, " @@%s\n", reset);
754 if (lc_a && !o->irreversible_delete)
755 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
756 if (lc_b)
757 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
758 if (textconv_one)
759 free((char *)data_one);
760 if (textconv_two)
761 free((char *)data_two);
764 struct diff_words_buffer {
765 mmfile_t text;
766 long alloc;
767 struct diff_words_orig {
768 const char *begin, *end;
769 } *orig;
770 int orig_nr, orig_alloc;
773 static void diff_words_append(char *line, unsigned long len,
774 struct diff_words_buffer *buffer)
776 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
777 line++;
778 len--;
779 memcpy(buffer->text.ptr + buffer->text.size, line, len);
780 buffer->text.size += len;
781 buffer->text.ptr[buffer->text.size] = '\0';
784 struct diff_words_style_elem {
785 const char *prefix;
786 const char *suffix;
787 const char *color; /* NULL; filled in by the setup code if
788 * color is enabled */
791 struct diff_words_style {
792 enum diff_words_type type;
793 struct diff_words_style_elem new, old, ctx;
794 const char *newline;
797 static struct diff_words_style diff_words_styles[] = {
798 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
799 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
800 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
803 struct diff_words_data {
804 struct diff_words_buffer minus, plus;
805 const char *current_plus;
806 int last_minus;
807 struct diff_options *opt;
808 regex_t *word_regex;
809 enum diff_words_type type;
810 struct diff_words_style *style;
813 static int fn_out_diff_words_write_helper(FILE *fp,
814 struct diff_words_style_elem *st_el,
815 const char *newline,
816 size_t count, const char *buf,
817 const char *line_prefix)
819 int print = 0;
821 while (count) {
822 char *p = memchr(buf, '\n', count);
823 if (print)
824 fputs(line_prefix, fp);
825 if (p != buf) {
826 if (st_el->color && fputs(st_el->color, fp) < 0)
827 return -1;
828 if (fputs(st_el->prefix, fp) < 0 ||
829 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
830 fputs(st_el->suffix, fp) < 0)
831 return -1;
832 if (st_el->color && *st_el->color
833 && fputs(GIT_COLOR_RESET, fp) < 0)
834 return -1;
836 if (!p)
837 return 0;
838 if (fputs(newline, fp) < 0)
839 return -1;
840 count -= p + 1 - buf;
841 buf = p + 1;
842 print = 1;
844 return 0;
848 * '--color-words' algorithm can be described as:
850 * 1. collect a the minus/plus lines of a diff hunk, divided into
851 * minus-lines and plus-lines;
853 * 2. break both minus-lines and plus-lines into words and
854 * place them into two mmfile_t with one word for each line;
856 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
858 * And for the common parts of the both file, we output the plus side text.
859 * diff_words->current_plus is used to trace the current position of the plus file
860 * which printed. diff_words->last_minus is used to trace the last minus word
861 * printed.
863 * For '--graph' to work with '--color-words', we need to output the graph prefix
864 * on each line of color words output. Generally, there are two conditions on
865 * which we should output the prefix.
867 * 1. diff_words->last_minus == 0 &&
868 * diff_words->current_plus == diff_words->plus.text.ptr
870 * that is: the plus text must start as a new line, and if there is no minus
871 * word printed, a graph prefix must be printed.
873 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
874 * *(diff_words->current_plus - 1) == '\n'
876 * that is: a graph prefix must be printed following a '\n'
878 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
880 if ((diff_words->last_minus == 0 &&
881 diff_words->current_plus == diff_words->plus.text.ptr) ||
882 (diff_words->current_plus > diff_words->plus.text.ptr &&
883 *(diff_words->current_plus - 1) == '\n')) {
884 return 1;
885 } else {
886 return 0;
890 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
892 struct diff_words_data *diff_words = priv;
893 struct diff_words_style *style = diff_words->style;
894 int minus_first, minus_len, plus_first, plus_len;
895 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
896 struct diff_options *opt = diff_words->opt;
897 const char *line_prefix;
899 if (line[0] != '@' || parse_hunk_header(line, len,
900 &minus_first, &minus_len, &plus_first, &plus_len))
901 return;
903 assert(opt);
904 line_prefix = diff_line_prefix(opt);
906 /* POSIX requires that first be decremented by one if len == 0... */
907 if (minus_len) {
908 minus_begin = diff_words->minus.orig[minus_first].begin;
909 minus_end =
910 diff_words->minus.orig[minus_first + minus_len - 1].end;
911 } else
912 minus_begin = minus_end =
913 diff_words->minus.orig[minus_first].end;
915 if (plus_len) {
916 plus_begin = diff_words->plus.orig[plus_first].begin;
917 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
918 } else
919 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
921 if (color_words_output_graph_prefix(diff_words)) {
922 fputs(line_prefix, diff_words->opt->file);
924 if (diff_words->current_plus != plus_begin) {
925 fn_out_diff_words_write_helper(diff_words->opt->file,
926 &style->ctx, style->newline,
927 plus_begin - diff_words->current_plus,
928 diff_words->current_plus, line_prefix);
929 if (*(plus_begin - 1) == '\n')
930 fputs(line_prefix, diff_words->opt->file);
932 if (minus_begin != minus_end) {
933 fn_out_diff_words_write_helper(diff_words->opt->file,
934 &style->old, style->newline,
935 minus_end - minus_begin, minus_begin,
936 line_prefix);
938 if (plus_begin != plus_end) {
939 fn_out_diff_words_write_helper(diff_words->opt->file,
940 &style->new, style->newline,
941 plus_end - plus_begin, plus_begin,
942 line_prefix);
945 diff_words->current_plus = plus_end;
946 diff_words->last_minus = minus_first;
949 /* This function starts looking at *begin, and returns 0 iff a word was found. */
950 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
951 int *begin, int *end)
953 if (word_regex && *begin < buffer->size) {
954 regmatch_t match[1];
955 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
956 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
957 '\n', match[0].rm_eo - match[0].rm_so);
958 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
959 *begin += match[0].rm_so;
960 return *begin >= *end;
962 return -1;
965 /* find the next word */
966 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
967 (*begin)++;
968 if (*begin >= buffer->size)
969 return -1;
971 /* find the end of the word */
972 *end = *begin + 1;
973 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
974 (*end)++;
976 return 0;
980 * This function splits the words in buffer->text, stores the list with
981 * newline separator into out, and saves the offsets of the original words
982 * in buffer->orig.
984 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
985 regex_t *word_regex)
987 int i, j;
988 long alloc = 0;
990 out->size = 0;
991 out->ptr = NULL;
993 /* fake an empty "0th" word */
994 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
995 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
996 buffer->orig_nr = 1;
998 for (i = 0; i < buffer->text.size; i++) {
999 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1000 return;
1002 /* store original boundaries */
1003 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1004 buffer->orig_alloc);
1005 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1006 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1007 buffer->orig_nr++;
1009 /* store one word */
1010 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1011 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1012 out->ptr[out->size + j - i] = '\n';
1013 out->size += j - i + 1;
1015 i = j - 1;
1019 /* this executes the word diff on the accumulated buffers */
1020 static void diff_words_show(struct diff_words_data *diff_words)
1022 xpparam_t xpp;
1023 xdemitconf_t xecfg;
1024 mmfile_t minus, plus;
1025 struct diff_words_style *style = diff_words->style;
1027 struct diff_options *opt = diff_words->opt;
1028 const char *line_prefix;
1030 assert(opt);
1031 line_prefix = diff_line_prefix(opt);
1033 /* special case: only removal */
1034 if (!diff_words->plus.text.size) {
1035 fputs(line_prefix, diff_words->opt->file);
1036 fn_out_diff_words_write_helper(diff_words->opt->file,
1037 &style->old, style->newline,
1038 diff_words->minus.text.size,
1039 diff_words->minus.text.ptr, line_prefix);
1040 diff_words->minus.text.size = 0;
1041 return;
1044 diff_words->current_plus = diff_words->plus.text.ptr;
1045 diff_words->last_minus = 0;
1047 memset(&xpp, 0, sizeof(xpp));
1048 memset(&xecfg, 0, sizeof(xecfg));
1049 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1050 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1051 xpp.flags = 0;
1052 /* as only the hunk header will be parsed, we need a 0-context */
1053 xecfg.ctxlen = 0;
1054 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1055 &xpp, &xecfg))
1056 die("unable to generate word diff");
1057 free(minus.ptr);
1058 free(plus.ptr);
1059 if (diff_words->current_plus != diff_words->plus.text.ptr +
1060 diff_words->plus.text.size) {
1061 if (color_words_output_graph_prefix(diff_words))
1062 fputs(line_prefix, diff_words->opt->file);
1063 fn_out_diff_words_write_helper(diff_words->opt->file,
1064 &style->ctx, style->newline,
1065 diff_words->plus.text.ptr + diff_words->plus.text.size
1066 - diff_words->current_plus, diff_words->current_plus,
1067 line_prefix);
1069 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1072 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1073 static void diff_words_flush(struct emit_callback *ecbdata)
1075 if (ecbdata->diff_words->minus.text.size ||
1076 ecbdata->diff_words->plus.text.size)
1077 diff_words_show(ecbdata->diff_words);
1080 static void diff_filespec_load_driver(struct diff_filespec *one)
1082 /* Use already-loaded driver */
1083 if (one->driver)
1084 return;
1086 if (S_ISREG(one->mode))
1087 one->driver = userdiff_find_by_path(one->path);
1089 /* Fallback to default settings */
1090 if (!one->driver)
1091 one->driver = userdiff_find_by_name("default");
1094 static const char *userdiff_word_regex(struct diff_filespec *one)
1096 diff_filespec_load_driver(one);
1097 return one->driver->word_regex;
1100 static void init_diff_words_data(struct emit_callback *ecbdata,
1101 struct diff_options *orig_opts,
1102 struct diff_filespec *one,
1103 struct diff_filespec *two)
1105 int i;
1106 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1107 memcpy(o, orig_opts, sizeof(struct diff_options));
1109 ecbdata->diff_words =
1110 xcalloc(1, sizeof(struct diff_words_data));
1111 ecbdata->diff_words->type = o->word_diff;
1112 ecbdata->diff_words->opt = o;
1113 if (!o->word_regex)
1114 o->word_regex = userdiff_word_regex(one);
1115 if (!o->word_regex)
1116 o->word_regex = userdiff_word_regex(two);
1117 if (!o->word_regex)
1118 o->word_regex = diff_word_regex_cfg;
1119 if (o->word_regex) {
1120 ecbdata->diff_words->word_regex = (regex_t *)
1121 xmalloc(sizeof(regex_t));
1122 if (regcomp(ecbdata->diff_words->word_regex,
1123 o->word_regex,
1124 REG_EXTENDED | REG_NEWLINE))
1125 die ("Invalid regular expression: %s",
1126 o->word_regex);
1128 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1129 if (o->word_diff == diff_words_styles[i].type) {
1130 ecbdata->diff_words->style =
1131 &diff_words_styles[i];
1132 break;
1135 if (want_color(o->use_color)) {
1136 struct diff_words_style *st = ecbdata->diff_words->style;
1137 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1138 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1139 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1143 static void free_diff_words_data(struct emit_callback *ecbdata)
1145 if (ecbdata->diff_words) {
1146 diff_words_flush(ecbdata);
1147 free (ecbdata->diff_words->opt);
1148 free (ecbdata->diff_words->minus.text.ptr);
1149 free (ecbdata->diff_words->minus.orig);
1150 free (ecbdata->diff_words->plus.text.ptr);
1151 free (ecbdata->diff_words->plus.orig);
1152 if (ecbdata->diff_words->word_regex) {
1153 regfree(ecbdata->diff_words->word_regex);
1154 free(ecbdata->diff_words->word_regex);
1156 free(ecbdata->diff_words);
1157 ecbdata->diff_words = NULL;
1161 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1163 if (want_color(diff_use_color))
1164 return diff_colors[ix];
1165 return "";
1168 const char *diff_line_prefix(struct diff_options *opt)
1170 struct strbuf *msgbuf;
1171 if (!opt->output_prefix)
1172 return "";
1174 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1175 return msgbuf->buf;
1178 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1180 const char *cp;
1181 unsigned long allot;
1182 size_t l = len;
1184 if (ecb->truncate)
1185 return ecb->truncate(line, len);
1186 cp = line;
1187 allot = l;
1188 while (0 < l) {
1189 (void) utf8_width(&cp, &l);
1190 if (!cp)
1191 break; /* truncated in the middle? */
1193 return allot - l;
1196 static void find_lno(const char *line, struct emit_callback *ecbdata)
1198 const char *p;
1199 ecbdata->lno_in_preimage = 0;
1200 ecbdata->lno_in_postimage = 0;
1201 p = strchr(line, '-');
1202 if (!p)
1203 return; /* cannot happen */
1204 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1205 p = strchr(p, '+');
1206 if (!p)
1207 return; /* cannot happen */
1208 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1211 static void fn_out_consume(void *priv, char *line, unsigned long len)
1213 struct emit_callback *ecbdata = priv;
1214 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
1215 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1216 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1217 struct diff_options *o = ecbdata->opt;
1218 const char *line_prefix = diff_line_prefix(o);
1220 o->found_changes = 1;
1222 if (ecbdata->header) {
1223 fprintf(o->file, "%s", ecbdata->header->buf);
1224 strbuf_reset(ecbdata->header);
1225 ecbdata->header = NULL;
1228 if (ecbdata->label_path[0]) {
1229 const char *name_a_tab, *name_b_tab;
1231 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
1232 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
1234 fprintf(o->file, "%s%s--- %s%s%s\n",
1235 line_prefix, meta, ecbdata->label_path[0], reset, name_a_tab);
1236 fprintf(o->file, "%s%s+++ %s%s%s\n",
1237 line_prefix, meta, ecbdata->label_path[1], reset, name_b_tab);
1238 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1241 if (diff_suppress_blank_empty
1242 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1243 line[0] = '\n';
1244 len = 1;
1247 if (line[0] == '@') {
1248 if (ecbdata->diff_words)
1249 diff_words_flush(ecbdata);
1250 len = sane_truncate_line(ecbdata, line, len);
1251 find_lno(line, ecbdata);
1252 emit_hunk_header(ecbdata, line, len);
1253 if (line[len-1] != '\n')
1254 putc('\n', o->file);
1255 return;
1258 if (ecbdata->diff_words) {
1259 if (line[0] == '-') {
1260 diff_words_append(line, len,
1261 &ecbdata->diff_words->minus);
1262 return;
1263 } else if (line[0] == '+') {
1264 diff_words_append(line, len,
1265 &ecbdata->diff_words->plus);
1266 return;
1267 } else if (starts_with(line, "\\ ")) {
1269 * Eat the "no newline at eof" marker as if we
1270 * saw a "+" or "-" line with nothing on it,
1271 * and return without diff_words_flush() to
1272 * defer processing. If this is the end of
1273 * preimage, more "+" lines may come after it.
1275 return;
1277 diff_words_flush(ecbdata);
1278 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
1279 emit_line(o, context, reset, line, len);
1280 fputs("~\n", o->file);
1281 } else {
1283 * Skip the prefix character, if any. With
1284 * diff_suppress_blank_empty, there may be
1285 * none.
1287 if (line[0] != '\n') {
1288 line++;
1289 len--;
1291 emit_line(o, context, reset, line, len);
1293 return;
1296 switch (line[0]) {
1297 case '+':
1298 ecbdata->lno_in_postimage++;
1299 emit_add_line(reset, ecbdata, line + 1, len - 1);
1300 break;
1301 case '-':
1302 ecbdata->lno_in_preimage++;
1303 emit_del_line(reset, ecbdata, line + 1, len - 1);
1304 break;
1305 case ' ':
1306 ecbdata->lno_in_postimage++;
1307 ecbdata->lno_in_preimage++;
1308 emit_context_line(reset, ecbdata, line + 1, len - 1);
1309 break;
1310 default:
1311 /* incomplete line at the end */
1312 ecbdata->lno_in_preimage++;
1313 emit_line(o, diff_get_color(ecbdata->color_diff, DIFF_CONTEXT),
1314 reset, line, len);
1315 break;
1319 static char *pprint_rename(const char *a, const char *b)
1321 const char *old = a;
1322 const char *new = b;
1323 struct strbuf name = STRBUF_INIT;
1324 int pfx_length, sfx_length;
1325 int pfx_adjust_for_slash;
1326 int len_a = strlen(a);
1327 int len_b = strlen(b);
1328 int a_midlen, b_midlen;
1329 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1330 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1332 if (qlen_a || qlen_b) {
1333 quote_c_style(a, &name, NULL, 0);
1334 strbuf_addstr(&name, " => ");
1335 quote_c_style(b, &name, NULL, 0);
1336 return strbuf_detach(&name, NULL);
1339 /* Find common prefix */
1340 pfx_length = 0;
1341 while (*old && *new && *old == *new) {
1342 if (*old == '/')
1343 pfx_length = old - a + 1;
1344 old++;
1345 new++;
1348 /* Find common suffix */
1349 old = a + len_a;
1350 new = b + len_b;
1351 sfx_length = 0;
1353 * If there is a common prefix, it must end in a slash. In
1354 * that case we let this loop run 1 into the prefix to see the
1355 * same slash.
1357 * If there is no common prefix, we cannot do this as it would
1358 * underrun the input strings.
1360 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
1361 while (a + pfx_length - pfx_adjust_for_slash <= old &&
1362 b + pfx_length - pfx_adjust_for_slash <= new &&
1363 *old == *new) {
1364 if (*old == '/')
1365 sfx_length = len_a - (old - a);
1366 old--;
1367 new--;
1371 * pfx{mid-a => mid-b}sfx
1372 * {pfx-a => pfx-b}sfx
1373 * pfx{sfx-a => sfx-b}
1374 * name-a => name-b
1376 a_midlen = len_a - pfx_length - sfx_length;
1377 b_midlen = len_b - pfx_length - sfx_length;
1378 if (a_midlen < 0)
1379 a_midlen = 0;
1380 if (b_midlen < 0)
1381 b_midlen = 0;
1383 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1384 if (pfx_length + sfx_length) {
1385 strbuf_add(&name, a, pfx_length);
1386 strbuf_addch(&name, '{');
1388 strbuf_add(&name, a + pfx_length, a_midlen);
1389 strbuf_addstr(&name, " => ");
1390 strbuf_add(&name, b + pfx_length, b_midlen);
1391 if (pfx_length + sfx_length) {
1392 strbuf_addch(&name, '}');
1393 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1395 return strbuf_detach(&name, NULL);
1398 struct diffstat_t {
1399 int nr;
1400 int alloc;
1401 struct diffstat_file {
1402 char *from_name;
1403 char *name;
1404 char *print_name;
1405 unsigned is_unmerged:1;
1406 unsigned is_binary:1;
1407 unsigned is_renamed:1;
1408 unsigned is_interesting:1;
1409 uintmax_t added, deleted;
1410 } **files;
1413 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1414 const char *name_a,
1415 const char *name_b)
1417 struct diffstat_file *x;
1418 x = xcalloc(1, sizeof(*x));
1419 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
1420 diffstat->files[diffstat->nr++] = x;
1421 if (name_b) {
1422 x->from_name = xstrdup(name_a);
1423 x->name = xstrdup(name_b);
1424 x->is_renamed = 1;
1426 else {
1427 x->from_name = NULL;
1428 x->name = xstrdup(name_a);
1430 return x;
1433 static void diffstat_consume(void *priv, char *line, unsigned long len)
1435 struct diffstat_t *diffstat = priv;
1436 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1438 if (line[0] == '+')
1439 x->added++;
1440 else if (line[0] == '-')
1441 x->deleted++;
1444 const char mime_boundary_leader[] = "------------";
1446 static int scale_linear(int it, int width, int max_change)
1448 if (!it)
1449 return 0;
1451 * make sure that at least one '-' or '+' is printed if
1452 * there is any change to this path. The easiest way is to
1453 * scale linearly as if the alloted width is one column shorter
1454 * than it is, and then add 1 to the result.
1456 return 1 + (it * (width - 1) / max_change);
1459 static void show_name(FILE *file,
1460 const char *prefix, const char *name, int len)
1462 fprintf(file, " %s%-*s |", prefix, len, name);
1465 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1467 if (cnt <= 0)
1468 return;
1469 fprintf(file, "%s", set);
1470 while (cnt--)
1471 putc(ch, file);
1472 fprintf(file, "%s", reset);
1475 static void fill_print_name(struct diffstat_file *file)
1477 char *pname;
1479 if (file->print_name)
1480 return;
1482 if (!file->is_renamed) {
1483 struct strbuf buf = STRBUF_INIT;
1484 if (quote_c_style(file->name, &buf, NULL, 0)) {
1485 pname = strbuf_detach(&buf, NULL);
1486 } else {
1487 pname = file->name;
1488 strbuf_release(&buf);
1490 } else {
1491 pname = pprint_rename(file->from_name, file->name);
1493 file->print_name = pname;
1496 int print_stat_summary(FILE *fp, int files, int insertions, int deletions)
1498 struct strbuf sb = STRBUF_INIT;
1499 int ret;
1501 if (!files) {
1502 assert(insertions == 0 && deletions == 0);
1503 return fprintf(fp, "%s\n", " 0 files changed");
1506 strbuf_addf(&sb,
1507 (files == 1) ? " %d file changed" : " %d files changed",
1508 files);
1511 * For binary diff, the caller may want to print "x files
1512 * changed" with insertions == 0 && deletions == 0.
1514 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
1515 * is probably less confusing (i.e skip over "2 files changed
1516 * but nothing about added/removed lines? Is this a bug in Git?").
1518 if (insertions || deletions == 0) {
1519 strbuf_addf(&sb,
1520 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
1521 insertions);
1524 if (deletions || insertions == 0) {
1525 strbuf_addf(&sb,
1526 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
1527 deletions);
1529 strbuf_addch(&sb, '\n');
1530 ret = fputs(sb.buf, fp);
1531 strbuf_release(&sb);
1532 return ret;
1535 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1537 int i, len, add, del, adds = 0, dels = 0;
1538 uintmax_t max_change = 0, max_len = 0;
1539 int total_files = data->nr, count;
1540 int width, name_width, graph_width, number_width = 0, bin_width = 0;
1541 const char *reset, *add_c, *del_c;
1542 const char *line_prefix = "";
1543 int extra_shown = 0;
1545 if (data->nr == 0)
1546 return;
1548 line_prefix = diff_line_prefix(options);
1549 count = options->stat_count ? options->stat_count : data->nr;
1551 reset = diff_get_color_opt(options, DIFF_RESET);
1552 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1553 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1556 * Find the longest filename and max number of changes
1558 for (i = 0; (i < count) && (i < data->nr); i++) {
1559 struct diffstat_file *file = data->files[i];
1560 uintmax_t change = file->added + file->deleted;
1562 if (!file->is_interesting && (change == 0)) {
1563 count++; /* not shown == room for one more */
1564 continue;
1566 fill_print_name(file);
1567 len = strlen(file->print_name);
1568 if (max_len < len)
1569 max_len = len;
1571 if (file->is_unmerged) {
1572 /* "Unmerged" is 8 characters */
1573 bin_width = bin_width < 8 ? 8 : bin_width;
1574 continue;
1576 if (file->is_binary) {
1577 /* "Bin XXX -> YYY bytes" */
1578 int w = 14 + decimal_width(file->added)
1579 + decimal_width(file->deleted);
1580 bin_width = bin_width < w ? w : bin_width;
1581 /* Display change counts aligned with "Bin" */
1582 number_width = 3;
1583 continue;
1586 if (max_change < change)
1587 max_change = change;
1589 count = i; /* where we can stop scanning in data->files[] */
1592 * We have width = stat_width or term_columns() columns total.
1593 * We want a maximum of min(max_len, stat_name_width) for the name part.
1594 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1595 * We also need 1 for " " and 4 + decimal_width(max_change)
1596 * for " | NNNN " and one the empty column at the end, altogether
1597 * 6 + decimal_width(max_change).
1599 * If there's not enough space, we will use the smaller of
1600 * stat_name_width (if set) and 5/8*width for the filename,
1601 * and the rest for constant elements + graph part, but no more
1602 * than stat_graph_width for the graph part.
1603 * (5/8 gives 50 for filename and 30 for the constant parts + graph
1604 * for the standard terminal size).
1606 * In other words: stat_width limits the maximum width, and
1607 * stat_name_width fixes the maximum width of the filename,
1608 * and is also used to divide available columns if there
1609 * aren't enough.
1611 * Binary files are displayed with "Bin XXX -> YYY bytes"
1612 * instead of the change count and graph. This part is treated
1613 * similarly to the graph part, except that it is not
1614 * "scaled". If total width is too small to accommodate the
1615 * guaranteed minimum width of the filename part and the
1616 * separators and this message, this message will "overflow"
1617 * making the line longer than the maximum width.
1620 if (options->stat_width == -1)
1621 width = term_columns() - strlen(line_prefix);
1622 else
1623 width = options->stat_width ? options->stat_width : 80;
1624 number_width = decimal_width(max_change) > number_width ?
1625 decimal_width(max_change) : number_width;
1627 if (options->stat_graph_width == -1)
1628 options->stat_graph_width = diff_stat_graph_width;
1631 * Guarantee 3/8*16==6 for the graph part
1632 * and 5/8*16==10 for the filename part
1634 if (width < 16 + 6 + number_width)
1635 width = 16 + 6 + number_width;
1638 * First assign sizes that are wanted, ignoring available width.
1639 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
1640 * starting from "XXX" should fit in graph_width.
1642 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
1643 if (options->stat_graph_width &&
1644 options->stat_graph_width < graph_width)
1645 graph_width = options->stat_graph_width;
1647 name_width = (options->stat_name_width > 0 &&
1648 options->stat_name_width < max_len) ?
1649 options->stat_name_width : max_len;
1652 * Adjust adjustable widths not to exceed maximum width
1654 if (name_width + number_width + 6 + graph_width > width) {
1655 if (graph_width > width * 3/8 - number_width - 6) {
1656 graph_width = width * 3/8 - number_width - 6;
1657 if (graph_width < 6)
1658 graph_width = 6;
1661 if (options->stat_graph_width &&
1662 graph_width > options->stat_graph_width)
1663 graph_width = options->stat_graph_width;
1664 if (name_width > width - number_width - 6 - graph_width)
1665 name_width = width - number_width - 6 - graph_width;
1666 else
1667 graph_width = width - number_width - 6 - name_width;
1671 * From here name_width is the width of the name area,
1672 * and graph_width is the width of the graph area.
1673 * max_change is used to scale graph properly.
1675 for (i = 0; i < count; i++) {
1676 const char *prefix = "";
1677 struct diffstat_file *file = data->files[i];
1678 char *name = file->print_name;
1679 uintmax_t added = file->added;
1680 uintmax_t deleted = file->deleted;
1681 int name_len;
1683 if (!file->is_interesting && (added + deleted == 0))
1684 continue;
1687 * "scale" the filename
1689 len = name_width;
1690 name_len = strlen(name);
1691 if (name_width < name_len) {
1692 char *slash;
1693 prefix = "...";
1694 len -= 3;
1695 name += name_len - len;
1696 slash = strchr(name, '/');
1697 if (slash)
1698 name = slash;
1701 if (file->is_binary) {
1702 fprintf(options->file, "%s", line_prefix);
1703 show_name(options->file, prefix, name, len);
1704 fprintf(options->file, " %*s", number_width, "Bin");
1705 if (!added && !deleted) {
1706 putc('\n', options->file);
1707 continue;
1709 fprintf(options->file, " %s%"PRIuMAX"%s",
1710 del_c, deleted, reset);
1711 fprintf(options->file, " -> ");
1712 fprintf(options->file, "%s%"PRIuMAX"%s",
1713 add_c, added, reset);
1714 fprintf(options->file, " bytes");
1715 fprintf(options->file, "\n");
1716 continue;
1718 else if (file->is_unmerged) {
1719 fprintf(options->file, "%s", line_prefix);
1720 show_name(options->file, prefix, name, len);
1721 fprintf(options->file, " Unmerged\n");
1722 continue;
1726 * scale the add/delete
1728 add = added;
1729 del = deleted;
1731 if (graph_width <= max_change) {
1732 int total = scale_linear(add + del, graph_width, max_change);
1733 if (total < 2 && add && del)
1734 /* width >= 2 due to the sanity check */
1735 total = 2;
1736 if (add < del) {
1737 add = scale_linear(add, graph_width, max_change);
1738 del = total - add;
1739 } else {
1740 del = scale_linear(del, graph_width, max_change);
1741 add = total - del;
1744 fprintf(options->file, "%s", line_prefix);
1745 show_name(options->file, prefix, name, len);
1746 fprintf(options->file, " %*"PRIuMAX"%s",
1747 number_width, added + deleted,
1748 added + deleted ? " " : "");
1749 show_graph(options->file, '+', add, add_c, reset);
1750 show_graph(options->file, '-', del, del_c, reset);
1751 fprintf(options->file, "\n");
1754 for (i = 0; i < data->nr; i++) {
1755 struct diffstat_file *file = data->files[i];
1756 uintmax_t added = file->added;
1757 uintmax_t deleted = file->deleted;
1759 if (file->is_unmerged ||
1760 (!file->is_interesting && (added + deleted == 0))) {
1761 total_files--;
1762 continue;
1765 if (!file->is_binary) {
1766 adds += added;
1767 dels += deleted;
1769 if (i < count)
1770 continue;
1771 if (!extra_shown)
1772 fprintf(options->file, "%s ...\n", line_prefix);
1773 extra_shown = 1;
1775 fprintf(options->file, "%s", line_prefix);
1776 print_stat_summary(options->file, total_files, adds, dels);
1779 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1781 int i, adds = 0, dels = 0, total_files = data->nr;
1783 if (data->nr == 0)
1784 return;
1786 for (i = 0; i < data->nr; i++) {
1787 int added = data->files[i]->added;
1788 int deleted= data->files[i]->deleted;
1790 if (data->files[i]->is_unmerged ||
1791 (!data->files[i]->is_interesting && (added + deleted == 0))) {
1792 total_files--;
1793 } else if (!data->files[i]->is_binary) { /* don't count bytes */
1794 adds += added;
1795 dels += deleted;
1798 fprintf(options->file, "%s", diff_line_prefix(options));
1799 print_stat_summary(options->file, total_files, adds, dels);
1802 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1804 int i;
1806 if (data->nr == 0)
1807 return;
1809 for (i = 0; i < data->nr; i++) {
1810 struct diffstat_file *file = data->files[i];
1812 fprintf(options->file, "%s", diff_line_prefix(options));
1814 if (file->is_binary)
1815 fprintf(options->file, "-\t-\t");
1816 else
1817 fprintf(options->file,
1818 "%"PRIuMAX"\t%"PRIuMAX"\t",
1819 file->added, file->deleted);
1820 if (options->line_termination) {
1821 fill_print_name(file);
1822 if (!file->is_renamed)
1823 write_name_quoted(file->name, options->file,
1824 options->line_termination);
1825 else {
1826 fputs(file->print_name, options->file);
1827 putc(options->line_termination, options->file);
1829 } else {
1830 if (file->is_renamed) {
1831 putc('\0', options->file);
1832 write_name_quoted(file->from_name, options->file, '\0');
1834 write_name_quoted(file->name, options->file, '\0');
1839 struct dirstat_file {
1840 const char *name;
1841 unsigned long changed;
1844 struct dirstat_dir {
1845 struct dirstat_file *files;
1846 int alloc, nr, permille, cumulative;
1849 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
1850 unsigned long changed, const char *base, int baselen)
1852 unsigned long this_dir = 0;
1853 unsigned int sources = 0;
1854 const char *line_prefix = diff_line_prefix(opt);
1856 while (dir->nr) {
1857 struct dirstat_file *f = dir->files;
1858 int namelen = strlen(f->name);
1859 unsigned long this;
1860 char *slash;
1862 if (namelen < baselen)
1863 break;
1864 if (memcmp(f->name, base, baselen))
1865 break;
1866 slash = strchr(f->name + baselen, '/');
1867 if (slash) {
1868 int newbaselen = slash + 1 - f->name;
1869 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
1870 sources++;
1871 } else {
1872 this = f->changed;
1873 dir->files++;
1874 dir->nr--;
1875 sources += 2;
1877 this_dir += this;
1881 * We don't report dirstat's for
1882 * - the top level
1883 * - or cases where everything came from a single directory
1884 * under this directory (sources == 1).
1886 if (baselen && sources != 1) {
1887 if (this_dir) {
1888 int permille = this_dir * 1000 / changed;
1889 if (permille >= dir->permille) {
1890 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
1891 permille / 10, permille % 10, baselen, base);
1892 if (!dir->cumulative)
1893 return 0;
1897 return this_dir;
1900 static int dirstat_compare(const void *_a, const void *_b)
1902 const struct dirstat_file *a = _a;
1903 const struct dirstat_file *b = _b;
1904 return strcmp(a->name, b->name);
1907 static void show_dirstat(struct diff_options *options)
1909 int i;
1910 unsigned long changed;
1911 struct dirstat_dir dir;
1912 struct diff_queue_struct *q = &diff_queued_diff;
1914 dir.files = NULL;
1915 dir.alloc = 0;
1916 dir.nr = 0;
1917 dir.permille = options->dirstat_permille;
1918 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1920 changed = 0;
1921 for (i = 0; i < q->nr; i++) {
1922 struct diff_filepair *p = q->queue[i];
1923 const char *name;
1924 unsigned long copied, added, damage;
1925 int content_changed;
1927 name = p->two->path ? p->two->path : p->one->path;
1929 if (p->one->oid_valid && p->two->oid_valid)
1930 content_changed = oidcmp(&p->one->oid, &p->two->oid);
1931 else
1932 content_changed = 1;
1934 if (!content_changed) {
1936 * The SHA1 has not changed, so pre-/post-content is
1937 * identical. We can therefore skip looking at the
1938 * file contents altogether.
1940 damage = 0;
1941 goto found_damage;
1944 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
1946 * In --dirstat-by-file mode, we don't really need to
1947 * look at the actual file contents at all.
1948 * The fact that the SHA1 changed is enough for us to
1949 * add this file to the list of results
1950 * (with each file contributing equal damage).
1952 damage = 1;
1953 goto found_damage;
1956 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1957 diff_populate_filespec(p->one, 0);
1958 diff_populate_filespec(p->two, 0);
1959 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1960 &copied, &added);
1961 diff_free_filespec_data(p->one);
1962 diff_free_filespec_data(p->two);
1963 } else if (DIFF_FILE_VALID(p->one)) {
1964 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
1965 copied = added = 0;
1966 diff_free_filespec_data(p->one);
1967 } else if (DIFF_FILE_VALID(p->two)) {
1968 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
1969 copied = 0;
1970 added = p->two->size;
1971 diff_free_filespec_data(p->two);
1972 } else
1973 continue;
1976 * Original minus copied is the removed material,
1977 * added is the new material. They are both damages
1978 * made to the preimage.
1979 * If the resulting damage is zero, we know that
1980 * diffcore_count_changes() considers the two entries to
1981 * be identical, but since content_changed is true, we
1982 * know that there must have been _some_ kind of change,
1983 * so we force all entries to have damage > 0.
1985 damage = (p->one->size - copied) + added;
1986 if (!damage)
1987 damage = 1;
1989 found_damage:
1990 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1991 dir.files[dir.nr].name = name;
1992 dir.files[dir.nr].changed = damage;
1993 changed += damage;
1994 dir.nr++;
1997 /* This can happen even with many files, if everything was renames */
1998 if (!changed)
1999 return;
2001 /* Show all directories with more than x% of the changes */
2002 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
2003 gather_dirstat(options, &dir, changed, "", 0);
2006 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2008 int i;
2009 unsigned long changed;
2010 struct dirstat_dir dir;
2012 if (data->nr == 0)
2013 return;
2015 dir.files = NULL;
2016 dir.alloc = 0;
2017 dir.nr = 0;
2018 dir.permille = options->dirstat_permille;
2019 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2021 changed = 0;
2022 for (i = 0; i < data->nr; i++) {
2023 struct diffstat_file *file = data->files[i];
2024 unsigned long damage = file->added + file->deleted;
2025 if (file->is_binary)
2027 * binary files counts bytes, not lines. Must find some
2028 * way to normalize binary bytes vs. textual lines.
2029 * The following heuristic assumes that there are 64
2030 * bytes per "line".
2031 * This is stupid and ugly, but very cheap...
2033 damage = (damage + 63) / 64;
2034 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2035 dir.files[dir.nr].name = file->name;
2036 dir.files[dir.nr].changed = damage;
2037 changed += damage;
2038 dir.nr++;
2041 /* This can happen even with many files, if everything was renames */
2042 if (!changed)
2043 return;
2045 /* Show all directories with more than x% of the changes */
2046 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
2047 gather_dirstat(options, &dir, changed, "", 0);
2050 static void free_diffstat_info(struct diffstat_t *diffstat)
2052 int i;
2053 for (i = 0; i < diffstat->nr; i++) {
2054 struct diffstat_file *f = diffstat->files[i];
2055 if (f->name != f->print_name)
2056 free(f->print_name);
2057 free(f->name);
2058 free(f->from_name);
2059 free(f);
2061 free(diffstat->files);
2064 struct checkdiff_t {
2065 const char *filename;
2066 int lineno;
2067 int conflict_marker_size;
2068 struct diff_options *o;
2069 unsigned ws_rule;
2070 unsigned status;
2073 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2075 char firstchar;
2076 int cnt;
2078 if (len < marker_size + 1)
2079 return 0;
2080 firstchar = line[0];
2081 switch (firstchar) {
2082 case '=': case '>': case '<': case '|':
2083 break;
2084 default:
2085 return 0;
2087 for (cnt = 1; cnt < marker_size; cnt++)
2088 if (line[cnt] != firstchar)
2089 return 0;
2090 /* line[1] thru line[marker_size-1] are same as firstchar */
2091 if (len < marker_size + 1 || !isspace(line[marker_size]))
2092 return 0;
2093 return 1;
2096 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2098 struct checkdiff_t *data = priv;
2099 int marker_size = data->conflict_marker_size;
2100 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2101 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2102 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2103 char *err;
2104 const char *line_prefix;
2106 assert(data->o);
2107 line_prefix = diff_line_prefix(data->o);
2109 if (line[0] == '+') {
2110 unsigned bad;
2111 data->lineno++;
2112 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2113 data->status |= 1;
2114 fprintf(data->o->file,
2115 "%s%s:%d: leftover conflict marker\n",
2116 line_prefix, data->filename, data->lineno);
2118 bad = ws_check(line + 1, len - 1, data->ws_rule);
2119 if (!bad)
2120 return;
2121 data->status |= bad;
2122 err = whitespace_error_string(bad);
2123 fprintf(data->o->file, "%s%s:%d: %s.\n",
2124 line_prefix, data->filename, data->lineno, err);
2125 free(err);
2126 emit_line(data->o, set, reset, line, 1);
2127 ws_check_emit(line + 1, len - 1, data->ws_rule,
2128 data->o->file, set, reset, ws);
2129 } else if (line[0] == ' ') {
2130 data->lineno++;
2131 } else if (line[0] == '@') {
2132 char *plus = strchr(line, '+');
2133 if (plus)
2134 data->lineno = strtol(plus, NULL, 10) - 1;
2135 else
2136 die("invalid diff");
2140 static unsigned char *deflate_it(char *data,
2141 unsigned long size,
2142 unsigned long *result_size)
2144 int bound;
2145 unsigned char *deflated;
2146 git_zstream stream;
2148 git_deflate_init(&stream, zlib_compression_level);
2149 bound = git_deflate_bound(&stream, size);
2150 deflated = xmalloc(bound);
2151 stream.next_out = deflated;
2152 stream.avail_out = bound;
2154 stream.next_in = (unsigned char *)data;
2155 stream.avail_in = size;
2156 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2157 ; /* nothing */
2158 git_deflate_end(&stream);
2159 *result_size = stream.total_out;
2160 return deflated;
2163 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two,
2164 const char *prefix)
2166 void *cp;
2167 void *delta;
2168 void *deflated;
2169 void *data;
2170 unsigned long orig_size;
2171 unsigned long delta_size;
2172 unsigned long deflate_size;
2173 unsigned long data_size;
2175 /* We could do deflated delta, or we could do just deflated two,
2176 * whichever is smaller.
2178 delta = NULL;
2179 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2180 if (one->size && two->size) {
2181 delta = diff_delta(one->ptr, one->size,
2182 two->ptr, two->size,
2183 &delta_size, deflate_size);
2184 if (delta) {
2185 void *to_free = delta;
2186 orig_size = delta_size;
2187 delta = deflate_it(delta, delta_size, &delta_size);
2188 free(to_free);
2192 if (delta && delta_size < deflate_size) {
2193 fprintf(file, "%sdelta %lu\n", prefix, orig_size);
2194 free(deflated);
2195 data = delta;
2196 data_size = delta_size;
2198 else {
2199 fprintf(file, "%sliteral %lu\n", prefix, two->size);
2200 free(delta);
2201 data = deflated;
2202 data_size = deflate_size;
2205 /* emit data encoded in base85 */
2206 cp = data;
2207 while (data_size) {
2208 int bytes = (52 < data_size) ? 52 : data_size;
2209 char line[70];
2210 data_size -= bytes;
2211 if (bytes <= 26)
2212 line[0] = bytes + 'A' - 1;
2213 else
2214 line[0] = bytes - 26 + 'a' - 1;
2215 encode_85(line + 1, cp, bytes);
2216 cp = (char *) cp + bytes;
2217 fprintf(file, "%s", prefix);
2218 fputs(line, file);
2219 fputc('\n', file);
2221 fprintf(file, "%s\n", prefix);
2222 free(data);
2225 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two,
2226 const char *prefix)
2228 fprintf(file, "%sGIT binary patch\n", prefix);
2229 emit_binary_diff_body(file, one, two, prefix);
2230 emit_binary_diff_body(file, two, one, prefix);
2233 int diff_filespec_is_binary(struct diff_filespec *one)
2235 if (one->is_binary == -1) {
2236 diff_filespec_load_driver(one);
2237 if (one->driver->binary != -1)
2238 one->is_binary = one->driver->binary;
2239 else {
2240 if (!one->data && DIFF_FILE_VALID(one))
2241 diff_populate_filespec(one, CHECK_BINARY);
2242 if (one->is_binary == -1 && one->data)
2243 one->is_binary = buffer_is_binary(one->data,
2244 one->size);
2245 if (one->is_binary == -1)
2246 one->is_binary = 0;
2249 return one->is_binary;
2252 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2254 diff_filespec_load_driver(one);
2255 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2258 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2260 if (!options->a_prefix)
2261 options->a_prefix = a;
2262 if (!options->b_prefix)
2263 options->b_prefix = b;
2266 struct userdiff_driver *get_textconv(struct diff_filespec *one)
2268 if (!DIFF_FILE_VALID(one))
2269 return NULL;
2271 diff_filespec_load_driver(one);
2272 return userdiff_get_textconv(one->driver);
2275 static void builtin_diff(const char *name_a,
2276 const char *name_b,
2277 struct diff_filespec *one,
2278 struct diff_filespec *two,
2279 const char *xfrm_msg,
2280 int must_show_header,
2281 struct diff_options *o,
2282 int complete_rewrite)
2284 mmfile_t mf1, mf2;
2285 const char *lbl[2];
2286 char *a_one, *b_two;
2287 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
2288 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2289 const char *a_prefix, *b_prefix;
2290 struct userdiff_driver *textconv_one = NULL;
2291 struct userdiff_driver *textconv_two = NULL;
2292 struct strbuf header = STRBUF_INIT;
2293 const char *line_prefix = diff_line_prefix(o);
2295 diff_set_mnemonic_prefix(o, "a/", "b/");
2296 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2297 a_prefix = o->b_prefix;
2298 b_prefix = o->a_prefix;
2299 } else {
2300 a_prefix = o->a_prefix;
2301 b_prefix = o->b_prefix;
2304 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
2305 (!one->mode || S_ISGITLINK(one->mode)) &&
2306 (!two->mode || S_ISGITLINK(two->mode))) {
2307 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2308 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2309 show_submodule_summary(o->file, one->path ? one->path : two->path,
2310 line_prefix,
2311 &one->oid, &two->oid,
2312 two->dirty_submodule,
2313 meta, del, add, reset);
2314 return;
2315 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
2316 (!one->mode || S_ISGITLINK(one->mode)) &&
2317 (!two->mode || S_ISGITLINK(two->mode))) {
2318 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2319 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2320 show_submodule_inline_diff(o->file, one->path ? one->path : two->path,
2321 line_prefix,
2322 &one->oid, &two->oid,
2323 two->dirty_submodule,
2324 meta, del, add, reset, o);
2325 return;
2328 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2329 textconv_one = get_textconv(one);
2330 textconv_two = get_textconv(two);
2333 /* Never use a non-valid filename anywhere if at all possible */
2334 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2335 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2337 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2338 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
2339 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2340 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
2341 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
2342 if (lbl[0][0] == '/') {
2343 /* /dev/null */
2344 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
2345 if (xfrm_msg)
2346 strbuf_addstr(&header, xfrm_msg);
2347 must_show_header = 1;
2349 else if (lbl[1][0] == '/') {
2350 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
2351 if (xfrm_msg)
2352 strbuf_addstr(&header, xfrm_msg);
2353 must_show_header = 1;
2355 else {
2356 if (one->mode != two->mode) {
2357 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
2358 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
2359 must_show_header = 1;
2361 if (xfrm_msg)
2362 strbuf_addstr(&header, xfrm_msg);
2365 * we do not run diff between different kind
2366 * of objects.
2368 if ((one->mode ^ two->mode) & S_IFMT)
2369 goto free_ab_and_return;
2370 if (complete_rewrite &&
2371 (textconv_one || !diff_filespec_is_binary(one)) &&
2372 (textconv_two || !diff_filespec_is_binary(two))) {
2373 fprintf(o->file, "%s", header.buf);
2374 strbuf_reset(&header);
2375 emit_rewrite_diff(name_a, name_b, one, two,
2376 textconv_one, textconv_two, o);
2377 o->found_changes = 1;
2378 goto free_ab_and_return;
2382 if (o->irreversible_delete && lbl[1][0] == '/') {
2383 fprintf(o->file, "%s", header.buf);
2384 strbuf_reset(&header);
2385 goto free_ab_and_return;
2386 } else if (!DIFF_OPT_TST(o, TEXT) &&
2387 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2388 (!textconv_two && diff_filespec_is_binary(two)) )) {
2389 if (!one->data && !two->data &&
2390 S_ISREG(one->mode) && S_ISREG(two->mode) &&
2391 !DIFF_OPT_TST(o, BINARY)) {
2392 if (!oidcmp(&one->oid, &two->oid)) {
2393 if (must_show_header)
2394 fprintf(o->file, "%s", header.buf);
2395 goto free_ab_and_return;
2397 fprintf(o->file, "%s", header.buf);
2398 fprintf(o->file, "%sBinary files %s and %s differ\n",
2399 line_prefix, lbl[0], lbl[1]);
2400 goto free_ab_and_return;
2402 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2403 die("unable to read files to diff");
2404 /* Quite common confusing case */
2405 if (mf1.size == mf2.size &&
2406 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2407 if (must_show_header)
2408 fprintf(o->file, "%s", header.buf);
2409 goto free_ab_and_return;
2411 fprintf(o->file, "%s", header.buf);
2412 strbuf_reset(&header);
2413 if (DIFF_OPT_TST(o, BINARY))
2414 emit_binary_diff(o->file, &mf1, &mf2, line_prefix);
2415 else
2416 fprintf(o->file, "%sBinary files %s and %s differ\n",
2417 line_prefix, lbl[0], lbl[1]);
2418 o->found_changes = 1;
2419 } else {
2420 /* Crazy xdl interfaces.. */
2421 const char *diffopts = getenv("GIT_DIFF_OPTS");
2422 const char *v;
2423 xpparam_t xpp;
2424 xdemitconf_t xecfg;
2425 struct emit_callback ecbdata;
2426 const struct userdiff_funcname *pe;
2428 if (must_show_header) {
2429 fprintf(o->file, "%s", header.buf);
2430 strbuf_reset(&header);
2433 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2434 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
2436 pe = diff_funcname_pattern(one);
2437 if (!pe)
2438 pe = diff_funcname_pattern(two);
2440 memset(&xpp, 0, sizeof(xpp));
2441 memset(&xecfg, 0, sizeof(xecfg));
2442 memset(&ecbdata, 0, sizeof(ecbdata));
2443 ecbdata.label_path = lbl;
2444 ecbdata.color_diff = want_color(o->use_color);
2445 ecbdata.ws_rule = whitespace_rule(name_b);
2446 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
2447 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2448 ecbdata.opt = o;
2449 ecbdata.header = header.len ? &header : NULL;
2450 xpp.flags = o->xdl_opts;
2451 xecfg.ctxlen = o->context;
2452 xecfg.interhunkctxlen = o->interhunkcontext;
2453 xecfg.flags = XDL_EMIT_FUNCNAMES;
2454 if (DIFF_OPT_TST(o, FUNCCONTEXT))
2455 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
2456 if (pe)
2457 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
2458 if (!diffopts)
2460 else if (skip_prefix(diffopts, "--unified=", &v))
2461 xecfg.ctxlen = strtoul(v, NULL, 10);
2462 else if (skip_prefix(diffopts, "-u", &v))
2463 xecfg.ctxlen = strtoul(v, NULL, 10);
2464 if (o->word_diff)
2465 init_diff_words_data(&ecbdata, o, one, two);
2466 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2467 &xpp, &xecfg))
2468 die("unable to generate diff for %s", one->path);
2469 if (o->word_diff)
2470 free_diff_words_data(&ecbdata);
2471 if (textconv_one)
2472 free(mf1.ptr);
2473 if (textconv_two)
2474 free(mf2.ptr);
2475 xdiff_clear_find_func(&xecfg);
2478 free_ab_and_return:
2479 strbuf_release(&header);
2480 diff_free_filespec_data(one);
2481 diff_free_filespec_data(two);
2482 free(a_one);
2483 free(b_two);
2484 return;
2487 static void builtin_diffstat(const char *name_a, const char *name_b,
2488 struct diff_filespec *one,
2489 struct diff_filespec *two,
2490 struct diffstat_t *diffstat,
2491 struct diff_options *o,
2492 struct diff_filepair *p)
2494 mmfile_t mf1, mf2;
2495 struct diffstat_file *data;
2496 int same_contents;
2497 int complete_rewrite = 0;
2499 if (!DIFF_PAIR_UNMERGED(p)) {
2500 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2501 complete_rewrite = 1;
2504 data = diffstat_add(diffstat, name_a, name_b);
2505 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
2507 if (!one || !two) {
2508 data->is_unmerged = 1;
2509 return;
2512 same_contents = !oidcmp(&one->oid, &two->oid);
2514 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2515 data->is_binary = 1;
2516 if (same_contents) {
2517 data->added = 0;
2518 data->deleted = 0;
2519 } else {
2520 data->added = diff_filespec_size(two);
2521 data->deleted = diff_filespec_size(one);
2525 else if (complete_rewrite) {
2526 diff_populate_filespec(one, 0);
2527 diff_populate_filespec(two, 0);
2528 data->deleted = count_lines(one->data, one->size);
2529 data->added = count_lines(two->data, two->size);
2532 else if (!same_contents) {
2533 /* Crazy xdl interfaces.. */
2534 xpparam_t xpp;
2535 xdemitconf_t xecfg;
2537 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2538 die("unable to read files to diff");
2540 memset(&xpp, 0, sizeof(xpp));
2541 memset(&xecfg, 0, sizeof(xecfg));
2542 xpp.flags = o->xdl_opts;
2543 xecfg.ctxlen = o->context;
2544 xecfg.interhunkctxlen = o->interhunkcontext;
2545 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2546 &xpp, &xecfg))
2547 die("unable to generate diffstat for %s", one->path);
2550 diff_free_filespec_data(one);
2551 diff_free_filespec_data(two);
2554 static void builtin_checkdiff(const char *name_a, const char *name_b,
2555 const char *attr_path,
2556 struct diff_filespec *one,
2557 struct diff_filespec *two,
2558 struct diff_options *o)
2560 mmfile_t mf1, mf2;
2561 struct checkdiff_t data;
2563 if (!two)
2564 return;
2566 memset(&data, 0, sizeof(data));
2567 data.filename = name_b ? name_b : name_a;
2568 data.lineno = 0;
2569 data.o = o;
2570 data.ws_rule = whitespace_rule(attr_path);
2571 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2573 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2574 die("unable to read files to diff");
2577 * All the other codepaths check both sides, but not checking
2578 * the "old" side here is deliberate. We are checking the newly
2579 * introduced changes, and as long as the "new" side is text, we
2580 * can and should check what it introduces.
2582 if (diff_filespec_is_binary(two))
2583 goto free_and_return;
2584 else {
2585 /* Crazy xdl interfaces.. */
2586 xpparam_t xpp;
2587 xdemitconf_t xecfg;
2589 memset(&xpp, 0, sizeof(xpp));
2590 memset(&xecfg, 0, sizeof(xecfg));
2591 xecfg.ctxlen = 1; /* at least one context line */
2592 xpp.flags = 0;
2593 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2594 &xpp, &xecfg))
2595 die("unable to generate checkdiff for %s", one->path);
2597 if (data.ws_rule & WS_BLANK_AT_EOF) {
2598 struct emit_callback ecbdata;
2599 int blank_at_eof;
2601 ecbdata.ws_rule = data.ws_rule;
2602 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2603 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
2605 if (blank_at_eof) {
2606 static char *err;
2607 if (!err)
2608 err = whitespace_error_string(WS_BLANK_AT_EOF);
2609 fprintf(o->file, "%s:%d: %s.\n",
2610 data.filename, blank_at_eof, err);
2611 data.status = 1; /* report errors */
2615 free_and_return:
2616 diff_free_filespec_data(one);
2617 diff_free_filespec_data(two);
2618 if (data.status)
2619 DIFF_OPT_SET(o, CHECK_FAILED);
2622 struct diff_filespec *alloc_filespec(const char *path)
2624 struct diff_filespec *spec;
2626 FLEXPTR_ALLOC_STR(spec, path, path);
2627 spec->count = 1;
2628 spec->is_binary = -1;
2629 return spec;
2632 void free_filespec(struct diff_filespec *spec)
2634 if (!--spec->count) {
2635 diff_free_filespec_data(spec);
2636 free(spec);
2640 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
2641 int sha1_valid, unsigned short mode)
2643 if (mode) {
2644 spec->mode = canon_mode(mode);
2645 hashcpy(spec->oid.hash, sha1);
2646 spec->oid_valid = sha1_valid;
2651 * Given a name and sha1 pair, if the index tells us the file in
2652 * the work tree has that object contents, return true, so that
2653 * prepare_temp_file() does not have to inflate and extract.
2655 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2657 const struct cache_entry *ce;
2658 struct stat st;
2659 int pos, len;
2662 * We do not read the cache ourselves here, because the
2663 * benchmark with my previous version that always reads cache
2664 * shows that it makes things worse for diff-tree comparing
2665 * two linux-2.6 kernel trees in an already checked out work
2666 * tree. This is because most diff-tree comparisons deal with
2667 * only a small number of files, while reading the cache is
2668 * expensive for a large project, and its cost outweighs the
2669 * savings we get by not inflating the object to a temporary
2670 * file. Practically, this code only helps when we are used
2671 * by diff-cache --cached, which does read the cache before
2672 * calling us.
2674 if (!active_cache)
2675 return 0;
2677 /* We want to avoid the working directory if our caller
2678 * doesn't need the data in a normal file, this system
2679 * is rather slow with its stat/open/mmap/close syscalls,
2680 * and the object is contained in a pack file. The pack
2681 * is probably already open and will be faster to obtain
2682 * the data through than the working directory. Loose
2683 * objects however would tend to be slower as they need
2684 * to be individually opened and inflated.
2686 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2687 return 0;
2690 * Similarly, if we'd have to convert the file contents anyway, that
2691 * makes the optimization not worthwhile.
2693 if (!want_file && would_convert_to_git(name))
2694 return 0;
2696 len = strlen(name);
2697 pos = cache_name_pos(name, len);
2698 if (pos < 0)
2699 return 0;
2700 ce = active_cache[pos];
2703 * This is not the sha1 we are looking for, or
2704 * unreusable because it is not a regular file.
2706 if (hashcmp(sha1, ce->oid.hash) || !S_ISREG(ce->ce_mode))
2707 return 0;
2710 * If ce is marked as "assume unchanged", there is no
2711 * guarantee that work tree matches what we are looking for.
2713 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2714 return 0;
2717 * If ce matches the file in the work tree, we can reuse it.
2719 if (ce_uptodate(ce) ||
2720 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2721 return 1;
2723 return 0;
2726 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2728 struct strbuf buf = STRBUF_INIT;
2729 char *dirty = "";
2731 /* Are we looking at the work tree? */
2732 if (s->dirty_submodule)
2733 dirty = "-dirty";
2735 strbuf_addf(&buf, "Subproject commit %s%s\n",
2736 oid_to_hex(&s->oid), dirty);
2737 s->size = buf.len;
2738 if (size_only) {
2739 s->data = NULL;
2740 strbuf_release(&buf);
2741 } else {
2742 s->data = strbuf_detach(&buf, NULL);
2743 s->should_free = 1;
2745 return 0;
2749 * While doing rename detection and pickaxe operation, we may need to
2750 * grab the data for the blob (or file) for our own in-core comparison.
2751 * diff_filespec has data and size fields for this purpose.
2753 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
2755 int size_only = flags & CHECK_SIZE_ONLY;
2756 int err = 0;
2758 * demote FAIL to WARN to allow inspecting the situation
2759 * instead of refusing.
2761 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
2762 ? SAFE_CRLF_WARN
2763 : safe_crlf);
2765 if (!DIFF_FILE_VALID(s))
2766 die("internal error: asking to populate invalid file.");
2767 if (S_ISDIR(s->mode))
2768 return -1;
2770 if (s->data)
2771 return 0;
2773 if (size_only && 0 < s->size)
2774 return 0;
2776 if (S_ISGITLINK(s->mode))
2777 return diff_populate_gitlink(s, size_only);
2779 if (!s->oid_valid ||
2780 reuse_worktree_file(s->path, s->oid.hash, 0)) {
2781 struct strbuf buf = STRBUF_INIT;
2782 struct stat st;
2783 int fd;
2785 if (lstat(s->path, &st) < 0) {
2786 if (errno == ENOENT) {
2787 err_empty:
2788 err = -1;
2789 empty:
2790 s->data = (char *)"";
2791 s->size = 0;
2792 return err;
2795 s->size = xsize_t(st.st_size);
2796 if (!s->size)
2797 goto empty;
2798 if (S_ISLNK(st.st_mode)) {
2799 struct strbuf sb = STRBUF_INIT;
2801 if (strbuf_readlink(&sb, s->path, s->size))
2802 goto err_empty;
2803 s->size = sb.len;
2804 s->data = strbuf_detach(&sb, NULL);
2805 s->should_free = 1;
2806 return 0;
2808 if (size_only)
2809 return 0;
2810 if ((flags & CHECK_BINARY) &&
2811 s->size > big_file_threshold && s->is_binary == -1) {
2812 s->is_binary = 1;
2813 return 0;
2815 fd = open(s->path, O_RDONLY);
2816 if (fd < 0)
2817 goto err_empty;
2818 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2819 close(fd);
2820 s->should_munmap = 1;
2823 * Convert from working tree format to canonical git format
2825 if (convert_to_git(s->path, s->data, s->size, &buf, crlf_warn)) {
2826 size_t size = 0;
2827 munmap(s->data, s->size);
2828 s->should_munmap = 0;
2829 s->data = strbuf_detach(&buf, &size);
2830 s->size = size;
2831 s->should_free = 1;
2834 else {
2835 enum object_type type;
2836 if (size_only || (flags & CHECK_BINARY)) {
2837 type = sha1_object_info(s->oid.hash, &s->size);
2838 if (type < 0)
2839 die("unable to read %s",
2840 oid_to_hex(&s->oid));
2841 if (size_only)
2842 return 0;
2843 if (s->size > big_file_threshold && s->is_binary == -1) {
2844 s->is_binary = 1;
2845 return 0;
2848 s->data = read_sha1_file(s->oid.hash, &type, &s->size);
2849 if (!s->data)
2850 die("unable to read %s", oid_to_hex(&s->oid));
2851 s->should_free = 1;
2853 return 0;
2856 void diff_free_filespec_blob(struct diff_filespec *s)
2858 if (s->should_free)
2859 free(s->data);
2860 else if (s->should_munmap)
2861 munmap(s->data, s->size);
2863 if (s->should_free || s->should_munmap) {
2864 s->should_free = s->should_munmap = 0;
2865 s->data = NULL;
2869 void diff_free_filespec_data(struct diff_filespec *s)
2871 diff_free_filespec_blob(s);
2872 free(s->cnt_data);
2873 s->cnt_data = NULL;
2876 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2877 void *blob,
2878 unsigned long size,
2879 const struct object_id *oid,
2880 int mode)
2882 int fd;
2883 struct strbuf buf = STRBUF_INIT;
2884 struct strbuf template = STRBUF_INIT;
2885 char *path_dup = xstrdup(path);
2886 const char *base = basename(path_dup);
2888 /* Generate "XXXXXX_basename.ext" */
2889 strbuf_addstr(&template, "XXXXXX_");
2890 strbuf_addstr(&template, base);
2892 fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
2893 if (fd < 0)
2894 die_errno("unable to create temp-file");
2895 if (convert_to_working_tree(path,
2896 (const char *)blob, (size_t)size, &buf)) {
2897 blob = buf.buf;
2898 size = buf.len;
2900 if (write_in_full(fd, blob, size) != size)
2901 die_errno("unable to write temp-file");
2902 close_tempfile(&temp->tempfile);
2903 temp->name = get_tempfile_path(&temp->tempfile);
2904 oid_to_hex_r(temp->hex, oid);
2905 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
2906 strbuf_release(&buf);
2907 strbuf_release(&template);
2908 free(path_dup);
2911 static struct diff_tempfile *prepare_temp_file(const char *name,
2912 struct diff_filespec *one)
2914 struct diff_tempfile *temp = claim_diff_tempfile();
2916 if (!DIFF_FILE_VALID(one)) {
2917 not_a_valid_file:
2918 /* A '-' entry produces this for file-2, and
2919 * a '+' entry produces this for file-1.
2921 temp->name = "/dev/null";
2922 xsnprintf(temp->hex, sizeof(temp->hex), ".");
2923 xsnprintf(temp->mode, sizeof(temp->mode), ".");
2924 return temp;
2927 if (!S_ISGITLINK(one->mode) &&
2928 (!one->oid_valid ||
2929 reuse_worktree_file(name, one->oid.hash, 1))) {
2930 struct stat st;
2931 if (lstat(name, &st) < 0) {
2932 if (errno == ENOENT)
2933 goto not_a_valid_file;
2934 die_errno("stat(%s)", name);
2936 if (S_ISLNK(st.st_mode)) {
2937 struct strbuf sb = STRBUF_INIT;
2938 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2939 die_errno("readlink(%s)", name);
2940 prep_temp_blob(name, temp, sb.buf, sb.len,
2941 (one->oid_valid ?
2942 &one->oid : &null_oid),
2943 (one->oid_valid ?
2944 one->mode : S_IFLNK));
2945 strbuf_release(&sb);
2947 else {
2948 /* we can borrow from the file in the work tree */
2949 temp->name = name;
2950 if (!one->oid_valid)
2951 sha1_to_hex_r(temp->hex, null_sha1);
2952 else
2953 sha1_to_hex_r(temp->hex, one->oid.hash);
2954 /* Even though we may sometimes borrow the
2955 * contents from the work tree, we always want
2956 * one->mode. mode is trustworthy even when
2957 * !(one->sha1_valid), as long as
2958 * DIFF_FILE_VALID(one).
2960 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
2962 return temp;
2964 else {
2965 if (diff_populate_filespec(one, 0))
2966 die("cannot read data blob for %s", one->path);
2967 prep_temp_blob(name, temp, one->data, one->size,
2968 &one->oid, one->mode);
2970 return temp;
2973 static void add_external_diff_name(struct argv_array *argv,
2974 const char *name,
2975 struct diff_filespec *df)
2977 struct diff_tempfile *temp = prepare_temp_file(name, df);
2978 argv_array_push(argv, temp->name);
2979 argv_array_push(argv, temp->hex);
2980 argv_array_push(argv, temp->mode);
2983 /* An external diff command takes:
2985 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2986 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2989 static void run_external_diff(const char *pgm,
2990 const char *name,
2991 const char *other,
2992 struct diff_filespec *one,
2993 struct diff_filespec *two,
2994 const char *xfrm_msg,
2995 int complete_rewrite,
2996 struct diff_options *o)
2998 struct argv_array argv = ARGV_ARRAY_INIT;
2999 struct argv_array env = ARGV_ARRAY_INIT;
3000 struct diff_queue_struct *q = &diff_queued_diff;
3002 argv_array_push(&argv, pgm);
3003 argv_array_push(&argv, name);
3005 if (one && two) {
3006 add_external_diff_name(&argv, name, one);
3007 if (!other)
3008 add_external_diff_name(&argv, name, two);
3009 else {
3010 add_external_diff_name(&argv, other, two);
3011 argv_array_push(&argv, other);
3012 argv_array_push(&argv, xfrm_msg);
3016 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3017 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3019 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3020 die(_("external diff died, stopping at %s"), name);
3022 remove_tempfile();
3023 argv_array_clear(&argv);
3024 argv_array_clear(&env);
3027 static int similarity_index(struct diff_filepair *p)
3029 return p->score * 100 / MAX_SCORE;
3032 static void fill_metainfo(struct strbuf *msg,
3033 const char *name,
3034 const char *other,
3035 struct diff_filespec *one,
3036 struct diff_filespec *two,
3037 struct diff_options *o,
3038 struct diff_filepair *p,
3039 int *must_show_header,
3040 int use_color)
3042 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3043 const char *reset = diff_get_color(use_color, DIFF_RESET);
3044 const char *line_prefix = diff_line_prefix(o);
3046 *must_show_header = 1;
3047 strbuf_init(msg, PATH_MAX * 2 + 300);
3048 switch (p->status) {
3049 case DIFF_STATUS_COPIED:
3050 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3051 line_prefix, set, similarity_index(p));
3052 strbuf_addf(msg, "%s\n%s%scopy from ",
3053 reset, line_prefix, set);
3054 quote_c_style(name, msg, NULL, 0);
3055 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3056 quote_c_style(other, msg, NULL, 0);
3057 strbuf_addf(msg, "%s\n", reset);
3058 break;
3059 case DIFF_STATUS_RENAMED:
3060 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3061 line_prefix, set, similarity_index(p));
3062 strbuf_addf(msg, "%s\n%s%srename from ",
3063 reset, line_prefix, set);
3064 quote_c_style(name, msg, NULL, 0);
3065 strbuf_addf(msg, "%s\n%s%srename to ",
3066 reset, line_prefix, set);
3067 quote_c_style(other, msg, NULL, 0);
3068 strbuf_addf(msg, "%s\n", reset);
3069 break;
3070 case DIFF_STATUS_MODIFIED:
3071 if (p->score) {
3072 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3073 line_prefix,
3074 set, similarity_index(p), reset);
3075 break;
3077 /* fallthru */
3078 default:
3079 *must_show_header = 0;
3081 if (one && two && oidcmp(&one->oid, &two->oid)) {
3082 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3084 if (DIFF_OPT_TST(o, BINARY)) {
3085 mmfile_t mf;
3086 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3087 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3088 abbrev = 40;
3090 strbuf_addf(msg, "%s%sindex %s..", line_prefix, set,
3091 find_unique_abbrev(one->oid.hash, abbrev));
3092 strbuf_addstr(msg, find_unique_abbrev(two->oid.hash, abbrev));
3093 if (one->mode == two->mode)
3094 strbuf_addf(msg, " %06o", one->mode);
3095 strbuf_addf(msg, "%s\n", reset);
3099 static void run_diff_cmd(const char *pgm,
3100 const char *name,
3101 const char *other,
3102 const char *attr_path,
3103 struct diff_filespec *one,
3104 struct diff_filespec *two,
3105 struct strbuf *msg,
3106 struct diff_options *o,
3107 struct diff_filepair *p)
3109 const char *xfrm_msg = NULL;
3110 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3111 int must_show_header = 0;
3114 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3115 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3116 if (drv && drv->external)
3117 pgm = drv->external;
3120 if (msg) {
3122 * don't use colors when the header is intended for an
3123 * external diff driver
3125 fill_metainfo(msg, name, other, one, two, o, p,
3126 &must_show_header,
3127 want_color(o->use_color) && !pgm);
3128 xfrm_msg = msg->len ? msg->buf : NULL;
3131 if (pgm) {
3132 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3133 complete_rewrite, o);
3134 return;
3136 if (one && two)
3137 builtin_diff(name, other ? other : name,
3138 one, two, xfrm_msg, must_show_header,
3139 o, complete_rewrite);
3140 else
3141 fprintf(o->file, "* Unmerged path %s\n", name);
3144 static void diff_fill_sha1_info(struct diff_filespec *one)
3146 if (DIFF_FILE_VALID(one)) {
3147 if (!one->oid_valid) {
3148 struct stat st;
3149 if (one->is_stdin) {
3150 oidclr(&one->oid);
3151 return;
3153 if (lstat(one->path, &st) < 0)
3154 die_errno("stat '%s'", one->path);
3155 if (index_path(one->oid.hash, one->path, &st, 0))
3156 die("cannot hash %s", one->path);
3159 else
3160 oidclr(&one->oid);
3163 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3165 /* Strip the prefix but do not molest /dev/null and absolute paths */
3166 if (*namep && **namep != '/') {
3167 *namep += prefix_length;
3168 if (**namep == '/')
3169 ++*namep;
3171 if (*otherp && **otherp != '/') {
3172 *otherp += prefix_length;
3173 if (**otherp == '/')
3174 ++*otherp;
3178 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3180 const char *pgm = external_diff();
3181 struct strbuf msg;
3182 struct diff_filespec *one = p->one;
3183 struct diff_filespec *two = p->two;
3184 const char *name;
3185 const char *other;
3186 const char *attr_path;
3188 name = p->one->path;
3189 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3190 attr_path = name;
3191 if (o->prefix_length)
3192 strip_prefix(o->prefix_length, &name, &other);
3194 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3195 pgm = NULL;
3197 if (DIFF_PAIR_UNMERGED(p)) {
3198 run_diff_cmd(pgm, name, NULL, attr_path,
3199 NULL, NULL, NULL, o, p);
3200 return;
3203 diff_fill_sha1_info(one);
3204 diff_fill_sha1_info(two);
3206 if (!pgm &&
3207 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3208 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3210 * a filepair that changes between file and symlink
3211 * needs to be split into deletion and creation.
3213 struct diff_filespec *null = alloc_filespec(two->path);
3214 run_diff_cmd(NULL, name, other, attr_path,
3215 one, null, &msg, o, p);
3216 free(null);
3217 strbuf_release(&msg);
3219 null = alloc_filespec(one->path);
3220 run_diff_cmd(NULL, name, other, attr_path,
3221 null, two, &msg, o, p);
3222 free(null);
3224 else
3225 run_diff_cmd(pgm, name, other, attr_path,
3226 one, two, &msg, o, p);
3228 strbuf_release(&msg);
3231 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3232 struct diffstat_t *diffstat)
3234 const char *name;
3235 const char *other;
3237 if (DIFF_PAIR_UNMERGED(p)) {
3238 /* unmerged */
3239 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
3240 return;
3243 name = p->one->path;
3244 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3246 if (o->prefix_length)
3247 strip_prefix(o->prefix_length, &name, &other);
3249 diff_fill_sha1_info(p->one);
3250 diff_fill_sha1_info(p->two);
3252 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
3255 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3257 const char *name;
3258 const char *other;
3259 const char *attr_path;
3261 if (DIFF_PAIR_UNMERGED(p)) {
3262 /* unmerged */
3263 return;
3266 name = p->one->path;
3267 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3268 attr_path = other ? other : name;
3270 if (o->prefix_length)
3271 strip_prefix(o->prefix_length, &name, &other);
3273 diff_fill_sha1_info(p->one);
3274 diff_fill_sha1_info(p->two);
3276 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
3279 void diff_setup(struct diff_options *options)
3281 memcpy(options, &default_diff_options, sizeof(*options));
3283 options->file = stdout;
3285 options->line_termination = '\n';
3286 options->break_opt = -1;
3287 options->rename_limit = -1;
3288 options->dirstat_permille = diff_dirstat_permille_default;
3289 options->context = diff_context_default;
3290 options->ws_error_highlight = WSEH_NEW;
3291 DIFF_OPT_SET(options, RENAME_EMPTY);
3293 /* pathchange left =NULL by default */
3294 options->change = diff_change;
3295 options->add_remove = diff_addremove;
3296 options->use_color = diff_use_color_default;
3297 options->detect_rename = diff_detect_rename_default;
3298 options->xdl_opts |= diff_algorithm;
3299 if (diff_compaction_heuristic)
3300 DIFF_XDL_SET(options, COMPACTION_HEURISTIC);
3302 options->orderfile = diff_order_file_cfg;
3304 if (diff_no_prefix) {
3305 options->a_prefix = options->b_prefix = "";
3306 } else if (!diff_mnemonic_prefix) {
3307 options->a_prefix = "a/";
3308 options->b_prefix = "b/";
3312 void diff_setup_done(struct diff_options *options)
3314 int count = 0;
3316 if (options->set_default)
3317 options->set_default(options);
3319 if (options->output_format & DIFF_FORMAT_NAME)
3320 count++;
3321 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3322 count++;
3323 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3324 count++;
3325 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3326 count++;
3327 if (count > 1)
3328 die("--name-only, --name-status, --check and -s are mutually exclusive");
3331 * Most of the time we can say "there are changes"
3332 * only by checking if there are changed paths, but
3333 * --ignore-whitespace* options force us to look
3334 * inside contents.
3337 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3338 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3339 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3340 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3341 else
3342 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3344 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3345 options->detect_rename = DIFF_DETECT_COPY;
3347 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3348 options->prefix = NULL;
3349 if (options->prefix)
3350 options->prefix_length = strlen(options->prefix);
3351 else
3352 options->prefix_length = 0;
3354 if (options->output_format & (DIFF_FORMAT_NAME |
3355 DIFF_FORMAT_NAME_STATUS |
3356 DIFF_FORMAT_CHECKDIFF |
3357 DIFF_FORMAT_NO_OUTPUT))
3358 options->output_format &= ~(DIFF_FORMAT_RAW |
3359 DIFF_FORMAT_NUMSTAT |
3360 DIFF_FORMAT_DIFFSTAT |
3361 DIFF_FORMAT_SHORTSTAT |
3362 DIFF_FORMAT_DIRSTAT |
3363 DIFF_FORMAT_SUMMARY |
3364 DIFF_FORMAT_PATCH);
3367 * These cases always need recursive; we do not drop caller-supplied
3368 * recursive bits for other formats here.
3370 if (options->output_format & (DIFF_FORMAT_PATCH |
3371 DIFF_FORMAT_NUMSTAT |
3372 DIFF_FORMAT_DIFFSTAT |
3373 DIFF_FORMAT_SHORTSTAT |
3374 DIFF_FORMAT_DIRSTAT |
3375 DIFF_FORMAT_SUMMARY |
3376 DIFF_FORMAT_CHECKDIFF))
3377 DIFF_OPT_SET(options, RECURSIVE);
3379 * Also pickaxe would not work very well if you do not say recursive
3381 if (options->pickaxe)
3382 DIFF_OPT_SET(options, RECURSIVE);
3384 * When patches are generated, submodules diffed against the work tree
3385 * must be checked for dirtiness too so it can be shown in the output
3387 if (options->output_format & DIFF_FORMAT_PATCH)
3388 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
3390 if (options->detect_rename && options->rename_limit < 0)
3391 options->rename_limit = diff_rename_limit_default;
3392 if (options->setup & DIFF_SETUP_USE_CACHE) {
3393 if (!active_cache)
3394 /* read-cache does not die even when it fails
3395 * so it is safe for us to do this here. Also
3396 * it does not smudge active_cache or active_nr
3397 * when it fails, so we do not have to worry about
3398 * cleaning it up ourselves either.
3400 read_cache();
3402 if (40 < options->abbrev)
3403 options->abbrev = 40; /* full */
3406 * It does not make sense to show the first hit we happened
3407 * to have found. It does not make sense not to return with
3408 * exit code in such a case either.
3410 if (DIFF_OPT_TST(options, QUICK)) {
3411 options->output_format = DIFF_FORMAT_NO_OUTPUT;
3412 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3415 options->diff_path_counter = 0;
3417 if (DIFF_OPT_TST(options, FOLLOW_RENAMES) && options->pathspec.nr != 1)
3418 die(_("--follow requires exactly one pathspec"));
3421 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
3423 char c, *eq;
3424 int len;
3426 if (*arg != '-')
3427 return 0;
3428 c = *++arg;
3429 if (!c)
3430 return 0;
3431 if (c == arg_short) {
3432 c = *++arg;
3433 if (!c)
3434 return 1;
3435 if (val && isdigit(c)) {
3436 char *end;
3437 int n = strtoul(arg, &end, 10);
3438 if (*end)
3439 return 0;
3440 *val = n;
3441 return 1;
3443 return 0;
3445 if (c != '-')
3446 return 0;
3447 arg++;
3448 eq = strchrnul(arg, '=');
3449 len = eq - arg;
3450 if (!len || strncmp(arg, arg_long, len))
3451 return 0;
3452 if (*eq) {
3453 int n;
3454 char *end;
3455 if (!isdigit(*++eq))
3456 return 0;
3457 n = strtoul(eq, &end, 10);
3458 if (*end)
3459 return 0;
3460 *val = n;
3462 return 1;
3465 static int diff_scoreopt_parse(const char *opt);
3467 static inline int short_opt(char opt, const char **argv,
3468 const char **optarg)
3470 const char *arg = argv[0];
3471 if (arg[0] != '-' || arg[1] != opt)
3472 return 0;
3473 if (arg[2] != '\0') {
3474 *optarg = arg + 2;
3475 return 1;
3477 if (!argv[1])
3478 die("Option '%c' requires a value", opt);
3479 *optarg = argv[1];
3480 return 2;
3483 int parse_long_opt(const char *opt, const char **argv,
3484 const char **optarg)
3486 const char *arg = argv[0];
3487 if (!skip_prefix(arg, "--", &arg))
3488 return 0;
3489 if (!skip_prefix(arg, opt, &arg))
3490 return 0;
3491 if (*arg == '=') { /* stuck form: --option=value */
3492 *optarg = arg + 1;
3493 return 1;
3495 if (*arg != '\0')
3496 return 0;
3497 /* separate form: --option value */
3498 if (!argv[1])
3499 die("Option '--%s' requires a value", opt);
3500 *optarg = argv[1];
3501 return 2;
3504 static int stat_opt(struct diff_options *options, const char **av)
3506 const char *arg = av[0];
3507 char *end;
3508 int width = options->stat_width;
3509 int name_width = options->stat_name_width;
3510 int graph_width = options->stat_graph_width;
3511 int count = options->stat_count;
3512 int argcount = 1;
3514 if (!skip_prefix(arg, "--stat", &arg))
3515 die("BUG: stat option does not begin with --stat: %s", arg);
3516 end = (char *)arg;
3518 switch (*arg) {
3519 case '-':
3520 if (skip_prefix(arg, "-width", &arg)) {
3521 if (*arg == '=')
3522 width = strtoul(arg + 1, &end, 10);
3523 else if (!*arg && !av[1])
3524 die("Option '--stat-width' requires a value");
3525 else if (!*arg) {
3526 width = strtoul(av[1], &end, 10);
3527 argcount = 2;
3529 } else if (skip_prefix(arg, "-name-width", &arg)) {
3530 if (*arg == '=')
3531 name_width = strtoul(arg + 1, &end, 10);
3532 else if (!*arg && !av[1])
3533 die("Option '--stat-name-width' requires a value");
3534 else if (!*arg) {
3535 name_width = strtoul(av[1], &end, 10);
3536 argcount = 2;
3538 } else if (skip_prefix(arg, "-graph-width", &arg)) {
3539 if (*arg == '=')
3540 graph_width = strtoul(arg + 1, &end, 10);
3541 else if (!*arg && !av[1])
3542 die("Option '--stat-graph-width' requires a value");
3543 else if (!*arg) {
3544 graph_width = strtoul(av[1], &end, 10);
3545 argcount = 2;
3547 } else if (skip_prefix(arg, "-count", &arg)) {
3548 if (*arg == '=')
3549 count = strtoul(arg + 1, &end, 10);
3550 else if (!*arg && !av[1])
3551 die("Option '--stat-count' requires a value");
3552 else if (!*arg) {
3553 count = strtoul(av[1], &end, 10);
3554 argcount = 2;
3557 break;
3558 case '=':
3559 width = strtoul(arg+1, &end, 10);
3560 if (*end == ',')
3561 name_width = strtoul(end+1, &end, 10);
3562 if (*end == ',')
3563 count = strtoul(end+1, &end, 10);
3566 /* Important! This checks all the error cases! */
3567 if (*end)
3568 return 0;
3569 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3570 options->stat_name_width = name_width;
3571 options->stat_graph_width = graph_width;
3572 options->stat_width = width;
3573 options->stat_count = count;
3574 return argcount;
3577 static int parse_dirstat_opt(struct diff_options *options, const char *params)
3579 struct strbuf errmsg = STRBUF_INIT;
3580 if (parse_dirstat_params(options, params, &errmsg))
3581 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
3582 errmsg.buf);
3583 strbuf_release(&errmsg);
3585 * The caller knows a dirstat-related option is given from the command
3586 * line; allow it to say "return this_function();"
3588 options->output_format |= DIFF_FORMAT_DIRSTAT;
3589 return 1;
3592 static int parse_submodule_opt(struct diff_options *options, const char *value)
3594 if (parse_submodule_params(options, value))
3595 die(_("Failed to parse --submodule option parameter: '%s'"),
3596 value);
3597 return 1;
3600 static const char diff_status_letters[] = {
3601 DIFF_STATUS_ADDED,
3602 DIFF_STATUS_COPIED,
3603 DIFF_STATUS_DELETED,
3604 DIFF_STATUS_MODIFIED,
3605 DIFF_STATUS_RENAMED,
3606 DIFF_STATUS_TYPE_CHANGED,
3607 DIFF_STATUS_UNKNOWN,
3608 DIFF_STATUS_UNMERGED,
3609 DIFF_STATUS_FILTER_AON,
3610 DIFF_STATUS_FILTER_BROKEN,
3611 '\0',
3614 static unsigned int filter_bit['Z' + 1];
3616 static void prepare_filter_bits(void)
3618 int i;
3620 if (!filter_bit[DIFF_STATUS_ADDED]) {
3621 for (i = 0; diff_status_letters[i]; i++)
3622 filter_bit[(int) diff_status_letters[i]] = (1 << i);
3626 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
3628 return opt->filter & filter_bit[(int) status];
3631 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
3633 int i, optch;
3635 prepare_filter_bits();
3638 * If there is a negation e.g. 'd' in the input, and we haven't
3639 * initialized the filter field with another --diff-filter, start
3640 * from full set of bits, except for AON.
3642 if (!opt->filter) {
3643 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
3644 if (optch < 'a' || 'z' < optch)
3645 continue;
3646 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
3647 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
3648 break;
3652 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
3653 unsigned int bit;
3654 int negate;
3656 if ('a' <= optch && optch <= 'z') {
3657 negate = 1;
3658 optch = toupper(optch);
3659 } else {
3660 negate = 0;
3663 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
3664 if (!bit)
3665 return optarg[i];
3666 if (negate)
3667 opt->filter &= ~bit;
3668 else
3669 opt->filter |= bit;
3671 return 0;
3674 static void enable_patch_output(int *fmt) {
3675 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
3676 *fmt |= DIFF_FORMAT_PATCH;
3679 static int parse_one_token(const char **arg, const char *token)
3681 const char *rest;
3682 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
3683 *arg = rest;
3684 return 1;
3686 return 0;
3689 static int parse_ws_error_highlight(struct diff_options *opt, const char *arg)
3691 const char *orig_arg = arg;
3692 unsigned val = 0;
3693 while (*arg) {
3694 if (parse_one_token(&arg, "none"))
3695 val = 0;
3696 else if (parse_one_token(&arg, "default"))
3697 val = WSEH_NEW;
3698 else if (parse_one_token(&arg, "all"))
3699 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
3700 else if (parse_one_token(&arg, "new"))
3701 val |= WSEH_NEW;
3702 else if (parse_one_token(&arg, "old"))
3703 val |= WSEH_OLD;
3704 else if (parse_one_token(&arg, "context"))
3705 val |= WSEH_CONTEXT;
3706 else {
3707 error("unknown value after ws-error-highlight=%.*s",
3708 (int)(arg - orig_arg), orig_arg);
3709 return 0;
3711 if (*arg)
3712 arg++;
3714 opt->ws_error_highlight = val;
3715 return 1;
3718 int diff_opt_parse(struct diff_options *options,
3719 const char **av, int ac, const char *prefix)
3721 const char *arg = av[0];
3722 const char *optarg;
3723 int argcount;
3725 if (!prefix)
3726 prefix = "";
3728 /* Output format options */
3729 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
3730 || opt_arg(arg, 'U', "unified", &options->context))
3731 enable_patch_output(&options->output_format);
3732 else if (!strcmp(arg, "--raw"))
3733 options->output_format |= DIFF_FORMAT_RAW;
3734 else if (!strcmp(arg, "--patch-with-raw")) {
3735 enable_patch_output(&options->output_format);
3736 options->output_format |= DIFF_FORMAT_RAW;
3737 } else if (!strcmp(arg, "--numstat"))
3738 options->output_format |= DIFF_FORMAT_NUMSTAT;
3739 else if (!strcmp(arg, "--shortstat"))
3740 options->output_format |= DIFF_FORMAT_SHORTSTAT;
3741 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
3742 return parse_dirstat_opt(options, "");
3743 else if (skip_prefix(arg, "-X", &arg))
3744 return parse_dirstat_opt(options, arg);
3745 else if (skip_prefix(arg, "--dirstat=", &arg))
3746 return parse_dirstat_opt(options, arg);
3747 else if (!strcmp(arg, "--cumulative"))
3748 return parse_dirstat_opt(options, "cumulative");
3749 else if (!strcmp(arg, "--dirstat-by-file"))
3750 return parse_dirstat_opt(options, "files");
3751 else if (skip_prefix(arg, "--dirstat-by-file=", &arg)) {
3752 parse_dirstat_opt(options, "files");
3753 return parse_dirstat_opt(options, arg);
3755 else if (!strcmp(arg, "--check"))
3756 options->output_format |= DIFF_FORMAT_CHECKDIFF;
3757 else if (!strcmp(arg, "--summary"))
3758 options->output_format |= DIFF_FORMAT_SUMMARY;
3759 else if (!strcmp(arg, "--patch-with-stat")) {
3760 enable_patch_output(&options->output_format);
3761 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3762 } else if (!strcmp(arg, "--name-only"))
3763 options->output_format |= DIFF_FORMAT_NAME;
3764 else if (!strcmp(arg, "--name-status"))
3765 options->output_format |= DIFF_FORMAT_NAME_STATUS;
3766 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
3767 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
3768 else if (starts_with(arg, "--stat"))
3769 /* --stat, --stat-width, --stat-name-width, or --stat-count */
3770 return stat_opt(options, av);
3772 /* renames options */
3773 else if (starts_with(arg, "-B") || starts_with(arg, "--break-rewrites=") ||
3774 !strcmp(arg, "--break-rewrites")) {
3775 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
3776 return error("invalid argument to -B: %s", arg+2);
3778 else if (starts_with(arg, "-M") || starts_with(arg, "--find-renames=") ||
3779 !strcmp(arg, "--find-renames")) {
3780 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3781 return error("invalid argument to -M: %s", arg+2);
3782 options->detect_rename = DIFF_DETECT_RENAME;
3784 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
3785 options->irreversible_delete = 1;
3787 else if (starts_with(arg, "-C") || starts_with(arg, "--find-copies=") ||
3788 !strcmp(arg, "--find-copies")) {
3789 if (options->detect_rename == DIFF_DETECT_COPY)
3790 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3791 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3792 return error("invalid argument to -C: %s", arg+2);
3793 options->detect_rename = DIFF_DETECT_COPY;
3795 else if (!strcmp(arg, "--no-renames"))
3796 options->detect_rename = 0;
3797 else if (!strcmp(arg, "--rename-empty"))
3798 DIFF_OPT_SET(options, RENAME_EMPTY);
3799 else if (!strcmp(arg, "--no-rename-empty"))
3800 DIFF_OPT_CLR(options, RENAME_EMPTY);
3801 else if (!strcmp(arg, "--relative"))
3802 DIFF_OPT_SET(options, RELATIVE_NAME);
3803 else if (skip_prefix(arg, "--relative=", &arg)) {
3804 DIFF_OPT_SET(options, RELATIVE_NAME);
3805 options->prefix = arg;
3808 /* xdiff options */
3809 else if (!strcmp(arg, "--minimal"))
3810 DIFF_XDL_SET(options, NEED_MINIMAL);
3811 else if (!strcmp(arg, "--no-minimal"))
3812 DIFF_XDL_CLR(options, NEED_MINIMAL);
3813 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
3814 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
3815 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
3816 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
3817 else if (!strcmp(arg, "--ignore-space-at-eol"))
3818 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
3819 else if (!strcmp(arg, "--ignore-blank-lines"))
3820 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
3821 else if (!strcmp(arg, "--compaction-heuristic"))
3822 DIFF_XDL_SET(options, COMPACTION_HEURISTIC);
3823 else if (!strcmp(arg, "--no-compaction-heuristic"))
3824 DIFF_XDL_CLR(options, COMPACTION_HEURISTIC);
3825 else if (!strcmp(arg, "--patience"))
3826 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
3827 else if (!strcmp(arg, "--histogram"))
3828 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
3829 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
3830 long value = parse_algorithm_value(optarg);
3831 if (value < 0)
3832 return error("option diff-algorithm accepts \"myers\", "
3833 "\"minimal\", \"patience\" and \"histogram\"");
3834 /* clear out previous settings */
3835 DIFF_XDL_CLR(options, NEED_MINIMAL);
3836 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3837 options->xdl_opts |= value;
3838 return argcount;
3841 /* flags options */
3842 else if (!strcmp(arg, "--binary")) {
3843 enable_patch_output(&options->output_format);
3844 DIFF_OPT_SET(options, BINARY);
3846 else if (!strcmp(arg, "--full-index"))
3847 DIFF_OPT_SET(options, FULL_INDEX);
3848 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
3849 DIFF_OPT_SET(options, TEXT);
3850 else if (!strcmp(arg, "-R"))
3851 DIFF_OPT_SET(options, REVERSE_DIFF);
3852 else if (!strcmp(arg, "--find-copies-harder"))
3853 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3854 else if (!strcmp(arg, "--follow"))
3855 DIFF_OPT_SET(options, FOLLOW_RENAMES);
3856 else if (!strcmp(arg, "--no-follow")) {
3857 DIFF_OPT_CLR(options, FOLLOW_RENAMES);
3858 DIFF_OPT_CLR(options, DEFAULT_FOLLOW_RENAMES);
3859 } else if (!strcmp(arg, "--color"))
3860 options->use_color = 1;
3861 else if (skip_prefix(arg, "--color=", &arg)) {
3862 int value = git_config_colorbool(NULL, arg);
3863 if (value < 0)
3864 return error("option `color' expects \"always\", \"auto\", or \"never\"");
3865 options->use_color = value;
3867 else if (!strcmp(arg, "--no-color"))
3868 options->use_color = 0;
3869 else if (!strcmp(arg, "--color-words")) {
3870 options->use_color = 1;
3871 options->word_diff = DIFF_WORDS_COLOR;
3873 else if (skip_prefix(arg, "--color-words=", &arg)) {
3874 options->use_color = 1;
3875 options->word_diff = DIFF_WORDS_COLOR;
3876 options->word_regex = arg;
3878 else if (!strcmp(arg, "--word-diff")) {
3879 if (options->word_diff == DIFF_WORDS_NONE)
3880 options->word_diff = DIFF_WORDS_PLAIN;
3882 else if (skip_prefix(arg, "--word-diff=", &arg)) {
3883 if (!strcmp(arg, "plain"))
3884 options->word_diff = DIFF_WORDS_PLAIN;
3885 else if (!strcmp(arg, "color")) {
3886 options->use_color = 1;
3887 options->word_diff = DIFF_WORDS_COLOR;
3889 else if (!strcmp(arg, "porcelain"))
3890 options->word_diff = DIFF_WORDS_PORCELAIN;
3891 else if (!strcmp(arg, "none"))
3892 options->word_diff = DIFF_WORDS_NONE;
3893 else
3894 die("bad --word-diff argument: %s", arg);
3896 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
3897 if (options->word_diff == DIFF_WORDS_NONE)
3898 options->word_diff = DIFF_WORDS_PLAIN;
3899 options->word_regex = optarg;
3900 return argcount;
3902 else if (!strcmp(arg, "--exit-code"))
3903 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3904 else if (!strcmp(arg, "--quiet"))
3905 DIFF_OPT_SET(options, QUICK);
3906 else if (!strcmp(arg, "--ext-diff"))
3907 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
3908 else if (!strcmp(arg, "--no-ext-diff"))
3909 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
3910 else if (!strcmp(arg, "--textconv"))
3911 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3912 else if (!strcmp(arg, "--no-textconv"))
3913 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
3914 else if (!strcmp(arg, "--ignore-submodules")) {
3915 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3916 handle_ignore_submodules_arg(options, "all");
3917 } else if (skip_prefix(arg, "--ignore-submodules=", &arg)) {
3918 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3919 handle_ignore_submodules_arg(options, arg);
3920 } else if (!strcmp(arg, "--submodule"))
3921 options->submodule_format = DIFF_SUBMODULE_LOG;
3922 else if (skip_prefix(arg, "--submodule=", &arg))
3923 return parse_submodule_opt(options, arg);
3924 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
3925 return parse_ws_error_highlight(options, arg);
3927 /* misc options */
3928 else if (!strcmp(arg, "-z"))
3929 options->line_termination = 0;
3930 else if ((argcount = short_opt('l', av, &optarg))) {
3931 options->rename_limit = strtoul(optarg, NULL, 10);
3932 return argcount;
3934 else if ((argcount = short_opt('S', av, &optarg))) {
3935 options->pickaxe = optarg;
3936 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
3937 return argcount;
3938 } else if ((argcount = short_opt('G', av, &optarg))) {
3939 options->pickaxe = optarg;
3940 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
3941 return argcount;
3943 else if (!strcmp(arg, "--pickaxe-all"))
3944 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
3945 else if (!strcmp(arg, "--pickaxe-regex"))
3946 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
3947 else if ((argcount = short_opt('O', av, &optarg))) {
3948 const char *path = prefix_filename(prefix, strlen(prefix), optarg);
3949 options->orderfile = xstrdup(path);
3950 return argcount;
3952 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
3953 int offending = parse_diff_filter_opt(optarg, options);
3954 if (offending)
3955 die("unknown change class '%c' in --diff-filter=%s",
3956 offending, optarg);
3957 return argcount;
3959 else if (!strcmp(arg, "--abbrev"))
3960 options->abbrev = DEFAULT_ABBREV;
3961 else if (skip_prefix(arg, "--abbrev=", &arg)) {
3962 options->abbrev = strtoul(arg, NULL, 10);
3963 if (options->abbrev < MINIMUM_ABBREV)
3964 options->abbrev = MINIMUM_ABBREV;
3965 else if (40 < options->abbrev)
3966 options->abbrev = 40;
3968 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
3969 options->a_prefix = optarg;
3970 return argcount;
3972 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
3973 options->line_prefix = optarg;
3974 options->line_prefix_length = strlen(options->line_prefix);
3975 graph_setup_line_prefix(options);
3976 return argcount;
3978 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
3979 options->b_prefix = optarg;
3980 return argcount;
3982 else if (!strcmp(arg, "--no-prefix"))
3983 options->a_prefix = options->b_prefix = "";
3984 else if (opt_arg(arg, '\0', "inter-hunk-context",
3985 &options->interhunkcontext))
3987 else if (!strcmp(arg, "-W"))
3988 DIFF_OPT_SET(options, FUNCCONTEXT);
3989 else if (!strcmp(arg, "--function-context"))
3990 DIFF_OPT_SET(options, FUNCCONTEXT);
3991 else if (!strcmp(arg, "--no-function-context"))
3992 DIFF_OPT_CLR(options, FUNCCONTEXT);
3993 else if ((argcount = parse_long_opt("output", av, &optarg))) {
3994 const char *path = prefix_filename(prefix, strlen(prefix), optarg);
3995 options->file = fopen(path, "w");
3996 if (!options->file)
3997 die_errno("Could not open '%s'", path);
3998 options->close_file = 1;
3999 if (options->use_color != GIT_COLOR_ALWAYS)
4000 options->use_color = GIT_COLOR_NEVER;
4001 return argcount;
4002 } else
4003 return 0;
4004 return 1;
4007 int parse_rename_score(const char **cp_p)
4009 unsigned long num, scale;
4010 int ch, dot;
4011 const char *cp = *cp_p;
4013 num = 0;
4014 scale = 1;
4015 dot = 0;
4016 for (;;) {
4017 ch = *cp;
4018 if ( !dot && ch == '.' ) {
4019 scale = 1;
4020 dot = 1;
4021 } else if ( ch == '%' ) {
4022 scale = dot ? scale*100 : 100;
4023 cp++; /* % is always at the end */
4024 break;
4025 } else if ( ch >= '0' && ch <= '9' ) {
4026 if ( scale < 100000 ) {
4027 scale *= 10;
4028 num = (num*10) + (ch-'0');
4030 } else {
4031 break;
4033 cp++;
4035 *cp_p = cp;
4037 /* user says num divided by scale and we say internally that
4038 * is MAX_SCORE * num / scale.
4040 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4043 static int diff_scoreopt_parse(const char *opt)
4045 int opt1, opt2, cmd;
4047 if (*opt++ != '-')
4048 return -1;
4049 cmd = *opt++;
4050 if (cmd == '-') {
4051 /* convert the long-form arguments into short-form versions */
4052 if (skip_prefix(opt, "break-rewrites", &opt)) {
4053 if (*opt == 0 || *opt++ == '=')
4054 cmd = 'B';
4055 } else if (skip_prefix(opt, "find-copies", &opt)) {
4056 if (*opt == 0 || *opt++ == '=')
4057 cmd = 'C';
4058 } else if (skip_prefix(opt, "find-renames", &opt)) {
4059 if (*opt == 0 || *opt++ == '=')
4060 cmd = 'M';
4063 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4064 return -1; /* that is not a -M, -C, or -B option */
4066 opt1 = parse_rename_score(&opt);
4067 if (cmd != 'B')
4068 opt2 = 0;
4069 else {
4070 if (*opt == 0)
4071 opt2 = 0;
4072 else if (*opt != '/')
4073 return -1; /* we expect -B80/99 or -B80 */
4074 else {
4075 opt++;
4076 opt2 = parse_rename_score(&opt);
4079 if (*opt != 0)
4080 return -1;
4081 return opt1 | (opt2 << 16);
4084 struct diff_queue_struct diff_queued_diff;
4086 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4088 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4089 queue->queue[queue->nr++] = dp;
4092 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4093 struct diff_filespec *one,
4094 struct diff_filespec *two)
4096 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4097 dp->one = one;
4098 dp->two = two;
4099 if (queue)
4100 diff_q(queue, dp);
4101 return dp;
4104 void diff_free_filepair(struct diff_filepair *p)
4106 free_filespec(p->one);
4107 free_filespec(p->two);
4108 free(p);
4111 /* This is different from find_unique_abbrev() in that
4112 * it stuffs the result with dots for alignment.
4114 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
4116 int abblen;
4117 const char *abbrev;
4118 if (len == 40)
4119 return sha1_to_hex(sha1);
4121 abbrev = find_unique_abbrev(sha1, len);
4122 abblen = strlen(abbrev);
4123 if (abblen < 37) {
4124 static char hex[41];
4125 if (len < abblen && abblen <= len + 2)
4126 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
4127 else
4128 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
4129 return hex;
4131 return sha1_to_hex(sha1);
4134 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4136 int line_termination = opt->line_termination;
4137 int inter_name_termination = line_termination ? '\t' : '\0';
4139 fprintf(opt->file, "%s", diff_line_prefix(opt));
4140 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
4141 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
4142 diff_unique_abbrev(p->one->oid.hash, opt->abbrev));
4143 fprintf(opt->file, "%s ",
4144 diff_unique_abbrev(p->two->oid.hash, opt->abbrev));
4146 if (p->score) {
4147 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
4148 inter_name_termination);
4149 } else {
4150 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
4153 if (p->status == DIFF_STATUS_COPIED ||
4154 p->status == DIFF_STATUS_RENAMED) {
4155 const char *name_a, *name_b;
4156 name_a = p->one->path;
4157 name_b = p->two->path;
4158 strip_prefix(opt->prefix_length, &name_a, &name_b);
4159 write_name_quoted(name_a, opt->file, inter_name_termination);
4160 write_name_quoted(name_b, opt->file, line_termination);
4161 } else {
4162 const char *name_a, *name_b;
4163 name_a = p->one->mode ? p->one->path : p->two->path;
4164 name_b = NULL;
4165 strip_prefix(opt->prefix_length, &name_a, &name_b);
4166 write_name_quoted(name_a, opt->file, line_termination);
4170 int diff_unmodified_pair(struct diff_filepair *p)
4172 /* This function is written stricter than necessary to support
4173 * the currently implemented transformers, but the idea is to
4174 * let transformers to produce diff_filepairs any way they want,
4175 * and filter and clean them up here before producing the output.
4177 struct diff_filespec *one = p->one, *two = p->two;
4179 if (DIFF_PAIR_UNMERGED(p))
4180 return 0; /* unmerged is interesting */
4182 /* deletion, addition, mode or type change
4183 * and rename are all interesting.
4185 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
4186 DIFF_PAIR_MODE_CHANGED(p) ||
4187 strcmp(one->path, two->path))
4188 return 0;
4190 /* both are valid and point at the same path. that is, we are
4191 * dealing with a change.
4193 if (one->oid_valid && two->oid_valid &&
4194 !oidcmp(&one->oid, &two->oid) &&
4195 !one->dirty_submodule && !two->dirty_submodule)
4196 return 1; /* no change */
4197 if (!one->oid_valid && !two->oid_valid)
4198 return 1; /* both look at the same file on the filesystem. */
4199 return 0;
4202 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
4204 if (diff_unmodified_pair(p))
4205 return;
4207 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4208 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4209 return; /* no tree diffs in patch format */
4211 run_diff(p, o);
4214 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
4215 struct diffstat_t *diffstat)
4217 if (diff_unmodified_pair(p))
4218 return;
4220 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4221 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4222 return; /* no useful stat for tree diffs */
4224 run_diffstat(p, o, diffstat);
4227 static void diff_flush_checkdiff(struct diff_filepair *p,
4228 struct diff_options *o)
4230 if (diff_unmodified_pair(p))
4231 return;
4233 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4234 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4235 return; /* nothing to check in tree diffs */
4237 run_checkdiff(p, o);
4240 int diff_queue_is_empty(void)
4242 struct diff_queue_struct *q = &diff_queued_diff;
4243 int i;
4244 for (i = 0; i < q->nr; i++)
4245 if (!diff_unmodified_pair(q->queue[i]))
4246 return 0;
4247 return 1;
4250 #if DIFF_DEBUG
4251 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
4253 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
4254 x, one ? one : "",
4255 s->path,
4256 DIFF_FILE_VALID(s) ? "valid" : "invalid",
4257 s->mode,
4258 s->oid_valid ? oid_to_hex(&s->oid) : "");
4259 fprintf(stderr, "queue[%d] %s size %lu\n",
4260 x, one ? one : "",
4261 s->size);
4264 void diff_debug_filepair(const struct diff_filepair *p, int i)
4266 diff_debug_filespec(p->one, i, "one");
4267 diff_debug_filespec(p->two, i, "two");
4268 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
4269 p->score, p->status ? p->status : '?',
4270 p->one->rename_used, p->broken_pair);
4273 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
4275 int i;
4276 if (msg)
4277 fprintf(stderr, "%s\n", msg);
4278 fprintf(stderr, "q->nr = %d\n", q->nr);
4279 for (i = 0; i < q->nr; i++) {
4280 struct diff_filepair *p = q->queue[i];
4281 diff_debug_filepair(p, i);
4284 #endif
4286 static void diff_resolve_rename_copy(void)
4288 int i;
4289 struct diff_filepair *p;
4290 struct diff_queue_struct *q = &diff_queued_diff;
4292 diff_debug_queue("resolve-rename-copy", q);
4294 for (i = 0; i < q->nr; i++) {
4295 p = q->queue[i];
4296 p->status = 0; /* undecided */
4297 if (DIFF_PAIR_UNMERGED(p))
4298 p->status = DIFF_STATUS_UNMERGED;
4299 else if (!DIFF_FILE_VALID(p->one))
4300 p->status = DIFF_STATUS_ADDED;
4301 else if (!DIFF_FILE_VALID(p->two))
4302 p->status = DIFF_STATUS_DELETED;
4303 else if (DIFF_PAIR_TYPE_CHANGED(p))
4304 p->status = DIFF_STATUS_TYPE_CHANGED;
4306 /* from this point on, we are dealing with a pair
4307 * whose both sides are valid and of the same type, i.e.
4308 * either in-place edit or rename/copy edit.
4310 else if (DIFF_PAIR_RENAME(p)) {
4312 * A rename might have re-connected a broken
4313 * pair up, causing the pathnames to be the
4314 * same again. If so, that's not a rename at
4315 * all, just a modification..
4317 * Otherwise, see if this source was used for
4318 * multiple renames, in which case we decrement
4319 * the count, and call it a copy.
4321 if (!strcmp(p->one->path, p->two->path))
4322 p->status = DIFF_STATUS_MODIFIED;
4323 else if (--p->one->rename_used > 0)
4324 p->status = DIFF_STATUS_COPIED;
4325 else
4326 p->status = DIFF_STATUS_RENAMED;
4328 else if (oidcmp(&p->one->oid, &p->two->oid) ||
4329 p->one->mode != p->two->mode ||
4330 p->one->dirty_submodule ||
4331 p->two->dirty_submodule ||
4332 is_null_oid(&p->one->oid))
4333 p->status = DIFF_STATUS_MODIFIED;
4334 else {
4335 /* This is a "no-change" entry and should not
4336 * happen anymore, but prepare for broken callers.
4338 error("feeding unmodified %s to diffcore",
4339 p->one->path);
4340 p->status = DIFF_STATUS_UNKNOWN;
4343 diff_debug_queue("resolve-rename-copy done", q);
4346 static int check_pair_status(struct diff_filepair *p)
4348 switch (p->status) {
4349 case DIFF_STATUS_UNKNOWN:
4350 return 0;
4351 case 0:
4352 die("internal error in diff-resolve-rename-copy");
4353 default:
4354 return 1;
4358 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4360 int fmt = opt->output_format;
4362 if (fmt & DIFF_FORMAT_CHECKDIFF)
4363 diff_flush_checkdiff(p, opt);
4364 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4365 diff_flush_raw(p, opt);
4366 else if (fmt & DIFF_FORMAT_NAME) {
4367 const char *name_a, *name_b;
4368 name_a = p->two->path;
4369 name_b = NULL;
4370 strip_prefix(opt->prefix_length, &name_a, &name_b);
4371 write_name_quoted(name_a, opt->file, opt->line_termination);
4375 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4377 if (fs->mode)
4378 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4379 else
4380 fprintf(file, " %s ", newdelete);
4381 write_name_quoted(fs->path, file, '\n');
4385 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
4386 const char *line_prefix)
4388 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
4389 fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
4390 p->two->mode, show_name ? ' ' : '\n');
4391 if (show_name) {
4392 write_name_quoted(p->two->path, file, '\n');
4397 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
4398 const char *line_prefix)
4400 char *names = pprint_rename(p->one->path, p->two->path);
4402 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
4403 free(names);
4404 show_mode_change(file, p, 0, line_prefix);
4407 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4409 FILE *file = opt->file;
4410 const char *line_prefix = diff_line_prefix(opt);
4412 switch(p->status) {
4413 case DIFF_STATUS_DELETED:
4414 fputs(line_prefix, file);
4415 show_file_mode_name(file, "delete", p->one);
4416 break;
4417 case DIFF_STATUS_ADDED:
4418 fputs(line_prefix, file);
4419 show_file_mode_name(file, "create", p->two);
4420 break;
4421 case DIFF_STATUS_COPIED:
4422 fputs(line_prefix, file);
4423 show_rename_copy(file, "copy", p, line_prefix);
4424 break;
4425 case DIFF_STATUS_RENAMED:
4426 fputs(line_prefix, file);
4427 show_rename_copy(file, "rename", p, line_prefix);
4428 break;
4429 default:
4430 if (p->score) {
4431 fprintf(file, "%s rewrite ", line_prefix);
4432 write_name_quoted(p->two->path, file, ' ');
4433 fprintf(file, "(%d%%)\n", similarity_index(p));
4435 show_mode_change(file, p, !p->score, line_prefix);
4436 break;
4440 struct patch_id_t {
4441 git_SHA_CTX *ctx;
4442 int patchlen;
4445 static int remove_space(char *line, int len)
4447 int i;
4448 char *dst = line;
4449 unsigned char c;
4451 for (i = 0; i < len; i++)
4452 if (!isspace((c = line[i])))
4453 *dst++ = c;
4455 return dst - line;
4458 static void patch_id_consume(void *priv, char *line, unsigned long len)
4460 struct patch_id_t *data = priv;
4461 int new_len;
4463 /* Ignore line numbers when computing the SHA1 of the patch */
4464 if (starts_with(line, "@@ -"))
4465 return;
4467 new_len = remove_space(line, len);
4469 git_SHA1_Update(data->ctx, line, new_len);
4470 data->patchlen += new_len;
4473 /* returns 0 upon success, and writes result into sha1 */
4474 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1, int diff_header_only)
4476 struct diff_queue_struct *q = &diff_queued_diff;
4477 int i;
4478 git_SHA_CTX ctx;
4479 struct patch_id_t data;
4480 char buffer[PATH_MAX * 4 + 20];
4482 git_SHA1_Init(&ctx);
4483 memset(&data, 0, sizeof(struct patch_id_t));
4484 data.ctx = &ctx;
4486 for (i = 0; i < q->nr; i++) {
4487 xpparam_t xpp;
4488 xdemitconf_t xecfg;
4489 mmfile_t mf1, mf2;
4490 struct diff_filepair *p = q->queue[i];
4491 int len1, len2;
4493 memset(&xpp, 0, sizeof(xpp));
4494 memset(&xecfg, 0, sizeof(xecfg));
4495 if (p->status == 0)
4496 return error("internal diff status error");
4497 if (p->status == DIFF_STATUS_UNKNOWN)
4498 continue;
4499 if (diff_unmodified_pair(p))
4500 continue;
4501 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4502 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4503 continue;
4504 if (DIFF_PAIR_UNMERGED(p))
4505 continue;
4507 diff_fill_sha1_info(p->one);
4508 diff_fill_sha1_info(p->two);
4510 len1 = remove_space(p->one->path, strlen(p->one->path));
4511 len2 = remove_space(p->two->path, strlen(p->two->path));
4512 if (p->one->mode == 0)
4513 len1 = snprintf(buffer, sizeof(buffer),
4514 "diff--gita/%.*sb/%.*s"
4515 "newfilemode%06o"
4516 "---/dev/null"
4517 "+++b/%.*s",
4518 len1, p->one->path,
4519 len2, p->two->path,
4520 p->two->mode,
4521 len2, p->two->path);
4522 else if (p->two->mode == 0)
4523 len1 = snprintf(buffer, sizeof(buffer),
4524 "diff--gita/%.*sb/%.*s"
4525 "deletedfilemode%06o"
4526 "---a/%.*s"
4527 "+++/dev/null",
4528 len1, p->one->path,
4529 len2, p->two->path,
4530 p->one->mode,
4531 len1, p->one->path);
4532 else
4533 len1 = snprintf(buffer, sizeof(buffer),
4534 "diff--gita/%.*sb/%.*s"
4535 "---a/%.*s"
4536 "+++b/%.*s",
4537 len1, p->one->path,
4538 len2, p->two->path,
4539 len1, p->one->path,
4540 len2, p->two->path);
4541 git_SHA1_Update(&ctx, buffer, len1);
4543 if (diff_header_only)
4544 continue;
4546 if (fill_mmfile(&mf1, p->one) < 0 ||
4547 fill_mmfile(&mf2, p->two) < 0)
4548 return error("unable to read files to diff");
4550 if (diff_filespec_is_binary(p->one) ||
4551 diff_filespec_is_binary(p->two)) {
4552 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
4553 40);
4554 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
4555 40);
4556 continue;
4559 xpp.flags = 0;
4560 xecfg.ctxlen = 3;
4561 xecfg.flags = 0;
4562 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
4563 &xpp, &xecfg))
4564 return error("unable to generate patch-id diff for %s",
4565 p->one->path);
4568 git_SHA1_Final(sha1, &ctx);
4569 return 0;
4572 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1, int diff_header_only)
4574 struct diff_queue_struct *q = &diff_queued_diff;
4575 int i;
4576 int result = diff_get_patch_id(options, sha1, diff_header_only);
4578 for (i = 0; i < q->nr; i++)
4579 diff_free_filepair(q->queue[i]);
4581 free(q->queue);
4582 DIFF_QUEUE_CLEAR(q);
4584 return result;
4587 static int is_summary_empty(const struct diff_queue_struct *q)
4589 int i;
4591 for (i = 0; i < q->nr; i++) {
4592 const struct diff_filepair *p = q->queue[i];
4594 switch (p->status) {
4595 case DIFF_STATUS_DELETED:
4596 case DIFF_STATUS_ADDED:
4597 case DIFF_STATUS_COPIED:
4598 case DIFF_STATUS_RENAMED:
4599 return 0;
4600 default:
4601 if (p->score)
4602 return 0;
4603 if (p->one->mode && p->two->mode &&
4604 p->one->mode != p->two->mode)
4605 return 0;
4606 break;
4609 return 1;
4612 static const char rename_limit_warning[] =
4613 "inexact rename detection was skipped due to too many files.";
4615 static const char degrade_cc_to_c_warning[] =
4616 "only found copies from modified paths due to too many files.";
4618 static const char rename_limit_advice[] =
4619 "you may want to set your %s variable to at least "
4620 "%d and retry the command.";
4622 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4624 if (degraded_cc)
4625 warning(degrade_cc_to_c_warning);
4626 else if (needed)
4627 warning(rename_limit_warning);
4628 else
4629 return;
4630 if (0 < needed && needed < 32767)
4631 warning(rename_limit_advice, varname, needed);
4634 void diff_flush(struct diff_options *options)
4636 struct diff_queue_struct *q = &diff_queued_diff;
4637 int i, output_format = options->output_format;
4638 int separator = 0;
4639 int dirstat_by_line = 0;
4642 * Order: raw, stat, summary, patch
4643 * or: name/name-status/checkdiff (other bits clear)
4645 if (!q->nr)
4646 goto free_queue;
4648 if (output_format & (DIFF_FORMAT_RAW |
4649 DIFF_FORMAT_NAME |
4650 DIFF_FORMAT_NAME_STATUS |
4651 DIFF_FORMAT_CHECKDIFF)) {
4652 for (i = 0; i < q->nr; i++) {
4653 struct diff_filepair *p = q->queue[i];
4654 if (check_pair_status(p))
4655 flush_one_pair(p, options);
4657 separator++;
4660 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
4661 dirstat_by_line = 1;
4663 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
4664 dirstat_by_line) {
4665 struct diffstat_t diffstat;
4667 memset(&diffstat, 0, sizeof(struct diffstat_t));
4668 for (i = 0; i < q->nr; i++) {
4669 struct diff_filepair *p = q->queue[i];
4670 if (check_pair_status(p))
4671 diff_flush_stat(p, options, &diffstat);
4673 if (output_format & DIFF_FORMAT_NUMSTAT)
4674 show_numstat(&diffstat, options);
4675 if (output_format & DIFF_FORMAT_DIFFSTAT)
4676 show_stats(&diffstat, options);
4677 if (output_format & DIFF_FORMAT_SHORTSTAT)
4678 show_shortstats(&diffstat, options);
4679 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
4680 show_dirstat_by_line(&diffstat, options);
4681 free_diffstat_info(&diffstat);
4682 separator++;
4684 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
4685 show_dirstat(options);
4687 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
4688 for (i = 0; i < q->nr; i++) {
4689 diff_summary(options, q->queue[i]);
4691 separator++;
4694 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
4695 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
4696 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4698 * run diff_flush_patch for the exit status. setting
4699 * options->file to /dev/null should be safe, because we
4700 * aren't supposed to produce any output anyway.
4702 if (options->close_file)
4703 fclose(options->file);
4704 options->file = fopen("/dev/null", "w");
4705 if (!options->file)
4706 die_errno("Could not open /dev/null");
4707 options->close_file = 1;
4708 for (i = 0; i < q->nr; i++) {
4709 struct diff_filepair *p = q->queue[i];
4710 if (check_pair_status(p))
4711 diff_flush_patch(p, options);
4712 if (options->found_changes)
4713 break;
4717 if (output_format & DIFF_FORMAT_PATCH) {
4718 if (separator) {
4719 fprintf(options->file, "%s%c",
4720 diff_line_prefix(options),
4721 options->line_termination);
4722 if (options->stat_sep) {
4723 /* attach patch instead of inline */
4724 fputs(options->stat_sep, options->file);
4728 for (i = 0; i < q->nr; i++) {
4729 struct diff_filepair *p = q->queue[i];
4730 if (check_pair_status(p))
4731 diff_flush_patch(p, options);
4735 if (output_format & DIFF_FORMAT_CALLBACK)
4736 options->format_callback(q, options, options->format_callback_data);
4738 for (i = 0; i < q->nr; i++)
4739 diff_free_filepair(q->queue[i]);
4740 free_queue:
4741 free(q->queue);
4742 DIFF_QUEUE_CLEAR(q);
4743 if (options->close_file)
4744 fclose(options->file);
4747 * Report the content-level differences with HAS_CHANGES;
4748 * diff_addremove/diff_change does not set the bit when
4749 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
4751 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4752 if (options->found_changes)
4753 DIFF_OPT_SET(options, HAS_CHANGES);
4754 else
4755 DIFF_OPT_CLR(options, HAS_CHANGES);
4759 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
4761 return (((p->status == DIFF_STATUS_MODIFIED) &&
4762 ((p->score &&
4763 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
4764 (!p->score &&
4765 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
4766 ((p->status != DIFF_STATUS_MODIFIED) &&
4767 filter_bit_tst(p->status, options)));
4770 static void diffcore_apply_filter(struct diff_options *options)
4772 int i;
4773 struct diff_queue_struct *q = &diff_queued_diff;
4774 struct diff_queue_struct outq;
4776 DIFF_QUEUE_CLEAR(&outq);
4778 if (!options->filter)
4779 return;
4781 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
4782 int found;
4783 for (i = found = 0; !found && i < q->nr; i++) {
4784 if (match_filter(options, q->queue[i]))
4785 found++;
4787 if (found)
4788 return;
4790 /* otherwise we will clear the whole queue
4791 * by copying the empty outq at the end of this
4792 * function, but first clear the current entries
4793 * in the queue.
4795 for (i = 0; i < q->nr; i++)
4796 diff_free_filepair(q->queue[i]);
4798 else {
4799 /* Only the matching ones */
4800 for (i = 0; i < q->nr; i++) {
4801 struct diff_filepair *p = q->queue[i];
4802 if (match_filter(options, p))
4803 diff_q(&outq, p);
4804 else
4805 diff_free_filepair(p);
4808 free(q->queue);
4809 *q = outq;
4812 /* Check whether two filespecs with the same mode and size are identical */
4813 static int diff_filespec_is_identical(struct diff_filespec *one,
4814 struct diff_filespec *two)
4816 if (S_ISGITLINK(one->mode))
4817 return 0;
4818 if (diff_populate_filespec(one, 0))
4819 return 0;
4820 if (diff_populate_filespec(two, 0))
4821 return 0;
4822 return !memcmp(one->data, two->data, one->size);
4825 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
4827 if (p->done_skip_stat_unmatch)
4828 return p->skip_stat_unmatch_result;
4830 p->done_skip_stat_unmatch = 1;
4831 p->skip_stat_unmatch_result = 0;
4833 * 1. Entries that come from stat info dirtiness
4834 * always have both sides (iow, not create/delete),
4835 * one side of the object name is unknown, with
4836 * the same mode and size. Keep the ones that
4837 * do not match these criteria. They have real
4838 * differences.
4840 * 2. At this point, the file is known to be modified,
4841 * with the same mode and size, and the object
4842 * name of one side is unknown. Need to inspect
4843 * the identical contents.
4845 if (!DIFF_FILE_VALID(p->one) || /* (1) */
4846 !DIFF_FILE_VALID(p->two) ||
4847 (p->one->oid_valid && p->two->oid_valid) ||
4848 (p->one->mode != p->two->mode) ||
4849 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
4850 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
4851 (p->one->size != p->two->size) ||
4852 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
4853 p->skip_stat_unmatch_result = 1;
4854 return p->skip_stat_unmatch_result;
4857 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
4859 int i;
4860 struct diff_queue_struct *q = &diff_queued_diff;
4861 struct diff_queue_struct outq;
4862 DIFF_QUEUE_CLEAR(&outq);
4864 for (i = 0; i < q->nr; i++) {
4865 struct diff_filepair *p = q->queue[i];
4867 if (diff_filespec_check_stat_unmatch(p))
4868 diff_q(&outq, p);
4869 else {
4871 * The caller can subtract 1 from skip_stat_unmatch
4872 * to determine how many paths were dirty only
4873 * due to stat info mismatch.
4875 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
4876 diffopt->skip_stat_unmatch++;
4877 diff_free_filepair(p);
4880 free(q->queue);
4881 *q = outq;
4884 static int diffnamecmp(const void *a_, const void *b_)
4886 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4887 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4888 const char *name_a, *name_b;
4890 name_a = a->one ? a->one->path : a->two->path;
4891 name_b = b->one ? b->one->path : b->two->path;
4892 return strcmp(name_a, name_b);
4895 void diffcore_fix_diff_index(struct diff_options *options)
4897 struct diff_queue_struct *q = &diff_queued_diff;
4898 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
4901 void diffcore_std(struct diff_options *options)
4903 /* NOTE please keep the following in sync with diff_tree_combined() */
4904 if (options->skip_stat_unmatch)
4905 diffcore_skip_stat_unmatch(options);
4906 if (!options->found_follow) {
4907 /* See try_to_follow_renames() in tree-diff.c */
4908 if (options->break_opt != -1)
4909 diffcore_break(options->break_opt);
4910 if (options->detect_rename)
4911 diffcore_rename(options);
4912 if (options->break_opt != -1)
4913 diffcore_merge_broken();
4915 if (options->pickaxe)
4916 diffcore_pickaxe(options);
4917 if (options->orderfile)
4918 diffcore_order(options->orderfile);
4919 if (!options->found_follow)
4920 /* See try_to_follow_renames() in tree-diff.c */
4921 diff_resolve_rename_copy();
4922 diffcore_apply_filter(options);
4924 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4925 DIFF_OPT_SET(options, HAS_CHANGES);
4926 else
4927 DIFF_OPT_CLR(options, HAS_CHANGES);
4929 options->found_follow = 0;
4932 int diff_result_code(struct diff_options *opt, int status)
4934 int result = 0;
4936 diff_warn_rename_limit("diff.renameLimit",
4937 opt->needed_rename_limit,
4938 opt->degraded_cc_to_c);
4939 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4940 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
4941 return status;
4942 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4943 DIFF_OPT_TST(opt, HAS_CHANGES))
4944 result |= 01;
4945 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4946 DIFF_OPT_TST(opt, CHECK_FAILED))
4947 result |= 02;
4948 return result;
4951 int diff_can_quit_early(struct diff_options *opt)
4953 return (DIFF_OPT_TST(opt, QUICK) &&
4954 !opt->filter &&
4955 DIFF_OPT_TST(opt, HAS_CHANGES));
4959 * Shall changes to this submodule be ignored?
4961 * Submodule changes can be configured to be ignored separately for each path,
4962 * but that configuration can be overridden from the command line.
4964 static int is_submodule_ignored(const char *path, struct diff_options *options)
4966 int ignored = 0;
4967 unsigned orig_flags = options->flags;
4968 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
4969 set_diffopt_flags_from_submodule_config(options, path);
4970 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
4971 ignored = 1;
4972 options->flags = orig_flags;
4973 return ignored;
4976 void diff_addremove(struct diff_options *options,
4977 int addremove, unsigned mode,
4978 const unsigned char *sha1,
4979 int sha1_valid,
4980 const char *concatpath, unsigned dirty_submodule)
4982 struct diff_filespec *one, *two;
4984 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
4985 return;
4987 /* This may look odd, but it is a preparation for
4988 * feeding "there are unchanged files which should
4989 * not produce diffs, but when you are doing copy
4990 * detection you would need them, so here they are"
4991 * entries to the diff-core. They will be prefixed
4992 * with something like '=' or '*' (I haven't decided
4993 * which but should not make any difference).
4994 * Feeding the same new and old to diff_change()
4995 * also has the same effect.
4996 * Before the final output happens, they are pruned after
4997 * merged into rename/copy pairs as appropriate.
4999 if (DIFF_OPT_TST(options, REVERSE_DIFF))
5000 addremove = (addremove == '+' ? '-' :
5001 addremove == '-' ? '+' : addremove);
5003 if (options->prefix &&
5004 strncmp(concatpath, options->prefix, options->prefix_length))
5005 return;
5007 one = alloc_filespec(concatpath);
5008 two = alloc_filespec(concatpath);
5010 if (addremove != '+')
5011 fill_filespec(one, sha1, sha1_valid, mode);
5012 if (addremove != '-') {
5013 fill_filespec(two, sha1, sha1_valid, mode);
5014 two->dirty_submodule = dirty_submodule;
5017 diff_queue(&diff_queued_diff, one, two);
5018 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5019 DIFF_OPT_SET(options, HAS_CHANGES);
5022 void diff_change(struct diff_options *options,
5023 unsigned old_mode, unsigned new_mode,
5024 const unsigned char *old_sha1,
5025 const unsigned char *new_sha1,
5026 int old_sha1_valid, int new_sha1_valid,
5027 const char *concatpath,
5028 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5030 struct diff_filespec *one, *two;
5031 struct diff_filepair *p;
5033 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
5034 is_submodule_ignored(concatpath, options))
5035 return;
5037 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
5038 unsigned tmp;
5039 const unsigned char *tmp_c;
5040 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
5041 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
5042 tmp = old_sha1_valid; old_sha1_valid = new_sha1_valid;
5043 new_sha1_valid = tmp;
5044 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
5045 new_dirty_submodule = tmp;
5048 if (options->prefix &&
5049 strncmp(concatpath, options->prefix, options->prefix_length))
5050 return;
5052 one = alloc_filespec(concatpath);
5053 two = alloc_filespec(concatpath);
5054 fill_filespec(one, old_sha1, old_sha1_valid, old_mode);
5055 fill_filespec(two, new_sha1, new_sha1_valid, new_mode);
5056 one->dirty_submodule = old_dirty_submodule;
5057 two->dirty_submodule = new_dirty_submodule;
5058 p = diff_queue(&diff_queued_diff, one, two);
5060 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5061 return;
5063 if (DIFF_OPT_TST(options, QUICK) && options->skip_stat_unmatch &&
5064 !diff_filespec_check_stat_unmatch(p))
5065 return;
5067 DIFF_OPT_SET(options, HAS_CHANGES);
5070 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
5072 struct diff_filepair *pair;
5073 struct diff_filespec *one, *two;
5075 if (options->prefix &&
5076 strncmp(path, options->prefix, options->prefix_length))
5077 return NULL;
5079 one = alloc_filespec(path);
5080 two = alloc_filespec(path);
5081 pair = diff_queue(&diff_queued_diff, one, two);
5082 pair->is_unmerged = 1;
5083 return pair;
5086 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
5087 size_t *outsize)
5089 struct diff_tempfile *temp;
5090 const char *argv[3];
5091 const char **arg = argv;
5092 struct child_process child = CHILD_PROCESS_INIT;
5093 struct strbuf buf = STRBUF_INIT;
5094 int err = 0;
5096 temp = prepare_temp_file(spec->path, spec);
5097 *arg++ = pgm;
5098 *arg++ = temp->name;
5099 *arg = NULL;
5101 child.use_shell = 1;
5102 child.argv = argv;
5103 child.out = -1;
5104 if (start_command(&child)) {
5105 remove_tempfile();
5106 return NULL;
5109 if (strbuf_read(&buf, child.out, 0) < 0)
5110 err = error("error reading from textconv command '%s'", pgm);
5111 close(child.out);
5113 if (finish_command(&child) || err) {
5114 strbuf_release(&buf);
5115 remove_tempfile();
5116 return NULL;
5118 remove_tempfile();
5120 return strbuf_detach(&buf, outsize);
5123 size_t fill_textconv(struct userdiff_driver *driver,
5124 struct diff_filespec *df,
5125 char **outbuf)
5127 size_t size;
5129 if (!driver) {
5130 if (!DIFF_FILE_VALID(df)) {
5131 *outbuf = "";
5132 return 0;
5134 if (diff_populate_filespec(df, 0))
5135 die("unable to read files to diff");
5136 *outbuf = df->data;
5137 return df->size;
5140 if (!driver->textconv)
5141 die("BUG: fill_textconv called with non-textconv driver");
5143 if (driver->textconv_cache && df->oid_valid) {
5144 *outbuf = notes_cache_get(driver->textconv_cache,
5145 df->oid.hash,
5146 &size);
5147 if (*outbuf)
5148 return size;
5151 *outbuf = run_textconv(driver->textconv, df, &size);
5152 if (!*outbuf)
5153 die("unable to read files to diff");
5155 if (driver->textconv_cache && df->oid_valid) {
5156 /* ignore errors, as we might be in a readonly repository */
5157 notes_cache_put(driver->textconv_cache, df->oid.hash, *outbuf,
5158 size);
5160 * we could save up changes and flush them all at the end,
5161 * but we would need an extra call after all diffing is done.
5162 * Since generating a cache entry is the slow path anyway,
5163 * this extra overhead probably isn't a big deal.
5165 notes_cache_write(driver->textconv_cache);
5168 return size;
5171 void setup_diff_pager(struct diff_options *opt)
5174 * If the user asked for our exit code, then either they want --quiet
5175 * or --exit-code. We should definitely not bother with a pager in the
5176 * former case, as we will generate no output. Since we still properly
5177 * report our exit code even when a pager is run, we _could_ run a
5178 * pager with --exit-code. But since we have not done so historically,
5179 * and because it is easy to find people oneline advising "git diff
5180 * --exit-code" in hooks and other scripts, we do not do so.
5182 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5183 check_pager_config("diff") != 0)
5184 setup_pager();