Merge branch 'ah/doc-wserrorhighlight' into maint
[git/git.git] / diff.c
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "config.h"
6 #include "tempfile.h"
7 #include "quote.h"
8 #include "diff.h"
9 #include "diffcore.h"
10 #include "delta.h"
11 #include "xdiff-interface.h"
12 #include "color.h"
13 #include "attr.h"
14 #include "run-command.h"
15 #include "utf8.h"
16 #include "userdiff.h"
17 #include "submodule-config.h"
18 #include "submodule.h"
19 #include "ll-merge.h"
20 #include "string-list.h"
21 #include "argv-array.h"
22 #include "graph.h"
23
24 #ifdef NO_FAST_WORKING_DIRECTORY
25 #define FAST_WORKING_DIRECTORY 0
26 #else
27 #define FAST_WORKING_DIRECTORY 1
28 #endif
29
30 static int diff_detect_rename_default;
31 static int diff_indent_heuristic = 1;
32 static int diff_rename_limit_default = 400;
33 static int diff_suppress_blank_empty;
34 static int diff_use_color_default = -1;
35 static int diff_context_default = 3;
36 static int diff_interhunk_context_default;
37 static const char *diff_word_regex_cfg;
38 static const char *external_diff_cmd_cfg;
39 static const char *diff_order_file_cfg;
40 int diff_auto_refresh_index = 1;
41 static int diff_mnemonic_prefix;
42 static int diff_no_prefix;
43 static int diff_stat_graph_width;
44 static int diff_dirstat_permille_default = 30;
45 static struct diff_options default_diff_options;
46 static long diff_algorithm;
47 static unsigned ws_error_highlight_default = WSEH_NEW;
48
49 static char diff_colors[][COLOR_MAXLEN] = {
50 GIT_COLOR_RESET,
51 GIT_COLOR_NORMAL, /* CONTEXT */
52 GIT_COLOR_BOLD, /* METAINFO */
53 GIT_COLOR_CYAN, /* FRAGINFO */
54 GIT_COLOR_RED, /* OLD */
55 GIT_COLOR_GREEN, /* NEW */
56 GIT_COLOR_YELLOW, /* COMMIT */
57 GIT_COLOR_BG_RED, /* WHITESPACE */
58 GIT_COLOR_NORMAL, /* FUNCINFO */
59 };
60
61 static NORETURN void die_want_option(const char *option_name)
62 {
63 die(_("option '%s' requires a value"), option_name);
64 }
65
66 static int parse_diff_color_slot(const char *var)
67 {
68 if (!strcasecmp(var, "context") || !strcasecmp(var, "plain"))
69 return DIFF_CONTEXT;
70 if (!strcasecmp(var, "meta"))
71 return DIFF_METAINFO;
72 if (!strcasecmp(var, "frag"))
73 return DIFF_FRAGINFO;
74 if (!strcasecmp(var, "old"))
75 return DIFF_FILE_OLD;
76 if (!strcasecmp(var, "new"))
77 return DIFF_FILE_NEW;
78 if (!strcasecmp(var, "commit"))
79 return DIFF_COMMIT;
80 if (!strcasecmp(var, "whitespace"))
81 return DIFF_WHITESPACE;
82 if (!strcasecmp(var, "func"))
83 return DIFF_FUNCINFO;
84 return -1;
85 }
86
87 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
88 struct strbuf *errmsg)
89 {
90 char *params_copy = xstrdup(params_string);
91 struct string_list params = STRING_LIST_INIT_NODUP;
92 int ret = 0;
93 int i;
94
95 if (*params_copy)
96 string_list_split_in_place(&params, params_copy, ',', -1);
97 for (i = 0; i < params.nr; i++) {
98 const char *p = params.items[i].string;
99 if (!strcmp(p, "changes")) {
100 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
101 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
102 } else if (!strcmp(p, "lines")) {
103 DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
104 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
105 } else if (!strcmp(p, "files")) {
106 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
107 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
108 } else if (!strcmp(p, "noncumulative")) {
109 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
110 } else if (!strcmp(p, "cumulative")) {
111 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
112 } else if (isdigit(*p)) {
113 char *end;
114 int permille = strtoul(p, &end, 10) * 10;
115 if (*end == '.' && isdigit(*++end)) {
116 /* only use first digit */
117 permille += *end - '0';
118 /* .. and ignore any further digits */
119 while (isdigit(*++end))
120 ; /* nothing */
121 }
122 if (!*end)
123 options->dirstat_permille = permille;
124 else {
125 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
126 p);
127 ret++;
128 }
129 } else {
130 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
131 ret++;
132 }
133
134 }
135 string_list_clear(&params, 0);
136 free(params_copy);
137 return ret;
138 }
139
140 static int parse_submodule_params(struct diff_options *options, const char *value)
141 {
142 if (!strcmp(value, "log"))
143 options->submodule_format = DIFF_SUBMODULE_LOG;
144 else if (!strcmp(value, "short"))
145 options->submodule_format = DIFF_SUBMODULE_SHORT;
146 else if (!strcmp(value, "diff"))
147 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
148 else
149 return -1;
150 return 0;
151 }
152
153 static int git_config_rename(const char *var, const char *value)
154 {
155 if (!value)
156 return DIFF_DETECT_RENAME;
157 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
158 return DIFF_DETECT_COPY;
159 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
160 }
161
162 long parse_algorithm_value(const char *value)
163 {
164 if (!value)
165 return -1;
166 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
167 return 0;
168 else if (!strcasecmp(value, "minimal"))
169 return XDF_NEED_MINIMAL;
170 else if (!strcasecmp(value, "patience"))
171 return XDF_PATIENCE_DIFF;
172 else if (!strcasecmp(value, "histogram"))
173 return XDF_HISTOGRAM_DIFF;
174 return -1;
175 }
176
177 static int parse_one_token(const char **arg, const char *token)
178 {
179 const char *rest;
180 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
181 *arg = rest;
182 return 1;
183 }
184 return 0;
185 }
186
187 static int parse_ws_error_highlight(const char *arg)
188 {
189 const char *orig_arg = arg;
190 unsigned val = 0;
191
192 while (*arg) {
193 if (parse_one_token(&arg, "none"))
194 val = 0;
195 else if (parse_one_token(&arg, "default"))
196 val = WSEH_NEW;
197 else if (parse_one_token(&arg, "all"))
198 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
199 else if (parse_one_token(&arg, "new"))
200 val |= WSEH_NEW;
201 else if (parse_one_token(&arg, "old"))
202 val |= WSEH_OLD;
203 else if (parse_one_token(&arg, "context"))
204 val |= WSEH_CONTEXT;
205 else {
206 return -1 - (int)(arg - orig_arg);
207 }
208 if (*arg)
209 arg++;
210 }
211 return val;
212 }
213
214 /*
215 * These are to give UI layer defaults.
216 * The core-level commands such as git-diff-files should
217 * never be affected by the setting of diff.renames
218 * the user happens to have in the configuration file.
219 */
220 void init_diff_ui_defaults(void)
221 {
222 diff_detect_rename_default = 1;
223 }
224
225 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
226 {
227 if (!strcmp(var, "diff.indentheuristic"))
228 diff_indent_heuristic = git_config_bool(var, value);
229 return 0;
230 }
231
232 int git_diff_ui_config(const char *var, const char *value, void *cb)
233 {
234 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
235 diff_use_color_default = git_config_colorbool(var, value);
236 return 0;
237 }
238 if (!strcmp(var, "diff.context")) {
239 diff_context_default = git_config_int(var, value);
240 if (diff_context_default < 0)
241 return -1;
242 return 0;
243 }
244 if (!strcmp(var, "diff.interhunkcontext")) {
245 diff_interhunk_context_default = git_config_int(var, value);
246 if (diff_interhunk_context_default < 0)
247 return -1;
248 return 0;
249 }
250 if (!strcmp(var, "diff.renames")) {
251 diff_detect_rename_default = git_config_rename(var, value);
252 return 0;
253 }
254 if (!strcmp(var, "diff.autorefreshindex")) {
255 diff_auto_refresh_index = git_config_bool(var, value);
256 return 0;
257 }
258 if (!strcmp(var, "diff.mnemonicprefix")) {
259 diff_mnemonic_prefix = git_config_bool(var, value);
260 return 0;
261 }
262 if (!strcmp(var, "diff.noprefix")) {
263 diff_no_prefix = git_config_bool(var, value);
264 return 0;
265 }
266 if (!strcmp(var, "diff.statgraphwidth")) {
267 diff_stat_graph_width = git_config_int(var, value);
268 return 0;
269 }
270 if (!strcmp(var, "diff.external"))
271 return git_config_string(&external_diff_cmd_cfg, var, value);
272 if (!strcmp(var, "diff.wordregex"))
273 return git_config_string(&diff_word_regex_cfg, var, value);
274 if (!strcmp(var, "diff.orderfile"))
275 return git_config_pathname(&diff_order_file_cfg, var, value);
276
277 if (!strcmp(var, "diff.ignoresubmodules"))
278 handle_ignore_submodules_arg(&default_diff_options, value);
279
280 if (!strcmp(var, "diff.submodule")) {
281 if (parse_submodule_params(&default_diff_options, value))
282 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
283 value);
284 return 0;
285 }
286
287 if (!strcmp(var, "diff.algorithm")) {
288 diff_algorithm = parse_algorithm_value(value);
289 if (diff_algorithm < 0)
290 return -1;
291 return 0;
292 }
293
294 if (!strcmp(var, "diff.wserrorhighlight")) {
295 int val = parse_ws_error_highlight(value);
296 if (val < 0)
297 return -1;
298 ws_error_highlight_default = val;
299 return 0;
300 }
301
302 return git_diff_basic_config(var, value, cb);
303 }
304
305 int git_diff_basic_config(const char *var, const char *value, void *cb)
306 {
307 const char *name;
308
309 if (!strcmp(var, "diff.renamelimit")) {
310 diff_rename_limit_default = git_config_int(var, value);
311 return 0;
312 }
313
314 if (userdiff_config(var, value) < 0)
315 return -1;
316
317 if (skip_prefix(var, "diff.color.", &name) ||
318 skip_prefix(var, "color.diff.", &name)) {
319 int slot = parse_diff_color_slot(name);
320 if (slot < 0)
321 return 0;
322 if (!value)
323 return config_error_nonbool(var);
324 return color_parse(value, diff_colors[slot]);
325 }
326
327 /* like GNU diff's --suppress-blank-empty option */
328 if (!strcmp(var, "diff.suppressblankempty") ||
329 /* for backwards compatibility */
330 !strcmp(var, "diff.suppress-blank-empty")) {
331 diff_suppress_blank_empty = git_config_bool(var, value);
332 return 0;
333 }
334
335 if (!strcmp(var, "diff.dirstat")) {
336 struct strbuf errmsg = STRBUF_INIT;
337 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
338 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
339 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
340 errmsg.buf);
341 strbuf_release(&errmsg);
342 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
343 return 0;
344 }
345
346 if (starts_with(var, "submodule."))
347 return parse_submodule_config_option(var, value);
348
349 if (git_diff_heuristic_config(var, value, cb) < 0)
350 return -1;
351
352 return git_default_config(var, value, cb);
353 }
354
355 static char *quote_two(const char *one, const char *two)
356 {
357 int need_one = quote_c_style(one, NULL, NULL, 1);
358 int need_two = quote_c_style(two, NULL, NULL, 1);
359 struct strbuf res = STRBUF_INIT;
360
361 if (need_one + need_two) {
362 strbuf_addch(&res, '"');
363 quote_c_style(one, &res, NULL, 1);
364 quote_c_style(two, &res, NULL, 1);
365 strbuf_addch(&res, '"');
366 } else {
367 strbuf_addstr(&res, one);
368 strbuf_addstr(&res, two);
369 }
370 return strbuf_detach(&res, NULL);
371 }
372
373 static const char *external_diff(void)
374 {
375 static const char *external_diff_cmd = NULL;
376 static int done_preparing = 0;
377
378 if (done_preparing)
379 return external_diff_cmd;
380 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
381 if (!external_diff_cmd)
382 external_diff_cmd = external_diff_cmd_cfg;
383 done_preparing = 1;
384 return external_diff_cmd;
385 }
386
387 /*
388 * Keep track of files used for diffing. Sometimes such an entry
389 * refers to a temporary file, sometimes to an existing file, and
390 * sometimes to "/dev/null".
391 */
392 static struct diff_tempfile {
393 /*
394 * filename external diff should read from, or NULL if this
395 * entry is currently not in use:
396 */
397 const char *name;
398
399 char hex[GIT_MAX_HEXSZ + 1];
400 char mode[10];
401
402 /*
403 * If this diff_tempfile instance refers to a temporary file,
404 * this tempfile object is used to manage its lifetime.
405 */
406 struct tempfile tempfile;
407 } diff_temp[2];
408
409 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
410
411 struct emit_callback {
412 int color_diff;
413 unsigned ws_rule;
414 int blank_at_eof_in_preimage;
415 int blank_at_eof_in_postimage;
416 int lno_in_preimage;
417 int lno_in_postimage;
418 sane_truncate_fn truncate;
419 const char **label_path;
420 struct diff_words_data *diff_words;
421 struct diff_options *opt;
422 struct strbuf *header;
423 };
424
425 static int count_lines(const char *data, int size)
426 {
427 int count, ch, completely_empty = 1, nl_just_seen = 0;
428 count = 0;
429 while (0 < size--) {
430 ch = *data++;
431 if (ch == '\n') {
432 count++;
433 nl_just_seen = 1;
434 completely_empty = 0;
435 }
436 else {
437 nl_just_seen = 0;
438 completely_empty = 0;
439 }
440 }
441 if (completely_empty)
442 return 0;
443 if (!nl_just_seen)
444 count++; /* no trailing newline */
445 return count;
446 }
447
448 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
449 {
450 if (!DIFF_FILE_VALID(one)) {
451 mf->ptr = (char *)""; /* does not matter */
452 mf->size = 0;
453 return 0;
454 }
455 else if (diff_populate_filespec(one, 0))
456 return -1;
457
458 mf->ptr = one->data;
459 mf->size = one->size;
460 return 0;
461 }
462
463 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
464 static unsigned long diff_filespec_size(struct diff_filespec *one)
465 {
466 if (!DIFF_FILE_VALID(one))
467 return 0;
468 diff_populate_filespec(one, CHECK_SIZE_ONLY);
469 return one->size;
470 }
471
472 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
473 {
474 char *ptr = mf->ptr;
475 long size = mf->size;
476 int cnt = 0;
477
478 if (!size)
479 return cnt;
480 ptr += size - 1; /* pointing at the very end */
481 if (*ptr != '\n')
482 ; /* incomplete line */
483 else
484 ptr--; /* skip the last LF */
485 while (mf->ptr < ptr) {
486 char *prev_eol;
487 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
488 if (*prev_eol == '\n')
489 break;
490 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
491 break;
492 cnt++;
493 ptr = prev_eol - 1;
494 }
495 return cnt;
496 }
497
498 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
499 struct emit_callback *ecbdata)
500 {
501 int l1, l2, at;
502 unsigned ws_rule = ecbdata->ws_rule;
503 l1 = count_trailing_blank(mf1, ws_rule);
504 l2 = count_trailing_blank(mf2, ws_rule);
505 if (l2 <= l1) {
506 ecbdata->blank_at_eof_in_preimage = 0;
507 ecbdata->blank_at_eof_in_postimage = 0;
508 return;
509 }
510 at = count_lines(mf1->ptr, mf1->size);
511 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
512
513 at = count_lines(mf2->ptr, mf2->size);
514 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
515 }
516
517 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
518 int first, const char *line, int len)
519 {
520 int has_trailing_newline, has_trailing_carriage_return;
521 int nofirst;
522 FILE *file = o->file;
523
524 fputs(diff_line_prefix(o), file);
525
526 if (len == 0) {
527 has_trailing_newline = (first == '\n');
528 has_trailing_carriage_return = (!has_trailing_newline &&
529 (first == '\r'));
530 nofirst = has_trailing_newline || has_trailing_carriage_return;
531 } else {
532 has_trailing_newline = (len > 0 && line[len-1] == '\n');
533 if (has_trailing_newline)
534 len--;
535 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
536 if (has_trailing_carriage_return)
537 len--;
538 nofirst = 0;
539 }
540
541 if (len || !nofirst) {
542 fputs(set, file);
543 if (!nofirst)
544 fputc(first, file);
545 fwrite(line, len, 1, file);
546 fputs(reset, file);
547 }
548 if (has_trailing_carriage_return)
549 fputc('\r', file);
550 if (has_trailing_newline)
551 fputc('\n', file);
552 }
553
554 static void emit_line(struct diff_options *o, const char *set, const char *reset,
555 const char *line, int len)
556 {
557 emit_line_0(o, set, reset, line[0], line+1, len-1);
558 }
559
560 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
561 {
562 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
563 ecbdata->blank_at_eof_in_preimage &&
564 ecbdata->blank_at_eof_in_postimage &&
565 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
566 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
567 return 0;
568 return ws_blank_line(line, len, ecbdata->ws_rule);
569 }
570
571 static void emit_line_checked(const char *reset,
572 struct emit_callback *ecbdata,
573 const char *line, int len,
574 enum color_diff color,
575 unsigned ws_error_highlight,
576 char sign)
577 {
578 const char *set = diff_get_color(ecbdata->color_diff, color);
579 const char *ws = NULL;
580
581 if (ecbdata->opt->ws_error_highlight & ws_error_highlight) {
582 ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
583 if (!*ws)
584 ws = NULL;
585 }
586
587 if (!ws)
588 emit_line_0(ecbdata->opt, set, reset, sign, line, len);
589 else if (sign == '+' && new_blank_line_at_eof(ecbdata, line, len))
590 /* Blank line at EOF - paint '+' as well */
591 emit_line_0(ecbdata->opt, ws, reset, sign, line, len);
592 else {
593 /* Emit just the prefix, then the rest. */
594 emit_line_0(ecbdata->opt, set, reset, sign, "", 0);
595 ws_check_emit(line, len, ecbdata->ws_rule,
596 ecbdata->opt->file, set, reset, ws);
597 }
598 }
599
600 static void emit_add_line(const char *reset,
601 struct emit_callback *ecbdata,
602 const char *line, int len)
603 {
604 emit_line_checked(reset, ecbdata, line, len,
605 DIFF_FILE_NEW, WSEH_NEW, '+');
606 }
607
608 static void emit_del_line(const char *reset,
609 struct emit_callback *ecbdata,
610 const char *line, int len)
611 {
612 emit_line_checked(reset, ecbdata, line, len,
613 DIFF_FILE_OLD, WSEH_OLD, '-');
614 }
615
616 static void emit_context_line(const char *reset,
617 struct emit_callback *ecbdata,
618 const char *line, int len)
619 {
620 emit_line_checked(reset, ecbdata, line, len,
621 DIFF_CONTEXT, WSEH_CONTEXT, ' ');
622 }
623
624 static void emit_hunk_header(struct emit_callback *ecbdata,
625 const char *line, int len)
626 {
627 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
628 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
629 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
630 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
631 static const char atat[2] = { '@', '@' };
632 const char *cp, *ep;
633 struct strbuf msgbuf = STRBUF_INIT;
634 int org_len = len;
635 int i = 1;
636
637 /*
638 * As a hunk header must begin with "@@ -<old>, +<new> @@",
639 * it always is at least 10 bytes long.
640 */
641 if (len < 10 ||
642 memcmp(line, atat, 2) ||
643 !(ep = memmem(line + 2, len - 2, atat, 2))) {
644 emit_line(ecbdata->opt, context, reset, line, len);
645 return;
646 }
647 ep += 2; /* skip over @@ */
648
649 /* The hunk header in fraginfo color */
650 strbuf_addstr(&msgbuf, frag);
651 strbuf_add(&msgbuf, line, ep - line);
652 strbuf_addstr(&msgbuf, reset);
653
654 /*
655 * trailing "\r\n"
656 */
657 for ( ; i < 3; i++)
658 if (line[len - i] == '\r' || line[len - i] == '\n')
659 len--;
660
661 /* blank before the func header */
662 for (cp = ep; ep - line < len; ep++)
663 if (*ep != ' ' && *ep != '\t')
664 break;
665 if (ep != cp) {
666 strbuf_addstr(&msgbuf, context);
667 strbuf_add(&msgbuf, cp, ep - cp);
668 strbuf_addstr(&msgbuf, reset);
669 }
670
671 if (ep < line + len) {
672 strbuf_addstr(&msgbuf, func);
673 strbuf_add(&msgbuf, ep, line + len - ep);
674 strbuf_addstr(&msgbuf, reset);
675 }
676
677 strbuf_add(&msgbuf, line + len, org_len - len);
678 emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
679 strbuf_release(&msgbuf);
680 }
681
682 static struct diff_tempfile *claim_diff_tempfile(void) {
683 int i;
684 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
685 if (!diff_temp[i].name)
686 return diff_temp + i;
687 die("BUG: diff is failing to clean up its tempfiles");
688 }
689
690 static void remove_tempfile(void)
691 {
692 int i;
693 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
694 if (is_tempfile_active(&diff_temp[i].tempfile))
695 delete_tempfile(&diff_temp[i].tempfile);
696 diff_temp[i].name = NULL;
697 }
698 }
699
700 static void print_line_count(FILE *file, int count)
701 {
702 switch (count) {
703 case 0:
704 fprintf(file, "0,0");
705 break;
706 case 1:
707 fprintf(file, "1");
708 break;
709 default:
710 fprintf(file, "1,%d", count);
711 break;
712 }
713 }
714
715 static void emit_rewrite_lines(struct emit_callback *ecb,
716 int prefix, const char *data, int size)
717 {
718 const char *endp = NULL;
719 static const char *nneof = " No newline at end of file\n";
720 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
721
722 while (0 < size) {
723 int len;
724
725 endp = memchr(data, '\n', size);
726 len = endp ? (endp - data + 1) : size;
727 if (prefix != '+') {
728 ecb->lno_in_preimage++;
729 emit_del_line(reset, ecb, data, len);
730 } else {
731 ecb->lno_in_postimage++;
732 emit_add_line(reset, ecb, data, len);
733 }
734 size -= len;
735 data += len;
736 }
737 if (!endp) {
738 const char *context = diff_get_color(ecb->color_diff,
739 DIFF_CONTEXT);
740 putc('\n', ecb->opt->file);
741 emit_line_0(ecb->opt, context, reset, '\\',
742 nneof, strlen(nneof));
743 }
744 }
745
746 static void emit_rewrite_diff(const char *name_a,
747 const char *name_b,
748 struct diff_filespec *one,
749 struct diff_filespec *two,
750 struct userdiff_driver *textconv_one,
751 struct userdiff_driver *textconv_two,
752 struct diff_options *o)
753 {
754 int lc_a, lc_b;
755 const char *name_a_tab, *name_b_tab;
756 const char *metainfo = diff_get_color(o->use_color, DIFF_METAINFO);
757 const char *fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
758 const char *reset = diff_get_color(o->use_color, DIFF_RESET);
759 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
760 const char *a_prefix, *b_prefix;
761 char *data_one, *data_two;
762 size_t size_one, size_two;
763 struct emit_callback ecbdata;
764 const char *line_prefix = diff_line_prefix(o);
765
766 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
767 a_prefix = o->b_prefix;
768 b_prefix = o->a_prefix;
769 } else {
770 a_prefix = o->a_prefix;
771 b_prefix = o->b_prefix;
772 }
773
774 name_a += (*name_a == '/');
775 name_b += (*name_b == '/');
776 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
777 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
778
779 strbuf_reset(&a_name);
780 strbuf_reset(&b_name);
781 quote_two_c_style(&a_name, a_prefix, name_a, 0);
782 quote_two_c_style(&b_name, b_prefix, name_b, 0);
783
784 size_one = fill_textconv(textconv_one, one, &data_one);
785 size_two = fill_textconv(textconv_two, two, &data_two);
786
787 memset(&ecbdata, 0, sizeof(ecbdata));
788 ecbdata.color_diff = want_color(o->use_color);
789 ecbdata.ws_rule = whitespace_rule(name_b);
790 ecbdata.opt = o;
791 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
792 mmfile_t mf1, mf2;
793 mf1.ptr = (char *)data_one;
794 mf2.ptr = (char *)data_two;
795 mf1.size = size_one;
796 mf2.size = size_two;
797 check_blank_at_eof(&mf1, &mf2, &ecbdata);
798 }
799 ecbdata.lno_in_preimage = 1;
800 ecbdata.lno_in_postimage = 1;
801
802 lc_a = count_lines(data_one, size_one);
803 lc_b = count_lines(data_two, size_two);
804 fprintf(o->file,
805 "%s%s--- %s%s%s\n%s%s+++ %s%s%s\n%s%s@@ -",
806 line_prefix, metainfo, a_name.buf, name_a_tab, reset,
807 line_prefix, metainfo, b_name.buf, name_b_tab, reset,
808 line_prefix, fraginfo);
809 if (!o->irreversible_delete)
810 print_line_count(o->file, lc_a);
811 else
812 fprintf(o->file, "?,?");
813 fprintf(o->file, " +");
814 print_line_count(o->file, lc_b);
815 fprintf(o->file, " @@%s\n", reset);
816 if (lc_a && !o->irreversible_delete)
817 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
818 if (lc_b)
819 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
820 if (textconv_one)
821 free((char *)data_one);
822 if (textconv_two)
823 free((char *)data_two);
824 }
825
826 struct diff_words_buffer {
827 mmfile_t text;
828 long alloc;
829 struct diff_words_orig {
830 const char *begin, *end;
831 } *orig;
832 int orig_nr, orig_alloc;
833 };
834
835 static void diff_words_append(char *line, unsigned long len,
836 struct diff_words_buffer *buffer)
837 {
838 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
839 line++;
840 len--;
841 memcpy(buffer->text.ptr + buffer->text.size, line, len);
842 buffer->text.size += len;
843 buffer->text.ptr[buffer->text.size] = '\0';
844 }
845
846 struct diff_words_style_elem {
847 const char *prefix;
848 const char *suffix;
849 const char *color; /* NULL; filled in by the setup code if
850 * color is enabled */
851 };
852
853 struct diff_words_style {
854 enum diff_words_type type;
855 struct diff_words_style_elem new, old, ctx;
856 const char *newline;
857 };
858
859 static struct diff_words_style diff_words_styles[] = {
860 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
861 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
862 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
863 };
864
865 struct diff_words_data {
866 struct diff_words_buffer minus, plus;
867 const char *current_plus;
868 int last_minus;
869 struct diff_options *opt;
870 regex_t *word_regex;
871 enum diff_words_type type;
872 struct diff_words_style *style;
873 };
874
875 static int fn_out_diff_words_write_helper(FILE *fp,
876 struct diff_words_style_elem *st_el,
877 const char *newline,
878 size_t count, const char *buf,
879 const char *line_prefix)
880 {
881 int print = 0;
882
883 while (count) {
884 char *p = memchr(buf, '\n', count);
885 if (print)
886 fputs(line_prefix, fp);
887 if (p != buf) {
888 if (st_el->color && fputs(st_el->color, fp) < 0)
889 return -1;
890 if (fputs(st_el->prefix, fp) < 0 ||
891 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
892 fputs(st_el->suffix, fp) < 0)
893 return -1;
894 if (st_el->color && *st_el->color
895 && fputs(GIT_COLOR_RESET, fp) < 0)
896 return -1;
897 }
898 if (!p)
899 return 0;
900 if (fputs(newline, fp) < 0)
901 return -1;
902 count -= p + 1 - buf;
903 buf = p + 1;
904 print = 1;
905 }
906 return 0;
907 }
908
909 /*
910 * '--color-words' algorithm can be described as:
911 *
912 * 1. collect the minus/plus lines of a diff hunk, divided into
913 * minus-lines and plus-lines;
914 *
915 * 2. break both minus-lines and plus-lines into words and
916 * place them into two mmfile_t with one word for each line;
917 *
918 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
919 *
920 * And for the common parts of the both file, we output the plus side text.
921 * diff_words->current_plus is used to trace the current position of the plus file
922 * which printed. diff_words->last_minus is used to trace the last minus word
923 * printed.
924 *
925 * For '--graph' to work with '--color-words', we need to output the graph prefix
926 * on each line of color words output. Generally, there are two conditions on
927 * which we should output the prefix.
928 *
929 * 1. diff_words->last_minus == 0 &&
930 * diff_words->current_plus == diff_words->plus.text.ptr
931 *
932 * that is: the plus text must start as a new line, and if there is no minus
933 * word printed, a graph prefix must be printed.
934 *
935 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
936 * *(diff_words->current_plus - 1) == '\n'
937 *
938 * that is: a graph prefix must be printed following a '\n'
939 */
940 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
941 {
942 if ((diff_words->last_minus == 0 &&
943 diff_words->current_plus == diff_words->plus.text.ptr) ||
944 (diff_words->current_plus > diff_words->plus.text.ptr &&
945 *(diff_words->current_plus - 1) == '\n')) {
946 return 1;
947 } else {
948 return 0;
949 }
950 }
951
952 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
953 {
954 struct diff_words_data *diff_words = priv;
955 struct diff_words_style *style = diff_words->style;
956 int minus_first, minus_len, plus_first, plus_len;
957 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
958 struct diff_options *opt = diff_words->opt;
959 const char *line_prefix;
960
961 if (line[0] != '@' || parse_hunk_header(line, len,
962 &minus_first, &minus_len, &plus_first, &plus_len))
963 return;
964
965 assert(opt);
966 line_prefix = diff_line_prefix(opt);
967
968 /* POSIX requires that first be decremented by one if len == 0... */
969 if (minus_len) {
970 minus_begin = diff_words->minus.orig[minus_first].begin;
971 minus_end =
972 diff_words->minus.orig[minus_first + minus_len - 1].end;
973 } else
974 minus_begin = minus_end =
975 diff_words->minus.orig[minus_first].end;
976
977 if (plus_len) {
978 plus_begin = diff_words->plus.orig[plus_first].begin;
979 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
980 } else
981 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
982
983 if (color_words_output_graph_prefix(diff_words)) {
984 fputs(line_prefix, diff_words->opt->file);
985 }
986 if (diff_words->current_plus != plus_begin) {
987 fn_out_diff_words_write_helper(diff_words->opt->file,
988 &style->ctx, style->newline,
989 plus_begin - diff_words->current_plus,
990 diff_words->current_plus, line_prefix);
991 if (*(plus_begin - 1) == '\n')
992 fputs(line_prefix, diff_words->opt->file);
993 }
994 if (minus_begin != minus_end) {
995 fn_out_diff_words_write_helper(diff_words->opt->file,
996 &style->old, style->newline,
997 minus_end - minus_begin, minus_begin,
998 line_prefix);
999 }
1000 if (plus_begin != plus_end) {
1001 fn_out_diff_words_write_helper(diff_words->opt->file,
1002 &style->new, style->newline,
1003 plus_end - plus_begin, plus_begin,
1004 line_prefix);
1005 }
1006
1007 diff_words->current_plus = plus_end;
1008 diff_words->last_minus = minus_first;
1009 }
1010
1011 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1012 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1013 int *begin, int *end)
1014 {
1015 if (word_regex && *begin < buffer->size) {
1016 regmatch_t match[1];
1017 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1018 buffer->size - *begin, 1, match, 0)) {
1019 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1020 '\n', match[0].rm_eo - match[0].rm_so);
1021 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1022 *begin += match[0].rm_so;
1023 return *begin >= *end;
1024 }
1025 return -1;
1026 }
1027
1028 /* find the next word */
1029 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1030 (*begin)++;
1031 if (*begin >= buffer->size)
1032 return -1;
1033
1034 /* find the end of the word */
1035 *end = *begin + 1;
1036 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1037 (*end)++;
1038
1039 return 0;
1040 }
1041
1042 /*
1043 * This function splits the words in buffer->text, stores the list with
1044 * newline separator into out, and saves the offsets of the original words
1045 * in buffer->orig.
1046 */
1047 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1048 regex_t *word_regex)
1049 {
1050 int i, j;
1051 long alloc = 0;
1052
1053 out->size = 0;
1054 out->ptr = NULL;
1055
1056 /* fake an empty "0th" word */
1057 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1058 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1059 buffer->orig_nr = 1;
1060
1061 for (i = 0; i < buffer->text.size; i++) {
1062 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1063 return;
1064
1065 /* store original boundaries */
1066 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1067 buffer->orig_alloc);
1068 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1069 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1070 buffer->orig_nr++;
1071
1072 /* store one word */
1073 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1074 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1075 out->ptr[out->size + j - i] = '\n';
1076 out->size += j - i + 1;
1077
1078 i = j - 1;
1079 }
1080 }
1081
1082 /* this executes the word diff on the accumulated buffers */
1083 static void diff_words_show(struct diff_words_data *diff_words)
1084 {
1085 xpparam_t xpp;
1086 xdemitconf_t xecfg;
1087 mmfile_t minus, plus;
1088 struct diff_words_style *style = diff_words->style;
1089
1090 struct diff_options *opt = diff_words->opt;
1091 const char *line_prefix;
1092
1093 assert(opt);
1094 line_prefix = diff_line_prefix(opt);
1095
1096 /* special case: only removal */
1097 if (!diff_words->plus.text.size) {
1098 fputs(line_prefix, diff_words->opt->file);
1099 fn_out_diff_words_write_helper(diff_words->opt->file,
1100 &style->old, style->newline,
1101 diff_words->minus.text.size,
1102 diff_words->minus.text.ptr, line_prefix);
1103 diff_words->minus.text.size = 0;
1104 return;
1105 }
1106
1107 diff_words->current_plus = diff_words->plus.text.ptr;
1108 diff_words->last_minus = 0;
1109
1110 memset(&xpp, 0, sizeof(xpp));
1111 memset(&xecfg, 0, sizeof(xecfg));
1112 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1113 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1114 xpp.flags = 0;
1115 /* as only the hunk header will be parsed, we need a 0-context */
1116 xecfg.ctxlen = 0;
1117 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1118 &xpp, &xecfg))
1119 die("unable to generate word diff");
1120 free(minus.ptr);
1121 free(plus.ptr);
1122 if (diff_words->current_plus != diff_words->plus.text.ptr +
1123 diff_words->plus.text.size) {
1124 if (color_words_output_graph_prefix(diff_words))
1125 fputs(line_prefix, diff_words->opt->file);
1126 fn_out_diff_words_write_helper(diff_words->opt->file,
1127 &style->ctx, style->newline,
1128 diff_words->plus.text.ptr + diff_words->plus.text.size
1129 - diff_words->current_plus, diff_words->current_plus,
1130 line_prefix);
1131 }
1132 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1133 }
1134
1135 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1136 static void diff_words_flush(struct emit_callback *ecbdata)
1137 {
1138 if (ecbdata->diff_words->minus.text.size ||
1139 ecbdata->diff_words->plus.text.size)
1140 diff_words_show(ecbdata->diff_words);
1141 }
1142
1143 static void diff_filespec_load_driver(struct diff_filespec *one)
1144 {
1145 /* Use already-loaded driver */
1146 if (one->driver)
1147 return;
1148
1149 if (S_ISREG(one->mode))
1150 one->driver = userdiff_find_by_path(one->path);
1151
1152 /* Fallback to default settings */
1153 if (!one->driver)
1154 one->driver = userdiff_find_by_name("default");
1155 }
1156
1157 static const char *userdiff_word_regex(struct diff_filespec *one)
1158 {
1159 diff_filespec_load_driver(one);
1160 return one->driver->word_regex;
1161 }
1162
1163 static void init_diff_words_data(struct emit_callback *ecbdata,
1164 struct diff_options *orig_opts,
1165 struct diff_filespec *one,
1166 struct diff_filespec *two)
1167 {
1168 int i;
1169 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1170 memcpy(o, orig_opts, sizeof(struct diff_options));
1171
1172 ecbdata->diff_words =
1173 xcalloc(1, sizeof(struct diff_words_data));
1174 ecbdata->diff_words->type = o->word_diff;
1175 ecbdata->diff_words->opt = o;
1176 if (!o->word_regex)
1177 o->word_regex = userdiff_word_regex(one);
1178 if (!o->word_regex)
1179 o->word_regex = userdiff_word_regex(two);
1180 if (!o->word_regex)
1181 o->word_regex = diff_word_regex_cfg;
1182 if (o->word_regex) {
1183 ecbdata->diff_words->word_regex = (regex_t *)
1184 xmalloc(sizeof(regex_t));
1185 if (regcomp(ecbdata->diff_words->word_regex,
1186 o->word_regex,
1187 REG_EXTENDED | REG_NEWLINE))
1188 die ("Invalid regular expression: %s",
1189 o->word_regex);
1190 }
1191 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1192 if (o->word_diff == diff_words_styles[i].type) {
1193 ecbdata->diff_words->style =
1194 &diff_words_styles[i];
1195 break;
1196 }
1197 }
1198 if (want_color(o->use_color)) {
1199 struct diff_words_style *st = ecbdata->diff_words->style;
1200 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1201 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1202 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1203 }
1204 }
1205
1206 static void free_diff_words_data(struct emit_callback *ecbdata)
1207 {
1208 if (ecbdata->diff_words) {
1209 diff_words_flush(ecbdata);
1210 free (ecbdata->diff_words->opt);
1211 free (ecbdata->diff_words->minus.text.ptr);
1212 free (ecbdata->diff_words->minus.orig);
1213 free (ecbdata->diff_words->plus.text.ptr);
1214 free (ecbdata->diff_words->plus.orig);
1215 if (ecbdata->diff_words->word_regex) {
1216 regfree(ecbdata->diff_words->word_regex);
1217 free(ecbdata->diff_words->word_regex);
1218 }
1219 FREE_AND_NULL(ecbdata->diff_words);
1220 }
1221 }
1222
1223 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1224 {
1225 if (want_color(diff_use_color))
1226 return diff_colors[ix];
1227 return "";
1228 }
1229
1230 const char *diff_line_prefix(struct diff_options *opt)
1231 {
1232 struct strbuf *msgbuf;
1233 if (!opt->output_prefix)
1234 return "";
1235
1236 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1237 return msgbuf->buf;
1238 }
1239
1240 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1241 {
1242 const char *cp;
1243 unsigned long allot;
1244 size_t l = len;
1245
1246 if (ecb->truncate)
1247 return ecb->truncate(line, len);
1248 cp = line;
1249 allot = l;
1250 while (0 < l) {
1251 (void) utf8_width(&cp, &l);
1252 if (!cp)
1253 break; /* truncated in the middle? */
1254 }
1255 return allot - l;
1256 }
1257
1258 static void find_lno(const char *line, struct emit_callback *ecbdata)
1259 {
1260 const char *p;
1261 ecbdata->lno_in_preimage = 0;
1262 ecbdata->lno_in_postimage = 0;
1263 p = strchr(line, '-');
1264 if (!p)
1265 return; /* cannot happen */
1266 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1267 p = strchr(p, '+');
1268 if (!p)
1269 return; /* cannot happen */
1270 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1271 }
1272
1273 static void fn_out_consume(void *priv, char *line, unsigned long len)
1274 {
1275 struct emit_callback *ecbdata = priv;
1276 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
1277 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1278 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1279 struct diff_options *o = ecbdata->opt;
1280 const char *line_prefix = diff_line_prefix(o);
1281
1282 o->found_changes = 1;
1283
1284 if (ecbdata->header) {
1285 fprintf(o->file, "%s", ecbdata->header->buf);
1286 strbuf_reset(ecbdata->header);
1287 ecbdata->header = NULL;
1288 }
1289
1290 if (ecbdata->label_path[0]) {
1291 const char *name_a_tab, *name_b_tab;
1292
1293 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
1294 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
1295
1296 fprintf(o->file, "%s%s--- %s%s%s\n",
1297 line_prefix, meta, ecbdata->label_path[0], reset, name_a_tab);
1298 fprintf(o->file, "%s%s+++ %s%s%s\n",
1299 line_prefix, meta, ecbdata->label_path[1], reset, name_b_tab);
1300 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1301 }
1302
1303 if (diff_suppress_blank_empty
1304 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1305 line[0] = '\n';
1306 len = 1;
1307 }
1308
1309 if (line[0] == '@') {
1310 if (ecbdata->diff_words)
1311 diff_words_flush(ecbdata);
1312 len = sane_truncate_line(ecbdata, line, len);
1313 find_lno(line, ecbdata);
1314 emit_hunk_header(ecbdata, line, len);
1315 if (line[len-1] != '\n')
1316 putc('\n', o->file);
1317 return;
1318 }
1319
1320 if (ecbdata->diff_words) {
1321 if (line[0] == '-') {
1322 diff_words_append(line, len,
1323 &ecbdata->diff_words->minus);
1324 return;
1325 } else if (line[0] == '+') {
1326 diff_words_append(line, len,
1327 &ecbdata->diff_words->plus);
1328 return;
1329 } else if (starts_with(line, "\\ ")) {
1330 /*
1331 * Eat the "no newline at eof" marker as if we
1332 * saw a "+" or "-" line with nothing on it,
1333 * and return without diff_words_flush() to
1334 * defer processing. If this is the end of
1335 * preimage, more "+" lines may come after it.
1336 */
1337 return;
1338 }
1339 diff_words_flush(ecbdata);
1340 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
1341 emit_line(o, context, reset, line, len);
1342 fputs("~\n", o->file);
1343 } else {
1344 /*
1345 * Skip the prefix character, if any. With
1346 * diff_suppress_blank_empty, there may be
1347 * none.
1348 */
1349 if (line[0] != '\n') {
1350 line++;
1351 len--;
1352 }
1353 emit_line(o, context, reset, line, len);
1354 }
1355 return;
1356 }
1357
1358 switch (line[0]) {
1359 case '+':
1360 ecbdata->lno_in_postimage++;
1361 emit_add_line(reset, ecbdata, line + 1, len - 1);
1362 break;
1363 case '-':
1364 ecbdata->lno_in_preimage++;
1365 emit_del_line(reset, ecbdata, line + 1, len - 1);
1366 break;
1367 case ' ':
1368 ecbdata->lno_in_postimage++;
1369 ecbdata->lno_in_preimage++;
1370 emit_context_line(reset, ecbdata, line + 1, len - 1);
1371 break;
1372 default:
1373 /* incomplete line at the end */
1374 ecbdata->lno_in_preimage++;
1375 emit_line(o, diff_get_color(ecbdata->color_diff, DIFF_CONTEXT),
1376 reset, line, len);
1377 break;
1378 }
1379 }
1380
1381 static char *pprint_rename(const char *a, const char *b)
1382 {
1383 const char *old = a;
1384 const char *new = b;
1385 struct strbuf name = STRBUF_INIT;
1386 int pfx_length, sfx_length;
1387 int pfx_adjust_for_slash;
1388 int len_a = strlen(a);
1389 int len_b = strlen(b);
1390 int a_midlen, b_midlen;
1391 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1392 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1393
1394 if (qlen_a || qlen_b) {
1395 quote_c_style(a, &name, NULL, 0);
1396 strbuf_addstr(&name, " => ");
1397 quote_c_style(b, &name, NULL, 0);
1398 return strbuf_detach(&name, NULL);
1399 }
1400
1401 /* Find common prefix */
1402 pfx_length = 0;
1403 while (*old && *new && *old == *new) {
1404 if (*old == '/')
1405 pfx_length = old - a + 1;
1406 old++;
1407 new++;
1408 }
1409
1410 /* Find common suffix */
1411 old = a + len_a;
1412 new = b + len_b;
1413 sfx_length = 0;
1414 /*
1415 * If there is a common prefix, it must end in a slash. In
1416 * that case we let this loop run 1 into the prefix to see the
1417 * same slash.
1418 *
1419 * If there is no common prefix, we cannot do this as it would
1420 * underrun the input strings.
1421 */
1422 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
1423 while (a + pfx_length - pfx_adjust_for_slash <= old &&
1424 b + pfx_length - pfx_adjust_for_slash <= new &&
1425 *old == *new) {
1426 if (*old == '/')
1427 sfx_length = len_a - (old - a);
1428 old--;
1429 new--;
1430 }
1431
1432 /*
1433 * pfx{mid-a => mid-b}sfx
1434 * {pfx-a => pfx-b}sfx
1435 * pfx{sfx-a => sfx-b}
1436 * name-a => name-b
1437 */
1438 a_midlen = len_a - pfx_length - sfx_length;
1439 b_midlen = len_b - pfx_length - sfx_length;
1440 if (a_midlen < 0)
1441 a_midlen = 0;
1442 if (b_midlen < 0)
1443 b_midlen = 0;
1444
1445 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1446 if (pfx_length + sfx_length) {
1447 strbuf_add(&name, a, pfx_length);
1448 strbuf_addch(&name, '{');
1449 }
1450 strbuf_add(&name, a + pfx_length, a_midlen);
1451 strbuf_addstr(&name, " => ");
1452 strbuf_add(&name, b + pfx_length, b_midlen);
1453 if (pfx_length + sfx_length) {
1454 strbuf_addch(&name, '}');
1455 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1456 }
1457 return strbuf_detach(&name, NULL);
1458 }
1459
1460 struct diffstat_t {
1461 int nr;
1462 int alloc;
1463 struct diffstat_file {
1464 char *from_name;
1465 char *name;
1466 char *print_name;
1467 unsigned is_unmerged:1;
1468 unsigned is_binary:1;
1469 unsigned is_renamed:1;
1470 unsigned is_interesting:1;
1471 uintmax_t added, deleted;
1472 } **files;
1473 };
1474
1475 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1476 const char *name_a,
1477 const char *name_b)
1478 {
1479 struct diffstat_file *x;
1480 x = xcalloc(1, sizeof(*x));
1481 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
1482 diffstat->files[diffstat->nr++] = x;
1483 if (name_b) {
1484 x->from_name = xstrdup(name_a);
1485 x->name = xstrdup(name_b);
1486 x->is_renamed = 1;
1487 }
1488 else {
1489 x->from_name = NULL;
1490 x->name = xstrdup(name_a);
1491 }
1492 return x;
1493 }
1494
1495 static void diffstat_consume(void *priv, char *line, unsigned long len)
1496 {
1497 struct diffstat_t *diffstat = priv;
1498 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1499
1500 if (line[0] == '+')
1501 x->added++;
1502 else if (line[0] == '-')
1503 x->deleted++;
1504 }
1505
1506 const char mime_boundary_leader[] = "------------";
1507
1508 static int scale_linear(int it, int width, int max_change)
1509 {
1510 if (!it)
1511 return 0;
1512 /*
1513 * make sure that at least one '-' or '+' is printed if
1514 * there is any change to this path. The easiest way is to
1515 * scale linearly as if the alloted width is one column shorter
1516 * than it is, and then add 1 to the result.
1517 */
1518 return 1 + (it * (width - 1) / max_change);
1519 }
1520
1521 static void show_name(FILE *file,
1522 const char *prefix, const char *name, int len)
1523 {
1524 fprintf(file, " %s%-*s |", prefix, len, name);
1525 }
1526
1527 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1528 {
1529 if (cnt <= 0)
1530 return;
1531 fprintf(file, "%s", set);
1532 while (cnt--)
1533 putc(ch, file);
1534 fprintf(file, "%s", reset);
1535 }
1536
1537 static void fill_print_name(struct diffstat_file *file)
1538 {
1539 char *pname;
1540
1541 if (file->print_name)
1542 return;
1543
1544 if (!file->is_renamed) {
1545 struct strbuf buf = STRBUF_INIT;
1546 if (quote_c_style(file->name, &buf, NULL, 0)) {
1547 pname = strbuf_detach(&buf, NULL);
1548 } else {
1549 pname = file->name;
1550 strbuf_release(&buf);
1551 }
1552 } else {
1553 pname = pprint_rename(file->from_name, file->name);
1554 }
1555 file->print_name = pname;
1556 }
1557
1558 int print_stat_summary(FILE *fp, int files, int insertions, int deletions)
1559 {
1560 struct strbuf sb = STRBUF_INIT;
1561 int ret;
1562
1563 if (!files) {
1564 assert(insertions == 0 && deletions == 0);
1565 return fprintf(fp, "%s\n", " 0 files changed");
1566 }
1567
1568 strbuf_addf(&sb,
1569 (files == 1) ? " %d file changed" : " %d files changed",
1570 files);
1571
1572 /*
1573 * For binary diff, the caller may want to print "x files
1574 * changed" with insertions == 0 && deletions == 0.
1575 *
1576 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
1577 * is probably less confusing (i.e skip over "2 files changed
1578 * but nothing about added/removed lines? Is this a bug in Git?").
1579 */
1580 if (insertions || deletions == 0) {
1581 strbuf_addf(&sb,
1582 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
1583 insertions);
1584 }
1585
1586 if (deletions || insertions == 0) {
1587 strbuf_addf(&sb,
1588 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
1589 deletions);
1590 }
1591 strbuf_addch(&sb, '\n');
1592 ret = fputs(sb.buf, fp);
1593 strbuf_release(&sb);
1594 return ret;
1595 }
1596
1597 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1598 {
1599 int i, len, add, del, adds = 0, dels = 0;
1600 uintmax_t max_change = 0, max_len = 0;
1601 int total_files = data->nr, count;
1602 int width, name_width, graph_width, number_width = 0, bin_width = 0;
1603 const char *reset, *add_c, *del_c;
1604 const char *line_prefix = "";
1605 int extra_shown = 0;
1606
1607 if (data->nr == 0)
1608 return;
1609
1610 line_prefix = diff_line_prefix(options);
1611 count = options->stat_count ? options->stat_count : data->nr;
1612
1613 reset = diff_get_color_opt(options, DIFF_RESET);
1614 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1615 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1616
1617 /*
1618 * Find the longest filename and max number of changes
1619 */
1620 for (i = 0; (i < count) && (i < data->nr); i++) {
1621 struct diffstat_file *file = data->files[i];
1622 uintmax_t change = file->added + file->deleted;
1623
1624 if (!file->is_interesting && (change == 0)) {
1625 count++; /* not shown == room for one more */
1626 continue;
1627 }
1628 fill_print_name(file);
1629 len = strlen(file->print_name);
1630 if (max_len < len)
1631 max_len = len;
1632
1633 if (file->is_unmerged) {
1634 /* "Unmerged" is 8 characters */
1635 bin_width = bin_width < 8 ? 8 : bin_width;
1636 continue;
1637 }
1638 if (file->is_binary) {
1639 /* "Bin XXX -> YYY bytes" */
1640 int w = 14 + decimal_width(file->added)
1641 + decimal_width(file->deleted);
1642 bin_width = bin_width < w ? w : bin_width;
1643 /* Display change counts aligned with "Bin" */
1644 number_width = 3;
1645 continue;
1646 }
1647
1648 if (max_change < change)
1649 max_change = change;
1650 }
1651 count = i; /* where we can stop scanning in data->files[] */
1652
1653 /*
1654 * We have width = stat_width or term_columns() columns total.
1655 * We want a maximum of min(max_len, stat_name_width) for the name part.
1656 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1657 * We also need 1 for " " and 4 + decimal_width(max_change)
1658 * for " | NNNN " and one the empty column at the end, altogether
1659 * 6 + decimal_width(max_change).
1660 *
1661 * If there's not enough space, we will use the smaller of
1662 * stat_name_width (if set) and 5/8*width for the filename,
1663 * and the rest for constant elements + graph part, but no more
1664 * than stat_graph_width for the graph part.
1665 * (5/8 gives 50 for filename and 30 for the constant parts + graph
1666 * for the standard terminal size).
1667 *
1668 * In other words: stat_width limits the maximum width, and
1669 * stat_name_width fixes the maximum width of the filename,
1670 * and is also used to divide available columns if there
1671 * aren't enough.
1672 *
1673 * Binary files are displayed with "Bin XXX -> YYY bytes"
1674 * instead of the change count and graph. This part is treated
1675 * similarly to the graph part, except that it is not
1676 * "scaled". If total width is too small to accommodate the
1677 * guaranteed minimum width of the filename part and the
1678 * separators and this message, this message will "overflow"
1679 * making the line longer than the maximum width.
1680 */
1681
1682 if (options->stat_width == -1)
1683 width = term_columns() - strlen(line_prefix);
1684 else
1685 width = options->stat_width ? options->stat_width : 80;
1686 number_width = decimal_width(max_change) > number_width ?
1687 decimal_width(max_change) : number_width;
1688
1689 if (options->stat_graph_width == -1)
1690 options->stat_graph_width = diff_stat_graph_width;
1691
1692 /*
1693 * Guarantee 3/8*16==6 for the graph part
1694 * and 5/8*16==10 for the filename part
1695 */
1696 if (width < 16 + 6 + number_width)
1697 width = 16 + 6 + number_width;
1698
1699 /*
1700 * First assign sizes that are wanted, ignoring available width.
1701 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
1702 * starting from "XXX" should fit in graph_width.
1703 */
1704 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
1705 if (options->stat_graph_width &&
1706 options->stat_graph_width < graph_width)
1707 graph_width = options->stat_graph_width;
1708
1709 name_width = (options->stat_name_width > 0 &&
1710 options->stat_name_width < max_len) ?
1711 options->stat_name_width : max_len;
1712
1713 /*
1714 * Adjust adjustable widths not to exceed maximum width
1715 */
1716 if (name_width + number_width + 6 + graph_width > width) {
1717 if (graph_width > width * 3/8 - number_width - 6) {
1718 graph_width = width * 3/8 - number_width - 6;
1719 if (graph_width < 6)
1720 graph_width = 6;
1721 }
1722
1723 if (options->stat_graph_width &&
1724 graph_width > options->stat_graph_width)
1725 graph_width = options->stat_graph_width;
1726 if (name_width > width - number_width - 6 - graph_width)
1727 name_width = width - number_width - 6 - graph_width;
1728 else
1729 graph_width = width - number_width - 6 - name_width;
1730 }
1731
1732 /*
1733 * From here name_width is the width of the name area,
1734 * and graph_width is the width of the graph area.
1735 * max_change is used to scale graph properly.
1736 */
1737 for (i = 0; i < count; i++) {
1738 const char *prefix = "";
1739 struct diffstat_file *file = data->files[i];
1740 char *name = file->print_name;
1741 uintmax_t added = file->added;
1742 uintmax_t deleted = file->deleted;
1743 int name_len;
1744
1745 if (!file->is_interesting && (added + deleted == 0))
1746 continue;
1747
1748 /*
1749 * "scale" the filename
1750 */
1751 len = name_width;
1752 name_len = strlen(name);
1753 if (name_width < name_len) {
1754 char *slash;
1755 prefix = "...";
1756 len -= 3;
1757 name += name_len - len;
1758 slash = strchr(name, '/');
1759 if (slash)
1760 name = slash;
1761 }
1762
1763 if (file->is_binary) {
1764 fprintf(options->file, "%s", line_prefix);
1765 show_name(options->file, prefix, name, len);
1766 fprintf(options->file, " %*s", number_width, "Bin");
1767 if (!added && !deleted) {
1768 putc('\n', options->file);
1769 continue;
1770 }
1771 fprintf(options->file, " %s%"PRIuMAX"%s",
1772 del_c, deleted, reset);
1773 fprintf(options->file, " -> ");
1774 fprintf(options->file, "%s%"PRIuMAX"%s",
1775 add_c, added, reset);
1776 fprintf(options->file, " bytes");
1777 fprintf(options->file, "\n");
1778 continue;
1779 }
1780 else if (file->is_unmerged) {
1781 fprintf(options->file, "%s", line_prefix);
1782 show_name(options->file, prefix, name, len);
1783 fprintf(options->file, " Unmerged\n");
1784 continue;
1785 }
1786
1787 /*
1788 * scale the add/delete
1789 */
1790 add = added;
1791 del = deleted;
1792
1793 if (graph_width <= max_change) {
1794 int total = scale_linear(add + del, graph_width, max_change);
1795 if (total < 2 && add && del)
1796 /* width >= 2 due to the sanity check */
1797 total = 2;
1798 if (add < del) {
1799 add = scale_linear(add, graph_width, max_change);
1800 del = total - add;
1801 } else {
1802 del = scale_linear(del, graph_width, max_change);
1803 add = total - del;
1804 }
1805 }
1806 fprintf(options->file, "%s", line_prefix);
1807 show_name(options->file, prefix, name, len);
1808 fprintf(options->file, " %*"PRIuMAX"%s",
1809 number_width, added + deleted,
1810 added + deleted ? " " : "");
1811 show_graph(options->file, '+', add, add_c, reset);
1812 show_graph(options->file, '-', del, del_c, reset);
1813 fprintf(options->file, "\n");
1814 }
1815
1816 for (i = 0; i < data->nr; i++) {
1817 struct diffstat_file *file = data->files[i];
1818 uintmax_t added = file->added;
1819 uintmax_t deleted = file->deleted;
1820
1821 if (file->is_unmerged ||
1822 (!file->is_interesting && (added + deleted == 0))) {
1823 total_files--;
1824 continue;
1825 }
1826
1827 if (!file->is_binary) {
1828 adds += added;
1829 dels += deleted;
1830 }
1831 if (i < count)
1832 continue;
1833 if (!extra_shown)
1834 fprintf(options->file, "%s ...\n", line_prefix);
1835 extra_shown = 1;
1836 }
1837 fprintf(options->file, "%s", line_prefix);
1838 print_stat_summary(options->file, total_files, adds, dels);
1839 }
1840
1841 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1842 {
1843 int i, adds = 0, dels = 0, total_files = data->nr;
1844
1845 if (data->nr == 0)
1846 return;
1847
1848 for (i = 0; i < data->nr; i++) {
1849 int added = data->files[i]->added;
1850 int deleted= data->files[i]->deleted;
1851
1852 if (data->files[i]->is_unmerged ||
1853 (!data->files[i]->is_interesting && (added + deleted == 0))) {
1854 total_files--;
1855 } else if (!data->files[i]->is_binary) { /* don't count bytes */
1856 adds += added;
1857 dels += deleted;
1858 }
1859 }
1860 fprintf(options->file, "%s", diff_line_prefix(options));
1861 print_stat_summary(options->file, total_files, adds, dels);
1862 }
1863
1864 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1865 {
1866 int i;
1867
1868 if (data->nr == 0)
1869 return;
1870
1871 for (i = 0; i < data->nr; i++) {
1872 struct diffstat_file *file = data->files[i];
1873
1874 fprintf(options->file, "%s", diff_line_prefix(options));
1875
1876 if (file->is_binary)
1877 fprintf(options->file, "-\t-\t");
1878 else
1879 fprintf(options->file,
1880 "%"PRIuMAX"\t%"PRIuMAX"\t",
1881 file->added, file->deleted);
1882 if (options->line_termination) {
1883 fill_print_name(file);
1884 if (!file->is_renamed)
1885 write_name_quoted(file->name, options->file,
1886 options->line_termination);
1887 else {
1888 fputs(file->print_name, options->file);
1889 putc(options->line_termination, options->file);
1890 }
1891 } else {
1892 if (file->is_renamed) {
1893 putc('\0', options->file);
1894 write_name_quoted(file->from_name, options->file, '\0');
1895 }
1896 write_name_quoted(file->name, options->file, '\0');
1897 }
1898 }
1899 }
1900
1901 struct dirstat_file {
1902 const char *name;
1903 unsigned long changed;
1904 };
1905
1906 struct dirstat_dir {
1907 struct dirstat_file *files;
1908 int alloc, nr, permille, cumulative;
1909 };
1910
1911 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
1912 unsigned long changed, const char *base, int baselen)
1913 {
1914 unsigned long this_dir = 0;
1915 unsigned int sources = 0;
1916 const char *line_prefix = diff_line_prefix(opt);
1917
1918 while (dir->nr) {
1919 struct dirstat_file *f = dir->files;
1920 int namelen = strlen(f->name);
1921 unsigned long this;
1922 char *slash;
1923
1924 if (namelen < baselen)
1925 break;
1926 if (memcmp(f->name, base, baselen))
1927 break;
1928 slash = strchr(f->name + baselen, '/');
1929 if (slash) {
1930 int newbaselen = slash + 1 - f->name;
1931 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
1932 sources++;
1933 } else {
1934 this = f->changed;
1935 dir->files++;
1936 dir->nr--;
1937 sources += 2;
1938 }
1939 this_dir += this;
1940 }
1941
1942 /*
1943 * We don't report dirstat's for
1944 * - the top level
1945 * - or cases where everything came from a single directory
1946 * under this directory (sources == 1).
1947 */
1948 if (baselen && sources != 1) {
1949 if (this_dir) {
1950 int permille = this_dir * 1000 / changed;
1951 if (permille >= dir->permille) {
1952 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
1953 permille / 10, permille % 10, baselen, base);
1954 if (!dir->cumulative)
1955 return 0;
1956 }
1957 }
1958 }
1959 return this_dir;
1960 }
1961
1962 static int dirstat_compare(const void *_a, const void *_b)
1963 {
1964 const struct dirstat_file *a = _a;
1965 const struct dirstat_file *b = _b;
1966 return strcmp(a->name, b->name);
1967 }
1968
1969 static void show_dirstat(struct diff_options *options)
1970 {
1971 int i;
1972 unsigned long changed;
1973 struct dirstat_dir dir;
1974 struct diff_queue_struct *q = &diff_queued_diff;
1975
1976 dir.files = NULL;
1977 dir.alloc = 0;
1978 dir.nr = 0;
1979 dir.permille = options->dirstat_permille;
1980 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1981
1982 changed = 0;
1983 for (i = 0; i < q->nr; i++) {
1984 struct diff_filepair *p = q->queue[i];
1985 const char *name;
1986 unsigned long copied, added, damage;
1987 int content_changed;
1988
1989 name = p->two->path ? p->two->path : p->one->path;
1990
1991 if (p->one->oid_valid && p->two->oid_valid)
1992 content_changed = oidcmp(&p->one->oid, &p->two->oid);
1993 else
1994 content_changed = 1;
1995
1996 if (!content_changed) {
1997 /*
1998 * The SHA1 has not changed, so pre-/post-content is
1999 * identical. We can therefore skip looking at the
2000 * file contents altogether.
2001 */
2002 damage = 0;
2003 goto found_damage;
2004 }
2005
2006 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
2007 /*
2008 * In --dirstat-by-file mode, we don't really need to
2009 * look at the actual file contents at all.
2010 * The fact that the SHA1 changed is enough for us to
2011 * add this file to the list of results
2012 * (with each file contributing equal damage).
2013 */
2014 damage = 1;
2015 goto found_damage;
2016 }
2017
2018 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2019 diff_populate_filespec(p->one, 0);
2020 diff_populate_filespec(p->two, 0);
2021 diffcore_count_changes(p->one, p->two, NULL, NULL,
2022 &copied, &added);
2023 diff_free_filespec_data(p->one);
2024 diff_free_filespec_data(p->two);
2025 } else if (DIFF_FILE_VALID(p->one)) {
2026 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2027 copied = added = 0;
2028 diff_free_filespec_data(p->one);
2029 } else if (DIFF_FILE_VALID(p->two)) {
2030 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
2031 copied = 0;
2032 added = p->two->size;
2033 diff_free_filespec_data(p->two);
2034 } else
2035 continue;
2036
2037 /*
2038 * Original minus copied is the removed material,
2039 * added is the new material. They are both damages
2040 * made to the preimage.
2041 * If the resulting damage is zero, we know that
2042 * diffcore_count_changes() considers the two entries to
2043 * be identical, but since content_changed is true, we
2044 * know that there must have been _some_ kind of change,
2045 * so we force all entries to have damage > 0.
2046 */
2047 damage = (p->one->size - copied) + added;
2048 if (!damage)
2049 damage = 1;
2050
2051 found_damage:
2052 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2053 dir.files[dir.nr].name = name;
2054 dir.files[dir.nr].changed = damage;
2055 changed += damage;
2056 dir.nr++;
2057 }
2058
2059 /* This can happen even with many files, if everything was renames */
2060 if (!changed)
2061 return;
2062
2063 /* Show all directories with more than x% of the changes */
2064 QSORT(dir.files, dir.nr, dirstat_compare);
2065 gather_dirstat(options, &dir, changed, "", 0);
2066 }
2067
2068 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2069 {
2070 int i;
2071 unsigned long changed;
2072 struct dirstat_dir dir;
2073
2074 if (data->nr == 0)
2075 return;
2076
2077 dir.files = NULL;
2078 dir.alloc = 0;
2079 dir.nr = 0;
2080 dir.permille = options->dirstat_permille;
2081 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2082
2083 changed = 0;
2084 for (i = 0; i < data->nr; i++) {
2085 struct diffstat_file *file = data->files[i];
2086 unsigned long damage = file->added + file->deleted;
2087 if (file->is_binary)
2088 /*
2089 * binary files counts bytes, not lines. Must find some
2090 * way to normalize binary bytes vs. textual lines.
2091 * The following heuristic assumes that there are 64
2092 * bytes per "line".
2093 * This is stupid and ugly, but very cheap...
2094 */
2095 damage = DIV_ROUND_UP(damage, 64);
2096 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2097 dir.files[dir.nr].name = file->name;
2098 dir.files[dir.nr].changed = damage;
2099 changed += damage;
2100 dir.nr++;
2101 }
2102
2103 /* This can happen even with many files, if everything was renames */
2104 if (!changed)
2105 return;
2106
2107 /* Show all directories with more than x% of the changes */
2108 QSORT(dir.files, dir.nr, dirstat_compare);
2109 gather_dirstat(options, &dir, changed, "", 0);
2110 }
2111
2112 static void free_diffstat_info(struct diffstat_t *diffstat)
2113 {
2114 int i;
2115 for (i = 0; i < diffstat->nr; i++) {
2116 struct diffstat_file *f = diffstat->files[i];
2117 if (f->name != f->print_name)
2118 free(f->print_name);
2119 free(f->name);
2120 free(f->from_name);
2121 free(f);
2122 }
2123 free(diffstat->files);
2124 }
2125
2126 struct checkdiff_t {
2127 const char *filename;
2128 int lineno;
2129 int conflict_marker_size;
2130 struct diff_options *o;
2131 unsigned ws_rule;
2132 unsigned status;
2133 };
2134
2135 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2136 {
2137 char firstchar;
2138 int cnt;
2139
2140 if (len < marker_size + 1)
2141 return 0;
2142 firstchar = line[0];
2143 switch (firstchar) {
2144 case '=': case '>': case '<': case '|':
2145 break;
2146 default:
2147 return 0;
2148 }
2149 for (cnt = 1; cnt < marker_size; cnt++)
2150 if (line[cnt] != firstchar)
2151 return 0;
2152 /* line[1] thru line[marker_size-1] are same as firstchar */
2153 if (len < marker_size + 1 || !isspace(line[marker_size]))
2154 return 0;
2155 return 1;
2156 }
2157
2158 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2159 {
2160 struct checkdiff_t *data = priv;
2161 int marker_size = data->conflict_marker_size;
2162 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2163 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2164 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2165 char *err;
2166 const char *line_prefix;
2167
2168 assert(data->o);
2169 line_prefix = diff_line_prefix(data->o);
2170
2171 if (line[0] == '+') {
2172 unsigned bad;
2173 data->lineno++;
2174 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2175 data->status |= 1;
2176 fprintf(data->o->file,
2177 "%s%s:%d: leftover conflict marker\n",
2178 line_prefix, data->filename, data->lineno);
2179 }
2180 bad = ws_check(line + 1, len - 1, data->ws_rule);
2181 if (!bad)
2182 return;
2183 data->status |= bad;
2184 err = whitespace_error_string(bad);
2185 fprintf(data->o->file, "%s%s:%d: %s.\n",
2186 line_prefix, data->filename, data->lineno, err);
2187 free(err);
2188 emit_line(data->o, set, reset, line, 1);
2189 ws_check_emit(line + 1, len - 1, data->ws_rule,
2190 data->o->file, set, reset, ws);
2191 } else if (line[0] == ' ') {
2192 data->lineno++;
2193 } else if (line[0] == '@') {
2194 char *plus = strchr(line, '+');
2195 if (plus)
2196 data->lineno = strtol(plus, NULL, 10) - 1;
2197 else
2198 die("invalid diff");
2199 }
2200 }
2201
2202 static unsigned char *deflate_it(char *data,
2203 unsigned long size,
2204 unsigned long *result_size)
2205 {
2206 int bound;
2207 unsigned char *deflated;
2208 git_zstream stream;
2209
2210 git_deflate_init(&stream, zlib_compression_level);
2211 bound = git_deflate_bound(&stream, size);
2212 deflated = xmalloc(bound);
2213 stream.next_out = deflated;
2214 stream.avail_out = bound;
2215
2216 stream.next_in = (unsigned char *)data;
2217 stream.avail_in = size;
2218 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2219 ; /* nothing */
2220 git_deflate_end(&stream);
2221 *result_size = stream.total_out;
2222 return deflated;
2223 }
2224
2225 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two,
2226 const char *prefix)
2227 {
2228 void *cp;
2229 void *delta;
2230 void *deflated;
2231 void *data;
2232 unsigned long orig_size;
2233 unsigned long delta_size;
2234 unsigned long deflate_size;
2235 unsigned long data_size;
2236
2237 /* We could do deflated delta, or we could do just deflated two,
2238 * whichever is smaller.
2239 */
2240 delta = NULL;
2241 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2242 if (one->size && two->size) {
2243 delta = diff_delta(one->ptr, one->size,
2244 two->ptr, two->size,
2245 &delta_size, deflate_size);
2246 if (delta) {
2247 void *to_free = delta;
2248 orig_size = delta_size;
2249 delta = deflate_it(delta, delta_size, &delta_size);
2250 free(to_free);
2251 }
2252 }
2253
2254 if (delta && delta_size < deflate_size) {
2255 fprintf(file, "%sdelta %lu\n", prefix, orig_size);
2256 free(deflated);
2257 data = delta;
2258 data_size = delta_size;
2259 }
2260 else {
2261 fprintf(file, "%sliteral %lu\n", prefix, two->size);
2262 free(delta);
2263 data = deflated;
2264 data_size = deflate_size;
2265 }
2266
2267 /* emit data encoded in base85 */
2268 cp = data;
2269 while (data_size) {
2270 int bytes = (52 < data_size) ? 52 : data_size;
2271 char line[70];
2272 data_size -= bytes;
2273 if (bytes <= 26)
2274 line[0] = bytes + 'A' - 1;
2275 else
2276 line[0] = bytes - 26 + 'a' - 1;
2277 encode_85(line + 1, cp, bytes);
2278 cp = (char *) cp + bytes;
2279 fprintf(file, "%s", prefix);
2280 fputs(line, file);
2281 fputc('\n', file);
2282 }
2283 fprintf(file, "%s\n", prefix);
2284 free(data);
2285 }
2286
2287 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two,
2288 const char *prefix)
2289 {
2290 fprintf(file, "%sGIT binary patch\n", prefix);
2291 emit_binary_diff_body(file, one, two, prefix);
2292 emit_binary_diff_body(file, two, one, prefix);
2293 }
2294
2295 int diff_filespec_is_binary(struct diff_filespec *one)
2296 {
2297 if (one->is_binary == -1) {
2298 diff_filespec_load_driver(one);
2299 if (one->driver->binary != -1)
2300 one->is_binary = one->driver->binary;
2301 else {
2302 if (!one->data && DIFF_FILE_VALID(one))
2303 diff_populate_filespec(one, CHECK_BINARY);
2304 if (one->is_binary == -1 && one->data)
2305 one->is_binary = buffer_is_binary(one->data,
2306 one->size);
2307 if (one->is_binary == -1)
2308 one->is_binary = 0;
2309 }
2310 }
2311 return one->is_binary;
2312 }
2313
2314 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2315 {
2316 diff_filespec_load_driver(one);
2317 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2318 }
2319
2320 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2321 {
2322 if (!options->a_prefix)
2323 options->a_prefix = a;
2324 if (!options->b_prefix)
2325 options->b_prefix = b;
2326 }
2327
2328 struct userdiff_driver *get_textconv(struct diff_filespec *one)
2329 {
2330 if (!DIFF_FILE_VALID(one))
2331 return NULL;
2332
2333 diff_filespec_load_driver(one);
2334 return userdiff_get_textconv(one->driver);
2335 }
2336
2337 static void builtin_diff(const char *name_a,
2338 const char *name_b,
2339 struct diff_filespec *one,
2340 struct diff_filespec *two,
2341 const char *xfrm_msg,
2342 int must_show_header,
2343 struct diff_options *o,
2344 int complete_rewrite)
2345 {
2346 mmfile_t mf1, mf2;
2347 const char *lbl[2];
2348 char *a_one, *b_two;
2349 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
2350 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2351 const char *a_prefix, *b_prefix;
2352 struct userdiff_driver *textconv_one = NULL;
2353 struct userdiff_driver *textconv_two = NULL;
2354 struct strbuf header = STRBUF_INIT;
2355 const char *line_prefix = diff_line_prefix(o);
2356
2357 diff_set_mnemonic_prefix(o, "a/", "b/");
2358 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2359 a_prefix = o->b_prefix;
2360 b_prefix = o->a_prefix;
2361 } else {
2362 a_prefix = o->a_prefix;
2363 b_prefix = o->b_prefix;
2364 }
2365
2366 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
2367 (!one->mode || S_ISGITLINK(one->mode)) &&
2368 (!two->mode || S_ISGITLINK(two->mode))) {
2369 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2370 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2371 show_submodule_summary(o->file, one->path ? one->path : two->path,
2372 line_prefix,
2373 &one->oid, &two->oid,
2374 two->dirty_submodule,
2375 meta, del, add, reset);
2376 return;
2377 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
2378 (!one->mode || S_ISGITLINK(one->mode)) &&
2379 (!two->mode || S_ISGITLINK(two->mode))) {
2380 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2381 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2382 show_submodule_inline_diff(o->file, one->path ? one->path : two->path,
2383 line_prefix,
2384 &one->oid, &two->oid,
2385 two->dirty_submodule,
2386 meta, del, add, reset, o);
2387 return;
2388 }
2389
2390 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2391 textconv_one = get_textconv(one);
2392 textconv_two = get_textconv(two);
2393 }
2394
2395 /* Never use a non-valid filename anywhere if at all possible */
2396 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2397 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2398
2399 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2400 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
2401 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2402 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
2403 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
2404 if (lbl[0][0] == '/') {
2405 /* /dev/null */
2406 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
2407 if (xfrm_msg)
2408 strbuf_addstr(&header, xfrm_msg);
2409 must_show_header = 1;
2410 }
2411 else if (lbl[1][0] == '/') {
2412 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
2413 if (xfrm_msg)
2414 strbuf_addstr(&header, xfrm_msg);
2415 must_show_header = 1;
2416 }
2417 else {
2418 if (one->mode != two->mode) {
2419 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
2420 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
2421 must_show_header = 1;
2422 }
2423 if (xfrm_msg)
2424 strbuf_addstr(&header, xfrm_msg);
2425
2426 /*
2427 * we do not run diff between different kind
2428 * of objects.
2429 */
2430 if ((one->mode ^ two->mode) & S_IFMT)
2431 goto free_ab_and_return;
2432 if (complete_rewrite &&
2433 (textconv_one || !diff_filespec_is_binary(one)) &&
2434 (textconv_two || !diff_filespec_is_binary(two))) {
2435 fprintf(o->file, "%s", header.buf);
2436 strbuf_reset(&header);
2437 emit_rewrite_diff(name_a, name_b, one, two,
2438 textconv_one, textconv_two, o);
2439 o->found_changes = 1;
2440 goto free_ab_and_return;
2441 }
2442 }
2443
2444 if (o->irreversible_delete && lbl[1][0] == '/') {
2445 fprintf(o->file, "%s", header.buf);
2446 strbuf_reset(&header);
2447 goto free_ab_and_return;
2448 } else if (!DIFF_OPT_TST(o, TEXT) &&
2449 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2450 (!textconv_two && diff_filespec_is_binary(two)) )) {
2451 if (!one->data && !two->data &&
2452 S_ISREG(one->mode) && S_ISREG(two->mode) &&
2453 !DIFF_OPT_TST(o, BINARY)) {
2454 if (!oidcmp(&one->oid, &two->oid)) {
2455 if (must_show_header)
2456 fprintf(o->file, "%s", header.buf);
2457 goto free_ab_and_return;
2458 }
2459 fprintf(o->file, "%s", header.buf);
2460 fprintf(o->file, "%sBinary files %s and %s differ\n",
2461 line_prefix, lbl[0], lbl[1]);
2462 goto free_ab_and_return;
2463 }
2464 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2465 die("unable to read files to diff");
2466 /* Quite common confusing case */
2467 if (mf1.size == mf2.size &&
2468 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2469 if (must_show_header)
2470 fprintf(o->file, "%s", header.buf);
2471 goto free_ab_and_return;
2472 }
2473 fprintf(o->file, "%s", header.buf);
2474 strbuf_reset(&header);
2475 if (DIFF_OPT_TST(o, BINARY))
2476 emit_binary_diff(o->file, &mf1, &mf2, line_prefix);
2477 else
2478 fprintf(o->file, "%sBinary files %s and %s differ\n",
2479 line_prefix, lbl[0], lbl[1]);
2480 o->found_changes = 1;
2481 } else {
2482 /* Crazy xdl interfaces.. */
2483 const char *diffopts = getenv("GIT_DIFF_OPTS");
2484 const char *v;
2485 xpparam_t xpp;
2486 xdemitconf_t xecfg;
2487 struct emit_callback ecbdata;
2488 const struct userdiff_funcname *pe;
2489
2490 if (must_show_header) {
2491 fprintf(o->file, "%s", header.buf);
2492 strbuf_reset(&header);
2493 }
2494
2495 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2496 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
2497
2498 pe = diff_funcname_pattern(one);
2499 if (!pe)
2500 pe = diff_funcname_pattern(two);
2501
2502 memset(&xpp, 0, sizeof(xpp));
2503 memset(&xecfg, 0, sizeof(xecfg));
2504 memset(&ecbdata, 0, sizeof(ecbdata));
2505 ecbdata.label_path = lbl;
2506 ecbdata.color_diff = want_color(o->use_color);
2507 ecbdata.ws_rule = whitespace_rule(name_b);
2508 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
2509 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2510 ecbdata.opt = o;
2511 ecbdata.header = header.len ? &header : NULL;
2512 xpp.flags = o->xdl_opts;
2513 xecfg.ctxlen = o->context;
2514 xecfg.interhunkctxlen = o->interhunkcontext;
2515 xecfg.flags = XDL_EMIT_FUNCNAMES;
2516 if (DIFF_OPT_TST(o, FUNCCONTEXT))
2517 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
2518 if (pe)
2519 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
2520 if (!diffopts)
2521 ;
2522 else if (skip_prefix(diffopts, "--unified=", &v))
2523 xecfg.ctxlen = strtoul(v, NULL, 10);
2524 else if (skip_prefix(diffopts, "-u", &v))
2525 xecfg.ctxlen = strtoul(v, NULL, 10);
2526 if (o->word_diff)
2527 init_diff_words_data(&ecbdata, o, one, two);
2528 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2529 &xpp, &xecfg))
2530 die("unable to generate diff for %s", one->path);
2531 if (o->word_diff)
2532 free_diff_words_data(&ecbdata);
2533 if (textconv_one)
2534 free(mf1.ptr);
2535 if (textconv_two)
2536 free(mf2.ptr);
2537 xdiff_clear_find_func(&xecfg);
2538 }
2539
2540 free_ab_and_return:
2541 strbuf_release(&header);
2542 diff_free_filespec_data(one);
2543 diff_free_filespec_data(two);
2544 free(a_one);
2545 free(b_two);
2546 return;
2547 }
2548
2549 static void builtin_diffstat(const char *name_a, const char *name_b,
2550 struct diff_filespec *one,
2551 struct diff_filespec *two,
2552 struct diffstat_t *diffstat,
2553 struct diff_options *o,
2554 struct diff_filepair *p)
2555 {
2556 mmfile_t mf1, mf2;
2557 struct diffstat_file *data;
2558 int same_contents;
2559 int complete_rewrite = 0;
2560
2561 if (!DIFF_PAIR_UNMERGED(p)) {
2562 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2563 complete_rewrite = 1;
2564 }
2565
2566 data = diffstat_add(diffstat, name_a, name_b);
2567 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
2568
2569 if (!one || !two) {
2570 data->is_unmerged = 1;
2571 return;
2572 }
2573
2574 same_contents = !oidcmp(&one->oid, &two->oid);
2575
2576 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2577 data->is_binary = 1;
2578 if (same_contents) {
2579 data->added = 0;
2580 data->deleted = 0;
2581 } else {
2582 data->added = diff_filespec_size(two);
2583 data->deleted = diff_filespec_size(one);
2584 }
2585 }
2586
2587 else if (complete_rewrite) {
2588 diff_populate_filespec(one, 0);
2589 diff_populate_filespec(two, 0);
2590 data->deleted = count_lines(one->data, one->size);
2591 data->added = count_lines(two->data, two->size);
2592 }
2593
2594 else if (!same_contents) {
2595 /* Crazy xdl interfaces.. */
2596 xpparam_t xpp;
2597 xdemitconf_t xecfg;
2598
2599 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2600 die("unable to read files to diff");
2601
2602 memset(&xpp, 0, sizeof(xpp));
2603 memset(&xecfg, 0, sizeof(xecfg));
2604 xpp.flags = o->xdl_opts;
2605 xecfg.ctxlen = o->context;
2606 xecfg.interhunkctxlen = o->interhunkcontext;
2607 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2608 &xpp, &xecfg))
2609 die("unable to generate diffstat for %s", one->path);
2610 }
2611
2612 diff_free_filespec_data(one);
2613 diff_free_filespec_data(two);
2614 }
2615
2616 static void builtin_checkdiff(const char *name_a, const char *name_b,
2617 const char *attr_path,
2618 struct diff_filespec *one,
2619 struct diff_filespec *two,
2620 struct diff_options *o)
2621 {
2622 mmfile_t mf1, mf2;
2623 struct checkdiff_t data;
2624
2625 if (!two)
2626 return;
2627
2628 memset(&data, 0, sizeof(data));
2629 data.filename = name_b ? name_b : name_a;
2630 data.lineno = 0;
2631 data.o = o;
2632 data.ws_rule = whitespace_rule(attr_path);
2633 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2634
2635 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2636 die("unable to read files to diff");
2637
2638 /*
2639 * All the other codepaths check both sides, but not checking
2640 * the "old" side here is deliberate. We are checking the newly
2641 * introduced changes, and as long as the "new" side is text, we
2642 * can and should check what it introduces.
2643 */
2644 if (diff_filespec_is_binary(two))
2645 goto free_and_return;
2646 else {
2647 /* Crazy xdl interfaces.. */
2648 xpparam_t xpp;
2649 xdemitconf_t xecfg;
2650
2651 memset(&xpp, 0, sizeof(xpp));
2652 memset(&xecfg, 0, sizeof(xecfg));
2653 xecfg.ctxlen = 1; /* at least one context line */
2654 xpp.flags = 0;
2655 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2656 &xpp, &xecfg))
2657 die("unable to generate checkdiff for %s", one->path);
2658
2659 if (data.ws_rule & WS_BLANK_AT_EOF) {
2660 struct emit_callback ecbdata;
2661 int blank_at_eof;
2662
2663 ecbdata.ws_rule = data.ws_rule;
2664 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2665 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
2666
2667 if (blank_at_eof) {
2668 static char *err;
2669 if (!err)
2670 err = whitespace_error_string(WS_BLANK_AT_EOF);
2671 fprintf(o->file, "%s:%d: %s.\n",
2672 data.filename, blank_at_eof, err);
2673 data.status = 1; /* report errors */
2674 }
2675 }
2676 }
2677 free_and_return:
2678 diff_free_filespec_data(one);
2679 diff_free_filespec_data(two);
2680 if (data.status)
2681 DIFF_OPT_SET(o, CHECK_FAILED);
2682 }
2683
2684 struct diff_filespec *alloc_filespec(const char *path)
2685 {
2686 struct diff_filespec *spec;
2687
2688 FLEXPTR_ALLOC_STR(spec, path, path);
2689 spec->count = 1;
2690 spec->is_binary = -1;
2691 return spec;
2692 }
2693
2694 void free_filespec(struct diff_filespec *spec)
2695 {
2696 if (!--spec->count) {
2697 diff_free_filespec_data(spec);
2698 free(spec);
2699 }
2700 }
2701
2702 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
2703 int oid_valid, unsigned short mode)
2704 {
2705 if (mode) {
2706 spec->mode = canon_mode(mode);
2707 oidcpy(&spec->oid, oid);
2708 spec->oid_valid = oid_valid;
2709 }
2710 }
2711
2712 /*
2713 * Given a name and sha1 pair, if the index tells us the file in
2714 * the work tree has that object contents, return true, so that
2715 * prepare_temp_file() does not have to inflate and extract.
2716 */
2717 static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
2718 {
2719 const struct cache_entry *ce;
2720 struct stat st;
2721 int pos, len;
2722
2723 /*
2724 * We do not read the cache ourselves here, because the
2725 * benchmark with my previous version that always reads cache
2726 * shows that it makes things worse for diff-tree comparing
2727 * two linux-2.6 kernel trees in an already checked out work
2728 * tree. This is because most diff-tree comparisons deal with
2729 * only a small number of files, while reading the cache is
2730 * expensive for a large project, and its cost outweighs the
2731 * savings we get by not inflating the object to a temporary
2732 * file. Practically, this code only helps when we are used
2733 * by diff-cache --cached, which does read the cache before
2734 * calling us.
2735 */
2736 if (!active_cache)
2737 return 0;
2738
2739 /* We want to avoid the working directory if our caller
2740 * doesn't need the data in a normal file, this system
2741 * is rather slow with its stat/open/mmap/close syscalls,
2742 * and the object is contained in a pack file. The pack
2743 * is probably already open and will be faster to obtain
2744 * the data through than the working directory. Loose
2745 * objects however would tend to be slower as they need
2746 * to be individually opened and inflated.
2747 */
2748 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
2749 return 0;
2750
2751 /*
2752 * Similarly, if we'd have to convert the file contents anyway, that
2753 * makes the optimization not worthwhile.
2754 */
2755 if (!want_file && would_convert_to_git(&the_index, name))
2756 return 0;
2757
2758 len = strlen(name);
2759 pos = cache_name_pos(name, len);
2760 if (pos < 0)
2761 return 0;
2762 ce = active_cache[pos];
2763
2764 /*
2765 * This is not the sha1 we are looking for, or
2766 * unreusable because it is not a regular file.
2767 */
2768 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
2769 return 0;
2770
2771 /*
2772 * If ce is marked as "assume unchanged", there is no
2773 * guarantee that work tree matches what we are looking for.
2774 */
2775 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2776 return 0;
2777
2778 /*
2779 * If ce matches the file in the work tree, we can reuse it.
2780 */
2781 if (ce_uptodate(ce) ||
2782 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2783 return 1;
2784
2785 return 0;
2786 }
2787
2788 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2789 {
2790 struct strbuf buf = STRBUF_INIT;
2791 char *dirty = "";
2792
2793 /* Are we looking at the work tree? */
2794 if (s->dirty_submodule)
2795 dirty = "-dirty";
2796
2797 strbuf_addf(&buf, "Subproject commit %s%s\n",
2798 oid_to_hex(&s->oid), dirty);
2799 s->size = buf.len;
2800 if (size_only) {
2801 s->data = NULL;
2802 strbuf_release(&buf);
2803 } else {
2804 s->data = strbuf_detach(&buf, NULL);
2805 s->should_free = 1;
2806 }
2807 return 0;
2808 }
2809
2810 /*
2811 * While doing rename detection and pickaxe operation, we may need to
2812 * grab the data for the blob (or file) for our own in-core comparison.
2813 * diff_filespec has data and size fields for this purpose.
2814 */
2815 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
2816 {
2817 int size_only = flags & CHECK_SIZE_ONLY;
2818 int err = 0;
2819 /*
2820 * demote FAIL to WARN to allow inspecting the situation
2821 * instead of refusing.
2822 */
2823 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
2824 ? SAFE_CRLF_WARN
2825 : safe_crlf);
2826
2827 if (!DIFF_FILE_VALID(s))
2828 die("internal error: asking to populate invalid file.");
2829 if (S_ISDIR(s->mode))
2830 return -1;
2831
2832 if (s->data)
2833 return 0;
2834
2835 if (size_only && 0 < s->size)
2836 return 0;
2837
2838 if (S_ISGITLINK(s->mode))
2839 return diff_populate_gitlink(s, size_only);
2840
2841 if (!s->oid_valid ||
2842 reuse_worktree_file(s->path, &s->oid, 0)) {
2843 struct strbuf buf = STRBUF_INIT;
2844 struct stat st;
2845 int fd;
2846
2847 if (lstat(s->path, &st) < 0) {
2848 if (errno == ENOENT) {
2849 err_empty:
2850 err = -1;
2851 empty:
2852 s->data = (char *)"";
2853 s->size = 0;
2854 return err;
2855 }
2856 }
2857 s->size = xsize_t(st.st_size);
2858 if (!s->size)
2859 goto empty;
2860 if (S_ISLNK(st.st_mode)) {
2861 struct strbuf sb = STRBUF_INIT;
2862
2863 if (strbuf_readlink(&sb, s->path, s->size))
2864 goto err_empty;
2865 s->size = sb.len;
2866 s->data = strbuf_detach(&sb, NULL);
2867 s->should_free = 1;
2868 return 0;
2869 }
2870
2871 /*
2872 * Even if the caller would be happy with getting
2873 * only the size, we cannot return early at this
2874 * point if the path requires us to run the content
2875 * conversion.
2876 */
2877 if (size_only && !would_convert_to_git(&the_index, s->path))
2878 return 0;
2879
2880 /*
2881 * Note: this check uses xsize_t(st.st_size) that may
2882 * not be the true size of the blob after it goes
2883 * through convert_to_git(). This may not strictly be
2884 * correct, but the whole point of big_file_threshold
2885 * and is_binary check being that we want to avoid
2886 * opening the file and inspecting the contents, this
2887 * is probably fine.
2888 */
2889 if ((flags & CHECK_BINARY) &&
2890 s->size > big_file_threshold && s->is_binary == -1) {
2891 s->is_binary = 1;
2892 return 0;
2893 }
2894 fd = open(s->path, O_RDONLY);
2895 if (fd < 0)
2896 goto err_empty;
2897 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2898 close(fd);
2899 s->should_munmap = 1;
2900
2901 /*
2902 * Convert from working tree format to canonical git format
2903 */
2904 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, crlf_warn)) {
2905 size_t size = 0;
2906 munmap(s->data, s->size);
2907 s->should_munmap = 0;
2908 s->data = strbuf_detach(&buf, &size);
2909 s->size = size;
2910 s->should_free = 1;
2911 }
2912 }
2913 else {
2914 enum object_type type;
2915 if (size_only || (flags & CHECK_BINARY)) {
2916 type = sha1_object_info(s->oid.hash, &s->size);
2917 if (type < 0)
2918 die("unable to read %s",
2919 oid_to_hex(&s->oid));
2920 if (size_only)
2921 return 0;
2922 if (s->size > big_file_threshold && s->is_binary == -1) {
2923 s->is_binary = 1;
2924 return 0;
2925 }
2926 }
2927 s->data = read_sha1_file(s->oid.hash, &type, &s->size);
2928 if (!s->data)
2929 die("unable to read %s", oid_to_hex(&s->oid));
2930 s->should_free = 1;
2931 }
2932 return 0;
2933 }
2934
2935 void diff_free_filespec_blob(struct diff_filespec *s)
2936 {
2937 if (s->should_free)
2938 free(s->data);
2939 else if (s->should_munmap)
2940 munmap(s->data, s->size);
2941
2942 if (s->should_free || s->should_munmap) {
2943 s->should_free = s->should_munmap = 0;
2944 s->data = NULL;
2945 }
2946 }
2947
2948 void diff_free_filespec_data(struct diff_filespec *s)
2949 {
2950 diff_free_filespec_blob(s);
2951 FREE_AND_NULL(s->cnt_data);
2952 }
2953
2954 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2955 void *blob,
2956 unsigned long size,
2957 const struct object_id *oid,
2958 int mode)
2959 {
2960 int fd;
2961 struct strbuf buf = STRBUF_INIT;
2962 struct strbuf template = STRBUF_INIT;
2963 char *path_dup = xstrdup(path);
2964 const char *base = basename(path_dup);
2965
2966 /* Generate "XXXXXX_basename.ext" */
2967 strbuf_addstr(&template, "XXXXXX_");
2968 strbuf_addstr(&template, base);
2969
2970 fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
2971 if (fd < 0)
2972 die_errno("unable to create temp-file");
2973 if (convert_to_working_tree(path,
2974 (const char *)blob, (size_t)size, &buf)) {
2975 blob = buf.buf;
2976 size = buf.len;
2977 }
2978 if (write_in_full(fd, blob, size) != size)
2979 die_errno("unable to write temp-file");
2980 close_tempfile(&temp->tempfile);
2981 temp->name = get_tempfile_path(&temp->tempfile);
2982 oid_to_hex_r(temp->hex, oid);
2983 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
2984 strbuf_release(&buf);
2985 strbuf_release(&template);
2986 free(path_dup);
2987 }
2988
2989 static struct diff_tempfile *prepare_temp_file(const char *name,
2990 struct diff_filespec *one)
2991 {
2992 struct diff_tempfile *temp = claim_diff_tempfile();
2993
2994 if (!DIFF_FILE_VALID(one)) {
2995 not_a_valid_file:
2996 /* A '-' entry produces this for file-2, and
2997 * a '+' entry produces this for file-1.
2998 */
2999 temp->name = "/dev/null";
3000 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3001 xsnprintf(temp->mode, sizeof(temp->mode), ".");
3002 return temp;
3003 }
3004
3005 if (!S_ISGITLINK(one->mode) &&
3006 (!one->oid_valid ||
3007 reuse_worktree_file(name, &one->oid, 1))) {
3008 struct stat st;
3009 if (lstat(name, &st) < 0) {
3010 if (errno == ENOENT)
3011 goto not_a_valid_file;
3012 die_errno("stat(%s)", name);
3013 }
3014 if (S_ISLNK(st.st_mode)) {
3015 struct strbuf sb = STRBUF_INIT;
3016 if (strbuf_readlink(&sb, name, st.st_size) < 0)
3017 die_errno("readlink(%s)", name);
3018 prep_temp_blob(name, temp, sb.buf, sb.len,
3019 (one->oid_valid ?
3020 &one->oid : &null_oid),
3021 (one->oid_valid ?
3022 one->mode : S_IFLNK));
3023 strbuf_release(&sb);
3024 }
3025 else {
3026 /* we can borrow from the file in the work tree */
3027 temp->name = name;
3028 if (!one->oid_valid)
3029 oid_to_hex_r(temp->hex, &null_oid);
3030 else
3031 oid_to_hex_r(temp->hex, &one->oid);
3032 /* Even though we may sometimes borrow the
3033 * contents from the work tree, we always want
3034 * one->mode. mode is trustworthy even when
3035 * !(one->oid_valid), as long as
3036 * DIFF_FILE_VALID(one).
3037 */
3038 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
3039 }
3040 return temp;
3041 }
3042 else {
3043 if (diff_populate_filespec(one, 0))
3044 die("cannot read data blob for %s", one->path);
3045 prep_temp_blob(name, temp, one->data, one->size,
3046 &one->oid, one->mode);
3047 }
3048 return temp;
3049 }
3050
3051 static void add_external_diff_name(struct argv_array *argv,
3052 const char *name,
3053 struct diff_filespec *df)
3054 {
3055 struct diff_tempfile *temp = prepare_temp_file(name, df);
3056 argv_array_push(argv, temp->name);
3057 argv_array_push(argv, temp->hex);
3058 argv_array_push(argv, temp->mode);
3059 }
3060
3061 /* An external diff command takes:
3062 *
3063 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3064 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3065 *
3066 */
3067 static void run_external_diff(const char *pgm,
3068 const char *name,
3069 const char *other,
3070 struct diff_filespec *one,
3071 struct diff_filespec *two,
3072 const char *xfrm_msg,
3073 int complete_rewrite,
3074 struct diff_options *o)
3075 {
3076 struct argv_array argv = ARGV_ARRAY_INIT;
3077 struct argv_array env = ARGV_ARRAY_INIT;
3078 struct diff_queue_struct *q = &diff_queued_diff;
3079
3080 argv_array_push(&argv, pgm);
3081 argv_array_push(&argv, name);
3082
3083 if (one && two) {
3084 add_external_diff_name(&argv, name, one);
3085 if (!other)
3086 add_external_diff_name(&argv, name, two);
3087 else {
3088 add_external_diff_name(&argv, other, two);
3089 argv_array_push(&argv, other);
3090 argv_array_push(&argv, xfrm_msg);
3091 }
3092 }
3093
3094 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3095 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3096
3097 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3098 die(_("external diff died, stopping at %s"), name);
3099
3100 remove_tempfile();
3101 argv_array_clear(&argv);
3102 argv_array_clear(&env);
3103 }
3104
3105 static int similarity_index(struct diff_filepair *p)
3106 {
3107 return p->score * 100 / MAX_SCORE;
3108 }
3109
3110 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3111 {
3112 if (startup_info->have_repository)
3113 return find_unique_abbrev(oid->hash, abbrev);
3114 else {
3115 char *hex = oid_to_hex(oid);
3116 if (abbrev < 0)
3117 abbrev = FALLBACK_DEFAULT_ABBREV;
3118 if (abbrev > GIT_SHA1_HEXSZ)
3119 die("BUG: oid abbreviation out of range: %d", abbrev);
3120 if (abbrev)
3121 hex[abbrev] = '\0';
3122 return hex;
3123 }
3124 }
3125
3126 static void fill_metainfo(struct strbuf *msg,
3127 const char *name,
3128 const char *other,
3129 struct diff_filespec *one,
3130 struct diff_filespec *two,
3131 struct diff_options *o,
3132 struct diff_filepair *p,
3133 int *must_show_header,
3134 int use_color)
3135 {
3136 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3137 const char *reset = diff_get_color(use_color, DIFF_RESET);
3138 const char *line_prefix = diff_line_prefix(o);
3139
3140 *must_show_header = 1;
3141 strbuf_init(msg, PATH_MAX * 2 + 300);
3142 switch (p->status) {
3143 case DIFF_STATUS_COPIED:
3144 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3145 line_prefix, set, similarity_index(p));
3146 strbuf_addf(msg, "%s\n%s%scopy from ",
3147 reset, line_prefix, set);
3148 quote_c_style(name, msg, NULL, 0);
3149 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3150 quote_c_style(other, msg, NULL, 0);
3151 strbuf_addf(msg, "%s\n", reset);
3152 break;
3153 case DIFF_STATUS_RENAMED:
3154 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3155 line_prefix, set, similarity_index(p));
3156 strbuf_addf(msg, "%s\n%s%srename from ",
3157 reset, line_prefix, set);
3158 quote_c_style(name, msg, NULL, 0);
3159 strbuf_addf(msg, "%s\n%s%srename to ",
3160 reset, line_prefix, set);
3161 quote_c_style(other, msg, NULL, 0);
3162 strbuf_addf(msg, "%s\n", reset);
3163 break;
3164 case DIFF_STATUS_MODIFIED:
3165 if (p->score) {
3166 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3167 line_prefix,
3168 set, similarity_index(p), reset);
3169 break;
3170 }
3171 /* fallthru */
3172 default:
3173 *must_show_header = 0;
3174 }
3175 if (one && two && oidcmp(&one->oid, &two->oid)) {
3176 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3177
3178 if (DIFF_OPT_TST(o, BINARY)) {
3179 mmfile_t mf;
3180 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3181 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3182 abbrev = 40;
3183 }
3184 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3185 diff_abbrev_oid(&one->oid, abbrev),
3186 diff_abbrev_oid(&two->oid, abbrev));
3187 if (one->mode == two->mode)
3188 strbuf_addf(msg, " %06o", one->mode);
3189 strbuf_addf(msg, "%s\n", reset);
3190 }
3191 }
3192
3193 static void run_diff_cmd(const char *pgm,
3194 const char *name,
3195 const char *other,
3196 const char *attr_path,
3197 struct diff_filespec *one,
3198 struct diff_filespec *two,
3199 struct strbuf *msg,
3200 struct diff_options *o,
3201 struct diff_filepair *p)
3202 {
3203 const char *xfrm_msg = NULL;
3204 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3205 int must_show_header = 0;
3206
3207
3208 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3209 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3210 if (drv && drv->external)
3211 pgm = drv->external;
3212 }
3213
3214 if (msg) {
3215 /*
3216 * don't use colors when the header is intended for an
3217 * external diff driver
3218 */
3219 fill_metainfo(msg, name, other, one, two, o, p,
3220 &must_show_header,
3221 want_color(o->use_color) && !pgm);
3222 xfrm_msg = msg->len ? msg->buf : NULL;
3223 }
3224
3225 if (pgm) {
3226 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3227 complete_rewrite, o);
3228 return;
3229 }
3230 if (one && two)
3231 builtin_diff(name, other ? other : name,
3232 one, two, xfrm_msg, must_show_header,
3233 o, complete_rewrite);
3234 else
3235 fprintf(o->file, "* Unmerged path %s\n", name);
3236 }
3237
3238 static void diff_fill_oid_info(struct diff_filespec *one)
3239 {
3240 if (DIFF_FILE_VALID(one)) {
3241 if (!one->oid_valid) {
3242 struct stat st;
3243 if (one->is_stdin) {
3244 oidclr(&one->oid);
3245 return;
3246 }
3247 if (lstat(one->path, &st) < 0)
3248 die_errno("stat '%s'", one->path);
3249 if (index_path(one->oid.hash, one->path, &st, 0))
3250 die("cannot hash %s", one->path);
3251 }
3252 }
3253 else
3254 oidclr(&one->oid);
3255 }
3256
3257 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3258 {
3259 /* Strip the prefix but do not molest /dev/null and absolute paths */
3260 if (*namep && **namep != '/') {
3261 *namep += prefix_length;
3262 if (**namep == '/')
3263 ++*namep;
3264 }
3265 if (*otherp && **otherp != '/') {
3266 *otherp += prefix_length;
3267 if (**otherp == '/')
3268 ++*otherp;
3269 }
3270 }
3271
3272 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3273 {
3274 const char *pgm = external_diff();
3275 struct strbuf msg;
3276 struct diff_filespec *one = p->one;
3277 struct diff_filespec *two = p->two;
3278 const char *name;
3279 const char *other;
3280 const char *attr_path;
3281
3282 name = p->one->path;
3283 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3284 attr_path = name;
3285 if (o->prefix_length)
3286 strip_prefix(o->prefix_length, &name, &other);
3287
3288 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3289 pgm = NULL;
3290
3291 if (DIFF_PAIR_UNMERGED(p)) {
3292 run_diff_cmd(pgm, name, NULL, attr_path,
3293 NULL, NULL, NULL, o, p);
3294 return;
3295 }
3296
3297 diff_fill_oid_info(one);
3298 diff_fill_oid_info(two);
3299
3300 if (!pgm &&
3301 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3302 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3303 /*
3304 * a filepair that changes between file and symlink
3305 * needs to be split into deletion and creation.
3306 */
3307 struct diff_filespec *null = alloc_filespec(two->path);
3308 run_diff_cmd(NULL, name, other, attr_path,
3309 one, null, &msg, o, p);
3310 free(null);
3311 strbuf_release(&msg);
3312
3313 null = alloc_filespec(one->path);
3314 run_diff_cmd(NULL, name, other, attr_path,
3315 null, two, &msg, o, p);
3316 free(null);
3317 }
3318 else
3319 run_diff_cmd(pgm, name, other, attr_path,
3320 one, two, &msg, o, p);
3321
3322 strbuf_release(&msg);
3323 }
3324
3325 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3326 struct diffstat_t *diffstat)
3327 {
3328 const char *name;
3329 const char *other;
3330
3331 if (DIFF_PAIR_UNMERGED(p)) {
3332 /* unmerged */
3333 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
3334 return;
3335 }
3336
3337 name = p->one->path;
3338 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3339
3340 if (o->prefix_length)
3341 strip_prefix(o->prefix_length, &name, &other);
3342
3343 diff_fill_oid_info(p->one);
3344 diff_fill_oid_info(p->two);
3345
3346 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
3347 }
3348
3349 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3350 {
3351 const char *name;
3352 const char *other;
3353 const char *attr_path;
3354
3355 if (DIFF_PAIR_UNMERGED(p)) {
3356 /* unmerged */
3357 return;
3358 }
3359
3360 name = p->one->path;
3361 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3362 attr_path = other ? other : name;
3363
3364 if (o->prefix_length)
3365 strip_prefix(o->prefix_length, &name, &other);
3366
3367 diff_fill_oid_info(p->one);
3368 diff_fill_oid_info(p->two);
3369
3370 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
3371 }
3372
3373 void diff_setup(struct diff_options *options)
3374 {
3375 memcpy(options, &default_diff_options, sizeof(*options));
3376
3377 options->file = stdout;
3378
3379 options->abbrev = DEFAULT_ABBREV;
3380 options->line_termination = '\n';
3381 options->break_opt = -1;
3382 options->rename_limit = -1;
3383 options->dirstat_permille = diff_dirstat_permille_default;
3384 options->context = diff_context_default;
3385 options->interhunkcontext = diff_interhunk_context_default;
3386 options->ws_error_highlight = ws_error_highlight_default;
3387 DIFF_OPT_SET(options, RENAME_EMPTY);
3388
3389 /* pathchange left =NULL by default */
3390 options->change = diff_change;
3391 options->add_remove = diff_addremove;
3392 options->use_color = diff_use_color_default;
3393 options->detect_rename = diff_detect_rename_default;
3394 options->xdl_opts |= diff_algorithm;
3395 if (diff_indent_heuristic)
3396 DIFF_XDL_SET(options, INDENT_HEURISTIC);
3397
3398 options->orderfile = diff_order_file_cfg;
3399
3400 if (diff_no_prefix) {
3401 options->a_prefix = options->b_prefix = "";
3402 } else if (!diff_mnemonic_prefix) {
3403 options->a_prefix = "a/";
3404 options->b_prefix = "b/";
3405 }
3406 }
3407
3408 void diff_setup_done(struct diff_options *options)
3409 {
3410 int count = 0;
3411
3412 if (options->set_default)
3413 options->set_default(options);
3414
3415 if (options->output_format & DIFF_FORMAT_NAME)
3416 count++;
3417 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3418 count++;
3419 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3420 count++;
3421 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3422 count++;
3423 if (count > 1)
3424 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
3425
3426 /*
3427 * Most of the time we can say "there are changes"
3428 * only by checking if there are changed paths, but
3429 * --ignore-whitespace* options force us to look
3430 * inside contents.
3431 */
3432
3433 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3434 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3435 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3436 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3437 else
3438 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3439
3440 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3441 options->detect_rename = DIFF_DETECT_COPY;
3442
3443 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3444 options->prefix = NULL;
3445 if (options->prefix)
3446 options->prefix_length = strlen(options->prefix);
3447 else
3448 options->prefix_length = 0;
3449
3450 if (options->output_format & (DIFF_FORMAT_NAME |
3451 DIFF_FORMAT_NAME_STATUS |
3452 DIFF_FORMAT_CHECKDIFF |
3453 DIFF_FORMAT_NO_OUTPUT))
3454 options->output_format &= ~(DIFF_FORMAT_RAW |
3455 DIFF_FORMAT_NUMSTAT |
3456 DIFF_FORMAT_DIFFSTAT |
3457 DIFF_FORMAT_SHORTSTAT |
3458 DIFF_FORMAT_DIRSTAT |
3459 DIFF_FORMAT_SUMMARY |
3460 DIFF_FORMAT_PATCH);
3461
3462 /*
3463 * These cases always need recursive; we do not drop caller-supplied
3464 * recursive bits for other formats here.
3465 */
3466 if (options->output_format & (DIFF_FORMAT_PATCH |
3467 DIFF_FORMAT_NUMSTAT |
3468 DIFF_FORMAT_DIFFSTAT |
3469 DIFF_FORMAT_SHORTSTAT |
3470 DIFF_FORMAT_DIRSTAT |
3471 DIFF_FORMAT_SUMMARY |
3472 DIFF_FORMAT_CHECKDIFF))
3473 DIFF_OPT_SET(options, RECURSIVE);
3474 /*
3475 * Also pickaxe would not work very well if you do not say recursive
3476 */
3477 if (options->pickaxe)
3478 DIFF_OPT_SET(options, RECURSIVE);
3479 /*
3480 * When patches are generated, submodules diffed against the work tree
3481 * must be checked for dirtiness too so it can be shown in the output
3482 */
3483 if (options->output_format & DIFF_FORMAT_PATCH)
3484 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
3485
3486 if (options->detect_rename && options->rename_limit < 0)
3487 options->rename_limit = diff_rename_limit_default;
3488 if (options->setup & DIFF_SETUP_USE_CACHE) {
3489 if (!active_cache)
3490 /* read-cache does not die even when it fails
3491 * so it is safe for us to do this here. Also
3492 * it does not smudge active_cache or active_nr
3493 * when it fails, so we do not have to worry about
3494 * cleaning it up ourselves either.
3495 */
3496 read_cache();
3497 }
3498 if (40 < options->abbrev)
3499 options->abbrev = 40; /* full */
3500
3501 /*
3502 * It does not make sense to show the first hit we happened
3503 * to have found. It does not make sense not to return with
3504 * exit code in such a case either.
3505 */
3506 if (DIFF_OPT_TST(options, QUICK)) {
3507 options->output_format = DIFF_FORMAT_NO_OUTPUT;
3508 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3509 }
3510
3511 options->diff_path_counter = 0;
3512
3513 if (DIFF_OPT_TST(options, FOLLOW_RENAMES) && options->pathspec.nr != 1)
3514 die(_("--follow requires exactly one pathspec"));
3515 }
3516
3517 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
3518 {
3519 char c, *eq;
3520 int len;
3521
3522 if (*arg != '-')
3523 return 0;
3524 c = *++arg;
3525 if (!c)
3526 return 0;
3527 if (c == arg_short) {
3528 c = *++arg;
3529 if (!c)
3530 return 1;
3531 if (val && isdigit(c)) {
3532 char *end;
3533 int n = strtoul(arg, &end, 10);
3534 if (*end)
3535 return 0;
3536 *val = n;
3537 return 1;
3538 }
3539 return 0;
3540 }
3541 if (c != '-')
3542 return 0;
3543 arg++;
3544 eq = strchrnul(arg, '=');
3545 len = eq - arg;
3546 if (!len || strncmp(arg, arg_long, len))
3547 return 0;
3548 if (*eq) {
3549 int n;
3550 char *end;
3551 if (!isdigit(*++eq))
3552 return 0;
3553 n = strtoul(eq, &end, 10);
3554 if (*end)
3555 return 0;
3556 *val = n;
3557 }
3558 return 1;
3559 }
3560
3561 static int diff_scoreopt_parse(const char *opt);
3562
3563 static inline int short_opt(char opt, const char **argv,
3564 const char **optarg)
3565 {
3566 const char *arg = argv[0];
3567 if (arg[0] != '-' || arg[1] != opt)
3568 return 0;
3569 if (arg[2] != '\0') {
3570 *optarg = arg + 2;
3571 return 1;
3572 }
3573 if (!argv[1])
3574 die("Option '%c' requires a value", opt);
3575 *optarg = argv[1];
3576 return 2;
3577 }
3578
3579 int parse_long_opt(const char *opt, const char **argv,
3580 const char **optarg)
3581 {
3582 const char *arg = argv[0];
3583 if (!skip_prefix(arg, "--", &arg))
3584 return 0;
3585 if (!skip_prefix(arg, opt, &arg))
3586 return 0;
3587 if (*arg == '=') { /* stuck form: --option=value */
3588 *optarg = arg + 1;
3589 return 1;
3590 }
3591 if (*arg != '\0')
3592 return 0;
3593 /* separate form: --option value */
3594 if (!argv[1])
3595 die("Option '--%s' requires a value", opt);
3596 *optarg = argv[1];
3597 return 2;
3598 }
3599
3600 static int stat_opt(struct diff_options *options, const char **av)
3601 {
3602 const char *arg = av[0];
3603 char *end;
3604 int width = options->stat_width;
3605 int name_width = options->stat_name_width;
3606 int graph_width = options->stat_graph_width;
3607 int count = options->stat_count;
3608 int argcount = 1;
3609
3610 if (!skip_prefix(arg, "--stat", &arg))
3611 die("BUG: stat option does not begin with --stat: %s", arg);
3612 end = (char *)arg;
3613
3614 switch (*arg) {
3615 case '-':
3616 if (skip_prefix(arg, "-width", &arg)) {
3617 if (*arg == '=')
3618 width = strtoul(arg + 1, &end, 10);
3619 else if (!*arg && !av[1])
3620 die_want_option("--stat-width");
3621 else if (!*arg) {
3622 width = strtoul(av[1], &end, 10);
3623 argcount = 2;
3624 }
3625 } else if (skip_prefix(arg, "-name-width", &arg)) {
3626 if (*arg == '=')
3627 name_width = strtoul(arg + 1, &end, 10);
3628 else if (!*arg && !av[1])
3629 die_want_option("--stat-name-width");
3630 else if (!*arg) {
3631 name_width = strtoul(av[1], &end, 10);
3632 argcount = 2;
3633 }
3634 } else if (skip_prefix(arg, "-graph-width", &arg)) {
3635 if (*arg == '=')
3636 graph_width = strtoul(arg + 1, &end, 10);
3637 else if (!*arg && !av[1])
3638 die_want_option("--stat-graph-width");
3639 else if (!*arg) {
3640 graph_width = strtoul(av[1], &end, 10);
3641 argcount = 2;
3642 }
3643 } else if (skip_prefix(arg, "-count", &arg)) {
3644 if (*arg == '=')
3645 count = strtoul(arg + 1, &end, 10);
3646 else if (!*arg && !av[1])
3647 die_want_option("--stat-count");
3648 else if (!*arg) {
3649 count = strtoul(av[1], &end, 10);
3650 argcount = 2;
3651 }
3652 }
3653 break;
3654 case '=':
3655 width = strtoul(arg+1, &end, 10);
3656 if (*end == ',')
3657 name_width = strtoul(end+1, &end, 10);
3658 if (*end == ',')
3659 count = strtoul(end+1, &end, 10);
3660 }
3661
3662 /* Important! This checks all the error cases! */
3663 if (*end)
3664 return 0;
3665 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3666 options->stat_name_width = name_width;
3667 options->stat_graph_width = graph_width;
3668 options->stat_width = width;
3669 options->stat_count = count;
3670 return argcount;
3671 }
3672
3673 static int parse_dirstat_opt(struct diff_options *options, const char *params)
3674 {
3675 struct strbuf errmsg = STRBUF_INIT;
3676 if (parse_dirstat_params(options, params, &errmsg))
3677 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
3678 errmsg.buf);
3679 strbuf_release(&errmsg);
3680 /*
3681 * The caller knows a dirstat-related option is given from the command
3682 * line; allow it to say "return this_function();"
3683 */
3684 options->output_format |= DIFF_FORMAT_DIRSTAT;
3685 return 1;
3686 }
3687
3688 static int parse_submodule_opt(struct diff_options *options, const char *value)
3689 {
3690 if (parse_submodule_params(options, value))
3691 die(_("Failed to parse --submodule option parameter: '%s'"),
3692 value);
3693 return 1;