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