diff: cast string constant in `fill_textconv()`
[git/gitster.git] / diff.c
blobcecda216cfaf0a16b707d09e4081e0a0d773bf43
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "base85.h"
7 #include "config.h"
8 #include "convert.h"
9 #include "environment.h"
10 #include "gettext.h"
11 #include "tempfile.h"
12 #include "quote.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "delta.h"
16 #include "hex.h"
17 #include "xdiff-interface.h"
18 #include "color.h"
19 #include "run-command.h"
20 #include "utf8.h"
21 #include "object-store-ll.h"
22 #include "userdiff.h"
23 #include "submodule.h"
24 #include "hashmap.h"
25 #include "mem-pool.h"
26 #include "merge-ll.h"
27 #include "string-list.h"
28 #include "strvec.h"
29 #include "graph.h"
30 #include "oid-array.h"
31 #include "packfile.h"
32 #include "pager.h"
33 #include "parse-options.h"
34 #include "help.h"
35 #include "promisor-remote.h"
36 #include "dir.h"
37 #include "object-file.h"
38 #include "object-name.h"
39 #include "read-cache-ll.h"
40 #include "setup.h"
41 #include "strmap.h"
42 #include "ws.h"
44 #ifdef NO_FAST_WORKING_DIRECTORY
45 #define FAST_WORKING_DIRECTORY 0
46 #else
47 #define FAST_WORKING_DIRECTORY 1
48 #endif
50 static int diff_detect_rename_default;
51 static int diff_indent_heuristic = 1;
52 static int diff_rename_limit_default = 1000;
53 static int diff_suppress_blank_empty;
54 static int diff_use_color_default = -1;
55 static int diff_color_moved_default;
56 static int diff_color_moved_ws_default;
57 static int diff_context_default = 3;
58 static int diff_interhunk_context_default;
59 static char *diff_word_regex_cfg;
60 static char *external_diff_cmd_cfg;
61 static char *diff_order_file_cfg;
62 int diff_auto_refresh_index = 1;
63 static int diff_mnemonic_prefix;
64 static int diff_no_prefix;
65 static char *diff_src_prefix;
66 static char *diff_dst_prefix;
67 static int diff_relative;
68 static int diff_stat_name_width;
69 static int diff_stat_graph_width;
70 static int diff_dirstat_permille_default = 30;
71 static struct diff_options default_diff_options;
72 static long diff_algorithm;
73 static unsigned ws_error_highlight_default = WSEH_NEW;
75 static char diff_colors[][COLOR_MAXLEN] = {
76 GIT_COLOR_RESET,
77 GIT_COLOR_NORMAL, /* CONTEXT */
78 GIT_COLOR_BOLD, /* METAINFO */
79 GIT_COLOR_CYAN, /* FRAGINFO */
80 GIT_COLOR_RED, /* OLD */
81 GIT_COLOR_GREEN, /* NEW */
82 GIT_COLOR_YELLOW, /* COMMIT */
83 GIT_COLOR_BG_RED, /* WHITESPACE */
84 GIT_COLOR_NORMAL, /* FUNCINFO */
85 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
86 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
87 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
88 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
89 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
90 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
91 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
92 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
93 GIT_COLOR_FAINT, /* CONTEXT_DIM */
94 GIT_COLOR_FAINT_RED, /* OLD_DIM */
95 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
96 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
97 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
98 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
101 static const char *color_diff_slots[] = {
102 [DIFF_CONTEXT] = "context",
103 [DIFF_METAINFO] = "meta",
104 [DIFF_FRAGINFO] = "frag",
105 [DIFF_FILE_OLD] = "old",
106 [DIFF_FILE_NEW] = "new",
107 [DIFF_COMMIT] = "commit",
108 [DIFF_WHITESPACE] = "whitespace",
109 [DIFF_FUNCINFO] = "func",
110 [DIFF_FILE_OLD_MOVED] = "oldMoved",
111 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
112 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
113 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
114 [DIFF_FILE_NEW_MOVED] = "newMoved",
115 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
116 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
117 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
118 [DIFF_CONTEXT_DIM] = "contextDimmed",
119 [DIFF_FILE_OLD_DIM] = "oldDimmed",
120 [DIFF_FILE_NEW_DIM] = "newDimmed",
121 [DIFF_CONTEXT_BOLD] = "contextBold",
122 [DIFF_FILE_OLD_BOLD] = "oldBold",
123 [DIFF_FILE_NEW_BOLD] = "newBold",
126 define_list_config_array_extra(color_diff_slots, {"plain"});
128 static int parse_diff_color_slot(const char *var)
130 if (!strcasecmp(var, "plain"))
131 return DIFF_CONTEXT;
132 return LOOKUP_CONFIG(color_diff_slots, var);
135 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
136 struct strbuf *errmsg)
138 char *params_copy = xstrdup(params_string);
139 struct string_list params = STRING_LIST_INIT_NODUP;
140 int ret = 0;
141 int i;
143 if (*params_copy)
144 string_list_split_in_place(&params, params_copy, ",", -1);
145 for (i = 0; i < params.nr; i++) {
146 const char *p = params.items[i].string;
147 if (!strcmp(p, "changes")) {
148 options->flags.dirstat_by_line = 0;
149 options->flags.dirstat_by_file = 0;
150 } else if (!strcmp(p, "lines")) {
151 options->flags.dirstat_by_line = 1;
152 options->flags.dirstat_by_file = 0;
153 } else if (!strcmp(p, "files")) {
154 options->flags.dirstat_by_line = 0;
155 options->flags.dirstat_by_file = 1;
156 } else if (!strcmp(p, "noncumulative")) {
157 options->flags.dirstat_cumulative = 0;
158 } else if (!strcmp(p, "cumulative")) {
159 options->flags.dirstat_cumulative = 1;
160 } else if (isdigit(*p)) {
161 char *end;
162 int permille = strtoul(p, &end, 10) * 10;
163 if (*end == '.' && isdigit(*++end)) {
164 /* only use first digit */
165 permille += *end - '0';
166 /* .. and ignore any further digits */
167 while (isdigit(*++end))
168 ; /* nothing */
170 if (!*end)
171 options->dirstat_permille = permille;
172 else {
173 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
175 ret++;
177 } else {
178 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
179 ret++;
183 string_list_clear(&params, 0);
184 free(params_copy);
185 return ret;
188 static int parse_submodule_params(struct diff_options *options, const char *value)
190 if (!strcmp(value, "log"))
191 options->submodule_format = DIFF_SUBMODULE_LOG;
192 else if (!strcmp(value, "short"))
193 options->submodule_format = DIFF_SUBMODULE_SHORT;
194 else if (!strcmp(value, "diff"))
195 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
197 * Please update $__git_diff_submodule_formats in
198 * git-completion.bash when you add new formats.
200 else
201 return -1;
202 return 0;
205 int git_config_rename(const char *var, const char *value)
207 if (!value)
208 return DIFF_DETECT_RENAME;
209 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
210 return DIFF_DETECT_COPY;
211 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
214 long parse_algorithm_value(const char *value)
216 if (!value)
217 return -1;
218 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
219 return 0;
220 else if (!strcasecmp(value, "minimal"))
221 return XDF_NEED_MINIMAL;
222 else if (!strcasecmp(value, "patience"))
223 return XDF_PATIENCE_DIFF;
224 else if (!strcasecmp(value, "histogram"))
225 return XDF_HISTOGRAM_DIFF;
227 * Please update $__git_diff_algorithms in git-completion.bash
228 * when you add new algorithms.
230 return -1;
233 static int parse_one_token(const char **arg, const char *token)
235 const char *rest;
236 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
237 *arg = rest;
238 return 1;
240 return 0;
243 static int parse_ws_error_highlight(const char *arg)
245 const char *orig_arg = arg;
246 unsigned val = 0;
248 while (*arg) {
249 if (parse_one_token(&arg, "none"))
250 val = 0;
251 else if (parse_one_token(&arg, "default"))
252 val = WSEH_NEW;
253 else if (parse_one_token(&arg, "all"))
254 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
255 else if (parse_one_token(&arg, "new"))
256 val |= WSEH_NEW;
257 else if (parse_one_token(&arg, "old"))
258 val |= WSEH_OLD;
259 else if (parse_one_token(&arg, "context"))
260 val |= WSEH_CONTEXT;
261 else {
262 return -1 - (int)(arg - orig_arg);
264 if (*arg)
265 arg++;
267 return val;
271 * These are to give UI layer defaults.
272 * The core-level commands such as git-diff-files should
273 * never be affected by the setting of diff.renames
274 * the user happens to have in the configuration file.
276 void init_diff_ui_defaults(void)
278 diff_detect_rename_default = DIFF_DETECT_RENAME;
281 int git_diff_heuristic_config(const char *var, const char *value,
282 void *cb UNUSED)
284 if (!strcmp(var, "diff.indentheuristic"))
285 diff_indent_heuristic = git_config_bool(var, value);
286 return 0;
289 static int parse_color_moved(const char *arg)
291 switch (git_parse_maybe_bool(arg)) {
292 case 0:
293 return COLOR_MOVED_NO;
294 case 1:
295 return COLOR_MOVED_DEFAULT;
296 default:
297 break;
300 if (!strcmp(arg, "no"))
301 return COLOR_MOVED_NO;
302 else if (!strcmp(arg, "plain"))
303 return COLOR_MOVED_PLAIN;
304 else if (!strcmp(arg, "blocks"))
305 return COLOR_MOVED_BLOCKS;
306 else if (!strcmp(arg, "zebra"))
307 return COLOR_MOVED_ZEBRA;
308 else if (!strcmp(arg, "default"))
309 return COLOR_MOVED_DEFAULT;
310 else if (!strcmp(arg, "dimmed-zebra"))
311 return COLOR_MOVED_ZEBRA_DIM;
312 else if (!strcmp(arg, "dimmed_zebra"))
313 return COLOR_MOVED_ZEBRA_DIM;
314 else
315 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
318 static unsigned parse_color_moved_ws(const char *arg)
320 int ret = 0;
321 struct string_list l = STRING_LIST_INIT_DUP;
322 struct string_list_item *i;
324 string_list_split(&l, arg, ',', -1);
326 for_each_string_list_item(i, &l) {
327 struct strbuf sb = STRBUF_INIT;
328 strbuf_addstr(&sb, i->string);
329 strbuf_trim(&sb);
331 if (!strcmp(sb.buf, "no"))
332 ret = 0;
333 else if (!strcmp(sb.buf, "ignore-space-change"))
334 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
335 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
336 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
337 else if (!strcmp(sb.buf, "ignore-all-space"))
338 ret |= XDF_IGNORE_WHITESPACE;
339 else if (!strcmp(sb.buf, "allow-indentation-change"))
340 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
341 else {
342 ret |= COLOR_MOVED_WS_ERROR;
343 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);
346 strbuf_release(&sb);
349 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
350 (ret & XDF_WHITESPACE_FLAGS)) {
351 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
352 ret |= COLOR_MOVED_WS_ERROR;
355 string_list_clear(&l, 0);
357 return ret;
360 int git_diff_ui_config(const char *var, const char *value,
361 const struct config_context *ctx, void *cb)
363 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
364 diff_use_color_default = git_config_colorbool(var, value);
365 return 0;
367 if (!strcmp(var, "diff.colormoved")) {
368 int cm = parse_color_moved(value);
369 if (cm < 0)
370 return -1;
371 diff_color_moved_default = cm;
372 return 0;
374 if (!strcmp(var, "diff.colormovedws")) {
375 unsigned cm;
376 if (!value)
377 return config_error_nonbool(var);
378 cm = parse_color_moved_ws(value);
379 if (cm & COLOR_MOVED_WS_ERROR)
380 return -1;
381 diff_color_moved_ws_default = cm;
382 return 0;
384 if (!strcmp(var, "diff.context")) {
385 diff_context_default = git_config_int(var, value, ctx->kvi);
386 if (diff_context_default < 0)
387 return -1;
388 return 0;
390 if (!strcmp(var, "diff.interhunkcontext")) {
391 diff_interhunk_context_default = git_config_int(var, value,
392 ctx->kvi);
393 if (diff_interhunk_context_default < 0)
394 return -1;
395 return 0;
397 if (!strcmp(var, "diff.renames")) {
398 diff_detect_rename_default = git_config_rename(var, value);
399 return 0;
401 if (!strcmp(var, "diff.autorefreshindex")) {
402 diff_auto_refresh_index = git_config_bool(var, value);
403 return 0;
405 if (!strcmp(var, "diff.mnemonicprefix")) {
406 diff_mnemonic_prefix = git_config_bool(var, value);
407 return 0;
409 if (!strcmp(var, "diff.noprefix")) {
410 diff_no_prefix = git_config_bool(var, value);
411 return 0;
413 if (!strcmp(var, "diff.srcprefix")) {
414 FREE_AND_NULL(diff_src_prefix);
415 return git_config_string(&diff_src_prefix, var, value);
417 if (!strcmp(var, "diff.dstprefix")) {
418 FREE_AND_NULL(diff_dst_prefix);
419 return git_config_string(&diff_dst_prefix, var, value);
421 if (!strcmp(var, "diff.relative")) {
422 diff_relative = git_config_bool(var, value);
423 return 0;
425 if (!strcmp(var, "diff.statnamewidth")) {
426 diff_stat_name_width = git_config_int(var, value, ctx->kvi);
427 return 0;
429 if (!strcmp(var, "diff.statgraphwidth")) {
430 diff_stat_graph_width = git_config_int(var, value, ctx->kvi);
431 return 0;
433 if (!strcmp(var, "diff.external"))
434 return git_config_string(&external_diff_cmd_cfg, var, value);
435 if (!strcmp(var, "diff.wordregex"))
436 return git_config_string(&diff_word_regex_cfg, var, value);
437 if (!strcmp(var, "diff.orderfile"))
438 return git_config_pathname(&diff_order_file_cfg, var, value);
440 if (!strcmp(var, "diff.ignoresubmodules")) {
441 if (!value)
442 return config_error_nonbool(var);
443 handle_ignore_submodules_arg(&default_diff_options, value);
446 if (!strcmp(var, "diff.submodule")) {
447 if (!value)
448 return config_error_nonbool(var);
449 if (parse_submodule_params(&default_diff_options, value))
450 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
451 value);
452 return 0;
455 if (!strcmp(var, "diff.algorithm")) {
456 if (!value)
457 return config_error_nonbool(var);
458 diff_algorithm = parse_algorithm_value(value);
459 if (diff_algorithm < 0)
460 return error(_("unknown value for config '%s': %s"),
461 var, value);
462 return 0;
465 if (git_color_config(var, value, cb) < 0)
466 return -1;
468 return git_diff_basic_config(var, value, ctx, cb);
471 int git_diff_basic_config(const char *var, const char *value,
472 const struct config_context *ctx, void *cb)
474 const char *name;
476 if (!strcmp(var, "diff.renamelimit")) {
477 diff_rename_limit_default = git_config_int(var, value, ctx->kvi);
478 return 0;
481 if (userdiff_config(var, value) < 0)
482 return -1;
484 if (skip_prefix(var, "diff.color.", &name) ||
485 skip_prefix(var, "color.diff.", &name)) {
486 int slot = parse_diff_color_slot(name);
487 if (slot < 0)
488 return 0;
489 if (!value)
490 return config_error_nonbool(var);
491 return color_parse(value, diff_colors[slot]);
494 if (!strcmp(var, "diff.wserrorhighlight")) {
495 int val;
496 if (!value)
497 return config_error_nonbool(var);
498 val = parse_ws_error_highlight(value);
499 if (val < 0)
500 return error(_("unknown value for config '%s': %s"),
501 var, value);
502 ws_error_highlight_default = val;
503 return 0;
506 /* like GNU diff's --suppress-blank-empty option */
507 if (!strcmp(var, "diff.suppressblankempty") ||
508 /* for backwards compatibility */
509 !strcmp(var, "diff.suppress-blank-empty")) {
510 diff_suppress_blank_empty = git_config_bool(var, value);
511 return 0;
514 if (!strcmp(var, "diff.dirstat")) {
515 struct strbuf errmsg = STRBUF_INIT;
516 if (!value)
517 return config_error_nonbool(var);
518 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
519 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
520 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
521 errmsg.buf);
522 strbuf_release(&errmsg);
523 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
524 return 0;
527 if (git_diff_heuristic_config(var, value, cb) < 0)
528 return -1;
530 return git_default_config(var, value, ctx, cb);
533 static char *quote_two(const char *one, const char *two)
535 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
536 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
537 struct strbuf res = STRBUF_INIT;
539 if (need_one + need_two) {
540 strbuf_addch(&res, '"');
541 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
542 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
543 strbuf_addch(&res, '"');
544 } else {
545 strbuf_addstr(&res, one);
546 strbuf_addstr(&res, two);
548 return strbuf_detach(&res, NULL);
551 static const char *external_diff(void)
553 static const char *external_diff_cmd = NULL;
554 static int done_preparing = 0;
556 if (done_preparing)
557 return external_diff_cmd;
558 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
559 if (!external_diff_cmd)
560 external_diff_cmd = external_diff_cmd_cfg;
561 done_preparing = 1;
562 return external_diff_cmd;
566 * Keep track of files used for diffing. Sometimes such an entry
567 * refers to a temporary file, sometimes to an existing file, and
568 * sometimes to "/dev/null".
570 static struct diff_tempfile {
572 * filename external diff should read from, or NULL if this
573 * entry is currently not in use:
575 const char *name;
577 char hex[GIT_MAX_HEXSZ + 1];
578 char mode[10];
581 * If this diff_tempfile instance refers to a temporary file,
582 * this tempfile object is used to manage its lifetime.
584 struct tempfile *tempfile;
585 } diff_temp[2];
587 struct emit_callback {
588 int color_diff;
589 unsigned ws_rule;
590 int blank_at_eof_in_preimage;
591 int blank_at_eof_in_postimage;
592 int lno_in_preimage;
593 int lno_in_postimage;
594 const char **label_path;
595 struct diff_words_data *diff_words;
596 struct diff_options *opt;
597 struct strbuf *header;
600 static int count_lines(const char *data, int size)
602 int count, ch, completely_empty = 1, nl_just_seen = 0;
603 count = 0;
604 while (0 < size--) {
605 ch = *data++;
606 if (ch == '\n') {
607 count++;
608 nl_just_seen = 1;
609 completely_empty = 0;
611 else {
612 nl_just_seen = 0;
613 completely_empty = 0;
616 if (completely_empty)
617 return 0;
618 if (!nl_just_seen)
619 count++; /* no trailing newline */
620 return count;
623 static int fill_mmfile(struct repository *r, mmfile_t *mf,
624 struct diff_filespec *one)
626 if (!DIFF_FILE_VALID(one)) {
627 mf->ptr = (char *)""; /* does not matter */
628 mf->size = 0;
629 return 0;
631 else if (diff_populate_filespec(r, one, NULL))
632 return -1;
634 mf->ptr = one->data;
635 mf->size = one->size;
636 return 0;
639 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
640 static unsigned long diff_filespec_size(struct repository *r,
641 struct diff_filespec *one)
643 struct diff_populate_filespec_options dpf_options = {
644 .check_size_only = 1,
647 if (!DIFF_FILE_VALID(one))
648 return 0;
649 diff_populate_filespec(r, one, &dpf_options);
650 return one->size;
653 static int count_trailing_blank(mmfile_t *mf)
655 char *ptr = mf->ptr;
656 long size = mf->size;
657 int cnt = 0;
659 if (!size)
660 return cnt;
661 ptr += size - 1; /* pointing at the very end */
662 if (*ptr != '\n')
663 ; /* incomplete line */
664 else
665 ptr--; /* skip the last LF */
666 while (mf->ptr < ptr) {
667 char *prev_eol;
668 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
669 if (*prev_eol == '\n')
670 break;
671 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
672 break;
673 cnt++;
674 ptr = prev_eol - 1;
676 return cnt;
679 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
680 struct emit_callback *ecbdata)
682 int l1, l2, at;
683 l1 = count_trailing_blank(mf1);
684 l2 = count_trailing_blank(mf2);
685 if (l2 <= l1) {
686 ecbdata->blank_at_eof_in_preimage = 0;
687 ecbdata->blank_at_eof_in_postimage = 0;
688 return;
690 at = count_lines(mf1->ptr, mf1->size);
691 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
693 at = count_lines(mf2->ptr, mf2->size);
694 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
697 static void emit_line_0(struct diff_options *o,
698 const char *set_sign, const char *set, unsigned reverse, const char *reset,
699 int first, const char *line, int len)
701 int has_trailing_newline, has_trailing_carriage_return;
702 int needs_reset = 0; /* at the end of the line */
703 FILE *file = o->file;
705 fputs(diff_line_prefix(o), file);
707 has_trailing_newline = (len > 0 && line[len-1] == '\n');
708 if (has_trailing_newline)
709 len--;
711 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
712 if (has_trailing_carriage_return)
713 len--;
715 if (!len && !first)
716 goto end_of_line;
718 if (reverse && want_color(o->use_color)) {
719 fputs(GIT_COLOR_REVERSE, file);
720 needs_reset = 1;
723 if (set_sign) {
724 fputs(set_sign, file);
725 needs_reset = 1;
728 if (first)
729 fputc(first, file);
731 if (!len)
732 goto end_of_line;
734 if (set) {
735 if (set_sign && set != set_sign)
736 fputs(reset, file);
737 fputs(set, file);
738 needs_reset = 1;
740 fwrite(line, len, 1, file);
741 needs_reset = 1; /* 'line' may contain color codes. */
743 end_of_line:
744 if (needs_reset)
745 fputs(reset, file);
746 if (has_trailing_carriage_return)
747 fputc('\r', file);
748 if (has_trailing_newline)
749 fputc('\n', file);
752 static void emit_line(struct diff_options *o, const char *set, const char *reset,
753 const char *line, int len)
755 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
758 enum diff_symbol {
759 DIFF_SYMBOL_BINARY_DIFF_HEADER,
760 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
761 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
762 DIFF_SYMBOL_BINARY_DIFF_BODY,
763 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
764 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
765 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
766 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
767 DIFF_SYMBOL_STATS_LINE,
768 DIFF_SYMBOL_WORD_DIFF,
769 DIFF_SYMBOL_STAT_SEP,
770 DIFF_SYMBOL_SUMMARY,
771 DIFF_SYMBOL_SUBMODULE_ADD,
772 DIFF_SYMBOL_SUBMODULE_DEL,
773 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
774 DIFF_SYMBOL_SUBMODULE_MODIFIED,
775 DIFF_SYMBOL_SUBMODULE_HEADER,
776 DIFF_SYMBOL_SUBMODULE_ERROR,
777 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
778 DIFF_SYMBOL_REWRITE_DIFF,
779 DIFF_SYMBOL_BINARY_FILES,
780 DIFF_SYMBOL_HEADER,
781 DIFF_SYMBOL_FILEPAIR_PLUS,
782 DIFF_SYMBOL_FILEPAIR_MINUS,
783 DIFF_SYMBOL_WORDS_PORCELAIN,
784 DIFF_SYMBOL_WORDS,
785 DIFF_SYMBOL_CONTEXT,
786 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
787 DIFF_SYMBOL_PLUS,
788 DIFF_SYMBOL_MINUS,
789 DIFF_SYMBOL_NO_LF_EOF,
790 DIFF_SYMBOL_CONTEXT_FRAGINFO,
791 DIFF_SYMBOL_CONTEXT_MARKER,
792 DIFF_SYMBOL_SEPARATOR
795 * Flags for content lines:
796 * 0..12 are whitespace rules
797 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
798 * 16 is marking if the line is blank at EOF
800 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
801 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
802 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
803 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
804 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
807 * This struct is used when we need to buffer the output of the diff output.
809 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
810 * into the pre/post image file. This pointer could be a union with the
811 * line pointer. By storing an offset into the file instead of the literal line,
812 * we can decrease the memory footprint for the buffered output. At first we
813 * may want to only have indirection for the content lines, but we could also
814 * enhance the state for emitting prefabricated lines, e.g. the similarity
815 * score line or hunk/file headers would only need to store a number or path
816 * and then the output can be constructed later on depending on state.
818 struct emitted_diff_symbol {
819 const char *line;
820 int len;
821 int flags;
822 int indent_off; /* Offset to first non-whitespace character */
823 int indent_width; /* The visual width of the indentation */
824 unsigned id;
825 enum diff_symbol s;
827 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
829 struct emitted_diff_symbols {
830 struct emitted_diff_symbol *buf;
831 int nr, alloc;
833 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
835 static void append_emitted_diff_symbol(struct diff_options *o,
836 struct emitted_diff_symbol *e)
838 struct emitted_diff_symbol *f;
840 ALLOC_GROW(o->emitted_symbols->buf,
841 o->emitted_symbols->nr + 1,
842 o->emitted_symbols->alloc);
843 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
845 memcpy(f, e, sizeof(struct emitted_diff_symbol));
846 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
849 static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
851 if (!e)
852 return;
853 free(e->buf);
854 free(e);
857 struct moved_entry {
858 const struct emitted_diff_symbol *es;
859 struct moved_entry *next_line;
860 struct moved_entry *next_match;
863 struct moved_block {
864 struct moved_entry *match;
865 int wsd; /* The whitespace delta of this block */
868 #define INDENT_BLANKLINE INT_MIN
870 static void fill_es_indent_data(struct emitted_diff_symbol *es)
872 unsigned int off = 0, i;
873 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
874 const char *s = es->line;
875 const int len = es->len;
877 /* skip any \v \f \r at start of indentation */
878 while (s[off] == '\f' || s[off] == '\v' ||
879 (s[off] == '\r' && off < len - 1))
880 off++;
882 /* calculate the visual width of indentation */
883 while(1) {
884 if (s[off] == ' ') {
885 width++;
886 off++;
887 } else if (s[off] == '\t') {
888 width += tab_width - (width % tab_width);
889 while (s[++off] == '\t')
890 width += tab_width;
891 } else {
892 break;
896 /* check if this line is blank */
897 for (i = off; i < len; i++)
898 if (!isspace(s[i]))
899 break;
901 if (i == len) {
902 es->indent_width = INDENT_BLANKLINE;
903 es->indent_off = len;
904 } else {
905 es->indent_off = off;
906 es->indent_width = width;
910 static int compute_ws_delta(const struct emitted_diff_symbol *a,
911 const struct emitted_diff_symbol *b)
913 int a_width = a->indent_width,
914 b_width = b->indent_width;
916 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
917 return INDENT_BLANKLINE;
919 return a_width - b_width;
922 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
923 const struct emitted_diff_symbol *l,
924 struct moved_block *pmb)
926 int a_width = cur->es->indent_width, b_width = l->indent_width;
927 int delta;
929 /* The text of each line must match */
930 if (cur->es->id != l->id)
931 return 1;
934 * If 'l' and 'cur' are both blank then we don't need to check the
935 * indent. We only need to check cur as we know the strings match.
936 * */
937 if (a_width == INDENT_BLANKLINE)
938 return 0;
941 * The indent changes of the block are known and stored in pmb->wsd;
942 * however we need to check if the indent changes of the current line
943 * match those of the current block.
945 delta = b_width - a_width;
948 * If the previous lines of this block were all blank then set its
949 * whitespace delta.
951 if (pmb->wsd == INDENT_BLANKLINE)
952 pmb->wsd = delta;
954 return delta != pmb->wsd;
957 struct interned_diff_symbol {
958 struct hashmap_entry ent;
959 struct emitted_diff_symbol *es;
962 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
963 const struct hashmap_entry *eptr,
964 const struct hashmap_entry *entry_or_key,
965 const void *keydata UNUSED)
967 const struct diff_options *diffopt = hashmap_cmp_fn_data;
968 const struct emitted_diff_symbol *a, *b;
969 unsigned flags = diffopt->color_moved_ws_handling
970 & XDF_WHITESPACE_FLAGS;
972 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
973 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
975 return !xdiff_compare_lines(a->line + a->indent_off,
976 a->len - a->indent_off,
977 b->line + b->indent_off,
978 b->len - b->indent_off, flags);
981 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
982 struct interned_diff_symbol *s)
984 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
985 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
986 l->len - l->indent_off, flags);
988 hashmap_entry_init(&s->ent, hash);
989 s->es = l;
992 struct moved_entry_list {
993 struct moved_entry *add, *del;
996 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
997 struct mem_pool *entry_mem_pool)
999 struct moved_entry *prev_line = NULL;
1000 struct mem_pool interned_pool;
1001 struct hashmap interned_map;
1002 struct moved_entry_list *entry_list = NULL;
1003 size_t entry_list_alloc = 0;
1004 unsigned id = 0;
1005 int n;
1007 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
1008 mem_pool_init(&interned_pool, 1024 * 1024);
1010 for (n = 0; n < o->emitted_symbols->nr; n++) {
1011 struct interned_diff_symbol key;
1012 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1013 struct interned_diff_symbol *s;
1014 struct moved_entry *entry;
1016 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
1017 prev_line = NULL;
1018 continue;
1021 if (o->color_moved_ws_handling &
1022 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1023 fill_es_indent_data(l);
1025 prepare_entry(o, l, &key);
1026 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
1027 if (s) {
1028 l->id = s->es->id;
1029 } else {
1030 l->id = id;
1031 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
1032 hashmap_add(&interned_map,
1033 memcpy(mem_pool_alloc(&interned_pool,
1034 sizeof(key)),
1035 &key, sizeof(key)));
1037 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
1038 entry->es = l;
1039 entry->next_line = NULL;
1040 if (prev_line && prev_line->es->s == l->s)
1041 prev_line->next_line = entry;
1042 prev_line = entry;
1043 if (l->s == DIFF_SYMBOL_PLUS) {
1044 entry->next_match = entry_list[l->id].add;
1045 entry_list[l->id].add = entry;
1046 } else {
1047 entry->next_match = entry_list[l->id].del;
1048 entry_list[l->id].del = entry;
1052 hashmap_clear(&interned_map);
1053 mem_pool_discard(&interned_pool, 0);
1055 return entry_list;
1058 static void pmb_advance_or_null(struct diff_options *o,
1059 struct emitted_diff_symbol *l,
1060 struct moved_block *pmb,
1061 int *pmb_nr)
1063 int i, j;
1065 for (i = 0, j = 0; i < *pmb_nr; i++) {
1066 int match;
1067 struct moved_entry *prev = pmb[i].match;
1068 struct moved_entry *cur = (prev && prev->next_line) ?
1069 prev->next_line : NULL;
1071 if (o->color_moved_ws_handling &
1072 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1073 match = cur &&
1074 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1075 else
1076 match = cur && cur->es->id == l->id;
1078 if (match) {
1079 pmb[j] = pmb[i];
1080 pmb[j++].match = cur;
1083 *pmb_nr = j;
1086 static void fill_potential_moved_blocks(struct diff_options *o,
1087 struct moved_entry *match,
1088 struct emitted_diff_symbol *l,
1089 struct moved_block **pmb_p,
1090 int *pmb_alloc_p, int *pmb_nr_p)
1093 struct moved_block *pmb = *pmb_p;
1094 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1097 * The current line is the start of a new block.
1098 * Setup the set of potential blocks.
1100 for (; match; match = match->next_match) {
1101 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1102 if (o->color_moved_ws_handling &
1103 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1104 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1105 else
1106 pmb[pmb_nr].wsd = 0;
1107 pmb[pmb_nr++].match = match;
1110 *pmb_p = pmb;
1111 *pmb_alloc_p = pmb_alloc;
1112 *pmb_nr_p = pmb_nr;
1116 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1118 * Otherwise, if the last block has fewer alphanumeric characters than
1119 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1120 * that block.
1122 * The last block consists of the (n - block_length)'th line up to but not
1123 * including the nth line.
1125 * Returns 0 if the last block is empty or is unset by this function, non zero
1126 * otherwise.
1128 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1129 * Think of a way to unify them.
1131 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1132 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1133 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1135 int i, alnum_count = 0;
1136 if (o->color_moved == COLOR_MOVED_PLAIN)
1137 return block_length;
1138 for (i = 1; i < block_length + 1; i++) {
1139 const char *c = o->emitted_symbols->buf[n - i].line;
1140 for (; *c; c++) {
1141 if (!isalnum(*c))
1142 continue;
1143 alnum_count++;
1144 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1145 return 1;
1148 for (i = 1; i < block_length + 1; i++)
1149 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1150 return 0;
1153 /* Find blocks of moved code, delegate actual coloring decision to helper */
1154 static void mark_color_as_moved(struct diff_options *o,
1155 struct moved_entry_list *entry_list)
1157 struct moved_block *pmb = NULL; /* potentially moved blocks */
1158 int pmb_nr = 0, pmb_alloc = 0;
1159 int n, flipped_block = 0, block_length = 0;
1160 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1163 for (n = 0; n < o->emitted_symbols->nr; n++) {
1164 struct moved_entry *match = NULL;
1165 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1167 switch (l->s) {
1168 case DIFF_SYMBOL_PLUS:
1169 match = entry_list[l->id].del;
1170 break;
1171 case DIFF_SYMBOL_MINUS:
1172 match = entry_list[l->id].add;
1173 break;
1174 default:
1175 flipped_block = 0;
1178 if (pmb_nr && (!match || l->s != moved_symbol)) {
1179 if (!adjust_last_block(o, n, block_length) &&
1180 block_length > 1) {
1182 * Rewind in case there is another match
1183 * starting at the second line of the block
1185 match = NULL;
1186 n -= block_length;
1188 pmb_nr = 0;
1189 block_length = 0;
1190 flipped_block = 0;
1192 if (!match) {
1193 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1194 continue;
1197 if (o->color_moved == COLOR_MOVED_PLAIN) {
1198 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1199 continue;
1202 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1204 if (pmb_nr == 0) {
1205 int contiguous = adjust_last_block(o, n, block_length);
1207 if (!contiguous && block_length > 1)
1209 * Rewind in case there is another match
1210 * starting at the second line of the block
1212 n -= block_length;
1213 else
1214 fill_potential_moved_blocks(o, match, l,
1215 &pmb, &pmb_alloc,
1216 &pmb_nr);
1218 if (contiguous && pmb_nr && moved_symbol == l->s)
1219 flipped_block = (flipped_block + 1) % 2;
1220 else
1221 flipped_block = 0;
1223 if (pmb_nr)
1224 moved_symbol = l->s;
1225 else
1226 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1228 block_length = 0;
1231 if (pmb_nr) {
1232 block_length++;
1233 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1234 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1235 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1238 adjust_last_block(o, n, block_length);
1240 free(pmb);
1243 static void dim_moved_lines(struct diff_options *o)
1245 int n;
1246 for (n = 0; n < o->emitted_symbols->nr; n++) {
1247 struct emitted_diff_symbol *prev = (n != 0) ?
1248 &o->emitted_symbols->buf[n - 1] : NULL;
1249 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1250 struct emitted_diff_symbol *next =
1251 (n < o->emitted_symbols->nr - 1) ?
1252 &o->emitted_symbols->buf[n + 1] : NULL;
1254 /* Not a plus or minus line? */
1255 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1256 continue;
1258 /* Not a moved line? */
1259 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1260 continue;
1263 * If prev or next are not a plus or minus line,
1264 * pretend they don't exist
1266 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1267 prev->s != DIFF_SYMBOL_MINUS)
1268 prev = NULL;
1269 if (next && next->s != DIFF_SYMBOL_PLUS &&
1270 next->s != DIFF_SYMBOL_MINUS)
1271 next = NULL;
1273 /* Inside a block? */
1274 if ((prev &&
1275 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1276 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1277 (next &&
1278 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1279 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1280 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1281 continue;
1284 /* Check if we are at an interesting bound: */
1285 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1286 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1287 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1288 continue;
1289 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1290 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1291 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1292 continue;
1295 * The boundary to prev and next are not interesting,
1296 * so this line is not interesting as a whole
1298 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1302 static void emit_line_ws_markup(struct diff_options *o,
1303 const char *set_sign, const char *set,
1304 const char *reset,
1305 int sign_index, const char *line, int len,
1306 unsigned ws_rule, int blank_at_eof)
1308 const char *ws = NULL;
1309 int sign = o->output_indicators[sign_index];
1311 if (o->ws_error_highlight & ws_rule) {
1312 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1313 if (!*ws)
1314 ws = NULL;
1317 if (!ws && !set_sign)
1318 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1319 else if (!ws) {
1320 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1321 } else if (blank_at_eof)
1322 /* Blank line at EOF - paint '+' as well */
1323 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1324 else {
1325 /* Emit just the prefix, then the rest. */
1326 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1327 sign, "", 0);
1328 ws_check_emit(line, len, ws_rule,
1329 o->file, set, reset, ws);
1333 static void emit_diff_symbol_from_struct(struct diff_options *o,
1334 struct emitted_diff_symbol *eds)
1336 static const char *nneof = " No newline at end of file\n";
1337 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1339 enum diff_symbol s = eds->s;
1340 const char *line = eds->line;
1341 int len = eds->len;
1342 unsigned flags = eds->flags;
1344 switch (s) {
1345 case DIFF_SYMBOL_NO_LF_EOF:
1346 context = diff_get_color_opt(o, DIFF_CONTEXT);
1347 reset = diff_get_color_opt(o, DIFF_RESET);
1348 putc('\n', o->file);
1349 emit_line_0(o, context, NULL, 0, reset, '\\',
1350 nneof, strlen(nneof));
1351 break;
1352 case DIFF_SYMBOL_SUBMODULE_HEADER:
1353 case DIFF_SYMBOL_SUBMODULE_ERROR:
1354 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1355 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1356 case DIFF_SYMBOL_SUMMARY:
1357 case DIFF_SYMBOL_STATS_LINE:
1358 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1359 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1360 emit_line(o, "", "", line, len);
1361 break;
1362 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1363 case DIFF_SYMBOL_CONTEXT_MARKER:
1364 context = diff_get_color_opt(o, DIFF_CONTEXT);
1365 reset = diff_get_color_opt(o, DIFF_RESET);
1366 emit_line(o, context, reset, line, len);
1367 break;
1368 case DIFF_SYMBOL_SEPARATOR:
1369 fprintf(o->file, "%s%c",
1370 diff_line_prefix(o),
1371 o->line_termination);
1372 break;
1373 case DIFF_SYMBOL_CONTEXT:
1374 set = diff_get_color_opt(o, DIFF_CONTEXT);
1375 reset = diff_get_color_opt(o, DIFF_RESET);
1376 set_sign = NULL;
1377 if (o->flags.dual_color_diffed_diffs) {
1378 char c = !len ? 0 : line[0];
1380 if (c == '+')
1381 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1382 else if (c == '@')
1383 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1384 else if (c == '-')
1385 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1387 emit_line_ws_markup(o, set_sign, set, reset,
1388 OUTPUT_INDICATOR_CONTEXT, line, len,
1389 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1390 break;
1391 case DIFF_SYMBOL_PLUS:
1392 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1393 DIFF_SYMBOL_MOVED_LINE_ALT |
1394 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1395 case DIFF_SYMBOL_MOVED_LINE |
1396 DIFF_SYMBOL_MOVED_LINE_ALT |
1397 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1398 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1399 break;
1400 case DIFF_SYMBOL_MOVED_LINE |
1401 DIFF_SYMBOL_MOVED_LINE_ALT:
1402 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1403 break;
1404 case DIFF_SYMBOL_MOVED_LINE |
1405 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1406 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1407 break;
1408 case DIFF_SYMBOL_MOVED_LINE:
1409 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1410 break;
1411 default:
1412 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1414 reset = diff_get_color_opt(o, DIFF_RESET);
1415 if (!o->flags.dual_color_diffed_diffs)
1416 set_sign = NULL;
1417 else {
1418 char c = !len ? 0 : line[0];
1420 set_sign = set;
1421 if (c == '-')
1422 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1423 else if (c == '@')
1424 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1425 else if (c == '+')
1426 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1427 else
1428 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1429 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1431 emit_line_ws_markup(o, set_sign, set, reset,
1432 OUTPUT_INDICATOR_NEW, line, len,
1433 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1434 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1435 break;
1436 case DIFF_SYMBOL_MINUS:
1437 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1438 DIFF_SYMBOL_MOVED_LINE_ALT |
1439 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1440 case DIFF_SYMBOL_MOVED_LINE |
1441 DIFF_SYMBOL_MOVED_LINE_ALT |
1442 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1443 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1444 break;
1445 case DIFF_SYMBOL_MOVED_LINE |
1446 DIFF_SYMBOL_MOVED_LINE_ALT:
1447 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1448 break;
1449 case DIFF_SYMBOL_MOVED_LINE |
1450 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1451 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1452 break;
1453 case DIFF_SYMBOL_MOVED_LINE:
1454 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1455 break;
1456 default:
1457 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1459 reset = diff_get_color_opt(o, DIFF_RESET);
1460 if (!o->flags.dual_color_diffed_diffs)
1461 set_sign = NULL;
1462 else {
1463 char c = !len ? 0 : line[0];
1465 set_sign = set;
1466 if (c == '+')
1467 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1468 else if (c == '@')
1469 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1470 else if (c == '-')
1471 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1472 else
1473 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1475 emit_line_ws_markup(o, set_sign, set, reset,
1476 OUTPUT_INDICATOR_OLD, line, len,
1477 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1478 break;
1479 case DIFF_SYMBOL_WORDS_PORCELAIN:
1480 context = diff_get_color_opt(o, DIFF_CONTEXT);
1481 reset = diff_get_color_opt(o, DIFF_RESET);
1482 emit_line(o, context, reset, line, len);
1483 fputs("~\n", o->file);
1484 break;
1485 case DIFF_SYMBOL_WORDS:
1486 context = diff_get_color_opt(o, DIFF_CONTEXT);
1487 reset = diff_get_color_opt(o, DIFF_RESET);
1489 * Skip the prefix character, if any. With
1490 * diff_suppress_blank_empty, there may be
1491 * none.
1493 if (line[0] != '\n') {
1494 line++;
1495 len--;
1497 emit_line(o, context, reset, line, len);
1498 break;
1499 case DIFF_SYMBOL_FILEPAIR_PLUS:
1500 meta = diff_get_color_opt(o, DIFF_METAINFO);
1501 reset = diff_get_color_opt(o, DIFF_RESET);
1502 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1503 line, reset,
1504 strchr(line, ' ') ? "\t" : "");
1505 break;
1506 case DIFF_SYMBOL_FILEPAIR_MINUS:
1507 meta = diff_get_color_opt(o, DIFF_METAINFO);
1508 reset = diff_get_color_opt(o, DIFF_RESET);
1509 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1510 line, reset,
1511 strchr(line, ' ') ? "\t" : "");
1512 break;
1513 case DIFF_SYMBOL_BINARY_FILES:
1514 case DIFF_SYMBOL_HEADER:
1515 fprintf(o->file, "%s", line);
1516 break;
1517 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1518 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1519 break;
1520 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1521 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1522 break;
1523 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1524 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1525 break;
1526 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1527 fputs(diff_line_prefix(o), o->file);
1528 fputc('\n', o->file);
1529 break;
1530 case DIFF_SYMBOL_REWRITE_DIFF:
1531 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1532 reset = diff_get_color_opt(o, DIFF_RESET);
1533 emit_line(o, fraginfo, reset, line, len);
1534 break;
1535 case DIFF_SYMBOL_SUBMODULE_ADD:
1536 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1537 reset = diff_get_color_opt(o, DIFF_RESET);
1538 emit_line(o, set, reset, line, len);
1539 break;
1540 case DIFF_SYMBOL_SUBMODULE_DEL:
1541 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1542 reset = diff_get_color_opt(o, DIFF_RESET);
1543 emit_line(o, set, reset, line, len);
1544 break;
1545 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1546 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1547 diff_line_prefix(o), line);
1548 break;
1549 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1550 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1551 diff_line_prefix(o), line);
1552 break;
1553 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1554 emit_line(o, "", "", " 0 files changed\n",
1555 strlen(" 0 files changed\n"));
1556 break;
1557 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1558 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1559 break;
1560 case DIFF_SYMBOL_WORD_DIFF:
1561 fprintf(o->file, "%.*s", len, line);
1562 break;
1563 case DIFF_SYMBOL_STAT_SEP:
1564 fputs(o->stat_sep, o->file);
1565 break;
1566 default:
1567 BUG("unknown diff symbol");
1571 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1572 const char *line, int len, unsigned flags)
1574 struct emitted_diff_symbol e = {
1575 .line = line, .len = len, .flags = flags, .s = s
1578 if (o->emitted_symbols)
1579 append_emitted_diff_symbol(o, &e);
1580 else
1581 emit_diff_symbol_from_struct(o, &e);
1584 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1586 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1589 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1591 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1594 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1596 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1597 path, strlen(path), 0);
1600 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1602 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1603 path, strlen(path), 0);
1606 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1608 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1609 header, strlen(header), 0);
1612 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1614 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1617 void diff_emit_submodule_pipethrough(struct diff_options *o,
1618 const char *line, int len)
1620 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1623 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1625 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1626 ecbdata->blank_at_eof_in_preimage &&
1627 ecbdata->blank_at_eof_in_postimage &&
1628 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1629 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1630 return 0;
1631 return ws_blank_line(line, len);
1634 static void emit_add_line(struct emit_callback *ecbdata,
1635 const char *line, int len)
1637 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1638 if (new_blank_line_at_eof(ecbdata, line, len))
1639 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1641 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1644 static void emit_del_line(struct emit_callback *ecbdata,
1645 const char *line, int len)
1647 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1648 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1651 static void emit_context_line(struct emit_callback *ecbdata,
1652 const char *line, int len)
1654 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1655 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1658 static void emit_hunk_header(struct emit_callback *ecbdata,
1659 const char *line, int len)
1661 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1662 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1663 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1664 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1665 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1666 static const char atat[2] = { '@', '@' };
1667 const char *cp, *ep;
1668 struct strbuf msgbuf = STRBUF_INIT;
1669 int org_len = len;
1670 int i = 1;
1673 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1674 * it always is at least 10 bytes long.
1676 if (len < 10 ||
1677 memcmp(line, atat, 2) ||
1678 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1679 emit_diff_symbol(ecbdata->opt,
1680 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1681 return;
1683 ep += 2; /* skip over @@ */
1685 /* The hunk header in fraginfo color */
1686 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1687 strbuf_addstr(&msgbuf, reverse);
1688 strbuf_addstr(&msgbuf, frag);
1689 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1690 strbuf_add(&msgbuf, atat, sizeof(atat));
1691 else
1692 strbuf_add(&msgbuf, line, ep - line);
1693 strbuf_addstr(&msgbuf, reset);
1696 * trailing "\r\n"
1698 for ( ; i < 3; i++)
1699 if (line[len - i] == '\r' || line[len - i] == '\n')
1700 len--;
1702 /* blank before the func header */
1703 for (cp = ep; ep - line < len; ep++)
1704 if (*ep != ' ' && *ep != '\t')
1705 break;
1706 if (ep != cp) {
1707 strbuf_addstr(&msgbuf, context);
1708 strbuf_add(&msgbuf, cp, ep - cp);
1709 strbuf_addstr(&msgbuf, reset);
1712 if (ep < line + len) {
1713 strbuf_addstr(&msgbuf, func);
1714 strbuf_add(&msgbuf, ep, line + len - ep);
1715 strbuf_addstr(&msgbuf, reset);
1718 strbuf_add(&msgbuf, line + len, org_len - len);
1719 strbuf_complete_line(&msgbuf);
1720 emit_diff_symbol(ecbdata->opt,
1721 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1722 strbuf_release(&msgbuf);
1725 static struct diff_tempfile *claim_diff_tempfile(void)
1727 int i;
1728 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1729 if (!diff_temp[i].name)
1730 return diff_temp + i;
1731 BUG("diff is failing to clean up its tempfiles");
1734 static void remove_tempfile(void)
1736 int i;
1737 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1738 if (is_tempfile_active(diff_temp[i].tempfile))
1739 delete_tempfile(&diff_temp[i].tempfile);
1740 diff_temp[i].name = NULL;
1744 static void add_line_count(struct strbuf *out, int count)
1746 switch (count) {
1747 case 0:
1748 strbuf_addstr(out, "0,0");
1749 break;
1750 case 1:
1751 strbuf_addstr(out, "1");
1752 break;
1753 default:
1754 strbuf_addf(out, "1,%d", count);
1755 break;
1759 static void emit_rewrite_lines(struct emit_callback *ecb,
1760 int prefix, const char *data, int size)
1762 const char *endp = NULL;
1764 while (0 < size) {
1765 int len;
1767 endp = memchr(data, '\n', size);
1768 len = endp ? (endp - data + 1) : size;
1769 if (prefix != '+') {
1770 ecb->lno_in_preimage++;
1771 emit_del_line(ecb, data, len);
1772 } else {
1773 ecb->lno_in_postimage++;
1774 emit_add_line(ecb, data, len);
1776 size -= len;
1777 data += len;
1779 if (!endp)
1780 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1783 static void emit_rewrite_diff(const char *name_a,
1784 const char *name_b,
1785 struct diff_filespec *one,
1786 struct diff_filespec *two,
1787 struct userdiff_driver *textconv_one,
1788 struct userdiff_driver *textconv_two,
1789 struct diff_options *o)
1791 int lc_a, lc_b;
1792 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1793 const char *a_prefix, *b_prefix;
1794 char *data_one, *data_two;
1795 size_t size_one, size_two;
1796 struct emit_callback ecbdata;
1797 struct strbuf out = STRBUF_INIT;
1799 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1800 a_prefix = o->b_prefix;
1801 b_prefix = o->a_prefix;
1802 } else {
1803 a_prefix = o->a_prefix;
1804 b_prefix = o->b_prefix;
1807 name_a += (*name_a == '/');
1808 name_b += (*name_b == '/');
1810 strbuf_reset(&a_name);
1811 strbuf_reset(&b_name);
1812 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1813 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1815 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1816 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1818 memset(&ecbdata, 0, sizeof(ecbdata));
1819 ecbdata.color_diff = want_color(o->use_color);
1820 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1821 ecbdata.opt = o;
1822 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1823 mmfile_t mf1, mf2;
1824 mf1.ptr = (char *)data_one;
1825 mf2.ptr = (char *)data_two;
1826 mf1.size = size_one;
1827 mf2.size = size_two;
1828 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1830 ecbdata.lno_in_preimage = 1;
1831 ecbdata.lno_in_postimage = 1;
1833 lc_a = count_lines(data_one, size_one);
1834 lc_b = count_lines(data_two, size_two);
1836 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1837 a_name.buf, a_name.len, 0);
1838 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1839 b_name.buf, b_name.len, 0);
1841 strbuf_addstr(&out, "@@ -");
1842 if (!o->irreversible_delete)
1843 add_line_count(&out, lc_a);
1844 else
1845 strbuf_addstr(&out, "?,?");
1846 strbuf_addstr(&out, " +");
1847 add_line_count(&out, lc_b);
1848 strbuf_addstr(&out, " @@\n");
1849 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1850 strbuf_release(&out);
1852 if (lc_a && !o->irreversible_delete)
1853 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1854 if (lc_b)
1855 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1856 if (textconv_one)
1857 free((char *)data_one);
1858 if (textconv_two)
1859 free((char *)data_two);
1862 struct diff_words_buffer {
1863 mmfile_t text;
1864 unsigned long alloc;
1865 struct diff_words_orig {
1866 const char *begin, *end;
1867 } *orig;
1868 int orig_nr, orig_alloc;
1871 static void diff_words_append(char *line, unsigned long len,
1872 struct diff_words_buffer *buffer)
1874 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1875 line++;
1876 len--;
1877 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1878 buffer->text.size += len;
1879 buffer->text.ptr[buffer->text.size] = '\0';
1882 struct diff_words_style_elem {
1883 const char *prefix;
1884 const char *suffix;
1885 const char *color; /* NULL; filled in by the setup code if
1886 * color is enabled */
1889 struct diff_words_style {
1890 enum diff_words_type type;
1891 struct diff_words_style_elem new_word, old_word, ctx;
1892 const char *newline;
1895 static struct diff_words_style diff_words_styles[] = {
1896 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1897 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1898 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1901 struct diff_words_data {
1902 struct diff_words_buffer minus, plus;
1903 const char *current_plus;
1904 int last_minus;
1905 struct diff_options *opt;
1906 regex_t *word_regex;
1907 enum diff_words_type type;
1908 struct diff_words_style *style;
1911 static int fn_out_diff_words_write_helper(struct diff_options *o,
1912 struct diff_words_style_elem *st_el,
1913 const char *newline,
1914 size_t count, const char *buf)
1916 int print = 0;
1917 struct strbuf sb = STRBUF_INIT;
1919 while (count) {
1920 char *p = memchr(buf, '\n', count);
1921 if (print)
1922 strbuf_addstr(&sb, diff_line_prefix(o));
1924 if (p != buf) {
1925 const char *reset = st_el->color && *st_el->color ?
1926 GIT_COLOR_RESET : NULL;
1927 if (st_el->color && *st_el->color)
1928 strbuf_addstr(&sb, st_el->color);
1929 strbuf_addstr(&sb, st_el->prefix);
1930 strbuf_add(&sb, buf, p ? p - buf : count);
1931 strbuf_addstr(&sb, st_el->suffix);
1932 if (reset)
1933 strbuf_addstr(&sb, reset);
1935 if (!p)
1936 goto out;
1938 strbuf_addstr(&sb, newline);
1939 count -= p + 1 - buf;
1940 buf = p + 1;
1941 print = 1;
1942 if (count) {
1943 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1944 sb.buf, sb.len, 0);
1945 strbuf_reset(&sb);
1949 out:
1950 if (sb.len)
1951 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1952 sb.buf, sb.len, 0);
1953 strbuf_release(&sb);
1954 return 0;
1958 * '--color-words' algorithm can be described as:
1960 * 1. collect the minus/plus lines of a diff hunk, divided into
1961 * minus-lines and plus-lines;
1963 * 2. break both minus-lines and plus-lines into words and
1964 * place them into two mmfile_t with one word for each line;
1966 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1968 * And for the common parts of the both file, we output the plus side text.
1969 * diff_words->current_plus is used to trace the current position of the plus file
1970 * which printed. diff_words->last_minus is used to trace the last minus word
1971 * printed.
1973 * For '--graph' to work with '--color-words', we need to output the graph prefix
1974 * on each line of color words output. Generally, there are two conditions on
1975 * which we should output the prefix.
1977 * 1. diff_words->last_minus == 0 &&
1978 * diff_words->current_plus == diff_words->plus.text.ptr
1980 * that is: the plus text must start as a new line, and if there is no minus
1981 * word printed, a graph prefix must be printed.
1983 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1984 * *(diff_words->current_plus - 1) == '\n'
1986 * that is: a graph prefix must be printed following a '\n'
1988 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1990 if ((diff_words->last_minus == 0 &&
1991 diff_words->current_plus == diff_words->plus.text.ptr) ||
1992 (diff_words->current_plus > diff_words->plus.text.ptr &&
1993 *(diff_words->current_plus - 1) == '\n')) {
1994 return 1;
1995 } else {
1996 return 0;
2000 static void fn_out_diff_words_aux(void *priv,
2001 long minus_first, long minus_len,
2002 long plus_first, long plus_len,
2003 const char *func UNUSED, long funclen UNUSED)
2005 struct diff_words_data *diff_words = priv;
2006 struct diff_words_style *style = diff_words->style;
2007 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
2008 struct diff_options *opt = diff_words->opt;
2009 const char *line_prefix;
2011 assert(opt);
2012 line_prefix = diff_line_prefix(opt);
2014 /* POSIX requires that first be decremented by one if len == 0... */
2015 if (minus_len) {
2016 minus_begin = diff_words->minus.orig[minus_first].begin;
2017 minus_end =
2018 diff_words->minus.orig[minus_first + minus_len - 1].end;
2019 } else
2020 minus_begin = minus_end =
2021 diff_words->minus.orig[minus_first].end;
2023 if (plus_len) {
2024 plus_begin = diff_words->plus.orig[plus_first].begin;
2025 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2026 } else
2027 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2029 if (color_words_output_graph_prefix(diff_words)) {
2030 fputs(line_prefix, diff_words->opt->file);
2032 if (diff_words->current_plus != plus_begin) {
2033 fn_out_diff_words_write_helper(diff_words->opt,
2034 &style->ctx, style->newline,
2035 plus_begin - diff_words->current_plus,
2036 diff_words->current_plus);
2038 if (minus_begin != minus_end) {
2039 fn_out_diff_words_write_helper(diff_words->opt,
2040 &style->old_word, style->newline,
2041 minus_end - minus_begin, minus_begin);
2043 if (plus_begin != plus_end) {
2044 fn_out_diff_words_write_helper(diff_words->opt,
2045 &style->new_word, style->newline,
2046 plus_end - plus_begin, plus_begin);
2049 diff_words->current_plus = plus_end;
2050 diff_words->last_minus = minus_first;
2053 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2054 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2055 int *begin, int *end)
2057 while (word_regex && *begin < buffer->size) {
2058 regmatch_t match[1];
2059 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2060 buffer->size - *begin, 1, match, 0)) {
2061 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2062 '\n', match[0].rm_eo - match[0].rm_so);
2063 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2064 *begin += match[0].rm_so;
2065 if (*begin == *end)
2066 (*begin)++;
2067 else
2068 return *begin > *end;
2069 } else {
2070 return -1;
2074 /* find the next word */
2075 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2076 (*begin)++;
2077 if (*begin >= buffer->size)
2078 return -1;
2080 /* find the end of the word */
2081 *end = *begin + 1;
2082 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2083 (*end)++;
2085 return 0;
2089 * This function splits the words in buffer->text, stores the list with
2090 * newline separator into out, and saves the offsets of the original words
2091 * in buffer->orig.
2093 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2094 regex_t *word_regex)
2096 int i, j;
2097 long alloc = 0;
2099 out->size = 0;
2100 out->ptr = NULL;
2102 /* fake an empty "0th" word */
2103 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2104 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2105 buffer->orig_nr = 1;
2107 for (i = 0; i < buffer->text.size; i++) {
2108 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2109 return;
2111 /* store original boundaries */
2112 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2113 buffer->orig_alloc);
2114 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2115 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2116 buffer->orig_nr++;
2118 /* store one word */
2119 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2120 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2121 out->ptr[out->size + j - i] = '\n';
2122 out->size += j - i + 1;
2124 i = j - 1;
2128 /* this executes the word diff on the accumulated buffers */
2129 static void diff_words_show(struct diff_words_data *diff_words)
2131 xpparam_t xpp;
2132 xdemitconf_t xecfg;
2133 mmfile_t minus, plus;
2134 struct diff_words_style *style = diff_words->style;
2136 struct diff_options *opt = diff_words->opt;
2137 const char *line_prefix;
2139 assert(opt);
2140 line_prefix = diff_line_prefix(opt);
2142 /* special case: only removal */
2143 if (!diff_words->plus.text.size) {
2144 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2145 line_prefix, strlen(line_prefix), 0);
2146 fn_out_diff_words_write_helper(diff_words->opt,
2147 &style->old_word, style->newline,
2148 diff_words->minus.text.size,
2149 diff_words->minus.text.ptr);
2150 diff_words->minus.text.size = 0;
2151 return;
2154 diff_words->current_plus = diff_words->plus.text.ptr;
2155 diff_words->last_minus = 0;
2157 memset(&xpp, 0, sizeof(xpp));
2158 memset(&xecfg, 0, sizeof(xecfg));
2159 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2160 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2161 xpp.flags = 0;
2162 /* as only the hunk header will be parsed, we need a 0-context */
2163 xecfg.ctxlen = 0;
2164 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2165 diff_words, &xpp, &xecfg))
2166 die("unable to generate word diff");
2167 free(minus.ptr);
2168 free(plus.ptr);
2169 if (diff_words->current_plus != diff_words->plus.text.ptr +
2170 diff_words->plus.text.size) {
2171 if (color_words_output_graph_prefix(diff_words))
2172 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2173 line_prefix, strlen(line_prefix), 0);
2174 fn_out_diff_words_write_helper(diff_words->opt,
2175 &style->ctx, style->newline,
2176 diff_words->plus.text.ptr + diff_words->plus.text.size
2177 - diff_words->current_plus, diff_words->current_plus);
2179 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2182 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2183 static void diff_words_flush(struct emit_callback *ecbdata)
2185 struct diff_options *wo = ecbdata->diff_words->opt;
2187 if (ecbdata->diff_words->minus.text.size ||
2188 ecbdata->diff_words->plus.text.size)
2189 diff_words_show(ecbdata->diff_words);
2191 if (wo->emitted_symbols) {
2192 struct diff_options *o = ecbdata->opt;
2193 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2194 int i;
2197 * NEEDSWORK:
2198 * Instead of appending each, concat all words to a line?
2200 for (i = 0; i < wol->nr; i++)
2201 append_emitted_diff_symbol(o, &wol->buf[i]);
2203 for (i = 0; i < wol->nr; i++)
2204 free((void *)wol->buf[i].line);
2206 wol->nr = 0;
2210 static void diff_filespec_load_driver(struct diff_filespec *one,
2211 struct index_state *istate)
2213 /* Use already-loaded driver */
2214 if (one->driver)
2215 return;
2217 if (S_ISREG(one->mode))
2218 one->driver = userdiff_find_by_path(istate, one->path);
2220 /* Fallback to default settings */
2221 if (!one->driver)
2222 one->driver = userdiff_find_by_name("default");
2225 static const char *userdiff_word_regex(struct diff_filespec *one,
2226 struct index_state *istate)
2228 diff_filespec_load_driver(one, istate);
2229 return one->driver->word_regex;
2232 static void init_diff_words_data(struct emit_callback *ecbdata,
2233 struct diff_options *orig_opts,
2234 struct diff_filespec *one,
2235 struct diff_filespec *two)
2237 int i;
2238 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2239 memcpy(o, orig_opts, sizeof(struct diff_options));
2241 CALLOC_ARRAY(ecbdata->diff_words, 1);
2242 ecbdata->diff_words->type = o->word_diff;
2243 ecbdata->diff_words->opt = o;
2245 if (orig_opts->emitted_symbols)
2246 CALLOC_ARRAY(o->emitted_symbols, 1);
2248 if (!o->word_regex)
2249 o->word_regex = userdiff_word_regex(one, o->repo->index);
2250 if (!o->word_regex)
2251 o->word_regex = userdiff_word_regex(two, o->repo->index);
2252 if (!o->word_regex)
2253 o->word_regex = diff_word_regex_cfg;
2254 if (o->word_regex) {
2255 ecbdata->diff_words->word_regex = (regex_t *)
2256 xmalloc(sizeof(regex_t));
2257 if (regcomp(ecbdata->diff_words->word_regex,
2258 o->word_regex,
2259 REG_EXTENDED | REG_NEWLINE))
2260 die("invalid regular expression: %s",
2261 o->word_regex);
2263 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2264 if (o->word_diff == diff_words_styles[i].type) {
2265 ecbdata->diff_words->style =
2266 &diff_words_styles[i];
2267 break;
2270 if (want_color(o->use_color)) {
2271 struct diff_words_style *st = ecbdata->diff_words->style;
2272 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2273 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2274 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2278 static void free_diff_words_data(struct emit_callback *ecbdata)
2280 if (ecbdata->diff_words) {
2281 diff_words_flush(ecbdata);
2282 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2283 free (ecbdata->diff_words->opt);
2284 free (ecbdata->diff_words->minus.text.ptr);
2285 free (ecbdata->diff_words->minus.orig);
2286 free (ecbdata->diff_words->plus.text.ptr);
2287 free (ecbdata->diff_words->plus.orig);
2288 if (ecbdata->diff_words->word_regex) {
2289 regfree(ecbdata->diff_words->word_regex);
2290 free(ecbdata->diff_words->word_regex);
2292 FREE_AND_NULL(ecbdata->diff_words);
2296 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2298 if (want_color(diff_use_color))
2299 return diff_colors[ix];
2300 return "";
2303 const char *diff_line_prefix(struct diff_options *opt)
2305 struct strbuf *msgbuf;
2306 if (!opt->output_prefix)
2307 return "";
2309 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2310 return msgbuf->buf;
2313 static unsigned long sane_truncate_line(char *line, unsigned long len)
2315 const char *cp;
2316 unsigned long allot;
2317 size_t l = len;
2319 cp = line;
2320 allot = l;
2321 while (0 < l) {
2322 (void) utf8_width(&cp, &l);
2323 if (!cp)
2324 break; /* truncated in the middle? */
2326 return allot - l;
2329 static void find_lno(const char *line, struct emit_callback *ecbdata)
2331 const char *p;
2332 ecbdata->lno_in_preimage = 0;
2333 ecbdata->lno_in_postimage = 0;
2334 p = strchr(line, '-');
2335 if (!p)
2336 return; /* cannot happen */
2337 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2338 p = strchr(p, '+');
2339 if (!p)
2340 return; /* cannot happen */
2341 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2344 static int fn_out_consume(void *priv, char *line, unsigned long len)
2346 struct emit_callback *ecbdata = priv;
2347 struct diff_options *o = ecbdata->opt;
2349 o->found_changes = 1;
2351 if (ecbdata->header) {
2352 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2353 ecbdata->header->buf, ecbdata->header->len, 0);
2354 strbuf_reset(ecbdata->header);
2355 ecbdata->header = NULL;
2358 if (ecbdata->label_path[0]) {
2359 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2360 ecbdata->label_path[0],
2361 strlen(ecbdata->label_path[0]), 0);
2362 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2363 ecbdata->label_path[1],
2364 strlen(ecbdata->label_path[1]), 0);
2365 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2368 if (diff_suppress_blank_empty
2369 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2370 line[0] = '\n';
2371 len = 1;
2374 if (line[0] == '@') {
2375 if (ecbdata->diff_words)
2376 diff_words_flush(ecbdata);
2377 len = sane_truncate_line(line, len);
2378 find_lno(line, ecbdata);
2379 emit_hunk_header(ecbdata, line, len);
2380 return 0;
2383 if (ecbdata->diff_words) {
2384 enum diff_symbol s =
2385 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2386 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2387 if (line[0] == '-') {
2388 diff_words_append(line, len,
2389 &ecbdata->diff_words->minus);
2390 return 0;
2391 } else if (line[0] == '+') {
2392 diff_words_append(line, len,
2393 &ecbdata->diff_words->plus);
2394 return 0;
2395 } else if (starts_with(line, "\\ ")) {
2397 * Eat the "no newline at eof" marker as if we
2398 * saw a "+" or "-" line with nothing on it,
2399 * and return without diff_words_flush() to
2400 * defer processing. If this is the end of
2401 * preimage, more "+" lines may come after it.
2403 return 0;
2405 diff_words_flush(ecbdata);
2406 emit_diff_symbol(o, s, line, len, 0);
2407 return 0;
2410 switch (line[0]) {
2411 case '+':
2412 ecbdata->lno_in_postimage++;
2413 emit_add_line(ecbdata, line + 1, len - 1);
2414 break;
2415 case '-':
2416 ecbdata->lno_in_preimage++;
2417 emit_del_line(ecbdata, line + 1, len - 1);
2418 break;
2419 case ' ':
2420 ecbdata->lno_in_postimage++;
2421 ecbdata->lno_in_preimage++;
2422 emit_context_line(ecbdata, line + 1, len - 1);
2423 break;
2424 default:
2425 /* incomplete line at the end */
2426 ecbdata->lno_in_preimage++;
2427 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2428 line, len, 0);
2429 break;
2431 return 0;
2434 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2436 const char *old_name = a;
2437 const char *new_name = b;
2438 int pfx_length, sfx_length;
2439 int pfx_adjust_for_slash;
2440 int len_a = strlen(a);
2441 int len_b = strlen(b);
2442 int a_midlen, b_midlen;
2443 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2444 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2446 if (qlen_a || qlen_b) {
2447 quote_c_style(a, name, NULL, 0);
2448 strbuf_addstr(name, " => ");
2449 quote_c_style(b, name, NULL, 0);
2450 return;
2453 /* Find common prefix */
2454 pfx_length = 0;
2455 while (*old_name && *new_name && *old_name == *new_name) {
2456 if (*old_name == '/')
2457 pfx_length = old_name - a + 1;
2458 old_name++;
2459 new_name++;
2462 /* Find common suffix */
2463 old_name = a + len_a;
2464 new_name = b + len_b;
2465 sfx_length = 0;
2467 * If there is a common prefix, it must end in a slash. In
2468 * that case we let this loop run 1 into the prefix to see the
2469 * same slash.
2471 * If there is no common prefix, we cannot do this as it would
2472 * underrun the input strings.
2474 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2475 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2476 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2477 *old_name == *new_name) {
2478 if (*old_name == '/')
2479 sfx_length = len_a - (old_name - a);
2480 old_name--;
2481 new_name--;
2485 * pfx{mid-a => mid-b}sfx
2486 * {pfx-a => pfx-b}sfx
2487 * pfx{sfx-a => sfx-b}
2488 * name-a => name-b
2490 a_midlen = len_a - pfx_length - sfx_length;
2491 b_midlen = len_b - pfx_length - sfx_length;
2492 if (a_midlen < 0)
2493 a_midlen = 0;
2494 if (b_midlen < 0)
2495 b_midlen = 0;
2497 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2498 if (pfx_length + sfx_length) {
2499 strbuf_add(name, a, pfx_length);
2500 strbuf_addch(name, '{');
2502 strbuf_add(name, a + pfx_length, a_midlen);
2503 strbuf_addstr(name, " => ");
2504 strbuf_add(name, b + pfx_length, b_midlen);
2505 if (pfx_length + sfx_length) {
2506 strbuf_addch(name, '}');
2507 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2511 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2512 const char *name_a,
2513 const char *name_b)
2515 struct diffstat_file *x;
2516 CALLOC_ARRAY(x, 1);
2517 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2518 diffstat->files[diffstat->nr++] = x;
2519 if (name_b) {
2520 x->from_name = xstrdup(name_a);
2521 x->name = xstrdup(name_b);
2522 x->is_renamed = 1;
2524 else {
2525 x->from_name = NULL;
2526 x->name = xstrdup(name_a);
2528 return x;
2531 static int diffstat_consume(void *priv, char *line, unsigned long len)
2533 struct diffstat_t *diffstat = priv;
2534 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2536 if (!len)
2537 BUG("xdiff fed us an empty line");
2539 if (line[0] == '+')
2540 x->added++;
2541 else if (line[0] == '-')
2542 x->deleted++;
2543 return 0;
2546 const char mime_boundary_leader[] = "------------";
2548 static int scale_linear(int it, int width, int max_change)
2550 if (!it)
2551 return 0;
2553 * make sure that at least one '-' or '+' is printed if
2554 * there is any change to this path. The easiest way is to
2555 * scale linearly as if the allotted width is one column shorter
2556 * than it is, and then add 1 to the result.
2558 return 1 + (it * (width - 1) / max_change);
2561 static void show_graph(struct strbuf *out, char ch, int cnt,
2562 const char *set, const char *reset)
2564 if (cnt <= 0)
2565 return;
2566 strbuf_addstr(out, set);
2567 strbuf_addchars(out, ch, cnt);
2568 strbuf_addstr(out, reset);
2571 static void fill_print_name(struct diffstat_file *file)
2573 struct strbuf pname = STRBUF_INIT;
2575 if (file->print_name)
2576 return;
2578 if (file->is_renamed)
2579 pprint_rename(&pname, file->from_name, file->name);
2580 else
2581 quote_c_style(file->name, &pname, NULL, 0);
2583 if (file->comments)
2584 strbuf_addf(&pname, " (%s)", file->comments);
2586 file->print_name = strbuf_detach(&pname, NULL);
2589 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2590 int files, int insertions, int deletions)
2592 struct strbuf sb = STRBUF_INIT;
2594 if (!files) {
2595 assert(insertions == 0 && deletions == 0);
2596 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2597 NULL, 0, 0);
2598 return;
2601 strbuf_addf(&sb,
2602 (files == 1) ? " %d file changed" : " %d files changed",
2603 files);
2606 * For binary diff, the caller may want to print "x files
2607 * changed" with insertions == 0 && deletions == 0.
2609 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2610 * is probably less confusing (i.e skip over "2 files changed
2611 * but nothing about added/removed lines? Is this a bug in Git?").
2613 if (insertions || deletions == 0) {
2614 strbuf_addf(&sb,
2615 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2616 insertions);
2619 if (deletions || insertions == 0) {
2620 strbuf_addf(&sb,
2621 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2622 deletions);
2624 strbuf_addch(&sb, '\n');
2625 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2626 sb.buf, sb.len, 0);
2627 strbuf_release(&sb);
2630 void print_stat_summary(FILE *fp, int files,
2631 int insertions, int deletions)
2633 struct diff_options o;
2634 memset(&o, 0, sizeof(o));
2635 o.file = fp;
2637 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2640 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2642 int i, len, add, del, adds = 0, dels = 0;
2643 uintmax_t max_change = 0, max_len = 0;
2644 int total_files = data->nr, count;
2645 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2646 const char *reset, *add_c, *del_c;
2647 int extra_shown = 0;
2648 const char *line_prefix = diff_line_prefix(options);
2649 struct strbuf out = STRBUF_INIT;
2651 if (data->nr == 0)
2652 return;
2654 count = options->stat_count ? options->stat_count : data->nr;
2656 reset = diff_get_color_opt(options, DIFF_RESET);
2657 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2658 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2661 * Find the longest filename and max number of changes
2663 for (i = 0; (i < count) && (i < data->nr); i++) {
2664 struct diffstat_file *file = data->files[i];
2665 uintmax_t change = file->added + file->deleted;
2667 if (!file->is_interesting && (change == 0)) {
2668 count++; /* not shown == room for one more */
2669 continue;
2671 fill_print_name(file);
2672 len = utf8_strwidth(file->print_name);
2673 if (max_len < len)
2674 max_len = len;
2676 if (file->is_unmerged) {
2677 /* "Unmerged" is 8 characters */
2678 bin_width = bin_width < 8 ? 8 : bin_width;
2679 continue;
2681 if (file->is_binary) {
2682 /* "Bin XXX -> YYY bytes" */
2683 int w = 14 + decimal_width(file->added)
2684 + decimal_width(file->deleted);
2685 bin_width = bin_width < w ? w : bin_width;
2686 /* Display change counts aligned with "Bin" */
2687 number_width = 3;
2688 continue;
2691 if (max_change < change)
2692 max_change = change;
2694 count = i; /* where we can stop scanning in data->files[] */
2697 * We have width = stat_width or term_columns() columns total.
2698 * We want a maximum of min(max_len, stat_name_width) for the name part.
2699 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2700 * We also need 1 for " " and 4 + decimal_width(max_change)
2701 * for " | NNNN " and one the empty column at the end, altogether
2702 * 6 + decimal_width(max_change).
2704 * If there's not enough space, we will use the smaller of
2705 * stat_name_width (if set) and 5/8*width for the filename,
2706 * and the rest for constant elements + graph part, but no more
2707 * than stat_graph_width for the graph part.
2708 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2709 * for the standard terminal size).
2711 * In other words: stat_width limits the maximum width, and
2712 * stat_name_width fixes the maximum width of the filename,
2713 * and is also used to divide available columns if there
2714 * aren't enough.
2716 * Binary files are displayed with "Bin XXX -> YYY bytes"
2717 * instead of the change count and graph. This part is treated
2718 * similarly to the graph part, except that it is not
2719 * "scaled". If total width is too small to accommodate the
2720 * guaranteed minimum width of the filename part and the
2721 * separators and this message, this message will "overflow"
2722 * making the line longer than the maximum width.
2726 * NEEDSWORK: line_prefix is often used for "log --graph" output
2727 * and contains ANSI-colored string. utf8_strnwidth() should be
2728 * used to correctly count the display width instead of strlen().
2730 if (options->stat_width == -1)
2731 width = term_columns() - strlen(line_prefix);
2732 else
2733 width = options->stat_width ? options->stat_width : 80;
2734 number_width = decimal_width(max_change) > number_width ?
2735 decimal_width(max_change) : number_width;
2737 if (options->stat_name_width == -1)
2738 options->stat_name_width = diff_stat_name_width;
2739 if (options->stat_graph_width == -1)
2740 options->stat_graph_width = diff_stat_graph_width;
2743 * Guarantee 3/8*16 == 6 for the graph part
2744 * and 5/8*16 == 10 for the filename part
2746 if (width < 16 + 6 + number_width)
2747 width = 16 + 6 + number_width;
2750 * First assign sizes that are wanted, ignoring available width.
2751 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2752 * starting from "XXX" should fit in graph_width.
2754 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2755 if (options->stat_graph_width &&
2756 options->stat_graph_width < graph_width)
2757 graph_width = options->stat_graph_width;
2759 name_width = (options->stat_name_width > 0 &&
2760 options->stat_name_width < max_len) ?
2761 options->stat_name_width : max_len;
2764 * Adjust adjustable widths not to exceed maximum width
2766 if (name_width + number_width + 6 + graph_width > width) {
2767 if (graph_width > width * 3/8 - number_width - 6) {
2768 graph_width = width * 3/8 - number_width - 6;
2769 if (graph_width < 6)
2770 graph_width = 6;
2773 if (options->stat_graph_width &&
2774 graph_width > options->stat_graph_width)
2775 graph_width = options->stat_graph_width;
2776 if (name_width > width - number_width - 6 - graph_width)
2777 name_width = width - number_width - 6 - graph_width;
2778 else
2779 graph_width = width - number_width - 6 - name_width;
2783 * From here name_width is the width of the name area,
2784 * and graph_width is the width of the graph area.
2785 * max_change is used to scale graph properly.
2787 for (i = 0; i < count; i++) {
2788 const char *prefix = "";
2789 struct diffstat_file *file = data->files[i];
2790 char *name = file->print_name;
2791 uintmax_t added = file->added;
2792 uintmax_t deleted = file->deleted;
2793 int name_len, padding;
2795 if (!file->is_interesting && (added + deleted == 0))
2796 continue;
2799 * "scale" the filename
2801 len = name_width;
2802 name_len = utf8_strwidth(name);
2803 if (name_width < name_len) {
2804 char *slash;
2805 prefix = "...";
2806 len -= 3;
2808 * NEEDSWORK: (name_len - len) counts the display
2809 * width, which would be shorter than the byte
2810 * length of the corresponding substring.
2811 * Advancing "name" by that number of bytes does
2812 * *NOT* skip over that many columns, so it is
2813 * very likely that chomping the pathname at the
2814 * slash we will find starting from "name" will
2815 * leave the resulting string still too long.
2817 name += name_len - len;
2818 slash = strchr(name, '/');
2819 if (slash)
2820 name = slash;
2822 padding = len - utf8_strwidth(name);
2823 if (padding < 0)
2824 padding = 0;
2826 if (file->is_binary) {
2827 strbuf_addf(&out, " %s%s%*s | %*s",
2828 prefix, name, padding, "",
2829 number_width, "Bin");
2830 if (!added && !deleted) {
2831 strbuf_addch(&out, '\n');
2832 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2833 out.buf, out.len, 0);
2834 strbuf_reset(&out);
2835 continue;
2837 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2838 del_c, deleted, reset);
2839 strbuf_addstr(&out, " -> ");
2840 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2841 add_c, added, reset);
2842 strbuf_addstr(&out, " bytes\n");
2843 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2844 out.buf, out.len, 0);
2845 strbuf_reset(&out);
2846 continue;
2848 else if (file->is_unmerged) {
2849 strbuf_addf(&out, " %s%s%*s | %*s",
2850 prefix, name, padding, "",
2851 number_width, "Unmerged\n");
2852 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2853 out.buf, out.len, 0);
2854 strbuf_reset(&out);
2855 continue;
2859 * scale the add/delete
2861 add = added;
2862 del = deleted;
2864 if (graph_width <= max_change) {
2865 int total = scale_linear(add + del, graph_width, max_change);
2866 if (total < 2 && add && del)
2867 /* width >= 2 due to the sanity check */
2868 total = 2;
2869 if (add < del) {
2870 add = scale_linear(add, graph_width, max_change);
2871 del = total - add;
2872 } else {
2873 del = scale_linear(del, graph_width, max_change);
2874 add = total - del;
2877 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
2878 prefix, name, padding, "",
2879 number_width, added + deleted,
2880 added + deleted ? " " : "");
2881 show_graph(&out, '+', add, add_c, reset);
2882 show_graph(&out, '-', del, del_c, reset);
2883 strbuf_addch(&out, '\n');
2884 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2885 out.buf, out.len, 0);
2886 strbuf_reset(&out);
2889 for (i = 0; i < data->nr; i++) {
2890 struct diffstat_file *file = data->files[i];
2891 uintmax_t added = file->added;
2892 uintmax_t deleted = file->deleted;
2894 if (file->is_unmerged ||
2895 (!file->is_interesting && (added + deleted == 0))) {
2896 total_files--;
2897 continue;
2900 if (!file->is_binary) {
2901 adds += added;
2902 dels += deleted;
2904 if (i < count)
2905 continue;
2906 if (!extra_shown)
2907 emit_diff_symbol(options,
2908 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2909 NULL, 0, 0);
2910 extra_shown = 1;
2913 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2914 strbuf_release(&out);
2917 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2919 int i, adds = 0, dels = 0, total_files = data->nr;
2921 if (data->nr == 0)
2922 return;
2924 for (i = 0; i < data->nr; i++) {
2925 int added = data->files[i]->added;
2926 int deleted = data->files[i]->deleted;
2928 if (data->files[i]->is_unmerged ||
2929 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2930 total_files--;
2931 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2932 adds += added;
2933 dels += deleted;
2936 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2939 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2941 int i;
2943 if (data->nr == 0)
2944 return;
2946 for (i = 0; i < data->nr; i++) {
2947 struct diffstat_file *file = data->files[i];
2949 fprintf(options->file, "%s", diff_line_prefix(options));
2951 if (file->is_binary)
2952 fprintf(options->file, "-\t-\t");
2953 else
2954 fprintf(options->file,
2955 "%"PRIuMAX"\t%"PRIuMAX"\t",
2956 file->added, file->deleted);
2957 if (options->line_termination) {
2958 fill_print_name(file);
2959 if (!file->is_renamed)
2960 write_name_quoted(file->name, options->file,
2961 options->line_termination);
2962 else {
2963 fputs(file->print_name, options->file);
2964 putc(options->line_termination, options->file);
2966 } else {
2967 if (file->is_renamed) {
2968 putc('\0', options->file);
2969 write_name_quoted(file->from_name, options->file, '\0');
2971 write_name_quoted(file->name, options->file, '\0');
2976 struct dirstat_file {
2977 const char *name;
2978 unsigned long changed;
2981 struct dirstat_dir {
2982 struct dirstat_file *files;
2983 int alloc, nr, permille, cumulative;
2986 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2987 unsigned long changed, const char *base, int baselen)
2989 unsigned long sum_changes = 0;
2990 unsigned int sources = 0;
2991 const char *line_prefix = diff_line_prefix(opt);
2993 while (dir->nr) {
2994 struct dirstat_file *f = dir->files;
2995 int namelen = strlen(f->name);
2996 unsigned long changes;
2997 char *slash;
2999 if (namelen < baselen)
3000 break;
3001 if (memcmp(f->name, base, baselen))
3002 break;
3003 slash = strchr(f->name + baselen, '/');
3004 if (slash) {
3005 int newbaselen = slash + 1 - f->name;
3006 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
3007 sources++;
3008 } else {
3009 changes = f->changed;
3010 dir->files++;
3011 dir->nr--;
3012 sources += 2;
3014 sum_changes += changes;
3018 * We don't report dirstat's for
3019 * - the top level
3020 * - or cases where everything came from a single directory
3021 * under this directory (sources == 1).
3023 if (baselen && sources != 1) {
3024 if (sum_changes) {
3025 int permille = sum_changes * 1000 / changed;
3026 if (permille >= dir->permille) {
3027 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
3028 permille / 10, permille % 10, baselen, base);
3029 if (!dir->cumulative)
3030 return 0;
3034 return sum_changes;
3037 static int dirstat_compare(const void *_a, const void *_b)
3039 const struct dirstat_file *a = _a;
3040 const struct dirstat_file *b = _b;
3041 return strcmp(a->name, b->name);
3044 static void conclude_dirstat(struct diff_options *options,
3045 struct dirstat_dir *dir,
3046 unsigned long changed)
3048 struct dirstat_file *to_free = dir->files;
3050 if (!changed) {
3051 /* This can happen even with many files, if everything was renames */
3053 } else {
3054 /* Show all directories with more than x% of the changes */
3055 QSORT(dir->files, dir->nr, dirstat_compare);
3056 gather_dirstat(options, dir, changed, "", 0);
3059 free(to_free);
3062 static void show_dirstat(struct diff_options *options)
3064 int i;
3065 unsigned long changed;
3066 struct dirstat_dir dir;
3067 struct diff_queue_struct *q = &diff_queued_diff;
3069 dir.files = NULL;
3070 dir.alloc = 0;
3071 dir.nr = 0;
3072 dir.permille = options->dirstat_permille;
3073 dir.cumulative = options->flags.dirstat_cumulative;
3075 changed = 0;
3076 for (i = 0; i < q->nr; i++) {
3077 struct diff_filepair *p = q->queue[i];
3078 const char *name;
3079 unsigned long copied, added, damage;
3080 struct diff_populate_filespec_options dpf_options = {
3081 .check_size_only = 1,
3084 name = p->two->path ? p->two->path : p->one->path;
3086 if (p->one->oid_valid && p->two->oid_valid &&
3087 oideq(&p->one->oid, &p->two->oid)) {
3089 * The SHA1 has not changed, so pre-/post-content is
3090 * identical. We can therefore skip looking at the
3091 * file contents altogether.
3093 damage = 0;
3094 goto found_damage;
3097 if (options->flags.dirstat_by_file) {
3099 * In --dirstat-by-file mode, we don't really need to
3100 * look at the actual file contents at all.
3101 * The fact that the SHA1 changed is enough for us to
3102 * add this file to the list of results
3103 * (with each file contributing equal damage).
3105 damage = 1;
3106 goto found_damage;
3109 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3110 diff_populate_filespec(options->repo, p->one, NULL);
3111 diff_populate_filespec(options->repo, p->two, NULL);
3112 diffcore_count_changes(options->repo,
3113 p->one, p->two, NULL, NULL,
3114 &copied, &added);
3115 diff_free_filespec_data(p->one);
3116 diff_free_filespec_data(p->two);
3117 } else if (DIFF_FILE_VALID(p->one)) {
3118 diff_populate_filespec(options->repo, p->one, &dpf_options);
3119 copied = added = 0;
3120 diff_free_filespec_data(p->one);
3121 } else if (DIFF_FILE_VALID(p->two)) {
3122 diff_populate_filespec(options->repo, p->two, &dpf_options);
3123 copied = 0;
3124 added = p->two->size;
3125 diff_free_filespec_data(p->two);
3126 } else
3127 continue;
3130 * Original minus copied is the removed material,
3131 * added is the new material. They are both damages
3132 * made to the preimage.
3133 * If the resulting damage is zero, we know that
3134 * diffcore_count_changes() considers the two entries to
3135 * be identical, but since the oid changed, we
3136 * know that there must have been _some_ kind of change,
3137 * so we force all entries to have damage > 0.
3139 damage = (p->one->size - copied) + added;
3140 if (!damage)
3141 damage = 1;
3143 found_damage:
3144 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3145 dir.files[dir.nr].name = name;
3146 dir.files[dir.nr].changed = damage;
3147 changed += damage;
3148 dir.nr++;
3151 conclude_dirstat(options, &dir, changed);
3154 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3156 int i;
3157 unsigned long changed;
3158 struct dirstat_dir dir;
3160 if (data->nr == 0)
3161 return;
3163 dir.files = NULL;
3164 dir.alloc = 0;
3165 dir.nr = 0;
3166 dir.permille = options->dirstat_permille;
3167 dir.cumulative = options->flags.dirstat_cumulative;
3169 changed = 0;
3170 for (i = 0; i < data->nr; i++) {
3171 struct diffstat_file *file = data->files[i];
3172 unsigned long damage = file->added + file->deleted;
3173 if (file->is_binary)
3175 * binary files counts bytes, not lines. Must find some
3176 * way to normalize binary bytes vs. textual lines.
3177 * The following heuristic assumes that there are 64
3178 * bytes per "line".
3179 * This is stupid and ugly, but very cheap...
3181 damage = DIV_ROUND_UP(damage, 64);
3182 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3183 dir.files[dir.nr].name = file->name;
3184 dir.files[dir.nr].changed = damage;
3185 changed += damage;
3186 dir.nr++;
3189 conclude_dirstat(options, &dir, changed);
3192 static void free_diffstat_file(struct diffstat_file *f)
3194 free(f->print_name);
3195 free(f->name);
3196 free(f->from_name);
3197 free(f);
3200 void free_diffstat_info(struct diffstat_t *diffstat)
3202 int i;
3203 for (i = 0; i < diffstat->nr; i++)
3204 free_diffstat_file(diffstat->files[i]);
3205 free(diffstat->files);
3208 struct checkdiff_t {
3209 const char *filename;
3210 int lineno;
3211 int conflict_marker_size;
3212 struct diff_options *o;
3213 unsigned ws_rule;
3214 unsigned status;
3217 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3219 char firstchar;
3220 int cnt;
3222 if (len < marker_size + 1)
3223 return 0;
3224 firstchar = line[0];
3225 switch (firstchar) {
3226 case '=': case '>': case '<': case '|':
3227 break;
3228 default:
3229 return 0;
3231 for (cnt = 1; cnt < marker_size; cnt++)
3232 if (line[cnt] != firstchar)
3233 return 0;
3234 /* line[1] through line[marker_size-1] are same as firstchar */
3235 if (len < marker_size + 1 || !isspace(line[marker_size]))
3236 return 0;
3237 return 1;
3240 static void checkdiff_consume_hunk(void *priv,
3241 long ob UNUSED, long on UNUSED,
3242 long nb, long nn UNUSED,
3243 const char *func UNUSED, long funclen UNUSED)
3246 struct checkdiff_t *data = priv;
3247 data->lineno = nb - 1;
3250 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3252 struct checkdiff_t *data = priv;
3253 int marker_size = data->conflict_marker_size;
3254 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3255 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3256 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3257 char *err;
3258 const char *line_prefix;
3260 assert(data->o);
3261 line_prefix = diff_line_prefix(data->o);
3263 if (line[0] == '+') {
3264 unsigned bad;
3265 data->lineno++;
3266 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3267 data->status |= 1;
3268 fprintf(data->o->file,
3269 "%s%s:%d: leftover conflict marker\n",
3270 line_prefix, data->filename, data->lineno);
3272 bad = ws_check(line + 1, len - 1, data->ws_rule);
3273 if (!bad)
3274 return 0;
3275 data->status |= bad;
3276 err = whitespace_error_string(bad);
3277 fprintf(data->o->file, "%s%s:%d: %s.\n",
3278 line_prefix, data->filename, data->lineno, err);
3279 free(err);
3280 emit_line(data->o, set, reset, line, 1);
3281 ws_check_emit(line + 1, len - 1, data->ws_rule,
3282 data->o->file, set, reset, ws);
3283 } else if (line[0] == ' ') {
3284 data->lineno++;
3286 return 0;
3289 static unsigned char *deflate_it(char *data,
3290 unsigned long size,
3291 unsigned long *result_size)
3293 int bound;
3294 unsigned char *deflated;
3295 git_zstream stream;
3297 git_deflate_init(&stream, zlib_compression_level);
3298 bound = git_deflate_bound(&stream, size);
3299 deflated = xmalloc(bound);
3300 stream.next_out = deflated;
3301 stream.avail_out = bound;
3303 stream.next_in = (unsigned char *)data;
3304 stream.avail_in = size;
3305 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3306 ; /* nothing */
3307 git_deflate_end(&stream);
3308 *result_size = stream.total_out;
3309 return deflated;
3312 static void emit_binary_diff_body(struct diff_options *o,
3313 mmfile_t *one, mmfile_t *two)
3315 void *cp;
3316 void *delta;
3317 void *deflated;
3318 void *data;
3319 unsigned long orig_size;
3320 unsigned long delta_size;
3321 unsigned long deflate_size;
3322 unsigned long data_size;
3324 /* We could do deflated delta, or we could do just deflated two,
3325 * whichever is smaller.
3327 delta = NULL;
3328 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3329 if (one->size && two->size) {
3330 delta = diff_delta(one->ptr, one->size,
3331 two->ptr, two->size,
3332 &delta_size, deflate_size);
3333 if (delta) {
3334 void *to_free = delta;
3335 orig_size = delta_size;
3336 delta = deflate_it(delta, delta_size, &delta_size);
3337 free(to_free);
3341 if (delta && delta_size < deflate_size) {
3342 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3343 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3344 s, strlen(s), 0);
3345 free(s);
3346 free(deflated);
3347 data = delta;
3348 data_size = delta_size;
3349 } else {
3350 char *s = xstrfmt("%lu", two->size);
3351 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3352 s, strlen(s), 0);
3353 free(s);
3354 free(delta);
3355 data = deflated;
3356 data_size = deflate_size;
3359 /* emit data encoded in base85 */
3360 cp = data;
3361 while (data_size) {
3362 int len;
3363 int bytes = (52 < data_size) ? 52 : data_size;
3364 char line[71];
3365 data_size -= bytes;
3366 if (bytes <= 26)
3367 line[0] = bytes + 'A' - 1;
3368 else
3369 line[0] = bytes - 26 + 'a' - 1;
3370 encode_85(line + 1, cp, bytes);
3371 cp = (char *) cp + bytes;
3373 len = strlen(line);
3374 line[len++] = '\n';
3375 line[len] = '\0';
3377 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3378 line, len, 0);
3380 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3381 free(data);
3384 static void emit_binary_diff(struct diff_options *o,
3385 mmfile_t *one, mmfile_t *two)
3387 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3388 emit_binary_diff_body(o, one, two);
3389 emit_binary_diff_body(o, two, one);
3392 int diff_filespec_is_binary(struct repository *r,
3393 struct diff_filespec *one)
3395 struct diff_populate_filespec_options dpf_options = {
3396 .check_binary = 1,
3399 if (one->is_binary == -1) {
3400 diff_filespec_load_driver(one, r->index);
3401 if (one->driver->binary != -1)
3402 one->is_binary = one->driver->binary;
3403 else {
3404 if (!one->data && DIFF_FILE_VALID(one))
3405 diff_populate_filespec(r, one, &dpf_options);
3406 if (one->is_binary == -1 && one->data)
3407 one->is_binary = buffer_is_binary(one->data,
3408 one->size);
3409 if (one->is_binary == -1)
3410 one->is_binary = 0;
3413 return one->is_binary;
3416 static const struct userdiff_funcname *
3417 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3419 diff_filespec_load_driver(one, o->repo->index);
3420 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3423 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3425 if (!options->a_prefix)
3426 options->a_prefix = a;
3427 if (!options->b_prefix)
3428 options->b_prefix = b;
3431 void diff_set_noprefix(struct diff_options *options)
3433 options->a_prefix = options->b_prefix = "";
3436 void diff_set_default_prefix(struct diff_options *options)
3438 options->a_prefix = diff_src_prefix ? diff_src_prefix : "a/";
3439 options->b_prefix = diff_dst_prefix ? diff_dst_prefix : "b/";
3442 struct userdiff_driver *get_textconv(struct repository *r,
3443 struct diff_filespec *one)
3445 if (!DIFF_FILE_VALID(one))
3446 return NULL;
3448 diff_filespec_load_driver(one, r->index);
3449 return userdiff_get_textconv(r, one->driver);
3452 static struct string_list *additional_headers(struct diff_options *o,
3453 const char *path)
3455 if (!o->additional_path_headers)
3456 return NULL;
3457 return strmap_get(o->additional_path_headers, path);
3460 static void add_formatted_header(struct strbuf *msg,
3461 const char *header,
3462 const char *line_prefix,
3463 const char *meta,
3464 const char *reset)
3466 const char *next, *newline;
3468 for (next = header; *next; next = newline) {
3469 newline = strchrnul(next, '\n');
3470 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3471 (int)(newline - next), next, reset);
3472 if (*newline)
3473 newline++;
3477 static void add_formatted_headers(struct strbuf *msg,
3478 struct string_list *more_headers,
3479 const char *line_prefix,
3480 const char *meta,
3481 const char *reset)
3483 int i;
3485 for (i = 0; i < more_headers->nr; i++)
3486 add_formatted_header(msg, more_headers->items[i].string,
3487 line_prefix, meta, reset);
3490 static int diff_filepair_is_phoney(struct diff_filespec *one,
3491 struct diff_filespec *two)
3494 * This function specifically looks for pairs injected by
3495 * create_filepairs_for_header_only_notifications(). Such
3496 * pairs are "phoney" in that they do not represent any
3497 * content or even mode difference, but were inserted because
3498 * diff_queued_diff previously had no pair associated with
3499 * that path but we needed some pair to avoid losing the
3500 * "remerge CONFLICT" header associated with the path.
3502 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3505 static int set_diff_algorithm(struct diff_options *opts,
3506 const char *alg)
3508 long value = parse_algorithm_value(alg);
3510 if (value < 0)
3511 return -1;
3513 /* clear out previous settings */
3514 DIFF_XDL_CLR(opts, NEED_MINIMAL);
3515 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3516 opts->xdl_opts |= value;
3518 return 0;
3521 static void builtin_diff(const char *name_a,
3522 const char *name_b,
3523 struct diff_filespec *one,
3524 struct diff_filespec *two,
3525 const char *xfrm_msg,
3526 int must_show_header,
3527 struct diff_options *o,
3528 int complete_rewrite)
3530 mmfile_t mf1, mf2;
3531 const char *lbl[2];
3532 char *a_one, *b_two;
3533 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3534 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3535 const char *a_prefix, *b_prefix;
3536 struct userdiff_driver *textconv_one = NULL;
3537 struct userdiff_driver *textconv_two = NULL;
3538 struct strbuf header = STRBUF_INIT;
3539 const char *line_prefix = diff_line_prefix(o);
3541 diff_set_mnemonic_prefix(o, "a/", "b/");
3542 if (o->flags.reverse_diff) {
3543 a_prefix = o->b_prefix;
3544 b_prefix = o->a_prefix;
3545 } else {
3546 a_prefix = o->a_prefix;
3547 b_prefix = o->b_prefix;
3550 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3551 (!one->mode || S_ISGITLINK(one->mode)) &&
3552 (!two->mode || S_ISGITLINK(two->mode)) &&
3553 (!diff_filepair_is_phoney(one, two))) {
3554 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3555 &one->oid, &two->oid,
3556 two->dirty_submodule);
3557 return;
3558 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3559 (!one->mode || S_ISGITLINK(one->mode)) &&
3560 (!two->mode || S_ISGITLINK(two->mode)) &&
3561 (!diff_filepair_is_phoney(one, two))) {
3562 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3563 &one->oid, &two->oid,
3564 two->dirty_submodule);
3565 return;
3568 if (o->flags.allow_textconv) {
3569 textconv_one = get_textconv(o->repo, one);
3570 textconv_two = get_textconv(o->repo, two);
3573 /* Never use a non-valid filename anywhere if at all possible */
3574 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3575 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3577 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3578 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3579 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3580 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3581 if (diff_filepair_is_phoney(one, two)) {
3583 * We should only reach this point for pairs generated from
3584 * create_filepairs_for_header_only_notifications(). For
3585 * these, we want to avoid the "/dev/null" special casing
3586 * above, because we do not want such pairs shown as either
3587 * "new file" or "deleted file" below.
3589 lbl[0] = a_one;
3590 lbl[1] = b_two;
3592 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3593 if (lbl[0][0] == '/') {
3594 /* /dev/null */
3595 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3596 if (xfrm_msg)
3597 strbuf_addstr(&header, xfrm_msg);
3598 o->found_changes = 1;
3599 must_show_header = 1;
3601 else if (lbl[1][0] == '/') {
3602 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3603 if (xfrm_msg)
3604 strbuf_addstr(&header, xfrm_msg);
3605 o->found_changes = 1;
3606 must_show_header = 1;
3608 else {
3609 if (one->mode != two->mode) {
3610 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3611 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3612 o->found_changes = 1;
3613 must_show_header = 1;
3615 if (xfrm_msg)
3616 strbuf_addstr(&header, xfrm_msg);
3619 * we do not run diff between different kind
3620 * of objects.
3622 if ((one->mode ^ two->mode) & S_IFMT)
3623 goto free_ab_and_return;
3624 if (complete_rewrite &&
3625 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3626 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3627 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3628 header.buf, header.len, 0);
3629 strbuf_reset(&header);
3630 emit_rewrite_diff(name_a, name_b, one, two,
3631 textconv_one, textconv_two, o);
3632 o->found_changes = 1;
3633 goto free_ab_and_return;
3637 if (o->irreversible_delete && lbl[1][0] == '/') {
3638 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3639 header.len, 0);
3640 strbuf_reset(&header);
3641 goto free_ab_and_return;
3642 } else if (!o->flags.text &&
3643 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3644 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3645 struct strbuf sb = STRBUF_INIT;
3646 if (!one->data && !two->data &&
3647 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3648 !o->flags.binary) {
3649 if (oideq(&one->oid, &two->oid)) {
3650 if (must_show_header)
3651 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3652 header.buf, header.len,
3654 goto free_ab_and_return;
3656 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3657 header.buf, header.len, 0);
3658 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3659 diff_line_prefix(o), lbl[0], lbl[1]);
3660 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3661 sb.buf, sb.len, 0);
3662 strbuf_release(&sb);
3663 goto free_ab_and_return;
3665 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3666 fill_mmfile(o->repo, &mf2, two) < 0)
3667 die("unable to read files to diff");
3668 /* Quite common confusing case */
3669 if (mf1.size == mf2.size &&
3670 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3671 if (must_show_header)
3672 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3673 header.buf, header.len, 0);
3674 goto free_ab_and_return;
3676 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3677 strbuf_reset(&header);
3678 if (o->flags.binary)
3679 emit_binary_diff(o, &mf1, &mf2);
3680 else {
3681 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3682 diff_line_prefix(o), lbl[0], lbl[1]);
3683 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3684 sb.buf, sb.len, 0);
3685 strbuf_release(&sb);
3687 o->found_changes = 1;
3688 } else {
3689 /* Crazy xdl interfaces.. */
3690 const char *diffopts;
3691 const char *v;
3692 xpparam_t xpp;
3693 xdemitconf_t xecfg;
3694 struct emit_callback ecbdata;
3695 const struct userdiff_funcname *pe;
3697 if (must_show_header) {
3698 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3699 header.buf, header.len, 0);
3700 strbuf_reset(&header);
3703 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3704 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3706 pe = diff_funcname_pattern(o, one);
3707 if (!pe)
3708 pe = diff_funcname_pattern(o, two);
3710 memset(&xpp, 0, sizeof(xpp));
3711 memset(&xecfg, 0, sizeof(xecfg));
3712 memset(&ecbdata, 0, sizeof(ecbdata));
3713 if (o->flags.suppress_diff_headers)
3714 lbl[0] = NULL;
3715 ecbdata.label_path = lbl;
3716 ecbdata.color_diff = want_color(o->use_color);
3717 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3718 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3719 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3720 ecbdata.opt = o;
3721 if (header.len && !o->flags.suppress_diff_headers)
3722 ecbdata.header = &header;
3723 xpp.flags = o->xdl_opts;
3724 xpp.ignore_regex = o->ignore_regex;
3725 xpp.ignore_regex_nr = o->ignore_regex_nr;
3726 xpp.anchors = o->anchors;
3727 xpp.anchors_nr = o->anchors_nr;
3728 xecfg.ctxlen = o->context;
3729 xecfg.interhunkctxlen = o->interhunkcontext;
3730 xecfg.flags = XDL_EMIT_FUNCNAMES;
3731 if (o->flags.funccontext)
3732 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3733 if (pe)
3734 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3736 diffopts = getenv("GIT_DIFF_OPTS");
3737 if (!diffopts)
3739 else if (skip_prefix(diffopts, "--unified=", &v))
3740 xecfg.ctxlen = strtoul(v, NULL, 10);
3741 else if (skip_prefix(diffopts, "-u", &v))
3742 xecfg.ctxlen = strtoul(v, NULL, 10);
3744 if (o->word_diff)
3745 init_diff_words_data(&ecbdata, o, one, two);
3746 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3747 &ecbdata, &xpp, &xecfg))
3748 die("unable to generate diff for %s", one->path);
3749 if (o->word_diff)
3750 free_diff_words_data(&ecbdata);
3751 if (textconv_one)
3752 free(mf1.ptr);
3753 if (textconv_two)
3754 free(mf2.ptr);
3755 xdiff_clear_find_func(&xecfg);
3758 free_ab_and_return:
3759 strbuf_release(&header);
3760 diff_free_filespec_data(one);
3761 diff_free_filespec_data(two);
3762 free(a_one);
3763 free(b_two);
3764 return;
3767 static const char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3769 if (!is_renamed) {
3770 if (p->status == DIFF_STATUS_ADDED) {
3771 if (S_ISLNK(p->two->mode))
3772 return "new +l";
3773 else if ((p->two->mode & 0777) == 0755)
3774 return "new +x";
3775 else
3776 return "new";
3777 } else if (p->status == DIFF_STATUS_DELETED)
3778 return "gone";
3780 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3781 return "mode -l";
3782 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3783 return "mode +l";
3784 else if ((p->one->mode & 0777) == 0644 &&
3785 (p->two->mode & 0777) == 0755)
3786 return "mode +x";
3787 else if ((p->one->mode & 0777) == 0755 &&
3788 (p->two->mode & 0777) == 0644)
3789 return "mode -x";
3790 return NULL;
3793 static void builtin_diffstat(const char *name_a, const char *name_b,
3794 struct diff_filespec *one,
3795 struct diff_filespec *two,
3796 struct diffstat_t *diffstat,
3797 struct diff_options *o,
3798 struct diff_filepair *p)
3800 mmfile_t mf1, mf2;
3801 struct diffstat_file *data;
3802 int may_differ;
3803 int complete_rewrite = 0;
3805 if (!DIFF_PAIR_UNMERGED(p)) {
3806 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3807 complete_rewrite = 1;
3810 data = diffstat_add(diffstat, name_a, name_b);
3811 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3812 if (o->flags.stat_with_summary)
3813 data->comments = get_compact_summary(p, data->is_renamed);
3815 if (!one || !two) {
3816 data->is_unmerged = 1;
3817 return;
3820 /* saves some reads if true, not a guarantee of diff outcome */
3821 may_differ = !(one->oid_valid && two->oid_valid &&
3822 oideq(&one->oid, &two->oid));
3824 if (diff_filespec_is_binary(o->repo, one) ||
3825 diff_filespec_is_binary(o->repo, two)) {
3826 data->is_binary = 1;
3827 if (!may_differ) {
3828 data->added = 0;
3829 data->deleted = 0;
3830 } else {
3831 data->added = diff_filespec_size(o->repo, two);
3832 data->deleted = diff_filespec_size(o->repo, one);
3836 else if (complete_rewrite) {
3837 diff_populate_filespec(o->repo, one, NULL);
3838 diff_populate_filespec(o->repo, two, NULL);
3839 data->deleted = count_lines(one->data, one->size);
3840 data->added = count_lines(two->data, two->size);
3843 else if (may_differ) {
3844 /* Crazy xdl interfaces.. */
3845 xpparam_t xpp;
3846 xdemitconf_t xecfg;
3848 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3849 fill_mmfile(o->repo, &mf2, two) < 0)
3850 die("unable to read files to diff");
3852 memset(&xpp, 0, sizeof(xpp));
3853 memset(&xecfg, 0, sizeof(xecfg));
3854 xpp.flags = o->xdl_opts;
3855 xpp.ignore_regex = o->ignore_regex;
3856 xpp.ignore_regex_nr = o->ignore_regex_nr;
3857 xpp.anchors = o->anchors;
3858 xpp.anchors_nr = o->anchors_nr;
3859 xecfg.ctxlen = o->context;
3860 xecfg.interhunkctxlen = o->interhunkcontext;
3861 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3862 if (xdi_diff_outf(&mf1, &mf2, NULL,
3863 diffstat_consume, diffstat, &xpp, &xecfg))
3864 die("unable to generate diffstat for %s", one->path);
3866 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3867 struct diffstat_file *file =
3868 diffstat->files[diffstat->nr - 1];
3870 * Omit diffstats of modified files where nothing changed.
3871 * Even if may_differ, this might be the case due to
3872 * ignoring whitespace changes, etc.
3874 * But note that we special-case additions, deletions,
3875 * renames, and mode changes as adding an empty file,
3876 * for example is still of interest.
3878 if ((p->status == DIFF_STATUS_MODIFIED)
3879 && !file->added
3880 && !file->deleted
3881 && one->mode == two->mode) {
3882 free_diffstat_file(file);
3883 diffstat->nr--;
3888 diff_free_filespec_data(one);
3889 diff_free_filespec_data(two);
3892 static void builtin_checkdiff(const char *name_a, const char *name_b,
3893 const char *attr_path,
3894 struct diff_filespec *one,
3895 struct diff_filespec *two,
3896 struct diff_options *o)
3898 mmfile_t mf1, mf2;
3899 struct checkdiff_t data;
3901 if (!two)
3902 return;
3904 memset(&data, 0, sizeof(data));
3905 data.filename = name_b ? name_b : name_a;
3906 data.lineno = 0;
3907 data.o = o;
3908 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3909 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3911 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3912 fill_mmfile(o->repo, &mf2, two) < 0)
3913 die("unable to read files to diff");
3916 * All the other codepaths check both sides, but not checking
3917 * the "old" side here is deliberate. We are checking the newly
3918 * introduced changes, and as long as the "new" side is text, we
3919 * can and should check what it introduces.
3921 if (diff_filespec_is_binary(o->repo, two))
3922 goto free_and_return;
3923 else {
3924 /* Crazy xdl interfaces.. */
3925 xpparam_t xpp;
3926 xdemitconf_t xecfg;
3928 memset(&xpp, 0, sizeof(xpp));
3929 memset(&xecfg, 0, sizeof(xecfg));
3930 xecfg.ctxlen = 1; /* at least one context line */
3931 xpp.flags = 0;
3932 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3933 checkdiff_consume, &data,
3934 &xpp, &xecfg))
3935 die("unable to generate checkdiff for %s", one->path);
3937 if (data.ws_rule & WS_BLANK_AT_EOF) {
3938 struct emit_callback ecbdata;
3939 int blank_at_eof;
3941 ecbdata.ws_rule = data.ws_rule;
3942 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3943 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3945 if (blank_at_eof) {
3946 static char *err;
3947 if (!err)
3948 err = whitespace_error_string(WS_BLANK_AT_EOF);
3949 fprintf(o->file, "%s:%d: %s.\n",
3950 data.filename, blank_at_eof, err);
3951 data.status = 1; /* report errors */
3955 free_and_return:
3956 diff_free_filespec_data(one);
3957 diff_free_filespec_data(two);
3958 if (data.status)
3959 o->flags.check_failed = 1;
3962 struct diff_filespec *alloc_filespec(const char *path)
3964 struct diff_filespec *spec;
3966 FLEXPTR_ALLOC_STR(spec, path, path);
3967 spec->count = 1;
3968 spec->is_binary = -1;
3969 return spec;
3972 void free_filespec(struct diff_filespec *spec)
3974 if (!--spec->count) {
3975 diff_free_filespec_data(spec);
3976 free(spec);
3980 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3981 int oid_valid, unsigned short mode)
3983 if (mode) {
3984 spec->mode = canon_mode(mode);
3985 oidcpy(&spec->oid, oid);
3986 spec->oid_valid = oid_valid;
3991 * Given a name and sha1 pair, if the index tells us the file in
3992 * the work tree has that object contents, return true, so that
3993 * prepare_temp_file() does not have to inflate and extract.
3995 static int reuse_worktree_file(struct index_state *istate,
3996 const char *name,
3997 const struct object_id *oid,
3998 int want_file)
4000 const struct cache_entry *ce;
4001 struct stat st;
4002 int pos, len;
4005 * We do not read the cache ourselves here, because the
4006 * benchmark with my previous version that always reads cache
4007 * shows that it makes things worse for diff-tree comparing
4008 * two linux-2.6 kernel trees in an already checked out work
4009 * tree. This is because most diff-tree comparisons deal with
4010 * only a small number of files, while reading the cache is
4011 * expensive for a large project, and its cost outweighs the
4012 * savings we get by not inflating the object to a temporary
4013 * file. Practically, this code only helps when we are used
4014 * by diff-cache --cached, which does read the cache before
4015 * calling us.
4017 if (!istate->cache)
4018 return 0;
4020 /* We want to avoid the working directory if our caller
4021 * doesn't need the data in a normal file, this system
4022 * is rather slow with its stat/open/mmap/close syscalls,
4023 * and the object is contained in a pack file. The pack
4024 * is probably already open and will be faster to obtain
4025 * the data through than the working directory. Loose
4026 * objects however would tend to be slower as they need
4027 * to be individually opened and inflated.
4029 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
4030 return 0;
4033 * Similarly, if we'd have to convert the file contents anyway, that
4034 * makes the optimization not worthwhile.
4036 if (!want_file && would_convert_to_git(istate, name))
4037 return 0;
4040 * If this path does not match our sparse-checkout definition,
4041 * then the file will not be in the working directory.
4043 if (!path_in_sparse_checkout(name, istate))
4044 return 0;
4046 len = strlen(name);
4047 pos = index_name_pos(istate, name, len);
4048 if (pos < 0)
4049 return 0;
4050 ce = istate->cache[pos];
4053 * This is not the sha1 we are looking for, or
4054 * unreusable because it is not a regular file.
4056 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4057 return 0;
4060 * If ce is marked as "assume unchanged", there is no
4061 * guarantee that work tree matches what we are looking for.
4063 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4064 return 0;
4067 * If ce matches the file in the work tree, we can reuse it.
4069 if (ce_uptodate(ce) ||
4070 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4071 return 1;
4073 return 0;
4076 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4078 struct strbuf buf = STRBUF_INIT;
4079 const char *dirty = "";
4081 /* Are we looking at the work tree? */
4082 if (s->dirty_submodule)
4083 dirty = "-dirty";
4085 strbuf_addf(&buf, "Subproject commit %s%s\n",
4086 oid_to_hex(&s->oid), dirty);
4087 s->size = buf.len;
4088 if (size_only) {
4089 s->data = NULL;
4090 strbuf_release(&buf);
4091 } else {
4092 s->data = strbuf_detach(&buf, NULL);
4093 s->should_free = 1;
4095 return 0;
4099 * While doing rename detection and pickaxe operation, we may need to
4100 * grab the data for the blob (or file) for our own in-core comparison.
4101 * diff_filespec has data and size fields for this purpose.
4103 int diff_populate_filespec(struct repository *r,
4104 struct diff_filespec *s,
4105 const struct diff_populate_filespec_options *options)
4107 int size_only = options ? options->check_size_only : 0;
4108 int check_binary = options ? options->check_binary : 0;
4109 int err = 0;
4110 int conv_flags = global_conv_flags_eol;
4112 * demote FAIL to WARN to allow inspecting the situation
4113 * instead of refusing.
4115 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4116 conv_flags = CONV_EOL_RNDTRP_WARN;
4118 if (!DIFF_FILE_VALID(s))
4119 die("internal error: asking to populate invalid file.");
4120 if (S_ISDIR(s->mode))
4121 return -1;
4123 if (s->data)
4124 return 0;
4126 if (size_only && 0 < s->size)
4127 return 0;
4129 if (S_ISGITLINK(s->mode))
4130 return diff_populate_gitlink(s, size_only);
4132 if (!s->oid_valid ||
4133 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4134 struct strbuf buf = STRBUF_INIT;
4135 struct stat st;
4136 int fd;
4138 if (lstat(s->path, &st) < 0) {
4139 err_empty:
4140 err = -1;
4141 empty:
4142 s->data = (char *)"";
4143 s->size = 0;
4144 return err;
4146 s->size = xsize_t(st.st_size);
4147 if (!s->size)
4148 goto empty;
4149 if (S_ISLNK(st.st_mode)) {
4150 struct strbuf sb = STRBUF_INIT;
4152 if (strbuf_readlink(&sb, s->path, s->size))
4153 goto err_empty;
4154 s->size = sb.len;
4155 s->data = strbuf_detach(&sb, NULL);
4156 s->should_free = 1;
4157 return 0;
4161 * Even if the caller would be happy with getting
4162 * only the size, we cannot return early at this
4163 * point if the path requires us to run the content
4164 * conversion.
4166 if (size_only && !would_convert_to_git(r->index, s->path))
4167 return 0;
4170 * Note: this check uses xsize_t(st.st_size) that may
4171 * not be the true size of the blob after it goes
4172 * through convert_to_git(). This may not strictly be
4173 * correct, but the whole point of big_file_threshold
4174 * and is_binary check being that we want to avoid
4175 * opening the file and inspecting the contents, this
4176 * is probably fine.
4178 if (check_binary &&
4179 s->size > big_file_threshold && s->is_binary == -1) {
4180 s->is_binary = 1;
4181 return 0;
4183 fd = open(s->path, O_RDONLY);
4184 if (fd < 0)
4185 goto err_empty;
4186 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4187 close(fd);
4188 s->should_munmap = 1;
4191 * Convert from working tree format to canonical git format
4193 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4194 size_t size = 0;
4195 munmap(s->data, s->size);
4196 s->should_munmap = 0;
4197 s->data = strbuf_detach(&buf, &size);
4198 s->size = size;
4199 s->should_free = 1;
4202 else {
4203 struct object_info info = {
4204 .sizep = &s->size
4207 if (!(size_only || check_binary))
4209 * Set contentp, since there is no chance that merely
4210 * the size is sufficient.
4212 info.contentp = &s->data;
4214 if (options && options->missing_object_cb) {
4215 if (!oid_object_info_extended(r, &s->oid, &info,
4216 OBJECT_INFO_LOOKUP_REPLACE |
4217 OBJECT_INFO_SKIP_FETCH_OBJECT))
4218 goto object_read;
4219 options->missing_object_cb(options->missing_object_data);
4221 if (oid_object_info_extended(r, &s->oid, &info,
4222 OBJECT_INFO_LOOKUP_REPLACE))
4223 die("unable to read %s", oid_to_hex(&s->oid));
4225 object_read:
4226 if (size_only || check_binary) {
4227 if (size_only)
4228 return 0;
4229 if (s->size > big_file_threshold && s->is_binary == -1) {
4230 s->is_binary = 1;
4231 return 0;
4234 if (!info.contentp) {
4235 info.contentp = &s->data;
4236 if (oid_object_info_extended(r, &s->oid, &info,
4237 OBJECT_INFO_LOOKUP_REPLACE))
4238 die("unable to read %s", oid_to_hex(&s->oid));
4240 s->should_free = 1;
4242 return 0;
4245 void diff_free_filespec_blob(struct diff_filespec *s)
4247 if (s->should_free)
4248 free(s->data);
4249 else if (s->should_munmap)
4250 munmap(s->data, s->size);
4252 if (s->should_free || s->should_munmap) {
4253 s->should_free = s->should_munmap = 0;
4254 s->data = NULL;
4258 void diff_free_filespec_data(struct diff_filespec *s)
4260 if (!s)
4261 return;
4263 diff_free_filespec_blob(s);
4264 FREE_AND_NULL(s->cnt_data);
4267 static void prep_temp_blob(struct index_state *istate,
4268 const char *path, struct diff_tempfile *temp,
4269 void *blob,
4270 unsigned long size,
4271 const struct object_id *oid,
4272 int mode)
4274 struct strbuf buf = STRBUF_INIT;
4275 char *path_dup = xstrdup(path);
4276 const char *base = basename(path_dup);
4277 struct checkout_metadata meta;
4279 init_checkout_metadata(&meta, NULL, NULL, oid);
4281 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4282 if (!temp->tempfile)
4283 die_errno("unable to create temp-file");
4284 if (convert_to_working_tree(istate, path,
4285 (const char *)blob, (size_t)size, &buf, &meta)) {
4286 blob = buf.buf;
4287 size = buf.len;
4289 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4290 close_tempfile_gently(temp->tempfile))
4291 die_errno("unable to write temp-file");
4292 temp->name = get_tempfile_path(temp->tempfile);
4293 oid_to_hex_r(temp->hex, oid);
4294 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4295 strbuf_release(&buf);
4296 free(path_dup);
4299 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4300 struct diff_filespec *one)
4302 struct diff_tempfile *temp = claim_diff_tempfile();
4304 if (!DIFF_FILE_VALID(one)) {
4305 not_a_valid_file:
4306 /* A '-' entry produces this for file-2, and
4307 * a '+' entry produces this for file-1.
4309 temp->name = "/dev/null";
4310 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4311 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4312 return temp;
4315 if (!S_ISGITLINK(one->mode) &&
4316 (!one->oid_valid ||
4317 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4318 struct stat st;
4319 if (lstat(one->path, &st) < 0) {
4320 if (errno == ENOENT)
4321 goto not_a_valid_file;
4322 die_errno("stat(%s)", one->path);
4324 if (S_ISLNK(st.st_mode)) {
4325 struct strbuf sb = STRBUF_INIT;
4326 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4327 die_errno("readlink(%s)", one->path);
4328 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4329 (one->oid_valid ?
4330 &one->oid : null_oid()),
4331 (one->oid_valid ?
4332 one->mode : S_IFLNK));
4333 strbuf_release(&sb);
4335 else {
4336 /* we can borrow from the file in the work tree */
4337 temp->name = one->path;
4338 if (!one->oid_valid)
4339 oid_to_hex_r(temp->hex, null_oid());
4340 else
4341 oid_to_hex_r(temp->hex, &one->oid);
4342 /* Even though we may sometimes borrow the
4343 * contents from the work tree, we always want
4344 * one->mode. mode is trustworthy even when
4345 * !(one->oid_valid), as long as
4346 * DIFF_FILE_VALID(one).
4348 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4350 return temp;
4352 else {
4353 if (diff_populate_filespec(r, one, NULL))
4354 die("cannot read data blob for %s", one->path);
4355 prep_temp_blob(r->index, one->path, temp,
4356 one->data, one->size,
4357 &one->oid, one->mode);
4359 return temp;
4362 static void add_external_diff_name(struct repository *r,
4363 struct strvec *argv,
4364 struct diff_filespec *df)
4366 struct diff_tempfile *temp = prepare_temp_file(r, df);
4367 strvec_push(argv, temp->name);
4368 strvec_push(argv, temp->hex);
4369 strvec_push(argv, temp->mode);
4372 /* An external diff command takes:
4374 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4375 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4378 static void run_external_diff(const char *pgm,
4379 const char *name,
4380 const char *other,
4381 struct diff_filespec *one,
4382 struct diff_filespec *two,
4383 const char *xfrm_msg,
4384 struct diff_options *o)
4386 struct child_process cmd = CHILD_PROCESS_INIT;
4387 struct diff_queue_struct *q = &diff_queued_diff;
4389 strvec_push(&cmd.args, pgm);
4390 strvec_push(&cmd.args, name);
4392 if (one && two) {
4393 add_external_diff_name(o->repo, &cmd.args, one);
4394 add_external_diff_name(o->repo, &cmd.args, two);
4395 if (other) {
4396 strvec_push(&cmd.args, other);
4397 if (xfrm_msg)
4398 strvec_push(&cmd.args, xfrm_msg);
4402 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4403 ++o->diff_path_counter);
4404 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4406 diff_free_filespec_data(one);
4407 diff_free_filespec_data(two);
4408 cmd.use_shell = 1;
4409 if (run_command(&cmd))
4410 die(_("external diff died, stopping at %s"), name);
4412 remove_tempfile();
4415 static int similarity_index(struct diff_filepair *p)
4417 return p->score * 100 / MAX_SCORE;
4420 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4422 if (startup_info->have_repository)
4423 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4424 else {
4425 char *hex = oid_to_hex(oid);
4426 if (abbrev < 0)
4427 abbrev = FALLBACK_DEFAULT_ABBREV;
4428 if (abbrev > the_hash_algo->hexsz)
4429 BUG("oid abbreviation out of range: %d", abbrev);
4430 if (abbrev)
4431 hex[abbrev] = '\0';
4432 return hex;
4436 static void fill_metainfo(struct strbuf *msg,
4437 const char *name,
4438 const char *other,
4439 struct diff_filespec *one,
4440 struct diff_filespec *two,
4441 struct diff_options *o,
4442 struct diff_filepair *p,
4443 int *must_show_header,
4444 int use_color)
4446 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4447 const char *reset = diff_get_color(use_color, DIFF_RESET);
4448 const char *line_prefix = diff_line_prefix(o);
4449 struct string_list *more_headers = NULL;
4451 *must_show_header = 1;
4452 strbuf_init(msg, PATH_MAX * 2 + 300);
4453 switch (p->status) {
4454 case DIFF_STATUS_COPIED:
4455 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4456 line_prefix, set, similarity_index(p));
4457 strbuf_addf(msg, "%s\n%s%scopy from ",
4458 reset, line_prefix, set);
4459 quote_c_style(name, msg, NULL, 0);
4460 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4461 quote_c_style(other, msg, NULL, 0);
4462 strbuf_addf(msg, "%s\n", reset);
4463 break;
4464 case DIFF_STATUS_RENAMED:
4465 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4466 line_prefix, set, similarity_index(p));
4467 strbuf_addf(msg, "%s\n%s%srename from ",
4468 reset, line_prefix, set);
4469 quote_c_style(name, msg, NULL, 0);
4470 strbuf_addf(msg, "%s\n%s%srename to ",
4471 reset, line_prefix, set);
4472 quote_c_style(other, msg, NULL, 0);
4473 strbuf_addf(msg, "%s\n", reset);
4474 break;
4475 case DIFF_STATUS_MODIFIED:
4476 if (p->score) {
4477 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4478 line_prefix,
4479 set, similarity_index(p), reset);
4480 break;
4482 /* fallthru */
4483 default:
4484 *must_show_header = 0;
4486 if ((more_headers = additional_headers(o, name))) {
4487 add_formatted_headers(msg, more_headers,
4488 line_prefix, set, reset);
4489 *must_show_header = 1;
4491 if (one && two && !oideq(&one->oid, &two->oid)) {
4492 const unsigned hexsz = the_hash_algo->hexsz;
4493 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4495 if (o->flags.full_index)
4496 abbrev = hexsz;
4498 if (o->flags.binary) {
4499 mmfile_t mf;
4500 if ((!fill_mmfile(o->repo, &mf, one) &&
4501 diff_filespec_is_binary(o->repo, one)) ||
4502 (!fill_mmfile(o->repo, &mf, two) &&
4503 diff_filespec_is_binary(o->repo, two)))
4504 abbrev = hexsz;
4506 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4507 diff_abbrev_oid(&one->oid, abbrev),
4508 diff_abbrev_oid(&two->oid, abbrev));
4509 if (one->mode == two->mode)
4510 strbuf_addf(msg, " %06o", one->mode);
4511 strbuf_addf(msg, "%s\n", reset);
4515 static void run_diff_cmd(const char *pgm,
4516 const char *name,
4517 const char *other,
4518 const char *attr_path,
4519 struct diff_filespec *one,
4520 struct diff_filespec *two,
4521 struct strbuf *msg,
4522 struct diff_options *o,
4523 struct diff_filepair *p)
4525 const char *xfrm_msg = NULL;
4526 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4527 int must_show_header = 0;
4528 struct userdiff_driver *drv = NULL;
4530 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4531 drv = userdiff_find_by_path(o->repo->index, attr_path);
4533 if (o->flags.allow_external && drv && drv->external)
4534 pgm = drv->external;
4536 if (msg) {
4538 * don't use colors when the header is intended for an
4539 * external diff driver
4541 fill_metainfo(msg, name, other, one, two, o, p,
4542 &must_show_header,
4543 want_color(o->use_color) && !pgm);
4544 xfrm_msg = msg->len ? msg->buf : NULL;
4547 if (pgm) {
4548 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4549 return;
4551 if (one && two) {
4552 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4553 set_diff_algorithm(o, drv->algorithm);
4555 builtin_diff(name, other ? other : name,
4556 one, two, xfrm_msg, must_show_header,
4557 o, complete_rewrite);
4558 } else {
4559 fprintf(o->file, "* Unmerged path %s\n", name);
4560 o->found_changes = 1;
4564 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4566 if (DIFF_FILE_VALID(one)) {
4567 if (!one->oid_valid) {
4568 struct stat st;
4569 if (one->is_stdin) {
4570 oidclr(&one->oid);
4571 return;
4573 if (lstat(one->path, &st) < 0)
4574 die_errno("stat '%s'", one->path);
4575 if (index_path(istate, &one->oid, one->path, &st, 0))
4576 die("cannot hash %s", one->path);
4579 else
4580 oidclr(&one->oid);
4583 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4585 /* Strip the prefix but do not molest /dev/null and absolute paths */
4586 if (*namep && !is_absolute_path(*namep)) {
4587 *namep += prefix_length;
4588 if (**namep == '/')
4589 ++*namep;
4591 if (*otherp && !is_absolute_path(*otherp)) {
4592 *otherp += prefix_length;
4593 if (**otherp == '/')
4594 ++*otherp;
4598 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4600 const char *pgm = external_diff();
4601 struct strbuf msg;
4602 struct diff_filespec *one = p->one;
4603 struct diff_filespec *two = p->two;
4604 const char *name;
4605 const char *other;
4606 const char *attr_path;
4608 name = one->path;
4609 other = (strcmp(name, two->path) ? two->path : NULL);
4610 attr_path = name;
4611 if (o->prefix_length)
4612 strip_prefix(o->prefix_length, &name, &other);
4614 if (!o->flags.allow_external)
4615 pgm = NULL;
4617 if (DIFF_PAIR_UNMERGED(p)) {
4618 run_diff_cmd(pgm, name, NULL, attr_path,
4619 NULL, NULL, NULL, o, p);
4620 return;
4623 diff_fill_oid_info(one, o->repo->index);
4624 diff_fill_oid_info(two, o->repo->index);
4626 if (!pgm &&
4627 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4628 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4630 * a filepair that changes between file and symlink
4631 * needs to be split into deletion and creation.
4633 struct diff_filespec *null = alloc_filespec(two->path);
4634 run_diff_cmd(NULL, name, other, attr_path,
4635 one, null, &msg,
4636 o, p);
4637 free(null);
4638 strbuf_release(&msg);
4640 null = alloc_filespec(one->path);
4641 run_diff_cmd(NULL, name, other, attr_path,
4642 null, two, &msg, o, p);
4643 free(null);
4645 else
4646 run_diff_cmd(pgm, name, other, attr_path,
4647 one, two, &msg, o, p);
4649 strbuf_release(&msg);
4652 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4653 struct diffstat_t *diffstat)
4655 const char *name;
4656 const char *other;
4658 if (!o->ignore_driver_algorithm) {
4659 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4660 p->one->path);
4662 if (drv && drv->algorithm)
4663 set_diff_algorithm(o, drv->algorithm);
4666 if (DIFF_PAIR_UNMERGED(p)) {
4667 /* unmerged */
4668 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4669 diffstat, o, p);
4670 return;
4673 name = p->one->path;
4674 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4676 if (o->prefix_length)
4677 strip_prefix(o->prefix_length, &name, &other);
4679 diff_fill_oid_info(p->one, o->repo->index);
4680 diff_fill_oid_info(p->two, o->repo->index);
4682 builtin_diffstat(name, other, p->one, p->two,
4683 diffstat, o, p);
4686 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4688 const char *name;
4689 const char *other;
4690 const char *attr_path;
4692 if (DIFF_PAIR_UNMERGED(p)) {
4693 /* unmerged */
4694 return;
4697 name = p->one->path;
4698 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4699 attr_path = other ? other : name;
4701 if (o->prefix_length)
4702 strip_prefix(o->prefix_length, &name, &other);
4704 diff_fill_oid_info(p->one, o->repo->index);
4705 diff_fill_oid_info(p->two, o->repo->index);
4707 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4710 void repo_diff_setup(struct repository *r, struct diff_options *options)
4712 memcpy(options, &default_diff_options, sizeof(*options));
4714 options->file = stdout;
4715 options->repo = r;
4717 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4718 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4719 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4720 options->abbrev = DEFAULT_ABBREV;
4721 options->line_termination = '\n';
4722 options->break_opt = -1;
4723 options->rename_limit = -1;
4724 options->dirstat_permille = diff_dirstat_permille_default;
4725 options->context = diff_context_default;
4726 options->interhunkcontext = diff_interhunk_context_default;
4727 options->ws_error_highlight = ws_error_highlight_default;
4728 options->flags.rename_empty = 1;
4729 options->flags.relative_name = diff_relative;
4730 options->objfind = NULL;
4732 /* pathchange left =NULL by default */
4733 options->change = diff_change;
4734 options->add_remove = diff_addremove;
4735 options->use_color = diff_use_color_default;
4736 options->detect_rename = diff_detect_rename_default;
4737 options->xdl_opts |= diff_algorithm;
4738 if (diff_indent_heuristic)
4739 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4741 options->orderfile = diff_order_file_cfg;
4743 if (!options->flags.ignore_submodule_set)
4744 options->flags.ignore_untracked_in_submodules = 1;
4746 if (diff_no_prefix) {
4747 diff_set_noprefix(options);
4748 } else if (!diff_mnemonic_prefix) {
4749 diff_set_default_prefix(options);
4752 options->color_moved = diff_color_moved_default;
4753 options->color_moved_ws_handling = diff_color_moved_ws_default;
4756 static const char diff_status_letters[] = {
4757 DIFF_STATUS_ADDED,
4758 DIFF_STATUS_COPIED,
4759 DIFF_STATUS_DELETED,
4760 DIFF_STATUS_MODIFIED,
4761 DIFF_STATUS_RENAMED,
4762 DIFF_STATUS_TYPE_CHANGED,
4763 DIFF_STATUS_UNKNOWN,
4764 DIFF_STATUS_UNMERGED,
4765 DIFF_STATUS_FILTER_AON,
4766 DIFF_STATUS_FILTER_BROKEN,
4767 '\0',
4770 static unsigned int filter_bit['Z' + 1];
4772 static void prepare_filter_bits(void)
4774 int i;
4776 if (!filter_bit[DIFF_STATUS_ADDED]) {
4777 for (i = 0; diff_status_letters[i]; i++)
4778 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4782 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4784 return opt->filter & filter_bit[(int) status];
4787 unsigned diff_filter_bit(char status)
4789 prepare_filter_bits();
4790 return filter_bit[(int) status];
4793 int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
4795 unsigned forbidden_magic;
4797 if (ps->nr != 1) {
4798 if (die_on_error)
4799 die(_("--follow requires exactly one pathspec"));
4800 return 0;
4803 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
4804 PATHSPEC_LITERAL);
4805 if (forbidden_magic) {
4806 if (die_on_error) {
4807 struct strbuf sb = STRBUF_INIT;
4808 pathspec_magic_names(forbidden_magic, &sb);
4809 die(_("pathspec magic not supported by --follow: %s"),
4810 sb.buf);
4812 return 0;
4815 return 1;
4818 void diff_setup_done(struct diff_options *options)
4820 unsigned check_mask = DIFF_FORMAT_NAME |
4821 DIFF_FORMAT_NAME_STATUS |
4822 DIFF_FORMAT_CHECKDIFF |
4823 DIFF_FORMAT_NO_OUTPUT;
4825 * This must be signed because we're comparing against a potentially
4826 * negative value.
4828 const int hexsz = the_hash_algo->hexsz;
4830 if (options->set_default)
4831 options->set_default(options);
4833 if (HAS_MULTI_BITS(options->output_format & check_mask))
4834 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4835 "--name-only", "--name-status", "--check", "-s");
4837 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4838 die(_("options '%s', '%s', and '%s' cannot be used together"),
4839 "-G", "-S", "--find-object");
4841 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4842 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4843 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4845 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4846 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4847 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4850 * Most of the time we can say "there are changes"
4851 * only by checking if there are changed paths, but
4852 * --ignore-whitespace* options force us to look
4853 * inside contents.
4856 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4857 options->ignore_regex_nr)
4858 options->flags.diff_from_contents = 1;
4859 else
4860 options->flags.diff_from_contents = 0;
4862 if (options->flags.find_copies_harder)
4863 options->detect_rename = DIFF_DETECT_COPY;
4865 if (!options->flags.relative_name)
4866 options->prefix = NULL;
4867 if (options->prefix)
4868 options->prefix_length = strlen(options->prefix);
4869 else
4870 options->prefix_length = 0;
4873 * --name-only, --name-status, --checkdiff, and -s
4874 * turn other output format off.
4876 if (options->output_format & (DIFF_FORMAT_NAME |
4877 DIFF_FORMAT_NAME_STATUS |
4878 DIFF_FORMAT_CHECKDIFF |
4879 DIFF_FORMAT_NO_OUTPUT))
4880 options->output_format &= ~(DIFF_FORMAT_RAW |
4881 DIFF_FORMAT_NUMSTAT |
4882 DIFF_FORMAT_DIFFSTAT |
4883 DIFF_FORMAT_SHORTSTAT |
4884 DIFF_FORMAT_DIRSTAT |
4885 DIFF_FORMAT_SUMMARY |
4886 DIFF_FORMAT_PATCH);
4889 * These cases always need recursive; we do not drop caller-supplied
4890 * recursive bits for other formats here.
4892 if (options->output_format & (DIFF_FORMAT_PATCH |
4893 DIFF_FORMAT_NUMSTAT |
4894 DIFF_FORMAT_DIFFSTAT |
4895 DIFF_FORMAT_SHORTSTAT |
4896 DIFF_FORMAT_DIRSTAT |
4897 DIFF_FORMAT_SUMMARY |
4898 DIFF_FORMAT_CHECKDIFF))
4899 options->flags.recursive = 1;
4901 * Also pickaxe would not work very well if you do not say recursive
4903 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4904 options->flags.recursive = 1;
4906 * When patches are generated, submodules diffed against the work tree
4907 * must be checked for dirtiness too so it can be shown in the output
4909 if (options->output_format & DIFF_FORMAT_PATCH)
4910 options->flags.dirty_submodules = 1;
4912 if (options->detect_rename && options->rename_limit < 0)
4913 options->rename_limit = diff_rename_limit_default;
4914 if (hexsz < options->abbrev)
4915 options->abbrev = hexsz; /* full */
4918 * It does not make sense to show the first hit we happened
4919 * to have found. It does not make sense not to return with
4920 * exit code in such a case either.
4922 if (options->flags.quick) {
4923 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4924 options->flags.exit_with_status = 1;
4927 options->diff_path_counter = 0;
4929 if (options->flags.follow_renames)
4930 diff_check_follow_pathspec(&options->pathspec, 1);
4932 if (!options->use_color || external_diff())
4933 options->color_moved = 0;
4935 if (options->filter_not) {
4936 if (!options->filter)
4937 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4938 options->filter &= ~options->filter_not;
4942 int parse_long_opt(const char *opt, const char **argv,
4943 const char **optarg)
4945 const char *arg = argv[0];
4946 if (!skip_prefix(arg, "--", &arg))
4947 return 0;
4948 if (!skip_prefix(arg, opt, &arg))
4949 return 0;
4950 if (*arg == '=') { /* stuck form: --option=value */
4951 *optarg = arg + 1;
4952 return 1;
4954 if (*arg != '\0')
4955 return 0;
4956 /* separate form: --option value */
4957 if (!argv[1])
4958 die("Option '--%s' requires a value", opt);
4959 *optarg = argv[1];
4960 return 2;
4963 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4965 struct diff_options *options = opt->value;
4966 int width = options->stat_width;
4967 int name_width = options->stat_name_width;
4968 int graph_width = options->stat_graph_width;
4969 int count = options->stat_count;
4970 char *end;
4972 BUG_ON_OPT_NEG(unset);
4974 if (!strcmp(opt->long_name, "stat")) {
4975 if (value) {
4976 width = strtoul(value, &end, 10);
4977 if (*end == ',')
4978 name_width = strtoul(end+1, &end, 10);
4979 if (*end == ',')
4980 count = strtoul(end+1, &end, 10);
4981 if (*end)
4982 return error(_("invalid --stat value: %s"), value);
4984 } else if (!strcmp(opt->long_name, "stat-width")) {
4985 width = strtoul(value, &end, 10);
4986 if (*end)
4987 return error(_("%s expects a numerical value"),
4988 opt->long_name);
4989 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4990 name_width = strtoul(value, &end, 10);
4991 if (*end)
4992 return error(_("%s expects a numerical value"),
4993 opt->long_name);
4994 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4995 graph_width = strtoul(value, &end, 10);
4996 if (*end)
4997 return error(_("%s expects a numerical value"),
4998 opt->long_name);
4999 } else if (!strcmp(opt->long_name, "stat-count")) {
5000 count = strtoul(value, &end, 10);
5001 if (*end)
5002 return error(_("%s expects a numerical value"),
5003 opt->long_name);
5004 } else
5005 BUG("%s should not get here", opt->long_name);
5007 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5008 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5009 options->stat_name_width = name_width;
5010 options->stat_graph_width = graph_width;
5011 options->stat_width = width;
5012 options->stat_count = count;
5013 return 0;
5016 static int parse_dirstat_opt(struct diff_options *options, const char *params)
5018 struct strbuf errmsg = STRBUF_INIT;
5019 if (parse_dirstat_params(options, params, &errmsg))
5020 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
5021 errmsg.buf);
5022 strbuf_release(&errmsg);
5024 * The caller knows a dirstat-related option is given from the command
5025 * line; allow it to say "return this_function();"
5027 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5028 options->output_format |= DIFF_FORMAT_DIRSTAT;
5029 return 1;
5032 static int diff_opt_diff_filter(const struct option *option,
5033 const char *optarg, int unset)
5035 struct diff_options *opt = option->value;
5036 int i, optch;
5038 BUG_ON_OPT_NEG(unset);
5039 prepare_filter_bits();
5041 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5042 unsigned int bit;
5043 int negate;
5045 if ('a' <= optch && optch <= 'z') {
5046 negate = 1;
5047 optch = toupper(optch);
5048 } else {
5049 negate = 0;
5052 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5053 if (!bit)
5054 return error(_("unknown change class '%c' in --diff-filter=%s"),
5055 optarg[i], optarg);
5056 if (negate)
5057 opt->filter_not |= bit;
5058 else
5059 opt->filter |= bit;
5061 return 0;
5064 static void enable_patch_output(int *fmt)
5066 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5067 *fmt |= DIFF_FORMAT_PATCH;
5070 static int diff_opt_ws_error_highlight(const struct option *option,
5071 const char *arg, int unset)
5073 struct diff_options *opt = option->value;
5074 int val = parse_ws_error_highlight(arg);
5076 BUG_ON_OPT_NEG(unset);
5077 if (val < 0)
5078 return error(_("unknown value after ws-error-highlight=%.*s"),
5079 -1 - val, arg);
5080 opt->ws_error_highlight = val;
5081 return 0;
5084 static int diff_opt_find_object(const struct option *option,
5085 const char *arg, int unset)
5087 struct diff_options *opt = option->value;
5088 struct object_id oid;
5090 BUG_ON_OPT_NEG(unset);
5091 if (repo_get_oid(the_repository, arg, &oid))
5092 return error(_("unable to resolve '%s'"), arg);
5094 if (!opt->objfind)
5095 CALLOC_ARRAY(opt->objfind, 1);
5097 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5098 opt->flags.recursive = 1;
5099 opt->flags.tree_in_recursive = 1;
5100 oidset_insert(opt->objfind, &oid);
5101 return 0;
5104 static int diff_opt_anchored(const struct option *opt,
5105 const char *arg, int unset)
5107 struct diff_options *options = opt->value;
5109 BUG_ON_OPT_NEG(unset);
5110 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5111 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5112 options->anchors_alloc);
5113 options->anchors[options->anchors_nr++] = xstrdup(arg);
5114 return 0;
5117 static int diff_opt_binary(const struct option *opt,
5118 const char *arg, int unset)
5120 struct diff_options *options = opt->value;
5122 BUG_ON_OPT_NEG(unset);
5123 BUG_ON_OPT_ARG(arg);
5124 enable_patch_output(&options->output_format);
5125 options->flags.binary = 1;
5126 return 0;
5129 static int diff_opt_break_rewrites(const struct option *opt,
5130 const char *arg, int unset)
5132 int *break_opt = opt->value;
5133 int opt1, opt2;
5135 BUG_ON_OPT_NEG(unset);
5136 if (!arg)
5137 arg = "";
5138 opt1 = parse_rename_score(&arg);
5139 if (*arg == 0)
5140 opt2 = 0;
5141 else if (*arg != '/')
5142 return error(_("%s expects <n>/<m> form"), opt->long_name);
5143 else {
5144 arg++;
5145 opt2 = parse_rename_score(&arg);
5147 if (*arg != 0)
5148 return error(_("%s expects <n>/<m> form"), opt->long_name);
5149 *break_opt = opt1 | (opt2 << 16);
5150 return 0;
5153 static int diff_opt_char(const struct option *opt,
5154 const char *arg, int unset)
5156 char *value = opt->value;
5158 BUG_ON_OPT_NEG(unset);
5159 if (arg[1])
5160 return error(_("%s expects a character, got '%s'"),
5161 opt->long_name, arg);
5162 *value = arg[0];
5163 return 0;
5166 static int diff_opt_color_moved(const struct option *opt,
5167 const char *arg, int unset)
5169 struct diff_options *options = opt->value;
5171 if (unset) {
5172 options->color_moved = COLOR_MOVED_NO;
5173 } else if (!arg) {
5174 if (diff_color_moved_default)
5175 options->color_moved = diff_color_moved_default;
5176 if (options->color_moved == COLOR_MOVED_NO)
5177 options->color_moved = COLOR_MOVED_DEFAULT;
5178 } else {
5179 int cm = parse_color_moved(arg);
5180 if (cm < 0)
5181 return error(_("bad --color-moved argument: %s"), arg);
5182 options->color_moved = cm;
5184 return 0;
5187 static int diff_opt_color_moved_ws(const struct option *opt,
5188 const char *arg, int unset)
5190 struct diff_options *options = opt->value;
5191 unsigned cm;
5193 if (unset) {
5194 options->color_moved_ws_handling = 0;
5195 return 0;
5198 cm = parse_color_moved_ws(arg);
5199 if (cm & COLOR_MOVED_WS_ERROR)
5200 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5201 options->color_moved_ws_handling = cm;
5202 return 0;
5205 static int diff_opt_color_words(const struct option *opt,
5206 const char *arg, int unset)
5208 struct diff_options *options = opt->value;
5210 BUG_ON_OPT_NEG(unset);
5211 options->use_color = 1;
5212 options->word_diff = DIFF_WORDS_COLOR;
5213 options->word_regex = arg;
5214 return 0;
5217 static int diff_opt_compact_summary(const struct option *opt,
5218 const char *arg, int unset)
5220 struct diff_options *options = opt->value;
5222 BUG_ON_OPT_ARG(arg);
5223 if (unset) {
5224 options->flags.stat_with_summary = 0;
5225 } else {
5226 options->flags.stat_with_summary = 1;
5227 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5228 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5230 return 0;
5233 static int diff_opt_diff_algorithm(const struct option *opt,
5234 const char *arg, int unset)
5236 struct diff_options *options = opt->value;
5238 BUG_ON_OPT_NEG(unset);
5240 if (set_diff_algorithm(options, arg))
5241 return error(_("option diff-algorithm accepts \"myers\", "
5242 "\"minimal\", \"patience\" and \"histogram\""));
5244 options->ignore_driver_algorithm = 1;
5246 return 0;
5249 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5250 const char *arg, int unset)
5252 struct diff_options *options = opt->value;
5254 BUG_ON_OPT_NEG(unset);
5255 BUG_ON_OPT_ARG(arg);
5257 if (set_diff_algorithm(options, opt->long_name))
5258 BUG("available diff algorithms include \"myers\", "
5259 "\"minimal\", \"patience\" and \"histogram\"");
5261 options->ignore_driver_algorithm = 1;
5263 return 0;
5266 static int diff_opt_dirstat(const struct option *opt,
5267 const char *arg, int unset)
5269 struct diff_options *options = opt->value;
5271 BUG_ON_OPT_NEG(unset);
5272 if (!strcmp(opt->long_name, "cumulative")) {
5273 if (arg)
5274 BUG("how come --cumulative take a value?");
5275 arg = "cumulative";
5276 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5277 parse_dirstat_opt(options, "files");
5278 parse_dirstat_opt(options, arg ? arg : "");
5279 return 0;
5282 static int diff_opt_find_copies(const struct option *opt,
5283 const char *arg, int unset)
5285 struct diff_options *options = opt->value;
5287 BUG_ON_OPT_NEG(unset);
5288 if (!arg)
5289 arg = "";
5290 options->rename_score = parse_rename_score(&arg);
5291 if (*arg != 0)
5292 return error(_("invalid argument to %s"), opt->long_name);
5294 if (options->detect_rename == DIFF_DETECT_COPY)
5295 options->flags.find_copies_harder = 1;
5296 else
5297 options->detect_rename = DIFF_DETECT_COPY;
5299 return 0;
5302 static int diff_opt_find_renames(const struct option *opt,
5303 const char *arg, int unset)
5305 struct diff_options *options = opt->value;
5307 BUG_ON_OPT_NEG(unset);
5308 if (!arg)
5309 arg = "";
5310 options->rename_score = parse_rename_score(&arg);
5311 if (*arg != 0)
5312 return error(_("invalid argument to %s"), opt->long_name);
5314 options->detect_rename = DIFF_DETECT_RENAME;
5315 return 0;
5318 static int diff_opt_follow(const struct option *opt,
5319 const char *arg, int unset)
5321 struct diff_options *options = opt->value;
5323 BUG_ON_OPT_ARG(arg);
5324 if (unset) {
5325 options->flags.follow_renames = 0;
5326 options->flags.default_follow_renames = 0;
5327 } else {
5328 options->flags.follow_renames = 1;
5330 return 0;
5333 static int diff_opt_ignore_submodules(const struct option *opt,
5334 const char *arg, int unset)
5336 struct diff_options *options = opt->value;
5338 BUG_ON_OPT_NEG(unset);
5339 if (!arg)
5340 arg = "all";
5341 options->flags.override_submodule_config = 1;
5342 handle_ignore_submodules_arg(options, arg);
5343 return 0;
5346 static int diff_opt_line_prefix(const struct option *opt,
5347 const char *optarg, int unset)
5349 struct diff_options *options = opt->value;
5351 BUG_ON_OPT_NEG(unset);
5352 options->line_prefix = optarg;
5353 options->line_prefix_length = strlen(options->line_prefix);
5354 graph_setup_line_prefix(options);
5355 return 0;
5358 static int diff_opt_no_prefix(const struct option *opt,
5359 const char *optarg, int unset)
5361 struct diff_options *options = opt->value;
5363 BUG_ON_OPT_NEG(unset);
5364 BUG_ON_OPT_ARG(optarg);
5365 diff_set_noprefix(options);
5366 return 0;
5369 static int diff_opt_default_prefix(const struct option *opt,
5370 const char *optarg, int unset)
5372 struct diff_options *options = opt->value;
5374 BUG_ON_OPT_NEG(unset);
5375 BUG_ON_OPT_ARG(optarg);
5376 FREE_AND_NULL(diff_src_prefix);
5377 FREE_AND_NULL(diff_dst_prefix);
5378 diff_set_default_prefix(options);
5379 return 0;
5382 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5383 const struct option *opt,
5384 const char *arg, int unset)
5386 struct diff_options *options = opt->value;
5387 char *path;
5389 BUG_ON_OPT_NEG(unset);
5390 path = prefix_filename(ctx->prefix, arg);
5391 options->file = xfopen(path, "w");
5392 options->close_file = 1;
5393 if (options->use_color != GIT_COLOR_ALWAYS)
5394 options->use_color = GIT_COLOR_NEVER;
5395 free(path);
5396 return 0;
5399 static int diff_opt_patience(const struct option *opt,
5400 const char *arg, int unset)
5402 struct diff_options *options = opt->value;
5403 int i;
5405 BUG_ON_OPT_NEG(unset);
5406 BUG_ON_OPT_ARG(arg);
5408 * Both --patience and --anchored use PATIENCE_DIFF
5409 * internally, so remove any anchors previously
5410 * specified.
5412 for (i = 0; i < options->anchors_nr; i++)
5413 free(options->anchors[i]);
5414 options->anchors_nr = 0;
5415 options->ignore_driver_algorithm = 1;
5417 return set_diff_algorithm(options, "patience");
5420 static int diff_opt_ignore_regex(const struct option *opt,
5421 const char *arg, int unset)
5423 struct diff_options *options = opt->value;
5424 regex_t *regex;
5426 BUG_ON_OPT_NEG(unset);
5427 regex = xmalloc(sizeof(*regex));
5428 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5429 return error(_("invalid regex given to -I: '%s'"), arg);
5430 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5431 options->ignore_regex_alloc);
5432 options->ignore_regex[options->ignore_regex_nr++] = regex;
5433 return 0;
5436 static int diff_opt_pickaxe_regex(const struct option *opt,
5437 const char *arg, int unset)
5439 struct diff_options *options = opt->value;
5441 BUG_ON_OPT_NEG(unset);
5442 options->pickaxe = arg;
5443 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5444 return 0;
5447 static int diff_opt_pickaxe_string(const struct option *opt,
5448 const char *arg, int unset)
5450 struct diff_options *options = opt->value;
5452 BUG_ON_OPT_NEG(unset);
5453 options->pickaxe = arg;
5454 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5455 return 0;
5458 static int diff_opt_relative(const struct option *opt,
5459 const char *arg, int unset)
5461 struct diff_options *options = opt->value;
5463 options->flags.relative_name = !unset;
5464 if (arg)
5465 options->prefix = arg;
5466 return 0;
5469 static int diff_opt_submodule(const struct option *opt,
5470 const char *arg, int unset)
5472 struct diff_options *options = opt->value;
5474 BUG_ON_OPT_NEG(unset);
5475 if (!arg)
5476 arg = "log";
5477 if (parse_submodule_params(options, arg))
5478 return error(_("failed to parse --submodule option parameter: '%s'"),
5479 arg);
5480 return 0;
5483 static int diff_opt_textconv(const struct option *opt,
5484 const char *arg, int unset)
5486 struct diff_options *options = opt->value;
5488 BUG_ON_OPT_ARG(arg);
5489 if (unset) {
5490 options->flags.allow_textconv = 0;
5491 } else {
5492 options->flags.allow_textconv = 1;
5493 options->flags.textconv_set_via_cmdline = 1;
5495 return 0;
5498 static int diff_opt_unified(const struct option *opt,
5499 const char *arg, int unset)
5501 struct diff_options *options = opt->value;
5502 char *s;
5504 BUG_ON_OPT_NEG(unset);
5506 if (arg) {
5507 options->context = strtol(arg, &s, 10);
5508 if (*s)
5509 return error(_("%s expects a numerical value"), "--unified");
5511 enable_patch_output(&options->output_format);
5513 return 0;
5516 static int diff_opt_word_diff(const struct option *opt,
5517 const char *arg, int unset)
5519 struct diff_options *options = opt->value;
5521 BUG_ON_OPT_NEG(unset);
5522 if (arg) {
5523 if (!strcmp(arg, "plain"))
5524 options->word_diff = DIFF_WORDS_PLAIN;
5525 else if (!strcmp(arg, "color")) {
5526 options->use_color = 1;
5527 options->word_diff = DIFF_WORDS_COLOR;
5529 else if (!strcmp(arg, "porcelain"))
5530 options->word_diff = DIFF_WORDS_PORCELAIN;
5531 else if (!strcmp(arg, "none"))
5532 options->word_diff = DIFF_WORDS_NONE;
5533 else
5534 return error(_("bad --word-diff argument: %s"), arg);
5535 } else {
5536 if (options->word_diff == DIFF_WORDS_NONE)
5537 options->word_diff = DIFF_WORDS_PLAIN;
5539 return 0;
5542 static int diff_opt_word_diff_regex(const struct option *opt,
5543 const char *arg, int unset)
5545 struct diff_options *options = opt->value;
5547 BUG_ON_OPT_NEG(unset);
5548 if (options->word_diff == DIFF_WORDS_NONE)
5549 options->word_diff = DIFF_WORDS_PLAIN;
5550 options->word_regex = arg;
5551 return 0;
5554 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5556 struct diff_options *options = opt->value;
5558 BUG_ON_OPT_NEG(unset);
5559 if (!strcmp(opt->long_name, "skip-to"))
5560 options->skip_instead_of_rotate = 1;
5561 else
5562 options->skip_instead_of_rotate = 0;
5563 options->rotate_to = arg;
5564 return 0;
5568 * Consider adding new flags to __git_diff_common_options
5569 * in contrib/completion/git-completion.bash
5571 struct option *add_diff_options(const struct option *opts,
5572 struct diff_options *options)
5574 struct option parseopts[] = {
5575 OPT_GROUP(N_("Diff output format options")),
5576 OPT_BITOP('p', "patch", &options->output_format,
5577 N_("generate patch"),
5578 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5579 OPT_SET_INT('s', "no-patch", &options->output_format,
5580 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
5581 OPT_BITOP('u', NULL, &options->output_format,
5582 N_("generate patch"),
5583 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5584 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5585 N_("generate diffs with <n> lines context"),
5586 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5587 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5588 N_("generate diffs with <n> lines context")),
5589 OPT_BITOP(0, "raw", &options->output_format,
5590 N_("generate the diff in raw format"),
5591 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
5592 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5593 N_("synonym for '-p --raw'"),
5594 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5595 DIFF_FORMAT_NO_OUTPUT),
5596 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5597 N_("synonym for '-p --stat'"),
5598 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5599 DIFF_FORMAT_NO_OUTPUT),
5600 OPT_BITOP(0, "numstat", &options->output_format,
5601 N_("machine friendly --stat"),
5602 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5603 OPT_BITOP(0, "shortstat", &options->output_format,
5604 N_("output only the last line of --stat"),
5605 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
5606 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1>,<param2>..."),
5607 N_("output the distribution of relative amount of changes for each sub-directory"),
5608 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5609 diff_opt_dirstat),
5610 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5611 N_("synonym for --dirstat=cumulative"),
5612 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5613 diff_opt_dirstat),
5614 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1>,<param2>..."),
5615 N_("synonym for --dirstat=files,<param1>,<param2>..."),
5616 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5617 diff_opt_dirstat),
5618 OPT_BIT_F(0, "check", &options->output_format,
5619 N_("warn if changes introduce conflict markers or whitespace errors"),
5620 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5621 OPT_BITOP(0, "summary", &options->output_format,
5622 N_("condensed summary such as creations, renames and mode changes"),
5623 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
5624 OPT_BIT_F(0, "name-only", &options->output_format,
5625 N_("show only names of changed files"),
5626 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5627 OPT_BIT_F(0, "name-status", &options->output_format,
5628 N_("show only names and status of changed files"),
5629 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5630 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5631 N_("generate diffstat"),
5632 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5633 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5634 N_("generate diffstat with a given width"),
5635 PARSE_OPT_NONEG, diff_opt_stat),
5636 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5637 N_("generate diffstat with a given name width"),
5638 PARSE_OPT_NONEG, diff_opt_stat),
5639 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5640 N_("generate diffstat with a given graph width"),
5641 PARSE_OPT_NONEG, diff_opt_stat),
5642 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5643 N_("generate diffstat with limited lines"),
5644 PARSE_OPT_NONEG, diff_opt_stat),
5645 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5646 N_("generate compact summary in diffstat"),
5647 PARSE_OPT_NOARG, diff_opt_compact_summary),
5648 OPT_CALLBACK_F(0, "binary", options, NULL,
5649 N_("output a binary diff that can be applied"),
5650 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5651 OPT_BOOL(0, "full-index", &options->flags.full_index,
5652 N_("show full pre- and post-image object names on the \"index\" lines")),
5653 OPT_COLOR_FLAG(0, "color", &options->use_color,
5654 N_("show colored diff")),
5655 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5656 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5657 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5658 OPT_SET_INT('z', NULL, &options->line_termination,
5659 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5661 OPT__ABBREV(&options->abbrev),
5662 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5663 N_("show the given source prefix instead of \"a/\""),
5664 PARSE_OPT_NONEG),
5665 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5666 N_("show the given destination prefix instead of \"b/\""),
5667 PARSE_OPT_NONEG),
5668 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5669 N_("prepend an additional prefix to every line of output"),
5670 PARSE_OPT_NONEG, diff_opt_line_prefix),
5671 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5672 N_("do not show any source or destination prefix"),
5673 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5674 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5675 N_("use default prefixes a/ and b/"),
5676 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5677 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5678 N_("show context between diff hunks up to the specified number of lines"),
5679 PARSE_OPT_NONEG),
5680 OPT_CALLBACK_F(0, "output-indicator-new",
5681 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5682 N_("<char>"),
5683 N_("specify the character to indicate a new line instead of '+'"),
5684 PARSE_OPT_NONEG, diff_opt_char),
5685 OPT_CALLBACK_F(0, "output-indicator-old",
5686 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5687 N_("<char>"),
5688 N_("specify the character to indicate an old line instead of '-'"),
5689 PARSE_OPT_NONEG, diff_opt_char),
5690 OPT_CALLBACK_F(0, "output-indicator-context",
5691 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5692 N_("<char>"),
5693 N_("specify the character to indicate a context instead of ' '"),
5694 PARSE_OPT_NONEG, diff_opt_char),
5696 OPT_GROUP(N_("Diff rename options")),
5697 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5698 N_("break complete rewrite changes into pairs of delete and create"),
5699 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5700 diff_opt_break_rewrites),
5701 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5702 N_("detect renames"),
5703 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5704 diff_opt_find_renames),
5705 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5706 N_("omit the preimage for deletes"),
5707 1, PARSE_OPT_NONEG),
5708 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5709 N_("detect copies"),
5710 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5711 diff_opt_find_copies),
5712 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5713 N_("use unmodified files as source to find copies")),
5714 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5715 N_("disable rename detection"),
5716 0, PARSE_OPT_NONEG),
5717 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5718 N_("use empty blobs as rename source")),
5719 OPT_CALLBACK_F(0, "follow", options, NULL,
5720 N_("continue listing the history of a file beyond renames"),
5721 PARSE_OPT_NOARG, diff_opt_follow),
5722 OPT_INTEGER('l', NULL, &options->rename_limit,
5723 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5725 OPT_GROUP(N_("Diff algorithm options")),
5726 OPT_CALLBACK_F(0, "minimal", options, NULL,
5727 N_("produce the smallest possible diff"),
5728 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5729 diff_opt_diff_algorithm_no_arg),
5730 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5731 N_("ignore whitespace when comparing lines"),
5732 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5733 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5734 N_("ignore changes in amount of whitespace"),
5735 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5736 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5737 N_("ignore changes in whitespace at EOL"),
5738 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5739 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5740 N_("ignore carrier-return at the end of line"),
5741 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5742 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5743 N_("ignore changes whose lines are all blank"),
5744 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5745 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5746 N_("ignore changes whose all lines match <regex>"),
5747 0, diff_opt_ignore_regex),
5748 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5749 N_("heuristic to shift diff hunk boundaries for easy reading"),
5750 XDF_INDENT_HEURISTIC),
5751 OPT_CALLBACK_F(0, "patience", options, NULL,
5752 N_("generate diff using the \"patience diff\" algorithm"),
5753 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5754 diff_opt_patience),
5755 OPT_CALLBACK_F(0, "histogram", options, NULL,
5756 N_("generate diff using the \"histogram diff\" algorithm"),
5757 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5758 diff_opt_diff_algorithm_no_arg),
5759 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5760 N_("choose a diff algorithm"),
5761 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5762 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5763 N_("generate diff using the \"anchored diff\" algorithm"),
5764 PARSE_OPT_NONEG, diff_opt_anchored),
5765 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5766 N_("show word diff, using <mode> to delimit changed words"),
5767 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5768 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5769 N_("use <regex> to decide what a word is"),
5770 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5771 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5772 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5773 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5774 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5775 N_("moved lines of code are colored differently"),
5776 PARSE_OPT_OPTARG, diff_opt_color_moved),
5777 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5778 N_("how white spaces are ignored in --color-moved"),
5779 0, diff_opt_color_moved_ws),
5781 OPT_GROUP(N_("Other diff options")),
5782 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5783 N_("when run from subdir, exclude changes outside and show relative paths"),
5784 PARSE_OPT_OPTARG,
5785 diff_opt_relative),
5786 OPT_BOOL('a', "text", &options->flags.text,
5787 N_("treat all files as text")),
5788 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5789 N_("swap two inputs, reverse the diff")),
5790 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5791 N_("exit with 1 if there were differences, 0 otherwise")),
5792 OPT_BOOL(0, "quiet", &options->flags.quick,
5793 N_("disable all output of the program")),
5794 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5795 N_("allow an external diff helper to be executed")),
5796 OPT_CALLBACK_F(0, "textconv", options, NULL,
5797 N_("run external text conversion filters when comparing binary files"),
5798 PARSE_OPT_NOARG, diff_opt_textconv),
5799 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5800 N_("ignore changes to submodules in the diff generation"),
5801 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5802 diff_opt_ignore_submodules),
5803 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5804 N_("specify how differences in submodules are shown"),
5805 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5806 diff_opt_submodule),
5807 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5808 N_("hide 'git add -N' entries from the index"),
5809 1, PARSE_OPT_NONEG),
5810 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5811 N_("treat 'git add -N' entries as real in the index"),
5812 0, PARSE_OPT_NONEG),
5813 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5814 N_("look for differences that change the number of occurrences of the specified string"),
5815 0, diff_opt_pickaxe_string),
5816 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5817 N_("look for differences that change the number of occurrences of the specified regex"),
5818 0, diff_opt_pickaxe_regex),
5819 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5820 N_("show all changes in the changeset with -S or -G"),
5821 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5822 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5823 N_("treat <string> in -S as extended POSIX regular expression"),
5824 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5825 OPT_FILENAME('O', NULL, &options->orderfile,
5826 N_("control the order in which files appear in the output")),
5827 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5828 N_("show the change in the specified path first"),
5829 PARSE_OPT_NONEG, diff_opt_rotate_to),
5830 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5831 N_("skip the output to the specified path"),
5832 PARSE_OPT_NONEG, diff_opt_rotate_to),
5833 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5834 N_("look for differences that change the number of occurrences of the specified object"),
5835 PARSE_OPT_NONEG, diff_opt_find_object),
5836 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5837 N_("select files by diff type"),
5838 PARSE_OPT_NONEG, diff_opt_diff_filter),
5839 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5840 N_("output to a specific file"),
5841 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5843 OPT_END()
5846 return parse_options_concat(opts, parseopts);
5849 int diff_opt_parse(struct diff_options *options,
5850 const char **av, int ac, const char *prefix)
5852 struct option no_options[] = { OPT_END() };
5853 struct option *parseopts = add_diff_options(no_options, options);
5855 if (!prefix)
5856 prefix = "";
5858 ac = parse_options(ac, av, prefix, parseopts, NULL,
5859 PARSE_OPT_KEEP_DASHDASH |
5860 PARSE_OPT_KEEP_UNKNOWN_OPT |
5861 PARSE_OPT_NO_INTERNAL_HELP |
5862 PARSE_OPT_ONE_SHOT |
5863 PARSE_OPT_STOP_AT_NON_OPTION);
5864 free(parseopts);
5866 return ac;
5869 int parse_rename_score(const char **cp_p)
5871 unsigned long num, scale;
5872 int ch, dot;
5873 const char *cp = *cp_p;
5875 num = 0;
5876 scale = 1;
5877 dot = 0;
5878 for (;;) {
5879 ch = *cp;
5880 if ( !dot && ch == '.' ) {
5881 scale = 1;
5882 dot = 1;
5883 } else if ( ch == '%' ) {
5884 scale = dot ? scale*100 : 100;
5885 cp++; /* % is always at the end */
5886 break;
5887 } else if ( ch >= '0' && ch <= '9' ) {
5888 if ( scale < 100000 ) {
5889 scale *= 10;
5890 num = (num*10) + (ch-'0');
5892 } else {
5893 break;
5895 cp++;
5897 *cp_p = cp;
5899 /* user says num divided by scale and we say internally that
5900 * is MAX_SCORE * num / scale.
5902 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5905 struct diff_queue_struct diff_queued_diff;
5907 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5909 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5910 queue->queue[queue->nr++] = dp;
5913 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5914 struct diff_filespec *one,
5915 struct diff_filespec *two)
5917 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5918 dp->one = one;
5919 dp->two = two;
5920 if (queue)
5921 diff_q(queue, dp);
5922 return dp;
5925 void diff_free_filepair(struct diff_filepair *p)
5927 free_filespec(p->one);
5928 free_filespec(p->two);
5929 free(p);
5932 void diff_free_queue(struct diff_queue_struct *q)
5934 for (int i = 0; i < q->nr; i++)
5935 diff_free_filepair(q->queue[i]);
5936 free(q->queue);
5939 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5941 int abblen;
5942 const char *abbrev;
5944 /* Do we want all 40 hex characters? */
5945 if (len == the_hash_algo->hexsz)
5946 return oid_to_hex(oid);
5948 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5949 abbrev = diff_abbrev_oid(oid, len);
5951 if (!print_sha1_ellipsis())
5952 return abbrev;
5954 abblen = strlen(abbrev);
5957 * In well-behaved cases, where the abbreviated result is the
5958 * same as the requested length, append three dots after the
5959 * abbreviation (hence the whole logic is limited to the case
5960 * where abblen < 37); when the actual abbreviated result is a
5961 * bit longer than the requested length, we reduce the number
5962 * of dots so that they match the well-behaved ones. However,
5963 * if the actual abbreviation is longer than the requested
5964 * length by more than three, we give up on aligning, and add
5965 * three dots anyway, to indicate that the output is not the
5966 * full object name. Yes, this may be suboptimal, but this
5967 * appears only in "diff --raw --abbrev" output and it is not
5968 * worth the effort to change it now. Note that this would
5969 * likely to work fine when the automatic sizing of default
5970 * abbreviation length is used--we would be fed -1 in "len" in
5971 * that case, and will end up always appending three-dots, but
5972 * the automatic sizing is supposed to give abblen that ensures
5973 * uniqueness across all objects (statistically speaking).
5975 if (abblen < the_hash_algo->hexsz - 3) {
5976 static char hex[GIT_MAX_HEXSZ + 1];
5977 if (len < abblen && abblen <= len + 2)
5978 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5979 else
5980 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5981 return hex;
5984 return oid_to_hex(oid);
5987 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5989 int line_termination = opt->line_termination;
5990 int inter_name_termination = line_termination ? '\t' : '\0';
5992 fprintf(opt->file, "%s", diff_line_prefix(opt));
5993 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5994 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5995 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5996 fprintf(opt->file, "%s ",
5997 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5999 if (p->score) {
6000 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
6001 inter_name_termination);
6002 } else {
6003 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6006 if (p->status == DIFF_STATUS_COPIED ||
6007 p->status == DIFF_STATUS_RENAMED) {
6008 const char *name_a, *name_b;
6009 name_a = p->one->path;
6010 name_b = p->two->path;
6011 strip_prefix(opt->prefix_length, &name_a, &name_b);
6012 write_name_quoted(name_a, opt->file, inter_name_termination);
6013 write_name_quoted(name_b, opt->file, line_termination);
6014 } else {
6015 const char *name_a, *name_b;
6016 name_a = p->one->mode ? p->one->path : p->two->path;
6017 name_b = NULL;
6018 strip_prefix(opt->prefix_length, &name_a, &name_b);
6019 write_name_quoted(name_a, opt->file, line_termination);
6023 int diff_unmodified_pair(struct diff_filepair *p)
6025 /* This function is written stricter than necessary to support
6026 * the currently implemented transformers, but the idea is to
6027 * let transformers to produce diff_filepairs any way they want,
6028 * and filter and clean them up here before producing the output.
6030 struct diff_filespec *one = p->one, *two = p->two;
6032 if (DIFF_PAIR_UNMERGED(p))
6033 return 0; /* unmerged is interesting */
6035 /* deletion, addition, mode or type change
6036 * and rename are all interesting.
6038 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
6039 DIFF_PAIR_MODE_CHANGED(p) ||
6040 strcmp(one->path, two->path))
6041 return 0;
6043 /* both are valid and point at the same path. that is, we are
6044 * dealing with a change.
6046 if (one->oid_valid && two->oid_valid &&
6047 oideq(&one->oid, &two->oid) &&
6048 !one->dirty_submodule && !two->dirty_submodule)
6049 return 1; /* no change */
6050 if (!one->oid_valid && !two->oid_valid)
6051 return 1; /* both look at the same file on the filesystem. */
6052 return 0;
6055 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6057 int include_conflict_headers =
6058 (additional_headers(o, p->one->path) &&
6059 !o->pickaxe_opts &&
6060 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6063 * Check if we can return early without showing a diff. Note that
6064 * diff_filepair only stores {oid, path, mode, is_valid}
6065 * information for each path, and thus diff_unmodified_pair() only
6066 * considers those bits of info. However, we do not want pairs
6067 * created by create_filepairs_for_header_only_notifications()
6068 * (which always look like unmodified pairs) to be ignored, so
6069 * return early if both p is unmodified AND we don't want to
6070 * include_conflict_headers.
6072 if (diff_unmodified_pair(p) && !include_conflict_headers)
6073 return;
6075 /* Actually, we can also return early to avoid showing tree diffs */
6076 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6077 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6078 return;
6080 run_diff(p, o);
6083 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6084 struct diffstat_t *diffstat)
6086 if (diff_unmodified_pair(p))
6087 return;
6089 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6090 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6091 return; /* no useful stat for tree diffs */
6093 run_diffstat(p, o, diffstat);
6096 static void diff_flush_checkdiff(struct diff_filepair *p,
6097 struct diff_options *o)
6099 if (diff_unmodified_pair(p))
6100 return;
6102 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6103 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6104 return; /* nothing to check in tree diffs */
6106 run_checkdiff(p, o);
6109 int diff_queue_is_empty(struct diff_options *o)
6111 struct diff_queue_struct *q = &diff_queued_diff;
6112 int i;
6113 int include_conflict_headers =
6114 (o->additional_path_headers &&
6115 strmap_get_size(o->additional_path_headers) &&
6116 !o->pickaxe_opts &&
6117 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6119 if (include_conflict_headers)
6120 return 0;
6122 for (i = 0; i < q->nr; i++)
6123 if (!diff_unmodified_pair(q->queue[i]))
6124 return 0;
6125 return 1;
6128 #if DIFF_DEBUG
6129 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6131 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6132 x, one ? one : "",
6133 s->path,
6134 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6135 s->mode,
6136 s->oid_valid ? oid_to_hex(&s->oid) : "");
6137 fprintf(stderr, "queue[%d] %s size %lu\n",
6138 x, one ? one : "",
6139 s->size);
6142 void diff_debug_filepair(const struct diff_filepair *p, int i)
6144 diff_debug_filespec(p->one, i, "one");
6145 diff_debug_filespec(p->two, i, "two");
6146 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6147 p->score, p->status ? p->status : '?',
6148 p->one->rename_used, p->broken_pair);
6151 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6153 int i;
6154 if (msg)
6155 fprintf(stderr, "%s\n", msg);
6156 fprintf(stderr, "q->nr = %d\n", q->nr);
6157 for (i = 0; i < q->nr; i++) {
6158 struct diff_filepair *p = q->queue[i];
6159 diff_debug_filepair(p, i);
6162 #endif
6164 static void diff_resolve_rename_copy(void)
6166 int i;
6167 struct diff_filepair *p;
6168 struct diff_queue_struct *q = &diff_queued_diff;
6170 diff_debug_queue("resolve-rename-copy", q);
6172 for (i = 0; i < q->nr; i++) {
6173 p = q->queue[i];
6174 p->status = 0; /* undecided */
6175 if (DIFF_PAIR_UNMERGED(p))
6176 p->status = DIFF_STATUS_UNMERGED;
6177 else if (!DIFF_FILE_VALID(p->one))
6178 p->status = DIFF_STATUS_ADDED;
6179 else if (!DIFF_FILE_VALID(p->two))
6180 p->status = DIFF_STATUS_DELETED;
6181 else if (DIFF_PAIR_TYPE_CHANGED(p))
6182 p->status = DIFF_STATUS_TYPE_CHANGED;
6184 /* from this point on, we are dealing with a pair
6185 * whose both sides are valid and of the same type, i.e.
6186 * either in-place edit or rename/copy edit.
6188 else if (DIFF_PAIR_RENAME(p)) {
6190 * A rename might have re-connected a broken
6191 * pair up, causing the pathnames to be the
6192 * same again. If so, that's not a rename at
6193 * all, just a modification..
6195 * Otherwise, see if this source was used for
6196 * multiple renames, in which case we decrement
6197 * the count, and call it a copy.
6199 if (!strcmp(p->one->path, p->two->path))
6200 p->status = DIFF_STATUS_MODIFIED;
6201 else if (--p->one->rename_used > 0)
6202 p->status = DIFF_STATUS_COPIED;
6203 else
6204 p->status = DIFF_STATUS_RENAMED;
6206 else if (!oideq(&p->one->oid, &p->two->oid) ||
6207 p->one->mode != p->two->mode ||
6208 p->one->dirty_submodule ||
6209 p->two->dirty_submodule ||
6210 is_null_oid(&p->one->oid))
6211 p->status = DIFF_STATUS_MODIFIED;
6212 else {
6213 /* This is a "no-change" entry and should not
6214 * happen anymore, but prepare for broken callers.
6216 error("feeding unmodified %s to diffcore",
6217 p->one->path);
6218 p->status = DIFF_STATUS_UNKNOWN;
6221 diff_debug_queue("resolve-rename-copy done", q);
6224 static int check_pair_status(struct diff_filepair *p)
6226 switch (p->status) {
6227 case DIFF_STATUS_UNKNOWN:
6228 return 0;
6229 case 0:
6230 die("internal error in diff-resolve-rename-copy");
6231 default:
6232 return 1;
6236 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6238 int fmt = opt->output_format;
6240 if (fmt & DIFF_FORMAT_CHECKDIFF)
6241 diff_flush_checkdiff(p, opt);
6242 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6243 diff_flush_raw(p, opt);
6244 else if (fmt & DIFF_FORMAT_NAME) {
6245 const char *name_a, *name_b;
6246 name_a = p->two->path;
6247 name_b = NULL;
6248 strip_prefix(opt->prefix_length, &name_a, &name_b);
6249 fprintf(opt->file, "%s", diff_line_prefix(opt));
6250 write_name_quoted(name_a, opt->file, opt->line_termination);
6253 opt->found_changes = 1;
6256 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6258 struct strbuf sb = STRBUF_INIT;
6259 if (fs->mode)
6260 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6261 else
6262 strbuf_addf(&sb, " %s ", newdelete);
6264 quote_c_style(fs->path, &sb, NULL, 0);
6265 strbuf_addch(&sb, '\n');
6266 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6267 sb.buf, sb.len, 0);
6268 strbuf_release(&sb);
6271 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6272 int show_name)
6274 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6275 struct strbuf sb = STRBUF_INIT;
6276 strbuf_addf(&sb, " mode change %06o => %06o",
6277 p->one->mode, p->two->mode);
6278 if (show_name) {
6279 strbuf_addch(&sb, ' ');
6280 quote_c_style(p->two->path, &sb, NULL, 0);
6282 strbuf_addch(&sb, '\n');
6283 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6284 sb.buf, sb.len, 0);
6285 strbuf_release(&sb);
6289 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6290 struct diff_filepair *p)
6292 struct strbuf sb = STRBUF_INIT;
6293 struct strbuf names = STRBUF_INIT;
6295 pprint_rename(&names, p->one->path, p->two->path);
6296 strbuf_addf(&sb, " %s %s (%d%%)\n",
6297 renamecopy, names.buf, similarity_index(p));
6298 strbuf_release(&names);
6299 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6300 sb.buf, sb.len, 0);
6301 show_mode_change(opt, p, 0);
6302 strbuf_release(&sb);
6305 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6307 switch(p->status) {
6308 case DIFF_STATUS_DELETED:
6309 show_file_mode_name(opt, "delete", p->one);
6310 break;
6311 case DIFF_STATUS_ADDED:
6312 show_file_mode_name(opt, "create", p->two);
6313 break;
6314 case DIFF_STATUS_COPIED:
6315 show_rename_copy(opt, "copy", p);
6316 break;
6317 case DIFF_STATUS_RENAMED:
6318 show_rename_copy(opt, "rename", p);
6319 break;
6320 default:
6321 if (p->score) {
6322 struct strbuf sb = STRBUF_INIT;
6323 strbuf_addstr(&sb, " rewrite ");
6324 quote_c_style(p->two->path, &sb, NULL, 0);
6325 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6326 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6327 sb.buf, sb.len, 0);
6328 strbuf_release(&sb);
6330 show_mode_change(opt, p, !p->score);
6331 break;
6335 struct patch_id_t {
6336 git_hash_ctx *ctx;
6337 int patchlen;
6340 static int remove_space(char *line, int len)
6342 int i;
6343 char *dst = line;
6344 unsigned char c;
6346 for (i = 0; i < len; i++)
6347 if (!isspace((c = line[i])))
6348 *dst++ = c;
6350 return dst - line;
6353 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6355 unsigned char hash[GIT_MAX_RAWSZ];
6356 unsigned short carry = 0;
6357 int i;
6359 the_hash_algo->final_fn(hash, ctx);
6360 the_hash_algo->init_fn(ctx);
6361 /* 20-byte sum, with carry */
6362 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6363 carry += result->hash[i] + hash[i];
6364 result->hash[i] = carry;
6365 carry >>= 8;
6369 static int patch_id_consume(void *priv, char *line, unsigned long len)
6371 struct patch_id_t *data = priv;
6372 int new_len;
6374 if (len > 12 && starts_with(line, "\\ "))
6375 return 0;
6376 new_len = remove_space(line, len);
6378 the_hash_algo->update_fn(data->ctx, line, new_len);
6379 data->patchlen += new_len;
6380 return 0;
6383 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6385 the_hash_algo->update_fn(ctx, str, strlen(str));
6388 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6390 /* large enough for 2^32 in octal */
6391 char buf[12];
6392 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6393 the_hash_algo->update_fn(ctx, buf, len);
6396 /* returns 0 upon success, and writes result into oid */
6397 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6399 struct diff_queue_struct *q = &diff_queued_diff;
6400 int i;
6401 git_hash_ctx ctx;
6402 struct patch_id_t data;
6404 the_hash_algo->init_fn(&ctx);
6405 memset(&data, 0, sizeof(struct patch_id_t));
6406 data.ctx = &ctx;
6407 oidclr(oid);
6409 for (i = 0; i < q->nr; i++) {
6410 xpparam_t xpp;
6411 xdemitconf_t xecfg;
6412 mmfile_t mf1, mf2;
6413 struct diff_filepair *p = q->queue[i];
6414 int len1, len2;
6416 memset(&xpp, 0, sizeof(xpp));
6417 memset(&xecfg, 0, sizeof(xecfg));
6418 if (p->status == 0)
6419 return error("internal diff status error");
6420 if (p->status == DIFF_STATUS_UNKNOWN)
6421 continue;
6422 if (diff_unmodified_pair(p))
6423 continue;
6424 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6425 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6426 continue;
6427 if (DIFF_PAIR_UNMERGED(p))
6428 continue;
6430 diff_fill_oid_info(p->one, options->repo->index);
6431 diff_fill_oid_info(p->two, options->repo->index);
6433 len1 = remove_space(p->one->path, strlen(p->one->path));
6434 len2 = remove_space(p->two->path, strlen(p->two->path));
6435 patch_id_add_string(&ctx, "diff--git");
6436 patch_id_add_string(&ctx, "a/");
6437 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6438 patch_id_add_string(&ctx, "b/");
6439 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6441 if (p->one->mode == 0) {
6442 patch_id_add_string(&ctx, "newfilemode");
6443 patch_id_add_mode(&ctx, p->two->mode);
6444 } else if (p->two->mode == 0) {
6445 patch_id_add_string(&ctx, "deletedfilemode");
6446 patch_id_add_mode(&ctx, p->one->mode);
6447 } else if (p->one->mode != p->two->mode) {
6448 patch_id_add_string(&ctx, "oldmode");
6449 patch_id_add_mode(&ctx, p->one->mode);
6450 patch_id_add_string(&ctx, "newmode");
6451 patch_id_add_mode(&ctx, p->two->mode);
6454 if (diff_header_only) {
6455 /* don't do anything since we're only populating header info */
6456 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6457 diff_filespec_is_binary(options->repo, p->two)) {
6458 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6459 the_hash_algo->hexsz);
6460 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6461 the_hash_algo->hexsz);
6462 } else {
6463 if (p->one->mode == 0) {
6464 patch_id_add_string(&ctx, "---/dev/null");
6465 patch_id_add_string(&ctx, "+++b/");
6466 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6467 } else if (p->two->mode == 0) {
6468 patch_id_add_string(&ctx, "---a/");
6469 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6470 patch_id_add_string(&ctx, "+++/dev/null");
6471 } else {
6472 patch_id_add_string(&ctx, "---a/");
6473 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6474 patch_id_add_string(&ctx, "+++b/");
6475 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6478 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6479 fill_mmfile(options->repo, &mf2, p->two) < 0)
6480 return error("unable to read files to diff");
6481 xpp.flags = 0;
6482 xecfg.ctxlen = 3;
6483 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6484 if (xdi_diff_outf(&mf1, &mf2, NULL,
6485 patch_id_consume, &data, &xpp, &xecfg))
6486 return error("unable to generate patch-id diff for %s",
6487 p->one->path);
6489 flush_one_hunk(oid, &ctx);
6492 return 0;
6495 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6497 struct diff_queue_struct *q = &diff_queued_diff;
6498 int result = diff_get_patch_id(options, oid, diff_header_only);
6500 diff_free_queue(q);
6501 DIFF_QUEUE_CLEAR(q);
6503 return result;
6506 static int is_summary_empty(const struct diff_queue_struct *q)
6508 int i;
6510 for (i = 0; i < q->nr; i++) {
6511 const struct diff_filepair *p = q->queue[i];
6513 switch (p->status) {
6514 case DIFF_STATUS_DELETED:
6515 case DIFF_STATUS_ADDED:
6516 case DIFF_STATUS_COPIED:
6517 case DIFF_STATUS_RENAMED:
6518 return 0;
6519 default:
6520 if (p->score)
6521 return 0;
6522 if (p->one->mode && p->two->mode &&
6523 p->one->mode != p->two->mode)
6524 return 0;
6525 break;
6528 return 1;
6531 static const char rename_limit_warning[] =
6532 N_("exhaustive rename detection was skipped due to too many files.");
6534 static const char degrade_cc_to_c_warning[] =
6535 N_("only found copies from modified paths due to too many files.");
6537 static const char rename_limit_advice[] =
6538 N_("you may want to set your %s variable to at least "
6539 "%d and retry the command.");
6541 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6543 fflush(stdout);
6544 if (degraded_cc)
6545 warning(_(degrade_cc_to_c_warning));
6546 else if (needed)
6547 warning(_(rename_limit_warning));
6548 else
6549 return;
6550 if (0 < needed)
6551 warning(_(rename_limit_advice), varname, needed);
6554 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6556 struct strset present;
6557 struct diff_queue_struct *q = &diff_queued_diff;
6558 struct hashmap_iter iter;
6559 struct strmap_entry *e;
6560 int i;
6562 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6565 * Find out which paths exist in diff_queued_diff, preferring
6566 * one->path for any pair that has multiple paths.
6568 for (i = 0; i < q->nr; i++) {
6569 struct diff_filepair *p = q->queue[i];
6570 char *path = p->one->path ? p->one->path : p->two->path;
6572 if (strmap_contains(o->additional_path_headers, path))
6573 strset_add(&present, path);
6577 * Loop over paths in additional_path_headers; for each NOT already
6578 * in diff_queued_diff, create a synthetic filepair and insert that
6579 * into diff_queued_diff.
6581 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6582 if (!strset_contains(&present, e->key)) {
6583 struct diff_filespec *one, *two;
6584 struct diff_filepair *p;
6586 one = alloc_filespec(e->key);
6587 two = alloc_filespec(e->key);
6588 fill_filespec(one, null_oid(), 0, 0);
6589 fill_filespec(two, null_oid(), 0, 0);
6590 p = diff_queue(q, one, two);
6591 p->status = DIFF_STATUS_MODIFIED;
6595 /* Re-sort the filepairs */
6596 diffcore_fix_diff_index();
6598 /* Cleanup */
6599 strset_clear(&present);
6602 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6604 int i;
6605 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6606 struct diff_queue_struct *q = &diff_queued_diff;
6608 if (WSEH_NEW & WS_RULE_MASK)
6609 BUG("WS rules bit mask overlaps with diff symbol flags");
6611 if (o->color_moved)
6612 o->emitted_symbols = &esm;
6614 if (o->additional_path_headers)
6615 create_filepairs_for_header_only_notifications(o);
6617 for (i = 0; i < q->nr; i++) {
6618 struct diff_filepair *p = q->queue[i];
6619 if (check_pair_status(p))
6620 diff_flush_patch(p, o);
6623 if (o->emitted_symbols) {
6624 if (o->color_moved) {
6625 struct mem_pool entry_pool;
6626 struct moved_entry_list *entry_list;
6628 mem_pool_init(&entry_pool, 1024 * 1024);
6629 entry_list = add_lines_to_move_detection(o,
6630 &entry_pool);
6631 mark_color_as_moved(o, entry_list);
6632 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6633 dim_moved_lines(o);
6635 mem_pool_discard(&entry_pool, 0);
6636 free(entry_list);
6639 for (i = 0; i < esm.nr; i++)
6640 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6642 for (i = 0; i < esm.nr; i++)
6643 free((void *)esm.buf[i].line);
6644 esm.nr = 0;
6646 o->emitted_symbols = NULL;
6650 static void diff_free_file(struct diff_options *options)
6652 if (options->close_file)
6653 fclose(options->file);
6656 static void diff_free_ignore_regex(struct diff_options *options)
6658 int i;
6660 for (i = 0; i < options->ignore_regex_nr; i++) {
6661 regfree(options->ignore_regex[i]);
6662 free(options->ignore_regex[i]);
6664 free(options->ignore_regex);
6667 void diff_free(struct diff_options *options)
6669 if (options->no_free)
6670 return;
6672 diff_free_file(options);
6673 diff_free_ignore_regex(options);
6674 clear_pathspec(&options->pathspec);
6677 void diff_flush(struct diff_options *options)
6679 struct diff_queue_struct *q = &diff_queued_diff;
6680 int i, output_format = options->output_format;
6681 int separator = 0;
6682 int dirstat_by_line = 0;
6685 * Order: raw, stat, summary, patch
6686 * or: name/name-status/checkdiff (other bits clear)
6688 if (!q->nr && !options->additional_path_headers)
6689 goto free_queue;
6691 if (output_format & (DIFF_FORMAT_RAW |
6692 DIFF_FORMAT_NAME |
6693 DIFF_FORMAT_NAME_STATUS |
6694 DIFF_FORMAT_CHECKDIFF)) {
6695 for (i = 0; i < q->nr; i++) {
6696 struct diff_filepair *p = q->queue[i];
6697 if (check_pair_status(p))
6698 flush_one_pair(p, options);
6700 separator++;
6703 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6704 dirstat_by_line = 1;
6706 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6707 dirstat_by_line) {
6708 struct diffstat_t diffstat;
6710 compute_diffstat(options, &diffstat, q);
6711 if (output_format & DIFF_FORMAT_NUMSTAT)
6712 show_numstat(&diffstat, options);
6713 if (output_format & DIFF_FORMAT_DIFFSTAT)
6714 show_stats(&diffstat, options);
6715 if (output_format & DIFF_FORMAT_SHORTSTAT)
6716 show_shortstats(&diffstat, options);
6717 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6718 show_dirstat_by_line(&diffstat, options);
6719 free_diffstat_info(&diffstat);
6720 separator++;
6722 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6723 show_dirstat(options);
6725 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6726 for (i = 0; i < q->nr; i++) {
6727 diff_summary(options, q->queue[i]);
6729 separator++;
6732 if (output_format & DIFF_FORMAT_PATCH) {
6733 if (separator) {
6734 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6735 if (options->stat_sep)
6736 /* attach patch instead of inline */
6737 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6738 NULL, 0, 0);
6741 diff_flush_patch_all_file_pairs(options);
6744 if (output_format & DIFF_FORMAT_CALLBACK)
6745 options->format_callback(q, options, options->format_callback_data);
6747 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6748 options->flags.exit_with_status &&
6749 options->flags.diff_from_contents) {
6751 * run diff_flush_patch for the exit status. setting
6752 * options->file to /dev/null should be safe, because we
6753 * aren't supposed to produce any output anyway.
6755 diff_free_file(options);
6756 options->file = xfopen("/dev/null", "w");
6757 options->close_file = 1;
6758 options->color_moved = 0;
6759 for (i = 0; i < q->nr; i++) {
6760 struct diff_filepair *p = q->queue[i];
6761 if (check_pair_status(p))
6762 diff_flush_patch(p, options);
6763 if (options->found_changes)
6764 break;
6768 free_queue:
6769 diff_free_queue(q);
6770 DIFF_QUEUE_CLEAR(q);
6771 diff_free(options);
6774 * Report the content-level differences with HAS_CHANGES;
6775 * diff_addremove/diff_change does not set the bit when
6776 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6778 if (options->flags.diff_from_contents) {
6779 if (options->found_changes)
6780 options->flags.has_changes = 1;
6781 else
6782 options->flags.has_changes = 0;
6786 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6788 return (((p->status == DIFF_STATUS_MODIFIED) &&
6789 ((p->score &&
6790 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6791 (!p->score &&
6792 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6793 ((p->status != DIFF_STATUS_MODIFIED) &&
6794 filter_bit_tst(p->status, options)));
6797 static void diffcore_apply_filter(struct diff_options *options)
6799 int i;
6800 struct diff_queue_struct *q = &diff_queued_diff;
6801 struct diff_queue_struct outq;
6803 DIFF_QUEUE_CLEAR(&outq);
6805 if (!options->filter)
6806 return;
6808 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6809 int found;
6810 for (i = found = 0; !found && i < q->nr; i++) {
6811 if (match_filter(options, q->queue[i]))
6812 found++;
6814 if (found)
6815 return;
6817 /* otherwise we will clear the whole queue
6818 * by copying the empty outq at the end of this
6819 * function, but first clear the current entries
6820 * in the queue.
6822 for (i = 0; i < q->nr; i++)
6823 diff_free_filepair(q->queue[i]);
6825 else {
6826 /* Only the matching ones */
6827 for (i = 0; i < q->nr; i++) {
6828 struct diff_filepair *p = q->queue[i];
6829 if (match_filter(options, p))
6830 diff_q(&outq, p);
6831 else
6832 diff_free_filepair(p);
6835 free(q->queue);
6836 *q = outq;
6839 /* Check whether two filespecs with the same mode and size are identical */
6840 static int diff_filespec_is_identical(struct repository *r,
6841 struct diff_filespec *one,
6842 struct diff_filespec *two)
6844 if (S_ISGITLINK(one->mode))
6845 return 0;
6846 if (diff_populate_filespec(r, one, NULL))
6847 return 0;
6848 if (diff_populate_filespec(r, two, NULL))
6849 return 0;
6850 return !memcmp(one->data, two->data, one->size);
6853 static int diff_filespec_check_stat_unmatch(struct repository *r,
6854 struct diff_filepair *p)
6856 struct diff_populate_filespec_options dpf_options = {
6857 .check_size_only = 1,
6858 .missing_object_cb = diff_queued_diff_prefetch,
6859 .missing_object_data = r,
6862 if (p->done_skip_stat_unmatch)
6863 return p->skip_stat_unmatch_result;
6865 p->done_skip_stat_unmatch = 1;
6866 p->skip_stat_unmatch_result = 0;
6868 * 1. Entries that come from stat info dirtiness
6869 * always have both sides (iow, not create/delete),
6870 * one side of the object name is unknown, with
6871 * the same mode and size. Keep the ones that
6872 * do not match these criteria. They have real
6873 * differences.
6875 * 2. At this point, the file is known to be modified,
6876 * with the same mode and size, and the object
6877 * name of one side is unknown. Need to inspect
6878 * the identical contents.
6880 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6881 !DIFF_FILE_VALID(p->two) ||
6882 (p->one->oid_valid && p->two->oid_valid) ||
6883 (p->one->mode != p->two->mode) ||
6884 diff_populate_filespec(r, p->one, &dpf_options) ||
6885 diff_populate_filespec(r, p->two, &dpf_options) ||
6886 (p->one->size != p->two->size) ||
6887 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6888 p->skip_stat_unmatch_result = 1;
6889 return p->skip_stat_unmatch_result;
6892 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6894 int i;
6895 struct diff_queue_struct *q = &diff_queued_diff;
6896 struct diff_queue_struct outq;
6897 DIFF_QUEUE_CLEAR(&outq);
6899 for (i = 0; i < q->nr; i++) {
6900 struct diff_filepair *p = q->queue[i];
6902 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6903 diff_q(&outq, p);
6904 else {
6906 * The caller can subtract 1 from skip_stat_unmatch
6907 * to determine how many paths were dirty only
6908 * due to stat info mismatch.
6910 if (!diffopt->flags.no_index)
6911 diffopt->skip_stat_unmatch++;
6912 diff_free_filepair(p);
6915 free(q->queue);
6916 *q = outq;
6919 static int diffnamecmp(const void *a_, const void *b_)
6921 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6922 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6923 const char *name_a, *name_b;
6925 name_a = a->one ? a->one->path : a->two->path;
6926 name_b = b->one ? b->one->path : b->two->path;
6927 return strcmp(name_a, name_b);
6930 void diffcore_fix_diff_index(void)
6932 struct diff_queue_struct *q = &diff_queued_diff;
6933 QSORT(q->queue, q->nr, diffnamecmp);
6936 void diff_add_if_missing(struct repository *r,
6937 struct oid_array *to_fetch,
6938 const struct diff_filespec *filespec)
6940 if (filespec && filespec->oid_valid &&
6941 !S_ISGITLINK(filespec->mode) &&
6942 oid_object_info_extended(r, &filespec->oid, NULL,
6943 OBJECT_INFO_FOR_PREFETCH))
6944 oid_array_append(to_fetch, &filespec->oid);
6947 void diff_queued_diff_prefetch(void *repository)
6949 struct repository *repo = repository;
6950 int i;
6951 struct diff_queue_struct *q = &diff_queued_diff;
6952 struct oid_array to_fetch = OID_ARRAY_INIT;
6954 for (i = 0; i < q->nr; i++) {
6955 struct diff_filepair *p = q->queue[i];
6956 diff_add_if_missing(repo, &to_fetch, p->one);
6957 diff_add_if_missing(repo, &to_fetch, p->two);
6961 * NEEDSWORK: Consider deduplicating the OIDs sent.
6963 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6965 oid_array_clear(&to_fetch);
6968 void init_diffstat_widths(struct diff_options *options)
6970 options->stat_width = -1; /* use full terminal width */
6971 options->stat_name_width = -1; /* respect diff.statNameWidth config */
6972 options->stat_graph_width = -1; /* respect diff.statGraphWidth config */
6975 void diffcore_std(struct diff_options *options)
6977 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6978 DIFF_FORMAT_NUMSTAT |
6979 DIFF_FORMAT_PATCH |
6980 DIFF_FORMAT_SHORTSTAT |
6981 DIFF_FORMAT_DIRSTAT;
6984 * Check if the user requested a blob-data-requiring diff output and/or
6985 * break-rewrite detection (which requires blob data). If yes, prefetch
6986 * the diff pairs.
6988 * If no prefetching occurs, diffcore_rename() will prefetch if it
6989 * decides that it needs inexact rename detection.
6991 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
6992 (options->output_format & output_formats_to_prefetch ||
6993 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6994 diff_queued_diff_prefetch(options->repo);
6996 /* NOTE please keep the following in sync with diff_tree_combined() */
6997 if (options->skip_stat_unmatch)
6998 diffcore_skip_stat_unmatch(options);
6999 if (!options->found_follow) {
7000 /* See try_to_follow_renames() in tree-diff.c */
7001 if (options->break_opt != -1)
7002 diffcore_break(options->repo,
7003 options->break_opt);
7004 if (options->detect_rename)
7005 diffcore_rename(options);
7006 if (options->break_opt != -1)
7007 diffcore_merge_broken();
7009 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
7010 diffcore_pickaxe(options);
7011 if (options->orderfile)
7012 diffcore_order(options->orderfile);
7013 if (options->rotate_to)
7014 diffcore_rotate(options);
7015 if (!options->found_follow)
7016 /* See try_to_follow_renames() in tree-diff.c */
7017 diff_resolve_rename_copy();
7018 diffcore_apply_filter(options);
7020 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
7021 options->flags.has_changes = 1;
7022 else
7023 options->flags.has_changes = 0;
7025 options->found_follow = 0;
7028 int diff_result_code(struct diff_options *opt)
7030 int result = 0;
7032 diff_warn_rename_limit("diff.renameLimit",
7033 opt->needed_rename_limit,
7034 opt->degraded_cc_to_c);
7036 if (opt->flags.exit_with_status &&
7037 opt->flags.has_changes)
7038 result |= 01;
7039 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
7040 opt->flags.check_failed)
7041 result |= 02;
7042 return result;
7045 int diff_can_quit_early(struct diff_options *opt)
7047 return (opt->flags.quick &&
7048 !opt->filter &&
7049 opt->flags.has_changes);
7053 * Shall changes to this submodule be ignored?
7055 * Submodule changes can be configured to be ignored separately for each path,
7056 * but that configuration can be overridden from the command line.
7058 static int is_submodule_ignored(const char *path, struct diff_options *options)
7060 int ignored = 0;
7061 struct diff_flags orig_flags = options->flags;
7062 if (!options->flags.override_submodule_config)
7063 set_diffopt_flags_from_submodule_config(options, path);
7064 if (options->flags.ignore_submodules)
7065 ignored = 1;
7066 options->flags = orig_flags;
7067 return ignored;
7070 void compute_diffstat(struct diff_options *options,
7071 struct diffstat_t *diffstat,
7072 struct diff_queue_struct *q)
7074 int i;
7076 memset(diffstat, 0, sizeof(struct diffstat_t));
7077 for (i = 0; i < q->nr; i++) {
7078 struct diff_filepair *p = q->queue[i];
7079 if (check_pair_status(p))
7080 diff_flush_stat(p, options, diffstat);
7082 options->found_changes = !!diffstat->nr;
7085 void diff_addremove(struct diff_options *options,
7086 int addremove, unsigned mode,
7087 const struct object_id *oid,
7088 int oid_valid,
7089 const char *concatpath, unsigned dirty_submodule)
7091 struct diff_filespec *one, *two;
7093 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7094 return;
7096 /* This may look odd, but it is a preparation for
7097 * feeding "there are unchanged files which should
7098 * not produce diffs, but when you are doing copy
7099 * detection you would need them, so here they are"
7100 * entries to the diff-core. They will be prefixed
7101 * with something like '=' or '*' (I haven't decided
7102 * which but should not make any difference).
7103 * Feeding the same new and old to diff_change()
7104 * also has the same effect.
7105 * Before the final output happens, they are pruned after
7106 * merged into rename/copy pairs as appropriate.
7108 if (options->flags.reverse_diff)
7109 addremove = (addremove == '+' ? '-' :
7110 addremove == '-' ? '+' : addremove);
7112 if (options->prefix &&
7113 strncmp(concatpath, options->prefix, options->prefix_length))
7114 return;
7116 one = alloc_filespec(concatpath);
7117 two = alloc_filespec(concatpath);
7119 if (addremove != '+')
7120 fill_filespec(one, oid, oid_valid, mode);
7121 if (addremove != '-') {
7122 fill_filespec(two, oid, oid_valid, mode);
7123 two->dirty_submodule = dirty_submodule;
7126 diff_queue(&diff_queued_diff, one, two);
7127 if (!options->flags.diff_from_contents)
7128 options->flags.has_changes = 1;
7131 void diff_change(struct diff_options *options,
7132 unsigned old_mode, unsigned new_mode,
7133 const struct object_id *old_oid,
7134 const struct object_id *new_oid,
7135 int old_oid_valid, int new_oid_valid,
7136 const char *concatpath,
7137 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7139 struct diff_filespec *one, *two;
7140 struct diff_filepair *p;
7142 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7143 is_submodule_ignored(concatpath, options))
7144 return;
7146 if (options->flags.reverse_diff) {
7147 SWAP(old_mode, new_mode);
7148 SWAP(old_oid, new_oid);
7149 SWAP(old_oid_valid, new_oid_valid);
7150 SWAP(old_dirty_submodule, new_dirty_submodule);
7153 if (options->prefix &&
7154 strncmp(concatpath, options->prefix, options->prefix_length))
7155 return;
7157 one = alloc_filespec(concatpath);
7158 two = alloc_filespec(concatpath);
7159 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7160 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7161 one->dirty_submodule = old_dirty_submodule;
7162 two->dirty_submodule = new_dirty_submodule;
7163 p = diff_queue(&diff_queued_diff, one, two);
7165 if (options->flags.diff_from_contents)
7166 return;
7168 if (options->flags.quick && options->skip_stat_unmatch &&
7169 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7170 diff_free_filespec_data(p->one);
7171 diff_free_filespec_data(p->two);
7172 return;
7175 options->flags.has_changes = 1;
7178 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7180 struct diff_filepair *pair;
7181 struct diff_filespec *one, *two;
7183 if (options->prefix &&
7184 strncmp(path, options->prefix, options->prefix_length))
7185 return NULL;
7187 one = alloc_filespec(path);
7188 two = alloc_filespec(path);
7189 pair = diff_queue(&diff_queued_diff, one, two);
7190 pair->is_unmerged = 1;
7191 return pair;
7194 static char *run_textconv(struct repository *r,
7195 const char *pgm,
7196 struct diff_filespec *spec,
7197 size_t *outsize)
7199 struct diff_tempfile *temp;
7200 struct child_process child = CHILD_PROCESS_INIT;
7201 struct strbuf buf = STRBUF_INIT;
7202 int err = 0;
7204 temp = prepare_temp_file(r, spec);
7205 strvec_push(&child.args, pgm);
7206 strvec_push(&child.args, temp->name);
7208 child.use_shell = 1;
7209 child.out = -1;
7210 if (start_command(&child)) {
7211 remove_tempfile();
7212 return NULL;
7215 if (strbuf_read(&buf, child.out, 0) < 0)
7216 err = error("error reading from textconv command '%s'", pgm);
7217 close(child.out);
7219 if (finish_command(&child) || err) {
7220 strbuf_release(&buf);
7221 remove_tempfile();
7222 return NULL;
7224 remove_tempfile();
7226 return strbuf_detach(&buf, outsize);
7229 size_t fill_textconv(struct repository *r,
7230 struct userdiff_driver *driver,
7231 struct diff_filespec *df,
7232 char **outbuf)
7234 size_t size;
7236 if (!driver) {
7237 if (!DIFF_FILE_VALID(df)) {
7238 *outbuf = (char *) "";
7239 return 0;
7241 if (diff_populate_filespec(r, df, NULL))
7242 die("unable to read files to diff");
7243 *outbuf = df->data;
7244 return df->size;
7247 if (!driver->textconv)
7248 BUG("fill_textconv called with non-textconv driver");
7250 if (driver->textconv_cache && df->oid_valid) {
7251 *outbuf = notes_cache_get(driver->textconv_cache,
7252 &df->oid,
7253 &size);
7254 if (*outbuf)
7255 return size;
7258 *outbuf = run_textconv(r, driver->textconv, df, &size);
7259 if (!*outbuf)
7260 die("unable to read files to diff");
7262 if (driver->textconv_cache && df->oid_valid) {
7263 /* ignore errors, as we might be in a readonly repository */
7264 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7265 size);
7267 * we could save up changes and flush them all at the end,
7268 * but we would need an extra call after all diffing is done.
7269 * Since generating a cache entry is the slow path anyway,
7270 * this extra overhead probably isn't a big deal.
7272 notes_cache_write(driver->textconv_cache);
7275 return size;
7278 int textconv_object(struct repository *r,
7279 const char *path,
7280 unsigned mode,
7281 const struct object_id *oid,
7282 int oid_valid,
7283 char **buf,
7284 unsigned long *buf_size)
7286 struct diff_filespec *df;
7287 struct userdiff_driver *textconv;
7289 df = alloc_filespec(path);
7290 fill_filespec(df, oid, oid_valid, mode);
7291 textconv = get_textconv(r, df);
7292 if (!textconv) {
7293 free_filespec(df);
7294 return 0;
7297 *buf_size = fill_textconv(r, textconv, df, buf);
7298 free_filespec(df);
7299 return 1;
7302 void setup_diff_pager(struct diff_options *opt)
7305 * If the user asked for our exit code, then either they want --quiet
7306 * or --exit-code. We should definitely not bother with a pager in the
7307 * former case, as we will generate no output. Since we still properly
7308 * report our exit code even when a pager is run, we _could_ run a
7309 * pager with --exit-code. But since we have not done so historically,
7310 * and because it is easy to find people oneline advising "git diff
7311 * --exit-code" in hooks and other scripts, we do not do so.
7313 if (!opt->flags.exit_with_status &&
7314 check_pager_config("diff") != 0)
7315 setup_pager();