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