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, "zebra"))
275 return COLOR_MOVED_ZEBRA;
276 else if (!strcmp(arg, "default"))
277 return COLOR_MOVED_DEFAULT;
278 else if (!strcmp(arg, "dimmed-zebra"))
279 return COLOR_MOVED_ZEBRA_DIM;
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', 'zebra', 'dimmed-zebra', 'plain'"));
286 int git_diff_ui_config(const char *var, const char *value, void *cb)
288 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
289 diff_use_color_default = git_config_colorbool(var, value);
292 if (!strcmp(var, "diff.colormoved")) {
293 int cm = parse_color_moved(value);
296 diff_color_moved_default = cm;
299 if (!strcmp(var, "diff.context")) {
300 diff_context_default = git_config_int(var, value);
301 if (diff_context_default < 0)
305 if (!strcmp(var, "diff.interhunkcontext")) {
306 diff_interhunk_context_default = git_config_int(var, value);
307 if (diff_interhunk_context_default < 0)
311 if (!strcmp(var, "diff.renames")) {
312 diff_detect_rename_default = git_config_rename(var, value);
315 if (!strcmp(var, "diff.autorefreshindex")) {
316 diff_auto_refresh_index = git_config_bool(var, value);
319 if (!strcmp(var, "diff.mnemonicprefix")) {
320 diff_mnemonic_prefix = git_config_bool(var, value);
323 if (!strcmp(var, "diff.noprefix")) {
324 diff_no_prefix = git_config_bool(var, value);
327 if (!strcmp(var, "diff.statgraphwidth")) {
328 diff_stat_graph_width = git_config_int(var, value);
331 if (!strcmp(var, "diff.external"))
332 return git_config_string(&external_diff_cmd_cfg, var, value);
333 if (!strcmp(var, "diff.wordregex"))
334 return git_config_string(&diff_word_regex_cfg, var, value);
335 if (!strcmp(var, "diff.orderfile"))
336 return git_config_pathname(&diff_order_file_cfg, var, value);
338 if (!strcmp(var, "diff.ignoresubmodules"))
339 handle_ignore_submodules_arg(&default_diff_options, value);
341 if (!strcmp(var, "diff.submodule")) {
342 if (parse_submodule_params(&default_diff_options, value))
343 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
348 if (!strcmp(var, "diff.algorithm")) {
349 diff_algorithm = parse_algorithm_value(value);
350 if (diff_algorithm < 0)
355 if (!strcmp(var, "diff.wserrorhighlight")) {
356 int val = parse_ws_error_highlight(value);
359 ws_error_highlight_default = val;
363 if (git_color_config(var, value, cb) < 0)
366 return git_diff_basic_config(var, value, cb);
369 int git_diff_basic_config(const char *var, const char *value, void *cb)
373 if (!strcmp(var, "diff.renamelimit")) {
374 diff_rename_limit_default = git_config_int(var, value);
378 if (userdiff_config(var, value) < 0)
381 if (skip_prefix(var, "diff.color.", &name) ||
382 skip_prefix(var, "color.diff.", &name)) {
383 int slot = parse_diff_color_slot(name);
387 return config_error_nonbool(var);
388 return color_parse(value, diff_colors[slot]);
391 /* like GNU diff's --suppress-blank-empty option */
392 if (!strcmp(var, "diff.suppressblankempty") ||
393 /* for backwards compatibility */
394 !strcmp(var, "diff.suppress-blank-empty")) {
395 diff_suppress_blank_empty = git_config_bool(var, value);
399 if (!strcmp(var, "diff.dirstat")) {
400 struct strbuf errmsg = STRBUF_INIT;
401 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
402 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
403 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
405 strbuf_release(&errmsg);
406 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
410 if (git_diff_heuristic_config(var, value, cb) < 0)
413 return git_default_config(var, value, cb);
416 static char *quote_two(const char *one, const char *two)
418 int need_one = quote_c_style(one, NULL, NULL, 1);
419 int need_two = quote_c_style(two, NULL, NULL, 1);
420 struct strbuf res = STRBUF_INIT;
422 if (need_one + need_two) {
423 strbuf_addch(&res, '"');
424 quote_c_style(one, &res, NULL, 1);
425 quote_c_style(two, &res, NULL, 1);
426 strbuf_addch(&res, '"');
428 strbuf_addstr(&res, one);
429 strbuf_addstr(&res, two);
431 return strbuf_detach(&res, NULL);
434 static const char *external_diff(void)
436 static const char *external_diff_cmd = NULL;
437 static int done_preparing = 0;
440 return external_diff_cmd;
441 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
442 if (!external_diff_cmd)
443 external_diff_cmd = external_diff_cmd_cfg;
445 return external_diff_cmd;
449 * Keep track of files used for diffing. Sometimes such an entry
450 * refers to a temporary file, sometimes to an existing file, and
451 * sometimes to "/dev/null".
453 static struct diff_tempfile {
455 * filename external diff should read from, or NULL if this
456 * entry is currently not in use:
460 char hex[GIT_MAX_HEXSZ + 1];
464 * If this diff_tempfile instance refers to a temporary file,
465 * this tempfile object is used to manage its lifetime.
467 struct tempfile *tempfile;
470 struct emit_callback {
473 int blank_at_eof_in_preimage;
474 int blank_at_eof_in_postimage;
476 int lno_in_postimage;
477 const char **label_path;
478 struct diff_words_data *diff_words;
479 struct diff_options *opt;
480 struct strbuf *header;
483 static int count_lines(const char *data, int size)
485 int count, ch, completely_empty = 1, nl_just_seen = 0;
492 completely_empty = 0;
496 completely_empty = 0;
499 if (completely_empty)
502 count++; /* no trailing newline */
506 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
508 if (!DIFF_FILE_VALID(one)) {
509 mf->ptr = (char *)""; /* does not matter */
513 else if (diff_populate_filespec(one, 0))
517 mf->size = one->size;
521 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
522 static unsigned long diff_filespec_size(struct diff_filespec *one)
524 if (!DIFF_FILE_VALID(one))
526 diff_populate_filespec(one, CHECK_SIZE_ONLY);
530 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
533 long size = mf->size;
538 ptr += size - 1; /* pointing at the very end */
540 ; /* incomplete line */
542 ptr--; /* skip the last LF */
543 while (mf->ptr < ptr) {
545 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
546 if (*prev_eol == '\n')
548 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
556 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
557 struct emit_callback *ecbdata)
560 unsigned ws_rule = ecbdata->ws_rule;
561 l1 = count_trailing_blank(mf1, ws_rule);
562 l2 = count_trailing_blank(mf2, ws_rule);
564 ecbdata->blank_at_eof_in_preimage = 0;
565 ecbdata->blank_at_eof_in_postimage = 0;
568 at = count_lines(mf1->ptr, mf1->size);
569 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
571 at = count_lines(mf2->ptr, mf2->size);
572 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
575 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
576 int first, const char *line, int len)
578 int has_trailing_newline, has_trailing_carriage_return;
580 FILE *file = o->file;
582 fputs(diff_line_prefix(o), file);
585 has_trailing_newline = (first == '\n');
586 has_trailing_carriage_return = (!has_trailing_newline &&
588 nofirst = has_trailing_newline || has_trailing_carriage_return;
590 has_trailing_newline = (len > 0 && line[len-1] == '\n');
591 if (has_trailing_newline)
593 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
594 if (has_trailing_carriage_return)
599 if (len || !nofirst) {
603 fwrite(line, len, 1, file);
606 if (has_trailing_carriage_return)
608 if (has_trailing_newline)
612 static void emit_line(struct diff_options *o, const char *set, const char *reset,
613 const char *line, int len)
615 emit_line_0(o, set, reset, line[0], line+1, len-1);
619 DIFF_SYMBOL_BINARY_DIFF_HEADER,
620 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
621 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
622 DIFF_SYMBOL_BINARY_DIFF_BODY,
623 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
624 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
625 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
626 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
627 DIFF_SYMBOL_STATS_LINE,
628 DIFF_SYMBOL_WORD_DIFF,
629 DIFF_SYMBOL_STAT_SEP,
631 DIFF_SYMBOL_SUBMODULE_ADD,
632 DIFF_SYMBOL_SUBMODULE_DEL,
633 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
634 DIFF_SYMBOL_SUBMODULE_MODIFIED,
635 DIFF_SYMBOL_SUBMODULE_HEADER,
636 DIFF_SYMBOL_SUBMODULE_ERROR,
637 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
638 DIFF_SYMBOL_REWRITE_DIFF,
639 DIFF_SYMBOL_BINARY_FILES,
641 DIFF_SYMBOL_FILEPAIR_PLUS,
642 DIFF_SYMBOL_FILEPAIR_MINUS,
643 DIFF_SYMBOL_WORDS_PORCELAIN,
646 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
649 DIFF_SYMBOL_NO_LF_EOF,
650 DIFF_SYMBOL_CONTEXT_FRAGINFO,
651 DIFF_SYMBOL_CONTEXT_MARKER,
652 DIFF_SYMBOL_SEPARATOR
655 * Flags for content lines:
656 * 0..12 are whitespace rules
657 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
658 * 16 is marking if the line is blank at EOF
660 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
661 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
662 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
663 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
664 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
667 * This struct is used when we need to buffer the output of the diff output.
669 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
670 * into the pre/post image file. This pointer could be a union with the
671 * line pointer. By storing an offset into the file instead of the literal line,
672 * we can decrease the memory footprint for the buffered output. At first we
673 * may want to only have indirection for the content lines, but we could also
674 * enhance the state for emitting prefabricated lines, e.g. the similarity
675 * score line or hunk/file headers would only need to store a number or path
676 * and then the output can be constructed later on depending on state.
678 struct emitted_diff_symbol {
684 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
686 struct emitted_diff_symbols {
687 struct emitted_diff_symbol *buf;
690 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
692 static void append_emitted_diff_symbol(struct diff_options *o,
693 struct emitted_diff_symbol *e)
695 struct emitted_diff_symbol *f;
697 ALLOC_GROW(o->emitted_symbols->buf,
698 o->emitted_symbols->nr + 1,
699 o->emitted_symbols->alloc);
700 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
702 memcpy(f, e, sizeof(struct emitted_diff_symbol));
703 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
707 struct hashmap_entry ent;
708 const struct emitted_diff_symbol *es;
709 struct moved_entry *next_line;
712 static int moved_entry_cmp(const struct diff_options *diffopt,
713 const struct moved_entry *a,
714 const struct moved_entry *b,
717 return !xdiff_compare_lines(a->es->line, a->es->len,
718 b->es->line, b->es->len,
722 static struct moved_entry *prepare_entry(struct diff_options *o,
725 struct moved_entry *ret = xmalloc(sizeof(*ret));
726 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
728 ret->ent.hash = xdiff_hash_string(l->line, l->len, o->xdl_opts);
730 ret->next_line = NULL;
735 static void add_lines_to_move_detection(struct diff_options *o,
736 struct hashmap *add_lines,
737 struct hashmap *del_lines)
739 struct moved_entry *prev_line = NULL;
742 for (n = 0; n < o->emitted_symbols->nr; n++) {
744 struct moved_entry *key;
746 switch (o->emitted_symbols->buf[n].s) {
747 case DIFF_SYMBOL_PLUS:
750 case DIFF_SYMBOL_MINUS:
758 key = prepare_entry(o, n);
759 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
760 prev_line->next_line = key;
762 hashmap_add(hm, key);
767 static int shrink_potential_moved_blocks(struct moved_entry **pmb,
772 /* Shrink the set of potential block to the remaining running */
773 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
774 while (lp < pmb_nr && pmb[lp])
776 /* lp points at the first NULL now */
778 while (rp > -1 && !pmb[rp])
780 /* rp points at the last non-NULL */
782 if (lp < pmb_nr && rp > -1 && lp < rp) {
790 /* Remember the number of running sets */
795 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
797 * Otherwise, if the last block has fewer alphanumeric characters than
798 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
801 * The last block consists of the (n - block_length)'th line up to but not
802 * including the nth line.
804 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
805 * Think of a way to unify them.
807 static void adjust_last_block(struct diff_options *o, int n, int block_length)
809 int i, alnum_count = 0;
810 if (o->color_moved == COLOR_MOVED_PLAIN)
812 for (i = 1; i < block_length + 1; i++) {
813 const char *c = o->emitted_symbols->buf[n - i].line;
818 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
822 for (i = 1; i < block_length + 1; i++)
823 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
826 /* Find blocks of moved code, delegate actual coloring decision to helper */
827 static void mark_color_as_moved(struct diff_options *o,
828 struct hashmap *add_lines,
829 struct hashmap *del_lines)
831 struct moved_entry **pmb = NULL; /* potentially moved blocks */
832 int pmb_nr = 0, pmb_alloc = 0;
833 int n, flipped_block = 1, block_length = 0;
836 for (n = 0; n < o->emitted_symbols->nr; n++) {
837 struct hashmap *hm = NULL;
838 struct moved_entry *key;
839 struct moved_entry *match = NULL;
840 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
844 case DIFF_SYMBOL_PLUS:
846 key = prepare_entry(o, n);
847 match = hashmap_get(hm, key, o);
850 case DIFF_SYMBOL_MINUS:
852 key = prepare_entry(o, n);
853 match = hashmap_get(hm, key, o);
861 adjust_last_block(o, n, block_length);
867 l->flags |= DIFF_SYMBOL_MOVED_LINE;
869 if (o->color_moved == COLOR_MOVED_PLAIN)
872 /* Check any potential block runs, advance each or nullify */
873 for (i = 0; i < pmb_nr; i++) {
874 struct moved_entry *p = pmb[i];
875 struct moved_entry *pnext = (p && p->next_line) ?
877 if (pnext && !hm->cmpfn(o, pnext, match, NULL)) {
878 pmb[i] = p->next_line;
884 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
888 * The current line is the start of a new block.
889 * Setup the set of potential blocks.
891 for (; match; match = hashmap_get_next(hm, match)) {
892 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
893 pmb[pmb_nr++] = match;
896 flipped_block = (flipped_block + 1) % 2;
898 adjust_last_block(o, n, block_length);
905 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
907 adjust_last_block(o, n, block_length);
912 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
913 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
914 static void dim_moved_lines(struct diff_options *o)
917 for (n = 0; n < o->emitted_symbols->nr; n++) {
918 struct emitted_diff_symbol *prev = (n != 0) ?
919 &o->emitted_symbols->buf[n - 1] : NULL;
920 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
921 struct emitted_diff_symbol *next =
922 (n < o->emitted_symbols->nr - 1) ?
923 &o->emitted_symbols->buf[n + 1] : NULL;
925 /* Not a plus or minus line? */
926 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
929 /* Not a moved line? */
930 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
934 * If prev or next are not a plus or minus line,
935 * pretend they don't exist
937 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
938 prev->s != DIFF_SYMBOL_MINUS)
940 if (next && next->s != DIFF_SYMBOL_PLUS &&
941 next->s != DIFF_SYMBOL_MINUS)
944 /* Inside a block? */
946 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
947 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
949 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
950 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
951 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
955 /* Check if we are at an interesting bound: */
956 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
957 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
958 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
960 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
961 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
962 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
966 * The boundary to prev and next are not interesting,
967 * so this line is not interesting as a whole
969 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
973 static void emit_line_ws_markup(struct diff_options *o,
974 const char *set, const char *reset,
975 const char *line, int len, char sign,
976 unsigned ws_rule, int blank_at_eof)
978 const char *ws = NULL;
980 if (o->ws_error_highlight & ws_rule) {
981 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
987 emit_line_0(o, set, reset, sign, line, len);
988 else if (blank_at_eof)
989 /* Blank line at EOF - paint '+' as well */
990 emit_line_0(o, ws, reset, sign, line, len);
992 /* Emit just the prefix, then the rest. */
993 emit_line_0(o, set, reset, sign, "", 0);
994 ws_check_emit(line, len, ws_rule,
995 o->file, set, reset, ws);
999 static void emit_diff_symbol_from_struct(struct diff_options *o,
1000 struct emitted_diff_symbol *eds)
1002 static const char *nneof = " No newline at end of file\n";
1003 const char *context, *reset, *set, *meta, *fraginfo;
1004 struct strbuf sb = STRBUF_INIT;
1006 enum diff_symbol s = eds->s;
1007 const char *line = eds->line;
1009 unsigned flags = eds->flags;
1012 case DIFF_SYMBOL_NO_LF_EOF:
1013 context = diff_get_color_opt(o, DIFF_CONTEXT);
1014 reset = diff_get_color_opt(o, DIFF_RESET);
1015 putc('\n', o->file);
1016 emit_line_0(o, context, reset, '\\',
1017 nneof, strlen(nneof));
1019 case DIFF_SYMBOL_SUBMODULE_HEADER:
1020 case DIFF_SYMBOL_SUBMODULE_ERROR:
1021 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1022 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1023 case DIFF_SYMBOL_SUMMARY:
1024 case DIFF_SYMBOL_STATS_LINE:
1025 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1026 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1027 emit_line(o, "", "", line, len);
1029 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1030 case DIFF_SYMBOL_CONTEXT_MARKER:
1031 context = diff_get_color_opt(o, DIFF_CONTEXT);
1032 reset = diff_get_color_opt(o, DIFF_RESET);
1033 emit_line(o, context, reset, line, len);
1035 case DIFF_SYMBOL_SEPARATOR:
1036 fprintf(o->file, "%s%c",
1037 diff_line_prefix(o),
1038 o->line_termination);
1040 case DIFF_SYMBOL_CONTEXT:
1041 set = diff_get_color_opt(o, DIFF_CONTEXT);
1042 reset = diff_get_color_opt(o, DIFF_RESET);
1043 emit_line_ws_markup(o, set, reset, line, len, ' ',
1044 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1046 case DIFF_SYMBOL_PLUS:
1047 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1048 DIFF_SYMBOL_MOVED_LINE_ALT |
1049 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1050 case DIFF_SYMBOL_MOVED_LINE |
1051 DIFF_SYMBOL_MOVED_LINE_ALT |
1052 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1053 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1055 case DIFF_SYMBOL_MOVED_LINE |
1056 DIFF_SYMBOL_MOVED_LINE_ALT:
1057 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1059 case DIFF_SYMBOL_MOVED_LINE |
1060 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1061 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1063 case DIFF_SYMBOL_MOVED_LINE:
1064 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1067 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1069 reset = diff_get_color_opt(o, DIFF_RESET);
1070 emit_line_ws_markup(o, set, reset, line, len, '+',
1071 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1072 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1074 case DIFF_SYMBOL_MINUS:
1075 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1076 DIFF_SYMBOL_MOVED_LINE_ALT |
1077 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1078 case DIFF_SYMBOL_MOVED_LINE |
1079 DIFF_SYMBOL_MOVED_LINE_ALT |
1080 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1081 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1083 case DIFF_SYMBOL_MOVED_LINE |
1084 DIFF_SYMBOL_MOVED_LINE_ALT:
1085 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1087 case DIFF_SYMBOL_MOVED_LINE |
1088 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1089 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1091 case DIFF_SYMBOL_MOVED_LINE:
1092 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1095 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1097 reset = diff_get_color_opt(o, DIFF_RESET);
1098 emit_line_ws_markup(o, set, reset, line, len, '-',
1099 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1101 case DIFF_SYMBOL_WORDS_PORCELAIN:
1102 context = diff_get_color_opt(o, DIFF_CONTEXT);
1103 reset = diff_get_color_opt(o, DIFF_RESET);
1104 emit_line(o, context, reset, line, len);
1105 fputs("~\n", o->file);
1107 case DIFF_SYMBOL_WORDS:
1108 context = diff_get_color_opt(o, DIFF_CONTEXT);
1109 reset = diff_get_color_opt(o, DIFF_RESET);
1111 * Skip the prefix character, if any. With
1112 * diff_suppress_blank_empty, there may be
1115 if (line[0] != '\n') {
1119 emit_line(o, context, reset, line, len);
1121 case DIFF_SYMBOL_FILEPAIR_PLUS:
1122 meta = diff_get_color_opt(o, DIFF_METAINFO);
1123 reset = diff_get_color_opt(o, DIFF_RESET);
1124 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1126 strchr(line, ' ') ? "\t" : "");
1128 case DIFF_SYMBOL_FILEPAIR_MINUS:
1129 meta = diff_get_color_opt(o, DIFF_METAINFO);
1130 reset = diff_get_color_opt(o, DIFF_RESET);
1131 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1133 strchr(line, ' ') ? "\t" : "");
1135 case DIFF_SYMBOL_BINARY_FILES:
1136 case DIFF_SYMBOL_HEADER:
1137 fprintf(o->file, "%s", line);
1139 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1140 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1142 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1143 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1145 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1146 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1148 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1149 fputs(diff_line_prefix(o), o->file);
1150 fputc('\n', o->file);
1152 case DIFF_SYMBOL_REWRITE_DIFF:
1153 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1154 reset = diff_get_color_opt(o, DIFF_RESET);
1155 emit_line(o, fraginfo, reset, line, len);
1157 case DIFF_SYMBOL_SUBMODULE_ADD:
1158 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1159 reset = diff_get_color_opt(o, DIFF_RESET);
1160 emit_line(o, set, reset, line, len);
1162 case DIFF_SYMBOL_SUBMODULE_DEL:
1163 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1164 reset = diff_get_color_opt(o, DIFF_RESET);
1165 emit_line(o, set, reset, line, len);
1167 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1168 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1169 diff_line_prefix(o), line);
1171 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1172 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1173 diff_line_prefix(o), line);
1175 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1176 emit_line(o, "", "", " 0 files changed\n",
1177 strlen(" 0 files changed\n"));
1179 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1180 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1182 case DIFF_SYMBOL_WORD_DIFF:
1183 fprintf(o->file, "%.*s", len, line);
1185 case DIFF_SYMBOL_STAT_SEP:
1186 fputs(o->stat_sep, o->file);
1189 die("BUG: unknown diff symbol");
1191 strbuf_release(&sb);
1194 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1195 const char *line, int len, unsigned flags)
1197 struct emitted_diff_symbol e = {line, len, flags, s};
1199 if (o->emitted_symbols)
1200 append_emitted_diff_symbol(o, &e);
1202 emit_diff_symbol_from_struct(o, &e);
1205 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1207 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1210 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1212 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1215 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1217 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1218 path, strlen(path), 0);
1221 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1223 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1224 path, strlen(path), 0);
1227 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1229 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1230 header, strlen(header), 0);
1233 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1235 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1238 void diff_emit_submodule_pipethrough(struct diff_options *o,
1239 const char *line, int len)
1241 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1244 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1246 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1247 ecbdata->blank_at_eof_in_preimage &&
1248 ecbdata->blank_at_eof_in_postimage &&
1249 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1250 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1252 return ws_blank_line(line, len, ecbdata->ws_rule);
1255 static void emit_add_line(const char *reset,
1256 struct emit_callback *ecbdata,
1257 const char *line, int len)
1259 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1260 if (new_blank_line_at_eof(ecbdata, line, len))
1261 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1263 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1266 static void emit_del_line(const char *reset,
1267 struct emit_callback *ecbdata,
1268 const char *line, int len)
1270 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1271 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1274 static void emit_context_line(const char *reset,
1275 struct emit_callback *ecbdata,
1276 const char *line, int len)
1278 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1279 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1282 static void emit_hunk_header(struct emit_callback *ecbdata,
1283 const char *line, int len)
1285 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1286 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1287 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1288 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1289 static const char atat[2] = { '@', '@' };
1290 const char *cp, *ep;
1291 struct strbuf msgbuf = STRBUF_INIT;
1296 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1297 * it always is at least 10 bytes long.
1300 memcmp(line, atat, 2) ||
1301 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1302 emit_diff_symbol(ecbdata->opt,
1303 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1306 ep += 2; /* skip over @@ */
1308 /* The hunk header in fraginfo color */
1309 strbuf_addstr(&msgbuf, frag);
1310 strbuf_add(&msgbuf, line, ep - line);
1311 strbuf_addstr(&msgbuf, reset);
1317 if (line[len - i] == '\r' || line[len - i] == '\n')
1320 /* blank before the func header */
1321 for (cp = ep; ep - line < len; ep++)
1322 if (*ep != ' ' && *ep != '\t')
1325 strbuf_addstr(&msgbuf, context);
1326 strbuf_add(&msgbuf, cp, ep - cp);
1327 strbuf_addstr(&msgbuf, reset);
1330 if (ep < line + len) {
1331 strbuf_addstr(&msgbuf, func);
1332 strbuf_add(&msgbuf, ep, line + len - ep);
1333 strbuf_addstr(&msgbuf, reset);
1336 strbuf_add(&msgbuf, line + len, org_len - len);
1337 strbuf_complete_line(&msgbuf);
1338 emit_diff_symbol(ecbdata->opt,
1339 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1340 strbuf_release(&msgbuf);
1343 static struct diff_tempfile *claim_diff_tempfile(void) {
1345 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1346 if (!diff_temp[i].name)
1347 return diff_temp + i;
1348 die("BUG: diff is failing to clean up its tempfiles");
1351 static void remove_tempfile(void)
1354 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1355 if (is_tempfile_active(diff_temp[i].tempfile))
1356 delete_tempfile(&diff_temp[i].tempfile);
1357 diff_temp[i].name = NULL;
1361 static void add_line_count(struct strbuf *out, int count)
1365 strbuf_addstr(out, "0,0");
1368 strbuf_addstr(out, "1");
1371 strbuf_addf(out, "1,%d", count);
1376 static void emit_rewrite_lines(struct emit_callback *ecb,
1377 int prefix, const char *data, int size)
1379 const char *endp = NULL;
1380 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1385 endp = memchr(data, '\n', size);
1386 len = endp ? (endp - data + 1) : size;
1387 if (prefix != '+') {
1388 ecb->lno_in_preimage++;
1389 emit_del_line(reset, ecb, data, len);
1391 ecb->lno_in_postimage++;
1392 emit_add_line(reset, ecb, data, len);
1398 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1401 static void emit_rewrite_diff(const char *name_a,
1403 struct diff_filespec *one,
1404 struct diff_filespec *two,
1405 struct userdiff_driver *textconv_one,
1406 struct userdiff_driver *textconv_two,
1407 struct diff_options *o)
1410 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1411 const char *a_prefix, *b_prefix;
1412 char *data_one, *data_two;
1413 size_t size_one, size_two;
1414 struct emit_callback ecbdata;
1415 struct strbuf out = STRBUF_INIT;
1417 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1418 a_prefix = o->b_prefix;
1419 b_prefix = o->a_prefix;
1421 a_prefix = o->a_prefix;
1422 b_prefix = o->b_prefix;
1425 name_a += (*name_a == '/');
1426 name_b += (*name_b == '/');
1428 strbuf_reset(&a_name);
1429 strbuf_reset(&b_name);
1430 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1431 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1433 size_one = fill_textconv(textconv_one, one, &data_one);
1434 size_two = fill_textconv(textconv_two, two, &data_two);
1436 memset(&ecbdata, 0, sizeof(ecbdata));
1437 ecbdata.color_diff = want_color(o->use_color);
1438 ecbdata.ws_rule = whitespace_rule(name_b);
1440 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1442 mf1.ptr = (char *)data_one;
1443 mf2.ptr = (char *)data_two;
1444 mf1.size = size_one;
1445 mf2.size = size_two;
1446 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1448 ecbdata.lno_in_preimage = 1;
1449 ecbdata.lno_in_postimage = 1;
1451 lc_a = count_lines(data_one, size_one);
1452 lc_b = count_lines(data_two, size_two);
1454 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1455 a_name.buf, a_name.len, 0);
1456 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1457 b_name.buf, b_name.len, 0);
1459 strbuf_addstr(&out, "@@ -");
1460 if (!o->irreversible_delete)
1461 add_line_count(&out, lc_a);
1463 strbuf_addstr(&out, "?,?");
1464 strbuf_addstr(&out, " +");
1465 add_line_count(&out, lc_b);
1466 strbuf_addstr(&out, " @@\n");
1467 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1468 strbuf_release(&out);
1470 if (lc_a && !o->irreversible_delete)
1471 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1473 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1475 free((char *)data_one);
1477 free((char *)data_two);
1480 struct diff_words_buffer {
1482 unsigned long alloc;
1483 struct diff_words_orig {
1484 const char *begin, *end;
1486 int orig_nr, orig_alloc;
1489 static void diff_words_append(char *line, unsigned long len,
1490 struct diff_words_buffer *buffer)
1492 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1495 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1496 buffer->text.size += len;
1497 buffer->text.ptr[buffer->text.size] = '\0';
1500 struct diff_words_style_elem {
1503 const char *color; /* NULL; filled in by the setup code if
1504 * color is enabled */
1507 struct diff_words_style {
1508 enum diff_words_type type;
1509 struct diff_words_style_elem new, old, ctx;
1510 const char *newline;
1513 static struct diff_words_style diff_words_styles[] = {
1514 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1515 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1516 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1519 struct diff_words_data {
1520 struct diff_words_buffer minus, plus;
1521 const char *current_plus;
1523 struct diff_options *opt;
1524 regex_t *word_regex;
1525 enum diff_words_type type;
1526 struct diff_words_style *style;
1529 static int fn_out_diff_words_write_helper(struct diff_options *o,
1530 struct diff_words_style_elem *st_el,
1531 const char *newline,
1532 size_t count, const char *buf)
1535 struct strbuf sb = STRBUF_INIT;
1538 char *p = memchr(buf, '\n', count);
1540 strbuf_addstr(&sb, diff_line_prefix(o));
1543 const char *reset = st_el->color && *st_el->color ?
1544 GIT_COLOR_RESET : NULL;
1545 if (st_el->color && *st_el->color)
1546 strbuf_addstr(&sb, st_el->color);
1547 strbuf_addstr(&sb, st_el->prefix);
1548 strbuf_add(&sb, buf, p ? p - buf : count);
1549 strbuf_addstr(&sb, st_el->suffix);
1551 strbuf_addstr(&sb, reset);
1556 strbuf_addstr(&sb, newline);
1557 count -= p + 1 - buf;
1561 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1569 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1571 strbuf_release(&sb);
1576 * '--color-words' algorithm can be described as:
1578 * 1. collect the minus/plus lines of a diff hunk, divided into
1579 * minus-lines and plus-lines;
1581 * 2. break both minus-lines and plus-lines into words and
1582 * place them into two mmfile_t with one word for each line;
1584 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1586 * And for the common parts of the both file, we output the plus side text.
1587 * diff_words->current_plus is used to trace the current position of the plus file
1588 * which printed. diff_words->last_minus is used to trace the last minus word
1591 * For '--graph' to work with '--color-words', we need to output the graph prefix
1592 * on each line of color words output. Generally, there are two conditions on
1593 * which we should output the prefix.
1595 * 1. diff_words->last_minus == 0 &&
1596 * diff_words->current_plus == diff_words->plus.text.ptr
1598 * that is: the plus text must start as a new line, and if there is no minus
1599 * word printed, a graph prefix must be printed.
1601 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1602 * *(diff_words->current_plus - 1) == '\n'
1604 * that is: a graph prefix must be printed following a '\n'
1606 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1608 if ((diff_words->last_minus == 0 &&
1609 diff_words->current_plus == diff_words->plus.text.ptr) ||
1610 (diff_words->current_plus > diff_words->plus.text.ptr &&
1611 *(diff_words->current_plus - 1) == '\n')) {
1618 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
1620 struct diff_words_data *diff_words = priv;
1621 struct diff_words_style *style = diff_words->style;
1622 int minus_first, minus_len, plus_first, plus_len;
1623 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1624 struct diff_options *opt = diff_words->opt;
1625 const char *line_prefix;
1627 if (line[0] != '@' || parse_hunk_header(line, len,
1628 &minus_first, &minus_len, &plus_first, &plus_len))
1632 line_prefix = diff_line_prefix(opt);
1634 /* POSIX requires that first be decremented by one if len == 0... */
1636 minus_begin = diff_words->minus.orig[minus_first].begin;
1638 diff_words->minus.orig[minus_first + minus_len - 1].end;
1640 minus_begin = minus_end =
1641 diff_words->minus.orig[minus_first].end;
1644 plus_begin = diff_words->plus.orig[plus_first].begin;
1645 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1647 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1649 if (color_words_output_graph_prefix(diff_words)) {
1650 fputs(line_prefix, diff_words->opt->file);
1652 if (diff_words->current_plus != plus_begin) {
1653 fn_out_diff_words_write_helper(diff_words->opt,
1654 &style->ctx, style->newline,
1655 plus_begin - diff_words->current_plus,
1656 diff_words->current_plus);
1658 if (minus_begin != minus_end) {
1659 fn_out_diff_words_write_helper(diff_words->opt,
1660 &style->old, style->newline,
1661 minus_end - minus_begin, minus_begin);
1663 if (plus_begin != plus_end) {
1664 fn_out_diff_words_write_helper(diff_words->opt,
1665 &style->new, style->newline,
1666 plus_end - plus_begin, plus_begin);
1669 diff_words->current_plus = plus_end;
1670 diff_words->last_minus = minus_first;
1673 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1674 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1675 int *begin, int *end)
1677 if (word_regex && *begin < buffer->size) {
1678 regmatch_t match[1];
1679 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1680 buffer->size - *begin, 1, match, 0)) {
1681 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1682 '\n', match[0].rm_eo - match[0].rm_so);
1683 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1684 *begin += match[0].rm_so;
1685 return *begin >= *end;
1690 /* find the next word */
1691 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1693 if (*begin >= buffer->size)
1696 /* find the end of the word */
1698 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1705 * This function splits the words in buffer->text, stores the list with
1706 * newline separator into out, and saves the offsets of the original words
1709 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1710 regex_t *word_regex)
1718 /* fake an empty "0th" word */
1719 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1720 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1721 buffer->orig_nr = 1;
1723 for (i = 0; i < buffer->text.size; i++) {
1724 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1727 /* store original boundaries */
1728 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1729 buffer->orig_alloc);
1730 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1731 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1734 /* store one word */
1735 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1736 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1737 out->ptr[out->size + j - i] = '\n';
1738 out->size += j - i + 1;
1744 /* this executes the word diff on the accumulated buffers */
1745 static void diff_words_show(struct diff_words_data *diff_words)
1749 mmfile_t minus, plus;
1750 struct diff_words_style *style = diff_words->style;
1752 struct diff_options *opt = diff_words->opt;
1753 const char *line_prefix;
1756 line_prefix = diff_line_prefix(opt);
1758 /* special case: only removal */
1759 if (!diff_words->plus.text.size) {
1760 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1761 line_prefix, strlen(line_prefix), 0);
1762 fn_out_diff_words_write_helper(diff_words->opt,
1763 &style->old, style->newline,
1764 diff_words->minus.text.size,
1765 diff_words->minus.text.ptr);
1766 diff_words->minus.text.size = 0;
1770 diff_words->current_plus = diff_words->plus.text.ptr;
1771 diff_words->last_minus = 0;
1773 memset(&xpp, 0, sizeof(xpp));
1774 memset(&xecfg, 0, sizeof(xecfg));
1775 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1776 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1778 /* as only the hunk header will be parsed, we need a 0-context */
1780 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1782 die("unable to generate word diff");
1785 if (diff_words->current_plus != diff_words->plus.text.ptr +
1786 diff_words->plus.text.size) {
1787 if (color_words_output_graph_prefix(diff_words))
1788 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1789 line_prefix, strlen(line_prefix), 0);
1790 fn_out_diff_words_write_helper(diff_words->opt,
1791 &style->ctx, style->newline,
1792 diff_words->plus.text.ptr + diff_words->plus.text.size
1793 - diff_words->current_plus, diff_words->current_plus);
1795 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1798 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1799 static void diff_words_flush(struct emit_callback *ecbdata)
1801 struct diff_options *wo = ecbdata->diff_words->opt;
1803 if (ecbdata->diff_words->minus.text.size ||
1804 ecbdata->diff_words->plus.text.size)
1805 diff_words_show(ecbdata->diff_words);
1807 if (wo->emitted_symbols) {
1808 struct diff_options *o = ecbdata->opt;
1809 struct emitted_diff_symbols *wol = wo->emitted_symbols;
1814 * Instead of appending each, concat all words to a line?
1816 for (i = 0; i < wol->nr; i++)
1817 append_emitted_diff_symbol(o, &wol->buf[i]);
1819 for (i = 0; i < wol->nr; i++)
1820 free((void *)wol->buf[i].line);
1826 static void diff_filespec_load_driver(struct diff_filespec *one)
1828 /* Use already-loaded driver */
1832 if (S_ISREG(one->mode))
1833 one->driver = userdiff_find_by_path(one->path);
1835 /* Fallback to default settings */
1837 one->driver = userdiff_find_by_name("default");
1840 static const char *userdiff_word_regex(struct diff_filespec *one)
1842 diff_filespec_load_driver(one);
1843 return one->driver->word_regex;
1846 static void init_diff_words_data(struct emit_callback *ecbdata,
1847 struct diff_options *orig_opts,
1848 struct diff_filespec *one,
1849 struct diff_filespec *two)
1852 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1853 memcpy(o, orig_opts, sizeof(struct diff_options));
1855 ecbdata->diff_words =
1856 xcalloc(1, sizeof(struct diff_words_data));
1857 ecbdata->diff_words->type = o->word_diff;
1858 ecbdata->diff_words->opt = o;
1860 if (orig_opts->emitted_symbols)
1861 o->emitted_symbols =
1862 xcalloc(1, sizeof(struct emitted_diff_symbols));
1865 o->word_regex = userdiff_word_regex(one);
1867 o->word_regex = userdiff_word_regex(two);
1869 o->word_regex = diff_word_regex_cfg;
1870 if (o->word_regex) {
1871 ecbdata->diff_words->word_regex = (regex_t *)
1872 xmalloc(sizeof(regex_t));
1873 if (regcomp(ecbdata->diff_words->word_regex,
1875 REG_EXTENDED | REG_NEWLINE))
1876 die ("Invalid regular expression: %s",
1879 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1880 if (o->word_diff == diff_words_styles[i].type) {
1881 ecbdata->diff_words->style =
1882 &diff_words_styles[i];
1886 if (want_color(o->use_color)) {
1887 struct diff_words_style *st = ecbdata->diff_words->style;
1888 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1889 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1890 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1894 static void free_diff_words_data(struct emit_callback *ecbdata)
1896 if (ecbdata->diff_words) {
1897 diff_words_flush(ecbdata);
1898 free (ecbdata->diff_words->opt->emitted_symbols);
1899 free (ecbdata->diff_words->opt);
1900 free (ecbdata->diff_words->minus.text.ptr);
1901 free (ecbdata->diff_words->minus.orig);
1902 free (ecbdata->diff_words->plus.text.ptr);
1903 free (ecbdata->diff_words->plus.orig);
1904 if (ecbdata->diff_words->word_regex) {
1905 regfree(ecbdata->diff_words->word_regex);
1906 free(ecbdata->diff_words->word_regex);
1908 FREE_AND_NULL(ecbdata->diff_words);
1912 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1914 if (want_color(diff_use_color))
1915 return diff_colors[ix];
1919 const char *diff_line_prefix(struct diff_options *opt)
1921 struct strbuf *msgbuf;
1922 if (!opt->output_prefix)
1925 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1929 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1932 unsigned long allot;
1938 (void) utf8_width(&cp, &l);
1940 break; /* truncated in the middle? */
1945 static void find_lno(const char *line, struct emit_callback *ecbdata)
1948 ecbdata->lno_in_preimage = 0;
1949 ecbdata->lno_in_postimage = 0;
1950 p = strchr(line, '-');
1952 return; /* cannot happen */
1953 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1956 return; /* cannot happen */
1957 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1960 static void fn_out_consume(void *priv, char *line, unsigned long len)
1962 struct emit_callback *ecbdata = priv;
1963 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1964 struct diff_options *o = ecbdata->opt;
1966 o->found_changes = 1;
1968 if (ecbdata->header) {
1969 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
1970 ecbdata->header->buf, ecbdata->header->len, 0);
1971 strbuf_reset(ecbdata->header);
1972 ecbdata->header = NULL;
1975 if (ecbdata->label_path[0]) {
1976 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1977 ecbdata->label_path[0],
1978 strlen(ecbdata->label_path[0]), 0);
1979 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1980 ecbdata->label_path[1],
1981 strlen(ecbdata->label_path[1]), 0);
1982 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1985 if (diff_suppress_blank_empty
1986 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1991 if (line[0] == '@') {
1992 if (ecbdata->diff_words)
1993 diff_words_flush(ecbdata);
1994 len = sane_truncate_line(ecbdata, line, len);
1995 find_lno(line, ecbdata);
1996 emit_hunk_header(ecbdata, line, len);
2000 if (ecbdata->diff_words) {
2001 enum diff_symbol s =
2002 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2003 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2004 if (line[0] == '-') {
2005 diff_words_append(line, len,
2006 &ecbdata->diff_words->minus);
2008 } else if (line[0] == '+') {
2009 diff_words_append(line, len,
2010 &ecbdata->diff_words->plus);
2012 } else if (starts_with(line, "\\ ")) {
2014 * Eat the "no newline at eof" marker as if we
2015 * saw a "+" or "-" line with nothing on it,
2016 * and return without diff_words_flush() to
2017 * defer processing. If this is the end of
2018 * preimage, more "+" lines may come after it.
2022 diff_words_flush(ecbdata);
2023 emit_diff_symbol(o, s, line, len, 0);
2029 ecbdata->lno_in_postimage++;
2030 emit_add_line(reset, ecbdata, line + 1, len - 1);
2033 ecbdata->lno_in_preimage++;
2034 emit_del_line(reset, ecbdata, line + 1, len - 1);
2037 ecbdata->lno_in_postimage++;
2038 ecbdata->lno_in_preimage++;
2039 emit_context_line(reset, ecbdata, line + 1, len - 1);
2042 /* incomplete line at the end */
2043 ecbdata->lno_in_preimage++;
2044 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2050 static char *pprint_rename(const char *a, const char *b)
2052 const char *old = a;
2053 const char *new = b;
2054 struct strbuf name = STRBUF_INIT;
2055 int pfx_length, sfx_length;
2056 int pfx_adjust_for_slash;
2057 int len_a = strlen(a);
2058 int len_b = strlen(b);
2059 int a_midlen, b_midlen;
2060 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2061 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2063 if (qlen_a || qlen_b) {
2064 quote_c_style(a, &name, NULL, 0);
2065 strbuf_addstr(&name, " => ");
2066 quote_c_style(b, &name, NULL, 0);
2067 return strbuf_detach(&name, NULL);
2070 /* Find common prefix */
2072 while (*old && *new && *old == *new) {
2074 pfx_length = old - a + 1;
2079 /* Find common suffix */
2084 * If there is a common prefix, it must end in a slash. In
2085 * that case we let this loop run 1 into the prefix to see the
2088 * If there is no common prefix, we cannot do this as it would
2089 * underrun the input strings.
2091 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2092 while (a + pfx_length - pfx_adjust_for_slash <= old &&
2093 b + pfx_length - pfx_adjust_for_slash <= new &&
2096 sfx_length = len_a - (old - a);
2102 * pfx{mid-a => mid-b}sfx
2103 * {pfx-a => pfx-b}sfx
2104 * pfx{sfx-a => sfx-b}
2107 a_midlen = len_a - pfx_length - sfx_length;
2108 b_midlen = len_b - pfx_length - sfx_length;
2114 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2115 if (pfx_length + sfx_length) {
2116 strbuf_add(&name, a, pfx_length);
2117 strbuf_addch(&name, '{');
2119 strbuf_add(&name, a + pfx_length, a_midlen);
2120 strbuf_addstr(&name, " => ");
2121 strbuf_add(&name, b + pfx_length, b_midlen);
2122 if (pfx_length + sfx_length) {
2123 strbuf_addch(&name, '}');
2124 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
2126 return strbuf_detach(&name, NULL);
2132 struct diffstat_file {
2136 unsigned is_unmerged:1;
2137 unsigned is_binary:1;
2138 unsigned is_renamed:1;
2139 unsigned is_interesting:1;
2140 uintmax_t added, deleted;
2144 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2148 struct diffstat_file *x;
2149 x = xcalloc(1, sizeof(*x));
2150 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2151 diffstat->files[diffstat->nr++] = x;
2153 x->from_name = xstrdup(name_a);
2154 x->name = xstrdup(name_b);
2158 x->from_name = NULL;
2159 x->name = xstrdup(name_a);
2164 static void diffstat_consume(void *priv, char *line, unsigned long len)
2166 struct diffstat_t *diffstat = priv;
2167 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2171 else if (line[0] == '-')
2175 const char mime_boundary_leader[] = "------------";
2177 static int scale_linear(int it, int width, int max_change)
2182 * make sure that at least one '-' or '+' is printed if
2183 * there is any change to this path. The easiest way is to
2184 * scale linearly as if the alloted width is one column shorter
2185 * than it is, and then add 1 to the result.
2187 return 1 + (it * (width - 1) / max_change);
2190 static void show_graph(struct strbuf *out, char ch, int cnt,
2191 const char *set, const char *reset)
2195 strbuf_addstr(out, set);
2196 strbuf_addchars(out, ch, cnt);
2197 strbuf_addstr(out, reset);
2200 static void fill_print_name(struct diffstat_file *file)
2204 if (file->print_name)
2207 if (!file->is_renamed) {
2208 struct strbuf buf = STRBUF_INIT;
2209 if (quote_c_style(file->name, &buf, NULL, 0)) {
2210 pname = strbuf_detach(&buf, NULL);
2213 strbuf_release(&buf);
2216 pname = pprint_rename(file->from_name, file->name);
2218 file->print_name = pname;
2221 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2222 int files, int insertions, int deletions)
2224 struct strbuf sb = STRBUF_INIT;
2227 assert(insertions == 0 && deletions == 0);
2228 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2234 (files == 1) ? " %d file changed" : " %d files changed",
2238 * For binary diff, the caller may want to print "x files
2239 * changed" with insertions == 0 && deletions == 0.
2241 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2242 * is probably less confusing (i.e skip over "2 files changed
2243 * but nothing about added/removed lines? Is this a bug in Git?").
2245 if (insertions || deletions == 0) {
2247 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2251 if (deletions || insertions == 0) {
2253 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2256 strbuf_addch(&sb, '\n');
2257 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2259 strbuf_release(&sb);
2262 void print_stat_summary(FILE *fp, int files,
2263 int insertions, int deletions)
2265 struct diff_options o;
2266 memset(&o, 0, sizeof(o));
2269 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2272 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2274 int i, len, add, del, adds = 0, dels = 0;
2275 uintmax_t max_change = 0, max_len = 0;
2276 int total_files = data->nr, count;
2277 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2278 const char *reset, *add_c, *del_c;
2279 int extra_shown = 0;
2280 const char *line_prefix = diff_line_prefix(options);
2281 struct strbuf out = STRBUF_INIT;
2286 count = options->stat_count ? options->stat_count : data->nr;
2288 reset = diff_get_color_opt(options, DIFF_RESET);
2289 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2290 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2293 * Find the longest filename and max number of changes
2295 for (i = 0; (i < count) && (i < data->nr); i++) {
2296 struct diffstat_file *file = data->files[i];
2297 uintmax_t change = file->added + file->deleted;
2299 if (!file->is_interesting && (change == 0)) {
2300 count++; /* not shown == room for one more */
2303 fill_print_name(file);
2304 len = strlen(file->print_name);
2308 if (file->is_unmerged) {
2309 /* "Unmerged" is 8 characters */
2310 bin_width = bin_width < 8 ? 8 : bin_width;
2313 if (file->is_binary) {
2314 /* "Bin XXX -> YYY bytes" */
2315 int w = 14 + decimal_width(file->added)
2316 + decimal_width(file->deleted);
2317 bin_width = bin_width < w ? w : bin_width;
2318 /* Display change counts aligned with "Bin" */
2323 if (max_change < change)
2324 max_change = change;
2326 count = i; /* where we can stop scanning in data->files[] */
2329 * We have width = stat_width or term_columns() columns total.
2330 * We want a maximum of min(max_len, stat_name_width) for the name part.
2331 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2332 * We also need 1 for " " and 4 + decimal_width(max_change)
2333 * for " | NNNN " and one the empty column at the end, altogether
2334 * 6 + decimal_width(max_change).
2336 * If there's not enough space, we will use the smaller of
2337 * stat_name_width (if set) and 5/8*width for the filename,
2338 * and the rest for constant elements + graph part, but no more
2339 * than stat_graph_width for the graph part.
2340 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2341 * for the standard terminal size).
2343 * In other words: stat_width limits the maximum width, and
2344 * stat_name_width fixes the maximum width of the filename,
2345 * and is also used to divide available columns if there
2348 * Binary files are displayed with "Bin XXX -> YYY bytes"
2349 * instead of the change count and graph. This part is treated
2350 * similarly to the graph part, except that it is not
2351 * "scaled". If total width is too small to accommodate the
2352 * guaranteed minimum width of the filename part and the
2353 * separators and this message, this message will "overflow"
2354 * making the line longer than the maximum width.
2357 if (options->stat_width == -1)
2358 width = term_columns() - strlen(line_prefix);
2360 width = options->stat_width ? options->stat_width : 80;
2361 number_width = decimal_width(max_change) > number_width ?
2362 decimal_width(max_change) : number_width;
2364 if (options->stat_graph_width == -1)
2365 options->stat_graph_width = diff_stat_graph_width;
2368 * Guarantee 3/8*16==6 for the graph part
2369 * and 5/8*16==10 for the filename part
2371 if (width < 16 + 6 + number_width)
2372 width = 16 + 6 + number_width;
2375 * First assign sizes that are wanted, ignoring available width.
2376 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2377 * starting from "XXX" should fit in graph_width.
2379 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2380 if (options->stat_graph_width &&
2381 options->stat_graph_width < graph_width)
2382 graph_width = options->stat_graph_width;
2384 name_width = (options->stat_name_width > 0 &&
2385 options->stat_name_width < max_len) ?
2386 options->stat_name_width : max_len;
2389 * Adjust adjustable widths not to exceed maximum width
2391 if (name_width + number_width + 6 + graph_width > width) {
2392 if (graph_width > width * 3/8 - number_width - 6) {
2393 graph_width = width * 3/8 - number_width - 6;
2394 if (graph_width < 6)
2398 if (options->stat_graph_width &&
2399 graph_width > options->stat_graph_width)
2400 graph_width = options->stat_graph_width;
2401 if (name_width > width - number_width - 6 - graph_width)
2402 name_width = width - number_width - 6 - graph_width;
2404 graph_width = width - number_width - 6 - name_width;
2408 * From here name_width is the width of the name area,
2409 * and graph_width is the width of the graph area.
2410 * max_change is used to scale graph properly.
2412 for (i = 0; i < count; i++) {
2413 const char *prefix = "";
2414 struct diffstat_file *file = data->files[i];
2415 char *name = file->print_name;
2416 uintmax_t added = file->added;
2417 uintmax_t deleted = file->deleted;
2420 if (!file->is_interesting && (added + deleted == 0))
2424 * "scale" the filename
2427 name_len = strlen(name);
2428 if (name_width < name_len) {
2432 name += name_len - len;
2433 slash = strchr(name, '/');
2438 if (file->is_binary) {
2439 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2440 strbuf_addf(&out, " %*s", number_width, "Bin");
2441 if (!added && !deleted) {
2442 strbuf_addch(&out, '\n');
2443 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2444 out.buf, out.len, 0);
2448 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2449 del_c, deleted, reset);
2450 strbuf_addstr(&out, " -> ");
2451 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2452 add_c, added, reset);
2453 strbuf_addstr(&out, " bytes\n");
2454 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2455 out.buf, out.len, 0);
2459 else if (file->is_unmerged) {
2460 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2461 strbuf_addstr(&out, " Unmerged\n");
2462 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2463 out.buf, out.len, 0);
2469 * scale the add/delete
2474 if (graph_width <= max_change) {
2475 int total = scale_linear(add + del, graph_width, max_change);
2476 if (total < 2 && add && del)
2477 /* width >= 2 due to the sanity check */
2480 add = scale_linear(add, graph_width, max_change);
2483 del = scale_linear(del, graph_width, max_change);
2487 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2488 strbuf_addf(&out, " %*"PRIuMAX"%s",
2489 number_width, added + deleted,
2490 added + deleted ? " " : "");
2491 show_graph(&out, '+', add, add_c, reset);
2492 show_graph(&out, '-', del, del_c, reset);
2493 strbuf_addch(&out, '\n');
2494 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2495 out.buf, out.len, 0);
2499 for (i = 0; i < data->nr; i++) {
2500 struct diffstat_file *file = data->files[i];
2501 uintmax_t added = file->added;
2502 uintmax_t deleted = file->deleted;
2504 if (file->is_unmerged ||
2505 (!file->is_interesting && (added + deleted == 0))) {
2510 if (!file->is_binary) {
2517 emit_diff_symbol(options,
2518 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2523 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2524 strbuf_release(&out);
2527 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2529 int i, adds = 0, dels = 0, total_files = data->nr;
2534 for (i = 0; i < data->nr; i++) {
2535 int added = data->files[i]->added;
2536 int deleted = data->files[i]->deleted;
2538 if (data->files[i]->is_unmerged ||
2539 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2541 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2546 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2549 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2556 for (i = 0; i < data->nr; i++) {
2557 struct diffstat_file *file = data->files[i];
2559 fprintf(options->file, "%s", diff_line_prefix(options));
2561 if (file->is_binary)
2562 fprintf(options->file, "-\t-\t");
2564 fprintf(options->file,
2565 "%"PRIuMAX"\t%"PRIuMAX"\t",
2566 file->added, file->deleted);
2567 if (options->line_termination) {
2568 fill_print_name(file);
2569 if (!file->is_renamed)
2570 write_name_quoted(file->name, options->file,
2571 options->line_termination);
2573 fputs(file->print_name, options->file);
2574 putc(options->line_termination, options->file);
2577 if (file->is_renamed) {
2578 putc('\0', options->file);
2579 write_name_quoted(file->from_name, options->file, '\0');
2581 write_name_quoted(file->name, options->file, '\0');
2586 struct dirstat_file {
2588 unsigned long changed;
2591 struct dirstat_dir {
2592 struct dirstat_file *files;
2593 int alloc, nr, permille, cumulative;
2596 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2597 unsigned long changed, const char *base, int baselen)
2599 unsigned long this_dir = 0;
2600 unsigned int sources = 0;
2601 const char *line_prefix = diff_line_prefix(opt);
2604 struct dirstat_file *f = dir->files;
2605 int namelen = strlen(f->name);
2609 if (namelen < baselen)
2611 if (memcmp(f->name, base, baselen))
2613 slash = strchr(f->name + baselen, '/');
2615 int newbaselen = slash + 1 - f->name;
2616 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2628 * We don't report dirstat's for
2630 * - or cases where everything came from a single directory
2631 * under this directory (sources == 1).
2633 if (baselen && sources != 1) {
2635 int permille = this_dir * 1000 / changed;
2636 if (permille >= dir->permille) {
2637 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2638 permille / 10, permille % 10, baselen, base);
2639 if (!dir->cumulative)
2647 static int dirstat_compare(const void *_a, const void *_b)
2649 const struct dirstat_file *a = _a;
2650 const struct dirstat_file *b = _b;
2651 return strcmp(a->name, b->name);
2654 static void show_dirstat(struct diff_options *options)
2657 unsigned long changed;
2658 struct dirstat_dir dir;
2659 struct diff_queue_struct *q = &diff_queued_diff;
2664 dir.permille = options->dirstat_permille;
2665 dir.cumulative = options->flags.dirstat_cumulative;
2668 for (i = 0; i < q->nr; i++) {
2669 struct diff_filepair *p = q->queue[i];
2671 unsigned long copied, added, damage;
2672 int content_changed;
2674 name = p->two->path ? p->two->path : p->one->path;
2676 if (p->one->oid_valid && p->two->oid_valid)
2677 content_changed = oidcmp(&p->one->oid, &p->two->oid);
2679 content_changed = 1;
2681 if (!content_changed) {
2683 * The SHA1 has not changed, so pre-/post-content is
2684 * identical. We can therefore skip looking at the
2685 * file contents altogether.
2691 if (options->flags.dirstat_by_file) {
2693 * In --dirstat-by-file mode, we don't really need to
2694 * look at the actual file contents at all.
2695 * The fact that the SHA1 changed is enough for us to
2696 * add this file to the list of results
2697 * (with each file contributing equal damage).
2703 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2704 diff_populate_filespec(p->one, 0);
2705 diff_populate_filespec(p->two, 0);
2706 diffcore_count_changes(p->one, p->two, NULL, NULL,
2708 diff_free_filespec_data(p->one);
2709 diff_free_filespec_data(p->two);
2710 } else if (DIFF_FILE_VALID(p->one)) {
2711 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2713 diff_free_filespec_data(p->one);
2714 } else if (DIFF_FILE_VALID(p->two)) {
2715 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
2717 added = p->two->size;
2718 diff_free_filespec_data(p->two);
2723 * Original minus copied is the removed material,
2724 * added is the new material. They are both damages
2725 * made to the preimage.
2726 * If the resulting damage is zero, we know that
2727 * diffcore_count_changes() considers the two entries to
2728 * be identical, but since content_changed is true, we
2729 * know that there must have been _some_ kind of change,
2730 * so we force all entries to have damage > 0.
2732 damage = (p->one->size - copied) + added;
2737 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2738 dir.files[dir.nr].name = name;
2739 dir.files[dir.nr].changed = damage;
2744 /* This can happen even with many files, if everything was renames */
2748 /* Show all directories with more than x% of the changes */
2749 QSORT(dir.files, dir.nr, dirstat_compare);
2750 gather_dirstat(options, &dir, changed, "", 0);
2753 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2756 unsigned long changed;
2757 struct dirstat_dir dir;
2765 dir.permille = options->dirstat_permille;
2766 dir.cumulative = options->flags.dirstat_cumulative;
2769 for (i = 0; i < data->nr; i++) {
2770 struct diffstat_file *file = data->files[i];
2771 unsigned long damage = file->added + file->deleted;
2772 if (file->is_binary)
2774 * binary files counts bytes, not lines. Must find some
2775 * way to normalize binary bytes vs. textual lines.
2776 * The following heuristic assumes that there are 64
2778 * This is stupid and ugly, but very cheap...
2780 damage = DIV_ROUND_UP(damage, 64);
2781 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2782 dir.files[dir.nr].name = file->name;
2783 dir.files[dir.nr].changed = damage;
2788 /* This can happen even with many files, if everything was renames */
2792 /* Show all directories with more than x% of the changes */
2793 QSORT(dir.files, dir.nr, dirstat_compare);
2794 gather_dirstat(options, &dir, changed, "", 0);
2797 static void free_diffstat_info(struct diffstat_t *diffstat)
2800 for (i = 0; i < diffstat->nr; i++) {
2801 struct diffstat_file *f = diffstat->files[i];
2802 if (f->name != f->print_name)
2803 free(f->print_name);
2808 free(diffstat->files);
2811 struct checkdiff_t {
2812 const char *filename;
2814 int conflict_marker_size;
2815 struct diff_options *o;
2820 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2825 if (len < marker_size + 1)
2827 firstchar = line[0];
2828 switch (firstchar) {
2829 case '=': case '>': case '<': case '|':
2834 for (cnt = 1; cnt < marker_size; cnt++)
2835 if (line[cnt] != firstchar)
2837 /* line[1] thru line[marker_size-1] are same as firstchar */
2838 if (len < marker_size + 1 || !isspace(line[marker_size]))
2843 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2845 struct checkdiff_t *data = priv;
2846 int marker_size = data->conflict_marker_size;
2847 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2848 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2849 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2851 const char *line_prefix;
2854 line_prefix = diff_line_prefix(data->o);
2856 if (line[0] == '+') {
2859 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2861 fprintf(data->o->file,
2862 "%s%s:%d: leftover conflict marker\n",
2863 line_prefix, data->filename, data->lineno);
2865 bad = ws_check(line + 1, len - 1, data->ws_rule);
2868 data->status |= bad;
2869 err = whitespace_error_string(bad);
2870 fprintf(data->o->file, "%s%s:%d: %s.\n",
2871 line_prefix, data->filename, data->lineno, err);
2873 emit_line(data->o, set, reset, line, 1);
2874 ws_check_emit(line + 1, len - 1, data->ws_rule,
2875 data->o->file, set, reset, ws);
2876 } else if (line[0] == ' ') {
2878 } else if (line[0] == '@') {
2879 char *plus = strchr(line, '+');
2881 data->lineno = strtol(plus, NULL, 10) - 1;
2883 die("invalid diff");
2887 static unsigned char *deflate_it(char *data,
2889 unsigned long *result_size)
2892 unsigned char *deflated;
2895 git_deflate_init(&stream, zlib_compression_level);
2896 bound = git_deflate_bound(&stream, size);
2897 deflated = xmalloc(bound);
2898 stream.next_out = deflated;
2899 stream.avail_out = bound;
2901 stream.next_in = (unsigned char *)data;
2902 stream.avail_in = size;
2903 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2905 git_deflate_end(&stream);
2906 *result_size = stream.total_out;
2910 static void emit_binary_diff_body(struct diff_options *o,
2911 mmfile_t *one, mmfile_t *two)
2917 unsigned long orig_size;
2918 unsigned long delta_size;
2919 unsigned long deflate_size;
2920 unsigned long data_size;
2922 /* We could do deflated delta, or we could do just deflated two,
2923 * whichever is smaller.
2926 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2927 if (one->size && two->size) {
2928 delta = diff_delta(one->ptr, one->size,
2929 two->ptr, two->size,
2930 &delta_size, deflate_size);
2932 void *to_free = delta;
2933 orig_size = delta_size;
2934 delta = deflate_it(delta, delta_size, &delta_size);
2939 if (delta && delta_size < deflate_size) {
2940 char *s = xstrfmt("%lu", orig_size);
2941 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
2946 data_size = delta_size;
2948 char *s = xstrfmt("%lu", two->size);
2949 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
2954 data_size = deflate_size;
2957 /* emit data encoded in base85 */
2961 int bytes = (52 < data_size) ? 52 : data_size;
2965 line[0] = bytes + 'A' - 1;
2967 line[0] = bytes - 26 + 'a' - 1;
2968 encode_85(line + 1, cp, bytes);
2969 cp = (char *) cp + bytes;
2975 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
2978 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
2982 static void emit_binary_diff(struct diff_options *o,
2983 mmfile_t *one, mmfile_t *two)
2985 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
2986 emit_binary_diff_body(o, one, two);
2987 emit_binary_diff_body(o, two, one);
2990 int diff_filespec_is_binary(struct diff_filespec *one)
2992 if (one->is_binary == -1) {
2993 diff_filespec_load_driver(one);
2994 if (one->driver->binary != -1)
2995 one->is_binary = one->driver->binary;
2997 if (!one->data && DIFF_FILE_VALID(one))
2998 diff_populate_filespec(one, CHECK_BINARY);
2999 if (one->is_binary == -1 && one->data)
3000 one->is_binary = buffer_is_binary(one->data,
3002 if (one->is_binary == -1)
3006 return one->is_binary;
3009 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
3011 diff_filespec_load_driver(one);
3012 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3015 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3017 if (!options->a_prefix)
3018 options->a_prefix = a;
3019 if (!options->b_prefix)
3020 options->b_prefix = b;
3023 struct userdiff_driver *get_textconv(struct diff_filespec *one)
3025 if (!DIFF_FILE_VALID(one))
3028 diff_filespec_load_driver(one);
3029 return userdiff_get_textconv(one->driver);
3032 static void builtin_diff(const char *name_a,
3034 struct diff_filespec *one,
3035 struct diff_filespec *two,
3036 const char *xfrm_msg,
3037 int must_show_header,
3038 struct diff_options *o,
3039 int complete_rewrite)
3043 char *a_one, *b_two;
3044 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3045 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3046 const char *a_prefix, *b_prefix;
3047 struct userdiff_driver *textconv_one = NULL;
3048 struct userdiff_driver *textconv_two = NULL;
3049 struct strbuf header = STRBUF_INIT;
3050 const char *line_prefix = diff_line_prefix(o);
3052 diff_set_mnemonic_prefix(o, "a/", "b/");
3053 if (o->flags.reverse_diff) {
3054 a_prefix = o->b_prefix;
3055 b_prefix = o->a_prefix;
3057 a_prefix = o->a_prefix;
3058 b_prefix = o->b_prefix;
3061 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3062 (!one->mode || S_ISGITLINK(one->mode)) &&
3063 (!two->mode || S_ISGITLINK(two->mode))) {
3064 show_submodule_summary(o, one->path ? one->path : two->path,
3065 &one->oid, &two->oid,
3066 two->dirty_submodule);
3068 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3069 (!one->mode || S_ISGITLINK(one->mode)) &&
3070 (!two->mode || S_ISGITLINK(two->mode))) {
3071 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3072 &one->oid, &two->oid,
3073 two->dirty_submodule);
3077 if (o->flags.allow_textconv) {
3078 textconv_one = get_textconv(one);
3079 textconv_two = get_textconv(two);
3082 /* Never use a non-valid filename anywhere if at all possible */
3083 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3084 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3086 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3087 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3088 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3089 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3090 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3091 if (lbl[0][0] == '/') {
3093 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3095 strbuf_addstr(&header, xfrm_msg);
3096 must_show_header = 1;
3098 else if (lbl[1][0] == '/') {
3099 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3101 strbuf_addstr(&header, xfrm_msg);
3102 must_show_header = 1;
3105 if (one->mode != two->mode) {
3106 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3107 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3108 must_show_header = 1;
3111 strbuf_addstr(&header, xfrm_msg);
3114 * we do not run diff between different kind
3117 if ((one->mode ^ two->mode) & S_IFMT)
3118 goto free_ab_and_return;
3119 if (complete_rewrite &&
3120 (textconv_one || !diff_filespec_is_binary(one)) &&
3121 (textconv_two || !diff_filespec_is_binary(two))) {
3122 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3123 header.buf, header.len, 0);
3124 strbuf_reset(&header);
3125 emit_rewrite_diff(name_a, name_b, one, two,
3126 textconv_one, textconv_two, o);
3127 o->found_changes = 1;
3128 goto free_ab_and_return;
3132 if (o->irreversible_delete && lbl[1][0] == '/') {
3133 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3135 strbuf_reset(&header);
3136 goto free_ab_and_return;
3137 } else if (!o->flags.text &&
3138 ( (!textconv_one && diff_filespec_is_binary(one)) ||
3139 (!textconv_two && diff_filespec_is_binary(two)) )) {
3140 struct strbuf sb = STRBUF_INIT;
3141 if (!one->data && !two->data &&
3142 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3144 if (!oidcmp(&one->oid, &two->oid)) {
3145 if (must_show_header)
3146 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3147 header.buf, header.len,
3149 goto free_ab_and_return;
3151 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3152 header.buf, header.len, 0);
3153 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3154 diff_line_prefix(o), lbl[0], lbl[1]);
3155 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3157 strbuf_release(&sb);
3158 goto free_ab_and_return;
3160 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3161 die("unable to read files to diff");
3162 /* Quite common confusing case */
3163 if (mf1.size == mf2.size &&
3164 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3165 if (must_show_header)
3166 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3167 header.buf, header.len, 0);
3168 goto free_ab_and_return;
3170 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3171 strbuf_reset(&header);
3172 if (o->flags.binary)
3173 emit_binary_diff(o, &mf1, &mf2);
3175 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3176 diff_line_prefix(o), lbl[0], lbl[1]);
3177 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3179 strbuf_release(&sb);
3181 o->found_changes = 1;
3183 /* Crazy xdl interfaces.. */
3184 const char *diffopts = getenv("GIT_DIFF_OPTS");
3188 struct emit_callback ecbdata;
3189 const struct userdiff_funcname *pe;
3191 if (must_show_header) {
3192 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3193 header.buf, header.len, 0);
3194 strbuf_reset(&header);
3197 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
3198 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
3200 pe = diff_funcname_pattern(one);
3202 pe = diff_funcname_pattern(two);
3204 memset(&xpp, 0, sizeof(xpp));
3205 memset(&xecfg, 0, sizeof(xecfg));
3206 memset(&ecbdata, 0, sizeof(ecbdata));
3207 ecbdata.label_path = lbl;
3208 ecbdata.color_diff = want_color(o->use_color);
3209 ecbdata.ws_rule = whitespace_rule(name_b);
3210 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3211 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3213 ecbdata.header = header.len ? &header : NULL;
3214 xpp.flags = o->xdl_opts;
3215 xpp.anchors = o->anchors;
3216 xpp.anchors_nr = o->anchors_nr;
3217 xecfg.ctxlen = o->context;
3218 xecfg.interhunkctxlen = o->interhunkcontext;
3219 xecfg.flags = XDL_EMIT_FUNCNAMES;
3220 if (o->flags.funccontext)
3221 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3223 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3226 else if (skip_prefix(diffopts, "--unified=", &v))
3227 xecfg.ctxlen = strtoul(v, NULL, 10);
3228 else if (skip_prefix(diffopts, "-u", &v))
3229 xecfg.ctxlen = strtoul(v, NULL, 10);
3231 init_diff_words_data(&ecbdata, o, one, two);
3232 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
3234 die("unable to generate diff for %s", one->path);
3236 free_diff_words_data(&ecbdata);
3241 xdiff_clear_find_func(&xecfg);
3245 strbuf_release(&header);
3246 diff_free_filespec_data(one);
3247 diff_free_filespec_data(two);
3253 static void builtin_diffstat(const char *name_a, const char *name_b,
3254 struct diff_filespec *one,
3255 struct diff_filespec *two,
3256 struct diffstat_t *diffstat,
3257 struct diff_options *o,
3258 struct diff_filepair *p)
3261 struct diffstat_file *data;
3263 int complete_rewrite = 0;
3265 if (!DIFF_PAIR_UNMERGED(p)) {
3266 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3267 complete_rewrite = 1;
3270 data = diffstat_add(diffstat, name_a, name_b);
3271 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3274 data->is_unmerged = 1;
3278 same_contents = !oidcmp(&one->oid, &two->oid);
3280 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
3281 data->is_binary = 1;
3282 if (same_contents) {
3286 data->added = diff_filespec_size(two);
3287 data->deleted = diff_filespec_size(one);
3291 else if (complete_rewrite) {
3292 diff_populate_filespec(one, 0);
3293 diff_populate_filespec(two, 0);
3294 data->deleted = count_lines(one->data, one->size);
3295 data->added = count_lines(two->data, two->size);
3298 else if (!same_contents) {
3299 /* Crazy xdl interfaces.. */
3303 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3304 die("unable to read files to diff");
3306 memset(&xpp, 0, sizeof(xpp));
3307 memset(&xecfg, 0, sizeof(xecfg));
3308 xpp.flags = o->xdl_opts;
3309 xpp.anchors = o->anchors;
3310 xpp.anchors_nr = o->anchors_nr;
3311 xecfg.ctxlen = o->context;
3312 xecfg.interhunkctxlen = o->interhunkcontext;
3313 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
3315 die("unable to generate diffstat for %s", one->path);
3318 diff_free_filespec_data(one);
3319 diff_free_filespec_data(two);
3322 static void builtin_checkdiff(const char *name_a, const char *name_b,
3323 const char *attr_path,
3324 struct diff_filespec *one,
3325 struct diff_filespec *two,
3326 struct diff_options *o)
3329 struct checkdiff_t data;
3334 memset(&data, 0, sizeof(data));
3335 data.filename = name_b ? name_b : name_a;
3338 data.ws_rule = whitespace_rule(attr_path);
3339 data.conflict_marker_size = ll_merge_marker_size(attr_path);
3341 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3342 die("unable to read files to diff");
3345 * All the other codepaths check both sides, but not checking
3346 * the "old" side here is deliberate. We are checking the newly
3347 * introduced changes, and as long as the "new" side is text, we
3348 * can and should check what it introduces.
3350 if (diff_filespec_is_binary(two))
3351 goto free_and_return;
3353 /* Crazy xdl interfaces.. */
3357 memset(&xpp, 0, sizeof(xpp));
3358 memset(&xecfg, 0, sizeof(xecfg));
3359 xecfg.ctxlen = 1; /* at least one context line */
3361 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
3363 die("unable to generate checkdiff for %s", one->path);
3365 if (data.ws_rule & WS_BLANK_AT_EOF) {
3366 struct emit_callback ecbdata;
3369 ecbdata.ws_rule = data.ws_rule;
3370 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3371 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3376 err = whitespace_error_string(WS_BLANK_AT_EOF);
3377 fprintf(o->file, "%s:%d: %s.\n",
3378 data.filename, blank_at_eof, err);
3379 data.status = 1; /* report errors */
3384 diff_free_filespec_data(one);
3385 diff_free_filespec_data(two);
3387 o->flags.check_failed = 1;
3390 struct diff_filespec *alloc_filespec(const char *path)
3392 struct diff_filespec *spec;
3394 FLEXPTR_ALLOC_STR(spec, path, path);
3396 spec->is_binary = -1;
3400 void free_filespec(struct diff_filespec *spec)
3402 if (!--spec->count) {
3403 diff_free_filespec_data(spec);
3408 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3409 int oid_valid, unsigned short mode)
3412 spec->mode = canon_mode(mode);
3413 oidcpy(&spec->oid, oid);
3414 spec->oid_valid = oid_valid;
3419 * Given a name and sha1 pair, if the index tells us the file in
3420 * the work tree has that object contents, return true, so that
3421 * prepare_temp_file() does not have to inflate and extract.
3423 static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
3425 const struct cache_entry *ce;
3430 * We do not read the cache ourselves here, because the
3431 * benchmark with my previous version that always reads cache
3432 * shows that it makes things worse for diff-tree comparing
3433 * two linux-2.6 kernel trees in an already checked out work
3434 * tree. This is because most diff-tree comparisons deal with
3435 * only a small number of files, while reading the cache is
3436 * expensive for a large project, and its cost outweighs the
3437 * savings we get by not inflating the object to a temporary
3438 * file. Practically, this code only helps when we are used
3439 * by diff-cache --cached, which does read the cache before
3445 /* We want to avoid the working directory if our caller
3446 * doesn't need the data in a normal file, this system
3447 * is rather slow with its stat/open/mmap/close syscalls,
3448 * and the object is contained in a pack file. The pack
3449 * is probably already open and will be faster to obtain
3450 * the data through than the working directory. Loose
3451 * objects however would tend to be slower as they need
3452 * to be individually opened and inflated.
3454 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
3458 * Similarly, if we'd have to convert the file contents anyway, that
3459 * makes the optimization not worthwhile.
3461 if (!want_file && would_convert_to_git(&the_index, name))
3465 pos = cache_name_pos(name, len);
3468 ce = active_cache[pos];
3471 * This is not the sha1 we are looking for, or
3472 * unreusable because it is not a regular file.
3474 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3478 * If ce is marked as "assume unchanged", there is no
3479 * guarantee that work tree matches what we are looking for.
3481 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3485 * If ce matches the file in the work tree, we can reuse it.
3487 if (ce_uptodate(ce) ||
3488 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3494 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3496 struct strbuf buf = STRBUF_INIT;
3499 /* Are we looking at the work tree? */
3500 if (s->dirty_submodule)
3503 strbuf_addf(&buf, "Subproject commit %s%s\n",
3504 oid_to_hex(&s->oid), dirty);
3508 strbuf_release(&buf);
3510 s->data = strbuf_detach(&buf, NULL);
3517 * While doing rename detection and pickaxe operation, we may need to
3518 * grab the data for the blob (or file) for our own in-core comparison.
3519 * diff_filespec has data and size fields for this purpose.
3521 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
3523 int size_only = flags & CHECK_SIZE_ONLY;
3526 * demote FAIL to WARN to allow inspecting the situation
3527 * instead of refusing.
3529 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
3533 if (!DIFF_FILE_VALID(s))
3534 die("internal error: asking to populate invalid file.");
3535 if (S_ISDIR(s->mode))
3541 if (size_only && 0 < s->size)
3544 if (S_ISGITLINK(s->mode))
3545 return diff_populate_gitlink(s, size_only);
3547 if (!s->oid_valid ||
3548 reuse_worktree_file(s->path, &s->oid, 0)) {
3549 struct strbuf buf = STRBUF_INIT;
3553 if (lstat(s->path, &st) < 0) {
3557 s->data = (char *)"";
3561 s->size = xsize_t(st.st_size);
3564 if (S_ISLNK(st.st_mode)) {
3565 struct strbuf sb = STRBUF_INIT;
3567 if (strbuf_readlink(&sb, s->path, s->size))
3570 s->data = strbuf_detach(&sb, NULL);
3576 * Even if the caller would be happy with getting
3577 * only the size, we cannot return early at this
3578 * point if the path requires us to run the content
3581 if (size_only && !would_convert_to_git(&the_index, s->path))
3585 * Note: this check uses xsize_t(st.st_size) that may
3586 * not be the true size of the blob after it goes
3587 * through convert_to_git(). This may not strictly be
3588 * correct, but the whole point of big_file_threshold
3589 * and is_binary check being that we want to avoid
3590 * opening the file and inspecting the contents, this
3593 if ((flags & CHECK_BINARY) &&
3594 s->size > big_file_threshold && s->is_binary == -1) {
3598 fd = open(s->path, O_RDONLY);
3601 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3603 s->should_munmap = 1;
3606 * Convert from working tree format to canonical git format
3608 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, crlf_warn)) {
3610 munmap(s->data, s->size);
3611 s->should_munmap = 0;
3612 s->data = strbuf_detach(&buf, &size);
3618 enum object_type type;
3619 if (size_only || (flags & CHECK_BINARY)) {
3620 type = sha1_object_info(s->oid.hash, &s->size);
3622 die("unable to read %s",
3623 oid_to_hex(&s->oid));
3626 if (s->size > big_file_threshold && s->is_binary == -1) {
3631 s->data = read_sha1_file(s->oid.hash, &type, &s->size);
3633 die("unable to read %s", oid_to_hex(&s->oid));
3639 void diff_free_filespec_blob(struct diff_filespec *s)
3643 else if (s->should_munmap)
3644 munmap(s->data, s->size);
3646 if (s->should_free || s->should_munmap) {
3647 s->should_free = s->should_munmap = 0;
3652 void diff_free_filespec_data(struct diff_filespec *s)
3654 diff_free_filespec_blob(s);
3655 FREE_AND_NULL(s->cnt_data);
3658 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
3661 const struct object_id *oid,
3664 struct strbuf buf = STRBUF_INIT;
3665 struct strbuf template = STRBUF_INIT;
3666 char *path_dup = xstrdup(path);
3667 const char *base = basename(path_dup);
3669 /* Generate "XXXXXX_basename.ext" */
3670 strbuf_addstr(&template, "XXXXXX_");
3671 strbuf_addstr(&template, base);
3673 temp->tempfile = mks_tempfile_ts(template.buf, strlen(base) + 1);
3674 if (!temp->tempfile)
3675 die_errno("unable to create temp-file");
3676 if (convert_to_working_tree(path,
3677 (const char *)blob, (size_t)size, &buf)) {
3681 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
3682 close_tempfile_gently(temp->tempfile))
3683 die_errno("unable to write temp-file");
3684 temp->name = get_tempfile_path(temp->tempfile);
3685 oid_to_hex_r(temp->hex, oid);
3686 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
3687 strbuf_release(&buf);
3688 strbuf_release(&template);
3692 static struct diff_tempfile *prepare_temp_file(const char *name,
3693 struct diff_filespec *one)
3695 struct diff_tempfile *temp = claim_diff_tempfile();
3697 if (!DIFF_FILE_VALID(one)) {
3699 /* A '-' entry produces this for file-2, and
3700 * a '+' entry produces this for file-1.
3702 temp->name = "/dev/null";
3703 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3704 xsnprintf(temp->mode, sizeof(temp->mode), ".");
3708 if (!S_ISGITLINK(one->mode) &&
3710 reuse_worktree_file(name, &one->oid, 1))) {
3712 if (lstat(name, &st) < 0) {
3713 if (errno == ENOENT)
3714 goto not_a_valid_file;
3715 die_errno("stat(%s)", name);
3717 if (S_ISLNK(st.st_mode)) {
3718 struct strbuf sb = STRBUF_INIT;
3719 if (strbuf_readlink(&sb, name, st.st_size) < 0)
3720 die_errno("readlink(%s)", name);
3721 prep_temp_blob(name, temp, sb.buf, sb.len,
3723 &one->oid : &null_oid),
3725 one->mode : S_IFLNK));
3726 strbuf_release(&sb);
3729 /* we can borrow from the file in the work tree */
3731 if (!one->oid_valid)
3732 oid_to_hex_r(temp->hex, &null_oid);
3734 oid_to_hex_r(temp->hex, &one->oid);
3735 /* Even though we may sometimes borrow the
3736 * contents from the work tree, we always want
3737 * one->mode. mode is trustworthy even when
3738 * !(one->oid_valid), as long as
3739 * DIFF_FILE_VALID(one).
3741 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
3746 if (diff_populate_filespec(one, 0))
3747 die("cannot read data blob for %s", one->path);
3748 prep_temp_blob(name, temp, one->data, one->size,
3749 &one->oid, one->mode);
3754 static void add_external_diff_name(struct argv_array *argv,
3756 struct diff_filespec *df)
3758 struct diff_tempfile *temp = prepare_temp_file(name, df);
3759 argv_array_push(argv, temp->name);
3760 argv_array_push(argv, temp->hex);
3761 argv_array_push(argv, temp->mode);
3764 /* An external diff command takes:
3766 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3767 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3770 static void run_external_diff(const char *pgm,
3773 struct diff_filespec *one,
3774 struct diff_filespec *two,
3775 const char *xfrm_msg,
3776 int complete_rewrite,
3777 struct diff_options *o)
3779 struct argv_array argv = ARGV_ARRAY_INIT;
3780 struct argv_array env = ARGV_ARRAY_INIT;
3781 struct diff_queue_struct *q = &diff_queued_diff;
3783 argv_array_push(&argv, pgm);
3784 argv_array_push(&argv, name);
3787 add_external_diff_name(&argv, name, one);
3789 add_external_diff_name(&argv, name, two);
3791 add_external_diff_name(&argv, other, two);
3792 argv_array_push(&argv, other);
3793 argv_array_push(&argv, xfrm_msg);
3797 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3798 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3800 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3801 die(_("external diff died, stopping at %s"), name);
3804 argv_array_clear(&argv);
3805 argv_array_clear(&env);
3808 static int similarity_index(struct diff_filepair *p)
3810 return p->score * 100 / MAX_SCORE;
3813 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3815 if (startup_info->have_repository)
3816 return find_unique_abbrev(oid->hash, abbrev);
3818 char *hex = oid_to_hex(oid);
3820 abbrev = FALLBACK_DEFAULT_ABBREV;
3821 if (abbrev > GIT_SHA1_HEXSZ)
3822 die("BUG: oid abbreviation out of range: %d", abbrev);
3829 static void fill_metainfo(struct strbuf *msg,
3832 struct diff_filespec *one,
3833 struct diff_filespec *two,
3834 struct diff_options *o,
3835 struct diff_filepair *p,
3836 int *must_show_header,
3839 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3840 const char *reset = diff_get_color(use_color, DIFF_RESET);
3841 const char *line_prefix = diff_line_prefix(o);
3843 *must_show_header = 1;
3844 strbuf_init(msg, PATH_MAX * 2 + 300);
3845 switch (p->status) {
3846 case DIFF_STATUS_COPIED:
3847 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3848 line_prefix, set, similarity_index(p));
3849 strbuf_addf(msg, "%s\n%s%scopy from ",
3850 reset, line_prefix, set);
3851 quote_c_style(name, msg, NULL, 0);
3852 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3853 quote_c_style(other, msg, NULL, 0);
3854 strbuf_addf(msg, "%s\n", reset);
3856 case DIFF_STATUS_RENAMED:
3857 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3858 line_prefix, set, similarity_index(p));
3859 strbuf_addf(msg, "%s\n%s%srename from ",
3860 reset, line_prefix, set);
3861 quote_c_style(name, msg, NULL, 0);
3862 strbuf_addf(msg, "%s\n%s%srename to ",
3863 reset, line_prefix, set);
3864 quote_c_style(other, msg, NULL, 0);
3865 strbuf_addf(msg, "%s\n", reset);
3867 case DIFF_STATUS_MODIFIED:
3869 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3871 set, similarity_index(p), reset);
3876 *must_show_header = 0;
3878 if (one && two && oidcmp(&one->oid, &two->oid)) {
3879 int abbrev = o->flags.full_index ? 40 : DEFAULT_ABBREV;
3881 if (o->flags.binary) {
3883 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3884 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3887 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3888 diff_abbrev_oid(&one->oid, abbrev),
3889 diff_abbrev_oid(&two->oid, abbrev));
3890 if (one->mode == two->mode)
3891 strbuf_addf(msg, " %06o", one->mode);
3892 strbuf_addf(msg, "%s\n", reset);
3896 static void run_diff_cmd(const char *pgm,
3899 const char *attr_path,
3900 struct diff_filespec *one,
3901 struct diff_filespec *two,
3903 struct diff_options *o,
3904 struct diff_filepair *p)
3906 const char *xfrm_msg = NULL;
3907 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3908 int must_show_header = 0;
3911 if (o->flags.allow_external) {
3912 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3913 if (drv && drv->external)
3914 pgm = drv->external;
3919 * don't use colors when the header is intended for an
3920 * external diff driver
3922 fill_metainfo(msg, name, other, one, two, o, p,
3924 want_color(o->use_color) && !pgm);
3925 xfrm_msg = msg->len ? msg->buf : NULL;
3929 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3930 complete_rewrite, o);
3934 builtin_diff(name, other ? other : name,
3935 one, two, xfrm_msg, must_show_header,
3936 o, complete_rewrite);
3938 fprintf(o->file, "* Unmerged path %s\n", name);
3941 static void diff_fill_oid_info(struct diff_filespec *one)
3943 if (DIFF_FILE_VALID(one)) {
3944 if (!one->oid_valid) {
3946 if (one->is_stdin) {
3950 if (lstat(one->path, &st) < 0)
3951 die_errno("stat '%s'", one->path);
3952 if (index_path(&one->oid, one->path, &st, 0))
3953 die("cannot hash %s", one->path);
3960 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3962 /* Strip the prefix but do not molest /dev/null and absolute paths */
3963 if (*namep && **namep != '/') {
3964 *namep += prefix_length;
3968 if (*otherp && **otherp != '/') {
3969 *otherp += prefix_length;
3970 if (**otherp == '/')
3975 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3977 const char *pgm = external_diff();
3979 struct diff_filespec *one = p->one;
3980 struct diff_filespec *two = p->two;
3983 const char *attr_path;
3986 other = (strcmp(name, two->path) ? two->path : NULL);
3988 if (o->prefix_length)
3989 strip_prefix(o->prefix_length, &name, &other);
3991 if (!o->flags.allow_external)
3994 if (DIFF_PAIR_UNMERGED(p)) {
3995 run_diff_cmd(pgm, name, NULL, attr_path,
3996 NULL, NULL, NULL, o, p);
4000 diff_fill_oid_info(one);
4001 diff_fill_oid_info(two);
4004 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4005 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4007 * a filepair that changes between file and symlink
4008 * needs to be split into deletion and creation.
4010 struct diff_filespec *null = alloc_filespec(two->path);
4011 run_diff_cmd(NULL, name, other, attr_path,
4012 one, null, &msg, o, p);
4014 strbuf_release(&msg);
4016 null = alloc_filespec(one->path);
4017 run_diff_cmd(NULL, name, other, attr_path,
4018 null, two, &msg, o, p);
4022 run_diff_cmd(pgm, name, other, attr_path,
4023 one, two, &msg, o, p);
4025 strbuf_release(&msg);
4028 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4029 struct diffstat_t *diffstat)
4034 if (DIFF_PAIR_UNMERGED(p)) {
4036 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
4040 name = p->one->path;
4041 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4043 if (o->prefix_length)
4044 strip_prefix(o->prefix_length, &name, &other);
4046 diff_fill_oid_info(p->one);
4047 diff_fill_oid_info(p->two);
4049 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
4052 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4056 const char *attr_path;
4058 if (DIFF_PAIR_UNMERGED(p)) {
4063 name = p->one->path;
4064 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4065 attr_path = other ? other : name;
4067 if (o->prefix_length)
4068 strip_prefix(o->prefix_length, &name, &other);
4070 diff_fill_oid_info(p->one);
4071 diff_fill_oid_info(p->two);
4073 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4076 void diff_setup(struct diff_options *options)
4078 memcpy(options, &default_diff_options, sizeof(*options));
4080 options->file = stdout;
4082 options->abbrev = DEFAULT_ABBREV;
4083 options->line_termination = '\n';
4084 options->break_opt = -1;
4085 options->rename_limit = -1;
4086 options->dirstat_permille = diff_dirstat_permille_default;
4087 options->context = diff_context_default;
4088 options->interhunkcontext = diff_interhunk_context_default;
4089 options->ws_error_highlight = ws_error_highlight_default;
4090 options->flags.rename_empty = 1;
4092 /* pathchange left =NULL by default */
4093 options->change = diff_change;
4094 options->add_remove = diff_addremove;
4095 options->use_color = diff_use_color_default;
4096 options->detect_rename = diff_detect_rename_default;
4097 options->xdl_opts |= diff_algorithm;
4098 if (diff_indent_heuristic)
4099 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4101 options->orderfile = diff_order_file_cfg;
4103 if (diff_no_prefix) {
4104 options->a_prefix = options->b_prefix = "";
4105 } else if (!diff_mnemonic_prefix) {
4106 options->a_prefix = "a/";
4107 options->b_prefix = "b/";
4110 options->color_moved = diff_color_moved_default;
4113 void diff_setup_done(struct diff_options *options)
4117 if (options->set_default)
4118 options->set_default(options);
4120 if (options->output_format & DIFF_FORMAT_NAME)
4122 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
4124 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
4126 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
4129 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4132 * Most of the time we can say "there are changes"
4133 * only by checking if there are changed paths, but
4134 * --ignore-whitespace* options force us to look
4138 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
4139 options->flags.diff_from_contents = 1;
4141 options->flags.diff_from_contents = 0;
4143 if (options->flags.find_copies_harder)
4144 options->detect_rename = DIFF_DETECT_COPY;
4146 if (!options->flags.relative_name)
4147 options->prefix = NULL;
4148 if (options->prefix)
4149 options->prefix_length = strlen(options->prefix);
4151 options->prefix_length = 0;
4153 if (options->output_format & (DIFF_FORMAT_NAME |
4154 DIFF_FORMAT_NAME_STATUS |
4155 DIFF_FORMAT_CHECKDIFF |
4156 DIFF_FORMAT_NO_OUTPUT))
4157 options->output_format &= ~(DIFF_FORMAT_RAW |
4158 DIFF_FORMAT_NUMSTAT |
4159 DIFF_FORMAT_DIFFSTAT |
4160 DIFF_FORMAT_SHORTSTAT |
4161 DIFF_FORMAT_DIRSTAT |
4162 DIFF_FORMAT_SUMMARY |
4166 * These cases always need recursive; we do not drop caller-supplied
4167 * recursive bits for other formats here.
4169 if (options->output_format & (DIFF_FORMAT_PATCH |
4170 DIFF_FORMAT_NUMSTAT |
4171 DIFF_FORMAT_DIFFSTAT |
4172 DIFF_FORMAT_SHORTSTAT |
4173 DIFF_FORMAT_DIRSTAT |
4174 DIFF_FORMAT_SUMMARY |
4175 DIFF_FORMAT_CHECKDIFF))
4176 options->flags.recursive = 1;
4178 * Also pickaxe would not work very well if you do not say recursive
4180 if (options->pickaxe)
4181 options->flags.recursive = 1;
4183 * When patches are generated, submodules diffed against the work tree
4184 * must be checked for dirtiness too so it can be shown in the output
4186 if (options->output_format & DIFF_FORMAT_PATCH)
4187 options->flags.dirty_submodules = 1;
4189 if (options->detect_rename && options->rename_limit < 0)
4190 options->rename_limit = diff_rename_limit_default;
4191 if (options->setup & DIFF_SETUP_USE_CACHE) {
4193 /* read-cache does not die even when it fails
4194 * so it is safe for us to do this here. Also
4195 * it does not smudge active_cache or active_nr
4196 * when it fails, so we do not have to worry about
4197 * cleaning it up ourselves either.
4201 if (40 < options->abbrev)
4202 options->abbrev = 40; /* full */
4205 * It does not make sense to show the first hit we happened
4206 * to have found. It does not make sense not to return with
4207 * exit code in such a case either.
4209 if (options->flags.quick) {
4210 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4211 options->flags.exit_with_status = 1;
4214 options->diff_path_counter = 0;
4216 if (options->flags.follow_renames && options->pathspec.nr != 1)
4217 die(_("--follow requires exactly one pathspec"));
4219 if (!options->use_color || external_diff())
4220 options->color_moved = 0;
4223 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4233 if (c == arg_short) {
4237 if (val && isdigit(c)) {
4239 int n = strtoul(arg, &end, 10);
4250 eq = strchrnul(arg, '=');
4252 if (!len || strncmp(arg, arg_long, len))
4257 if (!isdigit(*++eq))
4259 n = strtoul(eq, &end, 10);
4267 static int diff_scoreopt_parse(const char *opt);
4269 static inline int short_opt(char opt, const char **argv,
4270 const char **optarg)
4272 const char *arg = argv[0];
4273 if (arg[0] != '-' || arg[1] != opt)
4275 if (arg[2] != '\0') {
4280 die("Option '%c' requires a value", opt);
4285 int parse_long_opt(const char *opt, const char **argv,
4286 const char **optarg)
4288 const char *arg = argv[0];
4289 if (!skip_prefix(arg, "--", &arg))
4291 if (!skip_prefix(arg, opt, &arg))
4293 if (*arg == '=') { /* stuck form: --option=value */
4299 /* separate form: --option value */
4301 die("Option '--%s' requires a value", opt);
4306 static int stat_opt(struct diff_options *options, const char **av)
4308 const char *arg = av[0];
4310 int width = options->stat_width;
4311 int name_width = options->stat_name_width;
4312 int graph_width = options->stat_graph_width;
4313 int count = options->stat_count;
4316 if (!skip_prefix(arg, "--stat", &arg))
4317 die("BUG: stat option does not begin with --stat: %s", arg);
4322 if (skip_prefix(arg, "-width", &arg)) {
4324 width = strtoul(arg + 1, &end, 10);
4325 else if (!*arg && !av[1])
4326 die_want_option("--stat-width");
4328 width = strtoul(av[1], &end, 10);
4331 } else if (skip_prefix(arg, "-name-width", &arg)) {
4333 name_width = strtoul(arg + 1, &end, 10);
4334 else if (!*arg && !av[1])
4335 die_want_option("--stat-name-width");
4337 name_width = strtoul(av[1], &end, 10);
4340 } else if (skip_prefix(arg, "-graph-width", &arg)) {
4342 graph_width = strtoul(arg + 1, &end, 10);
4343 else if (!*arg && !av[1])
4344 die_want_option("--stat-graph-width");
4346 graph_width = strtoul(av[1], &end, 10);
4349 } else if (skip_prefix(arg, "-count", &arg)) {
4351 count = strtoul(arg + 1, &end, 10);
4352 else if (!*arg && !av[1])
4353 die_want_option("--stat-count");
4355 count = strtoul(av[1], &end, 10);
4361 width = strtoul(arg+1, &end, 10);
4363 name_width = strtoul(end+1, &end, 10);
4365 count = strtoul(end+1, &end, 10);
4368 /* Important! This checks all the error cases! */
4371 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4372 options->stat_name_width = name_width;
4373 options->stat_graph_width = graph_width;
4374 options->stat_width = width;
4375 options->stat_count = count;
4379 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4381 struct strbuf errmsg = STRBUF_INIT;
4382 if (parse_dirstat_params(options, params, &errmsg))
4383 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4385 strbuf_release(&errmsg);
4387 * The caller knows a dirstat-related option is given from the command
4388 * line; allow it to say "return this_function();"
4390 options->output_format |= DIFF_FORMAT_DIRSTAT;
4394 static int parse_submodule_opt(struct diff_options *options, const char *value)
4396 if (parse_submodule_params(options, value))
4397 die(_("Failed to parse --submodule option parameter: '%s'"),
4402 static const char diff_status_letters[] = {
4405 DIFF_STATUS_DELETED,
4406 DIFF_STATUS_MODIFIED,
4407 DIFF_STATUS_RENAMED,
4408 DIFF_STATUS_TYPE_CHANGED,
4409 DIFF_STATUS_UNKNOWN,
4410 DIFF_STATUS_UNMERGED,
4411 DIFF_STATUS_FILTER_AON,
4412 DIFF_STATUS_FILTER_BROKEN,
4416 static unsigned int filter_bit['Z' + 1];
4418 static void prepare_filter_bits(void)
4422 if (!filter_bit[DIFF_STATUS_ADDED]) {
4423 for (i = 0; diff_status_letters[i]; i++)
4424 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4428 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4430 return opt->filter & filter_bit[(int) status];
4433 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4437 prepare_filter_bits();
4440 * If there is a negation e.g. 'd' in the input, and we haven't
4441 * initialized the filter field with another --diff-filter, start
4442 * from full set of bits, except for AON.
4445 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4446 if (optch < 'a' || 'z' < optch)
4448 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4449 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4454 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4458 if ('a' <= optch && optch <= 'z') {
4460 optch = toupper(optch);
4465 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4469 opt->filter &= ~bit;
4476 static void enable_patch_output(int *fmt) {
4477 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4478 *fmt |= DIFF_FORMAT_PATCH;
4481 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4483 int val = parse_ws_error_highlight(arg);
4486 error("unknown value after ws-error-highlight=%.*s",
4490 opt->ws_error_highlight = val;
4494 int diff_opt_parse(struct diff_options *options,
4495 const char **av, int ac, const char *prefix)
4497 const char *arg = av[0];
4504 /* Output format options */
4505 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
4506 || opt_arg(arg, 'U', "unified", &options->context))
4507 enable_patch_output(&options->output_format);
4508 else if (!strcmp(arg, "--raw"))
4509 options->output_format |= DIFF_FORMAT_RAW;
4510 else if (!strcmp(arg, "--patch-with-raw")) {
4511 enable_patch_output(&options->output_format);
4512 options->output_format |= DIFF_FORMAT_RAW;
4513 } else if (!strcmp(arg, "--numstat"))
4514 options->output_format |= DIFF_FORMAT_NUMSTAT;
4515 else if (!strcmp(arg, "--shortstat"))
4516 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4517 else if (skip_prefix(arg, "-X", &arg) ||
4518 skip_to_optional_arg(arg, "--dirstat", &arg))
4519 return parse_dirstat_opt(options, arg);
4520 else if (!strcmp(arg, "--cumulative"))
4521 return parse_dirstat_opt(options, "cumulative");
4522 else if (skip_to_optional_arg(arg, "--dirstat-by-file", &arg)) {
4523 parse_dirstat_opt(options, "files");
4524 return parse_dirstat_opt(options, arg);
4526 else if (!strcmp(arg, "--check"))
4527 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4528 else if (!strcmp(arg, "--summary"))
4529 options->output_format |= DIFF_FORMAT_SUMMARY;
4530 else if (!strcmp(arg, "--patch-with-stat")) {
4531 enable_patch_output(&options->output_format);
4532 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4533 } else if (!strcmp(arg, "--name-only"))
4534 options->output_format |= DIFF_FORMAT_NAME;
4535 else if (!strcmp(arg, "--name-status"))
4536 options->output_format |= DIFF_FORMAT_NAME_STATUS;
4537 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
4538 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4539 else if (starts_with(arg, "--stat"))
4540 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4541 return stat_opt(options, av);
4543 /* renames options */
4544 else if (starts_with(arg, "-B") ||
4545 skip_to_optional_arg(arg, "--break-rewrites", NULL)) {
4546 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
4547 return error("invalid argument to -B: %s", arg+2);
4549 else if (starts_with(arg, "-M") ||
4550 skip_to_optional_arg(arg, "--find-renames", NULL)) {
4551 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4552 return error("invalid argument to -M: %s", arg+2);
4553 options->detect_rename = DIFF_DETECT_RENAME;
4555 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
4556 options->irreversible_delete = 1;
4558 else if (starts_with(arg, "-C") ||
4559 skip_to_optional_arg(arg, "--find-copies", NULL)) {
4560 if (options->detect_rename == DIFF_DETECT_COPY)
4561 options->flags.find_copies_harder = 1;
4562 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4563 return error("invalid argument to -C: %s", arg+2);
4564 options->detect_rename = DIFF_DETECT_COPY;
4566 else if (!strcmp(arg, "--no-renames"))
4567 options->detect_rename = 0;
4568 else if (!strcmp(arg, "--rename-empty"))
4569 options->flags.rename_empty = 1;
4570 else if (!strcmp(arg, "--no-rename-empty"))
4571 options->flags.rename_empty = 0;
4572 else if (skip_to_optional_arg_default(arg, "--relative", &arg, NULL)) {
4573 options->flags.relative_name = 1;
4575 options->prefix = arg;
4579 else if (!strcmp(arg, "--minimal"))
4580 DIFF_XDL_SET(options, NEED_MINIMAL);
4581 else if (!strcmp(arg, "--no-minimal"))
4582 DIFF_XDL_CLR(options, NEED_MINIMAL);
4583 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
4584 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
4585 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
4586 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
4587 else if (!strcmp(arg, "--ignore-space-at-eol"))
4588 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
4589 else if (!strcmp(arg, "--ignore-cr-at-eol"))
4590 DIFF_XDL_SET(options, IGNORE_CR_AT_EOL);
4591 else if (!strcmp(arg, "--ignore-blank-lines"))
4592 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
4593 else if (!strcmp(arg, "--indent-heuristic"))
4594 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4595 else if (!strcmp(arg, "--no-indent-heuristic"))
4596 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
4597 else if (!strcmp(arg, "--patience")) {
4599 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4601 * Both --patience and --anchored use PATIENCE_DIFF
4602 * internally, so remove any anchors previously
4605 for (i = 0; i < options->anchors_nr; i++)
4606 free(options->anchors[i]);
4607 options->anchors_nr = 0;
4608 } else if (!strcmp(arg, "--histogram"))
4609 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
4610 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
4611 long value = parse_algorithm_value(optarg);
4613 return error("option diff-algorithm accepts \"myers\", "
4614 "\"minimal\", \"patience\" and \"histogram\"");
4615 /* clear out previous settings */
4616 DIFF_XDL_CLR(options, NEED_MINIMAL);
4617 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4618 options->xdl_opts |= value;
4620 } else if (skip_prefix(arg, "--anchored=", &arg)) {
4621 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4622 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4623 options->anchors_alloc);
4624 options->anchors[options->anchors_nr++] = xstrdup(arg);
4628 else if (!strcmp(arg, "--binary")) {
4629 enable_patch_output(&options->output_format);
4630 options->flags.binary = 1;
4632 else if (!strcmp(arg, "--full-index"))
4633 options->flags.full_index = 1;
4634 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
4635 options->flags.text = 1;
4636 else if (!strcmp(arg, "-R"))
4637 options->flags.reverse_diff = 1;
4638 else if (!strcmp(arg, "--find-copies-harder"))
4639 options->flags.find_copies_harder = 1;
4640 else if (!strcmp(arg, "--follow"))
4641 options->flags.follow_renames = 1;
4642 else if (!strcmp(arg, "--no-follow")) {
4643 options->flags.follow_renames = 0;
4644 options->flags.default_follow_renames = 0;
4645 } else if (skip_to_optional_arg_default(arg, "--color", &arg, "always")) {
4646 int value = git_config_colorbool(NULL, arg);
4648 return error("option `color' expects \"always\", \"auto\", or \"never\"");
4649 options->use_color = value;
4651 else if (!strcmp(arg, "--no-color"))
4652 options->use_color = 0;
4653 else if (!strcmp(arg, "--color-moved")) {
4654 if (diff_color_moved_default)
4655 options->color_moved = diff_color_moved_default;
4656 if (options->color_moved == COLOR_MOVED_NO)
4657 options->color_moved = COLOR_MOVED_DEFAULT;
4658 } else if (!strcmp(arg, "--no-color-moved"))
4659 options->color_moved = COLOR_MOVED_NO;
4660 else if (skip_prefix(arg, "--color-moved=", &arg)) {
4661 int cm = parse_color_moved(arg);
4663 die("bad --color-moved argument: %s", arg);
4664 options->color_moved = cm;
4665 } else if (skip_to_optional_arg_default(arg, "--color-words", &options->word_regex, NULL)) {
4666 options->use_color = 1;
4667 options->word_diff = DIFF_WORDS_COLOR;
4669 else if (!strcmp(arg, "--word-diff")) {
4670 if (options->word_diff == DIFF_WORDS_NONE)
4671 options->word_diff = DIFF_WORDS_PLAIN;
4673 else if (skip_prefix(arg, "--word-diff=", &arg)) {
4674 if (!strcmp(arg, "plain"))
4675 options->word_diff = DIFF_WORDS_PLAIN;
4676 else if (!strcmp(arg, "color")) {
4677 options->use_color = 1;
4678 options->word_diff = DIFF_WORDS_COLOR;
4680 else if (!strcmp(arg, "porcelain"))
4681 options->word_diff = DIFF_WORDS_PORCELAIN;
4682 else if (!strcmp(arg, "none"))
4683 options->word_diff = DIFF_WORDS_NONE;
4685 die("bad --word-diff argument: %s", arg);
4687 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
4688 if (options->word_diff == DIFF_WORDS_NONE)
4689 options->word_diff = DIFF_WORDS_PLAIN;
4690 options->word_regex = optarg;
4693 else if (!strcmp(arg, "--exit-code"))
4694 options->flags.exit_with_status = 1;
4695 else if (!strcmp(arg, "--quiet"))
4696 options->flags.quick = 1;
4697 else if (!strcmp(arg, "--ext-diff"))
4698 options->flags.allow_external = 1;
4699 else if (!strcmp(arg, "--no-ext-diff"))
4700 options->flags.allow_external = 0;
4701 else if (!strcmp(arg, "--textconv")) {
4702 options->flags.allow_textconv = 1;
4703 options->flags.textconv_set_via_cmdline = 1;
4704 } else if (!strcmp(arg, "--no-textconv"))
4705 options->flags.allow_textconv = 0;
4706 else if (skip_to_optional_arg_default(arg, "--ignore-submodules", &arg, "all")) {
4707 options->flags.override_submodule_config = 1;
4708 handle_ignore_submodules_arg(options, arg);
4709 } else if (skip_to_optional_arg_default(arg, "--submodule", &arg, "log"))
4710 return parse_submodule_opt(options, arg);
4711 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
4712 return parse_ws_error_highlight_opt(options, arg);
4713 else if (!strcmp(arg, "--ita-invisible-in-index"))
4714 options->ita_invisible_in_index = 1;
4715 else if (!strcmp(arg, "--ita-visible-in-index"))
4716 options->ita_invisible_in_index = 0;
4719 else if (!strcmp(arg, "-z"))
4720 options->line_termination = 0;
4721 else if ((argcount = short_opt('l', av, &optarg))) {
4722 options->rename_limit = strtoul(optarg, NULL, 10);
4725 else if ((argcount = short_opt('S', av, &optarg))) {
4726 options->pickaxe = optarg;
4727 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
4729 } else if ((argcount = short_opt('G', av, &optarg))) {
4730 options->pickaxe = optarg;
4731 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
4734 else if (!strcmp(arg, "--pickaxe-all"))
4735 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
4736 else if (!strcmp(arg, "--pickaxe-regex"))
4737 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
4738 else if ((argcount = short_opt('O', av, &optarg))) {
4739 options->orderfile = prefix_filename(prefix, optarg);
4742 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
4743 int offending = parse_diff_filter_opt(optarg, options);
4745 die("unknown change class '%c' in --diff-filter=%s",
4749 else if (!strcmp(arg, "--no-abbrev"))
4750 options->abbrev = 0;
4751 else if (!strcmp(arg, "--abbrev"))
4752 options->abbrev = DEFAULT_ABBREV;
4753 else if (skip_prefix(arg, "--abbrev=", &arg)) {
4754 options->abbrev = strtoul(arg, NULL, 10);
4755 if (options->abbrev < MINIMUM_ABBREV)
4756 options->abbrev = MINIMUM_ABBREV;
4757 else if (40 < options->abbrev)
4758 options->abbrev = 40;
4760 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
4761 options->a_prefix = optarg;
4764 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
4765 options->line_prefix = optarg;
4766 options->line_prefix_length = strlen(options->line_prefix);
4767 graph_setup_line_prefix(options);
4770 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
4771 options->b_prefix = optarg;
4774 else if (!strcmp(arg, "--no-prefix"))
4775 options->a_prefix = options->b_prefix = "";
4776 else if (opt_arg(arg, '\0', "inter-hunk-context",
4777 &options->interhunkcontext))
4779 else if (!strcmp(arg, "-W"))
4780 options->flags.funccontext = 1;
4781 else if (!strcmp(arg, "--function-context"))
4782 options->flags.funccontext = 1;
4783 else if (!strcmp(arg, "--no-function-context"))
4784 options->flags.funccontext = 0;
4785 else if ((argcount = parse_long_opt("output", av, &optarg))) {
4786 char *path = prefix_filename(prefix, optarg);
4787 options->file = xfopen(path, "w");
4788 options->close_file = 1;
4789 if (options->use_color != GIT_COLOR_ALWAYS)
4790 options->use_color = GIT_COLOR_NEVER;
4798 int parse_rename_score(const char **cp_p)
4800 unsigned long num, scale;
4802 const char *cp = *cp_p;
4809 if ( !dot && ch == '.' ) {
4812 } else if ( ch == '%' ) {
4813 scale = dot ? scale*100 : 100;
4814 cp++; /* % is always at the end */
4816 } else if ( ch >= '0' && ch <= '9' ) {
4817 if ( scale < 100000 ) {
4819 num = (num*10) + (ch-'0');
4828 /* user says num divided by scale and we say internally that
4829 * is MAX_SCORE * num / scale.
4831 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4834 static int diff_scoreopt_parse(const char *opt)
4836 int opt1, opt2, cmd;
4842 /* convert the long-form arguments into short-form versions */
4843 if (skip_prefix(opt, "break-rewrites", &opt)) {
4844 if (*opt == 0 || *opt++ == '=')
4846 } else if (skip_prefix(opt, "find-copies", &opt)) {
4847 if (*opt == 0 || *opt++ == '=')
4849 } else if (skip_prefix(opt, "find-renames", &opt)) {
4850 if (*opt == 0 || *opt++ == '=')
4854 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4855 return -1; /* that is not a -M, -C, or -B option */
4857 opt1 = parse_rename_score(&opt);
4863 else if (*opt != '/')
4864 return -1; /* we expect -B80/99 or -B80 */
4867 opt2 = parse_rename_score(&opt);
4872 return opt1 | (opt2 << 16);
4875 struct diff_queue_struct diff_queued_diff;
4877 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4879 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4880 queue->queue[queue->nr++] = dp;
4883 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4884 struct diff_filespec *one,
4885 struct diff_filespec *two)
4887 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4895 void diff_free_filepair(struct diff_filepair *p)
4897 free_filespec(p->one);
4898 free_filespec(p->two);
4902 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
4907 /* Do we want all 40 hex characters? */
4908 if (len == GIT_SHA1_HEXSZ)
4909 return oid_to_hex(oid);
4911 /* An abbreviated value is fine, possibly followed by an ellipsis. */
4912 abbrev = diff_abbrev_oid(oid, len);
4914 if (!print_sha1_ellipsis())
4917 abblen = strlen(abbrev);
4920 * In well-behaved cases, where the abbreviated result is the
4921 * same as the requested length, append three dots after the
4922 * abbreviation (hence the whole logic is limited to the case
4923 * where abblen < 37); when the actual abbreviated result is a
4924 * bit longer than the requested length, we reduce the number
4925 * of dots so that they match the well-behaved ones. However,
4926 * if the actual abbreviation is longer than the requested
4927 * length by more than three, we give up on aligning, and add
4928 * three dots anyway, to indicate that the output is not the
4929 * full object name. Yes, this may be suboptimal, but this
4930 * appears only in "diff --raw --abbrev" output and it is not
4931 * worth the effort to change it now. Note that this would
4932 * likely to work fine when the automatic sizing of default
4933 * abbreviation length is used--we would be fed -1 in "len" in
4934 * that case, and will end up always appending three-dots, but
4935 * the automatic sizing is supposed to give abblen that ensures
4936 * uniqueness across all objects (statistically speaking).
4938 if (abblen < GIT_SHA1_HEXSZ - 3) {
4939 static char hex[GIT_MAX_HEXSZ + 1];
4940 if (len < abblen && abblen <= len + 2)
4941 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
4943 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
4947 return oid_to_hex(oid);
4950 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4952 int line_termination = opt->line_termination;
4953 int inter_name_termination = line_termination ? '\t' : '\0';
4955 fprintf(opt->file, "%s", diff_line_prefix(opt));
4956 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
4957 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
4958 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
4959 fprintf(opt->file, "%s ",
4960 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
4963 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
4964 inter_name_termination);
4966 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
4969 if (p->status == DIFF_STATUS_COPIED ||
4970 p->status == DIFF_STATUS_RENAMED) {
4971 const char *name_a, *name_b;
4972 name_a = p->one->path;
4973 name_b = p->two->path;
4974 strip_prefix(opt->prefix_length, &name_a, &name_b);
4975 write_name_quoted(name_a, opt->file, inter_name_termination);
4976 write_name_quoted(name_b, opt->file, line_termination);
4978 const char *name_a, *name_b;
4979 name_a = p->one->mode ? p->one->path : p->two->path;
4981 strip_prefix(opt->prefix_length, &name_a, &name_b);
4982 write_name_quoted(name_a, opt->file, line_termination);
4986 int diff_unmodified_pair(struct diff_filepair *p)
4988 /* This function is written stricter than necessary to support
4989 * the currently implemented transformers, but the idea is to
4990 * let transformers to produce diff_filepairs any way they want,
4991 * and filter and clean them up here before producing the output.
4993 struct diff_filespec *one = p->one, *two = p->two;
4995 if (DIFF_PAIR_UNMERGED(p))
4996 return 0; /* unmerged is interesting */
4998 /* deletion, addition, mode or type change
4999 * and rename are all interesting.
5001 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5002 DIFF_PAIR_MODE_CHANGED(p) ||
5003 strcmp(one->path, two->path))
5006 /* both are valid and point at the same path. that is, we are
5007 * dealing with a change.
5009 if (one->oid_valid && two->oid_valid &&
5010 !oidcmp(&one->oid, &two->oid) &&
5011 !one->dirty_submodule && !two->dirty_submodule)
5012 return 1; /* no change */
5013 if (!one->oid_valid && !two->oid_valid)
5014 return 1; /* both look at the same file on the filesystem. */
5018 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5020 if (diff_unmodified_pair(p))
5023 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5024 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5025 return; /* no tree diffs in patch format */
5030 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5031 struct diffstat_t *diffstat)
5033 if (diff_unmodified_pair(p))
5036 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5037 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5038 return; /* no useful stat for tree diffs */
5040 run_diffstat(p, o, diffstat);
5043 static void diff_flush_checkdiff(struct diff_filepair *p,
5044 struct diff_options *o)
5046 if (diff_unmodified_pair(p))
5049 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5050 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5051 return; /* nothing to check in tree diffs */
5053 run_checkdiff(p, o);
5056 int diff_queue_is_empty(void)
5058 struct diff_queue_struct *q = &diff_queued_diff;
5060 for (i = 0; i < q->nr; i++)
5061 if (!diff_unmodified_pair(q->queue[i]))
5067 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5069 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5072 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5074 s->oid_valid ? oid_to_hex(&s->oid) : "");
5075 fprintf(stderr, "queue[%d] %s size %lu\n",
5080 void diff_debug_filepair(const struct diff_filepair *p, int i)
5082 diff_debug_filespec(p->one, i, "one");
5083 diff_debug_filespec(p->two, i, "two");
5084 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5085 p->score, p->status ? p->status : '?',
5086 p->one->rename_used, p->broken_pair);
5089 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5093 fprintf(stderr, "%s\n", msg);
5094 fprintf(stderr, "q->nr = %d\n", q->nr);
5095 for (i = 0; i < q->nr; i++) {
5096 struct diff_filepair *p = q->queue[i];
5097 diff_debug_filepair(p, i);
5102 static void diff_resolve_rename_copy(void)
5105 struct diff_filepair *p;
5106 struct diff_queue_struct *q = &diff_queued_diff;
5108 diff_debug_queue("resolve-rename-copy", q);
5110 for (i = 0; i < q->nr; i++) {
5112 p->status = 0; /* undecided */
5113 if (DIFF_PAIR_UNMERGED(p))
5114 p->status = DIFF_STATUS_UNMERGED;
5115 else if (!DIFF_FILE_VALID(p->one))
5116 p->status = DIFF_STATUS_ADDED;
5117 else if (!DIFF_FILE_VALID(p->two))
5118 p->status = DIFF_STATUS_DELETED;
5119 else if (DIFF_PAIR_TYPE_CHANGED(p))
5120 p->status = DIFF_STATUS_TYPE_CHANGED;
5122 /* from this point on, we are dealing with a pair
5123 * whose both sides are valid and of the same type, i.e.
5124 * either in-place edit or rename/copy edit.
5126 else if (DIFF_PAIR_RENAME(p)) {
5128 * A rename might have re-connected a broken
5129 * pair up, causing the pathnames to be the
5130 * same again. If so, that's not a rename at
5131 * all, just a modification..
5133 * Otherwise, see if this source was used for
5134 * multiple renames, in which case we decrement
5135 * the count, and call it a copy.
5137 if (!strcmp(p->one->path, p->two->path))
5138 p->status = DIFF_STATUS_MODIFIED;
5139 else if (--p->one->rename_used > 0)
5140 p->status = DIFF_STATUS_COPIED;
5142 p->status = DIFF_STATUS_RENAMED;
5144 else if (oidcmp(&p->one->oid, &p->two->oid) ||
5145 p->one->mode != p->two->mode ||
5146 p->one->dirty_submodule ||
5147 p->two->dirty_submodule ||
5148 is_null_oid(&p->one->oid))
5149 p->status = DIFF_STATUS_MODIFIED;
5151 /* This is a "no-change" entry and should not
5152 * happen anymore, but prepare for broken callers.
5154 error("feeding unmodified %s to diffcore",
5156 p->status = DIFF_STATUS_UNKNOWN;
5159 diff_debug_queue("resolve-rename-copy done", q);
5162 static int check_pair_status(struct diff_filepair *p)
5164 switch (p->status) {
5165 case DIFF_STATUS_UNKNOWN:
5168 die("internal error in diff-resolve-rename-copy");
5174 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5176 int fmt = opt->output_format;
5178 if (fmt & DIFF_FORMAT_CHECKDIFF)
5179 diff_flush_checkdiff(p, opt);
5180 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5181 diff_flush_raw(p, opt);
5182 else if (fmt & DIFF_FORMAT_NAME) {
5183 const char *name_a, *name_b;
5184 name_a = p->two->path;
5186 strip_prefix(opt->prefix_length, &name_a, &name_b);
5187 fprintf(opt->file, "%s", diff_line_prefix(opt));
5188 write_name_quoted(name_a, opt->file, opt->line_termination);
5192 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5194 struct strbuf sb = STRBUF_INIT;
5196 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5198 strbuf_addf(&sb, " %s ", newdelete);
5200 quote_c_style(fs->path, &sb, NULL, 0);
5201 strbuf_addch(&sb, '\n');
5202 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5204 strbuf_release(&sb);
5207 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5210 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5211 struct strbuf sb = STRBUF_INIT;
5212 strbuf_addf(&sb, " mode change %06o => %06o",
5213 p->one->mode, p->two->mode);
5215 strbuf_addch(&sb, ' ');
5216 quote_c_style(p->two->path, &sb, NULL, 0);
5218 strbuf_addch(&sb, '\n');
5219 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5221 strbuf_release(&sb);
5225 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5226 struct diff_filepair *p)
5228 struct strbuf sb = STRBUF_INIT;
5229 char *names = pprint_rename(p->one->path, p->two->path);
5230 strbuf_addf(&sb, " %s %s (%d%%)\n",
5231 renamecopy, names, similarity_index(p));
5233 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5235 show_mode_change(opt, p, 0);
5236 strbuf_release(&sb);
5239 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5242 case DIFF_STATUS_DELETED:
5243 show_file_mode_name(opt, "delete", p->one);
5245 case DIFF_STATUS_ADDED:
5246 show_file_mode_name(opt, "create", p->two);
5248 case DIFF_STATUS_COPIED:
5249 show_rename_copy(opt, "copy", p);
5251 case DIFF_STATUS_RENAMED:
5252 show_rename_copy(opt, "rename", p);
5256 struct strbuf sb = STRBUF_INIT;
5257 strbuf_addstr(&sb, " rewrite ");
5258 quote_c_style(p->two->path, &sb, NULL, 0);
5259 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5260 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5262 strbuf_release(&sb);
5264 show_mode_change(opt, p, !p->score);
5274 static int remove_space(char *line, int len)
5280 for (i = 0; i < len; i++)
5281 if (!isspace((c = line[i])))
5287 static void patch_id_consume(void *priv, char *line, unsigned long len)
5289 struct patch_id_t *data = priv;
5292 /* Ignore line numbers when computing the SHA1 of the patch */
5293 if (starts_with(line, "@@ -"))
5296 new_len = remove_space(line, len);
5298 git_SHA1_Update(data->ctx, line, new_len);
5299 data->patchlen += new_len;
5302 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
5304 git_SHA1_Update(ctx, str, strlen(str));
5307 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
5309 /* large enough for 2^32 in octal */
5311 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
5312 git_SHA1_Update(ctx, buf, len);
5315 /* returns 0 upon success, and writes result into sha1 */
5316 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5318 struct diff_queue_struct *q = &diff_queued_diff;
5321 struct patch_id_t data;
5323 git_SHA1_Init(&ctx);
5324 memset(&data, 0, sizeof(struct patch_id_t));
5327 for (i = 0; i < q->nr; i++) {
5331 struct diff_filepair *p = q->queue[i];
5334 memset(&xpp, 0, sizeof(xpp));
5335 memset(&xecfg, 0, sizeof(xecfg));
5337 return error("internal diff status error");
5338 if (p->status == DIFF_STATUS_UNKNOWN)
5340 if (diff_unmodified_pair(p))
5342 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5343 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5345 if (DIFF_PAIR_UNMERGED(p))
5348 diff_fill_oid_info(p->one);
5349 diff_fill_oid_info(p->two);
5351 len1 = remove_space(p->one->path, strlen(p->one->path));
5352 len2 = remove_space(p->two->path, strlen(p->two->path));
5353 patch_id_add_string(&ctx, "diff--git");
5354 patch_id_add_string(&ctx, "a/");
5355 git_SHA1_Update(&ctx, p->one->path, len1);
5356 patch_id_add_string(&ctx, "b/");
5357 git_SHA1_Update(&ctx, p->two->path, len2);
5359 if (p->one->mode == 0) {
5360 patch_id_add_string(&ctx, "newfilemode");
5361 patch_id_add_mode(&ctx, p->two->mode);
5362 patch_id_add_string(&ctx, "---/dev/null");
5363 patch_id_add_string(&ctx, "+++b/");
5364 git_SHA1_Update(&ctx, p->two->path, len2);
5365 } else if (p->two->mode == 0) {
5366 patch_id_add_string(&ctx, "deletedfilemode");
5367 patch_id_add_mode(&ctx, p->one->mode);
5368 patch_id_add_string(&ctx, "---a/");
5369 git_SHA1_Update(&ctx, p->one->path, len1);
5370 patch_id_add_string(&ctx, "+++/dev/null");
5372 patch_id_add_string(&ctx, "---a/");
5373 git_SHA1_Update(&ctx, p->one->path, len1);
5374 patch_id_add_string(&ctx, "+++b/");
5375 git_SHA1_Update(&ctx, p->two->path, len2);
5378 if (diff_header_only)
5381 if (fill_mmfile(&mf1, p->one) < 0 ||
5382 fill_mmfile(&mf2, p->two) < 0)
5383 return error("unable to read files to diff");
5385 if (diff_filespec_is_binary(p->one) ||
5386 diff_filespec_is_binary(p->two)) {
5387 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5389 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5397 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
5399 return error("unable to generate patch-id diff for %s",
5403 git_SHA1_Final(oid->hash, &ctx);
5407 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5409 struct diff_queue_struct *q = &diff_queued_diff;
5411 int result = diff_get_patch_id(options, oid, diff_header_only);
5413 for (i = 0; i < q->nr; i++)
5414 diff_free_filepair(q->queue[i]);
5417 DIFF_QUEUE_CLEAR(q);
5422 static int is_summary_empty(const struct diff_queue_struct *q)
5426 for (i = 0; i < q->nr; i++) {
5427 const struct diff_filepair *p = q->queue[i];
5429 switch (p->status) {
5430 case DIFF_STATUS_DELETED:
5431 case DIFF_STATUS_ADDED:
5432 case DIFF_STATUS_COPIED:
5433 case DIFF_STATUS_RENAMED:
5438 if (p->one->mode && p->two->mode &&
5439 p->one->mode != p->two->mode)
5447 static const char rename_limit_warning[] =
5448 N_("inexact rename detection was skipped due to too many files.");
5450 static const char degrade_cc_to_c_warning[] =
5451 N_("only found copies from modified paths due to too many files.");
5453 static const char rename_limit_advice[] =
5454 N_("you may want to set your %s variable to at least "
5455 "%d and retry the command.");
5457 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
5461 warning(_(degrade_cc_to_c_warning));
5463 warning(_(rename_limit_warning));
5467 warning(_(rename_limit_advice), varname, needed);
5470 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
5473 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
5474 struct diff_queue_struct *q = &diff_queued_diff;
5476 if (WSEH_NEW & WS_RULE_MASK)
5477 die("BUG: WS rules bit mask overlaps with diff symbol flags");
5480 o->emitted_symbols = &esm;
5482 for (i = 0; i < q->nr; i++) {
5483 struct diff_filepair *p = q->queue[i];
5484 if (check_pair_status(p))
5485 diff_flush_patch(p, o);
5488 if (o->emitted_symbols) {
5489 if (o->color_moved) {
5490 struct hashmap add_lines, del_lines;
5492 hashmap_init(&del_lines,
5493 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5494 hashmap_init(&add_lines,
5495 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5497 add_lines_to_move_detection(o, &add_lines, &del_lines);
5498 mark_color_as_moved(o, &add_lines, &del_lines);
5499 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
5502 hashmap_free(&add_lines, 0);
5503 hashmap_free(&del_lines, 0);
5506 for (i = 0; i < esm.nr; i++)
5507 emit_diff_symbol_from_struct(o, &esm.buf[i]);
5509 for (i = 0; i < esm.nr; i++)
5510 free((void *)esm.buf[i].line);
5515 void diff_flush(struct diff_options *options)
5517 struct diff_queue_struct *q = &diff_queued_diff;
5518 int i, output_format = options->output_format;
5520 int dirstat_by_line = 0;
5523 * Order: raw, stat, summary, patch
5524 * or: name/name-status/checkdiff (other bits clear)
5529 if (output_format & (DIFF_FORMAT_RAW |
5531 DIFF_FORMAT_NAME_STATUS |
5532 DIFF_FORMAT_CHECKDIFF)) {
5533 for (i = 0; i < q->nr; i++) {
5534 struct diff_filepair *p = q->queue[i];
5535 if (check_pair_status(p))
5536 flush_one_pair(p, options);
5541 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
5542 dirstat_by_line = 1;
5544 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
5546 struct diffstat_t diffstat;
5548 memset(&diffstat, 0, sizeof(struct diffstat_t));
5549 for (i = 0; i < q->nr; i++) {
5550 struct diff_filepair *p = q->queue[i];
5551 if (check_pair_status(p))
5552 diff_flush_stat(p, options, &diffstat);
5554 if (output_format & DIFF_FORMAT_NUMSTAT)
5555 show_numstat(&diffstat, options);
5556 if (output_format & DIFF_FORMAT_DIFFSTAT)
5557 show_stats(&diffstat, options);
5558 if (output_format & DIFF_FORMAT_SHORTSTAT)
5559 show_shortstats(&diffstat, options);
5560 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
5561 show_dirstat_by_line(&diffstat, options);
5562 free_diffstat_info(&diffstat);
5565 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
5566 show_dirstat(options);
5568 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
5569 for (i = 0; i < q->nr; i++) {
5570 diff_summary(options, q->queue[i]);
5575 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
5576 options->flags.exit_with_status &&
5577 options->flags.diff_from_contents) {
5579 * run diff_flush_patch for the exit status. setting
5580 * options->file to /dev/null should be safe, because we
5581 * aren't supposed to produce any output anyway.
5583 if (options->close_file)
5584 fclose(options->file);
5585 options->file = xfopen("/dev/null", "w");
5586 options->close_file = 1;
5587 options->color_moved = 0;
5588 for (i = 0; i < q->nr; i++) {
5589 struct diff_filepair *p = q->queue[i];
5590 if (check_pair_status(p))
5591 diff_flush_patch(p, options);
5592 if (options->found_changes)
5597 if (output_format & DIFF_FORMAT_PATCH) {
5599 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
5600 if (options->stat_sep)
5601 /* attach patch instead of inline */
5602 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
5606 diff_flush_patch_all_file_pairs(options);
5609 if (output_format & DIFF_FORMAT_CALLBACK)
5610 options->format_callback(q, options, options->format_callback_data);
5612 for (i = 0; i < q->nr; i++)
5613 diff_free_filepair(q->queue[i]);
5616 DIFF_QUEUE_CLEAR(q);
5617 if (options->close_file)
5618 fclose(options->file);
5621 * Report the content-level differences with HAS_CHANGES;
5622 * diff_addremove/diff_change does not set the bit when
5623 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
5625 if (options->flags.diff_from_contents) {
5626 if (options->found_changes)
5627 options->flags.has_changes = 1;
5629 options->flags.has_changes = 0;
5633 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
5635 return (((p->status == DIFF_STATUS_MODIFIED) &&
5637 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
5639 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
5640 ((p->status != DIFF_STATUS_MODIFIED) &&
5641 filter_bit_tst(p->status, options)));
5644 static void diffcore_apply_filter(struct diff_options *options)
5647 struct diff_queue_struct *q = &diff_queued_diff;
5648 struct diff_queue_struct outq;
5650 DIFF_QUEUE_CLEAR(&outq);
5652 if (!options->filter)
5655 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
5657 for (i = found = 0; !found && i < q->nr; i++) {
5658 if (match_filter(options, q->queue[i]))
5664 /* otherwise we will clear the whole queue
5665 * by copying the empty outq at the end of this
5666 * function, but first clear the current entries
5669 for (i = 0; i < q->nr; i++)
5670 diff_free_filepair(q->queue[i]);
5673 /* Only the matching ones */
5674 for (i = 0; i < q->nr; i++) {
5675 struct diff_filepair *p = q->queue[i];
5676 if (match_filter(options, p))
5679 diff_free_filepair(p);
5686 /* Check whether two filespecs with the same mode and size are identical */
5687 static int diff_filespec_is_identical(struct diff_filespec *one,
5688 struct diff_filespec *two)
5690 if (S_ISGITLINK(one->mode))
5692 if (diff_populate_filespec(one, 0))
5694 if (diff_populate_filespec(two, 0))
5696 return !memcmp(one->data, two->data, one->size);
5699 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
5701 if (p->done_skip_stat_unmatch)
5702 return p->skip_stat_unmatch_result;
5704 p->done_skip_stat_unmatch = 1;
5705 p->skip_stat_unmatch_result = 0;
5707 * 1. Entries that come from stat info dirtiness
5708 * always have both sides (iow, not create/delete),
5709 * one side of the object name is unknown, with
5710 * the same mode and size. Keep the ones that
5711 * do not match these criteria. They have real
5714 * 2. At this point, the file is known to be modified,
5715 * with the same mode and size, and the object
5716 * name of one side is unknown. Need to inspect
5717 * the identical contents.
5719 if (!DIFF_FILE_VALID(p->one) || /* (1) */
5720 !DIFF_FILE_VALID(p->two) ||
5721 (p->one->oid_valid && p->two->oid_valid) ||
5722 (p->one->mode != p->two->mode) ||
5723 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
5724 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
5725 (p->one->size != p->two->size) ||
5726 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
5727 p->skip_stat_unmatch_result = 1;
5728 return p->skip_stat_unmatch_result;
5731 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
5734 struct diff_queue_struct *q = &diff_queued_diff;
5735 struct diff_queue_struct outq;
5736 DIFF_QUEUE_CLEAR(&outq);
5738 for (i = 0; i < q->nr; i++) {
5739 struct diff_filepair *p = q->queue[i];
5741 if (diff_filespec_check_stat_unmatch(p))
5745 * The caller can subtract 1 from skip_stat_unmatch
5746 * to determine how many paths were dirty only
5747 * due to stat info mismatch.
5749 if (!diffopt->flags.no_index)
5750 diffopt->skip_stat_unmatch++;
5751 diff_free_filepair(p);
5758 static int diffnamecmp(const void *a_, const void *b_)
5760 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
5761 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
5762 const char *name_a, *name_b;
5764 name_a = a->one ? a->one->path : a->two->path;
5765 name_b = b->one ? b->one->path : b->two->path;
5766 return strcmp(name_a, name_b);
5769 void diffcore_fix_diff_index(struct diff_options *options)
5771 struct diff_queue_struct *q = &diff_queued_diff;
5772 QSORT(q->queue, q->nr, diffnamecmp);
5775 void diffcore_std(struct diff_options *options)
5777 /* NOTE please keep the following in sync with diff_tree_combined() */
5778 if (options->skip_stat_unmatch)
5779 diffcore_skip_stat_unmatch(options);
5780 if (!options->found_follow) {
5781 /* See try_to_follow_renames() in tree-diff.c */
5782 if (options->break_opt != -1)
5783 diffcore_break(options->break_opt);
5784 if (options->detect_rename)
5785 diffcore_rename(options);
5786 if (options->break_opt != -1)
5787 diffcore_merge_broken();
5789 if (options->pickaxe)
5790 diffcore_pickaxe(options);
5791 if (options->orderfile)
5792 diffcore_order(options->orderfile);
5793 if (!options->found_follow)
5794 /* See try_to_follow_renames() in tree-diff.c */
5795 diff_resolve_rename_copy();
5796 diffcore_apply_filter(options);
5798 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
5799 options->flags.has_changes = 1;
5801 options->flags.has_changes = 0;
5803 options->found_follow = 0;
5806 int diff_result_code(struct diff_options *opt, int status)
5810 diff_warn_rename_limit("diff.renameLimit",
5811 opt->needed_rename_limit,
5812 opt->degraded_cc_to_c);
5813 if (!opt->flags.exit_with_status &&
5814 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
5816 if (opt->flags.exit_with_status &&
5817 opt->flags.has_changes)
5819 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
5820 opt->flags.check_failed)
5825 int diff_can_quit_early(struct diff_options *opt)
5827 return (opt->flags.quick &&
5829 opt->flags.has_changes);
5833 * Shall changes to this submodule be ignored?
5835 * Submodule changes can be configured to be ignored separately for each path,
5836 * but that configuration can be overridden from the command line.
5838 static int is_submodule_ignored(const char *path, struct diff_options *options)
5841 struct diff_flags orig_flags = options->flags;
5842 if (!options->flags.override_submodule_config)
5843 set_diffopt_flags_from_submodule_config(options, path);
5844 if (options->flags.ignore_submodules)
5846 options->flags = orig_flags;
5850 void diff_addremove(struct diff_options *options,
5851 int addremove, unsigned mode,
5852 const struct object_id *oid,
5854 const char *concatpath, unsigned dirty_submodule)
5856 struct diff_filespec *one, *two;
5858 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
5861 /* This may look odd, but it is a preparation for
5862 * feeding "there are unchanged files which should
5863 * not produce diffs, but when you are doing copy
5864 * detection you would need them, so here they are"
5865 * entries to the diff-core. They will be prefixed
5866 * with something like '=' or '*' (I haven't decided
5867 * which but should not make any difference).
5868 * Feeding the same new and old to diff_change()
5869 * also has the same effect.
5870 * Before the final output happens, they are pruned after
5871 * merged into rename/copy pairs as appropriate.
5873 if (options->flags.reverse_diff)
5874 addremove = (addremove == '+' ? '-' :
5875 addremove == '-' ? '+' : addremove);
5877 if (options->prefix &&
5878 strncmp(concatpath, options->prefix, options->prefix_length))
5881 one = alloc_filespec(concatpath);
5882 two = alloc_filespec(concatpath);
5884 if (addremove != '+')
5885 fill_filespec(one, oid, oid_valid, mode);
5886 if (addremove != '-') {
5887 fill_filespec(two, oid, oid_valid, mode);
5888 two->dirty_submodule = dirty_submodule;
5891 diff_queue(&diff_queued_diff, one, two);
5892 if (!options->flags.diff_from_contents)
5893 options->flags.has_changes = 1;
5896 void diff_change(struct diff_options *options,
5897 unsigned old_mode, unsigned new_mode,
5898 const struct object_id *old_oid,
5899 const struct object_id *new_oid,
5900 int old_oid_valid, int new_oid_valid,
5901 const char *concatpath,
5902 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5904 struct diff_filespec *one, *two;
5905 struct diff_filepair *p;
5907 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
5908 is_submodule_ignored(concatpath, options))
5911 if (options->flags.reverse_diff) {
5912 SWAP(old_mode, new_mode);
5913 SWAP(old_oid, new_oid);
5914 SWAP(old_oid_valid, new_oid_valid);
5915 SWAP(old_dirty_submodule, new_dirty_submodule);
5918 if (options->prefix &&
5919 strncmp(concatpath, options->prefix, options->prefix_length))
5922 one = alloc_filespec(concatpath);
5923 two = alloc_filespec(concatpath);
5924 fill_filespec(one, old_oid, old_oid_valid, old_mode);
5925 fill_filespec(two, new_oid, new_oid_valid, new_mode);
5926 one->dirty_submodule = old_dirty_submodule;
5927 two->dirty_submodule = new_dirty_submodule;
5928 p = diff_queue(&diff_queued_diff, one, two);
5930 if (options->flags.diff_from_contents)
5933 if (options->flags.quick && options->skip_stat_unmatch &&
5934 !diff_filespec_check_stat_unmatch(p))
5937 options->flags.has_changes = 1;
5940 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
5942 struct diff_filepair *pair;
5943 struct diff_filespec *one, *two;
5945 if (options->prefix &&
5946 strncmp(path, options->prefix, options->prefix_length))
5949 one = alloc_filespec(path);
5950 two = alloc_filespec(path);
5951 pair = diff_queue(&diff_queued_diff, one, two);
5952 pair->is_unmerged = 1;
5956 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
5959 struct diff_tempfile *temp;
5960 const char *argv[3];
5961 const char **arg = argv;
5962 struct child_process child = CHILD_PROCESS_INIT;
5963 struct strbuf buf = STRBUF_INIT;
5966 temp = prepare_temp_file(spec->path, spec);
5968 *arg++ = temp->name;
5971 child.use_shell = 1;
5974 if (start_command(&child)) {
5979 if (strbuf_read(&buf, child.out, 0) < 0)
5980 err = error("error reading from textconv command '%s'", pgm);
5983 if (finish_command(&child) || err) {
5984 strbuf_release(&buf);
5990 return strbuf_detach(&buf, outsize);
5993 size_t fill_textconv(struct userdiff_driver *driver,
5994 struct diff_filespec *df,
6000 if (!DIFF_FILE_VALID(df)) {
6004 if (diff_populate_filespec(df, 0))
6005 die("unable to read files to diff");
6010 if (!driver->textconv)
6011 die("BUG: fill_textconv called with non-textconv driver");
6013 if (driver->textconv_cache && df->oid_valid) {
6014 *outbuf = notes_cache_get(driver->textconv_cache,
6021 *outbuf = run_textconv(driver->textconv, df, &size);
6023 die("unable to read files to diff");
6025 if (driver->textconv_cache && df->oid_valid) {
6026 /* ignore errors, as we might be in a readonly repository */
6027 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6030 * we could save up changes and flush them all at the end,
6031 * but we would need an extra call after all diffing is done.
6032 * Since generating a cache entry is the slow path anyway,
6033 * this extra overhead probably isn't a big deal.
6035 notes_cache_write(driver->textconv_cache);
6041 int textconv_object(const char *path,
6043 const struct object_id *oid,
6046 unsigned long *buf_size)
6048 struct diff_filespec *df;
6049 struct userdiff_driver *textconv;
6051 df = alloc_filespec(path);
6052 fill_filespec(df, oid, oid_valid, mode);
6053 textconv = get_textconv(df);
6059 *buf_size = fill_textconv(textconv, df, buf);
6064 void setup_diff_pager(struct diff_options *opt)
6067 * If the user asked for our exit code, then either they want --quiet
6068 * or --exit-code. We should definitely not bother with a pager in the
6069 * former case, as we will generate no output. Since we still properly
6070 * report our exit code even when a pager is run, we _could_ run a
6071 * pager with --exit-code. But since we have not done so historically,
6072 * and because it is easy to find people oneline advising "git diff
6073 * --exit-code" in hooks and other scripts, we do not do so.
6075 if (!opt->flags.exit_with_status &&
6076 check_pager_config("diff") != 0)