interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / diff.c

7846 lines · 222169 bytes Raw Blame History
1/*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4
5#define USE_THE_REPOSITORY_VARIABLE
6#define DISABLE_SIGN_COMPARE_WARNINGS
7
8#include "git-compat-util.h"
9#include "abspath.h"
10#include "base85.h"
11#include "config.h"
12#include "convert.h"
13#include "environment.h"
14#include "gettext.h"
15#include "tempfile.h"
16#include "revision.h"
17#include "quote.h"
18#include "diff.h"
19#include "diffcore.h"
20#include "delta.h"
21#include "hex.h"
22#include "xdiff-interface.h"
23#include "color.h"
24#include "run-command.h"
25#include "utf8.h"
26#include "odb.h"
27#include "userdiff.h"
28#include "submodule.h"
29#include "hashmap.h"
30#include "mem-pool.h"
31#include "merge-ll.h"
32#include "string-list.h"
33#include "strvec.h"
34#include "tmp-objdir.h"
35#include "graph.h"
36#include "oid-array.h"
37#include "packfile.h"
38#include "pager.h"
39#include "parse-options.h"
40#include "help.h"
41#include "promisor-remote.h"
42#include "dir.h"
43#include "object-file.h"
44#include "object-name.h"
45#include "read-cache-ll.h"
46#include "setup.h"
47#include "strmap.h"
48#include "ws.h"
49
50#ifdef NO_FAST_WORKING_DIRECTORY
51#define FAST_WORKING_DIRECTORY 0
52#else
53#define FAST_WORKING_DIRECTORY 1
54#endif
55
56static int diff_detect_rename_default;
57static int diff_indent_heuristic = 1;
58static int diff_rename_limit_default = 1000;
59static int diff_suppress_blank_empty;
60static enum git_colorbool diff_use_color_default = GIT_COLOR_UNKNOWN;
61static int diff_color_moved_default;
62static int diff_color_moved_ws_default;
63static unsigned int diff_context_default = 3;
64static unsigned int diff_interhunk_context_default;
65static char *diff_word_regex_cfg;
66static struct external_diff external_diff_cfg;
67static char *diff_order_file_cfg;
68int diff_auto_refresh_index = 1;
69static int diff_mnemonic_prefix;
70static int diff_no_prefix;
71static char *diff_src_prefix;
72static char *diff_dst_prefix;
73static int diff_relative;
74static int diff_stat_name_width;
75static int diff_stat_graph_width;
76static int diff_dirstat_permille_default = 30;
77static struct diff_options default_diff_options;
78static long diff_algorithm;
79static unsigned ws_error_highlight_default = WSEH_NEW;
80
81static char diff_colors[][COLOR_MAXLEN] = {
82 GIT_COLOR_RESET,
83 GIT_COLOR_NORMAL, /* CONTEXT */
84 GIT_COLOR_BOLD, /* METAINFO */
85 GIT_COLOR_CYAN, /* FRAGINFO */
86 GIT_COLOR_RED, /* OLD */
87 GIT_COLOR_GREEN, /* NEW */
88 GIT_COLOR_YELLOW, /* COMMIT */
89 GIT_COLOR_BG_RED, /* WHITESPACE */
90 GIT_COLOR_NORMAL, /* FUNCINFO */
91 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
92 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
93 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
94 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
95 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
96 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
97 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
98 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
99 GIT_COLOR_FAINT, /* CONTEXT_DIM */
100 GIT_COLOR_FAINT_RED, /* OLD_DIM */
101 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
102 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
103 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
104 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
105};
106
107static const char *color_diff_slots[] = {
108 [DIFF_CONTEXT] = "context",
109 [DIFF_METAINFO] = "meta",
110 [DIFF_FRAGINFO] = "frag",
111 [DIFF_FILE_OLD] = "old",
112 [DIFF_FILE_NEW] = "new",
113 [DIFF_COMMIT] = "commit",
114 [DIFF_WHITESPACE] = "whitespace",
115 [DIFF_FUNCINFO] = "func",
116 [DIFF_FILE_OLD_MOVED] = "oldMoved",
117 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
118 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
119 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
120 [DIFF_FILE_NEW_MOVED] = "newMoved",
121 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
122 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
123 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
124 [DIFF_CONTEXT_DIM] = "contextDimmed",
125 [DIFF_FILE_OLD_DIM] = "oldDimmed",
126 [DIFF_FILE_NEW_DIM] = "newDimmed",
127 [DIFF_CONTEXT_BOLD] = "contextBold",
128 [DIFF_FILE_OLD_BOLD] = "oldBold",
129 [DIFF_FILE_NEW_BOLD] = "newBold",
130};
131
132define_list_config_array_extra(color_diff_slots, {"plain"});
133
134static int parse_diff_color_slot(const char *var)
135{
136 if (!strcasecmp(var, "plain"))
137 return DIFF_CONTEXT;
138 return LOOKUP_CONFIG(color_diff_slots, var);
139}
140
141static int parse_dirstat_params(struct diff_options *options, const char *params_string,
142 struct strbuf *errmsg)
143{
144 char *params_copy = xstrdup(params_string);
145 struct string_list params = STRING_LIST_INIT_NODUP;
146 int ret = 0;
147 int i;
148
149 if (*params_copy)
150 string_list_split_in_place(&params, params_copy, ",", -1);
151 for (i = 0; i < params.nr; i++) {
152 const char *p = params.items[i].string;
153 if (!strcmp(p, "changes")) {
154 options->flags.dirstat_by_line = 0;
155 options->flags.dirstat_by_file = 0;
156 } else if (!strcmp(p, "lines")) {
157 options->flags.dirstat_by_line = 1;
158 options->flags.dirstat_by_file = 0;
159 } else if (!strcmp(p, "files")) {
160 options->flags.dirstat_by_line = 0;
161 options->flags.dirstat_by_file = 1;
162 } else if (!strcmp(p, "noncumulative")) {
163 options->flags.dirstat_cumulative = 0;
164 } else if (!strcmp(p, "cumulative")) {
165 options->flags.dirstat_cumulative = 1;
166 } else if (isdigit(*p)) {
167 char *end;
168 int permille = strtoul(p, &end, 10) * 10;
169 if (*end == '.' && isdigit(*++end)) {
170 /* only use first digit */
171 permille += *end - '0';
172 /* .. and ignore any further digits */
173 while (isdigit(*++end))
174 ; /* nothing */
175 }
176 if (!*end)
177 options->dirstat_permille = permille;
178 else {
179 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
180 p);
181 ret++;
182 }
183 } else {
184 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
185 ret++;
186 }
187
188 }
189 string_list_clear(&params, 0);
190 free(params_copy);
191 return ret;
192}
193
194static int parse_submodule_params(struct diff_options *options, const char *value)
195{
196 if (!strcmp(value, "log"))
197 options->submodule_format = DIFF_SUBMODULE_LOG;
198 else if (!strcmp(value, "short"))
199 options->submodule_format = DIFF_SUBMODULE_SHORT;
200 else if (!strcmp(value, "diff"))
201 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
202 /*
203 * Please update $__git_diff_submodule_formats in
204 * git-completion.bash when you add new formats.
205 */
206 else
207 return -1;
208 return 0;
209}
210
211int git_config_rename(const char *var, const char *value)
212{
213 if (!value)
214 return DIFF_DETECT_RENAME;
215 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
216 return DIFF_DETECT_COPY;
217 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
218}
219
220long parse_algorithm_value(const char *value)
221{
222 if (!value)
223 return -1;
224 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
225 return 0;
226 else if (!strcasecmp(value, "minimal"))
227 return XDF_NEED_MINIMAL;
228 else if (!strcasecmp(value, "patience"))
229 return XDF_PATIENCE_DIFF;
230 else if (!strcasecmp(value, "histogram"))
231 return XDF_HISTOGRAM_DIFF;
232 /*
233 * Please update $__git_diff_algorithms in git-completion.bash
234 * when you add new algorithms.
235 */
236 return -1;
237}
238
239static int parse_one_token(const char **arg, const char *token)
240{
241 const char *rest;
242 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
243 *arg = rest;
244 return 1;
245 }
246 return 0;
247}
248
249static int parse_ws_error_highlight(const char *arg)
250{
251 const char *orig_arg = arg;
252 unsigned val = 0;
253
254 while (*arg) {
255 if (parse_one_token(&arg, "none"))
256 val = 0;
257 else if (parse_one_token(&arg, "default"))
258 val = WSEH_NEW;
259 else if (parse_one_token(&arg, "all"))
260 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
261 else if (parse_one_token(&arg, "new"))
262 val |= WSEH_NEW;
263 else if (parse_one_token(&arg, "old"))
264 val |= WSEH_OLD;
265 else if (parse_one_token(&arg, "context"))
266 val |= WSEH_CONTEXT;
267 else {
268 return -1 - (int)(arg - orig_arg);
269 }
270 if (*arg)
271 arg++;
272 }
273 return val;
274}
275
276/*
277 * These are to give UI layer defaults.
278 * The core-level commands such as git-diff-files should
279 * never be affected by the setting of diff.renames
280 * the user happens to have in the configuration file.
281 */
282void init_diff_ui_defaults(void)
283{
284 diff_detect_rename_default = DIFF_DETECT_RENAME;
285}
286
287int git_diff_heuristic_config(const char *var, const char *value,
288 void *cb UNUSED)
289{
290 if (!strcmp(var, "diff.indentheuristic"))
291 diff_indent_heuristic = git_config_bool(var, value);
292 return 0;
293}
294
295static int parse_color_moved(const char *arg)
296{
297 switch (git_parse_maybe_bool(arg)) {
298 case 0:
299 return COLOR_MOVED_NO;
300 case 1:
301 return COLOR_MOVED_DEFAULT;
302 default:
303 break;
304 }
305
306 if (!strcmp(arg, "no"))
307 return COLOR_MOVED_NO;
308 else if (!strcmp(arg, "plain"))
309 return COLOR_MOVED_PLAIN;
310 else if (!strcmp(arg, "blocks"))
311 return COLOR_MOVED_BLOCKS;
312 else if (!strcmp(arg, "zebra"))
313 return COLOR_MOVED_ZEBRA;
314 else if (!strcmp(arg, "default"))
315 return COLOR_MOVED_DEFAULT;
316 else if (!strcmp(arg, "dimmed-zebra"))
317 return COLOR_MOVED_ZEBRA_DIM;
318 else if (!strcmp(arg, "dimmed_zebra"))
319 return COLOR_MOVED_ZEBRA_DIM;
320 else
321 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
322}
323
324static unsigned parse_color_moved_ws(const char *arg)
325{
326 int ret = 0;
327 struct string_list l = STRING_LIST_INIT_DUP;
328 struct string_list_item *i;
329
330 string_list_split_f(&l, arg, ",", -1, STRING_LIST_SPLIT_TRIM);
331
332 for_each_string_list_item(i, &l) {
333 if (!strcmp(i->string, "no"))
334 ret = 0;
335 else if (!strcmp(i->string, "ignore-space-change"))
336 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
337 else if (!strcmp(i->string, "ignore-space-at-eol"))
338 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
339 else if (!strcmp(i->string, "ignore-all-space"))
340 ret |= XDF_IGNORE_WHITESPACE;
341 else if (!strcmp(i->string, "allow-indentation-change"))
342 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
343 else {
344 ret |= COLOR_MOVED_WS_ERROR;
345 error(_("unknown color-moved-ws mode '%s', possible values are 'ignore-space-change', 'ignore-space-at-eol', 'ignore-all-space', 'allow-indentation-change'"), i->string);
346 }
347 }
348
349 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
350 (ret & XDF_WHITESPACE_FLAGS)) {
351 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
352 ret |= COLOR_MOVED_WS_ERROR;
353 }
354
355 string_list_clear(&l, 0);
356
357 return ret;
358}
359
360int git_diff_ui_config(const char *var, const char *value,
361 const struct config_context *ctx, void *cb)
362{
363 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
364 diff_use_color_default = git_config_colorbool(var, value);
365 return 0;
366 }
367 if (!strcmp(var, "diff.colormoved")) {
368 int cm = parse_color_moved(value);
369 if (cm < 0)
370 return -1;
371 diff_color_moved_default = cm;
372 return 0;
373 }
374 if (!strcmp(var, "diff.colormovedws")) {
375 unsigned cm;
376 if (!value)
377 return config_error_nonbool(var);
378 cm = parse_color_moved_ws(value);
379 if (cm & COLOR_MOVED_WS_ERROR)
380 return -1;
381 diff_color_moved_ws_default = cm;
382 return 0;
383 }
384 if (!strcmp(var, "diff.context")) {
385 int val = git_config_int(var, value, ctx->kvi);
386 if (val < 0)
387 return -1;
388 diff_context_default = val;
389 return 0;
390 }
391 if (!strcmp(var, "diff.interhunkcontext")) {
392 int val = git_config_int(var, value, ctx->kvi);
393 if (val < 0)
394 return -1;
395 diff_interhunk_context_default = val;
396 return 0;
397 }
398 if (!strcmp(var, "diff.renames")) {
399 diff_detect_rename_default = git_config_rename(var, value);
400 return 0;
401 }
402 if (!strcmp(var, "diff.autorefreshindex")) {
403 diff_auto_refresh_index = git_config_bool(var, value);
404 return 0;
405 }
406 if (!strcmp(var, "diff.mnemonicprefix")) {
407 diff_mnemonic_prefix = git_config_bool(var, value);
408 return 0;
409 }
410 if (!strcmp(var, "diff.noprefix")) {
411 diff_no_prefix = git_config_bool(var, value);
412 return 0;
413 }
414 if (!strcmp(var, "diff.srcprefix")) {
415 FREE_AND_NULL(diff_src_prefix);
416 return git_config_string(&diff_src_prefix, var, value);
417 }
418 if (!strcmp(var, "diff.dstprefix")) {
419 FREE_AND_NULL(diff_dst_prefix);
420 return git_config_string(&diff_dst_prefix, var, value);
421 }
422 if (!strcmp(var, "diff.relative")) {
423 diff_relative = git_config_bool(var, value);
424 return 0;
425 }
426 if (!strcmp(var, "diff.statnamewidth")) {
427 diff_stat_name_width = git_config_int(var, value, ctx->kvi);
428 return 0;
429 }
430 if (!strcmp(var, "diff.statgraphwidth")) {
431 diff_stat_graph_width = git_config_int(var, value, ctx->kvi);
432 return 0;
433 }
434 if (!strcmp(var, "diff.external"))
435 return git_config_string(&external_diff_cfg.cmd, var, value);
436 if (!strcmp(var, "diff.trustexitcode")) {
437 external_diff_cfg.trust_exit_code = git_config_bool(var, value);
438 return 0;
439 }
440 if (!strcmp(var, "diff.wordregex"))
441 return git_config_string(&diff_word_regex_cfg, var, value);
442 if (!strcmp(var, "diff.orderfile")) {
443 FREE_AND_NULL(diff_order_file_cfg);
444 return git_config_pathname(&diff_order_file_cfg, var, value);
445 }
446
447 if (!strcmp(var, "diff.ignoresubmodules")) {
448 if (!value)
449 return config_error_nonbool(var);
450 handle_ignore_submodules_arg(&default_diff_options, value);
451 }
452
453 if (!strcmp(var, "diff.submodule")) {
454 if (!value)
455 return config_error_nonbool(var);
456 if (parse_submodule_params(&default_diff_options, value))
457 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
458 value);
459 return 0;
460 }
461
462 if (!strcmp(var, "diff.algorithm")) {
463 if (!value)
464 return config_error_nonbool(var);
465 diff_algorithm = parse_algorithm_value(value);
466 if (diff_algorithm < 0)
467 return error(_("unknown value for config '%s': %s"),
468 var, value);
469 return 0;
470 }
471
472 if (git_color_config(var, value, cb) < 0)
473 return -1;
474
475 return git_diff_basic_config(var, value, ctx, cb);
476}
477
478int git_diff_basic_config(const char *var, const char *value,
479 const struct config_context *ctx, void *cb)
480{
481 const char *name;
482
483 if (!strcmp(var, "diff.renamelimit")) {
484 diff_rename_limit_default = git_config_int(var, value, ctx->kvi);
485 return 0;
486 }
487
488 if (userdiff_config(var, value) < 0)
489 return -1;
490
491 if (skip_prefix(var, "diff.color.", &name) ||
492 skip_prefix(var, "color.diff.", &name)) {
493 int slot = parse_diff_color_slot(name);
494 if (slot < 0)
495 return 0;
496 if (!value)
497 return config_error_nonbool(var);
498 return color_parse(value, diff_colors[slot]);
499 }
500
501 if (!strcmp(var, "diff.wserrorhighlight")) {
502 int val;
503 if (!value)
504 return config_error_nonbool(var);
505 val = parse_ws_error_highlight(value);
506 if (val < 0)
507 return error(_("unknown value for config '%s': %s"),
508 var, value);
509 ws_error_highlight_default = val;
510 return 0;
511 }
512
513 /* like GNU diff's --suppress-blank-empty option */
514 if (!strcmp(var, "diff.suppressblankempty") ||
515 /* for backwards compatibility */
516 !strcmp(var, "diff.suppress-blank-empty")) {
517 diff_suppress_blank_empty = git_config_bool(var, value);
518 return 0;
519 }
520
521 if (!strcmp(var, "diff.dirstat")) {
522 struct strbuf errmsg = STRBUF_INIT;
523 if (!value)
524 return config_error_nonbool(var);
525 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
526 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
527 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
528 errmsg.buf);
529 strbuf_release(&errmsg);
530 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
531 return 0;
532 }
533
534 if (git_diff_heuristic_config(var, value, cb) < 0)
535 return -1;
536
537 return git_default_config(var, value, ctx, cb);
538}
539
540static char *quote_two(const char *one, const char *two)
541{
542 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
543 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
544 struct strbuf res = STRBUF_INIT;
545
546 if (need_one + need_two) {
547 strbuf_addch(&res, '"');
548 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
549 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
550 strbuf_addch(&res, '"');
551 } else {
552 strbuf_addstr(&res, one);
553 strbuf_addstr(&res, two);
554 }
555 return strbuf_detach(&res, NULL);
556}
557
558static const struct external_diff *external_diff(void)
559{
560 static struct external_diff external_diff_env, *external_diff_ptr;
561 static int done_preparing = 0;
562
563 if (done_preparing)
564 return external_diff_ptr;
565 external_diff_env.cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
566 if (git_env_bool("GIT_EXTERNAL_DIFF_TRUST_EXIT_CODE", 0))
567 external_diff_env.trust_exit_code = 1;
568 if (external_diff_env.cmd)
569 external_diff_ptr = &external_diff_env;
570 else if (external_diff_cfg.cmd)
571 external_diff_ptr = &external_diff_cfg;
572 done_preparing = 1;
573 return external_diff_ptr;
574}
575
576/*
577 * Keep track of files used for diffing. Sometimes such an entry
578 * refers to a temporary file, sometimes to an existing file, and
579 * sometimes to "/dev/null".
580 */
581static struct diff_tempfile {
582 /*
583 * filename external diff should read from, or NULL if this
584 * entry is currently not in use:
585 */
586 const char *name;
587
588 char hex[GIT_MAX_HEXSZ + 1];
589 char mode[10];
590
591 /*
592 * If this diff_tempfile instance refers to a temporary file,
593 * this tempfile object is used to manage its lifetime.
594 */
595 struct tempfile *tempfile;
596} diff_temp[2];
597
598struct emit_callback {
599 int color_diff;
600 unsigned ws_rule;
601 int blank_at_eof_in_preimage;
602 int blank_at_eof_in_postimage;
603 int lno_in_preimage;
604 int lno_in_postimage;
605 int last_line_kind;
606 const char **label_path;
607 struct diff_words_data *diff_words;
608 struct diff_options *opt;
609 struct strbuf *header;
610};
611
612/*
613 * State for the line-range callback wrappers that sit between
614 * xdi_diff_outf() and fn_out_consume(). xdiff produces a normal,
615 * unfiltered diff; the wrappers intercept each hunk header and line,
616 * track post-image position, and forward only lines that fall within
617 * the requested ranges. Contiguous in-range lines are collected into
618 * range hunks and flushed with a synthetic @@ header so that
619 * fn_out_consume() sees well-formed unified-diff fragments.
620 *
621 * Removal lines ('-') cannot be classified by post-image position, so
622 * they are buffered in pending_rm until the next '+' or ' ' line
623 * reveals whether they precede an in-range line (flush into range hunk) or
624 * an out-of-range line (discard).
625 */
626struct line_range_callback {
627 xdiff_emit_line_fn orig_line_fn;
628 void *orig_cb_data;
629 const struct range_set *ranges; /* 0-based [start, end) */
630 unsigned int cur_range; /* index into the range_set */
631
632 /* Post/pre-image line counters (1-based, set from hunk headers) */
633 long lno_post;
634 long lno_pre;
635
636 /*
637 * Function name from most recent xdiff hunk header;
638 * size matches struct func_line.buf in xdiff/xemit.c.
639 */
640 char func[80];
641 long funclen;
642
643 /* Range hunk being accumulated for the current range */
644 struct strbuf rhunk;
645 long rhunk_old_begin, rhunk_old_count;
646 long rhunk_new_begin, rhunk_new_count;
647 int rhunk_active;
648 int rhunk_has_changes; /* any '+' or '-' lines? */
649
650 /* Removal lines not yet known to be in-range */
651 struct strbuf pending_rm;
652 int pending_rm_count;
653 long pending_rm_pre_begin; /* pre-image line of first pending */
654
655 int ret; /* latched error from orig_line_fn */
656};
657
658static int count_lines(const char *data, int size)
659{
660 int count, ch, completely_empty = 1, nl_just_seen = 0;
661 count = 0;
662 while (0 < size--) {
663 ch = *data++;
664 if (ch == '\n') {
665 count++;
666 nl_just_seen = 1;
667 completely_empty = 0;
668 }
669 else {
670 nl_just_seen = 0;
671 completely_empty = 0;
672 }
673 }
674 if (completely_empty)
675 return 0;
676 if (!nl_just_seen)
677 count++; /* no trailing newline */
678 return count;
679}
680
681static int fill_mmfile(struct repository *r, mmfile_t *mf,
682 struct diff_filespec *one)
683{
684 if (!DIFF_FILE_VALID(one)) {
685 mf->ptr = (char *)""; /* does not matter */
686 mf->size = 0;
687 return 0;
688 }
689 else if (diff_populate_filespec(r, one, NULL))
690 return -1;
691
692 mf->ptr = one->data;
693 mf->size = one->size;
694 return 0;
695}
696
697/* like fill_mmfile, but only for size, so we can avoid retrieving blob */
698static unsigned long diff_filespec_size(struct repository *r,
699 struct diff_filespec *one)
700{
701 struct diff_populate_filespec_options dpf_options = {
702 .check_size_only = 1,
703 };
704
705 if (!DIFF_FILE_VALID(one))
706 return 0;
707 diff_populate_filespec(r, one, &dpf_options);
708 return one->size;
709}
710
711static int count_trailing_blank(mmfile_t *mf)
712{
713 char *ptr = mf->ptr;
714 long size = mf->size;
715 int cnt = 0;
716
717 if (!size)
718 return cnt;
719 ptr += size - 1; /* pointing at the very end */
720 if (*ptr != '\n')
721 ; /* incomplete line */
722 else
723 ptr--; /* skip the last LF */
724 while (mf->ptr < ptr) {
725 char *prev_eol;
726 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
727 if (*prev_eol == '\n')
728 break;
729 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
730 break;
731 cnt++;
732 ptr = prev_eol - 1;
733 }
734 return cnt;
735}
736
737static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
738 struct emit_callback *ecbdata)
739{
740 int l1, l2, at;
741 l1 = count_trailing_blank(mf1);
742 l2 = count_trailing_blank(mf2);
743 if (l2 <= l1) {
744 ecbdata->blank_at_eof_in_preimage = 0;
745 ecbdata->blank_at_eof_in_postimage = 0;
746 return;
747 }
748 at = count_lines(mf1->ptr, mf1->size);
749 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
750
751 at = count_lines(mf2->ptr, mf2->size);
752 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
753}
754
755static void emit_line_0(struct diff_options *o,
756 const char *set_sign, const char *set, unsigned reverse, const char *reset,
757 int first, const char *line, int len)
758{
759 int has_trailing_newline, has_trailing_carriage_return;
760 int needs_reset = 0; /* at the end of the line */
761 FILE *file = o->file;
762
763 fputs(diff_line_prefix(o), file);
764
765 has_trailing_newline = (len > 0 && line[len-1] == '\n');
766 if (has_trailing_newline)
767 len--;
768
769 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
770 if (has_trailing_carriage_return)
771 len--;
772
773 if (!len && !first)
774 goto end_of_line;
775
776 if (reverse && want_color(o->use_color)) {
777 fputs(GIT_COLOR_REVERSE, file);
778 needs_reset = 1;
779 }
780
781 if (set_sign) {
782 fputs(set_sign, file);
783 needs_reset = 1;
784 }
785
786 if (first)
787 fputc(first, file);
788
789 if (!len)
790 goto end_of_line;
791
792 if (set) {
793 if (set_sign && set != set_sign)
794 fputs(reset, file);
795 fputs(set, file);
796 needs_reset = 1;
797 }
798 fwrite(line, len, 1, file);
799 needs_reset = 1; /* 'line' may contain color codes. */
800
801end_of_line:
802 if (needs_reset)
803 fputs(reset, file);
804 if (has_trailing_carriage_return)
805 fputc('\r', file);
806 if (has_trailing_newline)
807 fputc('\n', file);
808}
809
810static void emit_line(struct diff_options *o, const char *set, const char *reset,
811 const char *line, int len)
812{
813 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
814}
815
816enum diff_symbol {
817 DIFF_SYMBOL_BINARY_DIFF_HEADER,
818 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
819 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
820 DIFF_SYMBOL_BINARY_DIFF_BODY,
821 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
822 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
823 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
824 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
825 DIFF_SYMBOL_STATS_LINE,
826 DIFF_SYMBOL_WORD_DIFF,
827 DIFF_SYMBOL_STAT_SEP,
828 DIFF_SYMBOL_SUMMARY,
829 DIFF_SYMBOL_SUBMODULE_ADD,
830 DIFF_SYMBOL_SUBMODULE_DEL,
831 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
832 DIFF_SYMBOL_SUBMODULE_MODIFIED,
833 DIFF_SYMBOL_SUBMODULE_HEADER,
834 DIFF_SYMBOL_SUBMODULE_ERROR,
835 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
836 DIFF_SYMBOL_REWRITE_DIFF,
837 DIFF_SYMBOL_BINARY_FILES,
838 DIFF_SYMBOL_HEADER,
839 DIFF_SYMBOL_FILEPAIR_PLUS,
840 DIFF_SYMBOL_FILEPAIR_MINUS,
841 DIFF_SYMBOL_WORDS_PORCELAIN,
842 DIFF_SYMBOL_WORDS,
843 DIFF_SYMBOL_CONTEXT,
844 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
845 DIFF_SYMBOL_PLUS,
846 DIFF_SYMBOL_MINUS,
847 DIFF_SYMBOL_CONTEXT_FRAGINFO,
848 DIFF_SYMBOL_CONTEXT_MARKER,
849 DIFF_SYMBOL_SEPARATOR
850};
851
852/*
853 * Flags for content lines:
854 * 0..15 are whitespace rules (see ws.h)
855 * 16..18 are WSEH_NEW | WSEH_CONTEXT | WSEH_OLD
856 * 19 is marking if the line is blank at EOF
857 * 20..22 are used for color-moved.
858 */
859#define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<19)
860#define DIFF_SYMBOL_MOVED_LINE (1<<20)
861#define DIFF_SYMBOL_MOVED_LINE_ALT (1<<21)
862#define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<22)
863
864#define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
865
866/*
867 * This struct is used when we need to buffer the output of the diff output.
868 *
869 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
870 * into the pre/post image file. This pointer could be a union with the
871 * line pointer. By storing an offset into the file instead of the literal line,
872 * we can decrease the memory footprint for the buffered output. At first we
873 * may want to only have indirection for the content lines, but we could also
874 * enhance the state for emitting prefabricated lines, e.g. the similarity
875 * score line or hunk/file headers would only need to store a number or path
876 * and then the output can be constructed later on depending on state.
877 */
878struct emitted_diff_symbol {
879 const char *line;
880 int len;
881 int flags;
882 int indent_off; /* Offset to first non-whitespace character */
883 int indent_width; /* The visual width of the indentation */
884 unsigned id;
885 enum diff_symbol s;
886};
887#define EMITTED_DIFF_SYMBOL_INIT { 0 }
888
889struct emitted_diff_symbols {
890 struct emitted_diff_symbol *buf;
891 int nr, alloc;
892};
893#define EMITTED_DIFF_SYMBOLS_INIT { 0 }
894
895static void append_emitted_diff_symbol(struct diff_options *o,
896 struct emitted_diff_symbol *e)
897{
898 struct emitted_diff_symbol *f;
899
900 ALLOC_GROW(o->emitted_symbols->buf,
901 o->emitted_symbols->nr + 1,
902 o->emitted_symbols->alloc);
903 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
904
905 memcpy(f, e, sizeof(struct emitted_diff_symbol));
906 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
907}
908
909static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
910{
911 if (!e)
912 return;
913 free(e->buf);
914 free(e);
915}
916
917struct moved_entry {
918 const struct emitted_diff_symbol *es;
919 struct moved_entry *next_line;
920 struct moved_entry *next_match;
921};
922
923struct moved_block {
924 struct moved_entry *match;
925 int wsd; /* The whitespace delta of this block */
926};
927
928#define INDENT_BLANKLINE INT_MIN
929
930static void fill_es_indent_data(struct emitted_diff_symbol *es)
931{
932 unsigned int off = 0, i;
933 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
934 const char *s = es->line;
935 const int len = es->len;
936
937 /* skip any \v \f \r at start of indentation */
938 while (s[off] == '\f' || s[off] == '\v' ||
939 (off < len - 1 && s[off] == '\r'))
940 off++;
941
942 /* calculate the visual width of indentation */
943 while(1) {
944 if (s[off] == ' ') {
945 width++;
946 off++;
947 } else if (s[off] == '\t') {
948 width += tab_width - (width % tab_width);
949 while (s[++off] == '\t')
950 width += tab_width;
951 } else {
952 break;
953 }
954 }
955
956 /* check if this line is blank */
957 for (i = off; i < len; i++)
958 if (!isspace(s[i]))
959 break;
960
961 if (i == len) {
962 es->indent_width = INDENT_BLANKLINE;
963 es->indent_off = len;
964 } else {
965 es->indent_off = off;
966 es->indent_width = width;
967 }
968}
969
970static int compute_ws_delta(const struct emitted_diff_symbol *a,
971 const struct emitted_diff_symbol *b)
972{
973 int a_width = a->indent_width,
974 b_width = b->indent_width;
975
976 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
977 return INDENT_BLANKLINE;
978
979 return a_width - b_width;
980}
981
982static int cmp_in_block_with_wsd(const struct moved_entry *cur,
983 const struct emitted_diff_symbol *l,
984 struct moved_block *pmb)
985{
986 int a_width = cur->es->indent_width, b_width = l->indent_width;
987 int delta;
988
989 /* The text of each line must match */
990 if (cur->es->id != l->id)
991 return 1;
992
993 /*
994 * If 'l' and 'cur' are both blank then we don't need to check the
995 * indent. We only need to check cur as we know the strings match.
996 * */
997 if (a_width == INDENT_BLANKLINE)
998 return 0;
999
1000 /*
1001 * The indent changes of the block are known and stored in pmb->wsd;
1002 * however we need to check if the indent changes of the current line
1003 * match those of the current block.
1004 */
1005 delta = b_width - a_width;
1006
1007 /*
1008 * If the previous lines of this block were all blank then set its
1009 * whitespace delta.
1010 */
1011 if (pmb->wsd == INDENT_BLANKLINE)
1012 pmb->wsd = delta;
1013
1014 return delta != pmb->wsd;
1015}
1016
1017struct interned_diff_symbol {
1018 struct hashmap_entry ent;
1019 struct emitted_diff_symbol *es;
1020};
1021
1022static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
1023 const struct hashmap_entry *eptr,
1024 const struct hashmap_entry *entry_or_key,
1025 const void *keydata UNUSED)
1026{
1027 const struct diff_options *diffopt = hashmap_cmp_fn_data;
1028 const struct emitted_diff_symbol *a, *b;
1029 unsigned flags = diffopt->color_moved_ws_handling
1030 & XDF_WHITESPACE_FLAGS;
1031
1032 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
1033 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
1034
1035 return !xdiff_compare_lines(a->line + a->indent_off,
1036 a->len - a->indent_off,
1037 b->line + b->indent_off,
1038 b->len - b->indent_off, flags);
1039}
1040
1041static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
1042 struct interned_diff_symbol *s)
1043{
1044 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
1045 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
1046 l->len - l->indent_off, flags);
1047
1048 hashmap_entry_init(&s->ent, hash);
1049 s->es = l;
1050}
1051
1052struct moved_entry_list {
1053 struct moved_entry *add, *del;
1054};
1055
1056static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
1057 struct mem_pool *entry_mem_pool)
1058{
1059 struct moved_entry *prev_line = NULL;
1060 struct mem_pool interned_pool;
1061 struct hashmap interned_map;
1062 struct moved_entry_list *entry_list = NULL;
1063 size_t entry_list_alloc = 0;
1064 unsigned id = 0;
1065 int n;
1066
1067 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
1068 mem_pool_init(&interned_pool, 1024 * 1024);
1069
1070 for (n = 0; n < o->emitted_symbols->nr; n++) {
1071 struct interned_diff_symbol key;
1072 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1073 struct interned_diff_symbol *s;
1074 struct moved_entry *entry;
1075
1076 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
1077 prev_line = NULL;
1078 continue;
1079 }
1080
1081 if (o->color_moved_ws_handling &
1082 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1083 fill_es_indent_data(l);
1084
1085 prepare_entry(o, l, &key);
1086 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
1087 if (s) {
1088 l->id = s->es->id;
1089 } else {
1090 l->id = id;
1091 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
1092 hashmap_add(&interned_map,
1093 memcpy(mem_pool_alloc(&interned_pool,
1094 sizeof(key)),
1095 &key, sizeof(key)));
1096 }
1097 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
1098 entry->es = l;
1099 entry->next_line = NULL;
1100 if (prev_line && prev_line->es->s == l->s)
1101 prev_line->next_line = entry;
1102 prev_line = entry;
1103 if (l->s == DIFF_SYMBOL_PLUS) {
1104 entry->next_match = entry_list[l->id].add;
1105 entry_list[l->id].add = entry;
1106 } else {
1107 entry->next_match = entry_list[l->id].del;
1108 entry_list[l->id].del = entry;
1109 }
1110 }
1111
1112 hashmap_clear(&interned_map);
1113 mem_pool_discard(&interned_pool, 0);
1114
1115 return entry_list;
1116}
1117
1118static void pmb_advance_or_null(struct diff_options *o,
1119 struct emitted_diff_symbol *l,
1120 struct moved_block *pmb,
1121 int *pmb_nr)
1122{
1123 int i, j;
1124
1125 for (i = 0, j = 0; i < *pmb_nr; i++) {
1126 int match;
1127 struct moved_entry *prev = pmb[i].match;
1128 struct moved_entry *cur = (prev && prev->next_line) ?
1129 prev->next_line : NULL;
1130
1131 if (o->color_moved_ws_handling &
1132 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1133 match = cur &&
1134 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1135 else
1136 match = cur && cur->es->id == l->id;
1137
1138 if (match) {
1139 pmb[j] = pmb[i];
1140 pmb[j++].match = cur;
1141 }
1142 }
1143 *pmb_nr = j;
1144}
1145
1146static void fill_potential_moved_blocks(struct diff_options *o,
1147 struct moved_entry *match,
1148 struct emitted_diff_symbol *l,
1149 struct moved_block **pmb_p,
1150 int *pmb_alloc_p, int *pmb_nr_p)
1151
1152{
1153 struct moved_block *pmb = *pmb_p;
1154 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1155
1156 /*
1157 * The current line is the start of a new block.
1158 * Setup the set of potential blocks.
1159 */
1160 for (; match; match = match->next_match) {
1161 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1162 if (o->color_moved_ws_handling &
1163 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1164 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1165 else
1166 pmb[pmb_nr].wsd = 0;
1167 pmb[pmb_nr++].match = match;
1168 }
1169
1170 *pmb_p = pmb;
1171 *pmb_alloc_p = pmb_alloc;
1172 *pmb_nr_p = pmb_nr;
1173}
1174
1175/*
1176 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1177 *
1178 * Otherwise, if the last block has fewer alphanumeric characters than
1179 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1180 * that block.
1181 *
1182 * The last block consists of the (n - block_length)'th line up to but not
1183 * including the nth line.
1184 *
1185 * Returns 0 if the last block is empty or is unset by this function, non zero
1186 * otherwise.
1187 *
1188 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1189 * Think of a way to unify them.
1190 */
1191#define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1192 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1193static int adjust_last_block(struct diff_options *o, int n, int block_length)
1194{
1195 int i, alnum_count = 0;
1196 if (o->color_moved == COLOR_MOVED_PLAIN)
1197 return block_length;
1198 for (i = 1; i < block_length + 1; i++) {
1199 const char *c = o->emitted_symbols->buf[n - i].line;
1200 for (; *c; c++) {
1201 if (!isalnum(*c))
1202 continue;
1203 alnum_count++;
1204 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1205 return 1;
1206 }
1207 }
1208 for (i = 1; i < block_length + 1; i++)
1209 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1210 return 0;
1211}
1212
1213/* Find blocks of moved code, delegate actual coloring decision to helper */
1214static void mark_color_as_moved(struct diff_options *o,
1215 struct moved_entry_list *entry_list)
1216{
1217 struct moved_block *pmb = NULL; /* potentially moved blocks */
1218 int pmb_nr = 0, pmb_alloc = 0;
1219 int n, flipped_block = 0, block_length = 0;
1220 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1221
1222
1223 for (n = 0; n < o->emitted_symbols->nr; n++) {
1224 struct moved_entry *match = NULL;
1225 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1226
1227 switch (l->s) {
1228 case DIFF_SYMBOL_PLUS:
1229 match = entry_list[l->id].del;
1230 break;
1231 case DIFF_SYMBOL_MINUS:
1232 match = entry_list[l->id].add;
1233 break;
1234 default:
1235 flipped_block = 0;
1236 }
1237
1238 if (pmb_nr && (!match || l->s != moved_symbol)) {
1239 if (!adjust_last_block(o, n, block_length) &&
1240 block_length > 1) {
1241 /*
1242 * Rewind in case there is another match
1243 * starting at the second line of the block
1244 */
1245 match = NULL;
1246 n -= block_length;
1247 }
1248 pmb_nr = 0;
1249 block_length = 0;
1250 flipped_block = 0;
1251 }
1252 if (!match) {
1253 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1254 continue;
1255 }
1256
1257 if (o->color_moved == COLOR_MOVED_PLAIN) {
1258 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1259 continue;
1260 }
1261
1262 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1263
1264 if (pmb_nr == 0) {
1265 int contiguous = adjust_last_block(o, n, block_length);
1266
1267 if (!contiguous && block_length > 1)
1268 /*
1269 * Rewind in case there is another match
1270 * starting at the second line of the block
1271 */
1272 n -= block_length;
1273 else
1274 fill_potential_moved_blocks(o, match, l,
1275 &pmb, &pmb_alloc,
1276 &pmb_nr);
1277
1278 if (contiguous && pmb_nr && moved_symbol == l->s)
1279 flipped_block = (flipped_block + 1) % 2;
1280 else
1281 flipped_block = 0;
1282
1283 if (pmb_nr)
1284 moved_symbol = l->s;
1285 else
1286 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1287
1288 block_length = 0;
1289 }
1290
1291 if (pmb_nr) {
1292 block_length++;
1293 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1294 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1295 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1296 }
1297 }
1298 adjust_last_block(o, n, block_length);
1299
1300 free(pmb);
1301}
1302
1303static void dim_moved_lines(struct diff_options *o)
1304{
1305 int n;
1306 for (n = 0; n < o->emitted_symbols->nr; n++) {
1307 struct emitted_diff_symbol *prev = (n != 0) ?
1308 &o->emitted_symbols->buf[n - 1] : NULL;
1309 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1310 struct emitted_diff_symbol *next =
1311 (n < o->emitted_symbols->nr - 1) ?
1312 &o->emitted_symbols->buf[n + 1] : NULL;
1313
1314 /* Not a plus or minus line? */
1315 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1316 continue;
1317
1318 /* Not a moved line? */
1319 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1320 continue;
1321
1322 /*
1323 * If prev or next are not a plus or minus line,
1324 * pretend they don't exist
1325 */
1326 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1327 prev->s != DIFF_SYMBOL_MINUS)
1328 prev = NULL;
1329 if (next && next->s != DIFF_SYMBOL_PLUS &&
1330 next->s != DIFF_SYMBOL_MINUS)
1331 next = NULL;
1332
1333 /* Inside a block? */
1334 if ((prev &&
1335 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1336 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1337 (next &&
1338 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1339 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1340 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1341 continue;
1342 }
1343
1344 /* Check if we are at an interesting bound: */
1345 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1346 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1347 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1348 continue;
1349 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1350 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1351 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1352 continue;
1353
1354 /*
1355 * The boundary to prev and next are not interesting,
1356 * so this line is not interesting as a whole
1357 */
1358 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1359 }
1360}
1361
1362static void emit_line_ws_markup(struct diff_options *o,
1363 const char *set_sign, const char *set,
1364 const char *reset,
1365 int sign_index, const char *line, int len,
1366 unsigned ws_rule, int blank_at_eof)
1367{
1368 const char *ws = NULL;
1369 int sign = o->output_indicators[sign_index];
1370
1371 if (diff_suppress_blank_empty &&
1372 sign_index == OUTPUT_INDICATOR_CONTEXT &&
1373 len == 1 && line[0] == '\n')
1374 sign = 0;
1375
1376 if (o->ws_error_highlight & ws_rule) {
1377 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1378 if (!*ws)
1379 ws = NULL;
1380 }
1381
1382 if (!ws && !set_sign) {
1383 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1384 } else if (!ws) {
1385 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1386 } else if (blank_at_eof) {
1387 /* Blank line at EOF - paint '+' as well */
1388 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1389 } else {
1390 /* Emit just the prefix, then the rest. */
1391 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1392 sign, "", 0);
1393 ws_check_emit(line, len, ws_rule,
1394 o->file, set, reset, ws);
1395 }
1396}
1397
1398static void emit_diff_symbol_from_struct(struct diff_options *o,
1399 struct emitted_diff_symbol *eds)
1400{
1401 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1402
1403 enum diff_symbol s = eds->s;
1404 const char *line = eds->line;
1405 int len = eds->len;
1406 unsigned flags = eds->flags;
1407
1408 if (!o->file)
1409 return;
1410
1411 switch (s) {
1412 case DIFF_SYMBOL_SUBMODULE_HEADER:
1413 case DIFF_SYMBOL_SUBMODULE_ERROR:
1414 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1415 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1416 case DIFF_SYMBOL_SUMMARY:
1417 case DIFF_SYMBOL_STATS_LINE:
1418 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1419 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1420 emit_line(o, "", "", line, len);
1421 break;
1422 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1423 if ((flags & WS_INCOMPLETE_LINE) &&
1424 (flags & o->ws_error_highlight))
1425 set = diff_get_color_opt(o, DIFF_WHITESPACE);
1426 else
1427 set = diff_get_color_opt(o, DIFF_CONTEXT);
1428 reset = diff_get_color_opt(o, DIFF_RESET);
1429 emit_line(o, set, reset, line, len);
1430 break;
1431 case DIFF_SYMBOL_CONTEXT_MARKER:
1432 context = diff_get_color_opt(o, DIFF_CONTEXT);
1433 reset = diff_get_color_opt(o, DIFF_RESET);
1434 emit_line(o, context, reset, line, len);
1435 break;
1436 case DIFF_SYMBOL_SEPARATOR:
1437 fprintf(o->file, "%s%c",
1438 diff_line_prefix(o),
1439 o->line_termination);
1440 break;
1441 case DIFF_SYMBOL_CONTEXT:
1442 set = diff_get_color_opt(o, DIFF_CONTEXT);
1443 reset = diff_get_color_opt(o, DIFF_RESET);
1444 set_sign = NULL;
1445 if (o->flags.dual_color_diffed_diffs) {
1446 char c = !len ? 0 : line[0];
1447
1448 if (c == '+')
1449 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1450 else if (c == '@')
1451 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1452 else if (c == '-')
1453 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1454 }
1455 emit_line_ws_markup(o, set_sign, set, reset,
1456 OUTPUT_INDICATOR_CONTEXT, line, len,
1457 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1458 break;
1459 case DIFF_SYMBOL_PLUS:
1460 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1461 DIFF_SYMBOL_MOVED_LINE_ALT |
1462 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1463 case DIFF_SYMBOL_MOVED_LINE |
1464 DIFF_SYMBOL_MOVED_LINE_ALT |
1465 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1466 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1467 break;
1468 case DIFF_SYMBOL_MOVED_LINE |
1469 DIFF_SYMBOL_MOVED_LINE_ALT:
1470 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1471 break;
1472 case DIFF_SYMBOL_MOVED_LINE |
1473 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1474 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1475 break;
1476 case DIFF_SYMBOL_MOVED_LINE:
1477 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1478 break;
1479 default:
1480 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1481 }
1482 reset = diff_get_color_opt(o, DIFF_RESET);
1483 if (!o->flags.dual_color_diffed_diffs)
1484 set_sign = NULL;
1485 else {
1486 char c = !len ? 0 : line[0];
1487
1488 set_sign = set;
1489 if (c == '-')
1490 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1491 else if (c == '@')
1492 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1493 else if (c == '+')
1494 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1495 else
1496 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1497 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1498 }
1499 emit_line_ws_markup(o, set_sign, set, reset,
1500 OUTPUT_INDICATOR_NEW, line, len,
1501 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1502 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1503 break;
1504 case DIFF_SYMBOL_MINUS:
1505 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1506 DIFF_SYMBOL_MOVED_LINE_ALT |
1507 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1508 case DIFF_SYMBOL_MOVED_LINE |
1509 DIFF_SYMBOL_MOVED_LINE_ALT |
1510 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1511 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1512 break;
1513 case DIFF_SYMBOL_MOVED_LINE |
1514 DIFF_SYMBOL_MOVED_LINE_ALT:
1515 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1516 break;
1517 case DIFF_SYMBOL_MOVED_LINE |
1518 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1519 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1520 break;
1521 case DIFF_SYMBOL_MOVED_LINE:
1522 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1523 break;
1524 default:
1525 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1526 }
1527 reset = diff_get_color_opt(o, DIFF_RESET);
1528 if (!o->flags.dual_color_diffed_diffs)
1529 set_sign = NULL;
1530 else {
1531 char c = !len ? 0 : line[0];
1532
1533 set_sign = set;
1534 if (c == '+')
1535 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1536 else if (c == '@')
1537 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1538 else if (c == '-')
1539 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1540 else
1541 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1542 }
1543 emit_line_ws_markup(o, set_sign, set, reset,
1544 OUTPUT_INDICATOR_OLD, line, len,
1545 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1546 break;
1547 case DIFF_SYMBOL_WORDS_PORCELAIN:
1548 context = diff_get_color_opt(o, DIFF_CONTEXT);
1549 reset = diff_get_color_opt(o, DIFF_RESET);
1550 emit_line(o, context, reset, line, len);
1551 fputs("~\n", o->file);
1552 break;
1553 case DIFF_SYMBOL_WORDS:
1554 context = diff_get_color_opt(o, DIFF_CONTEXT);
1555 reset = diff_get_color_opt(o, DIFF_RESET);
1556
1557 /* Skip the prefix character */
1558 line++; len--;
1559 emit_line(o, context, reset, line, len);
1560 break;
1561 case DIFF_SYMBOL_FILEPAIR_PLUS:
1562 meta = diff_get_color_opt(o, DIFF_METAINFO);
1563 reset = diff_get_color_opt(o, DIFF_RESET);
1564 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1565 line, reset,
1566 strchr(line, ' ') ? "\t" : "");
1567 break;
1568 case DIFF_SYMBOL_FILEPAIR_MINUS:
1569 meta = diff_get_color_opt(o, DIFF_METAINFO);
1570 reset = diff_get_color_opt(o, DIFF_RESET);
1571 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1572 line, reset,
1573 strchr(line, ' ') ? "\t" : "");
1574 break;
1575 case DIFF_SYMBOL_BINARY_FILES:
1576 case DIFF_SYMBOL_HEADER:
1577 fprintf(o->file, "%s", line);
1578 break;
1579 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1580 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1581 break;
1582 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1583 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1584 break;
1585 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1586 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1587 break;
1588 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1589 fputs(diff_line_prefix(o), o->file);
1590 fputc('\n', o->file);
1591 break;
1592 case DIFF_SYMBOL_REWRITE_DIFF:
1593 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1594 reset = diff_get_color_opt(o, DIFF_RESET);
1595 emit_line(o, fraginfo, reset, line, len);
1596 break;
1597 case DIFF_SYMBOL_SUBMODULE_ADD:
1598 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1599 reset = diff_get_color_opt(o, DIFF_RESET);
1600 emit_line(o, set, reset, line, len);
1601 break;
1602 case DIFF_SYMBOL_SUBMODULE_DEL:
1603 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1604 reset = diff_get_color_opt(o, DIFF_RESET);
1605 emit_line(o, set, reset, line, len);
1606 break;
1607 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1608 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1609 diff_line_prefix(o), line);
1610 break;
1611 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1612 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1613 diff_line_prefix(o), line);
1614 break;
1615 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1616 emit_line(o, "", "", " 0 files changed\n",
1617 strlen(" 0 files changed\n"));
1618 break;
1619 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1620 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1621 break;
1622 case DIFF_SYMBOL_WORD_DIFF:
1623 fprintf(o->file, "%.*s", len, line);
1624 break;
1625 case DIFF_SYMBOL_STAT_SEP:
1626 fputs(o->stat_sep, o->file);
1627 break;
1628 default:
1629 BUG("unknown diff symbol");
1630 }
1631}
1632
1633static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1634 const char *line, int len, unsigned flags)
1635{
1636 struct emitted_diff_symbol e = {
1637 .line = line, .len = len, .flags = flags, .s = s
1638 };
1639
1640 if (o->emitted_symbols)
1641 append_emitted_diff_symbol(o, &e);
1642 else
1643 emit_diff_symbol_from_struct(o, &e);
1644}
1645
1646void diff_emit_submodule_del(struct diff_options *o, const char *line)
1647{
1648 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1649}
1650
1651void diff_emit_submodule_add(struct diff_options *o, const char *line)
1652{
1653 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1654}
1655
1656void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1657{
1658 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1659 path, strlen(path), 0);
1660}
1661
1662void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1663{
1664 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1665 path, strlen(path), 0);
1666}
1667
1668void diff_emit_submodule_header(struct diff_options *o, const char *header)
1669{
1670 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1671 header, strlen(header), 0);
1672}
1673
1674void diff_emit_submodule_error(struct diff_options *o, const char *err)
1675{
1676 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1677}
1678
1679void diff_emit_submodule_pipethrough(struct diff_options *o,
1680 const char *line, int len)
1681{
1682 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1683}
1684
1685static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1686{
1687 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1688 ecbdata->blank_at_eof_in_preimage &&
1689 ecbdata->blank_at_eof_in_postimage &&
1690 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1691 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1692 return 0;
1693 return ws_blank_line(line, len);
1694}
1695
1696static void emit_add_line(struct emit_callback *ecbdata,
1697 const char *line, int len)
1698{
1699 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1700 if (new_blank_line_at_eof(ecbdata, line, len))
1701 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1702
1703 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1704}
1705
1706static void emit_del_line(struct emit_callback *ecbdata,
1707 const char *line, int len)
1708{
1709 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1710 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1711}
1712
1713static void emit_context_line(struct emit_callback *ecbdata,
1714 const char *line, int len)
1715{
1716 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1717 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1718}
1719
1720static void emit_incomplete_line_marker(struct emit_callback *ecbdata,
1721 const char *line, int len)
1722{
1723 int last_line_kind = ecbdata->last_line_kind;
1724 unsigned flags = (last_line_kind == '+'
1725 ? WSEH_NEW
1726 : last_line_kind == '-'
1727 ? WSEH_OLD
1728 : WSEH_CONTEXT) | ecbdata->ws_rule;
1729 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
1730 line, len, flags);
1731}
1732
1733static void emit_hunk_header(struct emit_callback *ecbdata,
1734 const char *line, int len)
1735{
1736 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1737 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1738 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1739 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1740 const char *reverse = want_color(ecbdata->color_diff) ? GIT_COLOR_REVERSE : "";
1741 static const char atat[2] = { '@', '@' };
1742 const char *cp, *ep;
1743 struct strbuf msgbuf = STRBUF_INIT;
1744 int org_len = len;
1745 int i = 1;
1746
1747 /*
1748 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1749 * it always is at least 10 bytes long.
1750 */
1751 if (len < 10 ||
1752 memcmp(line, atat, 2) ||
1753 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1754 emit_diff_symbol(ecbdata->opt,
1755 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1756 return;
1757 }
1758 ep += 2; /* skip over @@ */
1759
1760 /* The hunk header in fraginfo color */
1761 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1762 strbuf_addstr(&msgbuf, reverse);
1763 strbuf_addstr(&msgbuf, frag);
1764 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1765 strbuf_add(&msgbuf, atat, sizeof(atat));
1766 else
1767 strbuf_add(&msgbuf, line, ep - line);
1768 strbuf_addstr(&msgbuf, reset);
1769
1770 /*
1771 * trailing "\r\n"
1772 */
1773 for ( ; i < 3; i++)
1774 if (line[len - i] == '\r' || line[len - i] == '\n')
1775 len--;
1776
1777 /* blank before the func header */
1778 for (cp = ep; ep - line < len; ep++)
1779 if (*ep != ' ' && *ep != '\t')
1780 break;
1781 if (ep != cp) {
1782 strbuf_addstr(&msgbuf, context);
1783 strbuf_add(&msgbuf, cp, ep - cp);
1784 strbuf_addstr(&msgbuf, reset);
1785 }
1786
1787 if (ep < line + len) {
1788 strbuf_addstr(&msgbuf, func);
1789 strbuf_add(&msgbuf, ep, line + len - ep);
1790 strbuf_addstr(&msgbuf, reset);
1791 }
1792
1793 strbuf_add(&msgbuf, line + len, org_len - len);
1794 strbuf_complete_line(&msgbuf);
1795 emit_diff_symbol(ecbdata->opt,
1796 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1797 strbuf_release(&msgbuf);
1798}
1799
1800static struct diff_tempfile *claim_diff_tempfile(void)
1801{
1802 int i;
1803 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1804 if (!diff_temp[i].name)
1805 return diff_temp + i;
1806 BUG("diff is failing to clean up its tempfiles");
1807}
1808
1809static void remove_tempfile(void)
1810{
1811 int i;
1812 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1813 if (is_tempfile_active(diff_temp[i].tempfile))
1814 delete_tempfile(&diff_temp[i].tempfile);
1815 diff_temp[i].name = NULL;
1816 }
1817}
1818
1819static void add_line_count(struct strbuf *out, int count)
1820{
1821 switch (count) {
1822 case 0:
1823 strbuf_addstr(out, "0,0");
1824 break;
1825 case 1:
1826 strbuf_addstr(out, "1");
1827 break;
1828 default:
1829 strbuf_addf(out, "1,%d", count);
1830 break;
1831 }
1832}
1833
1834static void emit_rewrite_lines(struct emit_callback *ecbdata,
1835 int prefix, const char *data, int size)
1836{
1837 const char *endp = NULL;
1838
1839 while (0 < size) {
1840 int len, plen;
1841 char *pdata = NULL;
1842
1843 endp = memchr(data, '\n', size);
1844
1845 if (endp) {
1846 len = endp - data + 1;
1847 plen = len;
1848 } else {
1849 len = size;
1850 plen = len + 1;
1851 pdata = xmalloc(plen + 2);
1852 memcpy(pdata, data, len);
1853 pdata[len] = '\n';
1854 pdata[len + 1] = '\0';
1855 }
1856 if (prefix != '+') {
1857 ecbdata->lno_in_preimage++;
1858 emit_del_line(ecbdata, pdata ? pdata : data, plen);
1859 } else {
1860 ecbdata->lno_in_postimage++;
1861 emit_add_line(ecbdata, pdata ? pdata : data, plen);
1862 }
1863 free(pdata);
1864 size -= len;
1865 data += len;
1866 }
1867 if (!endp) {
1868 static const char nneof[] = "\\ No newline at end of file\n";
1869 ecbdata->last_line_kind = prefix;
1870 emit_incomplete_line_marker(ecbdata, nneof, sizeof(nneof) - 1);
1871 }
1872}
1873
1874static void emit_rewrite_diff(const char *name_a,
1875 const char *name_b,
1876 struct diff_filespec *one,
1877 struct diff_filespec *two,
1878 struct userdiff_driver *textconv_one,
1879 struct userdiff_driver *textconv_two,
1880 struct diff_options *o)
1881{
1882 int lc_a, lc_b;
1883 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1884 const char *a_prefix, *b_prefix;
1885 char *data_one, *data_two;
1886 size_t size_one, size_two;
1887 unsigned ws_rule;
1888 struct emit_callback ecbdata;
1889 struct strbuf out = STRBUF_INIT;
1890
1891 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1892 a_prefix = o->b_prefix;
1893 b_prefix = o->a_prefix;
1894 } else {
1895 a_prefix = o->a_prefix;
1896 b_prefix = o->b_prefix;
1897 }
1898
1899 name_a += (*name_a == '/');
1900 name_b += (*name_b == '/');
1901
1902 strbuf_reset(&a_name);
1903 strbuf_reset(&b_name);
1904 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1905 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1906
1907 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1908 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1909
1910 ws_rule = whitespace_rule(o->repo->index, name_b);
1911
1912 /* symlink being an incomplete line is not a news */
1913 if (DIFF_FILE_VALID(two) && S_ISLNK(two->mode))
1914 ws_rule &= ~WS_INCOMPLETE_LINE;
1915
1916 memset(&ecbdata, 0, sizeof(ecbdata));
1917 ecbdata.color_diff = o->use_color;
1918 ecbdata.ws_rule = ws_rule;
1919 ecbdata.opt = o;
1920 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1921 mmfile_t mf1, mf2;
1922 mf1.ptr = (char *)data_one;
1923 mf2.ptr = (char *)data_two;
1924 mf1.size = size_one;
1925 mf2.size = size_two;
1926 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1927 }
1928 ecbdata.lno_in_preimage = 1;
1929 ecbdata.lno_in_postimage = 1;
1930
1931 lc_a = count_lines(data_one, size_one);
1932 lc_b = count_lines(data_two, size_two);
1933
1934 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1935 a_name.buf, a_name.len, 0);
1936 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1937 b_name.buf, b_name.len, 0);
1938
1939 strbuf_addstr(&out, "@@ -");
1940 if (!o->irreversible_delete)
1941 add_line_count(&out, lc_a);
1942 else
1943 strbuf_addstr(&out, "?,?");
1944 strbuf_addstr(&out, " +");
1945 add_line_count(&out, lc_b);
1946 strbuf_addstr(&out, " @@\n");
1947 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1948 strbuf_release(&out);
1949
1950 if (lc_a && !o->irreversible_delete)
1951 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1952 if (lc_b)
1953 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1954 if (textconv_one)
1955 free((char *)data_one);
1956 if (textconv_two)
1957 free((char *)data_two);
1958}
1959
1960struct diff_words_buffer {
1961 mmfile_t text;
1962 unsigned long alloc;
1963 struct diff_words_orig {
1964 const char *begin, *end;
1965 } *orig;
1966 int orig_nr, orig_alloc;
1967};
1968
1969static void diff_words_append(char *line, unsigned long len,
1970 struct diff_words_buffer *buffer)
1971{
1972 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1973 line++;
1974 len--;
1975 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1976 buffer->text.size += len;
1977 buffer->text.ptr[buffer->text.size] = '\0';
1978}
1979
1980struct diff_words_style_elem {
1981 const char *prefix;
1982 const char *suffix;
1983 const char *color; /* NULL; filled in by the setup code if
1984 * color is enabled */
1985};
1986
1987struct diff_words_style {
1988 enum diff_words_type type;
1989 struct diff_words_style_elem new_word, old_word, ctx;
1990 const char *newline;
1991};
1992
1993static struct diff_words_style diff_words_styles[] = {
1994 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1995 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1996 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1997};
1998
1999struct diff_words_data {
2000 struct diff_words_buffer minus, plus;
2001 const char *current_plus;
2002 int last_minus;
2003 struct diff_options *opt;
2004 regex_t *word_regex;
2005 enum diff_words_type type;
2006 struct diff_words_style *style;
2007};
2008
2009static int fn_out_diff_words_write_helper(struct diff_options *o,
2010 struct diff_words_style_elem *st_el,
2011 const char *newline,
2012 size_t count, const char *buf)
2013{
2014 int print = 0;
2015 struct strbuf sb = STRBUF_INIT;
2016
2017 while (count) {
2018 const char *p = memchr(buf, '\n', count);
2019 if (print)
2020 strbuf_addstr(&sb, diff_line_prefix(o));
2021
2022 if (p != buf) {
2023 const char *reset = st_el->color && *st_el->color ?
2024 GIT_COLOR_RESET : NULL;
2025 if (st_el->color && *st_el->color)
2026 strbuf_addstr(&sb, st_el->color);
2027 strbuf_addstr(&sb, st_el->prefix);
2028 strbuf_add(&sb, buf, p ? p - buf : count);
2029 strbuf_addstr(&sb, st_el->suffix);
2030 if (reset)
2031 strbuf_addstr(&sb, reset);
2032 }
2033 if (!p)
2034 goto out;
2035
2036 strbuf_addstr(&sb, newline);
2037 count -= p + 1 - buf;
2038 buf = p + 1;
2039 print = 1;
2040 if (count) {
2041 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
2042 sb.buf, sb.len, 0);
2043 strbuf_reset(&sb);
2044 }
2045 }
2046
2047out:
2048 if (sb.len)
2049 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
2050 sb.buf, sb.len, 0);
2051 strbuf_release(&sb);
2052 return 0;
2053}
2054
2055/*
2056 * '--color-words' algorithm can be described as:
2057 *
2058 * 1. collect the minus/plus lines of a diff hunk, divided into
2059 * minus-lines and plus-lines;
2060 *
2061 * 2. break both minus-lines and plus-lines into words and
2062 * place them into two mmfile_t with one word for each line;
2063 *
2064 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
2065 *
2066 * And for the common parts of the both file, we output the plus side text.
2067 * diff_words->current_plus is used to trace the current position of the plus file
2068 * which printed. diff_words->last_minus is used to trace the last minus word
2069 * printed.
2070 *
2071 * For '--graph' to work with '--color-words', we need to output the graph prefix
2072 * on each line of color words output. Generally, there are two conditions on
2073 * which we should output the prefix.
2074 *
2075 * 1. diff_words->last_minus == 0 &&
2076 * diff_words->current_plus == diff_words->plus.text.ptr
2077 *
2078 * that is: the plus text must start as a new line, and if there is no minus
2079 * word printed, a graph prefix must be printed.
2080 *
2081 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
2082 * *(diff_words->current_plus - 1) == '\n'
2083 *
2084 * that is: a graph prefix must be printed following a '\n'
2085 */
2086static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
2087{
2088 if ((diff_words->last_minus == 0 &&
2089 diff_words->current_plus == diff_words->plus.text.ptr) ||
2090 (diff_words->current_plus > diff_words->plus.text.ptr &&
2091 *(diff_words->current_plus - 1) == '\n')) {
2092 return 1;
2093 } else {
2094 return 0;
2095 }
2096}
2097
2098static void fn_out_diff_words_aux(void *priv,
2099 long minus_first, long minus_len,
2100 long plus_first, long plus_len,
2101 const char *func UNUSED, long funclen UNUSED)
2102{
2103 struct diff_words_data *diff_words = priv;
2104 struct diff_words_style *style = diff_words->style;
2105 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
2106 struct diff_options *opt = diff_words->opt;
2107 const char *line_prefix;
2108
2109 assert(opt);
2110 line_prefix = diff_line_prefix(opt);
2111
2112 /* POSIX requires that first be decremented by one if len == 0... */
2113 if (minus_len) {
2114 minus_begin = diff_words->minus.orig[minus_first].begin;
2115 minus_end =
2116 diff_words->minus.orig[minus_first + minus_len - 1].end;
2117 } else
2118 minus_begin = minus_end =
2119 diff_words->minus.orig[minus_first].end;
2120
2121 if (plus_len) {
2122 plus_begin = diff_words->plus.orig[plus_first].begin;
2123 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2124 } else
2125 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2126
2127 if (color_words_output_graph_prefix(diff_words)) {
2128 fputs(line_prefix, diff_words->opt->file);
2129 }
2130 if (diff_words->current_plus != plus_begin) {
2131 fn_out_diff_words_write_helper(diff_words->opt,
2132 &style->ctx, style->newline,
2133 plus_begin - diff_words->current_plus,
2134 diff_words->current_plus);
2135 }
2136 if (minus_begin != minus_end) {
2137 fn_out_diff_words_write_helper(diff_words->opt,
2138 &style->old_word, style->newline,
2139 minus_end - minus_begin, minus_begin);
2140 }
2141 if (plus_begin != plus_end) {
2142 fn_out_diff_words_write_helper(diff_words->opt,
2143 &style->new_word, style->newline,
2144 plus_end - plus_begin, plus_begin);
2145 }
2146
2147 diff_words->current_plus = plus_end;
2148 diff_words->last_minus = minus_first;
2149}
2150
2151/* This function starts looking at *begin, and returns 0 iff a word was found. */
2152static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2153 int *begin, int *end)
2154{
2155 while (word_regex && *begin < buffer->size) {
2156 regmatch_t match[1];
2157 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2158 buffer->size - *begin, 1, match, 0)) {
2159 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2160 '\n', match[0].rm_eo - match[0].rm_so);
2161 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2162 *begin += match[0].rm_so;
2163 if (*begin == *end)
2164 (*begin)++;
2165 else
2166 return *begin > *end;
2167 } else {
2168 return -1;
2169 }
2170 }
2171
2172 /* find the next word */
2173 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2174 (*begin)++;
2175 if (*begin >= buffer->size)
2176 return -1;
2177
2178 /* find the end of the word */
2179 *end = *begin + 1;
2180 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2181 (*end)++;
2182
2183 return 0;
2184}
2185
2186/*
2187 * This function splits the words in buffer->text, stores the list with
2188 * newline separator into out, and saves the offsets of the original words
2189 * in buffer->orig.
2190 */
2191static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2192 regex_t *word_regex)
2193{
2194 int i, j;
2195 long alloc = 0;
2196
2197 out->size = 0;
2198 out->ptr = NULL;
2199
2200 /* fake an empty "0th" word */
2201 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2202 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2203 buffer->orig_nr = 1;
2204
2205 for (i = 0; i < buffer->text.size; i++) {
2206 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2207 return;
2208
2209 /* store original boundaries */
2210 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2211 buffer->orig_alloc);
2212 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2213 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2214 buffer->orig_nr++;
2215
2216 /* store one word */
2217 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2218 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2219 out->ptr[out->size + j - i] = '\n';
2220 out->size += j - i + 1;
2221
2222 i = j - 1;
2223 }
2224}
2225
2226/* this executes the word diff on the accumulated buffers */
2227static void diff_words_show(struct diff_words_data *diff_words)
2228{
2229 xpparam_t xpp;
2230 xdemitconf_t xecfg;
2231 mmfile_t minus, plus;
2232 struct diff_words_style *style = diff_words->style;
2233
2234 struct diff_options *opt = diff_words->opt;
2235 const char *line_prefix;
2236
2237 assert(opt);
2238 line_prefix = diff_line_prefix(opt);
2239
2240 /* special case: only removal */
2241 if (!diff_words->plus.text.size) {
2242 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2243 line_prefix, strlen(line_prefix), 0);
2244 fn_out_diff_words_write_helper(diff_words->opt,
2245 &style->old_word, style->newline,
2246 diff_words->minus.text.size,
2247 diff_words->minus.text.ptr);
2248 diff_words->minus.text.size = 0;
2249 return;
2250 }
2251
2252 diff_words->current_plus = diff_words->plus.text.ptr;
2253 diff_words->last_minus = 0;
2254
2255 memset(&xpp, 0, sizeof(xpp));
2256 memset(&xecfg, 0, sizeof(xecfg));
2257 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2258 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2259 xpp.flags = 0;
2260 /* as only the hunk header will be parsed, we need a 0-context */
2261 xecfg.ctxlen = 0;
2262 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2263 diff_words, &xpp, &xecfg))
2264 die("unable to generate word diff");
2265 free(minus.ptr);
2266 free(plus.ptr);
2267 if (diff_words->current_plus != diff_words->plus.text.ptr +
2268 diff_words->plus.text.size) {
2269 if (color_words_output_graph_prefix(diff_words))
2270 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2271 line_prefix, strlen(line_prefix), 0);
2272 fn_out_diff_words_write_helper(diff_words->opt,
2273 &style->ctx, style->newline,
2274 diff_words->plus.text.ptr + diff_words->plus.text.size
2275 - diff_words->current_plus, diff_words->current_plus);
2276 }
2277 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2278}
2279
2280/* In "color-words" mode, show word-diff of words accumulated in the buffer */
2281static void diff_words_flush(struct emit_callback *ecbdata)
2282{
2283 struct diff_options *wo = ecbdata->diff_words->opt;
2284
2285 if (ecbdata->diff_words->minus.text.size ||
2286 ecbdata->diff_words->plus.text.size)
2287 diff_words_show(ecbdata->diff_words);
2288
2289 if (wo->emitted_symbols) {
2290 struct diff_options *o = ecbdata->opt;
2291 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2292 int i;
2293
2294 /*
2295 * NEEDSWORK:
2296 * Instead of appending each, concat all words to a line?
2297 */
2298 for (i = 0; i < wol->nr; i++)
2299 append_emitted_diff_symbol(o, &wol->buf[i]);
2300
2301 for (i = 0; i < wol->nr; i++)
2302 free((void *)wol->buf[i].line);
2303
2304 wol->nr = 0;
2305 }
2306}
2307
2308static void diff_filespec_load_driver(struct diff_filespec *one,
2309 struct index_state *istate)
2310{
2311 /* Use already-loaded driver */
2312 if (one->driver)
2313 return;
2314
2315 if (S_ISREG(one->mode))
2316 one->driver = userdiff_find_by_path(istate, one->path);
2317
2318 /* Fallback to default settings */
2319 if (!one->driver)
2320 one->driver = userdiff_find_by_name("default");
2321}
2322
2323static const char *userdiff_word_regex(struct diff_filespec *one,
2324 struct index_state *istate)
2325{
2326 diff_filespec_load_driver(one, istate);
2327 return one->driver->word_regex;
2328}
2329
2330static void init_diff_words_data(struct emit_callback *ecbdata,
2331 struct diff_options *orig_opts,
2332 struct diff_filespec *one,
2333 struct diff_filespec *two)
2334{
2335 int i;
2336 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2337 memcpy(o, orig_opts, sizeof(struct diff_options));
2338
2339 CALLOC_ARRAY(ecbdata->diff_words, 1);
2340 ecbdata->diff_words->type = o->word_diff;
2341 ecbdata->diff_words->opt = o;
2342
2343 if (orig_opts->emitted_symbols)
2344 CALLOC_ARRAY(o->emitted_symbols, 1);
2345
2346 if (!o->word_regex)
2347 o->word_regex = userdiff_word_regex(one, o->repo->index);
2348 if (!o->word_regex)
2349 o->word_regex = userdiff_word_regex(two, o->repo->index);
2350 if (!o->word_regex)
2351 o->word_regex = diff_word_regex_cfg;
2352 if (o->word_regex) {
2353 ecbdata->diff_words->word_regex = (regex_t *)
2354 xmalloc(sizeof(regex_t));
2355 if (regcomp(ecbdata->diff_words->word_regex,
2356 o->word_regex,
2357 REG_EXTENDED | REG_NEWLINE))
2358 die("invalid regular expression: %s",
2359 o->word_regex);
2360 }
2361 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2362 if (o->word_diff == diff_words_styles[i].type) {
2363 ecbdata->diff_words->style =
2364 &diff_words_styles[i];
2365 break;
2366 }
2367 }
2368 if (want_color(o->use_color)) {
2369 struct diff_words_style *st = ecbdata->diff_words->style;
2370 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2371 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2372 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2373 }
2374}
2375
2376static void free_diff_words_data(struct emit_callback *ecbdata)
2377{
2378 if (ecbdata->diff_words) {
2379 diff_words_flush(ecbdata);
2380 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2381 free (ecbdata->diff_words->opt);
2382 free (ecbdata->diff_words->minus.text.ptr);
2383 free (ecbdata->diff_words->minus.orig);
2384 free (ecbdata->diff_words->plus.text.ptr);
2385 free (ecbdata->diff_words->plus.orig);
2386 if (ecbdata->diff_words->word_regex) {
2387 regfree(ecbdata->diff_words->word_regex);
2388 free(ecbdata->diff_words->word_regex);
2389 }
2390 FREE_AND_NULL(ecbdata->diff_words);
2391 }
2392}
2393
2394const char *diff_get_color(enum git_colorbool diff_use_color, enum color_diff ix)
2395{
2396 if (want_color(diff_use_color))
2397 return diff_colors[ix];
2398 return "";
2399}
2400
2401const char *diff_line_prefix(struct diff_options *opt)
2402{
2403 return opt->output_prefix ?
2404 opt->output_prefix(opt, opt->output_prefix_data) :
2405 "";
2406}
2407
2408static unsigned long sane_truncate_line(char *line, unsigned long len)
2409{
2410 const char *cp;
2411 unsigned long allot;
2412 size_t l = len;
2413
2414 cp = line;
2415 allot = l;
2416 while (0 < l) {
2417 (void) utf8_width(&cp, &l);
2418 if (!cp)
2419 break; /* truncated in the middle? */
2420 }
2421 return allot - l;
2422}
2423
2424static void find_lno(const char *line, struct emit_callback *ecbdata)
2425{
2426 const char *p;
2427 ecbdata->lno_in_preimage = 0;
2428 ecbdata->lno_in_postimage = 0;
2429 p = strchr(line, '-');
2430 if (!p)
2431 return; /* cannot happen */
2432 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2433 p = strchr(p, '+');
2434 if (!p)
2435 return; /* cannot happen */
2436 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2437}
2438
2439static int fn_out_consume(void *priv, char *line, unsigned long len)
2440{
2441 struct emit_callback *ecbdata = priv;
2442 struct diff_options *o = ecbdata->opt;
2443
2444 o->found_changes = 1;
2445
2446 if (ecbdata->header) {
2447 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2448 ecbdata->header->buf, ecbdata->header->len, 0);
2449 strbuf_reset(ecbdata->header);
2450 ecbdata->header = NULL;
2451 }
2452
2453 if (ecbdata->label_path[0]) {
2454 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2455 ecbdata->label_path[0],
2456 strlen(ecbdata->label_path[0]), 0);
2457 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2458 ecbdata->label_path[1],
2459 strlen(ecbdata->label_path[1]), 0);
2460 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2461 }
2462
2463 if (line[0] == '@') {
2464 if (ecbdata->diff_words)
2465 diff_words_flush(ecbdata);
2466 len = sane_truncate_line(line, len);
2467 find_lno(line, ecbdata);
2468 emit_hunk_header(ecbdata, line, len);
2469 return 0;
2470 }
2471
2472 if (ecbdata->diff_words) {
2473 enum diff_symbol s =
2474 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2475 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2476 if (line[0] == '-') {
2477 diff_words_append(line, len,
2478 &ecbdata->diff_words->minus);
2479 return 0;
2480 } else if (line[0] == '+') {
2481 diff_words_append(line, len,
2482 &ecbdata->diff_words->plus);
2483 return 0;
2484 } else if (starts_with(line, "\\ ")) {
2485 /*
2486 * Eat the "no newline at eof" marker as if we
2487 * saw a "+" or "-" line with nothing on it,
2488 * and return without diff_words_flush() to
2489 * defer processing. If this is the end of
2490 * preimage, more "+" lines may come after it.
2491 */
2492 return 0;
2493 }
2494 diff_words_flush(ecbdata);
2495 emit_diff_symbol(o, s, line, len, 0);
2496 return 0;
2497 }
2498
2499 switch (line[0]) {
2500 case '+':
2501 ecbdata->lno_in_postimage++;
2502 emit_add_line(ecbdata, line + 1, len - 1);
2503 break;
2504 case '-':
2505 ecbdata->lno_in_preimage++;
2506 emit_del_line(ecbdata, line + 1, len - 1);
2507 break;
2508 case ' ':
2509 ecbdata->lno_in_postimage++;
2510 ecbdata->lno_in_preimage++;
2511 emit_context_line(ecbdata, line + 1, len - 1);
2512 break;
2513 case '\\':
2514 /* incomplete line at the end */
2515 switch (ecbdata->last_line_kind) {
2516 case '+':
2517 case '-':
2518 case ' ':
2519 break;
2520 default:
2521 BUG("fn_out_consume: '\\No newline' after unknown line (%c)",
2522 ecbdata->last_line_kind);
2523 }
2524 ecbdata->lno_in_preimage++;
2525 emit_incomplete_line_marker(ecbdata, line, len);
2526 break;
2527 default:
2528 BUG("fn_out_consume: unknown line '%s'", line);
2529 }
2530 ecbdata->last_line_kind = line[0];
2531 return 0;
2532}
2533
2534static int quick_consume(void *priv, char *line UNUSED, unsigned long len UNUSED)
2535{
2536 struct emit_callback *ecbdata = priv;
2537 struct diff_options *o = ecbdata->opt;
2538
2539 o->found_changes = 1;
2540 return 1;
2541}
2542
2543static void discard_pending_rm(struct line_range_callback *s)
2544{
2545 strbuf_reset(&s->pending_rm);
2546 s->pending_rm_count = 0;
2547}
2548
2549static void flush_rhunk(struct line_range_callback *s)
2550{
2551 struct strbuf hdr = STRBUF_INIT;
2552 const char *p, *end;
2553
2554 if (!s->rhunk_active || s->ret)
2555 return;
2556
2557 /* Drain any pending removal lines into the range hunk */
2558 if (s->pending_rm_count) {
2559 strbuf_addbuf(&s->rhunk, &s->pending_rm);
2560 s->rhunk_old_count += s->pending_rm_count;
2561 s->rhunk_has_changes = 1;
2562 discard_pending_rm(s);
2563 }
2564
2565 /*
2566 * Suppress context-only hunks: they contain no actual changes
2567 * and would just be noise. This can happen when the inflated
2568 * ctxlen causes xdiff to emit context covering a range that
2569 * has no changes in this commit.
2570 */
2571 if (!s->rhunk_has_changes) {
2572 s->rhunk_active = 0;
2573 strbuf_reset(&s->rhunk);
2574 return;
2575 }
2576
2577 strbuf_addf(&hdr, "@@ -%ld,%ld +%ld,%ld @@",
2578 s->rhunk_old_begin, s->rhunk_old_count,
2579 s->rhunk_new_begin, s->rhunk_new_count);
2580 if (s->funclen > 0) {
2581 strbuf_addch(&hdr, ' ');
2582 strbuf_add(&hdr, s->func, s->funclen);
2583 }
2584 strbuf_addch(&hdr, '\n');
2585
2586 s->ret = s->orig_line_fn(s->orig_cb_data, hdr.buf, hdr.len);
2587 strbuf_release(&hdr);
2588
2589 /*
2590 * Replay buffered lines one at a time through fn_out_consume.
2591 * The cast discards const because xdiff_emit_line_fn takes
2592 * char *, though fn_out_consume does not modify the buffer.
2593 */
2594 p = s->rhunk.buf;
2595 end = p + s->rhunk.len;
2596 while (!s->ret && p < end) {
2597 const char *eol = memchr(p, '\n', end - p);
2598 unsigned long line_len = eol ? (unsigned long)(eol - p + 1)
2599 : (unsigned long)(end - p);
2600 s->ret = s->orig_line_fn(s->orig_cb_data, (char *)p, line_len);
2601 p += line_len;
2602 }
2603
2604 s->rhunk_active = 0;
2605 strbuf_reset(&s->rhunk);
2606}
2607
2608static void line_range_hunk_fn(void *data,
2609 long old_begin, long old_nr UNUSED,
2610 long new_begin, long new_nr UNUSED,
2611 const char *func, long funclen)
2612{
2613 struct line_range_callback *s = data;
2614
2615 /*
2616 * When count > 0, begin is 1-based. When count == 0, begin is
2617 * adjusted down by 1 by xdl_emit_hunk_hdr(), but no lines of
2618 * that type will arrive, so the value is unused.
2619 *
2620 * Any pending removal lines from the previous xdiff hunk are
2621 * intentionally left in pending_rm: the line callback will
2622 * flush or discard them when the next content line reveals
2623 * whether the removals precede in-range content.
2624 */
2625 s->lno_post = new_begin;
2626 s->lno_pre = old_begin;
2627
2628 if (funclen > 0) {
2629 if (funclen > (long)sizeof(s->func))
2630 funclen = sizeof(s->func);
2631 memcpy(s->func, func, funclen);
2632 }
2633 s->funclen = funclen;
2634}
2635
2636static int line_range_line_fn(void *priv, char *line, unsigned long len)
2637{
2638 struct line_range_callback *s = priv;
2639 const struct range *cur;
2640 long lno_0, cur_pre;
2641
2642 if (s->ret)
2643 return s->ret;
2644
2645 if (line[0] == '-') {
2646 if (!s->pending_rm_count)
2647 s->pending_rm_pre_begin = s->lno_pre;
2648 s->lno_pre++;
2649 strbuf_add(&s->pending_rm, line, len);
2650 s->pending_rm_count++;
2651 return s->ret;
2652 }
2653
2654 if (line[0] == '\\') {
2655 if (s->pending_rm_count)
2656 strbuf_add(&s->pending_rm, line, len);
2657 else if (s->rhunk_active)
2658 strbuf_add(&s->rhunk, line, len);
2659 /* otherwise outside tracked range; drop silently */
2660 return s->ret;
2661 }
2662
2663 if (line[0] != '+' && line[0] != ' ')
2664 BUG("unexpected diff line type '%c'", line[0]);
2665
2666 lno_0 = s->lno_post - 1;
2667 cur_pre = s->lno_pre; /* save before advancing for context lines */
2668 s->lno_post++;
2669 if (line[0] == ' ')
2670 s->lno_pre++;
2671
2672 /* Advance past ranges we've passed */
2673 while (s->cur_range < s->ranges->nr &&
2674 lno_0 >= s->ranges->ranges[s->cur_range].end) {
2675 if (s->rhunk_active)
2676 flush_rhunk(s);
2677 discard_pending_rm(s);
2678 s->cur_range++;
2679 }
2680
2681 /* Past all ranges */
2682 if (s->cur_range >= s->ranges->nr) {
2683 discard_pending_rm(s);
2684 return s->ret;
2685 }
2686
2687 cur = &s->ranges->ranges[s->cur_range];
2688
2689 /* Before current range */
2690 if (lno_0 < cur->start) {
2691 discard_pending_rm(s);
2692 return s->ret;
2693 }
2694
2695 /* In range so start a new range hunk if needed */
2696 if (!s->rhunk_active) {
2697 s->rhunk_active = 1;
2698 s->rhunk_has_changes = 0;
2699 s->rhunk_new_begin = lno_0 + 1;
2700 s->rhunk_old_begin = s->pending_rm_count
2701 ? s->pending_rm_pre_begin : cur_pre;
2702 s->rhunk_old_count = 0;
2703 s->rhunk_new_count = 0;
2704 strbuf_reset(&s->rhunk);
2705 }
2706
2707 /* Flush pending removals into range hunk */
2708 if (s->pending_rm_count) {
2709 strbuf_addbuf(&s->rhunk, &s->pending_rm);
2710 s->rhunk_old_count += s->pending_rm_count;
2711 s->rhunk_has_changes = 1;
2712 discard_pending_rm(s);
2713 }
2714
2715 strbuf_add(&s->rhunk, line, len);
2716 s->rhunk_new_count++;
2717 if (line[0] == '+')
2718 s->rhunk_has_changes = 1;
2719 else
2720 s->rhunk_old_count++;
2721
2722 return s->ret;
2723}
2724
2725static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2726{
2727 const char *old_name = a;
2728 const char *new_name = b;
2729 int pfx_length, sfx_length;
2730 int pfx_adjust_for_slash;
2731 int len_a = strlen(a);
2732 int len_b = strlen(b);
2733 int a_midlen, b_midlen;
2734 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2735 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2736
2737 if (qlen_a || qlen_b) {
2738 quote_c_style(a, name, NULL, 0);
2739 strbuf_addstr(name, " => ");
2740 quote_c_style(b, name, NULL, 0);
2741 return;
2742 }
2743
2744 /* Find common prefix */
2745 pfx_length = 0;
2746 while (*old_name && *new_name && *old_name == *new_name) {
2747 if (*old_name == '/')
2748 pfx_length = old_name - a + 1;
2749 old_name++;
2750 new_name++;
2751 }
2752
2753 /* Find common suffix */
2754 old_name = a + len_a;
2755 new_name = b + len_b;
2756 sfx_length = 0;
2757 /*
2758 * If there is a common prefix, it must end in a slash. In
2759 * that case we let this loop run 1 into the prefix to see the
2760 * same slash.
2761 *
2762 * If there is no common prefix, we cannot do this as it would
2763 * underrun the input strings.
2764 */
2765 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2766 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2767 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2768 *old_name == *new_name) {
2769 if (*old_name == '/')
2770 sfx_length = len_a - (old_name - a);
2771 old_name--;
2772 new_name--;
2773 }
2774
2775 /*
2776 * pfx{mid-a => mid-b}sfx
2777 * {pfx-a => pfx-b}sfx
2778 * pfx{sfx-a => sfx-b}
2779 * name-a => name-b
2780 */
2781 a_midlen = len_a - pfx_length - sfx_length;
2782 b_midlen = len_b - pfx_length - sfx_length;
2783 if (a_midlen < 0)
2784 a_midlen = 0;
2785 if (b_midlen < 0)
2786 b_midlen = 0;
2787
2788 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2789 if (pfx_length + sfx_length) {
2790 strbuf_add(name, a, pfx_length);
2791 strbuf_addch(name, '{');
2792 }
2793 strbuf_add(name, a + pfx_length, a_midlen);
2794 strbuf_addstr(name, " => ");
2795 strbuf_add(name, b + pfx_length, b_midlen);
2796 if (pfx_length + sfx_length) {
2797 strbuf_addch(name, '}');
2798 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2799 }
2800}
2801
2802static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2803 const char *name_a,
2804 const char *name_b)
2805{
2806 struct diffstat_file *x;
2807 CALLOC_ARRAY(x, 1);
2808 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2809 diffstat->files[diffstat->nr++] = x;
2810 if (name_b) {
2811 x->from_name = xstrdup(name_a);
2812 x->name = xstrdup(name_b);
2813 x->is_renamed = 1;
2814 }
2815 else {
2816 x->from_name = NULL;
2817 x->name = xstrdup(name_a);
2818 }
2819 return x;
2820}
2821
2822static int diffstat_consume(void *priv, char *line, unsigned long len)
2823{
2824 struct diffstat_t *diffstat = priv;
2825 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2826
2827 if (!len)
2828 BUG("xdiff fed us an empty line");
2829
2830 if (line[0] == '+')
2831 x->added++;
2832 else if (line[0] == '-')
2833 x->deleted++;
2834 return 0;
2835}
2836
2837const char mime_boundary_leader[] = "------------";
2838
2839static int scale_linear(int it, int width, int max_change)
2840{
2841 if (!it)
2842 return 0;
2843 /*
2844 * make sure that at least one '-' or '+' is printed if
2845 * there is any change to this path. The easiest way is to
2846 * scale linearly as if the allotted width is one column shorter
2847 * than it is, and then add 1 to the result.
2848 */
2849 return 1 + (it * (width - 1) / max_change);
2850}
2851
2852static void show_graph(struct strbuf *out, char ch, int cnt,
2853 const char *set, const char *reset)
2854{
2855 if (cnt <= 0)
2856 return;
2857 strbuf_addstr(out, set);
2858 strbuf_addchars(out, ch, cnt);
2859 strbuf_addstr(out, reset);
2860}
2861
2862static void fill_print_name(struct diffstat_file *file)
2863{
2864 struct strbuf pname = STRBUF_INIT;
2865
2866 if (file->print_name)
2867 return;
2868
2869 if (file->is_renamed)
2870 pprint_rename(&pname, file->from_name, file->name);
2871 else
2872 quote_c_style(file->name, &pname, NULL, 0);
2873
2874 if (file->comments)
2875 strbuf_addf(&pname, " (%s)", file->comments);
2876
2877 file->print_name = strbuf_detach(&pname, NULL);
2878}
2879
2880static void print_stat_summary_inserts_deletes(struct diff_options *options,
2881 int files, int insertions, int deletions)
2882{
2883 struct strbuf sb = STRBUF_INIT;
2884
2885 if (!files) {
2886 assert(insertions == 0 && deletions == 0);
2887 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2888 NULL, 0, 0);
2889 return;
2890 }
2891
2892 strbuf_addf(&sb,
2893 (files == 1) ? " %d file changed" : " %d files changed",
2894 files);
2895
2896 /*
2897 * For binary diff, the caller may want to print "x files
2898 * changed" with insertions == 0 && deletions == 0.
2899 *
2900 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2901 * is probably less confusing (i.e skip over "2 files changed
2902 * but nothing about added/removed lines? Is this a bug in Git?").
2903 */
2904 if (insertions || deletions == 0) {
2905 strbuf_addf(&sb,
2906 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2907 insertions);
2908 }
2909
2910 if (deletions || insertions == 0) {
2911 strbuf_addf(&sb,
2912 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2913 deletions);
2914 }
2915 strbuf_addch(&sb, '\n');
2916 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2917 sb.buf, sb.len, 0);
2918 strbuf_release(&sb);
2919}
2920
2921void print_stat_summary(FILE *fp, int files,
2922 int insertions, int deletions)
2923{
2924 struct diff_options o;
2925 memset(&o, 0, sizeof(o));
2926 o.file = fp;
2927
2928 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2929}
2930
2931/*
2932 * Like utf8_width(), but guaranteed safe for use in loops that subtract
2933 * per-character widths:
2934 *
2935 * - utf8_width() sets *start to NULL on invalid UTF-8 and returns 0;
2936 * we restore the pointer and advance by one byte, returning width 1
2937 * (matching the strlen()-based fallback in utf8_strwidth()).
2938 *
2939 * - utf8_width() returns -1 for control characters; we return 0
2940 * (matching utf8_strnwidth() which skips them).
2941 */
2942static int utf8_ish_width(const char **start)
2943{
2944 const char *old = *start;
2945 int w = utf8_width(start, NULL);
2946 if (!*start) {
2947 *start = old + 1;
2948 return 1;
2949 }
2950 return (w < 0) ? 0 : w;
2951}
2952
2953static void show_stats(struct diffstat_t *data, struct diff_options *options)
2954{
2955 int i, len, add, del, adds = 0, dels = 0;
2956 uintmax_t max_change = 0, max_len = 0;
2957 int total_files = data->nr, count;
2958 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2959 const char *reset, *add_c, *del_c;
2960 int extra_shown = 0;
2961 const char *line_prefix = diff_line_prefix(options);
2962 struct strbuf out = STRBUF_INIT;
2963
2964 if (data->nr == 0)
2965 return;
2966
2967 count = options->stat_count ? options->stat_count : data->nr;
2968
2969 reset = diff_get_color_opt(options, DIFF_RESET);
2970 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2971 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2972
2973 /*
2974 * Find the longest filename and max number of changes
2975 */
2976 for (i = 0; (i < count) && (i < data->nr); i++) {
2977 struct diffstat_file *file = data->files[i];
2978 uintmax_t change = file->added + file->deleted;
2979
2980 if (!file->is_interesting && (change == 0)) {
2981 count++; /* not shown == room for one more */
2982 continue;
2983 }
2984 fill_print_name(file);
2985 len = utf8_strwidth(file->print_name);
2986 if (max_len < len)
2987 max_len = len;
2988
2989 if (file->is_unmerged) {
2990 /* "Unmerged" is 8 characters */
2991 bin_width = bin_width < 8 ? 8 : bin_width;
2992 continue;
2993 }
2994 if (file->is_binary) {
2995 /* "Bin XXX -> YYY bytes" */
2996 int w = 14 + decimal_width(file->added)
2997 + decimal_width(file->deleted);
2998 bin_width = bin_width < w ? w : bin_width;
2999 /* Display change counts aligned with "Bin" */
3000 number_width = 3;
3001 continue;
3002 }
3003
3004 if (max_change < change)
3005 max_change = change;
3006 }
3007 count = i; /* where we can stop scanning in data->files[] */
3008
3009 /*
3010 * We have width = stat_width or term_columns() columns total minus the
3011 * length of line_prefix skipping ANSI escape codes to get the display
3012 * width (e.g., skip ANSI-colored strings in "log --graph --stat").
3013 * We want a maximum of min(max_len, stat_name_width) for the name part.
3014 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
3015 * We also need 1 for " " and 4 + decimal_width(max_change)
3016 * for " | NNNN " and one the empty column at the end, altogether
3017 * 6 + decimal_width(max_change).
3018 *
3019 * If there's not enough space, we will use the smaller of
3020 * stat_name_width (if set) and 5/8*width for the filename,
3021 * and the rest for constant elements + graph part, but no more
3022 * than stat_graph_width for the graph part.
3023 * (5/8 gives 50 for filename and 30 for the constant parts + graph
3024 * for the standard terminal size).
3025 *
3026 * In other words: stat_width limits the maximum width, and
3027 * stat_name_width fixes the maximum width of the filename,
3028 * and is also used to divide available columns if there
3029 * aren't enough.
3030 *
3031 * Binary files are displayed with "Bin XXX -> YYY bytes"
3032 * instead of the change count and graph. This part is treated
3033 * similarly to the graph part, except that it is not
3034 * "scaled". If total width is too small to accommodate the
3035 * guaranteed minimum width of the filename part and the
3036 * separators and this message, this message will "overflow"
3037 * making the line longer than the maximum width.
3038 */
3039 if (options->stat_width == -1)
3040 width = term_columns() - utf8_strnwidth(line_prefix, strlen(line_prefix), 1);
3041 else
3042 width = options->stat_width ? options->stat_width : 80;
3043 number_width = decimal_width(max_change) > number_width ?
3044 decimal_width(max_change) : number_width;
3045
3046 if (options->stat_name_width == -1)
3047 options->stat_name_width = diff_stat_name_width;
3048 if (options->stat_graph_width == -1)
3049 options->stat_graph_width = diff_stat_graph_width;
3050
3051 /*
3052 * Guarantee 3/8*16 == 6 for the graph part
3053 * and 5/8*16 == 10 for the filename part
3054 */
3055 if (width < 16 + 6 + number_width)
3056 width = 16 + 6 + number_width;
3057
3058 /*
3059 * First assign sizes that are wanted, ignoring available width.
3060 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
3061 * starting from "XXX" should fit in graph_width.
3062 */
3063 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
3064 if (options->stat_graph_width &&
3065 options->stat_graph_width < graph_width)
3066 graph_width = options->stat_graph_width;
3067
3068 name_width = (options->stat_name_width > 0 &&
3069 options->stat_name_width < max_len) ?
3070 options->stat_name_width : max_len;
3071
3072 /*
3073 * Adjust adjustable widths not to exceed maximum width
3074 */
3075 if (name_width + number_width + 6 + graph_width > width) {
3076 if (graph_width > width * 3/8 - number_width - 6) {
3077 graph_width = width * 3/8 - number_width - 6;
3078 if (graph_width < 6)
3079 graph_width = 6;
3080 }
3081
3082 if (options->stat_graph_width &&
3083 graph_width > options->stat_graph_width)
3084 graph_width = options->stat_graph_width;
3085 if (name_width > width - number_width - 6 - graph_width)
3086 name_width = width - number_width - 6 - graph_width;
3087 else
3088 graph_width = width - number_width - 6 - name_width;
3089 }
3090
3091 /*
3092 * From here name_width is the width of the name area,
3093 * and graph_width is the width of the graph area.
3094 * max_change is used to scale graph properly.
3095 */
3096 for (i = 0; i < count; i++) {
3097 const char *prefix = "";
3098 struct diffstat_file *file = data->files[i];
3099 char *name = file->print_name;
3100 uintmax_t added = file->added;
3101 uintmax_t deleted = file->deleted;
3102 int name_len, padding;
3103
3104 if (!file->is_interesting && (added + deleted == 0))
3105 continue;
3106
3107 /*
3108 * "scale" the filename
3109 */
3110 len = name_width;
3111 name_len = utf8_strwidth(name);
3112 if (name_width < name_len) {
3113 char *slash;
3114 prefix = "...";
3115 len -= 3;
3116 if (len < 0)
3117 len = 0;
3118
3119 while (name_len > len && *name)
3120 name_len -= utf8_ish_width((const char**)&name);
3121
3122 slash = strchr(name, '/');
3123 if (slash)
3124 name = slash;
3125 }
3126 padding = len - utf8_strwidth(name);
3127 if (padding < 0)
3128 padding = 0;
3129
3130 if (file->is_binary) {
3131 strbuf_addf(&out, " %s%s%*s | %*s",
3132 prefix, name, padding, "",
3133 number_width, "Bin");
3134 if (!added && !deleted) {
3135 strbuf_addch(&out, '\n');
3136 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
3137 out.buf, out.len, 0);
3138 strbuf_reset(&out);
3139 continue;
3140 }
3141 strbuf_addf(&out, " %s%"PRIuMAX"%s",
3142 del_c, deleted, reset);
3143 strbuf_addstr(&out, " -> ");
3144 strbuf_addf(&out, "%s%"PRIuMAX"%s",
3145 add_c, added, reset);
3146 strbuf_addstr(&out, " bytes\n");
3147 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
3148 out.buf, out.len, 0);
3149 strbuf_reset(&out);
3150 continue;
3151 }
3152 else if (file->is_unmerged) {
3153 strbuf_addf(&out, " %s%s%*s | %*s",
3154 prefix, name, padding, "",
3155 number_width, "Unmerged\n");
3156 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
3157 out.buf, out.len, 0);
3158 strbuf_reset(&out);
3159 continue;
3160 }
3161
3162 /*
3163 * scale the add/delete
3164 */
3165 add = added;
3166 del = deleted;
3167
3168 if (graph_width <= max_change) {
3169 int total = scale_linear(add + del, graph_width, max_change);
3170 if (total < 2 && add && del)
3171 /* width >= 2 due to the sanity check */
3172 total = 2;
3173 if (add < del) {
3174 add = scale_linear(add, graph_width, max_change);
3175 del = total - add;
3176 } else {
3177 del = scale_linear(del, graph_width, max_change);
3178 add = total - del;
3179 }
3180 }
3181 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
3182 prefix, name, padding, "",
3183 number_width, added + deleted,
3184 added + deleted ? " " : "");
3185 show_graph(&out, '+', add, add_c, reset);
3186 show_graph(&out, '-', del, del_c, reset);
3187 strbuf_addch(&out, '\n');
3188 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
3189 out.buf, out.len, 0);
3190 strbuf_reset(&out);
3191 }
3192
3193 for (i = 0; i < data->nr; i++) {
3194 struct diffstat_file *file = data->files[i];
3195 uintmax_t added = file->added;
3196 uintmax_t deleted = file->deleted;
3197
3198 if (file->is_unmerged ||
3199 (!file->is_interesting && (added + deleted == 0))) {
3200 total_files--;
3201 continue;
3202 }
3203
3204 if (!file->is_binary) {
3205 adds += added;
3206 dels += deleted;
3207 }
3208 if (i < count)
3209 continue;
3210 if (!extra_shown)
3211 emit_diff_symbol(options,
3212 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
3213 NULL, 0, 0);
3214 extra_shown = 1;
3215 }
3216
3217 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
3218 strbuf_release(&out);
3219}
3220
3221static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
3222{
3223 int i, adds = 0, dels = 0, total_files = data->nr;
3224
3225 if (data->nr == 0)
3226 return;
3227
3228 for (i = 0; i < data->nr; i++) {
3229 int added = data->files[i]->added;
3230 int deleted = data->files[i]->deleted;
3231
3232 if (data->files[i]->is_unmerged ||
3233 (!data->files[i]->is_interesting && (added + deleted == 0))) {
3234 total_files--;
3235 } else if (!data->files[i]->is_binary) { /* don't count bytes */
3236 adds += added;
3237 dels += deleted;
3238 }
3239 }
3240 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
3241}
3242
3243static void show_numstat(struct diffstat_t *data, struct diff_options *options)
3244{
3245 int i;
3246
3247 if (data->nr == 0)
3248 return;
3249
3250 for (i = 0; i < data->nr; i++) {
3251 struct diffstat_file *file = data->files[i];
3252
3253 fprintf(options->file, "%s", diff_line_prefix(options));
3254
3255 if (file->is_binary)
3256 fprintf(options->file, "-\t-\t");
3257 else
3258 fprintf(options->file,
3259 "%"PRIuMAX"\t%"PRIuMAX"\t",
3260 file->added, file->deleted);
3261 if (options->line_termination) {
3262 fill_print_name(file);
3263 if (!file->is_renamed)
3264 write_name_quoted(file->name, options->file,
3265 options->line_termination);
3266 else {
3267 fputs(file->print_name, options->file);
3268 putc(options->line_termination, options->file);
3269 }
3270 } else {
3271 if (file->is_renamed) {
3272 putc('\0', options->file);
3273 write_name_quoted(file->from_name, options->file, '\0');
3274 }
3275 write_name_quoted(file->name, options->file, '\0');
3276 }
3277 }
3278}
3279
3280struct dirstat_file {
3281 const char *name;
3282 unsigned long changed;
3283};
3284
3285struct dirstat_dir {
3286 struct dirstat_file *files;
3287 int alloc, nr, permille, cumulative;
3288};
3289
3290static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
3291 unsigned long changed, const char *base, int baselen)
3292{
3293 unsigned long sum_changes = 0;
3294 unsigned int sources = 0;
3295 const char *line_prefix = diff_line_prefix(opt);
3296
3297 while (dir->nr) {
3298 struct dirstat_file *f = dir->files;
3299 int namelen = strlen(f->name);
3300 unsigned long changes;
3301 const char *slash;
3302
3303 if (namelen < baselen)
3304 break;
3305 if (memcmp(f->name, base, baselen))
3306 break;
3307 slash = strchr(f->name + baselen, '/');
3308 if (slash) {
3309 int newbaselen = slash + 1 - f->name;
3310 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
3311 sources++;
3312 } else {
3313 changes = f->changed;
3314 dir->files++;
3315 dir->nr--;
3316 sources += 2;
3317 }
3318 sum_changes += changes;
3319 }
3320
3321 /*
3322 * We don't report dirstat's for
3323 * - the top level
3324 * - or cases where everything came from a single directory
3325 * under this directory (sources == 1).
3326 */
3327 if (baselen && sources != 1) {
3328 if (sum_changes) {
3329 int permille = sum_changes * 1000 / changed;
3330 if (permille >= dir->permille) {
3331 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
3332 permille / 10, permille % 10, baselen, base);
3333 if (!dir->cumulative)
3334 return 0;
3335 }
3336 }
3337 }
3338 return sum_changes;
3339}
3340
3341static int dirstat_compare(const void *_a, const void *_b)
3342{
3343 const struct dirstat_file *a = _a;
3344 const struct dirstat_file *b = _b;
3345 return strcmp(a->name, b->name);
3346}
3347
3348static void conclude_dirstat(struct diff_options *options,
3349 struct dirstat_dir *dir,
3350 unsigned long changed)
3351{
3352 struct dirstat_file *to_free = dir->files;
3353
3354 if (!changed) {
3355 /* This can happen even with many files, if everything was renames */
3356 ;
3357 } else {
3358 /* Show all directories with more than x% of the changes */
3359 QSORT(dir->files, dir->nr, dirstat_compare);
3360 gather_dirstat(options, dir, changed, "", 0);
3361 }
3362
3363 free(to_free);
3364}
3365
3366static void show_dirstat(struct diff_options *options)
3367{
3368 int i;
3369 unsigned long changed;
3370 struct dirstat_dir dir;
3371 struct diff_queue_struct *q = &diff_queued_diff;
3372
3373 dir.files = NULL;
3374 dir.alloc = 0;
3375 dir.nr = 0;
3376 dir.permille = options->dirstat_permille;
3377 dir.cumulative = options->flags.dirstat_cumulative;
3378
3379 changed = 0;
3380 for (i = 0; i < q->nr; i++) {
3381 struct diff_filepair *p = q->queue[i];
3382 const char *name;
3383 unsigned long copied, added, damage;
3384 struct diff_populate_filespec_options dpf_options = {
3385 .check_size_only = 1,
3386 };
3387
3388 name = p->two->path ? p->two->path : p->one->path;
3389
3390 if (p->one->oid_valid && p->two->oid_valid &&
3391 oideq(&p->one->oid, &p->two->oid)) {
3392 /*
3393 * The SHA1 has not changed, so pre-/post-content is
3394 * identical. We can therefore skip looking at the
3395 * file contents altogether.
3396 */
3397 damage = 0;
3398 goto found_damage;
3399 }
3400
3401 if (options->flags.dirstat_by_file) {
3402 /*
3403 * In --dirstat-by-file mode, we don't really need to
3404 * look at the actual file contents at all.
3405 * The fact that the SHA1 changed is enough for us to
3406 * add this file to the list of results
3407 * (with each file contributing equal damage).
3408 */
3409 damage = 1;
3410 goto found_damage;
3411 }
3412
3413 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3414 diff_populate_filespec(options->repo, p->one, NULL);
3415 diff_populate_filespec(options->repo, p->two, NULL);
3416 diffcore_count_changes(options->repo,
3417 p->one, p->two, NULL, NULL,
3418 &copied, &added);
3419 diff_free_filespec_data(p->one);
3420 diff_free_filespec_data(p->two);
3421 } else if (DIFF_FILE_VALID(p->one)) {
3422 diff_populate_filespec(options->repo, p->one, &dpf_options);
3423 copied = added = 0;
3424 diff_free_filespec_data(p->one);
3425 } else if (DIFF_FILE_VALID(p->two)) {
3426 diff_populate_filespec(options->repo, p->two, &dpf_options);
3427 copied = 0;
3428 added = p->two->size;
3429 diff_free_filespec_data(p->two);
3430 } else
3431 continue;
3432
3433 /*
3434 * Original minus copied is the removed material,
3435 * added is the new material. They are both damages
3436 * made to the preimage.
3437 * If the resulting damage is zero, we know that
3438 * diffcore_count_changes() considers the two entries to
3439 * be identical, but since the oid changed, we
3440 * know that there must have been _some_ kind of change,
3441 * so we force all entries to have damage > 0.
3442 */
3443 damage = (p->one->size - copied) + added;
3444 if (!damage)
3445 damage = 1;
3446
3447found_damage:
3448 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3449 dir.files[dir.nr].name = name;
3450 dir.files[dir.nr].changed = damage;
3451 changed += damage;
3452 dir.nr++;
3453 }
3454
3455 conclude_dirstat(options, &dir, changed);
3456}
3457
3458static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3459{
3460 int i;
3461 unsigned long changed;
3462 struct dirstat_dir dir;
3463
3464 if (data->nr == 0)
3465 return;
3466
3467 dir.files = NULL;
3468 dir.alloc = 0;
3469 dir.nr = 0;
3470 dir.permille = options->dirstat_permille;
3471 dir.cumulative = options->flags.dirstat_cumulative;
3472
3473 changed = 0;
3474 for (i = 0; i < data->nr; i++) {
3475 struct diffstat_file *file = data->files[i];
3476 unsigned long damage = file->added + file->deleted;
3477 if (file->is_binary)
3478 /*
3479 * binary files counts bytes, not lines. Must find some
3480 * way to normalize binary bytes vs. textual lines.
3481 * The following heuristic assumes that there are 64
3482 * bytes per "line".
3483 * This is stupid and ugly, but very cheap...
3484 */
3485 damage = DIV_ROUND_UP(damage, 64);
3486 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3487 dir.files[dir.nr].name = file->name;
3488 dir.files[dir.nr].changed = damage;
3489 changed += damage;
3490 dir.nr++;
3491 }
3492
3493 conclude_dirstat(options, &dir, changed);
3494}
3495
3496static void free_diffstat_file(struct diffstat_file *f)
3497{
3498 free(f->print_name);
3499 free(f->name);
3500 free(f->from_name);
3501 free(f);
3502}
3503
3504void free_diffstat_info(struct diffstat_t *diffstat)
3505{
3506 int i;
3507 for (i = 0; i < diffstat->nr; i++)
3508 free_diffstat_file(diffstat->files[i]);
3509 free(diffstat->files);
3510}
3511
3512struct checkdiff_t {
3513 const char *filename;
3514 int lineno;
3515 int conflict_marker_size;
3516 struct diff_options *o;
3517 unsigned ws_rule;
3518 unsigned status;
3519 int last_line_kind;
3520};
3521
3522static void checkdiff_consume_hunk(void *priv,
3523 long ob UNUSED, long on UNUSED,
3524 long nb, long nn UNUSED,
3525 const char *func UNUSED, long funclen UNUSED)
3526
3527{
3528 struct checkdiff_t *data = priv;
3529 data->lineno = nb - 1;
3530}
3531
3532static int checkdiff_consume(void *priv, char *line, unsigned long len)
3533{
3534 struct checkdiff_t *data = priv;
3535 int last_line_kind;
3536 int marker_size = data->conflict_marker_size;
3537 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3538 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3539 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3540 char *err;
3541 const char *line_prefix;
3542
3543 assert(data->o);
3544 line_prefix = diff_line_prefix(data->o);
3545
3546 last_line_kind = data->last_line_kind;
3547 data->last_line_kind = line[0];
3548 if (line[0] == '+') {
3549 unsigned bad;
3550 data->lineno++;
3551 if (is_conflict_marker_line(line + 1, len - 1, marker_size)) {
3552 data->status |= 1;
3553 fprintf(data->o->file,
3554 "%s%s:%d: leftover conflict marker\n",
3555 line_prefix, data->filename, data->lineno);
3556 }
3557 bad = ws_check(line + 1, len - 1, data->ws_rule);
3558 if (!bad)
3559 return 0;
3560 data->status |= bad;
3561 err = whitespace_error_string(bad);
3562 fprintf(data->o->file, "%s%s:%d: %s.\n",
3563 line_prefix, data->filename, data->lineno, err);
3564 free(err);
3565 emit_line(data->o, set, reset, line, 1);
3566 ws_check_emit(line + 1, len - 1, data->ws_rule,
3567 data->o->file, set, reset, ws);
3568 } else if (line[0] == ' ') {
3569 data->lineno++;
3570 } else if (line[0] == '\\') {
3571 /* no newline at the end of the line */
3572 if ((data->ws_rule & WS_INCOMPLETE_LINE) &&
3573 (last_line_kind == '+')) {
3574 unsigned bad = WS_INCOMPLETE_LINE;
3575 data->status |= bad;
3576 err = whitespace_error_string(bad);
3577 fprintf(data->o->file, "%s%s:%d: %s.\n",
3578 line_prefix, data->filename, data->lineno, err);
3579 free(err);
3580 }
3581 }
3582 return 0;
3583}
3584
3585static unsigned char *deflate_it(char *data,
3586 unsigned long size,
3587 unsigned long *result_size)
3588{
3589 size_t bound;
3590 unsigned char *deflated;
3591 git_zstream stream;
3592 struct repo_config_values *cfg = repo_config_values(the_repository);
3593
3594 git_deflate_init(&stream, cfg->zlib_compression_level);
3595 bound = git_deflate_bound(&stream, size);
3596 deflated = xmalloc(bound);
3597 stream.next_out = deflated;
3598 stream.avail_out = bound;
3599
3600 stream.next_in = (unsigned char *)data;
3601 stream.avail_in = size;
3602 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3603 ; /* nothing */
3604 git_deflate_end(&stream);
3605 *result_size = stream.total_out;
3606 return deflated;
3607}
3608
3609static void emit_binary_diff_line(char *line, int len, void *output_data)
3610{
3611 struct diff_options *o = output_data;
3612 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY, line, len, 0);
3613}
3614
3615static void emit_binary_diff_body(struct diff_options *o,
3616 mmfile_t *one, mmfile_t *two)
3617{
3618 void *delta;
3619 void *deflated;
3620 void *data;
3621 unsigned long orig_size;
3622 unsigned long delta_size;
3623 unsigned long deflate_size;
3624 unsigned long data_size;
3625
3626 /* We could do deflated delta, or we could do just deflated two,
3627 * whichever is smaller.
3628 */
3629 delta = NULL;
3630 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3631 if (one->size && two->size) {
3632 size_t delta_size_st = 0;
3633 delta = diff_delta(one->ptr, one->size,
3634 two->ptr, two->size,
3635 &delta_size_st, deflate_size);
3636 delta_size = cast_size_t_to_ulong(delta_size_st);
3637 if (delta) {
3638 void *to_free = delta;
3639 orig_size = delta_size;
3640 delta = deflate_it(delta, delta_size, &delta_size);
3641 free(to_free);
3642 }
3643 }
3644
3645 if (delta && delta_size < deflate_size) {
3646 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3647 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3648 s, strlen(s), 0);
3649 free(s);
3650 free(deflated);
3651 data = delta;
3652 data_size = delta_size;
3653 } else {
3654 char *s = xstrfmt("%"PRIuMAX, (uintmax_t)two->size);
3655 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3656 s, strlen(s), 0);
3657 free(s);
3658 free(delta);
3659 data = deflated;
3660 data_size = deflate_size;
3661 }
3662
3663 /* emit data encoded in base85 */
3664 chunk_and_encode85(data, data_size, emit_binary_diff_line, o);
3665 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3666 free(data);
3667}
3668
3669static void emit_binary_diff(struct diff_options *o,
3670 mmfile_t *one, mmfile_t *two)
3671{
3672 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3673 emit_binary_diff_body(o, one, two);
3674 emit_binary_diff_body(o, two, one);
3675}
3676
3677int diff_filespec_is_binary(struct repository *r,
3678 struct diff_filespec *one)
3679{
3680 struct diff_populate_filespec_options dpf_options = {
3681 .check_binary = 1,
3682 };
3683
3684 if (one->is_binary == -1) {
3685 diff_filespec_load_driver(one, r->index);
3686 if (one->driver->binary != -1)
3687 one->is_binary = one->driver->binary;
3688 else {
3689 if (!one->data && DIFF_FILE_VALID(one))
3690 diff_populate_filespec(r, one, &dpf_options);
3691 if (one->is_binary == -1 && one->data)
3692 one->is_binary = buffer_is_binary(one->data,
3693 one->size);
3694 if (one->is_binary == -1)
3695 one->is_binary = 0;
3696 }
3697 }
3698 return one->is_binary;
3699}
3700
3701static const struct userdiff_funcname *
3702diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3703{
3704 diff_filespec_load_driver(one, o->repo->index);
3705 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3706}
3707
3708void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3709{
3710 if (!options->a_prefix)
3711 options->a_prefix = a;
3712 if (!options->b_prefix)
3713 options->b_prefix = b;
3714}
3715
3716void diff_set_noprefix(struct diff_options *options)
3717{
3718 options->a_prefix = options->b_prefix = "";
3719}
3720
3721void diff_set_default_prefix(struct diff_options *options)
3722{
3723 options->a_prefix = diff_src_prefix ? diff_src_prefix : "a/";
3724 options->b_prefix = diff_dst_prefix ? diff_dst_prefix : "b/";
3725}
3726
3727struct userdiff_driver *get_textconv(struct repository *r,
3728 struct diff_filespec *one)
3729{
3730 if (!DIFF_FILE_VALID(one))
3731 return NULL;
3732
3733 diff_filespec_load_driver(one, r->index);
3734 return userdiff_get_textconv(r, one->driver);
3735}
3736
3737static struct string_list *additional_headers(struct diff_options *o,
3738 const char *path)
3739{
3740 if (!o->additional_path_headers)
3741 return NULL;
3742 return strmap_get(o->additional_path_headers, path);
3743}
3744
3745static void add_formatted_header(struct strbuf *msg,
3746 const char *header,
3747 const char *line_prefix,
3748 const char *meta,
3749 const char *reset)
3750{
3751 const char *next, *newline;
3752
3753 for (next = header; *next; next = newline) {
3754 newline = strchrnul(next, '\n');
3755 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3756 (int)(newline - next), next, reset);
3757 if (*newline)
3758 newline++;
3759 }
3760}
3761
3762static void add_formatted_headers(struct strbuf *msg,
3763 struct string_list *more_headers,
3764 const char *line_prefix,
3765 const char *meta,
3766 const char *reset)
3767{
3768 int i;
3769
3770 for (i = 0; i < more_headers->nr; i++)
3771 add_formatted_header(msg, more_headers->items[i].string,
3772 line_prefix, meta, reset);
3773}
3774
3775static int diff_filepair_is_phoney(struct diff_filespec *one,
3776 struct diff_filespec *two)
3777{
3778 /*
3779 * This function specifically looks for pairs injected by
3780 * create_filepairs_for_header_only_notifications(). Such
3781 * pairs are "phoney" in that they do not represent any
3782 * content or even mode difference, but were inserted because
3783 * diff_queued_diff previously had no pair associated with
3784 * that path but we needed some pair to avoid losing the
3785 * "remerge CONFLICT" header associated with the path.
3786 */
3787 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3788}
3789
3790static int set_diff_algorithm(struct diff_options *opts,
3791 const char *alg)
3792{
3793 long value = parse_algorithm_value(alg);
3794
3795 if (value < 0)
3796 return -1;
3797
3798 /* clear out previous settings */
3799 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3800 opts->xdl_opts |= value;
3801
3802 return 0;
3803}
3804
3805static void builtin_diff(const char *name_a,
3806 const char *name_b,
3807 struct diff_filespec *one,
3808 struct diff_filespec *two,
3809 const char *xfrm_msg,
3810 int must_show_header,
3811 struct diff_options *o,
3812 int complete_rewrite,
3813 const struct range_set *line_ranges)
3814{
3815 mmfile_t mf1, mf2;
3816 const char *lbl[2];
3817 char *a_one, *b_two;
3818 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3819 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3820 const char *a_prefix, *b_prefix;
3821 struct userdiff_driver *textconv_one = NULL;
3822 struct userdiff_driver *textconv_two = NULL;
3823 struct strbuf header = STRBUF_INIT;
3824 const char *line_prefix = diff_line_prefix(o);
3825
3826 diff_set_mnemonic_prefix(o, "a/", "b/");
3827 if (o->flags.reverse_diff) {
3828 a_prefix = o->b_prefix;
3829 b_prefix = o->a_prefix;
3830 } else {
3831 a_prefix = o->a_prefix;
3832 b_prefix = o->b_prefix;
3833 }
3834
3835 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3836 (!one->mode || S_ISGITLINK(one->mode)) &&
3837 (!two->mode || S_ISGITLINK(two->mode)) &&
3838 (!diff_filepair_is_phoney(one, two))) {
3839 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3840 &one->oid, &two->oid,
3841 two->dirty_submodule);
3842 o->found_changes = 1;
3843 return;
3844 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3845 (!one->mode || S_ISGITLINK(one->mode)) &&
3846 (!two->mode || S_ISGITLINK(two->mode)) &&
3847 (!diff_filepair_is_phoney(one, two))) {
3848 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3849 &one->oid, &two->oid,
3850 two->dirty_submodule);
3851 o->found_changes = 1;
3852 return;
3853 }
3854
3855 if (o->flags.allow_textconv) {
3856 textconv_one = get_textconv(o->repo, one);
3857 textconv_two = get_textconv(o->repo, two);
3858 }
3859
3860 /* Never use a non-valid filename anywhere if at all possible */
3861 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3862 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3863
3864 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3865 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3866 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3867 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3868 if (diff_filepair_is_phoney(one, two)) {
3869 /*
3870 * We should only reach this point for pairs generated from
3871 * create_filepairs_for_header_only_notifications(). For
3872 * these, we want to avoid the "/dev/null" special casing
3873 * above, because we do not want such pairs shown as either
3874 * "new file" or "deleted file" below.
3875 */
3876 lbl[0] = a_one;
3877 lbl[1] = b_two;
3878 }
3879 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3880 if (lbl[0][0] == '/') {
3881 /* /dev/null */
3882 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3883 if (xfrm_msg)
3884 strbuf_addstr(&header, xfrm_msg);
3885 o->found_changes = 1;
3886 must_show_header = 1;
3887 }
3888 else if (lbl[1][0] == '/') {
3889 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3890 if (xfrm_msg)
3891 strbuf_addstr(&header, xfrm_msg);
3892 o->found_changes = 1;
3893 must_show_header = 1;
3894 }
3895 else {
3896 if (one->mode != two->mode) {
3897 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3898 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3899 o->found_changes = 1;
3900 must_show_header = 1;
3901 }
3902 if (xfrm_msg)
3903 strbuf_addstr(&header, xfrm_msg);
3904
3905 /*
3906 * we do not run diff between different kind
3907 * of objects.
3908 */
3909 if ((one->mode ^ two->mode) & S_IFMT)
3910 goto free_ab_and_return;
3911 if (complete_rewrite &&
3912 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3913 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3914 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3915 header.buf, header.len, 0);
3916 strbuf_reset(&header);
3917 emit_rewrite_diff(name_a, name_b, one, two,
3918 textconv_one, textconv_two, o);
3919 o->found_changes = 1;
3920 goto free_ab_and_return;
3921 }
3922 }
3923
3924 if (o->irreversible_delete && lbl[1][0] == '/') {
3925 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3926 header.len, 0);
3927 strbuf_reset(&header);
3928 goto free_ab_and_return;
3929 } else if (!o->flags.text &&
3930 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3931 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3932 struct strbuf sb = STRBUF_INIT;
3933 if (!one->data && !two->data &&
3934 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3935 !o->flags.binary) {
3936 if (oideq(&one->oid, &two->oid)) {
3937 if (must_show_header)
3938 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3939 header.buf, header.len,
3940 0);
3941 goto free_ab_and_return;
3942 }
3943 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3944 header.buf, header.len, 0);
3945 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3946 diff_line_prefix(o), lbl[0], lbl[1]);
3947 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3948 sb.buf, sb.len, 0);
3949 strbuf_release(&sb);
3950 o->found_changes = 1;
3951 goto free_ab_and_return;
3952 }
3953 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3954 fill_mmfile(o->repo, &mf2, two) < 0)
3955 die("unable to read files to diff");
3956 /* Quite common confusing case */
3957 if (mf1.size == mf2.size &&
3958 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3959 if (must_show_header)
3960 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3961 header.buf, header.len, 0);
3962 goto free_ab_and_return;
3963 }
3964 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3965 strbuf_reset(&header);
3966 if (o->flags.binary)
3967 emit_binary_diff(o, &mf1, &mf2);
3968 else {
3969 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3970 diff_line_prefix(o), lbl[0], lbl[1]);
3971 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3972 sb.buf, sb.len, 0);
3973 strbuf_release(&sb);
3974 }
3975 o->found_changes = 1;
3976 } else {
3977 /* Crazy xdl interfaces.. */
3978 const char *diffopts;
3979 const char *v;
3980 xpparam_t xpp;
3981 xdemitconf_t xecfg;
3982 struct emit_callback ecbdata;
3983 unsigned ws_rule;
3984 const struct userdiff_funcname *pe;
3985
3986 if (must_show_header) {
3987 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3988 header.buf, header.len, 0);
3989 strbuf_reset(&header);
3990 }
3991
3992 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3993 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3994
3995 ws_rule = whitespace_rule(o->repo->index, name_b);
3996
3997 /* symlink being an incomplete line is not a news */
3998 if (DIFF_FILE_VALID(two) && S_ISLNK(two->mode))
3999 ws_rule &= ~WS_INCOMPLETE_LINE;
4000
4001 pe = diff_funcname_pattern(o, one);
4002 if (!pe)
4003 pe = diff_funcname_pattern(o, two);
4004
4005 memset(&xpp, 0, sizeof(xpp));
4006 memset(&xecfg, 0, sizeof(xecfg));
4007 memset(&ecbdata, 0, sizeof(ecbdata));
4008 if (o->flags.suppress_diff_headers)
4009 lbl[0] = NULL;
4010 ecbdata.label_path = lbl;
4011 ecbdata.color_diff = o->use_color;
4012 ecbdata.ws_rule = ws_rule;
4013 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
4014 check_blank_at_eof(&mf1, &mf2, &ecbdata);
4015 ecbdata.opt = o;
4016 if (header.len && !o->flags.suppress_diff_headers)
4017 ecbdata.header = &header;
4018 xpp.flags = o->xdl_opts;
4019 xpp.ignore_regex = o->ignore_regex;
4020 xpp.ignore_regex_nr = o->ignore_regex_nr;
4021 xpp.anchors = o->anchors;
4022 xpp.anchors_nr = o->anchors_nr;
4023 xecfg.ctxlen = o->context;
4024 xecfg.interhunkctxlen = o->interhunkcontext;
4025 xecfg.flags = XDL_EMIT_FUNCNAMES;
4026 if (o->flags.funccontext)
4027 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
4028 if (pe)
4029 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
4030
4031 diffopts = getenv("GIT_DIFF_OPTS");
4032 if (!diffopts)
4033 ;
4034 else if (skip_prefix(diffopts, "--unified=", &v))
4035 xecfg.ctxlen = strtoul(v, NULL, 10);
4036 else if (skip_prefix(diffopts, "-u", &v))
4037 xecfg.ctxlen = strtoul(v, NULL, 10);
4038
4039 if (o->word_diff)
4040 init_diff_words_data(&ecbdata, o, one, two);
4041 if (!o->file) {
4042 /*
4043 * Unlike the normal output case, we need to ignore the
4044 * return value from xdi_diff_outf() here, because
4045 * xdi_diff_outf() takes non-zero return from its
4046 * callback function as a sign of error and returns
4047 * early (which is why we return non-zero from our
4048 * callback, quick_consume()). Unfortunately,
4049 * xdi_diff_outf() signals an error by returning
4050 * non-zero.
4051 */
4052 xdi_diff_outf(&mf1, &mf2, NULL, quick_consume,
4053 &ecbdata, &xpp, &xecfg);
4054 } else if (line_ranges) {
4055 struct line_range_callback lr_state;
4056 unsigned int i;
4057 long max_span = 0;
4058
4059 memset(&lr_state, 0, sizeof(lr_state));
4060 lr_state.orig_line_fn = fn_out_consume;
4061 lr_state.orig_cb_data = &ecbdata;
4062 lr_state.ranges = line_ranges;
4063 strbuf_init(&lr_state.rhunk, 0);
4064 strbuf_init(&lr_state.pending_rm, 0);
4065
4066 /*
4067 * Inflate ctxlen so that all changes within
4068 * any single range are merged into one xdiff
4069 * hunk and the inter-change context is emitted.
4070 * The callback clips back to range boundaries.
4071 *
4072 * The optimal ctxlen depends on where changes
4073 * fall within the range, which is only known
4074 * after xdiff runs; the max range span is the
4075 * upper bound that guarantees correctness in a
4076 * single pass.
4077 */
4078 for (i = 0; i < line_ranges->nr; i++) {
4079 long span = line_ranges->ranges[i].end -
4080 line_ranges->ranges[i].start;
4081 if (span > max_span)
4082 max_span = span;
4083 }
4084 if (max_span > xecfg.ctxlen)
4085 xecfg.ctxlen = max_span;
4086
4087 if (xdi_diff_outf(&mf1, &mf2,
4088 line_range_hunk_fn,
4089 line_range_line_fn,
4090 &lr_state, &xpp, &xecfg))
4091 die("unable to generate diff for %s",
4092 one->path);
4093
4094 flush_rhunk(&lr_state);
4095 if (lr_state.ret)
4096 die("unable to generate diff for %s",
4097 one->path);
4098 strbuf_release(&lr_state.rhunk);
4099 strbuf_release(&lr_state.pending_rm);
4100 } else if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
4101 &ecbdata, &xpp, &xecfg))
4102 die("unable to generate diff for %s", one->path);
4103 if (o->word_diff)
4104 free_diff_words_data(&ecbdata);
4105 if (textconv_one)
4106 free(mf1.ptr);
4107 if (textconv_two)
4108 free(mf2.ptr);
4109 xdiff_clear_find_func(&xecfg);
4110 }
4111
4112 free_ab_and_return:
4113 strbuf_release(&header);
4114 diff_free_filespec_data(one);
4115 diff_free_filespec_data(two);
4116 free(a_one);
4117 free(b_two);
4118 return;
4119}
4120
4121static const char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
4122{
4123 if (!is_renamed) {
4124 if (p->status == DIFF_STATUS_ADDED) {
4125 if (S_ISLNK(p->two->mode))
4126 return "new +l";
4127 else if ((p->two->mode & 0777) == 0755)
4128 return "new +x";
4129 else
4130 return "new";
4131 } else if (p->status == DIFF_STATUS_DELETED)
4132 return "gone";
4133 }
4134 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
4135 return "mode -l";
4136 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
4137 return "mode +l";
4138 else if ((p->one->mode & 0777) == 0644 &&
4139 (p->two->mode & 0777) == 0755)
4140 return "mode +x";
4141 else if ((p->one->mode & 0777) == 0755 &&
4142 (p->two->mode & 0777) == 0644)
4143 return "mode -x";
4144 return NULL;
4145}
4146
4147static void builtin_diffstat(const char *name_a, const char *name_b,
4148 struct diff_filespec *one,
4149 struct diff_filespec *two,
4150 struct diffstat_t *diffstat,
4151 struct diff_options *o,
4152 struct diff_filepair *p)
4153{
4154 mmfile_t mf1, mf2;
4155 struct diffstat_file *data;
4156 int may_differ;
4157 int complete_rewrite = 0;
4158
4159 if (!DIFF_PAIR_UNMERGED(p)) {
4160 if (p->status == DIFF_STATUS_MODIFIED && p->score)
4161 complete_rewrite = 1;
4162 }
4163
4164 data = diffstat_add(diffstat, name_a, name_b);
4165 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
4166 if (o->flags.stat_with_summary)
4167 data->comments = get_compact_summary(p, data->is_renamed);
4168
4169 if (!one || !two) {
4170 data->is_unmerged = 1;
4171 return;
4172 }
4173
4174 /* saves some reads if true, not a guarantee of diff outcome */
4175 may_differ = !(one->oid_valid && two->oid_valid &&
4176 oideq(&one->oid, &two->oid));
4177
4178 if (diff_filespec_is_binary(o->repo, one) ||
4179 diff_filespec_is_binary(o->repo, two)) {
4180 data->is_binary = 1;
4181 if (!may_differ) {
4182 data->added = 0;
4183 data->deleted = 0;
4184 } else {
4185 data->added = diff_filespec_size(o->repo, two);
4186 data->deleted = diff_filespec_size(o->repo, one);
4187 }
4188 }
4189
4190 else if (complete_rewrite) {
4191 diff_populate_filespec(o->repo, one, NULL);
4192 diff_populate_filespec(o->repo, two, NULL);
4193 data->deleted = count_lines(one->data, one->size);
4194 data->added = count_lines(two->data, two->size);
4195 }
4196
4197 else if (may_differ) {
4198 /* Crazy xdl interfaces.. */
4199 xpparam_t xpp;
4200 xdemitconf_t xecfg;
4201
4202 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
4203 fill_mmfile(o->repo, &mf2, two) < 0)
4204 die("unable to read files to diff");
4205
4206 memset(&xpp, 0, sizeof(xpp));
4207 memset(&xecfg, 0, sizeof(xecfg));
4208 xpp.flags = o->xdl_opts;
4209 xpp.ignore_regex = o->ignore_regex;
4210 xpp.ignore_regex_nr = o->ignore_regex_nr;
4211 xpp.anchors = o->anchors;
4212 xpp.anchors_nr = o->anchors_nr;
4213 xecfg.ctxlen = o->context;
4214 xecfg.interhunkctxlen = o->interhunkcontext;
4215 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
4216 if (xdi_diff_outf(&mf1, &mf2, NULL,
4217 diffstat_consume, diffstat, &xpp, &xecfg))
4218 die("unable to generate diffstat for %s", one->path);
4219
4220 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
4221 struct diffstat_file *file =
4222 diffstat->files[diffstat->nr - 1];
4223 /*
4224 * Omit diffstats of modified files where nothing changed.
4225 * Even if may_differ, this might be the case due to
4226 * ignoring whitespace changes, etc.
4227 *
4228 * But note that we special-case additions, deletions,
4229 * renames, and mode changes as adding an empty file,
4230 * for example is still of interest.
4231 */
4232 if ((p->status == DIFF_STATUS_MODIFIED)
4233 && !file->added
4234 && !file->deleted
4235 && one->mode == two->mode) {
4236 free_diffstat_file(file);
4237 diffstat->nr--;
4238 }
4239 }
4240 }
4241
4242 diff_free_filespec_data(one);
4243 diff_free_filespec_data(two);
4244}
4245
4246static void builtin_checkdiff(const char *name_a, const char *name_b,
4247 const char *attr_path,
4248 struct diff_filespec *one,
4249 struct diff_filespec *two,
4250 struct diff_options *o)
4251{
4252 mmfile_t mf1, mf2;
4253 struct checkdiff_t data;
4254
4255 if (!two)
4256 return;
4257
4258 memset(&data, 0, sizeof(data));
4259 data.filename = name_b ? name_b : name_a;
4260 data.lineno = 0;
4261 data.o = o;
4262 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
4263 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
4264
4265 /* symlink being an incomplete line is not a news */
4266 if (DIFF_FILE_VALID(two) && S_ISLNK(two->mode))
4267 data.ws_rule &= ~WS_INCOMPLETE_LINE;
4268
4269 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
4270 fill_mmfile(o->repo, &mf2, two) < 0)
4271 die("unable to read files to diff");
4272
4273 /*
4274 * All the other codepaths check both sides, but not checking
4275 * the "old" side here is deliberate. We are checking the newly
4276 * introduced changes, and as long as the "new" side is text, we
4277 * can and should check what it introduces.
4278 */
4279 if (diff_filespec_is_binary(o->repo, two))
4280 goto free_and_return;
4281 else {
4282 /* Crazy xdl interfaces.. */
4283 xpparam_t xpp;
4284 xdemitconf_t xecfg;
4285
4286 memset(&xpp, 0, sizeof(xpp));
4287 memset(&xecfg, 0, sizeof(xecfg));
4288 xecfg.ctxlen = 1; /* at least one context line */
4289 xpp.flags = 0;
4290 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
4291 checkdiff_consume, &data,
4292 &xpp, &xecfg))
4293 die("unable to generate checkdiff for %s", one->path);
4294
4295 if (data.ws_rule & WS_BLANK_AT_EOF) {
4296 struct emit_callback ecbdata;
4297 int blank_at_eof;
4298
4299 ecbdata.ws_rule = data.ws_rule;
4300 check_blank_at_eof(&mf1, &mf2, &ecbdata);
4301 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
4302
4303 if (blank_at_eof) {
4304 static char *err;
4305 if (!err)
4306 err = whitespace_error_string(WS_BLANK_AT_EOF);
4307 fprintf(o->file, "%s:%d: %s.\n",
4308 data.filename, blank_at_eof, err);
4309 data.status = 1; /* report errors */
4310 }
4311 }
4312 }
4313 free_and_return:
4314 diff_free_filespec_data(one);
4315 diff_free_filespec_data(two);
4316 if (data.status)
4317 o->flags.check_failed = 1;
4318}
4319
4320struct diff_filespec *alloc_filespec(const char *path)
4321{
4322 struct diff_filespec *spec;
4323
4324 FLEXPTR_ALLOC_STR(spec, path, path);
4325 spec->count = 1;
4326 spec->is_binary = -1;
4327 return spec;
4328}
4329
4330void free_filespec(struct diff_filespec *spec)
4331{
4332 if (!--spec->count) {
4333 diff_free_filespec_data(spec);
4334 free(spec);
4335 }
4336}
4337
4338void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
4339 int oid_valid, unsigned short mode)
4340{
4341 if (mode) {
4342 spec->mode = canon_mode(mode);
4343 oidcpy(&spec->oid, oid);
4344 spec->oid_valid = oid_valid;
4345 }
4346}
4347
4348/*
4349 * Given a name and sha1 pair, if the index tells us the file in
4350 * the work tree has that object contents, return true, so that
4351 * prepare_temp_file() does not have to inflate and extract.
4352 */
4353static int reuse_worktree_file(struct index_state *istate,
4354 const char *name,
4355 const struct object_id *oid,
4356 int want_file)
4357{
4358 const struct cache_entry *ce;
4359 struct stat st;
4360 int pos, len;
4361
4362 /*
4363 * We do not read the cache ourselves here, because the
4364 * benchmark with my previous version that always reads cache
4365 * shows that it makes things worse for diff-tree comparing
4366 * two linux-2.6 kernel trees in an already checked out work
4367 * tree. This is because most diff-tree comparisons deal with
4368 * only a small number of files, while reading the cache is
4369 * expensive for a large project, and its cost outweighs the
4370 * savings we get by not inflating the object to a temporary
4371 * file. Practically, this code only helps when we are used
4372 * by diff-cache --cached, which does read the cache before
4373 * calling us.
4374 */
4375 if (!istate->cache)
4376 return 0;
4377
4378 /* We want to avoid the working directory if our caller
4379 * doesn't need the data in a normal file, this system
4380 * is rather slow with its stat/open/mmap/close syscalls,
4381 * and the object is contained in a pack file. The pack
4382 * is probably already open and will be faster to obtain
4383 * the data through than the working directory. Loose
4384 * objects however would tend to be slower as they need
4385 * to be individually opened and inflated.
4386 */
4387 if (!FAST_WORKING_DIRECTORY && !want_file &&
4388 has_object_pack(istate->repo, oid))
4389 return 0;
4390
4391 /*
4392 * Similarly, if we'd have to convert the file contents anyway, that
4393 * makes the optimization not worthwhile.
4394 */
4395 if (!want_file && would_convert_to_git(istate, name))
4396 return 0;
4397
4398 /*
4399 * If this path does not match our sparse-checkout definition,
4400 * then the file will not be in the working directory.
4401 */
4402 if (!path_in_sparse_checkout(name, istate))
4403 return 0;
4404
4405 len = strlen(name);
4406 pos = index_name_pos(istate, name, len);
4407 if (pos < 0)
4408 return 0;
4409 ce = istate->cache[pos];
4410
4411 /*
4412 * This is not the sha1 we are looking for, or
4413 * unreusable because it is not a regular file.
4414 */
4415 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4416 return 0;
4417
4418 /*
4419 * If ce is marked as "assume unchanged", there is no
4420 * guarantee that work tree matches what we are looking for.
4421 */
4422 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4423 return 0;
4424
4425 /*
4426 * If ce matches the file in the work tree, we can reuse it.
4427 */
4428 if (ce_uptodate(ce) ||
4429 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4430 return 1;
4431
4432 return 0;
4433}
4434
4435static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4436{
4437 struct strbuf buf = STRBUF_INIT;
4438 const char *dirty = "";
4439
4440 /* Are we looking at the work tree? */
4441 if (s->dirty_submodule)
4442 dirty = "-dirty";
4443
4444 strbuf_addf(&buf, "Subproject commit %s%s\n",
4445 oid_to_hex(&s->oid), dirty);
4446 s->size = buf.len;
4447 if (size_only) {
4448 s->data = NULL;
4449 strbuf_release(&buf);
4450 } else {
4451 s->data = strbuf_detach(&buf, NULL);
4452 s->should_free = 1;
4453 }
4454 return 0;
4455}
4456
4457/*
4458 * While doing rename detection and pickaxe operation, we may need to
4459 * grab the data for the blob (or file) for our own in-core comparison.
4460 * diff_filespec has data and size fields for this purpose.
4461 */
4462int diff_populate_filespec(struct repository *r,
4463 struct diff_filespec *s,
4464 const struct diff_populate_filespec_options *options)
4465{
4466 int size_only = options ? options->check_size_only : 0;
4467 int check_binary = options ? options->check_binary : 0;
4468 int err = 0;
4469 int conv_flags = global_conv_flags_eol;
4470 /*
4471 * demote FAIL to WARN to allow inspecting the situation
4472 * instead of refusing.
4473 */
4474 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4475 conv_flags = CONV_EOL_RNDTRP_WARN;
4476
4477 if (!DIFF_FILE_VALID(s))
4478 die("internal error: asking to populate invalid file.");
4479 if (S_ISDIR(s->mode))
4480 return -1;
4481
4482 if (s->data)
4483 return 0;
4484
4485 if (size_only && 0 < s->size)
4486 return 0;
4487
4488 if (S_ISGITLINK(s->mode))
4489 return diff_populate_gitlink(s, size_only);
4490
4491 if (!s->oid_valid ||
4492 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4493 struct strbuf buf = STRBUF_INIT;
4494 struct stat st;
4495 int fd;
4496
4497 if (lstat(s->path, &st) < 0) {
4498 err_empty:
4499 err = -1;
4500 empty:
4501 s->data = (char *)"";
4502 s->size = 0;
4503 return err;
4504 }
4505 s->size = xsize_t(st.st_size);
4506 if (!s->size)
4507 goto empty;
4508 if (S_ISLNK(st.st_mode)) {
4509 struct strbuf sb = STRBUF_INIT;
4510
4511 if (strbuf_readlink(&sb, s->path, s->size))
4512 goto err_empty;
4513 s->size = sb.len;
4514 s->data = strbuf_detach(&sb, NULL);
4515 s->should_free = 1;
4516 return 0;
4517 }
4518
4519 /*
4520 * Even if the caller would be happy with getting
4521 * only the size, we cannot return early at this
4522 * point if the path requires us to run the content
4523 * conversion.
4524 */
4525 if (size_only && !would_convert_to_git(r->index, s->path))
4526 return 0;
4527
4528 /*
4529 * Note: this check uses xsize_t(st.st_size) that may
4530 * not be the true size of the blob after it goes
4531 * through convert_to_git(). This may not strictly be
4532 * correct, but the whole point of big_file_threshold
4533 * and is_binary check being that we want to avoid
4534 * opening the file and inspecting the contents, this
4535 * is probably fine.
4536 */
4537 if (check_binary &&
4538 s->size > repo_settings_get_big_file_threshold(the_repository) &&
4539 s->is_binary == -1) {
4540 s->is_binary = 1;
4541 return 0;
4542 }
4543 fd = open(s->path, O_RDONLY);
4544 if (fd < 0)
4545 goto err_empty;
4546 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4547 close(fd);
4548 s->should_munmap = 1;
4549
4550 /*
4551 * Convert from working tree format to canonical git format
4552 */
4553 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4554 size_t size = 0;
4555 munmap(s->data, s->size);
4556 s->should_munmap = 0;
4557 s->data = strbuf_detach(&buf, &size);
4558 s->size = size;
4559 s->should_free = 1;
4560 }
4561 }
4562 else {
4563 size_t size_st = 0;
4564 struct object_info info = {
4565 .sizep = &size_st
4566 };
4567
4568 if (!(size_only || check_binary))
4569 /*
4570 * Set contentp, since there is no chance that merely
4571 * the size is sufficient.
4572 */
4573 info.contentp = &s->data;
4574
4575 if (options && options->missing_object_cb) {
4576 if (!odb_read_object_info_extended(r->objects, &s->oid, &info,
4577 OBJECT_INFO_LOOKUP_REPLACE |
4578 OBJECT_INFO_SKIP_FETCH_OBJECT))
4579 goto object_read;
4580 options->missing_object_cb(options->missing_object_data);
4581 }
4582 if (odb_read_object_info_extended(r->objects, &s->oid, &info,
4583 OBJECT_INFO_LOOKUP_REPLACE))
4584 die("unable to read %s", oid_to_hex(&s->oid));
4585
4586object_read:
4587 s->size = cast_size_t_to_ulong(size_st);
4588 if (size_only || check_binary) {
4589 if (size_only)
4590 return 0;
4591 if (s->size > repo_settings_get_big_file_threshold(the_repository) &&
4592 s->is_binary == -1) {
4593 s->is_binary = 1;
4594 return 0;
4595 }
4596 }
4597 if (!info.contentp) {
4598 info.contentp = &s->data;
4599 if (odb_read_object_info_extended(r->objects, &s->oid, &info,
4600 OBJECT_INFO_LOOKUP_REPLACE))
4601 die("unable to read %s", oid_to_hex(&s->oid));
4602 s->size = cast_size_t_to_ulong(size_st);
4603 }
4604 s->should_free = 1;
4605 }
4606 return 0;
4607}
4608
4609void diff_free_filespec_blob(struct diff_filespec *s)
4610{
4611 if (s->should_free)
4612 free(s->data);
4613 else if (s->should_munmap)
4614 munmap(s->data, s->size);
4615
4616 if (s->should_free || s->should_munmap) {
4617 s->should_free = s->should_munmap = 0;
4618 s->data = NULL;
4619 }
4620}
4621
4622void diff_free_filespec_data(struct diff_filespec *s)
4623{
4624 if (!s)
4625 return;
4626
4627 diff_free_filespec_blob(s);
4628 FREE_AND_NULL(s->cnt_data);
4629}
4630
4631static void prep_temp_blob(struct index_state *istate,
4632 const char *path, struct diff_tempfile *temp,
4633 void *blob,
4634 unsigned long size,
4635 const struct object_id *oid,
4636 int mode)
4637{
4638 struct strbuf buf = STRBUF_INIT;
4639 char *path_dup = xstrdup(path);
4640 const char *base = basename(path_dup);
4641 struct checkout_metadata meta;
4642
4643 init_checkout_metadata(&meta, NULL, NULL, oid);
4644
4645 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4646 if (!temp->tempfile)
4647 die_errno("unable to create temp-file");
4648 if (convert_to_working_tree(istate, path,
4649 (const char *)blob, (size_t)size, &buf, &meta)) {
4650 blob = buf.buf;
4651 size = buf.len;
4652 }
4653 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4654 close_tempfile_gently(temp->tempfile))
4655 die_errno("unable to write temp-file");
4656 temp->name = get_tempfile_path(temp->tempfile);
4657 oid_to_hex_r(temp->hex, oid);
4658 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4659 strbuf_release(&buf);
4660 free(path_dup);
4661}
4662
4663static struct diff_tempfile *prepare_temp_file(struct repository *r,
4664 struct diff_filespec *one)
4665{
4666 struct diff_tempfile *temp = claim_diff_tempfile();
4667
4668 if (!DIFF_FILE_VALID(one)) {
4669 not_a_valid_file:
4670 /* A '-' entry produces this for file-2, and
4671 * a '+' entry produces this for file-1.
4672 */
4673 temp->name = "/dev/null";
4674 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4675 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4676 return temp;
4677 }
4678
4679 if (!S_ISGITLINK(one->mode) &&
4680 (!one->oid_valid ||
4681 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4682 struct stat st;
4683 if (lstat(one->path, &st) < 0) {
4684 if (errno == ENOENT)
4685 goto not_a_valid_file;
4686 die_errno("stat(%s)", one->path);
4687 }
4688 if (S_ISLNK(st.st_mode)) {
4689 struct strbuf sb = STRBUF_INIT;
4690 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4691 die_errno("readlink(%s)", one->path);
4692 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4693 (one->oid_valid ?
4694 &one->oid : null_oid(the_hash_algo)),
4695 (one->oid_valid ?
4696 one->mode : S_IFLNK));
4697 strbuf_release(&sb);
4698 }
4699 else {
4700 /* we can borrow from the file in the work tree */
4701 temp->name = one->path;
4702 if (!one->oid_valid)
4703 oid_to_hex_r(temp->hex, null_oid(the_hash_algo));
4704 else
4705 oid_to_hex_r(temp->hex, &one->oid);
4706 /* Even though we may sometimes borrow the
4707 * contents from the work tree, we always want
4708 * one->mode. mode is trustworthy even when
4709 * !(one->oid_valid), as long as
4710 * DIFF_FILE_VALID(one).
4711 */
4712 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4713 }
4714 return temp;
4715 }
4716 else {
4717 if (diff_populate_filespec(r, one, NULL))
4718 die("cannot read data blob for %s", one->path);
4719 prep_temp_blob(r->index, one->path, temp,
4720 one->data, one->size,
4721 &one->oid, one->mode);
4722 }
4723 return temp;
4724}
4725
4726static void add_external_diff_name(struct repository *r,
4727 struct strvec *argv,
4728 struct diff_filespec *df)
4729{
4730 struct diff_tempfile *temp = prepare_temp_file(r, df);
4731 strvec_push(argv, temp->name);
4732 strvec_push(argv, temp->hex);
4733 strvec_push(argv, temp->mode);
4734}
4735
4736/* An external diff command takes:
4737 *
4738 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4739 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4740 *
4741 */
4742static void run_external_diff(const struct external_diff *pgm,
4743 const char *name,
4744 const char *other,
4745 struct diff_filespec *one,
4746 struct diff_filespec *two,
4747 const char *xfrm_msg,
4748 struct diff_options *o)
4749{
4750 struct child_process cmd = CHILD_PROCESS_INIT;
4751 struct diff_queue_struct *q = &diff_queued_diff;
4752 int rc;
4753
4754 /*
4755 * Trivial equality is handled by diff_unmodified_pair() before
4756 * we get here. If we don't need to show the diff and the
4757 * external diff program lacks the ability to tell us whether
4758 * it's empty then we consider it non-empty without even asking.
4759 */
4760 if (!pgm->trust_exit_code && !o->file) {
4761 o->found_changes = 1;
4762 return;
4763 }
4764
4765 strvec_push(&cmd.args, pgm->cmd);
4766 strvec_push(&cmd.args, name);
4767
4768 if (one && two) {
4769 add_external_diff_name(o->repo, &cmd.args, one);
4770 add_external_diff_name(o->repo, &cmd.args, two);
4771 if (other) {
4772 strvec_push(&cmd.args, other);
4773 if (xfrm_msg)
4774 strvec_push(&cmd.args, xfrm_msg);
4775 }
4776 }
4777
4778 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4779 ++o->diff_path_counter);
4780 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4781
4782 diff_free_filespec_data(one);
4783 diff_free_filespec_data(two);
4784 cmd.use_shell = 1;
4785 if (!o->file)
4786 cmd.no_stdout = 1;
4787 else if (o->file != stdout)
4788 cmd.out = xdup(fileno(o->file));
4789 rc = run_command(&cmd);
4790 if (!pgm->trust_exit_code && rc == 0)
4791 o->found_changes = 1;
4792 else if (pgm->trust_exit_code && rc == 0)
4793 ; /* nothing */
4794 else if (pgm->trust_exit_code && rc == 1)
4795 o->found_changes = 1;
4796 else
4797 die(_("external diff died, stopping at %s"), name);
4798
4799 remove_tempfile();
4800}
4801
4802static int similarity_index(struct diff_filepair *p)
4803{
4804 return p->score * 100 / MAX_SCORE;
4805}
4806
4807static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4808{
4809 if (startup_info->have_repository)
4810 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4811 else {
4812 char *hex = oid_to_hex(oid);
4813 if (abbrev < 0)
4814 abbrev = FALLBACK_DEFAULT_ABBREV;
4815 if (abbrev > the_hash_algo->hexsz)
4816 BUG("oid abbreviation out of range: %d", abbrev);
4817 if (abbrev)
4818 hex[abbrev] = '\0';
4819 return hex;
4820 }
4821}
4822
4823static void fill_metainfo(struct strbuf *msg,
4824 const char *name,
4825 const char *other,
4826 struct diff_filespec *one,
4827 struct diff_filespec *two,
4828 struct diff_options *o,
4829 struct diff_filepair *p,
4830 int *must_show_header,
4831 enum git_colorbool use_color)
4832{
4833 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4834 const char *reset = diff_get_color(use_color, DIFF_RESET);
4835 const char *line_prefix = diff_line_prefix(o);
4836 struct string_list *more_headers = NULL;
4837
4838 *must_show_header = 1;
4839 strbuf_init(msg, PATH_MAX * 2 + 300);
4840 switch (p->status) {
4841 case DIFF_STATUS_COPIED:
4842 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4843 line_prefix, set, similarity_index(p));
4844 strbuf_addf(msg, "%s\n%s%scopy from ",
4845 reset, line_prefix, set);
4846 quote_c_style(name, msg, NULL, 0);
4847 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4848 quote_c_style(other, msg, NULL, 0);
4849 strbuf_addf(msg, "%s\n", reset);
4850 break;
4851 case DIFF_STATUS_RENAMED:
4852 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4853 line_prefix, set, similarity_index(p));
4854 strbuf_addf(msg, "%s\n%s%srename from ",
4855 reset, line_prefix, set);
4856 quote_c_style(name, msg, NULL, 0);
4857 strbuf_addf(msg, "%s\n%s%srename to ",
4858 reset, line_prefix, set);
4859 quote_c_style(other, msg, NULL, 0);
4860 strbuf_addf(msg, "%s\n", reset);
4861 break;
4862 case DIFF_STATUS_MODIFIED:
4863 if (p->score) {
4864 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4865 line_prefix,
4866 set, similarity_index(p), reset);
4867 break;
4868 }
4869 /* fallthru */
4870 default:
4871 *must_show_header = 0;
4872 }
4873 if ((more_headers = additional_headers(o, name))) {
4874 add_formatted_headers(msg, more_headers,
4875 line_prefix, set, reset);
4876 *must_show_header = 1;
4877 }
4878 if (one && two && !oideq(&one->oid, &two->oid)) {
4879 const unsigned hexsz = the_hash_algo->hexsz;
4880 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4881
4882 if (o->flags.full_index)
4883 abbrev = hexsz;
4884
4885 if (o->flags.binary) {
4886 mmfile_t mf;
4887 if ((!fill_mmfile(o->repo, &mf, one) &&
4888 diff_filespec_is_binary(o->repo, one)) ||
4889 (!fill_mmfile(o->repo, &mf, two) &&
4890 diff_filespec_is_binary(o->repo, two)))
4891 abbrev = hexsz;
4892 }
4893 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4894 diff_abbrev_oid(&one->oid, abbrev),
4895 diff_abbrev_oid(&two->oid, abbrev));
4896 if (one->mode == two->mode)
4897 strbuf_addf(msg, " %06o", one->mode);
4898 strbuf_addf(msg, "%s\n", reset);
4899 }
4900}
4901
4902static void run_diff_cmd(const struct external_diff *pgm,
4903 const char *name,
4904 const char *other,
4905 const char *attr_path,
4906 struct diff_filespec *one,
4907 struct diff_filespec *two,
4908 struct strbuf *msg,
4909 struct diff_options *o,
4910 struct diff_filepair *p)
4911{
4912 const char *xfrm_msg = NULL;
4913 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4914 int must_show_header = 0;
4915 struct userdiff_driver *drv = NULL;
4916
4917 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4918 drv = userdiff_find_by_path(o->repo->index, attr_path);
4919
4920 if (o->flags.allow_external && drv && drv->external.cmd)
4921 pgm = &drv->external;
4922
4923 if (msg) {
4924 /*
4925 * don't use colors when the header is intended for an
4926 * external diff driver
4927 */
4928 fill_metainfo(msg, name, other, one, two, o, p,
4929 &must_show_header,
4930 pgm ? GIT_COLOR_NEVER : o->use_color);
4931 xfrm_msg = msg->len ? msg->buf : NULL;
4932 }
4933
4934 if (pgm) {
4935 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4936 return;
4937 }
4938 if (one && two) {
4939 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4940 set_diff_algorithm(o, drv->algorithm);
4941
4942 builtin_diff(name, other ? other : name,
4943 one, two, xfrm_msg, must_show_header,
4944 o, complete_rewrite, p->line_ranges);
4945 if (p->status == DIFF_STATUS_COPIED ||
4946 p->status == DIFF_STATUS_RENAMED)
4947 o->found_changes = 1;
4948 } else {
4949 if (o->file)
4950 fprintf(o->file, "* Unmerged path %s\n", name);
4951 o->found_changes = 1;
4952 }
4953}
4954
4955static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4956{
4957 if (DIFF_FILE_VALID(one)) {
4958 if (!one->oid_valid) {
4959 struct stat st;
4960 if (one->is_stdin) {
4961 oidclr(&one->oid, the_repository->hash_algo);
4962 return;
4963 }
4964 if (lstat(one->path, &st) < 0)
4965 die_errno("stat '%s'", one->path);
4966 if (index_path(istate, &one->oid, one->path, &st, 0))
4967 die("cannot hash %s", one->path);
4968 }
4969 }
4970 else
4971 oidclr(&one->oid, the_repository->hash_algo);
4972}
4973
4974static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4975{
4976 /* Strip the prefix but do not molest /dev/null and absolute paths */
4977 if (*namep && !is_absolute_path(*namep)) {
4978 *namep += prefix_length;
4979 if (**namep == '/')
4980 ++*namep;
4981 }
4982 if (*otherp && !is_absolute_path(*otherp)) {
4983 *otherp += prefix_length;
4984 if (**otherp == '/')
4985 ++*otherp;
4986 }
4987}
4988
4989static void run_diff(struct diff_filepair *p, struct diff_options *o)
4990{
4991 const struct external_diff *pgm = external_diff();
4992 struct strbuf msg;
4993 struct diff_filespec *one = p->one;
4994 struct diff_filespec *two = p->two;
4995 const char *name;
4996 const char *other;
4997 const char *attr_path;
4998
4999 name = one->path;
5000 other = (strcmp(name, two->path) ? two->path : NULL);
5001 attr_path = name;
5002 if (o->prefix_length)
5003 strip_prefix(o->prefix_length, &name, &other);
5004
5005 if (!o->flags.allow_external)
5006 pgm = NULL;
5007
5008 if (DIFF_PAIR_UNMERGED(p)) {
5009 run_diff_cmd(pgm, name, NULL, attr_path,
5010 NULL, NULL, NULL, o, p);
5011 return;
5012 }
5013
5014 diff_fill_oid_info(one, o->repo->index);
5015 diff_fill_oid_info(two, o->repo->index);
5016
5017 if (!pgm &&
5018 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
5019 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
5020 /*
5021 * a filepair that changes between file and symlink
5022 * needs to be split into deletion and creation.
5023 */
5024 struct diff_filespec *null = alloc_filespec(two->path);
5025 run_diff_cmd(NULL, name, other, attr_path,
5026 one, null, &msg,
5027 o, p);
5028 free(null);
5029 strbuf_release(&msg);
5030
5031 null = alloc_filespec(one->path);
5032 run_diff_cmd(NULL, name, other, attr_path,
5033 null, two, &msg, o, p);
5034 free(null);
5035 }
5036 else
5037 run_diff_cmd(pgm, name, other, attr_path,
5038 one, two, &msg, o, p);
5039
5040 strbuf_release(&msg);
5041}
5042
5043static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
5044 struct diffstat_t *diffstat)
5045{
5046 const char *name;
5047 const char *other;
5048
5049 if (!o->ignore_driver_algorithm) {
5050 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
5051 p->one->path);
5052
5053 if (drv && drv->algorithm)
5054 set_diff_algorithm(o, drv->algorithm);
5055 }
5056
5057 if (DIFF_PAIR_UNMERGED(p)) {
5058 /* unmerged */
5059 builtin_diffstat(p->one->path, NULL, NULL, NULL,
5060 diffstat, o, p);
5061 return;
5062 }
5063
5064 name = p->one->path;
5065 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
5066
5067 if (o->prefix_length)
5068 strip_prefix(o->prefix_length, &name, &other);
5069
5070 diff_fill_oid_info(p->one, o->repo->index);
5071 diff_fill_oid_info(p->two, o->repo->index);
5072
5073 builtin_diffstat(name, other, p->one, p->two,
5074 diffstat, o, p);
5075}
5076
5077static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
5078{
5079 const char *name;
5080 const char *other;
5081 const char *attr_path;
5082
5083 if (DIFF_PAIR_UNMERGED(p)) {
5084 /* unmerged */
5085 return;
5086 }
5087
5088 name = p->one->path;
5089 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
5090 attr_path = other ? other : name;
5091
5092 if (o->prefix_length)
5093 strip_prefix(o->prefix_length, &name, &other);
5094
5095 diff_fill_oid_info(p->one, o->repo->index);
5096 diff_fill_oid_info(p->two, o->repo->index);
5097
5098 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
5099}
5100
5101void repo_diff_setup(struct repository *r, struct diff_options *options)
5102{
5103 memcpy(options, &default_diff_options, sizeof(*options));
5104
5105 options->file = stdout;
5106 options->repo = r;
5107
5108 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
5109 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
5110 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
5111 options->abbrev = DEFAULT_ABBREV;
5112 options->line_termination = '\n';
5113 options->break_opt = -1;
5114 options->rename_limit = -1;
5115 options->dirstat_permille = diff_dirstat_permille_default;
5116 options->context = diff_context_default;
5117 options->interhunkcontext = diff_interhunk_context_default;
5118 options->ws_error_highlight = ws_error_highlight_default;
5119 options->flags.rename_empty = 1;
5120 options->flags.relative_name = diff_relative;
5121 options->objfind = NULL;
5122
5123 /* pathchange left =NULL by default */
5124 options->change = diff_change;
5125 options->add_remove = diff_addremove;
5126 options->use_color = diff_use_color_default;
5127 options->detect_rename = diff_detect_rename_default;
5128 options->xdl_opts |= diff_algorithm;
5129 if (diff_indent_heuristic)
5130 DIFF_XDL_SET(options, INDENT_HEURISTIC);
5131
5132 options->orderfile = xstrdup_or_null(diff_order_file_cfg);
5133
5134 if (!options->flags.ignore_submodule_set)
5135 options->flags.ignore_untracked_in_submodules = 1;
5136
5137 if (diff_no_prefix) {
5138 diff_set_noprefix(options);
5139 } else if (!diff_mnemonic_prefix) {
5140 diff_set_default_prefix(options);
5141 }
5142
5143 options->color_moved = diff_color_moved_default;
5144 options->color_moved_ws_handling = diff_color_moved_ws_default;
5145}
5146
5147static const char diff_status_letters[] = {
5148 DIFF_STATUS_ADDED,
5149 DIFF_STATUS_COPIED,
5150 DIFF_STATUS_DELETED,
5151 DIFF_STATUS_MODIFIED,
5152 DIFF_STATUS_RENAMED,
5153 DIFF_STATUS_TYPE_CHANGED,
5154 DIFF_STATUS_UNKNOWN,
5155 DIFF_STATUS_UNMERGED,
5156 DIFF_STATUS_FILTER_AON,
5157 DIFF_STATUS_FILTER_BROKEN,
5158 '\0',
5159};
5160
5161static unsigned int filter_bit['Z' + 1];
5162
5163static void prepare_filter_bits(void)
5164{
5165 int i;
5166
5167 if (!filter_bit[DIFF_STATUS_ADDED]) {
5168 for (i = 0; diff_status_letters[i]; i++)
5169 filter_bit[(int) diff_status_letters[i]] = (1 << i);
5170 }
5171}
5172
5173static unsigned filter_bit_tst(char status, const struct diff_options *opt)
5174{
5175 return opt->filter & filter_bit[(int) status];
5176}
5177
5178unsigned diff_filter_bit(char status)
5179{
5180 prepare_filter_bits();
5181 return filter_bit[(int) status];
5182}
5183
5184int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
5185{
5186 unsigned forbidden_magic;
5187
5188 if (ps->nr != 1) {
5189 if (die_on_error)
5190 die(_("--follow requires exactly one pathspec"));
5191 return 0;
5192 }
5193
5194 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
5195 PATHSPEC_LITERAL);
5196 if (forbidden_magic) {
5197 if (die_on_error) {
5198 struct strbuf sb = STRBUF_INIT;
5199 pathspec_magic_names(forbidden_magic, &sb);
5200 die(_("pathspec magic not supported by --follow: %s"),
5201 sb.buf);
5202 }
5203 return 0;
5204 }
5205
5206 return 1;
5207}
5208
5209void diff_setup_done(struct diff_options *options)
5210{
5211 unsigned check_mask = DIFF_FORMAT_NAME |
5212 DIFF_FORMAT_NAME_STATUS |
5213 DIFF_FORMAT_CHECKDIFF |
5214 DIFF_FORMAT_NO_OUTPUT;
5215 /*
5216 * This must be signed because we're comparing against a potentially
5217 * negative value.
5218 */
5219 const int hexsz = the_hash_algo->hexsz;
5220
5221 if (options->set_default)
5222 options->set_default(options);
5223
5224 if (HAS_MULTI_BITS(options->output_format & check_mask))
5225 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
5226 "--name-only", "--name-status", "--check", "-s");
5227
5228 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
5229 die(_("options '%s', '%s', and '%s' cannot be used together"),
5230 "-G", "-S", "--find-object");
5231
5232 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
5233 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
5234 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
5235
5236 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
5237 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
5238 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
5239
5240 /*
5241 * Most of the time we can say "there are changes"
5242 * only by checking if there are changed paths, but
5243 * --ignore-whitespace* options force us to look
5244 * inside contents.
5245 */
5246
5247 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
5248 options->ignore_regex_nr)
5249 options->flags.diff_from_contents = 1;
5250 else
5251 options->flags.diff_from_contents = 0;
5252
5253 if (options->flags.find_copies_harder)
5254 options->detect_rename = DIFF_DETECT_COPY;
5255
5256 if (!options->flags.relative_name)
5257 options->prefix = NULL;
5258 if (options->prefix)
5259 options->prefix_length = strlen(options->prefix);
5260 else
5261 options->prefix_length = 0;
5262
5263 /*
5264 * --name-only, --name-status, --checkdiff, and -s
5265 * turn other output format off.
5266 */
5267 if (options->output_format & (DIFF_FORMAT_NAME |
5268 DIFF_FORMAT_NAME_STATUS |
5269 DIFF_FORMAT_CHECKDIFF |
5270 DIFF_FORMAT_NO_OUTPUT))
5271 options->output_format &= ~(DIFF_FORMAT_RAW |
5272 DIFF_FORMAT_NUMSTAT |
5273 DIFF_FORMAT_DIFFSTAT |
5274 DIFF_FORMAT_SHORTSTAT |
5275 DIFF_FORMAT_DIRSTAT |
5276 DIFF_FORMAT_SUMMARY |
5277 DIFF_FORMAT_PATCH);
5278
5279 /*
5280 * These cases always need recursive; we do not drop caller-supplied
5281 * recursive bits for other formats here.
5282 */
5283 if (options->output_format & (DIFF_FORMAT_PATCH |
5284 DIFF_FORMAT_NUMSTAT |
5285 DIFF_FORMAT_DIFFSTAT |
5286 DIFF_FORMAT_SHORTSTAT |
5287 DIFF_FORMAT_DIRSTAT |
5288 DIFF_FORMAT_SUMMARY |
5289 DIFF_FORMAT_CHECKDIFF))
5290 options->flags.recursive = 1;
5291 /*
5292 * Also pickaxe would not work very well if you do not say recursive
5293 */
5294 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
5295 options->flags.recursive = 1;
5296 /*
5297 * When patches are generated, submodules diffed against the work tree
5298 * must be checked for dirtiness too so it can be shown in the output
5299 */
5300 if (options->output_format & DIFF_FORMAT_PATCH)
5301 options->flags.dirty_submodules = 1;
5302
5303 if (options->detect_rename && options->rename_limit < 0)
5304 options->rename_limit = diff_rename_limit_default;
5305 if (hexsz < options->abbrev)
5306 options->abbrev = hexsz; /* full */
5307
5308 /*
5309 * It does not make sense to show the first hit we happened
5310 * to have found. It does not make sense not to return with
5311 * exit code in such a case either.
5312 */
5313 if (options->flags.quick) {
5314 options->output_format = DIFF_FORMAT_NO_OUTPUT;
5315 options->flags.exit_with_status = 1;
5316 options->detect_rename = 0;
5317 options->flags.find_copies_harder = 0;
5318 }
5319
5320 /*
5321 * External diffs could declare non-identical contents equal
5322 * (think diff --ignore-space-change).
5323 */
5324 if (options->flags.allow_external && options->flags.exit_with_status)
5325 options->flags.diff_from_contents = 1;
5326
5327 options->diff_path_counter = 0;
5328
5329 if (options->flags.follow_renames)
5330 diff_check_follow_pathspec(&options->pathspec, 1);
5331
5332 if (options->flags.allow_external && external_diff())
5333 options->color_moved = 0;
5334
5335 if (options->filter_not) {
5336 if (!options->filter)
5337 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
5338 options->filter &= ~options->filter_not;
5339 }
5340
5341 if (options->pathspec.has_wildcard && options->max_depth_valid)
5342 die("max-depth cannot be used with wildcard pathspecs");
5343}
5344
5345int parse_long_opt(const char *opt, const char **argv,
5346 const char **optarg)
5347{
5348 const char *arg = argv[0];
5349 if (!skip_prefix(arg, "--", &arg))
5350 return 0;
5351 if (!skip_prefix(arg, opt, &arg))
5352 return 0;
5353 if (*arg == '=') { /* stuck form: --option=value */
5354 *optarg = arg + 1;
5355 return 1;
5356 }
5357 if (*arg != '\0')
5358 return 0;
5359 /* separate form: --option value */
5360 if (!argv[1])
5361 die("Option '--%s' requires a value", opt);
5362 *optarg = argv[1];
5363 return 2;
5364}
5365
5366static int diff_opt_stat(const struct option *opt, const char *value, int unset)
5367{
5368 struct diff_options *options = opt->value;
5369 int width = options->stat_width;
5370 int name_width = options->stat_name_width;
5371 int graph_width = options->stat_graph_width;
5372 int count = options->stat_count;
5373 char *end;
5374
5375 BUG_ON_OPT_NEG(unset);
5376
5377 if (!strcmp(opt->long_name, "stat")) {
5378 if (value) {
5379 width = strtoul(value, &end, 10);
5380 if (*end == ',')
5381 name_width = strtoul(end+1, &end, 10);
5382 if (*end == ',')
5383 count = strtoul(end+1, &end, 10);
5384 if (*end)
5385 return error(_("invalid --stat value: %s"), value);
5386 }
5387 } else if (!strcmp(opt->long_name, "stat-width")) {
5388 width = strtoul(value, &end, 10);
5389 if (*end)
5390 return error(_("%s expects a numerical value"),
5391 opt->long_name);
5392 } else if (!strcmp(opt->long_name, "stat-name-width")) {
5393 name_width = strtoul(value, &end, 10);
5394 if (*end)
5395 return error(_("%s expects a numerical value"),
5396 opt->long_name);
5397 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
5398 graph_width = strtoul(value, &end, 10);
5399 if (*end)
5400 return error(_("%s expects a numerical value"),
5401 opt->long_name);
5402 } else if (!strcmp(opt->long_name, "stat-count")) {
5403 count = strtoul(value, &end, 10);
5404 if (*end)
5405 return error(_("%s expects a numerical value"),
5406 opt->long_name);
5407 } else
5408 BUG("%s should not get here", opt->long_name);
5409
5410 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5411 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5412 options->stat_name_width = name_width;
5413 options->stat_graph_width = graph_width;
5414 options->stat_width = width;
5415 options->stat_count = count;
5416 return 0;
5417}
5418
5419static int parse_dirstat_opt(struct diff_options *options, const char *params)
5420{
5421 struct strbuf errmsg = STRBUF_INIT;
5422 if (parse_dirstat_params(options, params, &errmsg))
5423 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
5424 errmsg.buf);
5425 strbuf_release(&errmsg);
5426 /*
5427 * The caller knows a dirstat-related option is given from the command
5428 * line; allow it to say "return this_function();"
5429 */
5430 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5431 options->output_format |= DIFF_FORMAT_DIRSTAT;
5432 return 1;
5433}
5434
5435static int diff_opt_diff_filter(const struct option *option,
5436 const char *optarg, int unset)
5437{
5438 struct diff_options *opt = option->value;
5439 int i, optch;
5440
5441 BUG_ON_OPT_NEG(unset);
5442 prepare_filter_bits();
5443
5444 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5445 unsigned int bit;
5446 int negate;
5447
5448 if ('a' <= optch && optch <= 'z') {
5449 negate = 1;
5450 optch = toupper(optch);
5451 } else {
5452 negate = 0;
5453 }
5454
5455 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5456 if (!bit)
5457 return error(_("unknown change class '%c' in --diff-filter=%s"),
5458 optarg[i], optarg);
5459 if (negate)
5460 opt->filter_not |= bit;
5461 else
5462 opt->filter |= bit;
5463 }
5464 return 0;
5465}
5466
5467static void enable_patch_output(int *fmt)
5468{
5469 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5470 *fmt |= DIFF_FORMAT_PATCH;
5471}
5472
5473static int diff_opt_ws_error_highlight(const struct option *option,
5474 const char *arg, int unset)
5475{
5476 struct diff_options *opt = option->value;
5477 int val = parse_ws_error_highlight(arg);
5478
5479 BUG_ON_OPT_NEG(unset);
5480 if (val < 0)
5481 return error(_("unknown value after ws-error-highlight=%.*s"),
5482 -1 - val, arg);
5483 opt->ws_error_highlight = val;
5484 return 0;
5485}
5486
5487static int diff_opt_find_object(const struct option *option,
5488 const char *arg, int unset)
5489{
5490 struct diff_options *opt = option->value;
5491 struct object_id oid;
5492
5493 BUG_ON_OPT_NEG(unset);
5494 if (!startup_info->have_repository)
5495 return error(_("--find-object requires a git repository"));
5496 if (repo_get_oid(the_repository, arg, &oid))
5497 return error(_("unable to resolve '%s'"), arg);
5498
5499 if (!opt->objfind)
5500 CALLOC_ARRAY(opt->objfind, 1);
5501
5502 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5503 opt->flags.recursive = 1;
5504 opt->flags.tree_in_recursive = 1;
5505 oidset_insert(opt->objfind, &oid);
5506 return 0;
5507}
5508
5509static int diff_opt_anchored(const struct option *opt,
5510 const char *arg, int unset)
5511{
5512 struct diff_options *options = opt->value;
5513
5514 BUG_ON_OPT_NEG(unset);
5515 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5516 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5517 options->anchors_alloc);
5518 options->anchors[options->anchors_nr++] = xstrdup(arg);
5519 return 0;
5520}
5521
5522static int diff_opt_binary(const struct option *opt,
5523 const char *arg, int unset)
5524{
5525 struct diff_options *options = opt->value;
5526
5527 BUG_ON_OPT_NEG(unset);
5528 BUG_ON_OPT_ARG(arg);
5529 enable_patch_output(&options->output_format);
5530 options->flags.binary = 1;
5531 return 0;
5532}
5533
5534static int diff_opt_break_rewrites(const struct option *opt,
5535 const char *arg, int unset)
5536{
5537 int *break_opt = opt->value;
5538 int opt1, opt2;
5539
5540 BUG_ON_OPT_NEG(unset);
5541 if (!arg)
5542 arg = "";
5543 opt1 = parse_rename_score(&arg);
5544 if (*arg == 0)
5545 opt2 = 0;
5546 else if (*arg != '/')
5547 return error(_("%s expects <n>/<m> form"), opt->long_name);
5548 else {
5549 arg++;
5550 opt2 = parse_rename_score(&arg);
5551 }
5552 if (*arg != 0)
5553 return error(_("%s expects <n>/<m> form"), opt->long_name);
5554 *break_opt = opt1 | (opt2 << 16);
5555 return 0;
5556}
5557
5558static int diff_opt_char(const struct option *opt,
5559 const char *arg, int unset)
5560{
5561 char *value = opt->value;
5562
5563 BUG_ON_OPT_NEG(unset);
5564 if (arg[1])
5565 return error(_("%s expects a character, got '%s'"),
5566 opt->long_name, arg);
5567 *value = arg[0];
5568 return 0;
5569}
5570
5571static int diff_opt_color_moved(const struct option *opt,
5572 const char *arg, int unset)
5573{
5574 struct diff_options *options = opt->value;
5575
5576 if (unset) {
5577 options->color_moved = COLOR_MOVED_NO;
5578 } else if (!arg) {
5579 if (diff_color_moved_default)
5580 options->color_moved = diff_color_moved_default;
5581 if (options->color_moved == COLOR_MOVED_NO)
5582 options->color_moved = COLOR_MOVED_DEFAULT;
5583 } else {
5584 int cm = parse_color_moved(arg);
5585 if (cm < 0)
5586 return error(_("bad --color-moved argument: %s"), arg);
5587 options->color_moved = cm;
5588 }
5589 return 0;
5590}
5591
5592static int diff_opt_color_moved_ws(const struct option *opt,
5593 const char *arg, int unset)
5594{
5595 struct diff_options *options = opt->value;
5596 unsigned cm;
5597
5598 if (unset) {
5599 options->color_moved_ws_handling = 0;
5600 return 0;
5601 }
5602
5603 cm = parse_color_moved_ws(arg);
5604 if (cm & COLOR_MOVED_WS_ERROR)
5605 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5606 options->color_moved_ws_handling = cm;
5607 return 0;
5608}
5609
5610static int diff_opt_color_words(const struct option *opt,
5611 const char *arg, int unset)
5612{
5613 struct diff_options *options = opt->value;
5614
5615 BUG_ON_OPT_NEG(unset);
5616 options->use_color = GIT_COLOR_ALWAYS;
5617 options->word_diff = DIFF_WORDS_COLOR;
5618 options->word_regex = arg;
5619 return 0;
5620}
5621
5622static int diff_opt_compact_summary(const struct option *opt,
5623 const char *arg, int unset)
5624{
5625 struct diff_options *options = opt->value;
5626
5627 BUG_ON_OPT_ARG(arg);
5628 if (unset) {
5629 options->flags.stat_with_summary = 0;
5630 } else {
5631 options->flags.stat_with_summary = 1;
5632 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5633 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5634 }
5635 return 0;
5636}
5637
5638static int diff_opt_diff_algorithm(const struct option *opt,
5639 const char *arg, int unset)
5640{
5641 struct diff_options *options = opt->value;
5642
5643 BUG_ON_OPT_NEG(unset);
5644
5645 if (set_diff_algorithm(options, arg))
5646 return error(_("option diff-algorithm accepts \"myers\", "
5647 "\"minimal\", \"patience\" and \"histogram\""));
5648
5649 options->ignore_driver_algorithm = 1;
5650
5651 return 0;
5652}
5653
5654static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5655 const char *arg, int unset)
5656{
5657 struct diff_options *options = opt->value;
5658
5659 BUG_ON_OPT_NEG(unset);
5660 BUG_ON_OPT_ARG(arg);
5661
5662 if (set_diff_algorithm(options, opt->long_name))
5663 BUG("available diff algorithms include \"myers\", "
5664 "\"minimal\", \"patience\" and \"histogram\"");
5665
5666 options->ignore_driver_algorithm = 1;
5667
5668 return 0;
5669}
5670
5671static int diff_opt_dirstat(const struct option *opt,
5672 const char *arg, int unset)
5673{
5674 struct diff_options *options = opt->value;
5675
5676 BUG_ON_OPT_NEG(unset);
5677 if (!strcmp(opt->long_name, "cumulative")) {
5678 if (arg)
5679 BUG("how come --cumulative take a value?");
5680 arg = "cumulative";
5681 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5682 parse_dirstat_opt(options, "files");
5683 parse_dirstat_opt(options, arg ? arg : "");
5684 return 0;
5685}
5686
5687static int diff_opt_find_copies(const struct option *opt,
5688 const char *arg, int unset)
5689{
5690 struct diff_options *options = opt->value;
5691
5692 BUG_ON_OPT_NEG(unset);
5693 if (!arg)
5694 arg = "";
5695 options->rename_score = parse_rename_score(&arg);
5696 if (*arg != 0)
5697 return error(_("invalid argument to %s"), opt->long_name);
5698
5699 if (options->detect_rename == DIFF_DETECT_COPY)
5700 options->flags.find_copies_harder = 1;
5701 else
5702 options->detect_rename = DIFF_DETECT_COPY;
5703
5704 return 0;
5705}
5706
5707static int diff_opt_find_renames(const struct option *opt,
5708 const char *arg, int unset)
5709{
5710 struct diff_options *options = opt->value;
5711
5712 BUG_ON_OPT_NEG(unset);
5713 if (!arg)
5714 arg = "";
5715 options->rename_score = parse_rename_score(&arg);
5716 if (*arg != 0)
5717 return error(_("invalid argument to %s"), opt->long_name);
5718
5719 options->detect_rename = DIFF_DETECT_RENAME;
5720 return 0;
5721}
5722
5723static int diff_opt_follow(const struct option *opt,
5724 const char *arg, int unset)
5725{
5726 struct diff_options *options = opt->value;
5727
5728 BUG_ON_OPT_ARG(arg);
5729 if (unset) {
5730 options->flags.follow_renames = 0;
5731 options->flags.default_follow_renames = 0;
5732 } else {
5733 options->flags.follow_renames = 1;
5734 }
5735 return 0;
5736}
5737
5738static int diff_opt_ignore_submodules(const struct option *opt,
5739 const char *arg, int unset)
5740{
5741 struct diff_options *options = opt->value;
5742
5743 BUG_ON_OPT_NEG(unset);
5744 if (!arg)
5745 arg = "all";
5746 options->flags.override_submodule_config = 1;
5747 handle_ignore_submodules_arg(options, arg);
5748 return 0;
5749}
5750
5751static int diff_opt_line_prefix(const struct option *opt,
5752 const char *optarg, int unset)
5753{
5754 struct diff_options *options = opt->value;
5755
5756 BUG_ON_OPT_NEG(unset);
5757 options->line_prefix = optarg;
5758 graph_setup_line_prefix(options);
5759 return 0;
5760}
5761
5762static int diff_opt_no_prefix(const struct option *opt,
5763 const char *optarg, int unset)
5764{
5765 struct diff_options *options = opt->value;
5766
5767 BUG_ON_OPT_NEG(unset);
5768 BUG_ON_OPT_ARG(optarg);
5769 diff_set_noprefix(options);
5770 return 0;
5771}
5772
5773static int diff_opt_default_prefix(const struct option *opt,
5774 const char *optarg, int unset)
5775{
5776 struct diff_options *options = opt->value;
5777
5778 BUG_ON_OPT_NEG(unset);
5779 BUG_ON_OPT_ARG(optarg);
5780 FREE_AND_NULL(diff_src_prefix);
5781 FREE_AND_NULL(diff_dst_prefix);
5782 diff_set_default_prefix(options);
5783 return 0;
5784}
5785
5786static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5787 const struct option *opt,
5788 const char *arg, int unset)
5789{
5790 struct diff_options *options = opt->value;
5791 char *path;
5792
5793 BUG_ON_OPT_NEG(unset);
5794 path = prefix_filename(ctx->prefix, arg);
5795 options->file = xfopen(path, "w");
5796 options->close_file = 1;
5797 if (options->use_color != GIT_COLOR_ALWAYS)
5798 options->use_color = GIT_COLOR_NEVER;
5799 free(path);
5800 return 0;
5801}
5802
5803static int diff_opt_patience(const struct option *opt,
5804 const char *arg, int unset)
5805{
5806 struct diff_options *options = opt->value;
5807 int i;
5808
5809 BUG_ON_OPT_NEG(unset);
5810 BUG_ON_OPT_ARG(arg);
5811 /*
5812 * Both --patience and --anchored use PATIENCE_DIFF
5813 * internally, so remove any anchors previously
5814 * specified.
5815 */
5816 for (i = 0; i < options->anchors_nr; i++)
5817 free(options->anchors[i]);
5818 options->anchors_nr = 0;
5819 options->ignore_driver_algorithm = 1;
5820
5821 return set_diff_algorithm(options, "patience");
5822}
5823
5824static int diff_opt_ignore_regex(const struct option *opt,
5825 const char *arg, int unset)
5826{
5827 struct diff_options *options = opt->value;
5828 regex_t *regex;
5829
5830 BUG_ON_OPT_NEG(unset);
5831
5832 regex = xmalloc(sizeof(*regex));
5833 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE)) {
5834 free(regex);
5835 return error(_("invalid regex given to -I: '%s'"), arg);
5836 }
5837
5838 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5839 options->ignore_regex_alloc);
5840 options->ignore_regex[options->ignore_regex_nr++] = regex;
5841 return 0;
5842}
5843
5844static int diff_opt_pickaxe_regex(const struct option *opt,
5845 const char *arg, int unset)
5846{
5847 struct diff_options *options = opt->value;
5848
5849 BUG_ON_OPT_NEG(unset);
5850 options->pickaxe = arg;
5851 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5852 if (arg && !*arg)
5853 return error(_("-G requires a non-empty argument"));
5854 return 0;
5855}
5856
5857static int diff_opt_pickaxe_string(const struct option *opt,
5858 const char *arg, int unset)
5859{
5860 struct diff_options *options = opt->value;
5861
5862 BUG_ON_OPT_NEG(unset);
5863 options->pickaxe = arg;
5864 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5865 if (arg && !*arg)
5866 return error(_("-S requires a non-empty argument"));
5867 return 0;
5868}
5869
5870static int diff_opt_relative(const struct option *opt,
5871 const char *arg, int unset)
5872{
5873 struct diff_options *options = opt->value;
5874
5875 options->flags.relative_name = !unset;
5876 if (arg)
5877 options->prefix = arg;
5878 return 0;
5879}
5880
5881static int diff_opt_submodule(const struct option *opt,
5882 const char *arg, int unset)
5883{
5884 struct diff_options *options = opt->value;
5885
5886 BUG_ON_OPT_NEG(unset);
5887 if (!arg)
5888 arg = "log";
5889 if (parse_submodule_params(options, arg))
5890 return error(_("failed to parse --submodule option parameter: '%s'"),
5891 arg);
5892 return 0;
5893}
5894
5895static int diff_opt_textconv(const struct option *opt,
5896 const char *arg, int unset)
5897{
5898 struct diff_options *options = opt->value;
5899
5900 BUG_ON_OPT_ARG(arg);
5901 if (unset) {
5902 options->flags.allow_textconv = 0;
5903 } else {
5904 options->flags.allow_textconv = 1;
5905 options->flags.textconv_set_via_cmdline = 1;
5906 }
5907 return 0;
5908}
5909
5910static int diff_opt_unified(const struct option *opt,
5911 const char *arg, int unset)
5912{
5913 struct diff_options *options = opt->value;
5914 char *s;
5915
5916 BUG_ON_OPT_NEG(unset);
5917
5918 if (arg) {
5919 long val = strtol(arg, &s, 10);
5920 if (*s)
5921 return error(_("%s expects a numerical value"), "--unified");
5922 if (val < 0)
5923 return error(_("%s expects a non-negative integer"), "--unified");
5924 options->context = val;
5925 }
5926 enable_patch_output(&options->output_format);
5927
5928 return 0;
5929}
5930
5931static int diff_opt_word_diff(const struct option *opt,
5932 const char *arg, int unset)
5933{
5934 struct diff_options *options = opt->value;
5935
5936 BUG_ON_OPT_NEG(unset);
5937 if (arg) {
5938 if (!strcmp(arg, "plain"))
5939 options->word_diff = DIFF_WORDS_PLAIN;
5940 else if (!strcmp(arg, "color")) {
5941 options->use_color = GIT_COLOR_ALWAYS;
5942 options->word_diff = DIFF_WORDS_COLOR;
5943 }
5944 else if (!strcmp(arg, "porcelain"))
5945 options->word_diff = DIFF_WORDS_PORCELAIN;
5946 else if (!strcmp(arg, "none"))
5947 options->word_diff = DIFF_WORDS_NONE;
5948 else
5949 return error(_("bad --word-diff argument: %s"), arg);
5950 } else {
5951 if (options->word_diff == DIFF_WORDS_NONE)
5952 options->word_diff = DIFF_WORDS_PLAIN;
5953 }
5954 return 0;
5955}
5956
5957static int diff_opt_word_diff_regex(const struct option *opt,
5958 const char *arg, int unset)
5959{
5960 struct diff_options *options = opt->value;
5961
5962 BUG_ON_OPT_NEG(unset);
5963 if (options->word_diff == DIFF_WORDS_NONE)
5964 options->word_diff = DIFF_WORDS_PLAIN;
5965 options->word_regex = arg;
5966 return 0;
5967}
5968
5969static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5970{
5971 struct diff_options *options = opt->value;
5972
5973 BUG_ON_OPT_NEG(unset);
5974 if (!strcmp(opt->long_name, "skip-to"))
5975 options->skip_instead_of_rotate = 1;
5976 else
5977 options->skip_instead_of_rotate = 0;
5978 options->rotate_to = arg;
5979 return 0;
5980}
5981
5982static int diff_opt_max_depth(const struct option *opt,
5983 const char *arg, int unset)
5984{
5985 struct diff_options *options = opt->value;
5986
5987 BUG_ON_OPT_NEG(unset);
5988
5989 if (!git_parse_int(arg, &options->max_depth))
5990 return error(_("invalid value for '%s': '%s'"),
5991 "--max-depth", arg);
5992
5993 options->flags.recursive = 1;
5994 options->max_depth_valid = options->max_depth >= 0;
5995
5996 return 0;
5997}
5998
5999/*
6000 * Consider adding new flags to __git_diff_common_options
6001 * in contrib/completion/git-completion.bash
6002 */
6003struct option *add_diff_options(const struct option *opts,
6004 struct diff_options *options)
6005{
6006 struct option parseopts[] = {
6007 OPT_GROUP(N_("Diff output format options")),
6008 OPT_BITOP('p', "patch", &options->output_format,
6009 N_("generate patch"),
6010 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
6011 OPT_SET_INT('s', "no-patch", &options->output_format,
6012 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
6013 OPT_BITOP('u', NULL, &options->output_format,
6014 N_("generate patch"),
6015 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
6016 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
6017 N_("generate diffs with <n> lines context"),
6018 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
6019 OPT_BOOL('W', "function-context", &options->flags.funccontext,
6020 N_("generate diffs with <n> lines context")),
6021 OPT_BITOP(0, "raw", &options->output_format,
6022 N_("generate the diff in raw format"),
6023 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
6024 OPT_BITOP(0, "patch-with-raw", &options->output_format,
6025 N_("synonym for '-p --raw'"),
6026 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
6027 DIFF_FORMAT_NO_OUTPUT),
6028 OPT_BITOP(0, "patch-with-stat", &options->output_format,
6029 N_("synonym for '-p --stat'"),
6030 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
6031 DIFF_FORMAT_NO_OUTPUT),
6032 OPT_BITOP(0, "numstat", &options->output_format,
6033 N_("machine friendly --stat"),
6034 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
6035 OPT_BITOP(0, "shortstat", &options->output_format,
6036 N_("output only the last line of --stat"),
6037 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
6038 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1>,<param2>..."),
6039 N_("output the distribution of relative amount of changes for each sub-directory"),
6040 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6041 diff_opt_dirstat),
6042 OPT_CALLBACK_F(0, "cumulative", options, NULL,
6043 N_("synonym for --dirstat=cumulative"),
6044 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6045 diff_opt_dirstat),
6046 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1>,<param2>..."),
6047 N_("synonym for --dirstat=files,<param1>,<param2>..."),
6048 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6049 diff_opt_dirstat),
6050 OPT_BIT_F(0, "check", &options->output_format,
6051 N_("warn if changes introduce conflict markers or whitespace errors"),
6052 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
6053 OPT_BITOP(0, "summary", &options->output_format,
6054 N_("condensed summary such as creations, renames and mode changes"),
6055 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
6056 OPT_BIT_F(0, "name-only", &options->output_format,
6057 N_("show only names of changed files"),
6058 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
6059 OPT_BIT_F(0, "name-status", &options->output_format,
6060 N_("show only names and status of changed files"),
6061 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
6062 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
6063 N_("generate diffstat"),
6064 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
6065 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
6066 N_("generate diffstat with a given width"),
6067 PARSE_OPT_NONEG, diff_opt_stat),
6068 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
6069 N_("generate diffstat with a given name width"),
6070 PARSE_OPT_NONEG, diff_opt_stat),
6071 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
6072 N_("generate diffstat with a given graph width"),
6073 PARSE_OPT_NONEG, diff_opt_stat),
6074 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
6075 N_("generate diffstat with limited lines"),
6076 PARSE_OPT_NONEG, diff_opt_stat),
6077 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
6078 N_("generate compact summary in diffstat"),
6079 PARSE_OPT_NOARG, diff_opt_compact_summary),
6080 OPT_CALLBACK_F(0, "binary", options, NULL,
6081 N_("output a binary diff that can be applied"),
6082 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
6083 OPT_BOOL(0, "full-index", &options->flags.full_index,
6084 N_("show full pre- and post-image object names on the \"index\" lines")),
6085 OPT_COLOR_FLAG(0, "color", &options->use_color,
6086 N_("show colored diff")),
6087 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
6088 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
6089 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
6090 OPT_SET_INT('z', NULL, &options->line_termination,
6091 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
6092 0),
6093 OPT__ABBREV(&options->abbrev),
6094 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
6095 N_("show the given source prefix instead of \"a/\""),
6096 PARSE_OPT_NONEG),
6097 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
6098 N_("show the given destination prefix instead of \"b/\""),
6099 PARSE_OPT_NONEG),
6100 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
6101 N_("prepend an additional prefix to every line of output"),
6102 PARSE_OPT_NONEG, diff_opt_line_prefix),
6103 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
6104 N_("do not show any source or destination prefix"),
6105 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
6106 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
6107 N_("use default prefixes a/ and b/"),
6108 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
6109 OPT_UNSIGNED(0, "inter-hunk-context", &options->interhunkcontext,
6110 N_("show context between diff hunks up to the specified number of lines")),
6111 OPT_CALLBACK_F(0, "output-indicator-new",
6112 &options->output_indicators[OUTPUT_INDICATOR_NEW],
6113 N_("<char>"),
6114 N_("specify the character to indicate a new line instead of '+'"),
6115 PARSE_OPT_NONEG, diff_opt_char),
6116 OPT_CALLBACK_F(0, "output-indicator-old",
6117 &options->output_indicators[OUTPUT_INDICATOR_OLD],
6118 N_("<char>"),
6119 N_("specify the character to indicate an old line instead of '-'"),
6120 PARSE_OPT_NONEG, diff_opt_char),
6121 OPT_CALLBACK_F(0, "output-indicator-context",
6122 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
6123 N_("<char>"),
6124 N_("specify the character to indicate a context instead of ' '"),
6125 PARSE_OPT_NONEG, diff_opt_char),
6126
6127 OPT_GROUP(N_("Diff rename options")),
6128 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
6129 N_("break complete rewrite changes into pairs of delete and create"),
6130 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6131 diff_opt_break_rewrites),
6132 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
6133 N_("detect renames"),
6134 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6135 diff_opt_find_renames),
6136 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
6137 N_("omit the preimage for deletes"),
6138 1, PARSE_OPT_NONEG),
6139 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
6140 N_("detect copies"),
6141 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6142 diff_opt_find_copies),
6143 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
6144 N_("use unmodified files as source to find copies")),
6145 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
6146 N_("disable rename detection"),
6147 0, PARSE_OPT_NONEG),
6148 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
6149 N_("use empty blobs as rename source")),
6150 OPT_CALLBACK_F(0, "follow", options, NULL,
6151 N_("continue listing the history of a file beyond renames"),
6152 PARSE_OPT_NOARG, diff_opt_follow),
6153 OPT_INTEGER('l', NULL, &options->rename_limit,
6154 N_("limit to cheap rename/copy detection if the number of rename/copy targets exceeds this value")),
6155
6156 OPT_GROUP(N_("Diff algorithm options")),
6157 OPT_CALLBACK_F(0, "minimal", options, NULL,
6158 N_("produce the smallest possible diff"),
6159 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6160 diff_opt_diff_algorithm_no_arg),
6161 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
6162 N_("ignore whitespace when comparing lines"),
6163 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
6164 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
6165 N_("ignore changes in amount of whitespace"),
6166 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
6167 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
6168 N_("ignore changes in whitespace at EOL"),
6169 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
6170 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
6171 N_("ignore carrier-return at the end of line"),
6172 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
6173 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
6174 N_("ignore changes whose lines are all blank"),
6175 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
6176 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
6177 N_("ignore changes whose all lines match <regex>"),
6178 0, diff_opt_ignore_regex),
6179 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
6180 N_("heuristic to shift diff hunk boundaries for easy reading"),
6181 XDF_INDENT_HEURISTIC),
6182 OPT_CALLBACK_F(0, "patience", options, NULL,
6183 N_("generate diff using the \"patience diff\" algorithm"),
6184 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6185 diff_opt_patience),
6186 OPT_CALLBACK_F(0, "histogram", options, NULL,
6187 N_("generate diff using the \"histogram diff\" algorithm"),
6188 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6189 diff_opt_diff_algorithm_no_arg),
6190 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
6191 N_("choose a diff algorithm"),
6192 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
6193 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
6194 N_("generate diff using the \"anchored diff\" algorithm"),
6195 PARSE_OPT_NONEG, diff_opt_anchored),
6196 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
6197 N_("show word diff, using <mode> to delimit changed words"),
6198 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
6199 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
6200 N_("use <regex> to decide what a word is"),
6201 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
6202 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
6203 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
6204 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
6205 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
6206 N_("moved lines of code are colored differently"),
6207 PARSE_OPT_OPTARG, diff_opt_color_moved),
6208 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
6209 N_("how white spaces are ignored in --color-moved"),
6210 0, diff_opt_color_moved_ws),
6211
6212 OPT_GROUP(N_("Other diff options")),
6213 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
6214 N_("when run from subdir, exclude changes outside and show relative paths"),
6215 PARSE_OPT_OPTARG,
6216 diff_opt_relative),
6217 OPT_BOOL('a', "text", &options->flags.text,
6218 N_("treat all files as text")),
6219 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
6220 N_("swap two inputs, reverse the diff")),
6221 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
6222 N_("exit with 1 if there were differences, 0 otherwise")),
6223 OPT_BOOL(0, "quiet", &options->flags.quick,
6224 N_("disable all output of the program")),
6225 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
6226 N_("allow an external diff helper to be executed")),
6227 OPT_CALLBACK_F(0, "textconv", options, NULL,
6228 N_("run external text conversion filters when comparing binary files"),
6229 PARSE_OPT_NOARG, diff_opt_textconv),
6230 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
6231 N_("ignore changes to submodules in the diff generation"),
6232 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6233 diff_opt_ignore_submodules),
6234 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
6235 N_("specify how differences in submodules are shown"),
6236 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6237 diff_opt_submodule),
6238 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
6239 N_("hide 'git add -N' entries from the index"),
6240 1, PARSE_OPT_NONEG),
6241 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
6242 N_("treat 'git add -N' entries as real in the index"),
6243 0, PARSE_OPT_NONEG),
6244 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
6245 N_("look for differences that change the number of occurrences of the specified string"),
6246 0, diff_opt_pickaxe_string),
6247 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
6248 N_("look for differences that change the number of occurrences of the specified regex"),
6249 0, diff_opt_pickaxe_regex),
6250 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
6251 N_("show all changes in the changeset with -S or -G"),
6252 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
6253 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
6254 N_("treat <string> in -S as extended POSIX regular expression"),
6255 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
6256 OPT_FILENAME('O', NULL, &options->orderfile,
6257 N_("control the order in which files appear in the output")),
6258 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
6259 N_("show the change in the specified path first"),
6260 PARSE_OPT_NONEG, diff_opt_rotate_to),
6261 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
6262 N_("skip the output to the specified path"),
6263 PARSE_OPT_NONEG, diff_opt_rotate_to),
6264 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
6265 N_("look for differences that change the number of occurrences of the specified object"),
6266 PARSE_OPT_NONEG, diff_opt_find_object),
6267 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
6268 N_("select files by diff type"),
6269 PARSE_OPT_NONEG, diff_opt_diff_filter),
6270 OPT_CALLBACK_F(0, "max-depth", options, N_("<depth>"),
6271 N_("maximum tree depth to recurse"),
6272 PARSE_OPT_NONEG, diff_opt_max_depth),
6273
6274 {
6275 .type = OPTION_CALLBACK,
6276 .long_name = "output",
6277 .value = options,
6278 .argh = N_("<file>"),
6279 .help = N_("output to a specific file"),
6280 .flags = PARSE_OPT_NONEG,
6281 .ll_callback = diff_opt_output,
6282 },
6283 OPT_END()
6284 };
6285
6286 return parse_options_concat(opts, parseopts);
6287}
6288
6289int diff_opt_parse(struct diff_options *options,
6290 const char **av, int ac, const char *prefix)
6291{
6292 struct option no_options[] = { OPT_END() };
6293 struct option *parseopts = add_diff_options(no_options, options);
6294
6295 if (!prefix)
6296 prefix = "";
6297
6298 ac = parse_options(ac, av, prefix, parseopts, NULL,
6299 PARSE_OPT_KEEP_DASHDASH |
6300 PARSE_OPT_KEEP_UNKNOWN_OPT |
6301 PARSE_OPT_NO_INTERNAL_HELP |
6302 PARSE_OPT_ONE_SHOT |
6303 PARSE_OPT_STOP_AT_NON_OPTION);
6304 free(parseopts);
6305
6306 return ac;
6307}
6308
6309int parse_rename_score(const char **cp_p)
6310{
6311 unsigned long num, scale;
6312 int ch, dot;
6313 const char *cp = *cp_p;
6314
6315 num = 0;
6316 scale = 1;
6317 dot = 0;
6318 for (;;) {
6319 ch = *cp;
6320 if ( !dot && ch == '.' ) {
6321 scale = 1;
6322 dot = 1;
6323 } else if ( ch == '%' ) {
6324 scale = dot ? scale*100 : 100;
6325 cp++; /* % is always at the end */
6326 break;
6327 } else if ( ch >= '0' && ch <= '9' ) {
6328 if ( scale < 100000 ) {
6329 scale *= 10;
6330 num = (num*10) + (ch-'0');
6331 }
6332 } else {
6333 break;
6334 }
6335 cp++;
6336 }
6337 *cp_p = cp;
6338
6339 /* user says num divided by scale and we say internally that
6340 * is MAX_SCORE * num / scale.
6341 */
6342 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
6343}
6344
6345struct diff_queue_struct diff_queued_diff;
6346
6347void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
6348{
6349 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
6350 queue->queue[queue->nr++] = dp;
6351}
6352
6353struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
6354 struct diff_filespec *one,
6355 struct diff_filespec *two)
6356{
6357 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
6358 dp->one = one;
6359 dp->two = two;
6360 if (queue)
6361 diff_q(queue, dp);
6362 return dp;
6363}
6364
6365void diff_free_filepair(struct diff_filepair *p)
6366{
6367 free_filespec(p->one);
6368 free_filespec(p->two);
6369 free(p);
6370}
6371
6372void diff_queue_init(struct diff_queue_struct *q)
6373{
6374 struct diff_queue_struct blank = DIFF_QUEUE_INIT;
6375 memcpy(q, &blank, sizeof(*q));
6376}
6377
6378void diff_queue_clear(struct diff_queue_struct *q)
6379{
6380 for (int i = 0; i < q->nr; i++)
6381 diff_free_filepair(q->queue[i]);
6382 free(q->queue);
6383 diff_queue_init(q);
6384}
6385
6386const char *diff_aligned_abbrev(const struct object_id *oid, int len)
6387{
6388 int abblen;
6389 const char *abbrev;
6390
6391 /* Do we want all 40 hex characters? */
6392 if (len == the_hash_algo->hexsz)
6393 return oid_to_hex(oid);
6394
6395 /* An abbreviated value is fine, possibly followed by an ellipsis. */
6396 abbrev = diff_abbrev_oid(oid, len);
6397
6398 if (!print_sha1_ellipsis())
6399 return abbrev;
6400
6401 abblen = strlen(abbrev);
6402
6403 /*
6404 * In well-behaved cases, where the abbreviated result is the
6405 * same as the requested length, append three dots after the
6406 * abbreviation (hence the whole logic is limited to the case
6407 * where abblen < 37); when the actual abbreviated result is a
6408 * bit longer than the requested length, we reduce the number
6409 * of dots so that they match the well-behaved ones. However,
6410 * if the actual abbreviation is longer than the requested
6411 * length by more than three, we give up on aligning, and add
6412 * three dots anyway, to indicate that the output is not the
6413 * full object name. Yes, this may be suboptimal, but this
6414 * appears only in "diff --raw --abbrev" output and it is not
6415 * worth the effort to change it now. Note that this would
6416 * likely to work fine when the automatic sizing of default
6417 * abbreviation length is used--we would be fed -1 in "len" in
6418 * that case, and will end up always appending three-dots, but
6419 * the automatic sizing is supposed to give abblen that ensures
6420 * uniqueness across all objects (statistically speaking).
6421 */
6422 if (abblen < the_hash_algo->hexsz - 3) {
6423 static char hex[GIT_MAX_HEXSZ + 1];
6424 if (len < abblen && abblen <= len + 2)
6425 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
6426 else
6427 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
6428 return hex;
6429 }
6430
6431 return oid_to_hex(oid);
6432}
6433
6434static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6435{
6436 int line_termination = opt->line_termination;
6437 int inter_name_termination = line_termination ? '\t' : '\0';
6438
6439 fprintf(opt->file, "%s", diff_line_prefix(opt));
6440 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
6441 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
6442 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
6443 fprintf(opt->file, "%s ",
6444 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
6445 }
6446 if (p->score) {
6447 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
6448 inter_name_termination);
6449 } else {
6450 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6451 }
6452
6453 if (p->status == DIFF_STATUS_COPIED ||
6454 p->status == DIFF_STATUS_RENAMED) {
6455 const char *name_a, *name_b;
6456 name_a = p->one->path;
6457 name_b = p->two->path;
6458 strip_prefix(opt->prefix_length, &name_a, &name_b);
6459 write_name_quoted(name_a, opt->file, inter_name_termination);
6460 write_name_quoted(name_b, opt->file, line_termination);
6461 } else {
6462 const char *name_a, *name_b;
6463 name_a = p->one->mode ? p->one->path : p->two->path;
6464 name_b = NULL;
6465 strip_prefix(opt->prefix_length, &name_a, &name_b);
6466 write_name_quoted(name_a, opt->file, line_termination);
6467 }
6468}
6469
6470int diff_unmodified_pair(struct diff_filepair *p)
6471{
6472 /* This function is written stricter than necessary to support
6473 * the currently implemented transformers, but the idea is to
6474 * let transformers to produce diff_filepairs any way they want,
6475 * and filter and clean them up here before producing the output.
6476 */
6477 struct diff_filespec *one = p->one, *two = p->two;
6478
6479 if (DIFF_PAIR_UNMERGED(p))
6480 return 0; /* unmerged is interesting */
6481
6482 /* deletion, addition, mode or type change
6483 * and rename are all interesting.
6484 */
6485 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
6486 DIFF_PAIR_MODE_CHANGED(p) ||
6487 strcmp(one->path, two->path))
6488 return 0;
6489
6490 /* both are valid and point at the same path. that is, we are
6491 * dealing with a change.
6492 */
6493 if (one->oid_valid && two->oid_valid &&
6494 oideq(&one->oid, &two->oid) &&
6495 !one->dirty_submodule && !two->dirty_submodule)
6496 return 1; /* no change */
6497 if (!one->oid_valid && !two->oid_valid)
6498 return 1; /* both look at the same file on the filesystem. */
6499 return 0;
6500}
6501
6502static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6503{
6504 int include_conflict_headers =
6505 (additional_headers(o, p->one->path) &&
6506 !o->pickaxe_opts &&
6507 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6508
6509 /*
6510 * Check if we can return early without showing a diff. Note that
6511 * diff_filepair only stores {oid, path, mode, is_valid}
6512 * information for each path, and thus diff_unmodified_pair() only
6513 * considers those bits of info. However, we do not want pairs
6514 * created by create_filepairs_for_header_only_notifications()
6515 * (which always look like unmodified pairs) to be ignored, so
6516 * return early if both p is unmodified AND we don't want to
6517 * include_conflict_headers.
6518 */
6519 if (diff_unmodified_pair(p) && !include_conflict_headers)
6520 return;
6521
6522 /* Actually, we can also return early to avoid showing tree diffs */
6523 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6524 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6525 return;
6526
6527 run_diff(p, o);
6528}
6529
6530/* return 1 if any change is found; otherwise, return 0 */
6531static int diff_flush_patch_quietly(struct diff_filepair *p, struct diff_options *o)
6532{
6533 FILE *saved_file = o->file;
6534 int saved_found_changes = o->found_changes;
6535 int ret;
6536
6537 o->file = NULL;
6538 o->found_changes = 0;
6539 diff_flush_patch(p, o);
6540 ret = o->found_changes;
6541 o->file = saved_file;
6542 o->found_changes |= saved_found_changes;
6543 return ret;
6544}
6545
6546static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6547 struct diffstat_t *diffstat)
6548{
6549 if (diff_unmodified_pair(p))
6550 return;
6551
6552 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6553 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6554 return; /* no useful stat for tree diffs */
6555
6556 run_diffstat(p, o, diffstat);
6557}
6558
6559static void diff_flush_checkdiff(struct diff_filepair *p,
6560 struct diff_options *o)
6561{
6562 if (diff_unmodified_pair(p))
6563 return;
6564
6565 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6566 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6567 return; /* nothing to check in tree diffs */
6568
6569 run_checkdiff(p, o);
6570}
6571
6572int diff_queue_is_empty(struct diff_options *o)
6573{
6574 struct diff_queue_struct *q = &diff_queued_diff;
6575 int i;
6576 int include_conflict_headers =
6577 (o->additional_path_headers &&
6578 strmap_get_size(o->additional_path_headers) &&
6579 !o->pickaxe_opts &&
6580 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6581
6582 if (include_conflict_headers)
6583 return 0;
6584
6585 for (i = 0; i < q->nr; i++)
6586 if (!diff_unmodified_pair(q->queue[i]))
6587 return 0;
6588 return 1;
6589}
6590
6591#if DIFF_DEBUG
6592void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6593{
6594 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6595 x, one ? one : "",
6596 s->path,
6597 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6598 s->mode,
6599 s->oid_valid ? oid_to_hex(&s->oid) : "");
6600 fprintf(stderr, "queue[%d] %s size %lu\n",
6601 x, one ? one : "",
6602 s->size);
6603}
6604
6605void diff_debug_filepair(const struct diff_filepair *p, int i)
6606{
6607 diff_debug_filespec(p->one, i, "one");
6608 diff_debug_filespec(p->two, i, "two");
6609 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6610 p->score, p->status ? p->status : '?',
6611 p->one->rename_used, p->broken_pair);
6612}
6613
6614void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6615{
6616 int i;
6617 if (msg)
6618 fprintf(stderr, "%s\n", msg);
6619 fprintf(stderr, "q->nr = %d\n", q->nr);
6620 for (i = 0; i < q->nr; i++) {
6621 struct diff_filepair *p = q->queue[i];
6622 diff_debug_filepair(p, i);
6623 }
6624}
6625#endif
6626
6627static void diff_resolve_rename_copy(void)
6628{
6629 int i;
6630 struct diff_filepair *p;
6631 struct diff_queue_struct *q = &diff_queued_diff;
6632
6633 diff_debug_queue("resolve-rename-copy", q);
6634
6635 for (i = 0; i < q->nr; i++) {
6636 p = q->queue[i];
6637 p->status = 0; /* undecided */
6638 if (DIFF_PAIR_UNMERGED(p))
6639 p->status = DIFF_STATUS_UNMERGED;
6640 else if (!DIFF_FILE_VALID(p->one))
6641 p->status = DIFF_STATUS_ADDED;
6642 else if (!DIFF_FILE_VALID(p->two))
6643 p->status = DIFF_STATUS_DELETED;
6644 else if (DIFF_PAIR_TYPE_CHANGED(p))
6645 p->status = DIFF_STATUS_TYPE_CHANGED;
6646
6647 /* from this point on, we are dealing with a pair
6648 * whose both sides are valid and of the same type, i.e.
6649 * either in-place edit or rename/copy edit.
6650 */
6651 else if (DIFF_PAIR_RENAME(p)) {
6652 /*
6653 * A rename might have re-connected a broken
6654 * pair up, causing the pathnames to be the
6655 * same again. If so, that's not a rename at
6656 * all, just a modification..
6657 *
6658 * Otherwise, see if this source was used for
6659 * multiple renames, in which case we decrement
6660 * the count, and call it a copy.
6661 */
6662 if (!strcmp(p->one->path, p->two->path))
6663 p->status = DIFF_STATUS_MODIFIED;
6664 else if (--p->one->rename_used > 0)
6665 p->status = DIFF_STATUS_COPIED;
6666 else
6667 p->status = DIFF_STATUS_RENAMED;
6668 }
6669 else if (!oideq(&p->one->oid, &p->two->oid) ||
6670 p->one->mode != p->two->mode ||
6671 p->one->dirty_submodule ||
6672 p->two->dirty_submodule ||
6673 is_null_oid(&p->one->oid))
6674 p->status = DIFF_STATUS_MODIFIED;
6675 else {
6676 /* This is a "no-change" entry and should not
6677 * happen anymore, but prepare for broken callers.
6678 */
6679 error("feeding unmodified %s to diffcore",
6680 p->one->path);
6681 p->status = DIFF_STATUS_UNKNOWN;
6682 }
6683 }
6684 diff_debug_queue("resolve-rename-copy done", q);
6685}
6686
6687static int check_pair_status(struct diff_filepair *p)
6688{
6689 switch (p->status) {
6690 case DIFF_STATUS_UNKNOWN:
6691 return 0;
6692 case 0:
6693 die("internal error in diff-resolve-rename-copy");
6694 default:
6695 return 1;
6696 }
6697}
6698
6699static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6700{
6701 int fmt = opt->output_format;
6702
6703 if (fmt & DIFF_FORMAT_CHECKDIFF)
6704 diff_flush_checkdiff(p, opt);
6705 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6706 diff_flush_raw(p, opt);
6707 else if (fmt & DIFF_FORMAT_NAME) {
6708 const char *name_a, *name_b;
6709 name_a = p->two->path;
6710 name_b = NULL;
6711 strip_prefix(opt->prefix_length, &name_a, &name_b);
6712 fprintf(opt->file, "%s", diff_line_prefix(opt));
6713 write_name_quoted(name_a, opt->file, opt->line_termination);
6714 }
6715
6716 opt->found_changes = 1;
6717}
6718
6719static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6720{
6721 struct strbuf sb = STRBUF_INIT;
6722 if (fs->mode)
6723 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6724 else
6725 strbuf_addf(&sb, " %s ", newdelete);
6726
6727 quote_c_style(fs->path, &sb, NULL, 0);
6728 strbuf_addch(&sb, '\n');
6729 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6730 sb.buf, sb.len, 0);
6731 strbuf_release(&sb);
6732}
6733
6734static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6735 int show_name)
6736{
6737 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6738 struct strbuf sb = STRBUF_INIT;
6739 strbuf_addf(&sb, " mode change %06o => %06o",
6740 p->one->mode, p->two->mode);
6741 if (show_name) {
6742 strbuf_addch(&sb, ' ');
6743 quote_c_style(p->two->path, &sb, NULL, 0);
6744 }
6745 strbuf_addch(&sb, '\n');
6746 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6747 sb.buf, sb.len, 0);
6748 strbuf_release(&sb);
6749 }
6750}
6751
6752static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6753 struct diff_filepair *p)
6754{
6755 struct strbuf sb = STRBUF_INIT;
6756 struct strbuf names = STRBUF_INIT;
6757
6758 pprint_rename(&names, p->one->path, p->two->path);
6759 strbuf_addf(&sb, " %s %s (%d%%)\n",
6760 renamecopy, names.buf, similarity_index(p));
6761 strbuf_release(&names);
6762 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6763 sb.buf, sb.len, 0);
6764 show_mode_change(opt, p, 0);
6765 strbuf_release(&sb);
6766}
6767
6768static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6769{
6770 switch(p->status) {
6771 case DIFF_STATUS_DELETED:
6772 show_file_mode_name(opt, "delete", p->one);
6773 break;
6774 case DIFF_STATUS_ADDED:
6775 show_file_mode_name(opt, "create", p->two);
6776 break;
6777 case DIFF_STATUS_COPIED:
6778 show_rename_copy(opt, "copy", p);
6779 break;
6780 case DIFF_STATUS_RENAMED:
6781 show_rename_copy(opt, "rename", p);
6782 break;
6783 default:
6784 if (p->score) {
6785 struct strbuf sb = STRBUF_INIT;
6786 strbuf_addstr(&sb, " rewrite ");
6787 quote_c_style(p->two->path, &sb, NULL, 0);
6788 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6789 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6790 sb.buf, sb.len, 0);
6791 strbuf_release(&sb);
6792 }
6793 show_mode_change(opt, p, !p->score);
6794 break;
6795 }
6796}
6797
6798struct patch_id_t {
6799 struct git_hash_ctx *ctx;
6800 int patchlen;
6801};
6802
6803static int remove_space(char *line, int len)
6804{
6805 int i;
6806 char *dst = line;
6807 unsigned char c;
6808
6809 for (i = 0; i < len; i++)
6810 if (!isspace((c = line[i])))
6811 *dst++ = c;
6812
6813 return dst - line;
6814}
6815
6816void flush_one_hunk(struct object_id *result, struct git_hash_ctx *ctx)
6817{
6818 unsigned char hash[GIT_MAX_RAWSZ];
6819 unsigned short carry = 0;
6820 int i;
6821
6822 git_hash_final(hash, ctx);
6823 git_hash_init(ctx, the_hash_algo);
6824 /* 20-byte sum, with carry */
6825 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6826 carry += result->hash[i] + hash[i];
6827 result->hash[i] = carry;
6828 carry >>= 8;
6829 }
6830}
6831
6832static int patch_id_consume(void *priv, char *line, unsigned long len)
6833{
6834 struct patch_id_t *data = priv;
6835 int new_len;
6836
6837 if (len > 12 && starts_with(line, "\\ "))
6838 return 0;
6839 new_len = remove_space(line, len);
6840
6841 git_hash_update(data->ctx, line, new_len);
6842 data->patchlen += new_len;
6843 return 0;
6844}
6845
6846static void patch_id_add_string(struct git_hash_ctx *ctx, const char *str)
6847{
6848 git_hash_update(ctx, str, strlen(str));
6849}
6850
6851static void patch_id_add_mode(struct git_hash_ctx *ctx, unsigned mode)
6852{
6853 /* large enough for 2^32 in octal */
6854 char buf[12];
6855 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6856 git_hash_update(ctx, buf, len);
6857}
6858
6859/* returns 0 upon success, and writes result into oid */
6860static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6861{
6862 struct diff_queue_struct *q = &diff_queued_diff;
6863 int i;
6864 struct git_hash_ctx ctx;
6865 struct patch_id_t data;
6866
6867 git_hash_init(&ctx, the_hash_algo);
6868 memset(&data, 0, sizeof(struct patch_id_t));
6869 data.ctx = &ctx;
6870 oidclr(oid, the_repository->hash_algo);
6871
6872 for (i = 0; i < q->nr; i++) {
6873 xpparam_t xpp;
6874 xdemitconf_t xecfg;
6875 mmfile_t mf1, mf2;
6876 struct diff_filepair *p = q->queue[i];
6877 int len1, len2;
6878
6879 memset(&xpp, 0, sizeof(xpp));
6880 memset(&xecfg, 0, sizeof(xecfg));
6881 if (p->status == 0)
6882 return error("internal diff status error");
6883 if (p->status == DIFF_STATUS_UNKNOWN)
6884 continue;
6885 if (diff_unmodified_pair(p))
6886 continue;
6887 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6888 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6889 continue;
6890 if (DIFF_PAIR_UNMERGED(p))
6891 continue;
6892
6893 diff_fill_oid_info(p->one, options->repo->index);
6894 diff_fill_oid_info(p->two, options->repo->index);
6895
6896 len1 = remove_space(p->one->path, strlen(p->one->path));
6897 len2 = remove_space(p->two->path, strlen(p->two->path));
6898 patch_id_add_string(&ctx, "diff--git");
6899 patch_id_add_string(&ctx, "a/");
6900 git_hash_update(&ctx, p->one->path, len1);
6901 patch_id_add_string(&ctx, "b/");
6902 git_hash_update(&ctx, p->two->path, len2);
6903
6904 if (p->one->mode == 0) {
6905 patch_id_add_string(&ctx, "newfilemode");
6906 patch_id_add_mode(&ctx, p->two->mode);
6907 } else if (p->two->mode == 0) {
6908 patch_id_add_string(&ctx, "deletedfilemode");
6909 patch_id_add_mode(&ctx, p->one->mode);
6910 } else if (p->one->mode != p->two->mode) {
6911 patch_id_add_string(&ctx, "oldmode");
6912 patch_id_add_mode(&ctx, p->one->mode);
6913 patch_id_add_string(&ctx, "newmode");
6914 patch_id_add_mode(&ctx, p->two->mode);
6915 }
6916
6917 if (diff_header_only) {
6918 /* don't do anything since we're only populating header info */
6919 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6920 diff_filespec_is_binary(options->repo, p->two)) {
6921 git_hash_update(&ctx, oid_to_hex(&p->one->oid),
6922 the_hash_algo->hexsz);
6923 git_hash_update(&ctx, oid_to_hex(&p->two->oid),
6924 the_hash_algo->hexsz);
6925 } else {
6926 if (p->one->mode == 0) {
6927 patch_id_add_string(&ctx, "---/dev/null");
6928 patch_id_add_string(&ctx, "+++b/");
6929 git_hash_update(&ctx, p->two->path, len2);
6930 } else if (p->two->mode == 0) {
6931 patch_id_add_string(&ctx, "---a/");
6932 git_hash_update(&ctx, p->one->path, len1);
6933 patch_id_add_string(&ctx, "+++/dev/null");
6934 } else {
6935 patch_id_add_string(&ctx, "---a/");
6936 git_hash_update(&ctx, p->one->path, len1);
6937 patch_id_add_string(&ctx, "+++b/");
6938 git_hash_update(&ctx, p->two->path, len2);
6939 }
6940
6941 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6942 fill_mmfile(options->repo, &mf2, p->two) < 0)
6943 return error("unable to read files to diff");
6944 xpp.flags = 0;
6945 xecfg.ctxlen = 3;
6946 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6947 if (xdi_diff_outf(&mf1, &mf2, NULL,
6948 patch_id_consume, &data, &xpp, &xecfg))
6949 return error("unable to generate patch-id diff for %s",
6950 p->one->path);
6951 }
6952 flush_one_hunk(oid, &ctx);
6953 }
6954
6955 git_hash_discard(&ctx);
6956 return 0;
6957}
6958
6959int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6960{
6961 struct diff_queue_struct *q = &diff_queued_diff;
6962 int result = diff_get_patch_id(options, oid, diff_header_only);
6963
6964 diff_queue_clear(q);
6965
6966 return result;
6967}
6968
6969static int is_summary_empty(const struct diff_queue_struct *q)
6970{
6971 int i;
6972
6973 for (i = 0; i < q->nr; i++) {
6974 const struct diff_filepair *p = q->queue[i];
6975
6976 switch (p->status) {
6977 case DIFF_STATUS_DELETED:
6978 case DIFF_STATUS_ADDED:
6979 case DIFF_STATUS_COPIED:
6980 case DIFF_STATUS_RENAMED:
6981 return 0;
6982 default:
6983 if (p->score)
6984 return 0;
6985 if (p->one->mode && p->two->mode &&
6986 p->one->mode != p->two->mode)
6987 return 0;
6988 break;
6989 }
6990 }
6991 return 1;
6992}
6993
6994static const char rename_limit_warning[] =
6995N_("exhaustive rename detection was skipped due to too many files.");
6996
6997static const char degrade_cc_to_c_warning[] =
6998N_("only found copies from modified paths due to too many files.");
6999
7000static const char rename_limit_advice[] =
7001N_("you may want to set your %s variable to at least "
7002 "%d and retry the command.");
7003
7004void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
7005{
7006 fflush(stdout);
7007 if (degraded_cc)
7008 warning(_(degrade_cc_to_c_warning));
7009 else if (needed)
7010 warning(_(rename_limit_warning));
7011 else
7012 return;
7013 if (0 < needed)
7014 warning(_(rename_limit_advice), varname, needed);
7015}
7016
7017static void create_filepairs_for_header_only_notifications(struct diff_options *o)
7018{
7019 struct strset present;
7020 struct diff_queue_struct *q = &diff_queued_diff;
7021 struct hashmap_iter iter;
7022 struct strmap_entry *e;
7023 int i;
7024
7025 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
7026
7027 /*
7028 * Find out which paths exist in diff_queued_diff, preferring
7029 * one->path for any pair that has multiple paths.
7030 */
7031 for (i = 0; i < q->nr; i++) {
7032 struct diff_filepair *p = q->queue[i];
7033 char *path = p->one->path ? p->one->path : p->two->path;
7034
7035 if (strmap_contains(o->additional_path_headers, path))
7036 strset_add(&present, path);
7037 }
7038
7039 /*
7040 * Loop over paths in additional_path_headers; for each NOT already
7041 * in diff_queued_diff, create a synthetic filepair and insert that
7042 * into diff_queued_diff.
7043 */
7044 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
7045 if (!strset_contains(&present, e->key)) {
7046 struct diff_filespec *one, *two;
7047 struct diff_filepair *p;
7048
7049 one = alloc_filespec(e->key);
7050 two = alloc_filespec(e->key);
7051 fill_filespec(one, null_oid(the_hash_algo), 0, 0);
7052 fill_filespec(two, null_oid(the_hash_algo), 0, 0);
7053 p = diff_queue(q, one, two);
7054 p->status = DIFF_STATUS_MODIFIED;
7055 }
7056 }
7057
7058 /* Re-sort the filepairs */
7059 diffcore_fix_diff_index();
7060
7061 /* Cleanup */
7062 strset_clear(&present);
7063}
7064
7065static void diff_flush_patch_all_file_pairs(struct diff_options *o)
7066{
7067 int i;
7068 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
7069 struct diff_queue_struct *q = &diff_queued_diff;
7070
7071 if (WSEH_NEW & WS_RULE_MASK)
7072 BUG("WS rules bit mask overlaps with diff symbol flags");
7073
7074 if (o->color_moved && want_color(o->use_color))
7075 o->emitted_symbols = &esm;
7076
7077 if (o->additional_path_headers)
7078 create_filepairs_for_header_only_notifications(o);
7079
7080 for (i = 0; i < q->nr; i++) {
7081 struct diff_filepair *p = q->queue[i];
7082 if (check_pair_status(p))
7083 diff_flush_patch(p, o);
7084 }
7085
7086 if (o->emitted_symbols) {
7087 struct mem_pool entry_pool;
7088 struct moved_entry_list *entry_list;
7089
7090 mem_pool_init(&entry_pool, 1024 * 1024);
7091 entry_list = add_lines_to_move_detection(o, &entry_pool);
7092 mark_color_as_moved(o, entry_list);
7093 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
7094 dim_moved_lines(o);
7095
7096 mem_pool_discard(&entry_pool, 0);
7097 free(entry_list);
7098
7099 for (i = 0; i < esm.nr; i++)
7100 emit_diff_symbol_from_struct(o, &esm.buf[i]);
7101
7102 for (i = 0; i < esm.nr; i++)
7103 free((void *)esm.buf[i].line);
7104 esm.nr = 0;
7105
7106 o->emitted_symbols = NULL;
7107 }
7108}
7109
7110static void diff_free_file(struct diff_options *options)
7111{
7112 if (options->close_file && options->file) {
7113 fclose(options->file);
7114 options->file = NULL;
7115 }
7116}
7117
7118static void diff_free_ignore_regex(struct diff_options *options)
7119{
7120 int i;
7121
7122 for (i = 0; i < options->ignore_regex_nr; i++) {
7123 regfree(options->ignore_regex[i]);
7124 free(options->ignore_regex[i]);
7125 }
7126
7127 FREE_AND_NULL(options->ignore_regex);
7128 options->ignore_regex_nr = 0;
7129}
7130
7131void diff_free(struct diff_options *options)
7132{
7133 if (options->no_free)
7134 return;
7135
7136 if (options->objfind) {
7137 oidset_clear(options->objfind);
7138 FREE_AND_NULL(options->objfind);
7139 }
7140
7141 FREE_AND_NULL(options->orderfile);
7142 for (size_t i = 0; i < options->anchors_nr; i++)
7143 free(options->anchors[i]);
7144 FREE_AND_NULL(options->anchors);
7145 options->anchors_nr = options->anchors_alloc = 0;
7146
7147 diff_free_file(options);
7148 diff_free_ignore_regex(options);
7149 clear_pathspec(&options->pathspec);
7150}
7151
7152void diff_flush(struct diff_options *options)
7153{
7154 struct diff_queue_struct *q = &diff_queued_diff;
7155 int i, output_format = options->output_format;
7156 int separator = 0;
7157 int dirstat_by_line = 0;
7158
7159 /*
7160 * Order: raw, stat, summary, patch
7161 * or: name/name-status/checkdiff (other bits clear)
7162 */
7163 if (!q->nr && !options->additional_path_headers)
7164 goto free_queue;
7165
7166 if (output_format & (DIFF_FORMAT_RAW |
7167 DIFF_FORMAT_NAME |
7168 DIFF_FORMAT_NAME_STATUS |
7169 DIFF_FORMAT_CHECKDIFF)) {
7170 for (i = 0; i < q->nr; i++) {
7171 struct diff_filepair *p = q->queue[i];
7172
7173 if (!check_pair_status(p))
7174 continue;
7175
7176 if (options->flags.diff_from_contents &&
7177 !diff_flush_patch_quietly(p, options))
7178 continue;
7179
7180 flush_one_pair(p, options);
7181 }
7182 separator++;
7183 }
7184
7185 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
7186 dirstat_by_line = 1;
7187
7188 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
7189 dirstat_by_line) {
7190 struct diffstat_t diffstat;
7191
7192 compute_diffstat(options, &diffstat, q);
7193 if (output_format & DIFF_FORMAT_NUMSTAT)
7194 show_numstat(&diffstat, options);
7195 if (output_format & DIFF_FORMAT_DIFFSTAT)
7196 show_stats(&diffstat, options);
7197 if (output_format & DIFF_FORMAT_SHORTSTAT)
7198 show_shortstats(&diffstat, options);
7199 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
7200 show_dirstat_by_line(&diffstat, options);
7201 free_diffstat_info(&diffstat);
7202 separator++;
7203 }
7204 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
7205 show_dirstat(options);
7206
7207 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
7208 for (i = 0; i < q->nr; i++) {
7209 diff_summary(options, q->queue[i]);
7210 }
7211 separator++;
7212 }
7213
7214 if (output_format & DIFF_FORMAT_PATCH) {
7215 if (separator) {
7216 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
7217 if (options->stat_sep)
7218 /* attach patch instead of inline */
7219 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
7220 NULL, 0, 0);
7221 }
7222
7223 diff_flush_patch_all_file_pairs(options);
7224 }
7225
7226 if (output_format & DIFF_FORMAT_CALLBACK)
7227 options->format_callback(q, options, options->format_callback_data);
7228
7229 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
7230 options->flags.exit_with_status &&
7231 options->flags.diff_from_contents) {
7232 for (i = 0; i < q->nr; i++) {
7233 struct diff_filepair *p = q->queue[i];
7234 if (check_pair_status(p))
7235 diff_flush_patch_quietly(p, options);
7236 if (options->found_changes)
7237 break;
7238 }
7239 }
7240
7241free_queue:
7242 diff_queue_clear(q);
7243 diff_free(options);
7244
7245 /*
7246 * Report the content-level differences with HAS_CHANGES;
7247 * diff_addremove/diff_change does not set the bit when
7248 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
7249 */
7250 if (options->flags.diff_from_contents) {
7251 if (options->found_changes)
7252 options->flags.has_changes = 1;
7253 else
7254 options->flags.has_changes = 0;
7255 }
7256}
7257
7258static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
7259{
7260 return (((p->status == DIFF_STATUS_MODIFIED) &&
7261 ((p->score &&
7262 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
7263 (!p->score &&
7264 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
7265 ((p->status != DIFF_STATUS_MODIFIED) &&
7266 filter_bit_tst(p->status, options)));
7267}
7268
7269static void diffcore_apply_filter(struct diff_options *options)
7270{
7271 int i;
7272 struct diff_queue_struct *q = &diff_queued_diff;
7273 struct diff_queue_struct outq = DIFF_QUEUE_INIT;
7274
7275 if (!options->filter)
7276 return;
7277
7278 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
7279 int found;
7280 for (i = found = 0; !found && i < q->nr; i++) {
7281 if (match_filter(options, q->queue[i]))
7282 found++;
7283 }
7284 if (found)
7285 return;
7286
7287 /* otherwise we will clear the whole queue
7288 * by copying the empty outq at the end of this
7289 * function, but first clear the current entries
7290 * in the queue.
7291 */
7292 for (i = 0; i < q->nr; i++)
7293 diff_free_filepair(q->queue[i]);
7294 }
7295 else {
7296 /* Only the matching ones */
7297 for (i = 0; i < q->nr; i++) {
7298 struct diff_filepair *p = q->queue[i];
7299 if (match_filter(options, p))
7300 diff_q(&outq, p);
7301 else
7302 diff_free_filepair(p);
7303 }
7304 }
7305 free(q->queue);
7306 *q = outq;
7307}
7308
7309/* Check whether two filespecs with the same mode and size are identical */
7310static int diff_filespec_is_identical(struct repository *r,
7311 struct diff_filespec *one,
7312 struct diff_filespec *two)
7313{
7314 if (S_ISGITLINK(one->mode))
7315 return 0;
7316 if (diff_populate_filespec(r, one, NULL))
7317 return 0;
7318 if (diff_populate_filespec(r, two, NULL))
7319 return 0;
7320 return !memcmp(one->data, two->data, one->size);
7321}
7322
7323static int diff_filespec_check_stat_unmatch(struct repository *r,
7324 struct diff_filepair *p)
7325{
7326 struct diff_populate_filespec_options dpf_options = {
7327 .check_size_only = 1,
7328 .missing_object_cb = diff_queued_diff_prefetch,
7329 .missing_object_data = r,
7330 };
7331
7332 if (p->done_skip_stat_unmatch)
7333 return p->skip_stat_unmatch_result;
7334
7335 p->done_skip_stat_unmatch = 1;
7336 p->skip_stat_unmatch_result = 0;
7337 /*
7338 * 1. Entries that come from stat info dirtiness
7339 * always have both sides (iow, not create/delete),
7340 * one side of the object name is unknown, with
7341 * the same mode and size. Keep the ones that
7342 * do not match these criteria. They have real
7343 * differences.
7344 *
7345 * 2. At this point, the file is known to be modified,
7346 * with the same mode and size, and the object
7347 * name of one side is unknown. Need to inspect
7348 * the identical contents.
7349 */
7350 if (!DIFF_FILE_VALID(p->one) || /* (1) */
7351 !DIFF_FILE_VALID(p->two) ||
7352 (p->one->oid_valid && p->two->oid_valid) ||
7353 (p->one->mode != p->two->mode) ||
7354 diff_populate_filespec(r, p->one, &dpf_options) ||
7355 diff_populate_filespec(r, p->two, &dpf_options) ||
7356 (p->one->size != p->two->size) ||
7357 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
7358 p->skip_stat_unmatch_result = 1;
7359 return p->skip_stat_unmatch_result;
7360}
7361
7362static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
7363{
7364 int i;
7365 struct diff_queue_struct *q = &diff_queued_diff;
7366 struct diff_queue_struct outq = DIFF_QUEUE_INIT;
7367
7368 for (i = 0; i < q->nr; i++) {
7369 struct diff_filepair *p = q->queue[i];
7370
7371 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
7372 diff_q(&outq, p);
7373 else {
7374 /*
7375 * The caller can subtract 1 from skip_stat_unmatch
7376 * to determine how many paths were dirty only
7377 * due to stat info mismatch.
7378 */
7379 if (!diffopt->flags.no_index)
7380 diffopt->skip_stat_unmatch++;
7381 diff_free_filepair(p);
7382 q->queue[i] = NULL;
7383 }
7384 }
7385 free(q->queue);
7386 *q = outq;
7387}
7388
7389static int diffnamecmp(const void *a_, const void *b_)
7390{
7391 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
7392 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
7393 const char *name_a, *name_b;
7394
7395 name_a = a->one ? a->one->path : a->two->path;
7396 name_b = b->one ? b->one->path : b->two->path;
7397 return strcmp(name_a, name_b);
7398}
7399
7400void diffcore_fix_diff_index(void)
7401{
7402 struct diff_queue_struct *q = &diff_queued_diff;
7403 QSORT(q->queue, q->nr, diffnamecmp);
7404}
7405
7406void diff_add_if_missing(struct repository *r,
7407 struct oid_array *to_fetch,
7408 const struct diff_filespec *filespec)
7409{
7410 if (filespec && filespec->oid_valid &&
7411 !S_ISGITLINK(filespec->mode) &&
7412 odb_read_object_info_extended(r->objects, &filespec->oid, NULL,
7413 OBJECT_INFO_FOR_PREFETCH))
7414 oid_array_append(to_fetch, &filespec->oid);
7415}
7416
7417void diff_queued_diff_prefetch(void *repository)
7418{
7419 struct repository *repo = repository;
7420 int i;
7421 struct diff_queue_struct *q = &diff_queued_diff;
7422 struct oid_array to_fetch = OID_ARRAY_INIT;
7423
7424 for (i = 0; i < q->nr; i++) {
7425 struct diff_filepair *p = q->queue[i];
7426
7427 if (!p)
7428 continue;
7429
7430 diff_add_if_missing(repo, &to_fetch, p->one);
7431 diff_add_if_missing(repo, &to_fetch, p->two);
7432 }
7433
7434 /*
7435 * NEEDSWORK: Consider deduplicating the OIDs sent.
7436 */
7437 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
7438
7439 oid_array_clear(&to_fetch);
7440}
7441
7442void init_diffstat_widths(struct diff_options *options)
7443{
7444 options->stat_width = -1; /* use full terminal width */
7445 options->stat_name_width = -1; /* respect diff.statNameWidth config */
7446 options->stat_graph_width = -1; /* respect diff.statGraphWidth config */
7447}
7448
7449void diffcore_std(struct diff_options *options)
7450{
7451 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
7452 DIFF_FORMAT_NUMSTAT |
7453 DIFF_FORMAT_PATCH |
7454 DIFF_FORMAT_SHORTSTAT |
7455 DIFF_FORMAT_DIRSTAT;
7456
7457 /*
7458 * Check if the user requested a blob-data-requiring diff output and/or
7459 * break-rewrite detection (which requires blob data). If yes, prefetch
7460 * the diff pairs.
7461 *
7462 * If no prefetching occurs, diffcore_rename() will prefetch if it
7463 * decides that it needs inexact rename detection.
7464 */
7465 if (repo_has_promisor_remote(options->repo) &&
7466 (options->output_format & output_formats_to_prefetch ||
7467 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
7468 diff_queued_diff_prefetch(options->repo);
7469
7470 /* NOTE please keep the following in sync with diff_tree_combined() */
7471 if (options->skip_stat_unmatch)
7472 diffcore_skip_stat_unmatch(options);
7473 if (!options->found_follow) {
7474 /* See try_to_follow_renames() in tree-diff.c */
7475 if (options->break_opt != -1)
7476 diffcore_break(options->repo,
7477 options->break_opt);
7478 if (options->detect_rename)
7479 diffcore_rename(options);
7480 if (options->break_opt != -1)
7481 diffcore_merge_broken();
7482 }
7483 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
7484 diffcore_pickaxe(options);
7485 if (options->orderfile)
7486 diffcore_order(options->orderfile);
7487 if (options->rotate_to)
7488 diffcore_rotate(options);
7489 if (!options->found_follow && !options->skip_resolving_statuses)
7490 /* See try_to_follow_renames() in tree-diff.c */
7491 diff_resolve_rename_copy();
7492 diffcore_apply_filter(options);
7493
7494 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
7495 options->flags.has_changes = 1;
7496 else
7497 options->flags.has_changes = 0;
7498
7499 options->found_follow = 0;
7500}
7501
7502int diff_result_code(struct rev_info *revs)
7503{
7504 struct diff_options *opt = &revs->diffopt;
7505 int result = 0;
7506
7507 if (revs->remerge_diff) {
7508 tmp_objdir_destroy(revs->remerge_objdir);
7509 revs->remerge_objdir = NULL;
7510 }
7511
7512 diff_warn_rename_limit("diff.renameLimit",
7513 opt->needed_rename_limit,
7514 opt->degraded_cc_to_c);
7515
7516 if (opt->flags.exit_with_status &&
7517 opt->flags.has_changes)
7518 result |= 01;
7519 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
7520 opt->flags.check_failed)
7521 result |= 02;
7522 return result;
7523}
7524
7525int diff_can_quit_early(struct diff_options *opt)
7526{
7527 return (opt->flags.quick &&
7528 !opt->filter &&
7529 opt->flags.has_changes);
7530}
7531
7532/*
7533 * Shall changes to this submodule be ignored?
7534 *
7535 * Submodule changes can be configured to be ignored separately for each path,
7536 * but that configuration can be overridden from the command line.
7537 */
7538static int is_submodule_ignored(const char *path, struct diff_options *options)
7539{
7540 int ignored = 0;
7541 struct diff_flags orig_flags = options->flags;
7542 if (!options->flags.override_submodule_config)
7543 set_diffopt_flags_from_submodule_config(options, path);
7544 if (options->flags.ignore_submodules)
7545 ignored = 1;
7546 options->flags = orig_flags;
7547 return ignored;
7548}
7549
7550void compute_diffstat(struct diff_options *options,
7551 struct diffstat_t *diffstat,
7552 struct diff_queue_struct *q)
7553{
7554 int i;
7555
7556 memset(diffstat, 0, sizeof(struct diffstat_t));
7557 for (i = 0; i < q->nr; i++) {
7558 struct diff_filepair *p = q->queue[i];
7559 if (check_pair_status(p))
7560 diff_flush_stat(p, options, diffstat);
7561 }
7562 options->found_changes = !!diffstat->nr;
7563}
7564
7565struct diff_filepair *diff_queue_addremove(struct diff_queue_struct *queue,
7566 struct diff_options *options,
7567 int addremove, unsigned mode,
7568 const struct object_id *oid,
7569 int oid_valid,
7570 const char *concatpath,
7571 unsigned dirty_submodule)
7572{
7573 struct diff_filespec *one, *two;
7574 struct diff_filepair *pair;
7575
7576 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7577 return NULL;
7578
7579 /* This may look odd, but it is a preparation for
7580 * feeding "there are unchanged files which should
7581 * not produce diffs, but when you are doing copy
7582 * detection you would need them, so here they are"
7583 * entries to the diff-core. They will be prefixed
7584 * with something like '=' or '*' (I haven't decided
7585 * which but should not make any difference).
7586 * Feeding the same new and old to diff_change()
7587 * also has the same effect.
7588 * Before the final output happens, they are pruned after
7589 * merged into rename/copy pairs as appropriate.
7590 */
7591 if (options->flags.reverse_diff)
7592 addremove = (addremove == '+' ? '-' :
7593 addremove == '-' ? '+' : addremove);
7594
7595 if (options->prefix &&
7596 strncmp(concatpath, options->prefix, options->prefix_length))
7597 return NULL;
7598
7599 one = alloc_filespec(concatpath);
7600 two = alloc_filespec(concatpath);
7601
7602 if (addremove != '+')
7603 fill_filespec(one, oid, oid_valid, mode);
7604 if (addremove != '-') {
7605 fill_filespec(two, oid, oid_valid, mode);
7606 two->dirty_submodule = dirty_submodule;
7607 }
7608
7609 pair = diff_queue(queue, one, two);
7610 if (!options->flags.diff_from_contents)
7611 options->flags.has_changes = 1;
7612
7613 return pair;
7614}
7615
7616struct diff_filepair *diff_queue_change(struct diff_queue_struct *queue,
7617 struct diff_options *options,
7618 unsigned old_mode, unsigned new_mode,
7619 const struct object_id *old_oid,
7620 const struct object_id *new_oid,
7621 int old_oid_valid, int new_oid_valid,
7622 const char *concatpath,
7623 unsigned old_dirty_submodule,
7624 unsigned new_dirty_submodule)
7625{
7626 struct diff_filespec *one, *two;
7627 struct diff_filepair *p;
7628
7629 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7630 is_submodule_ignored(concatpath, options))
7631 return NULL;
7632
7633 if (options->flags.reverse_diff) {
7634 SWAP(old_mode, new_mode);
7635 SWAP(old_oid, new_oid);
7636 SWAP(old_oid_valid, new_oid_valid);
7637 SWAP(old_dirty_submodule, new_dirty_submodule);
7638 }
7639
7640 if (options->prefix &&
7641 strncmp(concatpath, options->prefix, options->prefix_length))
7642 return NULL;
7643
7644 one = alloc_filespec(concatpath);
7645 two = alloc_filespec(concatpath);
7646 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7647 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7648 one->dirty_submodule = old_dirty_submodule;
7649 two->dirty_submodule = new_dirty_submodule;
7650 p = diff_queue(queue, one, two);
7651
7652 if (options->flags.diff_from_contents)
7653 return p;
7654
7655 if (options->flags.quick && options->skip_stat_unmatch &&
7656 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7657 diff_free_filespec_data(p->one);
7658 diff_free_filespec_data(p->two);
7659 return p;
7660 }
7661
7662 options->flags.has_changes = 1;
7663
7664 return p;
7665}
7666
7667void diff_addremove(struct diff_options *options, int addremove, unsigned mode,
7668 const struct object_id *oid, int oid_valid,
7669 const char *concatpath, unsigned dirty_submodule)
7670{
7671 diff_queue_addremove(&diff_queued_diff, options, addremove, mode, oid,
7672 oid_valid, concatpath, dirty_submodule);
7673}
7674
7675void diff_change(struct diff_options *options,
7676 unsigned old_mode, unsigned new_mode,
7677 const struct object_id *old_oid,
7678 const struct object_id *new_oid,
7679 int old_oid_valid, int new_oid_valid,
7680 const char *concatpath,
7681 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7682{
7683 diff_queue_change(&diff_queued_diff, options, old_mode, new_mode,
7684 old_oid, new_oid, old_oid_valid, new_oid_valid,
7685 concatpath, old_dirty_submodule, new_dirty_submodule);
7686}
7687
7688void diff_same(struct diff_options *options,
7689 unsigned mode,
7690 const struct object_id *oid,
7691 const char *concatpath)
7692{
7693 struct diff_filespec *one;
7694
7695 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7696 return;
7697
7698 if (options->prefix &&
7699 strncmp(concatpath, options->prefix, options->prefix_length))
7700 return;
7701
7702 one = alloc_filespec(concatpath);
7703 fill_filespec(one, oid, 1, mode);
7704 one->count++;
7705 diff_queue(&diff_queued_diff, one, one);
7706}
7707
7708struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7709{
7710 struct diff_filepair *pair;
7711 struct diff_filespec *one, *two;
7712
7713 if (options->prefix &&
7714 strncmp(path, options->prefix, options->prefix_length))
7715 return NULL;
7716
7717 one = alloc_filespec(path);
7718 two = alloc_filespec(path);
7719 pair = diff_queue(&diff_queued_diff, one, two);
7720 pair->is_unmerged = 1;
7721 return pair;
7722}
7723
7724static char *run_textconv(struct repository *r,
7725 const char *pgm,
7726 struct diff_filespec *spec,
7727 size_t *outsize)
7728{
7729 struct diff_tempfile *temp;
7730 struct child_process child = CHILD_PROCESS_INIT;
7731 struct strbuf buf = STRBUF_INIT;
7732 int err = 0;
7733
7734 temp = prepare_temp_file(r, spec);
7735 strvec_push(&child.args, pgm);
7736 strvec_push(&child.args, temp->name);
7737
7738 child.use_shell = 1;
7739 child.out = -1;
7740 if (start_command(&child)) {
7741 remove_tempfile();
7742 return NULL;
7743 }
7744
7745 if (strbuf_read(&buf, child.out, 0) < 0)
7746 err = error("error reading from textconv command '%s'", pgm);
7747 close(child.out);
7748
7749 if (finish_command(&child) || err) {
7750 strbuf_release(&buf);
7751 remove_tempfile();
7752 return NULL;
7753 }
7754 remove_tempfile();
7755
7756 return strbuf_detach(&buf, outsize);
7757}
7758
7759size_t fill_textconv(struct repository *r,
7760 struct userdiff_driver *driver,
7761 struct diff_filespec *df,
7762 char **outbuf)
7763{
7764 size_t size;
7765
7766 if (!driver) {
7767 if (!DIFF_FILE_VALID(df)) {
7768 *outbuf = (char *) "";
7769 return 0;
7770 }
7771 if (diff_populate_filespec(r, df, NULL))
7772 die("unable to read files to diff");
7773 *outbuf = df->data;
7774 return df->size;
7775 }
7776
7777 if (!driver->textconv)
7778 BUG("fill_textconv called with non-textconv driver");
7779
7780 if (driver->textconv_cache && df->oid_valid) {
7781 *outbuf = notes_cache_get(driver->textconv_cache,
7782 &df->oid,
7783 &size);
7784 if (*outbuf)
7785 return size;
7786 }
7787
7788 *outbuf = run_textconv(r, driver->textconv, df, &size);
7789 if (!*outbuf)
7790 die("unable to read files to diff");
7791
7792 if (driver->textconv_cache && df->oid_valid) {
7793 /* ignore errors, as we might be in a readonly repository */
7794 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7795 size);
7796 /*
7797 * we could save up changes and flush them all at the end,
7798 * but we would need an extra call after all diffing is done.
7799 * Since generating a cache entry is the slow path anyway,
7800 * this extra overhead probably isn't a big deal.
7801 */
7802 notes_cache_write(driver->textconv_cache);
7803 }
7804
7805 return size;
7806}
7807
7808int textconv_object(struct repository *r,
7809 const char *path,
7810 unsigned mode,
7811 const struct object_id *oid,
7812 int oid_valid,
7813 char **buf,
7814 unsigned long *buf_size)
7815{
7816 struct diff_filespec *df;
7817 struct userdiff_driver *textconv;
7818
7819 df = alloc_filespec(path);
7820 fill_filespec(df, oid, oid_valid, mode);
7821 textconv = get_textconv(r, df);
7822 if (!textconv) {
7823 free_filespec(df);
7824 return 0;
7825 }
7826
7827 *buf_size = fill_textconv(r, textconv, df, buf);
7828 free_filespec(df);
7829 return 1;
7830}
7831
7832void setup_diff_pager(struct diff_options *opt)
7833{
7834 /*
7835 * If the user asked for our exit code, then either they want --quiet
7836 * or --exit-code. We should definitely not bother with a pager in the
7837 * former case, as we will generate no output. Since we still properly
7838 * report our exit code even when a pager is run, we _could_ run a
7839 * pager with --exit-code. But since we have not done so historically,
7840 * and because it is easy to find people oneline advising "git diff
7841 * --exit-code" in hooks and other scripts, we do not do so.
7842 */
7843 if (!opt->flags.exit_with_status &&
7844 check_pager_config(the_repository, "diff") != 0)
7845 setup_pager(the_repository);
7846}