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"
26 #ifdef NO_FAST_WORKING_DIRECTORY
27 #define FAST_WORKING_DIRECTORY 0
29 #define FAST_WORKING_DIRECTORY 1
32 static int diff_detect_rename_default;
33 static int diff_indent_heuristic = 1;
34 static int diff_rename_limit_default = 400;
35 static int diff_suppress_blank_empty;
36 static int diff_use_color_default = -1;
37 static int diff_color_moved_default;
38 static int diff_context_default = 3;
39 static int diff_interhunk_context_default;
40 static const char *diff_word_regex_cfg;
41 static const char *external_diff_cmd_cfg;
42 static const char *diff_order_file_cfg;
43 int diff_auto_refresh_index = 1;
44 static int diff_mnemonic_prefix;
45 static int diff_no_prefix;
46 static int diff_stat_graph_width;
47 static int diff_dirstat_permille_default = 30;
48 static struct diff_options default_diff_options;
49 static long diff_algorithm;
50 static unsigned ws_error_highlight_default = WSEH_NEW;
52 static char diff_colors[][COLOR_MAXLEN] = {
54 GIT_COLOR_NORMAL, /* CONTEXT */
55 GIT_COLOR_BOLD, /* METAINFO */
56 GIT_COLOR_CYAN, /* FRAGINFO */
57 GIT_COLOR_RED, /* OLD */
58 GIT_COLOR_GREEN, /* NEW */
59 GIT_COLOR_YELLOW, /* COMMIT */
60 GIT_COLOR_BG_RED, /* WHITESPACE */
61 GIT_COLOR_NORMAL, /* FUNCINFO */
62 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
63 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
64 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
65 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
66 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
67 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
68 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
69 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
72 static NORETURN void die_want_option(const char *option_name)
74 die(_("option '%s' requires a value"), option_name);
77 static int parse_diff_color_slot(const char *var)
79 if (!strcasecmp(var, "context") || !strcasecmp(var, "plain"))
81 if (!strcasecmp(var, "meta"))
83 if (!strcasecmp(var, "frag"))
85 if (!strcasecmp(var, "old"))
87 if (!strcasecmp(var, "new"))
89 if (!strcasecmp(var, "commit"))
91 if (!strcasecmp(var, "whitespace"))
92 return DIFF_WHITESPACE;
93 if (!strcasecmp(var, "func"))
95 if (!strcasecmp(var, "oldmoved"))
96 return DIFF_FILE_OLD_MOVED;
97 if (!strcasecmp(var, "oldmovedalternative"))
98 return DIFF_FILE_OLD_MOVED_ALT;
99 if (!strcasecmp(var, "oldmoveddimmed"))
100 return DIFF_FILE_OLD_MOVED_DIM;
101 if (!strcasecmp(var, "oldmovedalternativedimmed"))
102 return DIFF_FILE_OLD_MOVED_ALT_DIM;
103 if (!strcasecmp(var, "newmoved"))
104 return DIFF_FILE_NEW_MOVED;
105 if (!strcasecmp(var, "newmovedalternative"))
106 return DIFF_FILE_NEW_MOVED_ALT;
107 if (!strcasecmp(var, "newmoveddimmed"))
108 return DIFF_FILE_NEW_MOVED_DIM;
109 if (!strcasecmp(var, "newmovedalternativedimmed"))
110 return DIFF_FILE_NEW_MOVED_ALT_DIM;
114 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
115 struct strbuf *errmsg)
117 char *params_copy = xstrdup(params_string);
118 struct string_list params = STRING_LIST_INIT_NODUP;
123 string_list_split_in_place(¶ms, params_copy, ',', -1);
124 for (i = 0; i < params.nr; i++) {
125 const char *p = params.items[i].string;
126 if (!strcmp(p, "changes")) {
127 options->flags.dirstat_by_line = 0;
128 options->flags.dirstat_by_file = 0;
129 } else if (!strcmp(p, "lines")) {
130 options->flags.dirstat_by_line = 1;
131 options->flags.dirstat_by_file = 0;
132 } else if (!strcmp(p, "files")) {
133 options->flags.dirstat_by_line = 0;
134 options->flags.dirstat_by_file = 1;
135 } else if (!strcmp(p, "noncumulative")) {
136 options->flags.dirstat_cumulative = 0;
137 } else if (!strcmp(p, "cumulative")) {
138 options->flags.dirstat_cumulative = 1;
139 } else if (isdigit(*p)) {
141 int permille = strtoul(p, &end, 10) * 10;
142 if (*end == '.' && isdigit(*++end)) {
143 /* only use first digit */
144 permille += *end - '0';
145 /* .. and ignore any further digits */
146 while (isdigit(*++end))
150 options->dirstat_permille = permille;
152 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
157 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
162 string_list_clear(¶ms, 0);
167 static int parse_submodule_params(struct diff_options *options, const char *value)
169 if (!strcmp(value, "log"))
170 options->submodule_format = DIFF_SUBMODULE_LOG;
171 else if (!strcmp(value, "short"))
172 options->submodule_format = DIFF_SUBMODULE_SHORT;
173 else if (!strcmp(value, "diff"))
174 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
180 static int git_config_rename(const char *var, const char *value)
183 return DIFF_DETECT_RENAME;
184 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
185 return DIFF_DETECT_COPY;
186 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
189 long parse_algorithm_value(const char *value)
193 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
195 else if (!strcasecmp(value, "minimal"))
196 return XDF_NEED_MINIMAL;
197 else if (!strcasecmp(value, "patience"))
198 return XDF_PATIENCE_DIFF;
199 else if (!strcasecmp(value, "histogram"))
200 return XDF_HISTOGRAM_DIFF;
204 static int parse_one_token(const char **arg, const char *token)
207 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
214 static int parse_ws_error_highlight(const char *arg)
216 const char *orig_arg = arg;
220 if (parse_one_token(&arg, "none"))
222 else if (parse_one_token(&arg, "default"))
224 else if (parse_one_token(&arg, "all"))
225 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
226 else if (parse_one_token(&arg, "new"))
228 else if (parse_one_token(&arg, "old"))
230 else if (parse_one_token(&arg, "context"))
233 return -1 - (int)(arg - orig_arg);
242 * These are to give UI layer defaults.
243 * The core-level commands such as git-diff-files should
244 * never be affected by the setting of diff.renames
245 * the user happens to have in the configuration file.
247 void init_diff_ui_defaults(void)
249 diff_detect_rename_default = DIFF_DETECT_RENAME;
252 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
254 if (!strcmp(var, "diff.indentheuristic"))
255 diff_indent_heuristic = git_config_bool(var, value);
259 static int parse_color_moved(const char *arg)
261 switch (git_parse_maybe_bool(arg)) {
263 return COLOR_MOVED_NO;
265 return COLOR_MOVED_DEFAULT;
270 if (!strcmp(arg, "no"))
271 return COLOR_MOVED_NO;
272 else if (!strcmp(arg, "plain"))
273 return COLOR_MOVED_PLAIN;
274 else if (!strcmp(arg, "blocks"))
275 return COLOR_MOVED_BLOCKS;
276 else if (!strcmp(arg, "zebra"))
277 return COLOR_MOVED_ZEBRA;
278 else if (!strcmp(arg, "default"))
279 return COLOR_MOVED_DEFAULT;
280 else if (!strcmp(arg, "dimmed_zebra"))
281 return COLOR_MOVED_ZEBRA_DIM;
283 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed_zebra', 'plain'"));
286 static int parse_color_moved_ws(const char *arg)
289 struct string_list l = STRING_LIST_INIT_DUP;
290 struct string_list_item *i;
292 string_list_split(&l, arg, ',', -1);
294 for_each_string_list_item(i, &l) {
295 struct strbuf sb = STRBUF_INIT;
296 strbuf_addstr(&sb, i->string);
299 if (!strcmp(sb.buf, "ignore-space-change"))
300 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
301 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
302 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
303 else if (!strcmp(sb.buf, "ignore-all-space"))
304 ret |= XDF_IGNORE_WHITESPACE;
306 error(_("ignoring unknown color-moved-ws mode '%s'"), sb.buf);
311 string_list_clear(&l, 0);
316 int git_diff_ui_config(const char *var, const char *value, void *cb)
318 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
319 diff_use_color_default = git_config_colorbool(var, value);
322 if (!strcmp(var, "diff.colormoved")) {
323 int cm = parse_color_moved(value);
326 diff_color_moved_default = cm;
329 if (!strcmp(var, "diff.context")) {
330 diff_context_default = git_config_int(var, value);
331 if (diff_context_default < 0)
335 if (!strcmp(var, "diff.interhunkcontext")) {
336 diff_interhunk_context_default = git_config_int(var, value);
337 if (diff_interhunk_context_default < 0)
341 if (!strcmp(var, "diff.renames")) {
342 diff_detect_rename_default = git_config_rename(var, value);
345 if (!strcmp(var, "diff.autorefreshindex")) {
346 diff_auto_refresh_index = git_config_bool(var, value);
349 if (!strcmp(var, "diff.mnemonicprefix")) {
350 diff_mnemonic_prefix = git_config_bool(var, value);
353 if (!strcmp(var, "diff.noprefix")) {
354 diff_no_prefix = git_config_bool(var, value);
357 if (!strcmp(var, "diff.statgraphwidth")) {
358 diff_stat_graph_width = git_config_int(var, value);
361 if (!strcmp(var, "diff.external"))
362 return git_config_string(&external_diff_cmd_cfg, var, value);
363 if (!strcmp(var, "diff.wordregex"))
364 return git_config_string(&diff_word_regex_cfg, var, value);
365 if (!strcmp(var, "diff.orderfile"))
366 return git_config_pathname(&diff_order_file_cfg, var, value);
368 if (!strcmp(var, "diff.ignoresubmodules"))
369 handle_ignore_submodules_arg(&default_diff_options, value);
371 if (!strcmp(var, "diff.submodule")) {
372 if (parse_submodule_params(&default_diff_options, value))
373 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
378 if (!strcmp(var, "diff.algorithm")) {
379 diff_algorithm = parse_algorithm_value(value);
380 if (diff_algorithm < 0)
385 if (!strcmp(var, "diff.wserrorhighlight")) {
386 int val = parse_ws_error_highlight(value);
389 ws_error_highlight_default = val;
393 if (git_color_config(var, value, cb) < 0)
396 return git_diff_basic_config(var, value, cb);
399 int git_diff_basic_config(const char *var, const char *value, void *cb)
403 if (!strcmp(var, "diff.renamelimit")) {
404 diff_rename_limit_default = git_config_int(var, value);
408 if (userdiff_config(var, value) < 0)
411 if (skip_prefix(var, "diff.color.", &name) ||
412 skip_prefix(var, "color.diff.", &name)) {
413 int slot = parse_diff_color_slot(name);
417 return config_error_nonbool(var);
418 return color_parse(value, diff_colors[slot]);
421 /* like GNU diff's --suppress-blank-empty option */
422 if (!strcmp(var, "diff.suppressblankempty") ||
423 /* for backwards compatibility */
424 !strcmp(var, "diff.suppress-blank-empty")) {
425 diff_suppress_blank_empty = git_config_bool(var, value);
429 if (!strcmp(var, "diff.dirstat")) {
430 struct strbuf errmsg = STRBUF_INIT;
431 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
432 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
433 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
435 strbuf_release(&errmsg);
436 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
440 if (git_diff_heuristic_config(var, value, cb) < 0)
443 return git_default_config(var, value, cb);
446 static char *quote_two(const char *one, const char *two)
448 int need_one = quote_c_style(one, NULL, NULL, 1);
449 int need_two = quote_c_style(two, NULL, NULL, 1);
450 struct strbuf res = STRBUF_INIT;
452 if (need_one + need_two) {
453 strbuf_addch(&res, '"');
454 quote_c_style(one, &res, NULL, 1);
455 quote_c_style(two, &res, NULL, 1);
456 strbuf_addch(&res, '"');
458 strbuf_addstr(&res, one);
459 strbuf_addstr(&res, two);
461 return strbuf_detach(&res, NULL);
464 static const char *external_diff(void)
466 static const char *external_diff_cmd = NULL;
467 static int done_preparing = 0;
470 return external_diff_cmd;
471 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
472 if (!external_diff_cmd)
473 external_diff_cmd = external_diff_cmd_cfg;
475 return external_diff_cmd;
479 * Keep track of files used for diffing. Sometimes such an entry
480 * refers to a temporary file, sometimes to an existing file, and
481 * sometimes to "/dev/null".
483 static struct diff_tempfile {
485 * filename external diff should read from, or NULL if this
486 * entry is currently not in use:
490 char hex[GIT_MAX_HEXSZ + 1];
494 * If this diff_tempfile instance refers to a temporary file,
495 * this tempfile object is used to manage its lifetime.
497 struct tempfile *tempfile;
500 struct emit_callback {
503 int blank_at_eof_in_preimage;
504 int blank_at_eof_in_postimage;
506 int lno_in_postimage;
507 const char **label_path;
508 struct diff_words_data *diff_words;
509 struct diff_options *opt;
510 struct strbuf *header;
513 static int count_lines(const char *data, int size)
515 int count, ch, completely_empty = 1, nl_just_seen = 0;
522 completely_empty = 0;
526 completely_empty = 0;
529 if (completely_empty)
532 count++; /* no trailing newline */
536 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
538 if (!DIFF_FILE_VALID(one)) {
539 mf->ptr = (char *)""; /* does not matter */
543 else if (diff_populate_filespec(one, 0))
547 mf->size = one->size;
551 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
552 static unsigned long diff_filespec_size(struct diff_filespec *one)
554 if (!DIFF_FILE_VALID(one))
556 diff_populate_filespec(one, CHECK_SIZE_ONLY);
560 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
563 long size = mf->size;
568 ptr += size - 1; /* pointing at the very end */
570 ; /* incomplete line */
572 ptr--; /* skip the last LF */
573 while (mf->ptr < ptr) {
575 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
576 if (*prev_eol == '\n')
578 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
586 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
587 struct emit_callback *ecbdata)
590 unsigned ws_rule = ecbdata->ws_rule;
591 l1 = count_trailing_blank(mf1, ws_rule);
592 l2 = count_trailing_blank(mf2, ws_rule);
594 ecbdata->blank_at_eof_in_preimage = 0;
595 ecbdata->blank_at_eof_in_postimage = 0;
598 at = count_lines(mf1->ptr, mf1->size);
599 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
601 at = count_lines(mf2->ptr, mf2->size);
602 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
605 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
606 int first, const char *line, int len)
608 int has_trailing_newline, has_trailing_carriage_return;
610 FILE *file = o->file;
612 fputs(diff_line_prefix(o), file);
615 has_trailing_newline = (first == '\n');
616 has_trailing_carriage_return = (!has_trailing_newline &&
618 nofirst = has_trailing_newline || has_trailing_carriage_return;
620 has_trailing_newline = (len > 0 && line[len-1] == '\n');
621 if (has_trailing_newline)
623 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
624 if (has_trailing_carriage_return)
629 if (len || !nofirst) {
633 fwrite(line, len, 1, file);
636 if (has_trailing_carriage_return)
638 if (has_trailing_newline)
642 static void emit_line(struct diff_options *o, const char *set, const char *reset,
643 const char *line, int len)
645 emit_line_0(o, set, reset, line[0], line+1, len-1);
649 DIFF_SYMBOL_BINARY_DIFF_HEADER,
650 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
651 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
652 DIFF_SYMBOL_BINARY_DIFF_BODY,
653 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
654 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
655 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
656 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
657 DIFF_SYMBOL_STATS_LINE,
658 DIFF_SYMBOL_WORD_DIFF,
659 DIFF_SYMBOL_STAT_SEP,
661 DIFF_SYMBOL_SUBMODULE_ADD,
662 DIFF_SYMBOL_SUBMODULE_DEL,
663 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
664 DIFF_SYMBOL_SUBMODULE_MODIFIED,
665 DIFF_SYMBOL_SUBMODULE_HEADER,
666 DIFF_SYMBOL_SUBMODULE_ERROR,
667 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
668 DIFF_SYMBOL_REWRITE_DIFF,
669 DIFF_SYMBOL_BINARY_FILES,
671 DIFF_SYMBOL_FILEPAIR_PLUS,
672 DIFF_SYMBOL_FILEPAIR_MINUS,
673 DIFF_SYMBOL_WORDS_PORCELAIN,
676 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
679 DIFF_SYMBOL_NO_LF_EOF,
680 DIFF_SYMBOL_CONTEXT_FRAGINFO,
681 DIFF_SYMBOL_CONTEXT_MARKER,
682 DIFF_SYMBOL_SEPARATOR
685 * Flags for content lines:
686 * 0..12 are whitespace rules
687 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
688 * 16 is marking if the line is blank at EOF
690 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
691 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
692 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
693 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
694 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
697 * This struct is used when we need to buffer the output of the diff output.
699 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
700 * into the pre/post image file. This pointer could be a union with the
701 * line pointer. By storing an offset into the file instead of the literal line,
702 * we can decrease the memory footprint for the buffered output. At first we
703 * may want to only have indirection for the content lines, but we could also
704 * enhance the state for emitting prefabricated lines, e.g. the similarity
705 * score line or hunk/file headers would only need to store a number or path
706 * and then the output can be constructed later on depending on state.
708 struct emitted_diff_symbol {
714 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
716 struct emitted_diff_symbols {
717 struct emitted_diff_symbol *buf;
720 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
722 static void append_emitted_diff_symbol(struct diff_options *o,
723 struct emitted_diff_symbol *e)
725 struct emitted_diff_symbol *f;
727 ALLOC_GROW(o->emitted_symbols->buf,
728 o->emitted_symbols->nr + 1,
729 o->emitted_symbols->alloc);
730 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
732 memcpy(f, e, sizeof(struct emitted_diff_symbol));
733 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
737 struct hashmap_entry ent;
738 const struct emitted_diff_symbol *es;
739 struct moved_entry *next_line;
742 static int moved_entry_cmp(const void *hashmap_cmp_fn_data,
744 const void *entry_or_key,
747 const struct diff_options *diffopt = hashmap_cmp_fn_data;
748 const struct moved_entry *a = entry;
749 const struct moved_entry *b = entry_or_key;
750 unsigned flags = diffopt->color_moved_ws_handling
751 & XDF_WHITESPACE_FLAGS;
753 return !xdiff_compare_lines(a->es->line, a->es->len,
754 b->es->line, b->es->len,
758 static struct moved_entry *prepare_entry(struct diff_options *o,
761 struct moved_entry *ret = xmalloc(sizeof(*ret));
762 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
763 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
765 ret->ent.hash = xdiff_hash_string(l->line, l->len, flags);
767 ret->next_line = NULL;
772 static void add_lines_to_move_detection(struct diff_options *o,
773 struct hashmap *add_lines,
774 struct hashmap *del_lines)
776 struct moved_entry *prev_line = NULL;
779 for (n = 0; n < o->emitted_symbols->nr; n++) {
781 struct moved_entry *key;
783 switch (o->emitted_symbols->buf[n].s) {
784 case DIFF_SYMBOL_PLUS:
787 case DIFF_SYMBOL_MINUS:
795 key = prepare_entry(o, n);
796 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
797 prev_line->next_line = key;
799 hashmap_add(hm, key);
804 static void pmb_advance_or_null(struct diff_options *o,
805 struct moved_entry *match,
807 struct moved_entry **pmb,
811 for (i = 0; i < pmb_nr; i++) {
812 struct moved_entry *prev = pmb[i];
813 struct moved_entry *cur = (prev && prev->next_line) ?
814 prev->next_line : NULL;
815 if (cur && !hm->cmpfn(o, cur, match, NULL)) {
823 static int shrink_potential_moved_blocks(struct moved_entry **pmb,
828 /* Shrink the set of potential block to the remaining running */
829 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
830 while (lp < pmb_nr && pmb[lp])
832 /* lp points at the first NULL now */
834 while (rp > -1 && !pmb[rp])
836 /* rp points at the last non-NULL */
838 if (lp < pmb_nr && rp > -1 && lp < rp) {
846 /* Remember the number of running sets */
851 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
853 * Otherwise, if the last block has fewer alphanumeric characters than
854 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
857 * The last block consists of the (n - block_length)'th line up to but not
858 * including the nth line.
860 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
861 * Think of a way to unify them.
863 static void adjust_last_block(struct diff_options *o, int n, int block_length)
865 int i, alnum_count = 0;
866 if (o->color_moved == COLOR_MOVED_PLAIN)
868 for (i = 1; i < block_length + 1; i++) {
869 const char *c = o->emitted_symbols->buf[n - i].line;
874 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
878 for (i = 1; i < block_length + 1; i++)
879 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
882 /* Find blocks of moved code, delegate actual coloring decision to helper */
883 static void mark_color_as_moved(struct diff_options *o,
884 struct hashmap *add_lines,
885 struct hashmap *del_lines)
887 struct moved_entry **pmb = NULL; /* potentially moved blocks */
888 int pmb_nr = 0, pmb_alloc = 0;
889 int n, flipped_block = 1, block_length = 0;
892 for (n = 0; n < o->emitted_symbols->nr; n++) {
893 struct hashmap *hm = NULL;
894 struct moved_entry *key;
895 struct moved_entry *match = NULL;
896 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
899 case DIFF_SYMBOL_PLUS:
901 key = prepare_entry(o, n);
902 match = hashmap_get(hm, key, NULL);
905 case DIFF_SYMBOL_MINUS:
907 key = prepare_entry(o, n);
908 match = hashmap_get(hm, key, NULL);
916 adjust_last_block(o, n, block_length);
922 l->flags |= DIFF_SYMBOL_MOVED_LINE;
924 if (o->color_moved == COLOR_MOVED_PLAIN)
927 pmb_advance_or_null(o, match, hm, pmb, pmb_nr);
929 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
933 * The current line is the start of a new block.
934 * Setup the set of potential blocks.
936 for (; match; match = hashmap_get_next(hm, match)) {
937 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
938 pmb[pmb_nr++] = match;
941 flipped_block = (flipped_block + 1) % 2;
943 adjust_last_block(o, n, block_length);
949 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
950 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
952 adjust_last_block(o, n, block_length);
957 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
958 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
959 static void dim_moved_lines(struct diff_options *o)
962 for (n = 0; n < o->emitted_symbols->nr; n++) {
963 struct emitted_diff_symbol *prev = (n != 0) ?
964 &o->emitted_symbols->buf[n - 1] : NULL;
965 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
966 struct emitted_diff_symbol *next =
967 (n < o->emitted_symbols->nr - 1) ?
968 &o->emitted_symbols->buf[n + 1] : NULL;
970 /* Not a plus or minus line? */
971 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
974 /* Not a moved line? */
975 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
979 * If prev or next are not a plus or minus line,
980 * pretend they don't exist
982 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
983 prev->s != DIFF_SYMBOL_MINUS)
985 if (next && next->s != DIFF_SYMBOL_PLUS &&
986 next->s != DIFF_SYMBOL_MINUS)
989 /* Inside a block? */
991 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
992 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
994 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
995 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
996 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1000 /* Check if we are at an interesting bound: */
1001 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1002 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1003 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1005 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1006 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1007 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1011 * The boundary to prev and next are not interesting,
1012 * so this line is not interesting as a whole
1014 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1018 static void emit_line_ws_markup(struct diff_options *o,
1019 const char *set, const char *reset,
1020 const char *line, int len, char sign,
1021 unsigned ws_rule, int blank_at_eof)
1023 const char *ws = NULL;
1025 if (o->ws_error_highlight & ws_rule) {
1026 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1032 emit_line_0(o, set, reset, sign, line, len);
1033 else if (blank_at_eof)
1034 /* Blank line at EOF - paint '+' as well */
1035 emit_line_0(o, ws, reset, sign, line, len);
1037 /* Emit just the prefix, then the rest. */
1038 emit_line_0(o, set, reset, sign, "", 0);
1039 ws_check_emit(line, len, ws_rule,
1040 o->file, set, reset, ws);
1044 static void emit_diff_symbol_from_struct(struct diff_options *o,
1045 struct emitted_diff_symbol *eds)
1047 static const char *nneof = " No newline at end of file\n";
1048 const char *context, *reset, *set, *meta, *fraginfo;
1049 struct strbuf sb = STRBUF_INIT;
1051 enum diff_symbol s = eds->s;
1052 const char *line = eds->line;
1054 unsigned flags = eds->flags;
1057 case DIFF_SYMBOL_NO_LF_EOF:
1058 context = diff_get_color_opt(o, DIFF_CONTEXT);
1059 reset = diff_get_color_opt(o, DIFF_RESET);
1060 putc('\n', o->file);
1061 emit_line_0(o, context, reset, '\\',
1062 nneof, strlen(nneof));
1064 case DIFF_SYMBOL_SUBMODULE_HEADER:
1065 case DIFF_SYMBOL_SUBMODULE_ERROR:
1066 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1067 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1068 case DIFF_SYMBOL_SUMMARY:
1069 case DIFF_SYMBOL_STATS_LINE:
1070 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1071 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1072 emit_line(o, "", "", line, len);
1074 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1075 case DIFF_SYMBOL_CONTEXT_MARKER:
1076 context = diff_get_color_opt(o, DIFF_CONTEXT);
1077 reset = diff_get_color_opt(o, DIFF_RESET);
1078 emit_line(o, context, reset, line, len);
1080 case DIFF_SYMBOL_SEPARATOR:
1081 fprintf(o->file, "%s%c",
1082 diff_line_prefix(o),
1083 o->line_termination);
1085 case DIFF_SYMBOL_CONTEXT:
1086 set = diff_get_color_opt(o, DIFF_CONTEXT);
1087 reset = diff_get_color_opt(o, DIFF_RESET);
1088 emit_line_ws_markup(o, set, reset, line, len, ' ',
1089 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1091 case DIFF_SYMBOL_PLUS:
1092 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1093 DIFF_SYMBOL_MOVED_LINE_ALT |
1094 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1095 case DIFF_SYMBOL_MOVED_LINE |
1096 DIFF_SYMBOL_MOVED_LINE_ALT |
1097 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1098 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1100 case DIFF_SYMBOL_MOVED_LINE |
1101 DIFF_SYMBOL_MOVED_LINE_ALT:
1102 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1104 case DIFF_SYMBOL_MOVED_LINE |
1105 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1106 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1108 case DIFF_SYMBOL_MOVED_LINE:
1109 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1112 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1114 reset = diff_get_color_opt(o, DIFF_RESET);
1115 emit_line_ws_markup(o, set, reset, line, len, '+',
1116 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1117 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1119 case DIFF_SYMBOL_MINUS:
1120 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1121 DIFF_SYMBOL_MOVED_LINE_ALT |
1122 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1123 case DIFF_SYMBOL_MOVED_LINE |
1124 DIFF_SYMBOL_MOVED_LINE_ALT |
1125 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1126 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1128 case DIFF_SYMBOL_MOVED_LINE |
1129 DIFF_SYMBOL_MOVED_LINE_ALT:
1130 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1132 case DIFF_SYMBOL_MOVED_LINE |
1133 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1134 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1136 case DIFF_SYMBOL_MOVED_LINE:
1137 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1140 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1142 reset = diff_get_color_opt(o, DIFF_RESET);
1143 emit_line_ws_markup(o, set, reset, line, len, '-',
1144 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1146 case DIFF_SYMBOL_WORDS_PORCELAIN:
1147 context = diff_get_color_opt(o, DIFF_CONTEXT);
1148 reset = diff_get_color_opt(o, DIFF_RESET);
1149 emit_line(o, context, reset, line, len);
1150 fputs("~\n", o->file);
1152 case DIFF_SYMBOL_WORDS:
1153 context = diff_get_color_opt(o, DIFF_CONTEXT);
1154 reset = diff_get_color_opt(o, DIFF_RESET);
1156 * Skip the prefix character, if any. With
1157 * diff_suppress_blank_empty, there may be
1160 if (line[0] != '\n') {
1164 emit_line(o, context, reset, line, len);
1166 case DIFF_SYMBOL_FILEPAIR_PLUS:
1167 meta = diff_get_color_opt(o, DIFF_METAINFO);
1168 reset = diff_get_color_opt(o, DIFF_RESET);
1169 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1171 strchr(line, ' ') ? "\t" : "");
1173 case DIFF_SYMBOL_FILEPAIR_MINUS:
1174 meta = diff_get_color_opt(o, DIFF_METAINFO);
1175 reset = diff_get_color_opt(o, DIFF_RESET);
1176 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1178 strchr(line, ' ') ? "\t" : "");
1180 case DIFF_SYMBOL_BINARY_FILES:
1181 case DIFF_SYMBOL_HEADER:
1182 fprintf(o->file, "%s", line);
1184 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1185 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1187 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1188 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1190 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1191 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1193 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1194 fputs(diff_line_prefix(o), o->file);
1195 fputc('\n', o->file);
1197 case DIFF_SYMBOL_REWRITE_DIFF:
1198 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1199 reset = diff_get_color_opt(o, DIFF_RESET);
1200 emit_line(o, fraginfo, reset, line, len);
1202 case DIFF_SYMBOL_SUBMODULE_ADD:
1203 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1204 reset = diff_get_color_opt(o, DIFF_RESET);
1205 emit_line(o, set, reset, line, len);
1207 case DIFF_SYMBOL_SUBMODULE_DEL:
1208 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1209 reset = diff_get_color_opt(o, DIFF_RESET);
1210 emit_line(o, set, reset, line, len);
1212 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1213 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1214 diff_line_prefix(o), line);
1216 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1217 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1218 diff_line_prefix(o), line);
1220 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1221 emit_line(o, "", "", " 0 files changed\n",
1222 strlen(" 0 files changed\n"));
1224 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1225 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1227 case DIFF_SYMBOL_WORD_DIFF:
1228 fprintf(o->file, "%.*s", len, line);
1230 case DIFF_SYMBOL_STAT_SEP:
1231 fputs(o->stat_sep, o->file);
1234 die("BUG: unknown diff symbol");
1236 strbuf_release(&sb);
1239 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1240 const char *line, int len, unsigned flags)
1242 struct emitted_diff_symbol e = {line, len, flags, s};
1244 if (o->emitted_symbols)
1245 append_emitted_diff_symbol(o, &e);
1247 emit_diff_symbol_from_struct(o, &e);
1250 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1252 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1255 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1257 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1260 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1262 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1263 path, strlen(path), 0);
1266 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1268 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1269 path, strlen(path), 0);
1272 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1274 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1275 header, strlen(header), 0);
1278 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1280 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1283 void diff_emit_submodule_pipethrough(struct diff_options *o,
1284 const char *line, int len)
1286 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1289 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1291 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1292 ecbdata->blank_at_eof_in_preimage &&
1293 ecbdata->blank_at_eof_in_postimage &&
1294 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1295 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1297 return ws_blank_line(line, len, ecbdata->ws_rule);
1300 static void emit_add_line(const char *reset,
1301 struct emit_callback *ecbdata,
1302 const char *line, int len)
1304 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1305 if (new_blank_line_at_eof(ecbdata, line, len))
1306 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1308 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1311 static void emit_del_line(const char *reset,
1312 struct emit_callback *ecbdata,
1313 const char *line, int len)
1315 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1316 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1319 static void emit_context_line(const char *reset,
1320 struct emit_callback *ecbdata,
1321 const char *line, int len)
1323 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1324 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1327 static void emit_hunk_header(struct emit_callback *ecbdata,
1328 const char *line, int len)
1330 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1331 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1332 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1333 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1334 static const char atat[2] = { '@', '@' };
1335 const char *cp, *ep;
1336 struct strbuf msgbuf = STRBUF_INIT;
1341 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1342 * it always is at least 10 bytes long.
1345 memcmp(line, atat, 2) ||
1346 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1347 emit_diff_symbol(ecbdata->opt,
1348 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1351 ep += 2; /* skip over @@ */
1353 /* The hunk header in fraginfo color */
1354 strbuf_addstr(&msgbuf, frag);
1355 strbuf_add(&msgbuf, line, ep - line);
1356 strbuf_addstr(&msgbuf, reset);
1362 if (line[len - i] == '\r' || line[len - i] == '\n')
1365 /* blank before the func header */
1366 for (cp = ep; ep - line < len; ep++)
1367 if (*ep != ' ' && *ep != '\t')
1370 strbuf_addstr(&msgbuf, context);
1371 strbuf_add(&msgbuf, cp, ep - cp);
1372 strbuf_addstr(&msgbuf, reset);
1375 if (ep < line + len) {
1376 strbuf_addstr(&msgbuf, func);
1377 strbuf_add(&msgbuf, ep, line + len - ep);
1378 strbuf_addstr(&msgbuf, reset);
1381 strbuf_add(&msgbuf, line + len, org_len - len);
1382 strbuf_complete_line(&msgbuf);
1383 emit_diff_symbol(ecbdata->opt,
1384 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1385 strbuf_release(&msgbuf);
1388 static struct diff_tempfile *claim_diff_tempfile(void) {
1390 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1391 if (!diff_temp[i].name)
1392 return diff_temp + i;
1393 die("BUG: diff is failing to clean up its tempfiles");
1396 static void remove_tempfile(void)
1399 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1400 if (is_tempfile_active(diff_temp[i].tempfile))
1401 delete_tempfile(&diff_temp[i].tempfile);
1402 diff_temp[i].name = NULL;
1406 static void add_line_count(struct strbuf *out, int count)
1410 strbuf_addstr(out, "0,0");
1413 strbuf_addstr(out, "1");
1416 strbuf_addf(out, "1,%d", count);
1421 static void emit_rewrite_lines(struct emit_callback *ecb,
1422 int prefix, const char *data, int size)
1424 const char *endp = NULL;
1425 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1430 endp = memchr(data, '\n', size);
1431 len = endp ? (endp - data + 1) : size;
1432 if (prefix != '+') {
1433 ecb->lno_in_preimage++;
1434 emit_del_line(reset, ecb, data, len);
1436 ecb->lno_in_postimage++;
1437 emit_add_line(reset, ecb, data, len);
1443 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1446 static void emit_rewrite_diff(const char *name_a,
1448 struct diff_filespec *one,
1449 struct diff_filespec *two,
1450 struct userdiff_driver *textconv_one,
1451 struct userdiff_driver *textconv_two,
1452 struct diff_options *o)
1455 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1456 const char *a_prefix, *b_prefix;
1457 char *data_one, *data_two;
1458 size_t size_one, size_two;
1459 struct emit_callback ecbdata;
1460 struct strbuf out = STRBUF_INIT;
1462 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1463 a_prefix = o->b_prefix;
1464 b_prefix = o->a_prefix;
1466 a_prefix = o->a_prefix;
1467 b_prefix = o->b_prefix;
1470 name_a += (*name_a == '/');
1471 name_b += (*name_b == '/');
1473 strbuf_reset(&a_name);
1474 strbuf_reset(&b_name);
1475 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1476 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1478 size_one = fill_textconv(textconv_one, one, &data_one);
1479 size_two = fill_textconv(textconv_two, two, &data_two);
1481 memset(&ecbdata, 0, sizeof(ecbdata));
1482 ecbdata.color_diff = want_color(o->use_color);
1483 ecbdata.ws_rule = whitespace_rule(name_b);
1485 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1487 mf1.ptr = (char *)data_one;
1488 mf2.ptr = (char *)data_two;
1489 mf1.size = size_one;
1490 mf2.size = size_two;
1491 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1493 ecbdata.lno_in_preimage = 1;
1494 ecbdata.lno_in_postimage = 1;
1496 lc_a = count_lines(data_one, size_one);
1497 lc_b = count_lines(data_two, size_two);
1499 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1500 a_name.buf, a_name.len, 0);
1501 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1502 b_name.buf, b_name.len, 0);
1504 strbuf_addstr(&out, "@@ -");
1505 if (!o->irreversible_delete)
1506 add_line_count(&out, lc_a);
1508 strbuf_addstr(&out, "?,?");
1509 strbuf_addstr(&out, " +");
1510 add_line_count(&out, lc_b);
1511 strbuf_addstr(&out, " @@\n");
1512 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1513 strbuf_release(&out);
1515 if (lc_a && !o->irreversible_delete)
1516 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1518 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1520 free((char *)data_one);
1522 free((char *)data_two);
1525 struct diff_words_buffer {
1527 unsigned long alloc;
1528 struct diff_words_orig {
1529 const char *begin, *end;
1531 int orig_nr, orig_alloc;
1534 static void diff_words_append(char *line, unsigned long len,
1535 struct diff_words_buffer *buffer)
1537 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1540 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1541 buffer->text.size += len;
1542 buffer->text.ptr[buffer->text.size] = '\0';
1545 struct diff_words_style_elem {
1548 const char *color; /* NULL; filled in by the setup code if
1549 * color is enabled */
1552 struct diff_words_style {
1553 enum diff_words_type type;
1554 struct diff_words_style_elem new_word, old_word, ctx;
1555 const char *newline;
1558 static struct diff_words_style diff_words_styles[] = {
1559 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1560 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1561 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1564 struct diff_words_data {
1565 struct diff_words_buffer minus, plus;
1566 const char *current_plus;
1568 struct diff_options *opt;
1569 regex_t *word_regex;
1570 enum diff_words_type type;
1571 struct diff_words_style *style;
1574 static int fn_out_diff_words_write_helper(struct diff_options *o,
1575 struct diff_words_style_elem *st_el,
1576 const char *newline,
1577 size_t count, const char *buf)
1580 struct strbuf sb = STRBUF_INIT;
1583 char *p = memchr(buf, '\n', count);
1585 strbuf_addstr(&sb, diff_line_prefix(o));
1588 const char *reset = st_el->color && *st_el->color ?
1589 GIT_COLOR_RESET : NULL;
1590 if (st_el->color && *st_el->color)
1591 strbuf_addstr(&sb, st_el->color);
1592 strbuf_addstr(&sb, st_el->prefix);
1593 strbuf_add(&sb, buf, p ? p - buf : count);
1594 strbuf_addstr(&sb, st_el->suffix);
1596 strbuf_addstr(&sb, reset);
1601 strbuf_addstr(&sb, newline);
1602 count -= p + 1 - buf;
1606 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1614 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1616 strbuf_release(&sb);
1621 * '--color-words' algorithm can be described as:
1623 * 1. collect the minus/plus lines of a diff hunk, divided into
1624 * minus-lines and plus-lines;
1626 * 2. break both minus-lines and plus-lines into words and
1627 * place them into two mmfile_t with one word for each line;
1629 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1631 * And for the common parts of the both file, we output the plus side text.
1632 * diff_words->current_plus is used to trace the current position of the plus file
1633 * which printed. diff_words->last_minus is used to trace the last minus word
1636 * For '--graph' to work with '--color-words', we need to output the graph prefix
1637 * on each line of color words output. Generally, there are two conditions on
1638 * which we should output the prefix.
1640 * 1. diff_words->last_minus == 0 &&
1641 * diff_words->current_plus == diff_words->plus.text.ptr
1643 * that is: the plus text must start as a new line, and if there is no minus
1644 * word printed, a graph prefix must be printed.
1646 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1647 * *(diff_words->current_plus - 1) == '\n'
1649 * that is: a graph prefix must be printed following a '\n'
1651 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1653 if ((diff_words->last_minus == 0 &&
1654 diff_words->current_plus == diff_words->plus.text.ptr) ||
1655 (diff_words->current_plus > diff_words->plus.text.ptr &&
1656 *(diff_words->current_plus - 1) == '\n')) {
1663 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
1665 struct diff_words_data *diff_words = priv;
1666 struct diff_words_style *style = diff_words->style;
1667 int minus_first, minus_len, plus_first, plus_len;
1668 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1669 struct diff_options *opt = diff_words->opt;
1670 const char *line_prefix;
1672 if (line[0] != '@' || parse_hunk_header(line, len,
1673 &minus_first, &minus_len, &plus_first, &plus_len))
1677 line_prefix = diff_line_prefix(opt);
1679 /* POSIX requires that first be decremented by one if len == 0... */
1681 minus_begin = diff_words->minus.orig[minus_first].begin;
1683 diff_words->minus.orig[minus_first + minus_len - 1].end;
1685 minus_begin = minus_end =
1686 diff_words->minus.orig[minus_first].end;
1689 plus_begin = diff_words->plus.orig[plus_first].begin;
1690 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1692 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1694 if (color_words_output_graph_prefix(diff_words)) {
1695 fputs(line_prefix, diff_words->opt->file);
1697 if (diff_words->current_plus != plus_begin) {
1698 fn_out_diff_words_write_helper(diff_words->opt,
1699 &style->ctx, style->newline,
1700 plus_begin - diff_words->current_plus,
1701 diff_words->current_plus);
1703 if (minus_begin != minus_end) {
1704 fn_out_diff_words_write_helper(diff_words->opt,
1705 &style->old_word, style->newline,
1706 minus_end - minus_begin, minus_begin);
1708 if (plus_begin != plus_end) {
1709 fn_out_diff_words_write_helper(diff_words->opt,
1710 &style->new_word, style->newline,
1711 plus_end - plus_begin, plus_begin);
1714 diff_words->current_plus = plus_end;
1715 diff_words->last_minus = minus_first;
1718 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1719 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1720 int *begin, int *end)
1722 if (word_regex && *begin < buffer->size) {
1723 regmatch_t match[1];
1724 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1725 buffer->size - *begin, 1, match, 0)) {
1726 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1727 '\n', match[0].rm_eo - match[0].rm_so);
1728 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1729 *begin += match[0].rm_so;
1730 return *begin >= *end;
1735 /* find the next word */
1736 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1738 if (*begin >= buffer->size)
1741 /* find the end of the word */
1743 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1750 * This function splits the words in buffer->text, stores the list with
1751 * newline separator into out, and saves the offsets of the original words
1754 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1755 regex_t *word_regex)
1763 /* fake an empty "0th" word */
1764 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1765 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1766 buffer->orig_nr = 1;
1768 for (i = 0; i < buffer->text.size; i++) {
1769 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1772 /* store original boundaries */
1773 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1774 buffer->orig_alloc);
1775 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1776 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1779 /* store one word */
1780 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1781 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1782 out->ptr[out->size + j - i] = '\n';
1783 out->size += j - i + 1;
1789 /* this executes the word diff on the accumulated buffers */
1790 static void diff_words_show(struct diff_words_data *diff_words)
1794 mmfile_t minus, plus;
1795 struct diff_words_style *style = diff_words->style;
1797 struct diff_options *opt = diff_words->opt;
1798 const char *line_prefix;
1801 line_prefix = diff_line_prefix(opt);
1803 /* special case: only removal */
1804 if (!diff_words->plus.text.size) {
1805 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1806 line_prefix, strlen(line_prefix), 0);
1807 fn_out_diff_words_write_helper(diff_words->opt,
1808 &style->old_word, style->newline,
1809 diff_words->minus.text.size,
1810 diff_words->minus.text.ptr);
1811 diff_words->minus.text.size = 0;
1815 diff_words->current_plus = diff_words->plus.text.ptr;
1816 diff_words->last_minus = 0;
1818 memset(&xpp, 0, sizeof(xpp));
1819 memset(&xecfg, 0, sizeof(xecfg));
1820 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1821 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1823 /* as only the hunk header will be parsed, we need a 0-context */
1825 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1827 die("unable to generate word diff");
1830 if (diff_words->current_plus != diff_words->plus.text.ptr +
1831 diff_words->plus.text.size) {
1832 if (color_words_output_graph_prefix(diff_words))
1833 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1834 line_prefix, strlen(line_prefix), 0);
1835 fn_out_diff_words_write_helper(diff_words->opt,
1836 &style->ctx, style->newline,
1837 diff_words->plus.text.ptr + diff_words->plus.text.size
1838 - diff_words->current_plus, diff_words->current_plus);
1840 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1843 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1844 static void diff_words_flush(struct emit_callback *ecbdata)
1846 struct diff_options *wo = ecbdata->diff_words->opt;
1848 if (ecbdata->diff_words->minus.text.size ||
1849 ecbdata->diff_words->plus.text.size)
1850 diff_words_show(ecbdata->diff_words);
1852 if (wo->emitted_symbols) {
1853 struct diff_options *o = ecbdata->opt;
1854 struct emitted_diff_symbols *wol = wo->emitted_symbols;
1859 * Instead of appending each, concat all words to a line?
1861 for (i = 0; i < wol->nr; i++)
1862 append_emitted_diff_symbol(o, &wol->buf[i]);
1864 for (i = 0; i < wol->nr; i++)
1865 free((void *)wol->buf[i].line);
1871 static void diff_filespec_load_driver(struct diff_filespec *one)
1873 /* Use already-loaded driver */
1877 if (S_ISREG(one->mode))
1878 one->driver = userdiff_find_by_path(one->path);
1880 /* Fallback to default settings */
1882 one->driver = userdiff_find_by_name("default");
1885 static const char *userdiff_word_regex(struct diff_filespec *one)
1887 diff_filespec_load_driver(one);
1888 return one->driver->word_regex;
1891 static void init_diff_words_data(struct emit_callback *ecbdata,
1892 struct diff_options *orig_opts,
1893 struct diff_filespec *one,
1894 struct diff_filespec *two)
1897 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1898 memcpy(o, orig_opts, sizeof(struct diff_options));
1900 ecbdata->diff_words =
1901 xcalloc(1, sizeof(struct diff_words_data));
1902 ecbdata->diff_words->type = o->word_diff;
1903 ecbdata->diff_words->opt = o;
1905 if (orig_opts->emitted_symbols)
1906 o->emitted_symbols =
1907 xcalloc(1, sizeof(struct emitted_diff_symbols));
1910 o->word_regex = userdiff_word_regex(one);
1912 o->word_regex = userdiff_word_regex(two);
1914 o->word_regex = diff_word_regex_cfg;
1915 if (o->word_regex) {
1916 ecbdata->diff_words->word_regex = (regex_t *)
1917 xmalloc(sizeof(regex_t));
1918 if (regcomp(ecbdata->diff_words->word_regex,
1920 REG_EXTENDED | REG_NEWLINE))
1921 die ("Invalid regular expression: %s",
1924 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1925 if (o->word_diff == diff_words_styles[i].type) {
1926 ecbdata->diff_words->style =
1927 &diff_words_styles[i];
1931 if (want_color(o->use_color)) {
1932 struct diff_words_style *st = ecbdata->diff_words->style;
1933 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1934 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1935 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1939 static void free_diff_words_data(struct emit_callback *ecbdata)
1941 if (ecbdata->diff_words) {
1942 diff_words_flush(ecbdata);
1943 free (ecbdata->diff_words->opt->emitted_symbols);
1944 free (ecbdata->diff_words->opt);
1945 free (ecbdata->diff_words->minus.text.ptr);
1946 free (ecbdata->diff_words->minus.orig);
1947 free (ecbdata->diff_words->plus.text.ptr);
1948 free (ecbdata->diff_words->plus.orig);
1949 if (ecbdata->diff_words->word_regex) {
1950 regfree(ecbdata->diff_words->word_regex);
1951 free(ecbdata->diff_words->word_regex);
1953 FREE_AND_NULL(ecbdata->diff_words);
1957 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1959 if (want_color(diff_use_color))
1960 return diff_colors[ix];
1964 const char *diff_line_prefix(struct diff_options *opt)
1966 struct strbuf *msgbuf;
1967 if (!opt->output_prefix)
1970 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1974 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1977 unsigned long allot;
1983 (void) utf8_width(&cp, &l);
1985 break; /* truncated in the middle? */
1990 static void find_lno(const char *line, struct emit_callback *ecbdata)
1993 ecbdata->lno_in_preimage = 0;
1994 ecbdata->lno_in_postimage = 0;
1995 p = strchr(line, '-');
1997 return; /* cannot happen */
1998 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2001 return; /* cannot happen */
2002 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2005 static void fn_out_consume(void *priv, char *line, unsigned long len)
2007 struct emit_callback *ecbdata = priv;
2008 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
2009 struct diff_options *o = ecbdata->opt;
2011 o->found_changes = 1;
2013 if (ecbdata->header) {
2014 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2015 ecbdata->header->buf, ecbdata->header->len, 0);
2016 strbuf_reset(ecbdata->header);
2017 ecbdata->header = NULL;
2020 if (ecbdata->label_path[0]) {
2021 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2022 ecbdata->label_path[0],
2023 strlen(ecbdata->label_path[0]), 0);
2024 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2025 ecbdata->label_path[1],
2026 strlen(ecbdata->label_path[1]), 0);
2027 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2030 if (diff_suppress_blank_empty
2031 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2036 if (line[0] == '@') {
2037 if (ecbdata->diff_words)
2038 diff_words_flush(ecbdata);
2039 len = sane_truncate_line(ecbdata, line, len);
2040 find_lno(line, ecbdata);
2041 emit_hunk_header(ecbdata, line, len);
2045 if (ecbdata->diff_words) {
2046 enum diff_symbol s =
2047 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2048 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2049 if (line[0] == '-') {
2050 diff_words_append(line, len,
2051 &ecbdata->diff_words->minus);
2053 } else if (line[0] == '+') {
2054 diff_words_append(line, len,
2055 &ecbdata->diff_words->plus);
2057 } else if (starts_with(line, "\\ ")) {
2059 * Eat the "no newline at eof" marker as if we
2060 * saw a "+" or "-" line with nothing on it,
2061 * and return without diff_words_flush() to
2062 * defer processing. If this is the end of
2063 * preimage, more "+" lines may come after it.
2067 diff_words_flush(ecbdata);
2068 emit_diff_symbol(o, s, line, len, 0);
2074 ecbdata->lno_in_postimage++;
2075 emit_add_line(reset, ecbdata, line + 1, len - 1);
2078 ecbdata->lno_in_preimage++;
2079 emit_del_line(reset, ecbdata, line + 1, len - 1);
2082 ecbdata->lno_in_postimage++;
2083 ecbdata->lno_in_preimage++;
2084 emit_context_line(reset, ecbdata, line + 1, len - 1);
2087 /* incomplete line at the end */
2088 ecbdata->lno_in_preimage++;
2089 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2095 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2097 const char *old_name = a;
2098 const char *new_name = b;
2099 int pfx_length, sfx_length;
2100 int pfx_adjust_for_slash;
2101 int len_a = strlen(a);
2102 int len_b = strlen(b);
2103 int a_midlen, b_midlen;
2104 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2105 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2107 if (qlen_a || qlen_b) {
2108 quote_c_style(a, name, NULL, 0);
2109 strbuf_addstr(name, " => ");
2110 quote_c_style(b, name, NULL, 0);
2114 /* Find common prefix */
2116 while (*old_name && *new_name && *old_name == *new_name) {
2117 if (*old_name == '/')
2118 pfx_length = old_name - a + 1;
2123 /* Find common suffix */
2124 old_name = a + len_a;
2125 new_name = b + len_b;
2128 * If there is a common prefix, it must end in a slash. In
2129 * that case we let this loop run 1 into the prefix to see the
2132 * If there is no common prefix, we cannot do this as it would
2133 * underrun the input strings.
2135 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2136 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2137 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2138 *old_name == *new_name) {
2139 if (*old_name == '/')
2140 sfx_length = len_a - (old_name - a);
2146 * pfx{mid-a => mid-b}sfx
2147 * {pfx-a => pfx-b}sfx
2148 * pfx{sfx-a => sfx-b}
2151 a_midlen = len_a - pfx_length - sfx_length;
2152 b_midlen = len_b - pfx_length - sfx_length;
2158 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2159 if (pfx_length + sfx_length) {
2160 strbuf_add(name, a, pfx_length);
2161 strbuf_addch(name, '{');
2163 strbuf_add(name, a + pfx_length, a_midlen);
2164 strbuf_addstr(name, " => ");
2165 strbuf_add(name, b + pfx_length, b_midlen);
2166 if (pfx_length + sfx_length) {
2167 strbuf_addch(name, '}');
2168 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2175 struct diffstat_file {
2179 const char *comments;
2180 unsigned is_unmerged:1;
2181 unsigned is_binary:1;
2182 unsigned is_renamed:1;
2183 unsigned is_interesting:1;
2184 uintmax_t added, deleted;
2188 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2192 struct diffstat_file *x;
2193 x = xcalloc(1, sizeof(*x));
2194 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2195 diffstat->files[diffstat->nr++] = x;
2197 x->from_name = xstrdup(name_a);
2198 x->name = xstrdup(name_b);
2202 x->from_name = NULL;
2203 x->name = xstrdup(name_a);
2208 static void diffstat_consume(void *priv, char *line, unsigned long len)
2210 struct diffstat_t *diffstat = priv;
2211 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2215 else if (line[0] == '-')
2219 const char mime_boundary_leader[] = "------------";
2221 static int scale_linear(int it, int width, int max_change)
2226 * make sure that at least one '-' or '+' is printed if
2227 * there is any change to this path. The easiest way is to
2228 * scale linearly as if the alloted width is one column shorter
2229 * than it is, and then add 1 to the result.
2231 return 1 + (it * (width - 1) / max_change);
2234 static void show_graph(struct strbuf *out, char ch, int cnt,
2235 const char *set, const char *reset)
2239 strbuf_addstr(out, set);
2240 strbuf_addchars(out, ch, cnt);
2241 strbuf_addstr(out, reset);
2244 static void fill_print_name(struct diffstat_file *file)
2246 struct strbuf pname = STRBUF_INIT;
2248 if (file->print_name)
2251 if (file->is_renamed)
2252 pprint_rename(&pname, file->from_name, file->name);
2254 quote_c_style(file->name, &pname, NULL, 0);
2257 strbuf_addf(&pname, " (%s)", file->comments);
2259 file->print_name = strbuf_detach(&pname, NULL);
2262 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2263 int files, int insertions, int deletions)
2265 struct strbuf sb = STRBUF_INIT;
2268 assert(insertions == 0 && deletions == 0);
2269 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2275 (files == 1) ? " %d file changed" : " %d files changed",
2279 * For binary diff, the caller may want to print "x files
2280 * changed" with insertions == 0 && deletions == 0.
2282 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2283 * is probably less confusing (i.e skip over "2 files changed
2284 * but nothing about added/removed lines? Is this a bug in Git?").
2286 if (insertions || deletions == 0) {
2288 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2292 if (deletions || insertions == 0) {
2294 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2297 strbuf_addch(&sb, '\n');
2298 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2300 strbuf_release(&sb);
2303 void print_stat_summary(FILE *fp, int files,
2304 int insertions, int deletions)
2306 struct diff_options o;
2307 memset(&o, 0, sizeof(o));
2310 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2313 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2315 int i, len, add, del, adds = 0, dels = 0;
2316 uintmax_t max_change = 0, max_len = 0;
2317 int total_files = data->nr, count;
2318 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2319 const char *reset, *add_c, *del_c;
2320 int extra_shown = 0;
2321 const char *line_prefix = diff_line_prefix(options);
2322 struct strbuf out = STRBUF_INIT;
2327 count = options->stat_count ? options->stat_count : data->nr;
2329 reset = diff_get_color_opt(options, DIFF_RESET);
2330 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2331 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2334 * Find the longest filename and max number of changes
2336 for (i = 0; (i < count) && (i < data->nr); i++) {
2337 struct diffstat_file *file = data->files[i];
2338 uintmax_t change = file->added + file->deleted;
2340 if (!file->is_interesting && (change == 0)) {
2341 count++; /* not shown == room for one more */
2344 fill_print_name(file);
2345 len = strlen(file->print_name);
2349 if (file->is_unmerged) {
2350 /* "Unmerged" is 8 characters */
2351 bin_width = bin_width < 8 ? 8 : bin_width;
2354 if (file->is_binary) {
2355 /* "Bin XXX -> YYY bytes" */
2356 int w = 14 + decimal_width(file->added)
2357 + decimal_width(file->deleted);
2358 bin_width = bin_width < w ? w : bin_width;
2359 /* Display change counts aligned with "Bin" */
2364 if (max_change < change)
2365 max_change = change;
2367 count = i; /* where we can stop scanning in data->files[] */
2370 * We have width = stat_width or term_columns() columns total.
2371 * We want a maximum of min(max_len, stat_name_width) for the name part.
2372 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2373 * We also need 1 for " " and 4 + decimal_width(max_change)
2374 * for " | NNNN " and one the empty column at the end, altogether
2375 * 6 + decimal_width(max_change).
2377 * If there's not enough space, we will use the smaller of
2378 * stat_name_width (if set) and 5/8*width for the filename,
2379 * and the rest for constant elements + graph part, but no more
2380 * than stat_graph_width for the graph part.
2381 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2382 * for the standard terminal size).
2384 * In other words: stat_width limits the maximum width, and
2385 * stat_name_width fixes the maximum width of the filename,
2386 * and is also used to divide available columns if there
2389 * Binary files are displayed with "Bin XXX -> YYY bytes"
2390 * instead of the change count and graph. This part is treated
2391 * similarly to the graph part, except that it is not
2392 * "scaled". If total width is too small to accommodate the
2393 * guaranteed minimum width of the filename part and the
2394 * separators and this message, this message will "overflow"
2395 * making the line longer than the maximum width.
2398 if (options->stat_width == -1)
2399 width = term_columns() - strlen(line_prefix);
2401 width = options->stat_width ? options->stat_width : 80;
2402 number_width = decimal_width(max_change) > number_width ?
2403 decimal_width(max_change) : number_width;
2405 if (options->stat_graph_width == -1)
2406 options->stat_graph_width = diff_stat_graph_width;
2409 * Guarantee 3/8*16==6 for the graph part
2410 * and 5/8*16==10 for the filename part
2412 if (width < 16 + 6 + number_width)
2413 width = 16 + 6 + number_width;
2416 * First assign sizes that are wanted, ignoring available width.
2417 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2418 * starting from "XXX" should fit in graph_width.
2420 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2421 if (options->stat_graph_width &&
2422 options->stat_graph_width < graph_width)
2423 graph_width = options->stat_graph_width;
2425 name_width = (options->stat_name_width > 0 &&
2426 options->stat_name_width < max_len) ?
2427 options->stat_name_width : max_len;
2430 * Adjust adjustable widths not to exceed maximum width
2432 if (name_width + number_width + 6 + graph_width > width) {
2433 if (graph_width > width * 3/8 - number_width - 6) {
2434 graph_width = width * 3/8 - number_width - 6;
2435 if (graph_width < 6)
2439 if (options->stat_graph_width &&
2440 graph_width > options->stat_graph_width)
2441 graph_width = options->stat_graph_width;
2442 if (name_width > width - number_width - 6 - graph_width)
2443 name_width = width - number_width - 6 - graph_width;
2445 graph_width = width - number_width - 6 - name_width;
2449 * From here name_width is the width of the name area,
2450 * and graph_width is the width of the graph area.
2451 * max_change is used to scale graph properly.
2453 for (i = 0; i < count; i++) {
2454 const char *prefix = "";
2455 struct diffstat_file *file = data->files[i];
2456 char *name = file->print_name;
2457 uintmax_t added = file->added;
2458 uintmax_t deleted = file->deleted;
2461 if (!file->is_interesting && (added + deleted == 0))
2465 * "scale" the filename
2468 name_len = strlen(name);
2469 if (name_width < name_len) {
2473 name += name_len - len;
2474 slash = strchr(name, '/');
2479 if (file->is_binary) {
2480 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2481 strbuf_addf(&out, " %*s", number_width, "Bin");
2482 if (!added && !deleted) {
2483 strbuf_addch(&out, '\n');
2484 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2485 out.buf, out.len, 0);
2489 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2490 del_c, deleted, reset);
2491 strbuf_addstr(&out, " -> ");
2492 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2493 add_c, added, reset);
2494 strbuf_addstr(&out, " bytes\n");
2495 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2496 out.buf, out.len, 0);
2500 else if (file->is_unmerged) {
2501 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2502 strbuf_addstr(&out, " Unmerged\n");
2503 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2504 out.buf, out.len, 0);
2510 * scale the add/delete
2515 if (graph_width <= max_change) {
2516 int total = scale_linear(add + del, graph_width, max_change);
2517 if (total < 2 && add && del)
2518 /* width >= 2 due to the sanity check */
2521 add = scale_linear(add, graph_width, max_change);
2524 del = scale_linear(del, graph_width, max_change);
2528 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2529 strbuf_addf(&out, " %*"PRIuMAX"%s",
2530 number_width, added + deleted,
2531 added + deleted ? " " : "");
2532 show_graph(&out, '+', add, add_c, reset);
2533 show_graph(&out, '-', del, del_c, reset);
2534 strbuf_addch(&out, '\n');
2535 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2536 out.buf, out.len, 0);
2540 for (i = 0; i < data->nr; i++) {
2541 struct diffstat_file *file = data->files[i];
2542 uintmax_t added = file->added;
2543 uintmax_t deleted = file->deleted;
2545 if (file->is_unmerged ||
2546 (!file->is_interesting && (added + deleted == 0))) {
2551 if (!file->is_binary) {
2558 emit_diff_symbol(options,
2559 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2564 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2565 strbuf_release(&out);
2568 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2570 int i, adds = 0, dels = 0, total_files = data->nr;
2575 for (i = 0; i < data->nr; i++) {
2576 int added = data->files[i]->added;
2577 int deleted = data->files[i]->deleted;
2579 if (data->files[i]->is_unmerged ||
2580 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2582 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2587 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2590 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2597 for (i = 0; i < data->nr; i++) {
2598 struct diffstat_file *file = data->files[i];
2600 fprintf(options->file, "%s", diff_line_prefix(options));
2602 if (file->is_binary)
2603 fprintf(options->file, "-\t-\t");
2605 fprintf(options->file,
2606 "%"PRIuMAX"\t%"PRIuMAX"\t",
2607 file->added, file->deleted);
2608 if (options->line_termination) {
2609 fill_print_name(file);
2610 if (!file->is_renamed)
2611 write_name_quoted(file->name, options->file,
2612 options->line_termination);
2614 fputs(file->print_name, options->file);
2615 putc(options->line_termination, options->file);
2618 if (file->is_renamed) {
2619 putc('\0', options->file);
2620 write_name_quoted(file->from_name, options->file, '\0');
2622 write_name_quoted(file->name, options->file, '\0');
2627 struct dirstat_file {
2629 unsigned long changed;
2632 struct dirstat_dir {
2633 struct dirstat_file *files;
2634 int alloc, nr, permille, cumulative;
2637 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2638 unsigned long changed, const char *base, int baselen)
2640 unsigned long sum_changes = 0;
2641 unsigned int sources = 0;
2642 const char *line_prefix = diff_line_prefix(opt);
2645 struct dirstat_file *f = dir->files;
2646 int namelen = strlen(f->name);
2647 unsigned long changes;
2650 if (namelen < baselen)
2652 if (memcmp(f->name, base, baselen))
2654 slash = strchr(f->name + baselen, '/');
2656 int newbaselen = slash + 1 - f->name;
2657 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2660 changes = f->changed;
2665 sum_changes += changes;
2669 * We don't report dirstat's for
2671 * - or cases where everything came from a single directory
2672 * under this directory (sources == 1).
2674 if (baselen && sources != 1) {
2676 int permille = sum_changes * 1000 / changed;
2677 if (permille >= dir->permille) {
2678 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2679 permille / 10, permille % 10, baselen, base);
2680 if (!dir->cumulative)
2688 static int dirstat_compare(const void *_a, const void *_b)
2690 const struct dirstat_file *a = _a;
2691 const struct dirstat_file *b = _b;
2692 return strcmp(a->name, b->name);
2695 static void show_dirstat(struct diff_options *options)
2698 unsigned long changed;
2699 struct dirstat_dir dir;
2700 struct diff_queue_struct *q = &diff_queued_diff;
2705 dir.permille = options->dirstat_permille;
2706 dir.cumulative = options->flags.dirstat_cumulative;
2709 for (i = 0; i < q->nr; i++) {
2710 struct diff_filepair *p = q->queue[i];
2712 unsigned long copied, added, damage;
2713 int content_changed;
2715 name = p->two->path ? p->two->path : p->one->path;
2717 if (p->one->oid_valid && p->two->oid_valid)
2718 content_changed = oidcmp(&p->one->oid, &p->two->oid);
2720 content_changed = 1;
2722 if (!content_changed) {
2724 * The SHA1 has not changed, so pre-/post-content is
2725 * identical. We can therefore skip looking at the
2726 * file contents altogether.
2732 if (options->flags.dirstat_by_file) {
2734 * In --dirstat-by-file mode, we don't really need to
2735 * look at the actual file contents at all.
2736 * The fact that the SHA1 changed is enough for us to
2737 * add this file to the list of results
2738 * (with each file contributing equal damage).
2744 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2745 diff_populate_filespec(p->one, 0);
2746 diff_populate_filespec(p->two, 0);
2747 diffcore_count_changes(p->one, p->two, NULL, NULL,
2749 diff_free_filespec_data(p->one);
2750 diff_free_filespec_data(p->two);
2751 } else if (DIFF_FILE_VALID(p->one)) {
2752 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2754 diff_free_filespec_data(p->one);
2755 } else if (DIFF_FILE_VALID(p->two)) {
2756 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
2758 added = p->two->size;
2759 diff_free_filespec_data(p->two);
2764 * Original minus copied is the removed material,
2765 * added is the new material. They are both damages
2766 * made to the preimage.
2767 * If the resulting damage is zero, we know that
2768 * diffcore_count_changes() considers the two entries to
2769 * be identical, but since content_changed is true, we
2770 * know that there must have been _some_ kind of change,
2771 * so we force all entries to have damage > 0.
2773 damage = (p->one->size - copied) + added;
2778 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2779 dir.files[dir.nr].name = name;
2780 dir.files[dir.nr].changed = damage;
2785 /* This can happen even with many files, if everything was renames */
2789 /* Show all directories with more than x% of the changes */
2790 QSORT(dir.files, dir.nr, dirstat_compare);
2791 gather_dirstat(options, &dir, changed, "", 0);
2794 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2797 unsigned long changed;
2798 struct dirstat_dir dir;
2806 dir.permille = options->dirstat_permille;
2807 dir.cumulative = options->flags.dirstat_cumulative;
2810 for (i = 0; i < data->nr; i++) {
2811 struct diffstat_file *file = data->files[i];
2812 unsigned long damage = file->added + file->deleted;
2813 if (file->is_binary)
2815 * binary files counts bytes, not lines. Must find some
2816 * way to normalize binary bytes vs. textual lines.
2817 * The following heuristic assumes that there are 64
2819 * This is stupid and ugly, but very cheap...
2821 damage = DIV_ROUND_UP(damage, 64);
2822 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2823 dir.files[dir.nr].name = file->name;
2824 dir.files[dir.nr].changed = damage;
2829 /* This can happen even with many files, if everything was renames */
2833 /* Show all directories with more than x% of the changes */
2834 QSORT(dir.files, dir.nr, dirstat_compare);
2835 gather_dirstat(options, &dir, changed, "", 0);
2838 static void free_diffstat_info(struct diffstat_t *diffstat)
2841 for (i = 0; i < diffstat->nr; i++) {
2842 struct diffstat_file *f = diffstat->files[i];
2843 free(f->print_name);
2848 free(diffstat->files);
2851 struct checkdiff_t {
2852 const char *filename;
2854 int conflict_marker_size;
2855 struct diff_options *o;
2860 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2865 if (len < marker_size + 1)
2867 firstchar = line[0];
2868 switch (firstchar) {
2869 case '=': case '>': case '<': case '|':
2874 for (cnt = 1; cnt < marker_size; cnt++)
2875 if (line[cnt] != firstchar)
2877 /* line[1] thru line[marker_size-1] are same as firstchar */
2878 if (len < marker_size + 1 || !isspace(line[marker_size]))
2883 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2885 struct checkdiff_t *data = priv;
2886 int marker_size = data->conflict_marker_size;
2887 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2888 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2889 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2891 const char *line_prefix;
2894 line_prefix = diff_line_prefix(data->o);
2896 if (line[0] == '+') {
2899 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2901 fprintf(data->o->file,
2902 "%s%s:%d: leftover conflict marker\n",
2903 line_prefix, data->filename, data->lineno);
2905 bad = ws_check(line + 1, len - 1, data->ws_rule);
2908 data->status |= bad;
2909 err = whitespace_error_string(bad);
2910 fprintf(data->o->file, "%s%s:%d: %s.\n",
2911 line_prefix, data->filename, data->lineno, err);
2913 emit_line(data->o, set, reset, line, 1);
2914 ws_check_emit(line + 1, len - 1, data->ws_rule,
2915 data->o->file, set, reset, ws);
2916 } else if (line[0] == ' ') {
2918 } else if (line[0] == '@') {
2919 char *plus = strchr(line, '+');
2921 data->lineno = strtol(plus, NULL, 10) - 1;
2923 die("invalid diff");
2927 static unsigned char *deflate_it(char *data,
2929 unsigned long *result_size)
2932 unsigned char *deflated;
2935 git_deflate_init(&stream, zlib_compression_level);
2936 bound = git_deflate_bound(&stream, size);
2937 deflated = xmalloc(bound);
2938 stream.next_out = deflated;
2939 stream.avail_out = bound;
2941 stream.next_in = (unsigned char *)data;
2942 stream.avail_in = size;
2943 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2945 git_deflate_end(&stream);
2946 *result_size = stream.total_out;
2950 static void emit_binary_diff_body(struct diff_options *o,
2951 mmfile_t *one, mmfile_t *two)
2957 unsigned long orig_size;
2958 unsigned long delta_size;
2959 unsigned long deflate_size;
2960 unsigned long data_size;
2962 /* We could do deflated delta, or we could do just deflated two,
2963 * whichever is smaller.
2966 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2967 if (one->size && two->size) {
2968 delta = diff_delta(one->ptr, one->size,
2969 two->ptr, two->size,
2970 &delta_size, deflate_size);
2972 void *to_free = delta;
2973 orig_size = delta_size;
2974 delta = deflate_it(delta, delta_size, &delta_size);
2979 if (delta && delta_size < deflate_size) {
2980 char *s = xstrfmt("%lu", orig_size);
2981 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
2986 data_size = delta_size;
2988 char *s = xstrfmt("%lu", two->size);
2989 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
2994 data_size = deflate_size;
2997 /* emit data encoded in base85 */
3001 int bytes = (52 < data_size) ? 52 : data_size;
3005 line[0] = bytes + 'A' - 1;
3007 line[0] = bytes - 26 + 'a' - 1;
3008 encode_85(line + 1, cp, bytes);
3009 cp = (char *) cp + bytes;
3015 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3018 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3022 static void emit_binary_diff(struct diff_options *o,
3023 mmfile_t *one, mmfile_t *two)
3025 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3026 emit_binary_diff_body(o, one, two);
3027 emit_binary_diff_body(o, two, one);
3030 int diff_filespec_is_binary(struct diff_filespec *one)
3032 if (one->is_binary == -1) {
3033 diff_filespec_load_driver(one);
3034 if (one->driver->binary != -1)
3035 one->is_binary = one->driver->binary;
3037 if (!one->data && DIFF_FILE_VALID(one))
3038 diff_populate_filespec(one, CHECK_BINARY);
3039 if (one->is_binary == -1 && one->data)
3040 one->is_binary = buffer_is_binary(one->data,
3042 if (one->is_binary == -1)
3046 return one->is_binary;
3049 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
3051 diff_filespec_load_driver(one);
3052 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3055 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3057 if (!options->a_prefix)
3058 options->a_prefix = a;
3059 if (!options->b_prefix)
3060 options->b_prefix = b;
3063 struct userdiff_driver *get_textconv(struct diff_filespec *one)
3065 if (!DIFF_FILE_VALID(one))
3068 diff_filespec_load_driver(one);
3069 return userdiff_get_textconv(one->driver);
3072 static void builtin_diff(const char *name_a,
3074 struct diff_filespec *one,
3075 struct diff_filespec *two,
3076 const char *xfrm_msg,
3077 int must_show_header,
3078 struct diff_options *o,
3079 int complete_rewrite)
3083 char *a_one, *b_two;
3084 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3085 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3086 const char *a_prefix, *b_prefix;
3087 struct userdiff_driver *textconv_one = NULL;
3088 struct userdiff_driver *textconv_two = NULL;
3089 struct strbuf header = STRBUF_INIT;
3090 const char *line_prefix = diff_line_prefix(o);
3092 diff_set_mnemonic_prefix(o, "a/", "b/");
3093 if (o->flags.reverse_diff) {
3094 a_prefix = o->b_prefix;
3095 b_prefix = o->a_prefix;
3097 a_prefix = o->a_prefix;
3098 b_prefix = o->b_prefix;
3101 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3102 (!one->mode || S_ISGITLINK(one->mode)) &&
3103 (!two->mode || S_ISGITLINK(two->mode))) {
3104 show_submodule_summary(o, one->path ? one->path : two->path,
3105 &one->oid, &two->oid,
3106 two->dirty_submodule);
3108 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3109 (!one->mode || S_ISGITLINK(one->mode)) &&
3110 (!two->mode || S_ISGITLINK(two->mode))) {
3111 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3112 &one->oid, &two->oid,
3113 two->dirty_submodule);
3117 if (o->flags.allow_textconv) {
3118 textconv_one = get_textconv(one);
3119 textconv_two = get_textconv(two);
3122 /* Never use a non-valid filename anywhere if at all possible */
3123 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3124 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3126 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3127 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3128 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3129 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3130 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3131 if (lbl[0][0] == '/') {
3133 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3135 strbuf_addstr(&header, xfrm_msg);
3136 must_show_header = 1;
3138 else if (lbl[1][0] == '/') {
3139 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3141 strbuf_addstr(&header, xfrm_msg);
3142 must_show_header = 1;
3145 if (one->mode != two->mode) {
3146 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3147 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3148 must_show_header = 1;
3151 strbuf_addstr(&header, xfrm_msg);
3154 * we do not run diff between different kind
3157 if ((one->mode ^ two->mode) & S_IFMT)
3158 goto free_ab_and_return;
3159 if (complete_rewrite &&
3160 (textconv_one || !diff_filespec_is_binary(one)) &&
3161 (textconv_two || !diff_filespec_is_binary(two))) {
3162 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3163 header.buf, header.len, 0);
3164 strbuf_reset(&header);
3165 emit_rewrite_diff(name_a, name_b, one, two,
3166 textconv_one, textconv_two, o);
3167 o->found_changes = 1;
3168 goto free_ab_and_return;
3172 if (o->irreversible_delete && lbl[1][0] == '/') {
3173 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3175 strbuf_reset(&header);
3176 goto free_ab_and_return;
3177 } else if (!o->flags.text &&
3178 ( (!textconv_one && diff_filespec_is_binary(one)) ||
3179 (!textconv_two && diff_filespec_is_binary(two)) )) {
3180 struct strbuf sb = STRBUF_INIT;
3181 if (!one->data && !two->data &&
3182 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3184 if (!oidcmp(&one->oid, &two->oid)) {
3185 if (must_show_header)
3186 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3187 header.buf, header.len,
3189 goto free_ab_and_return;
3191 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3192 header.buf, header.len, 0);
3193 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3194 diff_line_prefix(o), lbl[0], lbl[1]);
3195 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3197 strbuf_release(&sb);
3198 goto free_ab_and_return;
3200 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3201 die("unable to read files to diff");
3202 /* Quite common confusing case */
3203 if (mf1.size == mf2.size &&
3204 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3205 if (must_show_header)
3206 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3207 header.buf, header.len, 0);
3208 goto free_ab_and_return;
3210 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3211 strbuf_reset(&header);
3212 if (o->flags.binary)
3213 emit_binary_diff(o, &mf1, &mf2);
3215 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3216 diff_line_prefix(o), lbl[0], lbl[1]);
3217 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3219 strbuf_release(&sb);
3221 o->found_changes = 1;
3223 /* Crazy xdl interfaces.. */
3224 const char *diffopts = getenv("GIT_DIFF_OPTS");
3228 struct emit_callback ecbdata;
3229 const struct userdiff_funcname *pe;
3231 if (must_show_header) {
3232 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3233 header.buf, header.len, 0);
3234 strbuf_reset(&header);
3237 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
3238 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
3240 pe = diff_funcname_pattern(one);
3242 pe = diff_funcname_pattern(two);
3244 memset(&xpp, 0, sizeof(xpp));
3245 memset(&xecfg, 0, sizeof(xecfg));
3246 memset(&ecbdata, 0, sizeof(ecbdata));
3247 ecbdata.label_path = lbl;
3248 ecbdata.color_diff = want_color(o->use_color);
3249 ecbdata.ws_rule = whitespace_rule(name_b);
3250 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3251 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3253 ecbdata.header = header.len ? &header : NULL;
3254 xpp.flags = o->xdl_opts;
3255 xpp.anchors = o->anchors;
3256 xpp.anchors_nr = o->anchors_nr;
3257 xecfg.ctxlen = o->context;
3258 xecfg.interhunkctxlen = o->interhunkcontext;
3259 xecfg.flags = XDL_EMIT_FUNCNAMES;
3260 if (o->flags.funccontext)
3261 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3263 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3266 else if (skip_prefix(diffopts, "--unified=", &v))
3267 xecfg.ctxlen = strtoul(v, NULL, 10);
3268 else if (skip_prefix(diffopts, "-u", &v))
3269 xecfg.ctxlen = strtoul(v, NULL, 10);
3271 init_diff_words_data(&ecbdata, o, one, two);
3272 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
3274 die("unable to generate diff for %s", one->path);
3276 free_diff_words_data(&ecbdata);
3281 xdiff_clear_find_func(&xecfg);
3285 strbuf_release(&header);
3286 diff_free_filespec_data(one);
3287 diff_free_filespec_data(two);
3293 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3296 if (p->status == DIFF_STATUS_ADDED) {
3297 if (S_ISLNK(p->two->mode))
3299 else if ((p->two->mode & 0777) == 0755)
3303 } else if (p->status == DIFF_STATUS_DELETED)
3306 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3308 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3310 else if ((p->one->mode & 0777) == 0644 &&
3311 (p->two->mode & 0777) == 0755)
3313 else if ((p->one->mode & 0777) == 0755 &&
3314 (p->two->mode & 0777) == 0644)
3319 static void builtin_diffstat(const char *name_a, const char *name_b,
3320 struct diff_filespec *one,
3321 struct diff_filespec *two,
3322 struct diffstat_t *diffstat,
3323 struct diff_options *o,
3324 struct diff_filepair *p)
3327 struct diffstat_file *data;
3329 int complete_rewrite = 0;
3331 if (!DIFF_PAIR_UNMERGED(p)) {
3332 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3333 complete_rewrite = 1;
3336 data = diffstat_add(diffstat, name_a, name_b);
3337 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3338 if (o->flags.stat_with_summary)
3339 data->comments = get_compact_summary(p, data->is_renamed);
3342 data->is_unmerged = 1;
3346 same_contents = !oidcmp(&one->oid, &two->oid);
3348 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
3349 data->is_binary = 1;
3350 if (same_contents) {
3354 data->added = diff_filespec_size(two);
3355 data->deleted = diff_filespec_size(one);
3359 else if (complete_rewrite) {
3360 diff_populate_filespec(one, 0);
3361 diff_populate_filespec(two, 0);
3362 data->deleted = count_lines(one->data, one->size);
3363 data->added = count_lines(two->data, two->size);
3366 else if (!same_contents) {
3367 /* Crazy xdl interfaces.. */
3371 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3372 die("unable to read files to diff");
3374 memset(&xpp, 0, sizeof(xpp));
3375 memset(&xecfg, 0, sizeof(xecfg));
3376 xpp.flags = o->xdl_opts;
3377 xpp.anchors = o->anchors;
3378 xpp.anchors_nr = o->anchors_nr;
3379 xecfg.ctxlen = o->context;
3380 xecfg.interhunkctxlen = o->interhunkcontext;
3381 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
3383 die("unable to generate diffstat for %s", one->path);
3386 diff_free_filespec_data(one);
3387 diff_free_filespec_data(two);
3390 static void builtin_checkdiff(const char *name_a, const char *name_b,
3391 const char *attr_path,
3392 struct diff_filespec *one,
3393 struct diff_filespec *two,
3394 struct diff_options *o)
3397 struct checkdiff_t data;
3402 memset(&data, 0, sizeof(data));
3403 data.filename = name_b ? name_b : name_a;
3406 data.ws_rule = whitespace_rule(attr_path);
3407 data.conflict_marker_size = ll_merge_marker_size(attr_path);
3409 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3410 die("unable to read files to diff");
3413 * All the other codepaths check both sides, but not checking
3414 * the "old" side here is deliberate. We are checking the newly
3415 * introduced changes, and as long as the "new" side is text, we
3416 * can and should check what it introduces.
3418 if (diff_filespec_is_binary(two))
3419 goto free_and_return;
3421 /* Crazy xdl interfaces.. */
3425 memset(&xpp, 0, sizeof(xpp));
3426 memset(&xecfg, 0, sizeof(xecfg));
3427 xecfg.ctxlen = 1; /* at least one context line */
3429 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
3431 die("unable to generate checkdiff for %s", one->path);
3433 if (data.ws_rule & WS_BLANK_AT_EOF) {
3434 struct emit_callback ecbdata;
3437 ecbdata.ws_rule = data.ws_rule;
3438 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3439 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3444 err = whitespace_error_string(WS_BLANK_AT_EOF);
3445 fprintf(o->file, "%s:%d: %s.\n",
3446 data.filename, blank_at_eof, err);
3447 data.status = 1; /* report errors */
3452 diff_free_filespec_data(one);
3453 diff_free_filespec_data(two);
3455 o->flags.check_failed = 1;
3458 struct diff_filespec *alloc_filespec(const char *path)
3460 struct diff_filespec *spec;
3462 FLEXPTR_ALLOC_STR(spec, path, path);
3464 spec->is_binary = -1;
3468 void free_filespec(struct diff_filespec *spec)
3470 if (!--spec->count) {
3471 diff_free_filespec_data(spec);
3476 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3477 int oid_valid, unsigned short mode)
3480 spec->mode = canon_mode(mode);
3481 oidcpy(&spec->oid, oid);
3482 spec->oid_valid = oid_valid;
3487 * Given a name and sha1 pair, if the index tells us the file in
3488 * the work tree has that object contents, return true, so that
3489 * prepare_temp_file() does not have to inflate and extract.
3491 static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
3493 const struct cache_entry *ce;
3498 * We do not read the cache ourselves here, because the
3499 * benchmark with my previous version that always reads cache
3500 * shows that it makes things worse for diff-tree comparing
3501 * two linux-2.6 kernel trees in an already checked out work
3502 * tree. This is because most diff-tree comparisons deal with
3503 * only a small number of files, while reading the cache is
3504 * expensive for a large project, and its cost outweighs the
3505 * savings we get by not inflating the object to a temporary
3506 * file. Practically, this code only helps when we are used
3507 * by diff-cache --cached, which does read the cache before
3513 /* We want to avoid the working directory if our caller
3514 * doesn't need the data in a normal file, this system
3515 * is rather slow with its stat/open/mmap/close syscalls,
3516 * and the object is contained in a pack file. The pack
3517 * is probably already open and will be faster to obtain
3518 * the data through than the working directory. Loose
3519 * objects however would tend to be slower as they need
3520 * to be individually opened and inflated.
3522 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
3526 * Similarly, if we'd have to convert the file contents anyway, that
3527 * makes the optimization not worthwhile.
3529 if (!want_file && would_convert_to_git(&the_index, name))
3533 pos = cache_name_pos(name, len);
3536 ce = active_cache[pos];
3539 * This is not the sha1 we are looking for, or
3540 * unreusable because it is not a regular file.
3542 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3546 * If ce is marked as "assume unchanged", there is no
3547 * guarantee that work tree matches what we are looking for.
3549 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3553 * If ce matches the file in the work tree, we can reuse it.
3555 if (ce_uptodate(ce) ||
3556 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3562 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3564 struct strbuf buf = STRBUF_INIT;
3567 /* Are we looking at the work tree? */
3568 if (s->dirty_submodule)
3571 strbuf_addf(&buf, "Subproject commit %s%s\n",
3572 oid_to_hex(&s->oid), dirty);
3576 strbuf_release(&buf);
3578 s->data = strbuf_detach(&buf, NULL);
3585 * While doing rename detection and pickaxe operation, we may need to
3586 * grab the data for the blob (or file) for our own in-core comparison.
3587 * diff_filespec has data and size fields for this purpose.
3589 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
3591 int size_only = flags & CHECK_SIZE_ONLY;
3593 int conv_flags = global_conv_flags_eol;
3595 * demote FAIL to WARN to allow inspecting the situation
3596 * instead of refusing.
3598 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3599 conv_flags = CONV_EOL_RNDTRP_WARN;
3601 if (!DIFF_FILE_VALID(s))
3602 die("internal error: asking to populate invalid file.");
3603 if (S_ISDIR(s->mode))
3609 if (size_only && 0 < s->size)
3612 if (S_ISGITLINK(s->mode))
3613 return diff_populate_gitlink(s, size_only);
3615 if (!s->oid_valid ||
3616 reuse_worktree_file(s->path, &s->oid, 0)) {
3617 struct strbuf buf = STRBUF_INIT;
3621 if (lstat(s->path, &st) < 0) {
3625 s->data = (char *)"";
3629 s->size = xsize_t(st.st_size);
3632 if (S_ISLNK(st.st_mode)) {
3633 struct strbuf sb = STRBUF_INIT;
3635 if (strbuf_readlink(&sb, s->path, s->size))
3638 s->data = strbuf_detach(&sb, NULL);
3644 * Even if the caller would be happy with getting
3645 * only the size, we cannot return early at this
3646 * point if the path requires us to run the content
3649 if (size_only && !would_convert_to_git(&the_index, s->path))
3653 * Note: this check uses xsize_t(st.st_size) that may
3654 * not be the true size of the blob after it goes
3655 * through convert_to_git(). This may not strictly be
3656 * correct, but the whole point of big_file_threshold
3657 * and is_binary check being that we want to avoid
3658 * opening the file and inspecting the contents, this
3661 if ((flags & CHECK_BINARY) &&
3662 s->size > big_file_threshold && s->is_binary == -1) {
3666 fd = open(s->path, O_RDONLY);
3669 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3671 s->should_munmap = 1;
3674 * Convert from working tree format to canonical git format
3676 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, conv_flags)) {
3678 munmap(s->data, s->size);
3679 s->should_munmap = 0;
3680 s->data = strbuf_detach(&buf, &size);
3686 enum object_type type;
3687 if (size_only || (flags & CHECK_BINARY)) {
3688 type = oid_object_info(&s->oid, &s->size);
3690 die("unable to read %s",
3691 oid_to_hex(&s->oid));
3694 if (s->size > big_file_threshold && s->is_binary == -1) {
3699 s->data = read_object_file(&s->oid, &type, &s->size);
3701 die("unable to read %s", oid_to_hex(&s->oid));
3707 void diff_free_filespec_blob(struct diff_filespec *s)
3711 else if (s->should_munmap)
3712 munmap(s->data, s->size);
3714 if (s->should_free || s->should_munmap) {
3715 s->should_free = s->should_munmap = 0;
3720 void diff_free_filespec_data(struct diff_filespec *s)
3722 diff_free_filespec_blob(s);
3723 FREE_AND_NULL(s->cnt_data);
3726 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
3729 const struct object_id *oid,
3732 struct strbuf buf = STRBUF_INIT;
3733 struct strbuf tempfile = STRBUF_INIT;
3734 char *path_dup = xstrdup(path);
3735 const char *base = basename(path_dup);
3737 /* Generate "XXXXXX_basename.ext" */
3738 strbuf_addstr(&tempfile, "XXXXXX_");
3739 strbuf_addstr(&tempfile, base);
3741 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
3742 if (!temp->tempfile)
3743 die_errno("unable to create temp-file");
3744 if (convert_to_working_tree(path,
3745 (const char *)blob, (size_t)size, &buf)) {
3749 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
3750 close_tempfile_gently(temp->tempfile))
3751 die_errno("unable to write temp-file");
3752 temp->name = get_tempfile_path(temp->tempfile);
3753 oid_to_hex_r(temp->hex, oid);
3754 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
3755 strbuf_release(&buf);
3756 strbuf_release(&tempfile);
3760 static struct diff_tempfile *prepare_temp_file(const char *name,
3761 struct diff_filespec *one)
3763 struct diff_tempfile *temp = claim_diff_tempfile();
3765 if (!DIFF_FILE_VALID(one)) {
3767 /* A '-' entry produces this for file-2, and
3768 * a '+' entry produces this for file-1.
3770 temp->name = "/dev/null";
3771 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3772 xsnprintf(temp->mode, sizeof(temp->mode), ".");
3776 if (!S_ISGITLINK(one->mode) &&
3778 reuse_worktree_file(name, &one->oid, 1))) {
3780 if (lstat(name, &st) < 0) {
3781 if (errno == ENOENT)
3782 goto not_a_valid_file;
3783 die_errno("stat(%s)", name);
3785 if (S_ISLNK(st.st_mode)) {
3786 struct strbuf sb = STRBUF_INIT;
3787 if (strbuf_readlink(&sb, name, st.st_size) < 0)
3788 die_errno("readlink(%s)", name);
3789 prep_temp_blob(name, temp, sb.buf, sb.len,
3791 &one->oid : &null_oid),
3793 one->mode : S_IFLNK));
3794 strbuf_release(&sb);
3797 /* we can borrow from the file in the work tree */
3799 if (!one->oid_valid)
3800 oid_to_hex_r(temp->hex, &null_oid);
3802 oid_to_hex_r(temp->hex, &one->oid);
3803 /* Even though we may sometimes borrow the
3804 * contents from the work tree, we always want
3805 * one->mode. mode is trustworthy even when
3806 * !(one->oid_valid), as long as
3807 * DIFF_FILE_VALID(one).
3809 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
3814 if (diff_populate_filespec(one, 0))
3815 die("cannot read data blob for %s", one->path);
3816 prep_temp_blob(name, temp, one->data, one->size,
3817 &one->oid, one->mode);
3822 static void add_external_diff_name(struct argv_array *argv,
3824 struct diff_filespec *df)
3826 struct diff_tempfile *temp = prepare_temp_file(name, df);
3827 argv_array_push(argv, temp->name);
3828 argv_array_push(argv, temp->hex);
3829 argv_array_push(argv, temp->mode);
3832 /* An external diff command takes:
3834 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3835 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3838 static void run_external_diff(const char *pgm,
3841 struct diff_filespec *one,
3842 struct diff_filespec *two,
3843 const char *xfrm_msg,
3844 int complete_rewrite,
3845 struct diff_options *o)
3847 struct argv_array argv = ARGV_ARRAY_INIT;
3848 struct argv_array env = ARGV_ARRAY_INIT;
3849 struct diff_queue_struct *q = &diff_queued_diff;
3851 argv_array_push(&argv, pgm);
3852 argv_array_push(&argv, name);
3855 add_external_diff_name(&argv, name, one);
3857 add_external_diff_name(&argv, name, two);
3859 add_external_diff_name(&argv, other, two);
3860 argv_array_push(&argv, other);
3861 argv_array_push(&argv, xfrm_msg);
3865 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3866 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3868 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3869 die(_("external diff died, stopping at %s"), name);
3872 argv_array_clear(&argv);
3873 argv_array_clear(&env);
3876 static int similarity_index(struct diff_filepair *p)
3878 return p->score * 100 / MAX_SCORE;
3881 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3883 if (startup_info->have_repository)
3884 return find_unique_abbrev(oid, abbrev);
3886 char *hex = oid_to_hex(oid);
3888 abbrev = FALLBACK_DEFAULT_ABBREV;
3889 if (abbrev > GIT_SHA1_HEXSZ)
3890 die("BUG: oid abbreviation out of range: %d", abbrev);
3897 static void fill_metainfo(struct strbuf *msg,
3900 struct diff_filespec *one,
3901 struct diff_filespec *two,
3902 struct diff_options *o,
3903 struct diff_filepair *p,
3904 int *must_show_header,
3907 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3908 const char *reset = diff_get_color(use_color, DIFF_RESET);
3909 const char *line_prefix = diff_line_prefix(o);
3911 *must_show_header = 1;
3912 strbuf_init(msg, PATH_MAX * 2 + 300);
3913 switch (p->status) {
3914 case DIFF_STATUS_COPIED:
3915 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3916 line_prefix, set, similarity_index(p));
3917 strbuf_addf(msg, "%s\n%s%scopy from ",
3918 reset, line_prefix, set);
3919 quote_c_style(name, msg, NULL, 0);
3920 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3921 quote_c_style(other, msg, NULL, 0);
3922 strbuf_addf(msg, "%s\n", reset);
3924 case DIFF_STATUS_RENAMED:
3925 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3926 line_prefix, set, similarity_index(p));
3927 strbuf_addf(msg, "%s\n%s%srename from ",
3928 reset, line_prefix, set);
3929 quote_c_style(name, msg, NULL, 0);
3930 strbuf_addf(msg, "%s\n%s%srename to ",
3931 reset, line_prefix, set);
3932 quote_c_style(other, msg, NULL, 0);
3933 strbuf_addf(msg, "%s\n", reset);
3935 case DIFF_STATUS_MODIFIED:
3937 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3939 set, similarity_index(p), reset);
3944 *must_show_header = 0;
3946 if (one && two && oidcmp(&one->oid, &two->oid)) {
3947 int abbrev = o->flags.full_index ? 40 : DEFAULT_ABBREV;
3949 if (o->flags.binary) {
3951 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3952 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3955 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3956 diff_abbrev_oid(&one->oid, abbrev),
3957 diff_abbrev_oid(&two->oid, abbrev));
3958 if (one->mode == two->mode)
3959 strbuf_addf(msg, " %06o", one->mode);
3960 strbuf_addf(msg, "%s\n", reset);
3964 static void run_diff_cmd(const char *pgm,
3967 const char *attr_path,
3968 struct diff_filespec *one,
3969 struct diff_filespec *two,
3971 struct diff_options *o,
3972 struct diff_filepair *p)
3974 const char *xfrm_msg = NULL;
3975 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3976 int must_show_header = 0;
3979 if (o->flags.allow_external) {
3980 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3981 if (drv && drv->external)
3982 pgm = drv->external;
3987 * don't use colors when the header is intended for an
3988 * external diff driver
3990 fill_metainfo(msg, name, other, one, two, o, p,
3992 want_color(o->use_color) && !pgm);
3993 xfrm_msg = msg->len ? msg->buf : NULL;
3997 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3998 complete_rewrite, o);
4002 builtin_diff(name, other ? other : name,
4003 one, two, xfrm_msg, must_show_header,
4004 o, complete_rewrite);
4006 fprintf(o->file, "* Unmerged path %s\n", name);
4009 static void diff_fill_oid_info(struct diff_filespec *one)
4011 if (DIFF_FILE_VALID(one)) {
4012 if (!one->oid_valid) {
4014 if (one->is_stdin) {
4018 if (lstat(one->path, &st) < 0)
4019 die_errno("stat '%s'", one->path);
4020 if (index_path(&one->oid, one->path, &st, 0))
4021 die("cannot hash %s", one->path);
4028 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4030 /* Strip the prefix but do not molest /dev/null and absolute paths */
4031 if (*namep && **namep != '/') {
4032 *namep += prefix_length;
4036 if (*otherp && **otherp != '/') {
4037 *otherp += prefix_length;
4038 if (**otherp == '/')
4043 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4045 const char *pgm = external_diff();
4047 struct diff_filespec *one = p->one;
4048 struct diff_filespec *two = p->two;
4051 const char *attr_path;
4054 other = (strcmp(name, two->path) ? two->path : NULL);
4056 if (o->prefix_length)
4057 strip_prefix(o->prefix_length, &name, &other);
4059 if (!o->flags.allow_external)
4062 if (DIFF_PAIR_UNMERGED(p)) {
4063 run_diff_cmd(pgm, name, NULL, attr_path,
4064 NULL, NULL, NULL, o, p);
4068 diff_fill_oid_info(one);
4069 diff_fill_oid_info(two);
4072 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4073 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4075 * a filepair that changes between file and symlink
4076 * needs to be split into deletion and creation.
4078 struct diff_filespec *null = alloc_filespec(two->path);
4079 run_diff_cmd(NULL, name, other, attr_path,
4080 one, null, &msg, o, p);
4082 strbuf_release(&msg);
4084 null = alloc_filespec(one->path);
4085 run_diff_cmd(NULL, name, other, attr_path,
4086 null, two, &msg, o, p);
4090 run_diff_cmd(pgm, name, other, attr_path,
4091 one, two, &msg, o, p);
4093 strbuf_release(&msg);
4096 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4097 struct diffstat_t *diffstat)
4102 if (DIFF_PAIR_UNMERGED(p)) {
4104 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
4108 name = p->one->path;
4109 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4111 if (o->prefix_length)
4112 strip_prefix(o->prefix_length, &name, &other);
4114 diff_fill_oid_info(p->one);
4115 diff_fill_oid_info(p->two);
4117 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
4120 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4124 const char *attr_path;
4126 if (DIFF_PAIR_UNMERGED(p)) {
4131 name = p->one->path;
4132 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4133 attr_path = other ? other : name;
4135 if (o->prefix_length)
4136 strip_prefix(o->prefix_length, &name, &other);
4138 diff_fill_oid_info(p->one);
4139 diff_fill_oid_info(p->two);
4141 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4144 void diff_setup(struct diff_options *options)
4146 memcpy(options, &default_diff_options, sizeof(*options));
4148 options->file = stdout;
4150 options->abbrev = DEFAULT_ABBREV;
4151 options->line_termination = '\n';
4152 options->break_opt = -1;
4153 options->rename_limit = -1;
4154 options->dirstat_permille = diff_dirstat_permille_default;
4155 options->context = diff_context_default;
4156 options->interhunkcontext = diff_interhunk_context_default;
4157 options->ws_error_highlight = ws_error_highlight_default;
4158 options->flags.rename_empty = 1;
4159 options->objfind = NULL;
4161 /* pathchange left =NULL by default */
4162 options->change = diff_change;
4163 options->add_remove = diff_addremove;
4164 options->use_color = diff_use_color_default;
4165 options->detect_rename = diff_detect_rename_default;
4166 options->xdl_opts |= diff_algorithm;
4167 if (diff_indent_heuristic)
4168 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4170 options->orderfile = diff_order_file_cfg;
4172 if (diff_no_prefix) {
4173 options->a_prefix = options->b_prefix = "";
4174 } else if (!diff_mnemonic_prefix) {
4175 options->a_prefix = "a/";
4176 options->b_prefix = "b/";
4179 options->color_moved = diff_color_moved_default;
4182 void diff_setup_done(struct diff_options *options)
4184 unsigned check_mask = DIFF_FORMAT_NAME |
4185 DIFF_FORMAT_NAME_STATUS |
4186 DIFF_FORMAT_CHECKDIFF |
4187 DIFF_FORMAT_NO_OUTPUT;
4189 if (options->set_default)
4190 options->set_default(options);
4192 if (HAS_MULTI_BITS(options->output_format & check_mask))
4193 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4195 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4196 die(_("-G, -S and --find-object are mutually exclusive"));
4199 * Most of the time we can say "there are changes"
4200 * only by checking if there are changed paths, but
4201 * --ignore-whitespace* options force us to look
4205 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
4206 options->flags.diff_from_contents = 1;
4208 options->flags.diff_from_contents = 0;
4210 if (options->flags.find_copies_harder)
4211 options->detect_rename = DIFF_DETECT_COPY;
4213 if (!options->flags.relative_name)
4214 options->prefix = NULL;
4215 if (options->prefix)
4216 options->prefix_length = strlen(options->prefix);
4218 options->prefix_length = 0;
4220 if (options->output_format & (DIFF_FORMAT_NAME |
4221 DIFF_FORMAT_NAME_STATUS |
4222 DIFF_FORMAT_CHECKDIFF |
4223 DIFF_FORMAT_NO_OUTPUT))
4224 options->output_format &= ~(DIFF_FORMAT_RAW |
4225 DIFF_FORMAT_NUMSTAT |
4226 DIFF_FORMAT_DIFFSTAT |
4227 DIFF_FORMAT_SHORTSTAT |
4228 DIFF_FORMAT_DIRSTAT |
4229 DIFF_FORMAT_SUMMARY |
4233 * These cases always need recursive; we do not drop caller-supplied
4234 * recursive bits for other formats here.
4236 if (options->output_format & (DIFF_FORMAT_PATCH |
4237 DIFF_FORMAT_NUMSTAT |
4238 DIFF_FORMAT_DIFFSTAT |
4239 DIFF_FORMAT_SHORTSTAT |
4240 DIFF_FORMAT_DIRSTAT |
4241 DIFF_FORMAT_SUMMARY |
4242 DIFF_FORMAT_CHECKDIFF))
4243 options->flags.recursive = 1;
4245 * Also pickaxe would not work very well if you do not say recursive
4247 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4248 options->flags.recursive = 1;
4250 * When patches are generated, submodules diffed against the work tree
4251 * must be checked for dirtiness too so it can be shown in the output
4253 if (options->output_format & DIFF_FORMAT_PATCH)
4254 options->flags.dirty_submodules = 1;
4256 if (options->detect_rename && options->rename_limit < 0)
4257 options->rename_limit = diff_rename_limit_default;
4258 if (options->setup & DIFF_SETUP_USE_CACHE) {
4260 /* read-cache does not die even when it fails
4261 * so it is safe for us to do this here. Also
4262 * it does not smudge active_cache or active_nr
4263 * when it fails, so we do not have to worry about
4264 * cleaning it up ourselves either.
4268 if (40 < options->abbrev)
4269 options->abbrev = 40; /* full */
4272 * It does not make sense to show the first hit we happened
4273 * to have found. It does not make sense not to return with
4274 * exit code in such a case either.
4276 if (options->flags.quick) {
4277 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4278 options->flags.exit_with_status = 1;
4281 options->diff_path_counter = 0;
4283 if (options->flags.follow_renames && options->pathspec.nr != 1)
4284 die(_("--follow requires exactly one pathspec"));
4286 if (!options->use_color || external_diff())
4287 options->color_moved = 0;
4290 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4300 if (c == arg_short) {
4304 if (val && isdigit(c)) {
4306 int n = strtoul(arg, &end, 10);
4317 eq = strchrnul(arg, '=');
4319 if (!len || strncmp(arg, arg_long, len))
4324 if (!isdigit(*++eq))
4326 n = strtoul(eq, &end, 10);
4334 static int diff_scoreopt_parse(const char *opt);
4336 static inline int short_opt(char opt, const char **argv,
4337 const char **optarg)
4339 const char *arg = argv[0];
4340 if (arg[0] != '-' || arg[1] != opt)
4342 if (arg[2] != '\0') {
4347 die("Option '%c' requires a value", opt);
4352 int parse_long_opt(const char *opt, const char **argv,
4353 const char **optarg)
4355 const char *arg = argv[0];
4356 if (!skip_prefix(arg, "--", &arg))
4358 if (!skip_prefix(arg, opt, &arg))
4360 if (*arg == '=') { /* stuck form: --option=value */
4366 /* separate form: --option value */
4368 die("Option '--%s' requires a value", opt);
4373 static int stat_opt(struct diff_options *options, const char **av)
4375 const char *arg = av[0];
4377 int width = options->stat_width;
4378 int name_width = options->stat_name_width;
4379 int graph_width = options->stat_graph_width;
4380 int count = options->stat_count;
4383 if (!skip_prefix(arg, "--stat", &arg))
4384 die("BUG: stat option does not begin with --stat: %s", arg);
4389 if (skip_prefix(arg, "-width", &arg)) {
4391 width = strtoul(arg + 1, &end, 10);
4392 else if (!*arg && !av[1])
4393 die_want_option("--stat-width");
4395 width = strtoul(av[1], &end, 10);
4398 } else if (skip_prefix(arg, "-name-width", &arg)) {
4400 name_width = strtoul(arg + 1, &end, 10);
4401 else if (!*arg && !av[1])
4402 die_want_option("--stat-name-width");
4404 name_width = strtoul(av[1], &end, 10);
4407 } else if (skip_prefix(arg, "-graph-width", &arg)) {
4409 graph_width = strtoul(arg + 1, &end, 10);
4410 else if (!*arg && !av[1])
4411 die_want_option("--stat-graph-width");
4413 graph_width = strtoul(av[1], &end, 10);
4416 } else if (skip_prefix(arg, "-count", &arg)) {
4418 count = strtoul(arg + 1, &end, 10);
4419 else if (!*arg && !av[1])
4420 die_want_option("--stat-count");
4422 count = strtoul(av[1], &end, 10);
4428 width = strtoul(arg+1, &end, 10);
4430 name_width = strtoul(end+1, &end, 10);
4432 count = strtoul(end+1, &end, 10);
4435 /* Important! This checks all the error cases! */
4438 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4439 options->stat_name_width = name_width;
4440 options->stat_graph_width = graph_width;
4441 options->stat_width = width;
4442 options->stat_count = count;
4446 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4448 struct strbuf errmsg = STRBUF_INIT;
4449 if (parse_dirstat_params(options, params, &errmsg))
4450 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4452 strbuf_release(&errmsg);
4454 * The caller knows a dirstat-related option is given from the command
4455 * line; allow it to say "return this_function();"
4457 options->output_format |= DIFF_FORMAT_DIRSTAT;
4461 static int parse_submodule_opt(struct diff_options *options, const char *value)
4463 if (parse_submodule_params(options, value))
4464 die(_("Failed to parse --submodule option parameter: '%s'"),
4469 static const char diff_status_letters[] = {
4472 DIFF_STATUS_DELETED,
4473 DIFF_STATUS_MODIFIED,
4474 DIFF_STATUS_RENAMED,
4475 DIFF_STATUS_TYPE_CHANGED,
4476 DIFF_STATUS_UNKNOWN,
4477 DIFF_STATUS_UNMERGED,
4478 DIFF_STATUS_FILTER_AON,
4479 DIFF_STATUS_FILTER_BROKEN,
4483 static unsigned int filter_bit['Z' + 1];
4485 static void prepare_filter_bits(void)
4489 if (!filter_bit[DIFF_STATUS_ADDED]) {
4490 for (i = 0; diff_status_letters[i]; i++)
4491 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4495 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4497 return opt->filter & filter_bit[(int) status];
4500 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4504 prepare_filter_bits();
4507 * If there is a negation e.g. 'd' in the input, and we haven't
4508 * initialized the filter field with another --diff-filter, start
4509 * from full set of bits, except for AON.
4512 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4513 if (optch < 'a' || 'z' < optch)
4515 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4516 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4521 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4525 if ('a' <= optch && optch <= 'z') {
4527 optch = toupper(optch);
4532 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4536 opt->filter &= ~bit;
4543 static void enable_patch_output(int *fmt) {
4544 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4545 *fmt |= DIFF_FORMAT_PATCH;
4548 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4550 int val = parse_ws_error_highlight(arg);
4553 error("unknown value after ws-error-highlight=%.*s",
4557 opt->ws_error_highlight = val;
4561 static int parse_objfind_opt(struct diff_options *opt, const char *arg)
4563 struct object_id oid;
4565 if (get_oid(arg, &oid))
4566 return error("unable to resolve '%s'", arg);
4569 opt->objfind = xcalloc(1, sizeof(*opt->objfind));
4571 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4572 opt->flags.recursive = 1;
4573 opt->flags.tree_in_recursive = 1;
4574 oidset_insert(opt->objfind, &oid);
4578 int diff_opt_parse(struct diff_options *options,
4579 const char **av, int ac, const char *prefix)
4581 const char *arg = av[0];
4588 /* Output format options */
4589 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
4590 || opt_arg(arg, 'U', "unified", &options->context))
4591 enable_patch_output(&options->output_format);
4592 else if (!strcmp(arg, "--raw"))
4593 options->output_format |= DIFF_FORMAT_RAW;
4594 else if (!strcmp(arg, "--patch-with-raw")) {
4595 enable_patch_output(&options->output_format);
4596 options->output_format |= DIFF_FORMAT_RAW;
4597 } else if (!strcmp(arg, "--numstat"))
4598 options->output_format |= DIFF_FORMAT_NUMSTAT;
4599 else if (!strcmp(arg, "--shortstat"))
4600 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4601 else if (skip_prefix(arg, "-X", &arg) ||
4602 skip_to_optional_arg(arg, "--dirstat", &arg))
4603 return parse_dirstat_opt(options, arg);
4604 else if (!strcmp(arg, "--cumulative"))
4605 return parse_dirstat_opt(options, "cumulative");
4606 else if (skip_to_optional_arg(arg, "--dirstat-by-file", &arg)) {
4607 parse_dirstat_opt(options, "files");
4608 return parse_dirstat_opt(options, arg);
4610 else if (!strcmp(arg, "--check"))
4611 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4612 else if (!strcmp(arg, "--summary"))
4613 options->output_format |= DIFF_FORMAT_SUMMARY;
4614 else if (!strcmp(arg, "--patch-with-stat")) {
4615 enable_patch_output(&options->output_format);
4616 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4617 } else if (!strcmp(arg, "--name-only"))
4618 options->output_format |= DIFF_FORMAT_NAME;
4619 else if (!strcmp(arg, "--name-status"))
4620 options->output_format |= DIFF_FORMAT_NAME_STATUS;
4621 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
4622 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4623 else if (starts_with(arg, "--stat"))
4624 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4625 return stat_opt(options, av);
4626 else if (!strcmp(arg, "--compact-summary")) {
4627 options->flags.stat_with_summary = 1;
4628 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4629 } else if (!strcmp(arg, "--no-compact-summary"))
4630 options->flags.stat_with_summary = 0;
4632 /* renames options */
4633 else if (starts_with(arg, "-B") ||
4634 skip_to_optional_arg(arg, "--break-rewrites", NULL)) {
4635 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
4636 return error("invalid argument to -B: %s", arg+2);
4638 else if (starts_with(arg, "-M") ||
4639 skip_to_optional_arg(arg, "--find-renames", NULL)) {
4640 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4641 return error("invalid argument to -M: %s", arg+2);
4642 options->detect_rename = DIFF_DETECT_RENAME;
4644 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
4645 options->irreversible_delete = 1;
4647 else if (starts_with(arg, "-C") ||
4648 skip_to_optional_arg(arg, "--find-copies", NULL)) {
4649 if (options->detect_rename == DIFF_DETECT_COPY)
4650 options->flags.find_copies_harder = 1;
4651 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4652 return error("invalid argument to -C: %s", arg+2);
4653 options->detect_rename = DIFF_DETECT_COPY;
4655 else if (!strcmp(arg, "--no-renames"))
4656 options->detect_rename = 0;
4657 else if (!strcmp(arg, "--rename-empty"))
4658 options->flags.rename_empty = 1;
4659 else if (!strcmp(arg, "--no-rename-empty"))
4660 options->flags.rename_empty = 0;
4661 else if (skip_to_optional_arg_default(arg, "--relative", &arg, NULL)) {
4662 options->flags.relative_name = 1;
4664 options->prefix = arg;
4668 else if (!strcmp(arg, "--minimal"))
4669 DIFF_XDL_SET(options, NEED_MINIMAL);
4670 else if (!strcmp(arg, "--no-minimal"))
4671 DIFF_XDL_CLR(options, NEED_MINIMAL);
4672 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
4673 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
4674 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
4675 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
4676 else if (!strcmp(arg, "--ignore-space-at-eol"))
4677 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
4678 else if (!strcmp(arg, "--ignore-cr-at-eol"))
4679 DIFF_XDL_SET(options, IGNORE_CR_AT_EOL);
4680 else if (!strcmp(arg, "--ignore-blank-lines"))
4681 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
4682 else if (!strcmp(arg, "--indent-heuristic"))
4683 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4684 else if (!strcmp(arg, "--no-indent-heuristic"))
4685 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
4686 else if (!strcmp(arg, "--patience")) {
4688 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4690 * Both --patience and --anchored use PATIENCE_DIFF
4691 * internally, so remove any anchors previously
4694 for (i = 0; i < options->anchors_nr; i++)
4695 free(options->anchors[i]);
4696 options->anchors_nr = 0;
4697 } else if (!strcmp(arg, "--histogram"))
4698 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
4699 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
4700 long value = parse_algorithm_value(optarg);
4702 return error("option diff-algorithm accepts \"myers\", "
4703 "\"minimal\", \"patience\" and \"histogram\"");
4704 /* clear out previous settings */
4705 DIFF_XDL_CLR(options, NEED_MINIMAL);
4706 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4707 options->xdl_opts |= value;
4709 } else if (skip_prefix(arg, "--anchored=", &arg)) {
4710 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4711 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4712 options->anchors_alloc);
4713 options->anchors[options->anchors_nr++] = xstrdup(arg);
4717 else if (!strcmp(arg, "--binary")) {
4718 enable_patch_output(&options->output_format);
4719 options->flags.binary = 1;
4721 else if (!strcmp(arg, "--full-index"))
4722 options->flags.full_index = 1;
4723 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
4724 options->flags.text = 1;
4725 else if (!strcmp(arg, "-R"))
4726 options->flags.reverse_diff = 1;
4727 else if (!strcmp(arg, "--find-copies-harder"))
4728 options->flags.find_copies_harder = 1;
4729 else if (!strcmp(arg, "--follow"))
4730 options->flags.follow_renames = 1;
4731 else if (!strcmp(arg, "--no-follow")) {
4732 options->flags.follow_renames = 0;
4733 options->flags.default_follow_renames = 0;
4734 } else if (skip_to_optional_arg_default(arg, "--color", &arg, "always")) {
4735 int value = git_config_colorbool(NULL, arg);
4737 return error("option `color' expects \"always\", \"auto\", or \"never\"");
4738 options->use_color = value;
4740 else if (!strcmp(arg, "--no-color"))
4741 options->use_color = 0;
4742 else if (!strcmp(arg, "--color-moved")) {
4743 if (diff_color_moved_default)
4744 options->color_moved = diff_color_moved_default;
4745 if (options->color_moved == COLOR_MOVED_NO)
4746 options->color_moved = COLOR_MOVED_DEFAULT;
4747 } else if (!strcmp(arg, "--no-color-moved"))
4748 options->color_moved = COLOR_MOVED_NO;
4749 else if (skip_prefix(arg, "--color-moved=", &arg)) {
4750 int cm = parse_color_moved(arg);
4752 die("bad --color-moved argument: %s", arg);
4753 options->color_moved = cm;
4754 } else if (skip_prefix(arg, "--color-moved-ws=", &arg)) {
4755 options->color_moved_ws_handling = parse_color_moved_ws(arg);
4756 } else if (skip_to_optional_arg_default(arg, "--color-words", &options->word_regex, NULL)) {
4757 options->use_color = 1;
4758 options->word_diff = DIFF_WORDS_COLOR;
4760 else if (!strcmp(arg, "--word-diff")) {
4761 if (options->word_diff == DIFF_WORDS_NONE)
4762 options->word_diff = DIFF_WORDS_PLAIN;
4764 else if (skip_prefix(arg, "--word-diff=", &arg)) {
4765 if (!strcmp(arg, "plain"))
4766 options->word_diff = DIFF_WORDS_PLAIN;
4767 else if (!strcmp(arg, "color")) {
4768 options->use_color = 1;
4769 options->word_diff = DIFF_WORDS_COLOR;
4771 else if (!strcmp(arg, "porcelain"))
4772 options->word_diff = DIFF_WORDS_PORCELAIN;
4773 else if (!strcmp(arg, "none"))
4774 options->word_diff = DIFF_WORDS_NONE;
4776 die("bad --word-diff argument: %s", arg);
4778 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
4779 if (options->word_diff == DIFF_WORDS_NONE)
4780 options->word_diff = DIFF_WORDS_PLAIN;
4781 options->word_regex = optarg;
4784 else if (!strcmp(arg, "--exit-code"))
4785 options->flags.exit_with_status = 1;
4786 else if (!strcmp(arg, "--quiet"))
4787 options->flags.quick = 1;
4788 else if (!strcmp(arg, "--ext-diff"))
4789 options->flags.allow_external = 1;
4790 else if (!strcmp(arg, "--no-ext-diff"))
4791 options->flags.allow_external = 0;
4792 else if (!strcmp(arg, "--textconv")) {
4793 options->flags.allow_textconv = 1;
4794 options->flags.textconv_set_via_cmdline = 1;
4795 } else if (!strcmp(arg, "--no-textconv"))
4796 options->flags.allow_textconv = 0;
4797 else if (skip_to_optional_arg_default(arg, "--ignore-submodules", &arg, "all")) {
4798 options->flags.override_submodule_config = 1;
4799 handle_ignore_submodules_arg(options, arg);
4800 } else if (skip_to_optional_arg_default(arg, "--submodule", &arg, "log"))
4801 return parse_submodule_opt(options, arg);
4802 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
4803 return parse_ws_error_highlight_opt(options, arg);
4804 else if (!strcmp(arg, "--ita-invisible-in-index"))
4805 options->ita_invisible_in_index = 1;
4806 else if (!strcmp(arg, "--ita-visible-in-index"))
4807 options->ita_invisible_in_index = 0;
4810 else if (!strcmp(arg, "-z"))
4811 options->line_termination = 0;
4812 else if ((argcount = short_opt('l', av, &optarg))) {
4813 options->rename_limit = strtoul(optarg, NULL, 10);
4816 else if ((argcount = short_opt('S', av, &optarg))) {
4817 options->pickaxe = optarg;
4818 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
4820 } else if ((argcount = short_opt('G', av, &optarg))) {
4821 options->pickaxe = optarg;
4822 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
4825 else if (!strcmp(arg, "--pickaxe-all"))
4826 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
4827 else if (!strcmp(arg, "--pickaxe-regex"))
4828 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
4829 else if ((argcount = short_opt('O', av, &optarg))) {
4830 options->orderfile = prefix_filename(prefix, optarg);
4832 } else if (skip_prefix(arg, "--find-object=", &arg))
4833 return parse_objfind_opt(options, arg);
4834 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
4835 int offending = parse_diff_filter_opt(optarg, options);
4837 die("unknown change class '%c' in --diff-filter=%s",
4841 else if (!strcmp(arg, "--no-abbrev"))
4842 options->abbrev = 0;
4843 else if (!strcmp(arg, "--abbrev"))
4844 options->abbrev = DEFAULT_ABBREV;
4845 else if (skip_prefix(arg, "--abbrev=", &arg)) {
4846 options->abbrev = strtoul(arg, NULL, 10);
4847 if (options->abbrev < MINIMUM_ABBREV)
4848 options->abbrev = MINIMUM_ABBREV;
4849 else if (40 < options->abbrev)
4850 options->abbrev = 40;
4852 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
4853 options->a_prefix = optarg;
4856 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
4857 options->line_prefix = optarg;
4858 options->line_prefix_length = strlen(options->line_prefix);
4859 graph_setup_line_prefix(options);
4862 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
4863 options->b_prefix = optarg;
4866 else if (!strcmp(arg, "--no-prefix"))
4867 options->a_prefix = options->b_prefix = "";
4868 else if (opt_arg(arg, '\0', "inter-hunk-context",
4869 &options->interhunkcontext))
4871 else if (!strcmp(arg, "-W"))
4872 options->flags.funccontext = 1;
4873 else if (!strcmp(arg, "--function-context"))
4874 options->flags.funccontext = 1;
4875 else if (!strcmp(arg, "--no-function-context"))
4876 options->flags.funccontext = 0;
4877 else if ((argcount = parse_long_opt("output", av, &optarg))) {
4878 char *path = prefix_filename(prefix, optarg);
4879 options->file = xfopen(path, "w");
4880 options->close_file = 1;
4881 if (options->use_color != GIT_COLOR_ALWAYS)
4882 options->use_color = GIT_COLOR_NEVER;
4890 int parse_rename_score(const char **cp_p)
4892 unsigned long num, scale;
4894 const char *cp = *cp_p;
4901 if ( !dot && ch == '.' ) {
4904 } else if ( ch == '%' ) {
4905 scale = dot ? scale*100 : 100;
4906 cp++; /* % is always at the end */
4908 } else if ( ch >= '0' && ch <= '9' ) {
4909 if ( scale < 100000 ) {
4911 num = (num*10) + (ch-'0');
4920 /* user says num divided by scale and we say internally that
4921 * is MAX_SCORE * num / scale.
4923 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4926 static int diff_scoreopt_parse(const char *opt)
4928 int opt1, opt2, cmd;
4934 /* convert the long-form arguments into short-form versions */
4935 if (skip_prefix(opt, "break-rewrites", &opt)) {
4936 if (*opt == 0 || *opt++ == '=')
4938 } else if (skip_prefix(opt, "find-copies", &opt)) {
4939 if (*opt == 0 || *opt++ == '=')
4941 } else if (skip_prefix(opt, "find-renames", &opt)) {
4942 if (*opt == 0 || *opt++ == '=')
4946 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4947 return -1; /* that is not a -M, -C, or -B option */
4949 opt1 = parse_rename_score(&opt);
4955 else if (*opt != '/')
4956 return -1; /* we expect -B80/99 or -B80 */
4959 opt2 = parse_rename_score(&opt);
4964 return opt1 | (opt2 << 16);
4967 struct diff_queue_struct diff_queued_diff;
4969 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4971 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4972 queue->queue[queue->nr++] = dp;
4975 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4976 struct diff_filespec *one,
4977 struct diff_filespec *two)
4979 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4987 void diff_free_filepair(struct diff_filepair *p)
4989 free_filespec(p->one);
4990 free_filespec(p->two);
4994 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
4999 /* Do we want all 40 hex characters? */
5000 if (len == GIT_SHA1_HEXSZ)
5001 return oid_to_hex(oid);
5003 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5004 abbrev = diff_abbrev_oid(oid, len);
5006 if (!print_sha1_ellipsis())
5009 abblen = strlen(abbrev);
5012 * In well-behaved cases, where the abbreviated result is the
5013 * same as the requested length, append three dots after the
5014 * abbreviation (hence the whole logic is limited to the case
5015 * where abblen < 37); when the actual abbreviated result is a
5016 * bit longer than the requested length, we reduce the number
5017 * of dots so that they match the well-behaved ones. However,
5018 * if the actual abbreviation is longer than the requested
5019 * length by more than three, we give up on aligning, and add
5020 * three dots anyway, to indicate that the output is not the
5021 * full object name. Yes, this may be suboptimal, but this
5022 * appears only in "diff --raw --abbrev" output and it is not
5023 * worth the effort to change it now. Note that this would
5024 * likely to work fine when the automatic sizing of default
5025 * abbreviation length is used--we would be fed -1 in "len" in
5026 * that case, and will end up always appending three-dots, but
5027 * the automatic sizing is supposed to give abblen that ensures
5028 * uniqueness across all objects (statistically speaking).
5030 if (abblen < GIT_SHA1_HEXSZ - 3) {
5031 static char hex[GIT_MAX_HEXSZ + 1];
5032 if (len < abblen && abblen <= len + 2)
5033 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5035 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5039 return oid_to_hex(oid);
5042 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5044 int line_termination = opt->line_termination;
5045 int inter_name_termination = line_termination ? '\t' : '\0';
5047 fprintf(opt->file, "%s", diff_line_prefix(opt));
5048 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5049 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5050 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5051 fprintf(opt->file, "%s ",
5052 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5055 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5056 inter_name_termination);
5058 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5061 if (p->status == DIFF_STATUS_COPIED ||
5062 p->status == DIFF_STATUS_RENAMED) {
5063 const char *name_a, *name_b;
5064 name_a = p->one->path;
5065 name_b = p->two->path;
5066 strip_prefix(opt->prefix_length, &name_a, &name_b);
5067 write_name_quoted(name_a, opt->file, inter_name_termination);
5068 write_name_quoted(name_b, opt->file, line_termination);
5070 const char *name_a, *name_b;
5071 name_a = p->one->mode ? p->one->path : p->two->path;
5073 strip_prefix(opt->prefix_length, &name_a, &name_b);
5074 write_name_quoted(name_a, opt->file, line_termination);
5078 int diff_unmodified_pair(struct diff_filepair *p)
5080 /* This function is written stricter than necessary to support
5081 * the currently implemented transformers, but the idea is to
5082 * let transformers to produce diff_filepairs any way they want,
5083 * and filter and clean them up here before producing the output.
5085 struct diff_filespec *one = p->one, *two = p->two;
5087 if (DIFF_PAIR_UNMERGED(p))
5088 return 0; /* unmerged is interesting */
5090 /* deletion, addition, mode or type change
5091 * and rename are all interesting.
5093 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5094 DIFF_PAIR_MODE_CHANGED(p) ||
5095 strcmp(one->path, two->path))
5098 /* both are valid and point at the same path. that is, we are
5099 * dealing with a change.
5101 if (one->oid_valid && two->oid_valid &&
5102 !oidcmp(&one->oid, &two->oid) &&
5103 !one->dirty_submodule && !two->dirty_submodule)
5104 return 1; /* no change */
5105 if (!one->oid_valid && !two->oid_valid)
5106 return 1; /* both look at the same file on the filesystem. */
5110 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5112 if (diff_unmodified_pair(p))
5115 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5116 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5117 return; /* no tree diffs in patch format */
5122 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5123 struct diffstat_t *diffstat)
5125 if (diff_unmodified_pair(p))
5128 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5129 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5130 return; /* no useful stat for tree diffs */
5132 run_diffstat(p, o, diffstat);
5135 static void diff_flush_checkdiff(struct diff_filepair *p,
5136 struct diff_options *o)
5138 if (diff_unmodified_pair(p))
5141 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5142 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5143 return; /* nothing to check in tree diffs */
5145 run_checkdiff(p, o);
5148 int diff_queue_is_empty(void)
5150 struct diff_queue_struct *q = &diff_queued_diff;
5152 for (i = 0; i < q->nr; i++)
5153 if (!diff_unmodified_pair(q->queue[i]))
5159 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5161 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5164 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5166 s->oid_valid ? oid_to_hex(&s->oid) : "");
5167 fprintf(stderr, "queue[%d] %s size %lu\n",
5172 void diff_debug_filepair(const struct diff_filepair *p, int i)
5174 diff_debug_filespec(p->one, i, "one");
5175 diff_debug_filespec(p->two, i, "two");
5176 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5177 p->score, p->status ? p->status : '?',
5178 p->one->rename_used, p->broken_pair);
5181 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5185 fprintf(stderr, "%s\n", msg);
5186 fprintf(stderr, "q->nr = %d\n", q->nr);
5187 for (i = 0; i < q->nr; i++) {
5188 struct diff_filepair *p = q->queue[i];
5189 diff_debug_filepair(p, i);
5194 static void diff_resolve_rename_copy(void)
5197 struct diff_filepair *p;
5198 struct diff_queue_struct *q = &diff_queued_diff;
5200 diff_debug_queue("resolve-rename-copy", q);
5202 for (i = 0; i < q->nr; i++) {
5204 p->status = 0; /* undecided */
5205 if (DIFF_PAIR_UNMERGED(p))
5206 p->status = DIFF_STATUS_UNMERGED;
5207 else if (!DIFF_FILE_VALID(p->one))
5208 p->status = DIFF_STATUS_ADDED;
5209 else if (!DIFF_FILE_VALID(p->two))
5210 p->status = DIFF_STATUS_DELETED;
5211 else if (DIFF_PAIR_TYPE_CHANGED(p))
5212 p->status = DIFF_STATUS_TYPE_CHANGED;
5214 /* from this point on, we are dealing with a pair
5215 * whose both sides are valid and of the same type, i.e.
5216 * either in-place edit or rename/copy edit.
5218 else if (DIFF_PAIR_RENAME(p)) {
5220 * A rename might have re-connected a broken
5221 * pair up, causing the pathnames to be the
5222 * same again. If so, that's not a rename at
5223 * all, just a modification..
5225 * Otherwise, see if this source was used for
5226 * multiple renames, in which case we decrement
5227 * the count, and call it a copy.
5229 if (!strcmp(p->one->path, p->two->path))
5230 p->status = DIFF_STATUS_MODIFIED;
5231 else if (--p->one->rename_used > 0)
5232 p->status = DIFF_STATUS_COPIED;
5234 p->status = DIFF_STATUS_RENAMED;
5236 else if (oidcmp(&p->one->oid, &p->two->oid) ||
5237 p->one->mode != p->two->mode ||
5238 p->one->dirty_submodule ||
5239 p->two->dirty_submodule ||
5240 is_null_oid(&p->one->oid))
5241 p->status = DIFF_STATUS_MODIFIED;
5243 /* This is a "no-change" entry and should not
5244 * happen anymore, but prepare for broken callers.
5246 error("feeding unmodified %s to diffcore",
5248 p->status = DIFF_STATUS_UNKNOWN;
5251 diff_debug_queue("resolve-rename-copy done", q);
5254 static int check_pair_status(struct diff_filepair *p)
5256 switch (p->status) {
5257 case DIFF_STATUS_UNKNOWN:
5260 die("internal error in diff-resolve-rename-copy");
5266 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5268 int fmt = opt->output_format;
5270 if (fmt & DIFF_FORMAT_CHECKDIFF)
5271 diff_flush_checkdiff(p, opt);
5272 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5273 diff_flush_raw(p, opt);
5274 else if (fmt & DIFF_FORMAT_NAME) {
5275 const char *name_a, *name_b;
5276 name_a = p->two->path;
5278 strip_prefix(opt->prefix_length, &name_a, &name_b);
5279 fprintf(opt->file, "%s", diff_line_prefix(opt));
5280 write_name_quoted(name_a, opt->file, opt->line_termination);
5284 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5286 struct strbuf sb = STRBUF_INIT;
5288 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5290 strbuf_addf(&sb, " %s ", newdelete);
5292 quote_c_style(fs->path, &sb, NULL, 0);
5293 strbuf_addch(&sb, '\n');
5294 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5296 strbuf_release(&sb);
5299 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5302 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5303 struct strbuf sb = STRBUF_INIT;
5304 strbuf_addf(&sb, " mode change %06o => %06o",
5305 p->one->mode, p->two->mode);
5307 strbuf_addch(&sb, ' ');
5308 quote_c_style(p->two->path, &sb, NULL, 0);
5310 strbuf_addch(&sb, '\n');
5311 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5313 strbuf_release(&sb);
5317 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5318 struct diff_filepair *p)
5320 struct strbuf sb = STRBUF_INIT;
5321 struct strbuf names = STRBUF_INIT;
5323 pprint_rename(&names, p->one->path, p->two->path);
5324 strbuf_addf(&sb, " %s %s (%d%%)\n",
5325 renamecopy, names.buf, similarity_index(p));
5326 strbuf_release(&names);
5327 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5329 show_mode_change(opt, p, 0);
5330 strbuf_release(&sb);
5333 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5336 case DIFF_STATUS_DELETED:
5337 show_file_mode_name(opt, "delete", p->one);
5339 case DIFF_STATUS_ADDED:
5340 show_file_mode_name(opt, "create", p->two);
5342 case DIFF_STATUS_COPIED:
5343 show_rename_copy(opt, "copy", p);
5345 case DIFF_STATUS_RENAMED:
5346 show_rename_copy(opt, "rename", p);
5350 struct strbuf sb = STRBUF_INIT;
5351 strbuf_addstr(&sb, " rewrite ");
5352 quote_c_style(p->two->path, &sb, NULL, 0);
5353 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5354 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5356 strbuf_release(&sb);
5358 show_mode_change(opt, p, !p->score);
5368 static int remove_space(char *line, int len)
5374 for (i = 0; i < len; i++)
5375 if (!isspace((c = line[i])))
5381 static void patch_id_consume(void *priv, char *line, unsigned long len)
5383 struct patch_id_t *data = priv;
5386 /* Ignore line numbers when computing the SHA1 of the patch */
5387 if (starts_with(line, "@@ -"))
5390 new_len = remove_space(line, len);
5392 git_SHA1_Update(data->ctx, line, new_len);
5393 data->patchlen += new_len;
5396 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
5398 git_SHA1_Update(ctx, str, strlen(str));
5401 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
5403 /* large enough for 2^32 in octal */
5405 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
5406 git_SHA1_Update(ctx, buf, len);
5409 /* returns 0 upon success, and writes result into sha1 */
5410 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5412 struct diff_queue_struct *q = &diff_queued_diff;
5415 struct patch_id_t data;
5417 git_SHA1_Init(&ctx);
5418 memset(&data, 0, sizeof(struct patch_id_t));
5421 for (i = 0; i < q->nr; i++) {
5425 struct diff_filepair *p = q->queue[i];
5428 memset(&xpp, 0, sizeof(xpp));
5429 memset(&xecfg, 0, sizeof(xecfg));
5431 return error("internal diff status error");
5432 if (p->status == DIFF_STATUS_UNKNOWN)
5434 if (diff_unmodified_pair(p))
5436 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5437 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5439 if (DIFF_PAIR_UNMERGED(p))
5442 diff_fill_oid_info(p->one);
5443 diff_fill_oid_info(p->two);
5445 len1 = remove_space(p->one->path, strlen(p->one->path));
5446 len2 = remove_space(p->two->path, strlen(p->two->path));
5447 patch_id_add_string(&ctx, "diff--git");
5448 patch_id_add_string(&ctx, "a/");
5449 git_SHA1_Update(&ctx, p->one->path, len1);
5450 patch_id_add_string(&ctx, "b/");
5451 git_SHA1_Update(&ctx, p->two->path, len2);
5453 if (p->one->mode == 0) {
5454 patch_id_add_string(&ctx, "newfilemode");
5455 patch_id_add_mode(&ctx, p->two->mode);
5456 patch_id_add_string(&ctx, "---/dev/null");
5457 patch_id_add_string(&ctx, "+++b/");
5458 git_SHA1_Update(&ctx, p->two->path, len2);
5459 } else if (p->two->mode == 0) {
5460 patch_id_add_string(&ctx, "deletedfilemode");
5461 patch_id_add_mode(&ctx, p->one->mode);
5462 patch_id_add_string(&ctx, "---a/");
5463 git_SHA1_Update(&ctx, p->one->path, len1);
5464 patch_id_add_string(&ctx, "+++/dev/null");
5466 patch_id_add_string(&ctx, "---a/");
5467 git_SHA1_Update(&ctx, p->one->path, len1);
5468 patch_id_add_string(&ctx, "+++b/");
5469 git_SHA1_Update(&ctx, p->two->path, len2);
5472 if (diff_header_only)
5475 if (fill_mmfile(&mf1, p->one) < 0 ||
5476 fill_mmfile(&mf2, p->two) < 0)
5477 return error("unable to read files to diff");
5479 if (diff_filespec_is_binary(p->one) ||
5480 diff_filespec_is_binary(p->two)) {
5481 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5483 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5491 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
5493 return error("unable to generate patch-id diff for %s",
5497 git_SHA1_Final(oid->hash, &ctx);
5501 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5503 struct diff_queue_struct *q = &diff_queued_diff;
5505 int result = diff_get_patch_id(options, oid, diff_header_only);
5507 for (i = 0; i < q->nr; i++)
5508 diff_free_filepair(q->queue[i]);
5511 DIFF_QUEUE_CLEAR(q);
5516 static int is_summary_empty(const struct diff_queue_struct *q)
5520 for (i = 0; i < q->nr; i++) {
5521 const struct diff_filepair *p = q->queue[i];
5523 switch (p->status) {
5524 case DIFF_STATUS_DELETED:
5525 case DIFF_STATUS_ADDED:
5526 case DIFF_STATUS_COPIED:
5527 case DIFF_STATUS_RENAMED:
5532 if (p->one->mode && p->two->mode &&
5533 p->one->mode != p->two->mode)
5541 static const char rename_limit_warning[] =
5542 N_("inexact rename detection was skipped due to too many files.");
5544 static const char degrade_cc_to_c_warning[] =
5545 N_("only found copies from modified paths due to too many files.");
5547 static const char rename_limit_advice[] =
5548 N_("you may want to set your %s variable to at least "
5549 "%d and retry the command.");
5551 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
5555 warning(_(degrade_cc_to_c_warning));
5557 warning(_(rename_limit_warning));
5561 warning(_(rename_limit_advice), varname, needed);
5564 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
5567 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
5568 struct diff_queue_struct *q = &diff_queued_diff;
5570 if (WSEH_NEW & WS_RULE_MASK)
5571 die("BUG: WS rules bit mask overlaps with diff symbol flags");
5574 o->emitted_symbols = &esm;
5576 for (i = 0; i < q->nr; i++) {
5577 struct diff_filepair *p = q->queue[i];
5578 if (check_pair_status(p))
5579 diff_flush_patch(p, o);
5582 if (o->emitted_symbols) {
5583 if (o->color_moved) {
5584 struct hashmap add_lines, del_lines;
5586 hashmap_init(&del_lines, moved_entry_cmp, o, 0);
5587 hashmap_init(&add_lines, moved_entry_cmp, o, 0);
5589 add_lines_to_move_detection(o, &add_lines, &del_lines);
5590 mark_color_as_moved(o, &add_lines, &del_lines);
5591 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
5594 hashmap_free(&add_lines, 0);
5595 hashmap_free(&del_lines, 0);
5598 for (i = 0; i < esm.nr; i++)
5599 emit_diff_symbol_from_struct(o, &esm.buf[i]);
5601 for (i = 0; i < esm.nr; i++)
5602 free((void *)esm.buf[i].line);
5607 void diff_flush(struct diff_options *options)
5609 struct diff_queue_struct *q = &diff_queued_diff;
5610 int i, output_format = options->output_format;
5612 int dirstat_by_line = 0;
5615 * Order: raw, stat, summary, patch
5616 * or: name/name-status/checkdiff (other bits clear)
5621 if (output_format & (DIFF_FORMAT_RAW |
5623 DIFF_FORMAT_NAME_STATUS |
5624 DIFF_FORMAT_CHECKDIFF)) {
5625 for (i = 0; i < q->nr; i++) {
5626 struct diff_filepair *p = q->queue[i];
5627 if (check_pair_status(p))
5628 flush_one_pair(p, options);
5633 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
5634 dirstat_by_line = 1;
5636 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
5638 struct diffstat_t diffstat;
5640 memset(&diffstat, 0, sizeof(struct diffstat_t));
5641 for (i = 0; i < q->nr; i++) {
5642 struct diff_filepair *p = q->queue[i];
5643 if (check_pair_status(p))
5644 diff_flush_stat(p, options, &diffstat);
5646 if (output_format & DIFF_FORMAT_NUMSTAT)
5647 show_numstat(&diffstat, options);
5648 if (output_format & DIFF_FORMAT_DIFFSTAT)
5649 show_stats(&diffstat, options);
5650 if (output_format & DIFF_FORMAT_SHORTSTAT)
5651 show_shortstats(&diffstat, options);
5652 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
5653 show_dirstat_by_line(&diffstat, options);
5654 free_diffstat_info(&diffstat);
5657 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
5658 show_dirstat(options);
5660 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
5661 for (i = 0; i < q->nr; i++) {
5662 diff_summary(options, q->queue[i]);
5667 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
5668 options->flags.exit_with_status &&
5669 options->flags.diff_from_contents) {
5671 * run diff_flush_patch for the exit status. setting
5672 * options->file to /dev/null should be safe, because we
5673 * aren't supposed to produce any output anyway.
5675 if (options->close_file)
5676 fclose(options->file);
5677 options->file = xfopen("/dev/null", "w");
5678 options->close_file = 1;
5679 options->color_moved = 0;
5680 for (i = 0; i < q->nr; i++) {
5681 struct diff_filepair *p = q->queue[i];
5682 if (check_pair_status(p))
5683 diff_flush_patch(p, options);
5684 if (options->found_changes)
5689 if (output_format & DIFF_FORMAT_PATCH) {
5691 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
5692 if (options->stat_sep)
5693 /* attach patch instead of inline */
5694 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
5698 diff_flush_patch_all_file_pairs(options);
5701 if (output_format & DIFF_FORMAT_CALLBACK)
5702 options->format_callback(q, options, options->format_callback_data);
5704 for (i = 0; i < q->nr; i++)
5705 diff_free_filepair(q->queue[i]);
5708 DIFF_QUEUE_CLEAR(q);
5709 if (options->close_file)
5710 fclose(options->file);
5713 * Report the content-level differences with HAS_CHANGES;
5714 * diff_addremove/diff_change does not set the bit when
5715 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
5717 if (options->flags.diff_from_contents) {
5718 if (options->found_changes)
5719 options->flags.has_changes = 1;
5721 options->flags.has_changes = 0;
5725 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
5727 return (((p->status == DIFF_STATUS_MODIFIED) &&
5729 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
5731 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
5732 ((p->status != DIFF_STATUS_MODIFIED) &&
5733 filter_bit_tst(p->status, options)));
5736 static void diffcore_apply_filter(struct diff_options *options)
5739 struct diff_queue_struct *q = &diff_queued_diff;
5740 struct diff_queue_struct outq;
5742 DIFF_QUEUE_CLEAR(&outq);
5744 if (!options->filter)
5747 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
5749 for (i = found = 0; !found && i < q->nr; i++) {
5750 if (match_filter(options, q->queue[i]))
5756 /* otherwise we will clear the whole queue
5757 * by copying the empty outq at the end of this
5758 * function, but first clear the current entries
5761 for (i = 0; i < q->nr; i++)
5762 diff_free_filepair(q->queue[i]);
5765 /* Only the matching ones */
5766 for (i = 0; i < q->nr; i++) {
5767 struct diff_filepair *p = q->queue[i];
5768 if (match_filter(options, p))
5771 diff_free_filepair(p);
5778 /* Check whether two filespecs with the same mode and size are identical */
5779 static int diff_filespec_is_identical(struct diff_filespec *one,
5780 struct diff_filespec *two)
5782 if (S_ISGITLINK(one->mode))
5784 if (diff_populate_filespec(one, 0))
5786 if (diff_populate_filespec(two, 0))
5788 return !memcmp(one->data, two->data, one->size);
5791 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
5793 if (p->done_skip_stat_unmatch)
5794 return p->skip_stat_unmatch_result;
5796 p->done_skip_stat_unmatch = 1;
5797 p->skip_stat_unmatch_result = 0;
5799 * 1. Entries that come from stat info dirtiness
5800 * always have both sides (iow, not create/delete),
5801 * one side of the object name is unknown, with
5802 * the same mode and size. Keep the ones that
5803 * do not match these criteria. They have real
5806 * 2. At this point, the file is known to be modified,
5807 * with the same mode and size, and the object
5808 * name of one side is unknown. Need to inspect
5809 * the identical contents.
5811 if (!DIFF_FILE_VALID(p->one) || /* (1) */
5812 !DIFF_FILE_VALID(p->two) ||
5813 (p->one->oid_valid && p->two->oid_valid) ||
5814 (p->one->mode != p->two->mode) ||
5815 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
5816 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
5817 (p->one->size != p->two->size) ||
5818 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
5819 p->skip_stat_unmatch_result = 1;
5820 return p->skip_stat_unmatch_result;
5823 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
5826 struct diff_queue_struct *q = &diff_queued_diff;
5827 struct diff_queue_struct outq;
5828 DIFF_QUEUE_CLEAR(&outq);
5830 for (i = 0; i < q->nr; i++) {
5831 struct diff_filepair *p = q->queue[i];
5833 if (diff_filespec_check_stat_unmatch(p))
5837 * The caller can subtract 1 from skip_stat_unmatch
5838 * to determine how many paths were dirty only
5839 * due to stat info mismatch.
5841 if (!diffopt->flags.no_index)
5842 diffopt->skip_stat_unmatch++;
5843 diff_free_filepair(p);
5850 static int diffnamecmp(const void *a_, const void *b_)
5852 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
5853 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
5854 const char *name_a, *name_b;
5856 name_a = a->one ? a->one->path : a->two->path;
5857 name_b = b->one ? b->one->path : b->two->path;
5858 return strcmp(name_a, name_b);
5861 void diffcore_fix_diff_index(struct diff_options *options)
5863 struct diff_queue_struct *q = &diff_queued_diff;
5864 QSORT(q->queue, q->nr, diffnamecmp);
5867 void diffcore_std(struct diff_options *options)
5869 /* NOTE please keep the following in sync with diff_tree_combined() */
5870 if (options->skip_stat_unmatch)
5871 diffcore_skip_stat_unmatch(options);
5872 if (!options->found_follow) {
5873 /* See try_to_follow_renames() in tree-diff.c */
5874 if (options->break_opt != -1)
5875 diffcore_break(options->break_opt);
5876 if (options->detect_rename)
5877 diffcore_rename(options);
5878 if (options->break_opt != -1)
5879 diffcore_merge_broken();
5881 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
5882 diffcore_pickaxe(options);
5883 if (options->orderfile)
5884 diffcore_order(options->orderfile);
5885 if (!options->found_follow)
5886 /* See try_to_follow_renames() in tree-diff.c */
5887 diff_resolve_rename_copy();
5888 diffcore_apply_filter(options);
5890 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
5891 options->flags.has_changes = 1;
5893 options->flags.has_changes = 0;
5895 options->found_follow = 0;
5898 int diff_result_code(struct diff_options *opt, int status)
5902 diff_warn_rename_limit("diff.renameLimit",
5903 opt->needed_rename_limit,
5904 opt->degraded_cc_to_c);
5905 if (!opt->flags.exit_with_status &&
5906 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
5908 if (opt->flags.exit_with_status &&
5909 opt->flags.has_changes)
5911 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
5912 opt->flags.check_failed)
5917 int diff_can_quit_early(struct diff_options *opt)
5919 return (opt->flags.quick &&
5921 opt->flags.has_changes);
5925 * Shall changes to this submodule be ignored?
5927 * Submodule changes can be configured to be ignored separately for each path,
5928 * but that configuration can be overridden from the command line.
5930 static int is_submodule_ignored(const char *path, struct diff_options *options)
5933 struct diff_flags orig_flags = options->flags;
5934 if (!options->flags.override_submodule_config)
5935 set_diffopt_flags_from_submodule_config(options, path);
5936 if (options->flags.ignore_submodules)
5938 options->flags = orig_flags;
5942 void diff_addremove(struct diff_options *options,
5943 int addremove, unsigned mode,
5944 const struct object_id *oid,
5946 const char *concatpath, unsigned dirty_submodule)
5948 struct diff_filespec *one, *two;
5950 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
5953 /* This may look odd, but it is a preparation for
5954 * feeding "there are unchanged files which should
5955 * not produce diffs, but when you are doing copy
5956 * detection you would need them, so here they are"
5957 * entries to the diff-core. They will be prefixed
5958 * with something like '=' or '*' (I haven't decided
5959 * which but should not make any difference).
5960 * Feeding the same new and old to diff_change()
5961 * also has the same effect.
5962 * Before the final output happens, they are pruned after
5963 * merged into rename/copy pairs as appropriate.
5965 if (options->flags.reverse_diff)
5966 addremove = (addremove == '+' ? '-' :
5967 addremove == '-' ? '+' : addremove);
5969 if (options->prefix &&
5970 strncmp(concatpath, options->prefix, options->prefix_length))
5973 one = alloc_filespec(concatpath);
5974 two = alloc_filespec(concatpath);
5976 if (addremove != '+')
5977 fill_filespec(one, oid, oid_valid, mode);
5978 if (addremove != '-') {
5979 fill_filespec(two, oid, oid_valid, mode);
5980 two->dirty_submodule = dirty_submodule;
5983 diff_queue(&diff_queued_diff, one, two);
5984 if (!options->flags.diff_from_contents)
5985 options->flags.has_changes = 1;
5988 void diff_change(struct diff_options *options,
5989 unsigned old_mode, unsigned new_mode,
5990 const struct object_id *old_oid,
5991 const struct object_id *new_oid,
5992 int old_oid_valid, int new_oid_valid,
5993 const char *concatpath,
5994 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5996 struct diff_filespec *one, *two;
5997 struct diff_filepair *p;
5999 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6000 is_submodule_ignored(concatpath, options))
6003 if (options->flags.reverse_diff) {
6004 SWAP(old_mode, new_mode);
6005 SWAP(old_oid, new_oid);
6006 SWAP(old_oid_valid, new_oid_valid);
6007 SWAP(old_dirty_submodule, new_dirty_submodule);
6010 if (options->prefix &&
6011 strncmp(concatpath, options->prefix, options->prefix_length))
6014 one = alloc_filespec(concatpath);
6015 two = alloc_filespec(concatpath);
6016 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6017 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6018 one->dirty_submodule = old_dirty_submodule;
6019 two->dirty_submodule = new_dirty_submodule;
6020 p = diff_queue(&diff_queued_diff, one, two);
6022 if (options->flags.diff_from_contents)
6025 if (options->flags.quick && options->skip_stat_unmatch &&
6026 !diff_filespec_check_stat_unmatch(p))
6029 options->flags.has_changes = 1;
6032 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6034 struct diff_filepair *pair;
6035 struct diff_filespec *one, *two;
6037 if (options->prefix &&
6038 strncmp(path, options->prefix, options->prefix_length))
6041 one = alloc_filespec(path);
6042 two = alloc_filespec(path);
6043 pair = diff_queue(&diff_queued_diff, one, two);
6044 pair->is_unmerged = 1;
6048 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
6051 struct diff_tempfile *temp;
6052 const char *argv[3];
6053 const char **arg = argv;
6054 struct child_process child = CHILD_PROCESS_INIT;
6055 struct strbuf buf = STRBUF_INIT;
6058 temp = prepare_temp_file(spec->path, spec);
6060 *arg++ = temp->name;
6063 child.use_shell = 1;
6066 if (start_command(&child)) {
6071 if (strbuf_read(&buf, child.out, 0) < 0)
6072 err = error("error reading from textconv command '%s'", pgm);
6075 if (finish_command(&child) || err) {
6076 strbuf_release(&buf);
6082 return strbuf_detach(&buf, outsize);
6085 size_t fill_textconv(struct userdiff_driver *driver,
6086 struct diff_filespec *df,
6092 if (!DIFF_FILE_VALID(df)) {
6096 if (diff_populate_filespec(df, 0))
6097 die("unable to read files to diff");
6102 if (!driver->textconv)
6103 die("BUG: fill_textconv called with non-textconv driver");
6105 if (driver->textconv_cache && df->oid_valid) {
6106 *outbuf = notes_cache_get(driver->textconv_cache,
6113 *outbuf = run_textconv(driver->textconv, df, &size);
6115 die("unable to read files to diff");
6117 if (driver->textconv_cache && df->oid_valid) {
6118 /* ignore errors, as we might be in a readonly repository */
6119 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6122 * we could save up changes and flush them all at the end,
6123 * but we would need an extra call after all diffing is done.
6124 * Since generating a cache entry is the slow path anyway,
6125 * this extra overhead probably isn't a big deal.
6127 notes_cache_write(driver->textconv_cache);
6133 int textconv_object(const char *path,
6135 const struct object_id *oid,
6138 unsigned long *buf_size)
6140 struct diff_filespec *df;
6141 struct userdiff_driver *textconv;
6143 df = alloc_filespec(path);
6144 fill_filespec(df, oid, oid_valid, mode);
6145 textconv = get_textconv(df);
6151 *buf_size = fill_textconv(textconv, df, buf);
6156 void setup_diff_pager(struct diff_options *opt)
6159 * If the user asked for our exit code, then either they want --quiet
6160 * or --exit-code. We should definitely not bother with a pager in the
6161 * former case, as we will generate no output. Since we still properly
6162 * report our exit code even when a pager is run, we _could_ run a
6163 * pager with --exit-code. But since we have not done so historically,
6164 * and because it is easy to find people oneline advising "git diff
6165 * --exit-code" in hooks and other scripts, we do not do so.
6167 if (!opt->flags.exit_with_status &&
6168 check_pager_config("diff") != 0)