at commit 53d330c3

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
56 static int diff_detect_rename_default;
57 static int diff_indent_heuristic = 1;
58 static int diff_rename_limit_default = 1000;
59 static int diff_suppress_blank_empty;
60 static enum git_colorbool diff_use_color_default = GIT_COLOR_UNKNOWN;
61 static int diff_color_moved_default;
62 static int diff_color_moved_ws_default;
63 static unsigned int diff_context_default = 3;
64 static unsigned int diff_interhunk_context_default;
65 static char *diff_word_regex_cfg;
66 static struct external_diff external_diff_cfg;
67 static char *diff_order_file_cfg;
68 int diff_auto_refresh_index = 1;
69 static int diff_mnemonic_prefix;
70 static int diff_no_prefix;
71 static char *diff_src_prefix;
72 static char *diff_dst_prefix;
73 static int diff_relative;
74 static int diff_stat_name_width;
75 static int diff_stat_graph_width;
76 static int diff_dirstat_permille_default = 30;
77 static struct diff_options default_diff_options;
78 static long diff_algorithm;
79 static unsigned ws_error_highlight_default = WSEH_NEW;
80
81 static 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
107 static 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
132 define_list_config_array_extra(color_diff_slots, {"plain"});
133
134 static 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
141 static 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
194 static 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
211 int 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
220 long 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
239 static 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
249 static 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 */
282 void init_diff_ui_defaults(void)
283 {
284 diff_detect_rename_default = DIFF_DETECT_RENAME;
285 }
286
287 int 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
295 static 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
324 static 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
360 int 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
478 int 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
540 static 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
558 static 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 */
581 static 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
598 struct 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 */
626 struct 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
658 static 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
681 static 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 */
698 static 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
711 static 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
737 static 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
755 static 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
801 end_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
810 static 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
816 enum 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 */
878 struct 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
889 struct emitted_diff_symbols {
890 struct emitted_diff_symbol *buf;
891 int nr, alloc;
892 };
893 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
894
895 static 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
909 static 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
917 struct moved_entry {
918 const struct emitted_diff_symbol *es;
919 struct moved_entry *next_line;
920 struct moved_entry *next_match;
921 };
922
923 struct 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
930 static 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
970 static 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
982 static 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
1017 struct interned_diff_symbol {
1018 struct hashmap_entry ent;
1019 struct emitted_diff_symbol *es;
1020 };
1021
1022 static 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
1041 static 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
1052 struct moved_entry_list {
1053 struct moved_entry *add, *del;
1054 };
1055
1056 static 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
1118 static 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
1146 static 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)
1193 static 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 */
1214 static 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
1303 static 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
1362 static 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
1398 static 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
1633 static 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
1646 void 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
1651 void 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
1656 void 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
1662 void 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
1668 void 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
1674 void 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
1679 void 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
1685 static 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
1696 static 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
1706 static 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
1713 static 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
1720 static 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
1733 static 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
1800 static 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
1809 static 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
1819 static 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
1834 static 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
1874 static 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
1960 struct 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
1969 static 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
1980 struct 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
1987 struct 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
1993 static 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
1999 struct 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
2009 static 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
2047 out:
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 */
2086 static 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
2098 static 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. */
2152 static 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 */
2191 static 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 */
2227 static 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 */
2281 static 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
2308 static 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
2323 static 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
2330 static 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
2376 static 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
2394 const 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
2401 const 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
2408 static 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
2424 static 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
2439 static 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
2534 static 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
2543 static void discard_pending_rm(struct line_range_callback *s)
2544 {
2545 strbuf_reset(&s->pending_rm);
2546 s->pending_rm_count = 0;
2547 }
2548
2549 static 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
2608 static 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
2636 static 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
2725 static 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
2802 static 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
2822 static 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
2837 const char mime_boundary_leader[] = "------------";
2838
2839 static 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
2852 static 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
2862 static 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
2880 static 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
2921 void 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 */
2942 static 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
2953 static 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
3221 static 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
3243 static 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
3280 struct dirstat_file {
3281 const char *name;
3282 unsigned long changed;
3283 };
3284
3285 struct dirstat_dir {
3286 struct dirstat_file *files;
3287 int alloc, nr, permille, cumulative;
3288 };
3289
3290 static 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
3341 static 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
3348 static 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
3366 static 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
3447 found_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
3458 static 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
3496 static 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
3504 void 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
3512 struct 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
3522 static 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
3532 static 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
3585 static unsigned char *deflate_it(char *data,
3586 unsigned long size,
3587 unsigned long *result_size)
3588 {
3589 int 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
3609 static void emit_binary_diff_body(struct diff_options *o,
3610 mmfile_t *one, mmfile_t *two)
3611 {
3612 void *cp;
3613 void *delta;
3614 void *deflated;
3615 void *data;
3616 unsigned long orig_size;
3617 unsigned long delta_size;
3618 unsigned long deflate_size;
3619 unsigned long data_size;
3620
3621 /* We could do deflated delta, or we could do just deflated two,
3622 * whichever is smaller.
3623 */
3624 delta = NULL;
3625 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3626 if (one->size && two->size) {
3627 delta = diff_delta(one->ptr, one->size,
3628 two->ptr, two->size,
3629 &delta_size, deflate_size);
3630 if (delta) {
3631 void *to_free = delta;
3632 orig_size = delta_size;
3633 delta = deflate_it(delta, delta_size, &delta_size);
3634 free(to_free);
3635 }
3636 }
3637
3638 if (delta && delta_size < deflate_size) {
3639 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3640 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3641 s, strlen(s), 0);
3642 free(s);
3643 free(deflated);
3644 data = delta;
3645 data_size = delta_size;
3646 } else {
3647 char *s = xstrfmt("%lu", two->size);
3648 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3649 s, strlen(s), 0);
3650 free(s);
3651 free(delta);
3652 data = deflated;
3653 data_size = deflate_size;
3654 }
3655
3656 /* emit data encoded in base85 */
3657 cp = data;
3658 while (data_size) {
3659 int len;
3660 int bytes = (52 < data_size) ? 52 : data_size;
3661 char line[71];
3662 data_size -= bytes;
3663 if (bytes <= 26)
3664 line[0] = bytes + 'A' - 1;
3665 else
3666 line[0] = bytes - 26 + 'a' - 1;
3667 encode_85(line + 1, cp, bytes);
3668 cp = (char *) cp + bytes;
3669
3670 len = strlen(line);
3671 line[len++] = '\n';
3672 line[len] = '\0';
3673
3674 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3675 line, len, 0);
3676 }
3677 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3678 free(data);
3679 }
3680
3681 static void emit_binary_diff(struct diff_options *o,
3682 mmfile_t *one, mmfile_t *two)
3683 {
3684 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3685 emit_binary_diff_body(o, one, two);
3686 emit_binary_diff_body(o, two, one);
3687 }
3688
3689 int diff_filespec_is_binary(struct repository *r,
3690 struct diff_filespec *one)
3691 {
3692 struct diff_populate_filespec_options dpf_options = {
3693 .check_binary = 1,
3694 };
3695
3696 if (one->is_binary == -1) {
3697 diff_filespec_load_driver(one, r->index);
3698 if (one->driver->binary != -1)
3699 one->is_binary = one->driver->binary;
3700 else {
3701 if (!one->data && DIFF_FILE_VALID(one))
3702 diff_populate_filespec(r, one, &dpf_options);
3703 if (one->is_binary == -1 && one->data)
3704 one->is_binary = buffer_is_binary(one->data,
3705 one->size);
3706 if (one->is_binary == -1)
3707 one->is_binary = 0;
3708 }
3709 }
3710 return one->is_binary;
3711 }
3712
3713 static const struct userdiff_funcname *
3714 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3715 {
3716 diff_filespec_load_driver(one, o->repo->index);
3717 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3718 }
3719
3720 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3721 {
3722 if (!options->a_prefix)
3723 options->a_prefix = a;
3724 if (!options->b_prefix)
3725 options->b_prefix = b;
3726 }
3727
3728 void diff_set_noprefix(struct diff_options *options)
3729 {
3730 options->a_prefix = options->b_prefix = "";
3731 }
3732
3733 void diff_set_default_prefix(struct diff_options *options)
3734 {
3735 options->a_prefix = diff_src_prefix ? diff_src_prefix : "a/";
3736 options->b_prefix = diff_dst_prefix ? diff_dst_prefix : "b/";
3737 }
3738
3739 struct userdiff_driver *get_textconv(struct repository *r,
3740 struct diff_filespec *one)
3741 {
3742 if (!DIFF_FILE_VALID(one))
3743 return NULL;
3744
3745 diff_filespec_load_driver(one, r->index);
3746 return userdiff_get_textconv(r, one->driver);
3747 }
3748
3749 static struct string_list *additional_headers(struct diff_options *o,
3750 const char *path)
3751 {
3752 if (!o->additional_path_headers)
3753 return NULL;
3754 return strmap_get(o->additional_path_headers, path);
3755 }
3756
3757 static void add_formatted_header(struct strbuf *msg,
3758 const char *header,
3759 const char *line_prefix,
3760 const char *meta,
3761 const char *reset)
3762 {
3763 const char *next, *newline;
3764
3765 for (next = header; *next; next = newline) {
3766 newline = strchrnul(next, '\n');
3767 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3768 (int)(newline - next), next, reset);
3769 if (*newline)
3770 newline++;
3771 }
3772 }
3773
3774 static void add_formatted_headers(struct strbuf *msg,
3775 struct string_list *more_headers,
3776 const char *line_prefix,
3777 const char *meta,
3778 const char *reset)
3779 {
3780 int i;
3781
3782 for (i = 0; i < more_headers->nr; i++)
3783 add_formatted_header(msg, more_headers->items[i].string,
3784 line_prefix, meta, reset);
3785 }
3786
3787 static int diff_filepair_is_phoney(struct diff_filespec *one,
3788 struct diff_filespec *two)
3789 {
3790 /*
3791 * This function specifically looks for pairs injected by
3792 * create_filepairs_for_header_only_notifications(). Such
3793 * pairs are "phoney" in that they do not represent any
3794 * content or even mode difference, but were inserted because
3795 * diff_queued_diff previously had no pair associated with
3796 * that path but we needed some pair to avoid losing the
3797 * "remerge CONFLICT" header associated with the path.
3798 */
3799 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3800 }
3801
3802 static int set_diff_algorithm(struct diff_options *opts,
3803 const char *alg)
3804 {
3805 long value = parse_algorithm_value(alg);
3806
3807 if (value < 0)
3808 return -1;
3809
3810 /* clear out previous settings */
3811 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3812 opts->xdl_opts |= value;
3813
3814 return 0;
3815 }
3816
3817 static void builtin_diff(const char *name_a,
3818 const char *name_b,
3819 struct diff_filespec *one,
3820 struct diff_filespec *two,
3821 const char *xfrm_msg,
3822 int must_show_header,
3823 struct diff_options *o,
3824 int complete_rewrite,
3825 const struct range_set *line_ranges)
3826 {
3827 mmfile_t mf1, mf2;
3828 const char *lbl[2];
3829 char *a_one, *b_two;
3830 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3831 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3832 const char *a_prefix, *b_prefix;
3833 struct userdiff_driver *textconv_one = NULL;
3834 struct userdiff_driver *textconv_two = NULL;
3835 struct strbuf header = STRBUF_INIT;
3836 const char *line_prefix = diff_line_prefix(o);
3837
3838 diff_set_mnemonic_prefix(o, "a/", "b/");
3839 if (o->flags.reverse_diff) {
3840 a_prefix = o->b_prefix;
3841 b_prefix = o->a_prefix;
3842 } else {
3843 a_prefix = o->a_prefix;
3844 b_prefix = o->b_prefix;
3845 }
3846
3847 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3848 (!one->mode || S_ISGITLINK(one->mode)) &&
3849 (!two->mode || S_ISGITLINK(two->mode)) &&
3850 (!diff_filepair_is_phoney(one, two))) {
3851 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3852 &one->oid, &two->oid,
3853 two->dirty_submodule);
3854 o->found_changes = 1;
3855 return;
3856 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3857 (!one->mode || S_ISGITLINK(one->mode)) &&
3858 (!two->mode || S_ISGITLINK(two->mode)) &&
3859 (!diff_filepair_is_phoney(one, two))) {
3860 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3861 &one->oid, &two->oid,
3862 two->dirty_submodule);
3863 o->found_changes = 1;
3864 return;
3865 }
3866
3867 if (o->flags.allow_textconv) {
3868 textconv_one = get_textconv(o->repo, one);
3869 textconv_two = get_textconv(o->repo, two);
3870 }
3871
3872 /* Never use a non-valid filename anywhere if at all possible */
3873 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3874 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3875
3876 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3877 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3878 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3879 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3880 if (diff_filepair_is_phoney(one, two)) {
3881 /*
3882 * We should only reach this point for pairs generated from
3883 * create_filepairs_for_header_only_notifications(). For
3884 * these, we want to avoid the "/dev/null" special casing
3885 * above, because we do not want such pairs shown as either
3886 * "new file" or "deleted file" below.
3887 */
3888 lbl[0] = a_one;
3889 lbl[1] = b_two;
3890 }
3891 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3892 if (lbl[0][0] == '/') {
3893 /* /dev/null */
3894 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3895 if (xfrm_msg)
3896 strbuf_addstr(&header, xfrm_msg);
3897 o->found_changes = 1;
3898 must_show_header = 1;
3899 }
3900 else if (lbl[1][0] == '/') {
3901 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3902 if (xfrm_msg)
3903 strbuf_addstr(&header, xfrm_msg);
3904 o->found_changes = 1;
3905 must_show_header = 1;
3906 }
3907 else {
3908 if (one->mode != two->mode) {
3909 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3910 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3911 o->found_changes = 1;
3912 must_show_header = 1;
3913 }
3914 if (xfrm_msg)
3915 strbuf_addstr(&header, xfrm_msg);
3916
3917 /*
3918 * we do not run diff between different kind
3919 * of objects.
3920 */
3921 if ((one->mode ^ two->mode) & S_IFMT)
3922 goto free_ab_and_return;
3923 if (complete_rewrite &&
3924 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3925 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3926 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3927 header.buf, header.len, 0);
3928 strbuf_reset(&header);
3929 emit_rewrite_diff(name_a, name_b, one, two,
3930 textconv_one, textconv_two, o);
3931 o->found_changes = 1;
3932 goto free_ab_and_return;
3933 }
3934 }
3935
3936 if (o->irreversible_delete && lbl[1][0] == '/') {
3937 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3938 header.len, 0);
3939 strbuf_reset(&header);
3940 goto free_ab_and_return;
3941 } else if (!o->flags.text &&
3942 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3943 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3944 struct strbuf sb = STRBUF_INIT;
3945 if (!one->data && !two->data &&
3946 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3947 !o->flags.binary) {
3948 if (oideq(&one->oid, &two->oid)) {
3949 if (must_show_header)
3950 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3951 header.buf, header.len,
3952 0);
3953 goto free_ab_and_return;
3954 }
3955 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3956 header.buf, header.len, 0);
3957 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3958 diff_line_prefix(o), lbl[0], lbl[1]);
3959 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3960 sb.buf, sb.len, 0);
3961 strbuf_release(&sb);
3962 o->found_changes = 1;
3963 goto free_ab_and_return;
3964 }
3965 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3966 fill_mmfile(o->repo, &mf2, two) < 0)
3967 die("unable to read files to diff");
3968 /* Quite common confusing case */
3969 if (mf1.size == mf2.size &&
3970 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3971 if (must_show_header)
3972 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3973 header.buf, header.len, 0);
3974 goto free_ab_and_return;
3975 }
3976 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3977 strbuf_reset(&header);
3978 if (o->flags.binary)
3979 emit_binary_diff(o, &mf1, &mf2);
3980 else {
3981 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3982 diff_line_prefix(o), lbl[0], lbl[1]);
3983 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3984 sb.buf, sb.len, 0);
3985 strbuf_release(&sb);
3986 }
3987 o->found_changes = 1;
3988 } else {
3989 /* Crazy xdl interfaces.. */
3990 const char *diffopts;
3991 const char *v;
3992 xpparam_t xpp;
3993 xdemitconf_t xecfg;
3994 struct emit_callback ecbdata;
3995 unsigned ws_rule;
3996 const struct userdiff_funcname *pe;
3997
3998 if (must_show_header) {
3999 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
4000 header.buf, header.len, 0);
4001 strbuf_reset(&header);
4002 }
4003
4004 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
4005 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
4006
4007 ws_rule = whitespace_rule(o->repo->index, name_b);
4008
4009 /* symlink being an incomplete line is not a news */
4010 if (DIFF_FILE_VALID(two) && S_ISLNK(two->mode))
4011 ws_rule &= ~WS_INCOMPLETE_LINE;
4012
4013 pe = diff_funcname_pattern(o, one);
4014 if (!pe)
4015 pe = diff_funcname_pattern(o, two);
4016
4017 memset(&xpp, 0, sizeof(xpp));
4018 memset(&xecfg, 0, sizeof(xecfg));
4019 memset(&ecbdata, 0, sizeof(ecbdata));
4020 if (o->flags.suppress_diff_headers)
4021 lbl[0] = NULL;
4022 ecbdata.label_path = lbl;
4023 ecbdata.color_diff = o->use_color;
4024 ecbdata.ws_rule = ws_rule;
4025 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
4026 check_blank_at_eof(&mf1, &mf2, &ecbdata);
4027 ecbdata.opt = o;
4028 if (header.len && !o->flags.suppress_diff_headers)
4029 ecbdata.header = &header;
4030 xpp.flags = o->xdl_opts;
4031 xpp.ignore_regex = o->ignore_regex;
4032 xpp.ignore_regex_nr = o->ignore_regex_nr;
4033 xpp.anchors = o->anchors;
4034 xpp.anchors_nr = o->anchors_nr;
4035 xecfg.ctxlen = o->context;
4036 xecfg.interhunkctxlen = o->interhunkcontext;
4037 xecfg.flags = XDL_EMIT_FUNCNAMES;
4038 if (o->flags.funccontext)
4039 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
4040 if (pe)
4041 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
4042
4043 diffopts = getenv("GIT_DIFF_OPTS");
4044 if (!diffopts)
4045 ;
4046 else if (skip_prefix(diffopts, "--unified=", &v))
4047 xecfg.ctxlen = strtoul(v, NULL, 10);
4048 else if (skip_prefix(diffopts, "-u", &v))
4049 xecfg.ctxlen = strtoul(v, NULL, 10);
4050
4051 if (o->word_diff)
4052 init_diff_words_data(&ecbdata, o, one, two);
4053 if (!o->file) {
4054 /*
4055 * Unlike the normal output case, we need to ignore the
4056 * return value from xdi_diff_outf() here, because
4057 * xdi_diff_outf() takes non-zero return from its
4058 * callback function as a sign of error and returns
4059 * early (which is why we return non-zero from our
4060 * callback, quick_consume()). Unfortunately,
4061 * xdi_diff_outf() signals an error by returning
4062 * non-zero.
4063 */
4064 xdi_diff_outf(&mf1, &mf2, NULL, quick_consume,
4065 &ecbdata, &xpp, &xecfg);
4066 } else if (line_ranges) {
4067 struct line_range_callback lr_state;
4068 unsigned int i;
4069 long max_span = 0;
4070
4071 memset(&lr_state, 0, sizeof(lr_state));
4072 lr_state.orig_line_fn = fn_out_consume;
4073 lr_state.orig_cb_data = &ecbdata;
4074 lr_state.ranges = line_ranges;
4075 strbuf_init(&lr_state.rhunk, 0);
4076 strbuf_init(&lr_state.pending_rm, 0);
4077
4078 /*
4079 * Inflate ctxlen so that all changes within
4080 * any single range are merged into one xdiff
4081 * hunk and the inter-change context is emitted.
4082 * The callback clips back to range boundaries.
4083 *
4084 * The optimal ctxlen depends on where changes
4085 * fall within the range, which is only known
4086 * after xdiff runs; the max range span is the
4087 * upper bound that guarantees correctness in a
4088 * single pass.
4089 */
4090 for (i = 0; i < line_ranges->nr; i++) {
4091 long span = line_ranges->ranges[i].end -
4092 line_ranges->ranges[i].start;
4093 if (span > max_span)
4094 max_span = span;
4095 }
4096 if (max_span > xecfg.ctxlen)
4097 xecfg.ctxlen = max_span;
4098
4099 if (xdi_diff_outf(&mf1, &mf2,
4100 line_range_hunk_fn,
4101 line_range_line_fn,
4102 &lr_state, &xpp, &xecfg))
4103 die("unable to generate diff for %s",
4104 one->path);
4105
4106 flush_rhunk(&lr_state);
4107 if (lr_state.ret)
4108 die("unable to generate diff for %s",
4109 one->path);
4110 strbuf_release(&lr_state.rhunk);
4111 strbuf_release(&lr_state.pending_rm);
4112 } else if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
4113 &ecbdata, &xpp, &xecfg))
4114 die("unable to generate diff for %s", one->path);
4115 if (o->word_diff)
4116 free_diff_words_data(&ecbdata);
4117 if (textconv_one)
4118 free(mf1.ptr);
4119 if (textconv_two)
4120 free(mf2.ptr);
4121 xdiff_clear_find_func(&xecfg);
4122 }
4123
4124 free_ab_and_return:
4125 strbuf_release(&header);
4126 diff_free_filespec_data(one);
4127 diff_free_filespec_data(two);
4128 free(a_one);
4129 free(b_two);
4130 return;
4131 }
4132
4133 static const char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
4134 {
4135 if (!is_renamed) {
4136 if (p->status == DIFF_STATUS_ADDED) {
4137 if (S_ISLNK(p->two->mode))
4138 return "new +l";
4139 else if ((p->two->mode & 0777) == 0755)
4140 return "new +x";
4141 else
4142 return "new";
4143 } else if (p->status == DIFF_STATUS_DELETED)
4144 return "gone";
4145 }
4146 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
4147 return "mode -l";
4148 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
4149 return "mode +l";
4150 else if ((p->one->mode & 0777) == 0644 &&
4151 (p->two->mode & 0777) == 0755)
4152 return "mode +x";
4153 else if ((p->one->mode & 0777) == 0755 &&
4154 (p->two->mode & 0777) == 0644)
4155 return "mode -x";
4156 return NULL;
4157 }
4158
4159 static void builtin_diffstat(const char *name_a, const char *name_b,
4160 struct diff_filespec *one,
4161 struct diff_filespec *two,
4162 struct diffstat_t *diffstat,
4163 struct diff_options *o,
4164 struct diff_filepair *p)
4165 {
4166 mmfile_t mf1, mf2;
4167 struct diffstat_file *data;
4168 int may_differ;
4169 int complete_rewrite = 0;
4170
4171 if (!DIFF_PAIR_UNMERGED(p)) {
4172 if (p->status == DIFF_STATUS_MODIFIED && p->score)
4173 complete_rewrite = 1;
4174 }
4175
4176 data = diffstat_add(diffstat, name_a, name_b);
4177 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
4178 if (o->flags.stat_with_summary)
4179 data->comments = get_compact_summary(p, data->is_renamed);
4180
4181 if (!one || !two) {
4182 data->is_unmerged = 1;
4183 return;
4184 }
4185
4186 /* saves some reads if true, not a guarantee of diff outcome */
4187 may_differ = !(one->oid_valid && two->oid_valid &&
4188 oideq(&one->oid, &two->oid));
4189
4190 if (diff_filespec_is_binary(o->repo, one) ||
4191 diff_filespec_is_binary(o->repo, two)) {
4192 data->is_binary = 1;
4193 if (!may_differ) {
4194 data->added = 0;
4195 data->deleted = 0;
4196 } else {
4197 data->added = diff_filespec_size(o->repo, two);
4198 data->deleted = diff_filespec_size(o->repo, one);
4199 }
4200 }
4201
4202 else if (complete_rewrite) {
4203 diff_populate_filespec(o->repo, one, NULL);
4204 diff_populate_filespec(o->repo, two, NULL);
4205 data->deleted = count_lines(one->data, one->size);
4206 data->added = count_lines(two->data, two->size);
4207 }
4208
4209 else if (may_differ) {
4210 /* Crazy xdl interfaces.. */
4211 xpparam_t xpp;
4212 xdemitconf_t xecfg;
4213
4214 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
4215 fill_mmfile(o->repo, &mf2, two) < 0)
4216 die("unable to read files to diff");
4217
4218 memset(&xpp, 0, sizeof(xpp));
4219 memset(&xecfg, 0, sizeof(xecfg));
4220 xpp.flags = o->xdl_opts;
4221 xpp.ignore_regex = o->ignore_regex;
4222 xpp.ignore_regex_nr = o->ignore_regex_nr;
4223 xpp.anchors = o->anchors;
4224 xpp.anchors_nr = o->anchors_nr;
4225 xecfg.ctxlen = o->context;
4226 xecfg.interhunkctxlen = o->interhunkcontext;
4227 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
4228 if (xdi_diff_outf(&mf1, &mf2, NULL,
4229 diffstat_consume, diffstat, &xpp, &xecfg))
4230 die("unable to generate diffstat for %s", one->path);
4231
4232 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
4233 struct diffstat_file *file =
4234 diffstat->files[diffstat->nr - 1];
4235 /*
4236 * Omit diffstats of modified files where nothing changed.
4237 * Even if may_differ, this might be the case due to
4238 * ignoring whitespace changes, etc.
4239 *
4240 * But note that we special-case additions, deletions,
4241 * renames, and mode changes as adding an empty file,
4242 * for example is still of interest.
4243 */
4244 if ((p->status == DIFF_STATUS_MODIFIED)
4245 && !file->added
4246 && !file->deleted
4247 && one->mode == two->mode) {
4248 free_diffstat_file(file);
4249 diffstat->nr--;
4250 }
4251 }
4252 }
4253
4254 diff_free_filespec_data(one);
4255 diff_free_filespec_data(two);
4256 }
4257
4258 static void builtin_checkdiff(const char *name_a, const char *name_b,
4259 const char *attr_path,
4260 struct diff_filespec *one,
4261 struct diff_filespec *two,
4262 struct diff_options *o)
4263 {
4264 mmfile_t mf1, mf2;
4265 struct checkdiff_t data;
4266
4267 if (!two)
4268 return;
4269
4270 memset(&data, 0, sizeof(data));
4271 data.filename = name_b ? name_b : name_a;
4272 data.lineno = 0;
4273 data.o = o;
4274 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
4275 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
4276
4277 /* symlink being an incomplete line is not a news */
4278 if (DIFF_FILE_VALID(two) && S_ISLNK(two->mode))
4279 data.ws_rule &= ~WS_INCOMPLETE_LINE;
4280
4281 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
4282 fill_mmfile(o->repo, &mf2, two) < 0)
4283 die("unable to read files to diff");
4284
4285 /*
4286 * All the other codepaths check both sides, but not checking
4287 * the "old" side here is deliberate. We are checking the newly
4288 * introduced changes, and as long as the "new" side is text, we
4289 * can and should check what it introduces.
4290 */
4291 if (diff_filespec_is_binary(o->repo, two))
4292 goto free_and_return;
4293 else {
4294 /* Crazy xdl interfaces.. */
4295 xpparam_t xpp;
4296 xdemitconf_t xecfg;
4297
4298 memset(&xpp, 0, sizeof(xpp));
4299 memset(&xecfg, 0, sizeof(xecfg));
4300 xecfg.ctxlen = 1; /* at least one context line */
4301 xpp.flags = 0;
4302 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
4303 checkdiff_consume, &data,
4304 &xpp, &xecfg))
4305 die("unable to generate checkdiff for %s", one->path);
4306
4307 if (data.ws_rule & WS_BLANK_AT_EOF) {
4308 struct emit_callback ecbdata;
4309 int blank_at_eof;
4310
4311 ecbdata.ws_rule = data.ws_rule;
4312 check_blank_at_eof(&mf1, &mf2, &ecbdata);
4313 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
4314
4315 if (blank_at_eof) {
4316 static char *err;
4317 if (!err)
4318 err = whitespace_error_string(WS_BLANK_AT_EOF);
4319 fprintf(o->file, "%s:%d: %s.\n",
4320 data.filename, blank_at_eof, err);
4321 data.status = 1; /* report errors */
4322 }
4323 }
4324 }
4325 free_and_return:
4326 diff_free_filespec_data(one);
4327 diff_free_filespec_data(two);
4328 if (data.status)
4329 o->flags.check_failed = 1;
4330 }
4331
4332 struct diff_filespec *alloc_filespec(const char *path)
4333 {
4334 struct diff_filespec *spec;
4335
4336 FLEXPTR_ALLOC_STR(spec, path, path);
4337 spec->count = 1;
4338 spec->is_binary = -1;
4339 return spec;
4340 }
4341
4342 void free_filespec(struct diff_filespec *spec)
4343 {
4344 if (!--spec->count) {
4345 diff_free_filespec_data(spec);
4346 free(spec);
4347 }
4348 }
4349
4350 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
4351 int oid_valid, unsigned short mode)
4352 {
4353 if (mode) {
4354 spec->mode = canon_mode(mode);
4355 oidcpy(&spec->oid, oid);
4356 spec->oid_valid = oid_valid;
4357 }
4358 }
4359
4360 /*
4361 * Given a name and sha1 pair, if the index tells us the file in
4362 * the work tree has that object contents, return true, so that
4363 * prepare_temp_file() does not have to inflate and extract.
4364 */
4365 static int reuse_worktree_file(struct index_state *istate,
4366 const char *name,
4367 const struct object_id *oid,
4368 int want_file)
4369 {
4370 const struct cache_entry *ce;
4371 struct stat st;
4372 int pos, len;
4373
4374 /*
4375 * We do not read the cache ourselves here, because the
4376 * benchmark with my previous version that always reads cache
4377 * shows that it makes things worse for diff-tree comparing
4378 * two linux-2.6 kernel trees in an already checked out work
4379 * tree. This is because most diff-tree comparisons deal with
4380 * only a small number of files, while reading the cache is
4381 * expensive for a large project, and its cost outweighs the
4382 * savings we get by not inflating the object to a temporary
4383 * file. Practically, this code only helps when we are used
4384 * by diff-cache --cached, which does read the cache before
4385 * calling us.
4386 */
4387 if (!istate->cache)
4388 return 0;
4389
4390 /* We want to avoid the working directory if our caller
4391 * doesn't need the data in a normal file, this system
4392 * is rather slow with its stat/open/mmap/close syscalls,
4393 * and the object is contained in a pack file. The pack
4394 * is probably already open and will be faster to obtain
4395 * the data through than the working directory. Loose
4396 * objects however would tend to be slower as they need
4397 * to be individually opened and inflated.
4398 */
4399 if (!FAST_WORKING_DIRECTORY && !want_file &&
4400 has_object_pack(istate->repo, oid))
4401 return 0;
4402
4403 /*
4404 * Similarly, if we'd have to convert the file contents anyway, that
4405 * makes the optimization not worthwhile.
4406 */
4407 if (!want_file && would_convert_to_git(istate, name))
4408 return 0;
4409
4410 /*
4411 * If this path does not match our sparse-checkout definition,
4412 * then the file will not be in the working directory.
4413 */
4414 if (!path_in_sparse_checkout(name, istate))
4415 return 0;
4416
4417 len = strlen(name);
4418 pos = index_name_pos(istate, name, len);
4419 if (pos < 0)
4420 return 0;
4421 ce = istate->cache[pos];
4422
4423 /*
4424 * This is not the sha1 we are looking for, or
4425 * unreusable because it is not a regular file.
4426 */
4427 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4428 return 0;
4429
4430 /*
4431 * If ce is marked as "assume unchanged", there is no
4432 * guarantee that work tree matches what we are looking for.
4433 */
4434 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4435 return 0;
4436
4437 /*
4438 * If ce matches the file in the work tree, we can reuse it.
4439 */
4440 if (ce_uptodate(ce) ||
4441 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4442 return 1;
4443
4444 return 0;
4445 }
4446
4447 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4448 {
4449 struct strbuf buf = STRBUF_INIT;
4450 const char *dirty = "";
4451
4452 /* Are we looking at the work tree? */
4453 if (s->dirty_submodule)
4454 dirty = "-dirty";
4455
4456 strbuf_addf(&buf, "Subproject commit %s%s\n",
4457 oid_to_hex(&s->oid), dirty);
4458 s->size = buf.len;
4459 if (size_only) {
4460 s->data = NULL;
4461 strbuf_release(&buf);
4462 } else {
4463 s->data = strbuf_detach(&buf, NULL);
4464 s->should_free = 1;
4465 }
4466 return 0;
4467 }
4468
4469 /*
4470 * While doing rename detection and pickaxe operation, we may need to
4471 * grab the data for the blob (or file) for our own in-core comparison.
4472 * diff_filespec has data and size fields for this purpose.
4473 */
4474 int diff_populate_filespec(struct repository *r,
4475 struct diff_filespec *s,
4476 const struct diff_populate_filespec_options *options)
4477 {
4478 int size_only = options ? options->check_size_only : 0;
4479 int check_binary = options ? options->check_binary : 0;
4480 int err = 0;
4481 int conv_flags = global_conv_flags_eol;
4482 /*
4483 * demote FAIL to WARN to allow inspecting the situation
4484 * instead of refusing.
4485 */
4486 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4487 conv_flags = CONV_EOL_RNDTRP_WARN;
4488
4489 if (!DIFF_FILE_VALID(s))
4490 die("internal error: asking to populate invalid file.");
4491 if (S_ISDIR(s->mode))
4492 return -1;
4493
4494 if (s->data)
4495 return 0;
4496
4497 if (size_only && 0 < s->size)
4498 return 0;
4499
4500 if (S_ISGITLINK(s->mode))
4501 return diff_populate_gitlink(s, size_only);
4502
4503 if (!s->oid_valid ||
4504 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4505 struct strbuf buf = STRBUF_INIT;
4506 struct stat st;
4507 int fd;
4508
4509 if (lstat(s->path, &st) < 0) {
4510 err_empty:
4511 err = -1;
4512 empty:
4513 s->data = (char *)"";
4514 s->size = 0;
4515 return err;
4516 }
4517 s->size = xsize_t(st.st_size);
4518 if (!s->size)
4519 goto empty;
4520 if (S_ISLNK(st.st_mode)) {
4521 struct strbuf sb = STRBUF_INIT;
4522
4523 if (strbuf_readlink(&sb, s->path, s->size))
4524 goto err_empty;
4525 s->size = sb.len;
4526 s->data = strbuf_detach(&sb, NULL);
4527 s->should_free = 1;
4528 return 0;
4529 }
4530
4531 /*
4532 * Even if the caller would be happy with getting
4533 * only the size, we cannot return early at this
4534 * point if the path requires us to run the content
4535 * conversion.
4536 */
4537 if (size_only && !would_convert_to_git(r->index, s->path))
4538 return 0;
4539
4540 /*
4541 * Note: this check uses xsize_t(st.st_size) that may
4542 * not be the true size of the blob after it goes
4543 * through convert_to_git(). This may not strictly be
4544 * correct, but the whole point of big_file_threshold
4545 * and is_binary check being that we want to avoid
4546 * opening the file and inspecting the contents, this
4547 * is probably fine.
4548 */
4549 if (check_binary &&
4550 s->size > repo_settings_get_big_file_threshold(the_repository) &&
4551 s->is_binary == -1) {
4552 s->is_binary = 1;
4553 return 0;
4554 }
4555 fd = open(s->path, O_RDONLY);
4556 if (fd < 0)
4557 goto err_empty;
4558 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4559 close(fd);
4560 s->should_munmap = 1;
4561
4562 /*
4563 * Convert from working tree format to canonical git format
4564 */
4565 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4566 size_t size = 0;
4567 munmap(s->data, s->size);
4568 s->should_munmap = 0;
4569 s->data = strbuf_detach(&buf, &size);
4570 s->size = size;
4571 s->should_free = 1;
4572 }
4573 }
4574 else {
4575 size_t size_st = 0;
4576 struct object_info info = {
4577 .sizep = &size_st
4578 };
4579
4580 if (!(size_only || check_binary))
4581 /*
4582 * Set contentp, since there is no chance that merely
4583 * the size is sufficient.
4584 */
4585 info.contentp = &s->data;
4586
4587 if (options && options->missing_object_cb) {
4588 if (!odb_read_object_info_extended(r->objects, &s->oid, &info,
4589 OBJECT_INFO_LOOKUP_REPLACE |
4590 OBJECT_INFO_SKIP_FETCH_OBJECT))
4591 goto object_read;
4592 options->missing_object_cb(options->missing_object_data);
4593 }
4594 if (odb_read_object_info_extended(r->objects, &s->oid, &info,
4595 OBJECT_INFO_LOOKUP_REPLACE))
4596 die("unable to read %s", oid_to_hex(&s->oid));
4597
4598 object_read:
4599 s->size = cast_size_t_to_ulong(size_st);
4600 if (size_only || check_binary) {
4601 if (size_only)
4602 return 0;
4603 if (s->size > repo_settings_get_big_file_threshold(the_repository) &&
4604 s->is_binary == -1) {
4605 s->is_binary = 1;
4606 return 0;
4607 }
4608 }
4609 if (!info.contentp) {
4610 info.contentp = &s->data;
4611 if (odb_read_object_info_extended(r->objects, &s->oid, &info,
4612 OBJECT_INFO_LOOKUP_REPLACE))
4613 die("unable to read %s", oid_to_hex(&s->oid));
4614 s->size = cast_size_t_to_ulong(size_st);
4615 }
4616 s->should_free = 1;
4617 }
4618 return 0;
4619 }
4620
4621 void diff_free_filespec_blob(struct diff_filespec *s)
4622 {
4623 if (s->should_free)
4624 free(s->data);
4625 else if (s->should_munmap)
4626 munmap(s->data, s->size);
4627
4628 if (s->should_free || s->should_munmap) {
4629 s->should_free = s->should_munmap = 0;
4630 s->data = NULL;
4631 }
4632 }
4633
4634 void diff_free_filespec_data(struct diff_filespec *s)
4635 {
4636 if (!s)
4637 return;
4638
4639 diff_free_filespec_blob(s);
4640 FREE_AND_NULL(s->cnt_data);
4641 }
4642
4643 static void prep_temp_blob(struct index_state *istate,
4644 const char *path, struct diff_tempfile *temp,
4645 void *blob,
4646 unsigned long size,
4647 const struct object_id *oid,
4648 int mode)
4649 {
4650 struct strbuf buf = STRBUF_INIT;
4651 char *path_dup = xstrdup(path);
4652 const char *base = basename(path_dup);
4653 struct checkout_metadata meta;
4654
4655 init_checkout_metadata(&meta, NULL, NULL, oid);
4656
4657 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4658 if (!temp->tempfile)
4659 die_errno("unable to create temp-file");
4660 if (convert_to_working_tree(istate, path,
4661 (const char *)blob, (size_t)size, &buf, &meta)) {
4662 blob = buf.buf;
4663 size = buf.len;
4664 }
4665 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4666 close_tempfile_gently(temp->tempfile))
4667 die_errno("unable to write temp-file");
4668 temp->name = get_tempfile_path(temp->tempfile);
4669 oid_to_hex_r(temp->hex, oid);
4670 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4671 strbuf_release(&buf);
4672 free(path_dup);
4673 }
4674
4675 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4676 struct diff_filespec *one)
4677 {
4678 struct diff_tempfile *temp = claim_diff_tempfile();
4679
4680 if (!DIFF_FILE_VALID(one)) {
4681 not_a_valid_file:
4682 /* A '-' entry produces this for file-2, and
4683 * a '+' entry produces this for file-1.
4684 */
4685 temp->name = "/dev/null";
4686 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4687 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4688 return temp;
4689 }
4690
4691 if (!S_ISGITLINK(one->mode) &&
4692 (!one->oid_valid ||
4693 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4694 struct stat st;
4695 if (lstat(one->path, &st) < 0) {
4696 if (errno == ENOENT)
4697 goto not_a_valid_file;
4698 die_errno("stat(%s)", one->path);
4699 }
4700 if (S_ISLNK(st.st_mode)) {
4701 struct strbuf sb = STRBUF_INIT;
4702 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4703 die_errno("readlink(%s)", one->path);
4704 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4705 (one->oid_valid ?
4706 &one->oid : null_oid(the_hash_algo)),
4707 (one->oid_valid ?
4708 one->mode : S_IFLNK));
4709 strbuf_release(&sb);
4710 }
4711 else {
4712 /* we can borrow from the file in the work tree */
4713 temp->name = one->path;
4714 if (!one->oid_valid)
4715 oid_to_hex_r(temp->hex, null_oid(the_hash_algo));
4716 else
4717 oid_to_hex_r(temp->hex, &one->oid);
4718 /* Even though we may sometimes borrow the
4719 * contents from the work tree, we always want
4720 * one->mode. mode is trustworthy even when
4721 * !(one->oid_valid), as long as
4722 * DIFF_FILE_VALID(one).
4723 */
4724 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4725 }
4726 return temp;
4727 }
4728 else {
4729 if (diff_populate_filespec(r, one, NULL))
4730 die("cannot read data blob for %s", one->path);
4731 prep_temp_blob(r->index, one->path, temp,
4732 one->data, one->size,
4733 &one->oid, one->mode);
4734 }
4735 return temp;
4736 }
4737
4738 static void add_external_diff_name(struct repository *r,
4739 struct strvec *argv,
4740 struct diff_filespec *df)
4741 {
4742 struct diff_tempfile *temp = prepare_temp_file(r, df);
4743 strvec_push(argv, temp->name);
4744 strvec_push(argv, temp->hex);
4745 strvec_push(argv, temp->mode);
4746 }
4747
4748 /* An external diff command takes:
4749 *
4750 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4751 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4752 *
4753 */
4754 static void run_external_diff(const struct external_diff *pgm,
4755 const char *name,
4756 const char *other,
4757 struct diff_filespec *one,
4758 struct diff_filespec *two,
4759 const char *xfrm_msg,
4760 struct diff_options *o)
4761 {
4762 struct child_process cmd = CHILD_PROCESS_INIT;
4763 struct diff_queue_struct *q = &diff_queued_diff;
4764 int rc;
4765
4766 /*
4767 * Trivial equality is handled by diff_unmodified_pair() before
4768 * we get here. If we don't need to show the diff and the
4769 * external diff program lacks the ability to tell us whether
4770 * it's empty then we consider it non-empty without even asking.
4771 */
4772 if (!pgm->trust_exit_code && !o->file) {
4773 o->found_changes = 1;
4774 return;
4775 }
4776
4777 strvec_push(&cmd.args, pgm->cmd);
4778 strvec_push(&cmd.args, name);
4779
4780 if (one && two) {
4781 add_external_diff_name(o->repo, &cmd.args, one);
4782 add_external_diff_name(o->repo, &cmd.args, two);
4783 if (other) {
4784 strvec_push(&cmd.args, other);
4785 if (xfrm_msg)
4786 strvec_push(&cmd.args, xfrm_msg);
4787 }
4788 }
4789
4790 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4791 ++o->diff_path_counter);
4792 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4793
4794 diff_free_filespec_data(one);
4795 diff_free_filespec_data(two);
4796 cmd.use_shell = 1;
4797 if (!o->file)
4798 cmd.no_stdout = 1;
4799 else if (o->file != stdout)
4800 cmd.out = xdup(fileno(o->file));
4801 rc = run_command(&cmd);
4802 if (!pgm->trust_exit_code && rc == 0)
4803 o->found_changes = 1;
4804 else if (pgm->trust_exit_code && rc == 0)
4805 ; /* nothing */
4806 else if (pgm->trust_exit_code && rc == 1)
4807 o->found_changes = 1;
4808 else
4809 die(_("external diff died, stopping at %s"), name);
4810
4811 remove_tempfile();
4812 }
4813
4814 static int similarity_index(struct diff_filepair *p)
4815 {
4816 return p->score * 100 / MAX_SCORE;
4817 }
4818
4819 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4820 {
4821 if (startup_info->have_repository)
4822 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4823 else {
4824 char *hex = oid_to_hex(oid);
4825 if (abbrev < 0)
4826 abbrev = FALLBACK_DEFAULT_ABBREV;
4827 if (abbrev > the_hash_algo->hexsz)
4828 BUG("oid abbreviation out of range: %d", abbrev);
4829 if (abbrev)
4830 hex[abbrev] = '\0';
4831 return hex;
4832 }
4833 }
4834
4835 static void fill_metainfo(struct strbuf *msg,
4836 const char *name,
4837 const char *other,
4838 struct diff_filespec *one,
4839 struct diff_filespec *two,
4840 struct diff_options *o,
4841 struct diff_filepair *p,
4842 int *must_show_header,
4843 enum git_colorbool use_color)
4844 {
4845 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4846 const char *reset = diff_get_color(use_color, DIFF_RESET);
4847 const char *line_prefix = diff_line_prefix(o);
4848 struct string_list *more_headers = NULL;
4849
4850 *must_show_header = 1;
4851 strbuf_init(msg, PATH_MAX * 2 + 300);
4852 switch (p->status) {
4853 case DIFF_STATUS_COPIED:
4854 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4855 line_prefix, set, similarity_index(p));
4856 strbuf_addf(msg, "%s\n%s%scopy from ",
4857 reset, line_prefix, set);
4858 quote_c_style(name, msg, NULL, 0);
4859 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4860 quote_c_style(other, msg, NULL, 0);
4861 strbuf_addf(msg, "%s\n", reset);
4862 break;
4863 case DIFF_STATUS_RENAMED:
4864 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4865 line_prefix, set, similarity_index(p));
4866 strbuf_addf(msg, "%s\n%s%srename from ",
4867 reset, line_prefix, set);
4868 quote_c_style(name, msg, NULL, 0);
4869 strbuf_addf(msg, "%s\n%s%srename to ",
4870 reset, line_prefix, set);
4871 quote_c_style(other, msg, NULL, 0);
4872 strbuf_addf(msg, "%s\n", reset);
4873 break;
4874 case DIFF_STATUS_MODIFIED:
4875 if (p->score) {
4876 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4877 line_prefix,
4878 set, similarity_index(p), reset);
4879 break;
4880 }
4881 /* fallthru */
4882 default:
4883 *must_show_header = 0;
4884 }
4885 if ((more_headers = additional_headers(o, name))) {
4886 add_formatted_headers(msg, more_headers,
4887 line_prefix, set, reset);
4888 *must_show_header = 1;
4889 }
4890 if (one && two && !oideq(&one->oid, &two->oid)) {
4891 const unsigned hexsz = the_hash_algo->hexsz;
4892 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4893
4894 if (o->flags.full_index)
4895 abbrev = hexsz;
4896
4897 if (o->flags.binary) {
4898 mmfile_t mf;
4899 if ((!fill_mmfile(o->repo, &mf, one) &&
4900 diff_filespec_is_binary(o->repo, one)) ||
4901 (!fill_mmfile(o->repo, &mf, two) &&
4902 diff_filespec_is_binary(o->repo, two)))
4903 abbrev = hexsz;
4904 }
4905 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4906 diff_abbrev_oid(&one->oid, abbrev),
4907 diff_abbrev_oid(&two->oid, abbrev));
4908 if (one->mode == two->mode)
4909 strbuf_addf(msg, " %06o", one->mode);
4910 strbuf_addf(msg, "%s\n", reset);
4911 }
4912 }
4913
4914 static void run_diff_cmd(const struct external_diff *pgm,
4915 const char *name,
4916 const char *other,
4917 const char *attr_path,
4918 struct diff_filespec *one,
4919 struct diff_filespec *two,
4920 struct strbuf *msg,
4921 struct diff_options *o,
4922 struct diff_filepair *p)
4923 {
4924 const char *xfrm_msg = NULL;
4925 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4926 int must_show_header = 0;
4927 struct userdiff_driver *drv = NULL;
4928
4929 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4930 drv = userdiff_find_by_path(o->repo->index, attr_path);
4931
4932 if (o->flags.allow_external && drv && drv->external.cmd)
4933 pgm = &drv->external;
4934
4935 if (msg) {
4936 /*
4937 * don't use colors when the header is intended for an
4938 * external diff driver
4939 */
4940 fill_metainfo(msg, name, other, one, two, o, p,
4941 &must_show_header,
4942 pgm ? GIT_COLOR_NEVER : o->use_color);
4943 xfrm_msg = msg->len ? msg->buf : NULL;
4944 }
4945
4946 if (pgm) {
4947 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4948 return;
4949 }
4950 if (one && two) {
4951 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4952 set_diff_algorithm(o, drv->algorithm);
4953
4954 builtin_diff(name, other ? other : name,
4955 one, two, xfrm_msg, must_show_header,
4956 o, complete_rewrite, p->line_ranges);
4957 if (p->status == DIFF_STATUS_COPIED ||
4958 p->status == DIFF_STATUS_RENAMED)
4959 o->found_changes = 1;
4960 } else {
4961 if (o->file)
4962 fprintf(o->file, "* Unmerged path %s\n", name);
4963 o->found_changes = 1;
4964 }
4965 }
4966
4967 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4968 {
4969 if (DIFF_FILE_VALID(one)) {
4970 if (!one->oid_valid) {
4971 struct stat st;
4972 if (one->is_stdin) {
4973 oidclr(&one->oid, the_repository->hash_algo);
4974 return;
4975 }
4976 if (lstat(one->path, &st) < 0)
4977 die_errno("stat '%s'", one->path);
4978 if (index_path(istate, &one->oid, one->path, &st, 0))
4979 die("cannot hash %s", one->path);
4980 }
4981 }
4982 else
4983 oidclr(&one->oid, the_repository->hash_algo);
4984 }
4985
4986 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4987 {
4988 /* Strip the prefix but do not molest /dev/null and absolute paths */
4989 if (*namep && !is_absolute_path(*namep)) {
4990 *namep += prefix_length;
4991 if (**namep == '/')
4992 ++*namep;
4993 }
4994 if (*otherp && !is_absolute_path(*otherp)) {
4995 *otherp += prefix_length;
4996 if (**otherp == '/')
4997 ++*otherp;
4998 }
4999 }
5000
5001 static void run_diff(struct diff_filepair *p, struct diff_options *o)
5002 {
5003 const struct external_diff *pgm = external_diff();
5004 struct strbuf msg;
5005 struct diff_filespec *one = p->one;
5006 struct diff_filespec *two = p->two;
5007 const char *name;
5008 const char *other;
5009 const char *attr_path;
5010
5011 name = one->path;
5012 other = (strcmp(name, two->path) ? two->path : NULL);
5013 attr_path = name;
5014 if (o->prefix_length)
5015 strip_prefix(o->prefix_length, &name, &other);
5016
5017 if (!o->flags.allow_external)
5018 pgm = NULL;
5019
5020 if (DIFF_PAIR_UNMERGED(p)) {
5021 run_diff_cmd(pgm, name, NULL, attr_path,
5022 NULL, NULL, NULL, o, p);
5023 return;
5024 }
5025
5026 diff_fill_oid_info(one, o->repo->index);
5027 diff_fill_oid_info(two, o->repo->index);
5028
5029 if (!pgm &&
5030 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
5031 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
5032 /*
5033 * a filepair that changes between file and symlink
5034 * needs to be split into deletion and creation.
5035 */
5036 struct diff_filespec *null = alloc_filespec(two->path);
5037 run_diff_cmd(NULL, name, other, attr_path,
5038 one, null, &msg,
5039 o, p);
5040 free(null);
5041 strbuf_release(&msg);
5042
5043 null = alloc_filespec(one->path);
5044 run_diff_cmd(NULL, name, other, attr_path,
5045 null, two, &msg, o, p);
5046 free(null);
5047 }
5048 else
5049 run_diff_cmd(pgm, name, other, attr_path,
5050 one, two, &msg, o, p);
5051
5052 strbuf_release(&msg);
5053 }
5054
5055 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
5056 struct diffstat_t *diffstat)
5057 {
5058 const char *name;
5059 const char *other;
5060
5061 if (!o->ignore_driver_algorithm) {
5062 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
5063 p->one->path);
5064
5065 if (drv && drv->algorithm)
5066 set_diff_algorithm(o, drv->algorithm);
5067 }
5068
5069 if (DIFF_PAIR_UNMERGED(p)) {
5070 /* unmerged */
5071 builtin_diffstat(p->one->path, NULL, NULL, NULL,
5072 diffstat, o, p);
5073 return;
5074 }
5075
5076 name = p->one->path;
5077 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
5078
5079 if (o->prefix_length)
5080 strip_prefix(o->prefix_length, &name, &other);
5081
5082 diff_fill_oid_info(p->one, o->repo->index);
5083 diff_fill_oid_info(p->two, o->repo->index);
5084
5085 builtin_diffstat(name, other, p->one, p->two,
5086 diffstat, o, p);
5087 }
5088
5089 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
5090 {
5091 const char *name;
5092 const char *other;
5093 const char *attr_path;
5094
5095 if (DIFF_PAIR_UNMERGED(p)) {
5096 /* unmerged */
5097 return;
5098 }
5099
5100 name = p->one->path;
5101 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
5102 attr_path = other ? other : name;
5103
5104 if (o->prefix_length)
5105 strip_prefix(o->prefix_length, &name, &other);
5106
5107 diff_fill_oid_info(p->one, o->repo->index);
5108 diff_fill_oid_info(p->two, o->repo->index);
5109
5110 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
5111 }
5112
5113 void repo_diff_setup(struct repository *r, struct diff_options *options)
5114 {
5115 memcpy(options, &default_diff_options, sizeof(*options));
5116
5117 options->file = stdout;
5118 options->repo = r;
5119
5120 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
5121 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
5122 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
5123 options->abbrev = DEFAULT_ABBREV;
5124 options->line_termination = '\n';
5125 options->break_opt = -1;
5126 options->rename_limit = -1;
5127 options->dirstat_permille = diff_dirstat_permille_default;
5128 options->context = diff_context_default;
5129 options->interhunkcontext = diff_interhunk_context_default;
5130 options->ws_error_highlight = ws_error_highlight_default;
5131 options->flags.rename_empty = 1;
5132 options->flags.relative_name = diff_relative;
5133 options->objfind = NULL;
5134
5135 /* pathchange left =NULL by default */
5136 options->change = diff_change;
5137 options->add_remove = diff_addremove;
5138 options->use_color = diff_use_color_default;
5139 options->detect_rename = diff_detect_rename_default;
5140 options->xdl_opts |= diff_algorithm;
5141 if (diff_indent_heuristic)
5142 DIFF_XDL_SET(options, INDENT_HEURISTIC);
5143
5144 options->orderfile = xstrdup_or_null(diff_order_file_cfg);
5145
5146 if (!options->flags.ignore_submodule_set)
5147 options->flags.ignore_untracked_in_submodules = 1;
5148
5149 if (diff_no_prefix) {
5150 diff_set_noprefix(options);
5151 } else if (!diff_mnemonic_prefix) {
5152 diff_set_default_prefix(options);
5153 }
5154
5155 options->color_moved = diff_color_moved_default;
5156 options->color_moved_ws_handling = diff_color_moved_ws_default;
5157 }
5158
5159 static const char diff_status_letters[] = {
5160 DIFF_STATUS_ADDED,
5161 DIFF_STATUS_COPIED,
5162 DIFF_STATUS_DELETED,
5163 DIFF_STATUS_MODIFIED,
5164 DIFF_STATUS_RENAMED,
5165 DIFF_STATUS_TYPE_CHANGED,
5166 DIFF_STATUS_UNKNOWN,
5167 DIFF_STATUS_UNMERGED,
5168 DIFF_STATUS_FILTER_AON,
5169 DIFF_STATUS_FILTER_BROKEN,
5170 '\0',
5171 };
5172
5173 static unsigned int filter_bit['Z' + 1];
5174
5175 static void prepare_filter_bits(void)
5176 {
5177 int i;
5178
5179 if (!filter_bit[DIFF_STATUS_ADDED]) {
5180 for (i = 0; diff_status_letters[i]; i++)
5181 filter_bit[(int) diff_status_letters[i]] = (1 << i);
5182 }
5183 }
5184
5185 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
5186 {
5187 return opt->filter & filter_bit[(int) status];
5188 }
5189
5190 unsigned diff_filter_bit(char status)
5191 {
5192 prepare_filter_bits();
5193 return filter_bit[(int) status];
5194 }
5195
5196 int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
5197 {
5198 unsigned forbidden_magic;
5199
5200 if (ps->nr != 1) {
5201 if (die_on_error)
5202 die(_("--follow requires exactly one pathspec"));
5203 return 0;
5204 }
5205
5206 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
5207 PATHSPEC_LITERAL);
5208 if (forbidden_magic) {
5209 if (die_on_error) {
5210 struct strbuf sb = STRBUF_INIT;
5211 pathspec_magic_names(forbidden_magic, &sb);
5212 die(_("pathspec magic not supported by --follow: %s"),
5213 sb.buf);
5214 }
5215 return 0;
5216 }
5217
5218 return 1;
5219 }
5220
5221 void diff_setup_done(struct diff_options *options)
5222 {
5223 unsigned check_mask = DIFF_FORMAT_NAME |
5224 DIFF_FORMAT_NAME_STATUS |
5225 DIFF_FORMAT_CHECKDIFF |
5226 DIFF_FORMAT_NO_OUTPUT;
5227 /*
5228 * This must be signed because we're comparing against a potentially
5229 * negative value.
5230 */
5231 const int hexsz = the_hash_algo->hexsz;
5232
5233 if (options->set_default)
5234 options->set_default(options);
5235
5236 if (HAS_MULTI_BITS(options->output_format & check_mask))
5237 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
5238 "--name-only", "--name-status", "--check", "-s");
5239
5240 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
5241 die(_("options '%s', '%s', and '%s' cannot be used together"),
5242 "-G", "-S", "--find-object");
5243
5244 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
5245 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
5246 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
5247
5248 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
5249 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
5250 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
5251
5252 /*
5253 * Most of the time we can say "there are changes"
5254 * only by checking if there are changed paths, but
5255 * --ignore-whitespace* options force us to look
5256 * inside contents.
5257 */
5258
5259 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
5260 options->ignore_regex_nr)
5261 options->flags.diff_from_contents = 1;
5262 else
5263 options->flags.diff_from_contents = 0;
5264
5265 if (options->flags.find_copies_harder)
5266 options->detect_rename = DIFF_DETECT_COPY;
5267
5268 if (!options->flags.relative_name)
5269 options->prefix = NULL;
5270 if (options->prefix)
5271 options->prefix_length = strlen(options->prefix);
5272 else
5273 options->prefix_length = 0;
5274
5275 /*
5276 * --name-only, --name-status, --checkdiff, and -s
5277 * turn other output format off.
5278 */
5279 if (options->output_format & (DIFF_FORMAT_NAME |
5280 DIFF_FORMAT_NAME_STATUS |
5281 DIFF_FORMAT_CHECKDIFF |
5282 DIFF_FORMAT_NO_OUTPUT))
5283 options->output_format &= ~(DIFF_FORMAT_RAW |
5284 DIFF_FORMAT_NUMSTAT |
5285 DIFF_FORMAT_DIFFSTAT |
5286 DIFF_FORMAT_SHORTSTAT |
5287 DIFF_FORMAT_DIRSTAT |
5288 DIFF_FORMAT_SUMMARY |
5289 DIFF_FORMAT_PATCH);
5290
5291 /*
5292 * These cases always need recursive; we do not drop caller-supplied
5293 * recursive bits for other formats here.
5294 */
5295 if (options->output_format & (DIFF_FORMAT_PATCH |
5296 DIFF_FORMAT_NUMSTAT |
5297 DIFF_FORMAT_DIFFSTAT |
5298 DIFF_FORMAT_SHORTSTAT |
5299 DIFF_FORMAT_DIRSTAT |
5300 DIFF_FORMAT_SUMMARY |
5301 DIFF_FORMAT_CHECKDIFF))
5302 options->flags.recursive = 1;
5303 /*
5304 * Also pickaxe would not work very well if you do not say recursive
5305 */
5306 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
5307 options->flags.recursive = 1;
5308 /*
5309 * When patches are generated, submodules diffed against the work tree
5310 * must be checked for dirtiness too so it can be shown in the output
5311 */
5312 if (options->output_format & DIFF_FORMAT_PATCH)
5313 options->flags.dirty_submodules = 1;
5314
5315 if (options->detect_rename && options->rename_limit < 0)
5316 options->rename_limit = diff_rename_limit_default;
5317 if (hexsz < options->abbrev)
5318 options->abbrev = hexsz; /* full */
5319
5320 /*
5321 * It does not make sense to show the first hit we happened
5322 * to have found. It does not make sense not to return with
5323 * exit code in such a case either.
5324 */
5325 if (options->flags.quick) {
5326 options->output_format = DIFF_FORMAT_NO_OUTPUT;
5327 options->flags.exit_with_status = 1;
5328 options->detect_rename = 0;
5329 options->flags.find_copies_harder = 0;
5330 }
5331
5332 /*
5333 * External diffs could declare non-identical contents equal
5334 * (think diff --ignore-space-change).
5335 */
5336 if (options->flags.allow_external && options->flags.exit_with_status)
5337 options->flags.diff_from_contents = 1;
5338
5339 options->diff_path_counter = 0;
5340
5341 if (options->flags.follow_renames)
5342 diff_check_follow_pathspec(&options->pathspec, 1);
5343
5344 if (options->flags.allow_external && external_diff())
5345 options->color_moved = 0;
5346
5347 if (options->filter_not) {
5348 if (!options->filter)
5349 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
5350 options->filter &= ~options->filter_not;
5351 }
5352
5353 if (options->pathspec.has_wildcard && options->max_depth_valid)
5354 die("max-depth cannot be used with wildcard pathspecs");
5355 }
5356
5357 int parse_long_opt(const char *opt, const char **argv,
5358 const char **optarg)
5359 {
5360 const char *arg = argv[0];
5361 if (!skip_prefix(arg, "--", &arg))
5362 return 0;
5363 if (!skip_prefix(arg, opt, &arg))
5364 return 0;
5365 if (*arg == '=') { /* stuck form: --option=value */
5366 *optarg = arg + 1;
5367 return 1;
5368 }
5369 if (*arg != '\0')
5370 return 0;
5371 /* separate form: --option value */
5372 if (!argv[1])
5373 die("Option '--%s' requires a value", opt);
5374 *optarg = argv[1];
5375 return 2;
5376 }
5377
5378 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
5379 {
5380 struct diff_options *options = opt->value;
5381 int width = options->stat_width;
5382 int name_width = options->stat_name_width;
5383 int graph_width = options->stat_graph_width;
5384 int count = options->stat_count;
5385 char *end;
5386
5387 BUG_ON_OPT_NEG(unset);
5388
5389 if (!strcmp(opt->long_name, "stat")) {
5390 if (value) {
5391 width = strtoul(value, &end, 10);
5392 if (*end == ',')
5393 name_width = strtoul(end+1, &end, 10);
5394 if (*end == ',')
5395 count = strtoul(end+1, &end, 10);
5396 if (*end)
5397 return error(_("invalid --stat value: %s"), value);
5398 }
5399 } else if (!strcmp(opt->long_name, "stat-width")) {
5400 width = strtoul(value, &end, 10);
5401 if (*end)
5402 return error(_("%s expects a numerical value"),
5403 opt->long_name);
5404 } else if (!strcmp(opt->long_name, "stat-name-width")) {
5405 name_width = strtoul(value, &end, 10);
5406 if (*end)
5407 return error(_("%s expects a numerical value"),
5408 opt->long_name);
5409 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
5410 graph_width = strtoul(value, &end, 10);
5411 if (*end)
5412 return error(_("%s expects a numerical value"),
5413 opt->long_name);
5414 } else if (!strcmp(opt->long_name, "stat-count")) {
5415 count = strtoul(value, &end, 10);
5416 if (*end)
5417 return error(_("%s expects a numerical value"),
5418 opt->long_name);
5419 } else
5420 BUG("%s should not get here", opt->long_name);
5421
5422 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5423 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5424 options->stat_name_width = name_width;
5425 options->stat_graph_width = graph_width;
5426 options->stat_width = width;
5427 options->stat_count = count;
5428 return 0;
5429 }
5430
5431 static int parse_dirstat_opt(struct diff_options *options, const char *params)
5432 {
5433 struct strbuf errmsg = STRBUF_INIT;
5434 if (parse_dirstat_params(options, params, &errmsg))
5435 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
5436 errmsg.buf);
5437 strbuf_release(&errmsg);
5438 /*
5439 * The caller knows a dirstat-related option is given from the command
5440 * line; allow it to say "return this_function();"
5441 */
5442 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5443 options->output_format |= DIFF_FORMAT_DIRSTAT;
5444 return 1;
5445 }
5446
5447 static int diff_opt_diff_filter(const struct option *option,
5448 const char *optarg, int unset)
5449 {
5450 struct diff_options *opt = option->value;
5451 int i, optch;
5452
5453 BUG_ON_OPT_NEG(unset);
5454 prepare_filter_bits();
5455
5456 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5457 unsigned int bit;
5458 int negate;
5459
5460 if ('a' <= optch && optch <= 'z') {
5461 negate = 1;
5462 optch = toupper(optch);
5463 } else {
5464 negate = 0;
5465 }
5466
5467 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5468 if (!bit)
5469 return error(_("unknown change class '%c' in --diff-filter=%s"),
5470 optarg[i], optarg);
5471 if (negate)
5472 opt->filter_not |= bit;
5473 else
5474 opt->filter |= bit;
5475 }
5476 return 0;
5477 }
5478
5479 static void enable_patch_output(int *fmt)
5480 {
5481 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5482 *fmt |= DIFF_FORMAT_PATCH;
5483 }
5484
5485 static int diff_opt_ws_error_highlight(const struct option *option,
5486 const char *arg, int unset)
5487 {
5488 struct diff_options *opt = option->value;
5489 int val = parse_ws_error_highlight(arg);
5490
5491 BUG_ON_OPT_NEG(unset);
5492 if (val < 0)
5493 return error(_("unknown value after ws-error-highlight=%.*s"),
5494 -1 - val, arg);
5495 opt->ws_error_highlight = val;
5496 return 0;
5497 }
5498
5499 static int diff_opt_find_object(const struct option *option,
5500 const char *arg, int unset)
5501 {
5502 struct diff_options *opt = option->value;
5503 struct object_id oid;
5504
5505 BUG_ON_OPT_NEG(unset);
5506 if (!startup_info->have_repository)
5507 return error(_("--find-object requires a git repository"));
5508 if (repo_get_oid(the_repository, arg, &oid))
5509 return error(_("unable to resolve '%s'"), arg);
5510
5511 if (!opt->objfind)
5512 CALLOC_ARRAY(opt->objfind, 1);
5513
5514 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5515 opt->flags.recursive = 1;
5516 opt->flags.tree_in_recursive = 1;
5517 oidset_insert(opt->objfind, &oid);
5518 return 0;
5519 }
5520
5521 static int diff_opt_anchored(const struct option *opt,
5522 const char *arg, int unset)
5523 {
5524 struct diff_options *options = opt->value;
5525
5526 BUG_ON_OPT_NEG(unset);
5527 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5528 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5529 options->anchors_alloc);
5530 options->anchors[options->anchors_nr++] = xstrdup(arg);
5531 return 0;
5532 }
5533
5534 static int diff_opt_binary(const struct option *opt,
5535 const char *arg, int unset)
5536 {
5537 struct diff_options *options = opt->value;
5538
5539 BUG_ON_OPT_NEG(unset);
5540 BUG_ON_OPT_ARG(arg);
5541 enable_patch_output(&options->output_format);
5542 options->flags.binary = 1;
5543 return 0;
5544 }
5545
5546 static int diff_opt_break_rewrites(const struct option *opt,
5547 const char *arg, int unset)
5548 {
5549 int *break_opt = opt->value;
5550 int opt1, opt2;
5551
5552 BUG_ON_OPT_NEG(unset);
5553 if (!arg)
5554 arg = "";
5555 opt1 = parse_rename_score(&arg);
5556 if (*arg == 0)
5557 opt2 = 0;
5558 else if (*arg != '/')
5559 return error(_("%s expects <n>/<m> form"), opt->long_name);
5560 else {
5561 arg++;
5562 opt2 = parse_rename_score(&arg);
5563 }
5564 if (*arg != 0)
5565 return error(_("%s expects <n>/<m> form"), opt->long_name);
5566 *break_opt = opt1 | (opt2 << 16);
5567 return 0;
5568 }
5569
5570 static int diff_opt_char(const struct option *opt,
5571 const char *arg, int unset)
5572 {
5573 char *value = opt->value;
5574
5575 BUG_ON_OPT_NEG(unset);
5576 if (arg[1])
5577 return error(_("%s expects a character, got '%s'"),
5578 opt->long_name, arg);
5579 *value = arg[0];
5580 return 0;
5581 }
5582
5583 static int diff_opt_color_moved(const struct option *opt,
5584 const char *arg, int unset)
5585 {
5586 struct diff_options *options = opt->value;
5587
5588 if (unset) {
5589 options->color_moved = COLOR_MOVED_NO;
5590 } else if (!arg) {
5591 if (diff_color_moved_default)
5592 options->color_moved = diff_color_moved_default;
5593 if (options->color_moved == COLOR_MOVED_NO)
5594 options->color_moved = COLOR_MOVED_DEFAULT;
5595 } else {
5596 int cm = parse_color_moved(arg);
5597 if (cm < 0)
5598 return error(_("bad --color-moved argument: %s"), arg);
5599 options->color_moved = cm;
5600 }
5601 return 0;
5602 }
5603
5604 static int diff_opt_color_moved_ws(const struct option *opt,
5605 const char *arg, int unset)
5606 {
5607 struct diff_options *options = opt->value;
5608 unsigned cm;
5609
5610 if (unset) {
5611 options->color_moved_ws_handling = 0;
5612 return 0;
5613 }
5614
5615 cm = parse_color_moved_ws(arg);
5616 if (cm & COLOR_MOVED_WS_ERROR)
5617 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5618 options->color_moved_ws_handling = cm;
5619 return 0;
5620 }
5621
5622 static int diff_opt_color_words(const struct option *opt,
5623 const char *arg, int unset)
5624 {
5625 struct diff_options *options = opt->value;
5626
5627 BUG_ON_OPT_NEG(unset);
5628 options->use_color = GIT_COLOR_ALWAYS;
5629 options->word_diff = DIFF_WORDS_COLOR;
5630 options->word_regex = arg;
5631 return 0;
5632 }
5633
5634 static int diff_opt_compact_summary(const struct option *opt,
5635 const char *arg, int unset)
5636 {
5637 struct diff_options *options = opt->value;
5638
5639 BUG_ON_OPT_ARG(arg);
5640 if (unset) {
5641 options->flags.stat_with_summary = 0;
5642 } else {
5643 options->flags.stat_with_summary = 1;
5644 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5645 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5646 }
5647 return 0;
5648 }
5649
5650 static int diff_opt_diff_algorithm(const struct option *opt,
5651 const char *arg, int unset)
5652 {
5653 struct diff_options *options = opt->value;
5654
5655 BUG_ON_OPT_NEG(unset);
5656
5657 if (set_diff_algorithm(options, arg))
5658 return error(_("option diff-algorithm accepts \"myers\", "
5659 "\"minimal\", \"patience\" and \"histogram\""));
5660
5661 options->ignore_driver_algorithm = 1;
5662
5663 return 0;
5664 }
5665
5666 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5667 const char *arg, int unset)
5668 {
5669 struct diff_options *options = opt->value;
5670
5671 BUG_ON_OPT_NEG(unset);
5672 BUG_ON_OPT_ARG(arg);
5673
5674 if (set_diff_algorithm(options, opt->long_name))
5675 BUG("available diff algorithms include \"myers\", "
5676 "\"minimal\", \"patience\" and \"histogram\"");
5677
5678 options->ignore_driver_algorithm = 1;
5679
5680 return 0;
5681 }
5682
5683 static int diff_opt_dirstat(const struct option *opt,
5684 const char *arg, int unset)
5685 {
5686 struct diff_options *options = opt->value;
5687
5688 BUG_ON_OPT_NEG(unset);
5689 if (!strcmp(opt->long_name, "cumulative")) {
5690 if (arg)
5691 BUG("how come --cumulative take a value?");
5692 arg = "cumulative";
5693 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5694 parse_dirstat_opt(options, "files");
5695 parse_dirstat_opt(options, arg ? arg : "");
5696 return 0;
5697 }
5698
5699 static int diff_opt_find_copies(const struct option *opt,
5700 const char *arg, int unset)
5701 {
5702 struct diff_options *options = opt->value;
5703
5704 BUG_ON_OPT_NEG(unset);
5705 if (!arg)
5706 arg = "";
5707 options->rename_score = parse_rename_score(&arg);
5708 if (*arg != 0)
5709 return error(_("invalid argument to %s"), opt->long_name);
5710
5711 if (options->detect_rename == DIFF_DETECT_COPY)
5712 options->flags.find_copies_harder = 1;
5713 else
5714 options->detect_rename = DIFF_DETECT_COPY;
5715
5716 return 0;
5717 }
5718
5719 static int diff_opt_find_renames(const struct option *opt,
5720 const char *arg, int unset)
5721 {
5722 struct diff_options *options = opt->value;
5723
5724 BUG_ON_OPT_NEG(unset);
5725 if (!arg)
5726 arg = "";
5727 options->rename_score = parse_rename_score(&arg);
5728 if (*arg != 0)
5729 return error(_("invalid argument to %s"), opt->long_name);
5730
5731 options->detect_rename = DIFF_DETECT_RENAME;
5732 return 0;
5733 }
5734
5735 static int diff_opt_follow(const struct option *opt,
5736 const char *arg, int unset)
5737 {
5738 struct diff_options *options = opt->value;
5739
5740 BUG_ON_OPT_ARG(arg);
5741 if (unset) {
5742 options->flags.follow_renames = 0;
5743 options->flags.default_follow_renames = 0;
5744 } else {
5745 options->flags.follow_renames = 1;
5746 }
5747 return 0;
5748 }
5749
5750 static int diff_opt_ignore_submodules(const struct option *opt,
5751 const char *arg, int unset)
5752 {
5753 struct diff_options *options = opt->value;
5754
5755 BUG_ON_OPT_NEG(unset);
5756 if (!arg)
5757 arg = "all";
5758 options->flags.override_submodule_config = 1;
5759 handle_ignore_submodules_arg(options, arg);
5760 return 0;
5761 }
5762
5763 static int diff_opt_line_prefix(const struct option *opt,
5764 const char *optarg, int unset)
5765 {
5766 struct diff_options *options = opt->value;
5767
5768 BUG_ON_OPT_NEG(unset);
5769 options->line_prefix = optarg;
5770 graph_setup_line_prefix(options);
5771 return 0;
5772 }
5773
5774 static int diff_opt_no_prefix(const struct option *opt,
5775 const char *optarg, int unset)
5776 {
5777 struct diff_options *options = opt->value;
5778
5779 BUG_ON_OPT_NEG(unset);
5780 BUG_ON_OPT_ARG(optarg);
5781 diff_set_noprefix(options);
5782 return 0;
5783 }
5784
5785 static int diff_opt_default_prefix(const struct option *opt,
5786 const char *optarg, int unset)
5787 {
5788 struct diff_options *options = opt->value;
5789
5790 BUG_ON_OPT_NEG(unset);
5791 BUG_ON_OPT_ARG(optarg);
5792 FREE_AND_NULL(diff_src_prefix);
5793 FREE_AND_NULL(diff_dst_prefix);
5794 diff_set_default_prefix(options);
5795 return 0;
5796 }
5797
5798 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5799 const struct option *opt,
5800 const char *arg, int unset)
5801 {
5802 struct diff_options *options = opt->value;
5803 char *path;
5804
5805 BUG_ON_OPT_NEG(unset);
5806 path = prefix_filename(ctx->prefix, arg);
5807 options->file = xfopen(path, "w");
5808 options->close_file = 1;
5809 if (options->use_color != GIT_COLOR_ALWAYS)
5810 options->use_color = GIT_COLOR_NEVER;
5811 free(path);
5812 return 0;
5813 }
5814
5815 static int diff_opt_patience(const struct option *opt,
5816 const char *arg, int unset)
5817 {
5818 struct diff_options *options = opt->value;
5819 int i;
5820
5821 BUG_ON_OPT_NEG(unset);
5822 BUG_ON_OPT_ARG(arg);
5823 /*
5824 * Both --patience and --anchored use PATIENCE_DIFF
5825 * internally, so remove any anchors previously
5826 * specified.
5827 */
5828 for (i = 0; i < options->anchors_nr; i++)
5829 free(options->anchors[i]);
5830 options->anchors_nr = 0;
5831 options->ignore_driver_algorithm = 1;
5832
5833 return set_diff_algorithm(options, "patience");
5834 }
5835
5836 static int diff_opt_ignore_regex(const struct option *opt,
5837 const char *arg, int unset)
5838 {
5839 struct diff_options *options = opt->value;
5840 regex_t *regex;
5841
5842 BUG_ON_OPT_NEG(unset);
5843
5844 regex = xmalloc(sizeof(*regex));
5845 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE)) {
5846 free(regex);
5847 return error(_("invalid regex given to -I: '%s'"), arg);
5848 }
5849
5850 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5851 options->ignore_regex_alloc);
5852 options->ignore_regex[options->ignore_regex_nr++] = regex;
5853 return 0;
5854 }
5855
5856 static int diff_opt_pickaxe_regex(const struct option *opt,
5857 const char *arg, int unset)
5858 {
5859 struct diff_options *options = opt->value;
5860
5861 BUG_ON_OPT_NEG(unset);
5862 options->pickaxe = arg;
5863 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5864 if (arg && !*arg)
5865 return error(_("-G requires a non-empty argument"));
5866 return 0;
5867 }
5868
5869 static int diff_opt_pickaxe_string(const struct option *opt,
5870 const char *arg, int unset)
5871 {
5872 struct diff_options *options = opt->value;
5873
5874 BUG_ON_OPT_NEG(unset);
5875 options->pickaxe = arg;
5876 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5877 if (arg && !*arg)
5878 return error(_("-S requires a non-empty argument"));
5879 return 0;
5880 }
5881
5882 static int diff_opt_relative(const struct option *opt,
5883 const char *arg, int unset)
5884 {
5885 struct diff_options *options = opt->value;
5886
5887 options->flags.relative_name = !unset;
5888 if (arg)
5889 options->prefix = arg;
5890 return 0;
5891 }
5892
5893 static int diff_opt_submodule(const struct option *opt,
5894 const char *arg, int unset)
5895 {
5896 struct diff_options *options = opt->value;
5897
5898 BUG_ON_OPT_NEG(unset);
5899 if (!arg)
5900 arg = "log";
5901 if (parse_submodule_params(options, arg))
5902 return error(_("failed to parse --submodule option parameter: '%s'"),
5903 arg);
5904 return 0;
5905 }
5906
5907 static int diff_opt_textconv(const struct option *opt,
5908 const char *arg, int unset)
5909 {
5910 struct diff_options *options = opt->value;
5911
5912 BUG_ON_OPT_ARG(arg);
5913 if (unset) {
5914 options->flags.allow_textconv = 0;
5915 } else {
5916 options->flags.allow_textconv = 1;
5917 options->flags.textconv_set_via_cmdline = 1;
5918 }
5919 return 0;
5920 }
5921
5922 static int diff_opt_unified(const struct option *opt,
5923 const char *arg, int unset)
5924 {
5925 struct diff_options *options = opt->value;
5926 char *s;
5927
5928 BUG_ON_OPT_NEG(unset);
5929
5930 if (arg) {
5931 long val = strtol(arg, &s, 10);
5932 if (*s)
5933 return error(_("%s expects a numerical value"), "--unified");
5934 if (val < 0)
5935 return error(_("%s expects a non-negative integer"), "--unified");
5936 options->context = val;
5937 }
5938 enable_patch_output(&options->output_format);
5939
5940 return 0;
5941 }
5942
5943 static int diff_opt_word_diff(const struct option *opt,
5944 const char *arg, int unset)
5945 {
5946 struct diff_options *options = opt->value;
5947
5948 BUG_ON_OPT_NEG(unset);
5949 if (arg) {
5950 if (!strcmp(arg, "plain"))
5951 options->word_diff = DIFF_WORDS_PLAIN;
5952 else if (!strcmp(arg, "color")) {
5953 options->use_color = GIT_COLOR_ALWAYS;
5954 options->word_diff = DIFF_WORDS_COLOR;
5955 }
5956 else if (!strcmp(arg, "porcelain"))
5957 options->word_diff = DIFF_WORDS_PORCELAIN;
5958 else if (!strcmp(arg, "none"))
5959 options->word_diff = DIFF_WORDS_NONE;
5960 else
5961 return error(_("bad --word-diff argument: %s"), arg);
5962 } else {
5963 if (options->word_diff == DIFF_WORDS_NONE)
5964 options->word_diff = DIFF_WORDS_PLAIN;
5965 }
5966 return 0;
5967 }
5968
5969 static int diff_opt_word_diff_regex(const struct option *opt,
5970 const char *arg, int unset)
5971 {
5972 struct diff_options *options = opt->value;
5973
5974 BUG_ON_OPT_NEG(unset);
5975 if (options->word_diff == DIFF_WORDS_NONE)
5976 options->word_diff = DIFF_WORDS_PLAIN;
5977 options->word_regex = arg;
5978 return 0;
5979 }
5980
5981 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5982 {
5983 struct diff_options *options = opt->value;
5984
5985 BUG_ON_OPT_NEG(unset);
5986 if (!strcmp(opt->long_name, "skip-to"))
5987 options->skip_instead_of_rotate = 1;
5988 else
5989 options->skip_instead_of_rotate = 0;
5990 options->rotate_to = arg;
5991 return 0;
5992 }
5993
5994 static int diff_opt_max_depth(const struct option *opt,
5995 const char *arg, int unset)
5996 {
5997 struct diff_options *options = opt->value;
5998
5999 BUG_ON_OPT_NEG(unset);
6000
6001 if (!git_parse_int(arg, &options->max_depth))
6002 return error(_("invalid value for '%s': '%s'"),
6003 "--max-depth", arg);
6004
6005 options->flags.recursive = 1;
6006 options->max_depth_valid = options->max_depth >= 0;
6007
6008 return 0;
6009 }
6010
6011 /*
6012 * Consider adding new flags to __git_diff_common_options
6013 * in contrib/completion/git-completion.bash
6014 */
6015 struct option *add_diff_options(const struct option *opts,
6016 struct diff_options *options)
6017 {
6018 struct option parseopts[] = {
6019 OPT_GROUP(N_("Diff output format options")),
6020 OPT_BITOP('p', "patch", &options->output_format,
6021 N_("generate patch"),
6022 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
6023 OPT_SET_INT('s', "no-patch", &options->output_format,
6024 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
6025 OPT_BITOP('u', NULL, &options->output_format,
6026 N_("generate patch"),
6027 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
6028 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
6029 N_("generate diffs with <n> lines context"),
6030 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
6031 OPT_BOOL('W', "function-context", &options->flags.funccontext,
6032 N_("generate diffs with <n> lines context")),
6033 OPT_BITOP(0, "raw", &options->output_format,
6034 N_("generate the diff in raw format"),
6035 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
6036 OPT_BITOP(0, "patch-with-raw", &options->output_format,
6037 N_("synonym for '-p --raw'"),
6038 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
6039 DIFF_FORMAT_NO_OUTPUT),
6040 OPT_BITOP(0, "patch-with-stat", &options->output_format,
6041 N_("synonym for '-p --stat'"),
6042 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
6043 DIFF_FORMAT_NO_OUTPUT),
6044 OPT_BITOP(0, "numstat", &options->output_format,
6045 N_("machine friendly --stat"),
6046 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
6047 OPT_BITOP(0, "shortstat", &options->output_format,
6048 N_("output only the last line of --stat"),
6049 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
6050 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1>,<param2>..."),
6051 N_("output the distribution of relative amount of changes for each sub-directory"),
6052 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6053 diff_opt_dirstat),
6054 OPT_CALLBACK_F(0, "cumulative", options, NULL,
6055 N_("synonym for --dirstat=cumulative"),
6056 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6057 diff_opt_dirstat),
6058 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1>,<param2>..."),
6059 N_("synonym for --dirstat=files,<param1>,<param2>..."),
6060 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6061 diff_opt_dirstat),
6062 OPT_BIT_F(0, "check", &options->output_format,
6063 N_("warn if changes introduce conflict markers or whitespace errors"),
6064 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
6065 OPT_BITOP(0, "summary", &options->output_format,
6066 N_("condensed summary such as creations, renames and mode changes"),
6067 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
6068 OPT_BIT_F(0, "name-only", &options->output_format,
6069 N_("show only names of changed files"),
6070 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
6071 OPT_BIT_F(0, "name-status", &options->output_format,
6072 N_("show only names and status of changed files"),
6073 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
6074 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
6075 N_("generate diffstat"),
6076 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
6077 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
6078 N_("generate diffstat with a given width"),
6079 PARSE_OPT_NONEG, diff_opt_stat),
6080 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
6081 N_("generate diffstat with a given name width"),
6082 PARSE_OPT_NONEG, diff_opt_stat),
6083 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
6084 N_("generate diffstat with a given graph width"),
6085 PARSE_OPT_NONEG, diff_opt_stat),
6086 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
6087 N_("generate diffstat with limited lines"),
6088 PARSE_OPT_NONEG, diff_opt_stat),
6089 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
6090 N_("generate compact summary in diffstat"),
6091 PARSE_OPT_NOARG, diff_opt_compact_summary),
6092 OPT_CALLBACK_F(0, "binary", options, NULL,
6093 N_("output a binary diff that can be applied"),
6094 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
6095 OPT_BOOL(0, "full-index", &options->flags.full_index,
6096 N_("show full pre- and post-image object names on the \"index\" lines")),
6097 OPT_COLOR_FLAG(0, "color", &options->use_color,
6098 N_("show colored diff")),
6099 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
6100 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
6101 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
6102 OPT_SET_INT('z', NULL, &options->line_termination,
6103 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
6104 0),
6105 OPT__ABBREV(&options->abbrev),
6106 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
6107 N_("show the given source prefix instead of \"a/\""),
6108 PARSE_OPT_NONEG),
6109 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
6110 N_("show the given destination prefix instead of \"b/\""),
6111 PARSE_OPT_NONEG),
6112 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
6113 N_("prepend an additional prefix to every line of output"),
6114 PARSE_OPT_NONEG, diff_opt_line_prefix),
6115 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
6116 N_("do not show any source or destination prefix"),
6117 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
6118 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
6119 N_("use default prefixes a/ and b/"),
6120 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
6121 OPT_UNSIGNED(0, "inter-hunk-context", &options->interhunkcontext,
6122 N_("show context between diff hunks up to the specified number of lines")),
6123 OPT_CALLBACK_F(0, "output-indicator-new",
6124 &options->output_indicators[OUTPUT_INDICATOR_NEW],
6125 N_("<char>"),
6126 N_("specify the character to indicate a new line instead of '+'"),
6127 PARSE_OPT_NONEG, diff_opt_char),
6128 OPT_CALLBACK_F(0, "output-indicator-old",
6129 &options->output_indicators[OUTPUT_INDICATOR_OLD],
6130 N_("<char>"),
6131 N_("specify the character to indicate an old line instead of '-'"),
6132 PARSE_OPT_NONEG, diff_opt_char),
6133 OPT_CALLBACK_F(0, "output-indicator-context",
6134 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
6135 N_("<char>"),
6136 N_("specify the character to indicate a context instead of ' '"),
6137 PARSE_OPT_NONEG, diff_opt_char),
6138
6139 OPT_GROUP(N_("Diff rename options")),
6140 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
6141 N_("break complete rewrite changes into pairs of delete and create"),
6142 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6143 diff_opt_break_rewrites),
6144 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
6145 N_("detect renames"),
6146 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6147 diff_opt_find_renames),
6148 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
6149 N_("omit the preimage for deletes"),
6150 1, PARSE_OPT_NONEG),
6151 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
6152 N_("detect copies"),
6153 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6154 diff_opt_find_copies),
6155 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
6156 N_("use unmodified files as source to find copies")),
6157 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
6158 N_("disable rename detection"),
6159 0, PARSE_OPT_NONEG),
6160 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
6161 N_("use empty blobs as rename source")),
6162 OPT_CALLBACK_F(0, "follow", options, NULL,
6163 N_("continue listing the history of a file beyond renames"),
6164 PARSE_OPT_NOARG, diff_opt_follow),
6165 OPT_INTEGER('l', NULL, &options->rename_limit,
6166 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
6167
6168 OPT_GROUP(N_("Diff algorithm options")),
6169 OPT_CALLBACK_F(0, "minimal", options, NULL,
6170 N_("produce the smallest possible diff"),
6171 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6172 diff_opt_diff_algorithm_no_arg),
6173 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
6174 N_("ignore whitespace when comparing lines"),
6175 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
6176 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
6177 N_("ignore changes in amount of whitespace"),
6178 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
6179 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
6180 N_("ignore changes in whitespace at EOL"),
6181 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
6182 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
6183 N_("ignore carrier-return at the end of line"),
6184 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
6185 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
6186 N_("ignore changes whose lines are all blank"),
6187 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
6188 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
6189 N_("ignore changes whose all lines match <regex>"),
6190 0, diff_opt_ignore_regex),
6191 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
6192 N_("heuristic to shift diff hunk boundaries for easy reading"),
6193 XDF_INDENT_HEURISTIC),
6194 OPT_CALLBACK_F(0, "patience", options, NULL,
6195 N_("generate diff using the \"patience diff\" algorithm"),
6196 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6197 diff_opt_patience),
6198 OPT_CALLBACK_F(0, "histogram", options, NULL,
6199 N_("generate diff using the \"histogram diff\" algorithm"),
6200 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6201 diff_opt_diff_algorithm_no_arg),
6202 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
6203 N_("choose a diff algorithm"),
6204 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
6205 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
6206 N_("generate diff using the \"anchored diff\" algorithm"),
6207 PARSE_OPT_NONEG, diff_opt_anchored),
6208 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
6209 N_("show word diff, using <mode> to delimit changed words"),
6210 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
6211 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
6212 N_("use <regex> to decide what a word is"),
6213 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
6214 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
6215 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
6216 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
6217 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
6218 N_("moved lines of code are colored differently"),
6219 PARSE_OPT_OPTARG, diff_opt_color_moved),
6220 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
6221 N_("how white spaces are ignored in --color-moved"),
6222 0, diff_opt_color_moved_ws),
6223
6224 OPT_GROUP(N_("Other diff options")),
6225 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
6226 N_("when run from subdir, exclude changes outside and show relative paths"),
6227 PARSE_OPT_OPTARG,
6228 diff_opt_relative),
6229 OPT_BOOL('a', "text", &options->flags.text,
6230 N_("treat all files as text")),
6231 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
6232 N_("swap two inputs, reverse the diff")),
6233 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
6234 N_("exit with 1 if there were differences, 0 otherwise")),
6235 OPT_BOOL(0, "quiet", &options->flags.quick,
6236 N_("disable all output of the program")),
6237 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
6238 N_("allow an external diff helper to be executed")),
6239 OPT_CALLBACK_F(0, "textconv", options, NULL,
6240 N_("run external text conversion filters when comparing binary files"),
6241 PARSE_OPT_NOARG, diff_opt_textconv),
6242 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
6243 N_("ignore changes to submodules in the diff generation"),
6244 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6245 diff_opt_ignore_submodules),
6246 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
6247 N_("specify how differences in submodules are shown"),
6248 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6249 diff_opt_submodule),
6250 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
6251 N_("hide 'git add -N' entries from the index"),
6252 1, PARSE_OPT_NONEG),
6253 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
6254 N_("treat 'git add -N' entries as real in the index"),
6255 0, PARSE_OPT_NONEG),
6256 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
6257 N_("look for differences that change the number of occurrences of the specified string"),
6258 0, diff_opt_pickaxe_string),
6259 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
6260 N_("look for differences that change the number of occurrences of the specified regex"),
6261 0, diff_opt_pickaxe_regex),
6262 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
6263 N_("show all changes in the changeset with -S or -G"),
6264 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
6265 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
6266 N_("treat <string> in -S as extended POSIX regular expression"),
6267 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
6268 OPT_FILENAME('O', NULL, &options->orderfile,
6269 N_("control the order in which files appear in the output")),
6270 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
6271 N_("show the change in the specified path first"),
6272 PARSE_OPT_NONEG, diff_opt_rotate_to),
6273 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
6274 N_("skip the output to the specified path"),
6275 PARSE_OPT_NONEG, diff_opt_rotate_to),
6276 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
6277 N_("look for differences that change the number of occurrences of the specified object"),
6278 PARSE_OPT_NONEG, diff_opt_find_object),
6279 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
6280 N_("select files by diff type"),
6281 PARSE_OPT_NONEG, diff_opt_diff_filter),
6282 OPT_CALLBACK_F(0, "max-depth", options, N_("<depth>"),
6283 N_("maximum tree depth to recurse"),
6284 PARSE_OPT_NONEG, diff_opt_max_depth),
6285
6286 {
6287 .type = OPTION_CALLBACK,
6288 .long_name = "output",
6289 .value = options,
6290 .argh = N_("<file>"),
6291 .help = N_("output to a specific file"),
6292 .flags = PARSE_OPT_NONEG,
6293 .ll_callback = diff_opt_output,
6294 },
6295 OPT_END()
6296 };
6297
6298 return parse_options_concat(opts, parseopts);
6299 }
6300
6301 int diff_opt_parse(struct diff_options *options,
6302 const char **av, int ac, const char *prefix)
6303 {
6304 struct option no_options[] = { OPT_END() };
6305 struct option *parseopts = add_diff_options(no_options, options);
6306
6307 if (!prefix)
6308 prefix = "";
6309
6310 ac = parse_options(ac, av, prefix, parseopts, NULL,
6311 PARSE_OPT_KEEP_DASHDASH |
6312 PARSE_OPT_KEEP_UNKNOWN_OPT |
6313 PARSE_OPT_NO_INTERNAL_HELP |
6314 PARSE_OPT_ONE_SHOT |
6315 PARSE_OPT_STOP_AT_NON_OPTION);
6316 free(parseopts);
6317
6318 return ac;
6319 }
6320
6321 int parse_rename_score(const char **cp_p)
6322 {
6323 unsigned long num, scale;
6324 int ch, dot;
6325 const char *cp = *cp_p;
6326
6327 num = 0;
6328 scale = 1;
6329 dot = 0;
6330 for (;;) {
6331 ch = *cp;
6332 if ( !dot && ch == '.' ) {
6333 scale = 1;
6334 dot = 1;
6335 } else if ( ch == '%' ) {
6336 scale = dot ? scale*100 : 100;
6337 cp++; /* % is always at the end */
6338 break;
6339 } else if ( ch >= '0' && ch <= '9' ) {
6340 if ( scale < 100000 ) {
6341 scale *= 10;
6342 num = (num*10) + (ch-'0');
6343 }
6344 } else {
6345 break;
6346 }
6347 cp++;
6348 }
6349 *cp_p = cp;
6350
6351 /* user says num divided by scale and we say internally that
6352 * is MAX_SCORE * num / scale.
6353 */
6354 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
6355 }
6356
6357 struct diff_queue_struct diff_queued_diff;
6358
6359 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
6360 {
6361 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
6362 queue->queue[queue->nr++] = dp;
6363 }
6364
6365 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
6366 struct diff_filespec *one,
6367 struct diff_filespec *two)
6368 {
6369 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
6370 dp->one = one;
6371 dp->two = two;
6372 if (queue)
6373 diff_q(queue, dp);
6374 return dp;
6375 }
6376
6377 void diff_free_filepair(struct diff_filepair *p)
6378 {
6379 free_filespec(p->one);
6380 free_filespec(p->two);
6381 free(p);
6382 }
6383
6384 void diff_queue_init(struct diff_queue_struct *q)
6385 {
6386 struct diff_queue_struct blank = DIFF_QUEUE_INIT;
6387 memcpy(q, &blank, sizeof(*q));
6388 }
6389
6390 void diff_queue_clear(struct diff_queue_struct *q)
6391 {
6392 for (int i = 0; i < q->nr; i++)
6393 diff_free_filepair(q->queue[i]);
6394 free(q->queue);
6395 diff_queue_init(q);
6396 }
6397
6398 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
6399 {
6400 int abblen;
6401 const char *abbrev;
6402
6403 /* Do we want all 40 hex characters? */
6404 if (len == the_hash_algo->hexsz)
6405 return oid_to_hex(oid);
6406
6407 /* An abbreviated value is fine, possibly followed by an ellipsis. */
6408 abbrev = diff_abbrev_oid(oid, len);
6409
6410 if (!print_sha1_ellipsis())
6411 return abbrev;
6412
6413 abblen = strlen(abbrev);
6414
6415 /*
6416 * In well-behaved cases, where the abbreviated result is the
6417 * same as the requested length, append three dots after the
6418 * abbreviation (hence the whole logic is limited to the case
6419 * where abblen < 37); when the actual abbreviated result is a
6420 * bit longer than the requested length, we reduce the number
6421 * of dots so that they match the well-behaved ones. However,
6422 * if the actual abbreviation is longer than the requested
6423 * length by more than three, we give up on aligning, and add
6424 * three dots anyway, to indicate that the output is not the
6425 * full object name. Yes, this may be suboptimal, but this
6426 * appears only in "diff --raw --abbrev" output and it is not
6427 * worth the effort to change it now. Note that this would
6428 * likely to work fine when the automatic sizing of default
6429 * abbreviation length is used--we would be fed -1 in "len" in
6430 * that case, and will end up always appending three-dots, but
6431 * the automatic sizing is supposed to give abblen that ensures
6432 * uniqueness across all objects (statistically speaking).
6433 */
6434 if (abblen < the_hash_algo->hexsz - 3) {
6435 static char hex[GIT_MAX_HEXSZ + 1];
6436 if (len < abblen && abblen <= len + 2)
6437 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
6438 else
6439 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
6440 return hex;
6441 }
6442
6443 return oid_to_hex(oid);
6444 }
6445
6446 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6447 {
6448 int line_termination = opt->line_termination;
6449 int inter_name_termination = line_termination ? '\t' : '\0';
6450
6451 fprintf(opt->file, "%s", diff_line_prefix(opt));
6452 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
6453 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
6454 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
6455 fprintf(opt->file, "%s ",
6456 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
6457 }
6458 if (p->score) {
6459 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
6460 inter_name_termination);
6461 } else {
6462 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6463 }
6464
6465 if (p->status == DIFF_STATUS_COPIED ||
6466 p->status == DIFF_STATUS_RENAMED) {
6467 const char *name_a, *name_b;
6468 name_a = p->one->path;
6469 name_b = p->two->path;
6470 strip_prefix(opt->prefix_length, &name_a, &name_b);
6471 write_name_quoted(name_a, opt->file, inter_name_termination);
6472 write_name_quoted(name_b, opt->file, line_termination);
6473 } else {
6474 const char *name_a, *name_b;
6475 name_a = p->one->mode ? p->one->path : p->two->path;
6476 name_b = NULL;
6477 strip_prefix(opt->prefix_length, &name_a, &name_b);
6478 write_name_quoted(name_a, opt->file, line_termination);
6479 }
6480 }
6481
6482 int diff_unmodified_pair(struct diff_filepair *p)
6483 {
6484 /* This function is written stricter than necessary to support
6485 * the currently implemented transformers, but the idea is to
6486 * let transformers to produce diff_filepairs any way they want,
6487 * and filter and clean them up here before producing the output.
6488 */
6489 struct diff_filespec *one = p->one, *two = p->two;
6490
6491 if (DIFF_PAIR_UNMERGED(p))
6492 return 0; /* unmerged is interesting */
6493
6494 /* deletion, addition, mode or type change
6495 * and rename are all interesting.
6496 */
6497 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
6498 DIFF_PAIR_MODE_CHANGED(p) ||
6499 strcmp(one->path, two->path))
6500 return 0;
6501
6502 /* both are valid and point at the same path. that is, we are
6503 * dealing with a change.
6504 */
6505 if (one->oid_valid && two->oid_valid &&
6506 oideq(&one->oid, &two->oid) &&
6507 !one->dirty_submodule && !two->dirty_submodule)
6508 return 1; /* no change */
6509 if (!one->oid_valid && !two->oid_valid)
6510 return 1; /* both look at the same file on the filesystem. */
6511 return 0;
6512 }
6513
6514 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6515 {
6516 int include_conflict_headers =
6517 (additional_headers(o, p->one->path) &&
6518 !o->pickaxe_opts &&
6519 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6520
6521 /*
6522 * Check if we can return early without showing a diff. Note that
6523 * diff_filepair only stores {oid, path, mode, is_valid}
6524 * information for each path, and thus diff_unmodified_pair() only
6525 * considers those bits of info. However, we do not want pairs
6526 * created by create_filepairs_for_header_only_notifications()
6527 * (which always look like unmodified pairs) to be ignored, so
6528 * return early if both p is unmodified AND we don't want to
6529 * include_conflict_headers.
6530 */
6531 if (diff_unmodified_pair(p) && !include_conflict_headers)
6532 return;
6533
6534 /* Actually, we can also return early to avoid showing tree diffs */
6535 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6536 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6537 return;
6538
6539 run_diff(p, o);
6540 }
6541
6542 /* return 1 if any change is found; otherwise, return 0 */
6543 static int diff_flush_patch_quietly(struct diff_filepair *p, struct diff_options *o)
6544 {
6545 FILE *saved_file = o->file;
6546 int saved_found_changes = o->found_changes;
6547 int ret;
6548
6549 o->file = NULL;
6550 o->found_changes = 0;
6551 diff_flush_patch(p, o);
6552 ret = o->found_changes;
6553 o->file = saved_file;
6554 o->found_changes |= saved_found_changes;
6555 return ret;
6556 }
6557
6558 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6559 struct diffstat_t *diffstat)
6560 {
6561 if (diff_unmodified_pair(p))
6562 return;
6563
6564 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6565 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6566 return; /* no useful stat for tree diffs */
6567
6568 run_diffstat(p, o, diffstat);
6569 }
6570
6571 static void diff_flush_checkdiff(struct diff_filepair *p,
6572 struct diff_options *o)
6573 {
6574 if (diff_unmodified_pair(p))
6575 return;
6576
6577 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6578 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6579 return; /* nothing to check in tree diffs */
6580
6581 run_checkdiff(p, o);
6582 }
6583
6584 int diff_queue_is_empty(struct diff_options *o)
6585 {
6586 struct diff_queue_struct *q = &diff_queued_diff;
6587 int i;
6588 int include_conflict_headers =
6589 (o->additional_path_headers &&
6590 strmap_get_size(o->additional_path_headers) &&
6591 !o->pickaxe_opts &&
6592 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6593
6594 if (include_conflict_headers)
6595 return 0;
6596
6597 for (i = 0; i < q->nr; i++)
6598 if (!diff_unmodified_pair(q->queue[i]))
6599 return 0;
6600 return 1;
6601 }
6602
6603 #if DIFF_DEBUG
6604 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6605 {
6606 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6607 x, one ? one : "",
6608 s->path,
6609 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6610 s->mode,
6611 s->oid_valid ? oid_to_hex(&s->oid) : "");
6612 fprintf(stderr, "queue[%d] %s size %lu\n",
6613 x, one ? one : "",
6614 s->size);
6615 }
6616
6617 void diff_debug_filepair(const struct diff_filepair *p, int i)
6618 {
6619 diff_debug_filespec(p->one, i, "one");
6620 diff_debug_filespec(p->two, i, "two");
6621 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6622 p->score, p->status ? p->status : '?',
6623 p->one->rename_used, p->broken_pair);
6624 }
6625
6626 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6627 {
6628 int i;
6629 if (msg)
6630 fprintf(stderr, "%s\n", msg);
6631 fprintf(stderr, "q->nr = %d\n", q->nr);
6632 for (i = 0; i < q->nr; i++) {
6633 struct diff_filepair *p = q->queue[i];
6634 diff_debug_filepair(p, i);
6635 }
6636 }
6637 #endif
6638
6639 static void diff_resolve_rename_copy(void)
6640 {
6641 int i;
6642 struct diff_filepair *p;
6643 struct diff_queue_struct *q = &diff_queued_diff;
6644
6645 diff_debug_queue("resolve-rename-copy", q);
6646
6647 for (i = 0; i < q->nr; i++) {
6648 p = q->queue[i];
6649 p->status = 0; /* undecided */
6650 if (DIFF_PAIR_UNMERGED(p))
6651 p->status = DIFF_STATUS_UNMERGED;
6652 else if (!DIFF_FILE_VALID(p->one))
6653 p->status = DIFF_STATUS_ADDED;
6654 else if (!DIFF_FILE_VALID(p->two))
6655 p->status = DIFF_STATUS_DELETED;
6656 else if (DIFF_PAIR_TYPE_CHANGED(p))
6657 p->status = DIFF_STATUS_TYPE_CHANGED;
6658
6659 /* from this point on, we are dealing with a pair
6660 * whose both sides are valid and of the same type, i.e.
6661 * either in-place edit or rename/copy edit.
6662 */
6663 else if (DIFF_PAIR_RENAME(p)) {
6664 /*
6665 * A rename might have re-connected a broken
6666 * pair up, causing the pathnames to be the
6667 * same again. If so, that's not a rename at
6668 * all, just a modification..
6669 *
6670 * Otherwise, see if this source was used for
6671 * multiple renames, in which case we decrement
6672 * the count, and call it a copy.
6673 */
6674 if (!strcmp(p->one->path, p->two->path))
6675 p->status = DIFF_STATUS_MODIFIED;
6676 else if (--p->one->rename_used > 0)
6677 p->status = DIFF_STATUS_COPIED;
6678 else
6679 p->status = DIFF_STATUS_RENAMED;
6680 }
6681 else if (!oideq(&p->one->oid, &p->two->oid) ||
6682 p->one->mode != p->two->mode ||
6683 p->one->dirty_submodule ||
6684 p->two->dirty_submodule ||
6685 is_null_oid(&p->one->oid))
6686 p->status = DIFF_STATUS_MODIFIED;
6687 else {
6688 /* This is a "no-change" entry and should not
6689 * happen anymore, but prepare for broken callers.
6690 */
6691 error("feeding unmodified %s to diffcore",
6692 p->one->path);
6693 p->status = DIFF_STATUS_UNKNOWN;
6694 }
6695 }
6696 diff_debug_queue("resolve-rename-copy done", q);
6697 }
6698
6699 static int check_pair_status(struct diff_filepair *p)
6700 {
6701 switch (p->status) {
6702 case DIFF_STATUS_UNKNOWN:
6703 return 0;
6704 case 0:
6705 die("internal error in diff-resolve-rename-copy");
6706 default:
6707 return 1;
6708 }
6709 }
6710
6711 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6712 {
6713 int fmt = opt->output_format;
6714
6715 if (fmt & DIFF_FORMAT_CHECKDIFF)
6716 diff_flush_checkdiff(p, opt);
6717 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6718 diff_flush_raw(p, opt);
6719 else if (fmt & DIFF_FORMAT_NAME) {
6720 const char *name_a, *name_b;
6721 name_a = p->two->path;
6722 name_b = NULL;
6723 strip_prefix(opt->prefix_length, &name_a, &name_b);
6724 fprintf(opt->file, "%s", diff_line_prefix(opt));
6725 write_name_quoted(name_a, opt->file, opt->line_termination);
6726 }
6727
6728 opt->found_changes = 1;
6729 }
6730
6731 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6732 {
6733 struct strbuf sb = STRBUF_INIT;
6734 if (fs->mode)
6735 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6736 else
6737 strbuf_addf(&sb, " %s ", newdelete);
6738
6739 quote_c_style(fs->path, &sb, NULL, 0);
6740 strbuf_addch(&sb, '\n');
6741 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6742 sb.buf, sb.len, 0);
6743 strbuf_release(&sb);
6744 }
6745
6746 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6747 int show_name)
6748 {
6749 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6750 struct strbuf sb = STRBUF_INIT;
6751 strbuf_addf(&sb, " mode change %06o => %06o",
6752 p->one->mode, p->two->mode);
6753 if (show_name) {
6754 strbuf_addch(&sb, ' ');
6755 quote_c_style(p->two->path, &sb, NULL, 0);
6756 }
6757 strbuf_addch(&sb, '\n');
6758 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6759 sb.buf, sb.len, 0);
6760 strbuf_release(&sb);
6761 }
6762 }
6763
6764 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6765 struct diff_filepair *p)
6766 {
6767 struct strbuf sb = STRBUF_INIT;
6768 struct strbuf names = STRBUF_INIT;
6769
6770 pprint_rename(&names, p->one->path, p->two->path);
6771 strbuf_addf(&sb, " %s %s (%d%%)\n",
6772 renamecopy, names.buf, similarity_index(p));
6773 strbuf_release(&names);
6774 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6775 sb.buf, sb.len, 0);
6776 show_mode_change(opt, p, 0);
6777 strbuf_release(&sb);
6778 }
6779
6780 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6781 {
6782 switch(p->status) {
6783 case DIFF_STATUS_DELETED:
6784 show_file_mode_name(opt, "delete", p->one);
6785 break;
6786 case DIFF_STATUS_ADDED:
6787 show_file_mode_name(opt, "create", p->two);
6788 break;
6789 case DIFF_STATUS_COPIED:
6790 show_rename_copy(opt, "copy", p);
6791 break;
6792 case DIFF_STATUS_RENAMED:
6793 show_rename_copy(opt, "rename", p);
6794 break;
6795 default:
6796 if (p->score) {
6797 struct strbuf sb = STRBUF_INIT;
6798 strbuf_addstr(&sb, " rewrite ");
6799 quote_c_style(p->two->path, &sb, NULL, 0);
6800 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6801 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6802 sb.buf, sb.len, 0);
6803 strbuf_release(&sb);
6804 }
6805 show_mode_change(opt, p, !p->score);
6806 break;
6807 }
6808 }
6809
6810 struct patch_id_t {
6811 struct git_hash_ctx *ctx;
6812 int patchlen;
6813 };
6814
6815 static int remove_space(char *line, int len)
6816 {
6817 int i;
6818 char *dst = line;
6819 unsigned char c;
6820
6821 for (i = 0; i < len; i++)
6822 if (!isspace((c = line[i])))
6823 *dst++ = c;
6824
6825 return dst - line;
6826 }
6827
6828 void flush_one_hunk(struct object_id *result, struct git_hash_ctx *ctx)
6829 {
6830 unsigned char hash[GIT_MAX_RAWSZ];
6831 unsigned short carry = 0;
6832 int i;
6833
6834 git_hash_final(hash, ctx);
6835 git_hash_init(ctx, the_hash_algo);
6836 /* 20-byte sum, with carry */
6837 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6838 carry += result->hash[i] + hash[i];
6839 result->hash[i] = carry;
6840 carry >>= 8;
6841 }
6842 }
6843
6844 static int patch_id_consume(void *priv, char *line, unsigned long len)
6845 {
6846 struct patch_id_t *data = priv;
6847 int new_len;
6848
6849 if (len > 12 && starts_with(line, "\\ "))
6850 return 0;
6851 new_len = remove_space(line, len);
6852
6853 git_hash_update(data->ctx, line, new_len);
6854 data->patchlen += new_len;
6855 return 0;
6856 }
6857
6858 static void patch_id_add_string(struct git_hash_ctx *ctx, const char *str)
6859 {
6860 git_hash_update(ctx, str, strlen(str));
6861 }
6862
6863 static void patch_id_add_mode(struct git_hash_ctx *ctx, unsigned mode)
6864 {
6865 /* large enough for 2^32 in octal */
6866 char buf[12];
6867 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6868 git_hash_update(ctx, buf, len);
6869 }
6870
6871 /* returns 0 upon success, and writes result into oid */
6872 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6873 {
6874 struct diff_queue_struct *q = &diff_queued_diff;
6875 int i;
6876 struct git_hash_ctx ctx;
6877 struct patch_id_t data;
6878
6879 git_hash_init(&ctx, the_hash_algo);
6880 memset(&data, 0, sizeof(struct patch_id_t));
6881 data.ctx = &ctx;
6882 oidclr(oid, the_repository->hash_algo);
6883
6884 for (i = 0; i < q->nr; i++) {
6885 xpparam_t xpp;
6886 xdemitconf_t xecfg;
6887 mmfile_t mf1, mf2;
6888 struct diff_filepair *p = q->queue[i];
6889 int len1, len2;
6890
6891 memset(&xpp, 0, sizeof(xpp));
6892 memset(&xecfg, 0, sizeof(xecfg));
6893 if (p->status == 0)
6894 return error("internal diff status error");
6895 if (p->status == DIFF_STATUS_UNKNOWN)
6896 continue;
6897 if (diff_unmodified_pair(p))
6898 continue;
6899 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6900 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6901 continue;
6902 if (DIFF_PAIR_UNMERGED(p))
6903 continue;
6904
6905 diff_fill_oid_info(p->one, options->repo->index);
6906 diff_fill_oid_info(p->two, options->repo->index);
6907
6908 len1 = remove_space(p->one->path, strlen(p->one->path));
6909 len2 = remove_space(p->two->path, strlen(p->two->path));
6910 patch_id_add_string(&ctx, "diff--git");
6911 patch_id_add_string(&ctx, "a/");
6912 git_hash_update(&ctx, p->one->path, len1);
6913 patch_id_add_string(&ctx, "b/");
6914 git_hash_update(&ctx, p->two->path, len2);
6915
6916 if (p->one->mode == 0) {
6917 patch_id_add_string(&ctx, "newfilemode");
6918 patch_id_add_mode(&ctx, p->two->mode);
6919 } else if (p->two->mode == 0) {
6920 patch_id_add_string(&ctx, "deletedfilemode");
6921 patch_id_add_mode(&ctx, p->one->mode);
6922 } else if (p->one->mode != p->two->mode) {
6923 patch_id_add_string(&ctx, "oldmode");
6924 patch_id_add_mode(&ctx, p->one->mode);
6925 patch_id_add_string(&ctx, "newmode");
6926 patch_id_add_mode(&ctx, p->two->mode);
6927 }
6928
6929 if (diff_header_only) {
6930 /* don't do anything since we're only populating header info */
6931 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6932 diff_filespec_is_binary(options->repo, p->two)) {
6933 git_hash_update(&ctx, oid_to_hex(&p->one->oid),
6934 the_hash_algo->hexsz);
6935 git_hash_update(&ctx, oid_to_hex(&p->two->oid),
6936 the_hash_algo->hexsz);
6937 } else {
6938 if (p->one->mode == 0) {
6939 patch_id_add_string(&ctx, "---/dev/null");
6940 patch_id_add_string(&ctx, "+++b/");
6941 git_hash_update(&ctx, p->two->path, len2);
6942 } else if (p->two->mode == 0) {
6943 patch_id_add_string(&ctx, "---a/");
6944 git_hash_update(&ctx, p->one->path, len1);
6945 patch_id_add_string(&ctx, "+++/dev/null");
6946 } else {
6947 patch_id_add_string(&ctx, "---a/");
6948 git_hash_update(&ctx, p->one->path, len1);
6949 patch_id_add_string(&ctx, "+++b/");
6950 git_hash_update(&ctx, p->two->path, len2);
6951 }
6952
6953 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6954 fill_mmfile(options->repo, &mf2, p->two) < 0)
6955 return error("unable to read files to diff");
6956 xpp.flags = 0;
6957 xecfg.ctxlen = 3;
6958 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6959 if (xdi_diff_outf(&mf1, &mf2, NULL,
6960 patch_id_consume, &data, &xpp, &xecfg))
6961 return error("unable to generate patch-id diff for %s",
6962 p->one->path);
6963 }
6964 flush_one_hunk(oid, &ctx);
6965 }
6966
6967 git_hash_discard(&ctx);
6968 return 0;
6969 }
6970
6971 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6972 {
6973 struct diff_queue_struct *q = &diff_queued_diff;
6974 int result = diff_get_patch_id(options, oid, diff_header_only);
6975
6976 diff_queue_clear(q);
6977
6978 return result;
6979 }
6980
6981 static int is_summary_empty(const struct diff_queue_struct *q)
6982 {
6983 int i;
6984
6985 for (i = 0; i < q->nr; i++) {
6986 const struct diff_filepair *p = q->queue[i];
6987
6988 switch (p->status) {
6989 case DIFF_STATUS_DELETED:
6990 case DIFF_STATUS_ADDED:
6991 case DIFF_STATUS_COPIED:
6992 case DIFF_STATUS_RENAMED:
6993 return 0;
6994 default:
6995 if (p->score)
6996 return 0;
6997 if (p->one->mode && p->two->mode &&
6998 p->one->mode != p->two->mode)
6999 return 0;
7000 break;
7001 }
7002 }
7003 return 1;
7004 }
7005
7006 static const char rename_limit_warning[] =
7007 N_("exhaustive rename detection was skipped due to too many files.");
7008
7009 static const char degrade_cc_to_c_warning[] =
7010 N_("only found copies from modified paths due to too many files.");
7011
7012 static const char rename_limit_advice[] =
7013 N_("you may want to set your %s variable to at least "
7014 "%d and retry the command.");
7015
7016 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
7017 {
7018 fflush(stdout);
7019 if (degraded_cc)
7020 warning(_(degrade_cc_to_c_warning));
7021 else if (needed)
7022 warning(_(rename_limit_warning));
7023 else
7024 return;
7025 if (0 < needed)
7026 warning(_(rename_limit_advice), varname, needed);
7027 }
7028
7029 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
7030 {
7031 struct strset present;
7032 struct diff_queue_struct *q = &diff_queued_diff;
7033 struct hashmap_iter iter;
7034 struct strmap_entry *e;
7035 int i;
7036
7037 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
7038
7039 /*
7040 * Find out which paths exist in diff_queued_diff, preferring
7041 * one->path for any pair that has multiple paths.
7042 */
7043 for (i = 0; i < q->nr; i++) {
7044 struct diff_filepair *p = q->queue[i];
7045 char *path = p->one->path ? p->one->path : p->two->path;
7046
7047 if (strmap_contains(o->additional_path_headers, path))
7048 strset_add(&present, path);
7049 }
7050
7051 /*
7052 * Loop over paths in additional_path_headers; for each NOT already
7053 * in diff_queued_diff, create a synthetic filepair and insert that
7054 * into diff_queued_diff.
7055 */
7056 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
7057 if (!strset_contains(&present, e->key)) {
7058 struct diff_filespec *one, *two;
7059 struct diff_filepair *p;
7060
7061 one = alloc_filespec(e->key);
7062 two = alloc_filespec(e->key);
7063 fill_filespec(one, null_oid(the_hash_algo), 0, 0);
7064 fill_filespec(two, null_oid(the_hash_algo), 0, 0);
7065 p = diff_queue(q, one, two);
7066 p->status = DIFF_STATUS_MODIFIED;
7067 }
7068 }
7069
7070 /* Re-sort the filepairs */
7071 diffcore_fix_diff_index();
7072
7073 /* Cleanup */
7074 strset_clear(&present);
7075 }
7076
7077 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
7078 {
7079 int i;
7080 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
7081 struct diff_queue_struct *q = &diff_queued_diff;
7082
7083 if (WSEH_NEW & WS_RULE_MASK)
7084 BUG("WS rules bit mask overlaps with diff symbol flags");
7085
7086 if (o->color_moved && want_color(o->use_color))
7087 o->emitted_symbols = &esm;
7088
7089 if (o->additional_path_headers)
7090 create_filepairs_for_header_only_notifications(o);
7091
7092 for (i = 0; i < q->nr; i++) {
7093 struct diff_filepair *p = q->queue[i];
7094 if (check_pair_status(p))
7095 diff_flush_patch(p, o);
7096 }
7097
7098 if (o->emitted_symbols) {
7099 struct mem_pool entry_pool;
7100 struct moved_entry_list *entry_list;
7101
7102 mem_pool_init(&entry_pool, 1024 * 1024);
7103 entry_list = add_lines_to_move_detection(o, &entry_pool);
7104 mark_color_as_moved(o, entry_list);
7105 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
7106 dim_moved_lines(o);
7107
7108 mem_pool_discard(&entry_pool, 0);
7109 free(entry_list);
7110
7111 for (i = 0; i < esm.nr; i++)
7112 emit_diff_symbol_from_struct(o, &esm.buf[i]);
7113
7114 for (i = 0; i < esm.nr; i++)
7115 free((void *)esm.buf[i].line);
7116 esm.nr = 0;
7117
7118 o->emitted_symbols = NULL;
7119 }
7120 }
7121
7122 static void diff_free_file(struct diff_options *options)
7123 {
7124 if (options->close_file && options->file) {
7125 fclose(options->file);
7126 options->file = NULL;
7127 }
7128 }
7129
7130 static void diff_free_ignore_regex(struct diff_options *options)
7131 {
7132 int i;
7133
7134 for (i = 0; i < options->ignore_regex_nr; i++) {
7135 regfree(options->ignore_regex[i]);
7136 free(options->ignore_regex[i]);
7137 }
7138
7139 FREE_AND_NULL(options->ignore_regex);
7140 options->ignore_regex_nr = 0;
7141 }
7142
7143 void diff_free(struct diff_options *options)
7144 {
7145 if (options->no_free)
7146 return;
7147
7148 if (options->objfind) {
7149 oidset_clear(options->objfind);
7150 FREE_AND_NULL(options->objfind);
7151 }
7152
7153 FREE_AND_NULL(options->orderfile);
7154 for (size_t i = 0; i < options->anchors_nr; i++)
7155 free(options->anchors[i]);
7156 FREE_AND_NULL(options->anchors);
7157 options->anchors_nr = options->anchors_alloc = 0;
7158
7159 diff_free_file(options);
7160 diff_free_ignore_regex(options);
7161 clear_pathspec(&options->pathspec);
7162 }
7163
7164 void diff_flush(struct diff_options *options)
7165 {
7166 struct diff_queue_struct *q = &diff_queued_diff;
7167 int i, output_format = options->output_format;
7168 int separator = 0;
7169 int dirstat_by_line = 0;
7170
7171 /*
7172 * Order: raw, stat, summary, patch
7173 * or: name/name-status/checkdiff (other bits clear)
7174 */
7175 if (!q->nr && !options->additional_path_headers)
7176 goto free_queue;
7177
7178 if (output_format & (DIFF_FORMAT_RAW |
7179 DIFF_FORMAT_NAME |
7180 DIFF_FORMAT_NAME_STATUS |
7181 DIFF_FORMAT_CHECKDIFF)) {
7182 for (i = 0; i < q->nr; i++) {
7183 struct diff_filepair *p = q->queue[i];
7184
7185 if (!check_pair_status(p))
7186 continue;
7187
7188 if (options->flags.diff_from_contents &&
7189 !diff_flush_patch_quietly(p, options))
7190 continue;
7191
7192 flush_one_pair(p, options);
7193 }
7194 separator++;
7195 }
7196
7197 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
7198 dirstat_by_line = 1;
7199
7200 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
7201 dirstat_by_line) {
7202 struct diffstat_t diffstat;
7203
7204 compute_diffstat(options, &diffstat, q);
7205 if (output_format & DIFF_FORMAT_NUMSTAT)
7206 show_numstat(&diffstat, options);
7207 if (output_format & DIFF_FORMAT_DIFFSTAT)
7208 show_stats(&diffstat, options);
7209 if (output_format & DIFF_FORMAT_SHORTSTAT)
7210 show_shortstats(&diffstat, options);
7211 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
7212 show_dirstat_by_line(&diffstat, options);
7213 free_diffstat_info(&diffstat);
7214 separator++;
7215 }
7216 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
7217 show_dirstat(options);
7218
7219 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
7220 for (i = 0; i < q->nr; i++) {
7221 diff_summary(options, q->queue[i]);
7222 }
7223 separator++;
7224 }
7225
7226 if (output_format & DIFF_FORMAT_PATCH) {
7227 if (separator) {
7228 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
7229 if (options->stat_sep)
7230 /* attach patch instead of inline */
7231 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
7232 NULL, 0, 0);
7233 }
7234
7235 diff_flush_patch_all_file_pairs(options);
7236 }
7237
7238 if (output_format & DIFF_FORMAT_CALLBACK)
7239 options->format_callback(q, options, options->format_callback_data);
7240
7241 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
7242 options->flags.exit_with_status &&
7243 options->flags.diff_from_contents) {
7244 for (i = 0; i < q->nr; i++) {
7245 struct diff_filepair *p = q->queue[i];
7246 if (check_pair_status(p))
7247 diff_flush_patch_quietly(p, options);
7248 if (options->found_changes)
7249 break;
7250 }
7251 }
7252
7253 free_queue:
7254 diff_queue_clear(q);
7255 diff_free(options);
7256
7257 /*
7258 * Report the content-level differences with HAS_CHANGES;
7259 * diff_addremove/diff_change does not set the bit when
7260 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
7261 */
7262 if (options->flags.diff_from_contents) {
7263 if (options->found_changes)
7264 options->flags.has_changes = 1;
7265 else
7266 options->flags.has_changes = 0;
7267 }
7268 }
7269
7270 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
7271 {
7272 return (((p->status == DIFF_STATUS_MODIFIED) &&
7273 ((p->score &&
7274 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
7275 (!p->score &&
7276 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
7277 ((p->status != DIFF_STATUS_MODIFIED) &&
7278 filter_bit_tst(p->status, options)));
7279 }
7280
7281 static void diffcore_apply_filter(struct diff_options *options)
7282 {
7283 int i;
7284 struct diff_queue_struct *q = &diff_queued_diff;
7285 struct diff_queue_struct outq = DIFF_QUEUE_INIT;
7286
7287 if (!options->filter)
7288 return;
7289
7290 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
7291 int found;
7292 for (i = found = 0; !found && i < q->nr; i++) {
7293 if (match_filter(options, q->queue[i]))
7294 found++;
7295 }
7296 if (found)
7297 return;
7298
7299 /* otherwise we will clear the whole queue
7300 * by copying the empty outq at the end of this
7301 * function, but first clear the current entries
7302 * in the queue.
7303 */
7304 for (i = 0; i < q->nr; i++)
7305 diff_free_filepair(q->queue[i]);
7306 }
7307 else {
7308 /* Only the matching ones */
7309 for (i = 0; i < q->nr; i++) {
7310 struct diff_filepair *p = q->queue[i];
7311 if (match_filter(options, p))
7312 diff_q(&outq, p);
7313 else
7314 diff_free_filepair(p);
7315 }
7316 }
7317 free(q->queue);
7318 *q = outq;
7319 }
7320
7321 /* Check whether two filespecs with the same mode and size are identical */
7322 static int diff_filespec_is_identical(struct repository *r,
7323 struct diff_filespec *one,
7324 struct diff_filespec *two)
7325 {
7326 if (S_ISGITLINK(one->mode))
7327 return 0;
7328 if (diff_populate_filespec(r, one, NULL))
7329 return 0;
7330 if (diff_populate_filespec(r, two, NULL))
7331 return 0;
7332 return !memcmp(one->data, two->data, one->size);
7333 }
7334
7335 static int diff_filespec_check_stat_unmatch(struct repository *r,
7336 struct diff_filepair *p)
7337 {
7338 struct diff_populate_filespec_options dpf_options = {
7339 .check_size_only = 1,
7340 .missing_object_cb = diff_queued_diff_prefetch,
7341 .missing_object_data = r,
7342 };
7343
7344 if (p->done_skip_stat_unmatch)
7345 return p->skip_stat_unmatch_result;
7346
7347 p->done_skip_stat_unmatch = 1;
7348 p->skip_stat_unmatch_result = 0;
7349 /*
7350 * 1. Entries that come from stat info dirtiness
7351 * always have both sides (iow, not create/delete),
7352 * one side of the object name is unknown, with
7353 * the same mode and size. Keep the ones that
7354 * do not match these criteria. They have real
7355 * differences.
7356 *
7357 * 2. At this point, the file is known to be modified,
7358 * with the same mode and size, and the object
7359 * name of one side is unknown. Need to inspect
7360 * the identical contents.
7361 */
7362 if (!DIFF_FILE_VALID(p->one) || /* (1) */
7363 !DIFF_FILE_VALID(p->two) ||
7364 (p->one->oid_valid && p->two->oid_valid) ||
7365 (p->one->mode != p->two->mode) ||
7366 diff_populate_filespec(r, p->one, &dpf_options) ||
7367 diff_populate_filespec(r, p->two, &dpf_options) ||
7368 (p->one->size != p->two->size) ||
7369 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
7370 p->skip_stat_unmatch_result = 1;
7371 return p->skip_stat_unmatch_result;
7372 }
7373
7374 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
7375 {
7376 int i;
7377 struct diff_queue_struct *q = &diff_queued_diff;
7378 struct diff_queue_struct outq = DIFF_QUEUE_INIT;
7379
7380 for (i = 0; i < q->nr; i++) {
7381 struct diff_filepair *p = q->queue[i];
7382
7383 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
7384 diff_q(&outq, p);
7385 else {
7386 /*
7387 * The caller can subtract 1 from skip_stat_unmatch
7388 * to determine how many paths were dirty only
7389 * due to stat info mismatch.
7390 */
7391 if (!diffopt->flags.no_index)
7392 diffopt->skip_stat_unmatch++;
7393 diff_free_filepair(p);
7394 q->queue[i] = NULL;
7395 }
7396 }
7397 free(q->queue);
7398 *q = outq;
7399 }
7400
7401 static int diffnamecmp(const void *a_, const void *b_)
7402 {
7403 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
7404 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
7405 const char *name_a, *name_b;
7406
7407 name_a = a->one ? a->one->path : a->two->path;
7408 name_b = b->one ? b->one->path : b->two->path;
7409 return strcmp(name_a, name_b);
7410 }
7411
7412 void diffcore_fix_diff_index(void)
7413 {
7414 struct diff_queue_struct *q = &diff_queued_diff;
7415 QSORT(q->queue, q->nr, diffnamecmp);
7416 }
7417
7418 void diff_add_if_missing(struct repository *r,
7419 struct oid_array *to_fetch,
7420 const struct diff_filespec *filespec)
7421 {
7422 if (filespec && filespec->oid_valid &&
7423 !S_ISGITLINK(filespec->mode) &&
7424 odb_read_object_info_extended(r->objects, &filespec->oid, NULL,
7425 OBJECT_INFO_FOR_PREFETCH))
7426 oid_array_append(to_fetch, &filespec->oid);
7427 }
7428
7429 void diff_queued_diff_prefetch(void *repository)
7430 {
7431 struct repository *repo = repository;
7432 int i;
7433 struct diff_queue_struct *q = &diff_queued_diff;
7434 struct oid_array to_fetch = OID_ARRAY_INIT;
7435
7436 for (i = 0; i < q->nr; i++) {
7437 struct diff_filepair *p = q->queue[i];
7438
7439 if (!p)
7440 continue;
7441
7442 diff_add_if_missing(repo, &to_fetch, p->one);
7443 diff_add_if_missing(repo, &to_fetch, p->two);
7444 }
7445
7446 /*
7447 * NEEDSWORK: Consider deduplicating the OIDs sent.
7448 */
7449 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
7450
7451 oid_array_clear(&to_fetch);
7452 }
7453
7454 void init_diffstat_widths(struct diff_options *options)
7455 {
7456 options->stat_width = -1; /* use full terminal width */
7457 options->stat_name_width = -1; /* respect diff.statNameWidth config */
7458 options->stat_graph_width = -1; /* respect diff.statGraphWidth config */
7459 }
7460
7461 void diffcore_std(struct diff_options *options)
7462 {
7463 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
7464 DIFF_FORMAT_NUMSTAT |
7465 DIFF_FORMAT_PATCH |
7466 DIFF_FORMAT_SHORTSTAT |
7467 DIFF_FORMAT_DIRSTAT;
7468
7469 /*
7470 * Check if the user requested a blob-data-requiring diff output and/or
7471 * break-rewrite detection (which requires blob data). If yes, prefetch
7472 * the diff pairs.
7473 *
7474 * If no prefetching occurs, diffcore_rename() will prefetch if it
7475 * decides that it needs inexact rename detection.
7476 */
7477 if (repo_has_promisor_remote(options->repo) &&
7478 (options->output_format & output_formats_to_prefetch ||
7479 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
7480 diff_queued_diff_prefetch(options->repo);
7481
7482 /* NOTE please keep the following in sync with diff_tree_combined() */
7483 if (options->skip_stat_unmatch)
7484 diffcore_skip_stat_unmatch(options);
7485 if (!options->found_follow) {
7486 /* See try_to_follow_renames() in tree-diff.c */
7487 if (options->break_opt != -1)
7488 diffcore_break(options->repo,
7489 options->break_opt);
7490 if (options->detect_rename)
7491 diffcore_rename(options);
7492 if (options->break_opt != -1)
7493 diffcore_merge_broken();
7494 }
7495 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
7496 diffcore_pickaxe(options);
7497 if (options->orderfile)
7498 diffcore_order(options->orderfile);
7499 if (options->rotate_to)
7500 diffcore_rotate(options);
7501 if (!options->found_follow && !options->skip_resolving_statuses)
7502 /* See try_to_follow_renames() in tree-diff.c */
7503 diff_resolve_rename_copy();
7504 diffcore_apply_filter(options);
7505
7506 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
7507 options->flags.has_changes = 1;
7508 else
7509 options->flags.has_changes = 0;
7510
7511 options->found_follow = 0;
7512 }
7513
7514 int diff_result_code(struct rev_info *revs)
7515 {
7516 struct diff_options *opt = &revs->diffopt;
7517 int result = 0;
7518
7519 if (revs->remerge_diff) {
7520 tmp_objdir_destroy(revs->remerge_objdir);
7521 revs->remerge_objdir = NULL;
7522 }
7523
7524 diff_warn_rename_limit("diff.renameLimit",
7525 opt->needed_rename_limit,
7526 opt->degraded_cc_to_c);
7527
7528 if (opt->flags.exit_with_status &&
7529 opt->flags.has_changes)
7530 result |= 01;
7531 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
7532 opt->flags.check_failed)
7533 result |= 02;
7534 return result;
7535 }
7536
7537 int diff_can_quit_early(struct diff_options *opt)
7538 {
7539 return (opt->flags.quick &&
7540 !opt->filter &&
7541 opt->flags.has_changes);
7542 }
7543
7544 /*
7545 * Shall changes to this submodule be ignored?
7546 *
7547 * Submodule changes can be configured to be ignored separately for each path,
7548 * but that configuration can be overridden from the command line.
7549 */
7550 static int is_submodule_ignored(const char *path, struct diff_options *options)
7551 {
7552 int ignored = 0;
7553 struct diff_flags orig_flags = options->flags;
7554 if (!options->flags.override_submodule_config)
7555 set_diffopt_flags_from_submodule_config(options, path);
7556 if (options->flags.ignore_submodules)
7557 ignored = 1;
7558 options->flags = orig_flags;
7559 return ignored;
7560 }
7561
7562 void compute_diffstat(struct diff_options *options,
7563 struct diffstat_t *diffstat,
7564 struct diff_queue_struct *q)
7565 {
7566 int i;
7567
7568 memset(diffstat, 0, sizeof(struct diffstat_t));
7569 for (i = 0; i < q->nr; i++) {
7570 struct diff_filepair *p = q->queue[i];
7571 if (check_pair_status(p))
7572 diff_flush_stat(p, options, diffstat);
7573 }
7574 options->found_changes = !!diffstat->nr;
7575 }
7576
7577 struct diff_filepair *diff_queue_addremove(struct diff_queue_struct *queue,
7578 struct diff_options *options,
7579 int addremove, unsigned mode,
7580 const struct object_id *oid,
7581 int oid_valid,
7582 const char *concatpath,
7583 unsigned dirty_submodule)
7584 {
7585 struct diff_filespec *one, *two;
7586 struct diff_filepair *pair;
7587
7588 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7589 return NULL;
7590
7591 /* This may look odd, but it is a preparation for
7592 * feeding "there are unchanged files which should
7593 * not produce diffs, but when you are doing copy
7594 * detection you would need them, so here they are"
7595 * entries to the diff-core. They will be prefixed
7596 * with something like '=' or '*' (I haven't decided
7597 * which but should not make any difference).
7598 * Feeding the same new and old to diff_change()
7599 * also has the same effect.
7600 * Before the final output happens, they are pruned after
7601 * merged into rename/copy pairs as appropriate.
7602 */
7603 if (options->flags.reverse_diff)
7604 addremove = (addremove == '+' ? '-' :
7605 addremove == '-' ? '+' : addremove);
7606
7607 if (options->prefix &&
7608 strncmp(concatpath, options->prefix, options->prefix_length))
7609 return NULL;
7610
7611 one = alloc_filespec(concatpath);
7612 two = alloc_filespec(concatpath);
7613
7614 if (addremove != '+')
7615 fill_filespec(one, oid, oid_valid, mode);
7616 if (addremove != '-') {
7617 fill_filespec(two, oid, oid_valid, mode);
7618 two->dirty_submodule = dirty_submodule;
7619 }
7620
7621 pair = diff_queue(queue, one, two);
7622 if (!options->flags.diff_from_contents)
7623 options->flags.has_changes = 1;
7624
7625 return pair;
7626 }
7627
7628 struct diff_filepair *diff_queue_change(struct diff_queue_struct *queue,
7629 struct diff_options *options,
7630 unsigned old_mode, unsigned new_mode,
7631 const struct object_id *old_oid,
7632 const struct object_id *new_oid,
7633 int old_oid_valid, int new_oid_valid,
7634 const char *concatpath,
7635 unsigned old_dirty_submodule,
7636 unsigned new_dirty_submodule)
7637 {
7638 struct diff_filespec *one, *two;
7639 struct diff_filepair *p;
7640
7641 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7642 is_submodule_ignored(concatpath, options))
7643 return NULL;
7644
7645 if (options->flags.reverse_diff) {
7646 SWAP(old_mode, new_mode);
7647 SWAP(old_oid, new_oid);
7648 SWAP(old_oid_valid, new_oid_valid);
7649 SWAP(old_dirty_submodule, new_dirty_submodule);
7650 }
7651
7652 if (options->prefix &&
7653 strncmp(concatpath, options->prefix, options->prefix_length))
7654 return NULL;
7655
7656 one = alloc_filespec(concatpath);
7657 two = alloc_filespec(concatpath);
7658 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7659 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7660 one->dirty_submodule = old_dirty_submodule;
7661 two->dirty_submodule = new_dirty_submodule;
7662 p = diff_queue(queue, one, two);
7663
7664 if (options->flags.diff_from_contents)
7665 return p;
7666
7667 if (options->flags.quick && options->skip_stat_unmatch &&
7668 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7669 diff_free_filespec_data(p->one);
7670 diff_free_filespec_data(p->two);
7671 return p;
7672 }
7673
7674 options->flags.has_changes = 1;
7675
7676 return p;
7677 }
7678
7679 void diff_addremove(struct diff_options *options, int addremove, unsigned mode,
7680 const struct object_id *oid, int oid_valid,
7681 const char *concatpath, unsigned dirty_submodule)
7682 {
7683 diff_queue_addremove(&diff_queued_diff, options, addremove, mode, oid,
7684 oid_valid, concatpath, dirty_submodule);
7685 }
7686
7687 void diff_change(struct diff_options *options,
7688 unsigned old_mode, unsigned new_mode,
7689 const struct object_id *old_oid,
7690 const struct object_id *new_oid,
7691 int old_oid_valid, int new_oid_valid,
7692 const char *concatpath,
7693 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7694 {
7695 diff_queue_change(&diff_queued_diff, options, old_mode, new_mode,
7696 old_oid, new_oid, old_oid_valid, new_oid_valid,
7697 concatpath, old_dirty_submodule, new_dirty_submodule);
7698 }
7699
7700 void diff_same(struct diff_options *options,
7701 unsigned mode,
7702 const struct object_id *oid,
7703 const char *concatpath)
7704 {
7705 struct diff_filespec *one;
7706
7707 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7708 return;
7709
7710 if (options->prefix &&
7711 strncmp(concatpath, options->prefix, options->prefix_length))
7712 return;
7713
7714 one = alloc_filespec(concatpath);
7715 fill_filespec(one, oid, 1, mode);
7716 one->count++;
7717 diff_queue(&diff_queued_diff, one, one);
7718 }
7719
7720 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7721 {
7722 struct diff_filepair *pair;
7723 struct diff_filespec *one, *two;
7724
7725 if (options->prefix &&
7726 strncmp(path, options->prefix, options->prefix_length))
7727 return NULL;
7728
7729 one = alloc_filespec(path);
7730 two = alloc_filespec(path);
7731 pair = diff_queue(&diff_queued_diff, one, two);
7732 pair->is_unmerged = 1;
7733 return pair;
7734 }
7735
7736 static char *run_textconv(struct repository *r,
7737 const char *pgm,
7738 struct diff_filespec *spec,
7739 size_t *outsize)
7740 {
7741 struct diff_tempfile *temp;
7742 struct child_process child = CHILD_PROCESS_INIT;
7743 struct strbuf buf = STRBUF_INIT;
7744 int err = 0;
7745
7746 temp = prepare_temp_file(r, spec);
7747 strvec_push(&child.args, pgm);
7748 strvec_push(&child.args, temp->name);
7749
7750 child.use_shell = 1;
7751 child.out = -1;
7752 if (start_command(&child)) {
7753 remove_tempfile();
7754 return NULL;
7755 }
7756
7757 if (strbuf_read(&buf, child.out, 0) < 0)
7758 err = error("error reading from textconv command '%s'", pgm);
7759 close(child.out);
7760
7761 if (finish_command(&child) || err) {
7762 strbuf_release(&buf);
7763 remove_tempfile();
7764 return NULL;
7765 }
7766 remove_tempfile();
7767
7768 return strbuf_detach(&buf, outsize);
7769 }
7770
7771 size_t fill_textconv(struct repository *r,
7772 struct userdiff_driver *driver,
7773 struct diff_filespec *df,
7774 char **outbuf)
7775 {
7776 size_t size;
7777
7778 if (!driver) {
7779 if (!DIFF_FILE_VALID(df)) {
7780 *outbuf = (char *) "";
7781 return 0;
7782 }
7783 if (diff_populate_filespec(r, df, NULL))
7784 die("unable to read files to diff");
7785 *outbuf = df->data;
7786 return df->size;
7787 }
7788
7789 if (!driver->textconv)
7790 BUG("fill_textconv called with non-textconv driver");
7791
7792 if (driver->textconv_cache && df->oid_valid) {
7793 *outbuf = notes_cache_get(driver->textconv_cache,
7794 &df->oid,
7795 &size);
7796 if (*outbuf)
7797 return size;
7798 }
7799
7800 *outbuf = run_textconv(r, driver->textconv, df, &size);
7801 if (!*outbuf)
7802 die("unable to read files to diff");
7803
7804 if (driver->textconv_cache && df->oid_valid) {
7805 /* ignore errors, as we might be in a readonly repository */
7806 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7807 size);
7808 /*
7809 * we could save up changes and flush them all at the end,
7810 * but we would need an extra call after all diffing is done.
7811 * Since generating a cache entry is the slow path anyway,
7812 * this extra overhead probably isn't a big deal.
7813 */
7814 notes_cache_write(driver->textconv_cache);
7815 }
7816
7817 return size;
7818 }
7819
7820 int textconv_object(struct repository *r,
7821 const char *path,
7822 unsigned mode,
7823 const struct object_id *oid,
7824 int oid_valid,
7825 char **buf,
7826 unsigned long *buf_size)
7827 {
7828 struct diff_filespec *df;
7829 struct userdiff_driver *textconv;
7830
7831 df = alloc_filespec(path);
7832 fill_filespec(df, oid, oid_valid, mode);
7833 textconv = get_textconv(r, df);
7834 if (!textconv) {
7835 free_filespec(df);
7836 return 0;
7837 }
7838
7839 *buf_size = fill_textconv(r, textconv, df, buf);
7840 free_filespec(df);
7841 return 1;
7842 }
7843
7844 void setup_diff_pager(struct diff_options *opt)
7845 {
7846 /*
7847 * If the user asked for our exit code, then either they want --quiet
7848 * or --exit-code. We should definitely not bother with a pager in the
7849 * former case, as we will generate no output. Since we still properly
7850 * report our exit code even when a pager is run, we _could_ run a
7851 * pager with --exit-code. But since we have not done so historically,
7852 * and because it is easy to find people oneline advising "git diff
7853 * --exit-code" in hooks and other scripts, we do not do so.
7854 */
7855 if (!opt->flags.exit_with_status &&
7856 check_pager_config(the_repository, "diff") != 0)
7857 setup_pager(the_repository);
7858 }