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