gc: use tempfile module to handle gc.pid file
[git/mjg.git] / diff.c
blob528d25ca9c3ec8df316bf2cd331151d7a71d5dd3
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 "sigchain.h"
17 #include "submodule.h"
18 #include "ll-merge.h"
19 #include "string-list.h"
20 #include "argv-array.h"
22 #ifdef NO_FAST_WORKING_DIRECTORY
23 #define FAST_WORKING_DIRECTORY 0
24 #else
25 #define FAST_WORKING_DIRECTORY 1
26 #endif
28 static int diff_detect_rename_default;
29 static int diff_rename_limit_default = 400;
30 static int diff_suppress_blank_empty;
31 static int diff_use_color_default = -1;
32 static int diff_context_default = 3;
33 static const char *diff_word_regex_cfg;
34 static const char *external_diff_cmd_cfg;
35 static const char *diff_order_file_cfg;
36 int diff_auto_refresh_index = 1;
37 static int diff_mnemonic_prefix;
38 static int diff_no_prefix;
39 static int diff_stat_graph_width;
40 static int diff_dirstat_permille_default = 30;
41 static struct diff_options default_diff_options;
42 static long diff_algorithm;
44 static char diff_colors[][COLOR_MAXLEN] = {
45 GIT_COLOR_RESET,
46 GIT_COLOR_NORMAL, /* PLAIN */
47 GIT_COLOR_BOLD, /* METAINFO */
48 GIT_COLOR_CYAN, /* FRAGINFO */
49 GIT_COLOR_RED, /* OLD */
50 GIT_COLOR_GREEN, /* NEW */
51 GIT_COLOR_YELLOW, /* COMMIT */
52 GIT_COLOR_BG_RED, /* WHITESPACE */
53 GIT_COLOR_NORMAL, /* FUNCINFO */
56 static int parse_diff_color_slot(const char *var)
58 if (!strcasecmp(var, "plain"))
59 return DIFF_PLAIN;
60 if (!strcasecmp(var, "meta"))
61 return DIFF_METAINFO;
62 if (!strcasecmp(var, "frag"))
63 return DIFF_FRAGINFO;
64 if (!strcasecmp(var, "old"))
65 return DIFF_FILE_OLD;
66 if (!strcasecmp(var, "new"))
67 return DIFF_FILE_NEW;
68 if (!strcasecmp(var, "commit"))
69 return DIFF_COMMIT;
70 if (!strcasecmp(var, "whitespace"))
71 return DIFF_WHITESPACE;
72 if (!strcasecmp(var, "func"))
73 return DIFF_FUNCINFO;
74 return -1;
77 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
78 struct strbuf *errmsg)
80 char *params_copy = xstrdup(params_string);
81 struct string_list params = STRING_LIST_INIT_NODUP;
82 int ret = 0;
83 int i;
85 if (*params_copy)
86 string_list_split_in_place(&params, params_copy, ',', -1);
87 for (i = 0; i < params.nr; i++) {
88 const char *p = params.items[i].string;
89 if (!strcmp(p, "changes")) {
90 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
91 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
92 } else if (!strcmp(p, "lines")) {
93 DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
94 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
95 } else if (!strcmp(p, "files")) {
96 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
97 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
98 } else if (!strcmp(p, "noncumulative")) {
99 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
100 } else if (!strcmp(p, "cumulative")) {
101 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
102 } else if (isdigit(*p)) {
103 char *end;
104 int permille = strtoul(p, &end, 10) * 10;
105 if (*end == '.' && isdigit(*++end)) {
106 /* only use first digit */
107 permille += *end - '0';
108 /* .. and ignore any further digits */
109 while (isdigit(*++end))
110 ; /* nothing */
112 if (!*end)
113 options->dirstat_permille = permille;
114 else {
115 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
117 ret++;
119 } else {
120 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
121 ret++;
125 string_list_clear(&params, 0);
126 free(params_copy);
127 return ret;
130 static int parse_submodule_params(struct diff_options *options, const char *value)
132 if (!strcmp(value, "log"))
133 DIFF_OPT_SET(options, SUBMODULE_LOG);
134 else if (!strcmp(value, "short"))
135 DIFF_OPT_CLR(options, SUBMODULE_LOG);
136 else
137 return -1;
138 return 0;
141 static int git_config_rename(const char *var, const char *value)
143 if (!value)
144 return DIFF_DETECT_RENAME;
145 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
146 return DIFF_DETECT_COPY;
147 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
150 long parse_algorithm_value(const char *value)
152 if (!value)
153 return -1;
154 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
155 return 0;
156 else if (!strcasecmp(value, "minimal"))
157 return XDF_NEED_MINIMAL;
158 else if (!strcasecmp(value, "patience"))
159 return XDF_PATIENCE_DIFF;
160 else if (!strcasecmp(value, "histogram"))
161 return XDF_HISTOGRAM_DIFF;
162 return -1;
166 * These are to give UI layer defaults.
167 * The core-level commands such as git-diff-files should
168 * never be affected by the setting of diff.renames
169 * the user happens to have in the configuration file.
171 int git_diff_ui_config(const char *var, const char *value, void *cb)
173 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
174 diff_use_color_default = git_config_colorbool(var, value);
175 return 0;
177 if (!strcmp(var, "diff.context")) {
178 diff_context_default = git_config_int(var, value);
179 if (diff_context_default < 0)
180 return -1;
181 return 0;
183 if (!strcmp(var, "diff.renames")) {
184 diff_detect_rename_default = git_config_rename(var, value);
185 return 0;
187 if (!strcmp(var, "diff.autorefreshindex")) {
188 diff_auto_refresh_index = git_config_bool(var, value);
189 return 0;
191 if (!strcmp(var, "diff.mnemonicprefix")) {
192 diff_mnemonic_prefix = git_config_bool(var, value);
193 return 0;
195 if (!strcmp(var, "diff.noprefix")) {
196 diff_no_prefix = git_config_bool(var, value);
197 return 0;
199 if (!strcmp(var, "diff.statgraphwidth")) {
200 diff_stat_graph_width = git_config_int(var, value);
201 return 0;
203 if (!strcmp(var, "diff.external"))
204 return git_config_string(&external_diff_cmd_cfg, var, value);
205 if (!strcmp(var, "diff.wordregex"))
206 return git_config_string(&diff_word_regex_cfg, var, value);
207 if (!strcmp(var, "diff.orderfile"))
208 return git_config_pathname(&diff_order_file_cfg, var, value);
210 if (!strcmp(var, "diff.ignoresubmodules"))
211 handle_ignore_submodules_arg(&default_diff_options, value);
213 if (!strcmp(var, "diff.submodule")) {
214 if (parse_submodule_params(&default_diff_options, value))
215 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
216 value);
217 return 0;
220 if (!strcmp(var, "diff.algorithm")) {
221 diff_algorithm = parse_algorithm_value(value);
222 if (diff_algorithm < 0)
223 return -1;
224 return 0;
227 if (git_color_config(var, value, cb) < 0)
228 return -1;
230 return git_diff_basic_config(var, value, cb);
233 int git_diff_basic_config(const char *var, const char *value, void *cb)
235 const char *name;
237 if (!strcmp(var, "diff.renamelimit")) {
238 diff_rename_limit_default = git_config_int(var, value);
239 return 0;
242 if (userdiff_config(var, value) < 0)
243 return -1;
245 if (skip_prefix(var, "diff.color.", &name) ||
246 skip_prefix(var, "color.diff.", &name)) {
247 int slot = parse_diff_color_slot(name);
248 if (slot < 0)
249 return 0;
250 if (!value)
251 return config_error_nonbool(var);
252 return color_parse(value, diff_colors[slot]);
255 /* like GNU diff's --suppress-blank-empty option */
256 if (!strcmp(var, "diff.suppressblankempty") ||
257 /* for backwards compatibility */
258 !strcmp(var, "diff.suppress-blank-empty")) {
259 diff_suppress_blank_empty = git_config_bool(var, value);
260 return 0;
263 if (!strcmp(var, "diff.dirstat")) {
264 struct strbuf errmsg = STRBUF_INIT;
265 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
266 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
267 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
268 errmsg.buf);
269 strbuf_release(&errmsg);
270 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
271 return 0;
274 if (starts_with(var, "submodule."))
275 return parse_submodule_config_option(var, value);
277 return git_default_config(var, value, cb);
280 static char *quote_two(const char *one, const char *two)
282 int need_one = quote_c_style(one, NULL, NULL, 1);
283 int need_two = quote_c_style(two, NULL, NULL, 1);
284 struct strbuf res = STRBUF_INIT;
286 if (need_one + need_two) {
287 strbuf_addch(&res, '"');
288 quote_c_style(one, &res, NULL, 1);
289 quote_c_style(two, &res, NULL, 1);
290 strbuf_addch(&res, '"');
291 } else {
292 strbuf_addstr(&res, one);
293 strbuf_addstr(&res, two);
295 return strbuf_detach(&res, NULL);
298 static const char *external_diff(void)
300 static const char *external_diff_cmd = NULL;
301 static int done_preparing = 0;
303 if (done_preparing)
304 return external_diff_cmd;
305 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
306 if (!external_diff_cmd)
307 external_diff_cmd = external_diff_cmd_cfg;
308 done_preparing = 1;
309 return external_diff_cmd;
313 * Keep track of files used for diffing. Sometimes such an entry
314 * refers to a temporary file, sometimes to an existing file, and
315 * sometimes to "/dev/null".
317 static struct diff_tempfile {
319 * filename external diff should read from, or NULL if this
320 * entry is currently not in use:
322 const char *name;
324 char hex[41];
325 char mode[10];
328 * If this diff_tempfile instance refers to a temporary file,
329 * this tempfile object is used to manage its lifetime.
331 struct tempfile tempfile;
332 } diff_temp[2];
334 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
336 struct emit_callback {
337 int color_diff;
338 unsigned ws_rule;
339 int blank_at_eof_in_preimage;
340 int blank_at_eof_in_postimage;
341 int lno_in_preimage;
342 int lno_in_postimage;
343 sane_truncate_fn truncate;
344 const char **label_path;
345 struct diff_words_data *diff_words;
346 struct diff_options *opt;
347 int *found_changesp;
348 struct strbuf *header;
351 static int count_lines(const char *data, int size)
353 int count, ch, completely_empty = 1, nl_just_seen = 0;
354 count = 0;
355 while (0 < size--) {
356 ch = *data++;
357 if (ch == '\n') {
358 count++;
359 nl_just_seen = 1;
360 completely_empty = 0;
362 else {
363 nl_just_seen = 0;
364 completely_empty = 0;
367 if (completely_empty)
368 return 0;
369 if (!nl_just_seen)
370 count++; /* no trailing newline */
371 return count;
374 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
376 if (!DIFF_FILE_VALID(one)) {
377 mf->ptr = (char *)""; /* does not matter */
378 mf->size = 0;
379 return 0;
381 else if (diff_populate_filespec(one, 0))
382 return -1;
384 mf->ptr = one->data;
385 mf->size = one->size;
386 return 0;
389 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
390 static unsigned long diff_filespec_size(struct diff_filespec *one)
392 if (!DIFF_FILE_VALID(one))
393 return 0;
394 diff_populate_filespec(one, CHECK_SIZE_ONLY);
395 return one->size;
398 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
400 char *ptr = mf->ptr;
401 long size = mf->size;
402 int cnt = 0;
404 if (!size)
405 return cnt;
406 ptr += size - 1; /* pointing at the very end */
407 if (*ptr != '\n')
408 ; /* incomplete line */
409 else
410 ptr--; /* skip the last LF */
411 while (mf->ptr < ptr) {
412 char *prev_eol;
413 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
414 if (*prev_eol == '\n')
415 break;
416 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
417 break;
418 cnt++;
419 ptr = prev_eol - 1;
421 return cnt;
424 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
425 struct emit_callback *ecbdata)
427 int l1, l2, at;
428 unsigned ws_rule = ecbdata->ws_rule;
429 l1 = count_trailing_blank(mf1, ws_rule);
430 l2 = count_trailing_blank(mf2, ws_rule);
431 if (l2 <= l1) {
432 ecbdata->blank_at_eof_in_preimage = 0;
433 ecbdata->blank_at_eof_in_postimage = 0;
434 return;
436 at = count_lines(mf1->ptr, mf1->size);
437 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
439 at = count_lines(mf2->ptr, mf2->size);
440 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
443 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
444 int first, const char *line, int len)
446 int has_trailing_newline, has_trailing_carriage_return;
447 int nofirst;
448 FILE *file = o->file;
450 fputs(diff_line_prefix(o), file);
452 if (len == 0) {
453 has_trailing_newline = (first == '\n');
454 has_trailing_carriage_return = (!has_trailing_newline &&
455 (first == '\r'));
456 nofirst = has_trailing_newline || has_trailing_carriage_return;
457 } else {
458 has_trailing_newline = (len > 0 && line[len-1] == '\n');
459 if (has_trailing_newline)
460 len--;
461 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
462 if (has_trailing_carriage_return)
463 len--;
464 nofirst = 0;
467 if (len || !nofirst) {
468 fputs(set, file);
469 if (!nofirst)
470 fputc(first, file);
471 fwrite(line, len, 1, file);
472 fputs(reset, file);
474 if (has_trailing_carriage_return)
475 fputc('\r', file);
476 if (has_trailing_newline)
477 fputc('\n', file);
480 static void emit_line(struct diff_options *o, const char *set, const char *reset,
481 const char *line, int len)
483 emit_line_0(o, set, reset, line[0], line+1, len-1);
486 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
488 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
489 ecbdata->blank_at_eof_in_preimage &&
490 ecbdata->blank_at_eof_in_postimage &&
491 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
492 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
493 return 0;
494 return ws_blank_line(line, len, ecbdata->ws_rule);
497 static void emit_add_line(const char *reset,
498 struct emit_callback *ecbdata,
499 const char *line, int len)
501 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
502 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
504 if (!*ws)
505 emit_line_0(ecbdata->opt, set, reset, '+', line, len);
506 else if (new_blank_line_at_eof(ecbdata, line, len))
507 /* Blank line at EOF - paint '+' as well */
508 emit_line_0(ecbdata->opt, ws, reset, '+', line, len);
509 else {
510 /* Emit just the prefix, then the rest. */
511 emit_line_0(ecbdata->opt, set, reset, '+', "", 0);
512 ws_check_emit(line, len, ecbdata->ws_rule,
513 ecbdata->opt->file, set, reset, ws);
517 static void emit_hunk_header(struct emit_callback *ecbdata,
518 const char *line, int len)
520 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
521 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
522 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
523 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
524 static const char atat[2] = { '@', '@' };
525 const char *cp, *ep;
526 struct strbuf msgbuf = STRBUF_INIT;
527 int org_len = len;
528 int i = 1;
531 * As a hunk header must begin with "@@ -<old>, +<new> @@",
532 * it always is at least 10 bytes long.
534 if (len < 10 ||
535 memcmp(line, atat, 2) ||
536 !(ep = memmem(line + 2, len - 2, atat, 2))) {
537 emit_line(ecbdata->opt, plain, reset, line, len);
538 return;
540 ep += 2; /* skip over @@ */
542 /* The hunk header in fraginfo color */
543 strbuf_addstr(&msgbuf, frag);
544 strbuf_add(&msgbuf, line, ep - line);
545 strbuf_addstr(&msgbuf, reset);
548 * trailing "\r\n"
550 for ( ; i < 3; i++)
551 if (line[len - i] == '\r' || line[len - i] == '\n')
552 len--;
554 /* blank before the func header */
555 for (cp = ep; ep - line < len; ep++)
556 if (*ep != ' ' && *ep != '\t')
557 break;
558 if (ep != cp) {
559 strbuf_addstr(&msgbuf, plain);
560 strbuf_add(&msgbuf, cp, ep - cp);
561 strbuf_addstr(&msgbuf, reset);
564 if (ep < line + len) {
565 strbuf_addstr(&msgbuf, func);
566 strbuf_add(&msgbuf, ep, line + len - ep);
567 strbuf_addstr(&msgbuf, reset);
570 strbuf_add(&msgbuf, line + len, org_len - len);
571 emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
572 strbuf_release(&msgbuf);
575 static struct diff_tempfile *claim_diff_tempfile(void) {
576 int i;
577 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
578 if (!diff_temp[i].name)
579 return diff_temp + i;
580 die("BUG: diff is failing to clean up its tempfiles");
583 static void remove_tempfile(void)
585 int i;
586 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
587 if (is_tempfile_active(&diff_temp[i].tempfile))
588 delete_tempfile(&diff_temp[i].tempfile);
589 diff_temp[i].name = NULL;
593 static void print_line_count(FILE *file, int count)
595 switch (count) {
596 case 0:
597 fprintf(file, "0,0");
598 break;
599 case 1:
600 fprintf(file, "1");
601 break;
602 default:
603 fprintf(file, "1,%d", count);
604 break;
608 static void emit_rewrite_lines(struct emit_callback *ecb,
609 int prefix, const char *data, int size)
611 const char *endp = NULL;
612 static const char *nneof = " No newline at end of file\n";
613 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
614 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
616 while (0 < size) {
617 int len;
619 endp = memchr(data, '\n', size);
620 len = endp ? (endp - data + 1) : size;
621 if (prefix != '+') {
622 ecb->lno_in_preimage++;
623 emit_line_0(ecb->opt, old, reset, '-',
624 data, len);
625 } else {
626 ecb->lno_in_postimage++;
627 emit_add_line(reset, ecb, data, len);
629 size -= len;
630 data += len;
632 if (!endp) {
633 const char *plain = diff_get_color(ecb->color_diff,
634 DIFF_PLAIN);
635 putc('\n', ecb->opt->file);
636 emit_line_0(ecb->opt, plain, reset, '\\',
637 nneof, strlen(nneof));
641 static void emit_rewrite_diff(const char *name_a,
642 const char *name_b,
643 struct diff_filespec *one,
644 struct diff_filespec *two,
645 struct userdiff_driver *textconv_one,
646 struct userdiff_driver *textconv_two,
647 struct diff_options *o)
649 int lc_a, lc_b;
650 const char *name_a_tab, *name_b_tab;
651 const char *metainfo = diff_get_color(o->use_color, DIFF_METAINFO);
652 const char *fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
653 const char *reset = diff_get_color(o->use_color, DIFF_RESET);
654 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
655 const char *a_prefix, *b_prefix;
656 char *data_one, *data_two;
657 size_t size_one, size_two;
658 struct emit_callback ecbdata;
659 const char *line_prefix = diff_line_prefix(o);
661 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
662 a_prefix = o->b_prefix;
663 b_prefix = o->a_prefix;
664 } else {
665 a_prefix = o->a_prefix;
666 b_prefix = o->b_prefix;
669 name_a += (*name_a == '/');
670 name_b += (*name_b == '/');
671 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
672 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
674 strbuf_reset(&a_name);
675 strbuf_reset(&b_name);
676 quote_two_c_style(&a_name, a_prefix, name_a, 0);
677 quote_two_c_style(&b_name, b_prefix, name_b, 0);
679 size_one = fill_textconv(textconv_one, one, &data_one);
680 size_two = fill_textconv(textconv_two, two, &data_two);
682 memset(&ecbdata, 0, sizeof(ecbdata));
683 ecbdata.color_diff = want_color(o->use_color);
684 ecbdata.found_changesp = &o->found_changes;
685 ecbdata.ws_rule = whitespace_rule(name_b);
686 ecbdata.opt = o;
687 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
688 mmfile_t mf1, mf2;
689 mf1.ptr = (char *)data_one;
690 mf2.ptr = (char *)data_two;
691 mf1.size = size_one;
692 mf2.size = size_two;
693 check_blank_at_eof(&mf1, &mf2, &ecbdata);
695 ecbdata.lno_in_preimage = 1;
696 ecbdata.lno_in_postimage = 1;
698 lc_a = count_lines(data_one, size_one);
699 lc_b = count_lines(data_two, size_two);
700 fprintf(o->file,
701 "%s%s--- %s%s%s\n%s%s+++ %s%s%s\n%s%s@@ -",
702 line_prefix, metainfo, a_name.buf, name_a_tab, reset,
703 line_prefix, metainfo, b_name.buf, name_b_tab, reset,
704 line_prefix, fraginfo);
705 if (!o->irreversible_delete)
706 print_line_count(o->file, lc_a);
707 else
708 fprintf(o->file, "?,?");
709 fprintf(o->file, " +");
710 print_line_count(o->file, lc_b);
711 fprintf(o->file, " @@%s\n", reset);
712 if (lc_a && !o->irreversible_delete)
713 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
714 if (lc_b)
715 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
716 if (textconv_one)
717 free((char *)data_one);
718 if (textconv_two)
719 free((char *)data_two);
722 struct diff_words_buffer {
723 mmfile_t text;
724 long alloc;
725 struct diff_words_orig {
726 const char *begin, *end;
727 } *orig;
728 int orig_nr, orig_alloc;
731 static void diff_words_append(char *line, unsigned long len,
732 struct diff_words_buffer *buffer)
734 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
735 line++;
736 len--;
737 memcpy(buffer->text.ptr + buffer->text.size, line, len);
738 buffer->text.size += len;
739 buffer->text.ptr[buffer->text.size] = '\0';
742 struct diff_words_style_elem {
743 const char *prefix;
744 const char *suffix;
745 const char *color; /* NULL; filled in by the setup code if
746 * color is enabled */
749 struct diff_words_style {
750 enum diff_words_type type;
751 struct diff_words_style_elem new, old, ctx;
752 const char *newline;
755 static struct diff_words_style diff_words_styles[] = {
756 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
757 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
758 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
761 struct diff_words_data {
762 struct diff_words_buffer minus, plus;
763 const char *current_plus;
764 int last_minus;
765 struct diff_options *opt;
766 regex_t *word_regex;
767 enum diff_words_type type;
768 struct diff_words_style *style;
771 static int fn_out_diff_words_write_helper(FILE *fp,
772 struct diff_words_style_elem *st_el,
773 const char *newline,
774 size_t count, const char *buf,
775 const char *line_prefix)
777 int print = 0;
779 while (count) {
780 char *p = memchr(buf, '\n', count);
781 if (print)
782 fputs(line_prefix, fp);
783 if (p != buf) {
784 if (st_el->color && fputs(st_el->color, fp) < 0)
785 return -1;
786 if (fputs(st_el->prefix, fp) < 0 ||
787 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
788 fputs(st_el->suffix, fp) < 0)
789 return -1;
790 if (st_el->color && *st_el->color
791 && fputs(GIT_COLOR_RESET, fp) < 0)
792 return -1;
794 if (!p)
795 return 0;
796 if (fputs(newline, fp) < 0)
797 return -1;
798 count -= p + 1 - buf;
799 buf = p + 1;
800 print = 1;
802 return 0;
806 * '--color-words' algorithm can be described as:
808 * 1. collect a the minus/plus lines of a diff hunk, divided into
809 * minus-lines and plus-lines;
811 * 2. break both minus-lines and plus-lines into words and
812 * place them into two mmfile_t with one word for each line;
814 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
816 * And for the common parts of the both file, we output the plus side text.
817 * diff_words->current_plus is used to trace the current position of the plus file
818 * which printed. diff_words->last_minus is used to trace the last minus word
819 * printed.
821 * For '--graph' to work with '--color-words', we need to output the graph prefix
822 * on each line of color words output. Generally, there are two conditions on
823 * which we should output the prefix.
825 * 1. diff_words->last_minus == 0 &&
826 * diff_words->current_plus == diff_words->plus.text.ptr
828 * that is: the plus text must start as a new line, and if there is no minus
829 * word printed, a graph prefix must be printed.
831 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
832 * *(diff_words->current_plus - 1) == '\n'
834 * that is: a graph prefix must be printed following a '\n'
836 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
838 if ((diff_words->last_minus == 0 &&
839 diff_words->current_plus == diff_words->plus.text.ptr) ||
840 (diff_words->current_plus > diff_words->plus.text.ptr &&
841 *(diff_words->current_plus - 1) == '\n')) {
842 return 1;
843 } else {
844 return 0;
848 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
850 struct diff_words_data *diff_words = priv;
851 struct diff_words_style *style = diff_words->style;
852 int minus_first, minus_len, plus_first, plus_len;
853 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
854 struct diff_options *opt = diff_words->opt;
855 const char *line_prefix;
857 if (line[0] != '@' || parse_hunk_header(line, len,
858 &minus_first, &minus_len, &plus_first, &plus_len))
859 return;
861 assert(opt);
862 line_prefix = diff_line_prefix(opt);
864 /* POSIX requires that first be decremented by one if len == 0... */
865 if (minus_len) {
866 minus_begin = diff_words->minus.orig[minus_first].begin;
867 minus_end =
868 diff_words->minus.orig[minus_first + minus_len - 1].end;
869 } else
870 minus_begin = minus_end =
871 diff_words->minus.orig[minus_first].end;
873 if (plus_len) {
874 plus_begin = diff_words->plus.orig[plus_first].begin;
875 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
876 } else
877 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
879 if (color_words_output_graph_prefix(diff_words)) {
880 fputs(line_prefix, diff_words->opt->file);
882 if (diff_words->current_plus != plus_begin) {
883 fn_out_diff_words_write_helper(diff_words->opt->file,
884 &style->ctx, style->newline,
885 plus_begin - diff_words->current_plus,
886 diff_words->current_plus, line_prefix);
887 if (*(plus_begin - 1) == '\n')
888 fputs(line_prefix, diff_words->opt->file);
890 if (minus_begin != minus_end) {
891 fn_out_diff_words_write_helper(diff_words->opt->file,
892 &style->old, style->newline,
893 minus_end - minus_begin, minus_begin,
894 line_prefix);
896 if (plus_begin != plus_end) {
897 fn_out_diff_words_write_helper(diff_words->opt->file,
898 &style->new, style->newline,
899 plus_end - plus_begin, plus_begin,
900 line_prefix);
903 diff_words->current_plus = plus_end;
904 diff_words->last_minus = minus_first;
907 /* This function starts looking at *begin, and returns 0 iff a word was found. */
908 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
909 int *begin, int *end)
911 if (word_regex && *begin < buffer->size) {
912 regmatch_t match[1];
913 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
914 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
915 '\n', match[0].rm_eo - match[0].rm_so);
916 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
917 *begin += match[0].rm_so;
918 return *begin >= *end;
920 return -1;
923 /* find the next word */
924 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
925 (*begin)++;
926 if (*begin >= buffer->size)
927 return -1;
929 /* find the end of the word */
930 *end = *begin + 1;
931 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
932 (*end)++;
934 return 0;
938 * This function splits the words in buffer->text, stores the list with
939 * newline separator into out, and saves the offsets of the original words
940 * in buffer->orig.
942 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
943 regex_t *word_regex)
945 int i, j;
946 long alloc = 0;
948 out->size = 0;
949 out->ptr = NULL;
951 /* fake an empty "0th" word */
952 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
953 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
954 buffer->orig_nr = 1;
956 for (i = 0; i < buffer->text.size; i++) {
957 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
958 return;
960 /* store original boundaries */
961 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
962 buffer->orig_alloc);
963 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
964 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
965 buffer->orig_nr++;
967 /* store one word */
968 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
969 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
970 out->ptr[out->size + j - i] = '\n';
971 out->size += j - i + 1;
973 i = j - 1;
977 /* this executes the word diff on the accumulated buffers */
978 static void diff_words_show(struct diff_words_data *diff_words)
980 xpparam_t xpp;
981 xdemitconf_t xecfg;
982 mmfile_t minus, plus;
983 struct diff_words_style *style = diff_words->style;
985 struct diff_options *opt = diff_words->opt;
986 const char *line_prefix;
988 assert(opt);
989 line_prefix = diff_line_prefix(opt);
991 /* special case: only removal */
992 if (!diff_words->plus.text.size) {
993 fputs(line_prefix, diff_words->opt->file);
994 fn_out_diff_words_write_helper(diff_words->opt->file,
995 &style->old, style->newline,
996 diff_words->minus.text.size,
997 diff_words->minus.text.ptr, line_prefix);
998 diff_words->minus.text.size = 0;
999 return;
1002 diff_words->current_plus = diff_words->plus.text.ptr;
1003 diff_words->last_minus = 0;
1005 memset(&xpp, 0, sizeof(xpp));
1006 memset(&xecfg, 0, sizeof(xecfg));
1007 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1008 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1009 xpp.flags = 0;
1010 /* as only the hunk header will be parsed, we need a 0-context */
1011 xecfg.ctxlen = 0;
1012 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1013 &xpp, &xecfg);
1014 free(minus.ptr);
1015 free(plus.ptr);
1016 if (diff_words->current_plus != diff_words->plus.text.ptr +
1017 diff_words->plus.text.size) {
1018 if (color_words_output_graph_prefix(diff_words))
1019 fputs(line_prefix, diff_words->opt->file);
1020 fn_out_diff_words_write_helper(diff_words->opt->file,
1021 &style->ctx, style->newline,
1022 diff_words->plus.text.ptr + diff_words->plus.text.size
1023 - diff_words->current_plus, diff_words->current_plus,
1024 line_prefix);
1026 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1029 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1030 static void diff_words_flush(struct emit_callback *ecbdata)
1032 if (ecbdata->diff_words->minus.text.size ||
1033 ecbdata->diff_words->plus.text.size)
1034 diff_words_show(ecbdata->diff_words);
1037 static void diff_filespec_load_driver(struct diff_filespec *one)
1039 /* Use already-loaded driver */
1040 if (one->driver)
1041 return;
1043 if (S_ISREG(one->mode))
1044 one->driver = userdiff_find_by_path(one->path);
1046 /* Fallback to default settings */
1047 if (!one->driver)
1048 one->driver = userdiff_find_by_name("default");
1051 static const char *userdiff_word_regex(struct diff_filespec *one)
1053 diff_filespec_load_driver(one);
1054 return one->driver->word_regex;
1057 static void init_diff_words_data(struct emit_callback *ecbdata,
1058 struct diff_options *orig_opts,
1059 struct diff_filespec *one,
1060 struct diff_filespec *two)
1062 int i;
1063 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1064 memcpy(o, orig_opts, sizeof(struct diff_options));
1066 ecbdata->diff_words =
1067 xcalloc(1, sizeof(struct diff_words_data));
1068 ecbdata->diff_words->type = o->word_diff;
1069 ecbdata->diff_words->opt = o;
1070 if (!o->word_regex)
1071 o->word_regex = userdiff_word_regex(one);
1072 if (!o->word_regex)
1073 o->word_regex = userdiff_word_regex(two);
1074 if (!o->word_regex)
1075 o->word_regex = diff_word_regex_cfg;
1076 if (o->word_regex) {
1077 ecbdata->diff_words->word_regex = (regex_t *)
1078 xmalloc(sizeof(regex_t));
1079 if (regcomp(ecbdata->diff_words->word_regex,
1080 o->word_regex,
1081 REG_EXTENDED | REG_NEWLINE))
1082 die ("Invalid regular expression: %s",
1083 o->word_regex);
1085 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1086 if (o->word_diff == diff_words_styles[i].type) {
1087 ecbdata->diff_words->style =
1088 &diff_words_styles[i];
1089 break;
1092 if (want_color(o->use_color)) {
1093 struct diff_words_style *st = ecbdata->diff_words->style;
1094 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1095 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1096 st->ctx.color = diff_get_color_opt(o, DIFF_PLAIN);
1100 static void free_diff_words_data(struct emit_callback *ecbdata)
1102 if (ecbdata->diff_words) {
1103 diff_words_flush(ecbdata);
1104 free (ecbdata->diff_words->opt);
1105 free (ecbdata->diff_words->minus.text.ptr);
1106 free (ecbdata->diff_words->minus.orig);
1107 free (ecbdata->diff_words->plus.text.ptr);
1108 free (ecbdata->diff_words->plus.orig);
1109 if (ecbdata->diff_words->word_regex) {
1110 regfree(ecbdata->diff_words->word_regex);
1111 free(ecbdata->diff_words->word_regex);
1113 free(ecbdata->diff_words);
1114 ecbdata->diff_words = NULL;
1118 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1120 if (want_color(diff_use_color))
1121 return diff_colors[ix];
1122 return "";
1125 const char *diff_line_prefix(struct diff_options *opt)
1127 struct strbuf *msgbuf;
1128 if (!opt->output_prefix)
1129 return "";
1131 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1132 return msgbuf->buf;
1135 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1137 const char *cp;
1138 unsigned long allot;
1139 size_t l = len;
1141 if (ecb->truncate)
1142 return ecb->truncate(line, len);
1143 cp = line;
1144 allot = l;
1145 while (0 < l) {
1146 (void) utf8_width(&cp, &l);
1147 if (!cp)
1148 break; /* truncated in the middle? */
1150 return allot - l;
1153 static void find_lno(const char *line, struct emit_callback *ecbdata)
1155 const char *p;
1156 ecbdata->lno_in_preimage = 0;
1157 ecbdata->lno_in_postimage = 0;
1158 p = strchr(line, '-');
1159 if (!p)
1160 return; /* cannot happen */
1161 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1162 p = strchr(p, '+');
1163 if (!p)
1164 return; /* cannot happen */
1165 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1168 static void fn_out_consume(void *priv, char *line, unsigned long len)
1170 struct emit_callback *ecbdata = priv;
1171 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
1172 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
1173 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1174 struct diff_options *o = ecbdata->opt;
1175 const char *line_prefix = diff_line_prefix(o);
1177 if (ecbdata->header) {
1178 fprintf(ecbdata->opt->file, "%s", ecbdata->header->buf);
1179 strbuf_reset(ecbdata->header);
1180 ecbdata->header = NULL;
1182 *(ecbdata->found_changesp) = 1;
1184 if (ecbdata->label_path[0]) {
1185 const char *name_a_tab, *name_b_tab;
1187 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
1188 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
1190 fprintf(ecbdata->opt->file, "%s%s--- %s%s%s\n",
1191 line_prefix, meta, ecbdata->label_path[0], reset, name_a_tab);
1192 fprintf(ecbdata->opt->file, "%s%s+++ %s%s%s\n",
1193 line_prefix, meta, ecbdata->label_path[1], reset, name_b_tab);
1194 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1197 if (diff_suppress_blank_empty
1198 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1199 line[0] = '\n';
1200 len = 1;
1203 if (line[0] == '@') {
1204 if (ecbdata->diff_words)
1205 diff_words_flush(ecbdata);
1206 len = sane_truncate_line(ecbdata, line, len);
1207 find_lno(line, ecbdata);
1208 emit_hunk_header(ecbdata, line, len);
1209 if (line[len-1] != '\n')
1210 putc('\n', ecbdata->opt->file);
1211 return;
1214 if (len < 1) {
1215 emit_line(ecbdata->opt, reset, reset, line, len);
1216 if (ecbdata->diff_words
1217 && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
1218 fputs("~\n", ecbdata->opt->file);
1219 return;
1222 if (ecbdata->diff_words) {
1223 if (line[0] == '-') {
1224 diff_words_append(line, len,
1225 &ecbdata->diff_words->minus);
1226 return;
1227 } else if (line[0] == '+') {
1228 diff_words_append(line, len,
1229 &ecbdata->diff_words->plus);
1230 return;
1231 } else if (starts_with(line, "\\ ")) {
1233 * Eat the "no newline at eof" marker as if we
1234 * saw a "+" or "-" line with nothing on it,
1235 * and return without diff_words_flush() to
1236 * defer processing. If this is the end of
1237 * preimage, more "+" lines may come after it.
1239 return;
1241 diff_words_flush(ecbdata);
1242 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
1243 emit_line(ecbdata->opt, plain, reset, line, len);
1244 fputs("~\n", ecbdata->opt->file);
1245 } else {
1247 * Skip the prefix character, if any. With
1248 * diff_suppress_blank_empty, there may be
1249 * none.
1251 if (line[0] != '\n') {
1252 line++;
1253 len--;
1255 emit_line(ecbdata->opt, plain, reset, line, len);
1257 return;
1260 if (line[0] != '+') {
1261 const char *color =
1262 diff_get_color(ecbdata->color_diff,
1263 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
1264 ecbdata->lno_in_preimage++;
1265 if (line[0] == ' ')
1266 ecbdata->lno_in_postimage++;
1267 emit_line(ecbdata->opt, color, reset, line, len);
1268 } else {
1269 ecbdata->lno_in_postimage++;
1270 emit_add_line(reset, ecbdata, line + 1, len - 1);
1274 static char *pprint_rename(const char *a, const char *b)
1276 const char *old = a;
1277 const char *new = b;
1278 struct strbuf name = STRBUF_INIT;
1279 int pfx_length, sfx_length;
1280 int pfx_adjust_for_slash;
1281 int len_a = strlen(a);
1282 int len_b = strlen(b);
1283 int a_midlen, b_midlen;
1284 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1285 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1287 if (qlen_a || qlen_b) {
1288 quote_c_style(a, &name, NULL, 0);
1289 strbuf_addstr(&name, " => ");
1290 quote_c_style(b, &name, NULL, 0);
1291 return strbuf_detach(&name, NULL);
1294 /* Find common prefix */
1295 pfx_length = 0;
1296 while (*old && *new && *old == *new) {
1297 if (*old == '/')
1298 pfx_length = old - a + 1;
1299 old++;
1300 new++;
1303 /* Find common suffix */
1304 old = a + len_a;
1305 new = b + len_b;
1306 sfx_length = 0;
1308 * If there is a common prefix, it must end in a slash. In
1309 * that case we let this loop run 1 into the prefix to see the
1310 * same slash.
1312 * If there is no common prefix, we cannot do this as it would
1313 * underrun the input strings.
1315 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
1316 while (a + pfx_length - pfx_adjust_for_slash <= old &&
1317 b + pfx_length - pfx_adjust_for_slash <= new &&
1318 *old == *new) {
1319 if (*old == '/')
1320 sfx_length = len_a - (old - a);
1321 old--;
1322 new--;
1326 * pfx{mid-a => mid-b}sfx
1327 * {pfx-a => pfx-b}sfx
1328 * pfx{sfx-a => sfx-b}
1329 * name-a => name-b
1331 a_midlen = len_a - pfx_length - sfx_length;
1332 b_midlen = len_b - pfx_length - sfx_length;
1333 if (a_midlen < 0)
1334 a_midlen = 0;
1335 if (b_midlen < 0)
1336 b_midlen = 0;
1338 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1339 if (pfx_length + sfx_length) {
1340 strbuf_add(&name, a, pfx_length);
1341 strbuf_addch(&name, '{');
1343 strbuf_add(&name, a + pfx_length, a_midlen);
1344 strbuf_addstr(&name, " => ");
1345 strbuf_add(&name, b + pfx_length, b_midlen);
1346 if (pfx_length + sfx_length) {
1347 strbuf_addch(&name, '}');
1348 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1350 return strbuf_detach(&name, NULL);
1353 struct diffstat_t {
1354 int nr;
1355 int alloc;
1356 struct diffstat_file {
1357 char *from_name;
1358 char *name;
1359 char *print_name;
1360 unsigned is_unmerged:1;
1361 unsigned is_binary:1;
1362 unsigned is_renamed:1;
1363 unsigned is_interesting:1;
1364 uintmax_t added, deleted;
1365 } **files;
1368 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1369 const char *name_a,
1370 const char *name_b)
1372 struct diffstat_file *x;
1373 x = xcalloc(1, sizeof(*x));
1374 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
1375 diffstat->files[diffstat->nr++] = x;
1376 if (name_b) {
1377 x->from_name = xstrdup(name_a);
1378 x->name = xstrdup(name_b);
1379 x->is_renamed = 1;
1381 else {
1382 x->from_name = NULL;
1383 x->name = xstrdup(name_a);
1385 return x;
1388 static void diffstat_consume(void *priv, char *line, unsigned long len)
1390 struct diffstat_t *diffstat = priv;
1391 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1393 if (line[0] == '+')
1394 x->added++;
1395 else if (line[0] == '-')
1396 x->deleted++;
1399 const char mime_boundary_leader[] = "------------";
1401 static int scale_linear(int it, int width, int max_change)
1403 if (!it)
1404 return 0;
1406 * make sure that at least one '-' or '+' is printed if
1407 * there is any change to this path. The easiest way is to
1408 * scale linearly as if the alloted width is one column shorter
1409 * than it is, and then add 1 to the result.
1411 return 1 + (it * (width - 1) / max_change);
1414 static void show_name(FILE *file,
1415 const char *prefix, const char *name, int len)
1417 fprintf(file, " %s%-*s |", prefix, len, name);
1420 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1422 if (cnt <= 0)
1423 return;
1424 fprintf(file, "%s", set);
1425 while (cnt--)
1426 putc(ch, file);
1427 fprintf(file, "%s", reset);
1430 static void fill_print_name(struct diffstat_file *file)
1432 char *pname;
1434 if (file->print_name)
1435 return;
1437 if (!file->is_renamed) {
1438 struct strbuf buf = STRBUF_INIT;
1439 if (quote_c_style(file->name, &buf, NULL, 0)) {
1440 pname = strbuf_detach(&buf, NULL);
1441 } else {
1442 pname = file->name;
1443 strbuf_release(&buf);
1445 } else {
1446 pname = pprint_rename(file->from_name, file->name);
1448 file->print_name = pname;
1451 int print_stat_summary(FILE *fp, int files, int insertions, int deletions)
1453 struct strbuf sb = STRBUF_INIT;
1454 int ret;
1456 if (!files) {
1457 assert(insertions == 0 && deletions == 0);
1458 return fprintf(fp, "%s\n", " 0 files changed");
1461 strbuf_addf(&sb,
1462 (files == 1) ? " %d file changed" : " %d files changed",
1463 files);
1466 * For binary diff, the caller may want to print "x files
1467 * changed" with insertions == 0 && deletions == 0.
1469 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
1470 * is probably less confusing (i.e skip over "2 files changed
1471 * but nothing about added/removed lines? Is this a bug in Git?").
1473 if (insertions || deletions == 0) {
1474 strbuf_addf(&sb,
1475 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
1476 insertions);
1479 if (deletions || insertions == 0) {
1480 strbuf_addf(&sb,
1481 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
1482 deletions);
1484 strbuf_addch(&sb, '\n');
1485 ret = fputs(sb.buf, fp);
1486 strbuf_release(&sb);
1487 return ret;
1490 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1492 int i, len, add, del, adds = 0, dels = 0;
1493 uintmax_t max_change = 0, max_len = 0;
1494 int total_files = data->nr, count;
1495 int width, name_width, graph_width, number_width = 0, bin_width = 0;
1496 const char *reset, *add_c, *del_c;
1497 const char *line_prefix = "";
1498 int extra_shown = 0;
1500 if (data->nr == 0)
1501 return;
1503 line_prefix = diff_line_prefix(options);
1504 count = options->stat_count ? options->stat_count : data->nr;
1506 reset = diff_get_color_opt(options, DIFF_RESET);
1507 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1508 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1511 * Find the longest filename and max number of changes
1513 for (i = 0; (i < count) && (i < data->nr); i++) {
1514 struct diffstat_file *file = data->files[i];
1515 uintmax_t change = file->added + file->deleted;
1517 if (!file->is_interesting && (change == 0)) {
1518 count++; /* not shown == room for one more */
1519 continue;
1521 fill_print_name(file);
1522 len = strlen(file->print_name);
1523 if (max_len < len)
1524 max_len = len;
1526 if (file->is_unmerged) {
1527 /* "Unmerged" is 8 characters */
1528 bin_width = bin_width < 8 ? 8 : bin_width;
1529 continue;
1531 if (file->is_binary) {
1532 /* "Bin XXX -> YYY bytes" */
1533 int w = 14 + decimal_width(file->added)
1534 + decimal_width(file->deleted);
1535 bin_width = bin_width < w ? w : bin_width;
1536 /* Display change counts aligned with "Bin" */
1537 number_width = 3;
1538 continue;
1541 if (max_change < change)
1542 max_change = change;
1544 count = i; /* where we can stop scanning in data->files[] */
1547 * We have width = stat_width or term_columns() columns total.
1548 * We want a maximum of min(max_len, stat_name_width) for the name part.
1549 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1550 * We also need 1 for " " and 4 + decimal_width(max_change)
1551 * for " | NNNN " and one the empty column at the end, altogether
1552 * 6 + decimal_width(max_change).
1554 * If there's not enough space, we will use the smaller of
1555 * stat_name_width (if set) and 5/8*width for the filename,
1556 * and the rest for constant elements + graph part, but no more
1557 * than stat_graph_width for the graph part.
1558 * (5/8 gives 50 for filename and 30 for the constant parts + graph
1559 * for the standard terminal size).
1561 * In other words: stat_width limits the maximum width, and
1562 * stat_name_width fixes the maximum width of the filename,
1563 * and is also used to divide available columns if there
1564 * aren't enough.
1566 * Binary files are displayed with "Bin XXX -> YYY bytes"
1567 * instead of the change count and graph. This part is treated
1568 * similarly to the graph part, except that it is not
1569 * "scaled". If total width is too small to accommodate the
1570 * guaranteed minimum width of the filename part and the
1571 * separators and this message, this message will "overflow"
1572 * making the line longer than the maximum width.
1575 if (options->stat_width == -1)
1576 width = term_columns() - options->output_prefix_length;
1577 else
1578 width = options->stat_width ? options->stat_width : 80;
1579 number_width = decimal_width(max_change) > number_width ?
1580 decimal_width(max_change) : number_width;
1582 if (options->stat_graph_width == -1)
1583 options->stat_graph_width = diff_stat_graph_width;
1586 * Guarantee 3/8*16==6 for the graph part
1587 * and 5/8*16==10 for the filename part
1589 if (width < 16 + 6 + number_width)
1590 width = 16 + 6 + number_width;
1593 * First assign sizes that are wanted, ignoring available width.
1594 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
1595 * starting from "XXX" should fit in graph_width.
1597 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
1598 if (options->stat_graph_width &&
1599 options->stat_graph_width < graph_width)
1600 graph_width = options->stat_graph_width;
1602 name_width = (options->stat_name_width > 0 &&
1603 options->stat_name_width < max_len) ?
1604 options->stat_name_width : max_len;
1607 * Adjust adjustable widths not to exceed maximum width
1609 if (name_width + number_width + 6 + graph_width > width) {
1610 if (graph_width > width * 3/8 - number_width - 6) {
1611 graph_width = width * 3/8 - number_width - 6;
1612 if (graph_width < 6)
1613 graph_width = 6;
1616 if (options->stat_graph_width &&
1617 graph_width > options->stat_graph_width)
1618 graph_width = options->stat_graph_width;
1619 if (name_width > width - number_width - 6 - graph_width)
1620 name_width = width - number_width - 6 - graph_width;
1621 else
1622 graph_width = width - number_width - 6 - name_width;
1626 * From here name_width is the width of the name area,
1627 * and graph_width is the width of the graph area.
1628 * max_change is used to scale graph properly.
1630 for (i = 0; i < count; i++) {
1631 const char *prefix = "";
1632 struct diffstat_file *file = data->files[i];
1633 char *name = file->print_name;
1634 uintmax_t added = file->added;
1635 uintmax_t deleted = file->deleted;
1636 int name_len;
1638 if (!file->is_interesting && (added + deleted == 0))
1639 continue;
1642 * "scale" the filename
1644 len = name_width;
1645 name_len = strlen(name);
1646 if (name_width < name_len) {
1647 char *slash;
1648 prefix = "...";
1649 len -= 3;
1650 name += name_len - len;
1651 slash = strchr(name, '/');
1652 if (slash)
1653 name = slash;
1656 if (file->is_binary) {
1657 fprintf(options->file, "%s", line_prefix);
1658 show_name(options->file, prefix, name, len);
1659 fprintf(options->file, " %*s", number_width, "Bin");
1660 if (!added && !deleted) {
1661 putc('\n', options->file);
1662 continue;
1664 fprintf(options->file, " %s%"PRIuMAX"%s",
1665 del_c, deleted, reset);
1666 fprintf(options->file, " -> ");
1667 fprintf(options->file, "%s%"PRIuMAX"%s",
1668 add_c, added, reset);
1669 fprintf(options->file, " bytes");
1670 fprintf(options->file, "\n");
1671 continue;
1673 else if (file->is_unmerged) {
1674 fprintf(options->file, "%s", line_prefix);
1675 show_name(options->file, prefix, name, len);
1676 fprintf(options->file, " Unmerged\n");
1677 continue;
1681 * scale the add/delete
1683 add = added;
1684 del = deleted;
1686 if (graph_width <= max_change) {
1687 int total = scale_linear(add + del, graph_width, max_change);
1688 if (total < 2 && add && del)
1689 /* width >= 2 due to the sanity check */
1690 total = 2;
1691 if (add < del) {
1692 add = scale_linear(add, graph_width, max_change);
1693 del = total - add;
1694 } else {
1695 del = scale_linear(del, graph_width, max_change);
1696 add = total - del;
1699 fprintf(options->file, "%s", line_prefix);
1700 show_name(options->file, prefix, name, len);
1701 fprintf(options->file, " %*"PRIuMAX"%s",
1702 number_width, added + deleted,
1703 added + deleted ? " " : "");
1704 show_graph(options->file, '+', add, add_c, reset);
1705 show_graph(options->file, '-', del, del_c, reset);
1706 fprintf(options->file, "\n");
1709 for (i = 0; i < data->nr; i++) {
1710 struct diffstat_file *file = data->files[i];
1711 uintmax_t added = file->added;
1712 uintmax_t deleted = file->deleted;
1714 if (file->is_unmerged ||
1715 (!file->is_interesting && (added + deleted == 0))) {
1716 total_files--;
1717 continue;
1720 if (!file->is_binary) {
1721 adds += added;
1722 dels += deleted;
1724 if (i < count)
1725 continue;
1726 if (!extra_shown)
1727 fprintf(options->file, "%s ...\n", line_prefix);
1728 extra_shown = 1;
1730 fprintf(options->file, "%s", line_prefix);
1731 print_stat_summary(options->file, total_files, adds, dels);
1734 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1736 int i, adds = 0, dels = 0, total_files = data->nr;
1738 if (data->nr == 0)
1739 return;
1741 for (i = 0; i < data->nr; i++) {
1742 int added = data->files[i]->added;
1743 int deleted= data->files[i]->deleted;
1745 if (data->files[i]->is_unmerged ||
1746 (!data->files[i]->is_interesting && (added + deleted == 0))) {
1747 total_files--;
1748 } else if (!data->files[i]->is_binary) { /* don't count bytes */
1749 adds += added;
1750 dels += deleted;
1753 fprintf(options->file, "%s", diff_line_prefix(options));
1754 print_stat_summary(options->file, total_files, adds, dels);
1757 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1759 int i;
1761 if (data->nr == 0)
1762 return;
1764 for (i = 0; i < data->nr; i++) {
1765 struct diffstat_file *file = data->files[i];
1767 fprintf(options->file, "%s", diff_line_prefix(options));
1769 if (file->is_binary)
1770 fprintf(options->file, "-\t-\t");
1771 else
1772 fprintf(options->file,
1773 "%"PRIuMAX"\t%"PRIuMAX"\t",
1774 file->added, file->deleted);
1775 if (options->line_termination) {
1776 fill_print_name(file);
1777 if (!file->is_renamed)
1778 write_name_quoted(file->name, options->file,
1779 options->line_termination);
1780 else {
1781 fputs(file->print_name, options->file);
1782 putc(options->line_termination, options->file);
1784 } else {
1785 if (file->is_renamed) {
1786 putc('\0', options->file);
1787 write_name_quoted(file->from_name, options->file, '\0');
1789 write_name_quoted(file->name, options->file, '\0');
1794 struct dirstat_file {
1795 const char *name;
1796 unsigned long changed;
1799 struct dirstat_dir {
1800 struct dirstat_file *files;
1801 int alloc, nr, permille, cumulative;
1804 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
1805 unsigned long changed, const char *base, int baselen)
1807 unsigned long this_dir = 0;
1808 unsigned int sources = 0;
1809 const char *line_prefix = diff_line_prefix(opt);
1811 while (dir->nr) {
1812 struct dirstat_file *f = dir->files;
1813 int namelen = strlen(f->name);
1814 unsigned long this;
1815 char *slash;
1817 if (namelen < baselen)
1818 break;
1819 if (memcmp(f->name, base, baselen))
1820 break;
1821 slash = strchr(f->name + baselen, '/');
1822 if (slash) {
1823 int newbaselen = slash + 1 - f->name;
1824 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
1825 sources++;
1826 } else {
1827 this = f->changed;
1828 dir->files++;
1829 dir->nr--;
1830 sources += 2;
1832 this_dir += this;
1836 * We don't report dirstat's for
1837 * - the top level
1838 * - or cases where everything came from a single directory
1839 * under this directory (sources == 1).
1841 if (baselen && sources != 1) {
1842 if (this_dir) {
1843 int permille = this_dir * 1000 / changed;
1844 if (permille >= dir->permille) {
1845 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
1846 permille / 10, permille % 10, baselen, base);
1847 if (!dir->cumulative)
1848 return 0;
1852 return this_dir;
1855 static int dirstat_compare(const void *_a, const void *_b)
1857 const struct dirstat_file *a = _a;
1858 const struct dirstat_file *b = _b;
1859 return strcmp(a->name, b->name);
1862 static void show_dirstat(struct diff_options *options)
1864 int i;
1865 unsigned long changed;
1866 struct dirstat_dir dir;
1867 struct diff_queue_struct *q = &diff_queued_diff;
1869 dir.files = NULL;
1870 dir.alloc = 0;
1871 dir.nr = 0;
1872 dir.permille = options->dirstat_permille;
1873 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1875 changed = 0;
1876 for (i = 0; i < q->nr; i++) {
1877 struct diff_filepair *p = q->queue[i];
1878 const char *name;
1879 unsigned long copied, added, damage;
1880 int content_changed;
1882 name = p->two->path ? p->two->path : p->one->path;
1884 if (p->one->sha1_valid && p->two->sha1_valid)
1885 content_changed = hashcmp(p->one->sha1, p->two->sha1);
1886 else
1887 content_changed = 1;
1889 if (!content_changed) {
1891 * The SHA1 has not changed, so pre-/post-content is
1892 * identical. We can therefore skip looking at the
1893 * file contents altogether.
1895 damage = 0;
1896 goto found_damage;
1899 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
1901 * In --dirstat-by-file mode, we don't really need to
1902 * look at the actual file contents at all.
1903 * The fact that the SHA1 changed is enough for us to
1904 * add this file to the list of results
1905 * (with each file contributing equal damage).
1907 damage = 1;
1908 goto found_damage;
1911 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1912 diff_populate_filespec(p->one, 0);
1913 diff_populate_filespec(p->two, 0);
1914 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1915 &copied, &added);
1916 diff_free_filespec_data(p->one);
1917 diff_free_filespec_data(p->two);
1918 } else if (DIFF_FILE_VALID(p->one)) {
1919 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
1920 copied = added = 0;
1921 diff_free_filespec_data(p->one);
1922 } else if (DIFF_FILE_VALID(p->two)) {
1923 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
1924 copied = 0;
1925 added = p->two->size;
1926 diff_free_filespec_data(p->two);
1927 } else
1928 continue;
1931 * Original minus copied is the removed material,
1932 * added is the new material. They are both damages
1933 * made to the preimage.
1934 * If the resulting damage is zero, we know that
1935 * diffcore_count_changes() considers the two entries to
1936 * be identical, but since content_changed is true, we
1937 * know that there must have been _some_ kind of change,
1938 * so we force all entries to have damage > 0.
1940 damage = (p->one->size - copied) + added;
1941 if (!damage)
1942 damage = 1;
1944 found_damage:
1945 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1946 dir.files[dir.nr].name = name;
1947 dir.files[dir.nr].changed = damage;
1948 changed += damage;
1949 dir.nr++;
1952 /* This can happen even with many files, if everything was renames */
1953 if (!changed)
1954 return;
1956 /* Show all directories with more than x% of the changes */
1957 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1958 gather_dirstat(options, &dir, changed, "", 0);
1961 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
1963 int i;
1964 unsigned long changed;
1965 struct dirstat_dir dir;
1967 if (data->nr == 0)
1968 return;
1970 dir.files = NULL;
1971 dir.alloc = 0;
1972 dir.nr = 0;
1973 dir.permille = options->dirstat_permille;
1974 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1976 changed = 0;
1977 for (i = 0; i < data->nr; i++) {
1978 struct diffstat_file *file = data->files[i];
1979 unsigned long damage = file->added + file->deleted;
1980 if (file->is_binary)
1982 * binary files counts bytes, not lines. Must find some
1983 * way to normalize binary bytes vs. textual lines.
1984 * The following heuristic assumes that there are 64
1985 * bytes per "line".
1986 * This is stupid and ugly, but very cheap...
1988 damage = (damage + 63) / 64;
1989 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1990 dir.files[dir.nr].name = file->name;
1991 dir.files[dir.nr].changed = damage;
1992 changed += damage;
1993 dir.nr++;
1996 /* This can happen even with many files, if everything was renames */
1997 if (!changed)
1998 return;
2000 /* Show all directories with more than x% of the changes */
2001 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
2002 gather_dirstat(options, &dir, changed, "", 0);
2005 static void free_diffstat_info(struct diffstat_t *diffstat)
2007 int i;
2008 for (i = 0; i < diffstat->nr; i++) {
2009 struct diffstat_file *f = diffstat->files[i];
2010 if (f->name != f->print_name)
2011 free(f->print_name);
2012 free(f->name);
2013 free(f->from_name);
2014 free(f);
2016 free(diffstat->files);
2019 struct checkdiff_t {
2020 const char *filename;
2021 int lineno;
2022 int conflict_marker_size;
2023 struct diff_options *o;
2024 unsigned ws_rule;
2025 unsigned status;
2028 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2030 char firstchar;
2031 int cnt;
2033 if (len < marker_size + 1)
2034 return 0;
2035 firstchar = line[0];
2036 switch (firstchar) {
2037 case '=': case '>': case '<': case '|':
2038 break;
2039 default:
2040 return 0;
2042 for (cnt = 1; cnt < marker_size; cnt++)
2043 if (line[cnt] != firstchar)
2044 return 0;
2045 /* line[1] thru line[marker_size-1] are same as firstchar */
2046 if (len < marker_size + 1 || !isspace(line[marker_size]))
2047 return 0;
2048 return 1;
2051 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2053 struct checkdiff_t *data = priv;
2054 int marker_size = data->conflict_marker_size;
2055 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2056 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2057 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2058 char *err;
2059 const char *line_prefix;
2061 assert(data->o);
2062 line_prefix = diff_line_prefix(data->o);
2064 if (line[0] == '+') {
2065 unsigned bad;
2066 data->lineno++;
2067 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2068 data->status |= 1;
2069 fprintf(data->o->file,
2070 "%s%s:%d: leftover conflict marker\n",
2071 line_prefix, data->filename, data->lineno);
2073 bad = ws_check(line + 1, len - 1, data->ws_rule);
2074 if (!bad)
2075 return;
2076 data->status |= bad;
2077 err = whitespace_error_string(bad);
2078 fprintf(data->o->file, "%s%s:%d: %s.\n",
2079 line_prefix, data->filename, data->lineno, err);
2080 free(err);
2081 emit_line(data->o, set, reset, line, 1);
2082 ws_check_emit(line + 1, len - 1, data->ws_rule,
2083 data->o->file, set, reset, ws);
2084 } else if (line[0] == ' ') {
2085 data->lineno++;
2086 } else if (line[0] == '@') {
2087 char *plus = strchr(line, '+');
2088 if (plus)
2089 data->lineno = strtol(plus, NULL, 10) - 1;
2090 else
2091 die("invalid diff");
2095 static unsigned char *deflate_it(char *data,
2096 unsigned long size,
2097 unsigned long *result_size)
2099 int bound;
2100 unsigned char *deflated;
2101 git_zstream stream;
2103 git_deflate_init(&stream, zlib_compression_level);
2104 bound = git_deflate_bound(&stream, size);
2105 deflated = xmalloc(bound);
2106 stream.next_out = deflated;
2107 stream.avail_out = bound;
2109 stream.next_in = (unsigned char *)data;
2110 stream.avail_in = size;
2111 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2112 ; /* nothing */
2113 git_deflate_end(&stream);
2114 *result_size = stream.total_out;
2115 return deflated;
2118 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two,
2119 const char *prefix)
2121 void *cp;
2122 void *delta;
2123 void *deflated;
2124 void *data;
2125 unsigned long orig_size;
2126 unsigned long delta_size;
2127 unsigned long deflate_size;
2128 unsigned long data_size;
2130 /* We could do deflated delta, or we could do just deflated two,
2131 * whichever is smaller.
2133 delta = NULL;
2134 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2135 if (one->size && two->size) {
2136 delta = diff_delta(one->ptr, one->size,
2137 two->ptr, two->size,
2138 &delta_size, deflate_size);
2139 if (delta) {
2140 void *to_free = delta;
2141 orig_size = delta_size;
2142 delta = deflate_it(delta, delta_size, &delta_size);
2143 free(to_free);
2147 if (delta && delta_size < deflate_size) {
2148 fprintf(file, "%sdelta %lu\n", prefix, orig_size);
2149 free(deflated);
2150 data = delta;
2151 data_size = delta_size;
2153 else {
2154 fprintf(file, "%sliteral %lu\n", prefix, two->size);
2155 free(delta);
2156 data = deflated;
2157 data_size = deflate_size;
2160 /* emit data encoded in base85 */
2161 cp = data;
2162 while (data_size) {
2163 int bytes = (52 < data_size) ? 52 : data_size;
2164 char line[70];
2165 data_size -= bytes;
2166 if (bytes <= 26)
2167 line[0] = bytes + 'A' - 1;
2168 else
2169 line[0] = bytes - 26 + 'a' - 1;
2170 encode_85(line + 1, cp, bytes);
2171 cp = (char *) cp + bytes;
2172 fprintf(file, "%s", prefix);
2173 fputs(line, file);
2174 fputc('\n', file);
2176 fprintf(file, "%s\n", prefix);
2177 free(data);
2180 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two,
2181 const char *prefix)
2183 fprintf(file, "%sGIT binary patch\n", prefix);
2184 emit_binary_diff_body(file, one, two, prefix);
2185 emit_binary_diff_body(file, two, one, prefix);
2188 int diff_filespec_is_binary(struct diff_filespec *one)
2190 if (one->is_binary == -1) {
2191 diff_filespec_load_driver(one);
2192 if (one->driver->binary != -1)
2193 one->is_binary = one->driver->binary;
2194 else {
2195 if (!one->data && DIFF_FILE_VALID(one))
2196 diff_populate_filespec(one, CHECK_BINARY);
2197 if (one->is_binary == -1 && one->data)
2198 one->is_binary = buffer_is_binary(one->data,
2199 one->size);
2200 if (one->is_binary == -1)
2201 one->is_binary = 0;
2204 return one->is_binary;
2207 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2209 diff_filespec_load_driver(one);
2210 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2213 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2215 if (!options->a_prefix)
2216 options->a_prefix = a;
2217 if (!options->b_prefix)
2218 options->b_prefix = b;
2221 struct userdiff_driver *get_textconv(struct diff_filespec *one)
2223 if (!DIFF_FILE_VALID(one))
2224 return NULL;
2226 diff_filespec_load_driver(one);
2227 return userdiff_get_textconv(one->driver);
2230 static void builtin_diff(const char *name_a,
2231 const char *name_b,
2232 struct diff_filespec *one,
2233 struct diff_filespec *two,
2234 const char *xfrm_msg,
2235 int must_show_header,
2236 struct diff_options *o,
2237 int complete_rewrite)
2239 mmfile_t mf1, mf2;
2240 const char *lbl[2];
2241 char *a_one, *b_two;
2242 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
2243 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2244 const char *a_prefix, *b_prefix;
2245 struct userdiff_driver *textconv_one = NULL;
2246 struct userdiff_driver *textconv_two = NULL;
2247 struct strbuf header = STRBUF_INIT;
2248 const char *line_prefix = diff_line_prefix(o);
2250 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
2251 (!one->mode || S_ISGITLINK(one->mode)) &&
2252 (!two->mode || S_ISGITLINK(two->mode))) {
2253 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2254 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2255 show_submodule_summary(o->file, one->path ? one->path : two->path,
2256 line_prefix,
2257 one->sha1, two->sha1, two->dirty_submodule,
2258 meta, del, add, reset);
2259 return;
2262 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2263 textconv_one = get_textconv(one);
2264 textconv_two = get_textconv(two);
2267 diff_set_mnemonic_prefix(o, "a/", "b/");
2268 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2269 a_prefix = o->b_prefix;
2270 b_prefix = o->a_prefix;
2271 } else {
2272 a_prefix = o->a_prefix;
2273 b_prefix = o->b_prefix;
2276 /* Never use a non-valid filename anywhere if at all possible */
2277 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2278 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2280 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2281 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
2282 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2283 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
2284 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
2285 if (lbl[0][0] == '/') {
2286 /* /dev/null */
2287 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
2288 if (xfrm_msg)
2289 strbuf_addstr(&header, xfrm_msg);
2290 must_show_header = 1;
2292 else if (lbl[1][0] == '/') {
2293 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
2294 if (xfrm_msg)
2295 strbuf_addstr(&header, xfrm_msg);
2296 must_show_header = 1;
2298 else {
2299 if (one->mode != two->mode) {
2300 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
2301 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
2302 must_show_header = 1;
2304 if (xfrm_msg)
2305 strbuf_addstr(&header, xfrm_msg);
2308 * we do not run diff between different kind
2309 * of objects.
2311 if ((one->mode ^ two->mode) & S_IFMT)
2312 goto free_ab_and_return;
2313 if (complete_rewrite &&
2314 (textconv_one || !diff_filespec_is_binary(one)) &&
2315 (textconv_two || !diff_filespec_is_binary(two))) {
2316 fprintf(o->file, "%s", header.buf);
2317 strbuf_reset(&header);
2318 emit_rewrite_diff(name_a, name_b, one, two,
2319 textconv_one, textconv_two, o);
2320 o->found_changes = 1;
2321 goto free_ab_and_return;
2325 if (o->irreversible_delete && lbl[1][0] == '/') {
2326 fprintf(o->file, "%s", header.buf);
2327 strbuf_reset(&header);
2328 goto free_ab_and_return;
2329 } else if (!DIFF_OPT_TST(o, TEXT) &&
2330 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2331 (!textconv_two && diff_filespec_is_binary(two)) )) {
2332 if (!one->data && !two->data &&
2333 S_ISREG(one->mode) && S_ISREG(two->mode) &&
2334 !DIFF_OPT_TST(o, BINARY)) {
2335 if (!hashcmp(one->sha1, two->sha1)) {
2336 if (must_show_header)
2337 fprintf(o->file, "%s", header.buf);
2338 goto free_ab_and_return;
2340 fprintf(o->file, "%s", header.buf);
2341 fprintf(o->file, "%sBinary files %s and %s differ\n",
2342 line_prefix, lbl[0], lbl[1]);
2343 goto free_ab_and_return;
2345 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2346 die("unable to read files to diff");
2347 /* Quite common confusing case */
2348 if (mf1.size == mf2.size &&
2349 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2350 if (must_show_header)
2351 fprintf(o->file, "%s", header.buf);
2352 goto free_ab_and_return;
2354 fprintf(o->file, "%s", header.buf);
2355 strbuf_reset(&header);
2356 if (DIFF_OPT_TST(o, BINARY))
2357 emit_binary_diff(o->file, &mf1, &mf2, line_prefix);
2358 else
2359 fprintf(o->file, "%sBinary files %s and %s differ\n",
2360 line_prefix, lbl[0], lbl[1]);
2361 o->found_changes = 1;
2362 } else {
2363 /* Crazy xdl interfaces.. */
2364 const char *diffopts = getenv("GIT_DIFF_OPTS");
2365 const char *v;
2366 xpparam_t xpp;
2367 xdemitconf_t xecfg;
2368 struct emit_callback ecbdata;
2369 const struct userdiff_funcname *pe;
2371 if (must_show_header) {
2372 fprintf(o->file, "%s", header.buf);
2373 strbuf_reset(&header);
2376 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2377 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
2379 pe = diff_funcname_pattern(one);
2380 if (!pe)
2381 pe = diff_funcname_pattern(two);
2383 memset(&xpp, 0, sizeof(xpp));
2384 memset(&xecfg, 0, sizeof(xecfg));
2385 memset(&ecbdata, 0, sizeof(ecbdata));
2386 ecbdata.label_path = lbl;
2387 ecbdata.color_diff = want_color(o->use_color);
2388 ecbdata.found_changesp = &o->found_changes;
2389 ecbdata.ws_rule = whitespace_rule(name_b);
2390 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
2391 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2392 ecbdata.opt = o;
2393 ecbdata.header = header.len ? &header : NULL;
2394 xpp.flags = o->xdl_opts;
2395 xecfg.ctxlen = o->context;
2396 xecfg.interhunkctxlen = o->interhunkcontext;
2397 xecfg.flags = XDL_EMIT_FUNCNAMES;
2398 if (DIFF_OPT_TST(o, FUNCCONTEXT))
2399 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
2400 if (pe)
2401 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
2402 if (!diffopts)
2404 else if (skip_prefix(diffopts, "--unified=", &v))
2405 xecfg.ctxlen = strtoul(v, NULL, 10);
2406 else if (skip_prefix(diffopts, "-u", &v))
2407 xecfg.ctxlen = strtoul(v, NULL, 10);
2408 if (o->word_diff)
2409 init_diff_words_data(&ecbdata, o, one, two);
2410 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2411 &xpp, &xecfg);
2412 if (o->word_diff)
2413 free_diff_words_data(&ecbdata);
2414 if (textconv_one)
2415 free(mf1.ptr);
2416 if (textconv_two)
2417 free(mf2.ptr);
2418 xdiff_clear_find_func(&xecfg);
2421 free_ab_and_return:
2422 strbuf_release(&header);
2423 diff_free_filespec_data(one);
2424 diff_free_filespec_data(two);
2425 free(a_one);
2426 free(b_two);
2427 return;
2430 static void builtin_diffstat(const char *name_a, const char *name_b,
2431 struct diff_filespec *one,
2432 struct diff_filespec *two,
2433 struct diffstat_t *diffstat,
2434 struct diff_options *o,
2435 struct diff_filepair *p)
2437 mmfile_t mf1, mf2;
2438 struct diffstat_file *data;
2439 int same_contents;
2440 int complete_rewrite = 0;
2442 if (!DIFF_PAIR_UNMERGED(p)) {
2443 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2444 complete_rewrite = 1;
2447 data = diffstat_add(diffstat, name_a, name_b);
2448 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
2450 if (!one || !two) {
2451 data->is_unmerged = 1;
2452 return;
2455 same_contents = !hashcmp(one->sha1, two->sha1);
2457 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2458 data->is_binary = 1;
2459 if (same_contents) {
2460 data->added = 0;
2461 data->deleted = 0;
2462 } else {
2463 data->added = diff_filespec_size(two);
2464 data->deleted = diff_filespec_size(one);
2468 else if (complete_rewrite) {
2469 diff_populate_filespec(one, 0);
2470 diff_populate_filespec(two, 0);
2471 data->deleted = count_lines(one->data, one->size);
2472 data->added = count_lines(two->data, two->size);
2475 else if (!same_contents) {
2476 /* Crazy xdl interfaces.. */
2477 xpparam_t xpp;
2478 xdemitconf_t xecfg;
2480 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2481 die("unable to read files to diff");
2483 memset(&xpp, 0, sizeof(xpp));
2484 memset(&xecfg, 0, sizeof(xecfg));
2485 xpp.flags = o->xdl_opts;
2486 xecfg.ctxlen = o->context;
2487 xecfg.interhunkctxlen = o->interhunkcontext;
2488 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2489 &xpp, &xecfg);
2492 diff_free_filespec_data(one);
2493 diff_free_filespec_data(two);
2496 static void builtin_checkdiff(const char *name_a, const char *name_b,
2497 const char *attr_path,
2498 struct diff_filespec *one,
2499 struct diff_filespec *two,
2500 struct diff_options *o)
2502 mmfile_t mf1, mf2;
2503 struct checkdiff_t data;
2505 if (!two)
2506 return;
2508 memset(&data, 0, sizeof(data));
2509 data.filename = name_b ? name_b : name_a;
2510 data.lineno = 0;
2511 data.o = o;
2512 data.ws_rule = whitespace_rule(attr_path);
2513 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2515 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2516 die("unable to read files to diff");
2519 * All the other codepaths check both sides, but not checking
2520 * the "old" side here is deliberate. We are checking the newly
2521 * introduced changes, and as long as the "new" side is text, we
2522 * can and should check what it introduces.
2524 if (diff_filespec_is_binary(two))
2525 goto free_and_return;
2526 else {
2527 /* Crazy xdl interfaces.. */
2528 xpparam_t xpp;
2529 xdemitconf_t xecfg;
2531 memset(&xpp, 0, sizeof(xpp));
2532 memset(&xecfg, 0, sizeof(xecfg));
2533 xecfg.ctxlen = 1; /* at least one context line */
2534 xpp.flags = 0;
2535 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2536 &xpp, &xecfg);
2538 if (data.ws_rule & WS_BLANK_AT_EOF) {
2539 struct emit_callback ecbdata;
2540 int blank_at_eof;
2542 ecbdata.ws_rule = data.ws_rule;
2543 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2544 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
2546 if (blank_at_eof) {
2547 static char *err;
2548 if (!err)
2549 err = whitespace_error_string(WS_BLANK_AT_EOF);
2550 fprintf(o->file, "%s:%d: %s.\n",
2551 data.filename, blank_at_eof, err);
2552 data.status = 1; /* report errors */
2556 free_and_return:
2557 diff_free_filespec_data(one);
2558 diff_free_filespec_data(two);
2559 if (data.status)
2560 DIFF_OPT_SET(o, CHECK_FAILED);
2563 struct diff_filespec *alloc_filespec(const char *path)
2565 int namelen = strlen(path);
2566 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
2568 memset(spec, 0, sizeof(*spec));
2569 spec->path = (char *)(spec + 1);
2570 memcpy(spec->path, path, namelen+1);
2571 spec->count = 1;
2572 spec->is_binary = -1;
2573 return spec;
2576 void free_filespec(struct diff_filespec *spec)
2578 if (!--spec->count) {
2579 diff_free_filespec_data(spec);
2580 free(spec);
2584 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
2585 int sha1_valid, unsigned short mode)
2587 if (mode) {
2588 spec->mode = canon_mode(mode);
2589 hashcpy(spec->sha1, sha1);
2590 spec->sha1_valid = sha1_valid;
2595 * Given a name and sha1 pair, if the index tells us the file in
2596 * the work tree has that object contents, return true, so that
2597 * prepare_temp_file() does not have to inflate and extract.
2599 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2601 const struct cache_entry *ce;
2602 struct stat st;
2603 int pos, len;
2606 * We do not read the cache ourselves here, because the
2607 * benchmark with my previous version that always reads cache
2608 * shows that it makes things worse for diff-tree comparing
2609 * two linux-2.6 kernel trees in an already checked out work
2610 * tree. This is because most diff-tree comparisons deal with
2611 * only a small number of files, while reading the cache is
2612 * expensive for a large project, and its cost outweighs the
2613 * savings we get by not inflating the object to a temporary
2614 * file. Practically, this code only helps when we are used
2615 * by diff-cache --cached, which does read the cache before
2616 * calling us.
2618 if (!active_cache)
2619 return 0;
2621 /* We want to avoid the working directory if our caller
2622 * doesn't need the data in a normal file, this system
2623 * is rather slow with its stat/open/mmap/close syscalls,
2624 * and the object is contained in a pack file. The pack
2625 * is probably already open and will be faster to obtain
2626 * the data through than the working directory. Loose
2627 * objects however would tend to be slower as they need
2628 * to be individually opened and inflated.
2630 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2631 return 0;
2633 len = strlen(name);
2634 pos = cache_name_pos(name, len);
2635 if (pos < 0)
2636 return 0;
2637 ce = active_cache[pos];
2640 * This is not the sha1 we are looking for, or
2641 * unreusable because it is not a regular file.
2643 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
2644 return 0;
2647 * If ce is marked as "assume unchanged", there is no
2648 * guarantee that work tree matches what we are looking for.
2650 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2651 return 0;
2654 * If ce matches the file in the work tree, we can reuse it.
2656 if (ce_uptodate(ce) ||
2657 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2658 return 1;
2660 return 0;
2663 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2665 int len;
2666 char *data = xmalloc(100), *dirty = "";
2668 /* Are we looking at the work tree? */
2669 if (s->dirty_submodule)
2670 dirty = "-dirty";
2672 len = snprintf(data, 100,
2673 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2674 s->data = data;
2675 s->size = len;
2676 s->should_free = 1;
2677 if (size_only) {
2678 s->data = NULL;
2679 free(data);
2681 return 0;
2685 * While doing rename detection and pickaxe operation, we may need to
2686 * grab the data for the blob (or file) for our own in-core comparison.
2687 * diff_filespec has data and size fields for this purpose.
2689 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
2691 int size_only = flags & CHECK_SIZE_ONLY;
2692 int err = 0;
2694 * demote FAIL to WARN to allow inspecting the situation
2695 * instead of refusing.
2697 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
2698 ? SAFE_CRLF_WARN
2699 : safe_crlf);
2701 if (!DIFF_FILE_VALID(s))
2702 die("internal error: asking to populate invalid file.");
2703 if (S_ISDIR(s->mode))
2704 return -1;
2706 if (s->data)
2707 return 0;
2709 if (size_only && 0 < s->size)
2710 return 0;
2712 if (S_ISGITLINK(s->mode))
2713 return diff_populate_gitlink(s, size_only);
2715 if (!s->sha1_valid ||
2716 reuse_worktree_file(s->path, s->sha1, 0)) {
2717 struct strbuf buf = STRBUF_INIT;
2718 struct stat st;
2719 int fd;
2721 if (lstat(s->path, &st) < 0) {
2722 if (errno == ENOENT) {
2723 err_empty:
2724 err = -1;
2725 empty:
2726 s->data = (char *)"";
2727 s->size = 0;
2728 return err;
2731 s->size = xsize_t(st.st_size);
2732 if (!s->size)
2733 goto empty;
2734 if (S_ISLNK(st.st_mode)) {
2735 struct strbuf sb = STRBUF_INIT;
2737 if (strbuf_readlink(&sb, s->path, s->size))
2738 goto err_empty;
2739 s->size = sb.len;
2740 s->data = strbuf_detach(&sb, NULL);
2741 s->should_free = 1;
2742 return 0;
2744 if (size_only)
2745 return 0;
2746 if ((flags & CHECK_BINARY) &&
2747 s->size > big_file_threshold && s->is_binary == -1) {
2748 s->is_binary = 1;
2749 return 0;
2751 fd = open(s->path, O_RDONLY);
2752 if (fd < 0)
2753 goto err_empty;
2754 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2755 close(fd);
2756 s->should_munmap = 1;
2759 * Convert from working tree format to canonical git format
2761 if (convert_to_git(s->path, s->data, s->size, &buf, crlf_warn)) {
2762 size_t size = 0;
2763 munmap(s->data, s->size);
2764 s->should_munmap = 0;
2765 s->data = strbuf_detach(&buf, &size);
2766 s->size = size;
2767 s->should_free = 1;
2770 else {
2771 enum object_type type;
2772 if (size_only || (flags & CHECK_BINARY)) {
2773 type = sha1_object_info(s->sha1, &s->size);
2774 if (type < 0)
2775 die("unable to read %s", sha1_to_hex(s->sha1));
2776 if (size_only)
2777 return 0;
2778 if (s->size > big_file_threshold && s->is_binary == -1) {
2779 s->is_binary = 1;
2780 return 0;
2783 s->data = read_sha1_file(s->sha1, &type, &s->size);
2784 if (!s->data)
2785 die("unable to read %s", sha1_to_hex(s->sha1));
2786 s->should_free = 1;
2788 return 0;
2791 void diff_free_filespec_blob(struct diff_filespec *s)
2793 if (s->should_free)
2794 free(s->data);
2795 else if (s->should_munmap)
2796 munmap(s->data, s->size);
2798 if (s->should_free || s->should_munmap) {
2799 s->should_free = s->should_munmap = 0;
2800 s->data = NULL;
2804 void diff_free_filespec_data(struct diff_filespec *s)
2806 diff_free_filespec_blob(s);
2807 free(s->cnt_data);
2808 s->cnt_data = NULL;
2811 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2812 void *blob,
2813 unsigned long size,
2814 const unsigned char *sha1,
2815 int mode)
2817 int fd;
2818 struct strbuf buf = STRBUF_INIT;
2819 struct strbuf template = STRBUF_INIT;
2820 char *path_dup = xstrdup(path);
2821 const char *base = basename(path_dup);
2823 /* Generate "XXXXXX_basename.ext" */
2824 strbuf_addstr(&template, "XXXXXX_");
2825 strbuf_addstr(&template, base);
2827 fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
2828 if (fd < 0)
2829 die_errno("unable to create temp-file");
2830 if (convert_to_working_tree(path,
2831 (const char *)blob, (size_t)size, &buf)) {
2832 blob = buf.buf;
2833 size = buf.len;
2835 if (write_in_full(fd, blob, size) != size)
2836 die_errno("unable to write temp-file");
2837 close_tempfile(&temp->tempfile);
2838 temp->name = get_tempfile_path(&temp->tempfile);
2839 strcpy(temp->hex, sha1_to_hex(sha1));
2840 temp->hex[40] = 0;
2841 sprintf(temp->mode, "%06o", mode);
2842 strbuf_release(&buf);
2843 strbuf_release(&template);
2844 free(path_dup);
2847 static struct diff_tempfile *prepare_temp_file(const char *name,
2848 struct diff_filespec *one)
2850 struct diff_tempfile *temp = claim_diff_tempfile();
2852 if (!DIFF_FILE_VALID(one)) {
2853 not_a_valid_file:
2854 /* A '-' entry produces this for file-2, and
2855 * a '+' entry produces this for file-1.
2857 temp->name = "/dev/null";
2858 strcpy(temp->hex, ".");
2859 strcpy(temp->mode, ".");
2860 return temp;
2863 if (!S_ISGITLINK(one->mode) &&
2864 (!one->sha1_valid ||
2865 reuse_worktree_file(name, one->sha1, 1))) {
2866 struct stat st;
2867 if (lstat(name, &st) < 0) {
2868 if (errno == ENOENT)
2869 goto not_a_valid_file;
2870 die_errno("stat(%s)", name);
2872 if (S_ISLNK(st.st_mode)) {
2873 struct strbuf sb = STRBUF_INIT;
2874 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2875 die_errno("readlink(%s)", name);
2876 prep_temp_blob(name, temp, sb.buf, sb.len,
2877 (one->sha1_valid ?
2878 one->sha1 : null_sha1),
2879 (one->sha1_valid ?
2880 one->mode : S_IFLNK));
2881 strbuf_release(&sb);
2883 else {
2884 /* we can borrow from the file in the work tree */
2885 temp->name = name;
2886 if (!one->sha1_valid)
2887 strcpy(temp->hex, sha1_to_hex(null_sha1));
2888 else
2889 strcpy(temp->hex, sha1_to_hex(one->sha1));
2890 /* Even though we may sometimes borrow the
2891 * contents from the work tree, we always want
2892 * one->mode. mode is trustworthy even when
2893 * !(one->sha1_valid), as long as
2894 * DIFF_FILE_VALID(one).
2896 sprintf(temp->mode, "%06o", one->mode);
2898 return temp;
2900 else {
2901 if (diff_populate_filespec(one, 0))
2902 die("cannot read data blob for %s", one->path);
2903 prep_temp_blob(name, temp, one->data, one->size,
2904 one->sha1, one->mode);
2906 return temp;
2909 static void add_external_diff_name(struct argv_array *argv,
2910 const char *name,
2911 struct diff_filespec *df)
2913 struct diff_tempfile *temp = prepare_temp_file(name, df);
2914 argv_array_push(argv, temp->name);
2915 argv_array_push(argv, temp->hex);
2916 argv_array_push(argv, temp->mode);
2919 /* An external diff command takes:
2921 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2922 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2925 static void run_external_diff(const char *pgm,
2926 const char *name,
2927 const char *other,
2928 struct diff_filespec *one,
2929 struct diff_filespec *two,
2930 const char *xfrm_msg,
2931 int complete_rewrite,
2932 struct diff_options *o)
2934 struct argv_array argv = ARGV_ARRAY_INIT;
2935 struct argv_array env = ARGV_ARRAY_INIT;
2936 struct diff_queue_struct *q = &diff_queued_diff;
2938 argv_array_push(&argv, pgm);
2939 argv_array_push(&argv, name);
2941 if (one && two) {
2942 add_external_diff_name(&argv, name, one);
2943 if (!other)
2944 add_external_diff_name(&argv, name, two);
2945 else {
2946 add_external_diff_name(&argv, other, two);
2947 argv_array_push(&argv, other);
2948 argv_array_push(&argv, xfrm_msg);
2952 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
2953 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
2955 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
2956 die(_("external diff died, stopping at %s"), name);
2958 remove_tempfile();
2959 argv_array_clear(&argv);
2960 argv_array_clear(&env);
2963 static int similarity_index(struct diff_filepair *p)
2965 return p->score * 100 / MAX_SCORE;
2968 static void fill_metainfo(struct strbuf *msg,
2969 const char *name,
2970 const char *other,
2971 struct diff_filespec *one,
2972 struct diff_filespec *two,
2973 struct diff_options *o,
2974 struct diff_filepair *p,
2975 int *must_show_header,
2976 int use_color)
2978 const char *set = diff_get_color(use_color, DIFF_METAINFO);
2979 const char *reset = diff_get_color(use_color, DIFF_RESET);
2980 const char *line_prefix = diff_line_prefix(o);
2982 *must_show_header = 1;
2983 strbuf_init(msg, PATH_MAX * 2 + 300);
2984 switch (p->status) {
2985 case DIFF_STATUS_COPIED:
2986 strbuf_addf(msg, "%s%ssimilarity index %d%%",
2987 line_prefix, set, similarity_index(p));
2988 strbuf_addf(msg, "%s\n%s%scopy from ",
2989 reset, line_prefix, set);
2990 quote_c_style(name, msg, NULL, 0);
2991 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
2992 quote_c_style(other, msg, NULL, 0);
2993 strbuf_addf(msg, "%s\n", reset);
2994 break;
2995 case DIFF_STATUS_RENAMED:
2996 strbuf_addf(msg, "%s%ssimilarity index %d%%",
2997 line_prefix, set, similarity_index(p));
2998 strbuf_addf(msg, "%s\n%s%srename from ",
2999 reset, line_prefix, set);
3000 quote_c_style(name, msg, NULL, 0);
3001 strbuf_addf(msg, "%s\n%s%srename to ",
3002 reset, line_prefix, set);
3003 quote_c_style(other, msg, NULL, 0);
3004 strbuf_addf(msg, "%s\n", reset);
3005 break;
3006 case DIFF_STATUS_MODIFIED:
3007 if (p->score) {
3008 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3009 line_prefix,
3010 set, similarity_index(p), reset);
3011 break;
3013 /* fallthru */
3014 default:
3015 *must_show_header = 0;
3017 if (one && two && hashcmp(one->sha1, two->sha1)) {
3018 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3020 if (DIFF_OPT_TST(o, BINARY)) {
3021 mmfile_t mf;
3022 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3023 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3024 abbrev = 40;
3026 strbuf_addf(msg, "%s%sindex %s..", line_prefix, set,
3027 find_unique_abbrev(one->sha1, abbrev));
3028 strbuf_addstr(msg, find_unique_abbrev(two->sha1, abbrev));
3029 if (one->mode == two->mode)
3030 strbuf_addf(msg, " %06o", one->mode);
3031 strbuf_addf(msg, "%s\n", reset);
3035 static void run_diff_cmd(const char *pgm,
3036 const char *name,
3037 const char *other,
3038 const char *attr_path,
3039 struct diff_filespec *one,
3040 struct diff_filespec *two,
3041 struct strbuf *msg,
3042 struct diff_options *o,
3043 struct diff_filepair *p)
3045 const char *xfrm_msg = NULL;
3046 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3047 int must_show_header = 0;
3050 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3051 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3052 if (drv && drv->external)
3053 pgm = drv->external;
3056 if (msg) {
3058 * don't use colors when the header is intended for an
3059 * external diff driver
3061 fill_metainfo(msg, name, other, one, two, o, p,
3062 &must_show_header,
3063 want_color(o->use_color) && !pgm);
3064 xfrm_msg = msg->len ? msg->buf : NULL;
3067 if (pgm) {
3068 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3069 complete_rewrite, o);
3070 return;
3072 if (one && two)
3073 builtin_diff(name, other ? other : name,
3074 one, two, xfrm_msg, must_show_header,
3075 o, complete_rewrite);
3076 else
3077 fprintf(o->file, "* Unmerged path %s\n", name);
3080 static void diff_fill_sha1_info(struct diff_filespec *one)
3082 if (DIFF_FILE_VALID(one)) {
3083 if (!one->sha1_valid) {
3084 struct stat st;
3085 if (one->is_stdin) {
3086 hashcpy(one->sha1, null_sha1);
3087 return;
3089 if (lstat(one->path, &st) < 0)
3090 die_errno("stat '%s'", one->path);
3091 if (index_path(one->sha1, one->path, &st, 0))
3092 die("cannot hash %s", one->path);
3095 else
3096 hashclr(one->sha1);
3099 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3101 /* Strip the prefix but do not molest /dev/null and absolute paths */
3102 if (*namep && **namep != '/') {
3103 *namep += prefix_length;
3104 if (**namep == '/')
3105 ++*namep;
3107 if (*otherp && **otherp != '/') {
3108 *otherp += prefix_length;
3109 if (**otherp == '/')
3110 ++*otherp;
3114 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3116 const char *pgm = external_diff();
3117 struct strbuf msg;
3118 struct diff_filespec *one = p->one;
3119 struct diff_filespec *two = p->two;
3120 const char *name;
3121 const char *other;
3122 const char *attr_path;
3124 name = p->one->path;
3125 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3126 attr_path = name;
3127 if (o->prefix_length)
3128 strip_prefix(o->prefix_length, &name, &other);
3130 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3131 pgm = NULL;
3133 if (DIFF_PAIR_UNMERGED(p)) {
3134 run_diff_cmd(pgm, name, NULL, attr_path,
3135 NULL, NULL, NULL, o, p);
3136 return;
3139 diff_fill_sha1_info(one);
3140 diff_fill_sha1_info(two);
3142 if (!pgm &&
3143 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3144 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3146 * a filepair that changes between file and symlink
3147 * needs to be split into deletion and creation.
3149 struct diff_filespec *null = alloc_filespec(two->path);
3150 run_diff_cmd(NULL, name, other, attr_path,
3151 one, null, &msg, o, p);
3152 free(null);
3153 strbuf_release(&msg);
3155 null = alloc_filespec(one->path);
3156 run_diff_cmd(NULL, name, other, attr_path,
3157 null, two, &msg, o, p);
3158 free(null);
3160 else
3161 run_diff_cmd(pgm, name, other, attr_path,
3162 one, two, &msg, o, p);
3164 strbuf_release(&msg);
3167 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3168 struct diffstat_t *diffstat)
3170 const char *name;
3171 const char *other;
3173 if (DIFF_PAIR_UNMERGED(p)) {
3174 /* unmerged */
3175 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
3176 return;
3179 name = p->one->path;
3180 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3182 if (o->prefix_length)
3183 strip_prefix(o->prefix_length, &name, &other);
3185 diff_fill_sha1_info(p->one);
3186 diff_fill_sha1_info(p->two);
3188 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
3191 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3193 const char *name;
3194 const char *other;
3195 const char *attr_path;
3197 if (DIFF_PAIR_UNMERGED(p)) {
3198 /* unmerged */
3199 return;
3202 name = p->one->path;
3203 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3204 attr_path = other ? other : name;
3206 if (o->prefix_length)
3207 strip_prefix(o->prefix_length, &name, &other);
3209 diff_fill_sha1_info(p->one);
3210 diff_fill_sha1_info(p->two);
3212 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
3215 void diff_setup(struct diff_options *options)
3217 memcpy(options, &default_diff_options, sizeof(*options));
3219 options->file = stdout;
3221 options->line_termination = '\n';
3222 options->break_opt = -1;
3223 options->rename_limit = -1;
3224 options->dirstat_permille = diff_dirstat_permille_default;
3225 options->context = diff_context_default;
3226 DIFF_OPT_SET(options, RENAME_EMPTY);
3228 /* pathchange left =NULL by default */
3229 options->change = diff_change;
3230 options->add_remove = diff_addremove;
3231 options->use_color = diff_use_color_default;
3232 options->detect_rename = diff_detect_rename_default;
3233 options->xdl_opts |= diff_algorithm;
3235 options->orderfile = diff_order_file_cfg;
3237 if (diff_no_prefix) {
3238 options->a_prefix = options->b_prefix = "";
3239 } else if (!diff_mnemonic_prefix) {
3240 options->a_prefix = "a/";
3241 options->b_prefix = "b/";
3245 void diff_setup_done(struct diff_options *options)
3247 int count = 0;
3249 if (options->set_default)
3250 options->set_default(options);
3252 if (options->output_format & DIFF_FORMAT_NAME)
3253 count++;
3254 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3255 count++;
3256 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3257 count++;
3258 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3259 count++;
3260 if (count > 1)
3261 die("--name-only, --name-status, --check and -s are mutually exclusive");
3264 * Most of the time we can say "there are changes"
3265 * only by checking if there are changed paths, but
3266 * --ignore-whitespace* options force us to look
3267 * inside contents.
3270 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3271 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3272 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3273 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3274 else
3275 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3277 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3278 options->detect_rename = DIFF_DETECT_COPY;
3280 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3281 options->prefix = NULL;
3282 if (options->prefix)
3283 options->prefix_length = strlen(options->prefix);
3284 else
3285 options->prefix_length = 0;
3287 if (options->output_format & (DIFF_FORMAT_NAME |
3288 DIFF_FORMAT_NAME_STATUS |
3289 DIFF_FORMAT_CHECKDIFF |
3290 DIFF_FORMAT_NO_OUTPUT))
3291 options->output_format &= ~(DIFF_FORMAT_RAW |
3292 DIFF_FORMAT_NUMSTAT |
3293 DIFF_FORMAT_DIFFSTAT |
3294 DIFF_FORMAT_SHORTSTAT |
3295 DIFF_FORMAT_DIRSTAT |
3296 DIFF_FORMAT_SUMMARY |
3297 DIFF_FORMAT_PATCH);
3300 * These cases always need recursive; we do not drop caller-supplied
3301 * recursive bits for other formats here.
3303 if (options->output_format & (DIFF_FORMAT_PATCH |
3304 DIFF_FORMAT_NUMSTAT |
3305 DIFF_FORMAT_DIFFSTAT |
3306 DIFF_FORMAT_SHORTSTAT |
3307 DIFF_FORMAT_DIRSTAT |
3308 DIFF_FORMAT_SUMMARY |
3309 DIFF_FORMAT_CHECKDIFF))
3310 DIFF_OPT_SET(options, RECURSIVE);
3312 * Also pickaxe would not work very well if you do not say recursive
3314 if (options->pickaxe)
3315 DIFF_OPT_SET(options, RECURSIVE);
3317 * When patches are generated, submodules diffed against the work tree
3318 * must be checked for dirtiness too so it can be shown in the output
3320 if (options->output_format & DIFF_FORMAT_PATCH)
3321 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
3323 if (options->detect_rename && options->rename_limit < 0)
3324 options->rename_limit = diff_rename_limit_default;
3325 if (options->setup & DIFF_SETUP_USE_CACHE) {
3326 if (!active_cache)
3327 /* read-cache does not die even when it fails
3328 * so it is safe for us to do this here. Also
3329 * it does not smudge active_cache or active_nr
3330 * when it fails, so we do not have to worry about
3331 * cleaning it up ourselves either.
3333 read_cache();
3335 if (options->abbrev <= 0 || 40 < options->abbrev)
3336 options->abbrev = 40; /* full */
3339 * It does not make sense to show the first hit we happened
3340 * to have found. It does not make sense not to return with
3341 * exit code in such a case either.
3343 if (DIFF_OPT_TST(options, QUICK)) {
3344 options->output_format = DIFF_FORMAT_NO_OUTPUT;
3345 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3348 options->diff_path_counter = 0;
3350 if (DIFF_OPT_TST(options, FOLLOW_RENAMES) && options->pathspec.nr != 1)
3351 die(_("--follow requires exactly one pathspec"));
3354 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
3356 char c, *eq;
3357 int len;
3359 if (*arg != '-')
3360 return 0;
3361 c = *++arg;
3362 if (!c)
3363 return 0;
3364 if (c == arg_short) {
3365 c = *++arg;
3366 if (!c)
3367 return 1;
3368 if (val && isdigit(c)) {
3369 char *end;
3370 int n = strtoul(arg, &end, 10);
3371 if (*end)
3372 return 0;
3373 *val = n;
3374 return 1;
3376 return 0;
3378 if (c != '-')
3379 return 0;
3380 arg++;
3381 eq = strchrnul(arg, '=');
3382 len = eq - arg;
3383 if (!len || strncmp(arg, arg_long, len))
3384 return 0;
3385 if (*eq) {
3386 int n;
3387 char *end;
3388 if (!isdigit(*++eq))
3389 return 0;
3390 n = strtoul(eq, &end, 10);
3391 if (*end)
3392 return 0;
3393 *val = n;
3395 return 1;
3398 static int diff_scoreopt_parse(const char *opt);
3400 static inline int short_opt(char opt, const char **argv,
3401 const char **optarg)
3403 const char *arg = argv[0];
3404 if (arg[0] != '-' || arg[1] != opt)
3405 return 0;
3406 if (arg[2] != '\0') {
3407 *optarg = arg + 2;
3408 return 1;
3410 if (!argv[1])
3411 die("Option '%c' requires a value", opt);
3412 *optarg = argv[1];
3413 return 2;
3416 int parse_long_opt(const char *opt, const char **argv,
3417 const char **optarg)
3419 const char *arg = argv[0];
3420 if (!skip_prefix(arg, "--", &arg))
3421 return 0;
3422 if (!skip_prefix(arg, opt, &arg))
3423 return 0;
3424 if (*arg == '=') { /* stuck form: --option=value */
3425 *optarg = arg + 1;
3426 return 1;
3428 if (*arg != '\0')
3429 return 0;
3430 /* separate form: --option value */
3431 if (!argv[1])
3432 die("Option '--%s' requires a value", opt);
3433 *optarg = argv[1];
3434 return 2;
3437 static int stat_opt(struct diff_options *options, const char **av)
3439 const char *arg = av[0];
3440 char *end;
3441 int width = options->stat_width;
3442 int name_width = options->stat_name_width;
3443 int graph_width = options->stat_graph_width;
3444 int count = options->stat_count;
3445 int argcount = 1;
3447 if (!skip_prefix(arg, "--stat", &arg))
3448 die("BUG: stat option does not begin with --stat: %s", arg);
3449 end = (char *)arg;
3451 switch (*arg) {
3452 case '-':
3453 if (skip_prefix(arg, "-width", &arg)) {
3454 if (*arg == '=')
3455 width = strtoul(arg + 1, &end, 10);
3456 else if (!*arg && !av[1])
3457 die("Option '--stat-width' requires a value");
3458 else if (!*arg) {
3459 width = strtoul(av[1], &end, 10);
3460 argcount = 2;
3462 } else if (skip_prefix(arg, "-name-width", &arg)) {
3463 if (*arg == '=')
3464 name_width = strtoul(arg + 1, &end, 10);
3465 else if (!*arg && !av[1])
3466 die("Option '--stat-name-width' requires a value");
3467 else if (!*arg) {
3468 name_width = strtoul(av[1], &end, 10);
3469 argcount = 2;
3471 } else if (skip_prefix(arg, "-graph-width", &arg)) {
3472 if (*arg == '=')
3473 graph_width = strtoul(arg + 1, &end, 10);
3474 else if (!*arg && !av[1])
3475 die("Option '--stat-graph-width' requires a value");
3476 else if (!*arg) {
3477 graph_width = strtoul(av[1], &end, 10);
3478 argcount = 2;
3480 } else if (skip_prefix(arg, "-count", &arg)) {
3481 if (*arg == '=')
3482 count = strtoul(arg + 1, &end, 10);
3483 else if (!*arg && !av[1])
3484 die("Option '--stat-count' requires a value");
3485 else if (!*arg) {
3486 count = strtoul(av[1], &end, 10);
3487 argcount = 2;
3490 break;
3491 case '=':
3492 width = strtoul(arg+1, &end, 10);
3493 if (*end == ',')
3494 name_width = strtoul(end+1, &end, 10);
3495 if (*end == ',')
3496 count = strtoul(end+1, &end, 10);
3499 /* Important! This checks all the error cases! */
3500 if (*end)
3501 return 0;
3502 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3503 options->stat_name_width = name_width;
3504 options->stat_graph_width = graph_width;
3505 options->stat_width = width;
3506 options->stat_count = count;
3507 return argcount;
3510 static int parse_dirstat_opt(struct diff_options *options, const char *params)
3512 struct strbuf errmsg = STRBUF_INIT;
3513 if (parse_dirstat_params(options, params, &errmsg))
3514 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
3515 errmsg.buf);
3516 strbuf_release(&errmsg);
3518 * The caller knows a dirstat-related option is given from the command
3519 * line; allow it to say "return this_function();"
3521 options->output_format |= DIFF_FORMAT_DIRSTAT;
3522 return 1;
3525 static int parse_submodule_opt(struct diff_options *options, const char *value)
3527 if (parse_submodule_params(options, value))
3528 die(_("Failed to parse --submodule option parameter: '%s'"),
3529 value);
3530 return 1;
3533 static const char diff_status_letters[] = {
3534 DIFF_STATUS_ADDED,
3535 DIFF_STATUS_COPIED,
3536 DIFF_STATUS_DELETED,
3537 DIFF_STATUS_MODIFIED,
3538 DIFF_STATUS_RENAMED,
3539 DIFF_STATUS_TYPE_CHANGED,
3540 DIFF_STATUS_UNKNOWN,
3541 DIFF_STATUS_UNMERGED,
3542 DIFF_STATUS_FILTER_AON,
3543 DIFF_STATUS_FILTER_BROKEN,
3544 '\0',
3547 static unsigned int filter_bit['Z' + 1];
3549 static void prepare_filter_bits(void)
3551 int i;
3553 if (!filter_bit[DIFF_STATUS_ADDED]) {
3554 for (i = 0; diff_status_letters[i]; i++)
3555 filter_bit[(int) diff_status_letters[i]] = (1 << i);
3559 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
3561 return opt->filter & filter_bit[(int) status];
3564 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
3566 int i, optch;
3568 prepare_filter_bits();
3571 * If there is a negation e.g. 'd' in the input, and we haven't
3572 * initialized the filter field with another --diff-filter, start
3573 * from full set of bits, except for AON.
3575 if (!opt->filter) {
3576 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
3577 if (optch < 'a' || 'z' < optch)
3578 continue;
3579 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
3580 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
3581 break;
3585 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
3586 unsigned int bit;
3587 int negate;
3589 if ('a' <= optch && optch <= 'z') {
3590 negate = 1;
3591 optch = toupper(optch);
3592 } else {
3593 negate = 0;
3596 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
3597 if (!bit)
3598 return optarg[i];
3599 if (negate)
3600 opt->filter &= ~bit;
3601 else
3602 opt->filter |= bit;
3604 return 0;
3607 static void enable_patch_output(int *fmt) {
3608 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
3609 *fmt |= DIFF_FORMAT_PATCH;
3612 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
3614 const char *arg = av[0];
3615 const char *optarg;
3616 int argcount;
3618 /* Output format options */
3619 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
3620 || opt_arg(arg, 'U', "unified", &options->context))
3621 enable_patch_output(&options->output_format);
3622 else if (!strcmp(arg, "--raw"))
3623 options->output_format |= DIFF_FORMAT_RAW;
3624 else if (!strcmp(arg, "--patch-with-raw")) {
3625 enable_patch_output(&options->output_format);
3626 options->output_format |= DIFF_FORMAT_RAW;
3627 } else if (!strcmp(arg, "--numstat"))
3628 options->output_format |= DIFF_FORMAT_NUMSTAT;
3629 else if (!strcmp(arg, "--shortstat"))
3630 options->output_format |= DIFF_FORMAT_SHORTSTAT;
3631 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
3632 return parse_dirstat_opt(options, "");
3633 else if (skip_prefix(arg, "-X", &arg))
3634 return parse_dirstat_opt(options, arg);
3635 else if (skip_prefix(arg, "--dirstat=", &arg))
3636 return parse_dirstat_opt(options, arg);
3637 else if (!strcmp(arg, "--cumulative"))
3638 return parse_dirstat_opt(options, "cumulative");
3639 else if (!strcmp(arg, "--dirstat-by-file"))
3640 return parse_dirstat_opt(options, "files");
3641 else if (skip_prefix(arg, "--dirstat-by-file=", &arg)) {
3642 parse_dirstat_opt(options, "files");
3643 return parse_dirstat_opt(options, arg);
3645 else if (!strcmp(arg, "--check"))
3646 options->output_format |= DIFF_FORMAT_CHECKDIFF;
3647 else if (!strcmp(arg, "--summary"))
3648 options->output_format |= DIFF_FORMAT_SUMMARY;
3649 else if (!strcmp(arg, "--patch-with-stat")) {
3650 enable_patch_output(&options->output_format);
3651 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3652 } else if (!strcmp(arg, "--name-only"))
3653 options->output_format |= DIFF_FORMAT_NAME;
3654 else if (!strcmp(arg, "--name-status"))
3655 options->output_format |= DIFF_FORMAT_NAME_STATUS;
3656 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
3657 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
3658 else if (starts_with(arg, "--stat"))
3659 /* --stat, --stat-width, --stat-name-width, or --stat-count */
3660 return stat_opt(options, av);
3662 /* renames options */
3663 else if (starts_with(arg, "-B") || starts_with(arg, "--break-rewrites=") ||
3664 !strcmp(arg, "--break-rewrites")) {
3665 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
3666 return error("invalid argument to -B: %s", arg+2);
3668 else if (starts_with(arg, "-M") || starts_with(arg, "--find-renames=") ||
3669 !strcmp(arg, "--find-renames")) {
3670 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3671 return error("invalid argument to -M: %s", arg+2);
3672 options->detect_rename = DIFF_DETECT_RENAME;
3674 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
3675 options->irreversible_delete = 1;
3677 else if (starts_with(arg, "-C") || starts_with(arg, "--find-copies=") ||
3678 !strcmp(arg, "--find-copies")) {
3679 if (options->detect_rename == DIFF_DETECT_COPY)
3680 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3681 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3682 return error("invalid argument to -C: %s", arg+2);
3683 options->detect_rename = DIFF_DETECT_COPY;
3685 else if (!strcmp(arg, "--no-renames"))
3686 options->detect_rename = 0;
3687 else if (!strcmp(arg, "--rename-empty"))
3688 DIFF_OPT_SET(options, RENAME_EMPTY);
3689 else if (!strcmp(arg, "--no-rename-empty"))
3690 DIFF_OPT_CLR(options, RENAME_EMPTY);
3691 else if (!strcmp(arg, "--relative"))
3692 DIFF_OPT_SET(options, RELATIVE_NAME);
3693 else if (skip_prefix(arg, "--relative=", &arg)) {
3694 DIFF_OPT_SET(options, RELATIVE_NAME);
3695 options->prefix = arg;
3698 /* xdiff options */
3699 else if (!strcmp(arg, "--minimal"))
3700 DIFF_XDL_SET(options, NEED_MINIMAL);
3701 else if (!strcmp(arg, "--no-minimal"))
3702 DIFF_XDL_CLR(options, NEED_MINIMAL);
3703 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
3704 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
3705 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
3706 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
3707 else if (!strcmp(arg, "--ignore-space-at-eol"))
3708 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
3709 else if (!strcmp(arg, "--ignore-blank-lines"))
3710 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
3711 else if (!strcmp(arg, "--patience"))
3712 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
3713 else if (!strcmp(arg, "--histogram"))
3714 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
3715 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
3716 long value = parse_algorithm_value(optarg);
3717 if (value < 0)
3718 return error("option diff-algorithm accepts \"myers\", "
3719 "\"minimal\", \"patience\" and \"histogram\"");
3720 /* clear out previous settings */
3721 DIFF_XDL_CLR(options, NEED_MINIMAL);
3722 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3723 options->xdl_opts |= value;
3724 return argcount;
3727 /* flags options */
3728 else if (!strcmp(arg, "--binary")) {
3729 enable_patch_output(&options->output_format);
3730 DIFF_OPT_SET(options, BINARY);
3732 else if (!strcmp(arg, "--full-index"))
3733 DIFF_OPT_SET(options, FULL_INDEX);
3734 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
3735 DIFF_OPT_SET(options, TEXT);
3736 else if (!strcmp(arg, "-R"))
3737 DIFF_OPT_SET(options, REVERSE_DIFF);
3738 else if (!strcmp(arg, "--find-copies-harder"))
3739 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3740 else if (!strcmp(arg, "--follow"))
3741 DIFF_OPT_SET(options, FOLLOW_RENAMES);
3742 else if (!strcmp(arg, "--no-follow"))
3743 DIFF_OPT_CLR(options, FOLLOW_RENAMES);
3744 else if (!strcmp(arg, "--color"))
3745 options->use_color = 1;
3746 else if (skip_prefix(arg, "--color=", &arg)) {
3747 int value = git_config_colorbool(NULL, arg);
3748 if (value < 0)
3749 return error("option `color' expects \"always\", \"auto\", or \"never\"");
3750 options->use_color = value;
3752 else if (!strcmp(arg, "--no-color"))
3753 options->use_color = 0;
3754 else if (!strcmp(arg, "--color-words")) {
3755 options->use_color = 1;
3756 options->word_diff = DIFF_WORDS_COLOR;
3758 else if (skip_prefix(arg, "--color-words=", &arg)) {
3759 options->use_color = 1;
3760 options->word_diff = DIFF_WORDS_COLOR;
3761 options->word_regex = arg;
3763 else if (!strcmp(arg, "--word-diff")) {
3764 if (options->word_diff == DIFF_WORDS_NONE)
3765 options->word_diff = DIFF_WORDS_PLAIN;
3767 else if (skip_prefix(arg, "--word-diff=", &arg)) {
3768 if (!strcmp(arg, "plain"))
3769 options->word_diff = DIFF_WORDS_PLAIN;
3770 else if (!strcmp(arg, "color")) {
3771 options->use_color = 1;
3772 options->word_diff = DIFF_WORDS_COLOR;
3774 else if (!strcmp(arg, "porcelain"))
3775 options->word_diff = DIFF_WORDS_PORCELAIN;
3776 else if (!strcmp(arg, "none"))
3777 options->word_diff = DIFF_WORDS_NONE;
3778 else
3779 die("bad --word-diff argument: %s", arg);
3781 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
3782 if (options->word_diff == DIFF_WORDS_NONE)
3783 options->word_diff = DIFF_WORDS_PLAIN;
3784 options->word_regex = optarg;
3785 return argcount;
3787 else if (!strcmp(arg, "--exit-code"))
3788 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3789 else if (!strcmp(arg, "--quiet"))
3790 DIFF_OPT_SET(options, QUICK);
3791 else if (!strcmp(arg, "--ext-diff"))
3792 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
3793 else if (!strcmp(arg, "--no-ext-diff"))
3794 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
3795 else if (!strcmp(arg, "--textconv"))
3796 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3797 else if (!strcmp(arg, "--no-textconv"))
3798 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
3799 else if (!strcmp(arg, "--ignore-submodules")) {
3800 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3801 handle_ignore_submodules_arg(options, "all");
3802 } else if (skip_prefix(arg, "--ignore-submodules=", &arg)) {
3803 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3804 handle_ignore_submodules_arg(options, arg);
3805 } else if (!strcmp(arg, "--submodule"))
3806 DIFF_OPT_SET(options, SUBMODULE_LOG);
3807 else if (skip_prefix(arg, "--submodule=", &arg))
3808 return parse_submodule_opt(options, arg);
3810 /* misc options */
3811 else if (!strcmp(arg, "-z"))
3812 options->line_termination = 0;
3813 else if ((argcount = short_opt('l', av, &optarg))) {
3814 options->rename_limit = strtoul(optarg, NULL, 10);
3815 return argcount;
3817 else if ((argcount = short_opt('S', av, &optarg))) {
3818 options->pickaxe = optarg;
3819 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
3820 return argcount;
3821 } else if ((argcount = short_opt('G', av, &optarg))) {
3822 options->pickaxe = optarg;
3823 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
3824 return argcount;
3826 else if (!strcmp(arg, "--pickaxe-all"))
3827 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
3828 else if (!strcmp(arg, "--pickaxe-regex"))
3829 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
3830 else if ((argcount = short_opt('O', av, &optarg))) {
3831 options->orderfile = optarg;
3832 return argcount;
3834 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
3835 int offending = parse_diff_filter_opt(optarg, options);
3836 if (offending)
3837 die("unknown change class '%c' in --diff-filter=%s",
3838 offending, optarg);
3839 return argcount;
3841 else if (!strcmp(arg, "--abbrev"))
3842 options->abbrev = DEFAULT_ABBREV;
3843 else if (skip_prefix(arg, "--abbrev=", &arg)) {
3844 options->abbrev = strtoul(arg, NULL, 10);
3845 if (options->abbrev < MINIMUM_ABBREV)
3846 options->abbrev = MINIMUM_ABBREV;
3847 else if (40 < options->abbrev)
3848 options->abbrev = 40;
3850 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
3851 options->a_prefix = optarg;
3852 return argcount;
3854 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
3855 options->b_prefix = optarg;
3856 return argcount;
3858 else if (!strcmp(arg, "--no-prefix"))
3859 options->a_prefix = options->b_prefix = "";
3860 else if (opt_arg(arg, '\0', "inter-hunk-context",
3861 &options->interhunkcontext))
3863 else if (!strcmp(arg, "-W"))
3864 DIFF_OPT_SET(options, FUNCCONTEXT);
3865 else if (!strcmp(arg, "--function-context"))
3866 DIFF_OPT_SET(options, FUNCCONTEXT);
3867 else if (!strcmp(arg, "--no-function-context"))
3868 DIFF_OPT_CLR(options, FUNCCONTEXT);
3869 else if ((argcount = parse_long_opt("output", av, &optarg))) {
3870 options->file = fopen(optarg, "w");
3871 if (!options->file)
3872 die_errno("Could not open '%s'", optarg);
3873 options->close_file = 1;
3874 return argcount;
3875 } else
3876 return 0;
3877 return 1;
3880 int parse_rename_score(const char **cp_p)
3882 unsigned long num, scale;
3883 int ch, dot;
3884 const char *cp = *cp_p;
3886 num = 0;
3887 scale = 1;
3888 dot = 0;
3889 for (;;) {
3890 ch = *cp;
3891 if ( !dot && ch == '.' ) {
3892 scale = 1;
3893 dot = 1;
3894 } else if ( ch == '%' ) {
3895 scale = dot ? scale*100 : 100;
3896 cp++; /* % is always at the end */
3897 break;
3898 } else if ( ch >= '0' && ch <= '9' ) {
3899 if ( scale < 100000 ) {
3900 scale *= 10;
3901 num = (num*10) + (ch-'0');
3903 } else {
3904 break;
3906 cp++;
3908 *cp_p = cp;
3910 /* user says num divided by scale and we say internally that
3911 * is MAX_SCORE * num / scale.
3913 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3916 static int diff_scoreopt_parse(const char *opt)
3918 int opt1, opt2, cmd;
3920 if (*opt++ != '-')
3921 return -1;
3922 cmd = *opt++;
3923 if (cmd == '-') {
3924 /* convert the long-form arguments into short-form versions */
3925 if (skip_prefix(opt, "break-rewrites", &opt)) {
3926 if (*opt == 0 || *opt++ == '=')
3927 cmd = 'B';
3928 } else if (skip_prefix(opt, "find-copies", &opt)) {
3929 if (*opt == 0 || *opt++ == '=')
3930 cmd = 'C';
3931 } else if (skip_prefix(opt, "find-renames", &opt)) {
3932 if (*opt == 0 || *opt++ == '=')
3933 cmd = 'M';
3936 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3937 return -1; /* that is not a -M, -C, or -B option */
3939 opt1 = parse_rename_score(&opt);
3940 if (cmd != 'B')
3941 opt2 = 0;
3942 else {
3943 if (*opt == 0)
3944 opt2 = 0;
3945 else if (*opt != '/')
3946 return -1; /* we expect -B80/99 or -B80 */
3947 else {
3948 opt++;
3949 opt2 = parse_rename_score(&opt);
3952 if (*opt != 0)
3953 return -1;
3954 return opt1 | (opt2 << 16);
3957 struct diff_queue_struct diff_queued_diff;
3959 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3961 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
3962 queue->queue[queue->nr++] = dp;
3965 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3966 struct diff_filespec *one,
3967 struct diff_filespec *two)
3969 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3970 dp->one = one;
3971 dp->two = two;
3972 if (queue)
3973 diff_q(queue, dp);
3974 return dp;
3977 void diff_free_filepair(struct diff_filepair *p)
3979 free_filespec(p->one);
3980 free_filespec(p->two);
3981 free(p);
3984 /* This is different from find_unique_abbrev() in that
3985 * it stuffs the result with dots for alignment.
3987 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3989 int abblen;
3990 const char *abbrev;
3991 if (len == 40)
3992 return sha1_to_hex(sha1);
3994 abbrev = find_unique_abbrev(sha1, len);
3995 abblen = strlen(abbrev);
3996 if (abblen < 37) {
3997 static char hex[41];
3998 if (len < abblen && abblen <= len + 2)
3999 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
4000 else
4001 sprintf(hex, "%s...", abbrev);
4002 return hex;
4004 return sha1_to_hex(sha1);
4007 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4009 int line_termination = opt->line_termination;
4010 int inter_name_termination = line_termination ? '\t' : '\0';
4012 fprintf(opt->file, "%s", diff_line_prefix(opt));
4013 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
4014 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
4015 diff_unique_abbrev(p->one->sha1, opt->abbrev));
4016 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
4018 if (p->score) {
4019 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
4020 inter_name_termination);
4021 } else {
4022 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
4025 if (p->status == DIFF_STATUS_COPIED ||
4026 p->status == DIFF_STATUS_RENAMED) {
4027 const char *name_a, *name_b;
4028 name_a = p->one->path;
4029 name_b = p->two->path;
4030 strip_prefix(opt->prefix_length, &name_a, &name_b);
4031 write_name_quoted(name_a, opt->file, inter_name_termination);
4032 write_name_quoted(name_b, opt->file, line_termination);
4033 } else {
4034 const char *name_a, *name_b;
4035 name_a = p->one->mode ? p->one->path : p->two->path;
4036 name_b = NULL;
4037 strip_prefix(opt->prefix_length, &name_a, &name_b);
4038 write_name_quoted(name_a, opt->file, line_termination);
4042 int diff_unmodified_pair(struct diff_filepair *p)
4044 /* This function is written stricter than necessary to support
4045 * the currently implemented transformers, but the idea is to
4046 * let transformers to produce diff_filepairs any way they want,
4047 * and filter and clean them up here before producing the output.
4049 struct diff_filespec *one = p->one, *two = p->two;
4051 if (DIFF_PAIR_UNMERGED(p))
4052 return 0; /* unmerged is interesting */
4054 /* deletion, addition, mode or type change
4055 * and rename are all interesting.
4057 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
4058 DIFF_PAIR_MODE_CHANGED(p) ||
4059 strcmp(one->path, two->path))
4060 return 0;
4062 /* both are valid and point at the same path. that is, we are
4063 * dealing with a change.
4065 if (one->sha1_valid && two->sha1_valid &&
4066 !hashcmp(one->sha1, two->sha1) &&
4067 !one->dirty_submodule && !two->dirty_submodule)
4068 return 1; /* no change */
4069 if (!one->sha1_valid && !two->sha1_valid)
4070 return 1; /* both look at the same file on the filesystem. */
4071 return 0;
4074 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
4076 if (diff_unmodified_pair(p))
4077 return;
4079 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4080 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4081 return; /* no tree diffs in patch format */
4083 run_diff(p, o);
4086 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
4087 struct diffstat_t *diffstat)
4089 if (diff_unmodified_pair(p))
4090 return;
4092 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4093 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4094 return; /* no useful stat for tree diffs */
4096 run_diffstat(p, o, diffstat);
4099 static void diff_flush_checkdiff(struct diff_filepair *p,
4100 struct diff_options *o)
4102 if (diff_unmodified_pair(p))
4103 return;
4105 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4106 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4107 return; /* nothing to check in tree diffs */
4109 run_checkdiff(p, o);
4112 int diff_queue_is_empty(void)
4114 struct diff_queue_struct *q = &diff_queued_diff;
4115 int i;
4116 for (i = 0; i < q->nr; i++)
4117 if (!diff_unmodified_pair(q->queue[i]))
4118 return 0;
4119 return 1;
4122 #if DIFF_DEBUG
4123 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
4125 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
4126 x, one ? one : "",
4127 s->path,
4128 DIFF_FILE_VALID(s) ? "valid" : "invalid",
4129 s->mode,
4130 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
4131 fprintf(stderr, "queue[%d] %s size %lu\n",
4132 x, one ? one : "",
4133 s->size);
4136 void diff_debug_filepair(const struct diff_filepair *p, int i)
4138 diff_debug_filespec(p->one, i, "one");
4139 diff_debug_filespec(p->two, i, "two");
4140 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
4141 p->score, p->status ? p->status : '?',
4142 p->one->rename_used, p->broken_pair);
4145 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
4147 int i;
4148 if (msg)
4149 fprintf(stderr, "%s\n", msg);
4150 fprintf(stderr, "q->nr = %d\n", q->nr);
4151 for (i = 0; i < q->nr; i++) {
4152 struct diff_filepair *p = q->queue[i];
4153 diff_debug_filepair(p, i);
4156 #endif
4158 static void diff_resolve_rename_copy(void)
4160 int i;
4161 struct diff_filepair *p;
4162 struct diff_queue_struct *q = &diff_queued_diff;
4164 diff_debug_queue("resolve-rename-copy", q);
4166 for (i = 0; i < q->nr; i++) {
4167 p = q->queue[i];
4168 p->status = 0; /* undecided */
4169 if (DIFF_PAIR_UNMERGED(p))
4170 p->status = DIFF_STATUS_UNMERGED;
4171 else if (!DIFF_FILE_VALID(p->one))
4172 p->status = DIFF_STATUS_ADDED;
4173 else if (!DIFF_FILE_VALID(p->two))
4174 p->status = DIFF_STATUS_DELETED;
4175 else if (DIFF_PAIR_TYPE_CHANGED(p))
4176 p->status = DIFF_STATUS_TYPE_CHANGED;
4178 /* from this point on, we are dealing with a pair
4179 * whose both sides are valid and of the same type, i.e.
4180 * either in-place edit or rename/copy edit.
4182 else if (DIFF_PAIR_RENAME(p)) {
4184 * A rename might have re-connected a broken
4185 * pair up, causing the pathnames to be the
4186 * same again. If so, that's not a rename at
4187 * all, just a modification..
4189 * Otherwise, see if this source was used for
4190 * multiple renames, in which case we decrement
4191 * the count, and call it a copy.
4193 if (!strcmp(p->one->path, p->two->path))
4194 p->status = DIFF_STATUS_MODIFIED;
4195 else if (--p->one->rename_used > 0)
4196 p->status = DIFF_STATUS_COPIED;
4197 else
4198 p->status = DIFF_STATUS_RENAMED;
4200 else if (hashcmp(p->one->sha1, p->two->sha1) ||
4201 p->one->mode != p->two->mode ||
4202 p->one->dirty_submodule ||
4203 p->two->dirty_submodule ||
4204 is_null_sha1(p->one->sha1))
4205 p->status = DIFF_STATUS_MODIFIED;
4206 else {
4207 /* This is a "no-change" entry and should not
4208 * happen anymore, but prepare for broken callers.
4210 error("feeding unmodified %s to diffcore",
4211 p->one->path);
4212 p->status = DIFF_STATUS_UNKNOWN;
4215 diff_debug_queue("resolve-rename-copy done", q);
4218 static int check_pair_status(struct diff_filepair *p)
4220 switch (p->status) {
4221 case DIFF_STATUS_UNKNOWN:
4222 return 0;
4223 case 0:
4224 die("internal error in diff-resolve-rename-copy");
4225 default:
4226 return 1;
4230 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4232 int fmt = opt->output_format;
4234 if (fmt & DIFF_FORMAT_CHECKDIFF)
4235 diff_flush_checkdiff(p, opt);
4236 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4237 diff_flush_raw(p, opt);
4238 else if (fmt & DIFF_FORMAT_NAME) {
4239 const char *name_a, *name_b;
4240 name_a = p->two->path;
4241 name_b = NULL;
4242 strip_prefix(opt->prefix_length, &name_a, &name_b);
4243 write_name_quoted(name_a, opt->file, opt->line_termination);
4247 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4249 if (fs->mode)
4250 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4251 else
4252 fprintf(file, " %s ", newdelete);
4253 write_name_quoted(fs->path, file, '\n');
4257 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
4258 const char *line_prefix)
4260 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
4261 fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
4262 p->two->mode, show_name ? ' ' : '\n');
4263 if (show_name) {
4264 write_name_quoted(p->two->path, file, '\n');
4269 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
4270 const char *line_prefix)
4272 char *names = pprint_rename(p->one->path, p->two->path);
4274 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
4275 free(names);
4276 show_mode_change(file, p, 0, line_prefix);
4279 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4281 FILE *file = opt->file;
4282 const char *line_prefix = diff_line_prefix(opt);
4284 switch(p->status) {
4285 case DIFF_STATUS_DELETED:
4286 fputs(line_prefix, file);
4287 show_file_mode_name(file, "delete", p->one);
4288 break;
4289 case DIFF_STATUS_ADDED:
4290 fputs(line_prefix, file);
4291 show_file_mode_name(file, "create", p->two);
4292 break;
4293 case DIFF_STATUS_COPIED:
4294 fputs(line_prefix, file);
4295 show_rename_copy(file, "copy", p, line_prefix);
4296 break;
4297 case DIFF_STATUS_RENAMED:
4298 fputs(line_prefix, file);
4299 show_rename_copy(file, "rename", p, line_prefix);
4300 break;
4301 default:
4302 if (p->score) {
4303 fprintf(file, "%s rewrite ", line_prefix);
4304 write_name_quoted(p->two->path, file, ' ');
4305 fprintf(file, "(%d%%)\n", similarity_index(p));
4307 show_mode_change(file, p, !p->score, line_prefix);
4308 break;
4312 struct patch_id_t {
4313 git_SHA_CTX *ctx;
4314 int patchlen;
4317 static int remove_space(char *line, int len)
4319 int i;
4320 char *dst = line;
4321 unsigned char c;
4323 for (i = 0; i < len; i++)
4324 if (!isspace((c = line[i])))
4325 *dst++ = c;
4327 return dst - line;
4330 static void patch_id_consume(void *priv, char *line, unsigned long len)
4332 struct patch_id_t *data = priv;
4333 int new_len;
4335 /* Ignore line numbers when computing the SHA1 of the patch */
4336 if (starts_with(line, "@@ -"))
4337 return;
4339 new_len = remove_space(line, len);
4341 git_SHA1_Update(data->ctx, line, new_len);
4342 data->patchlen += new_len;
4345 /* returns 0 upon success, and writes result into sha1 */
4346 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
4348 struct diff_queue_struct *q = &diff_queued_diff;
4349 int i;
4350 git_SHA_CTX ctx;
4351 struct patch_id_t data;
4352 char buffer[PATH_MAX * 4 + 20];
4354 git_SHA1_Init(&ctx);
4355 memset(&data, 0, sizeof(struct patch_id_t));
4356 data.ctx = &ctx;
4358 for (i = 0; i < q->nr; i++) {
4359 xpparam_t xpp;
4360 xdemitconf_t xecfg;
4361 mmfile_t mf1, mf2;
4362 struct diff_filepair *p = q->queue[i];
4363 int len1, len2;
4365 memset(&xpp, 0, sizeof(xpp));
4366 memset(&xecfg, 0, sizeof(xecfg));
4367 if (p->status == 0)
4368 return error("internal diff status error");
4369 if (p->status == DIFF_STATUS_UNKNOWN)
4370 continue;
4371 if (diff_unmodified_pair(p))
4372 continue;
4373 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4374 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4375 continue;
4376 if (DIFF_PAIR_UNMERGED(p))
4377 continue;
4379 diff_fill_sha1_info(p->one);
4380 diff_fill_sha1_info(p->two);
4381 if (fill_mmfile(&mf1, p->one) < 0 ||
4382 fill_mmfile(&mf2, p->two) < 0)
4383 return error("unable to read files to diff");
4385 len1 = remove_space(p->one->path, strlen(p->one->path));
4386 len2 = remove_space(p->two->path, strlen(p->two->path));
4387 if (p->one->mode == 0)
4388 len1 = snprintf(buffer, sizeof(buffer),
4389 "diff--gita/%.*sb/%.*s"
4390 "newfilemode%06o"
4391 "---/dev/null"
4392 "+++b/%.*s",
4393 len1, p->one->path,
4394 len2, p->two->path,
4395 p->two->mode,
4396 len2, p->two->path);
4397 else if (p->two->mode == 0)
4398 len1 = snprintf(buffer, sizeof(buffer),
4399 "diff--gita/%.*sb/%.*s"
4400 "deletedfilemode%06o"
4401 "---a/%.*s"
4402 "+++/dev/null",
4403 len1, p->one->path,
4404 len2, p->two->path,
4405 p->one->mode,
4406 len1, p->one->path);
4407 else
4408 len1 = snprintf(buffer, sizeof(buffer),
4409 "diff--gita/%.*sb/%.*s"
4410 "---a/%.*s"
4411 "+++b/%.*s",
4412 len1, p->one->path,
4413 len2, p->two->path,
4414 len1, p->one->path,
4415 len2, p->two->path);
4416 git_SHA1_Update(&ctx, buffer, len1);
4418 if (diff_filespec_is_binary(p->one) ||
4419 diff_filespec_is_binary(p->two)) {
4420 git_SHA1_Update(&ctx, sha1_to_hex(p->one->sha1), 40);
4421 git_SHA1_Update(&ctx, sha1_to_hex(p->two->sha1), 40);
4422 continue;
4425 xpp.flags = 0;
4426 xecfg.ctxlen = 3;
4427 xecfg.flags = 0;
4428 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
4429 &xpp, &xecfg);
4432 git_SHA1_Final(sha1, &ctx);
4433 return 0;
4436 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
4438 struct diff_queue_struct *q = &diff_queued_diff;
4439 int i;
4440 int result = diff_get_patch_id(options, sha1);
4442 for (i = 0; i < q->nr; i++)
4443 diff_free_filepair(q->queue[i]);
4445 free(q->queue);
4446 DIFF_QUEUE_CLEAR(q);
4448 return result;
4451 static int is_summary_empty(const struct diff_queue_struct *q)
4453 int i;
4455 for (i = 0; i < q->nr; i++) {
4456 const struct diff_filepair *p = q->queue[i];
4458 switch (p->status) {
4459 case DIFF_STATUS_DELETED:
4460 case DIFF_STATUS_ADDED:
4461 case DIFF_STATUS_COPIED:
4462 case DIFF_STATUS_RENAMED:
4463 return 0;
4464 default:
4465 if (p->score)
4466 return 0;
4467 if (p->one->mode && p->two->mode &&
4468 p->one->mode != p->two->mode)
4469 return 0;
4470 break;
4473 return 1;
4476 static const char rename_limit_warning[] =
4477 "inexact rename detection was skipped due to too many files.";
4479 static const char degrade_cc_to_c_warning[] =
4480 "only found copies from modified paths due to too many files.";
4482 static const char rename_limit_advice[] =
4483 "you may want to set your %s variable to at least "
4484 "%d and retry the command.";
4486 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4488 if (degraded_cc)
4489 warning(degrade_cc_to_c_warning);
4490 else if (needed)
4491 warning(rename_limit_warning);
4492 else
4493 return;
4494 if (0 < needed && needed < 32767)
4495 warning(rename_limit_advice, varname, needed);
4498 void diff_flush(struct diff_options *options)
4500 struct diff_queue_struct *q = &diff_queued_diff;
4501 int i, output_format = options->output_format;
4502 int separator = 0;
4503 int dirstat_by_line = 0;
4506 * Order: raw, stat, summary, patch
4507 * or: name/name-status/checkdiff (other bits clear)
4509 if (!q->nr)
4510 goto free_queue;
4512 if (output_format & (DIFF_FORMAT_RAW |
4513 DIFF_FORMAT_NAME |
4514 DIFF_FORMAT_NAME_STATUS |
4515 DIFF_FORMAT_CHECKDIFF)) {
4516 for (i = 0; i < q->nr; i++) {
4517 struct diff_filepair *p = q->queue[i];
4518 if (check_pair_status(p))
4519 flush_one_pair(p, options);
4521 separator++;
4524 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
4525 dirstat_by_line = 1;
4527 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
4528 dirstat_by_line) {
4529 struct diffstat_t diffstat;
4531 memset(&diffstat, 0, sizeof(struct diffstat_t));
4532 for (i = 0; i < q->nr; i++) {
4533 struct diff_filepair *p = q->queue[i];
4534 if (check_pair_status(p))
4535 diff_flush_stat(p, options, &diffstat);
4537 if (output_format & DIFF_FORMAT_NUMSTAT)
4538 show_numstat(&diffstat, options);
4539 if (output_format & DIFF_FORMAT_DIFFSTAT)
4540 show_stats(&diffstat, options);
4541 if (output_format & DIFF_FORMAT_SHORTSTAT)
4542 show_shortstats(&diffstat, options);
4543 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
4544 show_dirstat_by_line(&diffstat, options);
4545 free_diffstat_info(&diffstat);
4546 separator++;
4548 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
4549 show_dirstat(options);
4551 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
4552 for (i = 0; i < q->nr; i++) {
4553 diff_summary(options, q->queue[i]);
4555 separator++;
4558 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
4559 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
4560 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4562 * run diff_flush_patch for the exit status. setting
4563 * options->file to /dev/null should be safe, because we
4564 * aren't supposed to produce any output anyway.
4566 if (options->close_file)
4567 fclose(options->file);
4568 options->file = fopen("/dev/null", "w");
4569 if (!options->file)
4570 die_errno("Could not open /dev/null");
4571 options->close_file = 1;
4572 for (i = 0; i < q->nr; i++) {
4573 struct diff_filepair *p = q->queue[i];
4574 if (check_pair_status(p))
4575 diff_flush_patch(p, options);
4576 if (options->found_changes)
4577 break;
4581 if (output_format & DIFF_FORMAT_PATCH) {
4582 if (separator) {
4583 fprintf(options->file, "%s%c",
4584 diff_line_prefix(options),
4585 options->line_termination);
4586 if (options->stat_sep) {
4587 /* attach patch instead of inline */
4588 fputs(options->stat_sep, options->file);
4592 for (i = 0; i < q->nr; i++) {
4593 struct diff_filepair *p = q->queue[i];
4594 if (check_pair_status(p))
4595 diff_flush_patch(p, options);
4599 if (output_format & DIFF_FORMAT_CALLBACK)
4600 options->format_callback(q, options, options->format_callback_data);
4602 for (i = 0; i < q->nr; i++)
4603 diff_free_filepair(q->queue[i]);
4604 free_queue:
4605 free(q->queue);
4606 DIFF_QUEUE_CLEAR(q);
4607 if (options->close_file)
4608 fclose(options->file);
4611 * Report the content-level differences with HAS_CHANGES;
4612 * diff_addremove/diff_change does not set the bit when
4613 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
4615 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4616 if (options->found_changes)
4617 DIFF_OPT_SET(options, HAS_CHANGES);
4618 else
4619 DIFF_OPT_CLR(options, HAS_CHANGES);
4623 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
4625 return (((p->status == DIFF_STATUS_MODIFIED) &&
4626 ((p->score &&
4627 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
4628 (!p->score &&
4629 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
4630 ((p->status != DIFF_STATUS_MODIFIED) &&
4631 filter_bit_tst(p->status, options)));
4634 static void diffcore_apply_filter(struct diff_options *options)
4636 int i;
4637 struct diff_queue_struct *q = &diff_queued_diff;
4638 struct diff_queue_struct outq;
4640 DIFF_QUEUE_CLEAR(&outq);
4642 if (!options->filter)
4643 return;
4645 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
4646 int found;
4647 for (i = found = 0; !found && i < q->nr; i++) {
4648 if (match_filter(options, q->queue[i]))
4649 found++;
4651 if (found)
4652 return;
4654 /* otherwise we will clear the whole queue
4655 * by copying the empty outq at the end of this
4656 * function, but first clear the current entries
4657 * in the queue.
4659 for (i = 0; i < q->nr; i++)
4660 diff_free_filepair(q->queue[i]);
4662 else {
4663 /* Only the matching ones */
4664 for (i = 0; i < q->nr; i++) {
4665 struct diff_filepair *p = q->queue[i];
4666 if (match_filter(options, p))
4667 diff_q(&outq, p);
4668 else
4669 diff_free_filepair(p);
4672 free(q->queue);
4673 *q = outq;
4676 /* Check whether two filespecs with the same mode and size are identical */
4677 static int diff_filespec_is_identical(struct diff_filespec *one,
4678 struct diff_filespec *two)
4680 if (S_ISGITLINK(one->mode))
4681 return 0;
4682 if (diff_populate_filespec(one, 0))
4683 return 0;
4684 if (diff_populate_filespec(two, 0))
4685 return 0;
4686 return !memcmp(one->data, two->data, one->size);
4689 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
4691 if (p->done_skip_stat_unmatch)
4692 return p->skip_stat_unmatch_result;
4694 p->done_skip_stat_unmatch = 1;
4695 p->skip_stat_unmatch_result = 0;
4697 * 1. Entries that come from stat info dirtiness
4698 * always have both sides (iow, not create/delete),
4699 * one side of the object name is unknown, with
4700 * the same mode and size. Keep the ones that
4701 * do not match these criteria. They have real
4702 * differences.
4704 * 2. At this point, the file is known to be modified,
4705 * with the same mode and size, and the object
4706 * name of one side is unknown. Need to inspect
4707 * the identical contents.
4709 if (!DIFF_FILE_VALID(p->one) || /* (1) */
4710 !DIFF_FILE_VALID(p->two) ||
4711 (p->one->sha1_valid && p->two->sha1_valid) ||
4712 (p->one->mode != p->two->mode) ||
4713 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
4714 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
4715 (p->one->size != p->two->size) ||
4716 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
4717 p->skip_stat_unmatch_result = 1;
4718 return p->skip_stat_unmatch_result;
4721 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
4723 int i;
4724 struct diff_queue_struct *q = &diff_queued_diff;
4725 struct diff_queue_struct outq;
4726 DIFF_QUEUE_CLEAR(&outq);
4728 for (i = 0; i < q->nr; i++) {
4729 struct diff_filepair *p = q->queue[i];
4731 if (diff_filespec_check_stat_unmatch(p))
4732 diff_q(&outq, p);
4733 else {
4735 * The caller can subtract 1 from skip_stat_unmatch
4736 * to determine how many paths were dirty only
4737 * due to stat info mismatch.
4739 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
4740 diffopt->skip_stat_unmatch++;
4741 diff_free_filepair(p);
4744 free(q->queue);
4745 *q = outq;
4748 static int diffnamecmp(const void *a_, const void *b_)
4750 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4751 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4752 const char *name_a, *name_b;
4754 name_a = a->one ? a->one->path : a->two->path;
4755 name_b = b->one ? b->one->path : b->two->path;
4756 return strcmp(name_a, name_b);
4759 void diffcore_fix_diff_index(struct diff_options *options)
4761 struct diff_queue_struct *q = &diff_queued_diff;
4762 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
4765 void diffcore_std(struct diff_options *options)
4767 /* NOTE please keep the following in sync with diff_tree_combined() */
4768 if (options->skip_stat_unmatch)
4769 diffcore_skip_stat_unmatch(options);
4770 if (!options->found_follow) {
4771 /* See try_to_follow_renames() in tree-diff.c */
4772 if (options->break_opt != -1)
4773 diffcore_break(options->break_opt);
4774 if (options->detect_rename)
4775 diffcore_rename(options);
4776 if (options->break_opt != -1)
4777 diffcore_merge_broken();
4779 if (options->pickaxe)
4780 diffcore_pickaxe(options);
4781 if (options->orderfile)
4782 diffcore_order(options->orderfile);
4783 if (!options->found_follow)
4784 /* See try_to_follow_renames() in tree-diff.c */
4785 diff_resolve_rename_copy();
4786 diffcore_apply_filter(options);
4788 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4789 DIFF_OPT_SET(options, HAS_CHANGES);
4790 else
4791 DIFF_OPT_CLR(options, HAS_CHANGES);
4793 options->found_follow = 0;
4796 int diff_result_code(struct diff_options *opt, int status)
4798 int result = 0;
4800 diff_warn_rename_limit("diff.renameLimit",
4801 opt->needed_rename_limit,
4802 opt->degraded_cc_to_c);
4803 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4804 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
4805 return status;
4806 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4807 DIFF_OPT_TST(opt, HAS_CHANGES))
4808 result |= 01;
4809 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4810 DIFF_OPT_TST(opt, CHECK_FAILED))
4811 result |= 02;
4812 return result;
4815 int diff_can_quit_early(struct diff_options *opt)
4817 return (DIFF_OPT_TST(opt, QUICK) &&
4818 !opt->filter &&
4819 DIFF_OPT_TST(opt, HAS_CHANGES));
4823 * Shall changes to this submodule be ignored?
4825 * Submodule changes can be configured to be ignored separately for each path,
4826 * but that configuration can be overridden from the command line.
4828 static int is_submodule_ignored(const char *path, struct diff_options *options)
4830 int ignored = 0;
4831 unsigned orig_flags = options->flags;
4832 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
4833 set_diffopt_flags_from_submodule_config(options, path);
4834 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
4835 ignored = 1;
4836 options->flags = orig_flags;
4837 return ignored;
4840 void diff_addremove(struct diff_options *options,
4841 int addremove, unsigned mode,
4842 const unsigned char *sha1,
4843 int sha1_valid,
4844 const char *concatpath, unsigned dirty_submodule)
4846 struct diff_filespec *one, *two;
4848 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
4849 return;
4851 /* This may look odd, but it is a preparation for
4852 * feeding "there are unchanged files which should
4853 * not produce diffs, but when you are doing copy
4854 * detection you would need them, so here they are"
4855 * entries to the diff-core. They will be prefixed
4856 * with something like '=' or '*' (I haven't decided
4857 * which but should not make any difference).
4858 * Feeding the same new and old to diff_change()
4859 * also has the same effect.
4860 * Before the final output happens, they are pruned after
4861 * merged into rename/copy pairs as appropriate.
4863 if (DIFF_OPT_TST(options, REVERSE_DIFF))
4864 addremove = (addremove == '+' ? '-' :
4865 addremove == '-' ? '+' : addremove);
4867 if (options->prefix &&
4868 strncmp(concatpath, options->prefix, options->prefix_length))
4869 return;
4871 one = alloc_filespec(concatpath);
4872 two = alloc_filespec(concatpath);
4874 if (addremove != '+')
4875 fill_filespec(one, sha1, sha1_valid, mode);
4876 if (addremove != '-') {
4877 fill_filespec(two, sha1, sha1_valid, mode);
4878 two->dirty_submodule = dirty_submodule;
4881 diff_queue(&diff_queued_diff, one, two);
4882 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4883 DIFF_OPT_SET(options, HAS_CHANGES);
4886 void diff_change(struct diff_options *options,
4887 unsigned old_mode, unsigned new_mode,
4888 const unsigned char *old_sha1,
4889 const unsigned char *new_sha1,
4890 int old_sha1_valid, int new_sha1_valid,
4891 const char *concatpath,
4892 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
4894 struct diff_filespec *one, *two;
4895 struct diff_filepair *p;
4897 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
4898 is_submodule_ignored(concatpath, options))
4899 return;
4901 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
4902 unsigned tmp;
4903 const unsigned char *tmp_c;
4904 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
4905 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
4906 tmp = old_sha1_valid; old_sha1_valid = new_sha1_valid;
4907 new_sha1_valid = tmp;
4908 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
4909 new_dirty_submodule = tmp;
4912 if (options->prefix &&
4913 strncmp(concatpath, options->prefix, options->prefix_length))
4914 return;
4916 one = alloc_filespec(concatpath);
4917 two = alloc_filespec(concatpath);
4918 fill_filespec(one, old_sha1, old_sha1_valid, old_mode);
4919 fill_filespec(two, new_sha1, new_sha1_valid, new_mode);
4920 one->dirty_submodule = old_dirty_submodule;
4921 two->dirty_submodule = new_dirty_submodule;
4922 p = diff_queue(&diff_queued_diff, one, two);
4924 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4925 return;
4927 if (DIFF_OPT_TST(options, QUICK) && options->skip_stat_unmatch &&
4928 !diff_filespec_check_stat_unmatch(p))
4929 return;
4931 DIFF_OPT_SET(options, HAS_CHANGES);
4934 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
4936 struct diff_filepair *pair;
4937 struct diff_filespec *one, *two;
4939 if (options->prefix &&
4940 strncmp(path, options->prefix, options->prefix_length))
4941 return NULL;
4943 one = alloc_filespec(path);
4944 two = alloc_filespec(path);
4945 pair = diff_queue(&diff_queued_diff, one, two);
4946 pair->is_unmerged = 1;
4947 return pair;
4950 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
4951 size_t *outsize)
4953 struct diff_tempfile *temp;
4954 const char *argv[3];
4955 const char **arg = argv;
4956 struct child_process child = CHILD_PROCESS_INIT;
4957 struct strbuf buf = STRBUF_INIT;
4958 int err = 0;
4960 temp = prepare_temp_file(spec->path, spec);
4961 *arg++ = pgm;
4962 *arg++ = temp->name;
4963 *arg = NULL;
4965 child.use_shell = 1;
4966 child.argv = argv;
4967 child.out = -1;
4968 if (start_command(&child)) {
4969 remove_tempfile();
4970 return NULL;
4973 if (strbuf_read(&buf, child.out, 0) < 0)
4974 err = error("error reading from textconv command '%s'", pgm);
4975 close(child.out);
4977 if (finish_command(&child) || err) {
4978 strbuf_release(&buf);
4979 remove_tempfile();
4980 return NULL;
4982 remove_tempfile();
4984 return strbuf_detach(&buf, outsize);
4987 size_t fill_textconv(struct userdiff_driver *driver,
4988 struct diff_filespec *df,
4989 char **outbuf)
4991 size_t size;
4993 if (!driver || !driver->textconv) {
4994 if (!DIFF_FILE_VALID(df)) {
4995 *outbuf = "";
4996 return 0;
4998 if (diff_populate_filespec(df, 0))
4999 die("unable to read files to diff");
5000 *outbuf = df->data;
5001 return df->size;
5004 if (driver->textconv_cache && df->sha1_valid) {
5005 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
5006 &size);
5007 if (*outbuf)
5008 return size;
5011 *outbuf = run_textconv(driver->textconv, df, &size);
5012 if (!*outbuf)
5013 die("unable to read files to diff");
5015 if (driver->textconv_cache && df->sha1_valid) {
5016 /* ignore errors, as we might be in a readonly repository */
5017 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
5018 size);
5020 * we could save up changes and flush them all at the end,
5021 * but we would need an extra call after all diffing is done.
5022 * Since generating a cache entry is the slow path anyway,
5023 * this extra overhead probably isn't a big deal.
5025 notes_cache_write(driver->textconv_cache);
5028 return size;
5031 void setup_diff_pager(struct diff_options *opt)
5034 * If the user asked for our exit code, then either they want --quiet
5035 * or --exit-code. We should definitely not bother with a pager in the
5036 * former case, as we will generate no output. Since we still properly
5037 * report our exit code even when a pager is run, we _could_ run a
5038 * pager with --exit-code. But since we have not done so historically,
5039 * and because it is easy to find people oneline advising "git diff
5040 * --exit-code" in hooks and other scripts, we do not do so.
5042 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5043 check_pager_config("diff") != 0)
5044 setup_pager();