merge-recursive: honor diff.algorithm
[git/gitster.git] / diff.c
blobebb7538e040a716225b9cfb4852378bec07bb66a
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
5 #define USE_THE_REPOSITORY_VARIABLE
7 #include "git-compat-util.h"
8 #include "abspath.h"
9 #include "base85.h"
10 #include "config.h"
11 #include "convert.h"
12 #include "environment.h"
13 #include "gettext.h"
14 #include "tempfile.h"
15 #include "quote.h"
16 #include "diff.h"
17 #include "diffcore.h"
18 #include "delta.h"
19 #include "hex.h"
20 #include "xdiff-interface.h"
21 #include "color.h"
22 #include "run-command.h"
23 #include "utf8.h"
24 #include "object-store-ll.h"
25 #include "userdiff.h"
26 #include "submodule.h"
27 #include "hashmap.h"
28 #include "mem-pool.h"
29 #include "merge-ll.h"
30 #include "string-list.h"
31 #include "strvec.h"
32 #include "graph.h"
33 #include "oid-array.h"
34 #include "packfile.h"
35 #include "pager.h"
36 #include "parse-options.h"
37 #include "help.h"
38 #include "promisor-remote.h"
39 #include "dir.h"
40 #include "object-file.h"
41 #include "object-name.h"
42 #include "read-cache-ll.h"
43 #include "setup.h"
44 #include "strmap.h"
45 #include "ws.h"
47 #ifdef NO_FAST_WORKING_DIRECTORY
48 #define FAST_WORKING_DIRECTORY 0
49 #else
50 #define FAST_WORKING_DIRECTORY 1
51 #endif
53 static int diff_detect_rename_default;
54 static int diff_indent_heuristic = 1;
55 static int diff_rename_limit_default = 1000;
56 static int diff_suppress_blank_empty;
57 static int diff_use_color_default = -1;
58 static int diff_color_moved_default;
59 static int diff_color_moved_ws_default;
60 static int diff_context_default = 3;
61 static int diff_interhunk_context_default;
62 static char *diff_word_regex_cfg;
63 static struct external_diff external_diff_cfg;
64 static char *diff_order_file_cfg;
65 int diff_auto_refresh_index = 1;
66 static int diff_mnemonic_prefix;
67 static int diff_no_prefix;
68 static char *diff_src_prefix;
69 static char *diff_dst_prefix;
70 static int diff_relative;
71 static int diff_stat_name_width;
72 static int diff_stat_graph_width;
73 static int diff_dirstat_permille_default = 30;
74 static struct diff_options default_diff_options;
75 static long diff_algorithm;
76 static unsigned ws_error_highlight_default = WSEH_NEW;
78 static char diff_colors[][COLOR_MAXLEN] = {
79 GIT_COLOR_RESET,
80 GIT_COLOR_NORMAL, /* CONTEXT */
81 GIT_COLOR_BOLD, /* METAINFO */
82 GIT_COLOR_CYAN, /* FRAGINFO */
83 GIT_COLOR_RED, /* OLD */
84 GIT_COLOR_GREEN, /* NEW */
85 GIT_COLOR_YELLOW, /* COMMIT */
86 GIT_COLOR_BG_RED, /* WHITESPACE */
87 GIT_COLOR_NORMAL, /* FUNCINFO */
88 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
89 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
90 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
91 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
92 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
93 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
94 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
95 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
96 GIT_COLOR_FAINT, /* CONTEXT_DIM */
97 GIT_COLOR_FAINT_RED, /* OLD_DIM */
98 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
99 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
100 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
101 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
104 static const char *color_diff_slots[] = {
105 [DIFF_CONTEXT] = "context",
106 [DIFF_METAINFO] = "meta",
107 [DIFF_FRAGINFO] = "frag",
108 [DIFF_FILE_OLD] = "old",
109 [DIFF_FILE_NEW] = "new",
110 [DIFF_COMMIT] = "commit",
111 [DIFF_WHITESPACE] = "whitespace",
112 [DIFF_FUNCINFO] = "func",
113 [DIFF_FILE_OLD_MOVED] = "oldMoved",
114 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
115 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
116 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
117 [DIFF_FILE_NEW_MOVED] = "newMoved",
118 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
119 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
120 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
121 [DIFF_CONTEXT_DIM] = "contextDimmed",
122 [DIFF_FILE_OLD_DIM] = "oldDimmed",
123 [DIFF_FILE_NEW_DIM] = "newDimmed",
124 [DIFF_CONTEXT_BOLD] = "contextBold",
125 [DIFF_FILE_OLD_BOLD] = "oldBold",
126 [DIFF_FILE_NEW_BOLD] = "newBold",
129 define_list_config_array_extra(color_diff_slots, {"plain"});
131 static int parse_diff_color_slot(const char *var)
133 if (!strcasecmp(var, "plain"))
134 return DIFF_CONTEXT;
135 return LOOKUP_CONFIG(color_diff_slots, var);
138 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
139 struct strbuf *errmsg)
141 char *params_copy = xstrdup(params_string);
142 struct string_list params = STRING_LIST_INIT_NODUP;
143 int ret = 0;
144 int i;
146 if (*params_copy)
147 string_list_split_in_place(&params, params_copy, ",", -1);
148 for (i = 0; i < params.nr; i++) {
149 const char *p = params.items[i].string;
150 if (!strcmp(p, "changes")) {
151 options->flags.dirstat_by_line = 0;
152 options->flags.dirstat_by_file = 0;
153 } else if (!strcmp(p, "lines")) {
154 options->flags.dirstat_by_line = 1;
155 options->flags.dirstat_by_file = 0;
156 } else if (!strcmp(p, "files")) {
157 options->flags.dirstat_by_line = 0;
158 options->flags.dirstat_by_file = 1;
159 } else if (!strcmp(p, "noncumulative")) {
160 options->flags.dirstat_cumulative = 0;
161 } else if (!strcmp(p, "cumulative")) {
162 options->flags.dirstat_cumulative = 1;
163 } else if (isdigit(*p)) {
164 char *end;
165 int permille = strtoul(p, &end, 10) * 10;
166 if (*end == '.' && isdigit(*++end)) {
167 /* only use first digit */
168 permille += *end - '0';
169 /* .. and ignore any further digits */
170 while (isdigit(*++end))
171 ; /* nothing */
173 if (!*end)
174 options->dirstat_permille = permille;
175 else {
176 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
178 ret++;
180 } else {
181 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
182 ret++;
186 string_list_clear(&params, 0);
187 free(params_copy);
188 return ret;
191 static int parse_submodule_params(struct diff_options *options, const char *value)
193 if (!strcmp(value, "log"))
194 options->submodule_format = DIFF_SUBMODULE_LOG;
195 else if (!strcmp(value, "short"))
196 options->submodule_format = DIFF_SUBMODULE_SHORT;
197 else if (!strcmp(value, "diff"))
198 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
200 * Please update $__git_diff_submodule_formats in
201 * git-completion.bash when you add new formats.
203 else
204 return -1;
205 return 0;
208 int git_config_rename(const char *var, const char *value)
210 if (!value)
211 return DIFF_DETECT_RENAME;
212 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
213 return DIFF_DETECT_COPY;
214 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
217 long parse_algorithm_value(const char *value)
219 if (!value)
220 return -1;
221 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
222 return 0;
223 else if (!strcasecmp(value, "minimal"))
224 return XDF_NEED_MINIMAL;
225 else if (!strcasecmp(value, "patience"))
226 return XDF_PATIENCE_DIFF;
227 else if (!strcasecmp(value, "histogram"))
228 return XDF_HISTOGRAM_DIFF;
230 * Please update $__git_diff_algorithms in git-completion.bash
231 * when you add new algorithms.
233 return -1;
236 static int parse_one_token(const char **arg, const char *token)
238 const char *rest;
239 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
240 *arg = rest;
241 return 1;
243 return 0;
246 static int parse_ws_error_highlight(const char *arg)
248 const char *orig_arg = arg;
249 unsigned val = 0;
251 while (*arg) {
252 if (parse_one_token(&arg, "none"))
253 val = 0;
254 else if (parse_one_token(&arg, "default"))
255 val = WSEH_NEW;
256 else if (parse_one_token(&arg, "all"))
257 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
258 else if (parse_one_token(&arg, "new"))
259 val |= WSEH_NEW;
260 else if (parse_one_token(&arg, "old"))
261 val |= WSEH_OLD;
262 else if (parse_one_token(&arg, "context"))
263 val |= WSEH_CONTEXT;
264 else {
265 return -1 - (int)(arg - orig_arg);
267 if (*arg)
268 arg++;
270 return val;
274 * These are to give UI layer defaults.
275 * The core-level commands such as git-diff-files should
276 * never be affected by the setting of diff.renames
277 * the user happens to have in the configuration file.
279 void init_diff_ui_defaults(void)
281 diff_detect_rename_default = DIFF_DETECT_RENAME;
284 int git_diff_heuristic_config(const char *var, const char *value,
285 void *cb UNUSED)
287 if (!strcmp(var, "diff.indentheuristic"))
288 diff_indent_heuristic = git_config_bool(var, value);
289 return 0;
292 static int parse_color_moved(const char *arg)
294 switch (git_parse_maybe_bool(arg)) {
295 case 0:
296 return COLOR_MOVED_NO;
297 case 1:
298 return COLOR_MOVED_DEFAULT;
299 default:
300 break;
303 if (!strcmp(arg, "no"))
304 return COLOR_MOVED_NO;
305 else if (!strcmp(arg, "plain"))
306 return COLOR_MOVED_PLAIN;
307 else if (!strcmp(arg, "blocks"))
308 return COLOR_MOVED_BLOCKS;
309 else if (!strcmp(arg, "zebra"))
310 return COLOR_MOVED_ZEBRA;
311 else if (!strcmp(arg, "default"))
312 return COLOR_MOVED_DEFAULT;
313 else if (!strcmp(arg, "dimmed-zebra"))
314 return COLOR_MOVED_ZEBRA_DIM;
315 else if (!strcmp(arg, "dimmed_zebra"))
316 return COLOR_MOVED_ZEBRA_DIM;
317 else
318 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
321 static unsigned parse_color_moved_ws(const char *arg)
323 int ret = 0;
324 struct string_list l = STRING_LIST_INIT_DUP;
325 struct string_list_item *i;
327 string_list_split(&l, arg, ',', -1);
329 for_each_string_list_item(i, &l) {
330 struct strbuf sb = STRBUF_INIT;
331 strbuf_addstr(&sb, i->string);
332 strbuf_trim(&sb);
334 if (!strcmp(sb.buf, "no"))
335 ret = 0;
336 else if (!strcmp(sb.buf, "ignore-space-change"))
337 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
338 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
339 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
340 else if (!strcmp(sb.buf, "ignore-all-space"))
341 ret |= XDF_IGNORE_WHITESPACE;
342 else if (!strcmp(sb.buf, "allow-indentation-change"))
343 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
344 else {
345 ret |= COLOR_MOVED_WS_ERROR;
346 error(_("unknown color-moved-ws mode '%s', possible values are 'ignore-space-change', 'ignore-space-at-eol', 'ignore-all-space', 'allow-indentation-change'"), sb.buf);
349 strbuf_release(&sb);
352 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
353 (ret & XDF_WHITESPACE_FLAGS)) {
354 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
355 ret |= COLOR_MOVED_WS_ERROR;
358 string_list_clear(&l, 0);
360 return ret;
363 int git_diff_ui_config(const char *var, const char *value,
364 const struct config_context *ctx, void *cb)
366 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
367 diff_use_color_default = git_config_colorbool(var, value);
368 return 0;
370 if (!strcmp(var, "diff.colormoved")) {
371 int cm = parse_color_moved(value);
372 if (cm < 0)
373 return -1;
374 diff_color_moved_default = cm;
375 return 0;
377 if (!strcmp(var, "diff.colormovedws")) {
378 unsigned cm;
379 if (!value)
380 return config_error_nonbool(var);
381 cm = parse_color_moved_ws(value);
382 if (cm & COLOR_MOVED_WS_ERROR)
383 return -1;
384 diff_color_moved_ws_default = cm;
385 return 0;
387 if (!strcmp(var, "diff.context")) {
388 diff_context_default = git_config_int(var, value, ctx->kvi);
389 if (diff_context_default < 0)
390 return -1;
391 return 0;
393 if (!strcmp(var, "diff.interhunkcontext")) {
394 diff_interhunk_context_default = git_config_int(var, value,
395 ctx->kvi);
396 if (diff_interhunk_context_default < 0)
397 return -1;
398 return 0;
400 if (!strcmp(var, "diff.renames")) {
401 diff_detect_rename_default = git_config_rename(var, value);
402 return 0;
404 if (!strcmp(var, "diff.autorefreshindex")) {
405 diff_auto_refresh_index = git_config_bool(var, value);
406 return 0;
408 if (!strcmp(var, "diff.mnemonicprefix")) {
409 diff_mnemonic_prefix = git_config_bool(var, value);
410 return 0;
412 if (!strcmp(var, "diff.noprefix")) {
413 diff_no_prefix = git_config_bool(var, value);
414 return 0;
416 if (!strcmp(var, "diff.srcprefix")) {
417 FREE_AND_NULL(diff_src_prefix);
418 return git_config_string(&diff_src_prefix, var, value);
420 if (!strcmp(var, "diff.dstprefix")) {
421 FREE_AND_NULL(diff_dst_prefix);
422 return git_config_string(&diff_dst_prefix, var, value);
424 if (!strcmp(var, "diff.relative")) {
425 diff_relative = git_config_bool(var, value);
426 return 0;
428 if (!strcmp(var, "diff.statnamewidth")) {
429 diff_stat_name_width = git_config_int(var, value, ctx->kvi);
430 return 0;
432 if (!strcmp(var, "diff.statgraphwidth")) {
433 diff_stat_graph_width = git_config_int(var, value, ctx->kvi);
434 return 0;
436 if (!strcmp(var, "diff.external"))
437 return git_config_string(&external_diff_cfg.cmd, var, value);
438 if (!strcmp(var, "diff.trustexitcode")) {
439 external_diff_cfg.trust_exit_code = git_config_bool(var, value);
440 return 0;
442 if (!strcmp(var, "diff.wordregex"))
443 return git_config_string(&diff_word_regex_cfg, var, value);
444 if (!strcmp(var, "diff.orderfile"))
445 return git_config_pathname(&diff_order_file_cfg, var, value);
447 if (!strcmp(var, "diff.ignoresubmodules")) {
448 if (!value)
449 return config_error_nonbool(var);
450 handle_ignore_submodules_arg(&default_diff_options, value);
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;
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;
472 if (git_color_config(var, value, cb) < 0)
473 return -1;
475 return git_diff_basic_config(var, value, ctx, cb);
478 int git_diff_basic_config(const char *var, const char *value,
479 const struct config_context *ctx, void *cb)
481 const char *name;
483 if (!strcmp(var, "diff.renamelimit")) {
484 diff_rename_limit_default = git_config_int(var, value, ctx->kvi);
485 return 0;
488 if (userdiff_config(var, value) < 0)
489 return -1;
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]);
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;
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;
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;
534 if (git_diff_heuristic_config(var, value, cb) < 0)
535 return -1;
537 return git_default_config(var, value, ctx, cb);
540 static char *quote_two(const char *one, const char *two)
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;
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);
555 return strbuf_detach(&res, NULL);
558 static const struct external_diff *external_diff(void)
560 static struct external_diff external_diff_env, *external_diff_ptr;
561 static int done_preparing = 0;
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;
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".
581 static struct diff_tempfile {
583 * filename external diff should read from, or NULL if this
584 * entry is currently not in use:
586 const char *name;
588 char hex[GIT_MAX_HEXSZ + 1];
589 char mode[10];
592 * If this diff_tempfile instance refers to a temporary file,
593 * this tempfile object is used to manage its lifetime.
595 struct tempfile *tempfile;
596 } diff_temp[2];
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 const char **label_path;
606 struct diff_words_data *diff_words;
607 struct diff_options *opt;
608 struct strbuf *header;
611 static int count_lines(const char *data, int size)
613 int count, ch, completely_empty = 1, nl_just_seen = 0;
614 count = 0;
615 while (0 < size--) {
616 ch = *data++;
617 if (ch == '\n') {
618 count++;
619 nl_just_seen = 1;
620 completely_empty = 0;
622 else {
623 nl_just_seen = 0;
624 completely_empty = 0;
627 if (completely_empty)
628 return 0;
629 if (!nl_just_seen)
630 count++; /* no trailing newline */
631 return count;
634 static int fill_mmfile(struct repository *r, mmfile_t *mf,
635 struct diff_filespec *one)
637 if (!DIFF_FILE_VALID(one)) {
638 mf->ptr = (char *)""; /* does not matter */
639 mf->size = 0;
640 return 0;
642 else if (diff_populate_filespec(r, one, NULL))
643 return -1;
645 mf->ptr = one->data;
646 mf->size = one->size;
647 return 0;
650 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
651 static unsigned long diff_filespec_size(struct repository *r,
652 struct diff_filespec *one)
654 struct diff_populate_filespec_options dpf_options = {
655 .check_size_only = 1,
658 if (!DIFF_FILE_VALID(one))
659 return 0;
660 diff_populate_filespec(r, one, &dpf_options);
661 return one->size;
664 static int count_trailing_blank(mmfile_t *mf)
666 char *ptr = mf->ptr;
667 long size = mf->size;
668 int cnt = 0;
670 if (!size)
671 return cnt;
672 ptr += size - 1; /* pointing at the very end */
673 if (*ptr != '\n')
674 ; /* incomplete line */
675 else
676 ptr--; /* skip the last LF */
677 while (mf->ptr < ptr) {
678 char *prev_eol;
679 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
680 if (*prev_eol == '\n')
681 break;
682 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
683 break;
684 cnt++;
685 ptr = prev_eol - 1;
687 return cnt;
690 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
691 struct emit_callback *ecbdata)
693 int l1, l2, at;
694 l1 = count_trailing_blank(mf1);
695 l2 = count_trailing_blank(mf2);
696 if (l2 <= l1) {
697 ecbdata->blank_at_eof_in_preimage = 0;
698 ecbdata->blank_at_eof_in_postimage = 0;
699 return;
701 at = count_lines(mf1->ptr, mf1->size);
702 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
704 at = count_lines(mf2->ptr, mf2->size);
705 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
708 static void emit_line_0(struct diff_options *o,
709 const char *set_sign, const char *set, unsigned reverse, const char *reset,
710 int first, const char *line, int len)
712 int has_trailing_newline, has_trailing_carriage_return;
713 int needs_reset = 0; /* at the end of the line */
714 FILE *file = o->file;
716 fputs(diff_line_prefix(o), file);
718 has_trailing_newline = (len > 0 && line[len-1] == '\n');
719 if (has_trailing_newline)
720 len--;
722 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
723 if (has_trailing_carriage_return)
724 len--;
726 if (!len && !first)
727 goto end_of_line;
729 if (reverse && want_color(o->use_color)) {
730 fputs(GIT_COLOR_REVERSE, file);
731 needs_reset = 1;
734 if (set_sign) {
735 fputs(set_sign, file);
736 needs_reset = 1;
739 if (first)
740 fputc(first, file);
742 if (!len)
743 goto end_of_line;
745 if (set) {
746 if (set_sign && set != set_sign)
747 fputs(reset, file);
748 fputs(set, file);
749 needs_reset = 1;
751 fwrite(line, len, 1, file);
752 needs_reset = 1; /* 'line' may contain color codes. */
754 end_of_line:
755 if (needs_reset)
756 fputs(reset, file);
757 if (has_trailing_carriage_return)
758 fputc('\r', file);
759 if (has_trailing_newline)
760 fputc('\n', file);
763 static void emit_line(struct diff_options *o, const char *set, const char *reset,
764 const char *line, int len)
766 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
769 enum diff_symbol {
770 DIFF_SYMBOL_BINARY_DIFF_HEADER,
771 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
772 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
773 DIFF_SYMBOL_BINARY_DIFF_BODY,
774 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
775 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
776 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
777 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
778 DIFF_SYMBOL_STATS_LINE,
779 DIFF_SYMBOL_WORD_DIFF,
780 DIFF_SYMBOL_STAT_SEP,
781 DIFF_SYMBOL_SUMMARY,
782 DIFF_SYMBOL_SUBMODULE_ADD,
783 DIFF_SYMBOL_SUBMODULE_DEL,
784 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
785 DIFF_SYMBOL_SUBMODULE_MODIFIED,
786 DIFF_SYMBOL_SUBMODULE_HEADER,
787 DIFF_SYMBOL_SUBMODULE_ERROR,
788 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
789 DIFF_SYMBOL_REWRITE_DIFF,
790 DIFF_SYMBOL_BINARY_FILES,
791 DIFF_SYMBOL_HEADER,
792 DIFF_SYMBOL_FILEPAIR_PLUS,
793 DIFF_SYMBOL_FILEPAIR_MINUS,
794 DIFF_SYMBOL_WORDS_PORCELAIN,
795 DIFF_SYMBOL_WORDS,
796 DIFF_SYMBOL_CONTEXT,
797 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
798 DIFF_SYMBOL_PLUS,
799 DIFF_SYMBOL_MINUS,
800 DIFF_SYMBOL_NO_LF_EOF,
801 DIFF_SYMBOL_CONTEXT_FRAGINFO,
802 DIFF_SYMBOL_CONTEXT_MARKER,
803 DIFF_SYMBOL_SEPARATOR
806 * Flags for content lines:
807 * 0..12 are whitespace rules
808 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
809 * 16 is marking if the line is blank at EOF
811 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
812 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
813 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
814 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
815 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
818 * This struct is used when we need to buffer the output of the diff output.
820 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
821 * into the pre/post image file. This pointer could be a union with the
822 * line pointer. By storing an offset into the file instead of the literal line,
823 * we can decrease the memory footprint for the buffered output. At first we
824 * may want to only have indirection for the content lines, but we could also
825 * enhance the state for emitting prefabricated lines, e.g. the similarity
826 * score line or hunk/file headers would only need to store a number or path
827 * and then the output can be constructed later on depending on state.
829 struct emitted_diff_symbol {
830 const char *line;
831 int len;
832 int flags;
833 int indent_off; /* Offset to first non-whitespace character */
834 int indent_width; /* The visual width of the indentation */
835 unsigned id;
836 enum diff_symbol s;
838 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
840 struct emitted_diff_symbols {
841 struct emitted_diff_symbol *buf;
842 int nr, alloc;
844 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
846 static void append_emitted_diff_symbol(struct diff_options *o,
847 struct emitted_diff_symbol *e)
849 struct emitted_diff_symbol *f;
851 ALLOC_GROW(o->emitted_symbols->buf,
852 o->emitted_symbols->nr + 1,
853 o->emitted_symbols->alloc);
854 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
856 memcpy(f, e, sizeof(struct emitted_diff_symbol));
857 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
860 static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
862 if (!e)
863 return;
864 free(e->buf);
865 free(e);
868 struct moved_entry {
869 const struct emitted_diff_symbol *es;
870 struct moved_entry *next_line;
871 struct moved_entry *next_match;
874 struct moved_block {
875 struct moved_entry *match;
876 int wsd; /* The whitespace delta of this block */
879 #define INDENT_BLANKLINE INT_MIN
881 static void fill_es_indent_data(struct emitted_diff_symbol *es)
883 unsigned int off = 0, i;
884 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
885 const char *s = es->line;
886 const int len = es->len;
888 /* skip any \v \f \r at start of indentation */
889 while (s[off] == '\f' || s[off] == '\v' ||
890 (s[off] == '\r' && off < len - 1))
891 off++;
893 /* calculate the visual width of indentation */
894 while(1) {
895 if (s[off] == ' ') {
896 width++;
897 off++;
898 } else if (s[off] == '\t') {
899 width += tab_width - (width % tab_width);
900 while (s[++off] == '\t')
901 width += tab_width;
902 } else {
903 break;
907 /* check if this line is blank */
908 for (i = off; i < len; i++)
909 if (!isspace(s[i]))
910 break;
912 if (i == len) {
913 es->indent_width = INDENT_BLANKLINE;
914 es->indent_off = len;
915 } else {
916 es->indent_off = off;
917 es->indent_width = width;
921 static int compute_ws_delta(const struct emitted_diff_symbol *a,
922 const struct emitted_diff_symbol *b)
924 int a_width = a->indent_width,
925 b_width = b->indent_width;
927 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
928 return INDENT_BLANKLINE;
930 return a_width - b_width;
933 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
934 const struct emitted_diff_symbol *l,
935 struct moved_block *pmb)
937 int a_width = cur->es->indent_width, b_width = l->indent_width;
938 int delta;
940 /* The text of each line must match */
941 if (cur->es->id != l->id)
942 return 1;
945 * If 'l' and 'cur' are both blank then we don't need to check the
946 * indent. We only need to check cur as we know the strings match.
947 * */
948 if (a_width == INDENT_BLANKLINE)
949 return 0;
952 * The indent changes of the block are known and stored in pmb->wsd;
953 * however we need to check if the indent changes of the current line
954 * match those of the current block.
956 delta = b_width - a_width;
959 * If the previous lines of this block were all blank then set its
960 * whitespace delta.
962 if (pmb->wsd == INDENT_BLANKLINE)
963 pmb->wsd = delta;
965 return delta != pmb->wsd;
968 struct interned_diff_symbol {
969 struct hashmap_entry ent;
970 struct emitted_diff_symbol *es;
973 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
974 const struct hashmap_entry *eptr,
975 const struct hashmap_entry *entry_or_key,
976 const void *keydata UNUSED)
978 const struct diff_options *diffopt = hashmap_cmp_fn_data;
979 const struct emitted_diff_symbol *a, *b;
980 unsigned flags = diffopt->color_moved_ws_handling
981 & XDF_WHITESPACE_FLAGS;
983 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
984 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
986 return !xdiff_compare_lines(a->line + a->indent_off,
987 a->len - a->indent_off,
988 b->line + b->indent_off,
989 b->len - b->indent_off, flags);
992 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
993 struct interned_diff_symbol *s)
995 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
996 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
997 l->len - l->indent_off, flags);
999 hashmap_entry_init(&s->ent, hash);
1000 s->es = l;
1003 struct moved_entry_list {
1004 struct moved_entry *add, *del;
1007 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
1008 struct mem_pool *entry_mem_pool)
1010 struct moved_entry *prev_line = NULL;
1011 struct mem_pool interned_pool;
1012 struct hashmap interned_map;
1013 struct moved_entry_list *entry_list = NULL;
1014 size_t entry_list_alloc = 0;
1015 unsigned id = 0;
1016 int n;
1018 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
1019 mem_pool_init(&interned_pool, 1024 * 1024);
1021 for (n = 0; n < o->emitted_symbols->nr; n++) {
1022 struct interned_diff_symbol key;
1023 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1024 struct interned_diff_symbol *s;
1025 struct moved_entry *entry;
1027 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
1028 prev_line = NULL;
1029 continue;
1032 if (o->color_moved_ws_handling &
1033 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1034 fill_es_indent_data(l);
1036 prepare_entry(o, l, &key);
1037 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
1038 if (s) {
1039 l->id = s->es->id;
1040 } else {
1041 l->id = id;
1042 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
1043 hashmap_add(&interned_map,
1044 memcpy(mem_pool_alloc(&interned_pool,
1045 sizeof(key)),
1046 &key, sizeof(key)));
1048 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
1049 entry->es = l;
1050 entry->next_line = NULL;
1051 if (prev_line && prev_line->es->s == l->s)
1052 prev_line->next_line = entry;
1053 prev_line = entry;
1054 if (l->s == DIFF_SYMBOL_PLUS) {
1055 entry->next_match = entry_list[l->id].add;
1056 entry_list[l->id].add = entry;
1057 } else {
1058 entry->next_match = entry_list[l->id].del;
1059 entry_list[l->id].del = entry;
1063 hashmap_clear(&interned_map);
1064 mem_pool_discard(&interned_pool, 0);
1066 return entry_list;
1069 static void pmb_advance_or_null(struct diff_options *o,
1070 struct emitted_diff_symbol *l,
1071 struct moved_block *pmb,
1072 int *pmb_nr)
1074 int i, j;
1076 for (i = 0, j = 0; i < *pmb_nr; i++) {
1077 int match;
1078 struct moved_entry *prev = pmb[i].match;
1079 struct moved_entry *cur = (prev && prev->next_line) ?
1080 prev->next_line : NULL;
1082 if (o->color_moved_ws_handling &
1083 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1084 match = cur &&
1085 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1086 else
1087 match = cur && cur->es->id == l->id;
1089 if (match) {
1090 pmb[j] = pmb[i];
1091 pmb[j++].match = cur;
1094 *pmb_nr = j;
1097 static void fill_potential_moved_blocks(struct diff_options *o,
1098 struct moved_entry *match,
1099 struct emitted_diff_symbol *l,
1100 struct moved_block **pmb_p,
1101 int *pmb_alloc_p, int *pmb_nr_p)
1104 struct moved_block *pmb = *pmb_p;
1105 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1108 * The current line is the start of a new block.
1109 * Setup the set of potential blocks.
1111 for (; match; match = match->next_match) {
1112 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1113 if (o->color_moved_ws_handling &
1114 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1115 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1116 else
1117 pmb[pmb_nr].wsd = 0;
1118 pmb[pmb_nr++].match = match;
1121 *pmb_p = pmb;
1122 *pmb_alloc_p = pmb_alloc;
1123 *pmb_nr_p = pmb_nr;
1127 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1129 * Otherwise, if the last block has fewer alphanumeric characters than
1130 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1131 * that block.
1133 * The last block consists of the (n - block_length)'th line up to but not
1134 * including the nth line.
1136 * Returns 0 if the last block is empty or is unset by this function, non zero
1137 * otherwise.
1139 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1140 * Think of a way to unify them.
1142 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1143 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1144 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1146 int i, alnum_count = 0;
1147 if (o->color_moved == COLOR_MOVED_PLAIN)
1148 return block_length;
1149 for (i = 1; i < block_length + 1; i++) {
1150 const char *c = o->emitted_symbols->buf[n - i].line;
1151 for (; *c; c++) {
1152 if (!isalnum(*c))
1153 continue;
1154 alnum_count++;
1155 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1156 return 1;
1159 for (i = 1; i < block_length + 1; i++)
1160 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1161 return 0;
1164 /* Find blocks of moved code, delegate actual coloring decision to helper */
1165 static void mark_color_as_moved(struct diff_options *o,
1166 struct moved_entry_list *entry_list)
1168 struct moved_block *pmb = NULL; /* potentially moved blocks */
1169 int pmb_nr = 0, pmb_alloc = 0;
1170 int n, flipped_block = 0, block_length = 0;
1171 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1174 for (n = 0; n < o->emitted_symbols->nr; n++) {
1175 struct moved_entry *match = NULL;
1176 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1178 switch (l->s) {
1179 case DIFF_SYMBOL_PLUS:
1180 match = entry_list[l->id].del;
1181 break;
1182 case DIFF_SYMBOL_MINUS:
1183 match = entry_list[l->id].add;
1184 break;
1185 default:
1186 flipped_block = 0;
1189 if (pmb_nr && (!match || l->s != moved_symbol)) {
1190 if (!adjust_last_block(o, n, block_length) &&
1191 block_length > 1) {
1193 * Rewind in case there is another match
1194 * starting at the second line of the block
1196 match = NULL;
1197 n -= block_length;
1199 pmb_nr = 0;
1200 block_length = 0;
1201 flipped_block = 0;
1203 if (!match) {
1204 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1205 continue;
1208 if (o->color_moved == COLOR_MOVED_PLAIN) {
1209 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1210 continue;
1213 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1215 if (pmb_nr == 0) {
1216 int contiguous = adjust_last_block(o, n, block_length);
1218 if (!contiguous && block_length > 1)
1220 * Rewind in case there is another match
1221 * starting at the second line of the block
1223 n -= block_length;
1224 else
1225 fill_potential_moved_blocks(o, match, l,
1226 &pmb, &pmb_alloc,
1227 &pmb_nr);
1229 if (contiguous && pmb_nr && moved_symbol == l->s)
1230 flipped_block = (flipped_block + 1) % 2;
1231 else
1232 flipped_block = 0;
1234 if (pmb_nr)
1235 moved_symbol = l->s;
1236 else
1237 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1239 block_length = 0;
1242 if (pmb_nr) {
1243 block_length++;
1244 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1245 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1246 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1249 adjust_last_block(o, n, block_length);
1251 free(pmb);
1254 static void dim_moved_lines(struct diff_options *o)
1256 int n;
1257 for (n = 0; n < o->emitted_symbols->nr; n++) {
1258 struct emitted_diff_symbol *prev = (n != 0) ?
1259 &o->emitted_symbols->buf[n - 1] : NULL;
1260 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1261 struct emitted_diff_symbol *next =
1262 (n < o->emitted_symbols->nr - 1) ?
1263 &o->emitted_symbols->buf[n + 1] : NULL;
1265 /* Not a plus or minus line? */
1266 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1267 continue;
1269 /* Not a moved line? */
1270 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1271 continue;
1274 * If prev or next are not a plus or minus line,
1275 * pretend they don't exist
1277 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1278 prev->s != DIFF_SYMBOL_MINUS)
1279 prev = NULL;
1280 if (next && next->s != DIFF_SYMBOL_PLUS &&
1281 next->s != DIFF_SYMBOL_MINUS)
1282 next = NULL;
1284 /* Inside a block? */
1285 if ((prev &&
1286 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1287 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1288 (next &&
1289 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1290 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1291 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1292 continue;
1295 /* Check if we are at an interesting bound: */
1296 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1297 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1298 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1299 continue;
1300 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1301 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1302 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1303 continue;
1306 * The boundary to prev and next are not interesting,
1307 * so this line is not interesting as a whole
1309 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1313 static void emit_line_ws_markup(struct diff_options *o,
1314 const char *set_sign, const char *set,
1315 const char *reset,
1316 int sign_index, const char *line, int len,
1317 unsigned ws_rule, int blank_at_eof)
1319 const char *ws = NULL;
1320 int sign = o->output_indicators[sign_index];
1322 if (o->ws_error_highlight & ws_rule) {
1323 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1324 if (!*ws)
1325 ws = NULL;
1328 if (!ws && !set_sign)
1329 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1330 else if (!ws) {
1331 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1332 } else if (blank_at_eof)
1333 /* Blank line at EOF - paint '+' as well */
1334 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1335 else {
1336 /* Emit just the prefix, then the rest. */
1337 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1338 sign, "", 0);
1339 ws_check_emit(line, len, ws_rule,
1340 o->file, set, reset, ws);
1344 static void emit_diff_symbol_from_struct(struct diff_options *o,
1345 struct emitted_diff_symbol *eds)
1347 static const char *nneof = " No newline at end of file\n";
1348 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1350 enum diff_symbol s = eds->s;
1351 const char *line = eds->line;
1352 int len = eds->len;
1353 unsigned flags = eds->flags;
1355 switch (s) {
1356 case DIFF_SYMBOL_NO_LF_EOF:
1357 context = diff_get_color_opt(o, DIFF_CONTEXT);
1358 reset = diff_get_color_opt(o, DIFF_RESET);
1359 putc('\n', o->file);
1360 emit_line_0(o, context, NULL, 0, reset, '\\',
1361 nneof, strlen(nneof));
1362 break;
1363 case DIFF_SYMBOL_SUBMODULE_HEADER:
1364 case DIFF_SYMBOL_SUBMODULE_ERROR:
1365 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1366 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1367 case DIFF_SYMBOL_SUMMARY:
1368 case DIFF_SYMBOL_STATS_LINE:
1369 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1370 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1371 emit_line(o, "", "", line, len);
1372 break;
1373 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1374 case DIFF_SYMBOL_CONTEXT_MARKER:
1375 context = diff_get_color_opt(o, DIFF_CONTEXT);
1376 reset = diff_get_color_opt(o, DIFF_RESET);
1377 emit_line(o, context, reset, line, len);
1378 break;
1379 case DIFF_SYMBOL_SEPARATOR:
1380 fprintf(o->file, "%s%c",
1381 diff_line_prefix(o),
1382 o->line_termination);
1383 break;
1384 case DIFF_SYMBOL_CONTEXT:
1385 set = diff_get_color_opt(o, DIFF_CONTEXT);
1386 reset = diff_get_color_opt(o, DIFF_RESET);
1387 set_sign = NULL;
1388 if (o->flags.dual_color_diffed_diffs) {
1389 char c = !len ? 0 : line[0];
1391 if (c == '+')
1392 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1393 else if (c == '@')
1394 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1395 else if (c == '-')
1396 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1398 emit_line_ws_markup(o, set_sign, set, reset,
1399 OUTPUT_INDICATOR_CONTEXT, line, len,
1400 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1401 break;
1402 case DIFF_SYMBOL_PLUS:
1403 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1404 DIFF_SYMBOL_MOVED_LINE_ALT |
1405 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1406 case DIFF_SYMBOL_MOVED_LINE |
1407 DIFF_SYMBOL_MOVED_LINE_ALT |
1408 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1409 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1410 break;
1411 case DIFF_SYMBOL_MOVED_LINE |
1412 DIFF_SYMBOL_MOVED_LINE_ALT:
1413 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1414 break;
1415 case DIFF_SYMBOL_MOVED_LINE |
1416 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1417 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1418 break;
1419 case DIFF_SYMBOL_MOVED_LINE:
1420 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1421 break;
1422 default:
1423 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1425 reset = diff_get_color_opt(o, DIFF_RESET);
1426 if (!o->flags.dual_color_diffed_diffs)
1427 set_sign = NULL;
1428 else {
1429 char c = !len ? 0 : line[0];
1431 set_sign = set;
1432 if (c == '-')
1433 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1434 else if (c == '@')
1435 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1436 else if (c == '+')
1437 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1438 else
1439 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1440 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1442 emit_line_ws_markup(o, set_sign, set, reset,
1443 OUTPUT_INDICATOR_NEW, line, len,
1444 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1445 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1446 break;
1447 case DIFF_SYMBOL_MINUS:
1448 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1449 DIFF_SYMBOL_MOVED_LINE_ALT |
1450 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1451 case DIFF_SYMBOL_MOVED_LINE |
1452 DIFF_SYMBOL_MOVED_LINE_ALT |
1453 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1454 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1455 break;
1456 case DIFF_SYMBOL_MOVED_LINE |
1457 DIFF_SYMBOL_MOVED_LINE_ALT:
1458 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1459 break;
1460 case DIFF_SYMBOL_MOVED_LINE |
1461 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1462 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1463 break;
1464 case DIFF_SYMBOL_MOVED_LINE:
1465 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1466 break;
1467 default:
1468 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1470 reset = diff_get_color_opt(o, DIFF_RESET);
1471 if (!o->flags.dual_color_diffed_diffs)
1472 set_sign = NULL;
1473 else {
1474 char c = !len ? 0 : line[0];
1476 set_sign = set;
1477 if (c == '+')
1478 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1479 else if (c == '@')
1480 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1481 else if (c == '-')
1482 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1483 else
1484 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1486 emit_line_ws_markup(o, set_sign, set, reset,
1487 OUTPUT_INDICATOR_OLD, line, len,
1488 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1489 break;
1490 case DIFF_SYMBOL_WORDS_PORCELAIN:
1491 context = diff_get_color_opt(o, DIFF_CONTEXT);
1492 reset = diff_get_color_opt(o, DIFF_RESET);
1493 emit_line(o, context, reset, line, len);
1494 fputs("~\n", o->file);
1495 break;
1496 case DIFF_SYMBOL_WORDS:
1497 context = diff_get_color_opt(o, DIFF_CONTEXT);
1498 reset = diff_get_color_opt(o, DIFF_RESET);
1500 * Skip the prefix character, if any. With
1501 * diff_suppress_blank_empty, there may be
1502 * none.
1504 if (line[0] != '\n') {
1505 line++;
1506 len--;
1508 emit_line(o, context, reset, line, len);
1509 break;
1510 case DIFF_SYMBOL_FILEPAIR_PLUS:
1511 meta = diff_get_color_opt(o, DIFF_METAINFO);
1512 reset = diff_get_color_opt(o, DIFF_RESET);
1513 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1514 line, reset,
1515 strchr(line, ' ') ? "\t" : "");
1516 break;
1517 case DIFF_SYMBOL_FILEPAIR_MINUS:
1518 meta = diff_get_color_opt(o, DIFF_METAINFO);
1519 reset = diff_get_color_opt(o, DIFF_RESET);
1520 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1521 line, reset,
1522 strchr(line, ' ') ? "\t" : "");
1523 break;
1524 case DIFF_SYMBOL_BINARY_FILES:
1525 case DIFF_SYMBOL_HEADER:
1526 fprintf(o->file, "%s", line);
1527 break;
1528 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1529 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1530 break;
1531 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1532 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1533 break;
1534 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1535 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1536 break;
1537 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1538 fputs(diff_line_prefix(o), o->file);
1539 fputc('\n', o->file);
1540 break;
1541 case DIFF_SYMBOL_REWRITE_DIFF:
1542 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1543 reset = diff_get_color_opt(o, DIFF_RESET);
1544 emit_line(o, fraginfo, reset, line, len);
1545 break;
1546 case DIFF_SYMBOL_SUBMODULE_ADD:
1547 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1548 reset = diff_get_color_opt(o, DIFF_RESET);
1549 emit_line(o, set, reset, line, len);
1550 break;
1551 case DIFF_SYMBOL_SUBMODULE_DEL:
1552 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1553 reset = diff_get_color_opt(o, DIFF_RESET);
1554 emit_line(o, set, reset, line, len);
1555 break;
1556 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1557 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1558 diff_line_prefix(o), line);
1559 break;
1560 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1561 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1562 diff_line_prefix(o), line);
1563 break;
1564 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1565 emit_line(o, "", "", " 0 files changed\n",
1566 strlen(" 0 files changed\n"));
1567 break;
1568 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1569 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1570 break;
1571 case DIFF_SYMBOL_WORD_DIFF:
1572 fprintf(o->file, "%.*s", len, line);
1573 break;
1574 case DIFF_SYMBOL_STAT_SEP:
1575 fputs(o->stat_sep, o->file);
1576 break;
1577 default:
1578 BUG("unknown diff symbol");
1582 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1583 const char *line, int len, unsigned flags)
1585 struct emitted_diff_symbol e = {
1586 .line = line, .len = len, .flags = flags, .s = s
1589 if (o->emitted_symbols)
1590 append_emitted_diff_symbol(o, &e);
1591 else
1592 emit_diff_symbol_from_struct(o, &e);
1595 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1597 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1600 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1602 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1605 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1607 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1608 path, strlen(path), 0);
1611 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1613 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1614 path, strlen(path), 0);
1617 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1619 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1620 header, strlen(header), 0);
1623 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1625 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1628 void diff_emit_submodule_pipethrough(struct diff_options *o,
1629 const char *line, int len)
1631 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1634 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1636 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1637 ecbdata->blank_at_eof_in_preimage &&
1638 ecbdata->blank_at_eof_in_postimage &&
1639 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1640 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1641 return 0;
1642 return ws_blank_line(line, len);
1645 static void emit_add_line(struct emit_callback *ecbdata,
1646 const char *line, int len)
1648 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1649 if (new_blank_line_at_eof(ecbdata, line, len))
1650 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1652 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1655 static void emit_del_line(struct emit_callback *ecbdata,
1656 const char *line, int len)
1658 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1659 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1662 static void emit_context_line(struct emit_callback *ecbdata,
1663 const char *line, int len)
1665 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1666 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1669 static void emit_hunk_header(struct emit_callback *ecbdata,
1670 const char *line, int len)
1672 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1673 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1674 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1675 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1676 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1677 static const char atat[2] = { '@', '@' };
1678 const char *cp, *ep;
1679 struct strbuf msgbuf = STRBUF_INIT;
1680 int org_len = len;
1681 int i = 1;
1684 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1685 * it always is at least 10 bytes long.
1687 if (len < 10 ||
1688 memcmp(line, atat, 2) ||
1689 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1690 emit_diff_symbol(ecbdata->opt,
1691 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1692 return;
1694 ep += 2; /* skip over @@ */
1696 /* The hunk header in fraginfo color */
1697 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1698 strbuf_addstr(&msgbuf, reverse);
1699 strbuf_addstr(&msgbuf, frag);
1700 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1701 strbuf_add(&msgbuf, atat, sizeof(atat));
1702 else
1703 strbuf_add(&msgbuf, line, ep - line);
1704 strbuf_addstr(&msgbuf, reset);
1707 * trailing "\r\n"
1709 for ( ; i < 3; i++)
1710 if (line[len - i] == '\r' || line[len - i] == '\n')
1711 len--;
1713 /* blank before the func header */
1714 for (cp = ep; ep - line < len; ep++)
1715 if (*ep != ' ' && *ep != '\t')
1716 break;
1717 if (ep != cp) {
1718 strbuf_addstr(&msgbuf, context);
1719 strbuf_add(&msgbuf, cp, ep - cp);
1720 strbuf_addstr(&msgbuf, reset);
1723 if (ep < line + len) {
1724 strbuf_addstr(&msgbuf, func);
1725 strbuf_add(&msgbuf, ep, line + len - ep);
1726 strbuf_addstr(&msgbuf, reset);
1729 strbuf_add(&msgbuf, line + len, org_len - len);
1730 strbuf_complete_line(&msgbuf);
1731 emit_diff_symbol(ecbdata->opt,
1732 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1733 strbuf_release(&msgbuf);
1736 static struct diff_tempfile *claim_diff_tempfile(void)
1738 int i;
1739 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1740 if (!diff_temp[i].name)
1741 return diff_temp + i;
1742 BUG("diff is failing to clean up its tempfiles");
1745 static void remove_tempfile(void)
1747 int i;
1748 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1749 if (is_tempfile_active(diff_temp[i].tempfile))
1750 delete_tempfile(&diff_temp[i].tempfile);
1751 diff_temp[i].name = NULL;
1755 static void add_line_count(struct strbuf *out, int count)
1757 switch (count) {
1758 case 0:
1759 strbuf_addstr(out, "0,0");
1760 break;
1761 case 1:
1762 strbuf_addstr(out, "1");
1763 break;
1764 default:
1765 strbuf_addf(out, "1,%d", count);
1766 break;
1770 static void emit_rewrite_lines(struct emit_callback *ecb,
1771 int prefix, const char *data, int size)
1773 const char *endp = NULL;
1775 while (0 < size) {
1776 int len;
1778 endp = memchr(data, '\n', size);
1779 len = endp ? (endp - data + 1) : size;
1780 if (prefix != '+') {
1781 ecb->lno_in_preimage++;
1782 emit_del_line(ecb, data, len);
1783 } else {
1784 ecb->lno_in_postimage++;
1785 emit_add_line(ecb, data, len);
1787 size -= len;
1788 data += len;
1790 if (!endp)
1791 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1794 static void emit_rewrite_diff(const char *name_a,
1795 const char *name_b,
1796 struct diff_filespec *one,
1797 struct diff_filespec *two,
1798 struct userdiff_driver *textconv_one,
1799 struct userdiff_driver *textconv_two,
1800 struct diff_options *o)
1802 int lc_a, lc_b;
1803 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1804 const char *a_prefix, *b_prefix;
1805 char *data_one, *data_two;
1806 size_t size_one, size_two;
1807 struct emit_callback ecbdata;
1808 struct strbuf out = STRBUF_INIT;
1810 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1811 a_prefix = o->b_prefix;
1812 b_prefix = o->a_prefix;
1813 } else {
1814 a_prefix = o->a_prefix;
1815 b_prefix = o->b_prefix;
1818 name_a += (*name_a == '/');
1819 name_b += (*name_b == '/');
1821 strbuf_reset(&a_name);
1822 strbuf_reset(&b_name);
1823 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1824 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1826 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1827 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1829 memset(&ecbdata, 0, sizeof(ecbdata));
1830 ecbdata.color_diff = want_color(o->use_color);
1831 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1832 ecbdata.opt = o;
1833 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1834 mmfile_t mf1, mf2;
1835 mf1.ptr = (char *)data_one;
1836 mf2.ptr = (char *)data_two;
1837 mf1.size = size_one;
1838 mf2.size = size_two;
1839 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1841 ecbdata.lno_in_preimage = 1;
1842 ecbdata.lno_in_postimage = 1;
1844 lc_a = count_lines(data_one, size_one);
1845 lc_b = count_lines(data_two, size_two);
1847 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1848 a_name.buf, a_name.len, 0);
1849 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1850 b_name.buf, b_name.len, 0);
1852 strbuf_addstr(&out, "@@ -");
1853 if (!o->irreversible_delete)
1854 add_line_count(&out, lc_a);
1855 else
1856 strbuf_addstr(&out, "?,?");
1857 strbuf_addstr(&out, " +");
1858 add_line_count(&out, lc_b);
1859 strbuf_addstr(&out, " @@\n");
1860 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1861 strbuf_release(&out);
1863 if (lc_a && !o->irreversible_delete)
1864 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1865 if (lc_b)
1866 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1867 if (textconv_one)
1868 free((char *)data_one);
1869 if (textconv_two)
1870 free((char *)data_two);
1873 struct diff_words_buffer {
1874 mmfile_t text;
1875 unsigned long alloc;
1876 struct diff_words_orig {
1877 const char *begin, *end;
1878 } *orig;
1879 int orig_nr, orig_alloc;
1882 static void diff_words_append(char *line, unsigned long len,
1883 struct diff_words_buffer *buffer)
1885 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1886 line++;
1887 len--;
1888 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1889 buffer->text.size += len;
1890 buffer->text.ptr[buffer->text.size] = '\0';
1893 struct diff_words_style_elem {
1894 const char *prefix;
1895 const char *suffix;
1896 const char *color; /* NULL; filled in by the setup code if
1897 * color is enabled */
1900 struct diff_words_style {
1901 enum diff_words_type type;
1902 struct diff_words_style_elem new_word, old_word, ctx;
1903 const char *newline;
1906 static struct diff_words_style diff_words_styles[] = {
1907 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1908 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1909 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1912 struct diff_words_data {
1913 struct diff_words_buffer minus, plus;
1914 const char *current_plus;
1915 int last_minus;
1916 struct diff_options *opt;
1917 regex_t *word_regex;
1918 enum diff_words_type type;
1919 struct diff_words_style *style;
1922 static int fn_out_diff_words_write_helper(struct diff_options *o,
1923 struct diff_words_style_elem *st_el,
1924 const char *newline,
1925 size_t count, const char *buf)
1927 int print = 0;
1928 struct strbuf sb = STRBUF_INIT;
1930 while (count) {
1931 char *p = memchr(buf, '\n', count);
1932 if (print)
1933 strbuf_addstr(&sb, diff_line_prefix(o));
1935 if (p != buf) {
1936 const char *reset = st_el->color && *st_el->color ?
1937 GIT_COLOR_RESET : NULL;
1938 if (st_el->color && *st_el->color)
1939 strbuf_addstr(&sb, st_el->color);
1940 strbuf_addstr(&sb, st_el->prefix);
1941 strbuf_add(&sb, buf, p ? p - buf : count);
1942 strbuf_addstr(&sb, st_el->suffix);
1943 if (reset)
1944 strbuf_addstr(&sb, reset);
1946 if (!p)
1947 goto out;
1949 strbuf_addstr(&sb, newline);
1950 count -= p + 1 - buf;
1951 buf = p + 1;
1952 print = 1;
1953 if (count) {
1954 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1955 sb.buf, sb.len, 0);
1956 strbuf_reset(&sb);
1960 out:
1961 if (sb.len)
1962 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1963 sb.buf, sb.len, 0);
1964 strbuf_release(&sb);
1965 return 0;
1969 * '--color-words' algorithm can be described as:
1971 * 1. collect the minus/plus lines of a diff hunk, divided into
1972 * minus-lines and plus-lines;
1974 * 2. break both minus-lines and plus-lines into words and
1975 * place them into two mmfile_t with one word for each line;
1977 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1979 * And for the common parts of the both file, we output the plus side text.
1980 * diff_words->current_plus is used to trace the current position of the plus file
1981 * which printed. diff_words->last_minus is used to trace the last minus word
1982 * printed.
1984 * For '--graph' to work with '--color-words', we need to output the graph prefix
1985 * on each line of color words output. Generally, there are two conditions on
1986 * which we should output the prefix.
1988 * 1. diff_words->last_minus == 0 &&
1989 * diff_words->current_plus == diff_words->plus.text.ptr
1991 * that is: the plus text must start as a new line, and if there is no minus
1992 * word printed, a graph prefix must be printed.
1994 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1995 * *(diff_words->current_plus - 1) == '\n'
1997 * that is: a graph prefix must be printed following a '\n'
1999 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
2001 if ((diff_words->last_minus == 0 &&
2002 diff_words->current_plus == diff_words->plus.text.ptr) ||
2003 (diff_words->current_plus > diff_words->plus.text.ptr &&
2004 *(diff_words->current_plus - 1) == '\n')) {
2005 return 1;
2006 } else {
2007 return 0;
2011 static void fn_out_diff_words_aux(void *priv,
2012 long minus_first, long minus_len,
2013 long plus_first, long plus_len,
2014 const char *func UNUSED, long funclen UNUSED)
2016 struct diff_words_data *diff_words = priv;
2017 struct diff_words_style *style = diff_words->style;
2018 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
2019 struct diff_options *opt = diff_words->opt;
2020 const char *line_prefix;
2022 assert(opt);
2023 line_prefix = diff_line_prefix(opt);
2025 /* POSIX requires that first be decremented by one if len == 0... */
2026 if (minus_len) {
2027 minus_begin = diff_words->minus.orig[minus_first].begin;
2028 minus_end =
2029 diff_words->minus.orig[minus_first + minus_len - 1].end;
2030 } else
2031 minus_begin = minus_end =
2032 diff_words->minus.orig[minus_first].end;
2034 if (plus_len) {
2035 plus_begin = diff_words->plus.orig[plus_first].begin;
2036 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2037 } else
2038 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2040 if (color_words_output_graph_prefix(diff_words)) {
2041 fputs(line_prefix, diff_words->opt->file);
2043 if (diff_words->current_plus != plus_begin) {
2044 fn_out_diff_words_write_helper(diff_words->opt,
2045 &style->ctx, style->newline,
2046 plus_begin - diff_words->current_plus,
2047 diff_words->current_plus);
2049 if (minus_begin != minus_end) {
2050 fn_out_diff_words_write_helper(diff_words->opt,
2051 &style->old_word, style->newline,
2052 minus_end - minus_begin, minus_begin);
2054 if (plus_begin != plus_end) {
2055 fn_out_diff_words_write_helper(diff_words->opt,
2056 &style->new_word, style->newline,
2057 plus_end - plus_begin, plus_begin);
2060 diff_words->current_plus = plus_end;
2061 diff_words->last_minus = minus_first;
2064 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2065 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2066 int *begin, int *end)
2068 while (word_regex && *begin < buffer->size) {
2069 regmatch_t match[1];
2070 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2071 buffer->size - *begin, 1, match, 0)) {
2072 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2073 '\n', match[0].rm_eo - match[0].rm_so);
2074 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2075 *begin += match[0].rm_so;
2076 if (*begin == *end)
2077 (*begin)++;
2078 else
2079 return *begin > *end;
2080 } else {
2081 return -1;
2085 /* find the next word */
2086 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2087 (*begin)++;
2088 if (*begin >= buffer->size)
2089 return -1;
2091 /* find the end of the word */
2092 *end = *begin + 1;
2093 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2094 (*end)++;
2096 return 0;
2100 * This function splits the words in buffer->text, stores the list with
2101 * newline separator into out, and saves the offsets of the original words
2102 * in buffer->orig.
2104 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2105 regex_t *word_regex)
2107 int i, j;
2108 long alloc = 0;
2110 out->size = 0;
2111 out->ptr = NULL;
2113 /* fake an empty "0th" word */
2114 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2115 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2116 buffer->orig_nr = 1;
2118 for (i = 0; i < buffer->text.size; i++) {
2119 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2120 return;
2122 /* store original boundaries */
2123 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2124 buffer->orig_alloc);
2125 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2126 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2127 buffer->orig_nr++;
2129 /* store one word */
2130 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2131 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2132 out->ptr[out->size + j - i] = '\n';
2133 out->size += j - i + 1;
2135 i = j - 1;
2139 /* this executes the word diff on the accumulated buffers */
2140 static void diff_words_show(struct diff_words_data *diff_words)
2142 xpparam_t xpp;
2143 xdemitconf_t xecfg;
2144 mmfile_t minus, plus;
2145 struct diff_words_style *style = diff_words->style;
2147 struct diff_options *opt = diff_words->opt;
2148 const char *line_prefix;
2150 assert(opt);
2151 line_prefix = diff_line_prefix(opt);
2153 /* special case: only removal */
2154 if (!diff_words->plus.text.size) {
2155 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2156 line_prefix, strlen(line_prefix), 0);
2157 fn_out_diff_words_write_helper(diff_words->opt,
2158 &style->old_word, style->newline,
2159 diff_words->minus.text.size,
2160 diff_words->minus.text.ptr);
2161 diff_words->minus.text.size = 0;
2162 return;
2165 diff_words->current_plus = diff_words->plus.text.ptr;
2166 diff_words->last_minus = 0;
2168 memset(&xpp, 0, sizeof(xpp));
2169 memset(&xecfg, 0, sizeof(xecfg));
2170 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2171 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2172 xpp.flags = 0;
2173 /* as only the hunk header will be parsed, we need a 0-context */
2174 xecfg.ctxlen = 0;
2175 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2176 diff_words, &xpp, &xecfg))
2177 die("unable to generate word diff");
2178 free(minus.ptr);
2179 free(plus.ptr);
2180 if (diff_words->current_plus != diff_words->plus.text.ptr +
2181 diff_words->plus.text.size) {
2182 if (color_words_output_graph_prefix(diff_words))
2183 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2184 line_prefix, strlen(line_prefix), 0);
2185 fn_out_diff_words_write_helper(diff_words->opt,
2186 &style->ctx, style->newline,
2187 diff_words->plus.text.ptr + diff_words->plus.text.size
2188 - diff_words->current_plus, diff_words->current_plus);
2190 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2193 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2194 static void diff_words_flush(struct emit_callback *ecbdata)
2196 struct diff_options *wo = ecbdata->diff_words->opt;
2198 if (ecbdata->diff_words->minus.text.size ||
2199 ecbdata->diff_words->plus.text.size)
2200 diff_words_show(ecbdata->diff_words);
2202 if (wo->emitted_symbols) {
2203 struct diff_options *o = ecbdata->opt;
2204 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2205 int i;
2208 * NEEDSWORK:
2209 * Instead of appending each, concat all words to a line?
2211 for (i = 0; i < wol->nr; i++)
2212 append_emitted_diff_symbol(o, &wol->buf[i]);
2214 for (i = 0; i < wol->nr; i++)
2215 free((void *)wol->buf[i].line);
2217 wol->nr = 0;
2221 static void diff_filespec_load_driver(struct diff_filespec *one,
2222 struct index_state *istate)
2224 /* Use already-loaded driver */
2225 if (one->driver)
2226 return;
2228 if (S_ISREG(one->mode))
2229 one->driver = userdiff_find_by_path(istate, one->path);
2231 /* Fallback to default settings */
2232 if (!one->driver)
2233 one->driver = userdiff_find_by_name("default");
2236 static const char *userdiff_word_regex(struct diff_filespec *one,
2237 struct index_state *istate)
2239 diff_filespec_load_driver(one, istate);
2240 return one->driver->word_regex;
2243 static void init_diff_words_data(struct emit_callback *ecbdata,
2244 struct diff_options *orig_opts,
2245 struct diff_filespec *one,
2246 struct diff_filespec *two)
2248 int i;
2249 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2250 memcpy(o, orig_opts, sizeof(struct diff_options));
2252 CALLOC_ARRAY(ecbdata->diff_words, 1);
2253 ecbdata->diff_words->type = o->word_diff;
2254 ecbdata->diff_words->opt = o;
2256 if (orig_opts->emitted_symbols)
2257 CALLOC_ARRAY(o->emitted_symbols, 1);
2259 if (!o->word_regex)
2260 o->word_regex = userdiff_word_regex(one, o->repo->index);
2261 if (!o->word_regex)
2262 o->word_regex = userdiff_word_regex(two, o->repo->index);
2263 if (!o->word_regex)
2264 o->word_regex = diff_word_regex_cfg;
2265 if (o->word_regex) {
2266 ecbdata->diff_words->word_regex = (regex_t *)
2267 xmalloc(sizeof(regex_t));
2268 if (regcomp(ecbdata->diff_words->word_regex,
2269 o->word_regex,
2270 REG_EXTENDED | REG_NEWLINE))
2271 die("invalid regular expression: %s",
2272 o->word_regex);
2274 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2275 if (o->word_diff == diff_words_styles[i].type) {
2276 ecbdata->diff_words->style =
2277 &diff_words_styles[i];
2278 break;
2281 if (want_color(o->use_color)) {
2282 struct diff_words_style *st = ecbdata->diff_words->style;
2283 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2284 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2285 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2289 static void free_diff_words_data(struct emit_callback *ecbdata)
2291 if (ecbdata->diff_words) {
2292 diff_words_flush(ecbdata);
2293 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2294 free (ecbdata->diff_words->opt);
2295 free (ecbdata->diff_words->minus.text.ptr);
2296 free (ecbdata->diff_words->minus.orig);
2297 free (ecbdata->diff_words->plus.text.ptr);
2298 free (ecbdata->diff_words->plus.orig);
2299 if (ecbdata->diff_words->word_regex) {
2300 regfree(ecbdata->diff_words->word_regex);
2301 free(ecbdata->diff_words->word_regex);
2303 FREE_AND_NULL(ecbdata->diff_words);
2307 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2309 if (want_color(diff_use_color))
2310 return diff_colors[ix];
2311 return "";
2314 const char *diff_line_prefix(struct diff_options *opt)
2316 struct strbuf *msgbuf;
2317 if (!opt->output_prefix)
2318 return "";
2320 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2321 return msgbuf->buf;
2324 static unsigned long sane_truncate_line(char *line, unsigned long len)
2326 const char *cp;
2327 unsigned long allot;
2328 size_t l = len;
2330 cp = line;
2331 allot = l;
2332 while (0 < l) {
2333 (void) utf8_width(&cp, &l);
2334 if (!cp)
2335 break; /* truncated in the middle? */
2337 return allot - l;
2340 static void find_lno(const char *line, struct emit_callback *ecbdata)
2342 const char *p;
2343 ecbdata->lno_in_preimage = 0;
2344 ecbdata->lno_in_postimage = 0;
2345 p = strchr(line, '-');
2346 if (!p)
2347 return; /* cannot happen */
2348 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2349 p = strchr(p, '+');
2350 if (!p)
2351 return; /* cannot happen */
2352 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2355 static int fn_out_consume(void *priv, char *line, unsigned long len)
2357 struct emit_callback *ecbdata = priv;
2358 struct diff_options *o = ecbdata->opt;
2360 o->found_changes = 1;
2362 if (ecbdata->header) {
2363 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2364 ecbdata->header->buf, ecbdata->header->len, 0);
2365 strbuf_reset(ecbdata->header);
2366 ecbdata->header = NULL;
2369 if (ecbdata->label_path[0]) {
2370 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2371 ecbdata->label_path[0],
2372 strlen(ecbdata->label_path[0]), 0);
2373 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2374 ecbdata->label_path[1],
2375 strlen(ecbdata->label_path[1]), 0);
2376 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2379 if (diff_suppress_blank_empty
2380 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2381 line[0] = '\n';
2382 len = 1;
2385 if (line[0] == '@') {
2386 if (ecbdata->diff_words)
2387 diff_words_flush(ecbdata);
2388 len = sane_truncate_line(line, len);
2389 find_lno(line, ecbdata);
2390 emit_hunk_header(ecbdata, line, len);
2391 return 0;
2394 if (ecbdata->diff_words) {
2395 enum diff_symbol s =
2396 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2397 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2398 if (line[0] == '-') {
2399 diff_words_append(line, len,
2400 &ecbdata->diff_words->minus);
2401 return 0;
2402 } else if (line[0] == '+') {
2403 diff_words_append(line, len,
2404 &ecbdata->diff_words->plus);
2405 return 0;
2406 } else if (starts_with(line, "\\ ")) {
2408 * Eat the "no newline at eof" marker as if we
2409 * saw a "+" or "-" line with nothing on it,
2410 * and return without diff_words_flush() to
2411 * defer processing. If this is the end of
2412 * preimage, more "+" lines may come after it.
2414 return 0;
2416 diff_words_flush(ecbdata);
2417 emit_diff_symbol(o, s, line, len, 0);
2418 return 0;
2421 switch (line[0]) {
2422 case '+':
2423 ecbdata->lno_in_postimage++;
2424 emit_add_line(ecbdata, line + 1, len - 1);
2425 break;
2426 case '-':
2427 ecbdata->lno_in_preimage++;
2428 emit_del_line(ecbdata, line + 1, len - 1);
2429 break;
2430 case ' ':
2431 ecbdata->lno_in_postimage++;
2432 ecbdata->lno_in_preimage++;
2433 emit_context_line(ecbdata, line + 1, len - 1);
2434 break;
2435 default:
2436 /* incomplete line at the end */
2437 ecbdata->lno_in_preimage++;
2438 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2439 line, len, 0);
2440 break;
2442 return 0;
2445 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2447 const char *old_name = a;
2448 const char *new_name = b;
2449 int pfx_length, sfx_length;
2450 int pfx_adjust_for_slash;
2451 int len_a = strlen(a);
2452 int len_b = strlen(b);
2453 int a_midlen, b_midlen;
2454 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2455 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2457 if (qlen_a || qlen_b) {
2458 quote_c_style(a, name, NULL, 0);
2459 strbuf_addstr(name, " => ");
2460 quote_c_style(b, name, NULL, 0);
2461 return;
2464 /* Find common prefix */
2465 pfx_length = 0;
2466 while (*old_name && *new_name && *old_name == *new_name) {
2467 if (*old_name == '/')
2468 pfx_length = old_name - a + 1;
2469 old_name++;
2470 new_name++;
2473 /* Find common suffix */
2474 old_name = a + len_a;
2475 new_name = b + len_b;
2476 sfx_length = 0;
2478 * If there is a common prefix, it must end in a slash. In
2479 * that case we let this loop run 1 into the prefix to see the
2480 * same slash.
2482 * If there is no common prefix, we cannot do this as it would
2483 * underrun the input strings.
2485 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2486 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2487 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2488 *old_name == *new_name) {
2489 if (*old_name == '/')
2490 sfx_length = len_a - (old_name - a);
2491 old_name--;
2492 new_name--;
2496 * pfx{mid-a => mid-b}sfx
2497 * {pfx-a => pfx-b}sfx
2498 * pfx{sfx-a => sfx-b}
2499 * name-a => name-b
2501 a_midlen = len_a - pfx_length - sfx_length;
2502 b_midlen = len_b - pfx_length - sfx_length;
2503 if (a_midlen < 0)
2504 a_midlen = 0;
2505 if (b_midlen < 0)
2506 b_midlen = 0;
2508 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2509 if (pfx_length + sfx_length) {
2510 strbuf_add(name, a, pfx_length);
2511 strbuf_addch(name, '{');
2513 strbuf_add(name, a + pfx_length, a_midlen);
2514 strbuf_addstr(name, " => ");
2515 strbuf_add(name, b + pfx_length, b_midlen);
2516 if (pfx_length + sfx_length) {
2517 strbuf_addch(name, '}');
2518 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2522 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2523 const char *name_a,
2524 const char *name_b)
2526 struct diffstat_file *x;
2527 CALLOC_ARRAY(x, 1);
2528 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2529 diffstat->files[diffstat->nr++] = x;
2530 if (name_b) {
2531 x->from_name = xstrdup(name_a);
2532 x->name = xstrdup(name_b);
2533 x->is_renamed = 1;
2535 else {
2536 x->from_name = NULL;
2537 x->name = xstrdup(name_a);
2539 return x;
2542 static int diffstat_consume(void *priv, char *line, unsigned long len)
2544 struct diffstat_t *diffstat = priv;
2545 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2547 if (!len)
2548 BUG("xdiff fed us an empty line");
2550 if (line[0] == '+')
2551 x->added++;
2552 else if (line[0] == '-')
2553 x->deleted++;
2554 return 0;
2557 const char mime_boundary_leader[] = "------------";
2559 static int scale_linear(int it, int width, int max_change)
2561 if (!it)
2562 return 0;
2564 * make sure that at least one '-' or '+' is printed if
2565 * there is any change to this path. The easiest way is to
2566 * scale linearly as if the allotted width is one column shorter
2567 * than it is, and then add 1 to the result.
2569 return 1 + (it * (width - 1) / max_change);
2572 static void show_graph(struct strbuf *out, char ch, int cnt,
2573 const char *set, const char *reset)
2575 if (cnt <= 0)
2576 return;
2577 strbuf_addstr(out, set);
2578 strbuf_addchars(out, ch, cnt);
2579 strbuf_addstr(out, reset);
2582 static void fill_print_name(struct diffstat_file *file)
2584 struct strbuf pname = STRBUF_INIT;
2586 if (file->print_name)
2587 return;
2589 if (file->is_renamed)
2590 pprint_rename(&pname, file->from_name, file->name);
2591 else
2592 quote_c_style(file->name, &pname, NULL, 0);
2594 if (file->comments)
2595 strbuf_addf(&pname, " (%s)", file->comments);
2597 file->print_name = strbuf_detach(&pname, NULL);
2600 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2601 int files, int insertions, int deletions)
2603 struct strbuf sb = STRBUF_INIT;
2605 if (!files) {
2606 assert(insertions == 0 && deletions == 0);
2607 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2608 NULL, 0, 0);
2609 return;
2612 strbuf_addf(&sb,
2613 (files == 1) ? " %d file changed" : " %d files changed",
2614 files);
2617 * For binary diff, the caller may want to print "x files
2618 * changed" with insertions == 0 && deletions == 0.
2620 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2621 * is probably less confusing (i.e skip over "2 files changed
2622 * but nothing about added/removed lines? Is this a bug in Git?").
2624 if (insertions || deletions == 0) {
2625 strbuf_addf(&sb,
2626 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2627 insertions);
2630 if (deletions || insertions == 0) {
2631 strbuf_addf(&sb,
2632 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2633 deletions);
2635 strbuf_addch(&sb, '\n');
2636 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2637 sb.buf, sb.len, 0);
2638 strbuf_release(&sb);
2641 void print_stat_summary(FILE *fp, int files,
2642 int insertions, int deletions)
2644 struct diff_options o;
2645 memset(&o, 0, sizeof(o));
2646 o.file = fp;
2648 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2651 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2653 int i, len, add, del, adds = 0, dels = 0;
2654 uintmax_t max_change = 0, max_len = 0;
2655 int total_files = data->nr, count;
2656 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2657 const char *reset, *add_c, *del_c;
2658 int extra_shown = 0;
2659 const char *line_prefix = diff_line_prefix(options);
2660 struct strbuf out = STRBUF_INIT;
2662 if (data->nr == 0)
2663 return;
2665 count = options->stat_count ? options->stat_count : data->nr;
2667 reset = diff_get_color_opt(options, DIFF_RESET);
2668 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2669 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2672 * Find the longest filename and max number of changes
2674 for (i = 0; (i < count) && (i < data->nr); i++) {
2675 struct diffstat_file *file = data->files[i];
2676 uintmax_t change = file->added + file->deleted;
2678 if (!file->is_interesting && (change == 0)) {
2679 count++; /* not shown == room for one more */
2680 continue;
2682 fill_print_name(file);
2683 len = utf8_strwidth(file->print_name);
2684 if (max_len < len)
2685 max_len = len;
2687 if (file->is_unmerged) {
2688 /* "Unmerged" is 8 characters */
2689 bin_width = bin_width < 8 ? 8 : bin_width;
2690 continue;
2692 if (file->is_binary) {
2693 /* "Bin XXX -> YYY bytes" */
2694 int w = 14 + decimal_width(file->added)
2695 + decimal_width(file->deleted);
2696 bin_width = bin_width < w ? w : bin_width;
2697 /* Display change counts aligned with "Bin" */
2698 number_width = 3;
2699 continue;
2702 if (max_change < change)
2703 max_change = change;
2705 count = i; /* where we can stop scanning in data->files[] */
2708 * We have width = stat_width or term_columns() columns total.
2709 * We want a maximum of min(max_len, stat_name_width) for the name part.
2710 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2711 * We also need 1 for " " and 4 + decimal_width(max_change)
2712 * for " | NNNN " and one the empty column at the end, altogether
2713 * 6 + decimal_width(max_change).
2715 * If there's not enough space, we will use the smaller of
2716 * stat_name_width (if set) and 5/8*width for the filename,
2717 * and the rest for constant elements + graph part, but no more
2718 * than stat_graph_width for the graph part.
2719 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2720 * for the standard terminal size).
2722 * In other words: stat_width limits the maximum width, and
2723 * stat_name_width fixes the maximum width of the filename,
2724 * and is also used to divide available columns if there
2725 * aren't enough.
2727 * Binary files are displayed with "Bin XXX -> YYY bytes"
2728 * instead of the change count and graph. This part is treated
2729 * similarly to the graph part, except that it is not
2730 * "scaled". If total width is too small to accommodate the
2731 * guaranteed minimum width of the filename part and the
2732 * separators and this message, this message will "overflow"
2733 * making the line longer than the maximum width.
2737 * NEEDSWORK: line_prefix is often used for "log --graph" output
2738 * and contains ANSI-colored string. utf8_strnwidth() should be
2739 * used to correctly count the display width instead of strlen().
2741 if (options->stat_width == -1)
2742 width = term_columns() - strlen(line_prefix);
2743 else
2744 width = options->stat_width ? options->stat_width : 80;
2745 number_width = decimal_width(max_change) > number_width ?
2746 decimal_width(max_change) : number_width;
2748 if (options->stat_name_width == -1)
2749 options->stat_name_width = diff_stat_name_width;
2750 if (options->stat_graph_width == -1)
2751 options->stat_graph_width = diff_stat_graph_width;
2754 * Guarantee 3/8*16 == 6 for the graph part
2755 * and 5/8*16 == 10 for the filename part
2757 if (width < 16 + 6 + number_width)
2758 width = 16 + 6 + number_width;
2761 * First assign sizes that are wanted, ignoring available width.
2762 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2763 * starting from "XXX" should fit in graph_width.
2765 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2766 if (options->stat_graph_width &&
2767 options->stat_graph_width < graph_width)
2768 graph_width = options->stat_graph_width;
2770 name_width = (options->stat_name_width > 0 &&
2771 options->stat_name_width < max_len) ?
2772 options->stat_name_width : max_len;
2775 * Adjust adjustable widths not to exceed maximum width
2777 if (name_width + number_width + 6 + graph_width > width) {
2778 if (graph_width > width * 3/8 - number_width - 6) {
2779 graph_width = width * 3/8 - number_width - 6;
2780 if (graph_width < 6)
2781 graph_width = 6;
2784 if (options->stat_graph_width &&
2785 graph_width > options->stat_graph_width)
2786 graph_width = options->stat_graph_width;
2787 if (name_width > width - number_width - 6 - graph_width)
2788 name_width = width - number_width - 6 - graph_width;
2789 else
2790 graph_width = width - number_width - 6 - name_width;
2794 * From here name_width is the width of the name area,
2795 * and graph_width is the width of the graph area.
2796 * max_change is used to scale graph properly.
2798 for (i = 0; i < count; i++) {
2799 const char *prefix = "";
2800 struct diffstat_file *file = data->files[i];
2801 char *name = file->print_name;
2802 uintmax_t added = file->added;
2803 uintmax_t deleted = file->deleted;
2804 int name_len, padding;
2806 if (!file->is_interesting && (added + deleted == 0))
2807 continue;
2810 * "scale" the filename
2812 len = name_width;
2813 name_len = utf8_strwidth(name);
2814 if (name_width < name_len) {
2815 char *slash;
2816 prefix = "...";
2817 len -= 3;
2819 * NEEDSWORK: (name_len - len) counts the display
2820 * width, which would be shorter than the byte
2821 * length of the corresponding substring.
2822 * Advancing "name" by that number of bytes does
2823 * *NOT* skip over that many columns, so it is
2824 * very likely that chomping the pathname at the
2825 * slash we will find starting from "name" will
2826 * leave the resulting string still too long.
2828 name += name_len - len;
2829 slash = strchr(name, '/');
2830 if (slash)
2831 name = slash;
2833 padding = len - utf8_strwidth(name);
2834 if (padding < 0)
2835 padding = 0;
2837 if (file->is_binary) {
2838 strbuf_addf(&out, " %s%s%*s | %*s",
2839 prefix, name, padding, "",
2840 number_width, "Bin");
2841 if (!added && !deleted) {
2842 strbuf_addch(&out, '\n');
2843 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2844 out.buf, out.len, 0);
2845 strbuf_reset(&out);
2846 continue;
2848 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2849 del_c, deleted, reset);
2850 strbuf_addstr(&out, " -> ");
2851 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2852 add_c, added, reset);
2853 strbuf_addstr(&out, " bytes\n");
2854 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2855 out.buf, out.len, 0);
2856 strbuf_reset(&out);
2857 continue;
2859 else if (file->is_unmerged) {
2860 strbuf_addf(&out, " %s%s%*s | %*s",
2861 prefix, name, padding, "",
2862 number_width, "Unmerged\n");
2863 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2864 out.buf, out.len, 0);
2865 strbuf_reset(&out);
2866 continue;
2870 * scale the add/delete
2872 add = added;
2873 del = deleted;
2875 if (graph_width <= max_change) {
2876 int total = scale_linear(add + del, graph_width, max_change);
2877 if (total < 2 && add && del)
2878 /* width >= 2 due to the sanity check */
2879 total = 2;
2880 if (add < del) {
2881 add = scale_linear(add, graph_width, max_change);
2882 del = total - add;
2883 } else {
2884 del = scale_linear(del, graph_width, max_change);
2885 add = total - del;
2888 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
2889 prefix, name, padding, "",
2890 number_width, added + deleted,
2891 added + deleted ? " " : "");
2892 show_graph(&out, '+', add, add_c, reset);
2893 show_graph(&out, '-', del, del_c, reset);
2894 strbuf_addch(&out, '\n');
2895 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2896 out.buf, out.len, 0);
2897 strbuf_reset(&out);
2900 for (i = 0; i < data->nr; i++) {
2901 struct diffstat_file *file = data->files[i];
2902 uintmax_t added = file->added;
2903 uintmax_t deleted = file->deleted;
2905 if (file->is_unmerged ||
2906 (!file->is_interesting && (added + deleted == 0))) {
2907 total_files--;
2908 continue;
2911 if (!file->is_binary) {
2912 adds += added;
2913 dels += deleted;
2915 if (i < count)
2916 continue;
2917 if (!extra_shown)
2918 emit_diff_symbol(options,
2919 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2920 NULL, 0, 0);
2921 extra_shown = 1;
2924 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2925 strbuf_release(&out);
2928 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2930 int i, adds = 0, dels = 0, total_files = data->nr;
2932 if (data->nr == 0)
2933 return;
2935 for (i = 0; i < data->nr; i++) {
2936 int added = data->files[i]->added;
2937 int deleted = data->files[i]->deleted;
2939 if (data->files[i]->is_unmerged ||
2940 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2941 total_files--;
2942 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2943 adds += added;
2944 dels += deleted;
2947 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2950 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2952 int i;
2954 if (data->nr == 0)
2955 return;
2957 for (i = 0; i < data->nr; i++) {
2958 struct diffstat_file *file = data->files[i];
2960 fprintf(options->file, "%s", diff_line_prefix(options));
2962 if (file->is_binary)
2963 fprintf(options->file, "-\t-\t");
2964 else
2965 fprintf(options->file,
2966 "%"PRIuMAX"\t%"PRIuMAX"\t",
2967 file->added, file->deleted);
2968 if (options->line_termination) {
2969 fill_print_name(file);
2970 if (!file->is_renamed)
2971 write_name_quoted(file->name, options->file,
2972 options->line_termination);
2973 else {
2974 fputs(file->print_name, options->file);
2975 putc(options->line_termination, options->file);
2977 } else {
2978 if (file->is_renamed) {
2979 putc('\0', options->file);
2980 write_name_quoted(file->from_name, options->file, '\0');
2982 write_name_quoted(file->name, options->file, '\0');
2987 struct dirstat_file {
2988 const char *name;
2989 unsigned long changed;
2992 struct dirstat_dir {
2993 struct dirstat_file *files;
2994 int alloc, nr, permille, cumulative;
2997 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2998 unsigned long changed, const char *base, int baselen)
3000 unsigned long sum_changes = 0;
3001 unsigned int sources = 0;
3002 const char *line_prefix = diff_line_prefix(opt);
3004 while (dir->nr) {
3005 struct dirstat_file *f = dir->files;
3006 int namelen = strlen(f->name);
3007 unsigned long changes;
3008 char *slash;
3010 if (namelen < baselen)
3011 break;
3012 if (memcmp(f->name, base, baselen))
3013 break;
3014 slash = strchr(f->name + baselen, '/');
3015 if (slash) {
3016 int newbaselen = slash + 1 - f->name;
3017 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
3018 sources++;
3019 } else {
3020 changes = f->changed;
3021 dir->files++;
3022 dir->nr--;
3023 sources += 2;
3025 sum_changes += changes;
3029 * We don't report dirstat's for
3030 * - the top level
3031 * - or cases where everything came from a single directory
3032 * under this directory (sources == 1).
3034 if (baselen && sources != 1) {
3035 if (sum_changes) {
3036 int permille = sum_changes * 1000 / changed;
3037 if (permille >= dir->permille) {
3038 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
3039 permille / 10, permille % 10, baselen, base);
3040 if (!dir->cumulative)
3041 return 0;
3045 return sum_changes;
3048 static int dirstat_compare(const void *_a, const void *_b)
3050 const struct dirstat_file *a = _a;
3051 const struct dirstat_file *b = _b;
3052 return strcmp(a->name, b->name);
3055 static void conclude_dirstat(struct diff_options *options,
3056 struct dirstat_dir *dir,
3057 unsigned long changed)
3059 struct dirstat_file *to_free = dir->files;
3061 if (!changed) {
3062 /* This can happen even with many files, if everything was renames */
3064 } else {
3065 /* Show all directories with more than x% of the changes */
3066 QSORT(dir->files, dir->nr, dirstat_compare);
3067 gather_dirstat(options, dir, changed, "", 0);
3070 free(to_free);
3073 static void show_dirstat(struct diff_options *options)
3075 int i;
3076 unsigned long changed;
3077 struct dirstat_dir dir;
3078 struct diff_queue_struct *q = &diff_queued_diff;
3080 dir.files = NULL;
3081 dir.alloc = 0;
3082 dir.nr = 0;
3083 dir.permille = options->dirstat_permille;
3084 dir.cumulative = options->flags.dirstat_cumulative;
3086 changed = 0;
3087 for (i = 0; i < q->nr; i++) {
3088 struct diff_filepair *p = q->queue[i];
3089 const char *name;
3090 unsigned long copied, added, damage;
3091 struct diff_populate_filespec_options dpf_options = {
3092 .check_size_only = 1,
3095 name = p->two->path ? p->two->path : p->one->path;
3097 if (p->one->oid_valid && p->two->oid_valid &&
3098 oideq(&p->one->oid, &p->two->oid)) {
3100 * The SHA1 has not changed, so pre-/post-content is
3101 * identical. We can therefore skip looking at the
3102 * file contents altogether.
3104 damage = 0;
3105 goto found_damage;
3108 if (options->flags.dirstat_by_file) {
3110 * In --dirstat-by-file mode, we don't really need to
3111 * look at the actual file contents at all.
3112 * The fact that the SHA1 changed is enough for us to
3113 * add this file to the list of results
3114 * (with each file contributing equal damage).
3116 damage = 1;
3117 goto found_damage;
3120 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3121 diff_populate_filespec(options->repo, p->one, NULL);
3122 diff_populate_filespec(options->repo, p->two, NULL);
3123 diffcore_count_changes(options->repo,
3124 p->one, p->two, NULL, NULL,
3125 &copied, &added);
3126 diff_free_filespec_data(p->one);
3127 diff_free_filespec_data(p->two);
3128 } else if (DIFF_FILE_VALID(p->one)) {
3129 diff_populate_filespec(options->repo, p->one, &dpf_options);
3130 copied = added = 0;
3131 diff_free_filespec_data(p->one);
3132 } else if (DIFF_FILE_VALID(p->two)) {
3133 diff_populate_filespec(options->repo, p->two, &dpf_options);
3134 copied = 0;
3135 added = p->two->size;
3136 diff_free_filespec_data(p->two);
3137 } else
3138 continue;
3141 * Original minus copied is the removed material,
3142 * added is the new material. They are both damages
3143 * made to the preimage.
3144 * If the resulting damage is zero, we know that
3145 * diffcore_count_changes() considers the two entries to
3146 * be identical, but since the oid changed, we
3147 * know that there must have been _some_ kind of change,
3148 * so we force all entries to have damage > 0.
3150 damage = (p->one->size - copied) + added;
3151 if (!damage)
3152 damage = 1;
3154 found_damage:
3155 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3156 dir.files[dir.nr].name = name;
3157 dir.files[dir.nr].changed = damage;
3158 changed += damage;
3159 dir.nr++;
3162 conclude_dirstat(options, &dir, changed);
3165 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3167 int i;
3168 unsigned long changed;
3169 struct dirstat_dir dir;
3171 if (data->nr == 0)
3172 return;
3174 dir.files = NULL;
3175 dir.alloc = 0;
3176 dir.nr = 0;
3177 dir.permille = options->dirstat_permille;
3178 dir.cumulative = options->flags.dirstat_cumulative;
3180 changed = 0;
3181 for (i = 0; i < data->nr; i++) {
3182 struct diffstat_file *file = data->files[i];
3183 unsigned long damage = file->added + file->deleted;
3184 if (file->is_binary)
3186 * binary files counts bytes, not lines. Must find some
3187 * way to normalize binary bytes vs. textual lines.
3188 * The following heuristic assumes that there are 64
3189 * bytes per "line".
3190 * This is stupid and ugly, but very cheap...
3192 damage = DIV_ROUND_UP(damage, 64);
3193 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3194 dir.files[dir.nr].name = file->name;
3195 dir.files[dir.nr].changed = damage;
3196 changed += damage;
3197 dir.nr++;
3200 conclude_dirstat(options, &dir, changed);
3203 static void free_diffstat_file(struct diffstat_file *f)
3205 free(f->print_name);
3206 free(f->name);
3207 free(f->from_name);
3208 free(f);
3211 void free_diffstat_info(struct diffstat_t *diffstat)
3213 int i;
3214 for (i = 0; i < diffstat->nr; i++)
3215 free_diffstat_file(diffstat->files[i]);
3216 free(diffstat->files);
3219 struct checkdiff_t {
3220 const char *filename;
3221 int lineno;
3222 int conflict_marker_size;
3223 struct diff_options *o;
3224 unsigned ws_rule;
3225 unsigned status;
3228 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3230 char firstchar;
3231 int cnt;
3233 if (len < marker_size + 1)
3234 return 0;
3235 firstchar = line[0];
3236 switch (firstchar) {
3237 case '=': case '>': case '<': case '|':
3238 break;
3239 default:
3240 return 0;
3242 for (cnt = 1; cnt < marker_size; cnt++)
3243 if (line[cnt] != firstchar)
3244 return 0;
3245 /* line[1] through line[marker_size-1] are same as firstchar */
3246 if (len < marker_size + 1 || !isspace(line[marker_size]))
3247 return 0;
3248 return 1;
3251 static void checkdiff_consume_hunk(void *priv,
3252 long ob UNUSED, long on UNUSED,
3253 long nb, long nn UNUSED,
3254 const char *func UNUSED, long funclen UNUSED)
3257 struct checkdiff_t *data = priv;
3258 data->lineno = nb - 1;
3261 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3263 struct checkdiff_t *data = priv;
3264 int marker_size = data->conflict_marker_size;
3265 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3266 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3267 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3268 char *err;
3269 const char *line_prefix;
3271 assert(data->o);
3272 line_prefix = diff_line_prefix(data->o);
3274 if (line[0] == '+') {
3275 unsigned bad;
3276 data->lineno++;
3277 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3278 data->status |= 1;
3279 fprintf(data->o->file,
3280 "%s%s:%d: leftover conflict marker\n",
3281 line_prefix, data->filename, data->lineno);
3283 bad = ws_check(line + 1, len - 1, data->ws_rule);
3284 if (!bad)
3285 return 0;
3286 data->status |= bad;
3287 err = whitespace_error_string(bad);
3288 fprintf(data->o->file, "%s%s:%d: %s.\n",
3289 line_prefix, data->filename, data->lineno, err);
3290 free(err);
3291 emit_line(data->o, set, reset, line, 1);
3292 ws_check_emit(line + 1, len - 1, data->ws_rule,
3293 data->o->file, set, reset, ws);
3294 } else if (line[0] == ' ') {
3295 data->lineno++;
3297 return 0;
3300 static unsigned char *deflate_it(char *data,
3301 unsigned long size,
3302 unsigned long *result_size)
3304 int bound;
3305 unsigned char *deflated;
3306 git_zstream stream;
3308 git_deflate_init(&stream, zlib_compression_level);
3309 bound = git_deflate_bound(&stream, size);
3310 deflated = xmalloc(bound);
3311 stream.next_out = deflated;
3312 stream.avail_out = bound;
3314 stream.next_in = (unsigned char *)data;
3315 stream.avail_in = size;
3316 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3317 ; /* nothing */
3318 git_deflate_end(&stream);
3319 *result_size = stream.total_out;
3320 return deflated;
3323 static void emit_binary_diff_body(struct diff_options *o,
3324 mmfile_t *one, mmfile_t *two)
3326 void *cp;
3327 void *delta;
3328 void *deflated;
3329 void *data;
3330 unsigned long orig_size;
3331 unsigned long delta_size;
3332 unsigned long deflate_size;
3333 unsigned long data_size;
3335 /* We could do deflated delta, or we could do just deflated two,
3336 * whichever is smaller.
3338 delta = NULL;
3339 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3340 if (one->size && two->size) {
3341 delta = diff_delta(one->ptr, one->size,
3342 two->ptr, two->size,
3343 &delta_size, deflate_size);
3344 if (delta) {
3345 void *to_free = delta;
3346 orig_size = delta_size;
3347 delta = deflate_it(delta, delta_size, &delta_size);
3348 free(to_free);
3352 if (delta && delta_size < deflate_size) {
3353 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3354 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3355 s, strlen(s), 0);
3356 free(s);
3357 free(deflated);
3358 data = delta;
3359 data_size = delta_size;
3360 } else {
3361 char *s = xstrfmt("%lu", two->size);
3362 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3363 s, strlen(s), 0);
3364 free(s);
3365 free(delta);
3366 data = deflated;
3367 data_size = deflate_size;
3370 /* emit data encoded in base85 */
3371 cp = data;
3372 while (data_size) {
3373 int len;
3374 int bytes = (52 < data_size) ? 52 : data_size;
3375 char line[71];
3376 data_size -= bytes;
3377 if (bytes <= 26)
3378 line[0] = bytes + 'A' - 1;
3379 else
3380 line[0] = bytes - 26 + 'a' - 1;
3381 encode_85(line + 1, cp, bytes);
3382 cp = (char *) cp + bytes;
3384 len = strlen(line);
3385 line[len++] = '\n';
3386 line[len] = '\0';
3388 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3389 line, len, 0);
3391 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3392 free(data);
3395 static void emit_binary_diff(struct diff_options *o,
3396 mmfile_t *one, mmfile_t *two)
3398 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3399 emit_binary_diff_body(o, one, two);
3400 emit_binary_diff_body(o, two, one);
3403 int diff_filespec_is_binary(struct repository *r,
3404 struct diff_filespec *one)
3406 struct diff_populate_filespec_options dpf_options = {
3407 .check_binary = 1,
3410 if (one->is_binary == -1) {
3411 diff_filespec_load_driver(one, r->index);
3412 if (one->driver->binary != -1)
3413 one->is_binary = one->driver->binary;
3414 else {
3415 if (!one->data && DIFF_FILE_VALID(one))
3416 diff_populate_filespec(r, one, &dpf_options);
3417 if (one->is_binary == -1 && one->data)
3418 one->is_binary = buffer_is_binary(one->data,
3419 one->size);
3420 if (one->is_binary == -1)
3421 one->is_binary = 0;
3424 return one->is_binary;
3427 static const struct userdiff_funcname *
3428 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3430 diff_filespec_load_driver(one, o->repo->index);
3431 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3434 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3436 if (!options->a_prefix)
3437 options->a_prefix = a;
3438 if (!options->b_prefix)
3439 options->b_prefix = b;
3442 void diff_set_noprefix(struct diff_options *options)
3444 options->a_prefix = options->b_prefix = "";
3447 void diff_set_default_prefix(struct diff_options *options)
3449 options->a_prefix = diff_src_prefix ? diff_src_prefix : "a/";
3450 options->b_prefix = diff_dst_prefix ? diff_dst_prefix : "b/";
3453 struct userdiff_driver *get_textconv(struct repository *r,
3454 struct diff_filespec *one)
3456 if (!DIFF_FILE_VALID(one))
3457 return NULL;
3459 diff_filespec_load_driver(one, r->index);
3460 return userdiff_get_textconv(r, one->driver);
3463 static struct string_list *additional_headers(struct diff_options *o,
3464 const char *path)
3466 if (!o->additional_path_headers)
3467 return NULL;
3468 return strmap_get(o->additional_path_headers, path);
3471 static void add_formatted_header(struct strbuf *msg,
3472 const char *header,
3473 const char *line_prefix,
3474 const char *meta,
3475 const char *reset)
3477 const char *next, *newline;
3479 for (next = header; *next; next = newline) {
3480 newline = strchrnul(next, '\n');
3481 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3482 (int)(newline - next), next, reset);
3483 if (*newline)
3484 newline++;
3488 static void add_formatted_headers(struct strbuf *msg,
3489 struct string_list *more_headers,
3490 const char *line_prefix,
3491 const char *meta,
3492 const char *reset)
3494 int i;
3496 for (i = 0; i < more_headers->nr; i++)
3497 add_formatted_header(msg, more_headers->items[i].string,
3498 line_prefix, meta, reset);
3501 static int diff_filepair_is_phoney(struct diff_filespec *one,
3502 struct diff_filespec *two)
3505 * This function specifically looks for pairs injected by
3506 * create_filepairs_for_header_only_notifications(). Such
3507 * pairs are "phoney" in that they do not represent any
3508 * content or even mode difference, but were inserted because
3509 * diff_queued_diff previously had no pair associated with
3510 * that path but we needed some pair to avoid losing the
3511 * "remerge CONFLICT" header associated with the path.
3513 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3516 static int set_diff_algorithm(struct diff_options *opts,
3517 const char *alg)
3519 long value = parse_algorithm_value(alg);
3521 if (value < 0)
3522 return -1;
3524 /* clear out previous settings */
3525 DIFF_XDL_CLR(opts, NEED_MINIMAL);
3526 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3527 opts->xdl_opts |= value;
3529 return 0;
3532 static void builtin_diff(const char *name_a,
3533 const char *name_b,
3534 struct diff_filespec *one,
3535 struct diff_filespec *two,
3536 const char *xfrm_msg,
3537 int must_show_header,
3538 struct diff_options *o,
3539 int complete_rewrite)
3541 mmfile_t mf1, mf2;
3542 const char *lbl[2];
3543 char *a_one, *b_two;
3544 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3545 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3546 const char *a_prefix, *b_prefix;
3547 struct userdiff_driver *textconv_one = NULL;
3548 struct userdiff_driver *textconv_two = NULL;
3549 struct strbuf header = STRBUF_INIT;
3550 const char *line_prefix = diff_line_prefix(o);
3552 diff_set_mnemonic_prefix(o, "a/", "b/");
3553 if (o->flags.reverse_diff) {
3554 a_prefix = o->b_prefix;
3555 b_prefix = o->a_prefix;
3556 } else {
3557 a_prefix = o->a_prefix;
3558 b_prefix = o->b_prefix;
3561 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3562 (!one->mode || S_ISGITLINK(one->mode)) &&
3563 (!two->mode || S_ISGITLINK(two->mode)) &&
3564 (!diff_filepair_is_phoney(one, two))) {
3565 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3566 &one->oid, &two->oid,
3567 two->dirty_submodule);
3568 return;
3569 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3570 (!one->mode || S_ISGITLINK(one->mode)) &&
3571 (!two->mode || S_ISGITLINK(two->mode)) &&
3572 (!diff_filepair_is_phoney(one, two))) {
3573 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3574 &one->oid, &two->oid,
3575 two->dirty_submodule);
3576 return;
3579 if (o->flags.allow_textconv) {
3580 textconv_one = get_textconv(o->repo, one);
3581 textconv_two = get_textconv(o->repo, two);
3584 /* Never use a non-valid filename anywhere if at all possible */
3585 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3586 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3588 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3589 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3590 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3591 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3592 if (diff_filepair_is_phoney(one, two)) {
3594 * We should only reach this point for pairs generated from
3595 * create_filepairs_for_header_only_notifications(). For
3596 * these, we want to avoid the "/dev/null" special casing
3597 * above, because we do not want such pairs shown as either
3598 * "new file" or "deleted file" below.
3600 lbl[0] = a_one;
3601 lbl[1] = b_two;
3603 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3604 if (lbl[0][0] == '/') {
3605 /* /dev/null */
3606 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3607 if (xfrm_msg)
3608 strbuf_addstr(&header, xfrm_msg);
3609 o->found_changes = 1;
3610 must_show_header = 1;
3612 else if (lbl[1][0] == '/') {
3613 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3614 if (xfrm_msg)
3615 strbuf_addstr(&header, xfrm_msg);
3616 o->found_changes = 1;
3617 must_show_header = 1;
3619 else {
3620 if (one->mode != two->mode) {
3621 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3622 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3623 o->found_changes = 1;
3624 must_show_header = 1;
3626 if (xfrm_msg)
3627 strbuf_addstr(&header, xfrm_msg);
3630 * we do not run diff between different kind
3631 * of objects.
3633 if ((one->mode ^ two->mode) & S_IFMT)
3634 goto free_ab_and_return;
3635 if (complete_rewrite &&
3636 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3637 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3638 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3639 header.buf, header.len, 0);
3640 strbuf_reset(&header);
3641 emit_rewrite_diff(name_a, name_b, one, two,
3642 textconv_one, textconv_two, o);
3643 o->found_changes = 1;
3644 goto free_ab_and_return;
3648 if (o->irreversible_delete && lbl[1][0] == '/') {
3649 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3650 header.len, 0);
3651 strbuf_reset(&header);
3652 goto free_ab_and_return;
3653 } else if (!o->flags.text &&
3654 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3655 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3656 struct strbuf sb = STRBUF_INIT;
3657 if (!one->data && !two->data &&
3658 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3659 !o->flags.binary) {
3660 if (oideq(&one->oid, &two->oid)) {
3661 if (must_show_header)
3662 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3663 header.buf, header.len,
3665 goto free_ab_and_return;
3667 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3668 header.buf, header.len, 0);
3669 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3670 diff_line_prefix(o), lbl[0], lbl[1]);
3671 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3672 sb.buf, sb.len, 0);
3673 strbuf_release(&sb);
3674 goto free_ab_and_return;
3676 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3677 fill_mmfile(o->repo, &mf2, two) < 0)
3678 die("unable to read files to diff");
3679 /* Quite common confusing case */
3680 if (mf1.size == mf2.size &&
3681 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3682 if (must_show_header)
3683 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3684 header.buf, header.len, 0);
3685 goto free_ab_and_return;
3687 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3688 strbuf_reset(&header);
3689 if (o->flags.binary)
3690 emit_binary_diff(o, &mf1, &mf2);
3691 else {
3692 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3693 diff_line_prefix(o), lbl[0], lbl[1]);
3694 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3695 sb.buf, sb.len, 0);
3696 strbuf_release(&sb);
3698 o->found_changes = 1;
3699 } else {
3700 /* Crazy xdl interfaces.. */
3701 const char *diffopts;
3702 const char *v;
3703 xpparam_t xpp;
3704 xdemitconf_t xecfg;
3705 struct emit_callback ecbdata;
3706 const struct userdiff_funcname *pe;
3708 if (must_show_header) {
3709 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3710 header.buf, header.len, 0);
3711 strbuf_reset(&header);
3714 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3715 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3717 pe = diff_funcname_pattern(o, one);
3718 if (!pe)
3719 pe = diff_funcname_pattern(o, two);
3721 memset(&xpp, 0, sizeof(xpp));
3722 memset(&xecfg, 0, sizeof(xecfg));
3723 memset(&ecbdata, 0, sizeof(ecbdata));
3724 if (o->flags.suppress_diff_headers)
3725 lbl[0] = NULL;
3726 ecbdata.label_path = lbl;
3727 ecbdata.color_diff = want_color(o->use_color);
3728 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3729 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3730 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3731 ecbdata.opt = o;
3732 if (header.len && !o->flags.suppress_diff_headers)
3733 ecbdata.header = &header;
3734 xpp.flags = o->xdl_opts;
3735 xpp.ignore_regex = o->ignore_regex;
3736 xpp.ignore_regex_nr = o->ignore_regex_nr;
3737 xpp.anchors = o->anchors;
3738 xpp.anchors_nr = o->anchors_nr;
3739 xecfg.ctxlen = o->context;
3740 xecfg.interhunkctxlen = o->interhunkcontext;
3741 xecfg.flags = XDL_EMIT_FUNCNAMES;
3742 if (o->flags.funccontext)
3743 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3744 if (pe)
3745 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3747 diffopts = getenv("GIT_DIFF_OPTS");
3748 if (!diffopts)
3750 else if (skip_prefix(diffopts, "--unified=", &v))
3751 xecfg.ctxlen = strtoul(v, NULL, 10);
3752 else if (skip_prefix(diffopts, "-u", &v))
3753 xecfg.ctxlen = strtoul(v, NULL, 10);
3755 if (o->word_diff)
3756 init_diff_words_data(&ecbdata, o, one, two);
3757 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3758 &ecbdata, &xpp, &xecfg))
3759 die("unable to generate diff for %s", one->path);
3760 if (o->word_diff)
3761 free_diff_words_data(&ecbdata);
3762 if (textconv_one)
3763 free(mf1.ptr);
3764 if (textconv_two)
3765 free(mf2.ptr);
3766 xdiff_clear_find_func(&xecfg);
3769 free_ab_and_return:
3770 strbuf_release(&header);
3771 diff_free_filespec_data(one);
3772 diff_free_filespec_data(two);
3773 free(a_one);
3774 free(b_two);
3775 return;
3778 static const char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3780 if (!is_renamed) {
3781 if (p->status == DIFF_STATUS_ADDED) {
3782 if (S_ISLNK(p->two->mode))
3783 return "new +l";
3784 else if ((p->two->mode & 0777) == 0755)
3785 return "new +x";
3786 else
3787 return "new";
3788 } else if (p->status == DIFF_STATUS_DELETED)
3789 return "gone";
3791 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3792 return "mode -l";
3793 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3794 return "mode +l";
3795 else if ((p->one->mode & 0777) == 0644 &&
3796 (p->two->mode & 0777) == 0755)
3797 return "mode +x";
3798 else if ((p->one->mode & 0777) == 0755 &&
3799 (p->two->mode & 0777) == 0644)
3800 return "mode -x";
3801 return NULL;
3804 static void builtin_diffstat(const char *name_a, const char *name_b,
3805 struct diff_filespec *one,
3806 struct diff_filespec *two,
3807 struct diffstat_t *diffstat,
3808 struct diff_options *o,
3809 struct diff_filepair *p)
3811 mmfile_t mf1, mf2;
3812 struct diffstat_file *data;
3813 int may_differ;
3814 int complete_rewrite = 0;
3816 if (!DIFF_PAIR_UNMERGED(p)) {
3817 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3818 complete_rewrite = 1;
3821 data = diffstat_add(diffstat, name_a, name_b);
3822 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3823 if (o->flags.stat_with_summary)
3824 data->comments = get_compact_summary(p, data->is_renamed);
3826 if (!one || !two) {
3827 data->is_unmerged = 1;
3828 return;
3831 /* saves some reads if true, not a guarantee of diff outcome */
3832 may_differ = !(one->oid_valid && two->oid_valid &&
3833 oideq(&one->oid, &two->oid));
3835 if (diff_filespec_is_binary(o->repo, one) ||
3836 diff_filespec_is_binary(o->repo, two)) {
3837 data->is_binary = 1;
3838 if (!may_differ) {
3839 data->added = 0;
3840 data->deleted = 0;
3841 } else {
3842 data->added = diff_filespec_size(o->repo, two);
3843 data->deleted = diff_filespec_size(o->repo, one);
3847 else if (complete_rewrite) {
3848 diff_populate_filespec(o->repo, one, NULL);
3849 diff_populate_filespec(o->repo, two, NULL);
3850 data->deleted = count_lines(one->data, one->size);
3851 data->added = count_lines(two->data, two->size);
3854 else if (may_differ) {
3855 /* Crazy xdl interfaces.. */
3856 xpparam_t xpp;
3857 xdemitconf_t xecfg;
3859 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3860 fill_mmfile(o->repo, &mf2, two) < 0)
3861 die("unable to read files to diff");
3863 memset(&xpp, 0, sizeof(xpp));
3864 memset(&xecfg, 0, sizeof(xecfg));
3865 xpp.flags = o->xdl_opts;
3866 xpp.ignore_regex = o->ignore_regex;
3867 xpp.ignore_regex_nr = o->ignore_regex_nr;
3868 xpp.anchors = o->anchors;
3869 xpp.anchors_nr = o->anchors_nr;
3870 xecfg.ctxlen = o->context;
3871 xecfg.interhunkctxlen = o->interhunkcontext;
3872 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3873 if (xdi_diff_outf(&mf1, &mf2, NULL,
3874 diffstat_consume, diffstat, &xpp, &xecfg))
3875 die("unable to generate diffstat for %s", one->path);
3877 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3878 struct diffstat_file *file =
3879 diffstat->files[diffstat->nr - 1];
3881 * Omit diffstats of modified files where nothing changed.
3882 * Even if may_differ, this might be the case due to
3883 * ignoring whitespace changes, etc.
3885 * But note that we special-case additions, deletions,
3886 * renames, and mode changes as adding an empty file,
3887 * for example is still of interest.
3889 if ((p->status == DIFF_STATUS_MODIFIED)
3890 && !file->added
3891 && !file->deleted
3892 && one->mode == two->mode) {
3893 free_diffstat_file(file);
3894 diffstat->nr--;
3899 diff_free_filespec_data(one);
3900 diff_free_filespec_data(two);
3903 static void builtin_checkdiff(const char *name_a, const char *name_b,
3904 const char *attr_path,
3905 struct diff_filespec *one,
3906 struct diff_filespec *two,
3907 struct diff_options *o)
3909 mmfile_t mf1, mf2;
3910 struct checkdiff_t data;
3912 if (!two)
3913 return;
3915 memset(&data, 0, sizeof(data));
3916 data.filename = name_b ? name_b : name_a;
3917 data.lineno = 0;
3918 data.o = o;
3919 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3920 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3922 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3923 fill_mmfile(o->repo, &mf2, two) < 0)
3924 die("unable to read files to diff");
3927 * All the other codepaths check both sides, but not checking
3928 * the "old" side here is deliberate. We are checking the newly
3929 * introduced changes, and as long as the "new" side is text, we
3930 * can and should check what it introduces.
3932 if (diff_filespec_is_binary(o->repo, two))
3933 goto free_and_return;
3934 else {
3935 /* Crazy xdl interfaces.. */
3936 xpparam_t xpp;
3937 xdemitconf_t xecfg;
3939 memset(&xpp, 0, sizeof(xpp));
3940 memset(&xecfg, 0, sizeof(xecfg));
3941 xecfg.ctxlen = 1; /* at least one context line */
3942 xpp.flags = 0;
3943 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3944 checkdiff_consume, &data,
3945 &xpp, &xecfg))
3946 die("unable to generate checkdiff for %s", one->path);
3948 if (data.ws_rule & WS_BLANK_AT_EOF) {
3949 struct emit_callback ecbdata;
3950 int blank_at_eof;
3952 ecbdata.ws_rule = data.ws_rule;
3953 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3954 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3956 if (blank_at_eof) {
3957 static char *err;
3958 if (!err)
3959 err = whitespace_error_string(WS_BLANK_AT_EOF);
3960 fprintf(o->file, "%s:%d: %s.\n",
3961 data.filename, blank_at_eof, err);
3962 data.status = 1; /* report errors */
3966 free_and_return:
3967 diff_free_filespec_data(one);
3968 diff_free_filespec_data(two);
3969 if (data.status)
3970 o->flags.check_failed = 1;
3973 struct diff_filespec *alloc_filespec(const char *path)
3975 struct diff_filespec *spec;
3977 FLEXPTR_ALLOC_STR(spec, path, path);
3978 spec->count = 1;
3979 spec->is_binary = -1;
3980 return spec;
3983 void free_filespec(struct diff_filespec *spec)
3985 if (!--spec->count) {
3986 diff_free_filespec_data(spec);
3987 free(spec);
3991 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3992 int oid_valid, unsigned short mode)
3994 if (mode) {
3995 spec->mode = canon_mode(mode);
3996 oidcpy(&spec->oid, oid);
3997 spec->oid_valid = oid_valid;
4002 * Given a name and sha1 pair, if the index tells us the file in
4003 * the work tree has that object contents, return true, so that
4004 * prepare_temp_file() does not have to inflate and extract.
4006 static int reuse_worktree_file(struct index_state *istate,
4007 const char *name,
4008 const struct object_id *oid,
4009 int want_file)
4011 const struct cache_entry *ce;
4012 struct stat st;
4013 int pos, len;
4016 * We do not read the cache ourselves here, because the
4017 * benchmark with my previous version that always reads cache
4018 * shows that it makes things worse for diff-tree comparing
4019 * two linux-2.6 kernel trees in an already checked out work
4020 * tree. This is because most diff-tree comparisons deal with
4021 * only a small number of files, while reading the cache is
4022 * expensive for a large project, and its cost outweighs the
4023 * savings we get by not inflating the object to a temporary
4024 * file. Practically, this code only helps when we are used
4025 * by diff-cache --cached, which does read the cache before
4026 * calling us.
4028 if (!istate->cache)
4029 return 0;
4031 /* We want to avoid the working directory if our caller
4032 * doesn't need the data in a normal file, this system
4033 * is rather slow with its stat/open/mmap/close syscalls,
4034 * and the object is contained in a pack file. The pack
4035 * is probably already open and will be faster to obtain
4036 * the data through than the working directory. Loose
4037 * objects however would tend to be slower as they need
4038 * to be individually opened and inflated.
4040 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
4041 return 0;
4044 * Similarly, if we'd have to convert the file contents anyway, that
4045 * makes the optimization not worthwhile.
4047 if (!want_file && would_convert_to_git(istate, name))
4048 return 0;
4051 * If this path does not match our sparse-checkout definition,
4052 * then the file will not be in the working directory.
4054 if (!path_in_sparse_checkout(name, istate))
4055 return 0;
4057 len = strlen(name);
4058 pos = index_name_pos(istate, name, len);
4059 if (pos < 0)
4060 return 0;
4061 ce = istate->cache[pos];
4064 * This is not the sha1 we are looking for, or
4065 * unreusable because it is not a regular file.
4067 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4068 return 0;
4071 * If ce is marked as "assume unchanged", there is no
4072 * guarantee that work tree matches what we are looking for.
4074 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4075 return 0;
4078 * If ce matches the file in the work tree, we can reuse it.
4080 if (ce_uptodate(ce) ||
4081 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4082 return 1;
4084 return 0;
4087 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4089 struct strbuf buf = STRBUF_INIT;
4090 const char *dirty = "";
4092 /* Are we looking at the work tree? */
4093 if (s->dirty_submodule)
4094 dirty = "-dirty";
4096 strbuf_addf(&buf, "Subproject commit %s%s\n",
4097 oid_to_hex(&s->oid), dirty);
4098 s->size = buf.len;
4099 if (size_only) {
4100 s->data = NULL;
4101 strbuf_release(&buf);
4102 } else {
4103 s->data = strbuf_detach(&buf, NULL);
4104 s->should_free = 1;
4106 return 0;
4110 * While doing rename detection and pickaxe operation, we may need to
4111 * grab the data for the blob (or file) for our own in-core comparison.
4112 * diff_filespec has data and size fields for this purpose.
4114 int diff_populate_filespec(struct repository *r,
4115 struct diff_filespec *s,
4116 const struct diff_populate_filespec_options *options)
4118 int size_only = options ? options->check_size_only : 0;
4119 int check_binary = options ? options->check_binary : 0;
4120 int err = 0;
4121 int conv_flags = global_conv_flags_eol;
4123 * demote FAIL to WARN to allow inspecting the situation
4124 * instead of refusing.
4126 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4127 conv_flags = CONV_EOL_RNDTRP_WARN;
4129 if (!DIFF_FILE_VALID(s))
4130 die("internal error: asking to populate invalid file.");
4131 if (S_ISDIR(s->mode))
4132 return -1;
4134 if (s->data)
4135 return 0;
4137 if (size_only && 0 < s->size)
4138 return 0;
4140 if (S_ISGITLINK(s->mode))
4141 return diff_populate_gitlink(s, size_only);
4143 if (!s->oid_valid ||
4144 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4145 struct strbuf buf = STRBUF_INIT;
4146 struct stat st;
4147 int fd;
4149 if (lstat(s->path, &st) < 0) {
4150 err_empty:
4151 err = -1;
4152 empty:
4153 s->data = (char *)"";
4154 s->size = 0;
4155 return err;
4157 s->size = xsize_t(st.st_size);
4158 if (!s->size)
4159 goto empty;
4160 if (S_ISLNK(st.st_mode)) {
4161 struct strbuf sb = STRBUF_INIT;
4163 if (strbuf_readlink(&sb, s->path, s->size))
4164 goto err_empty;
4165 s->size = sb.len;
4166 s->data = strbuf_detach(&sb, NULL);
4167 s->should_free = 1;
4168 return 0;
4172 * Even if the caller would be happy with getting
4173 * only the size, we cannot return early at this
4174 * point if the path requires us to run the content
4175 * conversion.
4177 if (size_only && !would_convert_to_git(r->index, s->path))
4178 return 0;
4181 * Note: this check uses xsize_t(st.st_size) that may
4182 * not be the true size of the blob after it goes
4183 * through convert_to_git(). This may not strictly be
4184 * correct, but the whole point of big_file_threshold
4185 * and is_binary check being that we want to avoid
4186 * opening the file and inspecting the contents, this
4187 * is probably fine.
4189 if (check_binary &&
4190 s->size > big_file_threshold && s->is_binary == -1) {
4191 s->is_binary = 1;
4192 return 0;
4194 fd = open(s->path, O_RDONLY);
4195 if (fd < 0)
4196 goto err_empty;
4197 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4198 close(fd);
4199 s->should_munmap = 1;
4202 * Convert from working tree format to canonical git format
4204 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4205 size_t size = 0;
4206 munmap(s->data, s->size);
4207 s->should_munmap = 0;
4208 s->data = strbuf_detach(&buf, &size);
4209 s->size = size;
4210 s->should_free = 1;
4213 else {
4214 struct object_info info = {
4215 .sizep = &s->size
4218 if (!(size_only || check_binary))
4220 * Set contentp, since there is no chance that merely
4221 * the size is sufficient.
4223 info.contentp = &s->data;
4225 if (options && options->missing_object_cb) {
4226 if (!oid_object_info_extended(r, &s->oid, &info,
4227 OBJECT_INFO_LOOKUP_REPLACE |
4228 OBJECT_INFO_SKIP_FETCH_OBJECT))
4229 goto object_read;
4230 options->missing_object_cb(options->missing_object_data);
4232 if (oid_object_info_extended(r, &s->oid, &info,
4233 OBJECT_INFO_LOOKUP_REPLACE))
4234 die("unable to read %s", oid_to_hex(&s->oid));
4236 object_read:
4237 if (size_only || check_binary) {
4238 if (size_only)
4239 return 0;
4240 if (s->size > big_file_threshold && s->is_binary == -1) {
4241 s->is_binary = 1;
4242 return 0;
4245 if (!info.contentp) {
4246 info.contentp = &s->data;
4247 if (oid_object_info_extended(r, &s->oid, &info,
4248 OBJECT_INFO_LOOKUP_REPLACE))
4249 die("unable to read %s", oid_to_hex(&s->oid));
4251 s->should_free = 1;
4253 return 0;
4256 void diff_free_filespec_blob(struct diff_filespec *s)
4258 if (s->should_free)
4259 free(s->data);
4260 else if (s->should_munmap)
4261 munmap(s->data, s->size);
4263 if (s->should_free || s->should_munmap) {
4264 s->should_free = s->should_munmap = 0;
4265 s->data = NULL;
4269 void diff_free_filespec_data(struct diff_filespec *s)
4271 if (!s)
4272 return;
4274 diff_free_filespec_blob(s);
4275 FREE_AND_NULL(s->cnt_data);
4278 static void prep_temp_blob(struct index_state *istate,
4279 const char *path, struct diff_tempfile *temp,
4280 void *blob,
4281 unsigned long size,
4282 const struct object_id *oid,
4283 int mode)
4285 struct strbuf buf = STRBUF_INIT;
4286 char *path_dup = xstrdup(path);
4287 const char *base = basename(path_dup);
4288 struct checkout_metadata meta;
4290 init_checkout_metadata(&meta, NULL, NULL, oid);
4292 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4293 if (!temp->tempfile)
4294 die_errno("unable to create temp-file");
4295 if (convert_to_working_tree(istate, path,
4296 (const char *)blob, (size_t)size, &buf, &meta)) {
4297 blob = buf.buf;
4298 size = buf.len;
4300 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4301 close_tempfile_gently(temp->tempfile))
4302 die_errno("unable to write temp-file");
4303 temp->name = get_tempfile_path(temp->tempfile);
4304 oid_to_hex_r(temp->hex, oid);
4305 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4306 strbuf_release(&buf);
4307 free(path_dup);
4310 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4311 struct diff_filespec *one)
4313 struct diff_tempfile *temp = claim_diff_tempfile();
4315 if (!DIFF_FILE_VALID(one)) {
4316 not_a_valid_file:
4317 /* A '-' entry produces this for file-2, and
4318 * a '+' entry produces this for file-1.
4320 temp->name = "/dev/null";
4321 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4322 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4323 return temp;
4326 if (!S_ISGITLINK(one->mode) &&
4327 (!one->oid_valid ||
4328 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4329 struct stat st;
4330 if (lstat(one->path, &st) < 0) {
4331 if (errno == ENOENT)
4332 goto not_a_valid_file;
4333 die_errno("stat(%s)", one->path);
4335 if (S_ISLNK(st.st_mode)) {
4336 struct strbuf sb = STRBUF_INIT;
4337 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4338 die_errno("readlink(%s)", one->path);
4339 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4340 (one->oid_valid ?
4341 &one->oid : null_oid()),
4342 (one->oid_valid ?
4343 one->mode : S_IFLNK));
4344 strbuf_release(&sb);
4346 else {
4347 /* we can borrow from the file in the work tree */
4348 temp->name = one->path;
4349 if (!one->oid_valid)
4350 oid_to_hex_r(temp->hex, null_oid());
4351 else
4352 oid_to_hex_r(temp->hex, &one->oid);
4353 /* Even though we may sometimes borrow the
4354 * contents from the work tree, we always want
4355 * one->mode. mode is trustworthy even when
4356 * !(one->oid_valid), as long as
4357 * DIFF_FILE_VALID(one).
4359 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4361 return temp;
4363 else {
4364 if (diff_populate_filespec(r, one, NULL))
4365 die("cannot read data blob for %s", one->path);
4366 prep_temp_blob(r->index, one->path, temp,
4367 one->data, one->size,
4368 &one->oid, one->mode);
4370 return temp;
4373 static void add_external_diff_name(struct repository *r,
4374 struct strvec *argv,
4375 struct diff_filespec *df)
4377 struct diff_tempfile *temp = prepare_temp_file(r, df);
4378 strvec_push(argv, temp->name);
4379 strvec_push(argv, temp->hex);
4380 strvec_push(argv, temp->mode);
4383 /* An external diff command takes:
4385 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4386 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4389 static void run_external_diff(const struct external_diff *pgm,
4390 const char *name,
4391 const char *other,
4392 struct diff_filespec *one,
4393 struct diff_filespec *two,
4394 const char *xfrm_msg,
4395 struct diff_options *o)
4397 struct child_process cmd = CHILD_PROCESS_INIT;
4398 struct diff_queue_struct *q = &diff_queued_diff;
4399 int quiet = !(o->output_format & DIFF_FORMAT_PATCH);
4400 int rc;
4403 * Trivial equality is handled by diff_unmodified_pair() before
4404 * we get here. If we don't need to show the diff and the
4405 * external diff program lacks the ability to tell us whether
4406 * it's empty then we consider it non-empty without even asking.
4408 if (!pgm->trust_exit_code && quiet) {
4409 o->found_changes = 1;
4410 return;
4413 strvec_push(&cmd.args, pgm->cmd);
4414 strvec_push(&cmd.args, name);
4416 if (one && two) {
4417 add_external_diff_name(o->repo, &cmd.args, one);
4418 add_external_diff_name(o->repo, &cmd.args, two);
4419 if (other) {
4420 strvec_push(&cmd.args, other);
4421 if (xfrm_msg)
4422 strvec_push(&cmd.args, xfrm_msg);
4426 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4427 ++o->diff_path_counter);
4428 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4430 diff_free_filespec_data(one);
4431 diff_free_filespec_data(two);
4432 cmd.use_shell = 1;
4433 cmd.no_stdout = quiet;
4434 rc = run_command(&cmd);
4435 if (!pgm->trust_exit_code && rc == 0)
4436 o->found_changes = 1;
4437 else if (pgm->trust_exit_code && rc == 0)
4438 ; /* nothing */
4439 else if (pgm->trust_exit_code && rc == 1)
4440 o->found_changes = 1;
4441 else
4442 die(_("external diff died, stopping at %s"), name);
4444 remove_tempfile();
4447 static int similarity_index(struct diff_filepair *p)
4449 return p->score * 100 / MAX_SCORE;
4452 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4454 if (startup_info->have_repository)
4455 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4456 else {
4457 char *hex = oid_to_hex(oid);
4458 if (abbrev < 0)
4459 abbrev = FALLBACK_DEFAULT_ABBREV;
4460 if (abbrev > the_hash_algo->hexsz)
4461 BUG("oid abbreviation out of range: %d", abbrev);
4462 if (abbrev)
4463 hex[abbrev] = '\0';
4464 return hex;
4468 static void fill_metainfo(struct strbuf *msg,
4469 const char *name,
4470 const char *other,
4471 struct diff_filespec *one,
4472 struct diff_filespec *two,
4473 struct diff_options *o,
4474 struct diff_filepair *p,
4475 int *must_show_header,
4476 int use_color)
4478 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4479 const char *reset = diff_get_color(use_color, DIFF_RESET);
4480 const char *line_prefix = diff_line_prefix(o);
4481 struct string_list *more_headers = NULL;
4483 *must_show_header = 1;
4484 strbuf_init(msg, PATH_MAX * 2 + 300);
4485 switch (p->status) {
4486 case DIFF_STATUS_COPIED:
4487 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4488 line_prefix, set, similarity_index(p));
4489 strbuf_addf(msg, "%s\n%s%scopy from ",
4490 reset, line_prefix, set);
4491 quote_c_style(name, msg, NULL, 0);
4492 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4493 quote_c_style(other, msg, NULL, 0);
4494 strbuf_addf(msg, "%s\n", reset);
4495 break;
4496 case DIFF_STATUS_RENAMED:
4497 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4498 line_prefix, set, similarity_index(p));
4499 strbuf_addf(msg, "%s\n%s%srename from ",
4500 reset, line_prefix, set);
4501 quote_c_style(name, msg, NULL, 0);
4502 strbuf_addf(msg, "%s\n%s%srename to ",
4503 reset, line_prefix, set);
4504 quote_c_style(other, msg, NULL, 0);
4505 strbuf_addf(msg, "%s\n", reset);
4506 break;
4507 case DIFF_STATUS_MODIFIED:
4508 if (p->score) {
4509 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4510 line_prefix,
4511 set, similarity_index(p), reset);
4512 break;
4514 /* fallthru */
4515 default:
4516 *must_show_header = 0;
4518 if ((more_headers = additional_headers(o, name))) {
4519 add_formatted_headers(msg, more_headers,
4520 line_prefix, set, reset);
4521 *must_show_header = 1;
4523 if (one && two && !oideq(&one->oid, &two->oid)) {
4524 const unsigned hexsz = the_hash_algo->hexsz;
4525 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4527 if (o->flags.full_index)
4528 abbrev = hexsz;
4530 if (o->flags.binary) {
4531 mmfile_t mf;
4532 if ((!fill_mmfile(o->repo, &mf, one) &&
4533 diff_filespec_is_binary(o->repo, one)) ||
4534 (!fill_mmfile(o->repo, &mf, two) &&
4535 diff_filespec_is_binary(o->repo, two)))
4536 abbrev = hexsz;
4538 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4539 diff_abbrev_oid(&one->oid, abbrev),
4540 diff_abbrev_oid(&two->oid, abbrev));
4541 if (one->mode == two->mode)
4542 strbuf_addf(msg, " %06o", one->mode);
4543 strbuf_addf(msg, "%s\n", reset);
4547 static void run_diff_cmd(const struct external_diff *pgm,
4548 const char *name,
4549 const char *other,
4550 const char *attr_path,
4551 struct diff_filespec *one,
4552 struct diff_filespec *two,
4553 struct strbuf *msg,
4554 struct diff_options *o,
4555 struct diff_filepair *p)
4557 const char *xfrm_msg = NULL;
4558 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4559 int must_show_header = 0;
4560 struct userdiff_driver *drv = NULL;
4562 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4563 drv = userdiff_find_by_path(o->repo->index, attr_path);
4565 if (o->flags.allow_external && drv && drv->external.cmd)
4566 pgm = &drv->external;
4568 if (msg) {
4570 * don't use colors when the header is intended for an
4571 * external diff driver
4573 fill_metainfo(msg, name, other, one, two, o, p,
4574 &must_show_header,
4575 want_color(o->use_color) && !pgm);
4576 xfrm_msg = msg->len ? msg->buf : NULL;
4579 if (pgm) {
4580 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4581 return;
4583 if (one && two) {
4584 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4585 set_diff_algorithm(o, drv->algorithm);
4587 builtin_diff(name, other ? other : name,
4588 one, two, xfrm_msg, must_show_header,
4589 o, complete_rewrite);
4590 } else {
4591 fprintf(o->file, "* Unmerged path %s\n", name);
4592 o->found_changes = 1;
4596 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4598 if (DIFF_FILE_VALID(one)) {
4599 if (!one->oid_valid) {
4600 struct stat st;
4601 if (one->is_stdin) {
4602 oidclr(&one->oid, the_repository->hash_algo);
4603 return;
4605 if (lstat(one->path, &st) < 0)
4606 die_errno("stat '%s'", one->path);
4607 if (index_path(istate, &one->oid, one->path, &st, 0))
4608 die("cannot hash %s", one->path);
4611 else
4612 oidclr(&one->oid, the_repository->hash_algo);
4615 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4617 /* Strip the prefix but do not molest /dev/null and absolute paths */
4618 if (*namep && !is_absolute_path(*namep)) {
4619 *namep += prefix_length;
4620 if (**namep == '/')
4621 ++*namep;
4623 if (*otherp && !is_absolute_path(*otherp)) {
4624 *otherp += prefix_length;
4625 if (**otherp == '/')
4626 ++*otherp;
4630 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4632 const struct external_diff *pgm = external_diff();
4633 struct strbuf msg;
4634 struct diff_filespec *one = p->one;
4635 struct diff_filespec *two = p->two;
4636 const char *name;
4637 const char *other;
4638 const char *attr_path;
4640 name = one->path;
4641 other = (strcmp(name, two->path) ? two->path : NULL);
4642 attr_path = name;
4643 if (o->prefix_length)
4644 strip_prefix(o->prefix_length, &name, &other);
4646 if (!o->flags.allow_external)
4647 pgm = NULL;
4649 if (DIFF_PAIR_UNMERGED(p)) {
4650 run_diff_cmd(pgm, name, NULL, attr_path,
4651 NULL, NULL, NULL, o, p);
4652 return;
4655 diff_fill_oid_info(one, o->repo->index);
4656 diff_fill_oid_info(two, o->repo->index);
4658 if (!pgm &&
4659 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4660 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4662 * a filepair that changes between file and symlink
4663 * needs to be split into deletion and creation.
4665 struct diff_filespec *null = alloc_filespec(two->path);
4666 run_diff_cmd(NULL, name, other, attr_path,
4667 one, null, &msg,
4668 o, p);
4669 free(null);
4670 strbuf_release(&msg);
4672 null = alloc_filespec(one->path);
4673 run_diff_cmd(NULL, name, other, attr_path,
4674 null, two, &msg, o, p);
4675 free(null);
4677 else
4678 run_diff_cmd(pgm, name, other, attr_path,
4679 one, two, &msg, o, p);
4681 strbuf_release(&msg);
4684 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4685 struct diffstat_t *diffstat)
4687 const char *name;
4688 const char *other;
4690 if (!o->ignore_driver_algorithm) {
4691 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4692 p->one->path);
4694 if (drv && drv->algorithm)
4695 set_diff_algorithm(o, drv->algorithm);
4698 if (DIFF_PAIR_UNMERGED(p)) {
4699 /* unmerged */
4700 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4701 diffstat, o, p);
4702 return;
4705 name = p->one->path;
4706 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4708 if (o->prefix_length)
4709 strip_prefix(o->prefix_length, &name, &other);
4711 diff_fill_oid_info(p->one, o->repo->index);
4712 diff_fill_oid_info(p->two, o->repo->index);
4714 builtin_diffstat(name, other, p->one, p->two,
4715 diffstat, o, p);
4718 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4720 const char *name;
4721 const char *other;
4722 const char *attr_path;
4724 if (DIFF_PAIR_UNMERGED(p)) {
4725 /* unmerged */
4726 return;
4729 name = p->one->path;
4730 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4731 attr_path = other ? other : name;
4733 if (o->prefix_length)
4734 strip_prefix(o->prefix_length, &name, &other);
4736 diff_fill_oid_info(p->one, o->repo->index);
4737 diff_fill_oid_info(p->two, o->repo->index);
4739 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4742 void repo_diff_setup(struct repository *r, struct diff_options *options)
4744 memcpy(options, &default_diff_options, sizeof(*options));
4746 options->file = stdout;
4747 options->repo = r;
4749 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4750 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4751 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4752 options->abbrev = DEFAULT_ABBREV;
4753 options->line_termination = '\n';
4754 options->break_opt = -1;
4755 options->rename_limit = -1;
4756 options->dirstat_permille = diff_dirstat_permille_default;
4757 options->context = diff_context_default;
4758 options->interhunkcontext = diff_interhunk_context_default;
4759 options->ws_error_highlight = ws_error_highlight_default;
4760 options->flags.rename_empty = 1;
4761 options->flags.relative_name = diff_relative;
4762 options->objfind = NULL;
4764 /* pathchange left =NULL by default */
4765 options->change = diff_change;
4766 options->add_remove = diff_addremove;
4767 options->use_color = diff_use_color_default;
4768 options->detect_rename = diff_detect_rename_default;
4769 options->xdl_opts |= diff_algorithm;
4770 if (diff_indent_heuristic)
4771 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4773 options->orderfile = diff_order_file_cfg;
4775 if (!options->flags.ignore_submodule_set)
4776 options->flags.ignore_untracked_in_submodules = 1;
4778 if (diff_no_prefix) {
4779 diff_set_noprefix(options);
4780 } else if (!diff_mnemonic_prefix) {
4781 diff_set_default_prefix(options);
4784 options->color_moved = diff_color_moved_default;
4785 options->color_moved_ws_handling = diff_color_moved_ws_default;
4788 static const char diff_status_letters[] = {
4789 DIFF_STATUS_ADDED,
4790 DIFF_STATUS_COPIED,
4791 DIFF_STATUS_DELETED,
4792 DIFF_STATUS_MODIFIED,
4793 DIFF_STATUS_RENAMED,
4794 DIFF_STATUS_TYPE_CHANGED,
4795 DIFF_STATUS_UNKNOWN,
4796 DIFF_STATUS_UNMERGED,
4797 DIFF_STATUS_FILTER_AON,
4798 DIFF_STATUS_FILTER_BROKEN,
4799 '\0',
4802 static unsigned int filter_bit['Z' + 1];
4804 static void prepare_filter_bits(void)
4806 int i;
4808 if (!filter_bit[DIFF_STATUS_ADDED]) {
4809 for (i = 0; diff_status_letters[i]; i++)
4810 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4814 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4816 return opt->filter & filter_bit[(int) status];
4819 unsigned diff_filter_bit(char status)
4821 prepare_filter_bits();
4822 return filter_bit[(int) status];
4825 int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
4827 unsigned forbidden_magic;
4829 if (ps->nr != 1) {
4830 if (die_on_error)
4831 die(_("--follow requires exactly one pathspec"));
4832 return 0;
4835 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
4836 PATHSPEC_LITERAL);
4837 if (forbidden_magic) {
4838 if (die_on_error) {
4839 struct strbuf sb = STRBUF_INIT;
4840 pathspec_magic_names(forbidden_magic, &sb);
4841 die(_("pathspec magic not supported by --follow: %s"),
4842 sb.buf);
4844 return 0;
4847 return 1;
4850 void diff_setup_done(struct diff_options *options)
4852 unsigned check_mask = DIFF_FORMAT_NAME |
4853 DIFF_FORMAT_NAME_STATUS |
4854 DIFF_FORMAT_CHECKDIFF |
4855 DIFF_FORMAT_NO_OUTPUT;
4857 * This must be signed because we're comparing against a potentially
4858 * negative value.
4860 const int hexsz = the_hash_algo->hexsz;
4862 if (options->set_default)
4863 options->set_default(options);
4865 if (HAS_MULTI_BITS(options->output_format & check_mask))
4866 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4867 "--name-only", "--name-status", "--check", "-s");
4869 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4870 die(_("options '%s', '%s', and '%s' cannot be used together"),
4871 "-G", "-S", "--find-object");
4873 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4874 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4875 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4877 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4878 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4879 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4882 * Most of the time we can say "there are changes"
4883 * only by checking if there are changed paths, but
4884 * --ignore-whitespace* options force us to look
4885 * inside contents.
4888 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4889 options->ignore_regex_nr)
4890 options->flags.diff_from_contents = 1;
4891 else
4892 options->flags.diff_from_contents = 0;
4894 if (options->flags.find_copies_harder)
4895 options->detect_rename = DIFF_DETECT_COPY;
4897 if (!options->flags.relative_name)
4898 options->prefix = NULL;
4899 if (options->prefix)
4900 options->prefix_length = strlen(options->prefix);
4901 else
4902 options->prefix_length = 0;
4905 * --name-only, --name-status, --checkdiff, and -s
4906 * turn other output format off.
4908 if (options->output_format & (DIFF_FORMAT_NAME |
4909 DIFF_FORMAT_NAME_STATUS |
4910 DIFF_FORMAT_CHECKDIFF |
4911 DIFF_FORMAT_NO_OUTPUT))
4912 options->output_format &= ~(DIFF_FORMAT_RAW |
4913 DIFF_FORMAT_NUMSTAT |
4914 DIFF_FORMAT_DIFFSTAT |
4915 DIFF_FORMAT_SHORTSTAT |
4916 DIFF_FORMAT_DIRSTAT |
4917 DIFF_FORMAT_SUMMARY |
4918 DIFF_FORMAT_PATCH);
4921 * These cases always need recursive; we do not drop caller-supplied
4922 * recursive bits for other formats here.
4924 if (options->output_format & (DIFF_FORMAT_PATCH |
4925 DIFF_FORMAT_NUMSTAT |
4926 DIFF_FORMAT_DIFFSTAT |
4927 DIFF_FORMAT_SHORTSTAT |
4928 DIFF_FORMAT_DIRSTAT |
4929 DIFF_FORMAT_SUMMARY |
4930 DIFF_FORMAT_CHECKDIFF))
4931 options->flags.recursive = 1;
4933 * Also pickaxe would not work very well if you do not say recursive
4935 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4936 options->flags.recursive = 1;
4938 * When patches are generated, submodules diffed against the work tree
4939 * must be checked for dirtiness too so it can be shown in the output
4941 if (options->output_format & DIFF_FORMAT_PATCH)
4942 options->flags.dirty_submodules = 1;
4944 if (options->detect_rename && options->rename_limit < 0)
4945 options->rename_limit = diff_rename_limit_default;
4946 if (hexsz < options->abbrev)
4947 options->abbrev = hexsz; /* full */
4950 * It does not make sense to show the first hit we happened
4951 * to have found. It does not make sense not to return with
4952 * exit code in such a case either.
4954 if (options->flags.quick) {
4955 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4956 options->flags.exit_with_status = 1;
4960 * External diffs could declare non-identical contents equal
4961 * (think diff --ignore-space-change).
4963 if (options->flags.allow_external && options->flags.exit_with_status)
4964 options->flags.diff_from_contents = 1;
4966 options->diff_path_counter = 0;
4968 if (options->flags.follow_renames)
4969 diff_check_follow_pathspec(&options->pathspec, 1);
4971 if (!options->use_color ||
4972 (options->flags.allow_external && external_diff()))
4973 options->color_moved = 0;
4975 if (options->filter_not) {
4976 if (!options->filter)
4977 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4978 options->filter &= ~options->filter_not;
4982 int parse_long_opt(const char *opt, const char **argv,
4983 const char **optarg)
4985 const char *arg = argv[0];
4986 if (!skip_prefix(arg, "--", &arg))
4987 return 0;
4988 if (!skip_prefix(arg, opt, &arg))
4989 return 0;
4990 if (*arg == '=') { /* stuck form: --option=value */
4991 *optarg = arg + 1;
4992 return 1;
4994 if (*arg != '\0')
4995 return 0;
4996 /* separate form: --option value */
4997 if (!argv[1])
4998 die("Option '--%s' requires a value", opt);
4999 *optarg = argv[1];
5000 return 2;
5003 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
5005 struct diff_options *options = opt->value;
5006 int width = options->stat_width;
5007 int name_width = options->stat_name_width;
5008 int graph_width = options->stat_graph_width;
5009 int count = options->stat_count;
5010 char *end;
5012 BUG_ON_OPT_NEG(unset);
5014 if (!strcmp(opt->long_name, "stat")) {
5015 if (value) {
5016 width = strtoul(value, &end, 10);
5017 if (*end == ',')
5018 name_width = strtoul(end+1, &end, 10);
5019 if (*end == ',')
5020 count = strtoul(end+1, &end, 10);
5021 if (*end)
5022 return error(_("invalid --stat value: %s"), value);
5024 } else if (!strcmp(opt->long_name, "stat-width")) {
5025 width = strtoul(value, &end, 10);
5026 if (*end)
5027 return error(_("%s expects a numerical value"),
5028 opt->long_name);
5029 } else if (!strcmp(opt->long_name, "stat-name-width")) {
5030 name_width = strtoul(value, &end, 10);
5031 if (*end)
5032 return error(_("%s expects a numerical value"),
5033 opt->long_name);
5034 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
5035 graph_width = strtoul(value, &end, 10);
5036 if (*end)
5037 return error(_("%s expects a numerical value"),
5038 opt->long_name);
5039 } else if (!strcmp(opt->long_name, "stat-count")) {
5040 count = strtoul(value, &end, 10);
5041 if (*end)
5042 return error(_("%s expects a numerical value"),
5043 opt->long_name);
5044 } else
5045 BUG("%s should not get here", opt->long_name);
5047 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5048 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5049 options->stat_name_width = name_width;
5050 options->stat_graph_width = graph_width;
5051 options->stat_width = width;
5052 options->stat_count = count;
5053 return 0;
5056 static int parse_dirstat_opt(struct diff_options *options, const char *params)
5058 struct strbuf errmsg = STRBUF_INIT;
5059 if (parse_dirstat_params(options, params, &errmsg))
5060 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
5061 errmsg.buf);
5062 strbuf_release(&errmsg);
5064 * The caller knows a dirstat-related option is given from the command
5065 * line; allow it to say "return this_function();"
5067 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5068 options->output_format |= DIFF_FORMAT_DIRSTAT;
5069 return 1;
5072 static int diff_opt_diff_filter(const struct option *option,
5073 const char *optarg, int unset)
5075 struct diff_options *opt = option->value;
5076 int i, optch;
5078 BUG_ON_OPT_NEG(unset);
5079 prepare_filter_bits();
5081 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5082 unsigned int bit;
5083 int negate;
5085 if ('a' <= optch && optch <= 'z') {
5086 negate = 1;
5087 optch = toupper(optch);
5088 } else {
5089 negate = 0;
5092 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5093 if (!bit)
5094 return error(_("unknown change class '%c' in --diff-filter=%s"),
5095 optarg[i], optarg);
5096 if (negate)
5097 opt->filter_not |= bit;
5098 else
5099 opt->filter |= bit;
5101 return 0;
5104 static void enable_patch_output(int *fmt)
5106 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5107 *fmt |= DIFF_FORMAT_PATCH;
5110 static int diff_opt_ws_error_highlight(const struct option *option,
5111 const char *arg, int unset)
5113 struct diff_options *opt = option->value;
5114 int val = parse_ws_error_highlight(arg);
5116 BUG_ON_OPT_NEG(unset);
5117 if (val < 0)
5118 return error(_("unknown value after ws-error-highlight=%.*s"),
5119 -1 - val, arg);
5120 opt->ws_error_highlight = val;
5121 return 0;
5124 static int diff_opt_find_object(const struct option *option,
5125 const char *arg, int unset)
5127 struct diff_options *opt = option->value;
5128 struct object_id oid;
5130 BUG_ON_OPT_NEG(unset);
5131 if (repo_get_oid(the_repository, arg, &oid))
5132 return error(_("unable to resolve '%s'"), arg);
5134 if (!opt->objfind)
5135 CALLOC_ARRAY(opt->objfind, 1);
5137 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5138 opt->flags.recursive = 1;
5139 opt->flags.tree_in_recursive = 1;
5140 oidset_insert(opt->objfind, &oid);
5141 return 0;
5144 static int diff_opt_anchored(const struct option *opt,
5145 const char *arg, int unset)
5147 struct diff_options *options = opt->value;
5149 BUG_ON_OPT_NEG(unset);
5150 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5151 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5152 options->anchors_alloc);
5153 options->anchors[options->anchors_nr++] = xstrdup(arg);
5154 return 0;
5157 static int diff_opt_binary(const struct option *opt,
5158 const char *arg, int unset)
5160 struct diff_options *options = opt->value;
5162 BUG_ON_OPT_NEG(unset);
5163 BUG_ON_OPT_ARG(arg);
5164 enable_patch_output(&options->output_format);
5165 options->flags.binary = 1;
5166 return 0;
5169 static int diff_opt_break_rewrites(const struct option *opt,
5170 const char *arg, int unset)
5172 int *break_opt = opt->value;
5173 int opt1, opt2;
5175 BUG_ON_OPT_NEG(unset);
5176 if (!arg)
5177 arg = "";
5178 opt1 = parse_rename_score(&arg);
5179 if (*arg == 0)
5180 opt2 = 0;
5181 else if (*arg != '/')
5182 return error(_("%s expects <n>/<m> form"), opt->long_name);
5183 else {
5184 arg++;
5185 opt2 = parse_rename_score(&arg);
5187 if (*arg != 0)
5188 return error(_("%s expects <n>/<m> form"), opt->long_name);
5189 *break_opt = opt1 | (opt2 << 16);
5190 return 0;
5193 static int diff_opt_char(const struct option *opt,
5194 const char *arg, int unset)
5196 char *value = opt->value;
5198 BUG_ON_OPT_NEG(unset);
5199 if (arg[1])
5200 return error(_("%s expects a character, got '%s'"),
5201 opt->long_name, arg);
5202 *value = arg[0];
5203 return 0;
5206 static int diff_opt_color_moved(const struct option *opt,
5207 const char *arg, int unset)
5209 struct diff_options *options = opt->value;
5211 if (unset) {
5212 options->color_moved = COLOR_MOVED_NO;
5213 } else if (!arg) {
5214 if (diff_color_moved_default)
5215 options->color_moved = diff_color_moved_default;
5216 if (options->color_moved == COLOR_MOVED_NO)
5217 options->color_moved = COLOR_MOVED_DEFAULT;
5218 } else {
5219 int cm = parse_color_moved(arg);
5220 if (cm < 0)
5221 return error(_("bad --color-moved argument: %s"), arg);
5222 options->color_moved = cm;
5224 return 0;
5227 static int diff_opt_color_moved_ws(const struct option *opt,
5228 const char *arg, int unset)
5230 struct diff_options *options = opt->value;
5231 unsigned cm;
5233 if (unset) {
5234 options->color_moved_ws_handling = 0;
5235 return 0;
5238 cm = parse_color_moved_ws(arg);
5239 if (cm & COLOR_MOVED_WS_ERROR)
5240 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5241 options->color_moved_ws_handling = cm;
5242 return 0;
5245 static int diff_opt_color_words(const struct option *opt,
5246 const char *arg, int unset)
5248 struct diff_options *options = opt->value;
5250 BUG_ON_OPT_NEG(unset);
5251 options->use_color = 1;
5252 options->word_diff = DIFF_WORDS_COLOR;
5253 options->word_regex = arg;
5254 return 0;
5257 static int diff_opt_compact_summary(const struct option *opt,
5258 const char *arg, int unset)
5260 struct diff_options *options = opt->value;
5262 BUG_ON_OPT_ARG(arg);
5263 if (unset) {
5264 options->flags.stat_with_summary = 0;
5265 } else {
5266 options->flags.stat_with_summary = 1;
5267 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5268 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5270 return 0;
5273 static int diff_opt_diff_algorithm(const struct option *opt,
5274 const char *arg, int unset)
5276 struct diff_options *options = opt->value;
5278 BUG_ON_OPT_NEG(unset);
5280 if (set_diff_algorithm(options, arg))
5281 return error(_("option diff-algorithm accepts \"myers\", "
5282 "\"minimal\", \"patience\" and \"histogram\""));
5284 options->ignore_driver_algorithm = 1;
5286 return 0;
5289 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5290 const char *arg, int unset)
5292 struct diff_options *options = opt->value;
5294 BUG_ON_OPT_NEG(unset);
5295 BUG_ON_OPT_ARG(arg);
5297 if (set_diff_algorithm(options, opt->long_name))
5298 BUG("available diff algorithms include \"myers\", "
5299 "\"minimal\", \"patience\" and \"histogram\"");
5301 options->ignore_driver_algorithm = 1;
5303 return 0;
5306 static int diff_opt_dirstat(const struct option *opt,
5307 const char *arg, int unset)
5309 struct diff_options *options = opt->value;
5311 BUG_ON_OPT_NEG(unset);
5312 if (!strcmp(opt->long_name, "cumulative")) {
5313 if (arg)
5314 BUG("how come --cumulative take a value?");
5315 arg = "cumulative";
5316 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5317 parse_dirstat_opt(options, "files");
5318 parse_dirstat_opt(options, arg ? arg : "");
5319 return 0;
5322 static int diff_opt_find_copies(const struct option *opt,
5323 const char *arg, int unset)
5325 struct diff_options *options = opt->value;
5327 BUG_ON_OPT_NEG(unset);
5328 if (!arg)
5329 arg = "";
5330 options->rename_score = parse_rename_score(&arg);
5331 if (*arg != 0)
5332 return error(_("invalid argument to %s"), opt->long_name);
5334 if (options->detect_rename == DIFF_DETECT_COPY)
5335 options->flags.find_copies_harder = 1;
5336 else
5337 options->detect_rename = DIFF_DETECT_COPY;
5339 return 0;
5342 static int diff_opt_find_renames(const struct option *opt,
5343 const char *arg, int unset)
5345 struct diff_options *options = opt->value;
5347 BUG_ON_OPT_NEG(unset);
5348 if (!arg)
5349 arg = "";
5350 options->rename_score = parse_rename_score(&arg);
5351 if (*arg != 0)
5352 return error(_("invalid argument to %s"), opt->long_name);
5354 options->detect_rename = DIFF_DETECT_RENAME;
5355 return 0;
5358 static int diff_opt_follow(const struct option *opt,
5359 const char *arg, int unset)
5361 struct diff_options *options = opt->value;
5363 BUG_ON_OPT_ARG(arg);
5364 if (unset) {
5365 options->flags.follow_renames = 0;
5366 options->flags.default_follow_renames = 0;
5367 } else {
5368 options->flags.follow_renames = 1;
5370 return 0;
5373 static int diff_opt_ignore_submodules(const struct option *opt,
5374 const char *arg, int unset)
5376 struct diff_options *options = opt->value;
5378 BUG_ON_OPT_NEG(unset);
5379 if (!arg)
5380 arg = "all";
5381 options->flags.override_submodule_config = 1;
5382 handle_ignore_submodules_arg(options, arg);
5383 return 0;
5386 static int diff_opt_line_prefix(const struct option *opt,
5387 const char *optarg, int unset)
5389 struct diff_options *options = opt->value;
5391 BUG_ON_OPT_NEG(unset);
5392 options->line_prefix = optarg;
5393 options->line_prefix_length = strlen(options->line_prefix);
5394 graph_setup_line_prefix(options);
5395 return 0;
5398 static int diff_opt_no_prefix(const struct option *opt,
5399 const char *optarg, int unset)
5401 struct diff_options *options = opt->value;
5403 BUG_ON_OPT_NEG(unset);
5404 BUG_ON_OPT_ARG(optarg);
5405 diff_set_noprefix(options);
5406 return 0;
5409 static int diff_opt_default_prefix(const struct option *opt,
5410 const char *optarg, int unset)
5412 struct diff_options *options = opt->value;
5414 BUG_ON_OPT_NEG(unset);
5415 BUG_ON_OPT_ARG(optarg);
5416 FREE_AND_NULL(diff_src_prefix);
5417 FREE_AND_NULL(diff_dst_prefix);
5418 diff_set_default_prefix(options);
5419 return 0;
5422 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5423 const struct option *opt,
5424 const char *arg, int unset)
5426 struct diff_options *options = opt->value;
5427 char *path;
5429 BUG_ON_OPT_NEG(unset);
5430 path = prefix_filename(ctx->prefix, arg);
5431 options->file = xfopen(path, "w");
5432 options->close_file = 1;
5433 if (options->use_color != GIT_COLOR_ALWAYS)
5434 options->use_color = GIT_COLOR_NEVER;
5435 free(path);
5436 return 0;
5439 static int diff_opt_patience(const struct option *opt,
5440 const char *arg, int unset)
5442 struct diff_options *options = opt->value;
5443 int i;
5445 BUG_ON_OPT_NEG(unset);
5446 BUG_ON_OPT_ARG(arg);
5448 * Both --patience and --anchored use PATIENCE_DIFF
5449 * internally, so remove any anchors previously
5450 * specified.
5452 for (i = 0; i < options->anchors_nr; i++)
5453 free(options->anchors[i]);
5454 options->anchors_nr = 0;
5455 options->ignore_driver_algorithm = 1;
5457 return set_diff_algorithm(options, "patience");
5460 static int diff_opt_ignore_regex(const struct option *opt,
5461 const char *arg, int unset)
5463 struct diff_options *options = opt->value;
5464 regex_t *regex;
5466 BUG_ON_OPT_NEG(unset);
5467 regex = xmalloc(sizeof(*regex));
5468 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5469 return error(_("invalid regex given to -I: '%s'"), arg);
5470 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5471 options->ignore_regex_alloc);
5472 options->ignore_regex[options->ignore_regex_nr++] = regex;
5473 return 0;
5476 static int diff_opt_pickaxe_regex(const struct option *opt,
5477 const char *arg, int unset)
5479 struct diff_options *options = opt->value;
5481 BUG_ON_OPT_NEG(unset);
5482 options->pickaxe = arg;
5483 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5484 return 0;
5487 static int diff_opt_pickaxe_string(const struct option *opt,
5488 const char *arg, int unset)
5490 struct diff_options *options = opt->value;
5492 BUG_ON_OPT_NEG(unset);
5493 options->pickaxe = arg;
5494 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5495 return 0;
5498 static int diff_opt_relative(const struct option *opt,
5499 const char *arg, int unset)
5501 struct diff_options *options = opt->value;
5503 options->flags.relative_name = !unset;
5504 if (arg)
5505 options->prefix = arg;
5506 return 0;
5509 static int diff_opt_submodule(const struct option *opt,
5510 const char *arg, int unset)
5512 struct diff_options *options = opt->value;
5514 BUG_ON_OPT_NEG(unset);
5515 if (!arg)
5516 arg = "log";
5517 if (parse_submodule_params(options, arg))
5518 return error(_("failed to parse --submodule option parameter: '%s'"),
5519 arg);
5520 return 0;
5523 static int diff_opt_textconv(const struct option *opt,
5524 const char *arg, int unset)
5526 struct diff_options *options = opt->value;
5528 BUG_ON_OPT_ARG(arg);
5529 if (unset) {
5530 options->flags.allow_textconv = 0;
5531 } else {
5532 options->flags.allow_textconv = 1;
5533 options->flags.textconv_set_via_cmdline = 1;
5535 return 0;
5538 static int diff_opt_unified(const struct option *opt,
5539 const char *arg, int unset)
5541 struct diff_options *options = opt->value;
5542 char *s;
5544 BUG_ON_OPT_NEG(unset);
5546 if (arg) {
5547 options->context = strtol(arg, &s, 10);
5548 if (*s)
5549 return error(_("%s expects a numerical value"), "--unified");
5551 enable_patch_output(&options->output_format);
5553 return 0;
5556 static int diff_opt_word_diff(const struct option *opt,
5557 const char *arg, int unset)
5559 struct diff_options *options = opt->value;
5561 BUG_ON_OPT_NEG(unset);
5562 if (arg) {
5563 if (!strcmp(arg, "plain"))
5564 options->word_diff = DIFF_WORDS_PLAIN;
5565 else if (!strcmp(arg, "color")) {
5566 options->use_color = 1;
5567 options->word_diff = DIFF_WORDS_COLOR;
5569 else if (!strcmp(arg, "porcelain"))
5570 options->word_diff = DIFF_WORDS_PORCELAIN;
5571 else if (!strcmp(arg, "none"))
5572 options->word_diff = DIFF_WORDS_NONE;
5573 else
5574 return error(_("bad --word-diff argument: %s"), arg);
5575 } else {
5576 if (options->word_diff == DIFF_WORDS_NONE)
5577 options->word_diff = DIFF_WORDS_PLAIN;
5579 return 0;
5582 static int diff_opt_word_diff_regex(const struct option *opt,
5583 const char *arg, int unset)
5585 struct diff_options *options = opt->value;
5587 BUG_ON_OPT_NEG(unset);
5588 if (options->word_diff == DIFF_WORDS_NONE)
5589 options->word_diff = DIFF_WORDS_PLAIN;
5590 options->word_regex = arg;
5591 return 0;
5594 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5596 struct diff_options *options = opt->value;
5598 BUG_ON_OPT_NEG(unset);
5599 if (!strcmp(opt->long_name, "skip-to"))
5600 options->skip_instead_of_rotate = 1;
5601 else
5602 options->skip_instead_of_rotate = 0;
5603 options->rotate_to = arg;
5604 return 0;
5608 * Consider adding new flags to __git_diff_common_options
5609 * in contrib/completion/git-completion.bash
5611 struct option *add_diff_options(const struct option *opts,
5612 struct diff_options *options)
5614 struct option parseopts[] = {
5615 OPT_GROUP(N_("Diff output format options")),
5616 OPT_BITOP('p', "patch", &options->output_format,
5617 N_("generate patch"),
5618 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5619 OPT_SET_INT('s', "no-patch", &options->output_format,
5620 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
5621 OPT_BITOP('u', NULL, &options->output_format,
5622 N_("generate patch"),
5623 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5624 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5625 N_("generate diffs with <n> lines context"),
5626 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5627 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5628 N_("generate diffs with <n> lines context")),
5629 OPT_BITOP(0, "raw", &options->output_format,
5630 N_("generate the diff in raw format"),
5631 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
5632 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5633 N_("synonym for '-p --raw'"),
5634 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5635 DIFF_FORMAT_NO_OUTPUT),
5636 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5637 N_("synonym for '-p --stat'"),
5638 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5639 DIFF_FORMAT_NO_OUTPUT),
5640 OPT_BITOP(0, "numstat", &options->output_format,
5641 N_("machine friendly --stat"),
5642 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5643 OPT_BITOP(0, "shortstat", &options->output_format,
5644 N_("output only the last line of --stat"),
5645 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
5646 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1>,<param2>..."),
5647 N_("output the distribution of relative amount of changes for each sub-directory"),
5648 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5649 diff_opt_dirstat),
5650 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5651 N_("synonym for --dirstat=cumulative"),
5652 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5653 diff_opt_dirstat),
5654 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1>,<param2>..."),
5655 N_("synonym for --dirstat=files,<param1>,<param2>..."),
5656 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5657 diff_opt_dirstat),
5658 OPT_BIT_F(0, "check", &options->output_format,
5659 N_("warn if changes introduce conflict markers or whitespace errors"),
5660 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5661 OPT_BITOP(0, "summary", &options->output_format,
5662 N_("condensed summary such as creations, renames and mode changes"),
5663 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
5664 OPT_BIT_F(0, "name-only", &options->output_format,
5665 N_("show only names of changed files"),
5666 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5667 OPT_BIT_F(0, "name-status", &options->output_format,
5668 N_("show only names and status of changed files"),
5669 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5670 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5671 N_("generate diffstat"),
5672 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5673 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5674 N_("generate diffstat with a given width"),
5675 PARSE_OPT_NONEG, diff_opt_stat),
5676 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5677 N_("generate diffstat with a given name width"),
5678 PARSE_OPT_NONEG, diff_opt_stat),
5679 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5680 N_("generate diffstat with a given graph width"),
5681 PARSE_OPT_NONEG, diff_opt_stat),
5682 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5683 N_("generate diffstat with limited lines"),
5684 PARSE_OPT_NONEG, diff_opt_stat),
5685 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5686 N_("generate compact summary in diffstat"),
5687 PARSE_OPT_NOARG, diff_opt_compact_summary),
5688 OPT_CALLBACK_F(0, "binary", options, NULL,
5689 N_("output a binary diff that can be applied"),
5690 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5691 OPT_BOOL(0, "full-index", &options->flags.full_index,
5692 N_("show full pre- and post-image object names on the \"index\" lines")),
5693 OPT_COLOR_FLAG(0, "color", &options->use_color,
5694 N_("show colored diff")),
5695 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5696 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5697 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5698 OPT_SET_INT('z', NULL, &options->line_termination,
5699 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5701 OPT__ABBREV(&options->abbrev),
5702 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5703 N_("show the given source prefix instead of \"a/\""),
5704 PARSE_OPT_NONEG),
5705 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5706 N_("show the given destination prefix instead of \"b/\""),
5707 PARSE_OPT_NONEG),
5708 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5709 N_("prepend an additional prefix to every line of output"),
5710 PARSE_OPT_NONEG, diff_opt_line_prefix),
5711 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5712 N_("do not show any source or destination prefix"),
5713 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5714 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5715 N_("use default prefixes a/ and b/"),
5716 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5717 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5718 N_("show context between diff hunks up to the specified number of lines"),
5719 PARSE_OPT_NONEG),
5720 OPT_CALLBACK_F(0, "output-indicator-new",
5721 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5722 N_("<char>"),
5723 N_("specify the character to indicate a new line instead of '+'"),
5724 PARSE_OPT_NONEG, diff_opt_char),
5725 OPT_CALLBACK_F(0, "output-indicator-old",
5726 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5727 N_("<char>"),
5728 N_("specify the character to indicate an old line instead of '-'"),
5729 PARSE_OPT_NONEG, diff_opt_char),
5730 OPT_CALLBACK_F(0, "output-indicator-context",
5731 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5732 N_("<char>"),
5733 N_("specify the character to indicate a context instead of ' '"),
5734 PARSE_OPT_NONEG, diff_opt_char),
5736 OPT_GROUP(N_("Diff rename options")),
5737 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5738 N_("break complete rewrite changes into pairs of delete and create"),
5739 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5740 diff_opt_break_rewrites),
5741 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5742 N_("detect renames"),
5743 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5744 diff_opt_find_renames),
5745 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5746 N_("omit the preimage for deletes"),
5747 1, PARSE_OPT_NONEG),
5748 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5749 N_("detect copies"),
5750 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5751 diff_opt_find_copies),
5752 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5753 N_("use unmodified files as source to find copies")),
5754 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5755 N_("disable rename detection"),
5756 0, PARSE_OPT_NONEG),
5757 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5758 N_("use empty blobs as rename source")),
5759 OPT_CALLBACK_F(0, "follow", options, NULL,
5760 N_("continue listing the history of a file beyond renames"),
5761 PARSE_OPT_NOARG, diff_opt_follow),
5762 OPT_INTEGER('l', NULL, &options->rename_limit,
5763 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5765 OPT_GROUP(N_("Diff algorithm options")),
5766 OPT_CALLBACK_F(0, "minimal", options, NULL,
5767 N_("produce the smallest possible diff"),
5768 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5769 diff_opt_diff_algorithm_no_arg),
5770 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5771 N_("ignore whitespace when comparing lines"),
5772 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5773 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5774 N_("ignore changes in amount of whitespace"),
5775 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5776 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5777 N_("ignore changes in whitespace at EOL"),
5778 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5779 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5780 N_("ignore carrier-return at the end of line"),
5781 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5782 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5783 N_("ignore changes whose lines are all blank"),
5784 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5785 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5786 N_("ignore changes whose all lines match <regex>"),
5787 0, diff_opt_ignore_regex),
5788 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5789 N_("heuristic to shift diff hunk boundaries for easy reading"),
5790 XDF_INDENT_HEURISTIC),
5791 OPT_CALLBACK_F(0, "patience", options, NULL,
5792 N_("generate diff using the \"patience diff\" algorithm"),
5793 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5794 diff_opt_patience),
5795 OPT_CALLBACK_F(0, "histogram", options, NULL,
5796 N_("generate diff using the \"histogram diff\" algorithm"),
5797 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5798 diff_opt_diff_algorithm_no_arg),
5799 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5800 N_("choose a diff algorithm"),
5801 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5802 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5803 N_("generate diff using the \"anchored diff\" algorithm"),
5804 PARSE_OPT_NONEG, diff_opt_anchored),
5805 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5806 N_("show word diff, using <mode> to delimit changed words"),
5807 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5808 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5809 N_("use <regex> to decide what a word is"),
5810 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5811 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5812 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5813 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5814 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5815 N_("moved lines of code are colored differently"),
5816 PARSE_OPT_OPTARG, diff_opt_color_moved),
5817 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5818 N_("how white spaces are ignored in --color-moved"),
5819 0, diff_opt_color_moved_ws),
5821 OPT_GROUP(N_("Other diff options")),
5822 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5823 N_("when run from subdir, exclude changes outside and show relative paths"),
5824 PARSE_OPT_OPTARG,
5825 diff_opt_relative),
5826 OPT_BOOL('a', "text", &options->flags.text,
5827 N_("treat all files as text")),
5828 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5829 N_("swap two inputs, reverse the diff")),
5830 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5831 N_("exit with 1 if there were differences, 0 otherwise")),
5832 OPT_BOOL(0, "quiet", &options->flags.quick,
5833 N_("disable all output of the program")),
5834 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5835 N_("allow an external diff helper to be executed")),
5836 OPT_CALLBACK_F(0, "textconv", options, NULL,
5837 N_("run external text conversion filters when comparing binary files"),
5838 PARSE_OPT_NOARG, diff_opt_textconv),
5839 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5840 N_("ignore changes to submodules in the diff generation"),
5841 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5842 diff_opt_ignore_submodules),
5843 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5844 N_("specify how differences in submodules are shown"),
5845 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5846 diff_opt_submodule),
5847 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5848 N_("hide 'git add -N' entries from the index"),
5849 1, PARSE_OPT_NONEG),
5850 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5851 N_("treat 'git add -N' entries as real in the index"),
5852 0, PARSE_OPT_NONEG),
5853 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5854 N_("look for differences that change the number of occurrences of the specified string"),
5855 0, diff_opt_pickaxe_string),
5856 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5857 N_("look for differences that change the number of occurrences of the specified regex"),
5858 0, diff_opt_pickaxe_regex),
5859 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5860 N_("show all changes in the changeset with -S or -G"),
5861 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5862 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5863 N_("treat <string> in -S as extended POSIX regular expression"),
5864 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5865 OPT_FILENAME('O', NULL, &options->orderfile,
5866 N_("control the order in which files appear in the output")),
5867 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5868 N_("show the change in the specified path first"),
5869 PARSE_OPT_NONEG, diff_opt_rotate_to),
5870 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5871 N_("skip the output to the specified path"),
5872 PARSE_OPT_NONEG, diff_opt_rotate_to),
5873 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5874 N_("look for differences that change the number of occurrences of the specified object"),
5875 PARSE_OPT_NONEG, diff_opt_find_object),
5876 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5877 N_("select files by diff type"),
5878 PARSE_OPT_NONEG, diff_opt_diff_filter),
5879 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5880 N_("output to a specific file"),
5881 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5883 OPT_END()
5886 return parse_options_concat(opts, parseopts);
5889 int diff_opt_parse(struct diff_options *options,
5890 const char **av, int ac, const char *prefix)
5892 struct option no_options[] = { OPT_END() };
5893 struct option *parseopts = add_diff_options(no_options, options);
5895 if (!prefix)
5896 prefix = "";
5898 ac = parse_options(ac, av, prefix, parseopts, NULL,
5899 PARSE_OPT_KEEP_DASHDASH |
5900 PARSE_OPT_KEEP_UNKNOWN_OPT |
5901 PARSE_OPT_NO_INTERNAL_HELP |
5902 PARSE_OPT_ONE_SHOT |
5903 PARSE_OPT_STOP_AT_NON_OPTION);
5904 free(parseopts);
5906 return ac;
5909 int parse_rename_score(const char **cp_p)
5911 unsigned long num, scale;
5912 int ch, dot;
5913 const char *cp = *cp_p;
5915 num = 0;
5916 scale = 1;
5917 dot = 0;
5918 for (;;) {
5919 ch = *cp;
5920 if ( !dot && ch == '.' ) {
5921 scale = 1;
5922 dot = 1;
5923 } else if ( ch == '%' ) {
5924 scale = dot ? scale*100 : 100;
5925 cp++; /* % is always at the end */
5926 break;
5927 } else if ( ch >= '0' && ch <= '9' ) {
5928 if ( scale < 100000 ) {
5929 scale *= 10;
5930 num = (num*10) + (ch-'0');
5932 } else {
5933 break;
5935 cp++;
5937 *cp_p = cp;
5939 /* user says num divided by scale and we say internally that
5940 * is MAX_SCORE * num / scale.
5942 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5945 struct diff_queue_struct diff_queued_diff;
5947 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5949 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5950 queue->queue[queue->nr++] = dp;
5953 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5954 struct diff_filespec *one,
5955 struct diff_filespec *two)
5957 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5958 dp->one = one;
5959 dp->two = two;
5960 if (queue)
5961 diff_q(queue, dp);
5962 return dp;
5965 void diff_free_filepair(struct diff_filepair *p)
5967 free_filespec(p->one);
5968 free_filespec(p->two);
5969 free(p);
5972 void diff_free_queue(struct diff_queue_struct *q)
5974 for (int i = 0; i < q->nr; i++)
5975 diff_free_filepair(q->queue[i]);
5976 free(q->queue);
5979 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5981 int abblen;
5982 const char *abbrev;
5984 /* Do we want all 40 hex characters? */
5985 if (len == the_hash_algo->hexsz)
5986 return oid_to_hex(oid);
5988 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5989 abbrev = diff_abbrev_oid(oid, len);
5991 if (!print_sha1_ellipsis())
5992 return abbrev;
5994 abblen = strlen(abbrev);
5997 * In well-behaved cases, where the abbreviated result is the
5998 * same as the requested length, append three dots after the
5999 * abbreviation (hence the whole logic is limited to the case
6000 * where abblen < 37); when the actual abbreviated result is a
6001 * bit longer than the requested length, we reduce the number
6002 * of dots so that they match the well-behaved ones. However,
6003 * if the actual abbreviation is longer than the requested
6004 * length by more than three, we give up on aligning, and add
6005 * three dots anyway, to indicate that the output is not the
6006 * full object name. Yes, this may be suboptimal, but this
6007 * appears only in "diff --raw --abbrev" output and it is not
6008 * worth the effort to change it now. Note that this would
6009 * likely to work fine when the automatic sizing of default
6010 * abbreviation length is used--we would be fed -1 in "len" in
6011 * that case, and will end up always appending three-dots, but
6012 * the automatic sizing is supposed to give abblen that ensures
6013 * uniqueness across all objects (statistically speaking).
6015 if (abblen < the_hash_algo->hexsz - 3) {
6016 static char hex[GIT_MAX_HEXSZ + 1];
6017 if (len < abblen && abblen <= len + 2)
6018 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
6019 else
6020 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
6021 return hex;
6024 return oid_to_hex(oid);
6027 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6029 int line_termination = opt->line_termination;
6030 int inter_name_termination = line_termination ? '\t' : '\0';
6032 fprintf(opt->file, "%s", diff_line_prefix(opt));
6033 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
6034 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
6035 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
6036 fprintf(opt->file, "%s ",
6037 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
6039 if (p->score) {
6040 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
6041 inter_name_termination);
6042 } else {
6043 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6046 if (p->status == DIFF_STATUS_COPIED ||
6047 p->status == DIFF_STATUS_RENAMED) {
6048 const char *name_a, *name_b;
6049 name_a = p->one->path;
6050 name_b = p->two->path;
6051 strip_prefix(opt->prefix_length, &name_a, &name_b);
6052 write_name_quoted(name_a, opt->file, inter_name_termination);
6053 write_name_quoted(name_b, opt->file, line_termination);
6054 } else {
6055 const char *name_a, *name_b;
6056 name_a = p->one->mode ? p->one->path : p->two->path;
6057 name_b = NULL;
6058 strip_prefix(opt->prefix_length, &name_a, &name_b);
6059 write_name_quoted(name_a, opt->file, line_termination);
6063 int diff_unmodified_pair(struct diff_filepair *p)
6065 /* This function is written stricter than necessary to support
6066 * the currently implemented transformers, but the idea is to
6067 * let transformers to produce diff_filepairs any way they want,
6068 * and filter and clean them up here before producing the output.
6070 struct diff_filespec *one = p->one, *two = p->two;
6072 if (DIFF_PAIR_UNMERGED(p))
6073 return 0; /* unmerged is interesting */
6075 /* deletion, addition, mode or type change
6076 * and rename are all interesting.
6078 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
6079 DIFF_PAIR_MODE_CHANGED(p) ||
6080 strcmp(one->path, two->path))
6081 return 0;
6083 /* both are valid and point at the same path. that is, we are
6084 * dealing with a change.
6086 if (one->oid_valid && two->oid_valid &&
6087 oideq(&one->oid, &two->oid) &&
6088 !one->dirty_submodule && !two->dirty_submodule)
6089 return 1; /* no change */
6090 if (!one->oid_valid && !two->oid_valid)
6091 return 1; /* both look at the same file on the filesystem. */
6092 return 0;
6095 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6097 int include_conflict_headers =
6098 (additional_headers(o, p->one->path) &&
6099 !o->pickaxe_opts &&
6100 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6103 * Check if we can return early without showing a diff. Note that
6104 * diff_filepair only stores {oid, path, mode, is_valid}
6105 * information for each path, and thus diff_unmodified_pair() only
6106 * considers those bits of info. However, we do not want pairs
6107 * created by create_filepairs_for_header_only_notifications()
6108 * (which always look like unmodified pairs) to be ignored, so
6109 * return early if both p is unmodified AND we don't want to
6110 * include_conflict_headers.
6112 if (diff_unmodified_pair(p) && !include_conflict_headers)
6113 return;
6115 /* Actually, we can also return early to avoid showing tree diffs */
6116 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6117 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6118 return;
6120 run_diff(p, o);
6123 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6124 struct diffstat_t *diffstat)
6126 if (diff_unmodified_pair(p))
6127 return;
6129 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6130 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6131 return; /* no useful stat for tree diffs */
6133 run_diffstat(p, o, diffstat);
6136 static void diff_flush_checkdiff(struct diff_filepair *p,
6137 struct diff_options *o)
6139 if (diff_unmodified_pair(p))
6140 return;
6142 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6143 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6144 return; /* nothing to check in tree diffs */
6146 run_checkdiff(p, o);
6149 int diff_queue_is_empty(struct diff_options *o)
6151 struct diff_queue_struct *q = &diff_queued_diff;
6152 int i;
6153 int include_conflict_headers =
6154 (o->additional_path_headers &&
6155 strmap_get_size(o->additional_path_headers) &&
6156 !o->pickaxe_opts &&
6157 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6159 if (include_conflict_headers)
6160 return 0;
6162 for (i = 0; i < q->nr; i++)
6163 if (!diff_unmodified_pair(q->queue[i]))
6164 return 0;
6165 return 1;
6168 #if DIFF_DEBUG
6169 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6171 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6172 x, one ? one : "",
6173 s->path,
6174 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6175 s->mode,
6176 s->oid_valid ? oid_to_hex(&s->oid) : "");
6177 fprintf(stderr, "queue[%d] %s size %lu\n",
6178 x, one ? one : "",
6179 s->size);
6182 void diff_debug_filepair(const struct diff_filepair *p, int i)
6184 diff_debug_filespec(p->one, i, "one");
6185 diff_debug_filespec(p->two, i, "two");
6186 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6187 p->score, p->status ? p->status : '?',
6188 p->one->rename_used, p->broken_pair);
6191 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6193 int i;
6194 if (msg)
6195 fprintf(stderr, "%s\n", msg);
6196 fprintf(stderr, "q->nr = %d\n", q->nr);
6197 for (i = 0; i < q->nr; i++) {
6198 struct diff_filepair *p = q->queue[i];
6199 diff_debug_filepair(p, i);
6202 #endif
6204 static void diff_resolve_rename_copy(void)
6206 int i;
6207 struct diff_filepair *p;
6208 struct diff_queue_struct *q = &diff_queued_diff;
6210 diff_debug_queue("resolve-rename-copy", q);
6212 for (i = 0; i < q->nr; i++) {
6213 p = q->queue[i];
6214 p->status = 0; /* undecided */
6215 if (DIFF_PAIR_UNMERGED(p))
6216 p->status = DIFF_STATUS_UNMERGED;
6217 else if (!DIFF_FILE_VALID(p->one))
6218 p->status = DIFF_STATUS_ADDED;
6219 else if (!DIFF_FILE_VALID(p->two))
6220 p->status = DIFF_STATUS_DELETED;
6221 else if (DIFF_PAIR_TYPE_CHANGED(p))
6222 p->status = DIFF_STATUS_TYPE_CHANGED;
6224 /* from this point on, we are dealing with a pair
6225 * whose both sides are valid and of the same type, i.e.
6226 * either in-place edit or rename/copy edit.
6228 else if (DIFF_PAIR_RENAME(p)) {
6230 * A rename might have re-connected a broken
6231 * pair up, causing the pathnames to be the
6232 * same again. If so, that's not a rename at
6233 * all, just a modification..
6235 * Otherwise, see if this source was used for
6236 * multiple renames, in which case we decrement
6237 * the count, and call it a copy.
6239 if (!strcmp(p->one->path, p->two->path))
6240 p->status = DIFF_STATUS_MODIFIED;
6241 else if (--p->one->rename_used > 0)
6242 p->status = DIFF_STATUS_COPIED;
6243 else
6244 p->status = DIFF_STATUS_RENAMED;
6246 else if (!oideq(&p->one->oid, &p->two->oid) ||
6247 p->one->mode != p->two->mode ||
6248 p->one->dirty_submodule ||
6249 p->two->dirty_submodule ||
6250 is_null_oid(&p->one->oid))
6251 p->status = DIFF_STATUS_MODIFIED;
6252 else {
6253 /* This is a "no-change" entry and should not
6254 * happen anymore, but prepare for broken callers.
6256 error("feeding unmodified %s to diffcore",
6257 p->one->path);
6258 p->status = DIFF_STATUS_UNKNOWN;
6261 diff_debug_queue("resolve-rename-copy done", q);
6264 static int check_pair_status(struct diff_filepair *p)
6266 switch (p->status) {
6267 case DIFF_STATUS_UNKNOWN:
6268 return 0;
6269 case 0:
6270 die("internal error in diff-resolve-rename-copy");
6271 default:
6272 return 1;
6276 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6278 int fmt = opt->output_format;
6280 if (fmt & DIFF_FORMAT_CHECKDIFF)
6281 diff_flush_checkdiff(p, opt);
6282 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6283 diff_flush_raw(p, opt);
6284 else if (fmt & DIFF_FORMAT_NAME) {
6285 const char *name_a, *name_b;
6286 name_a = p->two->path;
6287 name_b = NULL;
6288 strip_prefix(opt->prefix_length, &name_a, &name_b);
6289 fprintf(opt->file, "%s", diff_line_prefix(opt));
6290 write_name_quoted(name_a, opt->file, opt->line_termination);
6293 opt->found_changes = 1;
6296 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6298 struct strbuf sb = STRBUF_INIT;
6299 if (fs->mode)
6300 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6301 else
6302 strbuf_addf(&sb, " %s ", newdelete);
6304 quote_c_style(fs->path, &sb, NULL, 0);
6305 strbuf_addch(&sb, '\n');
6306 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6307 sb.buf, sb.len, 0);
6308 strbuf_release(&sb);
6311 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6312 int show_name)
6314 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6315 struct strbuf sb = STRBUF_INIT;
6316 strbuf_addf(&sb, " mode change %06o => %06o",
6317 p->one->mode, p->two->mode);
6318 if (show_name) {
6319 strbuf_addch(&sb, ' ');
6320 quote_c_style(p->two->path, &sb, NULL, 0);
6322 strbuf_addch(&sb, '\n');
6323 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6324 sb.buf, sb.len, 0);
6325 strbuf_release(&sb);
6329 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6330 struct diff_filepair *p)
6332 struct strbuf sb = STRBUF_INIT;
6333 struct strbuf names = STRBUF_INIT;
6335 pprint_rename(&names, p->one->path, p->two->path);
6336 strbuf_addf(&sb, " %s %s (%d%%)\n",
6337 renamecopy, names.buf, similarity_index(p));
6338 strbuf_release(&names);
6339 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6340 sb.buf, sb.len, 0);
6341 show_mode_change(opt, p, 0);
6342 strbuf_release(&sb);
6345 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6347 switch(p->status) {
6348 case DIFF_STATUS_DELETED:
6349 show_file_mode_name(opt, "delete", p->one);
6350 break;
6351 case DIFF_STATUS_ADDED:
6352 show_file_mode_name(opt, "create", p->two);
6353 break;
6354 case DIFF_STATUS_COPIED:
6355 show_rename_copy(opt, "copy", p);
6356 break;
6357 case DIFF_STATUS_RENAMED:
6358 show_rename_copy(opt, "rename", p);
6359 break;
6360 default:
6361 if (p->score) {
6362 struct strbuf sb = STRBUF_INIT;
6363 strbuf_addstr(&sb, " rewrite ");
6364 quote_c_style(p->two->path, &sb, NULL, 0);
6365 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6366 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6367 sb.buf, sb.len, 0);
6368 strbuf_release(&sb);
6370 show_mode_change(opt, p, !p->score);
6371 break;
6375 struct patch_id_t {
6376 git_hash_ctx *ctx;
6377 int patchlen;
6380 static int remove_space(char *line, int len)
6382 int i;
6383 char *dst = line;
6384 unsigned char c;
6386 for (i = 0; i < len; i++)
6387 if (!isspace((c = line[i])))
6388 *dst++ = c;
6390 return dst - line;
6393 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6395 unsigned char hash[GIT_MAX_RAWSZ];
6396 unsigned short carry = 0;
6397 int i;
6399 the_hash_algo->final_fn(hash, ctx);
6400 the_hash_algo->init_fn(ctx);
6401 /* 20-byte sum, with carry */
6402 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6403 carry += result->hash[i] + hash[i];
6404 result->hash[i] = carry;
6405 carry >>= 8;
6409 static int patch_id_consume(void *priv, char *line, unsigned long len)
6411 struct patch_id_t *data = priv;
6412 int new_len;
6414 if (len > 12 && starts_with(line, "\\ "))
6415 return 0;
6416 new_len = remove_space(line, len);
6418 the_hash_algo->update_fn(data->ctx, line, new_len);
6419 data->patchlen += new_len;
6420 return 0;
6423 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6425 the_hash_algo->update_fn(ctx, str, strlen(str));
6428 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6430 /* large enough for 2^32 in octal */
6431 char buf[12];
6432 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6433 the_hash_algo->update_fn(ctx, buf, len);
6436 /* returns 0 upon success, and writes result into oid */
6437 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6439 struct diff_queue_struct *q = &diff_queued_diff;
6440 int i;
6441 git_hash_ctx ctx;
6442 struct patch_id_t data;
6444 the_hash_algo->init_fn(&ctx);
6445 memset(&data, 0, sizeof(struct patch_id_t));
6446 data.ctx = &ctx;
6447 oidclr(oid, the_repository->hash_algo);
6449 for (i = 0; i < q->nr; i++) {
6450 xpparam_t xpp;
6451 xdemitconf_t xecfg;
6452 mmfile_t mf1, mf2;
6453 struct diff_filepair *p = q->queue[i];
6454 int len1, len2;
6456 memset(&xpp, 0, sizeof(xpp));
6457 memset(&xecfg, 0, sizeof(xecfg));
6458 if (p->status == 0)
6459 return error("internal diff status error");
6460 if (p->status == DIFF_STATUS_UNKNOWN)
6461 continue;
6462 if (diff_unmodified_pair(p))
6463 continue;
6464 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6465 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6466 continue;
6467 if (DIFF_PAIR_UNMERGED(p))
6468 continue;
6470 diff_fill_oid_info(p->one, options->repo->index);
6471 diff_fill_oid_info(p->two, options->repo->index);
6473 len1 = remove_space(p->one->path, strlen(p->one->path));
6474 len2 = remove_space(p->two->path, strlen(p->two->path));
6475 patch_id_add_string(&ctx, "diff--git");
6476 patch_id_add_string(&ctx, "a/");
6477 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6478 patch_id_add_string(&ctx, "b/");
6479 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6481 if (p->one->mode == 0) {
6482 patch_id_add_string(&ctx, "newfilemode");
6483 patch_id_add_mode(&ctx, p->two->mode);
6484 } else if (p->two->mode == 0) {
6485 patch_id_add_string(&ctx, "deletedfilemode");
6486 patch_id_add_mode(&ctx, p->one->mode);
6487 } else if (p->one->mode != p->two->mode) {
6488 patch_id_add_string(&ctx, "oldmode");
6489 patch_id_add_mode(&ctx, p->one->mode);
6490 patch_id_add_string(&ctx, "newmode");
6491 patch_id_add_mode(&ctx, p->two->mode);
6494 if (diff_header_only) {
6495 /* don't do anything since we're only populating header info */
6496 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6497 diff_filespec_is_binary(options->repo, p->two)) {
6498 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6499 the_hash_algo->hexsz);
6500 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6501 the_hash_algo->hexsz);
6502 } else {
6503 if (p->one->mode == 0) {
6504 patch_id_add_string(&ctx, "---/dev/null");
6505 patch_id_add_string(&ctx, "+++b/");
6506 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6507 } else if (p->two->mode == 0) {
6508 patch_id_add_string(&ctx, "---a/");
6509 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6510 patch_id_add_string(&ctx, "+++/dev/null");
6511 } else {
6512 patch_id_add_string(&ctx, "---a/");
6513 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6514 patch_id_add_string(&ctx, "+++b/");
6515 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6518 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6519 fill_mmfile(options->repo, &mf2, p->two) < 0)
6520 return error("unable to read files to diff");
6521 xpp.flags = 0;
6522 xecfg.ctxlen = 3;
6523 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6524 if (xdi_diff_outf(&mf1, &mf2, NULL,
6525 patch_id_consume, &data, &xpp, &xecfg))
6526 return error("unable to generate patch-id diff for %s",
6527 p->one->path);
6529 flush_one_hunk(oid, &ctx);
6532 return 0;
6535 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6537 struct diff_queue_struct *q = &diff_queued_diff;
6538 int result = diff_get_patch_id(options, oid, diff_header_only);
6540 diff_free_queue(q);
6541 DIFF_QUEUE_CLEAR(q);
6543 return result;
6546 static int is_summary_empty(const struct diff_queue_struct *q)
6548 int i;
6550 for (i = 0; i < q->nr; i++) {
6551 const struct diff_filepair *p = q->queue[i];
6553 switch (p->status) {
6554 case DIFF_STATUS_DELETED:
6555 case DIFF_STATUS_ADDED:
6556 case DIFF_STATUS_COPIED:
6557 case DIFF_STATUS_RENAMED:
6558 return 0;
6559 default:
6560 if (p->score)
6561 return 0;
6562 if (p->one->mode && p->two->mode &&
6563 p->one->mode != p->two->mode)
6564 return 0;
6565 break;
6568 return 1;
6571 static const char rename_limit_warning[] =
6572 N_("exhaustive rename detection was skipped due to too many files.");
6574 static const char degrade_cc_to_c_warning[] =
6575 N_("only found copies from modified paths due to too many files.");
6577 static const char rename_limit_advice[] =
6578 N_("you may want to set your %s variable to at least "
6579 "%d and retry the command.");
6581 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6583 fflush(stdout);
6584 if (degraded_cc)
6585 warning(_(degrade_cc_to_c_warning));
6586 else if (needed)
6587 warning(_(rename_limit_warning));
6588 else
6589 return;
6590 if (0 < needed)
6591 warning(_(rename_limit_advice), varname, needed);
6594 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6596 struct strset present;
6597 struct diff_queue_struct *q = &diff_queued_diff;
6598 struct hashmap_iter iter;
6599 struct strmap_entry *e;
6600 int i;
6602 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6605 * Find out which paths exist in diff_queued_diff, preferring
6606 * one->path for any pair that has multiple paths.
6608 for (i = 0; i < q->nr; i++) {
6609 struct diff_filepair *p = q->queue[i];
6610 char *path = p->one->path ? p->one->path : p->two->path;
6612 if (strmap_contains(o->additional_path_headers, path))
6613 strset_add(&present, path);
6617 * Loop over paths in additional_path_headers; for each NOT already
6618 * in diff_queued_diff, create a synthetic filepair and insert that
6619 * into diff_queued_diff.
6621 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6622 if (!strset_contains(&present, e->key)) {
6623 struct diff_filespec *one, *two;
6624 struct diff_filepair *p;
6626 one = alloc_filespec(e->key);
6627 two = alloc_filespec(e->key);
6628 fill_filespec(one, null_oid(), 0, 0);
6629 fill_filespec(two, null_oid(), 0, 0);
6630 p = diff_queue(q, one, two);
6631 p->status = DIFF_STATUS_MODIFIED;
6635 /* Re-sort the filepairs */
6636 diffcore_fix_diff_index();
6638 /* Cleanup */
6639 strset_clear(&present);
6642 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6644 int i;
6645 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6646 struct diff_queue_struct *q = &diff_queued_diff;
6648 if (WSEH_NEW & WS_RULE_MASK)
6649 BUG("WS rules bit mask overlaps with diff symbol flags");
6651 if (o->color_moved)
6652 o->emitted_symbols = &esm;
6654 if (o->additional_path_headers)
6655 create_filepairs_for_header_only_notifications(o);
6657 for (i = 0; i < q->nr; i++) {
6658 struct diff_filepair *p = q->queue[i];
6659 if (check_pair_status(p))
6660 diff_flush_patch(p, o);
6663 if (o->emitted_symbols) {
6664 if (o->color_moved) {
6665 struct mem_pool entry_pool;
6666 struct moved_entry_list *entry_list;
6668 mem_pool_init(&entry_pool, 1024 * 1024);
6669 entry_list = add_lines_to_move_detection(o,
6670 &entry_pool);
6671 mark_color_as_moved(o, entry_list);
6672 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6673 dim_moved_lines(o);
6675 mem_pool_discard(&entry_pool, 0);
6676 free(entry_list);
6679 for (i = 0; i < esm.nr; i++)
6680 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6682 for (i = 0; i < esm.nr; i++)
6683 free((void *)esm.buf[i].line);
6684 esm.nr = 0;
6686 o->emitted_symbols = NULL;
6690 static void diff_free_file(struct diff_options *options)
6692 if (options->close_file && options->file) {
6693 fclose(options->file);
6694 options->file = NULL;
6698 static void diff_free_ignore_regex(struct diff_options *options)
6700 int i;
6702 for (i = 0; i < options->ignore_regex_nr; i++) {
6703 regfree(options->ignore_regex[i]);
6704 free(options->ignore_regex[i]);
6707 FREE_AND_NULL(options->ignore_regex);
6708 options->ignore_regex_nr = 0;
6711 void diff_free(struct diff_options *options)
6713 if (options->no_free)
6714 return;
6716 diff_free_file(options);
6717 diff_free_ignore_regex(options);
6718 clear_pathspec(&options->pathspec);
6721 void diff_flush(struct diff_options *options)
6723 struct diff_queue_struct *q = &diff_queued_diff;
6724 int i, output_format = options->output_format;
6725 int separator = 0;
6726 int dirstat_by_line = 0;
6729 * Order: raw, stat, summary, patch
6730 * or: name/name-status/checkdiff (other bits clear)
6732 if (!q->nr && !options->additional_path_headers)
6733 goto free_queue;
6735 if (output_format & (DIFF_FORMAT_RAW |
6736 DIFF_FORMAT_NAME |
6737 DIFF_FORMAT_NAME_STATUS |
6738 DIFF_FORMAT_CHECKDIFF)) {
6739 for (i = 0; i < q->nr; i++) {
6740 struct diff_filepair *p = q->queue[i];
6741 if (check_pair_status(p))
6742 flush_one_pair(p, options);
6744 separator++;
6747 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6748 dirstat_by_line = 1;
6750 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6751 dirstat_by_line) {
6752 struct diffstat_t diffstat;
6754 compute_diffstat(options, &diffstat, q);
6755 if (output_format & DIFF_FORMAT_NUMSTAT)
6756 show_numstat(&diffstat, options);
6757 if (output_format & DIFF_FORMAT_DIFFSTAT)
6758 show_stats(&diffstat, options);
6759 if (output_format & DIFF_FORMAT_SHORTSTAT)
6760 show_shortstats(&diffstat, options);
6761 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6762 show_dirstat_by_line(&diffstat, options);
6763 free_diffstat_info(&diffstat);
6764 separator++;
6766 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6767 show_dirstat(options);
6769 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6770 for (i = 0; i < q->nr; i++) {
6771 diff_summary(options, q->queue[i]);
6773 separator++;
6776 if (output_format & DIFF_FORMAT_PATCH) {
6777 if (separator) {
6778 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6779 if (options->stat_sep)
6780 /* attach patch instead of inline */
6781 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6782 NULL, 0, 0);
6785 diff_flush_patch_all_file_pairs(options);
6788 if (output_format & DIFF_FORMAT_CALLBACK)
6789 options->format_callback(q, options, options->format_callback_data);
6791 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6792 options->flags.exit_with_status &&
6793 options->flags.diff_from_contents) {
6795 * run diff_flush_patch for the exit status. setting
6796 * options->file to /dev/null should be safe, because we
6797 * aren't supposed to produce any output anyway.
6799 diff_free_file(options);
6800 options->file = xfopen("/dev/null", "w");
6801 options->close_file = 1;
6802 options->color_moved = 0;
6803 for (i = 0; i < q->nr; i++) {
6804 struct diff_filepair *p = q->queue[i];
6805 if (check_pair_status(p))
6806 diff_flush_patch(p, options);
6807 if (options->found_changes)
6808 break;
6812 free_queue:
6813 diff_free_queue(q);
6814 DIFF_QUEUE_CLEAR(q);
6815 diff_free(options);
6818 * Report the content-level differences with HAS_CHANGES;
6819 * diff_addremove/diff_change does not set the bit when
6820 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6822 if (options->flags.diff_from_contents) {
6823 if (options->found_changes)
6824 options->flags.has_changes = 1;
6825 else
6826 options->flags.has_changes = 0;
6830 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6832 return (((p->status == DIFF_STATUS_MODIFIED) &&
6833 ((p->score &&
6834 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6835 (!p->score &&
6836 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6837 ((p->status != DIFF_STATUS_MODIFIED) &&
6838 filter_bit_tst(p->status, options)));
6841 static void diffcore_apply_filter(struct diff_options *options)
6843 int i;
6844 struct diff_queue_struct *q = &diff_queued_diff;
6845 struct diff_queue_struct outq;
6847 DIFF_QUEUE_CLEAR(&outq);
6849 if (!options->filter)
6850 return;
6852 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6853 int found;
6854 for (i = found = 0; !found && i < q->nr; i++) {
6855 if (match_filter(options, q->queue[i]))
6856 found++;
6858 if (found)
6859 return;
6861 /* otherwise we will clear the whole queue
6862 * by copying the empty outq at the end of this
6863 * function, but first clear the current entries
6864 * in the queue.
6866 for (i = 0; i < q->nr; i++)
6867 diff_free_filepair(q->queue[i]);
6869 else {
6870 /* Only the matching ones */
6871 for (i = 0; i < q->nr; i++) {
6872 struct diff_filepair *p = q->queue[i];
6873 if (match_filter(options, p))
6874 diff_q(&outq, p);
6875 else
6876 diff_free_filepair(p);
6879 free(q->queue);
6880 *q = outq;
6883 /* Check whether two filespecs with the same mode and size are identical */
6884 static int diff_filespec_is_identical(struct repository *r,
6885 struct diff_filespec *one,
6886 struct diff_filespec *two)
6888 if (S_ISGITLINK(one->mode))
6889 return 0;
6890 if (diff_populate_filespec(r, one, NULL))
6891 return 0;
6892 if (diff_populate_filespec(r, two, NULL))
6893 return 0;
6894 return !memcmp(one->data, two->data, one->size);
6897 static int diff_filespec_check_stat_unmatch(struct repository *r,
6898 struct diff_filepair *p)
6900 struct diff_populate_filespec_options dpf_options = {
6901 .check_size_only = 1,
6902 .missing_object_cb = diff_queued_diff_prefetch,
6903 .missing_object_data = r,
6906 if (p->done_skip_stat_unmatch)
6907 return p->skip_stat_unmatch_result;
6909 p->done_skip_stat_unmatch = 1;
6910 p->skip_stat_unmatch_result = 0;
6912 * 1. Entries that come from stat info dirtiness
6913 * always have both sides (iow, not create/delete),
6914 * one side of the object name is unknown, with
6915 * the same mode and size. Keep the ones that
6916 * do not match these criteria. They have real
6917 * differences.
6919 * 2. At this point, the file is known to be modified,
6920 * with the same mode and size, and the object
6921 * name of one side is unknown. Need to inspect
6922 * the identical contents.
6924 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6925 !DIFF_FILE_VALID(p->two) ||
6926 (p->one->oid_valid && p->two->oid_valid) ||
6927 (p->one->mode != p->two->mode) ||
6928 diff_populate_filespec(r, p->one, &dpf_options) ||
6929 diff_populate_filespec(r, p->two, &dpf_options) ||
6930 (p->one->size != p->two->size) ||
6931 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6932 p->skip_stat_unmatch_result = 1;
6933 return p->skip_stat_unmatch_result;
6936 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6938 int i;
6939 struct diff_queue_struct *q = &diff_queued_diff;
6940 struct diff_queue_struct outq;
6941 DIFF_QUEUE_CLEAR(&outq);
6943 for (i = 0; i < q->nr; i++) {
6944 struct diff_filepair *p = q->queue[i];
6946 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6947 diff_q(&outq, p);
6948 else {
6950 * The caller can subtract 1 from skip_stat_unmatch
6951 * to determine how many paths were dirty only
6952 * due to stat info mismatch.
6954 if (!diffopt->flags.no_index)
6955 diffopt->skip_stat_unmatch++;
6956 diff_free_filepair(p);
6959 free(q->queue);
6960 *q = outq;
6963 static int diffnamecmp(const void *a_, const void *b_)
6965 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6966 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6967 const char *name_a, *name_b;
6969 name_a = a->one ? a->one->path : a->two->path;
6970 name_b = b->one ? b->one->path : b->two->path;
6971 return strcmp(name_a, name_b);
6974 void diffcore_fix_diff_index(void)
6976 struct diff_queue_struct *q = &diff_queued_diff;
6977 QSORT(q->queue, q->nr, diffnamecmp);
6980 void diff_add_if_missing(struct repository *r,
6981 struct oid_array *to_fetch,
6982 const struct diff_filespec *filespec)
6984 if (filespec && filespec->oid_valid &&
6985 !S_ISGITLINK(filespec->mode) &&
6986 oid_object_info_extended(r, &filespec->oid, NULL,
6987 OBJECT_INFO_FOR_PREFETCH))
6988 oid_array_append(to_fetch, &filespec->oid);
6991 void diff_queued_diff_prefetch(void *repository)
6993 struct repository *repo = repository;
6994 int i;
6995 struct diff_queue_struct *q = &diff_queued_diff;
6996 struct oid_array to_fetch = OID_ARRAY_INIT;
6998 for (i = 0; i < q->nr; i++) {
6999 struct diff_filepair *p = q->queue[i];
7000 diff_add_if_missing(repo, &to_fetch, p->one);
7001 diff_add_if_missing(repo, &to_fetch, p->two);
7005 * NEEDSWORK: Consider deduplicating the OIDs sent.
7007 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
7009 oid_array_clear(&to_fetch);
7012 void init_diffstat_widths(struct diff_options *options)
7014 options->stat_width = -1; /* use full terminal width */
7015 options->stat_name_width = -1; /* respect diff.statNameWidth config */
7016 options->stat_graph_width = -1; /* respect diff.statGraphWidth config */
7019 void diffcore_std(struct diff_options *options)
7021 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
7022 DIFF_FORMAT_NUMSTAT |
7023 DIFF_FORMAT_PATCH |
7024 DIFF_FORMAT_SHORTSTAT |
7025 DIFF_FORMAT_DIRSTAT;
7028 * Check if the user requested a blob-data-requiring diff output and/or
7029 * break-rewrite detection (which requires blob data). If yes, prefetch
7030 * the diff pairs.
7032 * If no prefetching occurs, diffcore_rename() will prefetch if it
7033 * decides that it needs inexact rename detection.
7035 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
7036 (options->output_format & output_formats_to_prefetch ||
7037 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
7038 diff_queued_diff_prefetch(options->repo);
7040 /* NOTE please keep the following in sync with diff_tree_combined() */
7041 if (options->skip_stat_unmatch)
7042 diffcore_skip_stat_unmatch(options);
7043 if (!options->found_follow) {
7044 /* See try_to_follow_renames() in tree-diff.c */
7045 if (options->break_opt != -1)
7046 diffcore_break(options->repo,
7047 options->break_opt);
7048 if (options->detect_rename)
7049 diffcore_rename(options);
7050 if (options->break_opt != -1)
7051 diffcore_merge_broken();
7053 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
7054 diffcore_pickaxe(options);
7055 if (options->orderfile)
7056 diffcore_order(options->orderfile);
7057 if (options->rotate_to)
7058 diffcore_rotate(options);
7059 if (!options->found_follow)
7060 /* See try_to_follow_renames() in tree-diff.c */
7061 diff_resolve_rename_copy();
7062 diffcore_apply_filter(options);
7064 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
7065 options->flags.has_changes = 1;
7066 else
7067 options->flags.has_changes = 0;
7069 options->found_follow = 0;
7072 int diff_result_code(struct diff_options *opt)
7074 int result = 0;
7076 diff_warn_rename_limit("diff.renameLimit",
7077 opt->needed_rename_limit,
7078 opt->degraded_cc_to_c);
7080 if (opt->flags.exit_with_status &&
7081 opt->flags.has_changes)
7082 result |= 01;
7083 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
7084 opt->flags.check_failed)
7085 result |= 02;
7086 return result;
7089 int diff_can_quit_early(struct diff_options *opt)
7091 return (opt->flags.quick &&
7092 !opt->filter &&
7093 opt->flags.has_changes);
7097 * Shall changes to this submodule be ignored?
7099 * Submodule changes can be configured to be ignored separately for each path,
7100 * but that configuration can be overridden from the command line.
7102 static int is_submodule_ignored(const char *path, struct diff_options *options)
7104 int ignored = 0;
7105 struct diff_flags orig_flags = options->flags;
7106 if (!options->flags.override_submodule_config)
7107 set_diffopt_flags_from_submodule_config(options, path);
7108 if (options->flags.ignore_submodules)
7109 ignored = 1;
7110 options->flags = orig_flags;
7111 return ignored;
7114 void compute_diffstat(struct diff_options *options,
7115 struct diffstat_t *diffstat,
7116 struct diff_queue_struct *q)
7118 int i;
7120 memset(diffstat, 0, sizeof(struct diffstat_t));
7121 for (i = 0; i < q->nr; i++) {
7122 struct diff_filepair *p = q->queue[i];
7123 if (check_pair_status(p))
7124 diff_flush_stat(p, options, diffstat);
7126 options->found_changes = !!diffstat->nr;
7129 void diff_addremove(struct diff_options *options,
7130 int addremove, unsigned mode,
7131 const struct object_id *oid,
7132 int oid_valid,
7133 const char *concatpath, unsigned dirty_submodule)
7135 struct diff_filespec *one, *two;
7137 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7138 return;
7140 /* This may look odd, but it is a preparation for
7141 * feeding "there are unchanged files which should
7142 * not produce diffs, but when you are doing copy
7143 * detection you would need them, so here they are"
7144 * entries to the diff-core. They will be prefixed
7145 * with something like '=' or '*' (I haven't decided
7146 * which but should not make any difference).
7147 * Feeding the same new and old to diff_change()
7148 * also has the same effect.
7149 * Before the final output happens, they are pruned after
7150 * merged into rename/copy pairs as appropriate.
7152 if (options->flags.reverse_diff)
7153 addremove = (addremove == '+' ? '-' :
7154 addremove == '-' ? '+' : addremove);
7156 if (options->prefix &&
7157 strncmp(concatpath, options->prefix, options->prefix_length))
7158 return;
7160 one = alloc_filespec(concatpath);
7161 two = alloc_filespec(concatpath);
7163 if (addremove != '+')
7164 fill_filespec(one, oid, oid_valid, mode);
7165 if (addremove != '-') {
7166 fill_filespec(two, oid, oid_valid, mode);
7167 two->dirty_submodule = dirty_submodule;
7170 diff_queue(&diff_queued_diff, one, two);
7171 if (!options->flags.diff_from_contents)
7172 options->flags.has_changes = 1;
7175 void diff_change(struct diff_options *options,
7176 unsigned old_mode, unsigned new_mode,
7177 const struct object_id *old_oid,
7178 const struct object_id *new_oid,
7179 int old_oid_valid, int new_oid_valid,
7180 const char *concatpath,
7181 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7183 struct diff_filespec *one, *two;
7184 struct diff_filepair *p;
7186 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7187 is_submodule_ignored(concatpath, options))
7188 return;
7190 if (options->flags.reverse_diff) {
7191 SWAP(old_mode, new_mode);
7192 SWAP(old_oid, new_oid);
7193 SWAP(old_oid_valid, new_oid_valid);
7194 SWAP(old_dirty_submodule, new_dirty_submodule);
7197 if (options->prefix &&
7198 strncmp(concatpath, options->prefix, options->prefix_length))
7199 return;
7201 one = alloc_filespec(concatpath);
7202 two = alloc_filespec(concatpath);
7203 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7204 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7205 one->dirty_submodule = old_dirty_submodule;
7206 two->dirty_submodule = new_dirty_submodule;
7207 p = diff_queue(&diff_queued_diff, one, two);
7209 if (options->flags.diff_from_contents)
7210 return;
7212 if (options->flags.quick && options->skip_stat_unmatch &&
7213 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7214 diff_free_filespec_data(p->one);
7215 diff_free_filespec_data(p->two);
7216 return;
7219 options->flags.has_changes = 1;
7222 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7224 struct diff_filepair *pair;
7225 struct diff_filespec *one, *two;
7227 if (options->prefix &&
7228 strncmp(path, options->prefix, options->prefix_length))
7229 return NULL;
7231 one = alloc_filespec(path);
7232 two = alloc_filespec(path);
7233 pair = diff_queue(&diff_queued_diff, one, two);
7234 pair->is_unmerged = 1;
7235 return pair;
7238 static char *run_textconv(struct repository *r,
7239 const char *pgm,
7240 struct diff_filespec *spec,
7241 size_t *outsize)
7243 struct diff_tempfile *temp;
7244 struct child_process child = CHILD_PROCESS_INIT;
7245 struct strbuf buf = STRBUF_INIT;
7246 int err = 0;
7248 temp = prepare_temp_file(r, spec);
7249 strvec_push(&child.args, pgm);
7250 strvec_push(&child.args, temp->name);
7252 child.use_shell = 1;
7253 child.out = -1;
7254 if (start_command(&child)) {
7255 remove_tempfile();
7256 return NULL;
7259 if (strbuf_read(&buf, child.out, 0) < 0)
7260 err = error("error reading from textconv command '%s'", pgm);
7261 close(child.out);
7263 if (finish_command(&child) || err) {
7264 strbuf_release(&buf);
7265 remove_tempfile();
7266 return NULL;
7268 remove_tempfile();
7270 return strbuf_detach(&buf, outsize);
7273 size_t fill_textconv(struct repository *r,
7274 struct userdiff_driver *driver,
7275 struct diff_filespec *df,
7276 char **outbuf)
7278 size_t size;
7280 if (!driver) {
7281 if (!DIFF_FILE_VALID(df)) {
7282 *outbuf = (char *) "";
7283 return 0;
7285 if (diff_populate_filespec(r, df, NULL))
7286 die("unable to read files to diff");
7287 *outbuf = df->data;
7288 return df->size;
7291 if (!driver->textconv)
7292 BUG("fill_textconv called with non-textconv driver");
7294 if (driver->textconv_cache && df->oid_valid) {
7295 *outbuf = notes_cache_get(driver->textconv_cache,
7296 &df->oid,
7297 &size);
7298 if (*outbuf)
7299 return size;
7302 *outbuf = run_textconv(r, driver->textconv, df, &size);
7303 if (!*outbuf)
7304 die("unable to read files to diff");
7306 if (driver->textconv_cache && df->oid_valid) {
7307 /* ignore errors, as we might be in a readonly repository */
7308 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7309 size);
7311 * we could save up changes and flush them all at the end,
7312 * but we would need an extra call after all diffing is done.
7313 * Since generating a cache entry is the slow path anyway,
7314 * this extra overhead probably isn't a big deal.
7316 notes_cache_write(driver->textconv_cache);
7319 return size;
7322 int textconv_object(struct repository *r,
7323 const char *path,
7324 unsigned mode,
7325 const struct object_id *oid,
7326 int oid_valid,
7327 char **buf,
7328 unsigned long *buf_size)
7330 struct diff_filespec *df;
7331 struct userdiff_driver *textconv;
7333 df = alloc_filespec(path);
7334 fill_filespec(df, oid, oid_valid, mode);
7335 textconv = get_textconv(r, df);
7336 if (!textconv) {
7337 free_filespec(df);
7338 return 0;
7341 *buf_size = fill_textconv(r, textconv, df, buf);
7342 free_filespec(df);
7343 return 1;
7346 void setup_diff_pager(struct diff_options *opt)
7349 * If the user asked for our exit code, then either they want --quiet
7350 * or --exit-code. We should definitely not bother with a pager in the
7351 * former case, as we will generate no output. Since we still properly
7352 * report our exit code even when a pager is run, we _could_ run a
7353 * pager with --exit-code. But since we have not done so historically,
7354 * and because it is easy to find people oneline advising "git diff
7355 * --exit-code" in hooks and other scripts, we do not do so.
7357 if (!opt->flags.exit_with_status &&
7358 check_pager_config("diff") != 0)
7359 setup_pager();