2 * Copyright (C) 2005 Junio C Hamano
11 #include "xdiff-interface.h"
14 #include "run-command.h"
17 #include "submodule-config.h"
18 #include "submodule.h"
21 #include "string-list.h"
22 #include "argv-array.h"
25 #ifdef NO_FAST_WORKING_DIRECTORY
26 #define FAST_WORKING_DIRECTORY 0
28 #define FAST_WORKING_DIRECTORY 1
31 static int diff_detect_rename_default;
32 static int diff_indent_heuristic = 1;
33 static int diff_rename_limit_default = 400;
34 static int diff_suppress_blank_empty;
35 static int diff_use_color_default = -1;
36 static int diff_color_moved_default;
37 static int diff_context_default = 3;
38 static int diff_interhunk_context_default;
39 static const char *diff_word_regex_cfg;
40 static const char *external_diff_cmd_cfg;
41 static const char *diff_order_file_cfg;
42 int diff_auto_refresh_index = 1;
43 static int diff_mnemonic_prefix;
44 static int diff_no_prefix;
45 static int diff_stat_graph_width;
46 static int diff_dirstat_permille_default = 30;
47 static struct diff_options default_diff_options;
48 static long diff_algorithm;
49 static unsigned ws_error_highlight_default = WSEH_NEW;
51 static char diff_colors[][COLOR_MAXLEN] = {
53 GIT_COLOR_NORMAL, /* CONTEXT */
54 GIT_COLOR_BOLD, /* METAINFO */
55 GIT_COLOR_CYAN, /* FRAGINFO */
56 GIT_COLOR_RED, /* OLD */
57 GIT_COLOR_GREEN, /* NEW */
58 GIT_COLOR_YELLOW, /* COMMIT */
59 GIT_COLOR_BG_RED, /* WHITESPACE */
60 GIT_COLOR_NORMAL, /* FUNCINFO */
61 GIT_COLOR_MAGENTA, /* OLD_MOVED */
62 GIT_COLOR_BLUE, /* OLD_MOVED ALTERNATIVE */
63 GIT_COLOR_CYAN, /* NEW_MOVED */
64 GIT_COLOR_YELLOW, /* NEW_MOVED ALTERNATIVE */
67 static NORETURN void die_want_option(const char *option_name)
69 die(_("option '%s' requires a value"), option_name);
72 static int parse_diff_color_slot(const char *var)
74 if (!strcasecmp(var, "context") || !strcasecmp(var, "plain"))
76 if (!strcasecmp(var, "meta"))
78 if (!strcasecmp(var, "frag"))
80 if (!strcasecmp(var, "old"))
82 if (!strcasecmp(var, "new"))
84 if (!strcasecmp(var, "commit"))
86 if (!strcasecmp(var, "whitespace"))
87 return DIFF_WHITESPACE;
88 if (!strcasecmp(var, "func"))
90 if (!strcasecmp(var, "oldmoved"))
91 return DIFF_FILE_OLD_MOVED;
92 if (!strcasecmp(var, "oldmovedalternative"))
93 return DIFF_FILE_OLD_MOVED_ALT;
94 if (!strcasecmp(var, "newmoved"))
95 return DIFF_FILE_NEW_MOVED;
96 if (!strcasecmp(var, "newmovedalternative"))
97 return DIFF_FILE_NEW_MOVED_ALT;
101 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
102 struct strbuf *errmsg)
104 char *params_copy = xstrdup(params_string);
105 struct string_list params = STRING_LIST_INIT_NODUP;
110 string_list_split_in_place(¶ms, params_copy, ',', -1);
111 for (i = 0; i < params.nr; i++) {
112 const char *p = params.items[i].string;
113 if (!strcmp(p, "changes")) {
114 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
115 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
116 } else if (!strcmp(p, "lines")) {
117 DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
118 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
119 } else if (!strcmp(p, "files")) {
120 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
121 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
122 } else if (!strcmp(p, "noncumulative")) {
123 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
124 } else if (!strcmp(p, "cumulative")) {
125 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
126 } else if (isdigit(*p)) {
128 int permille = strtoul(p, &end, 10) * 10;
129 if (*end == '.' && isdigit(*++end)) {
130 /* only use first digit */
131 permille += *end - '0';
132 /* .. and ignore any further digits */
133 while (isdigit(*++end))
137 options->dirstat_permille = permille;
139 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
144 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
149 string_list_clear(¶ms, 0);
154 static int parse_submodule_params(struct diff_options *options, const char *value)
156 if (!strcmp(value, "log"))
157 options->submodule_format = DIFF_SUBMODULE_LOG;
158 else if (!strcmp(value, "short"))
159 options->submodule_format = DIFF_SUBMODULE_SHORT;
160 else if (!strcmp(value, "diff"))
161 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
167 static int git_config_rename(const char *var, const char *value)
170 return DIFF_DETECT_RENAME;
171 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
172 return DIFF_DETECT_COPY;
173 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
176 long parse_algorithm_value(const char *value)
180 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
182 else if (!strcasecmp(value, "minimal"))
183 return XDF_NEED_MINIMAL;
184 else if (!strcasecmp(value, "patience"))
185 return XDF_PATIENCE_DIFF;
186 else if (!strcasecmp(value, "histogram"))
187 return XDF_HISTOGRAM_DIFF;
191 static int parse_one_token(const char **arg, const char *token)
194 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
201 static int parse_ws_error_highlight(const char *arg)
203 const char *orig_arg = arg;
207 if (parse_one_token(&arg, "none"))
209 else if (parse_one_token(&arg, "default"))
211 else if (parse_one_token(&arg, "all"))
212 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
213 else if (parse_one_token(&arg, "new"))
215 else if (parse_one_token(&arg, "old"))
217 else if (parse_one_token(&arg, "context"))
220 return -1 - (int)(arg - orig_arg);
229 * These are to give UI layer defaults.
230 * The core-level commands such as git-diff-files should
231 * never be affected by the setting of diff.renames
232 * the user happens to have in the configuration file.
234 void init_diff_ui_defaults(void)
236 diff_detect_rename_default = 1;
239 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
241 if (!strcmp(var, "diff.indentheuristic"))
242 diff_indent_heuristic = git_config_bool(var, value);
246 static int parse_color_moved(const char *arg)
248 switch (git_parse_maybe_bool(arg)) {
250 return COLOR_MOVED_NO;
252 return COLOR_MOVED_DEFAULT;
257 if (!strcmp(arg, "no"))
258 return COLOR_MOVED_NO;
259 else if (!strcmp(arg, "zebra"))
260 return COLOR_MOVED_ZEBRA;
261 else if (!strcmp(arg, "default"))
262 return COLOR_MOVED_DEFAULT;
264 return error(_("color moved setting must be one of 'no', 'default', 'zebra'"));
267 int git_diff_ui_config(const char *var, const char *value, void *cb)
269 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
270 diff_use_color_default = git_config_colorbool(var, value);
273 if (!strcmp(var, "diff.colormoved")) {
274 int cm = parse_color_moved(value);
277 diff_color_moved_default = cm;
280 if (!strcmp(var, "diff.context")) {
281 diff_context_default = git_config_int(var, value);
282 if (diff_context_default < 0)
286 if (!strcmp(var, "diff.interhunkcontext")) {
287 diff_interhunk_context_default = git_config_int(var, value);
288 if (diff_interhunk_context_default < 0)
292 if (!strcmp(var, "diff.renames")) {
293 diff_detect_rename_default = git_config_rename(var, value);
296 if (!strcmp(var, "diff.autorefreshindex")) {
297 diff_auto_refresh_index = git_config_bool(var, value);
300 if (!strcmp(var, "diff.mnemonicprefix")) {
301 diff_mnemonic_prefix = git_config_bool(var, value);
304 if (!strcmp(var, "diff.noprefix")) {
305 diff_no_prefix = git_config_bool(var, value);
308 if (!strcmp(var, "diff.statgraphwidth")) {
309 diff_stat_graph_width = git_config_int(var, value);
312 if (!strcmp(var, "diff.external"))
313 return git_config_string(&external_diff_cmd_cfg, var, value);
314 if (!strcmp(var, "diff.wordregex"))
315 return git_config_string(&diff_word_regex_cfg, var, value);
316 if (!strcmp(var, "diff.orderfile"))
317 return git_config_pathname(&diff_order_file_cfg, var, value);
319 if (!strcmp(var, "diff.ignoresubmodules"))
320 handle_ignore_submodules_arg(&default_diff_options, value);
322 if (!strcmp(var, "diff.submodule")) {
323 if (parse_submodule_params(&default_diff_options, value))
324 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
329 if (!strcmp(var, "diff.algorithm")) {
330 diff_algorithm = parse_algorithm_value(value);
331 if (diff_algorithm < 0)
336 if (!strcmp(var, "diff.wserrorhighlight")) {
337 int val = parse_ws_error_highlight(value);
340 ws_error_highlight_default = val;
344 if (git_color_config(var, value, cb) < 0)
347 return git_diff_basic_config(var, value, cb);
350 int git_diff_basic_config(const char *var, const char *value, void *cb)
354 if (!strcmp(var, "diff.renamelimit")) {
355 diff_rename_limit_default = git_config_int(var, value);
359 if (userdiff_config(var, value) < 0)
362 if (skip_prefix(var, "diff.color.", &name) ||
363 skip_prefix(var, "color.diff.", &name)) {
364 int slot = parse_diff_color_slot(name);
368 return config_error_nonbool(var);
369 return color_parse(value, diff_colors[slot]);
372 /* like GNU diff's --suppress-blank-empty option */
373 if (!strcmp(var, "diff.suppressblankempty") ||
374 /* for backwards compatibility */
375 !strcmp(var, "diff.suppress-blank-empty")) {
376 diff_suppress_blank_empty = git_config_bool(var, value);
380 if (!strcmp(var, "diff.dirstat")) {
381 struct strbuf errmsg = STRBUF_INIT;
382 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
383 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
384 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
386 strbuf_release(&errmsg);
387 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
391 if (starts_with(var, "submodule."))
392 return parse_submodule_config_option(var, value);
394 if (git_diff_heuristic_config(var, value, cb) < 0)
397 return git_default_config(var, value, cb);
400 static char *quote_two(const char *one, const char *two)
402 int need_one = quote_c_style(one, NULL, NULL, 1);
403 int need_two = quote_c_style(two, NULL, NULL, 1);
404 struct strbuf res = STRBUF_INIT;
406 if (need_one + need_two) {
407 strbuf_addch(&res, '"');
408 quote_c_style(one, &res, NULL, 1);
409 quote_c_style(two, &res, NULL, 1);
410 strbuf_addch(&res, '"');
412 strbuf_addstr(&res, one);
413 strbuf_addstr(&res, two);
415 return strbuf_detach(&res, NULL);
418 static const char *external_diff(void)
420 static const char *external_diff_cmd = NULL;
421 static int done_preparing = 0;
424 return external_diff_cmd;
425 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
426 if (!external_diff_cmd)
427 external_diff_cmd = external_diff_cmd_cfg;
429 return external_diff_cmd;
433 * Keep track of files used for diffing. Sometimes such an entry
434 * refers to a temporary file, sometimes to an existing file, and
435 * sometimes to "/dev/null".
437 static struct diff_tempfile {
439 * filename external diff should read from, or NULL if this
440 * entry is currently not in use:
444 char hex[GIT_MAX_HEXSZ + 1];
448 * If this diff_tempfile instance refers to a temporary file,
449 * this tempfile object is used to manage its lifetime.
451 struct tempfile tempfile;
454 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
456 struct emit_callback {
459 int blank_at_eof_in_preimage;
460 int blank_at_eof_in_postimage;
462 int lno_in_postimage;
463 sane_truncate_fn truncate;
464 const char **label_path;
465 struct diff_words_data *diff_words;
466 struct diff_options *opt;
467 struct strbuf *header;
470 static int count_lines(const char *data, int size)
472 int count, ch, completely_empty = 1, nl_just_seen = 0;
479 completely_empty = 0;
483 completely_empty = 0;
486 if (completely_empty)
489 count++; /* no trailing newline */
493 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
495 if (!DIFF_FILE_VALID(one)) {
496 mf->ptr = (char *)""; /* does not matter */
500 else if (diff_populate_filespec(one, 0))
504 mf->size = one->size;
508 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
509 static unsigned long diff_filespec_size(struct diff_filespec *one)
511 if (!DIFF_FILE_VALID(one))
513 diff_populate_filespec(one, CHECK_SIZE_ONLY);
517 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
520 long size = mf->size;
525 ptr += size - 1; /* pointing at the very end */
527 ; /* incomplete line */
529 ptr--; /* skip the last LF */
530 while (mf->ptr < ptr) {
532 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
533 if (*prev_eol == '\n')
535 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
543 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
544 struct emit_callback *ecbdata)
547 unsigned ws_rule = ecbdata->ws_rule;
548 l1 = count_trailing_blank(mf1, ws_rule);
549 l2 = count_trailing_blank(mf2, ws_rule);
551 ecbdata->blank_at_eof_in_preimage = 0;
552 ecbdata->blank_at_eof_in_postimage = 0;
555 at = count_lines(mf1->ptr, mf1->size);
556 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
558 at = count_lines(mf2->ptr, mf2->size);
559 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
562 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
563 int first, const char *line, int len)
565 int has_trailing_newline, has_trailing_carriage_return;
567 FILE *file = o->file;
569 fputs(diff_line_prefix(o), file);
572 has_trailing_newline = (first == '\n');
573 has_trailing_carriage_return = (!has_trailing_newline &&
575 nofirst = has_trailing_newline || has_trailing_carriage_return;
577 has_trailing_newline = (len > 0 && line[len-1] == '\n');
578 if (has_trailing_newline)
580 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
581 if (has_trailing_carriage_return)
586 if (len || !nofirst) {
590 fwrite(line, len, 1, file);
593 if (has_trailing_carriage_return)
595 if (has_trailing_newline)
599 static void emit_line(struct diff_options *o, const char *set, const char *reset,
600 const char *line, int len)
602 emit_line_0(o, set, reset, line[0], line+1, len-1);
606 DIFF_SYMBOL_BINARY_DIFF_HEADER,
607 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
608 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
609 DIFF_SYMBOL_BINARY_DIFF_BODY,
610 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
611 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
612 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
613 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
614 DIFF_SYMBOL_STATS_LINE,
615 DIFF_SYMBOL_WORD_DIFF,
616 DIFF_SYMBOL_STAT_SEP,
618 DIFF_SYMBOL_SUBMODULE_ADD,
619 DIFF_SYMBOL_SUBMODULE_DEL,
620 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
621 DIFF_SYMBOL_SUBMODULE_MODIFIED,
622 DIFF_SYMBOL_SUBMODULE_HEADER,
623 DIFF_SYMBOL_SUBMODULE_ERROR,
624 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
625 DIFF_SYMBOL_REWRITE_DIFF,
626 DIFF_SYMBOL_BINARY_FILES,
628 DIFF_SYMBOL_FILEPAIR_PLUS,
629 DIFF_SYMBOL_FILEPAIR_MINUS,
630 DIFF_SYMBOL_WORDS_PORCELAIN,
633 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
636 DIFF_SYMBOL_NO_LF_EOF,
637 DIFF_SYMBOL_CONTEXT_FRAGINFO,
638 DIFF_SYMBOL_CONTEXT_MARKER,
639 DIFF_SYMBOL_SEPARATOR
642 * Flags for content lines:
643 * 0..12 are whitespace rules
644 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
645 * 16 is marking if the line is blank at EOF
647 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
648 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
649 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
650 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
653 * This struct is used when we need to buffer the output of the diff output.
655 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
656 * into the pre/post image file. This pointer could be a union with the
657 * line pointer. By storing an offset into the file instead of the literal line,
658 * we can decrease the memory footprint for the buffered output. At first we
659 * may want to only have indirection for the content lines, but we could also
660 * enhance the state for emitting prefabricated lines, e.g. the similarity
661 * score line or hunk/file headers would only need to store a number or path
662 * and then the output can be constructed later on depending on state.
664 struct emitted_diff_symbol {
670 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
672 struct emitted_diff_symbols {
673 struct emitted_diff_symbol *buf;
676 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
678 static void append_emitted_diff_symbol(struct diff_options *o,
679 struct emitted_diff_symbol *e)
681 struct emitted_diff_symbol *f;
683 ALLOC_GROW(o->emitted_symbols->buf,
684 o->emitted_symbols->nr + 1,
685 o->emitted_symbols->alloc);
686 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
688 memcpy(f, e, sizeof(struct emitted_diff_symbol));
689 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
693 struct hashmap_entry ent;
694 const struct emitted_diff_symbol *es;
695 struct moved_entry *next_line;
698 static int next_byte(const char **cp, const char **endp,
699 const struct diff_options *diffopt)
706 if (DIFF_XDL_TST(diffopt, IGNORE_WHITESPACE_CHANGE)) {
707 while (*cp < *endp && isspace(**cp))
710 * After skipping a couple of whitespaces, we still have to
711 * account for one space.
716 if (DIFF_XDL_TST(diffopt, IGNORE_WHITESPACE)) {
717 while (*cp < *endp && isspace(**cp))
719 /* return the first non-ws character via the usual below */
722 retval = (unsigned char)(**cp);
727 static int moved_entry_cmp(const struct diff_options *diffopt,
728 const struct moved_entry *a,
729 const struct moved_entry *b,
732 const char *ap = a->es->line, *ae = a->es->line + a->es->len;
733 const char *bp = b->es->line, *be = b->es->line + b->es->len;
735 if (!(diffopt->xdl_opts & XDF_WHITESPACE_FLAGS))
736 return a->es->len != b->es->len || memcmp(ap, bp, a->es->len);
738 if (DIFF_XDL_TST(diffopt, IGNORE_WHITESPACE_AT_EOL)) {
739 while (ae > ap && isspace(*ae))
741 while (be > bp && isspace(*be))
747 ca = next_byte(&ap, &ae, diffopt);
748 cb = next_byte(&bp, &be, diffopt);
756 static unsigned get_string_hash(struct emitted_diff_symbol *es, struct diff_options *o)
758 if (o->xdl_opts & XDF_WHITESPACE_FLAGS) {
759 static struct strbuf sb = STRBUF_INIT;
760 const char *ap = es->line, *ae = es->line + es->len;
764 while (ae > ap && isspace(*ae))
766 while ((c = next_byte(&ap, &ae, o)) > 0)
767 strbuf_addch(&sb, c);
769 return memhash(sb.buf, sb.len);
771 return memhash(es->line, es->len);
775 static struct moved_entry *prepare_entry(struct diff_options *o,
778 struct moved_entry *ret = xmalloc(sizeof(*ret));
779 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
781 ret->ent.hash = get_string_hash(l, o);
783 ret->next_line = NULL;
788 static void add_lines_to_move_detection(struct diff_options *o,
789 struct hashmap *add_lines,
790 struct hashmap *del_lines)
792 struct moved_entry *prev_line = NULL;
795 for (n = 0; n < o->emitted_symbols->nr; n++) {
797 struct moved_entry *key;
799 switch (o->emitted_symbols->buf[n].s) {
800 case DIFF_SYMBOL_PLUS:
803 case DIFF_SYMBOL_MINUS:
811 key = prepare_entry(o, n);
812 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
813 prev_line->next_line = key;
815 hashmap_add(hm, key);
820 static int shrink_potential_moved_blocks(struct moved_entry **pmb,
825 /* Shrink the set of potential block to the remaining running */
826 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
827 while (lp < pmb_nr && pmb[lp])
829 /* lp points at the first NULL now */
831 while (rp > -1 && !pmb[rp])
833 /* rp points at the last non-NULL */
835 if (lp < pmb_nr && rp > -1 && lp < rp) {
843 /* Remember the number of running sets */
847 /* Find blocks of moved code, delegate actual coloring decision to helper */
848 static void mark_color_as_moved(struct diff_options *o,
849 struct hashmap *add_lines,
850 struct hashmap *del_lines)
852 struct moved_entry **pmb = NULL; /* potentially moved blocks */
853 int pmb_nr = 0, pmb_alloc = 0;
854 int n, flipped_block = 1, block_length = 0;
857 for (n = 0; n < o->emitted_symbols->nr; n++) {
858 struct hashmap *hm = NULL;
859 struct moved_entry *key;
860 struct moved_entry *match = NULL;
861 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
865 case DIFF_SYMBOL_PLUS:
867 key = prepare_entry(o, n);
868 match = hashmap_get(hm, key, o);
871 case DIFF_SYMBOL_MINUS:
873 key = prepare_entry(o, n);
874 match = hashmap_get(hm, key, o);
882 if (block_length < COLOR_MOVED_MIN_BLOCK_LENGTH) {
883 for (i = 0; i < block_length + 1; i++) {
884 l = &o->emitted_symbols->buf[n - i];
885 l->flags &= ~DIFF_SYMBOL_MOVED_LINE;
893 l->flags |= DIFF_SYMBOL_MOVED_LINE;
896 /* Check any potential block runs, advance each or nullify */
897 for (i = 0; i < pmb_nr; i++) {
898 struct moved_entry *p = pmb[i];
899 struct moved_entry *pnext = (p && p->next_line) ?
901 if (pnext && !hm->cmpfn(o, pnext, match, NULL)) {
902 pmb[i] = p->next_line;
908 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
912 * The current line is the start of a new block.
913 * Setup the set of potential blocks.
915 for (; match; match = hashmap_get_next(hm, match)) {
916 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
917 pmb[pmb_nr++] = match;
920 flipped_block = (flipped_block + 1) % 2;
924 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
930 static void emit_line_ws_markup(struct diff_options *o,
931 const char *set, const char *reset,
932 const char *line, int len, char sign,
933 unsigned ws_rule, int blank_at_eof)
935 const char *ws = NULL;
937 if (o->ws_error_highlight & ws_rule) {
938 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
944 emit_line_0(o, set, reset, sign, line, len);
945 else if (blank_at_eof)
946 /* Blank line at EOF - paint '+' as well */
947 emit_line_0(o, ws, reset, sign, line, len);
949 /* Emit just the prefix, then the rest. */
950 emit_line_0(o, set, reset, sign, "", 0);
951 ws_check_emit(line, len, ws_rule,
952 o->file, set, reset, ws);
956 static void emit_diff_symbol_from_struct(struct diff_options *o,
957 struct emitted_diff_symbol *eds)
959 static const char *nneof = " No newline at end of file\n";
960 const char *context, *reset, *set, *meta, *fraginfo;
961 struct strbuf sb = STRBUF_INIT;
963 enum diff_symbol s = eds->s;
964 const char *line = eds->line;
966 unsigned flags = eds->flags;
969 case DIFF_SYMBOL_NO_LF_EOF:
970 context = diff_get_color_opt(o, DIFF_CONTEXT);
971 reset = diff_get_color_opt(o, DIFF_RESET);
973 emit_line_0(o, context, reset, '\\',
974 nneof, strlen(nneof));
976 case DIFF_SYMBOL_SUBMODULE_HEADER:
977 case DIFF_SYMBOL_SUBMODULE_ERROR:
978 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
979 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
980 case DIFF_SYMBOL_SUMMARY:
981 case DIFF_SYMBOL_STATS_LINE:
982 case DIFF_SYMBOL_BINARY_DIFF_BODY:
983 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
984 emit_line(o, "", "", line, len);
986 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
987 case DIFF_SYMBOL_CONTEXT_MARKER:
988 context = diff_get_color_opt(o, DIFF_CONTEXT);
989 reset = diff_get_color_opt(o, DIFF_RESET);
990 emit_line(o, context, reset, line, len);
992 case DIFF_SYMBOL_SEPARATOR:
993 fprintf(o->file, "%s%c",
995 o->line_termination);
997 case DIFF_SYMBOL_CONTEXT:
998 set = diff_get_color_opt(o, DIFF_CONTEXT);
999 reset = diff_get_color_opt(o, DIFF_RESET);
1000 emit_line_ws_markup(o, set, reset, line, len, ' ',
1001 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1003 case DIFF_SYMBOL_PLUS:
1004 if (flags & DIFF_SYMBOL_MOVED_LINE_ALT)
1005 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1006 else if (flags & DIFF_SYMBOL_MOVED_LINE)
1007 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1009 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1010 reset = diff_get_color_opt(o, DIFF_RESET);
1011 emit_line_ws_markup(o, set, reset, line, len, '+',
1012 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1013 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1015 case DIFF_SYMBOL_MINUS:
1016 if (flags & DIFF_SYMBOL_MOVED_LINE_ALT)
1017 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1018 else if (flags & DIFF_SYMBOL_MOVED_LINE)
1019 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1021 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1022 reset = diff_get_color_opt(o, DIFF_RESET);
1023 emit_line_ws_markup(o, set, reset, line, len, '-',
1024 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1026 case DIFF_SYMBOL_WORDS_PORCELAIN:
1027 context = diff_get_color_opt(o, DIFF_CONTEXT);
1028 reset = diff_get_color_opt(o, DIFF_RESET);
1029 emit_line(o, context, reset, line, len);
1030 fputs("~\n", o->file);
1032 case DIFF_SYMBOL_WORDS:
1033 context = diff_get_color_opt(o, DIFF_CONTEXT);
1034 reset = diff_get_color_opt(o, DIFF_RESET);
1036 * Skip the prefix character, if any. With
1037 * diff_suppress_blank_empty, there may be
1040 if (line[0] != '\n') {
1044 emit_line(o, context, reset, line, len);
1046 case DIFF_SYMBOL_FILEPAIR_PLUS:
1047 meta = diff_get_color_opt(o, DIFF_METAINFO);
1048 reset = diff_get_color_opt(o, DIFF_RESET);
1049 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1051 strchr(line, ' ') ? "\t" : "");
1053 case DIFF_SYMBOL_FILEPAIR_MINUS:
1054 meta = diff_get_color_opt(o, DIFF_METAINFO);
1055 reset = diff_get_color_opt(o, DIFF_RESET);
1056 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1058 strchr(line, ' ') ? "\t" : "");
1060 case DIFF_SYMBOL_BINARY_FILES:
1061 case DIFF_SYMBOL_HEADER:
1062 fprintf(o->file, "%s", line);
1064 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1065 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1067 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1068 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1070 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1071 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1073 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1074 fputs(diff_line_prefix(o), o->file);
1075 fputc('\n', o->file);
1077 case DIFF_SYMBOL_REWRITE_DIFF:
1078 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1079 reset = diff_get_color_opt(o, DIFF_RESET);
1080 emit_line(o, fraginfo, reset, line, len);
1082 case DIFF_SYMBOL_SUBMODULE_ADD:
1083 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1084 reset = diff_get_color_opt(o, DIFF_RESET);
1085 emit_line(o, set, reset, line, len);
1087 case DIFF_SYMBOL_SUBMODULE_DEL:
1088 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1089 reset = diff_get_color_opt(o, DIFF_RESET);
1090 emit_line(o, set, reset, line, len);
1092 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1093 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1094 diff_line_prefix(o), line);
1096 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1097 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1098 diff_line_prefix(o), line);
1100 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1101 emit_line(o, "", "", " 0 files changed\n",
1102 strlen(" 0 files changed\n"));
1104 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1105 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1107 case DIFF_SYMBOL_WORD_DIFF:
1108 fprintf(o->file, "%.*s", len, line);
1110 case DIFF_SYMBOL_STAT_SEP:
1111 fputs(o->stat_sep, o->file);
1114 die("BUG: unknown diff symbol");
1116 strbuf_release(&sb);
1119 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1120 const char *line, int len, unsigned flags)
1122 struct emitted_diff_symbol e = {line, len, flags, s};
1124 if (o->emitted_symbols)
1125 append_emitted_diff_symbol(o, &e);
1127 emit_diff_symbol_from_struct(o, &e);
1130 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1132 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1135 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1137 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1140 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1142 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1143 path, strlen(path), 0);
1146 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1148 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1149 path, strlen(path), 0);
1152 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1154 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1155 header, strlen(header), 0);
1158 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1160 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1163 void diff_emit_submodule_pipethrough(struct diff_options *o,
1164 const char *line, int len)
1166 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1169 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1171 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1172 ecbdata->blank_at_eof_in_preimage &&
1173 ecbdata->blank_at_eof_in_postimage &&
1174 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1175 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1177 return ws_blank_line(line, len, ecbdata->ws_rule);
1180 static void emit_add_line(const char *reset,
1181 struct emit_callback *ecbdata,
1182 const char *line, int len)
1184 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1185 if (new_blank_line_at_eof(ecbdata, line, len))
1186 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1188 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1191 static void emit_del_line(const char *reset,
1192 struct emit_callback *ecbdata,
1193 const char *line, int len)
1195 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1196 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1199 static void emit_context_line(const char *reset,
1200 struct emit_callback *ecbdata,
1201 const char *line, int len)
1203 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1204 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1207 static void emit_hunk_header(struct emit_callback *ecbdata,
1208 const char *line, int len)
1210 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1211 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1212 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1213 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1214 static const char atat[2] = { '@', '@' };
1215 const char *cp, *ep;
1216 struct strbuf msgbuf = STRBUF_INIT;
1221 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1222 * it always is at least 10 bytes long.
1225 memcmp(line, atat, 2) ||
1226 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1227 emit_diff_symbol(ecbdata->opt,
1228 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1231 ep += 2; /* skip over @@ */
1233 /* The hunk header in fraginfo color */
1234 strbuf_addstr(&msgbuf, frag);
1235 strbuf_add(&msgbuf, line, ep - line);
1236 strbuf_addstr(&msgbuf, reset);
1242 if (line[len - i] == '\r' || line[len - i] == '\n')
1245 /* blank before the func header */
1246 for (cp = ep; ep - line < len; ep++)
1247 if (*ep != ' ' && *ep != '\t')
1250 strbuf_addstr(&msgbuf, context);
1251 strbuf_add(&msgbuf, cp, ep - cp);
1252 strbuf_addstr(&msgbuf, reset);
1255 if (ep < line + len) {
1256 strbuf_addstr(&msgbuf, func);
1257 strbuf_add(&msgbuf, ep, line + len - ep);
1258 strbuf_addstr(&msgbuf, reset);
1261 strbuf_add(&msgbuf, line + len, org_len - len);
1262 strbuf_complete_line(&msgbuf);
1263 emit_diff_symbol(ecbdata->opt,
1264 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1265 strbuf_release(&msgbuf);
1268 static struct diff_tempfile *claim_diff_tempfile(void) {
1270 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1271 if (!diff_temp[i].name)
1272 return diff_temp + i;
1273 die("BUG: diff is failing to clean up its tempfiles");
1276 static void remove_tempfile(void)
1279 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1280 if (is_tempfile_active(&diff_temp[i].tempfile))
1281 delete_tempfile(&diff_temp[i].tempfile);
1282 diff_temp[i].name = NULL;
1286 static void add_line_count(struct strbuf *out, int count)
1290 strbuf_addstr(out, "0,0");
1293 strbuf_addstr(out, "1");
1296 strbuf_addf(out, "1,%d", count);
1301 static void emit_rewrite_lines(struct emit_callback *ecb,
1302 int prefix, const char *data, int size)
1304 const char *endp = NULL;
1305 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1310 endp = memchr(data, '\n', size);
1311 len = endp ? (endp - data + 1) : size;
1312 if (prefix != '+') {
1313 ecb->lno_in_preimage++;
1314 emit_del_line(reset, ecb, data, len);
1316 ecb->lno_in_postimage++;
1317 emit_add_line(reset, ecb, data, len);
1323 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1326 static void emit_rewrite_diff(const char *name_a,
1328 struct diff_filespec *one,
1329 struct diff_filespec *two,
1330 struct userdiff_driver *textconv_one,
1331 struct userdiff_driver *textconv_two,
1332 struct diff_options *o)
1335 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1336 const char *a_prefix, *b_prefix;
1337 char *data_one, *data_two;
1338 size_t size_one, size_two;
1339 struct emit_callback ecbdata;
1340 struct strbuf out = STRBUF_INIT;
1342 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
1343 a_prefix = o->b_prefix;
1344 b_prefix = o->a_prefix;
1346 a_prefix = o->a_prefix;
1347 b_prefix = o->b_prefix;
1350 name_a += (*name_a == '/');
1351 name_b += (*name_b == '/');
1353 strbuf_reset(&a_name);
1354 strbuf_reset(&b_name);
1355 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1356 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1358 size_one = fill_textconv(textconv_one, one, &data_one);
1359 size_two = fill_textconv(textconv_two, two, &data_two);
1361 memset(&ecbdata, 0, sizeof(ecbdata));
1362 ecbdata.color_diff = want_color(o->use_color);
1363 ecbdata.ws_rule = whitespace_rule(name_b);
1365 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1367 mf1.ptr = (char *)data_one;
1368 mf2.ptr = (char *)data_two;
1369 mf1.size = size_one;
1370 mf2.size = size_two;
1371 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1373 ecbdata.lno_in_preimage = 1;
1374 ecbdata.lno_in_postimage = 1;
1376 lc_a = count_lines(data_one, size_one);
1377 lc_b = count_lines(data_two, size_two);
1379 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1380 a_name.buf, a_name.len, 0);
1381 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1382 b_name.buf, b_name.len, 0);
1384 strbuf_addstr(&out, "@@ -");
1385 if (!o->irreversible_delete)
1386 add_line_count(&out, lc_a);
1388 strbuf_addstr(&out, "?,?");
1389 strbuf_addstr(&out, " +");
1390 add_line_count(&out, lc_b);
1391 strbuf_addstr(&out, " @@\n");
1392 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1393 strbuf_release(&out);
1395 if (lc_a && !o->irreversible_delete)
1396 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1398 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1400 free((char *)data_one);
1402 free((char *)data_two);
1405 struct diff_words_buffer {
1408 struct diff_words_orig {
1409 const char *begin, *end;
1411 int orig_nr, orig_alloc;
1414 static void diff_words_append(char *line, unsigned long len,
1415 struct diff_words_buffer *buffer)
1417 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1420 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1421 buffer->text.size += len;
1422 buffer->text.ptr[buffer->text.size] = '\0';
1425 struct diff_words_style_elem {
1428 const char *color; /* NULL; filled in by the setup code if
1429 * color is enabled */
1432 struct diff_words_style {
1433 enum diff_words_type type;
1434 struct diff_words_style_elem new, old, ctx;
1435 const char *newline;
1438 static struct diff_words_style diff_words_styles[] = {
1439 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1440 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1441 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1444 struct diff_words_data {
1445 struct diff_words_buffer minus, plus;
1446 const char *current_plus;
1448 struct diff_options *opt;
1449 regex_t *word_regex;
1450 enum diff_words_type type;
1451 struct diff_words_style *style;
1454 static int fn_out_diff_words_write_helper(struct diff_options *o,
1455 struct diff_words_style_elem *st_el,
1456 const char *newline,
1457 size_t count, const char *buf)
1460 struct strbuf sb = STRBUF_INIT;
1463 char *p = memchr(buf, '\n', count);
1465 strbuf_addstr(&sb, diff_line_prefix(o));
1468 const char *reset = st_el->color && *st_el->color ?
1469 GIT_COLOR_RESET : NULL;
1470 if (st_el->color && *st_el->color)
1471 strbuf_addstr(&sb, st_el->color);
1472 strbuf_addstr(&sb, st_el->prefix);
1473 strbuf_add(&sb, buf, p ? p - buf : count);
1474 strbuf_addstr(&sb, st_el->suffix);
1476 strbuf_addstr(&sb, reset);
1481 strbuf_addstr(&sb, newline);
1482 count -= p + 1 - buf;
1486 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1494 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1496 strbuf_release(&sb);
1501 * '--color-words' algorithm can be described as:
1503 * 1. collect the minus/plus lines of a diff hunk, divided into
1504 * minus-lines and plus-lines;
1506 * 2. break both minus-lines and plus-lines into words and
1507 * place them into two mmfile_t with one word for each line;
1509 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1511 * And for the common parts of the both file, we output the plus side text.
1512 * diff_words->current_plus is used to trace the current position of the plus file
1513 * which printed. diff_words->last_minus is used to trace the last minus word
1516 * For '--graph' to work with '--color-words', we need to output the graph prefix
1517 * on each line of color words output. Generally, there are two conditions on
1518 * which we should output the prefix.
1520 * 1. diff_words->last_minus == 0 &&
1521 * diff_words->current_plus == diff_words->plus.text.ptr
1523 * that is: the plus text must start as a new line, and if there is no minus
1524 * word printed, a graph prefix must be printed.
1526 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1527 * *(diff_words->current_plus - 1) == '\n'
1529 * that is: a graph prefix must be printed following a '\n'
1531 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1533 if ((diff_words->last_minus == 0 &&
1534 diff_words->current_plus == diff_words->plus.text.ptr) ||
1535 (diff_words->current_plus > diff_words->plus.text.ptr &&
1536 *(diff_words->current_plus - 1) == '\n')) {
1543 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
1545 struct diff_words_data *diff_words = priv;
1546 struct diff_words_style *style = diff_words->style;
1547 int minus_first, minus_len, plus_first, plus_len;
1548 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1549 struct diff_options *opt = diff_words->opt;
1550 const char *line_prefix;
1552 if (line[0] != '@' || parse_hunk_header(line, len,
1553 &minus_first, &minus_len, &plus_first, &plus_len))
1557 line_prefix = diff_line_prefix(opt);
1559 /* POSIX requires that first be decremented by one if len == 0... */
1561 minus_begin = diff_words->minus.orig[minus_first].begin;
1563 diff_words->minus.orig[minus_first + minus_len - 1].end;
1565 minus_begin = minus_end =
1566 diff_words->minus.orig[minus_first].end;
1569 plus_begin = diff_words->plus.orig[plus_first].begin;
1570 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1572 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1574 if (color_words_output_graph_prefix(diff_words)) {
1575 fputs(line_prefix, diff_words->opt->file);
1577 if (diff_words->current_plus != plus_begin) {
1578 fn_out_diff_words_write_helper(diff_words->opt,
1579 &style->ctx, style->newline,
1580 plus_begin - diff_words->current_plus,
1581 diff_words->current_plus);
1583 if (minus_begin != minus_end) {
1584 fn_out_diff_words_write_helper(diff_words->opt,
1585 &style->old, style->newline,
1586 minus_end - minus_begin, minus_begin);
1588 if (plus_begin != plus_end) {
1589 fn_out_diff_words_write_helper(diff_words->opt,
1590 &style->new, style->newline,
1591 plus_end - plus_begin, plus_begin);
1594 diff_words->current_plus = plus_end;
1595 diff_words->last_minus = minus_first;
1598 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1599 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1600 int *begin, int *end)
1602 if (word_regex && *begin < buffer->size) {
1603 regmatch_t match[1];
1604 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1605 buffer->size - *begin, 1, match, 0)) {
1606 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1607 '\n', match[0].rm_eo - match[0].rm_so);
1608 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1609 *begin += match[0].rm_so;
1610 return *begin >= *end;
1615 /* find the next word */
1616 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1618 if (*begin >= buffer->size)
1621 /* find the end of the word */
1623 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1630 * This function splits the words in buffer->text, stores the list with
1631 * newline separator into out, and saves the offsets of the original words
1634 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1635 regex_t *word_regex)
1643 /* fake an empty "0th" word */
1644 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1645 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1646 buffer->orig_nr = 1;
1648 for (i = 0; i < buffer->text.size; i++) {
1649 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1652 /* store original boundaries */
1653 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1654 buffer->orig_alloc);
1655 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1656 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1659 /* store one word */
1660 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1661 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1662 out->ptr[out->size + j - i] = '\n';
1663 out->size += j - i + 1;
1669 /* this executes the word diff on the accumulated buffers */
1670 static void diff_words_show(struct diff_words_data *diff_words)
1674 mmfile_t minus, plus;
1675 struct diff_words_style *style = diff_words->style;
1677 struct diff_options *opt = diff_words->opt;
1678 const char *line_prefix;
1681 line_prefix = diff_line_prefix(opt);
1683 /* special case: only removal */
1684 if (!diff_words->plus.text.size) {
1685 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1686 line_prefix, strlen(line_prefix), 0);
1687 fn_out_diff_words_write_helper(diff_words->opt,
1688 &style->old, style->newline,
1689 diff_words->minus.text.size,
1690 diff_words->minus.text.ptr);
1691 diff_words->minus.text.size = 0;
1695 diff_words->current_plus = diff_words->plus.text.ptr;
1696 diff_words->last_minus = 0;
1698 memset(&xpp, 0, sizeof(xpp));
1699 memset(&xecfg, 0, sizeof(xecfg));
1700 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1701 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1703 /* as only the hunk header will be parsed, we need a 0-context */
1705 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1707 die("unable to generate word diff");
1710 if (diff_words->current_plus != diff_words->plus.text.ptr +
1711 diff_words->plus.text.size) {
1712 if (color_words_output_graph_prefix(diff_words))
1713 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1714 line_prefix, strlen(line_prefix), 0);
1715 fn_out_diff_words_write_helper(diff_words->opt,
1716 &style->ctx, style->newline,
1717 diff_words->plus.text.ptr + diff_words->plus.text.size
1718 - diff_words->current_plus, diff_words->current_plus);
1720 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1723 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1724 static void diff_words_flush(struct emit_callback *ecbdata)
1726 struct diff_options *wo = ecbdata->diff_words->opt;
1728 if (ecbdata->diff_words->minus.text.size ||
1729 ecbdata->diff_words->plus.text.size)
1730 diff_words_show(ecbdata->diff_words);
1732 if (wo->emitted_symbols) {
1733 struct diff_options *o = ecbdata->opt;
1734 struct emitted_diff_symbols *wol = wo->emitted_symbols;
1739 * Instead of appending each, concat all words to a line?
1741 for (i = 0; i < wol->nr; i++)
1742 append_emitted_diff_symbol(o, &wol->buf[i]);
1744 for (i = 0; i < wol->nr; i++)
1745 free((void *)wol->buf[i].line);
1751 static void diff_filespec_load_driver(struct diff_filespec *one)
1753 /* Use already-loaded driver */
1757 if (S_ISREG(one->mode))
1758 one->driver = userdiff_find_by_path(one->path);
1760 /* Fallback to default settings */
1762 one->driver = userdiff_find_by_name("default");
1765 static const char *userdiff_word_regex(struct diff_filespec *one)
1767 diff_filespec_load_driver(one);
1768 return one->driver->word_regex;
1771 static void init_diff_words_data(struct emit_callback *ecbdata,
1772 struct diff_options *orig_opts,
1773 struct diff_filespec *one,
1774 struct diff_filespec *two)
1777 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1778 memcpy(o, orig_opts, sizeof(struct diff_options));
1780 ecbdata->diff_words =
1781 xcalloc(1, sizeof(struct diff_words_data));
1782 ecbdata->diff_words->type = o->word_diff;
1783 ecbdata->diff_words->opt = o;
1785 if (orig_opts->emitted_symbols)
1786 o->emitted_symbols =
1787 xcalloc(1, sizeof(struct emitted_diff_symbols));
1790 o->word_regex = userdiff_word_regex(one);
1792 o->word_regex = userdiff_word_regex(two);
1794 o->word_regex = diff_word_regex_cfg;
1795 if (o->word_regex) {
1796 ecbdata->diff_words->word_regex = (regex_t *)
1797 xmalloc(sizeof(regex_t));
1798 if (regcomp(ecbdata->diff_words->word_regex,
1800 REG_EXTENDED | REG_NEWLINE))
1801 die ("Invalid regular expression: %s",
1804 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1805 if (o->word_diff == diff_words_styles[i].type) {
1806 ecbdata->diff_words->style =
1807 &diff_words_styles[i];
1811 if (want_color(o->use_color)) {
1812 struct diff_words_style *st = ecbdata->diff_words->style;
1813 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1814 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1815 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1819 static void free_diff_words_data(struct emit_callback *ecbdata)
1821 if (ecbdata->diff_words) {
1822 diff_words_flush(ecbdata);
1823 free (ecbdata->diff_words->opt->emitted_symbols);
1824 free (ecbdata->diff_words->opt);
1825 free (ecbdata->diff_words->minus.text.ptr);
1826 free (ecbdata->diff_words->minus.orig);
1827 free (ecbdata->diff_words->plus.text.ptr);
1828 free (ecbdata->diff_words->plus.orig);
1829 if (ecbdata->diff_words->word_regex) {
1830 regfree(ecbdata->diff_words->word_regex);
1831 free(ecbdata->diff_words->word_regex);
1833 FREE_AND_NULL(ecbdata->diff_words);
1837 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1839 if (want_color(diff_use_color))
1840 return diff_colors[ix];
1844 const char *diff_line_prefix(struct diff_options *opt)
1846 struct strbuf *msgbuf;
1847 if (!opt->output_prefix)
1850 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1854 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1857 unsigned long allot;
1861 return ecb->truncate(line, len);
1865 (void) utf8_width(&cp, &l);
1867 break; /* truncated in the middle? */
1872 static void find_lno(const char *line, struct emit_callback *ecbdata)
1875 ecbdata->lno_in_preimage = 0;
1876 ecbdata->lno_in_postimage = 0;
1877 p = strchr(line, '-');
1879 return; /* cannot happen */
1880 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1883 return; /* cannot happen */
1884 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1887 static void fn_out_consume(void *priv, char *line, unsigned long len)
1889 struct emit_callback *ecbdata = priv;
1890 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1891 struct diff_options *o = ecbdata->opt;
1893 o->found_changes = 1;
1895 if (ecbdata->header) {
1896 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
1897 ecbdata->header->buf, ecbdata->header->len, 0);
1898 strbuf_reset(ecbdata->header);
1899 ecbdata->header = NULL;
1902 if (ecbdata->label_path[0]) {
1903 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1904 ecbdata->label_path[0],
1905 strlen(ecbdata->label_path[0]), 0);
1906 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1907 ecbdata->label_path[1],
1908 strlen(ecbdata->label_path[1]), 0);
1909 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1912 if (diff_suppress_blank_empty
1913 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1918 if (line[0] == '@') {
1919 if (ecbdata->diff_words)
1920 diff_words_flush(ecbdata);
1921 len = sane_truncate_line(ecbdata, line, len);
1922 find_lno(line, ecbdata);
1923 emit_hunk_header(ecbdata, line, len);
1927 if (ecbdata->diff_words) {
1928 enum diff_symbol s =
1929 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
1930 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
1931 if (line[0] == '-') {
1932 diff_words_append(line, len,
1933 &ecbdata->diff_words->minus);
1935 } else if (line[0] == '+') {
1936 diff_words_append(line, len,
1937 &ecbdata->diff_words->plus);
1939 } else if (starts_with(line, "\\ ")) {
1941 * Eat the "no newline at eof" marker as if we
1942 * saw a "+" or "-" line with nothing on it,
1943 * and return without diff_words_flush() to
1944 * defer processing. If this is the end of
1945 * preimage, more "+" lines may come after it.
1949 diff_words_flush(ecbdata);
1950 emit_diff_symbol(o, s, line, len, 0);
1956 ecbdata->lno_in_postimage++;
1957 emit_add_line(reset, ecbdata, line + 1, len - 1);
1960 ecbdata->lno_in_preimage++;
1961 emit_del_line(reset, ecbdata, line + 1, len - 1);
1964 ecbdata->lno_in_postimage++;
1965 ecbdata->lno_in_preimage++;
1966 emit_context_line(reset, ecbdata, line + 1, len - 1);
1969 /* incomplete line at the end */
1970 ecbdata->lno_in_preimage++;
1971 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
1977 static char *pprint_rename(const char *a, const char *b)
1979 const char *old = a;
1980 const char *new = b;
1981 struct strbuf name = STRBUF_INIT;
1982 int pfx_length, sfx_length;
1983 int pfx_adjust_for_slash;
1984 int len_a = strlen(a);
1985 int len_b = strlen(b);
1986 int a_midlen, b_midlen;
1987 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1988 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1990 if (qlen_a || qlen_b) {
1991 quote_c_style(a, &name, NULL, 0);
1992 strbuf_addstr(&name, " => ");
1993 quote_c_style(b, &name, NULL, 0);
1994 return strbuf_detach(&name, NULL);
1997 /* Find common prefix */
1999 while (*old && *new && *old == *new) {
2001 pfx_length = old - a + 1;
2006 /* Find common suffix */
2011 * If there is a common prefix, it must end in a slash. In
2012 * that case we let this loop run 1 into the prefix to see the
2015 * If there is no common prefix, we cannot do this as it would
2016 * underrun the input strings.
2018 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2019 while (a + pfx_length - pfx_adjust_for_slash <= old &&
2020 b + pfx_length - pfx_adjust_for_slash <= new &&
2023 sfx_length = len_a - (old - a);
2029 * pfx{mid-a => mid-b}sfx
2030 * {pfx-a => pfx-b}sfx
2031 * pfx{sfx-a => sfx-b}
2034 a_midlen = len_a - pfx_length - sfx_length;
2035 b_midlen = len_b - pfx_length - sfx_length;
2041 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2042 if (pfx_length + sfx_length) {
2043 strbuf_add(&name, a, pfx_length);
2044 strbuf_addch(&name, '{');
2046 strbuf_add(&name, a + pfx_length, a_midlen);
2047 strbuf_addstr(&name, " => ");
2048 strbuf_add(&name, b + pfx_length, b_midlen);
2049 if (pfx_length + sfx_length) {
2050 strbuf_addch(&name, '}');
2051 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
2053 return strbuf_detach(&name, NULL);
2059 struct diffstat_file {
2063 unsigned is_unmerged:1;
2064 unsigned is_binary:1;
2065 unsigned is_renamed:1;
2066 unsigned is_interesting:1;
2067 uintmax_t added, deleted;
2071 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2075 struct diffstat_file *x;
2076 x = xcalloc(1, sizeof(*x));
2077 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2078 diffstat->files[diffstat->nr++] = x;
2080 x->from_name = xstrdup(name_a);
2081 x->name = xstrdup(name_b);
2085 x->from_name = NULL;
2086 x->name = xstrdup(name_a);
2091 static void diffstat_consume(void *priv, char *line, unsigned long len)
2093 struct diffstat_t *diffstat = priv;
2094 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2098 else if (line[0] == '-')
2102 const char mime_boundary_leader[] = "------------";
2104 static int scale_linear(int it, int width, int max_change)
2109 * make sure that at least one '-' or '+' is printed if
2110 * there is any change to this path. The easiest way is to
2111 * scale linearly as if the alloted width is one column shorter
2112 * than it is, and then add 1 to the result.
2114 return 1 + (it * (width - 1) / max_change);
2117 static void show_graph(struct strbuf *out, char ch, int cnt,
2118 const char *set, const char *reset)
2122 strbuf_addstr(out, set);
2123 strbuf_addchars(out, ch, cnt);
2124 strbuf_addstr(out, reset);
2127 static void fill_print_name(struct diffstat_file *file)
2131 if (file->print_name)
2134 if (!file->is_renamed) {
2135 struct strbuf buf = STRBUF_INIT;
2136 if (quote_c_style(file->name, &buf, NULL, 0)) {
2137 pname = strbuf_detach(&buf, NULL);
2140 strbuf_release(&buf);
2143 pname = pprint_rename(file->from_name, file->name);
2145 file->print_name = pname;
2148 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2149 int files, int insertions, int deletions)
2151 struct strbuf sb = STRBUF_INIT;
2154 assert(insertions == 0 && deletions == 0);
2155 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2161 (files == 1) ? " %d file changed" : " %d files changed",
2165 * For binary diff, the caller may want to print "x files
2166 * changed" with insertions == 0 && deletions == 0.
2168 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2169 * is probably less confusing (i.e skip over "2 files changed
2170 * but nothing about added/removed lines? Is this a bug in Git?").
2172 if (insertions || deletions == 0) {
2174 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2178 if (deletions || insertions == 0) {
2180 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2183 strbuf_addch(&sb, '\n');
2184 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2186 strbuf_release(&sb);
2189 void print_stat_summary(FILE *fp, int files,
2190 int insertions, int deletions)
2192 struct diff_options o;
2193 memset(&o, 0, sizeof(o));
2196 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2199 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2201 int i, len, add, del, adds = 0, dels = 0;
2202 uintmax_t max_change = 0, max_len = 0;
2203 int total_files = data->nr, count;
2204 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2205 const char *reset, *add_c, *del_c;
2206 int extra_shown = 0;
2207 const char *line_prefix = diff_line_prefix(options);
2208 struct strbuf out = STRBUF_INIT;
2213 count = options->stat_count ? options->stat_count : data->nr;
2215 reset = diff_get_color_opt(options, DIFF_RESET);
2216 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2217 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2220 * Find the longest filename and max number of changes
2222 for (i = 0; (i < count) && (i < data->nr); i++) {
2223 struct diffstat_file *file = data->files[i];
2224 uintmax_t change = file->added + file->deleted;
2226 if (!file->is_interesting && (change == 0)) {
2227 count++; /* not shown == room for one more */
2230 fill_print_name(file);
2231 len = strlen(file->print_name);
2235 if (file->is_unmerged) {
2236 /* "Unmerged" is 8 characters */
2237 bin_width = bin_width < 8 ? 8 : bin_width;
2240 if (file->is_binary) {
2241 /* "Bin XXX -> YYY bytes" */
2242 int w = 14 + decimal_width(file->added)
2243 + decimal_width(file->deleted);
2244 bin_width = bin_width < w ? w : bin_width;
2245 /* Display change counts aligned with "Bin" */
2250 if (max_change < change)
2251 max_change = change;
2253 count = i; /* where we can stop scanning in data->files[] */
2256 * We have width = stat_width or term_columns() columns total.
2257 * We want a maximum of min(max_len, stat_name_width) for the name part.
2258 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2259 * We also need 1 for " " and 4 + decimal_width(max_change)
2260 * for " | NNNN " and one the empty column at the end, altogether
2261 * 6 + decimal_width(max_change).
2263 * If there's not enough space, we will use the smaller of
2264 * stat_name_width (if set) and 5/8*width for the filename,
2265 * and the rest for constant elements + graph part, but no more
2266 * than stat_graph_width for the graph part.
2267 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2268 * for the standard terminal size).
2270 * In other words: stat_width limits the maximum width, and
2271 * stat_name_width fixes the maximum width of the filename,
2272 * and is also used to divide available columns if there
2275 * Binary files are displayed with "Bin XXX -> YYY bytes"
2276 * instead of the change count and graph. This part is treated
2277 * similarly to the graph part, except that it is not
2278 * "scaled". If total width is too small to accommodate the
2279 * guaranteed minimum width of the filename part and the
2280 * separators and this message, this message will "overflow"
2281 * making the line longer than the maximum width.
2284 if (options->stat_width == -1)
2285 width = term_columns() - strlen(line_prefix);
2287 width = options->stat_width ? options->stat_width : 80;
2288 number_width = decimal_width(max_change) > number_width ?
2289 decimal_width(max_change) : number_width;
2291 if (options->stat_graph_width == -1)
2292 options->stat_graph_width = diff_stat_graph_width;
2295 * Guarantee 3/8*16==6 for the graph part
2296 * and 5/8*16==10 for the filename part
2298 if (width < 16 + 6 + number_width)
2299 width = 16 + 6 + number_width;
2302 * First assign sizes that are wanted, ignoring available width.
2303 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2304 * starting from "XXX" should fit in graph_width.
2306 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2307 if (options->stat_graph_width &&
2308 options->stat_graph_width < graph_width)
2309 graph_width = options->stat_graph_width;
2311 name_width = (options->stat_name_width > 0 &&
2312 options->stat_name_width < max_len) ?
2313 options->stat_name_width : max_len;
2316 * Adjust adjustable widths not to exceed maximum width
2318 if (name_width + number_width + 6 + graph_width > width) {
2319 if (graph_width > width * 3/8 - number_width - 6) {
2320 graph_width = width * 3/8 - number_width - 6;
2321 if (graph_width < 6)
2325 if (options->stat_graph_width &&
2326 graph_width > options->stat_graph_width)
2327 graph_width = options->stat_graph_width;
2328 if (name_width > width - number_width - 6 - graph_width)
2329 name_width = width - number_width - 6 - graph_width;
2331 graph_width = width - number_width - 6 - name_width;
2335 * From here name_width is the width of the name area,
2336 * and graph_width is the width of the graph area.
2337 * max_change is used to scale graph properly.
2339 for (i = 0; i < count; i++) {
2340 const char *prefix = "";
2341 struct diffstat_file *file = data->files[i];
2342 char *name = file->print_name;
2343 uintmax_t added = file->added;
2344 uintmax_t deleted = file->deleted;
2347 if (!file->is_interesting && (added + deleted == 0))
2351 * "scale" the filename
2354 name_len = strlen(name);
2355 if (name_width < name_len) {
2359 name += name_len - len;
2360 slash = strchr(name, '/');
2365 if (file->is_binary) {
2366 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2367 strbuf_addf(&out, " %*s", number_width, "Bin");
2368 if (!added && !deleted) {
2369 strbuf_addch(&out, '\n');
2370 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2371 out.buf, out.len, 0);
2375 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2376 del_c, deleted, reset);
2377 strbuf_addstr(&out, " -> ");
2378 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2379 add_c, added, reset);
2380 strbuf_addstr(&out, " bytes\n");
2381 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2382 out.buf, out.len, 0);
2386 else if (file->is_unmerged) {
2387 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2388 strbuf_addstr(&out, " Unmerged\n");
2389 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2390 out.buf, out.len, 0);
2396 * scale the add/delete
2401 if (graph_width <= max_change) {
2402 int total = scale_linear(add + del, graph_width, max_change);
2403 if (total < 2 && add && del)
2404 /* width >= 2 due to the sanity check */
2407 add = scale_linear(add, graph_width, max_change);
2410 del = scale_linear(del, graph_width, max_change);
2414 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2415 strbuf_addf(&out, " %*"PRIuMAX"%s",
2416 number_width, added + deleted,
2417 added + deleted ? " " : "");
2418 show_graph(&out, '+', add, add_c, reset);
2419 show_graph(&out, '-', del, del_c, reset);
2420 strbuf_addch(&out, '\n');
2421 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2422 out.buf, out.len, 0);
2426 for (i = 0; i < data->nr; i++) {
2427 struct diffstat_file *file = data->files[i];
2428 uintmax_t added = file->added;
2429 uintmax_t deleted = file->deleted;
2431 if (file->is_unmerged ||
2432 (!file->is_interesting && (added + deleted == 0))) {
2437 if (!file->is_binary) {
2444 emit_diff_symbol(options,
2445 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2450 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2453 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2455 int i, adds = 0, dels = 0, total_files = data->nr;
2460 for (i = 0; i < data->nr; i++) {
2461 int added = data->files[i]->added;
2462 int deleted = data->files[i]->deleted;
2464 if (data->files[i]->is_unmerged ||
2465 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2467 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2472 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2475 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2482 for (i = 0; i < data->nr; i++) {
2483 struct diffstat_file *file = data->files[i];
2485 fprintf(options->file, "%s", diff_line_prefix(options));
2487 if (file->is_binary)
2488 fprintf(options->file, "-\t-\t");
2490 fprintf(options->file,
2491 "%"PRIuMAX"\t%"PRIuMAX"\t",
2492 file->added, file->deleted);
2493 if (options->line_termination) {
2494 fill_print_name(file);
2495 if (!file->is_renamed)
2496 write_name_quoted(file->name, options->file,
2497 options->line_termination);
2499 fputs(file->print_name, options->file);
2500 putc(options->line_termination, options->file);
2503 if (file->is_renamed) {
2504 putc('\0', options->file);
2505 write_name_quoted(file->from_name, options->file, '\0');
2507 write_name_quoted(file->name, options->file, '\0');
2512 struct dirstat_file {
2514 unsigned long changed;
2517 struct dirstat_dir {
2518 struct dirstat_file *files;
2519 int alloc, nr, permille, cumulative;
2522 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2523 unsigned long changed, const char *base, int baselen)
2525 unsigned long this_dir = 0;
2526 unsigned int sources = 0;
2527 const char *line_prefix = diff_line_prefix(opt);
2530 struct dirstat_file *f = dir->files;
2531 int namelen = strlen(f->name);
2535 if (namelen < baselen)
2537 if (memcmp(f->name, base, baselen))
2539 slash = strchr(f->name + baselen, '/');
2541 int newbaselen = slash + 1 - f->name;
2542 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2554 * We don't report dirstat's for
2556 * - or cases where everything came from a single directory
2557 * under this directory (sources == 1).
2559 if (baselen && sources != 1) {
2561 int permille = this_dir * 1000 / changed;
2562 if (permille >= dir->permille) {
2563 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2564 permille / 10, permille % 10, baselen, base);
2565 if (!dir->cumulative)
2573 static int dirstat_compare(const void *_a, const void *_b)
2575 const struct dirstat_file *a = _a;
2576 const struct dirstat_file *b = _b;
2577 return strcmp(a->name, b->name);
2580 static void show_dirstat(struct diff_options *options)
2583 unsigned long changed;
2584 struct dirstat_dir dir;
2585 struct diff_queue_struct *q = &diff_queued_diff;
2590 dir.permille = options->dirstat_permille;
2591 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2594 for (i = 0; i < q->nr; i++) {
2595 struct diff_filepair *p = q->queue[i];
2597 unsigned long copied, added, damage;
2598 int content_changed;
2600 name = p->two->path ? p->two->path : p->one->path;
2602 if (p->one->oid_valid && p->two->oid_valid)
2603 content_changed = oidcmp(&p->one->oid, &p->two->oid);
2605 content_changed = 1;
2607 if (!content_changed) {
2609 * The SHA1 has not changed, so pre-/post-content is
2610 * identical. We can therefore skip looking at the
2611 * file contents altogether.
2617 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
2619 * In --dirstat-by-file mode, we don't really need to
2620 * look at the actual file contents at all.
2621 * The fact that the SHA1 changed is enough for us to
2622 * add this file to the list of results
2623 * (with each file contributing equal damage).
2629 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2630 diff_populate_filespec(p->one, 0);
2631 diff_populate_filespec(p->two, 0);
2632 diffcore_count_changes(p->one, p->two, NULL, NULL,
2634 diff_free_filespec_data(p->one);
2635 diff_free_filespec_data(p->two);
2636 } else if (DIFF_FILE_VALID(p->one)) {
2637 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2639 diff_free_filespec_data(p->one);
2640 } else if (DIFF_FILE_VALID(p->two)) {
2641 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
2643 added = p->two->size;
2644 diff_free_filespec_data(p->two);
2649 * Original minus copied is the removed material,
2650 * added is the new material. They are both damages
2651 * made to the preimage.
2652 * If the resulting damage is zero, we know that
2653 * diffcore_count_changes() considers the two entries to
2654 * be identical, but since content_changed is true, we
2655 * know that there must have been _some_ kind of change,
2656 * so we force all entries to have damage > 0.
2658 damage = (p->one->size - copied) + added;
2663 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2664 dir.files[dir.nr].name = name;
2665 dir.files[dir.nr].changed = damage;
2670 /* This can happen even with many files, if everything was renames */
2674 /* Show all directories with more than x% of the changes */
2675 QSORT(dir.files, dir.nr, dirstat_compare);
2676 gather_dirstat(options, &dir, changed, "", 0);
2679 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2682 unsigned long changed;
2683 struct dirstat_dir dir;
2691 dir.permille = options->dirstat_permille;
2692 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2695 for (i = 0; i < data->nr; i++) {
2696 struct diffstat_file *file = data->files[i];
2697 unsigned long damage = file->added + file->deleted;
2698 if (file->is_binary)
2700 * binary files counts bytes, not lines. Must find some
2701 * way to normalize binary bytes vs. textual lines.
2702 * The following heuristic assumes that there are 64
2704 * This is stupid and ugly, but very cheap...
2706 damage = (damage + 63) / 64;
2707 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2708 dir.files[dir.nr].name = file->name;
2709 dir.files[dir.nr].changed = damage;
2714 /* This can happen even with many files, if everything was renames */
2718 /* Show all directories with more than x% of the changes */
2719 QSORT(dir.files, dir.nr, dirstat_compare);
2720 gather_dirstat(options, &dir, changed, "", 0);
2723 static void free_diffstat_info(struct diffstat_t *diffstat)
2726 for (i = 0; i < diffstat->nr; i++) {
2727 struct diffstat_file *f = diffstat->files[i];
2728 if (f->name != f->print_name)
2729 free(f->print_name);
2734 free(diffstat->files);
2737 struct checkdiff_t {
2738 const char *filename;
2740 int conflict_marker_size;
2741 struct diff_options *o;
2746 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2751 if (len < marker_size + 1)
2753 firstchar = line[0];
2754 switch (firstchar) {
2755 case '=': case '>': case '<': case '|':
2760 for (cnt = 1; cnt < marker_size; cnt++)
2761 if (line[cnt] != firstchar)
2763 /* line[1] thru line[marker_size-1] are same as firstchar */
2764 if (len < marker_size + 1 || !isspace(line[marker_size]))
2769 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2771 struct checkdiff_t *data = priv;
2772 int marker_size = data->conflict_marker_size;
2773 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2774 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2775 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2777 const char *line_prefix;
2780 line_prefix = diff_line_prefix(data->o);
2782 if (line[0] == '+') {
2785 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2787 fprintf(data->o->file,
2788 "%s%s:%d: leftover conflict marker\n",
2789 line_prefix, data->filename, data->lineno);
2791 bad = ws_check(line + 1, len - 1, data->ws_rule);
2794 data->status |= bad;
2795 err = whitespace_error_string(bad);
2796 fprintf(data->o->file, "%s%s:%d: %s.\n",
2797 line_prefix, data->filename, data->lineno, err);
2799 emit_line(data->o, set, reset, line, 1);
2800 ws_check_emit(line + 1, len - 1, data->ws_rule,
2801 data->o->file, set, reset, ws);
2802 } else if (line[0] == ' ') {
2804 } else if (line[0] == '@') {
2805 char *plus = strchr(line, '+');
2807 data->lineno = strtol(plus, NULL, 10) - 1;
2809 die("invalid diff");
2813 static unsigned char *deflate_it(char *data,
2815 unsigned long *result_size)
2818 unsigned char *deflated;
2821 git_deflate_init(&stream, zlib_compression_level);
2822 bound = git_deflate_bound(&stream, size);
2823 deflated = xmalloc(bound);
2824 stream.next_out = deflated;
2825 stream.avail_out = bound;
2827 stream.next_in = (unsigned char *)data;
2828 stream.avail_in = size;
2829 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2831 git_deflate_end(&stream);
2832 *result_size = stream.total_out;
2836 static void emit_binary_diff_body(struct diff_options *o,
2837 mmfile_t *one, mmfile_t *two)
2843 unsigned long orig_size;
2844 unsigned long delta_size;
2845 unsigned long deflate_size;
2846 unsigned long data_size;
2848 /* We could do deflated delta, or we could do just deflated two,
2849 * whichever is smaller.
2852 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2853 if (one->size && two->size) {
2854 delta = diff_delta(one->ptr, one->size,
2855 two->ptr, two->size,
2856 &delta_size, deflate_size);
2858 void *to_free = delta;
2859 orig_size = delta_size;
2860 delta = deflate_it(delta, delta_size, &delta_size);
2865 if (delta && delta_size < deflate_size) {
2866 char *s = xstrfmt("%lu", orig_size);
2867 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
2872 data_size = delta_size;
2874 char *s = xstrfmt("%lu", two->size);
2875 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
2880 data_size = deflate_size;
2883 /* emit data encoded in base85 */
2887 int bytes = (52 < data_size) ? 52 : data_size;
2891 line[0] = bytes + 'A' - 1;
2893 line[0] = bytes - 26 + 'a' - 1;
2894 encode_85(line + 1, cp, bytes);
2895 cp = (char *) cp + bytes;
2901 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
2904 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
2908 static void emit_binary_diff(struct diff_options *o,
2909 mmfile_t *one, mmfile_t *two)
2911 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
2912 emit_binary_diff_body(o, one, two);
2913 emit_binary_diff_body(o, two, one);
2916 int diff_filespec_is_binary(struct diff_filespec *one)
2918 if (one->is_binary == -1) {
2919 diff_filespec_load_driver(one);
2920 if (one->driver->binary != -1)
2921 one->is_binary = one->driver->binary;
2923 if (!one->data && DIFF_FILE_VALID(one))
2924 diff_populate_filespec(one, CHECK_BINARY);
2925 if (one->is_binary == -1 && one->data)
2926 one->is_binary = buffer_is_binary(one->data,
2928 if (one->is_binary == -1)
2932 return one->is_binary;
2935 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2937 diff_filespec_load_driver(one);
2938 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2941 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2943 if (!options->a_prefix)
2944 options->a_prefix = a;
2945 if (!options->b_prefix)
2946 options->b_prefix = b;
2949 struct userdiff_driver *get_textconv(struct diff_filespec *one)
2951 if (!DIFF_FILE_VALID(one))
2954 diff_filespec_load_driver(one);
2955 return userdiff_get_textconv(one->driver);
2958 static void builtin_diff(const char *name_a,
2960 struct diff_filespec *one,
2961 struct diff_filespec *two,
2962 const char *xfrm_msg,
2963 int must_show_header,
2964 struct diff_options *o,
2965 int complete_rewrite)
2969 char *a_one, *b_two;
2970 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
2971 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2972 const char *a_prefix, *b_prefix;
2973 struct userdiff_driver *textconv_one = NULL;
2974 struct userdiff_driver *textconv_two = NULL;
2975 struct strbuf header = STRBUF_INIT;
2976 const char *line_prefix = diff_line_prefix(o);
2978 diff_set_mnemonic_prefix(o, "a/", "b/");
2979 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2980 a_prefix = o->b_prefix;
2981 b_prefix = o->a_prefix;
2983 a_prefix = o->a_prefix;
2984 b_prefix = o->b_prefix;
2987 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
2988 (!one->mode || S_ISGITLINK(one->mode)) &&
2989 (!two->mode || S_ISGITLINK(two->mode))) {
2990 show_submodule_summary(o, one->path ? one->path : two->path,
2991 &one->oid, &two->oid,
2992 two->dirty_submodule);
2994 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
2995 (!one->mode || S_ISGITLINK(one->mode)) &&
2996 (!two->mode || S_ISGITLINK(two->mode))) {
2997 show_submodule_inline_diff(o, one->path ? one->path : two->path,
2998 &one->oid, &two->oid,
2999 two->dirty_submodule);
3003 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
3004 textconv_one = get_textconv(one);
3005 textconv_two = get_textconv(two);
3008 /* Never use a non-valid filename anywhere if at all possible */
3009 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3010 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3012 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3013 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3014 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3015 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3016 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3017 if (lbl[0][0] == '/') {
3019 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3021 strbuf_addstr(&header, xfrm_msg);
3022 must_show_header = 1;
3024 else if (lbl[1][0] == '/') {
3025 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3027 strbuf_addstr(&header, xfrm_msg);
3028 must_show_header = 1;
3031 if (one->mode != two->mode) {
3032 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3033 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3034 must_show_header = 1;
3037 strbuf_addstr(&header, xfrm_msg);
3040 * we do not run diff between different kind
3043 if ((one->mode ^ two->mode) & S_IFMT)
3044 goto free_ab_and_return;
3045 if (complete_rewrite &&
3046 (textconv_one || !diff_filespec_is_binary(one)) &&
3047 (textconv_two || !diff_filespec_is_binary(two))) {
3048 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3049 header.buf, header.len, 0);
3050 strbuf_reset(&header);
3051 emit_rewrite_diff(name_a, name_b, one, two,
3052 textconv_one, textconv_two, o);
3053 o->found_changes = 1;
3054 goto free_ab_and_return;
3058 if (o->irreversible_delete && lbl[1][0] == '/') {
3059 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3061 strbuf_reset(&header);
3062 goto free_ab_and_return;
3063 } else if (!DIFF_OPT_TST(o, TEXT) &&
3064 ( (!textconv_one && diff_filespec_is_binary(one)) ||
3065 (!textconv_two && diff_filespec_is_binary(two)) )) {
3066 struct strbuf sb = STRBUF_INIT;
3067 if (!one->data && !two->data &&
3068 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3069 !DIFF_OPT_TST(o, BINARY)) {
3070 if (!oidcmp(&one->oid, &two->oid)) {
3071 if (must_show_header)
3072 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3073 header.buf, header.len,
3075 goto free_ab_and_return;
3077 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3078 header.buf, header.len, 0);
3079 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3080 diff_line_prefix(o), lbl[0], lbl[1]);
3081 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3083 strbuf_release(&sb);
3084 goto free_ab_and_return;
3086 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3087 die("unable to read files to diff");
3088 /* Quite common confusing case */
3089 if (mf1.size == mf2.size &&
3090 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3091 if (must_show_header)
3092 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3093 header.buf, header.len, 0);
3094 goto free_ab_and_return;
3096 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3097 strbuf_reset(&header);
3098 if (DIFF_OPT_TST(o, BINARY))
3099 emit_binary_diff(o, &mf1, &mf2);
3101 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3102 diff_line_prefix(o), lbl[0], lbl[1]);
3103 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3105 strbuf_release(&sb);
3107 o->found_changes = 1;
3109 /* Crazy xdl interfaces.. */
3110 const char *diffopts = getenv("GIT_DIFF_OPTS");
3114 struct emit_callback ecbdata;
3115 const struct userdiff_funcname *pe;
3117 if (must_show_header) {
3118 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3119 header.buf, header.len, 0);
3120 strbuf_reset(&header);
3123 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
3124 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
3126 pe = diff_funcname_pattern(one);
3128 pe = diff_funcname_pattern(two);
3130 memset(&xpp, 0, sizeof(xpp));
3131 memset(&xecfg, 0, sizeof(xecfg));
3132 memset(&ecbdata, 0, sizeof(ecbdata));
3133 ecbdata.label_path = lbl;
3134 ecbdata.color_diff = want_color(o->use_color);
3135 ecbdata.ws_rule = whitespace_rule(name_b);
3136 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3137 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3139 ecbdata.header = header.len ? &header : NULL;
3140 xpp.flags = o->xdl_opts;
3141 xecfg.ctxlen = o->context;
3142 xecfg.interhunkctxlen = o->interhunkcontext;
3143 xecfg.flags = XDL_EMIT_FUNCNAMES;
3144 if (DIFF_OPT_TST(o, FUNCCONTEXT))
3145 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3147 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3150 else if (skip_prefix(diffopts, "--unified=", &v))
3151 xecfg.ctxlen = strtoul(v, NULL, 10);
3152 else if (skip_prefix(diffopts, "-u", &v))
3153 xecfg.ctxlen = strtoul(v, NULL, 10);
3155 init_diff_words_data(&ecbdata, o, one, two);
3156 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
3158 die("unable to generate diff for %s", one->path);
3160 free_diff_words_data(&ecbdata);
3165 xdiff_clear_find_func(&xecfg);
3169 strbuf_release(&header);
3170 diff_free_filespec_data(one);
3171 diff_free_filespec_data(two);
3177 static void builtin_diffstat(const char *name_a, const char *name_b,
3178 struct diff_filespec *one,
3179 struct diff_filespec *two,
3180 struct diffstat_t *diffstat,
3181 struct diff_options *o,
3182 struct diff_filepair *p)
3185 struct diffstat_file *data;
3187 int complete_rewrite = 0;
3189 if (!DIFF_PAIR_UNMERGED(p)) {
3190 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3191 complete_rewrite = 1;
3194 data = diffstat_add(diffstat, name_a, name_b);
3195 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3198 data->is_unmerged = 1;
3202 same_contents = !oidcmp(&one->oid, &two->oid);
3204 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
3205 data->is_binary = 1;
3206 if (same_contents) {
3210 data->added = diff_filespec_size(two);
3211 data->deleted = diff_filespec_size(one);
3215 else if (complete_rewrite) {
3216 diff_populate_filespec(one, 0);
3217 diff_populate_filespec(two, 0);
3218 data->deleted = count_lines(one->data, one->size);
3219 data->added = count_lines(two->data, two->size);
3222 else if (!same_contents) {
3223 /* Crazy xdl interfaces.. */
3227 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3228 die("unable to read files to diff");
3230 memset(&xpp, 0, sizeof(xpp));
3231 memset(&xecfg, 0, sizeof(xecfg));
3232 xpp.flags = o->xdl_opts;
3233 xecfg.ctxlen = o->context;
3234 xecfg.interhunkctxlen = o->interhunkcontext;
3235 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
3237 die("unable to generate diffstat for %s", one->path);
3240 diff_free_filespec_data(one);
3241 diff_free_filespec_data(two);
3244 static void builtin_checkdiff(const char *name_a, const char *name_b,
3245 const char *attr_path,
3246 struct diff_filespec *one,
3247 struct diff_filespec *two,
3248 struct diff_options *o)
3251 struct checkdiff_t data;
3256 memset(&data, 0, sizeof(data));
3257 data.filename = name_b ? name_b : name_a;
3260 data.ws_rule = whitespace_rule(attr_path);
3261 data.conflict_marker_size = ll_merge_marker_size(attr_path);
3263 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3264 die("unable to read files to diff");
3267 * All the other codepaths check both sides, but not checking
3268 * the "old" side here is deliberate. We are checking the newly
3269 * introduced changes, and as long as the "new" side is text, we
3270 * can and should check what it introduces.
3272 if (diff_filespec_is_binary(two))
3273 goto free_and_return;
3275 /* Crazy xdl interfaces.. */
3279 memset(&xpp, 0, sizeof(xpp));
3280 memset(&xecfg, 0, sizeof(xecfg));
3281 xecfg.ctxlen = 1; /* at least one context line */
3283 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
3285 die("unable to generate checkdiff for %s", one->path);
3287 if (data.ws_rule & WS_BLANK_AT_EOF) {
3288 struct emit_callback ecbdata;
3291 ecbdata.ws_rule = data.ws_rule;
3292 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3293 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3298 err = whitespace_error_string(WS_BLANK_AT_EOF);
3299 fprintf(o->file, "%s:%d: %s.\n",
3300 data.filename, blank_at_eof, err);
3301 data.status = 1; /* report errors */
3306 diff_free_filespec_data(one);
3307 diff_free_filespec_data(two);
3309 DIFF_OPT_SET(o, CHECK_FAILED);
3312 struct diff_filespec *alloc_filespec(const char *path)
3314 struct diff_filespec *spec;
3316 FLEXPTR_ALLOC_STR(spec, path, path);
3318 spec->is_binary = -1;
3322 void free_filespec(struct diff_filespec *spec)
3324 if (!--spec->count) {
3325 diff_free_filespec_data(spec);
3330 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3331 int oid_valid, unsigned short mode)
3334 spec->mode = canon_mode(mode);
3335 oidcpy(&spec->oid, oid);
3336 spec->oid_valid = oid_valid;
3341 * Given a name and sha1 pair, if the index tells us the file in
3342 * the work tree has that object contents, return true, so that
3343 * prepare_temp_file() does not have to inflate and extract.
3345 static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
3347 const struct cache_entry *ce;
3352 * We do not read the cache ourselves here, because the
3353 * benchmark with my previous version that always reads cache
3354 * shows that it makes things worse for diff-tree comparing
3355 * two linux-2.6 kernel trees in an already checked out work
3356 * tree. This is because most diff-tree comparisons deal with
3357 * only a small number of files, while reading the cache is
3358 * expensive for a large project, and its cost outweighs the
3359 * savings we get by not inflating the object to a temporary
3360 * file. Practically, this code only helps when we are used
3361 * by diff-cache --cached, which does read the cache before
3367 /* We want to avoid the working directory if our caller
3368 * doesn't need the data in a normal file, this system
3369 * is rather slow with its stat/open/mmap/close syscalls,
3370 * and the object is contained in a pack file. The pack
3371 * is probably already open and will be faster to obtain
3372 * the data through than the working directory. Loose
3373 * objects however would tend to be slower as they need
3374 * to be individually opened and inflated.
3376 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
3380 * Similarly, if we'd have to convert the file contents anyway, that
3381 * makes the optimization not worthwhile.
3383 if (!want_file && would_convert_to_git(&the_index, name))
3387 pos = cache_name_pos(name, len);
3390 ce = active_cache[pos];
3393 * This is not the sha1 we are looking for, or
3394 * unreusable because it is not a regular file.
3396 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3400 * If ce is marked as "assume unchanged", there is no
3401 * guarantee that work tree matches what we are looking for.
3403 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3407 * If ce matches the file in the work tree, we can reuse it.
3409 if (ce_uptodate(ce) ||
3410 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3416 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3418 struct strbuf buf = STRBUF_INIT;
3421 /* Are we looking at the work tree? */
3422 if (s->dirty_submodule)
3425 strbuf_addf(&buf, "Subproject commit %s%s\n",
3426 oid_to_hex(&s->oid), dirty);
3430 strbuf_release(&buf);
3432 s->data = strbuf_detach(&buf, NULL);
3439 * While doing rename detection and pickaxe operation, we may need to
3440 * grab the data for the blob (or file) for our own in-core comparison.
3441 * diff_filespec has data and size fields for this purpose.
3443 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
3445 int size_only = flags & CHECK_SIZE_ONLY;
3448 * demote FAIL to WARN to allow inspecting the situation
3449 * instead of refusing.
3451 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
3455 if (!DIFF_FILE_VALID(s))
3456 die("internal error: asking to populate invalid file.");
3457 if (S_ISDIR(s->mode))
3463 if (size_only && 0 < s->size)
3466 if (S_ISGITLINK(s->mode))
3467 return diff_populate_gitlink(s, size_only);
3469 if (!s->oid_valid ||
3470 reuse_worktree_file(s->path, &s->oid, 0)) {
3471 struct strbuf buf = STRBUF_INIT;
3475 if (lstat(s->path, &st) < 0) {
3476 if (errno == ENOENT) {
3480 s->data = (char *)"";
3485 s->size = xsize_t(st.st_size);
3488 if (S_ISLNK(st.st_mode)) {
3489 struct strbuf sb = STRBUF_INIT;
3491 if (strbuf_readlink(&sb, s->path, s->size))
3494 s->data = strbuf_detach(&sb, NULL);
3500 * Even if the caller would be happy with getting
3501 * only the size, we cannot return early at this
3502 * point if the path requires us to run the content
3505 if (size_only && !would_convert_to_git(&the_index, s->path))
3509 * Note: this check uses xsize_t(st.st_size) that may
3510 * not be the true size of the blob after it goes
3511 * through convert_to_git(). This may not strictly be
3512 * correct, but the whole point of big_file_threshold
3513 * and is_binary check being that we want to avoid
3514 * opening the file and inspecting the contents, this
3517 if ((flags & CHECK_BINARY) &&
3518 s->size > big_file_threshold && s->is_binary == -1) {
3522 fd = open(s->path, O_RDONLY);
3525 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3527 s->should_munmap = 1;
3530 * Convert from working tree format to canonical git format
3532 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, crlf_warn)) {
3534 munmap(s->data, s->size);
3535 s->should_munmap = 0;
3536 s->data = strbuf_detach(&buf, &size);
3542 enum object_type type;
3543 if (size_only || (flags & CHECK_BINARY)) {
3544 type = sha1_object_info(s->oid.hash, &s->size);
3546 die("unable to read %s",
3547 oid_to_hex(&s->oid));
3550 if (s->size > big_file_threshold && s->is_binary == -1) {
3555 s->data = read_sha1_file(s->oid.hash, &type, &s->size);
3557 die("unable to read %s", oid_to_hex(&s->oid));
3563 void diff_free_filespec_blob(struct diff_filespec *s)
3567 else if (s->should_munmap)
3568 munmap(s->data, s->size);
3570 if (s->should_free || s->should_munmap) {
3571 s->should_free = s->should_munmap = 0;
3576 void diff_free_filespec_data(struct diff_filespec *s)
3578 diff_free_filespec_blob(s);
3579 FREE_AND_NULL(s->cnt_data);
3582 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
3585 const struct object_id *oid,
3589 struct strbuf buf = STRBUF_INIT;
3590 struct strbuf template = STRBUF_INIT;
3591 char *path_dup = xstrdup(path);
3592 const char *base = basename(path_dup);
3594 /* Generate "XXXXXX_basename.ext" */
3595 strbuf_addstr(&template, "XXXXXX_");
3596 strbuf_addstr(&template, base);
3598 fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
3600 die_errno("unable to create temp-file");
3601 if (convert_to_working_tree(path,
3602 (const char *)blob, (size_t)size, &buf)) {
3606 if (write_in_full(fd, blob, size) != size)
3607 die_errno("unable to write temp-file");
3608 close_tempfile(&temp->tempfile);
3609 temp->name = get_tempfile_path(&temp->tempfile);
3610 oid_to_hex_r(temp->hex, oid);
3611 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
3612 strbuf_release(&buf);
3613 strbuf_release(&template);
3617 static struct diff_tempfile *prepare_temp_file(const char *name,
3618 struct diff_filespec *one)
3620 struct diff_tempfile *temp = claim_diff_tempfile();
3622 if (!DIFF_FILE_VALID(one)) {
3624 /* A '-' entry produces this for file-2, and
3625 * a '+' entry produces this for file-1.
3627 temp->name = "/dev/null";
3628 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3629 xsnprintf(temp->mode, sizeof(temp->mode), ".");
3633 if (!S_ISGITLINK(one->mode) &&
3635 reuse_worktree_file(name, &one->oid, 1))) {
3637 if (lstat(name, &st) < 0) {
3638 if (errno == ENOENT)
3639 goto not_a_valid_file;
3640 die_errno("stat(%s)", name);
3642 if (S_ISLNK(st.st_mode)) {
3643 struct strbuf sb = STRBUF_INIT;
3644 if (strbuf_readlink(&sb, name, st.st_size) < 0)
3645 die_errno("readlink(%s)", name);
3646 prep_temp_blob(name, temp, sb.buf, sb.len,
3648 &one->oid : &null_oid),
3650 one->mode : S_IFLNK));
3651 strbuf_release(&sb);
3654 /* we can borrow from the file in the work tree */
3656 if (!one->oid_valid)
3657 oid_to_hex_r(temp->hex, &null_oid);
3659 oid_to_hex_r(temp->hex, &one->oid);
3660 /* Even though we may sometimes borrow the
3661 * contents from the work tree, we always want
3662 * one->mode. mode is trustworthy even when
3663 * !(one->oid_valid), as long as
3664 * DIFF_FILE_VALID(one).
3666 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
3671 if (diff_populate_filespec(one, 0))
3672 die("cannot read data blob for %s", one->path);
3673 prep_temp_blob(name, temp, one->data, one->size,
3674 &one->oid, one->mode);
3679 static void add_external_diff_name(struct argv_array *argv,
3681 struct diff_filespec *df)
3683 struct diff_tempfile *temp = prepare_temp_file(name, df);
3684 argv_array_push(argv, temp->name);
3685 argv_array_push(argv, temp->hex);
3686 argv_array_push(argv, temp->mode);
3689 /* An external diff command takes:
3691 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3692 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3695 static void run_external_diff(const char *pgm,
3698 struct diff_filespec *one,
3699 struct diff_filespec *two,
3700 const char *xfrm_msg,
3701 int complete_rewrite,
3702 struct diff_options *o)
3704 struct argv_array argv = ARGV_ARRAY_INIT;
3705 struct argv_array env = ARGV_ARRAY_INIT;
3706 struct diff_queue_struct *q = &diff_queued_diff;
3708 argv_array_push(&argv, pgm);
3709 argv_array_push(&argv, name);
3712 add_external_diff_name(&argv, name, one);
3714 add_external_diff_name(&argv, name, two);
3716 add_external_diff_name(&argv, other, two);
3717 argv_array_push(&argv, other);
3718 argv_array_push(&argv, xfrm_msg);
3722 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3723 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3725 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3726 die(_("external diff died, stopping at %s"), name);
3729 argv_array_clear(&argv);
3730 argv_array_clear(&env);
3733 static int similarity_index(struct diff_filepair *p)
3735 return p->score * 100 / MAX_SCORE;
3738 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3740 if (startup_info->have_repository)
3741 return find_unique_abbrev(oid->hash, abbrev);
3743 char *hex = oid_to_hex(oid);
3745 abbrev = FALLBACK_DEFAULT_ABBREV;
3746 if (abbrev > GIT_SHA1_HEXSZ)
3747 die("BUG: oid abbreviation out of range: %d", abbrev);
3754 static void fill_metainfo(struct strbuf *msg,
3757 struct diff_filespec *one,
3758 struct diff_filespec *two,
3759 struct diff_options *o,
3760 struct diff_filepair *p,
3761 int *must_show_header,
3764 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3765 const char *reset = diff_get_color(use_color, DIFF_RESET);
3766 const char *line_prefix = diff_line_prefix(o);
3768 *must_show_header = 1;
3769 strbuf_init(msg, PATH_MAX * 2 + 300);
3770 switch (p->status) {
3771 case DIFF_STATUS_COPIED:
3772 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3773 line_prefix, set, similarity_index(p));
3774 strbuf_addf(msg, "%s\n%s%scopy from ",
3775 reset, line_prefix, set);
3776 quote_c_style(name, msg, NULL, 0);
3777 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3778 quote_c_style(other, msg, NULL, 0);
3779 strbuf_addf(msg, "%s\n", reset);
3781 case DIFF_STATUS_RENAMED:
3782 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3783 line_prefix, set, similarity_index(p));
3784 strbuf_addf(msg, "%s\n%s%srename from ",
3785 reset, line_prefix, set);
3786 quote_c_style(name, msg, NULL, 0);
3787 strbuf_addf(msg, "%s\n%s%srename to ",
3788 reset, line_prefix, set);
3789 quote_c_style(other, msg, NULL, 0);
3790 strbuf_addf(msg, "%s\n", reset);
3792 case DIFF_STATUS_MODIFIED:
3794 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3796 set, similarity_index(p), reset);
3801 *must_show_header = 0;
3803 if (one && two && oidcmp(&one->oid, &two->oid)) {
3804 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3806 if (DIFF_OPT_TST(o, BINARY)) {
3808 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3809 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3812 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3813 diff_abbrev_oid(&one->oid, abbrev),
3814 diff_abbrev_oid(&two->oid, abbrev));
3815 if (one->mode == two->mode)
3816 strbuf_addf(msg, " %06o", one->mode);
3817 strbuf_addf(msg, "%s\n", reset);
3821 static void run_diff_cmd(const char *pgm,
3824 const char *attr_path,
3825 struct diff_filespec *one,
3826 struct diff_filespec *two,
3828 struct diff_options *o,
3829 struct diff_filepair *p)
3831 const char *xfrm_msg = NULL;
3832 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3833 int must_show_header = 0;
3836 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3837 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3838 if (drv && drv->external)
3839 pgm = drv->external;
3844 * don't use colors when the header is intended for an
3845 * external diff driver
3847 fill_metainfo(msg, name, other, one, two, o, p,
3849 want_color(o->use_color) && !pgm);
3850 xfrm_msg = msg->len ? msg->buf : NULL;
3854 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3855 complete_rewrite, o);
3859 builtin_diff(name, other ? other : name,
3860 one, two, xfrm_msg, must_show_header,
3861 o, complete_rewrite);
3863 fprintf(o->file, "* Unmerged path %s\n", name);
3866 static void diff_fill_oid_info(struct diff_filespec *one)
3868 if (DIFF_FILE_VALID(one)) {
3869 if (!one->oid_valid) {
3871 if (one->is_stdin) {
3875 if (lstat(one->path, &st) < 0)
3876 die_errno("stat '%s'", one->path);
3877 if (index_path(one->oid.hash, one->path, &st, 0))
3878 die("cannot hash %s", one->path);
3885 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3887 /* Strip the prefix but do not molest /dev/null and absolute paths */
3888 if (*namep && **namep != '/') {
3889 *namep += prefix_length;
3893 if (*otherp && **otherp != '/') {
3894 *otherp += prefix_length;
3895 if (**otherp == '/')
3900 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3902 const char *pgm = external_diff();
3904 struct diff_filespec *one = p->one;
3905 struct diff_filespec *two = p->two;
3908 const char *attr_path;
3911 other = (strcmp(name, two->path) ? two->path : NULL);
3913 if (o->prefix_length)
3914 strip_prefix(o->prefix_length, &name, &other);
3916 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3919 if (DIFF_PAIR_UNMERGED(p)) {
3920 run_diff_cmd(pgm, name, NULL, attr_path,
3921 NULL, NULL, NULL, o, p);
3925 diff_fill_oid_info(one);
3926 diff_fill_oid_info(two);
3929 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3930 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3932 * a filepair that changes between file and symlink
3933 * needs to be split into deletion and creation.
3935 struct diff_filespec *null = alloc_filespec(two->path);
3936 run_diff_cmd(NULL, name, other, attr_path,
3937 one, null, &msg, o, p);
3939 strbuf_release(&msg);
3941 null = alloc_filespec(one->path);
3942 run_diff_cmd(NULL, name, other, attr_path,
3943 null, two, &msg, o, p);
3947 run_diff_cmd(pgm, name, other, attr_path,
3948 one, two, &msg, o, p);
3950 strbuf_release(&msg);
3953 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3954 struct diffstat_t *diffstat)
3959 if (DIFF_PAIR_UNMERGED(p)) {
3961 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
3965 name = p->one->path;
3966 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3968 if (o->prefix_length)
3969 strip_prefix(o->prefix_length, &name, &other);
3971 diff_fill_oid_info(p->one);
3972 diff_fill_oid_info(p->two);
3974 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
3977 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3981 const char *attr_path;
3983 if (DIFF_PAIR_UNMERGED(p)) {
3988 name = p->one->path;
3989 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3990 attr_path = other ? other : name;
3992 if (o->prefix_length)
3993 strip_prefix(o->prefix_length, &name, &other);
3995 diff_fill_oid_info(p->one);
3996 diff_fill_oid_info(p->two);
3998 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4001 void diff_setup(struct diff_options *options)
4003 memcpy(options, &default_diff_options, sizeof(*options));
4005 options->file = stdout;
4007 options->abbrev = DEFAULT_ABBREV;
4008 options->line_termination = '\n';
4009 options->break_opt = -1;
4010 options->rename_limit = -1;
4011 options->dirstat_permille = diff_dirstat_permille_default;
4012 options->context = diff_context_default;
4013 options->interhunkcontext = diff_interhunk_context_default;
4014 options->ws_error_highlight = ws_error_highlight_default;
4015 DIFF_OPT_SET(options, RENAME_EMPTY);
4017 /* pathchange left =NULL by default */
4018 options->change = diff_change;
4019 options->add_remove = diff_addremove;
4020 options->use_color = diff_use_color_default;
4021 options->detect_rename = diff_detect_rename_default;
4022 options->xdl_opts |= diff_algorithm;
4023 if (diff_indent_heuristic)
4024 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4026 options->orderfile = diff_order_file_cfg;
4028 if (diff_no_prefix) {
4029 options->a_prefix = options->b_prefix = "";
4030 } else if (!diff_mnemonic_prefix) {
4031 options->a_prefix = "a/";
4032 options->b_prefix = "b/";
4035 options->color_moved = diff_color_moved_default;
4038 void diff_setup_done(struct diff_options *options)
4042 if (options->set_default)
4043 options->set_default(options);
4045 if (options->output_format & DIFF_FORMAT_NAME)
4047 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
4049 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
4051 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
4054 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4057 * Most of the time we can say "there are changes"
4058 * only by checking if there are changed paths, but
4059 * --ignore-whitespace* options force us to look
4063 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
4064 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
4065 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
4066 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
4068 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
4070 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
4071 options->detect_rename = DIFF_DETECT_COPY;
4073 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
4074 options->prefix = NULL;
4075 if (options->prefix)
4076 options->prefix_length = strlen(options->prefix);
4078 options->prefix_length = 0;
4080 if (options->output_format & (DIFF_FORMAT_NAME |
4081 DIFF_FORMAT_NAME_STATUS |
4082 DIFF_FORMAT_CHECKDIFF |
4083 DIFF_FORMAT_NO_OUTPUT))
4084 options->output_format &= ~(DIFF_FORMAT_RAW |
4085 DIFF_FORMAT_NUMSTAT |
4086 DIFF_FORMAT_DIFFSTAT |
4087 DIFF_FORMAT_SHORTSTAT |
4088 DIFF_FORMAT_DIRSTAT |
4089 DIFF_FORMAT_SUMMARY |
4093 * These cases always need recursive; we do not drop caller-supplied
4094 * recursive bits for other formats here.
4096 if (options->output_format & (DIFF_FORMAT_PATCH |
4097 DIFF_FORMAT_NUMSTAT |
4098 DIFF_FORMAT_DIFFSTAT |
4099 DIFF_FORMAT_SHORTSTAT |
4100 DIFF_FORMAT_DIRSTAT |
4101 DIFF_FORMAT_SUMMARY |
4102 DIFF_FORMAT_CHECKDIFF))
4103 DIFF_OPT_SET(options, RECURSIVE);
4105 * Also pickaxe would not work very well if you do not say recursive
4107 if (options->pickaxe)
4108 DIFF_OPT_SET(options, RECURSIVE);
4110 * When patches are generated, submodules diffed against the work tree
4111 * must be checked for dirtiness too so it can be shown in the output
4113 if (options->output_format & DIFF_FORMAT_PATCH)
4114 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
4116 if (options->detect_rename && options->rename_limit < 0)
4117 options->rename_limit = diff_rename_limit_default;
4118 if (options->setup & DIFF_SETUP_USE_CACHE) {
4120 /* read-cache does not die even when it fails
4121 * so it is safe for us to do this here. Also
4122 * it does not smudge active_cache or active_nr
4123 * when it fails, so we do not have to worry about
4124 * cleaning it up ourselves either.
4128 if (40 < options->abbrev)
4129 options->abbrev = 40; /* full */
4132 * It does not make sense to show the first hit we happened
4133 * to have found. It does not make sense not to return with
4134 * exit code in such a case either.
4136 if (DIFF_OPT_TST(options, QUICK)) {
4137 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4138 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
4141 options->diff_path_counter = 0;
4143 if (DIFF_OPT_TST(options, FOLLOW_RENAMES) && options->pathspec.nr != 1)
4144 die(_("--follow requires exactly one pathspec"));
4146 if (!options->use_color || external_diff())
4147 options->color_moved = 0;
4150 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4160 if (c == arg_short) {
4164 if (val && isdigit(c)) {
4166 int n = strtoul(arg, &end, 10);
4177 eq = strchrnul(arg, '=');
4179 if (!len || strncmp(arg, arg_long, len))
4184 if (!isdigit(*++eq))
4186 n = strtoul(eq, &end, 10);
4194 static int diff_scoreopt_parse(const char *opt);
4196 static inline int short_opt(char opt, const char **argv,
4197 const char **optarg)
4199 const char *arg = argv[0];
4200 if (arg[0] != '-' || arg[1] != opt)
4202 if (arg[2] != '\0') {
4207 die("Option '%c' requires a value", opt);
4212 int parse_long_opt(const char *opt, const char **argv,
4213 const char **optarg)
4215 const char *arg = argv[0];
4216 if (!skip_prefix(arg, "--", &arg))
4218 if (!skip_prefix(arg, opt, &arg))
4220 if (*arg == '=') { /* stuck form: --option=value */
4226 /* separate form: --option value */
4228 die("Option '--%s' requires a value", opt);
4233 static int stat_opt(struct diff_options *options, const char **av)
4235 const char *arg = av[0];
4237 int width = options->stat_width;
4238 int name_width = options->stat_name_width;
4239 int graph_width = options->stat_graph_width;
4240 int count = options->stat_count;
4243 if (!skip_prefix(arg, "--stat", &arg))
4244 die("BUG: stat option does not begin with --stat: %s", arg);
4249 if (skip_prefix(arg, "-width", &arg)) {
4251 width = strtoul(arg + 1, &end, 10);
4252 else if (!*arg && !av[1])
4253 die_want_option("--stat-width");
4255 width = strtoul(av[1], &end, 10);
4258 } else if (skip_prefix(arg, "-name-width", &arg)) {
4260 name_width = strtoul(arg + 1, &end, 10);
4261 else if (!*arg && !av[1])
4262 die_want_option("--stat-name-width");
4264 name_width = strtoul(av[1], &end, 10);
4267 } else if (skip_prefix(arg, "-graph-width", &arg)) {
4269 graph_width = strtoul(arg + 1, &end, 10);
4270 else if (!*arg && !av[1])
4271 die_want_option("--stat-graph-width");
4273 graph_width = strtoul(av[1], &end, 10);
4276 } else if (skip_prefix(arg, "-count", &arg)) {
4278 count = strtoul(arg + 1, &end, 10);
4279 else if (!*arg && !av[1])
4280 die_want_option("--stat-count");
4282 count = strtoul(av[1], &end, 10);
4288 width = strtoul(arg+1, &end, 10);
4290 name_width = strtoul(end+1, &end, 10);
4292 count = strtoul(end+1, &end, 10);
4295 /* Important! This checks all the error cases! */
4298 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4299 options->stat_name_width = name_width;
4300 options->stat_graph_width = graph_width;
4301 options->stat_width = width;
4302 options->stat_count = count;
4306 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4308 struct strbuf errmsg = STRBUF_INIT;
4309 if (parse_dirstat_params(options, params, &errmsg))
4310 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4312 strbuf_release(&errmsg);
4314 * The caller knows a dirstat-related option is given from the command
4315 * line; allow it to say "return this_function();"
4317 options->output_format |= DIFF_FORMAT_DIRSTAT;
4321 static int parse_submodule_opt(struct diff_options *options, const char *value)
4323 if (parse_submodule_params(options, value))
4324 die(_("Failed to parse --submodule option parameter: '%s'"),
4329 static const char diff_status_letters[] = {
4332 DIFF_STATUS_DELETED,
4333 DIFF_STATUS_MODIFIED,
4334 DIFF_STATUS_RENAMED,
4335 DIFF_STATUS_TYPE_CHANGED,
4336 DIFF_STATUS_UNKNOWN,
4337 DIFF_STATUS_UNMERGED,
4338 DIFF_STATUS_FILTER_AON,
4339 DIFF_STATUS_FILTER_BROKEN,
4343 static unsigned int filter_bit['Z' + 1];
4345 static void prepare_filter_bits(void)
4349 if (!filter_bit[DIFF_STATUS_ADDED]) {
4350 for (i = 0; diff_status_letters[i]; i++)
4351 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4355 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4357 return opt->filter & filter_bit[(int) status];
4360 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4364 prepare_filter_bits();
4367 * If there is a negation e.g. 'd' in the input, and we haven't
4368 * initialized the filter field with another --diff-filter, start
4369 * from full set of bits, except for AON.
4372 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4373 if (optch < 'a' || 'z' < optch)
4375 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4376 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4381 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4385 if ('a' <= optch && optch <= 'z') {
4387 optch = toupper(optch);
4392 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4396 opt->filter &= ~bit;
4403 static void enable_patch_output(int *fmt) {
4404 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4405 *fmt |= DIFF_FORMAT_PATCH;
4408 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4410 int val = parse_ws_error_highlight(arg);
4413 error("unknown value after ws-error-highlight=%.*s",
4417 opt->ws_error_highlight = val;
4421 int diff_opt_parse(struct diff_options *options,
4422 const char **av, int ac, const char *prefix)
4424 const char *arg = av[0];
4431 /* Output format options */
4432 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
4433 || opt_arg(arg, 'U', "unified", &options->context))
4434 enable_patch_output(&options->output_format);
4435 else if (!strcmp(arg, "--raw"))
4436 options->output_format |= DIFF_FORMAT_RAW;
4437 else if (!strcmp(arg, "--patch-with-raw")) {
4438 enable_patch_output(&options->output_format);
4439 options->output_format |= DIFF_FORMAT_RAW;
4440 } else if (!strcmp(arg, "--numstat"))
4441 options->output_format |= DIFF_FORMAT_NUMSTAT;
4442 else if (!strcmp(arg, "--shortstat"))
4443 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4444 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
4445 return parse_dirstat_opt(options, "");
4446 else if (skip_prefix(arg, "-X", &arg))
4447 return parse_dirstat_opt(options, arg);
4448 else if (skip_prefix(arg, "--dirstat=", &arg))
4449 return parse_dirstat_opt(options, arg);
4450 else if (!strcmp(arg, "--cumulative"))
4451 return parse_dirstat_opt(options, "cumulative");
4452 else if (!strcmp(arg, "--dirstat-by-file"))
4453 return parse_dirstat_opt(options, "files");
4454 else if (skip_prefix(arg, "--dirstat-by-file=", &arg)) {
4455 parse_dirstat_opt(options, "files");
4456 return parse_dirstat_opt(options, arg);
4458 else if (!strcmp(arg, "--check"))
4459 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4460 else if (!strcmp(arg, "--summary"))
4461 options->output_format |= DIFF_FORMAT_SUMMARY;
4462 else if (!strcmp(arg, "--patch-with-stat")) {
4463 enable_patch_output(&options->output_format);
4464 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4465 } else if (!strcmp(arg, "--name-only"))
4466 options->output_format |= DIFF_FORMAT_NAME;
4467 else if (!strcmp(arg, "--name-status"))
4468 options->output_format |= DIFF_FORMAT_NAME_STATUS;
4469 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
4470 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4471 else if (starts_with(arg, "--stat"))
4472 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4473 return stat_opt(options, av);
4475 /* renames options */
4476 else if (starts_with(arg, "-B") || starts_with(arg, "--break-rewrites=") ||
4477 !strcmp(arg, "--break-rewrites")) {
4478 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
4479 return error("invalid argument to -B: %s", arg+2);
4481 else if (starts_with(arg, "-M") || starts_with(arg, "--find-renames=") ||
4482 !strcmp(arg, "--find-renames")) {
4483 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4484 return error("invalid argument to -M: %s", arg+2);
4485 options->detect_rename = DIFF_DETECT_RENAME;
4487 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
4488 options->irreversible_delete = 1;
4490 else if (starts_with(arg, "-C") || starts_with(arg, "--find-copies=") ||
4491 !strcmp(arg, "--find-copies")) {
4492 if (options->detect_rename == DIFF_DETECT_COPY)
4493 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
4494 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4495 return error("invalid argument to -C: %s", arg+2);
4496 options->detect_rename = DIFF_DETECT_COPY;
4498 else if (!strcmp(arg, "--no-renames"))
4499 options->detect_rename = 0;
4500 else if (!strcmp(arg, "--rename-empty"))
4501 DIFF_OPT_SET(options, RENAME_EMPTY);
4502 else if (!strcmp(arg, "--no-rename-empty"))
4503 DIFF_OPT_CLR(options, RENAME_EMPTY);
4504 else if (!strcmp(arg, "--relative"))
4505 DIFF_OPT_SET(options, RELATIVE_NAME);
4506 else if (skip_prefix(arg, "--relative=", &arg)) {
4507 DIFF_OPT_SET(options, RELATIVE_NAME);
4508 options->prefix = arg;
4512 else if (!strcmp(arg, "--minimal"))
4513 DIFF_XDL_SET(options, NEED_MINIMAL);
4514 else if (!strcmp(arg, "--no-minimal"))
4515 DIFF_XDL_CLR(options, NEED_MINIMAL);
4516 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
4517 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
4518 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
4519 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
4520 else if (!strcmp(arg, "--ignore-space-at-eol"))
4521 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
4522 else if (!strcmp(arg, "--ignore-blank-lines"))
4523 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
4524 else if (!strcmp(arg, "--indent-heuristic"))
4525 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4526 else if (!strcmp(arg, "--no-indent-heuristic"))
4527 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
4528 else if (!strcmp(arg, "--patience"))
4529 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4530 else if (!strcmp(arg, "--histogram"))
4531 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
4532 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
4533 long value = parse_algorithm_value(optarg);
4535 return error("option diff-algorithm accepts \"myers\", "
4536 "\"minimal\", \"patience\" and \"histogram\"");
4537 /* clear out previous settings */
4538 DIFF_XDL_CLR(options, NEED_MINIMAL);
4539 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4540 options->xdl_opts |= value;
4545 else if (!strcmp(arg, "--binary")) {
4546 enable_patch_output(&options->output_format);
4547 DIFF_OPT_SET(options, BINARY);
4549 else if (!strcmp(arg, "--full-index"))
4550 DIFF_OPT_SET(options, FULL_INDEX);
4551 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
4552 DIFF_OPT_SET(options, TEXT);
4553 else if (!strcmp(arg, "-R"))
4554 DIFF_OPT_SET(options, REVERSE_DIFF);
4555 else if (!strcmp(arg, "--find-copies-harder"))
4556 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
4557 else if (!strcmp(arg, "--follow"))
4558 DIFF_OPT_SET(options, FOLLOW_RENAMES);
4559 else if (!strcmp(arg, "--no-follow")) {
4560 DIFF_OPT_CLR(options, FOLLOW_RENAMES);
4561 DIFF_OPT_CLR(options, DEFAULT_FOLLOW_RENAMES);
4562 } else if (!strcmp(arg, "--color"))
4563 options->use_color = 1;
4564 else if (skip_prefix(arg, "--color=", &arg)) {
4565 int value = git_config_colorbool(NULL, arg);
4567 return error("option `color' expects \"always\", \"auto\", or \"never\"");
4568 options->use_color = value;
4570 else if (!strcmp(arg, "--no-color"))
4571 options->use_color = 0;
4572 else if (!strcmp(arg, "--color-moved")) {
4573 if (diff_color_moved_default)
4574 options->color_moved = diff_color_moved_default;
4575 if (options->color_moved == COLOR_MOVED_NO)
4576 options->color_moved = COLOR_MOVED_DEFAULT;
4577 } else if (!strcmp(arg, "--no-color-moved"))
4578 options->color_moved = COLOR_MOVED_NO;
4579 else if (skip_prefix(arg, "--color-moved=", &arg)) {
4580 int cm = parse_color_moved(arg);
4582 die("bad --color-moved argument: %s", arg);
4583 options->color_moved = cm;
4584 } else if (!strcmp(arg, "--color-words")) {
4585 options->use_color = 1;
4586 options->word_diff = DIFF_WORDS_COLOR;
4588 else if (skip_prefix(arg, "--color-words=", &arg)) {
4589 options->use_color = 1;
4590 options->word_diff = DIFF_WORDS_COLOR;
4591 options->word_regex = arg;
4593 else if (!strcmp(arg, "--word-diff")) {
4594 if (options->word_diff == DIFF_WORDS_NONE)
4595 options->word_diff = DIFF_WORDS_PLAIN;
4597 else if (skip_prefix(arg, "--word-diff=", &arg)) {
4598 if (!strcmp(arg, "plain"))
4599 options->word_diff = DIFF_WORDS_PLAIN;
4600 else if (!strcmp(arg, "color")) {
4601 options->use_color = 1;
4602 options->word_diff = DIFF_WORDS_COLOR;
4604 else if (!strcmp(arg, "porcelain"))
4605 options->word_diff = DIFF_WORDS_PORCELAIN;
4606 else if (!strcmp(arg, "none"))
4607 options->word_diff = DIFF_WORDS_NONE;
4609 die("bad --word-diff argument: %s", arg);
4611 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
4612 if (options->word_diff == DIFF_WORDS_NONE)
4613 options->word_diff = DIFF_WORDS_PLAIN;
4614 options->word_regex = optarg;
4617 else if (!strcmp(arg, "--exit-code"))
4618 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
4619 else if (!strcmp(arg, "--quiet"))
4620 DIFF_OPT_SET(options, QUICK);
4621 else if (!strcmp(arg, "--ext-diff"))
4622 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
4623 else if (!strcmp(arg, "--no-ext-diff"))
4624 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
4625 else if (!strcmp(arg, "--textconv"))
4626 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
4627 else if (!strcmp(arg, "--no-textconv"))
4628 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
4629 else if (!strcmp(arg, "--ignore-submodules")) {
4630 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
4631 handle_ignore_submodules_arg(options, "all");
4632 } else if (skip_prefix(arg, "--ignore-submodules=", &arg)) {
4633 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
4634 handle_ignore_submodules_arg(options, arg);
4635 } else if (!strcmp(arg, "--submodule"))
4636 options->submodule_format = DIFF_SUBMODULE_LOG;
4637 else if (skip_prefix(arg, "--submodule=", &arg))
4638 return parse_submodule_opt(options, arg);
4639 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
4640 return parse_ws_error_highlight_opt(options, arg);
4641 else if (!strcmp(arg, "--ita-invisible-in-index"))
4642 options->ita_invisible_in_index = 1;
4643 else if (!strcmp(arg, "--ita-visible-in-index"))
4644 options->ita_invisible_in_index = 0;
4647 else if (!strcmp(arg, "-z"))
4648 options->line_termination = 0;
4649 else if ((argcount = short_opt('l', av, &optarg))) {
4650 options->rename_limit = strtoul(optarg, NULL, 10);
4653 else if ((argcount = short_opt('S', av, &optarg))) {
4654 options->pickaxe = optarg;
4655 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
4657 } else if ((argcount = short_opt('G', av, &optarg))) {
4658 options->pickaxe = optarg;
4659 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
4662 else if (!strcmp(arg, "--pickaxe-all"))
4663 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
4664 else if (!strcmp(arg, "--pickaxe-regex"))
4665 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
4666 else if ((argcount = short_opt('O', av, &optarg))) {
4667 options->orderfile = prefix_filename(prefix, optarg);
4670 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
4671 int offending = parse_diff_filter_opt(optarg, options);
4673 die("unknown change class '%c' in --diff-filter=%s",
4677 else if (!strcmp(arg, "--no-abbrev"))
4678 options->abbrev = 0;
4679 else if (!strcmp(arg, "--abbrev"))
4680 options->abbrev = DEFAULT_ABBREV;
4681 else if (skip_prefix(arg, "--abbrev=", &arg)) {
4682 options->abbrev = strtoul(arg, NULL, 10);
4683 if (options->abbrev < MINIMUM_ABBREV)
4684 options->abbrev = MINIMUM_ABBREV;
4685 else if (40 < options->abbrev)
4686 options->abbrev = 40;
4688 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
4689 options->a_prefix = optarg;
4692 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
4693 options->line_prefix = optarg;
4694 options->line_prefix_length = strlen(options->line_prefix);
4695 graph_setup_line_prefix(options);
4698 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
4699 options->b_prefix = optarg;
4702 else if (!strcmp(arg, "--no-prefix"))
4703 options->a_prefix = options->b_prefix = "";
4704 else if (opt_arg(arg, '\0', "inter-hunk-context",
4705 &options->interhunkcontext))
4707 else if (!strcmp(arg, "-W"))
4708 DIFF_OPT_SET(options, FUNCCONTEXT);
4709 else if (!strcmp(arg, "--function-context"))
4710 DIFF_OPT_SET(options, FUNCCONTEXT);
4711 else if (!strcmp(arg, "--no-function-context"))
4712 DIFF_OPT_CLR(options, FUNCCONTEXT);
4713 else if ((argcount = parse_long_opt("output", av, &optarg))) {
4714 char *path = prefix_filename(prefix, optarg);
4715 options->file = xfopen(path, "w");
4716 options->close_file = 1;
4717 if (options->use_color != GIT_COLOR_ALWAYS)
4718 options->use_color = GIT_COLOR_NEVER;
4726 int parse_rename_score(const char **cp_p)
4728 unsigned long num, scale;
4730 const char *cp = *cp_p;
4737 if ( !dot && ch == '.' ) {
4740 } else if ( ch == '%' ) {
4741 scale = dot ? scale*100 : 100;
4742 cp++; /* % is always at the end */
4744 } else if ( ch >= '0' && ch <= '9' ) {
4745 if ( scale < 100000 ) {
4747 num = (num*10) + (ch-'0');
4756 /* user says num divided by scale and we say internally that
4757 * is MAX_SCORE * num / scale.
4759 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4762 static int diff_scoreopt_parse(const char *opt)
4764 int opt1, opt2, cmd;
4770 /* convert the long-form arguments into short-form versions */
4771 if (skip_prefix(opt, "break-rewrites", &opt)) {
4772 if (*opt == 0 || *opt++ == '=')
4774 } else if (skip_prefix(opt, "find-copies", &opt)) {
4775 if (*opt == 0 || *opt++ == '=')
4777 } else if (skip_prefix(opt, "find-renames", &opt)) {
4778 if (*opt == 0 || *opt++ == '=')
4782 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4783 return -1; /* that is not a -M, -C, or -B option */
4785 opt1 = parse_rename_score(&opt);
4791 else if (*opt != '/')
4792 return -1; /* we expect -B80/99 or -B80 */
4795 opt2 = parse_rename_score(&opt);
4800 return opt1 | (opt2 << 16);
4803 struct diff_queue_struct diff_queued_diff;
4805 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4807 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4808 queue->queue[queue->nr++] = dp;
4811 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4812 struct diff_filespec *one,
4813 struct diff_filespec *two)
4815 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4823 void diff_free_filepair(struct diff_filepair *p)
4825 free_filespec(p->one);
4826 free_filespec(p->two);
4830 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
4835 if (len == GIT_SHA1_HEXSZ)
4836 return oid_to_hex(oid);
4838 abbrev = diff_abbrev_oid(oid, len);
4839 abblen = strlen(abbrev);
4842 * In well-behaved cases, where the abbbreviated result is the
4843 * same as the requested length, append three dots after the
4844 * abbreviation (hence the whole logic is limited to the case
4845 * where abblen < 37); when the actual abbreviated result is a
4846 * bit longer than the requested length, we reduce the number
4847 * of dots so that they match the well-behaved ones. However,
4848 * if the actual abbreviation is longer than the requested
4849 * length by more than three, we give up on aligning, and add
4850 * three dots anyway, to indicate that the output is not the
4851 * full object name. Yes, this may be suboptimal, but this
4852 * appears only in "diff --raw --abbrev" output and it is not
4853 * worth the effort to change it now. Note that this would
4854 * likely to work fine when the automatic sizing of default
4855 * abbreviation length is used--we would be fed -1 in "len" in
4856 * that case, and will end up always appending three-dots, but
4857 * the automatic sizing is supposed to give abblen that ensures
4858 * uniqueness across all objects (statistically speaking).
4860 if (abblen < GIT_SHA1_HEXSZ - 3) {
4861 static char hex[GIT_MAX_HEXSZ + 1];
4862 if (len < abblen && abblen <= len + 2)
4863 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
4865 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
4869 return oid_to_hex(oid);
4872 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4874 int line_termination = opt->line_termination;
4875 int inter_name_termination = line_termination ? '\t' : '\0';
4877 fprintf(opt->file, "%s", diff_line_prefix(opt));
4878 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
4879 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
4880 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
4881 fprintf(opt->file, "%s ",
4882 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
4885 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
4886 inter_name_termination);
4888 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
4891 if (p->status == DIFF_STATUS_COPIED ||
4892 p->status == DIFF_STATUS_RENAMED) {
4893 const char *name_a, *name_b;
4894 name_a = p->one->path;
4895 name_b = p->two->path;
4896 strip_prefix(opt->prefix_length, &name_a, &name_b);
4897 write_name_quoted(name_a, opt->file, inter_name_termination);
4898 write_name_quoted(name_b, opt->file, line_termination);
4900 const char *name_a, *name_b;
4901 name_a = p->one->mode ? p->one->path : p->two->path;
4903 strip_prefix(opt->prefix_length, &name_a, &name_b);
4904 write_name_quoted(name_a, opt->file, line_termination);
4908 int diff_unmodified_pair(struct diff_filepair *p)
4910 /* This function is written stricter than necessary to support
4911 * the currently implemented transformers, but the idea is to
4912 * let transformers to produce diff_filepairs any way they want,
4913 * and filter and clean them up here before producing the output.
4915 struct diff_filespec *one = p->one, *two = p->two;
4917 if (DIFF_PAIR_UNMERGED(p))
4918 return 0; /* unmerged is interesting */
4920 /* deletion, addition, mode or type change
4921 * and rename are all interesting.
4923 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
4924 DIFF_PAIR_MODE_CHANGED(p) ||
4925 strcmp(one->path, two->path))
4928 /* both are valid and point at the same path. that is, we are
4929 * dealing with a change.
4931 if (one->oid_valid && two->oid_valid &&
4932 !oidcmp(&one->oid, &two->oid) &&
4933 !one->dirty_submodule && !two->dirty_submodule)
4934 return 1; /* no change */
4935 if (!one->oid_valid && !two->oid_valid)
4936 return 1; /* both look at the same file on the filesystem. */
4940 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
4942 if (diff_unmodified_pair(p))
4945 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4946 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4947 return; /* no tree diffs in patch format */
4952 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
4953 struct diffstat_t *diffstat)
4955 if (diff_unmodified_pair(p))
4958 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4959 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4960 return; /* no useful stat for tree diffs */
4962 run_diffstat(p, o, diffstat);
4965 static void diff_flush_checkdiff(struct diff_filepair *p,
4966 struct diff_options *o)
4968 if (diff_unmodified_pair(p))
4971 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4972 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4973 return; /* nothing to check in tree diffs */
4975 run_checkdiff(p, o);
4978 int diff_queue_is_empty(void)
4980 struct diff_queue_struct *q = &diff_queued_diff;
4982 for (i = 0; i < q->nr; i++)
4983 if (!diff_unmodified_pair(q->queue[i]))
4989 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
4991 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
4994 DIFF_FILE_VALID(s) ? "valid" : "invalid",
4996 s->oid_valid ? oid_to_hex(&s->oid) : "");
4997 fprintf(stderr, "queue[%d] %s size %lu\n",
5002 void diff_debug_filepair(const struct diff_filepair *p, int i)
5004 diff_debug_filespec(p->one, i, "one");
5005 diff_debug_filespec(p->two, i, "two");
5006 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5007 p->score, p->status ? p->status : '?',
5008 p->one->rename_used, p->broken_pair);
5011 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5015 fprintf(stderr, "%s\n", msg);
5016 fprintf(stderr, "q->nr = %d\n", q->nr);
5017 for (i = 0; i < q->nr; i++) {
5018 struct diff_filepair *p = q->queue[i];
5019 diff_debug_filepair(p, i);
5024 static void diff_resolve_rename_copy(void)
5027 struct diff_filepair *p;
5028 struct diff_queue_struct *q = &diff_queued_diff;
5030 diff_debug_queue("resolve-rename-copy", q);
5032 for (i = 0; i < q->nr; i++) {
5034 p->status = 0; /* undecided */
5035 if (DIFF_PAIR_UNMERGED(p))
5036 p->status = DIFF_STATUS_UNMERGED;
5037 else if (!DIFF_FILE_VALID(p->one))
5038 p->status = DIFF_STATUS_ADDED;
5039 else if (!DIFF_FILE_VALID(p->two))
5040 p->status = DIFF_STATUS_DELETED;
5041 else if (DIFF_PAIR_TYPE_CHANGED(p))
5042 p->status = DIFF_STATUS_TYPE_CHANGED;
5044 /* from this point on, we are dealing with a pair
5045 * whose both sides are valid and of the same type, i.e.
5046 * either in-place edit or rename/copy edit.
5048 else if (DIFF_PAIR_RENAME(p)) {
5050 * A rename might have re-connected a broken
5051 * pair up, causing the pathnames to be the
5052 * same again. If so, that's not a rename at
5053 * all, just a modification..
5055 * Otherwise, see if this source was used for
5056 * multiple renames, in which case we decrement
5057 * the count, and call it a copy.
5059 if (!strcmp(p->one->path, p->two->path))
5060 p->status = DIFF_STATUS_MODIFIED;
5061 else if (--p->one->rename_used > 0)
5062 p->status = DIFF_STATUS_COPIED;
5064 p->status = DIFF_STATUS_RENAMED;
5066 else if (oidcmp(&p->one->oid, &p->two->oid) ||
5067 p->one->mode != p->two->mode ||
5068 p->one->dirty_submodule ||
5069 p->two->dirty_submodule ||
5070 is_null_oid(&p->one->oid))
5071 p->status = DIFF_STATUS_MODIFIED;
5073 /* This is a "no-change" entry and should not
5074 * happen anymore, but prepare for broken callers.
5076 error("feeding unmodified %s to diffcore",
5078 p->status = DIFF_STATUS_UNKNOWN;
5081 diff_debug_queue("resolve-rename-copy done", q);
5084 static int check_pair_status(struct diff_filepair *p)
5086 switch (p->status) {
5087 case DIFF_STATUS_UNKNOWN:
5090 die("internal error in diff-resolve-rename-copy");
5096 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5098 int fmt = opt->output_format;
5100 if (fmt & DIFF_FORMAT_CHECKDIFF)
5101 diff_flush_checkdiff(p, opt);
5102 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5103 diff_flush_raw(p, opt);
5104 else if (fmt & DIFF_FORMAT_NAME) {
5105 const char *name_a, *name_b;
5106 name_a = p->two->path;
5108 strip_prefix(opt->prefix_length, &name_a, &name_b);
5109 fprintf(opt->file, "%s", diff_line_prefix(opt));
5110 write_name_quoted(name_a, opt->file, opt->line_termination);
5114 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5116 struct strbuf sb = STRBUF_INIT;
5118 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5120 strbuf_addf(&sb, " %s ", newdelete);
5122 quote_c_style(fs->path, &sb, NULL, 0);
5123 strbuf_addch(&sb, '\n');
5124 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5126 strbuf_release(&sb);
5129 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5132 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5133 struct strbuf sb = STRBUF_INIT;
5134 strbuf_addf(&sb, " mode change %06o => %06o",
5135 p->one->mode, p->two->mode);
5137 strbuf_addch(&sb, ' ');
5138 quote_c_style(p->two->path, &sb, NULL, 0);
5140 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5142 strbuf_release(&sb);
5146 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5147 struct diff_filepair *p)
5149 struct strbuf sb = STRBUF_INIT;
5150 char *names = pprint_rename(p->one->path, p->two->path);
5151 strbuf_addf(&sb, " %s %s (%d%%)\n",
5152 renamecopy, names, similarity_index(p));
5154 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5156 show_mode_change(opt, p, 0);
5159 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5162 case DIFF_STATUS_DELETED:
5163 show_file_mode_name(opt, "delete", p->one);
5165 case DIFF_STATUS_ADDED:
5166 show_file_mode_name(opt, "create", p->two);
5168 case DIFF_STATUS_COPIED:
5169 show_rename_copy(opt, "copy", p);
5171 case DIFF_STATUS_RENAMED:
5172 show_rename_copy(opt, "rename", p);
5176 struct strbuf sb = STRBUF_INIT;
5177 strbuf_addstr(&sb, " rewrite ");
5178 quote_c_style(p->two->path, &sb, NULL, 0);
5179 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5180 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5183 show_mode_change(opt, p, !p->score);
5193 static int remove_space(char *line, int len)
5199 for (i = 0; i < len; i++)
5200 if (!isspace((c = line[i])))
5206 static void patch_id_consume(void *priv, char *line, unsigned long len)
5208 struct patch_id_t *data = priv;
5211 /* Ignore line numbers when computing the SHA1 of the patch */
5212 if (starts_with(line, "@@ -"))
5215 new_len = remove_space(line, len);
5217 git_SHA1_Update(data->ctx, line, new_len);
5218 data->patchlen += new_len;
5221 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
5223 git_SHA1_Update(ctx, str, strlen(str));
5226 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
5228 /* large enough for 2^32 in octal */
5230 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
5231 git_SHA1_Update(ctx, buf, len);
5234 /* returns 0 upon success, and writes result into sha1 */
5235 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5237 struct diff_queue_struct *q = &diff_queued_diff;
5240 struct patch_id_t data;
5242 git_SHA1_Init(&ctx);
5243 memset(&data, 0, sizeof(struct patch_id_t));
5246 for (i = 0; i < q->nr; i++) {
5250 struct diff_filepair *p = q->queue[i];
5253 memset(&xpp, 0, sizeof(xpp));
5254 memset(&xecfg, 0, sizeof(xecfg));
5256 return error("internal diff status error");
5257 if (p->status == DIFF_STATUS_UNKNOWN)
5259 if (diff_unmodified_pair(p))
5261 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5262 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5264 if (DIFF_PAIR_UNMERGED(p))
5267 diff_fill_oid_info(p->one);
5268 diff_fill_oid_info(p->two);
5270 len1 = remove_space(p->one->path, strlen(p->one->path));
5271 len2 = remove_space(p->two->path, strlen(p->two->path));
5272 patch_id_add_string(&ctx, "diff--git");
5273 patch_id_add_string(&ctx, "a/");
5274 git_SHA1_Update(&ctx, p->one->path, len1);
5275 patch_id_add_string(&ctx, "b/");
5276 git_SHA1_Update(&ctx, p->two->path, len2);
5278 if (p->one->mode == 0) {
5279 patch_id_add_string(&ctx, "newfilemode");
5280 patch_id_add_mode(&ctx, p->two->mode);
5281 patch_id_add_string(&ctx, "---/dev/null");
5282 patch_id_add_string(&ctx, "+++b/");
5283 git_SHA1_Update(&ctx, p->two->path, len2);
5284 } else if (p->two->mode == 0) {
5285 patch_id_add_string(&ctx, "deletedfilemode");
5286 patch_id_add_mode(&ctx, p->one->mode);
5287 patch_id_add_string(&ctx, "---a/");
5288 git_SHA1_Update(&ctx, p->one->path, len1);
5289 patch_id_add_string(&ctx, "+++/dev/null");
5291 patch_id_add_string(&ctx, "---a/");
5292 git_SHA1_Update(&ctx, p->one->path, len1);
5293 patch_id_add_string(&ctx, "+++b/");
5294 git_SHA1_Update(&ctx, p->two->path, len2);
5297 if (diff_header_only)
5300 if (fill_mmfile(&mf1, p->one) < 0 ||
5301 fill_mmfile(&mf2, p->two) < 0)
5302 return error("unable to read files to diff");
5304 if (diff_filespec_is_binary(p->one) ||
5305 diff_filespec_is_binary(p->two)) {
5306 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5308 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5316 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
5318 return error("unable to generate patch-id diff for %s",
5322 git_SHA1_Final(oid->hash, &ctx);
5326 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5328 struct diff_queue_struct *q = &diff_queued_diff;
5330 int result = diff_get_patch_id(options, oid, diff_header_only);
5332 for (i = 0; i < q->nr; i++)
5333 diff_free_filepair(q->queue[i]);
5336 DIFF_QUEUE_CLEAR(q);
5341 static int is_summary_empty(const struct diff_queue_struct *q)
5345 for (i = 0; i < q->nr; i++) {
5346 const struct diff_filepair *p = q->queue[i];
5348 switch (p->status) {
5349 case DIFF_STATUS_DELETED:
5350 case DIFF_STATUS_ADDED:
5351 case DIFF_STATUS_COPIED:
5352 case DIFF_STATUS_RENAMED:
5357 if (p->one->mode && p->two->mode &&
5358 p->one->mode != p->two->mode)
5366 static const char rename_limit_warning[] =
5367 N_("inexact rename detection was skipped due to too many files.");
5369 static const char degrade_cc_to_c_warning[] =
5370 N_("only found copies from modified paths due to too many files.");
5372 static const char rename_limit_advice[] =
5373 N_("you may want to set your %s variable to at least "
5374 "%d and retry the command.");
5376 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
5379 warning(_(degrade_cc_to_c_warning));
5381 warning(_(rename_limit_warning));
5384 if (0 < needed && needed < 32767)
5385 warning(_(rename_limit_advice), varname, needed);
5388 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
5391 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
5392 struct diff_queue_struct *q = &diff_queued_diff;
5394 if (WSEH_NEW & WS_RULE_MASK)
5395 die("BUG: WS rules bit mask overlaps with diff symbol flags");
5398 o->emitted_symbols = &esm;
5400 for (i = 0; i < q->nr; i++) {
5401 struct diff_filepair *p = q->queue[i];
5402 if (check_pair_status(p))
5403 diff_flush_patch(p, o);
5406 if (o->emitted_symbols) {
5407 if (o->color_moved) {
5408 struct hashmap add_lines, del_lines;
5410 hashmap_init(&del_lines,
5411 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5412 hashmap_init(&add_lines,
5413 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5415 add_lines_to_move_detection(o, &add_lines, &del_lines);
5416 mark_color_as_moved(o, &add_lines, &del_lines);
5418 hashmap_free(&add_lines, 0);
5419 hashmap_free(&del_lines, 0);
5422 for (i = 0; i < esm.nr; i++)
5423 emit_diff_symbol_from_struct(o, &esm.buf[i]);
5425 for (i = 0; i < esm.nr; i++)
5426 free((void *)esm.buf[i].line);
5431 void diff_flush(struct diff_options *options)
5433 struct diff_queue_struct *q = &diff_queued_diff;
5434 int i, output_format = options->output_format;
5436 int dirstat_by_line = 0;
5439 * Order: raw, stat, summary, patch
5440 * or: name/name-status/checkdiff (other bits clear)
5445 if (output_format & (DIFF_FORMAT_RAW |
5447 DIFF_FORMAT_NAME_STATUS |
5448 DIFF_FORMAT_CHECKDIFF)) {
5449 for (i = 0; i < q->nr; i++) {
5450 struct diff_filepair *p = q->queue[i];
5451 if (check_pair_status(p))
5452 flush_one_pair(p, options);
5457 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
5458 dirstat_by_line = 1;
5460 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
5462 struct diffstat_t diffstat;
5464 memset(&diffstat, 0, sizeof(struct diffstat_t));
5465 for (i = 0; i < q->nr; i++) {
5466 struct diff_filepair *p = q->queue[i];
5467 if (check_pair_status(p))
5468 diff_flush_stat(p, options, &diffstat);
5470 if (output_format & DIFF_FORMAT_NUMSTAT)
5471 show_numstat(&diffstat, options);
5472 if (output_format & DIFF_FORMAT_DIFFSTAT)
5473 show_stats(&diffstat, options);
5474 if (output_format & DIFF_FORMAT_SHORTSTAT)
5475 show_shortstats(&diffstat, options);
5476 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
5477 show_dirstat_by_line(&diffstat, options);
5478 free_diffstat_info(&diffstat);
5481 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
5482 show_dirstat(options);
5484 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
5485 for (i = 0; i < q->nr; i++) {
5486 diff_summary(options, q->queue[i]);
5491 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
5492 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
5493 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
5495 * run diff_flush_patch for the exit status. setting
5496 * options->file to /dev/null should be safe, because we
5497 * aren't supposed to produce any output anyway.
5499 if (options->close_file)
5500 fclose(options->file);
5501 options->file = xfopen("/dev/null", "w");
5502 options->close_file = 1;
5503 options->color_moved = 0;
5504 for (i = 0; i < q->nr; i++) {
5505 struct diff_filepair *p = q->queue[i];
5506 if (check_pair_status(p))
5507 diff_flush_patch(p, options);
5508 if (options->found_changes)
5513 if (output_format & DIFF_FORMAT_PATCH) {
5515 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
5516 if (options->stat_sep)
5517 /* attach patch instead of inline */
5518 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
5522 diff_flush_patch_all_file_pairs(options);
5525 if (output_format & DIFF_FORMAT_CALLBACK)
5526 options->format_callback(q, options, options->format_callback_data);
5528 for (i = 0; i < q->nr; i++)
5529 diff_free_filepair(q->queue[i]);
5532 DIFF_QUEUE_CLEAR(q);
5533 if (options->close_file)
5534 fclose(options->file);
5537 * Report the content-level differences with HAS_CHANGES;
5538 * diff_addremove/diff_change does not set the bit when
5539 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
5541 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
5542 if (options->found_changes)
5543 DIFF_OPT_SET(options, HAS_CHANGES);
5545 DIFF_OPT_CLR(options, HAS_CHANGES);
5549 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
5551 return (((p->status == DIFF_STATUS_MODIFIED) &&
5553 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
5555 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
5556 ((p->status != DIFF_STATUS_MODIFIED) &&
5557 filter_bit_tst(p->status, options)));
5560 static void diffcore_apply_filter(struct diff_options *options)
5563 struct diff_queue_struct *q = &diff_queued_diff;
5564 struct diff_queue_struct outq;
5566 DIFF_QUEUE_CLEAR(&outq);
5568 if (!options->filter)
5571 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
5573 for (i = found = 0; !found && i < q->nr; i++) {
5574 if (match_filter(options, q->queue[i]))
5580 /* otherwise we will clear the whole queue
5581 * by copying the empty outq at the end of this
5582 * function, but first clear the current entries
5585 for (i = 0; i < q->nr; i++)
5586 diff_free_filepair(q->queue[i]);
5589 /* Only the matching ones */
5590 for (i = 0; i < q->nr; i++) {
5591 struct diff_filepair *p = q->queue[i];
5592 if (match_filter(options, p))
5595 diff_free_filepair(p);
5602 /* Check whether two filespecs with the same mode and size are identical */
5603 static int diff_filespec_is_identical(struct diff_filespec *one,
5604 struct diff_filespec *two)
5606 if (S_ISGITLINK(one->mode))
5608 if (diff_populate_filespec(one, 0))
5610 if (diff_populate_filespec(two, 0))
5612 return !memcmp(one->data, two->data, one->size);
5615 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
5617 if (p->done_skip_stat_unmatch)
5618 return p->skip_stat_unmatch_result;
5620 p->done_skip_stat_unmatch = 1;
5621 p->skip_stat_unmatch_result = 0;
5623 * 1. Entries that come from stat info dirtiness
5624 * always have both sides (iow, not create/delete),
5625 * one side of the object name is unknown, with
5626 * the same mode and size. Keep the ones that
5627 * do not match these criteria. They have real
5630 * 2. At this point, the file is known to be modified,
5631 * with the same mode and size, and the object
5632 * name of one side is unknown. Need to inspect
5633 * the identical contents.
5635 if (!DIFF_FILE_VALID(p->one) || /* (1) */
5636 !DIFF_FILE_VALID(p->two) ||
5637 (p->one->oid_valid && p->two->oid_valid) ||
5638 (p->one->mode != p->two->mode) ||
5639 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
5640 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
5641 (p->one->size != p->two->size) ||
5642 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
5643 p->skip_stat_unmatch_result = 1;
5644 return p->skip_stat_unmatch_result;
5647 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
5650 struct diff_queue_struct *q = &diff_queued_diff;
5651 struct diff_queue_struct outq;
5652 DIFF_QUEUE_CLEAR(&outq);
5654 for (i = 0; i < q->nr; i++) {
5655 struct diff_filepair *p = q->queue[i];
5657 if (diff_filespec_check_stat_unmatch(p))
5661 * The caller can subtract 1 from skip_stat_unmatch
5662 * to determine how many paths were dirty only
5663 * due to stat info mismatch.
5665 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
5666 diffopt->skip_stat_unmatch++;
5667 diff_free_filepair(p);
5674 static int diffnamecmp(const void *a_, const void *b_)
5676 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
5677 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
5678 const char *name_a, *name_b;
5680 name_a = a->one ? a->one->path : a->two->path;
5681 name_b = b->one ? b->one->path : b->two->path;
5682 return strcmp(name_a, name_b);
5685 void diffcore_fix_diff_index(struct diff_options *options)
5687 struct diff_queue_struct *q = &diff_queued_diff;
5688 QSORT(q->queue, q->nr, diffnamecmp);
5691 void diffcore_std(struct diff_options *options)
5693 /* NOTE please keep the following in sync with diff_tree_combined() */
5694 if (options->skip_stat_unmatch)
5695 diffcore_skip_stat_unmatch(options);
5696 if (!options->found_follow) {
5697 /* See try_to_follow_renames() in tree-diff.c */
5698 if (options->break_opt != -1)
5699 diffcore_break(options->break_opt);
5700 if (options->detect_rename)
5701 diffcore_rename(options);
5702 if (options->break_opt != -1)
5703 diffcore_merge_broken();
5705 if (options->pickaxe)
5706 diffcore_pickaxe(options);
5707 if (options->orderfile)
5708 diffcore_order(options->orderfile);
5709 if (!options->found_follow)
5710 /* See try_to_follow_renames() in tree-diff.c */
5711 diff_resolve_rename_copy();
5712 diffcore_apply_filter(options);
5714 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5715 DIFF_OPT_SET(options, HAS_CHANGES);
5717 DIFF_OPT_CLR(options, HAS_CHANGES);
5719 options->found_follow = 0;
5722 int diff_result_code(struct diff_options *opt, int status)
5726 diff_warn_rename_limit("diff.renameLimit",
5727 opt->needed_rename_limit,
5728 opt->degraded_cc_to_c);
5729 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5730 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
5732 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5733 DIFF_OPT_TST(opt, HAS_CHANGES))
5735 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
5736 DIFF_OPT_TST(opt, CHECK_FAILED))
5741 int diff_can_quit_early(struct diff_options *opt)
5743 return (DIFF_OPT_TST(opt, QUICK) &&
5745 DIFF_OPT_TST(opt, HAS_CHANGES));
5749 * Shall changes to this submodule be ignored?
5751 * Submodule changes can be configured to be ignored separately for each path,
5752 * but that configuration can be overridden from the command line.
5754 static int is_submodule_ignored(const char *path, struct diff_options *options)
5757 unsigned orig_flags = options->flags;
5758 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
5759 set_diffopt_flags_from_submodule_config(options, path);
5760 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
5762 options->flags = orig_flags;
5766 void diff_addremove(struct diff_options *options,
5767 int addremove, unsigned mode,
5768 const struct object_id *oid,
5770 const char *concatpath, unsigned dirty_submodule)
5772 struct diff_filespec *one, *two;
5774 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
5777 /* This may look odd, but it is a preparation for
5778 * feeding "there are unchanged files which should
5779 * not produce diffs, but when you are doing copy
5780 * detection you would need them, so here they are"
5781 * entries to the diff-core. They will be prefixed
5782 * with something like '=' or '*' (I haven't decided
5783 * which but should not make any difference).
5784 * Feeding the same new and old to diff_change()
5785 * also has the same effect.
5786 * Before the final output happens, they are pruned after
5787 * merged into rename/copy pairs as appropriate.
5789 if (DIFF_OPT_TST(options, REVERSE_DIFF))
5790 addremove = (addremove == '+' ? '-' :
5791 addremove == '-' ? '+' : addremove);
5793 if (options->prefix &&
5794 strncmp(concatpath, options->prefix, options->prefix_length))
5797 one = alloc_filespec(concatpath);
5798 two = alloc_filespec(concatpath);
5800 if (addremove != '+')
5801 fill_filespec(one, oid, oid_valid, mode);
5802 if (addremove != '-') {
5803 fill_filespec(two, oid, oid_valid, mode);
5804 two->dirty_submodule = dirty_submodule;
5807 diff_queue(&diff_queued_diff, one, two);
5808 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5809 DIFF_OPT_SET(options, HAS_CHANGES);
5812 void diff_change(struct diff_options *options,
5813 unsigned old_mode, unsigned new_mode,
5814 const struct object_id *old_oid,
5815 const struct object_id *new_oid,
5816 int old_oid_valid, int new_oid_valid,
5817 const char *concatpath,
5818 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5820 struct diff_filespec *one, *two;
5821 struct diff_filepair *p;
5823 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
5824 is_submodule_ignored(concatpath, options))
5827 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
5828 SWAP(old_mode, new_mode);
5829 SWAP(old_oid, new_oid);
5830 SWAP(old_oid_valid, new_oid_valid);
5831 SWAP(old_dirty_submodule, new_dirty_submodule);
5834 if (options->prefix &&
5835 strncmp(concatpath, options->prefix, options->prefix_length))
5838 one = alloc_filespec(concatpath);
5839 two = alloc_filespec(concatpath);
5840 fill_filespec(one, old_oid, old_oid_valid, old_mode);
5841 fill_filespec(two, new_oid, new_oid_valid, new_mode);
5842 one->dirty_submodule = old_dirty_submodule;
5843 two->dirty_submodule = new_dirty_submodule;
5844 p = diff_queue(&diff_queued_diff, one, two);
5846 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5849 if (DIFF_OPT_TST(options, QUICK) && options->skip_stat_unmatch &&
5850 !diff_filespec_check_stat_unmatch(p))
5853 DIFF_OPT_SET(options, HAS_CHANGES);
5856 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
5858 struct diff_filepair *pair;
5859 struct diff_filespec *one, *two;
5861 if (options->prefix &&
5862 strncmp(path, options->prefix, options->prefix_length))
5865 one = alloc_filespec(path);
5866 two = alloc_filespec(path);
5867 pair = diff_queue(&diff_queued_diff, one, two);
5868 pair->is_unmerged = 1;
5872 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
5875 struct diff_tempfile *temp;
5876 const char *argv[3];
5877 const char **arg = argv;
5878 struct child_process child = CHILD_PROCESS_INIT;
5879 struct strbuf buf = STRBUF_INIT;
5882 temp = prepare_temp_file(spec->path, spec);
5884 *arg++ = temp->name;
5887 child.use_shell = 1;
5890 if (start_command(&child)) {
5895 if (strbuf_read(&buf, child.out, 0) < 0)
5896 err = error("error reading from textconv command '%s'", pgm);
5899 if (finish_command(&child) || err) {
5900 strbuf_release(&buf);
5906 return strbuf_detach(&buf, outsize);
5909 size_t fill_textconv(struct userdiff_driver *driver,
5910 struct diff_filespec *df,
5916 if (!DIFF_FILE_VALID(df)) {
5920 if (diff_populate_filespec(df, 0))
5921 die("unable to read files to diff");
5926 if (!driver->textconv)
5927 die("BUG: fill_textconv called with non-textconv driver");
5929 if (driver->textconv_cache && df->oid_valid) {
5930 *outbuf = notes_cache_get(driver->textconv_cache,
5937 *outbuf = run_textconv(driver->textconv, df, &size);
5939 die("unable to read files to diff");
5941 if (driver->textconv_cache && df->oid_valid) {
5942 /* ignore errors, as we might be in a readonly repository */
5943 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
5946 * we could save up changes and flush them all at the end,
5947 * but we would need an extra call after all diffing is done.
5948 * Since generating a cache entry is the slow path anyway,
5949 * this extra overhead probably isn't a big deal.
5951 notes_cache_write(driver->textconv_cache);
5957 int textconv_object(const char *path,
5959 const struct object_id *oid,
5962 unsigned long *buf_size)
5964 struct diff_filespec *df;
5965 struct userdiff_driver *textconv;
5967 df = alloc_filespec(path);
5968 fill_filespec(df, oid, oid_valid, mode);
5969 textconv = get_textconv(df);
5975 *buf_size = fill_textconv(textconv, df, buf);
5980 void setup_diff_pager(struct diff_options *opt)
5983 * If the user asked for our exit code, then either they want --quiet
5984 * or --exit-code. We should definitely not bother with a pager in the
5985 * former case, as we will generate no output. Since we still properly
5986 * report our exit code even when a pager is run, we _could_ run a
5987 * pager with --exit-code. But since we have not done so historically,
5988 * and because it is easy to find people oneline advising "git diff
5989 * --exit-code" in hooks and other scripts, we do not do so.
5991 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5992 check_pager_config("diff") != 0)