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