1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "quote.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "delta.h"
9 #include "xdiff-interface.h"
10 #include "color.h"
11 #include "attr.h"
12 #include "run-command.h"
13 #include "utf8.h"
14 #include "userdiff.h"
15 #include "sigchain.h"
16 #include "submodule.h"
17 #include "ll-merge.h"
19 #ifdef NO_FAST_WORKING_DIRECTORY
20 #define FAST_WORKING_DIRECTORY 0
21 #else
22 #define FAST_WORKING_DIRECTORY 1
23 #endif
25 static int diff_detect_rename_default;
26 static int diff_rename_limit_default = 400;
27 static int diff_suppress_blank_empty;
28 int diff_use_color_default = -1;
29 static const char *diff_word_regex_cfg;
30 static const char *external_diff_cmd_cfg;
31 int diff_auto_refresh_index = 1;
32 static int diff_mnemonic_prefix;
33 static int diff_no_prefix;
34 static int diff_stat_graph_width;
35 static int diff_dirstat_permille_default = 30;
36 static struct diff_options default_diff_options;
38 static char diff_colors[][COLOR_MAXLEN] = {
39 GIT_COLOR_RESET,
40 GIT_COLOR_NORMAL, /* PLAIN */
41 GIT_COLOR_BOLD, /* METAINFO */
42 GIT_COLOR_CYAN, /* FRAGINFO */
43 GIT_COLOR_RED, /* OLD */
44 GIT_COLOR_GREEN, /* NEW */
45 GIT_COLOR_YELLOW, /* COMMIT */
46 GIT_COLOR_BG_RED, /* WHITESPACE */
47 GIT_COLOR_NORMAL, /* FUNCINFO */
48 };
50 static int parse_diff_color_slot(const char *var, int ofs)
51 {
52 if (!strcasecmp(var+ofs, "plain"))
53 return DIFF_PLAIN;
54 if (!strcasecmp(var+ofs, "meta"))
55 return DIFF_METAINFO;
56 if (!strcasecmp(var+ofs, "frag"))
57 return DIFF_FRAGINFO;
58 if (!strcasecmp(var+ofs, "old"))
59 return DIFF_FILE_OLD;
60 if (!strcasecmp(var+ofs, "new"))
61 return DIFF_FILE_NEW;
62 if (!strcasecmp(var+ofs, "commit"))
63 return DIFF_COMMIT;
64 if (!strcasecmp(var+ofs, "whitespace"))
65 return DIFF_WHITESPACE;
66 if (!strcasecmp(var+ofs, "func"))
67 return DIFF_FUNCINFO;
68 return -1;
69 }
71 static int parse_dirstat_params(struct diff_options *options, const char *params,
72 struct strbuf *errmsg)
73 {
74 const char *p = params;
75 int p_len, ret = 0;
77 while (*p) {
78 p_len = strchrnul(p, ',') - p;
79 if (!memcmp(p, "changes", p_len)) {
80 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
81 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
82 } else if (!memcmp(p, "lines", p_len)) {
83 DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
84 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
85 } else if (!memcmp(p, "files", p_len)) {
86 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
87 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
88 } else if (!memcmp(p, "noncumulative", p_len)) {
89 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
90 } else if (!memcmp(p, "cumulative", p_len)) {
91 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
92 } else if (isdigit(*p)) {
93 char *end;
94 int permille = strtoul(p, &end, 10) * 10;
95 if (*end == '.' && isdigit(*++end)) {
96 /* only use first digit */
97 permille += *end - '0';
98 /* .. and ignore any further digits */
99 while (isdigit(*++end))
100 ; /* nothing */
101 }
102 if (end - p == p_len)
103 options->dirstat_permille = permille;
104 else {
105 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%.*s'\n"),
106 p_len, p);
107 ret++;
108 }
109 } else {
110 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%.*s'\n"),
111 p_len, p);
112 ret++;
113 }
115 p += p_len;
117 if (*p)
118 p++; /* more parameters, swallow separator */
119 }
120 return ret;
121 }
123 static int git_config_rename(const char *var, const char *value)
124 {
125 if (!value)
126 return DIFF_DETECT_RENAME;
127 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
128 return DIFF_DETECT_COPY;
129 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
130 }
132 /*
133 * These are to give UI layer defaults.
134 * The core-level commands such as git-diff-files should
135 * never be affected by the setting of diff.renames
136 * the user happens to have in the configuration file.
137 */
138 int git_diff_ui_config(const char *var, const char *value, void *cb)
139 {
140 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
141 diff_use_color_default = git_config_colorbool(var, value);
142 return 0;
143 }
144 if (!strcmp(var, "diff.renames")) {
145 diff_detect_rename_default = git_config_rename(var, value);
146 return 0;
147 }
148 if (!strcmp(var, "diff.autorefreshindex")) {
149 diff_auto_refresh_index = git_config_bool(var, value);
150 return 0;
151 }
152 if (!strcmp(var, "diff.mnemonicprefix")) {
153 diff_mnemonic_prefix = git_config_bool(var, value);
154 return 0;
155 }
156 if (!strcmp(var, "diff.noprefix")) {
157 diff_no_prefix = git_config_bool(var, value);
158 return 0;
159 }
160 if (!strcmp(var, "diff.statgraphwidth")) {
161 diff_stat_graph_width = git_config_int(var, value);
162 return 0;
163 }
164 if (!strcmp(var, "diff.external"))
165 return git_config_string(&external_diff_cmd_cfg, var, value);
166 if (!strcmp(var, "diff.wordregex"))
167 return git_config_string(&diff_word_regex_cfg, var, value);
169 if (!strcmp(var, "diff.ignoresubmodules"))
170 handle_ignore_submodules_arg(&default_diff_options, value);
172 if (git_color_config(var, value, cb) < 0)
173 return -1;
175 return git_diff_basic_config(var, value, cb);
176 }
178 int git_diff_basic_config(const char *var, const char *value, void *cb)
179 {
180 if (!strcmp(var, "diff.renamelimit")) {
181 diff_rename_limit_default = git_config_int(var, value);
182 return 0;
183 }
185 switch (userdiff_config(var, value)) {
186 case 0: break;
187 case -1: return -1;
188 default: return 0;
189 }
191 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
192 int slot = parse_diff_color_slot(var, 11);
193 if (slot < 0)
194 return 0;
195 if (!value)
196 return config_error_nonbool(var);
197 color_parse(value, var, diff_colors[slot]);
198 return 0;
199 }
201 /* like GNU diff's --suppress-blank-empty option */
202 if (!strcmp(var, "diff.suppressblankempty") ||
203 /* for backwards compatibility */
204 !strcmp(var, "diff.suppress-blank-empty")) {
205 diff_suppress_blank_empty = git_config_bool(var, value);
206 return 0;
207 }
209 if (!strcmp(var, "diff.dirstat")) {
210 struct strbuf errmsg = STRBUF_INIT;
211 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
212 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
213 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
214 errmsg.buf);
215 strbuf_release(&errmsg);
216 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
217 return 0;
218 }
220 if (!prefixcmp(var, "submodule."))
221 return parse_submodule_config_option(var, value);
223 return git_default_config(var, value, cb);
224 }
226 static char *quote_two(const char *one, const char *two)
227 {
228 int need_one = quote_c_style(one, NULL, NULL, 1);
229 int need_two = quote_c_style(two, NULL, NULL, 1);
230 struct strbuf res = STRBUF_INIT;
232 if (need_one + need_two) {
233 strbuf_addch(&res, '"');
234 quote_c_style(one, &res, NULL, 1);
235 quote_c_style(two, &res, NULL, 1);
236 strbuf_addch(&res, '"');
237 } else {
238 strbuf_addstr(&res, one);
239 strbuf_addstr(&res, two);
240 }
241 return strbuf_detach(&res, NULL);
242 }
244 static const char *external_diff(void)
245 {
246 static const char *external_diff_cmd = NULL;
247 static int done_preparing = 0;
249 if (done_preparing)
250 return external_diff_cmd;
251 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
252 if (!external_diff_cmd)
253 external_diff_cmd = external_diff_cmd_cfg;
254 done_preparing = 1;
255 return external_diff_cmd;
256 }
258 static struct diff_tempfile {
259 const char *name; /* filename external diff should read from */
260 char hex[41];
261 char mode[10];
262 char tmp_path[PATH_MAX];
263 } diff_temp[2];
265 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
267 struct emit_callback {
268 int color_diff;
269 unsigned ws_rule;
270 int blank_at_eof_in_preimage;
271 int blank_at_eof_in_postimage;
272 int lno_in_preimage;
273 int lno_in_postimage;
274 sane_truncate_fn truncate;
275 const char **label_path;
276 struct diff_words_data *diff_words;
277 struct diff_options *opt;
278 int *found_changesp;
279 struct strbuf *header;
280 };
282 static int count_lines(const char *data, int size)
283 {
284 int count, ch, completely_empty = 1, nl_just_seen = 0;
285 count = 0;
286 while (0 < size--) {
287 ch = *data++;
288 if (ch == '\n') {
289 count++;
290 nl_just_seen = 1;
291 completely_empty = 0;
292 }
293 else {
294 nl_just_seen = 0;
295 completely_empty = 0;
296 }
297 }
298 if (completely_empty)
299 return 0;
300 if (!nl_just_seen)
301 count++; /* no trailing newline */
302 return count;
303 }
305 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
306 {
307 if (!DIFF_FILE_VALID(one)) {
308 mf->ptr = (char *)""; /* does not matter */
309 mf->size = 0;
310 return 0;
311 }
312 else if (diff_populate_filespec(one, 0))
313 return -1;
315 mf->ptr = one->data;
316 mf->size = one->size;
317 return 0;
318 }
320 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
321 static unsigned long diff_filespec_size(struct diff_filespec *one)
322 {
323 if (!DIFF_FILE_VALID(one))
324 return 0;
325 diff_populate_filespec(one, 1);
326 return one->size;
327 }
329 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
330 {
331 char *ptr = mf->ptr;
332 long size = mf->size;
333 int cnt = 0;
335 if (!size)
336 return cnt;
337 ptr += size - 1; /* pointing at the very end */
338 if (*ptr != '\n')
339 ; /* incomplete line */
340 else
341 ptr--; /* skip the last LF */
342 while (mf->ptr < ptr) {
343 char *prev_eol;
344 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
345 if (*prev_eol == '\n')
346 break;
347 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
348 break;
349 cnt++;
350 ptr = prev_eol - 1;
351 }
352 return cnt;
353 }
355 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
356 struct emit_callback *ecbdata)
357 {
358 int l1, l2, at;
359 unsigned ws_rule = ecbdata->ws_rule;
360 l1 = count_trailing_blank(mf1, ws_rule);
361 l2 = count_trailing_blank(mf2, ws_rule);
362 if (l2 <= l1) {
363 ecbdata->blank_at_eof_in_preimage = 0;
364 ecbdata->blank_at_eof_in_postimage = 0;
365 return;
366 }
367 at = count_lines(mf1->ptr, mf1->size);
368 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
370 at = count_lines(mf2->ptr, mf2->size);
371 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
372 }
374 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
375 int first, const char *line, int len)
376 {
377 int has_trailing_newline, has_trailing_carriage_return;
378 int nofirst;
379 FILE *file = o->file;
381 if (o->output_prefix) {
382 struct strbuf *msg = NULL;
383 msg = o->output_prefix(o, o->output_prefix_data);
384 assert(msg);
385 fwrite(msg->buf, msg->len, 1, file);
386 }
388 if (len == 0) {
389 has_trailing_newline = (first == '\n');
390 has_trailing_carriage_return = (!has_trailing_newline &&
391 (first == '\r'));
392 nofirst = has_trailing_newline || has_trailing_carriage_return;
393 } else {
394 has_trailing_newline = (len > 0 && line[len-1] == '\n');
395 if (has_trailing_newline)
396 len--;
397 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
398 if (has_trailing_carriage_return)
399 len--;
400 nofirst = 0;
401 }
403 if (len || !nofirst) {
404 fputs(set, file);
405 if (!nofirst)
406 fputc(first, file);
407 fwrite(line, len, 1, file);
408 fputs(reset, file);
409 }
410 if (has_trailing_carriage_return)
411 fputc('\r', file);
412 if (has_trailing_newline)
413 fputc('\n', file);
414 }
416 static void emit_line(struct diff_options *o, const char *set, const char *reset,
417 const char *line, int len)
418 {
419 emit_line_0(o, set, reset, line[0], line+1, len-1);
420 }
422 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
423 {
424 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
425 ecbdata->blank_at_eof_in_preimage &&
426 ecbdata->blank_at_eof_in_postimage &&
427 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
428 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
429 return 0;
430 return ws_blank_line(line, len, ecbdata->ws_rule);
431 }
433 static void emit_add_line(const char *reset,
434 struct emit_callback *ecbdata,
435 const char *line, int len)
436 {
437 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
438 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
440 if (!*ws)
441 emit_line_0(ecbdata->opt, set, reset, '+', line, len);
442 else if (new_blank_line_at_eof(ecbdata, line, len))
443 /* Blank line at EOF - paint '+' as well */
444 emit_line_0(ecbdata->opt, ws, reset, '+', line, len);
445 else {
446 /* Emit just the prefix, then the rest. */
447 emit_line_0(ecbdata->opt, set, reset, '+', "", 0);
448 ws_check_emit(line, len, ecbdata->ws_rule,
449 ecbdata->opt->file, set, reset, ws);
450 }
451 }
453 static void emit_hunk_header(struct emit_callback *ecbdata,
454 const char *line, int len)
455 {
456 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
457 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
458 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
459 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
460 static const char atat[2] = { '@', '@' };
461 const char *cp, *ep;
462 struct strbuf msgbuf = STRBUF_INIT;
463 int org_len = len;
464 int i = 1;
466 /*
467 * As a hunk header must begin with "@@ -<old>, +<new> @@",
468 * it always is at least 10 bytes long.
469 */
470 if (len < 10 ||
471 memcmp(line, atat, 2) ||
472 !(ep = memmem(line + 2, len - 2, atat, 2))) {
473 emit_line(ecbdata->opt, plain, reset, line, len);
474 return;
475 }
476 ep += 2; /* skip over @@ */
478 /* The hunk header in fraginfo color */
479 strbuf_add(&msgbuf, frag, strlen(frag));
480 strbuf_add(&msgbuf, line, ep - line);
481 strbuf_add(&msgbuf, reset, strlen(reset));
483 /*
484 * trailing "\r\n"
485 */
486 for ( ; i < 3; i++)
487 if (line[len - i] == '\r' || line[len - i] == '\n')
488 len--;
490 /* blank before the func header */
491 for (cp = ep; ep - line < len; ep++)
492 if (*ep != ' ' && *ep != '\t')
493 break;
494 if (ep != cp) {
495 strbuf_add(&msgbuf, plain, strlen(plain));
496 strbuf_add(&msgbuf, cp, ep - cp);
497 strbuf_add(&msgbuf, reset, strlen(reset));
498 }
500 if (ep < line + len) {
501 strbuf_add(&msgbuf, func, strlen(func));
502 strbuf_add(&msgbuf, ep, line + len - ep);
503 strbuf_add(&msgbuf, reset, strlen(reset));
504 }
506 strbuf_add(&msgbuf, line + len, org_len - len);
507 emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
508 strbuf_release(&msgbuf);
509 }
511 static struct diff_tempfile *claim_diff_tempfile(void) {
512 int i;
513 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
514 if (!diff_temp[i].name)
515 return diff_temp + i;
516 die("BUG: diff is failing to clean up its tempfiles");
517 }
519 static int remove_tempfile_installed;
521 static void remove_tempfile(void)
522 {
523 int i;
524 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
525 if (diff_temp[i].name == diff_temp[i].tmp_path)
526 unlink_or_warn(diff_temp[i].name);
527 diff_temp[i].name = NULL;
528 }
529 }
531 static void remove_tempfile_on_signal(int signo)
532 {
533 remove_tempfile();
534 sigchain_pop(signo);
535 raise(signo);
536 }
538 static void print_line_count(FILE *file, int count)
539 {
540 switch (count) {
541 case 0:
542 fprintf(file, "0,0");
543 break;
544 case 1:
545 fprintf(file, "1");
546 break;
547 default:
548 fprintf(file, "1,%d", count);
549 break;
550 }
551 }
553 static void emit_rewrite_lines(struct emit_callback *ecb,
554 int prefix, const char *data, int size)
555 {
556 const char *endp = NULL;
557 static const char *nneof = " No newline at end of file\n";
558 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
559 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
561 while (0 < size) {
562 int len;
564 endp = memchr(data, '\n', size);
565 len = endp ? (endp - data + 1) : size;
566 if (prefix != '+') {
567 ecb->lno_in_preimage++;
568 emit_line_0(ecb->opt, old, reset, '-',
569 data, len);
570 } else {
571 ecb->lno_in_postimage++;
572 emit_add_line(reset, ecb, data, len);
573 }
574 size -= len;
575 data += len;
576 }
577 if (!endp) {
578 const char *plain = diff_get_color(ecb->color_diff,
579 DIFF_PLAIN);
580 emit_line_0(ecb->opt, plain, reset, '\\',
581 nneof, strlen(nneof));
582 }
583 }
585 static void emit_rewrite_diff(const char *name_a,
586 const char *name_b,
587 struct diff_filespec *one,
588 struct diff_filespec *two,
589 struct userdiff_driver *textconv_one,
590 struct userdiff_driver *textconv_two,
591 struct diff_options *o)
592 {
593 int lc_a, lc_b;
594 const char *name_a_tab, *name_b_tab;
595 const char *metainfo = diff_get_color(o->use_color, DIFF_METAINFO);
596 const char *fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
597 const char *reset = diff_get_color(o->use_color, DIFF_RESET);
598 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
599 const char *a_prefix, *b_prefix;
600 char *data_one, *data_two;
601 size_t size_one, size_two;
602 struct emit_callback ecbdata;
603 char *line_prefix = "";
604 struct strbuf *msgbuf;
606 if (o && o->output_prefix) {
607 msgbuf = o->output_prefix(o, o->output_prefix_data);
608 line_prefix = msgbuf->buf;
609 }
611 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
612 a_prefix = o->b_prefix;
613 b_prefix = o->a_prefix;
614 } else {
615 a_prefix = o->a_prefix;
616 b_prefix = o->b_prefix;
617 }
619 name_a += (*name_a == '/');
620 name_b += (*name_b == '/');
621 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
622 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
624 strbuf_reset(&a_name);
625 strbuf_reset(&b_name);
626 quote_two_c_style(&a_name, a_prefix, name_a, 0);
627 quote_two_c_style(&b_name, b_prefix, name_b, 0);
629 size_one = fill_textconv(textconv_one, one, &data_one);
630 size_two = fill_textconv(textconv_two, two, &data_two);
632 memset(&ecbdata, 0, sizeof(ecbdata));
633 ecbdata.color_diff = want_color(o->use_color);
634 ecbdata.found_changesp = &o->found_changes;
635 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
636 ecbdata.opt = o;
637 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
638 mmfile_t mf1, mf2;
639 mf1.ptr = (char *)data_one;
640 mf2.ptr = (char *)data_two;
641 mf1.size = size_one;
642 mf2.size = size_two;
643 check_blank_at_eof(&mf1, &mf2, &ecbdata);
644 }
645 ecbdata.lno_in_preimage = 1;
646 ecbdata.lno_in_postimage = 1;
648 lc_a = count_lines(data_one, size_one);
649 lc_b = count_lines(data_two, size_two);
650 fprintf(o->file,
651 "%s%s--- %s%s%s\n%s%s+++ %s%s%s\n%s%s@@ -",
652 line_prefix, metainfo, a_name.buf, name_a_tab, reset,
653 line_prefix, metainfo, b_name.buf, name_b_tab, reset,
654 line_prefix, fraginfo);
655 if (!o->irreversible_delete)
656 print_line_count(o->file, lc_a);
657 else
658 fprintf(o->file, "?,?");
659 fprintf(o->file, " +");
660 print_line_count(o->file, lc_b);
661 fprintf(o->file, " @@%s\n", reset);
662 if (lc_a && !o->irreversible_delete)
663 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
664 if (lc_b)
665 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
666 if (textconv_one)
667 free((char *)data_one);
668 if (textconv_two)
669 free((char *)data_two);
670 }
672 struct diff_words_buffer {
673 mmfile_t text;
674 long alloc;
675 struct diff_words_orig {
676 const char *begin, *end;
677 } *orig;
678 int orig_nr, orig_alloc;
679 };
681 static void diff_words_append(char *line, unsigned long len,
682 struct diff_words_buffer *buffer)
683 {
684 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
685 line++;
686 len--;
687 memcpy(buffer->text.ptr + buffer->text.size, line, len);
688 buffer->text.size += len;
689 buffer->text.ptr[buffer->text.size] = '\0';
690 }
692 struct diff_words_style_elem {
693 const char *prefix;
694 const char *suffix;
695 const char *color; /* NULL; filled in by the setup code if
696 * color is enabled */
697 };
699 struct diff_words_style {
700 enum diff_words_type type;
701 struct diff_words_style_elem new, old, ctx;
702 const char *newline;
703 };
705 static struct diff_words_style diff_words_styles[] = {
706 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
707 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
708 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
709 };
711 struct diff_words_data {
712 struct diff_words_buffer minus, plus;
713 const char *current_plus;
714 int last_minus;
715 struct diff_options *opt;
716 regex_t *word_regex;
717 enum diff_words_type type;
718 struct diff_words_style *style;
719 };
721 static int fn_out_diff_words_write_helper(FILE *fp,
722 struct diff_words_style_elem *st_el,
723 const char *newline,
724 size_t count, const char *buf,
725 const char *line_prefix)
726 {
727 int print = 0;
729 while (count) {
730 char *p = memchr(buf, '\n', count);
731 if (print)
732 fputs(line_prefix, fp);
733 if (p != buf) {
734 if (st_el->color && fputs(st_el->color, fp) < 0)
735 return -1;
736 if (fputs(st_el->prefix, fp) < 0 ||
737 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
738 fputs(st_el->suffix, fp) < 0)
739 return -1;
740 if (st_el->color && *st_el->color
741 && fputs(GIT_COLOR_RESET, fp) < 0)
742 return -1;
743 }
744 if (!p)
745 return 0;
746 if (fputs(newline, fp) < 0)
747 return -1;
748 count -= p + 1 - buf;
749 buf = p + 1;
750 print = 1;
751 }
752 return 0;
753 }
755 /*
756 * '--color-words' algorithm can be described as:
757 *
758 * 1. collect a the minus/plus lines of a diff hunk, divided into
759 * minus-lines and plus-lines;
760 *
761 * 2. break both minus-lines and plus-lines into words and
762 * place them into two mmfile_t with one word for each line;
763 *
764 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
765 *
766 * And for the common parts of the both file, we output the plus side text.
767 * diff_words->current_plus is used to trace the current position of the plus file
768 * which printed. diff_words->last_minus is used to trace the last minus word
769 * printed.
770 *
771 * For '--graph' to work with '--color-words', we need to output the graph prefix
772 * on each line of color words output. Generally, there are two conditions on
773 * which we should output the prefix.
774 *
775 * 1. diff_words->last_minus == 0 &&
776 * diff_words->current_plus == diff_words->plus.text.ptr
777 *
778 * that is: the plus text must start as a new line, and if there is no minus
779 * word printed, a graph prefix must be printed.
780 *
781 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
782 * *(diff_words->current_plus - 1) == '\n'
783 *
784 * that is: a graph prefix must be printed following a '\n'
785 */
786 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
787 {
788 if ((diff_words->last_minus == 0 &&
789 diff_words->current_plus == diff_words->plus.text.ptr) ||
790 (diff_words->current_plus > diff_words->plus.text.ptr &&
791 *(diff_words->current_plus - 1) == '\n')) {
792 return 1;
793 } else {
794 return 0;
795 }
796 }
798 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
799 {
800 struct diff_words_data *diff_words = priv;
801 struct diff_words_style *style = diff_words->style;
802 int minus_first, minus_len, plus_first, plus_len;
803 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
804 struct diff_options *opt = diff_words->opt;
805 struct strbuf *msgbuf;
806 char *line_prefix = "";
808 if (line[0] != '@' || parse_hunk_header(line, len,
809 &minus_first, &minus_len, &plus_first, &plus_len))
810 return;
812 assert(opt);
813 if (opt->output_prefix) {
814 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
815 line_prefix = msgbuf->buf;
816 }
818 /* POSIX requires that first be decremented by one if len == 0... */
819 if (minus_len) {
820 minus_begin = diff_words->minus.orig[minus_first].begin;
821 minus_end =
822 diff_words->minus.orig[minus_first + minus_len - 1].end;
823 } else
824 minus_begin = minus_end =
825 diff_words->minus.orig[minus_first].end;
827 if (plus_len) {
828 plus_begin = diff_words->plus.orig[plus_first].begin;
829 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
830 } else
831 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
833 if (color_words_output_graph_prefix(diff_words)) {
834 fputs(line_prefix, diff_words->opt->file);
835 }
836 if (diff_words->current_plus != plus_begin) {
837 fn_out_diff_words_write_helper(diff_words->opt->file,
838 &style->ctx, style->newline,
839 plus_begin - diff_words->current_plus,
840 diff_words->current_plus, line_prefix);
841 if (*(plus_begin - 1) == '\n')
842 fputs(line_prefix, diff_words->opt->file);
843 }
844 if (minus_begin != minus_end) {
845 fn_out_diff_words_write_helper(diff_words->opt->file,
846 &style->old, style->newline,
847 minus_end - minus_begin, minus_begin,
848 line_prefix);
849 }
850 if (plus_begin != plus_end) {
851 fn_out_diff_words_write_helper(diff_words->opt->file,
852 &style->new, style->newline,
853 plus_end - plus_begin, plus_begin,
854 line_prefix);
855 }
857 diff_words->current_plus = plus_end;
858 diff_words->last_minus = minus_first;
859 }
861 /* This function starts looking at *begin, and returns 0 iff a word was found. */
862 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
863 int *begin, int *end)
864 {
865 if (word_regex && *begin < buffer->size) {
866 regmatch_t match[1];
867 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
868 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
869 '\n', match[0].rm_eo - match[0].rm_so);
870 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
871 *begin += match[0].rm_so;
872 return *begin >= *end;
873 }
874 return -1;
875 }
877 /* find the next word */
878 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
879 (*begin)++;
880 if (*begin >= buffer->size)
881 return -1;
883 /* find the end of the word */
884 *end = *begin + 1;
885 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
886 (*end)++;
888 return 0;
889 }
891 /*
892 * This function splits the words in buffer->text, stores the list with
893 * newline separator into out, and saves the offsets of the original words
894 * in buffer->orig.
895 */
896 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
897 regex_t *word_regex)
898 {
899 int i, j;
900 long alloc = 0;
902 out->size = 0;
903 out->ptr = NULL;
905 /* fake an empty "0th" word */
906 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
907 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
908 buffer->orig_nr = 1;
910 for (i = 0; i < buffer->text.size; i++) {
911 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
912 return;
914 /* store original boundaries */
915 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
916 buffer->orig_alloc);
917 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
918 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
919 buffer->orig_nr++;
921 /* store one word */
922 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
923 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
924 out->ptr[out->size + j - i] = '\n';
925 out->size += j - i + 1;
927 i = j - 1;
928 }
929 }
931 /* this executes the word diff on the accumulated buffers */
932 static void diff_words_show(struct diff_words_data *diff_words)
933 {
934 xpparam_t xpp;
935 xdemitconf_t xecfg;
936 mmfile_t minus, plus;
937 struct diff_words_style *style = diff_words->style;
939 struct diff_options *opt = diff_words->opt;
940 struct strbuf *msgbuf;
941 char *line_prefix = "";
943 assert(opt);
944 if (opt->output_prefix) {
945 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
946 line_prefix = msgbuf->buf;
947 }
949 /* special case: only removal */
950 if (!diff_words->plus.text.size) {
951 fputs(line_prefix, diff_words->opt->file);
952 fn_out_diff_words_write_helper(diff_words->opt->file,
953 &style->old, style->newline,
954 diff_words->minus.text.size,
955 diff_words->minus.text.ptr, line_prefix);
956 diff_words->minus.text.size = 0;
957 return;
958 }
960 diff_words->current_plus = diff_words->plus.text.ptr;
961 diff_words->last_minus = 0;
963 memset(&xpp, 0, sizeof(xpp));
964 memset(&xecfg, 0, sizeof(xecfg));
965 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
966 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
967 xpp.flags = 0;
968 /* as only the hunk header will be parsed, we need a 0-context */
969 xecfg.ctxlen = 0;
970 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
971 &xpp, &xecfg);
972 free(minus.ptr);
973 free(plus.ptr);
974 if (diff_words->current_plus != diff_words->plus.text.ptr +
975 diff_words->plus.text.size) {
976 if (color_words_output_graph_prefix(diff_words))
977 fputs(line_prefix, diff_words->opt->file);
978 fn_out_diff_words_write_helper(diff_words->opt->file,
979 &style->ctx, style->newline,
980 diff_words->plus.text.ptr + diff_words->plus.text.size
981 - diff_words->current_plus, diff_words->current_plus,
982 line_prefix);
983 }
984 diff_words->minus.text.size = diff_words->plus.text.size = 0;
985 }
987 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
988 static void diff_words_flush(struct emit_callback *ecbdata)
989 {
990 if (ecbdata->diff_words->minus.text.size ||
991 ecbdata->diff_words->plus.text.size)
992 diff_words_show(ecbdata->diff_words);
993 }
995 static void free_diff_words_data(struct emit_callback *ecbdata)
996 {
997 if (ecbdata->diff_words) {
998 diff_words_flush(ecbdata);
999 free (ecbdata->diff_words->minus.text.ptr);
1000 free (ecbdata->diff_words->minus.orig);
1001 free (ecbdata->diff_words->plus.text.ptr);
1002 free (ecbdata->diff_words->plus.orig);
1003 if (ecbdata->diff_words->word_regex) {
1004 regfree(ecbdata->diff_words->word_regex);
1005 free(ecbdata->diff_words->word_regex);
1006 }
1007 free(ecbdata->diff_words);
1008 ecbdata->diff_words = NULL;
1009 }
1010 }
1012 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1013 {
1014 if (want_color(diff_use_color))
1015 return diff_colors[ix];
1016 return "";
1017 }
1019 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1020 {
1021 const char *cp;
1022 unsigned long allot;
1023 size_t l = len;
1025 if (ecb->truncate)
1026 return ecb->truncate(line, len);
1027 cp = line;
1028 allot = l;
1029 while (0 < l) {
1030 (void) utf8_width(&cp, &l);
1031 if (!cp)
1032 break; /* truncated in the middle? */
1033 }
1034 return allot - l;
1035 }
1037 static void find_lno(const char *line, struct emit_callback *ecbdata)
1038 {
1039 const char *p;
1040 ecbdata->lno_in_preimage = 0;
1041 ecbdata->lno_in_postimage = 0;
1042 p = strchr(line, '-');
1043 if (!p)
1044 return; /* cannot happen */
1045 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1046 p = strchr(p, '+');
1047 if (!p)
1048 return; /* cannot happen */
1049 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1050 }
1052 static void fn_out_consume(void *priv, char *line, unsigned long len)
1053 {
1054 struct emit_callback *ecbdata = priv;
1055 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
1056 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
1057 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1058 struct diff_options *o = ecbdata->opt;
1059 char *line_prefix = "";
1060 struct strbuf *msgbuf;
1062 if (o && o->output_prefix) {
1063 msgbuf = o->output_prefix(o, o->output_prefix_data);
1064 line_prefix = msgbuf->buf;
1065 }
1067 if (ecbdata->header) {
1068 fprintf(ecbdata->opt->file, "%s", ecbdata->header->buf);
1069 strbuf_reset(ecbdata->header);
1070 ecbdata->header = NULL;
1071 }
1072 *(ecbdata->found_changesp) = 1;
1074 if (ecbdata->label_path[0]) {
1075 const char *name_a_tab, *name_b_tab;
1077 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
1078 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
1080 fprintf(ecbdata->opt->file, "%s%s--- %s%s%s\n",
1081 line_prefix, meta, ecbdata->label_path[0], reset, name_a_tab);
1082 fprintf(ecbdata->opt->file, "%s%s+++ %s%s%s\n",
1083 line_prefix, meta, ecbdata->label_path[1], reset, name_b_tab);
1084 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1085 }
1087 if (diff_suppress_blank_empty
1088 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1089 line[0] = '\n';
1090 len = 1;
1091 }
1093 if (line[0] == '@') {
1094 if (ecbdata->diff_words)
1095 diff_words_flush(ecbdata);
1096 len = sane_truncate_line(ecbdata, line, len);
1097 find_lno(line, ecbdata);
1098 emit_hunk_header(ecbdata, line, len);
1099 if (line[len-1] != '\n')
1100 putc('\n', ecbdata->opt->file);
1101 return;
1102 }
1104 if (len < 1) {
1105 emit_line(ecbdata->opt, reset, reset, line, len);
1106 if (ecbdata->diff_words
1107 && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
1108 fputs("~\n", ecbdata->opt->file);
1109 return;
1110 }
1112 if (ecbdata->diff_words) {
1113 if (line[0] == '-') {
1114 diff_words_append(line, len,
1115 &ecbdata->diff_words->minus);
1116 return;
1117 } else if (line[0] == '+') {
1118 diff_words_append(line, len,
1119 &ecbdata->diff_words->plus);
1120 return;
1121 } else if (!prefixcmp(line, "\\ ")) {
1122 /*
1123 * Eat the "no newline at eof" marker as if we
1124 * saw a "+" or "-" line with nothing on it,
1125 * and return without diff_words_flush() to
1126 * defer processing. If this is the end of
1127 * preimage, more "+" lines may come after it.
1128 */
1129 return;
1130 }
1131 diff_words_flush(ecbdata);
1132 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
1133 emit_line(ecbdata->opt, plain, reset, line, len);
1134 fputs("~\n", ecbdata->opt->file);
1135 } else {
1136 /*
1137 * Skip the prefix character, if any. With
1138 * diff_suppress_blank_empty, there may be
1139 * none.
1140 */
1141 if (line[0] != '\n') {
1142 line++;
1143 len--;
1144 }
1145 emit_line(ecbdata->opt, plain, reset, line, len);
1146 }
1147 return;
1148 }
1150 if (line[0] != '+') {
1151 const char *color =
1152 diff_get_color(ecbdata->color_diff,
1153 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
1154 ecbdata->lno_in_preimage++;
1155 if (line[0] == ' ')
1156 ecbdata->lno_in_postimage++;
1157 emit_line(ecbdata->opt, color, reset, line, len);
1158 } else {
1159 ecbdata->lno_in_postimage++;
1160 emit_add_line(reset, ecbdata, line + 1, len - 1);
1161 }
1162 }
1164 static char *pprint_rename(const char *a, const char *b)
1165 {
1166 const char *old = a;
1167 const char *new = b;
1168 struct strbuf name = STRBUF_INIT;
1169 int pfx_length, sfx_length;
1170 int len_a = strlen(a);
1171 int len_b = strlen(b);
1172 int a_midlen, b_midlen;
1173 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1174 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1176 if (qlen_a || qlen_b) {
1177 quote_c_style(a, &name, NULL, 0);
1178 strbuf_addstr(&name, " => ");
1179 quote_c_style(b, &name, NULL, 0);
1180 return strbuf_detach(&name, NULL);
1181 }
1183 /* Find common prefix */
1184 pfx_length = 0;
1185 while (*old && *new && *old == *new) {
1186 if (*old == '/')
1187 pfx_length = old - a + 1;
1188 old++;
1189 new++;
1190 }
1192 /* Find common suffix */
1193 old = a + len_a;
1194 new = b + len_b;
1195 sfx_length = 0;
1196 while (a <= old && b <= new && *old == *new) {
1197 if (*old == '/')
1198 sfx_length = len_a - (old - a);
1199 old--;
1200 new--;
1201 }
1203 /*
1204 * pfx{mid-a => mid-b}sfx
1205 * {pfx-a => pfx-b}sfx
1206 * pfx{sfx-a => sfx-b}
1207 * name-a => name-b
1208 */
1209 a_midlen = len_a - pfx_length - sfx_length;
1210 b_midlen = len_b - pfx_length - sfx_length;
1211 if (a_midlen < 0)
1212 a_midlen = 0;
1213 if (b_midlen < 0)
1214 b_midlen = 0;
1216 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1217 if (pfx_length + sfx_length) {
1218 strbuf_add(&name, a, pfx_length);
1219 strbuf_addch(&name, '{');
1220 }
1221 strbuf_add(&name, a + pfx_length, a_midlen);
1222 strbuf_addstr(&name, " => ");
1223 strbuf_add(&name, b + pfx_length, b_midlen);
1224 if (pfx_length + sfx_length) {
1225 strbuf_addch(&name, '}');
1226 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1227 }
1228 return strbuf_detach(&name, NULL);
1229 }
1231 struct diffstat_t {
1232 int nr;
1233 int alloc;
1234 struct diffstat_file {
1235 char *from_name;
1236 char *name;
1237 char *print_name;
1238 unsigned is_unmerged:1;
1239 unsigned is_binary:1;
1240 unsigned is_renamed:1;
1241 uintmax_t added, deleted;
1242 } **files;
1243 };
1245 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1246 const char *name_a,
1247 const char *name_b)
1248 {
1249 struct diffstat_file *x;
1250 x = xcalloc(sizeof (*x), 1);
1251 if (diffstat->nr == diffstat->alloc) {
1252 diffstat->alloc = alloc_nr(diffstat->alloc);
1253 diffstat->files = xrealloc(diffstat->files,
1254 diffstat->alloc * sizeof(x));
1255 }
1256 diffstat->files[diffstat->nr++] = x;
1257 if (name_b) {
1258 x->from_name = xstrdup(name_a);
1259 x->name = xstrdup(name_b);
1260 x->is_renamed = 1;
1261 }
1262 else {
1263 x->from_name = NULL;
1264 x->name = xstrdup(name_a);
1265 }
1266 return x;
1267 }
1269 static void diffstat_consume(void *priv, char *line, unsigned long len)
1270 {
1271 struct diffstat_t *diffstat = priv;
1272 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1274 if (line[0] == '+')
1275 x->added++;
1276 else if (line[0] == '-')
1277 x->deleted++;
1278 }
1280 const char mime_boundary_leader[] = "------------";
1282 static int scale_linear(int it, int width, int max_change)
1283 {
1284 if (!it)
1285 return 0;
1286 /*
1287 * make sure that at least one '-' or '+' is printed if
1288 * there is any change to this path. The easiest way is to
1289 * scale linearly as if the alloted width is one column shorter
1290 * than it is, and then add 1 to the result.
1291 */
1292 return 1 + (it * (width - 1) / max_change);
1293 }
1295 static void show_name(FILE *file,
1296 const char *prefix, const char *name, int len)
1297 {
1298 fprintf(file, " %s%-*s |", prefix, len, name);
1299 }
1301 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1302 {
1303 if (cnt <= 0)
1304 return;
1305 fprintf(file, "%s", set);
1306 while (cnt--)
1307 putc(ch, file);
1308 fprintf(file, "%s", reset);
1309 }
1311 static void fill_print_name(struct diffstat_file *file)
1312 {
1313 char *pname;
1315 if (file->print_name)
1316 return;
1318 if (!file->is_renamed) {
1319 struct strbuf buf = STRBUF_INIT;
1320 if (quote_c_style(file->name, &buf, NULL, 0)) {
1321 pname = strbuf_detach(&buf, NULL);
1322 } else {
1323 pname = file->name;
1324 strbuf_release(&buf);
1325 }
1326 } else {
1327 pname = pprint_rename(file->from_name, file->name);
1328 }
1329 file->print_name = pname;
1330 }
1332 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1333 {
1334 int i, len, add, del, adds = 0, dels = 0;
1335 uintmax_t max_change = 0, max_len = 0;
1336 int total_files = data->nr;
1337 int width, name_width, graph_width, number_width = 4, count;
1338 const char *reset, *add_c, *del_c;
1339 const char *line_prefix = "";
1340 int extra_shown = 0;
1341 struct strbuf *msg = NULL;
1343 if (data->nr == 0)
1344 return;
1346 if (options->output_prefix) {
1347 msg = options->output_prefix(options, options->output_prefix_data);
1348 line_prefix = msg->buf;
1349 }
1351 count = options->stat_count ? options->stat_count : data->nr;
1353 reset = diff_get_color_opt(options, DIFF_RESET);
1354 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1355 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1357 /*
1358 * Find the longest filename and max number of changes
1359 */
1360 for (i = 0; (i < count) && (i < data->nr); i++) {
1361 struct diffstat_file *file = data->files[i];
1362 uintmax_t change = file->added + file->deleted;
1363 if (!data->files[i]->is_renamed &&
1364 (change == 0)) {
1365 count++; /* not shown == room for one more */
1366 continue;
1367 }
1368 fill_print_name(file);
1369 len = strlen(file->print_name);
1370 if (max_len < len)
1371 max_len = len;
1373 if (file->is_binary || file->is_unmerged)
1374 continue;
1375 if (max_change < change)
1376 max_change = change;
1377 }
1378 count = i; /* min(count, data->nr) */
1380 /*
1381 * We have width = stat_width or term_columns() columns total.
1382 * We want a maximum of min(max_len, stat_name_width) for the name part.
1383 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1384 * We also need 1 for " " and 4 + decimal_width(max_change)
1385 * for " | NNNN " and one the empty column at the end, altogether
1386 * 6 + decimal_width(max_change).
1387 *
1388 * If there's not enough space, we will use the smaller of
1389 * stat_name_width (if set) and 5/8*width for the filename,
1390 * and the rest for constant elements + graph part, but no more
1391 * than stat_graph_width for the graph part.
1392 * (5/8 gives 50 for filename and 30 for the constant parts + graph
1393 * for the standard terminal size).
1394 *
1395 * In other words: stat_width limits the maximum width, and
1396 * stat_name_width fixes the maximum width of the filename,
1397 * and is also used to divide available columns if there
1398 * aren't enough.
1399 */
1401 if (options->stat_width == -1)
1402 width = term_columns();
1403 else
1404 width = options->stat_width ? options->stat_width : 80;
1406 if (options->stat_graph_width == -1)
1407 options->stat_graph_width = diff_stat_graph_width;
1409 /*
1410 * Guarantee 3/8*16==6 for the graph part
1411 * and 5/8*16==10 for the filename part
1412 */
1413 if (width < 16 + 6 + number_width)
1414 width = 16 + 6 + number_width;
1416 /*
1417 * First assign sizes that are wanted, ignoring available width.
1418 */
1419 graph_width = (options->stat_graph_width &&
1420 options->stat_graph_width < max_change) ?
1421 options->stat_graph_width : max_change;
1422 name_width = (options->stat_name_width > 0 &&
1423 options->stat_name_width < max_len) ?
1424 options->stat_name_width : max_len;
1426 /*
1427 * Adjust adjustable widths not to exceed maximum width
1428 */
1429 if (name_width + number_width + 6 + graph_width > width) {
1430 if (graph_width > width * 3/8 - number_width - 6)
1431 graph_width = width * 3/8 - number_width - 6;
1432 if (options->stat_graph_width &&
1433 graph_width > options->stat_graph_width)
1434 graph_width = options->stat_graph_width;
1435 if (name_width > width - number_width - 6 - graph_width)
1436 name_width = width - number_width - 6 - graph_width;
1437 else
1438 graph_width = width - number_width - 6 - name_width;
1439 }
1441 /*
1442 * From here name_width is the width of the name area,
1443 * and graph_width is the width of the graph area.
1444 * max_change is used to scale graph properly.
1445 */
1446 for (i = 0; i < count; i++) {
1447 const char *prefix = "";
1448 char *name = data->files[i]->print_name;
1449 uintmax_t added = data->files[i]->added;
1450 uintmax_t deleted = data->files[i]->deleted;
1451 int name_len;
1453 if (!data->files[i]->is_renamed &&
1454 (added + deleted == 0)) {
1455 total_files--;
1456 continue;
1457 }
1458 /*
1459 * "scale" the filename
1460 */
1461 len = name_width;
1462 name_len = strlen(name);
1463 if (name_width < name_len) {
1464 char *slash;
1465 prefix = "...";
1466 len -= 3;
1467 name += name_len - len;
1468 slash = strchr(name, '/');
1469 if (slash)
1470 name = slash;
1471 }
1473 if (data->files[i]->is_binary) {
1474 fprintf(options->file, "%s", line_prefix);
1475 show_name(options->file, prefix, name, len);
1476 fprintf(options->file, " Bin ");
1477 fprintf(options->file, "%s%"PRIuMAX"%s",
1478 del_c, deleted, reset);
1479 fprintf(options->file, " -> ");
1480 fprintf(options->file, "%s%"PRIuMAX"%s",
1481 add_c, added, reset);
1482 fprintf(options->file, " bytes");
1483 fprintf(options->file, "\n");
1484 continue;
1485 }
1486 else if (data->files[i]->is_unmerged) {
1487 fprintf(options->file, "%s", line_prefix);
1488 show_name(options->file, prefix, name, len);
1489 fprintf(options->file, " Unmerged\n");
1490 continue;
1491 }
1493 /*
1494 * scale the add/delete
1495 */
1496 add = added;
1497 del = deleted;
1498 adds += add;
1499 dels += del;
1501 if (graph_width <= max_change) {
1502 int total = add + del;
1504 total = scale_linear(add + del, graph_width, max_change);
1505 if (total < 2 && add && del)
1506 /* width >= 2 due to the sanity check */
1507 total = 2;
1508 if (add < del) {
1509 add = scale_linear(add, graph_width, max_change);
1510 del = total - add;
1511 } else {
1512 del = scale_linear(del, graph_width, max_change);
1513 add = total - del;
1514 }
1515 }
1516 fprintf(options->file, "%s", line_prefix);
1517 show_name(options->file, prefix, name, len);
1518 fprintf(options->file, "%5"PRIuMAX"%s", added + deleted,
1519 added + deleted ? " " : "");
1520 show_graph(options->file, '+', add, add_c, reset);
1521 show_graph(options->file, '-', del, del_c, reset);
1522 fprintf(options->file, "\n");
1523 }
1524 for (i = count; i < data->nr; i++) {
1525 uintmax_t added = data->files[i]->added;
1526 uintmax_t deleted = data->files[i]->deleted;
1527 if (!data->files[i]->is_renamed &&
1528 (added + deleted == 0)) {
1529 total_files--;
1530 continue;
1531 }
1532 adds += added;
1533 dels += deleted;
1534 if (!extra_shown)
1535 fprintf(options->file, "%s ...\n", line_prefix);
1536 extra_shown = 1;
1537 }
1538 fprintf(options->file, "%s", line_prefix);
1539 fprintf(options->file,
1540 " %d files changed, %d insertions(+), %d deletions(-)\n",
1541 total_files, adds, dels);
1542 }
1544 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1545 {
1546 int i, adds = 0, dels = 0, total_files = data->nr;
1548 if (data->nr == 0)
1549 return;
1551 for (i = 0; i < data->nr; i++) {
1552 if (!data->files[i]->is_binary &&
1553 !data->files[i]->is_unmerged) {
1554 int added = data->files[i]->added;
1555 int deleted= data->files[i]->deleted;
1556 if (!data->files[i]->is_renamed &&
1557 (added + deleted == 0)) {
1558 total_files--;
1559 } else {
1560 adds += added;
1561 dels += deleted;
1562 }
1563 }
1564 }
1565 if (options->output_prefix) {
1566 struct strbuf *msg = NULL;
1567 msg = options->output_prefix(options,
1568 options->output_prefix_data);
1569 fprintf(options->file, "%s", msg->buf);
1570 }
1571 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1572 total_files, adds, dels);
1573 }
1575 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1576 {
1577 int i;
1579 if (data->nr == 0)
1580 return;
1582 for (i = 0; i < data->nr; i++) {
1583 struct diffstat_file *file = data->files[i];
1585 if (options->output_prefix) {
1586 struct strbuf *msg = NULL;
1587 msg = options->output_prefix(options,
1588 options->output_prefix_data);
1589 fprintf(options->file, "%s", msg->buf);
1590 }
1592 if (file->is_binary)
1593 fprintf(options->file, "-\t-\t");
1594 else
1595 fprintf(options->file,
1596 "%"PRIuMAX"\t%"PRIuMAX"\t",
1597 file->added, file->deleted);
1598 if (options->line_termination) {
1599 fill_print_name(file);
1600 if (!file->is_renamed)
1601 write_name_quoted(file->name, options->file,
1602 options->line_termination);
1603 else {
1604 fputs(file->print_name, options->file);
1605 putc(options->line_termination, options->file);
1606 }
1607 } else {
1608 if (file->is_renamed) {
1609 putc('\0', options->file);
1610 write_name_quoted(file->from_name, options->file, '\0');
1611 }
1612 write_name_quoted(file->name, options->file, '\0');
1613 }
1614 }
1615 }
1617 struct dirstat_file {
1618 const char *name;
1619 unsigned long changed;
1620 };
1622 struct dirstat_dir {
1623 struct dirstat_file *files;
1624 int alloc, nr, permille, cumulative;
1625 };
1627 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
1628 unsigned long changed, const char *base, int baselen)
1629 {
1630 unsigned long this_dir = 0;
1631 unsigned int sources = 0;
1632 const char *line_prefix = "";
1633 struct strbuf *msg = NULL;
1635 if (opt->output_prefix) {
1636 msg = opt->output_prefix(opt, opt->output_prefix_data);
1637 line_prefix = msg->buf;
1638 }
1640 while (dir->nr) {
1641 struct dirstat_file *f = dir->files;
1642 int namelen = strlen(f->name);
1643 unsigned long this;
1644 char *slash;
1646 if (namelen < baselen)
1647 break;
1648 if (memcmp(f->name, base, baselen))
1649 break;
1650 slash = strchr(f->name + baselen, '/');
1651 if (slash) {
1652 int newbaselen = slash + 1 - f->name;
1653 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
1654 sources++;
1655 } else {
1656 this = f->changed;
1657 dir->files++;
1658 dir->nr--;
1659 sources += 2;
1660 }
1661 this_dir += this;
1662 }
1664 /*
1665 * We don't report dirstat's for
1666 * - the top level
1667 * - or cases where everything came from a single directory
1668 * under this directory (sources == 1).
1669 */
1670 if (baselen && sources != 1) {
1671 if (this_dir) {
1672 int permille = this_dir * 1000 / changed;
1673 if (permille >= dir->permille) {
1674 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
1675 permille / 10, permille % 10, baselen, base);
1676 if (!dir->cumulative)
1677 return 0;
1678 }
1679 }
1680 }
1681 return this_dir;
1682 }
1684 static int dirstat_compare(const void *_a, const void *_b)
1685 {
1686 const struct dirstat_file *a = _a;
1687 const struct dirstat_file *b = _b;
1688 return strcmp(a->name, b->name);
1689 }
1691 static void show_dirstat(struct diff_options *options)
1692 {
1693 int i;
1694 unsigned long changed;
1695 struct dirstat_dir dir;
1696 struct diff_queue_struct *q = &diff_queued_diff;
1698 dir.files = NULL;
1699 dir.alloc = 0;
1700 dir.nr = 0;
1701 dir.permille = options->dirstat_permille;
1702 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1704 changed = 0;
1705 for (i = 0; i < q->nr; i++) {
1706 struct diff_filepair *p = q->queue[i];
1707 const char *name;
1708 unsigned long copied, added, damage;
1709 int content_changed;
1711 name = p->two->path ? p->two->path : p->one->path;
1713 if (p->one->sha1_valid && p->two->sha1_valid)
1714 content_changed = hashcmp(p->one->sha1, p->two->sha1);
1715 else
1716 content_changed = 1;
1718 if (!content_changed) {
1719 /*
1720 * The SHA1 has not changed, so pre-/post-content is
1721 * identical. We can therefore skip looking at the
1722 * file contents altogether.
1723 */
1724 damage = 0;
1725 goto found_damage;
1726 }
1728 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
1729 /*
1730 * In --dirstat-by-file mode, we don't really need to
1731 * look at the actual file contents at all.
1732 * The fact that the SHA1 changed is enough for us to
1733 * add this file to the list of results
1734 * (with each file contributing equal damage).
1735 */
1736 damage = 1;
1737 goto found_damage;
1738 }
1740 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1741 diff_populate_filespec(p->one, 0);
1742 diff_populate_filespec(p->two, 0);
1743 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1744 &copied, &added);
1745 diff_free_filespec_data(p->one);
1746 diff_free_filespec_data(p->two);
1747 } else if (DIFF_FILE_VALID(p->one)) {
1748 diff_populate_filespec(p->one, 1);
1749 copied = added = 0;
1750 diff_free_filespec_data(p->one);
1751 } else if (DIFF_FILE_VALID(p->two)) {
1752 diff_populate_filespec(p->two, 1);
1753 copied = 0;
1754 added = p->two->size;
1755 diff_free_filespec_data(p->two);
1756 } else
1757 continue;
1759 /*
1760 * Original minus copied is the removed material,
1761 * added is the new material. They are both damages
1762 * made to the preimage.
1763 * If the resulting damage is zero, we know that
1764 * diffcore_count_changes() considers the two entries to
1765 * be identical, but since content_changed is true, we
1766 * know that there must have been _some_ kind of change,
1767 * so we force all entries to have damage > 0.
1768 */
1769 damage = (p->one->size - copied) + added;
1770 if (!damage)
1771 damage = 1;
1773 found_damage:
1774 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1775 dir.files[dir.nr].name = name;
1776 dir.files[dir.nr].changed = damage;
1777 changed += damage;
1778 dir.nr++;
1779 }
1781 /* This can happen even with many files, if everything was renames */
1782 if (!changed)
1783 return;
1785 /* Show all directories with more than x% of the changes */
1786 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1787 gather_dirstat(options, &dir, changed, "", 0);
1788 }
1790 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
1791 {
1792 int i;
1793 unsigned long changed;
1794 struct dirstat_dir dir;
1796 if (data->nr == 0)
1797 return;
1799 dir.files = NULL;
1800 dir.alloc = 0;
1801 dir.nr = 0;
1802 dir.permille = options->dirstat_permille;
1803 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1805 changed = 0;
1806 for (i = 0; i < data->nr; i++) {
1807 struct diffstat_file *file = data->files[i];
1808 unsigned long damage = file->added + file->deleted;
1809 if (file->is_binary)
1810 /*
1811 * binary files counts bytes, not lines. Must find some
1812 * way to normalize binary bytes vs. textual lines.
1813 * The following heuristic assumes that there are 64
1814 * bytes per "line".
1815 * This is stupid and ugly, but very cheap...
1816 */
1817 damage = (damage + 63) / 64;
1818 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1819 dir.files[dir.nr].name = file->name;
1820 dir.files[dir.nr].changed = damage;
1821 changed += damage;
1822 dir.nr++;
1823 }
1825 /* This can happen even with many files, if everything was renames */
1826 if (!changed)
1827 return;
1829 /* Show all directories with more than x% of the changes */
1830 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1831 gather_dirstat(options, &dir, changed, "", 0);
1832 }
1834 static void free_diffstat_info(struct diffstat_t *diffstat)
1835 {
1836 int i;
1837 for (i = 0; i < diffstat->nr; i++) {
1838 struct diffstat_file *f = diffstat->files[i];
1839 if (f->name != f->print_name)
1840 free(f->print_name);
1841 free(f->name);
1842 free(f->from_name);
1843 free(f);
1844 }
1845 free(diffstat->files);
1846 }
1848 struct checkdiff_t {
1849 const char *filename;
1850 int lineno;
1851 int conflict_marker_size;
1852 struct diff_options *o;
1853 unsigned ws_rule;
1854 unsigned status;
1855 };
1857 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
1858 {
1859 char firstchar;
1860 int cnt;
1862 if (len < marker_size + 1)
1863 return 0;
1864 firstchar = line[0];
1865 switch (firstchar) {
1866 case '=': case '>': case '<': case '|':
1867 break;
1868 default:
1869 return 0;
1870 }
1871 for (cnt = 1; cnt < marker_size; cnt++)
1872 if (line[cnt] != firstchar)
1873 return 0;
1874 /* line[1] thru line[marker_size-1] are same as firstchar */
1875 if (len < marker_size + 1 || !isspace(line[marker_size]))
1876 return 0;
1877 return 1;
1878 }
1880 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1881 {
1882 struct checkdiff_t *data = priv;
1883 int marker_size = data->conflict_marker_size;
1884 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
1885 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
1886 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
1887 char *err;
1888 char *line_prefix = "";
1889 struct strbuf *msgbuf;
1891 assert(data->o);
1892 if (data->o->output_prefix) {
1893 msgbuf = data->o->output_prefix(data->o,
1894 data->o->output_prefix_data);
1895 line_prefix = msgbuf->buf;
1896 }
1898 if (line[0] == '+') {
1899 unsigned bad;
1900 data->lineno++;
1901 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
1902 data->status |= 1;
1903 fprintf(data->o->file,
1904 "%s%s:%d: leftover conflict marker\n",
1905 line_prefix, data->filename, data->lineno);
1906 }
1907 bad = ws_check(line + 1, len - 1, data->ws_rule);
1908 if (!bad)
1909 return;
1910 data->status |= bad;
1911 err = whitespace_error_string(bad);
1912 fprintf(data->o->file, "%s%s:%d: %s.\n",
1913 line_prefix, data->filename, data->lineno, err);
1914 free(err);
1915 emit_line(data->o, set, reset, line, 1);
1916 ws_check_emit(line + 1, len - 1, data->ws_rule,
1917 data->o->file, set, reset, ws);
1918 } else if (line[0] == ' ') {
1919 data->lineno++;
1920 } else if (line[0] == '@') {
1921 char *plus = strchr(line, '+');
1922 if (plus)
1923 data->lineno = strtol(plus, NULL, 10) - 1;
1924 else
1925 die("invalid diff");
1926 }
1927 }
1929 static unsigned char *deflate_it(char *data,
1930 unsigned long size,
1931 unsigned long *result_size)
1932 {
1933 int bound;
1934 unsigned char *deflated;
1935 git_zstream stream;
1937 memset(&stream, 0, sizeof(stream));
1938 git_deflate_init(&stream, zlib_compression_level);
1939 bound = git_deflate_bound(&stream, size);
1940 deflated = xmalloc(bound);
1941 stream.next_out = deflated;
1942 stream.avail_out = bound;
1944 stream.next_in = (unsigned char *)data;
1945 stream.avail_in = size;
1946 while (git_deflate(&stream, Z_FINISH) == Z_OK)
1947 ; /* nothing */
1948 git_deflate_end(&stream);
1949 *result_size = stream.total_out;
1950 return deflated;
1951 }
1953 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two, char *prefix)
1954 {
1955 void *cp;
1956 void *delta;
1957 void *deflated;
1958 void *data;
1959 unsigned long orig_size;
1960 unsigned long delta_size;
1961 unsigned long deflate_size;
1962 unsigned long data_size;
1964 /* We could do deflated delta, or we could do just deflated two,
1965 * whichever is smaller.
1966 */
1967 delta = NULL;
1968 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1969 if (one->size && two->size) {
1970 delta = diff_delta(one->ptr, one->size,
1971 two->ptr, two->size,
1972 &delta_size, deflate_size);
1973 if (delta) {
1974 void *to_free = delta;
1975 orig_size = delta_size;
1976 delta = deflate_it(delta, delta_size, &delta_size);
1977 free(to_free);
1978 }
1979 }
1981 if (delta && delta_size < deflate_size) {
1982 fprintf(file, "%sdelta %lu\n", prefix, orig_size);
1983 free(deflated);
1984 data = delta;
1985 data_size = delta_size;
1986 }
1987 else {
1988 fprintf(file, "%sliteral %lu\n", prefix, two->size);
1989 free(delta);
1990 data = deflated;
1991 data_size = deflate_size;
1992 }
1994 /* emit data encoded in base85 */
1995 cp = data;
1996 while (data_size) {
1997 int bytes = (52 < data_size) ? 52 : data_size;
1998 char line[70];
1999 data_size -= bytes;
2000 if (bytes <= 26)
2001 line[0] = bytes + 'A' - 1;
2002 else
2003 line[0] = bytes - 26 + 'a' - 1;
2004 encode_85(line + 1, cp, bytes);
2005 cp = (char *) cp + bytes;
2006 fprintf(file, "%s", prefix);
2007 fputs(line, file);
2008 fputc('\n', file);
2009 }
2010 fprintf(file, "%s\n", prefix);
2011 free(data);
2012 }
2014 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two, char *prefix)
2015 {
2016 fprintf(file, "%sGIT binary patch\n", prefix);
2017 emit_binary_diff_body(file, one, two, prefix);
2018 emit_binary_diff_body(file, two, one, prefix);
2019 }
2021 static void diff_filespec_load_driver(struct diff_filespec *one)
2022 {
2023 /* Use already-loaded driver */
2024 if (one->driver)
2025 return;
2027 if (S_ISREG(one->mode))
2028 one->driver = userdiff_find_by_path(one->path);
2030 /* Fallback to default settings */
2031 if (!one->driver)
2032 one->driver = userdiff_find_by_name("default");
2033 }
2035 int diff_filespec_is_binary(struct diff_filespec *one)
2036 {
2037 if (one->is_binary == -1) {
2038 diff_filespec_load_driver(one);
2039 if (one->driver->binary != -1)
2040 one->is_binary = one->driver->binary;
2041 else {
2042 if (!one->data && DIFF_FILE_VALID(one))
2043 diff_populate_filespec(one, 0);
2044 if (one->data)
2045 one->is_binary = buffer_is_binary(one->data,
2046 one->size);
2047 if (one->is_binary == -1)
2048 one->is_binary = 0;
2049 }
2050 }
2051 return one->is_binary;
2052 }
2054 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2055 {
2056 diff_filespec_load_driver(one);
2057 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2058 }
2060 static const char *userdiff_word_regex(struct diff_filespec *one)
2061 {
2062 diff_filespec_load_driver(one);
2063 return one->driver->word_regex;
2064 }
2066 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2067 {
2068 if (!options->a_prefix)
2069 options->a_prefix = a;
2070 if (!options->b_prefix)
2071 options->b_prefix = b;
2072 }
2074 struct userdiff_driver *get_textconv(struct diff_filespec *one)
2075 {
2076 if (!DIFF_FILE_VALID(one))
2077 return NULL;
2079 diff_filespec_load_driver(one);
2080 return userdiff_get_textconv(one->driver);
2081 }
2083 static void builtin_diff(const char *name_a,
2084 const char *name_b,
2085 struct diff_filespec *one,
2086 struct diff_filespec *two,
2087 const char *xfrm_msg,
2088 int must_show_header,
2089 struct diff_options *o,
2090 int complete_rewrite)
2091 {
2092 mmfile_t mf1, mf2;
2093 const char *lbl[2];
2094 char *a_one, *b_two;
2095 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
2096 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2097 const char *a_prefix, *b_prefix;
2098 struct userdiff_driver *textconv_one = NULL;
2099 struct userdiff_driver *textconv_two = NULL;
2100 struct strbuf header = STRBUF_INIT;
2101 struct strbuf *msgbuf;
2102 char *line_prefix = "";
2104 if (o->output_prefix) {
2105 msgbuf = o->output_prefix(o, o->output_prefix_data);
2106 line_prefix = msgbuf->buf;
2107 }
2109 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
2110 (!one->mode || S_ISGITLINK(one->mode)) &&
2111 (!two->mode || S_ISGITLINK(two->mode))) {
2112 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2113 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2114 show_submodule_summary(o->file, one ? one->path : two->path,
2115 one->sha1, two->sha1, two->dirty_submodule,
2116 del, add, reset);
2117 return;
2118 }
2120 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2121 textconv_one = get_textconv(one);
2122 textconv_two = get_textconv(two);
2123 }
2125 diff_set_mnemonic_prefix(o, "a/", "b/");
2126 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2127 a_prefix = o->b_prefix;
2128 b_prefix = o->a_prefix;
2129 } else {
2130 a_prefix = o->a_prefix;
2131 b_prefix = o->b_prefix;
2132 }
2134 /* Never use a non-valid filename anywhere if at all possible */
2135 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2136 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2138 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2139 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
2140 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2141 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
2142 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, set, a_one, b_two, reset);
2143 if (lbl[0][0] == '/') {
2144 /* /dev/null */
2145 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, set, two->mode, reset);
2146 if (xfrm_msg)
2147 strbuf_addstr(&header, xfrm_msg);
2148 must_show_header = 1;
2149 }
2150 else if (lbl[1][0] == '/') {
2151 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, set, one->mode, reset);
2152 if (xfrm_msg)
2153 strbuf_addstr(&header, xfrm_msg);
2154 must_show_header = 1;
2155 }
2156 else {
2157 if (one->mode != two->mode) {
2158 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, set, one->mode, reset);
2159 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, set, two->mode, reset);
2160 must_show_header = 1;
2161 }
2162 if (xfrm_msg)
2163 strbuf_addstr(&header, xfrm_msg);
2165 /*
2166 * we do not run diff between different kind
2167 * of objects.
2168 */
2169 if ((one->mode ^ two->mode) & S_IFMT)
2170 goto free_ab_and_return;
2171 if (complete_rewrite &&
2172 (textconv_one || !diff_filespec_is_binary(one)) &&
2173 (textconv_two || !diff_filespec_is_binary(two))) {
2174 fprintf(o->file, "%s", header.buf);
2175 strbuf_reset(&header);
2176 emit_rewrite_diff(name_a, name_b, one, two,
2177 textconv_one, textconv_two, o);
2178 o->found_changes = 1;
2179 goto free_ab_and_return;
2180 }
2181 }
2183 if (o->irreversible_delete && lbl[1][0] == '/') {
2184 fprintf(o->file, "%s", header.buf);
2185 strbuf_reset(&header);
2186 goto free_ab_and_return;
2187 } else if (!DIFF_OPT_TST(o, TEXT) &&
2188 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2189 (!textconv_two && diff_filespec_is_binary(two)) )) {
2190 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2191 die("unable to read files to diff");
2192 /* Quite common confusing case */
2193 if (mf1.size == mf2.size &&
2194 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2195 if (must_show_header)
2196 fprintf(o->file, "%s", header.buf);
2197 goto free_ab_and_return;
2198 }
2199 fprintf(o->file, "%s", header.buf);
2200 strbuf_reset(&header);
2201 if (DIFF_OPT_TST(o, BINARY))
2202 emit_binary_diff(o->file, &mf1, &mf2, line_prefix);
2203 else
2204 fprintf(o->file, "%sBinary files %s and %s differ\n",
2205 line_prefix, lbl[0], lbl[1]);
2206 o->found_changes = 1;
2207 } else {
2208 /* Crazy xdl interfaces.. */
2209 const char *diffopts = getenv("GIT_DIFF_OPTS");
2210 xpparam_t xpp;
2211 xdemitconf_t xecfg;
2212 struct emit_callback ecbdata;
2213 const struct userdiff_funcname *pe;
2215 if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS) || must_show_header) {
2216 fprintf(o->file, "%s", header.buf);
2217 strbuf_reset(&header);
2218 }
2220 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2221 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
2223 pe = diff_funcname_pattern(one);
2224 if (!pe)
2225 pe = diff_funcname_pattern(two);
2227 memset(&xpp, 0, sizeof(xpp));
2228 memset(&xecfg, 0, sizeof(xecfg));
2229 memset(&ecbdata, 0, sizeof(ecbdata));
2230 ecbdata.label_path = lbl;
2231 ecbdata.color_diff = want_color(o->use_color);
2232 ecbdata.found_changesp = &o->found_changes;
2233 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
2234 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
2235 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2236 ecbdata.opt = o;
2237 ecbdata.header = header.len ? &header : NULL;
2238 xpp.flags = o->xdl_opts;
2239 xecfg.ctxlen = o->context;
2240 xecfg.interhunkctxlen = o->interhunkcontext;
2241 xecfg.flags = XDL_EMIT_FUNCNAMES;
2242 if (DIFF_OPT_TST(o, FUNCCONTEXT))
2243 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
2244 if (pe)
2245 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
2246 if (!diffopts)
2247 ;
2248 else if (!prefixcmp(diffopts, "--unified="))
2249 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
2250 else if (!prefixcmp(diffopts, "-u"))
2251 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
2252 if (o->word_diff) {
2253 int i;
2255 ecbdata.diff_words =
2256 xcalloc(1, sizeof(struct diff_words_data));
2257 ecbdata.diff_words->type = o->word_diff;
2258 ecbdata.diff_words->opt = o;
2259 if (!o->word_regex)
2260 o->word_regex = userdiff_word_regex(one);
2261 if (!o->word_regex)
2262 o->word_regex = userdiff_word_regex(two);
2263 if (!o->word_regex)
2264 o->word_regex = diff_word_regex_cfg;
2265 if (o->word_regex) {
2266 ecbdata.diff_words->word_regex = (regex_t *)
2267 xmalloc(sizeof(regex_t));
2268 if (regcomp(ecbdata.diff_words->word_regex,
2269 o->word_regex,
2270 REG_EXTENDED | REG_NEWLINE))
2271 die ("Invalid regular expression: %s",
2272 o->word_regex);
2273 }
2274 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2275 if (o->word_diff == diff_words_styles[i].type) {
2276 ecbdata.diff_words->style =
2277 &diff_words_styles[i];
2278 break;
2279 }
2280 }
2281 if (want_color(o->use_color)) {
2282 struct diff_words_style *st = ecbdata.diff_words->style;
2283 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2284 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2285 st->ctx.color = diff_get_color_opt(o, DIFF_PLAIN);
2286 }
2287 }
2288 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2289 &xpp, &xecfg);
2290 if (o->word_diff)
2291 free_diff_words_data(&ecbdata);
2292 if (textconv_one)
2293 free(mf1.ptr);
2294 if (textconv_two)
2295 free(mf2.ptr);
2296 xdiff_clear_find_func(&xecfg);
2297 }
2299 free_ab_and_return:
2300 strbuf_release(&header);
2301 diff_free_filespec_data(one);
2302 diff_free_filespec_data(two);
2303 free(a_one);
2304 free(b_two);
2305 return;
2306 }
2308 static void builtin_diffstat(const char *name_a, const char *name_b,
2309 struct diff_filespec *one,
2310 struct diff_filespec *two,
2311 struct diffstat_t *diffstat,
2312 struct diff_options *o,
2313 int complete_rewrite)
2314 {
2315 mmfile_t mf1, mf2;
2316 struct diffstat_file *data;
2318 data = diffstat_add(diffstat, name_a, name_b);
2320 if (!one || !two) {
2321 data->is_unmerged = 1;
2322 return;
2323 }
2325 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2326 data->is_binary = 1;
2327 data->added = diff_filespec_size(two);
2328 data->deleted = diff_filespec_size(one);
2329 }
2331 else if (complete_rewrite) {
2332 diff_populate_filespec(one, 0);
2333 diff_populate_filespec(two, 0);
2334 data->deleted = count_lines(one->data, one->size);
2335 data->added = count_lines(two->data, two->size);
2336 }
2338 else {
2339 /* Crazy xdl interfaces.. */
2340 xpparam_t xpp;
2341 xdemitconf_t xecfg;
2343 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2344 die("unable to read files to diff");
2346 memset(&xpp, 0, sizeof(xpp));
2347 memset(&xecfg, 0, sizeof(xecfg));
2348 xpp.flags = o->xdl_opts;
2349 xecfg.ctxlen = o->context;
2350 xecfg.interhunkctxlen = o->interhunkcontext;
2351 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2352 &xpp, &xecfg);
2353 }
2355 diff_free_filespec_data(one);
2356 diff_free_filespec_data(two);
2357 }
2359 static void builtin_checkdiff(const char *name_a, const char *name_b,
2360 const char *attr_path,
2361 struct diff_filespec *one,
2362 struct diff_filespec *two,
2363 struct diff_options *o)
2364 {
2365 mmfile_t mf1, mf2;
2366 struct checkdiff_t data;
2368 if (!two)
2369 return;
2371 memset(&data, 0, sizeof(data));
2372 data.filename = name_b ? name_b : name_a;
2373 data.lineno = 0;
2374 data.o = o;
2375 data.ws_rule = whitespace_rule(attr_path);
2376 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2378 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2379 die("unable to read files to diff");
2381 /*
2382 * All the other codepaths check both sides, but not checking
2383 * the "old" side here is deliberate. We are checking the newly
2384 * introduced changes, and as long as the "new" side is text, we
2385 * can and should check what it introduces.
2386 */
2387 if (diff_filespec_is_binary(two))
2388 goto free_and_return;
2389 else {
2390 /* Crazy xdl interfaces.. */
2391 xpparam_t xpp;
2392 xdemitconf_t xecfg;
2394 memset(&xpp, 0, sizeof(xpp));
2395 memset(&xecfg, 0, sizeof(xecfg));
2396 xecfg.ctxlen = 1; /* at least one context line */
2397 xpp.flags = 0;
2398 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2399 &xpp, &xecfg);
2401 if (data.ws_rule & WS_BLANK_AT_EOF) {
2402 struct emit_callback ecbdata;
2403 int blank_at_eof;
2405 ecbdata.ws_rule = data.ws_rule;
2406 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2407 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
2409 if (blank_at_eof) {
2410 static char *err;
2411 if (!err)
2412 err = whitespace_error_string(WS_BLANK_AT_EOF);
2413 fprintf(o->file, "%s:%d: %s.\n",
2414 data.filename, blank_at_eof, err);
2415 data.status = 1; /* report errors */
2416 }
2417 }
2418 }
2419 free_and_return:
2420 diff_free_filespec_data(one);
2421 diff_free_filespec_data(two);
2422 if (data.status)
2423 DIFF_OPT_SET(o, CHECK_FAILED);
2424 }
2426 struct diff_filespec *alloc_filespec(const char *path)
2427 {
2428 int namelen = strlen(path);
2429 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
2431 memset(spec, 0, sizeof(*spec));
2432 spec->path = (char *)(spec + 1);
2433 memcpy(spec->path, path, namelen+1);
2434 spec->count = 1;
2435 spec->is_binary = -1;
2436 return spec;
2437 }
2439 void free_filespec(struct diff_filespec *spec)
2440 {
2441 if (!--spec->count) {
2442 diff_free_filespec_data(spec);
2443 free(spec);
2444 }
2445 }
2447 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
2448 unsigned short mode)
2449 {
2450 if (mode) {
2451 spec->mode = canon_mode(mode);
2452 hashcpy(spec->sha1, sha1);
2453 spec->sha1_valid = !is_null_sha1(sha1);
2454 }
2455 }
2457 /*
2458 * Given a name and sha1 pair, if the index tells us the file in
2459 * the work tree has that object contents, return true, so that
2460 * prepare_temp_file() does not have to inflate and extract.
2461 */
2462 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2463 {
2464 struct cache_entry *ce;
2465 struct stat st;
2466 int pos, len;
2468 /*
2469 * We do not read the cache ourselves here, because the
2470 * benchmark with my previous version that always reads cache
2471 * shows that it makes things worse for diff-tree comparing
2472 * two linux-2.6 kernel trees in an already checked out work
2473 * tree. This is because most diff-tree comparisons deal with
2474 * only a small number of files, while reading the cache is
2475 * expensive for a large project, and its cost outweighs the
2476 * savings we get by not inflating the object to a temporary
2477 * file. Practically, this code only helps when we are used
2478 * by diff-cache --cached, which does read the cache before
2479 * calling us.
2480 */
2481 if (!active_cache)
2482 return 0;
2484 /* We want to avoid the working directory if our caller
2485 * doesn't need the data in a normal file, this system
2486 * is rather slow with its stat/open/mmap/close syscalls,
2487 * and the object is contained in a pack file. The pack
2488 * is probably already open and will be faster to obtain
2489 * the data through than the working directory. Loose
2490 * objects however would tend to be slower as they need
2491 * to be individually opened and inflated.
2492 */
2493 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2494 return 0;
2496 len = strlen(name);
2497 pos = cache_name_pos(name, len);
2498 if (pos < 0)
2499 return 0;
2500 ce = active_cache[pos];
2502 /*
2503 * This is not the sha1 we are looking for, or
2504 * unreusable because it is not a regular file.
2505 */
2506 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
2507 return 0;
2509 /*
2510 * If ce is marked as "assume unchanged", there is no
2511 * guarantee that work tree matches what we are looking for.
2512 */
2513 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2514 return 0;
2516 /*
2517 * If ce matches the file in the work tree, we can reuse it.
2518 */
2519 if (ce_uptodate(ce) ||
2520 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2521 return 1;
2523 return 0;
2524 }
2526 static int populate_from_stdin(struct diff_filespec *s)
2527 {
2528 struct strbuf buf = STRBUF_INIT;
2529 size_t size = 0;
2531 if (strbuf_read(&buf, 0, 0) < 0)
2532 return error("error while reading from stdin %s",
2533 strerror(errno));
2535 s->should_munmap = 0;
2536 s->data = strbuf_detach(&buf, &size);
2537 s->size = size;
2538 s->should_free = 1;
2539 return 0;
2540 }
2542 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2543 {
2544 int len;
2545 char *data = xmalloc(100), *dirty = "";
2547 /* Are we looking at the work tree? */
2548 if (s->dirty_submodule)
2549 dirty = "-dirty";
2551 len = snprintf(data, 100,
2552 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2553 s->data = data;
2554 s->size = len;
2555 s->should_free = 1;
2556 if (size_only) {
2557 s->data = NULL;
2558 free(data);
2559 }
2560 return 0;
2561 }
2563 /*
2564 * While doing rename detection and pickaxe operation, we may need to
2565 * grab the data for the blob (or file) for our own in-core comparison.
2566 * diff_filespec has data and size fields for this purpose.
2567 */
2568 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2569 {
2570 int err = 0;
2571 if (!DIFF_FILE_VALID(s))
2572 die("internal error: asking to populate invalid file.");
2573 if (S_ISDIR(s->mode))
2574 return -1;
2576 if (s->data)
2577 return 0;
2579 if (size_only && 0 < s->size)
2580 return 0;
2582 if (S_ISGITLINK(s->mode))
2583 return diff_populate_gitlink(s, size_only);
2585 if (!s->sha1_valid ||
2586 reuse_worktree_file(s->path, s->sha1, 0)) {
2587 struct strbuf buf = STRBUF_INIT;
2588 struct stat st;
2589 int fd;
2591 if (!strcmp(s->path, "-"))
2592 return populate_from_stdin(s);
2594 if (lstat(s->path, &st) < 0) {
2595 if (errno == ENOENT) {
2596 err_empty:
2597 err = -1;
2598 empty:
2599 s->data = (char *)"";
2600 s->size = 0;
2601 return err;
2602 }
2603 }
2604 s->size = xsize_t(st.st_size);
2605 if (!s->size)
2606 goto empty;
2607 if (S_ISLNK(st.st_mode)) {
2608 struct strbuf sb = STRBUF_INIT;
2610 if (strbuf_readlink(&sb, s->path, s->size))
2611 goto err_empty;
2612 s->size = sb.len;
2613 s->data = strbuf_detach(&sb, NULL);
2614 s->should_free = 1;
2615 return 0;
2616 }
2617 if (size_only)
2618 return 0;
2619 fd = open(s->path, O_RDONLY);
2620 if (fd < 0)
2621 goto err_empty;
2622 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2623 close(fd);
2624 s->should_munmap = 1;
2626 /*
2627 * Convert from working tree format to canonical git format
2628 */
2629 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2630 size_t size = 0;
2631 munmap(s->data, s->size);
2632 s->should_munmap = 0;
2633 s->data = strbuf_detach(&buf, &size);
2634 s->size = size;
2635 s->should_free = 1;
2636 }
2637 }
2638 else {
2639 enum object_type type;
2640 if (size_only) {
2641 type = sha1_object_info(s->sha1, &s->size);
2642 if (type < 0)
2643 die("unable to read %s", sha1_to_hex(s->sha1));
2644 } else {
2645 s->data = read_sha1_file(s->sha1, &type, &s->size);
2646 if (!s->data)
2647 die("unable to read %s", sha1_to_hex(s->sha1));
2648 s->should_free = 1;
2649 }
2650 }
2651 return 0;
2652 }
2654 void diff_free_filespec_blob(struct diff_filespec *s)
2655 {
2656 if (s->should_free)
2657 free(s->data);
2658 else if (s->should_munmap)
2659 munmap(s->data, s->size);
2661 if (s->should_free || s->should_munmap) {
2662 s->should_free = s->should_munmap = 0;
2663 s->data = NULL;
2664 }
2665 }
2667 void diff_free_filespec_data(struct diff_filespec *s)
2668 {
2669 diff_free_filespec_blob(s);
2670 free(s->cnt_data);
2671 s->cnt_data = NULL;
2672 }
2674 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2675 void *blob,
2676 unsigned long size,
2677 const unsigned char *sha1,
2678 int mode)
2679 {
2680 int fd;
2681 struct strbuf buf = STRBUF_INIT;
2682 struct strbuf template = STRBUF_INIT;
2683 char *path_dup = xstrdup(path);
2684 const char *base = basename(path_dup);
2686 /* Generate "XXXXXX_basename.ext" */
2687 strbuf_addstr(&template, "XXXXXX_");
2688 strbuf_addstr(&template, base);
2690 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2691 strlen(base) + 1);
2692 if (fd < 0)
2693 die_errno("unable to create temp-file");
2694 if (convert_to_working_tree(path,
2695 (const char *)blob, (size_t)size, &buf)) {
2696 blob = buf.buf;
2697 size = buf.len;
2698 }
2699 if (write_in_full(fd, blob, size) != size)
2700 die_errno("unable to write temp-file");
2701 close(fd);
2702 temp->name = temp->tmp_path;
2703 strcpy(temp->hex, sha1_to_hex(sha1));
2704 temp->hex[40] = 0;
2705 sprintf(temp->mode, "%06o", mode);
2706 strbuf_release(&buf);
2707 strbuf_release(&template);
2708 free(path_dup);
2709 }
2711 static struct diff_tempfile *prepare_temp_file(const char *name,
2712 struct diff_filespec *one)
2713 {
2714 struct diff_tempfile *temp = claim_diff_tempfile();
2716 if (!DIFF_FILE_VALID(one)) {
2717 not_a_valid_file:
2718 /* A '-' entry produces this for file-2, and
2719 * a '+' entry produces this for file-1.
2720 */
2721 temp->name = "/dev/null";
2722 strcpy(temp->hex, ".");
2723 strcpy(temp->mode, ".");
2724 return temp;
2725 }
2727 if (!remove_tempfile_installed) {
2728 atexit(remove_tempfile);
2729 sigchain_push_common(remove_tempfile_on_signal);
2730 remove_tempfile_installed = 1;
2731 }
2733 if (!one->sha1_valid ||
2734 reuse_worktree_file(name, one->sha1, 1)) {
2735 struct stat st;
2736 if (lstat(name, &st) < 0) {
2737 if (errno == ENOENT)
2738 goto not_a_valid_file;
2739 die_errno("stat(%s)", name);
2740 }
2741 if (S_ISLNK(st.st_mode)) {
2742 struct strbuf sb = STRBUF_INIT;
2743 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2744 die_errno("readlink(%s)", name);
2745 prep_temp_blob(name, temp, sb.buf, sb.len,
2746 (one->sha1_valid ?
2747 one->sha1 : null_sha1),
2748 (one->sha1_valid ?
2749 one->mode : S_IFLNK));
2750 strbuf_release(&sb);
2751 }
2752 else {
2753 /* we can borrow from the file in the work tree */
2754 temp->name = name;
2755 if (!one->sha1_valid)
2756 strcpy(temp->hex, sha1_to_hex(null_sha1));
2757 else
2758 strcpy(temp->hex, sha1_to_hex(one->sha1));
2759 /* Even though we may sometimes borrow the
2760 * contents from the work tree, we always want
2761 * one->mode. mode is trustworthy even when
2762 * !(one->sha1_valid), as long as
2763 * DIFF_FILE_VALID(one).
2764 */
2765 sprintf(temp->mode, "%06o", one->mode);
2766 }
2767 return temp;
2768 }
2769 else {
2770 if (diff_populate_filespec(one, 0))
2771 die("cannot read data blob for %s", one->path);
2772 prep_temp_blob(name, temp, one->data, one->size,
2773 one->sha1, one->mode);
2774 }
2775 return temp;
2776 }
2778 /* An external diff command takes:
2779 *
2780 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2781 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2782 *
2783 */
2784 static void run_external_diff(const char *pgm,
2785 const char *name,
2786 const char *other,
2787 struct diff_filespec *one,
2788 struct diff_filespec *two,
2789 const char *xfrm_msg,
2790 int complete_rewrite)
2791 {
2792 const char *spawn_arg[10];
2793 int retval;
2794 const char **arg = &spawn_arg[0];
2796 if (one && two) {
2797 struct diff_tempfile *temp_one, *temp_two;
2798 const char *othername = (other ? other : name);
2799 temp_one = prepare_temp_file(name, one);
2800 temp_two = prepare_temp_file(othername, two);
2801 *arg++ = pgm;
2802 *arg++ = name;
2803 *arg++ = temp_one->name;
2804 *arg++ = temp_one->hex;
2805 *arg++ = temp_one->mode;
2806 *arg++ = temp_two->name;
2807 *arg++ = temp_two->hex;
2808 *arg++ = temp_two->mode;
2809 if (other) {
2810 *arg++ = other;
2811 *arg++ = xfrm_msg;
2812 }
2813 } else {
2814 *arg++ = pgm;
2815 *arg++ = name;
2816 }
2817 *arg = NULL;
2818 fflush(NULL);
2819 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2820 remove_tempfile();
2821 if (retval) {
2822 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2823 exit(1);
2824 }
2825 }
2827 static int similarity_index(struct diff_filepair *p)
2828 {
2829 return p->score * 100 / MAX_SCORE;
2830 }
2832 static void fill_metainfo(struct strbuf *msg,
2833 const char *name,
2834 const char *other,
2835 struct diff_filespec *one,
2836 struct diff_filespec *two,
2837 struct diff_options *o,
2838 struct diff_filepair *p,
2839 int *must_show_header,
2840 int use_color)
2841 {
2842 const char *set = diff_get_color(use_color, DIFF_METAINFO);
2843 const char *reset = diff_get_color(use_color, DIFF_RESET);
2844 struct strbuf *msgbuf;
2845 char *line_prefix = "";
2847 *must_show_header = 1;
2848 if (o->output_prefix) {
2849 msgbuf = o->output_prefix(o, o->output_prefix_data);
2850 line_prefix = msgbuf->buf;
2851 }
2852 strbuf_init(msg, PATH_MAX * 2 + 300);
2853 switch (p->status) {
2854 case DIFF_STATUS_COPIED:
2855 strbuf_addf(msg, "%s%ssimilarity index %d%%",
2856 line_prefix, set, similarity_index(p));
2857 strbuf_addf(msg, "%s\n%s%scopy from ",
2858 reset, line_prefix, set);
2859 quote_c_style(name, msg, NULL, 0);
2860 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
2861 quote_c_style(other, msg, NULL, 0);
2862 strbuf_addf(msg, "%s\n", reset);
2863 break;
2864 case DIFF_STATUS_RENAMED:
2865 strbuf_addf(msg, "%s%ssimilarity index %d%%",
2866 line_prefix, set, similarity_index(p));
2867 strbuf_addf(msg, "%s\n%s%srename from ",
2868 reset, line_prefix, set);
2869 quote_c_style(name, msg, NULL, 0);
2870 strbuf_addf(msg, "%s\n%s%srename to ",
2871 reset, line_prefix, set);
2872 quote_c_style(other, msg, NULL, 0);
2873 strbuf_addf(msg, "%s\n", reset);
2874 break;
2875 case DIFF_STATUS_MODIFIED:
2876 if (p->score) {
2877 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
2878 line_prefix,
2879 set, similarity_index(p), reset);
2880 break;
2881 }
2882 /* fallthru */
2883 default:
2884 *must_show_header = 0;
2885 }
2886 if (one && two && hashcmp(one->sha1, two->sha1)) {
2887 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2889 if (DIFF_OPT_TST(o, BINARY)) {
2890 mmfile_t mf;
2891 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2892 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2893 abbrev = 40;
2894 }
2895 strbuf_addf(msg, "%s%sindex %s..", line_prefix, set,
2896 find_unique_abbrev(one->sha1, abbrev));
2897 strbuf_addstr(msg, find_unique_abbrev(two->sha1, abbrev));
2898 if (one->mode == two->mode)
2899 strbuf_addf(msg, " %06o", one->mode);
2900 strbuf_addf(msg, "%s\n", reset);
2901 }
2902 }
2904 static void run_diff_cmd(const char *pgm,
2905 const char *name,
2906 const char *other,
2907 const char *attr_path,
2908 struct diff_filespec *one,
2909 struct diff_filespec *two,
2910 struct strbuf *msg,
2911 struct diff_options *o,
2912 struct diff_filepair *p)
2913 {
2914 const char *xfrm_msg = NULL;
2915 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2916 int must_show_header = 0;
2918 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2919 pgm = NULL;
2920 else {
2921 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2922 if (drv && drv->external)
2923 pgm = drv->external;
2924 }
2926 if (msg) {
2927 /*
2928 * don't use colors when the header is intended for an
2929 * external diff driver
2930 */
2931 fill_metainfo(msg, name, other, one, two, o, p,
2932 &must_show_header,
2933 want_color(o->use_color) && !pgm);
2934 xfrm_msg = msg->len ? msg->buf : NULL;
2935 }
2937 if (pgm) {
2938 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2939 complete_rewrite);
2940 return;
2941 }
2942 if (one && two)
2943 builtin_diff(name, other ? other : name,
2944 one, two, xfrm_msg, must_show_header,
2945 o, complete_rewrite);
2946 else
2947 fprintf(o->file, "* Unmerged path %s\n", name);
2948 }
2950 static void diff_fill_sha1_info(struct diff_filespec *one)
2951 {
2952 if (DIFF_FILE_VALID(one)) {
2953 if (!one->sha1_valid) {
2954 struct stat st;
2955 if (!strcmp(one->path, "-")) {
2956 hashcpy(one->sha1, null_sha1);
2957 return;
2958 }
2959 if (lstat(one->path, &st) < 0)
2960 die_errno("stat '%s'", one->path);
2961 if (index_path(one->sha1, one->path, &st, 0))
2962 die("cannot hash %s", one->path);
2963 }
2964 }
2965 else
2966 hashclr(one->sha1);
2967 }
2969 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2970 {
2971 /* Strip the prefix but do not molest /dev/null and absolute paths */
2972 if (*namep && **namep != '/') {
2973 *namep += prefix_length;
2974 if (**namep == '/')
2975 ++*namep;
2976 }
2977 if (*otherp && **otherp != '/') {
2978 *otherp += prefix_length;
2979 if (**otherp == '/')
2980 ++*otherp;
2981 }
2982 }
2984 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2985 {
2986 const char *pgm = external_diff();
2987 struct strbuf msg;
2988 struct diff_filespec *one = p->one;
2989 struct diff_filespec *two = p->two;
2990 const char *name;
2991 const char *other;
2992 const char *attr_path;
2994 name = p->one->path;
2995 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2996 attr_path = name;
2997 if (o->prefix_length)
2998 strip_prefix(o->prefix_length, &name, &other);
3000 if (DIFF_PAIR_UNMERGED(p)) {
3001 run_diff_cmd(pgm, name, NULL, attr_path,
3002 NULL, NULL, NULL, o, p);
3003 return;
3004 }
3006 diff_fill_sha1_info(one);
3007 diff_fill_sha1_info(two);
3009 if (!pgm &&
3010 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3011 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3012 /*
3013 * a filepair that changes between file and symlink
3014 * needs to be split into deletion and creation.
3015 */
3016 struct diff_filespec *null = alloc_filespec(two->path);
3017 run_diff_cmd(NULL, name, other, attr_path,
3018 one, null, &msg, o, p);
3019 free(null);
3020 strbuf_release(&msg);
3022 null = alloc_filespec(one->path);
3023 run_diff_cmd(NULL, name, other, attr_path,
3024 null, two, &msg, o, p);
3025 free(null);
3026 }
3027 else
3028 run_diff_cmd(pgm, name, other, attr_path,
3029 one, two, &msg, o, p);
3031 strbuf_release(&msg);
3032 }
3034 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3035 struct diffstat_t *diffstat)
3036 {
3037 const char *name;
3038 const char *other;
3039 int complete_rewrite = 0;
3041 if (DIFF_PAIR_UNMERGED(p)) {
3042 /* unmerged */
3043 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
3044 return;
3045 }
3047 name = p->one->path;
3048 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3050 if (o->prefix_length)
3051 strip_prefix(o->prefix_length, &name, &other);
3053 diff_fill_sha1_info(p->one);
3054 diff_fill_sha1_info(p->two);
3056 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3057 complete_rewrite = 1;
3058 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
3059 }
3061 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3062 {
3063 const char *name;
3064 const char *other;
3065 const char *attr_path;
3067 if (DIFF_PAIR_UNMERGED(p)) {
3068 /* unmerged */
3069 return;
3070 }
3072 name = p->one->path;
3073 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3074 attr_path = other ? other : name;
3076 if (o->prefix_length)
3077 strip_prefix(o->prefix_length, &name, &other);
3079 diff_fill_sha1_info(p->one);
3080 diff_fill_sha1_info(p->two);
3082 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
3083 }
3085 void diff_setup(struct diff_options *options)
3086 {
3087 memcpy(options, &default_diff_options, sizeof(*options));
3089 options->file = stdout;
3091 options->line_termination = '\n';
3092 options->break_opt = -1;
3093 options->rename_limit = -1;
3094 options->dirstat_permille = diff_dirstat_permille_default;
3095 options->context = 3;
3097 options->change = diff_change;
3098 options->add_remove = diff_addremove;
3099 options->use_color = diff_use_color_default;
3100 options->detect_rename = diff_detect_rename_default;
3102 if (diff_no_prefix) {
3103 options->a_prefix = options->b_prefix = "";
3104 } else if (!diff_mnemonic_prefix) {
3105 options->a_prefix = "a/";
3106 options->b_prefix = "b/";
3107 }
3108 }
3110 int diff_setup_done(struct diff_options *options)
3111 {
3112 int count = 0;
3114 if (options->output_format & DIFF_FORMAT_NAME)
3115 count++;
3116 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3117 count++;
3118 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3119 count++;
3120 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3121 count++;
3122 if (count > 1)
3123 die("--name-only, --name-status, --check and -s are mutually exclusive");
3125 /*
3126 * Most of the time we can say "there are changes"
3127 * only by checking if there are changed paths, but
3128 * --ignore-whitespace* options force us to look
3129 * inside contents.
3130 */
3132 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3133 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3134 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3135 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3136 else
3137 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3139 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3140 options->detect_rename = DIFF_DETECT_COPY;
3142 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3143 options->prefix = NULL;
3144 if (options->prefix)
3145 options->prefix_length = strlen(options->prefix);
3146 else
3147 options->prefix_length = 0;
3149 if (options->output_format & (DIFF_FORMAT_NAME |
3150 DIFF_FORMAT_NAME_STATUS |
3151 DIFF_FORMAT_CHECKDIFF |
3152 DIFF_FORMAT_NO_OUTPUT))
3153 options->output_format &= ~(DIFF_FORMAT_RAW |
3154 DIFF_FORMAT_NUMSTAT |
3155 DIFF_FORMAT_DIFFSTAT |
3156 DIFF_FORMAT_SHORTSTAT |
3157 DIFF_FORMAT_DIRSTAT |
3158 DIFF_FORMAT_SUMMARY |
3159 DIFF_FORMAT_PATCH);
3161 /*
3162 * These cases always need recursive; we do not drop caller-supplied
3163 * recursive bits for other formats here.
3164 */
3165 if (options->output_format & (DIFF_FORMAT_PATCH |
3166 DIFF_FORMAT_NUMSTAT |
3167 DIFF_FORMAT_DIFFSTAT |
3168 DIFF_FORMAT_SHORTSTAT |
3169 DIFF_FORMAT_DIRSTAT |
3170 DIFF_FORMAT_SUMMARY |
3171 DIFF_FORMAT_CHECKDIFF))
3172 DIFF_OPT_SET(options, RECURSIVE);
3173 /*
3174 * Also pickaxe would not work very well if you do not say recursive
3175 */
3176 if (options->pickaxe)
3177 DIFF_OPT_SET(options, RECURSIVE);
3178 /*
3179 * When patches are generated, submodules diffed against the work tree
3180 * must be checked for dirtiness too so it can be shown in the output
3181 */
3182 if (options->output_format & DIFF_FORMAT_PATCH)
3183 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
3185 if (options->detect_rename && options->rename_limit < 0)
3186 options->rename_limit = diff_rename_limit_default;
3187 if (options->setup & DIFF_SETUP_USE_CACHE) {
3188 if (!active_cache)
3189 /* read-cache does not die even when it fails
3190 * so it is safe for us to do this here. Also
3191 * it does not smudge active_cache or active_nr
3192 * when it fails, so we do not have to worry about
3193 * cleaning it up ourselves either.
3194 */
3195 read_cache();
3196 }
3197 if (options->abbrev <= 0 || 40 < options->abbrev)
3198 options->abbrev = 40; /* full */
3200 /*
3201 * It does not make sense to show the first hit we happened
3202 * to have found. It does not make sense not to return with
3203 * exit code in such a case either.
3204 */
3205 if (DIFF_OPT_TST(options, QUICK)) {
3206 options->output_format = DIFF_FORMAT_NO_OUTPUT;
3207 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3208 }
3210 return 0;
3211 }
3213 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
3214 {
3215 char c, *eq;
3216 int len;
3218 if (*arg != '-')
3219 return 0;
3220 c = *++arg;
3221 if (!c)
3222 return 0;
3223 if (c == arg_short) {
3224 c = *++arg;
3225 if (!c)
3226 return 1;
3227 if (val && isdigit(c)) {
3228 char *end;
3229 int n = strtoul(arg, &end, 10);
3230 if (*end)
3231 return 0;
3232 *val = n;
3233 return 1;
3234 }
3235 return 0;
3236 }
3237 if (c != '-')
3238 return 0;
3239 arg++;
3240 eq = strchr(arg, '=');
3241 if (eq)
3242 len = eq - arg;
3243 else
3244 len = strlen(arg);
3245 if (!len || strncmp(arg, arg_long, len))
3246 return 0;
3247 if (eq) {
3248 int n;
3249 char *end;
3250 if (!isdigit(*++eq))
3251 return 0;
3252 n = strtoul(eq, &end, 10);
3253 if (*end)
3254 return 0;
3255 *val = n;
3256 }
3257 return 1;
3258 }
3260 static int diff_scoreopt_parse(const char *opt);
3262 static inline int short_opt(char opt, const char **argv,
3263 const char **optarg)
3264 {
3265 const char *arg = argv[0];
3266 if (arg[0] != '-' || arg[1] != opt)
3267 return 0;
3268 if (arg[2] != '\0') {
3269 *optarg = arg + 2;
3270 return 1;
3271 }
3272 if (!argv[1])
3273 die("Option '%c' requires a value", opt);
3274 *optarg = argv[1];
3275 return 2;
3276 }
3278 int parse_long_opt(const char *opt, const char **argv,
3279 const char **optarg)
3280 {
3281 const char *arg = argv[0];
3282 if (arg[0] != '-' || arg[1] != '-')
3283 return 0;
3284 arg += strlen("--");
3285 if (prefixcmp(arg, opt))
3286 return 0;
3287 arg += strlen(opt);
3288 if (*arg == '=') { /* sticked form: --option=value */
3289 *optarg = arg + 1;
3290 return 1;
3291 }
3292 if (*arg != '\0')
3293 return 0;
3294 /* separate form: --option value */
3295 if (!argv[1])
3296 die("Option '--%s' requires a value", opt);
3297 *optarg = argv[1];
3298 return 2;
3299 }
3301 static int stat_opt(struct diff_options *options, const char **av)
3302 {
3303 const char *arg = av[0];
3304 char *end;
3305 int width = options->stat_width;
3306 int name_width = options->stat_name_width;
3307 int graph_width = options->stat_graph_width;
3308 int count = options->stat_count;
3309 int argcount = 1;
3311 arg += strlen("--stat");
3312 end = (char *)arg;
3314 switch (*arg) {
3315 case '-':
3316 if (!prefixcmp(arg, "-width")) {
3317 arg += strlen("-width");
3318 if (*arg == '=')
3319 width = strtoul(arg + 1, &end, 10);
3320 else if (!*arg && !av[1])
3321 die("Option '--stat-width' requires a value");
3322 else if (!*arg) {
3323 width = strtoul(av[1], &end, 10);
3324 argcount = 2;
3325 }
3326 } else if (!prefixcmp(arg, "-name-width")) {
3327 arg += strlen("-name-width");
3328 if (*arg == '=')
3329 name_width = strtoul(arg + 1, &end, 10);
3330 else if (!*arg && !av[1])
3331 die("Option '--stat-name-width' requires a value");
3332 else if (!*arg) {
3333 name_width = strtoul(av[1], &end, 10);
3334 argcount = 2;
3335 }
3336 } else if (!prefixcmp(arg, "-graph-width")) {
3337 arg += strlen("-graph-width");
3338 if (*arg == '=')
3339 graph_width = strtoul(arg + 1, &end, 10);
3340 else if (!*arg && !av[1])
3341 die("Option '--stat-graph-width' requires a value");
3342 else if (!*arg) {
3343 graph_width = strtoul(av[1], &end, 10);
3344 argcount = 2;
3345 }
3346 } else if (!prefixcmp(arg, "-count")) {
3347 arg += strlen("-count");
3348 if (*arg == '=')
3349 count = strtoul(arg + 1, &end, 10);
3350 else if (!*arg && !av[1])
3351 die("Option '--stat-count' requires a value");
3352 else if (!*arg) {
3353 count = strtoul(av[1], &end, 10);
3354 argcount = 2;
3355 }
3356 }
3357 break;
3358 case '=':
3359 width = strtoul(arg+1, &end, 10);
3360 if (*end == ',')
3361 name_width = strtoul(end+1, &end, 10);
3362 if (*end == ',')
3363 count = strtoul(end+1, &end, 10);
3364 }
3366 /* Important! This checks all the error cases! */
3367 if (*end)
3368 return 0;
3369 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3370 options->stat_name_width = name_width;
3371 options->stat_graph_width = graph_width;
3372 options->stat_width = width;
3373 options->stat_count = count;
3374 return argcount;
3375 }
3377 static int parse_dirstat_opt(struct diff_options *options, const char *params)
3378 {
3379 struct strbuf errmsg = STRBUF_INIT;
3380 if (parse_dirstat_params(options, params, &errmsg))
3381 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
3382 errmsg.buf);
3383 strbuf_release(&errmsg);
3384 /*
3385 * The caller knows a dirstat-related option is given from the command
3386 * line; allow it to say "return this_function();"
3387 */
3388 options->output_format |= DIFF_FORMAT_DIRSTAT;
3389 return 1;
3390 }
3392 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
3393 {
3394 const char *arg = av[0];
3395 const char *optarg;
3396 int argcount;
3398 /* Output format options */
3399 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch"))
3400 options->output_format |= DIFF_FORMAT_PATCH;
3401 else if (opt_arg(arg, 'U', "unified", &options->context))
3402 options->output_format |= DIFF_FORMAT_PATCH;
3403 else if (!strcmp(arg, "--raw"))
3404 options->output_format |= DIFF_FORMAT_RAW;
3405 else if (!strcmp(arg, "--patch-with-raw"))
3406 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
3407 else if (!strcmp(arg, "--numstat"))
3408 options->output_format |= DIFF_FORMAT_NUMSTAT;
3409 else if (!strcmp(arg, "--shortstat"))
3410 options->output_format |= DIFF_FORMAT_SHORTSTAT;
3411 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
3412 return parse_dirstat_opt(options, "");
3413 else if (!prefixcmp(arg, "-X"))
3414 return parse_dirstat_opt(options, arg + 2);
3415 else if (!prefixcmp(arg, "--dirstat="))
3416 return parse_dirstat_opt(options, arg + 10);
3417 else if (!strcmp(arg, "--cumulative"))
3418 return parse_dirstat_opt(options, "cumulative");
3419 else if (!strcmp(arg, "--dirstat-by-file"))
3420 return parse_dirstat_opt(options, "files");
3421 else if (!prefixcmp(arg, "--dirstat-by-file=")) {
3422 parse_dirstat_opt(options, "files");
3423 return parse_dirstat_opt(options, arg + 18);
3424 }
3425 else if (!strcmp(arg, "--check"))
3426 options->output_format |= DIFF_FORMAT_CHECKDIFF;
3427 else if (!strcmp(arg, "--summary"))
3428 options->output_format |= DIFF_FORMAT_SUMMARY;
3429 else if (!strcmp(arg, "--patch-with-stat"))
3430 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
3431 else if (!strcmp(arg, "--name-only"))
3432 options->output_format |= DIFF_FORMAT_NAME;
3433 else if (!strcmp(arg, "--name-status"))
3434 options->output_format |= DIFF_FORMAT_NAME_STATUS;
3435 else if (!strcmp(arg, "-s"))
3436 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
3437 else if (!prefixcmp(arg, "--stat"))
3438 /* --stat, --stat-width, --stat-name-width, or --stat-count */
3439 return stat_opt(options, av);
3441 /* renames options */
3442 else if (!prefixcmp(arg, "-B") || !prefixcmp(arg, "--break-rewrites=") ||
3443 !strcmp(arg, "--break-rewrites")) {
3444 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
3445 return error("invalid argument to -B: %s", arg+2);
3446 }
3447 else if (!prefixcmp(arg, "-M") || !prefixcmp(arg, "--find-renames=") ||
3448 !strcmp(arg, "--find-renames")) {
3449 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3450 return error("invalid argument to -M: %s", arg+2);
3451 options->detect_rename = DIFF_DETECT_RENAME;
3452 }
3453 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
3454 options->irreversible_delete = 1;
3455 }
3456 else if (!prefixcmp(arg, "-C") || !prefixcmp(arg, "--find-copies=") ||
3457 !strcmp(arg, "--find-copies")) {
3458 if (options->detect_rename == DIFF_DETECT_COPY)
3459 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3460 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3461 return error("invalid argument to -C: %s", arg+2);
3462 options->detect_rename = DIFF_DETECT_COPY;
3463 }
3464 else if (!strcmp(arg, "--no-renames"))
3465 options->detect_rename = 0;
3466 else if (!strcmp(arg, "--relative"))
3467 DIFF_OPT_SET(options, RELATIVE_NAME);
3468 else if (!prefixcmp(arg, "--relative=")) {
3469 DIFF_OPT_SET(options, RELATIVE_NAME);
3470 options->prefix = arg + 11;
3471 }
3473 /* xdiff options */
3474 else if (!strcmp(arg, "--minimal"))
3475 DIFF_XDL_SET(options, NEED_MINIMAL);
3476 else if (!strcmp(arg, "--no-minimal"))
3477 DIFF_XDL_CLR(options, NEED_MINIMAL);
3478 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
3479 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
3480 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
3481 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
3482 else if (!strcmp(arg, "--ignore-space-at-eol"))
3483 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
3484 else if (!strcmp(arg, "--patience"))
3485 DIFF_XDL_SET(options, PATIENCE_DIFF);
3486 else if (!strcmp(arg, "--histogram"))
3487 DIFF_XDL_SET(options, HISTOGRAM_DIFF);
3489 /* flags options */
3490 else if (!strcmp(arg, "--binary")) {
3491 options->output_format |= DIFF_FORMAT_PATCH;
3492 DIFF_OPT_SET(options, BINARY);
3493 }
3494 else if (!strcmp(arg, "--full-index"))
3495 DIFF_OPT_SET(options, FULL_INDEX);
3496 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
3497 DIFF_OPT_SET(options, TEXT);
3498 else if (!strcmp(arg, "-R"))
3499 DIFF_OPT_SET(options, REVERSE_DIFF);
3500 else if (!strcmp(arg, "--find-copies-harder"))
3501 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3502 else if (!strcmp(arg, "--follow"))
3503 DIFF_OPT_SET(options, FOLLOW_RENAMES);
3504 else if (!strcmp(arg, "--color"))
3505 options->use_color = 1;
3506 else if (!prefixcmp(arg, "--color=")) {
3507 int value = git_config_colorbool(NULL, arg+8);
3508 if (value < 0)
3509 return error("option `color' expects \"always\", \"auto\", or \"never\"");
3510 options->use_color = value;
3511 }
3512 else if (!strcmp(arg, "--no-color"))
3513 options->use_color = 0;
3514 else if (!strcmp(arg, "--color-words")) {
3515 options->use_color = 1;
3516 options->word_diff = DIFF_WORDS_COLOR;
3517 }
3518 else if (!prefixcmp(arg, "--color-words=")) {
3519 options->use_color = 1;
3520 options->word_diff = DIFF_WORDS_COLOR;
3521 options->word_regex = arg + 14;
3522 }
3523 else if (!strcmp(arg, "--word-diff")) {
3524 if (options->word_diff == DIFF_WORDS_NONE)
3525 options->word_diff = DIFF_WORDS_PLAIN;
3526 }
3527 else if (!prefixcmp(arg, "--word-diff=")) {
3528 const char *type = arg + 12;
3529 if (!strcmp(type, "plain"))
3530 options->word_diff = DIFF_WORDS_PLAIN;
3531 else if (!strcmp(type, "color")) {
3532 options->use_color = 1;
3533 options->word_diff = DIFF_WORDS_COLOR;
3534 }
3535 else if (!strcmp(type, "porcelain"))
3536 options->word_diff = DIFF_WORDS_PORCELAIN;
3537 else if (!strcmp(type, "none"))
3538 options->word_diff = DIFF_WORDS_NONE;
3539 else
3540 die("bad --word-diff argument: %s", type);
3541 }
3542 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
3543 if (options->word_diff == DIFF_WORDS_NONE)
3544 options->word_diff = DIFF_WORDS_PLAIN;
3545 options->word_regex = optarg;
3546 return argcount;
3547 }
3548 else if (!strcmp(arg, "--exit-code"))
3549 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3550 else if (!strcmp(arg, "--quiet"))
3551 DIFF_OPT_SET(options, QUICK);
3552 else if (!strcmp(arg, "--ext-diff"))
3553 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
3554 else if (!strcmp(arg, "--no-ext-diff"))
3555 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
3556 else if (!strcmp(arg, "--textconv"))
3557 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3558 else if (!strcmp(arg, "--no-textconv"))
3559 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
3560 else if (!strcmp(arg, "--ignore-submodules")) {
3561 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3562 handle_ignore_submodules_arg(options, "all");
3563 } else if (!prefixcmp(arg, "--ignore-submodules=")) {
3564 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3565 handle_ignore_submodules_arg(options, arg + 20);
3566 } else if (!strcmp(arg, "--submodule"))
3567 DIFF_OPT_SET(options, SUBMODULE_LOG);
3568 else if (!prefixcmp(arg, "--submodule=")) {
3569 if (!strcmp(arg + 12, "log"))
3570 DIFF_OPT_SET(options, SUBMODULE_LOG);
3571 }
3573 /* misc options */
3574 else if (!strcmp(arg, "-z"))
3575 options->line_termination = 0;
3576 else if ((argcount = short_opt('l', av, &optarg))) {
3577 options->rename_limit = strtoul(optarg, NULL, 10);
3578 return argcount;
3579 }
3580 else if ((argcount = short_opt('S', av, &optarg))) {
3581 options->pickaxe = optarg;
3582 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
3583 return argcount;
3584 } else if ((argcount = short_opt('G', av, &optarg))) {
3585 options->pickaxe = optarg;
3586 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
3587 return argcount;
3588 }
3589 else if (!strcmp(arg, "--pickaxe-all"))
3590 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
3591 else if (!strcmp(arg, "--pickaxe-regex"))
3592 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
3593 else if ((argcount = short_opt('O', av, &optarg))) {
3594 options->orderfile = optarg;
3595 return argcount;
3596 }
3597 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
3598 options->filter = optarg;
3599 return argcount;
3600 }
3601 else if (!strcmp(arg, "--abbrev"))
3602 options->abbrev = DEFAULT_ABBREV;
3603 else if (!prefixcmp(arg, "--abbrev=")) {
3604 options->abbrev = strtoul(arg + 9, NULL, 10);
3605 if (options->abbrev < MINIMUM_ABBREV)
3606 options->abbrev = MINIMUM_ABBREV;
3607 else if (40 < options->abbrev)
3608 options->abbrev = 40;
3609 }
3610 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
3611 options->a_prefix = optarg;
3612 return argcount;
3613 }
3614 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
3615 options->b_prefix = optarg;
3616 return argcount;
3617 }
3618 else if (!strcmp(arg, "--no-prefix"))
3619 options->a_prefix = options->b_prefix = "";
3620 else if (opt_arg(arg, '\0', "inter-hunk-context",
3621 &options->interhunkcontext))
3622 ;
3623 else if (!strcmp(arg, "-W"))
3624 DIFF_OPT_SET(options, FUNCCONTEXT);
3625 else if (!strcmp(arg, "--function-context"))
3626 DIFF_OPT_SET(options, FUNCCONTEXT);
3627 else if (!strcmp(arg, "--no-function-context"))
3628 DIFF_OPT_CLR(options, FUNCCONTEXT);
3629 else if ((argcount = parse_long_opt("output", av, &optarg))) {
3630 options->file = fopen(optarg, "w");
3631 if (!options->file)
3632 die_errno("Could not open '%s'", optarg);
3633 options->close_file = 1;
3634 return argcount;
3635 } else
3636 return 0;
3637 return 1;
3638 }
3640 int parse_rename_score(const char **cp_p)
3641 {
3642 unsigned long num, scale;
3643 int ch, dot;
3644 const char *cp = *cp_p;
3646 num = 0;
3647 scale = 1;
3648 dot = 0;
3649 for (;;) {
3650 ch = *cp;
3651 if ( !dot && ch == '.' ) {
3652 scale = 1;
3653 dot = 1;
3654 } else if ( ch == '%' ) {
3655 scale = dot ? scale*100 : 100;
3656 cp++; /* % is always at the end */
3657 break;
3658 } else if ( ch >= '0' && ch <= '9' ) {
3659 if ( scale < 100000 ) {
3660 scale *= 10;
3661 num = (num*10) + (ch-'0');
3662 }
3663 } else {
3664 break;
3665 }
3666 cp++;
3667 }
3668 *cp_p = cp;
3670 /* user says num divided by scale and we say internally that
3671 * is MAX_SCORE * num / scale.
3672 */
3673 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3674 }
3676 static int diff_scoreopt_parse(const char *opt)
3677 {
3678 int opt1, opt2, cmd;
3680 if (*opt++ != '-')
3681 return -1;
3682 cmd = *opt++;
3683 if (cmd == '-') {
3684 /* convert the long-form arguments into short-form versions */
3685 if (!prefixcmp(opt, "break-rewrites")) {
3686 opt += strlen("break-rewrites");
3687 if (*opt == 0 || *opt++ == '=')
3688 cmd = 'B';
3689 } else if (!prefixcmp(opt, "find-copies")) {
3690 opt += strlen("find-copies");
3691 if (*opt == 0 || *opt++ == '=')
3692 cmd = 'C';
3693 } else if (!prefixcmp(opt, "find-renames")) {
3694 opt += strlen("find-renames");
3695 if (*opt == 0 || *opt++ == '=')
3696 cmd = 'M';
3697 }
3698 }
3699 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3700 return -1; /* that is not a -M, -C nor -B option */
3702 opt1 = parse_rename_score(&opt);
3703 if (cmd != 'B')
3704 opt2 = 0;
3705 else {
3706 if (*opt == 0)
3707 opt2 = 0;
3708 else if (*opt != '/')
3709 return -1; /* we expect -B80/99 or -B80 */
3710 else {
3711 opt++;
3712 opt2 = parse_rename_score(&opt);
3713 }
3714 }
3715 if (*opt != 0)
3716 return -1;
3717 return opt1 | (opt2 << 16);
3718 }
3720 struct diff_queue_struct diff_queued_diff;
3722 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3723 {
3724 if (queue->alloc <= queue->nr) {
3725 queue->alloc = alloc_nr(queue->alloc);
3726 queue->queue = xrealloc(queue->queue,
3727 sizeof(dp) * queue->alloc);
3728 }
3729 queue->queue[queue->nr++] = dp;
3730 }
3732 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3733 struct diff_filespec *one,
3734 struct diff_filespec *two)
3735 {
3736 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3737 dp->one = one;
3738 dp->two = two;
3739 if (queue)
3740 diff_q(queue, dp);
3741 return dp;
3742 }
3744 void diff_free_filepair(struct diff_filepair *p)
3745 {
3746 free_filespec(p->one);
3747 free_filespec(p->two);
3748 free(p);
3749 }
3751 /* This is different from find_unique_abbrev() in that
3752 * it stuffs the result with dots for alignment.
3753 */
3754 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3755 {
3756 int abblen;
3757 const char *abbrev;
3758 if (len == 40)
3759 return sha1_to_hex(sha1);
3761 abbrev = find_unique_abbrev(sha1, len);
3762 abblen = strlen(abbrev);
3763 if (abblen < 37) {
3764 static char hex[41];
3765 if (len < abblen && abblen <= len + 2)
3766 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3767 else
3768 sprintf(hex, "%s...", abbrev);
3769 return hex;
3770 }
3771 return sha1_to_hex(sha1);
3772 }
3774 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3775 {
3776 int line_termination = opt->line_termination;
3777 int inter_name_termination = line_termination ? '\t' : '\0';
3778 if (opt->output_prefix) {
3779 struct strbuf *msg = NULL;
3780 msg = opt->output_prefix(opt, opt->output_prefix_data);
3781 fprintf(opt->file, "%s", msg->buf);
3782 }
3784 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3785 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3786 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3787 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3788 }
3789 if (p->score) {
3790 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3791 inter_name_termination);
3792 } else {
3793 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3794 }
3796 if (p->status == DIFF_STATUS_COPIED ||
3797 p->status == DIFF_STATUS_RENAMED) {
3798 const char *name_a, *name_b;
3799 name_a = p->one->path;
3800 name_b = p->two->path;
3801 strip_prefix(opt->prefix_length, &name_a, &name_b);
3802 write_name_quoted(name_a, opt->file, inter_name_termination);
3803 write_name_quoted(name_b, opt->file, line_termination);
3804 } else {
3805 const char *name_a, *name_b;
3806 name_a = p->one->mode ? p->one->path : p->two->path;
3807 name_b = NULL;
3808 strip_prefix(opt->prefix_length, &name_a, &name_b);
3809 write_name_quoted(name_a, opt->file, line_termination);
3810 }
3811 }
3813 int diff_unmodified_pair(struct diff_filepair *p)
3814 {
3815 /* This function is written stricter than necessary to support
3816 * the currently implemented transformers, but the idea is to
3817 * let transformers to produce diff_filepairs any way they want,
3818 * and filter and clean them up here before producing the output.
3819 */
3820 struct diff_filespec *one = p->one, *two = p->two;
3822 if (DIFF_PAIR_UNMERGED(p))
3823 return 0; /* unmerged is interesting */
3825 /* deletion, addition, mode or type change
3826 * and rename are all interesting.
3827 */
3828 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3829 DIFF_PAIR_MODE_CHANGED(p) ||
3830 strcmp(one->path, two->path))
3831 return 0;
3833 /* both are valid and point at the same path. that is, we are
3834 * dealing with a change.
3835 */
3836 if (one->sha1_valid && two->sha1_valid &&
3837 !hashcmp(one->sha1, two->sha1) &&
3838 !one->dirty_submodule && !two->dirty_submodule)
3839 return 1; /* no change */
3840 if (!one->sha1_valid && !two->sha1_valid)
3841 return 1; /* both look at the same file on the filesystem. */
3842 return 0;
3843 }
3845 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3846 {
3847 if (diff_unmodified_pair(p))
3848 return;
3850 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3851 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3852 return; /* no tree diffs in patch format */
3854 run_diff(p, o);
3855 }
3857 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3858 struct diffstat_t *diffstat)
3859 {
3860 if (diff_unmodified_pair(p))
3861 return;
3863 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3864 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3865 return; /* no useful stat for tree diffs */
3867 run_diffstat(p, o, diffstat);
3868 }
3870 static void diff_flush_checkdiff(struct diff_filepair *p,
3871 struct diff_options *o)
3872 {
3873 if (diff_unmodified_pair(p))
3874 return;
3876 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3877 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3878 return; /* nothing to check in tree diffs */
3880 run_checkdiff(p, o);
3881 }
3883 int diff_queue_is_empty(void)
3884 {
3885 struct diff_queue_struct *q = &diff_queued_diff;
3886 int i;
3887 for (i = 0; i < q->nr; i++)
3888 if (!diff_unmodified_pair(q->queue[i]))
3889 return 0;
3890 return 1;
3891 }
3893 #if DIFF_DEBUG
3894 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3895 {
3896 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3897 x, one ? one : "",
3898 s->path,
3899 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3900 s->mode,
3901 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3902 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3903 x, one ? one : "",
3904 s->size, s->xfrm_flags);
3905 }
3907 void diff_debug_filepair(const struct diff_filepair *p, int i)
3908 {
3909 diff_debug_filespec(p->one, i, "one");
3910 diff_debug_filespec(p->two, i, "two");
3911 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3912 p->score, p->status ? p->status : '?',
3913 p->one->rename_used, p->broken_pair);
3914 }
3916 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3917 {
3918 int i;
3919 if (msg)
3920 fprintf(stderr, "%s\n", msg);
3921 fprintf(stderr, "q->nr = %d\n", q->nr);
3922 for (i = 0; i < q->nr; i++) {
3923 struct diff_filepair *p = q->queue[i];
3924 diff_debug_filepair(p, i);
3925 }
3926 }
3927 #endif
3929 static void diff_resolve_rename_copy(void)
3930 {
3931 int i;
3932 struct diff_filepair *p;
3933 struct diff_queue_struct *q = &diff_queued_diff;
3935 diff_debug_queue("resolve-rename-copy", q);
3937 for (i = 0; i < q->nr; i++) {
3938 p = q->queue[i];
3939 p->status = 0; /* undecided */
3940 if (DIFF_PAIR_UNMERGED(p))
3941 p->status = DIFF_STATUS_UNMERGED;
3942 else if (!DIFF_FILE_VALID(p->one))
3943 p->status = DIFF_STATUS_ADDED;
3944 else if (!DIFF_FILE_VALID(p->two))
3945 p->status = DIFF_STATUS_DELETED;
3946 else if (DIFF_PAIR_TYPE_CHANGED(p))
3947 p->status = DIFF_STATUS_TYPE_CHANGED;
3949 /* from this point on, we are dealing with a pair
3950 * whose both sides are valid and of the same type, i.e.
3951 * either in-place edit or rename/copy edit.
3952 */
3953 else if (DIFF_PAIR_RENAME(p)) {
3954 /*
3955 * A rename might have re-connected a broken
3956 * pair up, causing the pathnames to be the
3957 * same again. If so, that's not a rename at
3958 * all, just a modification..
3959 *
3960 * Otherwise, see if this source was used for
3961 * multiple renames, in which case we decrement
3962 * the count, and call it a copy.
3963 */
3964 if (!strcmp(p->one->path, p->two->path))
3965 p->status = DIFF_STATUS_MODIFIED;
3966 else if (--p->one->rename_used > 0)
3967 p->status = DIFF_STATUS_COPIED;
3968 else
3969 p->status = DIFF_STATUS_RENAMED;
3970 }
3971 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3972 p->one->mode != p->two->mode ||
3973 p->one->dirty_submodule ||
3974 p->two->dirty_submodule ||
3975 is_null_sha1(p->one->sha1))
3976 p->status = DIFF_STATUS_MODIFIED;
3977 else {
3978 /* This is a "no-change" entry and should not
3979 * happen anymore, but prepare for broken callers.
3980 */
3981 error("feeding unmodified %s to diffcore",
3982 p->one->path);
3983 p->status = DIFF_STATUS_UNKNOWN;
3984 }
3985 }
3986 diff_debug_queue("resolve-rename-copy done", q);
3987 }
3989 static int check_pair_status(struct diff_filepair *p)
3990 {
3991 switch (p->status) {
3992 case DIFF_STATUS_UNKNOWN:
3993 return 0;
3994 case 0:
3995 die("internal error in diff-resolve-rename-copy");
3996 default:
3997 return 1;
3998 }
3999 }
4001 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4002 {
4003 int fmt = opt->output_format;
4005 if (fmt & DIFF_FORMAT_CHECKDIFF)
4006 diff_flush_checkdiff(p, opt);
4007 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4008 diff_flush_raw(p, opt);
4009 else if (fmt & DIFF_FORMAT_NAME) {
4010 const char *name_a, *name_b;
4011 name_a = p->two->path;
4012 name_b = NULL;
4013 strip_prefix(opt->prefix_length, &name_a, &name_b);
4014 write_name_quoted(name_a, opt->file, opt->line_termination);
4015 }
4016 }
4018 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4019 {
4020 if (fs->mode)
4021 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4022 else
4023 fprintf(file, " %s ", newdelete);
4024 write_name_quoted(fs->path, file, '\n');
4025 }
4028 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
4029 const char *line_prefix)
4030 {
4031 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
4032 fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
4033 p->two->mode, show_name ? ' ' : '\n');
4034 if (show_name) {
4035 write_name_quoted(p->two->path, file, '\n');
4036 }
4037 }
4038 }
4040 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
4041 const char *line_prefix)
4042 {
4043 char *names = pprint_rename(p->one->path, p->two->path);
4045 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
4046 free(names);
4047 show_mode_change(file, p, 0, line_prefix);
4048 }
4050 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4051 {
4052 FILE *file = opt->file;
4053 char *line_prefix = "";
4055 if (opt->output_prefix) {
4056 struct strbuf *buf = opt->output_prefix(opt, opt->output_prefix_data);
4057 line_prefix = buf->buf;
4058 }
4060 switch(p->status) {
4061 case DIFF_STATUS_DELETED:
4062 fputs(line_prefix, file);
4063 show_file_mode_name(file, "delete", p->one);
4064 break;
4065 case DIFF_STATUS_ADDED:
4066 fputs(line_prefix, file);
4067 show_file_mode_name(file, "create", p->two);
4068 break;
4069 case DIFF_STATUS_COPIED:
4070 fputs(line_prefix, file);
4071 show_rename_copy(file, "copy", p, line_prefix);
4072 break;
4073 case DIFF_STATUS_RENAMED:
4074 fputs(line_prefix, file);
4075 show_rename_copy(file, "rename", p, line_prefix);
4076 break;
4077 default:
4078 if (p->score) {
4079 fprintf(file, "%s rewrite ", line_prefix);
4080 write_name_quoted(p->two->path, file, ' ');
4081 fprintf(file, "(%d%%)\n", similarity_index(p));
4082 }
4083 show_mode_change(file, p, !p->score, line_prefix);
4084 break;
4085 }
4086 }
4088 struct patch_id_t {
4089 git_SHA_CTX *ctx;
4090 int patchlen;
4091 };
4093 static int remove_space(char *line, int len)
4094 {
4095 int i;
4096 char *dst = line;
4097 unsigned char c;
4099 for (i = 0; i < len; i++)
4100 if (!isspace((c = line[i])))
4101 *dst++ = c;
4103 return dst - line;
4104 }
4106 static void patch_id_consume(void *priv, char *line, unsigned long len)
4107 {
4108 struct patch_id_t *data = priv;
4109 int new_len;
4111 /* Ignore line numbers when computing the SHA1 of the patch */
4112 if (!prefixcmp(line, "@@ -"))
4113 return;
4115 new_len = remove_space(line, len);
4117 git_SHA1_Update(data->ctx, line, new_len);
4118 data->patchlen += new_len;
4119 }
4121 /* returns 0 upon success, and writes result into sha1 */
4122 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
4123 {
4124 struct diff_queue_struct *q = &diff_queued_diff;
4125 int i;
4126 git_SHA_CTX ctx;
4127 struct patch_id_t data;
4128 char buffer[PATH_MAX * 4 + 20];
4130 git_SHA1_Init(&ctx);
4131 memset(&data, 0, sizeof(struct patch_id_t));
4132 data.ctx = &ctx;
4134 for (i = 0; i < q->nr; i++) {
4135 xpparam_t xpp;
4136 xdemitconf_t xecfg;
4137 mmfile_t mf1, mf2;
4138 struct diff_filepair *p = q->queue[i];
4139 int len1, len2;
4141 memset(&xpp, 0, sizeof(xpp));
4142 memset(&xecfg, 0, sizeof(xecfg));
4143 if (p->status == 0)
4144 return error("internal diff status error");
4145 if (p->status == DIFF_STATUS_UNKNOWN)
4146 continue;
4147 if (diff_unmodified_pair(p))
4148 continue;
4149 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4150 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4151 continue;
4152 if (DIFF_PAIR_UNMERGED(p))
4153 continue;
4155 diff_fill_sha1_info(p->one);
4156 diff_fill_sha1_info(p->two);
4157 if (fill_mmfile(&mf1, p->one) < 0 ||
4158 fill_mmfile(&mf2, p->two) < 0)
4159 return error("unable to read files to diff");
4161 len1 = remove_space(p->one->path, strlen(p->one->path));
4162 len2 = remove_space(p->two->path, strlen(p->two->path));
4163 if (p->one->mode == 0)
4164 len1 = snprintf(buffer, sizeof(buffer),
4165 "diff--gita/%.*sb/%.*s"
4166 "newfilemode%06o"
4167 "---/dev/null"
4168 "+++b/%.*s",
4169 len1, p->one->path,
4170 len2, p->two->path,
4171 p->two->mode,
4172 len2, p->two->path);
4173 else if (p->two->mode == 0)
4174 len1 = snprintf(buffer, sizeof(buffer),
4175 "diff--gita/%.*sb/%.*s"
4176 "deletedfilemode%06o"
4177 "---a/%.*s"
4178 "+++/dev/null",
4179 len1, p->one->path,
4180 len2, p->two->path,
4181 p->one->mode,
4182 len1, p->one->path);
4183 else
4184 len1 = snprintf(buffer, sizeof(buffer),
4185 "diff--gita/%.*sb/%.*s"
4186 "---a/%.*s"
4187 "+++b/%.*s",
4188 len1, p->one->path,
4189 len2, p->two->path,
4190 len1, p->one->path,
4191 len2, p->two->path);
4192 git_SHA1_Update(&ctx, buffer, len1);
4194 if (diff_filespec_is_binary(p->one) ||
4195 diff_filespec_is_binary(p->two)) {
4196 git_SHA1_Update(&ctx, sha1_to_hex(p->one->sha1), 40);
4197 git_SHA1_Update(&ctx, sha1_to_hex(p->two->sha1), 40);
4198 continue;
4199 }
4201 xpp.flags = 0;
4202 xecfg.ctxlen = 3;
4203 xecfg.flags = 0;
4204 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
4205 &xpp, &xecfg);
4206 }
4208 git_SHA1_Final(sha1, &ctx);
4209 return 0;
4210 }
4212 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
4213 {
4214 struct diff_queue_struct *q = &diff_queued_diff;
4215 int i;
4216 int result = diff_get_patch_id(options, sha1);
4218 for (i = 0; i < q->nr; i++)
4219 diff_free_filepair(q->queue[i]);
4221 free(q->queue);
4222 DIFF_QUEUE_CLEAR(q);
4224 return result;
4225 }
4227 static int is_summary_empty(const struct diff_queue_struct *q)
4228 {
4229 int i;
4231 for (i = 0; i < q->nr; i++) {
4232 const struct diff_filepair *p = q->queue[i];
4234 switch (p->status) {
4235 case DIFF_STATUS_DELETED:
4236 case DIFF_STATUS_ADDED:
4237 case DIFF_STATUS_COPIED:
4238 case DIFF_STATUS_RENAMED:
4239 return 0;
4240 default:
4241 if (p->score)
4242 return 0;
4243 if (p->one->mode && p->two->mode &&
4244 p->one->mode != p->two->mode)
4245 return 0;
4246 break;
4247 }
4248 }
4249 return 1;
4250 }
4252 static const char rename_limit_warning[] =
4253 "inexact rename detection was skipped due to too many files.";
4255 static const char degrade_cc_to_c_warning[] =
4256 "only found copies from modified paths due to too many files.";
4258 static const char rename_limit_advice[] =
4259 "you may want to set your %s variable to at least "
4260 "%d and retry the command.";
4262 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4263 {
4264 if (degraded_cc)
4265 warning(degrade_cc_to_c_warning);
4266 else if (needed)
4267 warning(rename_limit_warning);
4268 else
4269 return;
4270 if (0 < needed && needed < 32767)
4271 warning(rename_limit_advice, varname, needed);
4272 }
4274 void diff_flush(struct diff_options *options)
4275 {
4276 struct diff_queue_struct *q = &diff_queued_diff;
4277 int i, output_format = options->output_format;
4278 int separator = 0;
4279 int dirstat_by_line = 0;
4281 /*
4282 * Order: raw, stat, summary, patch
4283 * or: name/name-status/checkdiff (other bits clear)
4284 */
4285 if (!q->nr)
4286 goto free_queue;
4288 if (output_format & (DIFF_FORMAT_RAW |
4289 DIFF_FORMAT_NAME |
4290 DIFF_FORMAT_NAME_STATUS |
4291 DIFF_FORMAT_CHECKDIFF)) {
4292 for (i = 0; i < q->nr; i++) {
4293 struct diff_filepair *p = q->queue[i];
4294 if (check_pair_status(p))
4295 flush_one_pair(p, options);
4296 }
4297 separator++;
4298 }
4300 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
4301 dirstat_by_line = 1;
4303 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
4304 dirstat_by_line) {
4305 struct diffstat_t diffstat;
4307 memset(&diffstat, 0, sizeof(struct diffstat_t));
4308 for (i = 0; i < q->nr; i++) {
4309 struct diff_filepair *p = q->queue[i];
4310 if (check_pair_status(p))
4311 diff_flush_stat(p, options, &diffstat);
4312 }
4313 if (output_format & DIFF_FORMAT_NUMSTAT)
4314 show_numstat(&diffstat, options);
4315 if (output_format & DIFF_FORMAT_DIFFSTAT)
4316 show_stats(&diffstat, options);
4317 if (output_format & DIFF_FORMAT_SHORTSTAT)
4318 show_shortstats(&diffstat, options);
4319 if (output_format & DIFF_FORMAT_DIRSTAT)
4320 show_dirstat_by_line(&diffstat, options);
4321 free_diffstat_info(&diffstat);
4322 separator++;
4323 }
4324 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
4325 show_dirstat(options);
4327 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
4328 for (i = 0; i < q->nr; i++) {
4329 diff_summary(options, q->queue[i]);
4330 }
4331 separator++;
4332 }
4334 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
4335 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
4336 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4337 /*
4338 * run diff_flush_patch for the exit status. setting
4339 * options->file to /dev/null should be safe, becaue we
4340 * aren't supposed to produce any output anyway.
4341 */
4342 if (options->close_file)
4343 fclose(options->file);
4344 options->file = fopen("/dev/null", "w");
4345 if (!options->file)
4346 die_errno("Could not open /dev/null");
4347 options->close_file = 1;
4348 for (i = 0; i < q->nr; i++) {
4349 struct diff_filepair *p = q->queue[i];
4350 if (check_pair_status(p))
4351 diff_flush_patch(p, options);
4352 if (options->found_changes)
4353 break;
4354 }
4355 }
4357 if (output_format & DIFF_FORMAT_PATCH) {
4358 if (separator) {
4359 putc(options->line_termination, options->file);
4360 if (options->stat_sep) {
4361 /* attach patch instead of inline */
4362 fputs(options->stat_sep, options->file);
4363 }
4364 }
4366 for (i = 0; i < q->nr; i++) {
4367 struct diff_filepair *p = q->queue[i];
4368 if (check_pair_status(p))
4369 diff_flush_patch(p, options);
4370 }
4371 }
4373 if (output_format & DIFF_FORMAT_CALLBACK)
4374 options->format_callback(q, options, options->format_callback_data);
4376 for (i = 0; i < q->nr; i++)
4377 diff_free_filepair(q->queue[i]);
4378 free_queue:
4379 free(q->queue);
4380 DIFF_QUEUE_CLEAR(q);
4381 if (options->close_file)
4382 fclose(options->file);
4384 /*
4385 * Report the content-level differences with HAS_CHANGES;
4386 * diff_addremove/diff_change does not set the bit when
4387 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
4388 */
4389 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4390 if (options->found_changes)
4391 DIFF_OPT_SET(options, HAS_CHANGES);
4392 else
4393 DIFF_OPT_CLR(options, HAS_CHANGES);
4394 }
4395 }
4397 static void diffcore_apply_filter(const char *filter)
4398 {
4399 int i;
4400 struct diff_queue_struct *q = &diff_queued_diff;
4401 struct diff_queue_struct outq;
4402 DIFF_QUEUE_CLEAR(&outq);
4404 if (!filter)
4405 return;
4407 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
4408 int found;
4409 for (i = found = 0; !found && i < q->nr; i++) {
4410 struct diff_filepair *p = q->queue[i];
4411 if (((p->status == DIFF_STATUS_MODIFIED) &&
4412 ((p->score &&
4413 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4414 (!p->score &&
4415 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4416 ((p->status != DIFF_STATUS_MODIFIED) &&
4417 strchr(filter, p->status)))
4418 found++;
4419 }
4420 if (found)
4421 return;
4423 /* otherwise we will clear the whole queue
4424 * by copying the empty outq at the end of this
4425 * function, but first clear the current entries
4426 * in the queue.
4427 */
4428 for (i = 0; i < q->nr; i++)
4429 diff_free_filepair(q->queue[i]);
4430 }
4431 else {
4432 /* Only the matching ones */
4433 for (i = 0; i < q->nr; i++) {
4434 struct diff_filepair *p = q->queue[i];
4436 if (((p->status == DIFF_STATUS_MODIFIED) &&
4437 ((p->score &&
4438 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4439 (!p->score &&
4440 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4441 ((p->status != DIFF_STATUS_MODIFIED) &&
4442 strchr(filter, p->status)))
4443 diff_q(&outq, p);
4444 else
4445 diff_free_filepair(p);
4446 }
4447 }
4448 free(q->queue);
4449 *q = outq;
4450 }
4452 /* Check whether two filespecs with the same mode and size are identical */
4453 static int diff_filespec_is_identical(struct diff_filespec *one,
4454 struct diff_filespec *two)
4455 {
4456 if (S_ISGITLINK(one->mode))
4457 return 0;
4458 if (diff_populate_filespec(one, 0))
4459 return 0;
4460 if (diff_populate_filespec(two, 0))
4461 return 0;
4462 return !memcmp(one->data, two->data, one->size);
4463 }
4465 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
4466 {
4467 int i;
4468 struct diff_queue_struct *q = &diff_queued_diff;
4469 struct diff_queue_struct outq;
4470 DIFF_QUEUE_CLEAR(&outq);
4472 for (i = 0; i < q->nr; i++) {
4473 struct diff_filepair *p = q->queue[i];
4475 /*
4476 * 1. Entries that come from stat info dirtiness
4477 * always have both sides (iow, not create/delete),
4478 * one side of the object name is unknown, with
4479 * the same mode and size. Keep the ones that
4480 * do not match these criteria. They have real
4481 * differences.
4482 *
4483 * 2. At this point, the file is known to be modified,
4484 * with the same mode and size, and the object
4485 * name of one side is unknown. Need to inspect
4486 * the identical contents.
4487 */
4488 if (!DIFF_FILE_VALID(p->one) || /* (1) */
4489 !DIFF_FILE_VALID(p->two) ||
4490 (p->one->sha1_valid && p->two->sha1_valid) ||
4491 (p->one->mode != p->two->mode) ||
4492 diff_populate_filespec(p->one, 1) ||
4493 diff_populate_filespec(p->two, 1) ||
4494 (p->one->size != p->two->size) ||
4495 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
4496 diff_q(&outq, p);
4497 else {
4498 /*
4499 * The caller can subtract 1 from skip_stat_unmatch
4500 * to determine how many paths were dirty only
4501 * due to stat info mismatch.
4502 */
4503 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
4504 diffopt->skip_stat_unmatch++;
4505 diff_free_filepair(p);
4506 }
4507 }
4508 free(q->queue);
4509 *q = outq;
4510 }
4512 static int diffnamecmp(const void *a_, const void *b_)
4513 {
4514 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4515 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4516 const char *name_a, *name_b;
4518 name_a = a->one ? a->one->path : a->two->path;
4519 name_b = b->one ? b->one->path : b->two->path;
4520 return strcmp(name_a, name_b);
4521 }
4523 void diffcore_fix_diff_index(struct diff_options *options)
4524 {
4525 struct diff_queue_struct *q = &diff_queued_diff;
4526 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
4527 }
4529 void diffcore_std(struct diff_options *options)
4530 {
4531 if (options->skip_stat_unmatch)
4532 diffcore_skip_stat_unmatch(options);
4533 if (!options->found_follow) {
4534 /* See try_to_follow_renames() in tree-diff.c */
4535 if (options->break_opt != -1)
4536 diffcore_break(options->break_opt);
4537 if (options->detect_rename)
4538 diffcore_rename(options);
4539 if (options->break_opt != -1)
4540 diffcore_merge_broken();
4541 }
4542 if (options->pickaxe)
4543 diffcore_pickaxe(options);
4544 if (options->orderfile)
4545 diffcore_order(options->orderfile);
4546 if (!options->found_follow)
4547 /* See try_to_follow_renames() in tree-diff.c */
4548 diff_resolve_rename_copy();
4549 diffcore_apply_filter(options->filter);
4551 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4552 DIFF_OPT_SET(options, HAS_CHANGES);
4553 else
4554 DIFF_OPT_CLR(options, HAS_CHANGES);
4556 options->found_follow = 0;
4557 }
4559 int diff_result_code(struct diff_options *opt, int status)
4560 {
4561 int result = 0;
4563 diff_warn_rename_limit("diff.renamelimit",
4564 opt->needed_rename_limit,
4565 opt->degraded_cc_to_c);
4566 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4567 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
4568 return status;
4569 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4570 DIFF_OPT_TST(opt, HAS_CHANGES))
4571 result |= 01;
4572 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4573 DIFF_OPT_TST(opt, CHECK_FAILED))
4574 result |= 02;
4575 return result;
4576 }
4578 int diff_can_quit_early(struct diff_options *opt)
4579 {
4580 return (DIFF_OPT_TST(opt, QUICK) &&
4581 !opt->filter &&
4582 DIFF_OPT_TST(opt, HAS_CHANGES));
4583 }
4585 /*
4586 * Shall changes to this submodule be ignored?
4587 *
4588 * Submodule changes can be configured to be ignored separately for each path,
4589 * but that configuration can be overridden from the command line.
4590 */
4591 static int is_submodule_ignored(const char *path, struct diff_options *options)
4592 {
4593 int ignored = 0;
4594 unsigned orig_flags = options->flags;
4595 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
4596 set_diffopt_flags_from_submodule_config(options, path);
4597 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
4598 ignored = 1;
4599 options->flags = orig_flags;
4600 return ignored;
4601 }
4603 void diff_addremove(struct diff_options *options,
4604 int addremove, unsigned mode,
4605 const unsigned char *sha1,
4606 const char *concatpath, unsigned dirty_submodule)
4607 {
4608 struct diff_filespec *one, *two;
4610 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
4611 return;
4613 /* This may look odd, but it is a preparation for
4614 * feeding "there are unchanged files which should
4615 * not produce diffs, but when you are doing copy
4616 * detection you would need them, so here they are"
4617 * entries to the diff-core. They will be prefixed
4618 * with something like '=' or '*' (I haven't decided
4619 * which but should not make any difference).
4620 * Feeding the same new and old to diff_change()
4621 * also has the same effect.
4622 * Before the final output happens, they are pruned after
4623 * merged into rename/copy pairs as appropriate.
4624 */
4625 if (DIFF_OPT_TST(options, REVERSE_DIFF))
4626 addremove = (addremove == '+' ? '-' :
4627 addremove == '-' ? '+' : addremove);
4629 if (options->prefix &&
4630 strncmp(concatpath, options->prefix, options->prefix_length))
4631 return;
4633 one = alloc_filespec(concatpath);
4634 two = alloc_filespec(concatpath);
4636 if (addremove != '+')
4637 fill_filespec(one, sha1, mode);
4638 if (addremove != '-') {
4639 fill_filespec(two, sha1, mode);
4640 two->dirty_submodule = dirty_submodule;
4641 }
4643 diff_queue(&diff_queued_diff, one, two);
4644 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4645 DIFF_OPT_SET(options, HAS_CHANGES);
4646 }
4648 void diff_change(struct diff_options *options,
4649 unsigned old_mode, unsigned new_mode,
4650 const unsigned char *old_sha1,
4651 const unsigned char *new_sha1,
4652 const char *concatpath,
4653 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
4654 {
4655 struct diff_filespec *one, *two;
4657 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
4658 is_submodule_ignored(concatpath, options))
4659 return;
4661 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
4662 unsigned tmp;
4663 const unsigned char *tmp_c;
4664 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
4665 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
4666 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
4667 new_dirty_submodule = tmp;
4668 }
4670 if (options->prefix &&
4671 strncmp(concatpath, options->prefix, options->prefix_length))
4672 return;
4674 one = alloc_filespec(concatpath);
4675 two = alloc_filespec(concatpath);
4676 fill_filespec(one, old_sha1, old_mode);
4677 fill_filespec(two, new_sha1, new_mode);
4678 one->dirty_submodule = old_dirty_submodule;
4679 two->dirty_submodule = new_dirty_submodule;
4681 diff_queue(&diff_queued_diff, one, two);
4682 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4683 DIFF_OPT_SET(options, HAS_CHANGES);
4684 }
4686 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
4687 {
4688 struct diff_filepair *pair;
4689 struct diff_filespec *one, *two;
4691 if (options->prefix &&
4692 strncmp(path, options->prefix, options->prefix_length))
4693 return NULL;
4695 one = alloc_filespec(path);
4696 two = alloc_filespec(path);
4697 pair = diff_queue(&diff_queued_diff, one, two);
4698 pair->is_unmerged = 1;
4699 return pair;
4700 }
4702 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
4703 size_t *outsize)
4704 {
4705 struct diff_tempfile *temp;
4706 const char *argv[3];
4707 const char **arg = argv;
4708 struct child_process child;
4709 struct strbuf buf = STRBUF_INIT;
4710 int err = 0;
4712 temp = prepare_temp_file(spec->path, spec);
4713 *arg++ = pgm;
4714 *arg++ = temp->name;
4715 *arg = NULL;
4717 memset(&child, 0, sizeof(child));
4718 child.use_shell = 1;
4719 child.argv = argv;
4720 child.out = -1;
4721 if (start_command(&child)) {
4722 remove_tempfile();
4723 return NULL;
4724 }
4726 if (strbuf_read(&buf, child.out, 0) < 0)
4727 err = error("error reading from textconv command '%s'", pgm);
4728 close(child.out);
4730 if (finish_command(&child) || err) {
4731 strbuf_release(&buf);
4732 remove_tempfile();
4733 return NULL;
4734 }
4735 remove_tempfile();
4737 return strbuf_detach(&buf, outsize);
4738 }
4740 size_t fill_textconv(struct userdiff_driver *driver,
4741 struct diff_filespec *df,
4742 char **outbuf)
4743 {
4744 size_t size;
4746 if (!driver || !driver->textconv) {
4747 if (!DIFF_FILE_VALID(df)) {
4748 *outbuf = "";
4749 return 0;
4750 }
4751 if (diff_populate_filespec(df, 0))
4752 die("unable to read files to diff");
4753 *outbuf = df->data;
4754 return df->size;
4755 }
4757 if (driver->textconv_cache && df->sha1_valid) {
4758 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4759 &size);
4760 if (*outbuf)
4761 return size;
4762 }
4764 *outbuf = run_textconv(driver->textconv, df, &size);
4765 if (!*outbuf)
4766 die("unable to read files to diff");
4768 if (driver->textconv_cache && df->sha1_valid) {
4769 /* ignore errors, as we might be in a readonly repository */
4770 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4771 size);
4772 /*
4773 * we could save up changes and flush them all at the end,
4774 * but we would need an extra call after all diffing is done.
4775 * Since generating a cache entry is the slow path anyway,
4776 * this extra overhead probably isn't a big deal.
4777 */
4778 notes_cache_write(driver->textconv_cache);
4779 }
4781 return size;
4782 }