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