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