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