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