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