38f26091f313c9b63331718168e5d69ee148832b
1/*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4#include "cache.h"
5#include "config.h"
6#include "tempfile.h"
7#include "quote.h"
8#include "diff.h"
9#include "diffcore.h"
10#include "delta.h"
11#include "xdiff-interface.h"
12#include "color.h"
13#include "attr.h"
14#include "run-command.h"
15#include "utf8.h"
16#include "object-store.h"
17#include "userdiff.h"
18#include "submodule-config.h"
19#include "submodule.h"
20#include "hashmap.h"
21#include "ll-merge.h"
22#include "string-list.h"
23#include "argv-array.h"
24#include "graph.h"
25#include "packfile.h"
26#include "help.h"
27
28#ifdef NO_FAST_WORKING_DIRECTORY
29#define FAST_WORKING_DIRECTORY 0
30#else
31#define FAST_WORKING_DIRECTORY 1
32#endif
33
34static int diff_detect_rename_default;
35static int diff_indent_heuristic = 1;
36static int diff_rename_limit_default = 400;
37static int diff_suppress_blank_empty;
38static int diff_use_color_default = -1;
39static int diff_color_moved_default;
40static int diff_color_moved_ws_default;
41static int diff_context_default = 3;
42static int diff_interhunk_context_default;
43static const char *diff_word_regex_cfg;
44static const char *external_diff_cmd_cfg;
45static const char *diff_order_file_cfg;
46int diff_auto_refresh_index = 1;
47static int diff_mnemonic_prefix;
48static int diff_no_prefix;
49static int diff_stat_graph_width;
50static int diff_dirstat_permille_default = 30;
51static struct diff_options default_diff_options;
52static long diff_algorithm;
53static unsigned ws_error_highlight_default = WSEH_NEW;
54
55static char diff_colors[][COLOR_MAXLEN] = {
56 GIT_COLOR_RESET,
57 GIT_COLOR_NORMAL, /* CONTEXT */
58 GIT_COLOR_BOLD, /* METAINFO */
59 GIT_COLOR_CYAN, /* FRAGINFO */
60 GIT_COLOR_RED, /* OLD */
61 GIT_COLOR_GREEN, /* NEW */
62 GIT_COLOR_YELLOW, /* COMMIT */
63 GIT_COLOR_BG_RED, /* WHITESPACE */
64 GIT_COLOR_NORMAL, /* FUNCINFO */
65 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
66 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
67 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
68 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
69 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
70 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
71 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
72 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
73 GIT_COLOR_FAINT, /* CONTEXT_DIM */
74 GIT_COLOR_FAINT_RED, /* OLD_DIM */
75 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
76 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
77 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
78 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
79};
80
81static const char *color_diff_slots[] = {
82 [DIFF_CONTEXT] = "context",
83 [DIFF_METAINFO] = "meta",
84 [DIFF_FRAGINFO] = "frag",
85 [DIFF_FILE_OLD] = "old",
86 [DIFF_FILE_NEW] = "new",
87 [DIFF_COMMIT] = "commit",
88 [DIFF_WHITESPACE] = "whitespace",
89 [DIFF_FUNCINFO] = "func",
90 [DIFF_FILE_OLD_MOVED] = "oldMoved",
91 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
92 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
93 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
94 [DIFF_FILE_NEW_MOVED] = "newMoved",
95 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
96 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
97 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
98 [DIFF_CONTEXT_DIM] = "contextDimmed",
99 [DIFF_FILE_OLD_DIM] = "oldDimmed",
100 [DIFF_FILE_NEW_DIM] = "newDimmed",
101 [DIFF_CONTEXT_BOLD] = "contextBold",
102 [DIFF_FILE_OLD_BOLD] = "oldBold",
103 [DIFF_FILE_NEW_BOLD] = "newBold",
104};
105
106static NORETURN void die_want_option(const char *option_name)
107{
108 die(_("option '%s' requires a value"), option_name);
109}
110
111define_list_config_array_extra(color_diff_slots, {"plain"});
112
113static int parse_diff_color_slot(const char *var)
114{
115 if (!strcasecmp(var, "plain"))
116 return DIFF_CONTEXT;
117 return LOOKUP_CONFIG(color_diff_slots, var);
118}
119
120static int parse_dirstat_params(struct diff_options *options, const char *params_string,
121 struct strbuf *errmsg)
122{
123 char *params_copy = xstrdup(params_string);
124 struct string_list params = STRING_LIST_INIT_NODUP;
125 int ret = 0;
126 int i;
127
128 if (*params_copy)
129 string_list_split_in_place(¶ms, params_copy, ',', -1);
130 for (i = 0; i < params.nr; i++) {
131 const char *p = params.items[i].string;
132 if (!strcmp(p, "changes")) {
133 options->flags.dirstat_by_line = 0;
134 options->flags.dirstat_by_file = 0;
135 } else if (!strcmp(p, "lines")) {
136 options->flags.dirstat_by_line = 1;
137 options->flags.dirstat_by_file = 0;
138 } else if (!strcmp(p, "files")) {
139 options->flags.dirstat_by_line = 0;
140 options->flags.dirstat_by_file = 1;
141 } else if (!strcmp(p, "noncumulative")) {
142 options->flags.dirstat_cumulative = 0;
143 } else if (!strcmp(p, "cumulative")) {
144 options->flags.dirstat_cumulative = 1;
145 } else if (isdigit(*p)) {
146 char *end;
147 int permille = strtoul(p, &end, 10) * 10;
148 if (*end == '.' && isdigit(*++end)) {
149 /* only use first digit */
150 permille += *end - '0';
151 /* .. and ignore any further digits */
152 while (isdigit(*++end))
153 ; /* nothing */
154 }
155 if (!*end)
156 options->dirstat_permille = permille;
157 else {
158 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
159 p);
160 ret++;
161 }
162 } else {
163 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
164 ret++;
165 }
166
167 }
168 string_list_clear(¶ms, 0);
169 free(params_copy);
170 return ret;
171}
172
173static int parse_submodule_params(struct diff_options *options, const char *value)
174{
175 if (!strcmp(value, "log"))
176 options->submodule_format = DIFF_SUBMODULE_LOG;
177 else if (!strcmp(value, "short"))
178 options->submodule_format = DIFF_SUBMODULE_SHORT;
179 else if (!strcmp(value, "diff"))
180 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
181 else
182 return -1;
183 return 0;
184}
185
186int 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
195long parse_algorithm_value(const char *value)
196{
197 if (!value)
198 return -1;
199 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
200 return 0;
201 else if (!strcasecmp(value, "minimal"))
202 return XDF_NEED_MINIMAL;
203 else if (!strcasecmp(value, "patience"))
204 return XDF_PATIENCE_DIFF;
205 else if (!strcasecmp(value, "histogram"))
206 return XDF_HISTOGRAM_DIFF;
207 return -1;
208}
209
210static int parse_one_token(const char **arg, const char *token)
211{
212 const char *rest;
213 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
214 *arg = rest;
215 return 1;
216 }
217 return 0;
218}
219
220static int parse_ws_error_highlight(const char *arg)
221{
222 const char *orig_arg = arg;
223 unsigned val = 0;
224
225 while (*arg) {
226 if (parse_one_token(&arg, "none"))
227 val = 0;
228 else if (parse_one_token(&arg, "default"))
229 val = WSEH_NEW;
230 else if (parse_one_token(&arg, "all"))
231 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
232 else if (parse_one_token(&arg, "new"))
233 val |= WSEH_NEW;
234 else if (parse_one_token(&arg, "old"))
235 val |= WSEH_OLD;
236 else if (parse_one_token(&arg, "context"))
237 val |= WSEH_CONTEXT;
238 else {
239 return -1 - (int)(arg - orig_arg);
240 }
241 if (*arg)
242 arg++;
243 }
244 return val;
245}
246
247/*
248 * These are to give UI layer defaults.
249 * The core-level commands such as git-diff-files should
250 * never be affected by the setting of diff.renames
251 * the user happens to have in the configuration file.
252 */
253void init_diff_ui_defaults(void)
254{
255 diff_detect_rename_default = DIFF_DETECT_RENAME;
256}
257
258int git_diff_heuristic_config(const char *var, const char *value, void *cb)
259{
260 if (!strcmp(var, "diff.indentheuristic"))
261 diff_indent_heuristic = git_config_bool(var, value);
262 return 0;
263}
264
265static int parse_color_moved(const char *arg)
266{
267 switch (git_parse_maybe_bool(arg)) {
268 case 0:
269 return COLOR_MOVED_NO;
270 case 1:
271 return COLOR_MOVED_DEFAULT;
272 default:
273 break;
274 }
275
276 if (!strcmp(arg, "no"))
277 return COLOR_MOVED_NO;
278 else if (!strcmp(arg, "plain"))
279 return COLOR_MOVED_PLAIN;
280 else if (!strcmp(arg, "blocks"))
281 return COLOR_MOVED_BLOCKS;
282 else if (!strcmp(arg, "zebra"))
283 return COLOR_MOVED_ZEBRA;
284 else if (!strcmp(arg, "default"))
285 return COLOR_MOVED_DEFAULT;
286 else if (!strcmp(arg, "dimmed-zebra"))
287 return COLOR_MOVED_ZEBRA_DIM;
288 else if (!strcmp(arg, "dimmed_zebra"))
289 return COLOR_MOVED_ZEBRA_DIM;
290 else
291 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
292}
293
294static int parse_color_moved_ws(const char *arg)
295{
296 int ret = 0;
297 struct string_list l = STRING_LIST_INIT_DUP;
298 struct string_list_item *i;
299
300 string_list_split(&l, arg, ',', -1);
301
302 for_each_string_list_item(i, &l) {
303 struct strbuf sb = STRBUF_INIT;
304 strbuf_addstr(&sb, i->string);
305 strbuf_trim(&sb);
306
307 if (!strcmp(sb.buf, "ignore-space-change"))
308 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
309 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
310 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
311 else if (!strcmp(sb.buf, "ignore-all-space"))
312 ret |= XDF_IGNORE_WHITESPACE;
313 else if (!strcmp(sb.buf, "allow-indentation-change"))
314 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
315 else
316 error(_("ignoring unknown color-moved-ws mode '%s'"), sb.buf);
317
318 strbuf_release(&sb);
319 }
320
321 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
322 (ret & XDF_WHITESPACE_FLAGS))
323 die(_("color-moved-ws: allow-indentation-change cannot be combined with other white space modes"));
324
325 string_list_clear(&l, 0);
326
327 return ret;
328}
329
330int git_diff_ui_config(const char *var, const char *value, void *cb)
331{
332 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
333 diff_use_color_default = git_config_colorbool(var, value);
334 return 0;
335 }
336 if (!strcmp(var, "diff.colormoved")) {
337 int cm = parse_color_moved(value);
338 if (cm < 0)
339 return -1;
340 diff_color_moved_default = cm;
341 return 0;
342 }
343 if (!strcmp(var, "diff.colormovedws")) {
344 int cm = parse_color_moved_ws(value);
345 if (cm < 0)
346 return -1;
347 diff_color_moved_ws_default = cm;
348 return 0;
349 }
350 if (!strcmp(var, "diff.context")) {
351 diff_context_default = git_config_int(var, value);
352 if (diff_context_default < 0)
353 return -1;
354 return 0;
355 }
356 if (!strcmp(var, "diff.interhunkcontext")) {
357 diff_interhunk_context_default = git_config_int(var, value);
358 if (diff_interhunk_context_default < 0)
359 return -1;
360 return 0;
361 }
362 if (!strcmp(var, "diff.renames")) {
363 diff_detect_rename_default = git_config_rename(var, value);
364 return 0;
365 }
366 if (!strcmp(var, "diff.autorefreshindex")) {
367 diff_auto_refresh_index = git_config_bool(var, value);
368 return 0;
369 }
370 if (!strcmp(var, "diff.mnemonicprefix")) {
371 diff_mnemonic_prefix = git_config_bool(var, value);
372 return 0;
373 }
374 if (!strcmp(var, "diff.noprefix")) {
375 diff_no_prefix = git_config_bool(var, value);
376 return 0;
377 }
378 if (!strcmp(var, "diff.statgraphwidth")) {
379 diff_stat_graph_width = git_config_int(var, value);
380 return 0;
381 }
382 if (!strcmp(var, "diff.external"))
383 return git_config_string(&external_diff_cmd_cfg, var, value);
384 if (!strcmp(var, "diff.wordregex"))
385 return git_config_string(&diff_word_regex_cfg, var, value);
386 if (!strcmp(var, "diff.orderfile"))
387 return git_config_pathname(&diff_order_file_cfg, var, value);
388
389 if (!strcmp(var, "diff.ignoresubmodules"))
390 handle_ignore_submodules_arg(&default_diff_options, value);
391
392 if (!strcmp(var, "diff.submodule")) {
393 if (parse_submodule_params(&default_diff_options, value))
394 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
395 value);
396 return 0;
397 }
398
399 if (!strcmp(var, "diff.algorithm")) {
400 diff_algorithm = parse_algorithm_value(value);
401 if (diff_algorithm < 0)
402 return -1;
403 return 0;
404 }
405
406 if (!strcmp(var, "diff.wserrorhighlight")) {
407 int val = parse_ws_error_highlight(value);
408 if (val < 0)
409 return -1;
410 ws_error_highlight_default = val;
411 return 0;
412 }
413
414 if (git_color_config(var, value, cb) < 0)
415 return -1;
416
417 return git_diff_basic_config(var, value, cb);
418}
419
420int git_diff_basic_config(const char *var, const char *value, void *cb)
421{
422 const char *name;
423
424 if (!strcmp(var, "diff.renamelimit")) {
425 diff_rename_limit_default = git_config_int(var, value);
426 return 0;
427 }
428
429 if (userdiff_config(var, value) < 0)
430 return -1;
431
432 if (skip_prefix(var, "diff.color.", &name) ||
433 skip_prefix(var, "color.diff.", &name)) {
434 int slot = parse_diff_color_slot(name);
435 if (slot < 0)
436 return 0;
437 if (!value)
438 return config_error_nonbool(var);
439 return color_parse(value, diff_colors[slot]);
440 }
441
442 /* like GNU diff's --suppress-blank-empty option */
443 if (!strcmp(var, "diff.suppressblankempty") ||
444 /* for backwards compatibility */
445 !strcmp(var, "diff.suppress-blank-empty")) {
446 diff_suppress_blank_empty = git_config_bool(var, value);
447 return 0;
448 }
449
450 if (!strcmp(var, "diff.dirstat")) {
451 struct strbuf errmsg = STRBUF_INIT;
452 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
453 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
454 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
455 errmsg.buf);
456 strbuf_release(&errmsg);
457 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
458 return 0;
459 }
460
461 if (git_diff_heuristic_config(var, value, cb) < 0)
462 return -1;
463
464 return git_default_config(var, value, cb);
465}
466
467static char *quote_two(const char *one, const char *two)
468{
469 int need_one = quote_c_style(one, NULL, NULL, 1);
470 int need_two = quote_c_style(two, NULL, NULL, 1);
471 struct strbuf res = STRBUF_INIT;
472
473 if (need_one + need_two) {
474 strbuf_addch(&res, '"');
475 quote_c_style(one, &res, NULL, 1);
476 quote_c_style(two, &res, NULL, 1);
477 strbuf_addch(&res, '"');
478 } else {
479 strbuf_addstr(&res, one);
480 strbuf_addstr(&res, two);
481 }
482 return strbuf_detach(&res, NULL);
483}
484
485static const char *external_diff(void)
486{
487 static const char *external_diff_cmd = NULL;
488 static int done_preparing = 0;
489
490 if (done_preparing)
491 return external_diff_cmd;
492 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
493 if (!external_diff_cmd)
494 external_diff_cmd = external_diff_cmd_cfg;
495 done_preparing = 1;
496 return external_diff_cmd;
497}
498
499/*
500 * Keep track of files used for diffing. Sometimes such an entry
501 * refers to a temporary file, sometimes to an existing file, and
502 * sometimes to "/dev/null".
503 */
504static struct diff_tempfile {
505 /*
506 * filename external diff should read from, or NULL if this
507 * entry is currently not in use:
508 */
509 const char *name;
510
511 char hex[GIT_MAX_HEXSZ + 1];
512 char mode[10];
513
514 /*
515 * If this diff_tempfile instance refers to a temporary file,
516 * this tempfile object is used to manage its lifetime.
517 */
518 struct tempfile *tempfile;
519} diff_temp[2];
520
521struct emit_callback {
522 int color_diff;
523 unsigned ws_rule;
524 int blank_at_eof_in_preimage;
525 int blank_at_eof_in_postimage;
526 int lno_in_preimage;
527 int lno_in_postimage;
528 const char **label_path;
529 struct diff_words_data *diff_words;
530 struct diff_options *opt;
531 struct strbuf *header;
532};
533
534static int count_lines(const char *data, int size)
535{
536 int count, ch, completely_empty = 1, nl_just_seen = 0;
537 count = 0;
538 while (0 < size--) {
539 ch = *data++;
540 if (ch == '\n') {
541 count++;
542 nl_just_seen = 1;
543 completely_empty = 0;
544 }
545 else {
546 nl_just_seen = 0;
547 completely_empty = 0;
548 }
549 }
550 if (completely_empty)
551 return 0;
552 if (!nl_just_seen)
553 count++; /* no trailing newline */
554 return count;
555}
556
557static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
558{
559 if (!DIFF_FILE_VALID(one)) {
560 mf->ptr = (char *)""; /* does not matter */
561 mf->size = 0;
562 return 0;
563 }
564 else if (diff_populate_filespec(one, 0))
565 return -1;
566
567 mf->ptr = one->data;
568 mf->size = one->size;
569 return 0;
570}
571
572/* like fill_mmfile, but only for size, so we can avoid retrieving blob */
573static unsigned long diff_filespec_size(struct diff_filespec *one)
574{
575 if (!DIFF_FILE_VALID(one))
576 return 0;
577 diff_populate_filespec(one, CHECK_SIZE_ONLY);
578 return one->size;
579}
580
581static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
582{
583 char *ptr = mf->ptr;
584 long size = mf->size;
585 int cnt = 0;
586
587 if (!size)
588 return cnt;
589 ptr += size - 1; /* pointing at the very end */
590 if (*ptr != '\n')
591 ; /* incomplete line */
592 else
593 ptr--; /* skip the last LF */
594 while (mf->ptr < ptr) {
595 char *prev_eol;
596 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
597 if (*prev_eol == '\n')
598 break;
599 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
600 break;
601 cnt++;
602 ptr = prev_eol - 1;
603 }
604 return cnt;
605}
606
607static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
608 struct emit_callback *ecbdata)
609{
610 int l1, l2, at;
611 unsigned ws_rule = ecbdata->ws_rule;
612 l1 = count_trailing_blank(mf1, ws_rule);
613 l2 = count_trailing_blank(mf2, ws_rule);
614 if (l2 <= l1) {
615 ecbdata->blank_at_eof_in_preimage = 0;
616 ecbdata->blank_at_eof_in_postimage = 0;
617 return;
618 }
619 at = count_lines(mf1->ptr, mf1->size);
620 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
621
622 at = count_lines(mf2->ptr, mf2->size);
623 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
624}
625
626static void emit_line_0(struct diff_options *o,
627 const char *set_sign, const char *set, unsigned reverse, const char *reset,
628 int first, const char *line, int len)
629{
630 int has_trailing_newline, has_trailing_carriage_return;
631 int needs_reset = 0; /* at the end of the line */
632 FILE *file = o->file;
633
634 fputs(diff_line_prefix(o), file);
635
636 has_trailing_newline = (len > 0 && line[len-1] == '\n');
637 if (has_trailing_newline)
638 len--;
639
640 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
641 if (has_trailing_carriage_return)
642 len--;
643
644 if (!len && !first)
645 goto end_of_line;
646
647 if (reverse && want_color(o->use_color)) {
648 fputs(GIT_COLOR_REVERSE, file);
649 needs_reset = 1;
650 }
651
652 if (set_sign) {
653 fputs(set_sign, file);
654 needs_reset = 1;
655 }
656
657 if (first)
658 fputc(first, file);
659
660 if (!len)
661 goto end_of_line;
662
663 if (set) {
664 if (set_sign && set != set_sign)
665 fputs(reset, file);
666 fputs(set, file);
667 needs_reset = 1;
668 }
669 fwrite(line, len, 1, file);
670 needs_reset = 1; /* 'line' may contain color codes. */
671
672end_of_line:
673 if (needs_reset)
674 fputs(reset, file);
675 if (has_trailing_carriage_return)
676 fputc('\r', file);
677 if (has_trailing_newline)
678 fputc('\n', file);
679}
680
681static void emit_line(struct diff_options *o, const char *set, const char *reset,
682 const char *line, int len)
683{
684 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
685}
686
687enum diff_symbol {
688 DIFF_SYMBOL_BINARY_DIFF_HEADER,
689 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
690 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
691 DIFF_SYMBOL_BINARY_DIFF_BODY,
692 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
693 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
694 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
695 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
696 DIFF_SYMBOL_STATS_LINE,
697 DIFF_SYMBOL_WORD_DIFF,
698 DIFF_SYMBOL_STAT_SEP,
699 DIFF_SYMBOL_SUMMARY,
700 DIFF_SYMBOL_SUBMODULE_ADD,
701 DIFF_SYMBOL_SUBMODULE_DEL,
702 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
703 DIFF_SYMBOL_SUBMODULE_MODIFIED,
704 DIFF_SYMBOL_SUBMODULE_HEADER,
705 DIFF_SYMBOL_SUBMODULE_ERROR,
706 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
707 DIFF_SYMBOL_REWRITE_DIFF,
708 DIFF_SYMBOL_BINARY_FILES,
709 DIFF_SYMBOL_HEADER,
710 DIFF_SYMBOL_FILEPAIR_PLUS,
711 DIFF_SYMBOL_FILEPAIR_MINUS,
712 DIFF_SYMBOL_WORDS_PORCELAIN,
713 DIFF_SYMBOL_WORDS,
714 DIFF_SYMBOL_CONTEXT,
715 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
716 DIFF_SYMBOL_PLUS,
717 DIFF_SYMBOL_MINUS,
718 DIFF_SYMBOL_NO_LF_EOF,
719 DIFF_SYMBOL_CONTEXT_FRAGINFO,
720 DIFF_SYMBOL_CONTEXT_MARKER,
721 DIFF_SYMBOL_SEPARATOR
722};
723/*
724 * Flags for content lines:
725 * 0..12 are whitespace rules
726 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
727 * 16 is marking if the line is blank at EOF
728 */
729#define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
730#define DIFF_SYMBOL_MOVED_LINE (1<<17)
731#define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
732#define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
733#define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
734
735/*
736 * This struct is used when we need to buffer the output of the diff output.
737 *
738 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
739 * into the pre/post image file. This pointer could be a union with the
740 * line pointer. By storing an offset into the file instead of the literal line,
741 * we can decrease the memory footprint for the buffered output. At first we
742 * may want to only have indirection for the content lines, but we could also
743 * enhance the state for emitting prefabricated lines, e.g. the similarity
744 * score line or hunk/file headers would only need to store a number or path
745 * and then the output can be constructed later on depending on state.
746 */
747struct emitted_diff_symbol {
748 const char *line;
749 int len;
750 int flags;
751 enum diff_symbol s;
752};
753#define EMITTED_DIFF_SYMBOL_INIT {NULL}
754
755struct emitted_diff_symbols {
756 struct emitted_diff_symbol *buf;
757 int nr, alloc;
758};
759#define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
760
761static void append_emitted_diff_symbol(struct diff_options *o,
762 struct emitted_diff_symbol *e)
763{
764 struct emitted_diff_symbol *f;
765
766 ALLOC_GROW(o->emitted_symbols->buf,
767 o->emitted_symbols->nr + 1,
768 o->emitted_symbols->alloc);
769 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
770
771 memcpy(f, e, sizeof(struct emitted_diff_symbol));
772 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
773}
774
775struct moved_entry {
776 struct hashmap_entry ent;
777 const struct emitted_diff_symbol *es;
778 struct moved_entry *next_line;
779};
780
781/**
782 * The struct ws_delta holds white space differences between moved lines, i.e.
783 * between '+' and '-' lines that have been detected to be a move.
784 * The string contains the difference in leading white spaces, before the
785 * rest of the line is compared using the white space config for move
786 * coloring. The current_longer indicates if the first string in the
787 * comparision is longer than the second.
788 */
789struct ws_delta {
790 char *string;
791 unsigned int current_longer : 1;
792};
793#define WS_DELTA_INIT { NULL, 0 }
794
795struct moved_block {
796 struct moved_entry *match;
797 struct ws_delta wsd;
798};
799
800static void moved_block_clear(struct moved_block *b)
801{
802 FREE_AND_NULL(b->wsd.string);
803 b->match = NULL;
804}
805
806static int compute_ws_delta(const struct emitted_diff_symbol *a,
807 const struct emitted_diff_symbol *b,
808 struct ws_delta *out)
809{
810 const struct emitted_diff_symbol *longer = a->len > b->len ? a : b;
811 const struct emitted_diff_symbol *shorter = a->len > b->len ? b : a;
812 int d = longer->len - shorter->len;
813
814 if (strncmp(longer->line + d, shorter->line, shorter->len))
815 return 0;
816
817 out->string = xmemdupz(longer->line, d);
818 out->current_longer = (a == longer);
819
820 return 1;
821}
822
823static int cmp_in_block_with_wsd(const struct diff_options *o,
824 const struct moved_entry *cur,
825 const struct moved_entry *match,
826 struct moved_block *pmb,
827 int n)
828{
829 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
830 int al = cur->es->len, cl = l->len;
831 const char *a = cur->es->line,
832 *b = match->es->line,
833 *c = l->line;
834
835 int wslen;
836
837 /*
838 * We need to check if 'cur' is equal to 'match'.
839 * As those are from the same (+/-) side, we do not need to adjust for
840 * indent changes. However these were found using fuzzy matching
841 * so we do have to check if they are equal.
842 */
843 if (strcmp(a, b))
844 return 1;
845
846 if (!pmb->wsd.string)
847 /*
848 * The white space delta is not active? This can happen
849 * when we exit early in this function.
850 */
851 return 1;
852
853 /*
854 * The indent changes of the block are known and stored in
855 * pmb->wsd; however we need to check if the indent changes of the
856 * current line are still the same as before.
857 *
858 * To do so we need to compare 'l' to 'cur', adjusting the
859 * one of them for the white spaces, depending which was longer.
860 */
861
862 wslen = strlen(pmb->wsd.string);
863 if (pmb->wsd.current_longer) {
864 c += wslen;
865 cl -= wslen;
866 } else {
867 a += wslen;
868 al -= wslen;
869 }
870
871 if (al != cl || memcmp(a, c, al))
872 return 1;
873
874 return 0;
875}
876
877static int moved_entry_cmp(const void *hashmap_cmp_fn_data,
878 const void *entry,
879 const void *entry_or_key,
880 const void *keydata)
881{
882 const struct diff_options *diffopt = hashmap_cmp_fn_data;
883 const struct moved_entry *a = entry;
884 const struct moved_entry *b = entry_or_key;
885 unsigned flags = diffopt->color_moved_ws_handling
886 & XDF_WHITESPACE_FLAGS;
887
888 if (diffopt->color_moved_ws_handling &
889 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
890 /*
891 * As there is not specific white space config given,
892 * we'd need to check for a new block, so ignore all
893 * white space. The setup of the white space
894 * configuration for the next block is done else where
895 */
896 flags |= XDF_IGNORE_WHITESPACE;
897
898 return !xdiff_compare_lines(a->es->line, a->es->len,
899 b->es->line, b->es->len,
900 flags);
901}
902
903static struct moved_entry *prepare_entry(struct diff_options *o,
904 int line_no)
905{
906 struct moved_entry *ret = xmalloc(sizeof(*ret));
907 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
908 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
909
910 ret->ent.hash = xdiff_hash_string(l->line, l->len, flags);
911 ret->es = l;
912 ret->next_line = NULL;
913
914 return ret;
915}
916
917static void add_lines_to_move_detection(struct diff_options *o,
918 struct hashmap *add_lines,
919 struct hashmap *del_lines)
920{
921 struct moved_entry *prev_line = NULL;
922
923 int n;
924 for (n = 0; n < o->emitted_symbols->nr; n++) {
925 struct hashmap *hm;
926 struct moved_entry *key;
927
928 switch (o->emitted_symbols->buf[n].s) {
929 case DIFF_SYMBOL_PLUS:
930 hm = add_lines;
931 break;
932 case DIFF_SYMBOL_MINUS:
933 hm = del_lines;
934 break;
935 default:
936 prev_line = NULL;
937 continue;
938 }
939
940 key = prepare_entry(o, n);
941 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
942 prev_line->next_line = key;
943
944 hashmap_add(hm, key);
945 prev_line = key;
946 }
947}
948
949static void pmb_advance_or_null(struct diff_options *o,
950 struct moved_entry *match,
951 struct hashmap *hm,
952 struct moved_block *pmb,
953 int pmb_nr)
954{
955 int i;
956 for (i = 0; i < pmb_nr; i++) {
957 struct moved_entry *prev = pmb[i].match;
958 struct moved_entry *cur = (prev && prev->next_line) ?
959 prev->next_line : NULL;
960 if (cur && !hm->cmpfn(o, cur, match, NULL)) {
961 pmb[i].match = cur;
962 } else {
963 pmb[i].match = NULL;
964 }
965 }
966}
967
968static void pmb_advance_or_null_multi_match(struct diff_options *o,
969 struct moved_entry *match,
970 struct hashmap *hm,
971 struct moved_block *pmb,
972 int pmb_nr, int n)
973{
974 int i;
975 char *got_match = xcalloc(1, pmb_nr);
976
977 for (; match; match = hashmap_get_next(hm, match)) {
978 for (i = 0; i < pmb_nr; i++) {
979 struct moved_entry *prev = pmb[i].match;
980 struct moved_entry *cur = (prev && prev->next_line) ?
981 prev->next_line : NULL;
982 if (!cur)
983 continue;
984 if (!cmp_in_block_with_wsd(o, cur, match, &pmb[i], n))
985 got_match[i] |= 1;
986 }
987 }
988
989 for (i = 0; i < pmb_nr; i++) {
990 if (got_match[i]) {
991 /* Advance to the next line */
992 pmb[i].match = pmb[i].match->next_line;
993 } else {
994 moved_block_clear(&pmb[i]);
995 }
996 }
997}
998
999static int shrink_potential_moved_blocks(struct moved_block *pmb,
1000 int pmb_nr)
1001{
1002 int lp, rp;
1003
1004 /* Shrink the set of potential block to the remaining running */
1005 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
1006 while (lp < pmb_nr && pmb[lp].match)
1007 lp++;
1008 /* lp points at the first NULL now */
1009
1010 while (rp > -1 && !pmb[rp].match)
1011 rp--;
1012 /* rp points at the last non-NULL */
1013
1014 if (lp < pmb_nr && rp > -1 && lp < rp) {
1015 pmb[lp] = pmb[rp];
1016 pmb[rp].match = NULL;
1017 pmb[rp].wsd.string = NULL;
1018 rp--;
1019 lp++;
1020 }
1021 }
1022
1023 /* Remember the number of running sets */
1024 return rp + 1;
1025}
1026
1027/*
1028 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1029 *
1030 * Otherwise, if the last block has fewer alphanumeric characters than
1031 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1032 * that block.
1033 *
1034 * The last block consists of the (n - block_length)'th line up to but not
1035 * including the nth line.
1036 *
1037 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1038 * Think of a way to unify them.
1039 */
1040static void adjust_last_block(struct diff_options *o, int n, int block_length)
1041{
1042 int i, alnum_count = 0;
1043 if (o->color_moved == COLOR_MOVED_PLAIN)
1044 return;
1045 for (i = 1; i < block_length + 1; i++) {
1046 const char *c = o->emitted_symbols->buf[n - i].line;
1047 for (; *c; c++) {
1048 if (!isalnum(*c))
1049 continue;
1050 alnum_count++;
1051 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1052 return;
1053 }
1054 }
1055 for (i = 1; i < block_length + 1; i++)
1056 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
1057}
1058
1059/* Find blocks of moved code, delegate actual coloring decision to helper */
1060static void mark_color_as_moved(struct diff_options *o,
1061 struct hashmap *add_lines,
1062 struct hashmap *del_lines)
1063{
1064 struct moved_block *pmb = NULL; /* potentially moved blocks */
1065 int pmb_nr = 0, pmb_alloc = 0;
1066 int n, flipped_block = 1, block_length = 0;
1067
1068
1069 for (n = 0; n < o->emitted_symbols->nr; n++) {
1070 struct hashmap *hm = NULL;
1071 struct moved_entry *key;
1072 struct moved_entry *match = NULL;
1073 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1074
1075 switch (l->s) {
1076 case DIFF_SYMBOL_PLUS:
1077 hm = del_lines;
1078 key = prepare_entry(o, n);
1079 match = hashmap_get(hm, key, NULL);
1080 free(key);
1081 break;
1082 case DIFF_SYMBOL_MINUS:
1083 hm = add_lines;
1084 key = prepare_entry(o, n);
1085 match = hashmap_get(hm, key, NULL);
1086 free(key);
1087 break;
1088 default:
1089 flipped_block = 1;
1090 }
1091
1092 if (!match) {
1093 int i;
1094
1095 adjust_last_block(o, n, block_length);
1096 for(i = 0; i < pmb_nr; i++)
1097 moved_block_clear(&pmb[i]);
1098 pmb_nr = 0;
1099 block_length = 0;
1100 continue;
1101 }
1102
1103 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1104
1105 if (o->color_moved == COLOR_MOVED_PLAIN)
1106 continue;
1107
1108 if (o->color_moved_ws_handling &
1109 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1110 pmb_advance_or_null_multi_match(o, match, hm, pmb, pmb_nr, n);
1111 else
1112 pmb_advance_or_null(o, match, hm, pmb, pmb_nr);
1113
1114 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
1115
1116 if (pmb_nr == 0) {
1117 /*
1118 * The current line is the start of a new block.
1119 * Setup the set of potential blocks.
1120 */
1121 for (; match; match = hashmap_get_next(hm, match)) {
1122 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1123 if (o->color_moved_ws_handling &
1124 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) {
1125 if (compute_ws_delta(l, match->es,
1126 &pmb[pmb_nr].wsd))
1127 pmb[pmb_nr++].match = match;
1128 } else {
1129 pmb[pmb_nr].wsd.string = NULL;
1130 pmb[pmb_nr++].match = match;
1131 }
1132 }
1133
1134 flipped_block = (flipped_block + 1) % 2;
1135
1136 adjust_last_block(o, n, block_length);
1137 block_length = 0;
1138 }
1139
1140 block_length++;
1141
1142 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1143 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1144 }
1145 adjust_last_block(o, n, block_length);
1146
1147 for(n = 0; n < pmb_nr; n++)
1148 moved_block_clear(&pmb[n]);
1149 free(pmb);
1150}
1151
1152#define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1153 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1154static void dim_moved_lines(struct diff_options *o)
1155{
1156 int n;
1157 for (n = 0; n < o->emitted_symbols->nr; n++) {
1158 struct emitted_diff_symbol *prev = (n != 0) ?
1159 &o->emitted_symbols->buf[n - 1] : NULL;
1160 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1161 struct emitted_diff_symbol *next =
1162 (n < o->emitted_symbols->nr - 1) ?
1163 &o->emitted_symbols->buf[n + 1] : NULL;
1164
1165 /* Not a plus or minus line? */
1166 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1167 continue;
1168
1169 /* Not a moved line? */
1170 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1171 continue;
1172
1173 /*
1174 * If prev or next are not a plus or minus line,
1175 * pretend they don't exist
1176 */
1177 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1178 prev->s != DIFF_SYMBOL_MINUS)
1179 prev = NULL;
1180 if (next && next->s != DIFF_SYMBOL_PLUS &&
1181 next->s != DIFF_SYMBOL_MINUS)
1182 next = NULL;
1183
1184 /* Inside a block? */
1185 if ((prev &&
1186 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1187 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1188 (next &&
1189 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1190 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1191 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1192 continue;
1193 }
1194
1195 /* Check if we are at an interesting bound: */
1196 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1197 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1198 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1199 continue;
1200 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1201 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1202 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1203 continue;
1204
1205 /*
1206 * The boundary to prev and next are not interesting,
1207 * so this line is not interesting as a whole
1208 */
1209 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1210 }
1211}
1212
1213static void emit_line_ws_markup(struct diff_options *o,
1214 const char *set_sign, const char *set,
1215 const char *reset,
1216 char sign, const char *line, int len,
1217 unsigned ws_rule, int blank_at_eof)
1218{
1219 const char *ws = NULL;
1220
1221 if (o->ws_error_highlight & ws_rule) {
1222 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1223 if (!*ws)
1224 ws = NULL;
1225 }
1226
1227 if (!ws && !set_sign)
1228 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1229 else if (!ws) {
1230 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1231 } else if (blank_at_eof)
1232 /* Blank line at EOF - paint '+' as well */
1233 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1234 else {
1235 /* Emit just the prefix, then the rest. */
1236 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1237 sign, "", 0);
1238 ws_check_emit(line, len, ws_rule,
1239 o->file, set, reset, ws);
1240 }
1241}
1242
1243static void emit_diff_symbol_from_struct(struct diff_options *o,
1244 struct emitted_diff_symbol *eds)
1245{
1246 static const char *nneof = " No newline at end of file\n";
1247 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1248 struct strbuf sb = STRBUF_INIT;
1249
1250 enum diff_symbol s = eds->s;
1251 const char *line = eds->line;
1252 int len = eds->len;
1253 unsigned flags = eds->flags;
1254
1255 switch (s) {
1256 case DIFF_SYMBOL_NO_LF_EOF:
1257 context = diff_get_color_opt(o, DIFF_CONTEXT);
1258 reset = diff_get_color_opt(o, DIFF_RESET);
1259 putc('\n', o->file);
1260 emit_line_0(o, context, NULL, 0, reset, '\\',
1261 nneof, strlen(nneof));
1262 break;
1263 case DIFF_SYMBOL_SUBMODULE_HEADER:
1264 case DIFF_SYMBOL_SUBMODULE_ERROR:
1265 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1266 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1267 case DIFF_SYMBOL_SUMMARY:
1268 case DIFF_SYMBOL_STATS_LINE:
1269 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1270 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1271 emit_line(o, "", "", line, len);
1272 break;
1273 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1274 case DIFF_SYMBOL_CONTEXT_MARKER:
1275 context = diff_get_color_opt(o, DIFF_CONTEXT);
1276 reset = diff_get_color_opt(o, DIFF_RESET);
1277 emit_line(o, context, reset, line, len);
1278 break;
1279 case DIFF_SYMBOL_SEPARATOR:
1280 fprintf(o->file, "%s%c",
1281 diff_line_prefix(o),
1282 o->line_termination);
1283 break;
1284 case DIFF_SYMBOL_CONTEXT:
1285 set = diff_get_color_opt(o, DIFF_CONTEXT);
1286 reset = diff_get_color_opt(o, DIFF_RESET);
1287 set_sign = NULL;
1288 if (o->flags.dual_color_diffed_diffs) {
1289 char c = !len ? 0 : line[0];
1290
1291 if (c == '+')
1292 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1293 else if (c == '@')
1294 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1295 else if (c == '-')
1296 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1297 }
1298 emit_line_ws_markup(o, set_sign, set, reset,
1299 o->output_indicators[OUTPUT_INDICATOR_CONTEXT],
1300 line, len,
1301 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1302 break;
1303 case DIFF_SYMBOL_PLUS:
1304 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1305 DIFF_SYMBOL_MOVED_LINE_ALT |
1306 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1307 case DIFF_SYMBOL_MOVED_LINE |
1308 DIFF_SYMBOL_MOVED_LINE_ALT |
1309 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1310 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1311 break;
1312 case DIFF_SYMBOL_MOVED_LINE |
1313 DIFF_SYMBOL_MOVED_LINE_ALT:
1314 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1315 break;
1316 case DIFF_SYMBOL_MOVED_LINE |
1317 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1318 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1319 break;
1320 case DIFF_SYMBOL_MOVED_LINE:
1321 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1322 break;
1323 default:
1324 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1325 }
1326 reset = diff_get_color_opt(o, DIFF_RESET);
1327 if (!o->flags.dual_color_diffed_diffs)
1328 set_sign = NULL;
1329 else {
1330 char c = !len ? 0 : line[0];
1331
1332 set_sign = set;
1333 if (c == '-')
1334 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1335 else if (c == '@')
1336 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1337 else if (c == '+')
1338 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1339 else
1340 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1341 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1342 }
1343 emit_line_ws_markup(o, set_sign, set, reset,
1344 o->output_indicators[OUTPUT_INDICATOR_NEW],
1345 line, len,
1346 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1347 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1348 break;
1349 case DIFF_SYMBOL_MINUS:
1350 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1351 DIFF_SYMBOL_MOVED_LINE_ALT |
1352 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1353 case DIFF_SYMBOL_MOVED_LINE |
1354 DIFF_SYMBOL_MOVED_LINE_ALT |
1355 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1356 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1357 break;
1358 case DIFF_SYMBOL_MOVED_LINE |
1359 DIFF_SYMBOL_MOVED_LINE_ALT:
1360 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1361 break;
1362 case DIFF_SYMBOL_MOVED_LINE |
1363 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1364 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1365 break;
1366 case DIFF_SYMBOL_MOVED_LINE:
1367 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1368 break;
1369 default:
1370 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1371 }
1372 reset = diff_get_color_opt(o, DIFF_RESET);
1373 if (!o->flags.dual_color_diffed_diffs)
1374 set_sign = NULL;
1375 else {
1376 char c = !len ? 0 : line[0];
1377
1378 set_sign = set;
1379 if (c == '+')
1380 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1381 else if (c == '@')
1382 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1383 else if (c == '-')
1384 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1385 else
1386 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1387 }
1388 emit_line_ws_markup(o, set_sign, set, reset,
1389 o->output_indicators[OUTPUT_INDICATOR_OLD],
1390 line, len,
1391 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1392 break;
1393 case DIFF_SYMBOL_WORDS_PORCELAIN:
1394 context = diff_get_color_opt(o, DIFF_CONTEXT);
1395 reset = diff_get_color_opt(o, DIFF_RESET);
1396 emit_line(o, context, reset, line, len);
1397 fputs("~\n", o->file);
1398 break;
1399 case DIFF_SYMBOL_WORDS:
1400 context = diff_get_color_opt(o, DIFF_CONTEXT);
1401 reset = diff_get_color_opt(o, DIFF_RESET);
1402 /*
1403 * Skip the prefix character, if any. With
1404 * diff_suppress_blank_empty, there may be
1405 * none.
1406 */
1407 if (line[0] != '\n') {
1408 line++;
1409 len--;
1410 }
1411 emit_line(o, context, reset, line, len);
1412 break;
1413 case DIFF_SYMBOL_FILEPAIR_PLUS:
1414 meta = diff_get_color_opt(o, DIFF_METAINFO);
1415 reset = diff_get_color_opt(o, DIFF_RESET);
1416 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1417 line, reset,
1418 strchr(line, ' ') ? "\t" : "");
1419 break;
1420 case DIFF_SYMBOL_FILEPAIR_MINUS:
1421 meta = diff_get_color_opt(o, DIFF_METAINFO);
1422 reset = diff_get_color_opt(o, DIFF_RESET);
1423 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1424 line, reset,
1425 strchr(line, ' ') ? "\t" : "");
1426 break;
1427 case DIFF_SYMBOL_BINARY_FILES:
1428 case DIFF_SYMBOL_HEADER:
1429 fprintf(o->file, "%s", line);
1430 break;
1431 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1432 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1433 break;
1434 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1435 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1436 break;
1437 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1438 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1439 break;
1440 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1441 fputs(diff_line_prefix(o), o->file);
1442 fputc('\n', o->file);
1443 break;
1444 case DIFF_SYMBOL_REWRITE_DIFF:
1445 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1446 reset = diff_get_color_opt(o, DIFF_RESET);
1447 emit_line(o, fraginfo, reset, line, len);
1448 break;
1449 case DIFF_SYMBOL_SUBMODULE_ADD:
1450 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1451 reset = diff_get_color_opt(o, DIFF_RESET);
1452 emit_line(o, set, reset, line, len);
1453 break;
1454 case DIFF_SYMBOL_SUBMODULE_DEL:
1455 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1456 reset = diff_get_color_opt(o, DIFF_RESET);
1457 emit_line(o, set, reset, line, len);
1458 break;
1459 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1460 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1461 diff_line_prefix(o), line);
1462 break;
1463 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1464 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1465 diff_line_prefix(o), line);
1466 break;
1467 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1468 emit_line(o, "", "", " 0 files changed\n",
1469 strlen(" 0 files changed\n"));
1470 break;
1471 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1472 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1473 break;
1474 case DIFF_SYMBOL_WORD_DIFF:
1475 fprintf(o->file, "%.*s", len, line);
1476 break;
1477 case DIFF_SYMBOL_STAT_SEP:
1478 fputs(o->stat_sep, o->file);
1479 break;
1480 default:
1481 BUG("unknown diff symbol");
1482 }
1483 strbuf_release(&sb);
1484}
1485
1486static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1487 const char *line, int len, unsigned flags)
1488{
1489 struct emitted_diff_symbol e = {line, len, flags, s};
1490
1491 if (o->emitted_symbols)
1492 append_emitted_diff_symbol(o, &e);
1493 else
1494 emit_diff_symbol_from_struct(o, &e);
1495}
1496
1497void diff_emit_submodule_del(struct diff_options *o, const char *line)
1498{
1499 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1500}
1501
1502void diff_emit_submodule_add(struct diff_options *o, const char *line)
1503{
1504 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1505}
1506
1507void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1508{
1509 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1510 path, strlen(path), 0);
1511}
1512
1513void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1514{
1515 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1516 path, strlen(path), 0);
1517}
1518
1519void diff_emit_submodule_header(struct diff_options *o, const char *header)
1520{
1521 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1522 header, strlen(header), 0);
1523}
1524
1525void diff_emit_submodule_error(struct diff_options *o, const char *err)
1526{
1527 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1528}
1529
1530void diff_emit_submodule_pipethrough(struct diff_options *o,
1531 const char *line, int len)
1532{
1533 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1534}
1535
1536static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1537{
1538 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1539 ecbdata->blank_at_eof_in_preimage &&
1540 ecbdata->blank_at_eof_in_postimage &&
1541 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1542 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1543 return 0;
1544 return ws_blank_line(line, len, ecbdata->ws_rule);
1545}
1546
1547static void emit_add_line(const char *reset,
1548 struct emit_callback *ecbdata,
1549 const char *line, int len)
1550{
1551 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1552 if (new_blank_line_at_eof(ecbdata, line, len))
1553 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1554
1555 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1556}
1557
1558static void emit_del_line(const char *reset,
1559 struct emit_callback *ecbdata,
1560 const char *line, int len)
1561{
1562 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1563 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1564}
1565
1566static void emit_context_line(const char *reset,
1567 struct emit_callback *ecbdata,
1568 const char *line, int len)
1569{
1570 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1571 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1572}
1573
1574static void emit_hunk_header(struct emit_callback *ecbdata,
1575 const char *line, int len)
1576{
1577 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1578 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1579 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1580 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1581 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1582 static const char atat[2] = { '@', '@' };
1583 const char *cp, *ep;
1584 struct strbuf msgbuf = STRBUF_INIT;
1585 int org_len = len;
1586 int i = 1;
1587
1588 /*
1589 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1590 * it always is at least 10 bytes long.
1591 */
1592 if (len < 10 ||
1593 memcmp(line, atat, 2) ||
1594 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1595 emit_diff_symbol(ecbdata->opt,
1596 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1597 return;
1598 }
1599 ep += 2; /* skip over @@ */
1600
1601 /* The hunk header in fraginfo color */
1602 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1603 strbuf_addstr(&msgbuf, reverse);
1604 strbuf_addstr(&msgbuf, frag);
1605 strbuf_add(&msgbuf, line, ep - line);
1606 strbuf_addstr(&msgbuf, reset);
1607
1608 /*
1609 * trailing "\r\n"
1610 */
1611 for ( ; i < 3; i++)
1612 if (line[len - i] == '\r' || line[len - i] == '\n')
1613 len--;
1614
1615 /* blank before the func header */
1616 for (cp = ep; ep - line < len; ep++)
1617 if (*ep != ' ' && *ep != '\t')
1618 break;
1619 if (ep != cp) {
1620 strbuf_addstr(&msgbuf, context);
1621 strbuf_add(&msgbuf, cp, ep - cp);
1622 strbuf_addstr(&msgbuf, reset);
1623 }
1624
1625 if (ep < line + len) {
1626 strbuf_addstr(&msgbuf, func);
1627 strbuf_add(&msgbuf, ep, line + len - ep);
1628 strbuf_addstr(&msgbuf, reset);
1629 }
1630
1631 strbuf_add(&msgbuf, line + len, org_len - len);
1632 strbuf_complete_line(&msgbuf);
1633 emit_diff_symbol(ecbdata->opt,
1634 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1635 strbuf_release(&msgbuf);
1636}
1637
1638static struct diff_tempfile *claim_diff_tempfile(void) {
1639 int i;
1640 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1641 if (!diff_temp[i].name)
1642 return diff_temp + i;
1643 BUG("diff is failing to clean up its tempfiles");
1644}
1645
1646static void remove_tempfile(void)
1647{
1648 int i;
1649 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1650 if (is_tempfile_active(diff_temp[i].tempfile))
1651 delete_tempfile(&diff_temp[i].tempfile);
1652 diff_temp[i].name = NULL;
1653 }
1654}
1655
1656static void add_line_count(struct strbuf *out, int count)
1657{
1658 switch (count) {
1659 case 0:
1660 strbuf_addstr(out, "0,0");
1661 break;
1662 case 1:
1663 strbuf_addstr(out, "1");
1664 break;
1665 default:
1666 strbuf_addf(out, "1,%d", count);
1667 break;
1668 }
1669}
1670
1671static void emit_rewrite_lines(struct emit_callback *ecb,
1672 int prefix, const char *data, int size)
1673{
1674 const char *endp = NULL;
1675 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1676
1677 while (0 < size) {
1678 int len;
1679
1680 endp = memchr(data, '\n', size);
1681 len = endp ? (endp - data + 1) : size;
1682 if (prefix != '+') {
1683 ecb->lno_in_preimage++;
1684 emit_del_line(reset, ecb, data, len);
1685 } else {
1686 ecb->lno_in_postimage++;
1687 emit_add_line(reset, ecb, data, len);
1688 }
1689 size -= len;
1690 data += len;
1691 }
1692 if (!endp)
1693 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1694}
1695
1696static void emit_rewrite_diff(const char *name_a,
1697 const char *name_b,
1698 struct diff_filespec *one,
1699 struct diff_filespec *two,
1700 struct userdiff_driver *textconv_one,
1701 struct userdiff_driver *textconv_two,
1702 struct diff_options *o)
1703{
1704 int lc_a, lc_b;
1705 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1706 const char *a_prefix, *b_prefix;
1707 char *data_one, *data_two;
1708 size_t size_one, size_two;
1709 struct emit_callback ecbdata;
1710 struct strbuf out = STRBUF_INIT;
1711
1712 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1713 a_prefix = o->b_prefix;
1714 b_prefix = o->a_prefix;
1715 } else {
1716 a_prefix = o->a_prefix;
1717 b_prefix = o->b_prefix;
1718 }
1719
1720 name_a += (*name_a == '/');
1721 name_b += (*name_b == '/');
1722
1723 strbuf_reset(&a_name);
1724 strbuf_reset(&b_name);
1725 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1726 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1727
1728 size_one = fill_textconv(textconv_one, one, &data_one);
1729 size_two = fill_textconv(textconv_two, two, &data_two);
1730
1731 memset(&ecbdata, 0, sizeof(ecbdata));
1732 ecbdata.color_diff = want_color(o->use_color);
1733 ecbdata.ws_rule = whitespace_rule(name_b);
1734 ecbdata.opt = o;
1735 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1736 mmfile_t mf1, mf2;
1737 mf1.ptr = (char *)data_one;
1738 mf2.ptr = (char *)data_two;
1739 mf1.size = size_one;
1740 mf2.size = size_two;
1741 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1742 }
1743 ecbdata.lno_in_preimage = 1;
1744 ecbdata.lno_in_postimage = 1;
1745
1746 lc_a = count_lines(data_one, size_one);
1747 lc_b = count_lines(data_two, size_two);
1748
1749 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1750 a_name.buf, a_name.len, 0);
1751 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1752 b_name.buf, b_name.len, 0);
1753
1754 strbuf_addstr(&out, "@@ -");
1755 if (!o->irreversible_delete)
1756 add_line_count(&out, lc_a);
1757 else
1758 strbuf_addstr(&out, "?,?");
1759 strbuf_addstr(&out, " +");
1760 add_line_count(&out, lc_b);
1761 strbuf_addstr(&out, " @@\n");
1762 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1763 strbuf_release(&out);
1764
1765 if (lc_a && !o->irreversible_delete)
1766 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1767 if (lc_b)
1768 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1769 if (textconv_one)
1770 free((char *)data_one);
1771 if (textconv_two)
1772 free((char *)data_two);
1773}
1774
1775struct diff_words_buffer {
1776 mmfile_t text;
1777 unsigned long alloc;
1778 struct diff_words_orig {
1779 const char *begin, *end;
1780 } *orig;
1781 int orig_nr, orig_alloc;
1782};
1783
1784static void diff_words_append(char *line, unsigned long len,
1785 struct diff_words_buffer *buffer)
1786{
1787 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1788 line++;
1789 len--;
1790 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1791 buffer->text.size += len;
1792 buffer->text.ptr[buffer->text.size] = '\0';
1793}
1794
1795struct diff_words_style_elem {
1796 const char *prefix;
1797 const char *suffix;
1798 const char *color; /* NULL; filled in by the setup code if
1799 * color is enabled */
1800};
1801
1802struct diff_words_style {
1803 enum diff_words_type type;
1804 struct diff_words_style_elem new_word, old_word, ctx;
1805 const char *newline;
1806};
1807
1808static struct diff_words_style diff_words_styles[] = {
1809 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1810 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1811 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1812};
1813
1814struct diff_words_data {
1815 struct diff_words_buffer minus, plus;
1816 const char *current_plus;
1817 int last_minus;
1818 struct diff_options *opt;
1819 regex_t *word_regex;
1820 enum diff_words_type type;
1821 struct diff_words_style *style;
1822};
1823
1824static int fn_out_diff_words_write_helper(struct diff_options *o,
1825 struct diff_words_style_elem *st_el,
1826 const char *newline,
1827 size_t count, const char *buf)
1828{
1829 int print = 0;
1830 struct strbuf sb = STRBUF_INIT;
1831
1832 while (count) {
1833 char *p = memchr(buf, '\n', count);
1834 if (print)
1835 strbuf_addstr(&sb, diff_line_prefix(o));
1836
1837 if (p != buf) {
1838 const char *reset = st_el->color && *st_el->color ?
1839 GIT_COLOR_RESET : NULL;
1840 if (st_el->color && *st_el->color)
1841 strbuf_addstr(&sb, st_el->color);
1842 strbuf_addstr(&sb, st_el->prefix);
1843 strbuf_add(&sb, buf, p ? p - buf : count);
1844 strbuf_addstr(&sb, st_el->suffix);
1845 if (reset)
1846 strbuf_addstr(&sb, reset);
1847 }
1848 if (!p)
1849 goto out;
1850
1851 strbuf_addstr(&sb, newline);
1852 count -= p + 1 - buf;
1853 buf = p + 1;
1854 print = 1;
1855 if (count) {
1856 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1857 sb.buf, sb.len, 0);
1858 strbuf_reset(&sb);
1859 }
1860 }
1861
1862out:
1863 if (sb.len)
1864 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1865 sb.buf, sb.len, 0);
1866 strbuf_release(&sb);
1867 return 0;
1868}
1869
1870/*
1871 * '--color-words' algorithm can be described as:
1872 *
1873 * 1. collect the minus/plus lines of a diff hunk, divided into
1874 * minus-lines and plus-lines;
1875 *
1876 * 2. break both minus-lines and plus-lines into words and
1877 * place them into two mmfile_t with one word for each line;
1878 *
1879 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1880 *
1881 * And for the common parts of the both file, we output the plus side text.
1882 * diff_words->current_plus is used to trace the current position of the plus file
1883 * which printed. diff_words->last_minus is used to trace the last minus word
1884 * printed.
1885 *
1886 * For '--graph' to work with '--color-words', we need to output the graph prefix
1887 * on each line of color words output. Generally, there are two conditions on
1888 * which we should output the prefix.
1889 *
1890 * 1. diff_words->last_minus == 0 &&
1891 * diff_words->current_plus == diff_words->plus.text.ptr
1892 *
1893 * that is: the plus text must start as a new line, and if there is no minus
1894 * word printed, a graph prefix must be printed.
1895 *
1896 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1897 * *(diff_words->current_plus - 1) == '\n'
1898 *
1899 * that is: a graph prefix must be printed following a '\n'
1900 */
1901static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1902{
1903 if ((diff_words->last_minus == 0 &&
1904 diff_words->current_plus == diff_words->plus.text.ptr) ||
1905 (diff_words->current_plus > diff_words->plus.text.ptr &&
1906 *(diff_words->current_plus - 1) == '\n')) {
1907 return 1;
1908 } else {
1909 return 0;
1910 }
1911}
1912
1913static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
1914{
1915 struct diff_words_data *diff_words = priv;
1916 struct diff_words_style *style = diff_words->style;
1917 int minus_first, minus_len, plus_first, plus_len;
1918 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1919 struct diff_options *opt = diff_words->opt;
1920 const char *line_prefix;
1921
1922 if (line[0] != '@' || parse_hunk_header(line, len,
1923 &minus_first, &minus_len, &plus_first, &plus_len))
1924 return;
1925
1926 assert(opt);
1927 line_prefix = diff_line_prefix(opt);
1928
1929 /* POSIX requires that first be decremented by one if len == 0... */
1930 if (minus_len) {
1931 minus_begin = diff_words->minus.orig[minus_first].begin;
1932 minus_end =
1933 diff_words->minus.orig[minus_first + minus_len - 1].end;
1934 } else
1935 minus_begin = minus_end =
1936 diff_words->minus.orig[minus_first].end;
1937
1938 if (plus_len) {
1939 plus_begin = diff_words->plus.orig[plus_first].begin;
1940 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1941 } else
1942 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1943
1944 if (color_words_output_graph_prefix(diff_words)) {
1945 fputs(line_prefix, diff_words->opt->file);
1946 }
1947 if (diff_words->current_plus != plus_begin) {
1948 fn_out_diff_words_write_helper(diff_words->opt,
1949 &style->ctx, style->newline,
1950 plus_begin - diff_words->current_plus,
1951 diff_words->current_plus);
1952 }
1953 if (minus_begin != minus_end) {
1954 fn_out_diff_words_write_helper(diff_words->opt,
1955 &style->old_word, style->newline,
1956 minus_end - minus_begin, minus_begin);
1957 }
1958 if (plus_begin != plus_end) {
1959 fn_out_diff_words_write_helper(diff_words->opt,
1960 &style->new_word, style->newline,
1961 plus_end - plus_begin, plus_begin);
1962 }
1963
1964 diff_words->current_plus = plus_end;
1965 diff_words->last_minus = minus_first;
1966}
1967
1968/* This function starts looking at *begin, and returns 0 iff a word was found. */
1969static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1970 int *begin, int *end)
1971{
1972 if (word_regex && *begin < buffer->size) {
1973 regmatch_t match[1];
1974 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1975 buffer->size - *begin, 1, match, 0)) {
1976 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1977 '\n', match[0].rm_eo - match[0].rm_so);
1978 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1979 *begin += match[0].rm_so;
1980 return *begin >= *end;
1981 }
1982 return -1;
1983 }
1984
1985 /* find the next word */
1986 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1987 (*begin)++;
1988 if (*begin >= buffer->size)
1989 return -1;
1990
1991 /* find the end of the word */
1992 *end = *begin + 1;
1993 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1994 (*end)++;
1995
1996 return 0;
1997}
1998
1999/*
2000 * This function splits the words in buffer->text, stores the list with
2001 * newline separator into out, and saves the offsets of the original words
2002 * in buffer->orig.
2003 */
2004static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2005 regex_t *word_regex)
2006{
2007 int i, j;
2008 long alloc = 0;
2009
2010 out->size = 0;
2011 out->ptr = NULL;
2012
2013 /* fake an empty "0th" word */
2014 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2015 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2016 buffer->orig_nr = 1;
2017
2018 for (i = 0; i < buffer->text.size; i++) {
2019 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2020 return;
2021
2022 /* store original boundaries */
2023 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2024 buffer->orig_alloc);
2025 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2026 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2027 buffer->orig_nr++;
2028
2029 /* store one word */
2030 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2031 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2032 out->ptr[out->size + j - i] = '\n';
2033 out->size += j - i + 1;
2034
2035 i = j - 1;
2036 }
2037}
2038
2039/* this executes the word diff on the accumulated buffers */
2040static void diff_words_show(struct diff_words_data *diff_words)
2041{
2042 xpparam_t xpp;
2043 xdemitconf_t xecfg;
2044 mmfile_t minus, plus;
2045 struct diff_words_style *style = diff_words->style;
2046
2047 struct diff_options *opt = diff_words->opt;
2048 const char *line_prefix;
2049
2050 assert(opt);
2051 line_prefix = diff_line_prefix(opt);
2052
2053 /* special case: only removal */
2054 if (!diff_words->plus.text.size) {
2055 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2056 line_prefix, strlen(line_prefix), 0);
2057 fn_out_diff_words_write_helper(diff_words->opt,
2058 &style->old_word, style->newline,
2059 diff_words->minus.text.size,
2060 diff_words->minus.text.ptr);
2061 diff_words->minus.text.size = 0;
2062 return;
2063 }
2064
2065 diff_words->current_plus = diff_words->plus.text.ptr;
2066 diff_words->last_minus = 0;
2067
2068 memset(&xpp, 0, sizeof(xpp));
2069 memset(&xecfg, 0, sizeof(xecfg));
2070 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2071 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2072 xpp.flags = 0;
2073 /* as only the hunk header will be parsed, we need a 0-context */
2074 xecfg.ctxlen = 0;
2075 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
2076 &xpp, &xecfg))
2077 die("unable to generate word diff");
2078 free(minus.ptr);
2079 free(plus.ptr);
2080 if (diff_words->current_plus != diff_words->plus.text.ptr +
2081 diff_words->plus.text.size) {
2082 if (color_words_output_graph_prefix(diff_words))
2083 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2084 line_prefix, strlen(line_prefix), 0);
2085 fn_out_diff_words_write_helper(diff_words->opt,
2086 &style->ctx, style->newline,
2087 diff_words->plus.text.ptr + diff_words->plus.text.size
2088 - diff_words->current_plus, diff_words->current_plus);
2089 }
2090 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2091}
2092
2093/* In "color-words" mode, show word-diff of words accumulated in the buffer */
2094static void diff_words_flush(struct emit_callback *ecbdata)
2095{
2096 struct diff_options *wo = ecbdata->diff_words->opt;
2097
2098 if (ecbdata->diff_words->minus.text.size ||
2099 ecbdata->diff_words->plus.text.size)
2100 diff_words_show(ecbdata->diff_words);
2101
2102 if (wo->emitted_symbols) {
2103 struct diff_options *o = ecbdata->opt;
2104 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2105 int i;
2106
2107 /*
2108 * NEEDSWORK:
2109 * Instead of appending each, concat all words to a line?
2110 */
2111 for (i = 0; i < wol->nr; i++)
2112 append_emitted_diff_symbol(o, &wol->buf[i]);
2113
2114 for (i = 0; i < wol->nr; i++)
2115 free((void *)wol->buf[i].line);
2116
2117 wol->nr = 0;
2118 }
2119}
2120
2121static void diff_filespec_load_driver(struct diff_filespec *one)
2122{
2123 /* Use already-loaded driver */
2124 if (one->driver)
2125 return;
2126
2127 if (S_ISREG(one->mode))
2128 one->driver = userdiff_find_by_path(one->path);
2129
2130 /* Fallback to default settings */
2131 if (!one->driver)
2132 one->driver = userdiff_find_by_name("default");
2133}
2134
2135static const char *userdiff_word_regex(struct diff_filespec *one)
2136{
2137 diff_filespec_load_driver(one);
2138 return one->driver->word_regex;
2139}
2140
2141static void init_diff_words_data(struct emit_callback *ecbdata,
2142 struct diff_options *orig_opts,
2143 struct diff_filespec *one,
2144 struct diff_filespec *two)
2145{
2146 int i;
2147 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2148 memcpy(o, orig_opts, sizeof(struct diff_options));
2149
2150 ecbdata->diff_words =
2151 xcalloc(1, sizeof(struct diff_words_data));
2152 ecbdata->diff_words->type = o->word_diff;
2153 ecbdata->diff_words->opt = o;
2154
2155 if (orig_opts->emitted_symbols)
2156 o->emitted_symbols =
2157 xcalloc(1, sizeof(struct emitted_diff_symbols));
2158
2159 if (!o->word_regex)
2160 o->word_regex = userdiff_word_regex(one);
2161 if (!o->word_regex)
2162 o->word_regex = userdiff_word_regex(two);
2163 if (!o->word_regex)
2164 o->word_regex = diff_word_regex_cfg;
2165 if (o->word_regex) {
2166 ecbdata->diff_words->word_regex = (regex_t *)
2167 xmalloc(sizeof(regex_t));
2168 if (regcomp(ecbdata->diff_words->word_regex,
2169 o->word_regex,
2170 REG_EXTENDED | REG_NEWLINE))
2171 die("invalid regular expression: %s",
2172 o->word_regex);
2173 }
2174 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2175 if (o->word_diff == diff_words_styles[i].type) {
2176 ecbdata->diff_words->style =
2177 &diff_words_styles[i];
2178 break;
2179 }
2180 }
2181 if (want_color(o->use_color)) {
2182 struct diff_words_style *st = ecbdata->diff_words->style;
2183 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2184 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2185 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2186 }
2187}
2188
2189static void free_diff_words_data(struct emit_callback *ecbdata)
2190{
2191 if (ecbdata->diff_words) {
2192 diff_words_flush(ecbdata);
2193 free (ecbdata->diff_words->opt->emitted_symbols);
2194 free (ecbdata->diff_words->opt);
2195 free (ecbdata->diff_words->minus.text.ptr);
2196 free (ecbdata->diff_words->minus.orig);
2197 free (ecbdata->diff_words->plus.text.ptr);
2198 free (ecbdata->diff_words->plus.orig);
2199 if (ecbdata->diff_words->word_regex) {
2200 regfree(ecbdata->diff_words->word_regex);
2201 free(ecbdata->diff_words->word_regex);
2202 }
2203 FREE_AND_NULL(ecbdata->diff_words);
2204 }
2205}
2206
2207const char *diff_get_color(int diff_use_color, enum color_diff ix)
2208{
2209 if (want_color(diff_use_color))
2210 return diff_colors[ix];
2211 return "";
2212}
2213
2214const char *diff_line_prefix(struct diff_options *opt)
2215{
2216 struct strbuf *msgbuf;
2217 if (!opt->output_prefix)
2218 return "";
2219
2220 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2221 return msgbuf->buf;
2222}
2223
2224static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
2225{
2226 const char *cp;
2227 unsigned long allot;
2228 size_t l = len;
2229
2230 cp = line;
2231 allot = l;
2232 while (0 < l) {
2233 (void) utf8_width(&cp, &l);
2234 if (!cp)
2235 break; /* truncated in the middle? */
2236 }
2237 return allot - l;
2238}
2239
2240static void find_lno(const char *line, struct emit_callback *ecbdata)
2241{
2242 const char *p;
2243 ecbdata->lno_in_preimage = 0;
2244 ecbdata->lno_in_postimage = 0;
2245 p = strchr(line, '-');
2246 if (!p)
2247 return; /* cannot happen */
2248 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2249 p = strchr(p, '+');
2250 if (!p)
2251 return; /* cannot happen */
2252 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2253}
2254
2255static void fn_out_consume(void *priv, char *line, unsigned long len)
2256{
2257 struct emit_callback *ecbdata = priv;
2258 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
2259 struct diff_options *o = ecbdata->opt;
2260
2261 o->found_changes = 1;
2262
2263 if (ecbdata->header) {
2264 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2265 ecbdata->header->buf, ecbdata->header->len, 0);
2266 strbuf_reset(ecbdata->header);
2267 ecbdata->header = NULL;
2268 }
2269
2270 if (ecbdata->label_path[0]) {
2271 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2272 ecbdata->label_path[0],
2273 strlen(ecbdata->label_path[0]), 0);
2274 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2275 ecbdata->label_path[1],
2276 strlen(ecbdata->label_path[1]), 0);
2277 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2278 }
2279
2280 if (diff_suppress_blank_empty
2281 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2282 line[0] = '\n';
2283 len = 1;
2284 }
2285
2286 if (line[0] == '@') {
2287 if (ecbdata->diff_words)
2288 diff_words_flush(ecbdata);
2289 len = sane_truncate_line(ecbdata, line, len);
2290 find_lno(line, ecbdata);
2291 emit_hunk_header(ecbdata, line, len);
2292 return;
2293 }
2294
2295 if (ecbdata->diff_words) {
2296 enum diff_symbol s =
2297 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2298 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2299 if (line[0] == '-') {
2300 diff_words_append(line, len,
2301 &ecbdata->diff_words->minus);
2302 return;
2303 } else if (line[0] == '+') {
2304 diff_words_append(line, len,
2305 &ecbdata->diff_words->plus);
2306 return;
2307 } else if (starts_with(line, "\\ ")) {
2308 /*
2309 * Eat the "no newline at eof" marker as if we
2310 * saw a "+" or "-" line with nothing on it,
2311 * and return without diff_words_flush() to
2312 * defer processing. If this is the end of
2313 * preimage, more "+" lines may come after it.
2314 */
2315 return;
2316 }
2317 diff_words_flush(ecbdata);
2318 emit_diff_symbol(o, s, line, len, 0);
2319 return;
2320 }
2321
2322 switch (line[0]) {
2323 case '+':
2324 ecbdata->lno_in_postimage++;
2325 emit_add_line(reset, ecbdata, line + 1, len - 1);
2326 break;
2327 case '-':
2328 ecbdata->lno_in_preimage++;
2329 emit_del_line(reset, ecbdata, line + 1, len - 1);
2330 break;
2331 case ' ':
2332 ecbdata->lno_in_postimage++;
2333 ecbdata->lno_in_preimage++;
2334 emit_context_line(reset, ecbdata, line + 1, len - 1);
2335 break;
2336 default:
2337 /* incomplete line at the end */
2338 ecbdata->lno_in_preimage++;
2339 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2340 line, len, 0);
2341 break;
2342 }
2343}
2344
2345static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2346{
2347 const char *old_name = a;
2348 const char *new_name = b;
2349 int pfx_length, sfx_length;
2350 int pfx_adjust_for_slash;
2351 int len_a = strlen(a);
2352 int len_b = strlen(b);
2353 int a_midlen, b_midlen;
2354 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2355 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2356
2357 if (qlen_a || qlen_b) {
2358 quote_c_style(a, name, NULL, 0);
2359 strbuf_addstr(name, " => ");
2360 quote_c_style(b, name, NULL, 0);
2361 return;
2362 }
2363
2364 /* Find common prefix */
2365 pfx_length = 0;
2366 while (*old_name && *new_name && *old_name == *new_name) {
2367 if (*old_name == '/')
2368 pfx_length = old_name - a + 1;
2369 old_name++;
2370 new_name++;
2371 }
2372
2373 /* Find common suffix */
2374 old_name = a + len_a;
2375 new_name = b + len_b;
2376 sfx_length = 0;
2377 /*
2378 * If there is a common prefix, it must end in a slash. In
2379 * that case we let this loop run 1 into the prefix to see the
2380 * same slash.
2381 *
2382 * If there is no common prefix, we cannot do this as it would
2383 * underrun the input strings.
2384 */
2385 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2386 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2387 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2388 *old_name == *new_name) {
2389 if (*old_name == '/')
2390 sfx_length = len_a - (old_name - a);
2391 old_name--;
2392 new_name--;
2393 }
2394
2395 /*
2396 * pfx{mid-a => mid-b}sfx
2397 * {pfx-a => pfx-b}sfx
2398 * pfx{sfx-a => sfx-b}
2399 * name-a => name-b
2400 */
2401 a_midlen = len_a - pfx_length - sfx_length;
2402 b_midlen = len_b - pfx_length - sfx_length;
2403 if (a_midlen < 0)
2404 a_midlen = 0;
2405 if (b_midlen < 0)
2406 b_midlen = 0;
2407
2408 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2409 if (pfx_length + sfx_length) {
2410 strbuf_add(name, a, pfx_length);
2411 strbuf_addch(name, '{');
2412 }
2413 strbuf_add(name, a + pfx_length, a_midlen);
2414 strbuf_addstr(name, " => ");
2415 strbuf_add(name, b + pfx_length, b_midlen);
2416 if (pfx_length + sfx_length) {
2417 strbuf_addch(name, '}');
2418 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2419 }
2420}
2421
2422struct diffstat_t {
2423 int nr;
2424 int alloc;
2425 struct diffstat_file {
2426 char *from_name;
2427 char *name;
2428 char *print_name;
2429 const char *comments;
2430 unsigned is_unmerged:1;
2431 unsigned is_binary:1;
2432 unsigned is_renamed:1;
2433 unsigned is_interesting:1;
2434 uintmax_t added, deleted;
2435 } **files;
2436};
2437
2438static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2439 const char *name_a,
2440 const char *name_b)
2441{
2442 struct diffstat_file *x;
2443 x = xcalloc(1, sizeof(*x));
2444 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2445 diffstat->files[diffstat->nr++] = x;
2446 if (name_b) {
2447 x->from_name = xstrdup(name_a);
2448 x->name = xstrdup(name_b);
2449 x->is_renamed = 1;
2450 }
2451 else {
2452 x->from_name = NULL;
2453 x->name = xstrdup(name_a);
2454 }
2455 return x;
2456}
2457
2458static void diffstat_consume(void *priv, char *line, unsigned long len)
2459{
2460 struct diffstat_t *diffstat = priv;
2461 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2462
2463 if (line[0] == '+')
2464 x->added++;
2465 else if (line[0] == '-')
2466 x->deleted++;
2467}
2468
2469const char mime_boundary_leader[] = "------------";
2470
2471static int scale_linear(int it, int width, int max_change)
2472{
2473 if (!it)
2474 return 0;
2475 /*
2476 * make sure that at least one '-' or '+' is printed if
2477 * there is any change to this path. The easiest way is to
2478 * scale linearly as if the alloted width is one column shorter
2479 * than it is, and then add 1 to the result.
2480 */
2481 return 1 + (it * (width - 1) / max_change);
2482}
2483
2484static void show_graph(struct strbuf *out, char ch, int cnt,
2485 const char *set, const char *reset)
2486{
2487 if (cnt <= 0)
2488 return;
2489 strbuf_addstr(out, set);
2490 strbuf_addchars(out, ch, cnt);
2491 strbuf_addstr(out, reset);
2492}
2493
2494static void fill_print_name(struct diffstat_file *file)
2495{
2496 struct strbuf pname = STRBUF_INIT;
2497
2498 if (file->print_name)
2499 return;
2500
2501 if (file->is_renamed)
2502 pprint_rename(&pname, file->from_name, file->name);
2503 else
2504 quote_c_style(file->name, &pname, NULL, 0);
2505
2506 if (file->comments)
2507 strbuf_addf(&pname, " (%s)", file->comments);
2508
2509 file->print_name = strbuf_detach(&pname, NULL);
2510}
2511
2512static void print_stat_summary_inserts_deletes(struct diff_options *options,
2513 int files, int insertions, int deletions)
2514{
2515 struct strbuf sb = STRBUF_INIT;
2516
2517 if (!files) {
2518 assert(insertions == 0 && deletions == 0);
2519 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2520 NULL, 0, 0);
2521 return;
2522 }
2523
2524 strbuf_addf(&sb,
2525 (files == 1) ? " %d file changed" : " %d files changed",
2526 files);
2527
2528 /*
2529 * For binary diff, the caller may want to print "x files
2530 * changed" with insertions == 0 && deletions == 0.
2531 *
2532 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2533 * is probably less confusing (i.e skip over "2 files changed
2534 * but nothing about added/removed lines? Is this a bug in Git?").
2535 */
2536 if (insertions || deletions == 0) {
2537 strbuf_addf(&sb,
2538 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2539 insertions);
2540 }
2541
2542 if (deletions || insertions == 0) {
2543 strbuf_addf(&sb,
2544 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2545 deletions);
2546 }
2547 strbuf_addch(&sb, '\n');
2548 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2549 sb.buf, sb.len, 0);
2550 strbuf_release(&sb);
2551}
2552
2553void print_stat_summary(FILE *fp, int files,
2554 int insertions, int deletions)
2555{
2556 struct diff_options o;
2557 memset(&o, 0, sizeof(o));
2558 o.file = fp;
2559
2560 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2561}
2562
2563static void show_stats(struct diffstat_t *data, struct diff_options *options)
2564{
2565 int i, len, add, del, adds = 0, dels = 0;
2566 uintmax_t max_change = 0, max_len = 0;
2567 int total_files = data->nr, count;
2568 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2569 const char *reset, *add_c, *del_c;
2570 int extra_shown = 0;
2571 const char *line_prefix = diff_line_prefix(options);
2572 struct strbuf out = STRBUF_INIT;
2573
2574 if (data->nr == 0)
2575 return;
2576
2577 count = options->stat_count ? options->stat_count : data->nr;
2578
2579 reset = diff_get_color_opt(options, DIFF_RESET);
2580 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2581 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2582
2583 /*
2584 * Find the longest filename and max number of changes
2585 */
2586 for (i = 0; (i < count) && (i < data->nr); i++) {
2587 struct diffstat_file *file = data->files[i];
2588 uintmax_t change = file->added + file->deleted;
2589
2590 if (!file->is_interesting && (change == 0)) {
2591 count++; /* not shown == room for one more */
2592 continue;
2593 }
2594 fill_print_name(file);
2595 len = strlen(file->print_name);
2596 if (max_len < len)
2597 max_len = len;
2598
2599 if (file->is_unmerged) {
2600 /* "Unmerged" is 8 characters */
2601 bin_width = bin_width < 8 ? 8 : bin_width;
2602 continue;
2603 }
2604 if (file->is_binary) {
2605 /* "Bin XXX -> YYY bytes" */
2606 int w = 14 + decimal_width(file->added)
2607 + decimal_width(file->deleted);
2608 bin_width = bin_width < w ? w : bin_width;
2609 /* Display change counts aligned with "Bin" */
2610 number_width = 3;
2611 continue;
2612 }
2613
2614 if (max_change < change)
2615 max_change = change;
2616 }
2617 count = i; /* where we can stop scanning in data->files[] */
2618
2619 /*
2620 * We have width = stat_width or term_columns() columns total.
2621 * We want a maximum of min(max_len, stat_name_width) for the name part.
2622 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2623 * We also need 1 for " " and 4 + decimal_width(max_change)
2624 * for " | NNNN " and one the empty column at the end, altogether
2625 * 6 + decimal_width(max_change).
2626 *
2627 * If there's not enough space, we will use the smaller of
2628 * stat_name_width (if set) and 5/8*width for the filename,
2629 * and the rest for constant elements + graph part, but no more
2630 * than stat_graph_width for the graph part.
2631 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2632 * for the standard terminal size).
2633 *
2634 * In other words: stat_width limits the maximum width, and
2635 * stat_name_width fixes the maximum width of the filename,
2636 * and is also used to divide available columns if there
2637 * aren't enough.
2638 *
2639 * Binary files are displayed with "Bin XXX -> YYY bytes"
2640 * instead of the change count and graph. This part is treated
2641 * similarly to the graph part, except that it is not
2642 * "scaled". If total width is too small to accommodate the
2643 * guaranteed minimum width of the filename part and the
2644 * separators and this message, this message will "overflow"
2645 * making the line longer than the maximum width.
2646 */
2647
2648 if (options->stat_width == -1)
2649 width = term_columns() - strlen(line_prefix);
2650 else
2651 width = options->stat_width ? options->stat_width : 80;
2652 number_width = decimal_width(max_change) > number_width ?
2653 decimal_width(max_change) : number_width;
2654
2655 if (options->stat_graph_width == -1)
2656 options->stat_graph_width = diff_stat_graph_width;
2657
2658 /*
2659 * Guarantee 3/8*16==6 for the graph part
2660 * and 5/8*16==10 for the filename part
2661 */
2662 if (width < 16 + 6 + number_width)
2663 width = 16 + 6 + number_width;
2664
2665 /*
2666 * First assign sizes that are wanted, ignoring available width.
2667 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2668 * starting from "XXX" should fit in graph_width.
2669 */
2670 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2671 if (options->stat_graph_width &&
2672 options->stat_graph_width < graph_width)
2673 graph_width = options->stat_graph_width;
2674
2675 name_width = (options->stat_name_width > 0 &&
2676 options->stat_name_width < max_len) ?
2677 options->stat_name_width : max_len;
2678
2679 /*
2680 * Adjust adjustable widths not to exceed maximum width
2681 */
2682 if (name_width + number_width + 6 + graph_width > width) {
2683 if (graph_width > width * 3/8 - number_width - 6) {
2684 graph_width = width * 3/8 - number_width - 6;
2685 if (graph_width < 6)
2686 graph_width = 6;
2687 }
2688
2689 if (options->stat_graph_width &&
2690 graph_width > options->stat_graph_width)
2691 graph_width = options->stat_graph_width;
2692 if (name_width > width - number_width - 6 - graph_width)
2693 name_width = width - number_width - 6 - graph_width;
2694 else
2695 graph_width = width - number_width - 6 - name_width;
2696 }
2697
2698 /*
2699 * From here name_width is the width of the name area,
2700 * and graph_width is the width of the graph area.
2701 * max_change is used to scale graph properly.
2702 */
2703 for (i = 0; i < count; i++) {
2704 const char *prefix = "";
2705 struct diffstat_file *file = data->files[i];
2706 char *name = file->print_name;
2707 uintmax_t added = file->added;
2708 uintmax_t deleted = file->deleted;
2709 int name_len;
2710
2711 if (!file->is_interesting && (added + deleted == 0))
2712 continue;
2713
2714 /*
2715 * "scale" the filename
2716 */
2717 len = name_width;
2718 name_len = strlen(name);
2719 if (name_width < name_len) {
2720 char *slash;
2721 prefix = "...";
2722 len -= 3;
2723 name += name_len - len;
2724 slash = strchr(name, '/');
2725 if (slash)
2726 name = slash;
2727 }
2728
2729 if (file->is_binary) {
2730 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2731 strbuf_addf(&out, " %*s", number_width, "Bin");
2732 if (!added && !deleted) {
2733 strbuf_addch(&out, '\n');
2734 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2735 out.buf, out.len, 0);
2736 strbuf_reset(&out);
2737 continue;
2738 }
2739 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2740 del_c, deleted, reset);
2741 strbuf_addstr(&out, " -> ");
2742 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2743 add_c, added, reset);
2744 strbuf_addstr(&out, " bytes\n");
2745 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2746 out.buf, out.len, 0);
2747 strbuf_reset(&out);
2748 continue;
2749 }
2750 else if (file->is_unmerged) {
2751 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2752 strbuf_addstr(&out, " Unmerged\n");
2753 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2754 out.buf, out.len, 0);
2755 strbuf_reset(&out);
2756 continue;
2757 }
2758
2759 /*
2760 * scale the add/delete
2761 */
2762 add = added;
2763 del = deleted;
2764
2765 if (graph_width <= max_change) {
2766 int total = scale_linear(add + del, graph_width, max_change);
2767 if (total < 2 && add && del)
2768 /* width >= 2 due to the sanity check */
2769 total = 2;
2770 if (add < del) {
2771 add = scale_linear(add, graph_width, max_change);
2772 del = total - add;
2773 } else {
2774 del = scale_linear(del, graph_width, max_change);
2775 add = total - del;
2776 }
2777 }
2778 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2779 strbuf_addf(&out, " %*"PRIuMAX"%s",
2780 number_width, added + deleted,
2781 added + deleted ? " " : "");
2782 show_graph(&out, '+', add, add_c, reset);
2783 show_graph(&out, '-', del, del_c, reset);
2784 strbuf_addch(&out, '\n');
2785 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2786 out.buf, out.len, 0);
2787 strbuf_reset(&out);
2788 }
2789
2790 for (i = 0; i < data->nr; i++) {
2791 struct diffstat_file *file = data->files[i];
2792 uintmax_t added = file->added;
2793 uintmax_t deleted = file->deleted;
2794
2795 if (file->is_unmerged ||
2796 (!file->is_interesting && (added + deleted == 0))) {
2797 total_files--;
2798 continue;
2799 }
2800
2801 if (!file->is_binary) {
2802 adds += added;
2803 dels += deleted;
2804 }
2805 if (i < count)
2806 continue;
2807 if (!extra_shown)
2808 emit_diff_symbol(options,
2809 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2810 NULL, 0, 0);
2811 extra_shown = 1;
2812 }
2813
2814 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2815 strbuf_release(&out);
2816}
2817
2818static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2819{
2820 int i, adds = 0, dels = 0, total_files = data->nr;
2821
2822 if (data->nr == 0)
2823 return;
2824
2825 for (i = 0; i < data->nr; i++) {
2826 int added = data->files[i]->added;
2827 int deleted = data->files[i]->deleted;
2828
2829 if (data->files[i]->is_unmerged ||
2830 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2831 total_files--;
2832 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2833 adds += added;
2834 dels += deleted;
2835 }
2836 }
2837 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2838}
2839
2840static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2841{
2842 int i;
2843
2844 if (data->nr == 0)
2845 return;
2846
2847 for (i = 0; i < data->nr; i++) {
2848 struct diffstat_file *file = data->files[i];
2849
2850 fprintf(options->file, "%s", diff_line_prefix(options));
2851
2852 if (file->is_binary)
2853 fprintf(options->file, "-\t-\t");
2854 else
2855 fprintf(options->file,
2856 "%"PRIuMAX"\t%"PRIuMAX"\t",
2857 file->added, file->deleted);
2858 if (options->line_termination) {
2859 fill_print_name(file);
2860 if (!file->is_renamed)
2861 write_name_quoted(file->name, options->file,
2862 options->line_termination);
2863 else {
2864 fputs(file->print_name, options->file);
2865 putc(options->line_termination, options->file);
2866 }
2867 } else {
2868 if (file->is_renamed) {
2869 putc('\0', options->file);
2870 write_name_quoted(file->from_name, options->file, '\0');
2871 }
2872 write_name_quoted(file->name, options->file, '\0');
2873 }
2874 }
2875}
2876
2877struct dirstat_file {
2878 const char *name;
2879 unsigned long changed;
2880};
2881
2882struct dirstat_dir {
2883 struct dirstat_file *files;
2884 int alloc, nr, permille, cumulative;
2885};
2886
2887static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2888 unsigned long changed, const char *base, int baselen)
2889{
2890 unsigned long sum_changes = 0;
2891 unsigned int sources = 0;
2892 const char *line_prefix = diff_line_prefix(opt);
2893
2894 while (dir->nr) {
2895 struct dirstat_file *f = dir->files;
2896 int namelen = strlen(f->name);
2897 unsigned long changes;
2898 char *slash;
2899
2900 if (namelen < baselen)
2901 break;
2902 if (memcmp(f->name, base, baselen))
2903 break;
2904 slash = strchr(f->name + baselen, '/');
2905 if (slash) {
2906 int newbaselen = slash + 1 - f->name;
2907 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2908 sources++;
2909 } else {
2910 changes = f->changed;
2911 dir->files++;
2912 dir->nr--;
2913 sources += 2;
2914 }
2915 sum_changes += changes;
2916 }
2917
2918 /*
2919 * We don't report dirstat's for
2920 * - the top level
2921 * - or cases where everything came from a single directory
2922 * under this directory (sources == 1).
2923 */
2924 if (baselen && sources != 1) {
2925 if (sum_changes) {
2926 int permille = sum_changes * 1000 / changed;
2927 if (permille >= dir->permille) {
2928 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2929 permille / 10, permille % 10, baselen, base);
2930 if (!dir->cumulative)
2931 return 0;
2932 }
2933 }
2934 }
2935 return sum_changes;
2936}
2937
2938static int dirstat_compare(const void *_a, const void *_b)
2939{
2940 const struct dirstat_file *a = _a;
2941 const struct dirstat_file *b = _b;
2942 return strcmp(a->name, b->name);
2943}
2944
2945static void show_dirstat(struct diff_options *options)
2946{
2947 int i;
2948 unsigned long changed;
2949 struct dirstat_dir dir;
2950 struct diff_queue_struct *q = &diff_queued_diff;
2951
2952 dir.files = NULL;
2953 dir.alloc = 0;
2954 dir.nr = 0;
2955 dir.permille = options->dirstat_permille;
2956 dir.cumulative = options->flags.dirstat_cumulative;
2957
2958 changed = 0;
2959 for (i = 0; i < q->nr; i++) {
2960 struct diff_filepair *p = q->queue[i];
2961 const char *name;
2962 unsigned long copied, added, damage;
2963
2964 name = p->two->path ? p->two->path : p->one->path;
2965
2966 if (p->one->oid_valid && p->two->oid_valid &&
2967 oideq(&p->one->oid, &p->two->oid)) {
2968 /*
2969 * The SHA1 has not changed, so pre-/post-content is
2970 * identical. We can therefore skip looking at the
2971 * file contents altogether.
2972 */
2973 damage = 0;
2974 goto found_damage;
2975 }
2976
2977 if (options->flags.dirstat_by_file) {
2978 /*
2979 * In --dirstat-by-file mode, we don't really need to
2980 * look at the actual file contents at all.
2981 * The fact that the SHA1 changed is enough for us to
2982 * add this file to the list of results
2983 * (with each file contributing equal damage).
2984 */
2985 damage = 1;
2986 goto found_damage;
2987 }
2988
2989 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2990 diff_populate_filespec(p->one, 0);
2991 diff_populate_filespec(p->two, 0);
2992 diffcore_count_changes(p->one, p->two, NULL, NULL,
2993 &copied, &added);
2994 diff_free_filespec_data(p->one);
2995 diff_free_filespec_data(p->two);
2996 } else if (DIFF_FILE_VALID(p->one)) {
2997 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2998 copied = added = 0;
2999 diff_free_filespec_data(p->one);
3000 } else if (DIFF_FILE_VALID(p->two)) {
3001 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
3002 copied = 0;
3003 added = p->two->size;
3004 diff_free_filespec_data(p->two);
3005 } else
3006 continue;
3007
3008 /*
3009 * Original minus copied is the removed material,
3010 * added is the new material. They are both damages
3011 * made to the preimage.
3012 * If the resulting damage is zero, we know that
3013 * diffcore_count_changes() considers the two entries to
3014 * be identical, but since the oid changed, we
3015 * know that there must have been _some_ kind of change,
3016 * so we force all entries to have damage > 0.
3017 */
3018 damage = (p->one->size - copied) + added;
3019 if (!damage)
3020 damage = 1;
3021
3022found_damage:
3023 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3024 dir.files[dir.nr].name = name;
3025 dir.files[dir.nr].changed = damage;
3026 changed += damage;
3027 dir.nr++;
3028 }
3029
3030 /* This can happen even with many files, if everything was renames */
3031 if (!changed)
3032 return;
3033
3034 /* Show all directories with more than x% of the changes */
3035 QSORT(dir.files, dir.nr, dirstat_compare);
3036 gather_dirstat(options, &dir, changed, "", 0);
3037}
3038
3039static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3040{
3041 int i;
3042 unsigned long changed;
3043 struct dirstat_dir dir;
3044
3045 if (data->nr == 0)
3046 return;
3047
3048 dir.files = NULL;
3049 dir.alloc = 0;
3050 dir.nr = 0;
3051 dir.permille = options->dirstat_permille;
3052 dir.cumulative = options->flags.dirstat_cumulative;
3053
3054 changed = 0;
3055 for (i = 0; i < data->nr; i++) {
3056 struct diffstat_file *file = data->files[i];
3057 unsigned long damage = file->added + file->deleted;
3058 if (file->is_binary)
3059 /*
3060 * binary files counts bytes, not lines. Must find some
3061 * way to normalize binary bytes vs. textual lines.
3062 * The following heuristic assumes that there are 64
3063 * bytes per "line".
3064 * This is stupid and ugly, but very cheap...
3065 */
3066 damage = DIV_ROUND_UP(damage, 64);
3067 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3068 dir.files[dir.nr].name = file->name;
3069 dir.files[dir.nr].changed = damage;
3070 changed += damage;
3071 dir.nr++;
3072 }
3073
3074 /* This can happen even with many files, if everything was renames */
3075 if (!changed)
3076 return;
3077
3078 /* Show all directories with more than x% of the changes */
3079 QSORT(dir.files, dir.nr, dirstat_compare);
3080 gather_dirstat(options, &dir, changed, "", 0);
3081}
3082
3083static void free_diffstat_info(struct diffstat_t *diffstat)
3084{
3085 int i;
3086 for (i = 0; i < diffstat->nr; i++) {
3087 struct diffstat_file *f = diffstat->files[i];
3088 free(f->print_name);
3089 free(f->name);
3090 free(f->from_name);
3091 free(f);
3092 }
3093 free(diffstat->files);
3094}
3095
3096struct checkdiff_t {
3097 const char *filename;
3098 int lineno;
3099 int conflict_marker_size;
3100 struct diff_options *o;
3101 unsigned ws_rule;
3102 unsigned status;
3103};
3104
3105static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3106{
3107 char firstchar;
3108 int cnt;
3109
3110 if (len < marker_size + 1)
3111 return 0;
3112 firstchar = line[0];
3113 switch (firstchar) {
3114 case '=': case '>': case '<': case '|':
3115 break;
3116 default:
3117 return 0;
3118 }
3119 for (cnt = 1; cnt < marker_size; cnt++)
3120 if (line[cnt] != firstchar)
3121 return 0;
3122 /* line[1] thru line[marker_size-1] are same as firstchar */
3123 if (len < marker_size + 1 || !isspace(line[marker_size]))
3124 return 0;
3125 return 1;
3126}
3127
3128static void checkdiff_consume(void *priv, char *line, unsigned long len)
3129{
3130 struct checkdiff_t *data = priv;
3131 int marker_size = data->conflict_marker_size;
3132 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3133 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3134 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3135 char *err;
3136 const char *line_prefix;
3137
3138 assert(data->o);
3139 line_prefix = diff_line_prefix(data->o);
3140
3141 if (line[0] == '+') {
3142 unsigned bad;
3143 data->lineno++;
3144 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3145 data->status |= 1;
3146 fprintf(data->o->file,
3147 "%s%s:%d: leftover conflict marker\n",
3148 line_prefix, data->filename, data->lineno);
3149 }
3150 bad = ws_check(line + 1, len - 1, data->ws_rule);
3151 if (!bad)
3152 return;
3153 data->status |= bad;
3154 err = whitespace_error_string(bad);
3155 fprintf(data->o->file, "%s%s:%d: %s.\n",
3156 line_prefix, data->filename, data->lineno, err);
3157 free(err);
3158 emit_line(data->o, set, reset, line, 1);
3159 ws_check_emit(line + 1, len - 1, data->ws_rule,
3160 data->o->file, set, reset, ws);
3161 } else if (line[0] == ' ') {
3162 data->lineno++;
3163 } else if (line[0] == '@') {
3164 char *plus = strchr(line, '+');
3165 if (plus)
3166 data->lineno = strtol(plus, NULL, 10) - 1;
3167 else
3168 die("invalid diff");
3169 }
3170}
3171
3172static unsigned char *deflate_it(char *data,
3173 unsigned long size,
3174 unsigned long *result_size)
3175{
3176 int bound;
3177 unsigned char *deflated;
3178 git_zstream stream;
3179
3180 git_deflate_init(&stream, zlib_compression_level);
3181 bound = git_deflate_bound(&stream, size);
3182 deflated = xmalloc(bound);
3183 stream.next_out = deflated;
3184 stream.avail_out = bound;
3185
3186 stream.next_in = (unsigned char *)data;
3187 stream.avail_in = size;
3188 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3189 ; /* nothing */
3190 git_deflate_end(&stream);
3191 *result_size = stream.total_out;
3192 return deflated;
3193}
3194
3195static void emit_binary_diff_body(struct diff_options *o,
3196 mmfile_t *one, mmfile_t *two)
3197{
3198 void *cp;
3199 void *delta;
3200 void *deflated;
3201 void *data;
3202 unsigned long orig_size;
3203 unsigned long delta_size;
3204 unsigned long deflate_size;
3205 unsigned long data_size;
3206
3207 /* We could do deflated delta, or we could do just deflated two,
3208 * whichever is smaller.
3209 */
3210 delta = NULL;
3211 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3212 if (one->size && two->size) {
3213 delta = diff_delta(one->ptr, one->size,
3214 two->ptr, two->size,
3215 &delta_size, deflate_size);
3216 if (delta) {
3217 void *to_free = delta;
3218 orig_size = delta_size;
3219 delta = deflate_it(delta, delta_size, &delta_size);
3220 free(to_free);
3221 }
3222 }
3223
3224 if (delta && delta_size < deflate_size) {
3225 char *s = xstrfmt("%lu", orig_size);
3226 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3227 s, strlen(s), 0);
3228 free(s);
3229 free(deflated);
3230 data = delta;
3231 data_size = delta_size;
3232 } else {
3233 char *s = xstrfmt("%lu", two->size);
3234 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3235 s, strlen(s), 0);
3236 free(s);
3237 free(delta);
3238 data = deflated;
3239 data_size = deflate_size;
3240 }
3241
3242 /* emit data encoded in base85 */
3243 cp = data;
3244 while (data_size) {
3245 int len;
3246 int bytes = (52 < data_size) ? 52 : data_size;
3247 char line[71];
3248 data_size -= bytes;
3249 if (bytes <= 26)
3250 line[0] = bytes + 'A' - 1;
3251 else
3252 line[0] = bytes - 26 + 'a' - 1;
3253 encode_85(line + 1, cp, bytes);
3254 cp = (char *) cp + bytes;
3255
3256 len = strlen(line);
3257 line[len++] = '\n';
3258 line[len] = '\0';
3259
3260 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3261 line, len, 0);
3262 }
3263 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3264 free(data);
3265}
3266
3267static void emit_binary_diff(struct diff_options *o,
3268 mmfile_t *one, mmfile_t *two)
3269{
3270 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3271 emit_binary_diff_body(o, one, two);
3272 emit_binary_diff_body(o, two, one);
3273}
3274
3275int diff_filespec_is_binary(struct diff_filespec *one)
3276{
3277 if (one->is_binary == -1) {
3278 diff_filespec_load_driver(one);
3279 if (one->driver->binary != -1)
3280 one->is_binary = one->driver->binary;
3281 else {
3282 if (!one->data && DIFF_FILE_VALID(one))
3283 diff_populate_filespec(one, CHECK_BINARY);
3284 if (one->is_binary == -1 && one->data)
3285 one->is_binary = buffer_is_binary(one->data,
3286 one->size);
3287 if (one->is_binary == -1)
3288 one->is_binary = 0;
3289 }
3290 }
3291 return one->is_binary;
3292}
3293
3294static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
3295{
3296 diff_filespec_load_driver(one);
3297 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3298}
3299
3300void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3301{
3302 if (!options->a_prefix)
3303 options->a_prefix = a;
3304 if (!options->b_prefix)
3305 options->b_prefix = b;
3306}
3307
3308struct userdiff_driver *get_textconv(struct diff_filespec *one)
3309{
3310 if (!DIFF_FILE_VALID(one))
3311 return NULL;
3312
3313 diff_filespec_load_driver(one);
3314 return userdiff_get_textconv(one->driver);
3315}
3316
3317static void builtin_diff(const char *name_a,
3318 const char *name_b,
3319 struct diff_filespec *one,
3320 struct diff_filespec *two,
3321 const char *xfrm_msg,
3322 int must_show_header,
3323 struct diff_options *o,
3324 int complete_rewrite)
3325{
3326 mmfile_t mf1, mf2;
3327 const char *lbl[2];
3328 char *a_one, *b_two;
3329 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3330 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3331 const char *a_prefix, *b_prefix;
3332 struct userdiff_driver *textconv_one = NULL;
3333 struct userdiff_driver *textconv_two = NULL;
3334 struct strbuf header = STRBUF_INIT;
3335 const char *line_prefix = diff_line_prefix(o);
3336
3337 diff_set_mnemonic_prefix(o, "a/", "b/");
3338 if (o->flags.reverse_diff) {
3339 a_prefix = o->b_prefix;
3340 b_prefix = o->a_prefix;
3341 } else {
3342 a_prefix = o->a_prefix;
3343 b_prefix = o->b_prefix;
3344 }
3345
3346 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3347 (!one->mode || S_ISGITLINK(one->mode)) &&
3348 (!two->mode || S_ISGITLINK(two->mode))) {
3349 show_submodule_summary(o, one->path ? one->path : two->path,
3350 &one->oid, &two->oid,
3351 two->dirty_submodule);
3352 return;
3353 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3354 (!one->mode || S_ISGITLINK(one->mode)) &&
3355 (!two->mode || S_ISGITLINK(two->mode))) {
3356 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3357 &one->oid, &two->oid,
3358 two->dirty_submodule);
3359 return;
3360 }
3361
3362 if (o->flags.allow_textconv) {
3363 textconv_one = get_textconv(one);
3364 textconv_two = get_textconv(two);
3365 }
3366
3367 /* Never use a non-valid filename anywhere if at all possible */
3368 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3369 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3370
3371 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3372 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3373 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3374 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3375 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3376 if (lbl[0][0] == '/') {
3377 /* /dev/null */
3378 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3379 if (xfrm_msg)
3380 strbuf_addstr(&header, xfrm_msg);
3381 must_show_header = 1;
3382 }
3383 else if (lbl[1][0] == '/') {
3384 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3385 if (xfrm_msg)
3386 strbuf_addstr(&header, xfrm_msg);
3387 must_show_header = 1;
3388 }
3389 else {
3390 if (one->mode != two->mode) {
3391 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3392 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3393 must_show_header = 1;
3394 }
3395 if (xfrm_msg)
3396 strbuf_addstr(&header, xfrm_msg);
3397
3398 /*
3399 * we do not run diff between different kind
3400 * of objects.
3401 */
3402 if ((one->mode ^ two->mode) & S_IFMT)
3403 goto free_ab_and_return;
3404 if (complete_rewrite &&
3405 (textconv_one || !diff_filespec_is_binary(one)) &&
3406 (textconv_two || !diff_filespec_is_binary(two))) {
3407 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3408 header.buf, header.len, 0);
3409 strbuf_reset(&header);
3410 emit_rewrite_diff(name_a, name_b, one, two,
3411 textconv_one, textconv_two, o);
3412 o->found_changes = 1;
3413 goto free_ab_and_return;
3414 }
3415 }
3416
3417 if (o->irreversible_delete && lbl[1][0] == '/') {
3418 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3419 header.len, 0);
3420 strbuf_reset(&header);
3421 goto free_ab_and_return;
3422 } else if (!o->flags.text &&
3423 ( (!textconv_one && diff_filespec_is_binary(one)) ||
3424 (!textconv_two && diff_filespec_is_binary(two)) )) {
3425 struct strbuf sb = STRBUF_INIT;
3426 if (!one->data && !two->data &&
3427 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3428 !o->flags.binary) {
3429 if (oideq(&one->oid, &two->oid)) {
3430 if (must_show_header)
3431 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3432 header.buf, header.len,
3433 0);
3434 goto free_ab_and_return;
3435 }
3436 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3437 header.buf, header.len, 0);
3438 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3439 diff_line_prefix(o), lbl[0], lbl[1]);
3440 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3441 sb.buf, sb.len, 0);
3442 strbuf_release(&sb);
3443 goto free_ab_and_return;
3444 }
3445 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3446 die("unable to read files to diff");
3447 /* Quite common confusing case */
3448 if (mf1.size == mf2.size &&
3449 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3450 if (must_show_header)
3451 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3452 header.buf, header.len, 0);
3453 goto free_ab_and_return;
3454 }
3455 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3456 strbuf_reset(&header);
3457 if (o->flags.binary)
3458 emit_binary_diff(o, &mf1, &mf2);
3459 else {
3460 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3461 diff_line_prefix(o), lbl[0], lbl[1]);
3462 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3463 sb.buf, sb.len, 0);
3464 strbuf_release(&sb);
3465 }
3466 o->found_changes = 1;
3467 } else {
3468 /* Crazy xdl interfaces.. */
3469 const char *diffopts = getenv("GIT_DIFF_OPTS");
3470 const char *v;
3471 xpparam_t xpp;
3472 xdemitconf_t xecfg;
3473 struct emit_callback ecbdata;
3474 const struct userdiff_funcname *pe;
3475
3476 if (must_show_header) {
3477 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3478 header.buf, header.len, 0);
3479 strbuf_reset(&header);
3480 }
3481
3482 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
3483 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
3484
3485 pe = diff_funcname_pattern(one);
3486 if (!pe)
3487 pe = diff_funcname_pattern(two);
3488
3489 memset(&xpp, 0, sizeof(xpp));
3490 memset(&xecfg, 0, sizeof(xecfg));
3491 memset(&ecbdata, 0, sizeof(ecbdata));
3492 if (o->flags.suppress_diff_headers)
3493 lbl[0] = NULL;
3494 ecbdata.label_path = lbl;
3495 ecbdata.color_diff = want_color(o->use_color);
3496 ecbdata.ws_rule = whitespace_rule(name_b);
3497 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3498 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3499 ecbdata.opt = o;
3500 if (header.len && !o->flags.suppress_diff_headers)
3501 ecbdata.header = &header;
3502 xpp.flags = o->xdl_opts;
3503 xpp.anchors = o->anchors;
3504 xpp.anchors_nr = o->anchors_nr;
3505 xecfg.ctxlen = o->context;
3506 xecfg.interhunkctxlen = o->interhunkcontext;
3507 xecfg.flags = XDL_EMIT_FUNCNAMES;
3508 if (o->flags.funccontext)
3509 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3510 if (pe)
3511 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3512 if (!diffopts)
3513 ;
3514 else if (skip_prefix(diffopts, "--unified=", &v))
3515 xecfg.ctxlen = strtoul(v, NULL, 10);
3516 else if (skip_prefix(diffopts, "-u", &v))
3517 xecfg.ctxlen = strtoul(v, NULL, 10);
3518 if (o->word_diff)
3519 init_diff_words_data(&ecbdata, o, one, two);
3520 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
3521 &xpp, &xecfg))
3522 die("unable to generate diff for %s", one->path);
3523 if (o->word_diff)
3524 free_diff_words_data(&ecbdata);
3525 if (textconv_one)
3526 free(mf1.ptr);
3527 if (textconv_two)
3528 free(mf2.ptr);
3529 xdiff_clear_find_func(&xecfg);
3530 }
3531
3532 free_ab_and_return:
3533 strbuf_release(&header);
3534 diff_free_filespec_data(one);
3535 diff_free_filespec_data(two);
3536 free(a_one);
3537 free(b_two);
3538 return;
3539}
3540
3541static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3542{
3543 if (!is_renamed) {
3544 if (p->status == DIFF_STATUS_ADDED) {
3545 if (S_ISLNK(p->two->mode))
3546 return "new +l";
3547 else if ((p->two->mode & 0777) == 0755)
3548 return "new +x";
3549 else
3550 return "new";
3551 } else if (p->status == DIFF_STATUS_DELETED)
3552 return "gone";
3553 }
3554 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3555 return "mode -l";
3556 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3557 return "mode +l";
3558 else if ((p->one->mode & 0777) == 0644 &&
3559 (p->two->mode & 0777) == 0755)
3560 return "mode +x";
3561 else if ((p->one->mode & 0777) == 0755 &&
3562 (p->two->mode & 0777) == 0644)
3563 return "mode -x";
3564 return NULL;
3565}
3566
3567static void builtin_diffstat(const char *name_a, const char *name_b,
3568 struct diff_filespec *one,
3569 struct diff_filespec *two,
3570 struct diffstat_t *diffstat,
3571 struct diff_options *o,
3572 struct diff_filepair *p)
3573{
3574 mmfile_t mf1, mf2;
3575 struct diffstat_file *data;
3576 int same_contents;
3577 int complete_rewrite = 0;
3578
3579 if (!DIFF_PAIR_UNMERGED(p)) {
3580 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3581 complete_rewrite = 1;
3582 }
3583
3584 data = diffstat_add(diffstat, name_a, name_b);
3585 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3586 if (o->flags.stat_with_summary)
3587 data->comments = get_compact_summary(p, data->is_renamed);
3588
3589 if (!one || !two) {
3590 data->is_unmerged = 1;
3591 return;
3592 }
3593
3594 same_contents = oideq(&one->oid, &two->oid);
3595
3596 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
3597 data->is_binary = 1;
3598 if (same_contents) {
3599 data->added = 0;
3600 data->deleted = 0;
3601 } else {
3602 data->added = diff_filespec_size(two);
3603 data->deleted = diff_filespec_size(one);
3604 }
3605 }
3606
3607 else if (complete_rewrite) {
3608 diff_populate_filespec(one, 0);
3609 diff_populate_filespec(two, 0);
3610 data->deleted = count_lines(one->data, one->size);
3611 data->added = count_lines(two->data, two->size);
3612 }
3613
3614 else if (!same_contents) {
3615 /* Crazy xdl interfaces.. */
3616 xpparam_t xpp;
3617 xdemitconf_t xecfg;
3618
3619 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3620 die("unable to read files to diff");
3621
3622 memset(&xpp, 0, sizeof(xpp));
3623 memset(&xecfg, 0, sizeof(xecfg));
3624 xpp.flags = o->xdl_opts;
3625 xpp.anchors = o->anchors;
3626 xpp.anchors_nr = o->anchors_nr;
3627 xecfg.ctxlen = o->context;
3628 xecfg.interhunkctxlen = o->interhunkcontext;
3629 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
3630 &xpp, &xecfg))
3631 die("unable to generate diffstat for %s", one->path);
3632 }
3633
3634 diff_free_filespec_data(one);
3635 diff_free_filespec_data(two);
3636}
3637
3638static void builtin_checkdiff(const char *name_a, const char *name_b,
3639 const char *attr_path,
3640 struct diff_filespec *one,
3641 struct diff_filespec *two,
3642 struct diff_options *o)
3643{
3644 mmfile_t mf1, mf2;
3645 struct checkdiff_t data;
3646
3647 if (!two)
3648 return;
3649
3650 memset(&data, 0, sizeof(data));
3651 data.filename = name_b ? name_b : name_a;
3652 data.lineno = 0;
3653 data.o = o;
3654 data.ws_rule = whitespace_rule(attr_path);
3655 data.conflict_marker_size = ll_merge_marker_size(attr_path);
3656
3657 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3658 die("unable to read files to diff");
3659
3660 /*
3661 * All the other codepaths check both sides, but not checking
3662 * the "old" side here is deliberate. We are checking the newly
3663 * introduced changes, and as long as the "new" side is text, we
3664 * can and should check what it introduces.
3665 */
3666 if (diff_filespec_is_binary(two))
3667 goto free_and_return;
3668 else {
3669 /* Crazy xdl interfaces.. */
3670 xpparam_t xpp;
3671 xdemitconf_t xecfg;
3672
3673 memset(&xpp, 0, sizeof(xpp));
3674 memset(&xecfg, 0, sizeof(xecfg));
3675 xecfg.ctxlen = 1; /* at least one context line */
3676 xpp.flags = 0;
3677 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
3678 &xpp, &xecfg))
3679 die("unable to generate checkdiff for %s", one->path);
3680
3681 if (data.ws_rule & WS_BLANK_AT_EOF) {
3682 struct emit_callback ecbdata;
3683 int blank_at_eof;
3684
3685 ecbdata.ws_rule = data.ws_rule;
3686 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3687 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3688
3689 if (blank_at_eof) {
3690 static char *err;
3691 if (!err)
3692 err = whitespace_error_string(WS_BLANK_AT_EOF);
3693 fprintf(o->file, "%s:%d: %s.\n",
3694 data.filename, blank_at_eof, err);
3695 data.status = 1; /* report errors */
3696 }
3697 }
3698 }
3699 free_and_return:
3700 diff_free_filespec_data(one);
3701 diff_free_filespec_data(two);
3702 if (data.status)
3703 o->flags.check_failed = 1;
3704}
3705
3706struct diff_filespec *alloc_filespec(const char *path)
3707{
3708 struct diff_filespec *spec;
3709
3710 FLEXPTR_ALLOC_STR(spec, path, path);
3711 spec->count = 1;
3712 spec->is_binary = -1;
3713 return spec;
3714}
3715
3716void free_filespec(struct diff_filespec *spec)
3717{
3718 if (!--spec->count) {
3719 diff_free_filespec_data(spec);
3720 free(spec);
3721 }
3722}
3723
3724void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3725 int oid_valid, unsigned short mode)
3726{
3727 if (mode) {
3728 spec->mode = canon_mode(mode);
3729 oidcpy(&spec->oid, oid);
3730 spec->oid_valid = oid_valid;
3731 }
3732}
3733
3734/*
3735 * Given a name and sha1 pair, if the index tells us the file in
3736 * the work tree has that object contents, return true, so that
3737 * prepare_temp_file() does not have to inflate and extract.
3738 */
3739static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
3740{
3741 const struct cache_entry *ce;
3742 struct stat st;
3743 int pos, len;
3744
3745 /*
3746 * We do not read the cache ourselves here, because the
3747 * benchmark with my previous version that always reads cache
3748 * shows that it makes things worse for diff-tree comparing
3749 * two linux-2.6 kernel trees in an already checked out work
3750 * tree. This is because most diff-tree comparisons deal with
3751 * only a small number of files, while reading the cache is
3752 * expensive for a large project, and its cost outweighs the
3753 * savings we get by not inflating the object to a temporary
3754 * file. Practically, this code only helps when we are used
3755 * by diff-cache --cached, which does read the cache before
3756 * calling us.
3757 */
3758 if (!active_cache)
3759 return 0;
3760
3761 /* We want to avoid the working directory if our caller
3762 * doesn't need the data in a normal file, this system
3763 * is rather slow with its stat/open/mmap/close syscalls,
3764 * and the object is contained in a pack file. The pack
3765 * is probably already open and will be faster to obtain
3766 * the data through than the working directory. Loose
3767 * objects however would tend to be slower as they need
3768 * to be individually opened and inflated.
3769 */
3770 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3771 return 0;
3772
3773 /*
3774 * Similarly, if we'd have to convert the file contents anyway, that
3775 * makes the optimization not worthwhile.
3776 */
3777 if (!want_file && would_convert_to_git(&the_index, name))
3778 return 0;
3779
3780 len = strlen(name);
3781 pos = cache_name_pos(name, len);
3782 if (pos < 0)
3783 return 0;
3784 ce = active_cache[pos];
3785
3786 /*
3787 * This is not the sha1 we are looking for, or
3788 * unreusable because it is not a regular file.
3789 */
3790 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3791 return 0;
3792
3793 /*
3794 * If ce is marked as "assume unchanged", there is no
3795 * guarantee that work tree matches what we are looking for.
3796 */
3797 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3798 return 0;
3799
3800 /*
3801 * If ce matches the file in the work tree, we can reuse it.
3802 */
3803 if (ce_uptodate(ce) ||
3804 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3805 return 1;
3806
3807 return 0;
3808}
3809
3810static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3811{
3812 struct strbuf buf = STRBUF_INIT;
3813 char *dirty = "";
3814
3815 /* Are we looking at the work tree? */
3816 if (s->dirty_submodule)
3817 dirty = "-dirty";
3818
3819 strbuf_addf(&buf, "Subproject commit %s%s\n",
3820 oid_to_hex(&s->oid), dirty);
3821 s->size = buf.len;
3822 if (size_only) {
3823 s->data = NULL;
3824 strbuf_release(&buf);
3825 } else {
3826 s->data = strbuf_detach(&buf, NULL);
3827 s->should_free = 1;
3828 }
3829 return 0;
3830}
3831
3832/*
3833 * While doing rename detection and pickaxe operation, we may need to
3834 * grab the data for the blob (or file) for our own in-core comparison.
3835 * diff_filespec has data and size fields for this purpose.
3836 */
3837int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
3838{
3839 int size_only = flags & CHECK_SIZE_ONLY;
3840 int err = 0;
3841 int conv_flags = global_conv_flags_eol;
3842 /*
3843 * demote FAIL to WARN to allow inspecting the situation
3844 * instead of refusing.
3845 */
3846 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3847 conv_flags = CONV_EOL_RNDTRP_WARN;
3848
3849 if (!DIFF_FILE_VALID(s))
3850 die("internal error: asking to populate invalid file.");
3851 if (S_ISDIR(s->mode))
3852 return -1;
3853
3854 if (s->data)
3855 return 0;
3856
3857 if (size_only && 0 < s->size)
3858 return 0;
3859
3860 if (S_ISGITLINK(s->mode))
3861 return diff_populate_gitlink(s, size_only);
3862
3863 if (!s->oid_valid ||
3864 reuse_worktree_file(s->path, &s->oid, 0)) {
3865 struct strbuf buf = STRBUF_INIT;
3866 struct stat st;
3867 int fd;
3868
3869 if (lstat(s->path, &st) < 0) {
3870 err_empty:
3871 err = -1;
3872 empty:
3873 s->data = (char *)"";
3874 s->size = 0;
3875 return err;
3876 }
3877 s->size = xsize_t(st.st_size);
3878 if (!s->size)
3879 goto empty;
3880 if (S_ISLNK(st.st_mode)) {
3881 struct strbuf sb = STRBUF_INIT;
3882
3883 if (strbuf_readlink(&sb, s->path, s->size))
3884 goto err_empty;
3885 s->size = sb.len;
3886 s->data = strbuf_detach(&sb, NULL);
3887 s->should_free = 1;
3888 return 0;
3889 }
3890
3891 /*
3892 * Even if the caller would be happy with getting
3893 * only the size, we cannot return early at this
3894 * point if the path requires us to run the content
3895 * conversion.
3896 */
3897 if (size_only && !would_convert_to_git(&the_index, s->path))
3898 return 0;
3899
3900 /*
3901 * Note: this check uses xsize_t(st.st_size) that may
3902 * not be the true size of the blob after it goes
3903 * through convert_to_git(). This may not strictly be
3904 * correct, but the whole point of big_file_threshold
3905 * and is_binary check being that we want to avoid
3906 * opening the file and inspecting the contents, this
3907 * is probably fine.
3908 */
3909 if ((flags & CHECK_BINARY) &&
3910 s->size > big_file_threshold && s->is_binary == -1) {
3911 s->is_binary = 1;
3912 return 0;
3913 }
3914 fd = open(s->path, O_RDONLY);
3915 if (fd < 0)
3916 goto err_empty;
3917 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3918 close(fd);
3919 s->should_munmap = 1;
3920
3921 /*
3922 * Convert from working tree format to canonical git format
3923 */
3924 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, conv_flags)) {
3925 size_t size = 0;
3926 munmap(s->data, s->size);
3927 s->should_munmap = 0;
3928 s->data = strbuf_detach(&buf, &size);
3929 s->size = size;
3930 s->should_free = 1;
3931 }
3932 }
3933 else {
3934 enum object_type type;
3935 if (size_only || (flags & CHECK_BINARY)) {
3936 type = oid_object_info(the_repository, &s->oid,
3937 &s->size);
3938 if (type < 0)
3939 die("unable to read %s",
3940 oid_to_hex(&s->oid));
3941 if (size_only)
3942 return 0;
3943 if (s->size > big_file_threshold && s->is_binary == -1) {
3944 s->is_binary = 1;
3945 return 0;
3946 }
3947 }
3948 s->data = read_object_file(&s->oid, &type, &s->size);
3949 if (!s->data)
3950 die("unable to read %s", oid_to_hex(&s->oid));
3951 s->should_free = 1;
3952 }
3953 return 0;
3954}
3955
3956void diff_free_filespec_blob(struct diff_filespec *s)
3957{
3958 if (s->should_free)
3959 free(s->data);
3960 else if (s->should_munmap)
3961 munmap(s->data, s->size);
3962
3963 if (s->should_free || s->should_munmap) {
3964 s->should_free = s->should_munmap = 0;
3965 s->data = NULL;
3966 }
3967}
3968
3969void diff_free_filespec_data(struct diff_filespec *s)
3970{
3971 diff_free_filespec_blob(s);
3972 FREE_AND_NULL(s->cnt_data);
3973}
3974
3975static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
3976 void *blob,
3977 unsigned long size,
3978 const struct object_id *oid,
3979 int mode)
3980{
3981 struct strbuf buf = STRBUF_INIT;
3982 struct strbuf tempfile = STRBUF_INIT;
3983 char *path_dup = xstrdup(path);
3984 const char *base = basename(path_dup);
3985
3986 /* Generate "XXXXXX_basename.ext" */
3987 strbuf_addstr(&tempfile, "XXXXXX_");
3988 strbuf_addstr(&tempfile, base);
3989
3990 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
3991 if (!temp->tempfile)
3992 die_errno("unable to create temp-file");
3993 if (convert_to_working_tree(&the_index, path,
3994 (const char *)blob, (size_t)size, &buf)) {
3995 blob = buf.buf;
3996 size = buf.len;
3997 }
3998 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
3999 close_tempfile_gently(temp->tempfile))
4000 die_errno("unable to write temp-file");
4001 temp->name = get_tempfile_path(temp->tempfile);
4002 oid_to_hex_r(temp->hex, oid);
4003 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4004 strbuf_release(&buf);
4005 strbuf_release(&tempfile);
4006 free(path_dup);
4007}
4008
4009static struct diff_tempfile *prepare_temp_file(const char *name,
4010 struct diff_filespec *one)
4011{
4012 struct diff_tempfile *temp = claim_diff_tempfile();
4013
4014 if (!DIFF_FILE_VALID(one)) {
4015 not_a_valid_file:
4016 /* A '-' entry produces this for file-2, and
4017 * a '+' entry produces this for file-1.
4018 */
4019 temp->name = "/dev/null";
4020 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4021 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4022 return temp;
4023 }
4024
4025 if (!S_ISGITLINK(one->mode) &&
4026 (!one->oid_valid ||
4027 reuse_worktree_file(name, &one->oid, 1))) {
4028 struct stat st;
4029 if (lstat(name, &st) < 0) {
4030 if (errno == ENOENT)
4031 goto not_a_valid_file;
4032 die_errno("stat(%s)", name);
4033 }
4034 if (S_ISLNK(st.st_mode)) {
4035 struct strbuf sb = STRBUF_INIT;
4036 if (strbuf_readlink(&sb, name, st.st_size) < 0)
4037 die_errno("readlink(%s)", name);
4038 prep_temp_blob(name, temp, sb.buf, sb.len,
4039 (one->oid_valid ?
4040 &one->oid : &null_oid),
4041 (one->oid_valid ?
4042 one->mode : S_IFLNK));
4043 strbuf_release(&sb);
4044 }
4045 else {
4046 /* we can borrow from the file in the work tree */
4047 temp->name = name;
4048 if (!one->oid_valid)
4049 oid_to_hex_r(temp->hex, &null_oid);
4050 else
4051 oid_to_hex_r(temp->hex, &one->oid);
4052 /* Even though we may sometimes borrow the
4053 * contents from the work tree, we always want
4054 * one->mode. mode is trustworthy even when
4055 * !(one->oid_valid), as long as
4056 * DIFF_FILE_VALID(one).
4057 */
4058 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4059 }
4060 return temp;
4061 }
4062 else {
4063 if (diff_populate_filespec(one, 0))
4064 die("cannot read data blob for %s", one->path);
4065 prep_temp_blob(name, temp, one->data, one->size,
4066 &one->oid, one->mode);
4067 }
4068 return temp;
4069}
4070
4071static void add_external_diff_name(struct argv_array *argv,
4072 const char *name,
4073 struct diff_filespec *df)
4074{
4075 struct diff_tempfile *temp = prepare_temp_file(name, df);
4076 argv_array_push(argv, temp->name);
4077 argv_array_push(argv, temp->hex);
4078 argv_array_push(argv, temp->mode);
4079}
4080
4081/* An external diff command takes:
4082 *
4083 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4084 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4085 *
4086 */
4087static void run_external_diff(const char *pgm,
4088 const char *name,
4089 const char *other,
4090 struct diff_filespec *one,
4091 struct diff_filespec *two,
4092 const char *xfrm_msg,
4093 int complete_rewrite,
4094 struct diff_options *o)
4095{
4096 struct argv_array argv = ARGV_ARRAY_INIT;
4097 struct argv_array env = ARGV_ARRAY_INIT;
4098 struct diff_queue_struct *q = &diff_queued_diff;
4099
4100 argv_array_push(&argv, pgm);
4101 argv_array_push(&argv, name);
4102
4103 if (one && two) {
4104 add_external_diff_name(&argv, name, one);
4105 if (!other)
4106 add_external_diff_name(&argv, name, two);
4107 else {
4108 add_external_diff_name(&argv, other, two);
4109 argv_array_push(&argv, other);
4110 argv_array_push(&argv, xfrm_msg);
4111 }
4112 }
4113
4114 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4115 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4116
4117 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
4118 die(_("external diff died, stopping at %s"), name);
4119
4120 remove_tempfile();
4121 argv_array_clear(&argv);
4122 argv_array_clear(&env);
4123}
4124
4125static int similarity_index(struct diff_filepair *p)
4126{
4127 return p->score * 100 / MAX_SCORE;
4128}
4129
4130static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4131{
4132 if (startup_info->have_repository)
4133 return find_unique_abbrev(oid, abbrev);
4134 else {
4135 char *hex = oid_to_hex(oid);
4136 if (abbrev < 0)
4137 abbrev = FALLBACK_DEFAULT_ABBREV;
4138 if (abbrev > the_hash_algo->hexsz)
4139 BUG("oid abbreviation out of range: %d", abbrev);
4140 if (abbrev)
4141 hex[abbrev] = '\0';
4142 return hex;
4143 }
4144}
4145
4146static void fill_metainfo(struct strbuf *msg,
4147 const char *name,
4148 const char *other,
4149 struct diff_filespec *one,
4150 struct diff_filespec *two,
4151 struct diff_options *o,
4152 struct diff_filepair *p,
4153 int *must_show_header,
4154 int use_color)
4155{
4156 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4157 const char *reset = diff_get_color(use_color, DIFF_RESET);
4158 const char *line_prefix = diff_line_prefix(o);
4159
4160 *must_show_header = 1;
4161 strbuf_init(msg, PATH_MAX * 2 + 300);
4162 switch (p->status) {
4163 case DIFF_STATUS_COPIED:
4164 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4165 line_prefix, set, similarity_index(p));
4166 strbuf_addf(msg, "%s\n%s%scopy from ",
4167 reset, line_prefix, set);
4168 quote_c_style(name, msg, NULL, 0);
4169 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4170 quote_c_style(other, msg, NULL, 0);
4171 strbuf_addf(msg, "%s\n", reset);
4172 break;
4173 case DIFF_STATUS_RENAMED:
4174 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4175 line_prefix, set, similarity_index(p));
4176 strbuf_addf(msg, "%s\n%s%srename from ",
4177 reset, line_prefix, set);
4178 quote_c_style(name, msg, NULL, 0);
4179 strbuf_addf(msg, "%s\n%s%srename to ",
4180 reset, line_prefix, set);
4181 quote_c_style(other, msg, NULL, 0);
4182 strbuf_addf(msg, "%s\n", reset);
4183 break;
4184 case DIFF_STATUS_MODIFIED:
4185 if (p->score) {
4186 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4187 line_prefix,
4188 set, similarity_index(p), reset);
4189 break;
4190 }
4191 /* fallthru */
4192 default:
4193 *must_show_header = 0;
4194 }
4195 if (one && two && !oideq(&one->oid, &two->oid)) {
4196 const unsigned hexsz = the_hash_algo->hexsz;
4197 int abbrev = o->flags.full_index ? hexsz : DEFAULT_ABBREV;
4198
4199 if (o->flags.binary) {
4200 mmfile_t mf;
4201 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
4202 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
4203 abbrev = hexsz;
4204 }
4205 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4206 diff_abbrev_oid(&one->oid, abbrev),
4207 diff_abbrev_oid(&two->oid, abbrev));
4208 if (one->mode == two->mode)
4209 strbuf_addf(msg, " %06o", one->mode);
4210 strbuf_addf(msg, "%s\n", reset);
4211 }
4212}
4213
4214static void run_diff_cmd(const char *pgm,
4215 const char *name,
4216 const char *other,
4217 const char *attr_path,
4218 struct diff_filespec *one,
4219 struct diff_filespec *two,
4220 struct strbuf *msg,
4221 struct diff_options *o,
4222 struct diff_filepair *p)
4223{
4224 const char *xfrm_msg = NULL;
4225 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4226 int must_show_header = 0;
4227
4228
4229 if (o->flags.allow_external) {
4230 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
4231 if (drv && drv->external)
4232 pgm = drv->external;
4233 }
4234
4235 if (msg) {
4236 /*
4237 * don't use colors when the header is intended for an
4238 * external diff driver
4239 */
4240 fill_metainfo(msg, name, other, one, two, o, p,
4241 &must_show_header,
4242 want_color(o->use_color) && !pgm);
4243 xfrm_msg = msg->len ? msg->buf : NULL;
4244 }
4245
4246 if (pgm) {
4247 run_external_diff(pgm, name, other, one, two, xfrm_msg,
4248 complete_rewrite, o);
4249 return;
4250 }
4251 if (one && two)
4252 builtin_diff(name, other ? other : name,
4253 one, two, xfrm_msg, must_show_header,
4254 o, complete_rewrite);
4255 else
4256 fprintf(o->file, "* Unmerged path %s\n", name);
4257}
4258
4259static void diff_fill_oid_info(struct diff_filespec *one)
4260{
4261 if (DIFF_FILE_VALID(one)) {
4262 if (!one->oid_valid) {
4263 struct stat st;
4264 if (one->is_stdin) {
4265 oidclr(&one->oid);
4266 return;
4267 }
4268 if (lstat(one->path, &st) < 0)
4269 die_errno("stat '%s'", one->path);
4270 if (index_path(&one->oid, one->path, &st, 0))
4271 die("cannot hash %s", one->path);
4272 }
4273 }
4274 else
4275 oidclr(&one->oid);
4276}
4277
4278static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4279{
4280 /* Strip the prefix but do not molest /dev/null and absolute paths */
4281 if (*namep && **namep != '/') {
4282 *namep += prefix_length;
4283 if (**namep == '/')
4284 ++*namep;
4285 }
4286 if (*otherp && **otherp != '/') {
4287 *otherp += prefix_length;
4288 if (**otherp == '/')
4289 ++*otherp;
4290 }
4291}
4292
4293static void run_diff(struct diff_filepair *p, struct diff_options *o)
4294{
4295 const char *pgm = external_diff();
4296 struct strbuf msg;
4297 struct diff_filespec *one = p->one;
4298 struct diff_filespec *two = p->two;
4299 const char *name;
4300 const char *other;
4301 const char *attr_path;
4302
4303 name = one->path;
4304 other = (strcmp(name, two->path) ? two->path : NULL);
4305 attr_path = name;
4306 if (o->prefix_length)
4307 strip_prefix(o->prefix_length, &name, &other);
4308
4309 if (!o->flags.allow_external)
4310 pgm = NULL;
4311
4312 if (DIFF_PAIR_UNMERGED(p)) {
4313 run_diff_cmd(pgm, name, NULL, attr_path,
4314 NULL, NULL, NULL, o, p);
4315 return;
4316 }
4317
4318 diff_fill_oid_info(one);
4319 diff_fill_oid_info(two);
4320
4321 if (!pgm &&
4322 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4323 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4324 /*
4325 * a filepair that changes between file and symlink
4326 * needs to be split into deletion and creation.
4327 */
4328 struct diff_filespec *null = alloc_filespec(two->path);
4329 run_diff_cmd(NULL, name, other, attr_path,
4330 one, null, &msg, o, p);
4331 free(null);
4332 strbuf_release(&msg);
4333
4334 null = alloc_filespec(one->path);
4335 run_diff_cmd(NULL, name, other, attr_path,
4336 null, two, &msg, o, p);
4337 free(null);
4338 }
4339 else
4340 run_diff_cmd(pgm, name, other, attr_path,
4341 one, two, &msg, o, p);
4342
4343 strbuf_release(&msg);
4344}
4345
4346static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4347 struct diffstat_t *diffstat)
4348{
4349 const char *name;
4350 const char *other;
4351
4352 if (DIFF_PAIR_UNMERGED(p)) {
4353 /* unmerged */
4354 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
4355 return;
4356 }
4357
4358 name = p->one->path;
4359 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4360
4361 if (o->prefix_length)
4362 strip_prefix(o->prefix_length, &name, &other);
4363
4364 diff_fill_oid_info(p->one);
4365 diff_fill_oid_info(p->two);
4366
4367 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
4368}
4369
4370static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4371{
4372 const char *name;
4373 const char *other;
4374 const char *attr_path;
4375
4376 if (DIFF_PAIR_UNMERGED(p)) {
4377 /* unmerged */
4378 return;
4379 }
4380
4381 name = p->one->path;
4382 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4383 attr_path = other ? other : name;
4384
4385 if (o->prefix_length)
4386 strip_prefix(o->prefix_length, &name, &other);
4387
4388 diff_fill_oid_info(p->one);
4389 diff_fill_oid_info(p->two);
4390
4391 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4392}
4393
4394void diff_setup(struct diff_options *options)
4395{
4396 memcpy(options, &default_diff_options, sizeof(*options));
4397
4398 options->file = stdout;
4399
4400 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4401 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4402 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4403 options->abbrev = DEFAULT_ABBREV;
4404 options->line_termination = '\n';
4405 options->break_opt = -1;
4406 options->rename_limit = -1;
4407 options->dirstat_permille = diff_dirstat_permille_default;
4408 options->context = diff_context_default;
4409 options->interhunkcontext = diff_interhunk_context_default;
4410 options->ws_error_highlight = ws_error_highlight_default;
4411 options->flags.rename_empty = 1;
4412 options->objfind = NULL;
4413
4414 /* pathchange left =NULL by default */
4415 options->change = diff_change;
4416 options->add_remove = diff_addremove;
4417 options->use_color = diff_use_color_default;
4418 options->detect_rename = diff_detect_rename_default;
4419 options->xdl_opts |= diff_algorithm;
4420 if (diff_indent_heuristic)
4421 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4422
4423 options->orderfile = diff_order_file_cfg;
4424
4425 if (diff_no_prefix) {
4426 options->a_prefix = options->b_prefix = "";
4427 } else if (!diff_mnemonic_prefix) {
4428 options->a_prefix = "a/";
4429 options->b_prefix = "b/";
4430 }
4431
4432 options->color_moved = diff_color_moved_default;
4433 options->color_moved_ws_handling = diff_color_moved_ws_default;
4434}
4435
4436void diff_setup_done(struct diff_options *options)
4437{
4438 unsigned check_mask = DIFF_FORMAT_NAME |
4439 DIFF_FORMAT_NAME_STATUS |
4440 DIFF_FORMAT_CHECKDIFF |
4441 DIFF_FORMAT_NO_OUTPUT;
4442 /*
4443 * This must be signed because we're comparing against a potentially
4444 * negative value.
4445 */
4446 const int hexsz = the_hash_algo->hexsz;
4447
4448 if (options->set_default)
4449 options->set_default(options);
4450
4451 if (HAS_MULTI_BITS(options->output_format & check_mask))
4452 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4453
4454 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4455 die(_("-G, -S and --find-object are mutually exclusive"));
4456
4457 /*
4458 * Most of the time we can say "there are changes"
4459 * only by checking if there are changed paths, but
4460 * --ignore-whitespace* options force us to look
4461 * inside contents.
4462 */
4463
4464 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
4465 options->flags.diff_from_contents = 1;
4466 else
4467 options->flags.diff_from_contents = 0;
4468
4469 if (options->flags.find_copies_harder)
4470 options->detect_rename = DIFF_DETECT_COPY;
4471
4472 if (!options->flags.relative_name)
4473 options->prefix = NULL;
4474 if (options->prefix)
4475 options->prefix_length = strlen(options->prefix);
4476 else
4477 options->prefix_length = 0;
4478
4479 if (options->output_format & (DIFF_FORMAT_NAME |
4480 DIFF_FORMAT_NAME_STATUS |
4481 DIFF_FORMAT_CHECKDIFF |
4482 DIFF_FORMAT_NO_OUTPUT))
4483 options->output_format &= ~(DIFF_FORMAT_RAW |
4484 DIFF_FORMAT_NUMSTAT |
4485 DIFF_FORMAT_DIFFSTAT |
4486 DIFF_FORMAT_SHORTSTAT |
4487 DIFF_FORMAT_DIRSTAT |
4488 DIFF_FORMAT_SUMMARY |
4489 DIFF_FORMAT_PATCH);
4490
4491 /*
4492 * These cases always need recursive; we do not drop caller-supplied
4493 * recursive bits for other formats here.
4494 */
4495 if (options->output_format & (DIFF_FORMAT_PATCH |
4496 DIFF_FORMAT_NUMSTAT |
4497 DIFF_FORMAT_DIFFSTAT |
4498 DIFF_FORMAT_SHORTSTAT |
4499 DIFF_FORMAT_DIRSTAT |
4500 DIFF_FORMAT_SUMMARY |
4501 DIFF_FORMAT_CHECKDIFF))
4502 options->flags.recursive = 1;
4503 /*
4504 * Also pickaxe would not work very well if you do not say recursive
4505 */
4506 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4507 options->flags.recursive = 1;
4508 /*
4509 * When patches are generated, submodules diffed against the work tree
4510 * must be checked for dirtiness too so it can be shown in the output
4511 */
4512 if (options->output_format & DIFF_FORMAT_PATCH)
4513 options->flags.dirty_submodules = 1;
4514
4515 if (options->detect_rename && options->rename_limit < 0)
4516 options->rename_limit = diff_rename_limit_default;
4517 if (hexsz < options->abbrev)
4518 options->abbrev = hexsz; /* full */
4519
4520 /*
4521 * It does not make sense to show the first hit we happened
4522 * to have found. It does not make sense not to return with
4523 * exit code in such a case either.
4524 */
4525 if (options->flags.quick) {
4526 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4527 options->flags.exit_with_status = 1;
4528 }
4529
4530 options->diff_path_counter = 0;
4531
4532 if (options->flags.follow_renames && options->pathspec.nr != 1)
4533 die(_("--follow requires exactly one pathspec"));
4534
4535 if (!options->use_color || external_diff())
4536 options->color_moved = 0;
4537}
4538
4539static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4540{
4541 char c, *eq;
4542 int len;
4543
4544 if (*arg != '-')
4545 return 0;
4546 c = *++arg;
4547 if (!c)
4548 return 0;
4549 if (c == arg_short) {
4550 c = *++arg;
4551 if (!c)
4552 return 1;
4553 if (val && isdigit(c)) {
4554 char *end;
4555 int n = strtoul(arg, &end, 10);
4556 if (*end)
4557 return 0;
4558 *val = n;
4559 return 1;
4560 }
4561 return 0;
4562 }
4563 if (c != '-')
4564 return 0;
4565 arg++;
4566 eq = strchrnul(arg, '=');
4567 len = eq - arg;
4568 if (!len || strncmp(arg, arg_long, len))
4569 return 0;
4570 if (*eq) {
4571 int n;
4572 char *end;
4573 if (!isdigit(*++eq))
4574 return 0;
4575 n = strtoul(eq, &end, 10);
4576 if (*end)
4577 return 0;
4578 *val = n;
4579 }
4580 return 1;
4581}
4582
4583static int diff_scoreopt_parse(const char *opt);
4584
4585static inline int short_opt(char opt, const char **argv,
4586 const char **optarg)
4587{
4588 const char *arg = argv[0];
4589 if (arg[0] != '-' || arg[1] != opt)
4590 return 0;
4591 if (arg[2] != '\0') {
4592 *optarg = arg + 2;
4593 return 1;
4594 }
4595 if (!argv[1])
4596 die("Option '%c' requires a value", opt);
4597 *optarg = argv[1];
4598 return 2;
4599}
4600
4601int parse_long_opt(const char *opt, const char **argv,
4602 const char **optarg)
4603{
4604 const char *arg = argv[0];
4605 if (!skip_prefix(arg, "--", &arg))
4606 return 0;
4607 if (!skip_prefix(arg, opt, &arg))
4608 return 0;
4609 if (*arg == '=') { /* stuck form: --option=value */
4610 *optarg = arg + 1;
4611 return 1;
4612 }
4613 if (*arg != '\0')
4614 return 0;
4615 /* separate form: --option value */
4616 if (!argv[1])
4617 die("Option '--%s' requires a value", opt);
4618 *optarg = argv[1];
4619 return 2;
4620}
4621
4622static int stat_opt(struct diff_options *options, const char **av)
4623{
4624 const char *arg = av[0];
4625 char *end;
4626 int width = options->stat_width;
4627 int name_width = options->stat_name_width;
4628 int graph_width = options->stat_graph_width;
4629 int count = options->stat_count;
4630 int argcount = 1;
4631
4632 if (!skip_prefix(arg, "--stat", &arg))
4633 BUG("stat option does not begin with --stat: %s", arg);
4634 end = (char *)arg;
4635
4636 switch (*arg) {
4637 case '-':
4638 if (skip_prefix(arg, "-width", &arg)) {
4639 if (*arg == '=')
4640 width = strtoul(arg + 1, &end, 10);
4641 else if (!*arg && !av[1])
4642 die_want_option("--stat-width");
4643 else if (!*arg) {
4644 width = strtoul(av[1], &end, 10);
4645 argcount = 2;
4646 }
4647 } else if (skip_prefix(arg, "-name-width", &arg)) {
4648 if (*arg == '=')
4649 name_width = strtoul(arg + 1, &end, 10);
4650 else if (!*arg && !av[1])
4651 die_want_option("--stat-name-width");
4652 else if (!*arg) {
4653 name_width = strtoul(av[1], &end, 10);
4654 argcount = 2;
4655 }
4656 } else if (skip_prefix(arg, "-graph-width", &arg)) {
4657 if (*arg == '=')
4658 graph_width = strtoul(arg + 1, &end, 10);
4659 else if (!*arg && !av[1])
4660 die_want_option("--stat-graph-width");
4661 else if (!*arg) {
4662 graph_width = strtoul(av[1], &end, 10);
4663 argcount = 2;
4664 }
4665 } else if (skip_prefix(arg, "-count", &arg)) {
4666 if (*arg == '=')
4667 count = strtoul(arg + 1, &end, 10);
4668 else if (!*arg && !av[1])
4669 die_want_option("--stat-count");
4670 else if (!*arg) {
4671 count = strtoul(av[1], &end, 10);
4672 argcount = 2;
4673 }
4674 }
4675 break;
4676 case '=':
4677 width = strtoul(arg+1, &end, 10);
4678 if (*end == ',')
4679 name_width = strtoul(end+1, &end, 10);
4680 if (*end == ',')
4681 count = strtoul(end+1, &end, 10);
4682 }
4683
4684 /* Important! This checks all the error cases! */
4685 if (*end)
4686 return 0;
4687 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4688 options->stat_name_width = name_width;
4689 options->stat_graph_width = graph_width;
4690 options->stat_width = width;
4691 options->stat_count = count;
4692 return argcount;
4693}
4694
4695static int parse_dirstat_opt(struct diff_options *options, const char *params)
4696{
4697 struct strbuf errmsg = STRBUF_INIT;
4698 if (parse_dirstat_params(options, params, &errmsg))
4699 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4700 errmsg.buf);
4701 strbuf_release(&errmsg);
4702 /*
4703 * The caller knows a dirstat-related option is given from the command
4704 * line; allow it to say "return this_function();"
4705 */
4706 options->output_format |= DIFF_FORMAT_DIRSTAT;
4707 return 1;
4708}
4709
4710static int parse_submodule_opt(struct diff_options *options, const char *value)
4711{
4712 if (parse_submodule_params(options, value))
4713 die(_("Failed to parse --submodule option parameter: '%s'"),
4714 value);
4715 return 1;
4716}
4717
4718static const char diff_status_letters[] = {
4719 DIFF_STATUS_ADDED,
4720 DIFF_STATUS_COPIED,
4721 DIFF_STATUS_DELETED,
4722 DIFF_STATUS_MODIFIED,
4723 DIFF_STATUS_RENAMED,
4724 DIFF_STATUS_TYPE_CHANGED,
4725 DIFF_STATUS_UNKNOWN,
4726 DIFF_STATUS_UNMERGED,
4727 DIFF_STATUS_FILTER_AON,
4728 DIFF_STATUS_FILTER_BROKEN,
4729 '\0',
4730};
4731
4732static unsigned int filter_bit['Z' + 1];
4733
4734static void prepare_filter_bits(void)
4735{
4736 int i;
4737
4738 if (!filter_bit[DIFF_STATUS_ADDED]) {
4739 for (i = 0; diff_status_letters[i]; i++)
4740 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4741 }
4742}
4743
4744static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4745{
4746 return opt->filter & filter_bit[(int) status];
4747}
4748
4749static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4750{
4751 int i, optch;
4752
4753 prepare_filter_bits();
4754
4755 /*
4756 * If there is a negation e.g. 'd' in the input, and we haven't
4757 * initialized the filter field with another --diff-filter, start
4758 * from full set of bits, except for AON.
4759 */
4760 if (!opt->filter) {
4761 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4762 if (optch < 'a' || 'z' < optch)
4763 continue;
4764 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4765 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4766 break;
4767 }
4768 }
4769
4770 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4771 unsigned int bit;
4772 int negate;
4773
4774 if ('a' <= optch && optch <= 'z') {
4775 negate = 1;
4776 optch = toupper(optch);
4777 } else {
4778 negate = 0;
4779 }
4780
4781 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4782 if (!bit)
4783 return optarg[i];
4784 if (negate)
4785 opt->filter &= ~bit;
4786 else
4787 opt->filter |= bit;
4788 }
4789 return 0;
4790}
4791
4792static void enable_patch_output(int *fmt) {
4793 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4794 *fmt |= DIFF_FORMAT_PATCH;
4795}
4796
4797static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4798{
4799 int val = parse_ws_error_highlight(arg);
4800
4801 if (val < 0) {
4802 error("unknown value after ws-error-highlight=%.*s",
4803 -1 - val, arg);
4804 return 0;
4805 }
4806 opt->ws_error_highlight = val;
4807 return 1;
4808}
4809
4810static int parse_objfind_opt(struct diff_options *opt, const char *arg)
4811{
4812 struct object_id oid;
4813
4814 if (get_oid(arg, &oid))
4815 return error("unable to resolve '%s'", arg);
4816
4817 if (!opt->objfind)
4818 opt->objfind = xcalloc(1, sizeof(*opt->objfind));
4819
4820 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4821 opt->flags.recursive = 1;
4822 opt->flags.tree_in_recursive = 1;
4823 oidset_insert(opt->objfind, &oid);
4824 return 1;
4825}
4826
4827int diff_opt_parse(struct diff_options *options,
4828 const char **av, int ac, const char *prefix)
4829{
4830 const char *arg = av[0];
4831 const char *optarg;
4832 int argcount;
4833
4834 if (!prefix)
4835 prefix = "";
4836
4837 /* Output format options */
4838 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
4839 || opt_arg(arg, 'U', "unified", &options->context))
4840 enable_patch_output(&options->output_format);
4841 else if (!strcmp(arg, "--raw"))
4842 options->output_format |= DIFF_FORMAT_RAW;
4843 else if (!strcmp(arg, "--patch-with-raw")) {
4844 enable_patch_output(&options->output_format);
4845 options->output_format |= DIFF_FORMAT_RAW;
4846 } else if (!strcmp(arg, "--numstat"))
4847 options->output_format |= DIFF_FORMAT_NUMSTAT;
4848 else if (!strcmp(arg, "--shortstat"))
4849 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4850 else if (skip_prefix(arg, "-X", &arg) ||
4851 skip_to_optional_arg(arg, "--dirstat", &arg))
4852 return parse_dirstat_opt(options, arg);
4853 else if (!strcmp(arg, "--cumulative"))
4854 return parse_dirstat_opt(options, "cumulative");
4855 else if (skip_to_optional_arg(arg, "--dirstat-by-file", &arg)) {
4856 parse_dirstat_opt(options, "files");
4857 return parse_dirstat_opt(options, arg);
4858 }
4859 else if (!strcmp(arg, "--check"))
4860 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4861 else if (!strcmp(arg, "--summary"))
4862 options->output_format |= DIFF_FORMAT_SUMMARY;
4863 else if (!strcmp(arg, "--patch-with-stat")) {
4864 enable_patch_output(&options->output_format);
4865 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4866 } else if (!strcmp(arg, "--name-only"))
4867 options->output_format |= DIFF_FORMAT_NAME;
4868 else if (!strcmp(arg, "--name-status"))
4869 options->output_format |= DIFF_FORMAT_NAME_STATUS;
4870 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
4871 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4872 else if (starts_with(arg, "--stat"))
4873 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4874 return stat_opt(options, av);
4875 else if (!strcmp(arg, "--compact-summary")) {
4876 options->flags.stat_with_summary = 1;
4877 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4878 } else if (!strcmp(arg, "--no-compact-summary"))
4879 options->flags.stat_with_summary = 0;
4880 else if (skip_prefix(arg, "--output-indicator-new=", &arg))
4881 options->output_indicators[OUTPUT_INDICATOR_NEW] = arg[0];
4882 else if (skip_prefix(arg, "--output-indicator-old=", &arg))
4883 options->output_indicators[OUTPUT_INDICATOR_OLD] = arg[0];
4884 else if (skip_prefix(arg, "--output-indicator-context=", &arg))
4885 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = arg[0];
4886
4887 /* renames options */
4888 else if (starts_with(arg, "-B") ||
4889 skip_to_optional_arg(arg, "--break-rewrites", NULL)) {
4890 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
4891 return error("invalid argument to -B: %s", arg+2);
4892 }
4893 else if (starts_with(arg, "-M") ||
4894 skip_to_optional_arg(arg, "--find-renames", NULL)) {
4895 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4896 return error("invalid argument to -M: %s", arg+2);
4897 options->detect_rename = DIFF_DETECT_RENAME;
4898 }
4899 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
4900 options->irreversible_delete = 1;
4901 }
4902 else if (starts_with(arg, "-C") ||
4903 skip_to_optional_arg(arg, "--find-copies", NULL)) {
4904 if (options->detect_rename == DIFF_DETECT_COPY)
4905 options->flags.find_copies_harder = 1;
4906 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4907 return error("invalid argument to -C: %s", arg+2);
4908 options->detect_rename = DIFF_DETECT_COPY;
4909 }
4910 else if (!strcmp(arg, "--no-renames"))
4911 options->detect_rename = 0;
4912 else if (!strcmp(arg, "--rename-empty"))
4913 options->flags.rename_empty = 1;
4914 else if (!strcmp(arg, "--no-rename-empty"))
4915 options->flags.rename_empty = 0;
4916 else if (skip_to_optional_arg_default(arg, "--relative", &arg, NULL)) {
4917 options->flags.relative_name = 1;
4918 if (arg)
4919 options->prefix = arg;
4920 }
4921
4922 /* xdiff options */
4923 else if (!strcmp(arg, "--minimal"))
4924 DIFF_XDL_SET(options, NEED_MINIMAL);
4925 else if (!strcmp(arg, "--no-minimal"))
4926 DIFF_XDL_CLR(options, NEED_MINIMAL);
4927 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
4928 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
4929 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
4930 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
4931 else if (!strcmp(arg, "--ignore-space-at-eol"))
4932 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
4933 else if (!strcmp(arg, "--ignore-cr-at-eol"))
4934 DIFF_XDL_SET(options, IGNORE_CR_AT_EOL);
4935 else if (!strcmp(arg, "--ignore-blank-lines"))
4936 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
4937 else if (!strcmp(arg, "--indent-heuristic"))
4938 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4939 else if (!strcmp(arg, "--no-indent-heuristic"))
4940 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
4941 else if (!strcmp(arg, "--patience")) {
4942 int i;
4943 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4944 /*
4945 * Both --patience and --anchored use PATIENCE_DIFF
4946 * internally, so remove any anchors previously
4947 * specified.
4948 */
4949 for (i = 0; i < options->anchors_nr; i++)
4950 free(options->anchors[i]);
4951 options->anchors_nr = 0;
4952 } else if (!strcmp(arg, "--histogram"))
4953 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
4954 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
4955 long value = parse_algorithm_value(optarg);
4956 if (value < 0)
4957 return error("option diff-algorithm accepts \"myers\", "
4958 "\"minimal\", \"patience\" and \"histogram\"");
4959 /* clear out previous settings */
4960 DIFF_XDL_CLR(options, NEED_MINIMAL);
4961 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4962 options->xdl_opts |= value;
4963 return argcount;
4964 } else if (skip_prefix(arg, "--anchored=", &arg)) {
4965 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4966 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4967 options->anchors_alloc);
4968 options->anchors[options->anchors_nr++] = xstrdup(arg);
4969 }
4970
4971 /* flags options */
4972 else if (!strcmp(arg, "--binary")) {
4973 enable_patch_output(&options->output_format);
4974 options->flags.binary = 1;
4975 }
4976 else if (!strcmp(arg, "--full-index"))
4977 options->flags.full_index = 1;
4978 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
4979 options->flags.text = 1;
4980 else if (!strcmp(arg, "-R"))
4981 options->flags.reverse_diff = 1;
4982 else if (!strcmp(arg, "--find-copies-harder"))
4983 options->flags.find_copies_harder = 1;
4984 else if (!strcmp(arg, "--follow"))
4985 options->flags.follow_renames = 1;
4986 else if (!strcmp(arg, "--no-follow")) {
4987 options->flags.follow_renames = 0;
4988 options->flags.default_follow_renames = 0;
4989 } else if (skip_to_optional_arg_default(arg, "--color", &arg, "always")) {
4990 int value = git_config_colorbool(NULL, arg);
4991 if (value < 0)
4992 return error("option `color' expects \"always\", \"auto\", or \"never\"");
4993 options->use_color = value;
4994 }
4995 else if (!strcmp(arg, "--no-color"))
4996 options->use_color = 0;
4997 else if (!strcmp(arg, "--color-moved")) {
4998 if (diff_color_moved_default)
4999 options->color_moved = diff_color_moved_default;
5000 if (options->color_moved == COLOR_MOVED_NO)
5001 options->color_moved = COLOR_MOVED_DEFAULT;
5002 } else if (!strcmp(arg, "--no-color-moved"))
5003 options->color_moved = COLOR_MOVED_NO;
5004 else if (skip_prefix(arg, "--color-moved=", &arg)) {
5005 int cm = parse_color_moved(arg);
5006 if (cm < 0)
5007 die("bad --color-moved argument: %s", arg);
5008 options->color_moved = cm;
5009 } else if (skip_prefix(arg, "--color-moved-ws=", &arg)) {
5010 options->color_moved_ws_handling = parse_color_moved_ws(arg);
5011 } else if (skip_to_optional_arg_default(arg, "--color-words", &options->word_regex, NULL)) {
5012 options->use_color = 1;
5013 options->word_diff = DIFF_WORDS_COLOR;
5014 }
5015 else if (!strcmp(arg, "--word-diff")) {
5016 if (options->word_diff == DIFF_WORDS_NONE)
5017 options->word_diff = DIFF_WORDS_PLAIN;
5018 }
5019 else if (skip_prefix(arg, "--word-diff=", &arg)) {
5020 if (!strcmp(arg, "plain"))
5021 options->word_diff = DIFF_WORDS_PLAIN;
5022 else if (!strcmp(arg, "color")) {
5023 options->use_color = 1;
5024 options->word_diff = DIFF_WORDS_COLOR;
5025 }
5026 else if (!strcmp(arg, "porcelain"))
5027 options->word_diff = DIFF_WORDS_PORCELAIN;
5028 else if (!strcmp(arg, "none"))
5029 options->word_diff = DIFF_WORDS_NONE;
5030 else
5031 die("bad --word-diff argument: %s", arg);
5032 }
5033 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
5034 if (options->word_diff == DIFF_WORDS_NONE)
5035 options->word_diff = DIFF_WORDS_PLAIN;
5036 options->word_regex = optarg;
5037 return argcount;
5038 }
5039 else if (!strcmp(arg, "--exit-code"))
5040 options->flags.exit_with_status = 1;
5041 else if (!strcmp(arg, "--quiet"))
5042 options->flags.quick = 1;
5043 else if (!strcmp(arg, "--ext-diff"))
5044 options->flags.allow_external = 1;
5045 else if (!strcmp(arg, "--no-ext-diff"))
5046 options->flags.allow_external = 0;
5047 else if (!strcmp(arg, "--textconv")) {
5048 options->flags.allow_textconv = 1;
5049 options->flags.textconv_set_via_cmdline = 1;
5050 } else if (!strcmp(arg, "--no-textconv"))
5051 options->flags.allow_textconv = 0;
5052 else if (skip_to_optional_arg_default(arg, "--ignore-submodules", &arg, "all")) {
5053 options->flags.override_submodule_config = 1;
5054 handle_ignore_submodules_arg(options, arg);
5055 } else if (skip_to_optional_arg_default(arg, "--submodule", &arg, "log"))
5056 return parse_submodule_opt(options, arg);
5057 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
5058 return parse_ws_error_highlight_opt(options, arg);
5059 else if (!strcmp(arg, "--ita-invisible-in-index"))
5060 options->ita_invisible_in_index = 1;
5061 else if (!strcmp(arg, "--ita-visible-in-index"))
5062 options->ita_invisible_in_index = 0;
5063
5064 /* misc options */
5065 else if (!strcmp(arg, "-z"))
5066 options->line_termination = 0;
5067 else if ((argcount = short_opt('l', av, &optarg))) {
5068 options->rename_limit = strtoul(optarg, NULL, 10);
5069 return argcount;
5070 }
5071 else if ((argcount = short_opt('S', av, &optarg))) {
5072 options->pickaxe = optarg;
5073 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5074 return argcount;
5075 } else if ((argcount = short_opt('G', av, &optarg))) {
5076 options->pickaxe = optarg;
5077 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5078 return argcount;
5079 }
5080 else if (!strcmp(arg, "--pickaxe-all"))
5081 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
5082 else if (!strcmp(arg, "--pickaxe-regex"))
5083 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
5084 else if ((argcount = short_opt('O', av, &optarg))) {
5085 options->orderfile = prefix_filename(prefix, optarg);
5086 return argcount;
5087 } else if (skip_prefix(arg, "--find-object=", &arg))
5088 return parse_objfind_opt(options, arg);
5089 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
5090 int offending = parse_diff_filter_opt(optarg, options);
5091 if (offending)
5092 die("unknown change class '%c' in --diff-filter=%s",
5093 offending, optarg);
5094 return argcount;
5095 }
5096 else if (!strcmp(arg, "--no-abbrev"))
5097 options->abbrev = 0;
5098 else if (!strcmp(arg, "--abbrev"))
5099 options->abbrev = DEFAULT_ABBREV;
5100 else if (skip_prefix(arg, "--abbrev=", &arg)) {
5101 options->abbrev = strtoul(arg, NULL, 10);
5102 if (options->abbrev < MINIMUM_ABBREV)
5103 options->abbrev = MINIMUM_ABBREV;
5104 else if (the_hash_algo->hexsz < options->abbrev)
5105 options->abbrev = the_hash_algo->hexsz;
5106 }
5107 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
5108 options->a_prefix = optarg;
5109 return argcount;
5110 }
5111 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
5112 options->line_prefix = optarg;
5113 options->line_prefix_length = strlen(options->line_prefix);
5114 graph_setup_line_prefix(options);
5115 return argcount;
5116 }
5117 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
5118 options->b_prefix = optarg;
5119 return argcount;
5120 }
5121 else if (!strcmp(arg, "--no-prefix"))
5122 options->a_prefix = options->b_prefix = "";
5123 else if (opt_arg(arg, '\0', "inter-hunk-context",
5124 &options->interhunkcontext))
5125 ;
5126 else if (!strcmp(arg, "-W"))
5127 options->flags.funccontext = 1;
5128 else if (!strcmp(arg, "--function-context"))
5129 options->flags.funccontext = 1;
5130 else if (!strcmp(arg, "--no-function-context"))
5131 options->flags.funccontext = 0;
5132 else if ((argcount = parse_long_opt("output", av, &optarg))) {
5133 char *path = prefix_filename(prefix, optarg);
5134 options->file = xfopen(path, "w");
5135 options->close_file = 1;
5136 if (options->use_color != GIT_COLOR_ALWAYS)
5137 options->use_color = GIT_COLOR_NEVER;
5138 free(path);
5139 return argcount;
5140 } else
5141 return 0;
5142 return 1;
5143}
5144
5145int parse_rename_score(const char **cp_p)
5146{
5147 unsigned long num, scale;
5148 int ch, dot;
5149 const char *cp = *cp_p;
5150
5151 num = 0;
5152 scale = 1;
5153 dot = 0;
5154 for (;;) {
5155 ch = *cp;
5156 if ( !dot && ch == '.' ) {
5157 scale = 1;
5158 dot = 1;
5159 } else if ( ch == '%' ) {
5160 scale = dot ? scale*100 : 100;
5161 cp++; /* % is always at the end */
5162 break;
5163 } else if ( ch >= '0' && ch <= '9' ) {
5164 if ( scale < 100000 ) {
5165 scale *= 10;
5166 num = (num*10) + (ch-'0');
5167 }
5168 } else {
5169 break;
5170 }
5171 cp++;
5172 }
5173 *cp_p = cp;
5174
5175 /* user says num divided by scale and we say internally that
5176 * is MAX_SCORE * num / scale.
5177 */
5178 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5179}
5180
5181static int diff_scoreopt_parse(const char *opt)
5182{
5183 int opt1, opt2, cmd;
5184
5185 if (*opt++ != '-')
5186 return -1;
5187 cmd = *opt++;
5188 if (cmd == '-') {
5189 /* convert the long-form arguments into short-form versions */
5190 if (skip_prefix(opt, "break-rewrites", &opt)) {
5191 if (*opt == 0 || *opt++ == '=')
5192 cmd = 'B';
5193 } else if (skip_prefix(opt, "find-copies", &opt)) {
5194 if (*opt == 0 || *opt++ == '=')
5195 cmd = 'C';
5196 } else if (skip_prefix(opt, "find-renames", &opt)) {
5197 if (*opt == 0 || *opt++ == '=')
5198 cmd = 'M';
5199 }
5200 }
5201 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
5202 return -1; /* that is not a -M, -C, or -B option */
5203
5204 opt1 = parse_rename_score(&opt);
5205 if (cmd != 'B')
5206 opt2 = 0;
5207 else {
5208 if (*opt == 0)
5209 opt2 = 0;
5210 else if (*opt != '/')
5211 return -1; /* we expect -B80/99 or -B80 */
5212 else {
5213 opt++;
5214 opt2 = parse_rename_score(&opt);
5215 }
5216 }
5217 if (*opt != 0)
5218 return -1;
5219 return opt1 | (opt2 << 16);
5220}
5221
5222struct diff_queue_struct diff_queued_diff;
5223
5224void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5225{
5226 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5227 queue->queue[queue->nr++] = dp;
5228}
5229
5230struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5231 struct diff_filespec *one,
5232 struct diff_filespec *two)
5233{
5234 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5235 dp->one = one;
5236 dp->two = two;
5237 if (queue)
5238 diff_q(queue, dp);
5239 return dp;
5240}
5241
5242void diff_free_filepair(struct diff_filepair *p)
5243{
5244 free_filespec(p->one);
5245 free_filespec(p->two);
5246 free(p);
5247}
5248
5249const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5250{
5251 int abblen;
5252 const char *abbrev;
5253
5254 /* Do we want all 40 hex characters? */
5255 if (len == the_hash_algo->hexsz)
5256 return oid_to_hex(oid);
5257
5258 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5259 abbrev = diff_abbrev_oid(oid, len);
5260
5261 if (!print_sha1_ellipsis())
5262 return abbrev;
5263
5264 abblen = strlen(abbrev);
5265
5266 /*
5267 * In well-behaved cases, where the abbreviated result is the
5268 * same as the requested length, append three dots after the
5269 * abbreviation (hence the whole logic is limited to the case
5270 * where abblen < 37); when the actual abbreviated result is a
5271 * bit longer than the requested length, we reduce the number
5272 * of dots so that they match the well-behaved ones. However,
5273 * if the actual abbreviation is longer than the requested
5274 * length by more than three, we give up on aligning, and add
5275 * three dots anyway, to indicate that the output is not the
5276 * full object name. Yes, this may be suboptimal, but this
5277 * appears only in "diff --raw --abbrev" output and it is not
5278 * worth the effort to change it now. Note that this would
5279 * likely to work fine when the automatic sizing of default
5280 * abbreviation length is used--we would be fed -1 in "len" in
5281 * that case, and will end up always appending three-dots, but
5282 * the automatic sizing is supposed to give abblen that ensures
5283 * uniqueness across all objects (statistically speaking).
5284 */
5285 if (abblen < the_hash_algo->hexsz - 3) {
5286 static char hex[GIT_MAX_HEXSZ + 1];
5287 if (len < abblen && abblen <= len + 2)
5288 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5289 else
5290 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5291 return hex;
5292 }
5293
5294 return oid_to_hex(oid);
5295}
5296
5297static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5298{
5299 int line_termination = opt->line_termination;
5300 int inter_name_termination = line_termination ? '\t' : '\0';
5301
5302 fprintf(opt->file, "%s", diff_line_prefix(opt));
5303 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5304 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5305 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5306 fprintf(opt->file, "%s ",
5307 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5308 }
5309 if (p->score) {
5310 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5311 inter_name_termination);
5312 } else {
5313 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5314 }
5315
5316 if (p->status == DIFF_STATUS_COPIED ||
5317 p->status == DIFF_STATUS_RENAMED) {
5318 const char *name_a, *name_b;
5319 name_a = p->one->path;
5320 name_b = p->two->path;
5321 strip_prefix(opt->prefix_length, &name_a, &name_b);
5322 write_name_quoted(name_a, opt->file, inter_name_termination);
5323 write_name_quoted(name_b, opt->file, line_termination);
5324 } else {
5325 const char *name_a, *name_b;
5326 name_a = p->one->mode ? p->one->path : p->two->path;
5327 name_b = NULL;
5328 strip_prefix(opt->prefix_length, &name_a, &name_b);
5329 write_name_quoted(name_a, opt->file, line_termination);
5330 }
5331}
5332
5333int diff_unmodified_pair(struct diff_filepair *p)
5334{
5335 /* This function is written stricter than necessary to support
5336 * the currently implemented transformers, but the idea is to
5337 * let transformers to produce diff_filepairs any way they want,
5338 * and filter and clean them up here before producing the output.
5339 */
5340 struct diff_filespec *one = p->one, *two = p->two;
5341
5342 if (DIFF_PAIR_UNMERGED(p))
5343 return 0; /* unmerged is interesting */
5344
5345 /* deletion, addition, mode or type change
5346 * and rename are all interesting.
5347 */
5348 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5349 DIFF_PAIR_MODE_CHANGED(p) ||
5350 strcmp(one->path, two->path))
5351 return 0;
5352
5353 /* both are valid and point at the same path. that is, we are
5354 * dealing with a change.
5355 */
5356 if (one->oid_valid && two->oid_valid &&
5357 oideq(&one->oid, &two->oid) &&
5358 !one->dirty_submodule && !two->dirty_submodule)
5359 return 1; /* no change */
5360 if (!one->oid_valid && !two->oid_valid)
5361 return 1; /* both look at the same file on the filesystem. */
5362 return 0;
5363}
5364
5365static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5366{
5367 if (diff_unmodified_pair(p))
5368 return;
5369
5370 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5371 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5372 return; /* no tree diffs in patch format */
5373
5374 run_diff(p, o);
5375}
5376
5377static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5378 struct diffstat_t *diffstat)
5379{
5380 if (diff_unmodified_pair(p))
5381 return;
5382
5383 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5384 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5385 return; /* no useful stat for tree diffs */
5386
5387 run_diffstat(p, o, diffstat);
5388}
5389
5390static void diff_flush_checkdiff(struct diff_filepair *p,
5391 struct diff_options *o)
5392{
5393 if (diff_unmodified_pair(p))
5394 return;
5395
5396 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5397 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5398 return; /* nothing to check in tree diffs */
5399
5400 run_checkdiff(p, o);
5401}
5402
5403int diff_queue_is_empty(void)
5404{
5405 struct diff_queue_struct *q = &diff_queued_diff;
5406 int i;
5407 for (i = 0; i < q->nr; i++)
5408 if (!diff_unmodified_pair(q->queue[i]))
5409 return 0;
5410 return 1;
5411}
5412
5413#if DIFF_DEBUG
5414void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5415{
5416 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5417 x, one ? one : "",
5418 s->path,
5419 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5420 s->mode,
5421 s->oid_valid ? oid_to_hex(&s->oid) : "");
5422 fprintf(stderr, "queue[%d] %s size %lu\n",
5423 x, one ? one : "",
5424 s->size);
5425}
5426
5427void diff_debug_filepair(const struct diff_filepair *p, int i)
5428{
5429 diff_debug_filespec(p->one, i, "one");
5430 diff_debug_filespec(p->two, i, "two");
5431 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5432 p->score, p->status ? p->status : '?',
5433 p->one->rename_used, p->broken_pair);
5434}
5435
5436void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5437{
5438 int i;
5439 if (msg)
5440 fprintf(stderr, "%s\n", msg);
5441 fprintf(stderr, "q->nr = %d\n", q->nr);
5442 for (i = 0; i < q->nr; i++) {
5443 struct diff_filepair *p = q->queue[i];
5444 diff_debug_filepair(p, i);
5445 }
5446}
5447#endif
5448
5449static void diff_resolve_rename_copy(void)
5450{
5451 int i;
5452 struct diff_filepair *p;
5453 struct diff_queue_struct *q = &diff_queued_diff;
5454
5455 diff_debug_queue("resolve-rename-copy", q);
5456
5457 for (i = 0; i < q->nr; i++) {
5458 p = q->queue[i];
5459 p->status = 0; /* undecided */
5460 if (DIFF_PAIR_UNMERGED(p))
5461 p->status = DIFF_STATUS_UNMERGED;
5462 else if (!DIFF_FILE_VALID(p->one))
5463 p->status = DIFF_STATUS_ADDED;
5464 else if (!DIFF_FILE_VALID(p->two))
5465 p->status = DIFF_STATUS_DELETED;
5466 else if (DIFF_PAIR_TYPE_CHANGED(p))
5467 p->status = DIFF_STATUS_TYPE_CHANGED;
5468
5469 /* from this point on, we are dealing with a pair
5470 * whose both sides are valid and of the same type, i.e.
5471 * either in-place edit or rename/copy edit.
5472 */
5473 else if (DIFF_PAIR_RENAME(p)) {
5474 /*
5475 * A rename might have re-connected a broken
5476 * pair up, causing the pathnames to be the
5477 * same again. If so, that's not a rename at
5478 * all, just a modification..
5479 *
5480 * Otherwise, see if this source was used for
5481 * multiple renames, in which case we decrement
5482 * the count, and call it a copy.
5483 */
5484 if (!strcmp(p->one->path, p->two->path))
5485 p->status = DIFF_STATUS_MODIFIED;
5486 else if (--p->one->rename_used > 0)
5487 p->status = DIFF_STATUS_COPIED;
5488 else
5489 p->status = DIFF_STATUS_RENAMED;
5490 }
5491 else if (!oideq(&p->one->oid, &p->two->oid) ||
5492 p->one->mode != p->two->mode ||
5493 p->one->dirty_submodule ||
5494 p->two->dirty_submodule ||
5495 is_null_oid(&p->one->oid))
5496 p->status = DIFF_STATUS_MODIFIED;
5497 else {
5498 /* This is a "no-change" entry and should not
5499 * happen anymore, but prepare for broken callers.
5500 */
5501 error("feeding unmodified %s to diffcore",
5502 p->one->path);
5503 p->status = DIFF_STATUS_UNKNOWN;
5504 }
5505 }
5506 diff_debug_queue("resolve-rename-copy done", q);
5507}
5508
5509static int check_pair_status(struct diff_filepair *p)
5510{
5511 switch (p->status) {
5512 case DIFF_STATUS_UNKNOWN:
5513 return 0;
5514 case 0:
5515 die("internal error in diff-resolve-rename-copy");
5516 default:
5517 return 1;
5518 }
5519}
5520
5521static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5522{
5523 int fmt = opt->output_format;
5524
5525 if (fmt & DIFF_FORMAT_CHECKDIFF)
5526 diff_flush_checkdiff(p, opt);
5527 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5528 diff_flush_raw(p, opt);
5529 else if (fmt & DIFF_FORMAT_NAME) {
5530 const char *name_a, *name_b;
5531 name_a = p->two->path;
5532 name_b = NULL;
5533 strip_prefix(opt->prefix_length, &name_a, &name_b);
5534 fprintf(opt->file, "%s", diff_line_prefix(opt));
5535 write_name_quoted(name_a, opt->file, opt->line_termination);
5536 }
5537}
5538
5539static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5540{
5541 struct strbuf sb = STRBUF_INIT;
5542 if (fs->mode)
5543 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5544 else
5545 strbuf_addf(&sb, " %s ", newdelete);
5546
5547 quote_c_style(fs->path, &sb, NULL, 0);
5548 strbuf_addch(&sb, '\n');
5549 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5550 sb.buf, sb.len, 0);
5551 strbuf_release(&sb);
5552}
5553
5554static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5555 int show_name)
5556{
5557 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5558 struct strbuf sb = STRBUF_INIT;
5559 strbuf_addf(&sb, " mode change %06o => %06o",
5560 p->one->mode, p->two->mode);
5561 if (show_name) {
5562 strbuf_addch(&sb, ' ');
5563 quote_c_style(p->two->path, &sb, NULL, 0);
5564 }
5565 strbuf_addch(&sb, '\n');
5566 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5567 sb.buf, sb.len, 0);
5568 strbuf_release(&sb);
5569 }
5570}
5571
5572static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5573 struct diff_filepair *p)
5574{
5575 struct strbuf sb = STRBUF_INIT;
5576 struct strbuf names = STRBUF_INIT;
5577
5578 pprint_rename(&names, p->one->path, p->two->path);
5579 strbuf_addf(&sb, " %s %s (%d%%)\n",
5580 renamecopy, names.buf, similarity_index(p));
5581 strbuf_release(&names);
5582 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5583 sb.buf, sb.len, 0);
5584 show_mode_change(opt, p, 0);
5585 strbuf_release(&sb);
5586}
5587
5588static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5589{
5590 switch(p->status) {
5591 case DIFF_STATUS_DELETED:
5592 show_file_mode_name(opt, "delete", p->one);
5593 break;
5594 case DIFF_STATUS_ADDED:
5595 show_file_mode_name(opt, "create", p->two);
5596 break;
5597 case DIFF_STATUS_COPIED:
5598 show_rename_copy(opt, "copy", p);
5599 break;
5600 case DIFF_STATUS_RENAMED:
5601 show_rename_copy(opt, "rename", p);
5602 break;
5603 default:
5604 if (p->score) {
5605 struct strbuf sb = STRBUF_INIT;
5606 strbuf_addstr(&sb, " rewrite ");
5607 quote_c_style(p->two->path, &sb, NULL, 0);
5608 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5609 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5610 sb.buf, sb.len, 0);
5611 strbuf_release(&sb);
5612 }
5613 show_mode_change(opt, p, !p->score);
5614 break;
5615 }
5616}
5617
5618struct patch_id_t {
5619 git_SHA_CTX *ctx;
5620 int patchlen;
5621};
5622
5623static int remove_space(char *line, int len)
5624{
5625 int i;
5626 char *dst = line;
5627 unsigned char c;
5628
5629 for (i = 0; i < len; i++)
5630 if (!isspace((c = line[i])))
5631 *dst++ = c;
5632
5633 return dst - line;
5634}
5635
5636static void patch_id_consume(void *priv, char *line, unsigned long len)
5637{
5638 struct patch_id_t *data = priv;
5639 int new_len;
5640
5641 /* Ignore line numbers when computing the SHA1 of the patch */
5642 if (starts_with(line, "@@ -"))
5643 return;
5644
5645 new_len = remove_space(line, len);
5646
5647 git_SHA1_Update(data->ctx, line, new_len);
5648 data->patchlen += new_len;
5649}
5650
5651static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
5652{
5653 git_SHA1_Update(ctx, str, strlen(str));
5654}
5655
5656static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
5657{
5658 /* large enough for 2^32 in octal */
5659 char buf[12];
5660 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
5661 git_SHA1_Update(ctx, buf, len);
5662}
5663
5664/* returns 0 upon success, and writes result into sha1 */
5665static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5666{
5667 struct diff_queue_struct *q = &diff_queued_diff;
5668 int i;
5669 git_SHA_CTX ctx;
5670 struct patch_id_t data;
5671
5672 git_SHA1_Init(&ctx);
5673 memset(&data, 0, sizeof(struct patch_id_t));
5674 data.ctx = &ctx;
5675
5676 for (i = 0; i < q->nr; i++) {
5677 xpparam_t xpp;
5678 xdemitconf_t xecfg;
5679 mmfile_t mf1, mf2;
5680 struct diff_filepair *p = q->queue[i];
5681 int len1, len2;
5682
5683 memset(&xpp, 0, sizeof(xpp));
5684 memset(&xecfg, 0, sizeof(xecfg));
5685 if (p->status == 0)
5686 return error("internal diff status error");
5687 if (p->status == DIFF_STATUS_UNKNOWN)
5688 continue;
5689 if (diff_unmodified_pair(p))
5690 continue;
5691 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5692 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5693 continue;
5694 if (DIFF_PAIR_UNMERGED(p))
5695 continue;
5696
5697 diff_fill_oid_info(p->one);
5698 diff_fill_oid_info(p->two);
5699
5700 len1 = remove_space(p->one->path, strlen(p->one->path));
5701 len2 = remove_space(p->two->path, strlen(p->two->path));
5702 patch_id_add_string(&ctx, "diff--git");
5703 patch_id_add_string(&ctx, "a/");
5704 git_SHA1_Update(&ctx, p->one->path, len1);
5705 patch_id_add_string(&ctx, "b/");
5706 git_SHA1_Update(&ctx, p->two->path, len2);
5707
5708 if (p->one->mode == 0) {
5709 patch_id_add_string(&ctx, "newfilemode");
5710 patch_id_add_mode(&ctx, p->two->mode);
5711 patch_id_add_string(&ctx, "---/dev/null");
5712 patch_id_add_string(&ctx, "+++b/");
5713 git_SHA1_Update(&ctx, p->two->path, len2);
5714 } else if (p->two->mode == 0) {
5715 patch_id_add_string(&ctx, "deletedfilemode");
5716 patch_id_add_mode(&ctx, p->one->mode);
5717 patch_id_add_string(&ctx, "---a/");
5718 git_SHA1_Update(&ctx, p->one->path, len1);
5719 patch_id_add_string(&ctx, "+++/dev/null");
5720 } else {
5721 patch_id_add_string(&ctx, "---a/");
5722 git_SHA1_Update(&ctx, p->one->path, len1);
5723 patch_id_add_string(&ctx, "+++b/");
5724 git_SHA1_Update(&ctx, p->two->path, len2);
5725 }
5726
5727 if (diff_header_only)
5728 continue;
5729
5730 if (fill_mmfile(&mf1, p->one) < 0 ||
5731 fill_mmfile(&mf2, p->two) < 0)
5732 return error("unable to read files to diff");
5733
5734 if (diff_filespec_is_binary(p->one) ||
5735 diff_filespec_is_binary(p->two)) {
5736 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5737 GIT_SHA1_HEXSZ);
5738 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5739 GIT_SHA1_HEXSZ);
5740 continue;
5741 }
5742
5743 xpp.flags = 0;
5744 xecfg.ctxlen = 3;
5745 xecfg.flags = 0;
5746 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
5747 &xpp, &xecfg))
5748 return error("unable to generate patch-id diff for %s",
5749 p->one->path);
5750 }
5751
5752 git_SHA1_Final(oid->hash, &ctx);
5753 return 0;
5754}
5755
5756int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5757{
5758 struct diff_queue_struct *q = &diff_queued_diff;
5759 int i;
5760 int result = diff_get_patch_id(options, oid, diff_header_only);
5761
5762 for (i = 0; i < q->nr; i++)
5763 diff_free_filepair(q->queue[i]);
5764
5765 free(q->queue);
5766 DIFF_QUEUE_CLEAR(q);
5767
5768 return result;
5769}
5770
5771static int is_summary_empty(const struct diff_queue_struct *q)
5772{
5773 int i;
5774
5775 for (i = 0; i < q->nr; i++) {
5776 const struct diff_filepair *p = q->queue[i];
5777
5778 switch (p->status) {
5779 case DIFF_STATUS_DELETED:
5780 case DIFF_STATUS_ADDED:
5781 case DIFF_STATUS_COPIED:
5782 case DIFF_STATUS_RENAMED:
5783 return 0;
5784 default:
5785 if (p->score)
5786 return 0;
5787 if (p->one->mode && p->two->mode &&
5788 p->one->mode != p->two->mode)
5789 return 0;
5790 break;
5791 }
5792 }
5793 return 1;
5794}
5795
5796static const char rename_limit_warning[] =
5797N_("inexact rename detection was skipped due to too many files.");
5798
5799static const char degrade_cc_to_c_warning[] =
5800N_("only found copies from modified paths due to too many files.");
5801
5802static const char rename_limit_advice[] =
5803N_("you may want to set your %s variable to at least "
5804 "%d and retry the command.");
5805
5806void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
5807{
5808 fflush(stdout);
5809 if (degraded_cc)
5810 warning(_(degrade_cc_to_c_warning));
5811 else if (needed)
5812 warning(_(rename_limit_warning));
5813 else
5814 return;
5815 if (0 < needed)
5816 warning(_(rename_limit_advice), varname, needed);
5817}
5818
5819static void diff_flush_patch_all_file_pairs(struct diff_options *o)
5820{
5821 int i;
5822 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
5823 struct diff_queue_struct *q = &diff_queued_diff;
5824
5825 if (WSEH_NEW & WS_RULE_MASK)
5826 BUG("WS rules bit mask overlaps with diff symbol flags");
5827
5828 if (o->color_moved)
5829 o->emitted_symbols = &esm;
5830
5831 for (i = 0; i < q->nr; i++) {
5832 struct diff_filepair *p = q->queue[i];
5833 if (check_pair_status(p))
5834 diff_flush_patch(p, o);
5835 }
5836
5837 if (o->emitted_symbols) {
5838 if (o->color_moved) {
5839 struct hashmap add_lines, del_lines;
5840
5841 if (o->color_moved_ws_handling &
5842 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
5843 o->color_moved_ws_handling |= XDF_IGNORE_WHITESPACE;
5844
5845 hashmap_init(&del_lines, moved_entry_cmp, o, 0);
5846 hashmap_init(&add_lines, moved_entry_cmp, o, 0);
5847
5848 add_lines_to_move_detection(o, &add_lines, &del_lines);
5849 mark_color_as_moved(o, &add_lines, &del_lines);
5850 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
5851 dim_moved_lines(o);
5852
5853 hashmap_free(&add_lines, 0);
5854 hashmap_free(&del_lines, 0);
5855 }
5856
5857 for (i = 0; i < esm.nr; i++)
5858 emit_diff_symbol_from_struct(o, &esm.buf[i]);
5859
5860 for (i = 0; i < esm.nr; i++)
5861 free((void *)esm.buf[i].line);
5862 }
5863 esm.nr = 0;
5864}
5865
5866void diff_flush(struct diff_options *options)
5867{
5868 struct diff_queue_struct *q = &diff_queued_diff;
5869 int i, output_format = options->output_format;
5870 int separator = 0;
5871 int dirstat_by_line = 0;
5872
5873 /*
5874 * Order: raw, stat, summary, patch
5875 * or: name/name-status/checkdiff (other bits clear)
5876 */
5877 if (!q->nr)
5878 goto free_queue;
5879
5880 if (output_format & (DIFF_FORMAT_RAW |
5881 DIFF_FORMAT_NAME |
5882 DIFF_FORMAT_NAME_STATUS |
5883 DIFF_FORMAT_CHECKDIFF)) {
5884 for (i = 0; i < q->nr; i++) {
5885 struct diff_filepair *p = q->queue[i];
5886 if (check_pair_status(p))
5887 flush_one_pair(p, options);
5888 }
5889 separator++;
5890 }
5891
5892 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
5893 dirstat_by_line = 1;
5894
5895 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
5896 dirstat_by_line) {
5897 struct diffstat_t diffstat;
5898
5899 memset(&diffstat, 0, sizeof(struct diffstat_t));
5900 for (i = 0; i < q->nr; i++) {
5901 struct diff_filepair *p = q->queue[i];
5902 if (check_pair_status(p))
5903 diff_flush_stat(p, options, &diffstat);
5904 }
5905 if (output_format & DIFF_FORMAT_NUMSTAT)
5906 show_numstat(&diffstat, options);
5907 if (output_format & DIFF_FORMAT_DIFFSTAT)
5908 show_stats(&diffstat, options);
5909 if (output_format & DIFF_FORMAT_SHORTSTAT)
5910 show_shortstats(&diffstat, options);
5911 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
5912 show_dirstat_by_line(&diffstat, options);
5913 free_diffstat_info(&diffstat);
5914 separator++;
5915 }
5916 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
5917 show_dirstat(options);
5918
5919 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
5920 for (i = 0; i < q->nr; i++) {
5921 diff_summary(options, q->queue[i]);
5922 }
5923 separator++;
5924 }
5925
5926 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
5927 options->flags.exit_with_status &&
5928 options->flags.diff_from_contents) {
5929 /*
5930 * run diff_flush_patch for the exit status. setting
5931 * options->file to /dev/null should be safe, because we
5932 * aren't supposed to produce any output anyway.
5933 */
5934 if (options->close_file)
5935 fclose(options->file);
5936 options->file = xfopen("/dev/null", "w");
5937 options->close_file = 1;
5938 options->color_moved = 0;
5939 for (i = 0; i < q->nr; i++) {
5940 struct diff_filepair *p = q->queue[i];
5941 if (check_pair_status(p))
5942 diff_flush_patch(p, options);
5943 if (options->found_changes)
5944 break;
5945 }
5946 }
5947
5948 if (output_format & DIFF_FORMAT_PATCH) {
5949 if (separator) {
5950 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
5951 if (options->stat_sep)
5952 /* attach patch instead of inline */
5953 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
5954 NULL, 0, 0);
5955 }
5956
5957 diff_flush_patch_all_file_pairs(options);
5958 }
5959
5960 if (output_format & DIFF_FORMAT_CALLBACK)
5961 options->format_callback(q, options, options->format_callback_data);
5962
5963 for (i = 0; i < q->nr; i++)
5964 diff_free_filepair(q->queue[i]);
5965free_queue:
5966 free(q->queue);
5967 DIFF_QUEUE_CLEAR(q);
5968 if (options->close_file)
5969 fclose(options->file);
5970
5971 /*
5972 * Report the content-level differences with HAS_CHANGES;
5973 * diff_addremove/diff_change does not set the bit when
5974 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
5975 */
5976 if (options->flags.diff_from_contents) {
5977 if (options->found_changes)
5978 options->flags.has_changes = 1;
5979 else
5980 options->flags.has_changes = 0;
5981 }
5982}
5983
5984static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
5985{
5986 return (((p->status == DIFF_STATUS_MODIFIED) &&
5987 ((p->score &&
5988 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
5989 (!p->score &&
5990 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
5991 ((p->status != DIFF_STATUS_MODIFIED) &&
5992 filter_bit_tst(p->status, options)));
5993}
5994
5995static void diffcore_apply_filter(struct diff_options *options)
5996{
5997 int i;
5998 struct diff_queue_struct *q = &diff_queued_diff;
5999 struct diff_queue_struct outq;
6000
6001 DIFF_QUEUE_CLEAR(&outq);
6002
6003 if (!options->filter)
6004 return;
6005
6006 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6007 int found;
6008 for (i = found = 0; !found && i < q->nr; i++) {
6009 if (match_filter(options, q->queue[i]))
6010 found++;
6011 }
6012 if (found)
6013 return;
6014
6015 /* otherwise we will clear the whole queue
6016 * by copying the empty outq at the end of this
6017 * function, but first clear the current entries
6018 * in the queue.
6019 */
6020 for (i = 0; i < q->nr; i++)
6021 diff_free_filepair(q->queue[i]);
6022 }
6023 else {
6024 /* Only the matching ones */
6025 for (i = 0; i < q->nr; i++) {
6026 struct diff_filepair *p = q->queue[i];
6027 if (match_filter(options, p))
6028 diff_q(&outq, p);
6029 else
6030 diff_free_filepair(p);
6031 }
6032 }
6033 free(q->queue);
6034 *q = outq;
6035}
6036
6037/* Check whether two filespecs with the same mode and size are identical */
6038static int diff_filespec_is_identical(struct diff_filespec *one,
6039 struct diff_filespec *two)
6040{
6041 if (S_ISGITLINK(one->mode))
6042 return 0;
6043 if (diff_populate_filespec(one, 0))
6044 return 0;
6045 if (diff_populate_filespec(two, 0))
6046 return 0;
6047 return !memcmp(one->data, two->data, one->size);
6048}
6049
6050static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
6051{
6052 if (p->done_skip_stat_unmatch)
6053 return p->skip_stat_unmatch_result;
6054
6055 p->done_skip_stat_unmatch = 1;
6056 p->skip_stat_unmatch_result = 0;
6057 /*
6058 * 1. Entries that come from stat info dirtiness
6059 * always have both sides (iow, not create/delete),
6060 * one side of the object name is unknown, with
6061 * the same mode and size. Keep the ones that
6062 * do not match these criteria. They have real
6063 * differences.
6064 *
6065 * 2. At this point, the file is known to be modified,
6066 * with the same mode and size, and the object
6067 * name of one side is unknown. Need to inspect
6068 * the identical contents.
6069 */
6070 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6071 !DIFF_FILE_VALID(p->two) ||
6072 (p->one->oid_valid && p->two->oid_valid) ||
6073 (p->one->mode != p->two->mode) ||
6074 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
6075 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
6076 (p->one->size != p->two->size) ||
6077 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
6078 p->skip_stat_unmatch_result = 1;
6079 return p->skip_stat_unmatch_result;
6080}
6081
6082static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6083{
6084 int i;
6085 struct diff_queue_struct *q = &diff_queued_diff;
6086 struct diff_queue_struct outq;
6087 DIFF_QUEUE_CLEAR(&outq);
6088
6089 for (i = 0; i < q->nr; i++) {
6090 struct diff_filepair *p = q->queue[i];
6091
6092 if (diff_filespec_check_stat_unmatch(p))
6093 diff_q(&outq, p);
6094 else {
6095 /*
6096 * The caller can subtract 1 from skip_stat_unmatch
6097 * to determine how many paths were dirty only
6098 * due to stat info mismatch.
6099 */
6100 if (!diffopt->flags.no_index)
6101 diffopt->skip_stat_unmatch++;
6102 diff_free_filepair(p);
6103 }
6104 }
6105 free(q->queue);
6106 *q = outq;
6107}
6108
6109static int diffnamecmp(const void *a_, const void *b_)
6110{
6111 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6112 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6113 const char *name_a, *name_b;
6114
6115 name_a = a->one ? a->one->path : a->two->path;
6116 name_b = b->one ? b->one->path : b->two->path;
6117 return strcmp(name_a, name_b);
6118}
6119
6120void diffcore_fix_diff_index(struct diff_options *options)
6121{
6122 struct diff_queue_struct *q = &diff_queued_diff;
6123 QSORT(q->queue, q->nr, diffnamecmp);
6124}
6125
6126void diffcore_std(struct diff_options *options)
6127{
6128 /* NOTE please keep the following in sync with diff_tree_combined() */
6129 if (options->skip_stat_unmatch)
6130 diffcore_skip_stat_unmatch(options);
6131 if (!options->found_follow) {
6132 /* See try_to_follow_renames() in tree-diff.c */
6133 if (options->break_opt != -1)
6134 diffcore_break(options->break_opt);
6135 if (options->detect_rename)
6136 diffcore_rename(options);
6137 if (options->break_opt != -1)
6138 diffcore_merge_broken();
6139 }
6140 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6141 diffcore_pickaxe(options);
6142 if (options->orderfile)
6143 diffcore_order(options->orderfile);
6144 if (!options->found_follow)
6145 /* See try_to_follow_renames() in tree-diff.c */
6146 diff_resolve_rename_copy();
6147 diffcore_apply_filter(options);
6148
6149 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6150 options->flags.has_changes = 1;
6151 else
6152 options->flags.has_changes = 0;
6153
6154 options->found_follow = 0;
6155}
6156
6157int diff_result_code(struct diff_options *opt, int status)
6158{
6159 int result = 0;
6160
6161 diff_warn_rename_limit("diff.renameLimit",
6162 opt->needed_rename_limit,
6163 opt->degraded_cc_to_c);
6164 if (!opt->flags.exit_with_status &&
6165 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6166 return status;
6167 if (opt->flags.exit_with_status &&
6168 opt->flags.has_changes)
6169 result |= 01;
6170 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6171 opt->flags.check_failed)
6172 result |= 02;
6173 return result;
6174}
6175
6176int diff_can_quit_early(struct diff_options *opt)
6177{
6178 return (opt->flags.quick &&
6179 !opt->filter &&
6180 opt->flags.has_changes);
6181}
6182
6183/*
6184 * Shall changes to this submodule be ignored?
6185 *
6186 * Submodule changes can be configured to be ignored separately for each path,
6187 * but that configuration can be overridden from the command line.
6188 */
6189static int is_submodule_ignored(const char *path, struct diff_options *options)
6190{
6191 int ignored = 0;
6192 struct diff_flags orig_flags = options->flags;
6193 if (!options->flags.override_submodule_config)
6194 set_diffopt_flags_from_submodule_config(options, path);
6195 if (options->flags.ignore_submodules)
6196 ignored = 1;
6197 options->flags = orig_flags;
6198 return ignored;
6199}
6200
6201void diff_addremove(struct diff_options *options,
6202 int addremove, unsigned mode,
6203 const struct object_id *oid,
6204 int oid_valid,
6205 const char *concatpath, unsigned dirty_submodule)
6206{
6207 struct diff_filespec *one, *two;
6208
6209 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6210 return;
6211
6212 /* This may look odd, but it is a preparation for
6213 * feeding "there are unchanged files which should
6214 * not produce diffs, but when you are doing copy
6215 * detection you would need them, so here they are"
6216 * entries to the diff-core. They will be prefixed
6217 * with something like '=' or '*' (I haven't decided
6218 * which but should not make any difference).
6219 * Feeding the same new and old to diff_change()
6220 * also has the same effect.
6221 * Before the final output happens, they are pruned after
6222 * merged into rename/copy pairs as appropriate.
6223 */
6224 if (options->flags.reverse_diff)
6225 addremove = (addremove == '+' ? '-' :
6226 addremove == '-' ? '+' : addremove);
6227
6228 if (options->prefix &&
6229 strncmp(concatpath, options->prefix, options->prefix_length))
6230 return;
6231
6232 one = alloc_filespec(concatpath);
6233 two = alloc_filespec(concatpath);
6234
6235 if (addremove != '+')
6236 fill_filespec(one, oid, oid_valid, mode);
6237 if (addremove != '-') {
6238 fill_filespec(two, oid, oid_valid, mode);
6239 two->dirty_submodule = dirty_submodule;
6240 }
6241
6242 diff_queue(&diff_queued_diff, one, two);
6243 if (!options->flags.diff_from_contents)
6244 options->flags.has_changes = 1;
6245}
6246
6247void diff_change(struct diff_options *options,
6248 unsigned old_mode, unsigned new_mode,
6249 const struct object_id *old_oid,
6250 const struct object_id *new_oid,
6251 int old_oid_valid, int new_oid_valid,
6252 const char *concatpath,
6253 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6254{
6255 struct diff_filespec *one, *two;
6256 struct diff_filepair *p;
6257
6258 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6259 is_submodule_ignored(concatpath, options))
6260 return;
6261
6262 if (options->flags.reverse_diff) {
6263 SWAP(old_mode, new_mode);
6264 SWAP(old_oid, new_oid);
6265 SWAP(old_oid_valid, new_oid_valid);
6266 SWAP(old_dirty_submodule, new_dirty_submodule);
6267 }
6268
6269 if (options->prefix &&
6270 strncmp(concatpath, options->prefix, options->prefix_length))
6271 return;
6272
6273 one = alloc_filespec(concatpath);
6274 two = alloc_filespec(concatpath);
6275 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6276 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6277 one->dirty_submodule = old_dirty_submodule;
6278 two->dirty_submodule = new_dirty_submodule;
6279 p = diff_queue(&diff_queued_diff, one, two);
6280
6281 if (options->flags.diff_from_contents)
6282 return;
6283
6284 if (options->flags.quick && options->skip_stat_unmatch &&
6285 !diff_filespec_check_stat_unmatch(p))
6286 return;
6287
6288 options->flags.has_changes = 1;
6289}
6290
6291struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6292{
6293 struct diff_filepair *pair;
6294 struct diff_filespec *one, *two;
6295
6296 if (options->prefix &&
6297 strncmp(path, options->prefix, options->prefix_length))
6298 return NULL;
6299
6300 one = alloc_filespec(path);
6301 two = alloc_filespec(path);
6302 pair = diff_queue(&diff_queued_diff, one, two);
6303 pair->is_unmerged = 1;
6304 return pair;
6305}
6306
6307static char *run_textconv(const char *pgm, struct diff_filespec *spec,
6308 size_t *outsize)
6309{
6310 struct diff_tempfile *temp;
6311 const char *argv[3];
6312 const char **arg = argv;
6313 struct child_process child = CHILD_PROCESS_INIT;
6314 struct strbuf buf = STRBUF_INIT;
6315 int err = 0;
6316
6317 temp = prepare_temp_file(spec->path, spec);
6318 *arg++ = pgm;
6319 *arg++ = temp->name;
6320 *arg = NULL;
6321
6322 child.use_shell = 1;
6323 child.argv = argv;
6324 child.out = -1;
6325 if (start_command(&child)) {
6326 remove_tempfile();
6327 return NULL;
6328 }
6329
6330 if (strbuf_read(&buf, child.out, 0) < 0)
6331 err = error("error reading from textconv command '%s'", pgm);
6332 close(child.out);
6333
6334 if (finish_command(&child) || err) {
6335 strbuf_release(&buf);
6336 remove_tempfile();
6337 return NULL;
6338 }
6339 remove_tempfile();
6340
6341 return strbuf_detach(&buf, outsize);
6342}
6343
6344size_t fill_textconv(struct userdiff_driver *driver,
6345 struct diff_filespec *df,
6346 char **outbuf)
6347{
6348 size_t size;
6349
6350 if (!driver) {
6351 if (!DIFF_FILE_VALID(df)) {
6352 *outbuf = "";
6353 return 0;
6354 }
6355 if (diff_populate_filespec(df, 0))
6356 die("unable to read files to diff");
6357 *outbuf = df->data;
6358 return df->size;
6359 }
6360
6361 if (!driver->textconv)
6362 BUG("fill_textconv called with non-textconv driver");
6363
6364 if (driver->textconv_cache && df->oid_valid) {
6365 *outbuf = notes_cache_get(driver->textconv_cache,
6366 &df->oid,
6367 &size);
6368 if (*outbuf)
6369 return size;
6370 }
6371
6372 *outbuf = run_textconv(driver->textconv, df, &size);
6373 if (!*outbuf)
6374 die("unable to read files to diff");
6375
6376 if (driver->textconv_cache && df->oid_valid) {
6377 /* ignore errors, as we might be in a readonly repository */
6378 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6379 size);
6380 /*
6381 * we could save up changes and flush them all at the end,
6382 * but we would need an extra call after all diffing is done.
6383 * Since generating a cache entry is the slow path anyway,
6384 * this extra overhead probably isn't a big deal.
6385 */
6386 notes_cache_write(driver->textconv_cache);
6387 }
6388
6389 return size;
6390}
6391
6392int textconv_object(const char *path,
6393 unsigned mode,
6394 const struct object_id *oid,
6395 int oid_valid,
6396 char **buf,
6397 unsigned long *buf_size)
6398{
6399 struct diff_filespec *df;
6400 struct userdiff_driver *textconv;
6401
6402 df = alloc_filespec(path);
6403 fill_filespec(df, oid, oid_valid, mode);
6404 textconv = get_textconv(df);
6405 if (!textconv) {
6406 free_filespec(df);
6407 return 0;
6408 }
6409
6410 *buf_size = fill_textconv(textconv, df, buf);
6411 free_filespec(df);
6412 return 1;
6413}
6414
6415void setup_diff_pager(struct diff_options *opt)
6416{
6417 /*
6418 * If the user asked for our exit code, then either they want --quiet
6419 * or --exit-code. We should definitely not bother with a pager in the
6420 * former case, as we will generate no output. Since we still properly
6421 * report our exit code even when a pager is run, we _could_ run a
6422 * pager with --exit-code. But since we have not done so historically,
6423 * and because it is easy to find people oneline advising "git diff
6424 * --exit-code" in hooks and other scripts, we do not do so.
6425 */
6426 if (!opt->flags.exit_with_status &&
6427 check_pager_config("diff") != 0)
6428 setup_pager();
6429}