replace-object: allow do_lookup_replace_object to handle arbitrary repositories
[alt-git.git] / diff.c
blob1289df4b1f9f395010e475073c2c5e5ce43976a7
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "config.h"
6 #include "tempfile.h"
7 #include "quote.h"
8 #include "diff.h"
9 #include "diffcore.h"
10 #include "delta.h"
11 #include "xdiff-interface.h"
12 #include "color.h"
13 #include "attr.h"
14 #include "run-command.h"
15 #include "utf8.h"
16 #include "userdiff.h"
17 #include "submodule-config.h"
18 #include "submodule.h"
19 #include "hashmap.h"
20 #include "ll-merge.h"
21 #include "string-list.h"
22 #include "argv-array.h"
23 #include "graph.h"
24 #include "packfile.h"
26 #ifdef NO_FAST_WORKING_DIRECTORY
27 #define FAST_WORKING_DIRECTORY 0
28 #else
29 #define FAST_WORKING_DIRECTORY 1
30 #endif
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] = {
53 GIT_COLOR_RESET,
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"))
80 return DIFF_CONTEXT;
81 if (!strcasecmp(var, "meta"))
82 return DIFF_METAINFO;
83 if (!strcasecmp(var, "frag"))
84 return DIFF_FRAGINFO;
85 if (!strcasecmp(var, "old"))
86 return DIFF_FILE_OLD;
87 if (!strcasecmp(var, "new"))
88 return DIFF_FILE_NEW;
89 if (!strcasecmp(var, "commit"))
90 return DIFF_COMMIT;
91 if (!strcasecmp(var, "whitespace"))
92 return DIFF_WHITESPACE;
93 if (!strcasecmp(var, "func"))
94 return DIFF_FUNCINFO;
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;
111 return -1;
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;
119 int ret = 0;
120 int i;
122 if (*params_copy)
123 string_list_split_in_place(&params, 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)) {
140 char *end;
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))
147 ; /* nothing */
149 if (!*end)
150 options->dirstat_permille = permille;
151 else {
152 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
154 ret++;
156 } else {
157 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
158 ret++;
162 string_list_clear(&params, 0);
163 free(params_copy);
164 return ret;
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;
175 else
176 return -1;
177 return 0;
180 static int git_config_rename(const char *var, const char *value)
182 if (!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)
191 if (!value)
192 return -1;
193 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
194 return 0;
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;
201 return -1;
204 static int parse_one_token(const char **arg, const char *token)
206 const char *rest;
207 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
208 *arg = rest;
209 return 1;
211 return 0;
214 static int parse_ws_error_highlight(const char *arg)
216 const char *orig_arg = arg;
217 unsigned val = 0;
219 while (*arg) {
220 if (parse_one_token(&arg, "none"))
221 val = 0;
222 else if (parse_one_token(&arg, "default"))
223 val = WSEH_NEW;
224 else if (parse_one_token(&arg, "all"))
225 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
226 else if (parse_one_token(&arg, "new"))
227 val |= WSEH_NEW;
228 else if (parse_one_token(&arg, "old"))
229 val |= WSEH_OLD;
230 else if (parse_one_token(&arg, "context"))
231 val |= WSEH_CONTEXT;
232 else {
233 return -1 - (int)(arg - orig_arg);
235 if (*arg)
236 arg++;
238 return val;
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);
256 return 0;
259 static int parse_color_moved(const char *arg)
261 switch (git_parse_maybe_bool(arg)) {
262 case 0:
263 return COLOR_MOVED_NO;
264 case 1:
265 return COLOR_MOVED_DEFAULT;
266 default:
267 break;
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
281 return error(_("color moved setting must be one of 'no', 'default', 'zebra', 'dimmed_zebra', 'plain'"));
284 int git_diff_ui_config(const char *var, const char *value, void *cb)
286 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
287 diff_use_color_default = git_config_colorbool(var, value);
288 return 0;
290 if (!strcmp(var, "diff.colormoved")) {
291 int cm = parse_color_moved(value);
292 if (cm < 0)
293 return -1;
294 diff_color_moved_default = cm;
295 return 0;
297 if (!strcmp(var, "diff.context")) {
298 diff_context_default = git_config_int(var, value);
299 if (diff_context_default < 0)
300 return -1;
301 return 0;
303 if (!strcmp(var, "diff.interhunkcontext")) {
304 diff_interhunk_context_default = git_config_int(var, value);
305 if (diff_interhunk_context_default < 0)
306 return -1;
307 return 0;
309 if (!strcmp(var, "diff.renames")) {
310 diff_detect_rename_default = git_config_rename(var, value);
311 return 0;
313 if (!strcmp(var, "diff.autorefreshindex")) {
314 diff_auto_refresh_index = git_config_bool(var, value);
315 return 0;
317 if (!strcmp(var, "diff.mnemonicprefix")) {
318 diff_mnemonic_prefix = git_config_bool(var, value);
319 return 0;
321 if (!strcmp(var, "diff.noprefix")) {
322 diff_no_prefix = git_config_bool(var, value);
323 return 0;
325 if (!strcmp(var, "diff.statgraphwidth")) {
326 diff_stat_graph_width = git_config_int(var, value);
327 return 0;
329 if (!strcmp(var, "diff.external"))
330 return git_config_string(&external_diff_cmd_cfg, var, value);
331 if (!strcmp(var, "diff.wordregex"))
332 return git_config_string(&diff_word_regex_cfg, var, value);
333 if (!strcmp(var, "diff.orderfile"))
334 return git_config_pathname(&diff_order_file_cfg, var, value);
336 if (!strcmp(var, "diff.ignoresubmodules"))
337 handle_ignore_submodules_arg(&default_diff_options, value);
339 if (!strcmp(var, "diff.submodule")) {
340 if (parse_submodule_params(&default_diff_options, value))
341 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
342 value);
343 return 0;
346 if (!strcmp(var, "diff.algorithm")) {
347 diff_algorithm = parse_algorithm_value(value);
348 if (diff_algorithm < 0)
349 return -1;
350 return 0;
353 if (!strcmp(var, "diff.wserrorhighlight")) {
354 int val = parse_ws_error_highlight(value);
355 if (val < 0)
356 return -1;
357 ws_error_highlight_default = val;
358 return 0;
361 if (git_color_config(var, value, cb) < 0)
362 return -1;
364 return git_diff_basic_config(var, value, cb);
367 int git_diff_basic_config(const char *var, const char *value, void *cb)
369 const char *name;
371 if (!strcmp(var, "diff.renamelimit")) {
372 diff_rename_limit_default = git_config_int(var, value);
373 return 0;
376 if (userdiff_config(var, value) < 0)
377 return -1;
379 if (skip_prefix(var, "diff.color.", &name) ||
380 skip_prefix(var, "color.diff.", &name)) {
381 int slot = parse_diff_color_slot(name);
382 if (slot < 0)
383 return 0;
384 if (!value)
385 return config_error_nonbool(var);
386 return color_parse(value, diff_colors[slot]);
389 /* like GNU diff's --suppress-blank-empty option */
390 if (!strcmp(var, "diff.suppressblankempty") ||
391 /* for backwards compatibility */
392 !strcmp(var, "diff.suppress-blank-empty")) {
393 diff_suppress_blank_empty = git_config_bool(var, value);
394 return 0;
397 if (!strcmp(var, "diff.dirstat")) {
398 struct strbuf errmsg = STRBUF_INIT;
399 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
400 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
401 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
402 errmsg.buf);
403 strbuf_release(&errmsg);
404 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
405 return 0;
408 if (git_diff_heuristic_config(var, value, cb) < 0)
409 return -1;
411 return git_default_config(var, value, cb);
414 static char *quote_two(const char *one, const char *two)
416 int need_one = quote_c_style(one, NULL, NULL, 1);
417 int need_two = quote_c_style(two, NULL, NULL, 1);
418 struct strbuf res = STRBUF_INIT;
420 if (need_one + need_two) {
421 strbuf_addch(&res, '"');
422 quote_c_style(one, &res, NULL, 1);
423 quote_c_style(two, &res, NULL, 1);
424 strbuf_addch(&res, '"');
425 } else {
426 strbuf_addstr(&res, one);
427 strbuf_addstr(&res, two);
429 return strbuf_detach(&res, NULL);
432 static const char *external_diff(void)
434 static const char *external_diff_cmd = NULL;
435 static int done_preparing = 0;
437 if (done_preparing)
438 return external_diff_cmd;
439 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
440 if (!external_diff_cmd)
441 external_diff_cmd = external_diff_cmd_cfg;
442 done_preparing = 1;
443 return external_diff_cmd;
447 * Keep track of files used for diffing. Sometimes such an entry
448 * refers to a temporary file, sometimes to an existing file, and
449 * sometimes to "/dev/null".
451 static struct diff_tempfile {
453 * filename external diff should read from, or NULL if this
454 * entry is currently not in use:
456 const char *name;
458 char hex[GIT_MAX_HEXSZ + 1];
459 char mode[10];
462 * If this diff_tempfile instance refers to a temporary file,
463 * this tempfile object is used to manage its lifetime.
465 struct tempfile *tempfile;
466 } diff_temp[2];
468 struct emit_callback {
469 int color_diff;
470 unsigned ws_rule;
471 int blank_at_eof_in_preimage;
472 int blank_at_eof_in_postimage;
473 int lno_in_preimage;
474 int lno_in_postimage;
475 const char **label_path;
476 struct diff_words_data *diff_words;
477 struct diff_options *opt;
478 struct strbuf *header;
481 static int count_lines(const char *data, int size)
483 int count, ch, completely_empty = 1, nl_just_seen = 0;
484 count = 0;
485 while (0 < size--) {
486 ch = *data++;
487 if (ch == '\n') {
488 count++;
489 nl_just_seen = 1;
490 completely_empty = 0;
492 else {
493 nl_just_seen = 0;
494 completely_empty = 0;
497 if (completely_empty)
498 return 0;
499 if (!nl_just_seen)
500 count++; /* no trailing newline */
501 return count;
504 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
506 if (!DIFF_FILE_VALID(one)) {
507 mf->ptr = (char *)""; /* does not matter */
508 mf->size = 0;
509 return 0;
511 else if (diff_populate_filespec(one, 0))
512 return -1;
514 mf->ptr = one->data;
515 mf->size = one->size;
516 return 0;
519 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
520 static unsigned long diff_filespec_size(struct diff_filespec *one)
522 if (!DIFF_FILE_VALID(one))
523 return 0;
524 diff_populate_filespec(one, CHECK_SIZE_ONLY);
525 return one->size;
528 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
530 char *ptr = mf->ptr;
531 long size = mf->size;
532 int cnt = 0;
534 if (!size)
535 return cnt;
536 ptr += size - 1; /* pointing at the very end */
537 if (*ptr != '\n')
538 ; /* incomplete line */
539 else
540 ptr--; /* skip the last LF */
541 while (mf->ptr < ptr) {
542 char *prev_eol;
543 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
544 if (*prev_eol == '\n')
545 break;
546 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
547 break;
548 cnt++;
549 ptr = prev_eol - 1;
551 return cnt;
554 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
555 struct emit_callback *ecbdata)
557 int l1, l2, at;
558 unsigned ws_rule = ecbdata->ws_rule;
559 l1 = count_trailing_blank(mf1, ws_rule);
560 l2 = count_trailing_blank(mf2, ws_rule);
561 if (l2 <= l1) {
562 ecbdata->blank_at_eof_in_preimage = 0;
563 ecbdata->blank_at_eof_in_postimage = 0;
564 return;
566 at = count_lines(mf1->ptr, mf1->size);
567 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
569 at = count_lines(mf2->ptr, mf2->size);
570 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
573 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
574 int first, const char *line, int len)
576 int has_trailing_newline, has_trailing_carriage_return;
577 int nofirst;
578 FILE *file = o->file;
580 fputs(diff_line_prefix(o), file);
582 if (len == 0) {
583 has_trailing_newline = (first == '\n');
584 has_trailing_carriage_return = (!has_trailing_newline &&
585 (first == '\r'));
586 nofirst = has_trailing_newline || has_trailing_carriage_return;
587 } else {
588 has_trailing_newline = (len > 0 && line[len-1] == '\n');
589 if (has_trailing_newline)
590 len--;
591 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
592 if (has_trailing_carriage_return)
593 len--;
594 nofirst = 0;
597 if (len || !nofirst) {
598 fputs(set, file);
599 if (!nofirst)
600 fputc(first, file);
601 fwrite(line, len, 1, file);
602 fputs(reset, file);
604 if (has_trailing_carriage_return)
605 fputc('\r', file);
606 if (has_trailing_newline)
607 fputc('\n', file);
610 static void emit_line(struct diff_options *o, const char *set, const char *reset,
611 const char *line, int len)
613 emit_line_0(o, set, reset, line[0], line+1, len-1);
616 enum diff_symbol {
617 DIFF_SYMBOL_BINARY_DIFF_HEADER,
618 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
619 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
620 DIFF_SYMBOL_BINARY_DIFF_BODY,
621 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
622 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
623 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
624 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
625 DIFF_SYMBOL_STATS_LINE,
626 DIFF_SYMBOL_WORD_DIFF,
627 DIFF_SYMBOL_STAT_SEP,
628 DIFF_SYMBOL_SUMMARY,
629 DIFF_SYMBOL_SUBMODULE_ADD,
630 DIFF_SYMBOL_SUBMODULE_DEL,
631 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
632 DIFF_SYMBOL_SUBMODULE_MODIFIED,
633 DIFF_SYMBOL_SUBMODULE_HEADER,
634 DIFF_SYMBOL_SUBMODULE_ERROR,
635 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
636 DIFF_SYMBOL_REWRITE_DIFF,
637 DIFF_SYMBOL_BINARY_FILES,
638 DIFF_SYMBOL_HEADER,
639 DIFF_SYMBOL_FILEPAIR_PLUS,
640 DIFF_SYMBOL_FILEPAIR_MINUS,
641 DIFF_SYMBOL_WORDS_PORCELAIN,
642 DIFF_SYMBOL_WORDS,
643 DIFF_SYMBOL_CONTEXT,
644 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
645 DIFF_SYMBOL_PLUS,
646 DIFF_SYMBOL_MINUS,
647 DIFF_SYMBOL_NO_LF_EOF,
648 DIFF_SYMBOL_CONTEXT_FRAGINFO,
649 DIFF_SYMBOL_CONTEXT_MARKER,
650 DIFF_SYMBOL_SEPARATOR
653 * Flags for content lines:
654 * 0..12 are whitespace rules
655 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
656 * 16 is marking if the line is blank at EOF
658 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
659 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
660 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
661 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
662 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
665 * This struct is used when we need to buffer the output of the diff output.
667 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
668 * into the pre/post image file. This pointer could be a union with the
669 * line pointer. By storing an offset into the file instead of the literal line,
670 * we can decrease the memory footprint for the buffered output. At first we
671 * may want to only have indirection for the content lines, but we could also
672 * enhance the state for emitting prefabricated lines, e.g. the similarity
673 * score line or hunk/file headers would only need to store a number or path
674 * and then the output can be constructed later on depending on state.
676 struct emitted_diff_symbol {
677 const char *line;
678 int len;
679 int flags;
680 enum diff_symbol s;
682 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
684 struct emitted_diff_symbols {
685 struct emitted_diff_symbol *buf;
686 int nr, alloc;
688 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
690 static void append_emitted_diff_symbol(struct diff_options *o,
691 struct emitted_diff_symbol *e)
693 struct emitted_diff_symbol *f;
695 ALLOC_GROW(o->emitted_symbols->buf,
696 o->emitted_symbols->nr + 1,
697 o->emitted_symbols->alloc);
698 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
700 memcpy(f, e, sizeof(struct emitted_diff_symbol));
701 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
704 struct moved_entry {
705 struct hashmap_entry ent;
706 const struct emitted_diff_symbol *es;
707 struct moved_entry *next_line;
710 static int moved_entry_cmp(const struct diff_options *diffopt,
711 const struct moved_entry *a,
712 const struct moved_entry *b,
713 const void *keydata)
715 return !xdiff_compare_lines(a->es->line, a->es->len,
716 b->es->line, b->es->len,
717 diffopt->xdl_opts);
720 static struct moved_entry *prepare_entry(struct diff_options *o,
721 int line_no)
723 struct moved_entry *ret = xmalloc(sizeof(*ret));
724 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
726 ret->ent.hash = xdiff_hash_string(l->line, l->len, o->xdl_opts);
727 ret->es = l;
728 ret->next_line = NULL;
730 return ret;
733 static void add_lines_to_move_detection(struct diff_options *o,
734 struct hashmap *add_lines,
735 struct hashmap *del_lines)
737 struct moved_entry *prev_line = NULL;
739 int n;
740 for (n = 0; n < o->emitted_symbols->nr; n++) {
741 struct hashmap *hm;
742 struct moved_entry *key;
744 switch (o->emitted_symbols->buf[n].s) {
745 case DIFF_SYMBOL_PLUS:
746 hm = add_lines;
747 break;
748 case DIFF_SYMBOL_MINUS:
749 hm = del_lines;
750 break;
751 default:
752 prev_line = NULL;
753 continue;
756 key = prepare_entry(o, n);
757 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
758 prev_line->next_line = key;
760 hashmap_add(hm, key);
761 prev_line = key;
765 static int shrink_potential_moved_blocks(struct moved_entry **pmb,
766 int pmb_nr)
768 int lp, rp;
770 /* Shrink the set of potential block to the remaining running */
771 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
772 while (lp < pmb_nr && pmb[lp])
773 lp++;
774 /* lp points at the first NULL now */
776 while (rp > -1 && !pmb[rp])
777 rp--;
778 /* rp points at the last non-NULL */
780 if (lp < pmb_nr && rp > -1 && lp < rp) {
781 pmb[lp] = pmb[rp];
782 pmb[rp] = NULL;
783 rp--;
784 lp++;
788 /* Remember the number of running sets */
789 return rp + 1;
793 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
795 * Otherwise, if the last block has fewer alphanumeric characters than
796 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
797 * that block.
799 * The last block consists of the (n - block_length)'th line up to but not
800 * including the nth line.
802 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
803 * Think of a way to unify them.
805 static void adjust_last_block(struct diff_options *o, int n, int block_length)
807 int i, alnum_count = 0;
808 if (o->color_moved == COLOR_MOVED_PLAIN)
809 return;
810 for (i = 1; i < block_length + 1; i++) {
811 const char *c = o->emitted_symbols->buf[n - i].line;
812 for (; *c; c++) {
813 if (!isalnum(*c))
814 continue;
815 alnum_count++;
816 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
817 return;
820 for (i = 1; i < block_length + 1; i++)
821 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
824 /* Find blocks of moved code, delegate actual coloring decision to helper */
825 static void mark_color_as_moved(struct diff_options *o,
826 struct hashmap *add_lines,
827 struct hashmap *del_lines)
829 struct moved_entry **pmb = NULL; /* potentially moved blocks */
830 int pmb_nr = 0, pmb_alloc = 0;
831 int n, flipped_block = 1, block_length = 0;
834 for (n = 0; n < o->emitted_symbols->nr; n++) {
835 struct hashmap *hm = NULL;
836 struct moved_entry *key;
837 struct moved_entry *match = NULL;
838 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
839 int i;
841 switch (l->s) {
842 case DIFF_SYMBOL_PLUS:
843 hm = del_lines;
844 key = prepare_entry(o, n);
845 match = hashmap_get(hm, key, o);
846 free(key);
847 break;
848 case DIFF_SYMBOL_MINUS:
849 hm = add_lines;
850 key = prepare_entry(o, n);
851 match = hashmap_get(hm, key, o);
852 free(key);
853 break;
854 default:
855 flipped_block = 1;
858 if (!match) {
859 adjust_last_block(o, n, block_length);
860 pmb_nr = 0;
861 block_length = 0;
862 continue;
865 l->flags |= DIFF_SYMBOL_MOVED_LINE;
867 if (o->color_moved == COLOR_MOVED_PLAIN)
868 continue;
870 /* Check any potential block runs, advance each or nullify */
871 for (i = 0; i < pmb_nr; i++) {
872 struct moved_entry *p = pmb[i];
873 struct moved_entry *pnext = (p && p->next_line) ?
874 p->next_line : NULL;
875 if (pnext && !hm->cmpfn(o, pnext, match, NULL)) {
876 pmb[i] = p->next_line;
877 } else {
878 pmb[i] = NULL;
882 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
884 if (pmb_nr == 0) {
886 * The current line is the start of a new block.
887 * Setup the set of potential blocks.
889 for (; match; match = hashmap_get_next(hm, match)) {
890 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
891 pmb[pmb_nr++] = match;
894 flipped_block = (flipped_block + 1) % 2;
896 adjust_last_block(o, n, block_length);
897 block_length = 0;
900 block_length++;
902 if (flipped_block)
903 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
905 adjust_last_block(o, n, block_length);
907 free(pmb);
910 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
911 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
912 static void dim_moved_lines(struct diff_options *o)
914 int n;
915 for (n = 0; n < o->emitted_symbols->nr; n++) {
916 struct emitted_diff_symbol *prev = (n != 0) ?
917 &o->emitted_symbols->buf[n - 1] : NULL;
918 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
919 struct emitted_diff_symbol *next =
920 (n < o->emitted_symbols->nr - 1) ?
921 &o->emitted_symbols->buf[n + 1] : NULL;
923 /* Not a plus or minus line? */
924 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
925 continue;
927 /* Not a moved line? */
928 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
929 continue;
932 * If prev or next are not a plus or minus line,
933 * pretend they don't exist
935 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
936 prev->s != DIFF_SYMBOL_MINUS)
937 prev = NULL;
938 if (next && next->s != DIFF_SYMBOL_PLUS &&
939 next->s != DIFF_SYMBOL_MINUS)
940 next = NULL;
942 /* Inside a block? */
943 if ((prev &&
944 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
945 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
946 (next &&
947 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
948 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
949 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
950 continue;
953 /* Check if we are at an interesting bound: */
954 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
955 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
956 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
957 continue;
958 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
959 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
960 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
961 continue;
964 * The boundary to prev and next are not interesting,
965 * so this line is not interesting as a whole
967 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
971 static void emit_line_ws_markup(struct diff_options *o,
972 const char *set, const char *reset,
973 const char *line, int len, char sign,
974 unsigned ws_rule, int blank_at_eof)
976 const char *ws = NULL;
978 if (o->ws_error_highlight & ws_rule) {
979 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
980 if (!*ws)
981 ws = NULL;
984 if (!ws)
985 emit_line_0(o, set, reset, sign, line, len);
986 else if (blank_at_eof)
987 /* Blank line at EOF - paint '+' as well */
988 emit_line_0(o, ws, reset, sign, line, len);
989 else {
990 /* Emit just the prefix, then the rest. */
991 emit_line_0(o, set, reset, sign, "", 0);
992 ws_check_emit(line, len, ws_rule,
993 o->file, set, reset, ws);
997 static void emit_diff_symbol_from_struct(struct diff_options *o,
998 struct emitted_diff_symbol *eds)
1000 static const char *nneof = " No newline at end of file\n";
1001 const char *context, *reset, *set, *meta, *fraginfo;
1002 struct strbuf sb = STRBUF_INIT;
1004 enum diff_symbol s = eds->s;
1005 const char *line = eds->line;
1006 int len = eds->len;
1007 unsigned flags = eds->flags;
1009 switch (s) {
1010 case DIFF_SYMBOL_NO_LF_EOF:
1011 context = diff_get_color_opt(o, DIFF_CONTEXT);
1012 reset = diff_get_color_opt(o, DIFF_RESET);
1013 putc('\n', o->file);
1014 emit_line_0(o, context, reset, '\\',
1015 nneof, strlen(nneof));
1016 break;
1017 case DIFF_SYMBOL_SUBMODULE_HEADER:
1018 case DIFF_SYMBOL_SUBMODULE_ERROR:
1019 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1020 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1021 case DIFF_SYMBOL_SUMMARY:
1022 case DIFF_SYMBOL_STATS_LINE:
1023 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1024 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1025 emit_line(o, "", "", line, len);
1026 break;
1027 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1028 case DIFF_SYMBOL_CONTEXT_MARKER:
1029 context = diff_get_color_opt(o, DIFF_CONTEXT);
1030 reset = diff_get_color_opt(o, DIFF_RESET);
1031 emit_line(o, context, reset, line, len);
1032 break;
1033 case DIFF_SYMBOL_SEPARATOR:
1034 fprintf(o->file, "%s%c",
1035 diff_line_prefix(o),
1036 o->line_termination);
1037 break;
1038 case DIFF_SYMBOL_CONTEXT:
1039 set = diff_get_color_opt(o, DIFF_CONTEXT);
1040 reset = diff_get_color_opt(o, DIFF_RESET);
1041 emit_line_ws_markup(o, set, reset, line, len, ' ',
1042 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1043 break;
1044 case DIFF_SYMBOL_PLUS:
1045 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1046 DIFF_SYMBOL_MOVED_LINE_ALT |
1047 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1048 case DIFF_SYMBOL_MOVED_LINE |
1049 DIFF_SYMBOL_MOVED_LINE_ALT |
1050 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1051 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1052 break;
1053 case DIFF_SYMBOL_MOVED_LINE |
1054 DIFF_SYMBOL_MOVED_LINE_ALT:
1055 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1056 break;
1057 case DIFF_SYMBOL_MOVED_LINE |
1058 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1059 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1060 break;
1061 case DIFF_SYMBOL_MOVED_LINE:
1062 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1063 break;
1064 default:
1065 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1067 reset = diff_get_color_opt(o, DIFF_RESET);
1068 emit_line_ws_markup(o, set, reset, line, len, '+',
1069 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1070 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1071 break;
1072 case DIFF_SYMBOL_MINUS:
1073 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1074 DIFF_SYMBOL_MOVED_LINE_ALT |
1075 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1076 case DIFF_SYMBOL_MOVED_LINE |
1077 DIFF_SYMBOL_MOVED_LINE_ALT |
1078 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1079 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1080 break;
1081 case DIFF_SYMBOL_MOVED_LINE |
1082 DIFF_SYMBOL_MOVED_LINE_ALT:
1083 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1084 break;
1085 case DIFF_SYMBOL_MOVED_LINE |
1086 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1087 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1088 break;
1089 case DIFF_SYMBOL_MOVED_LINE:
1090 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1091 break;
1092 default:
1093 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1095 reset = diff_get_color_opt(o, DIFF_RESET);
1096 emit_line_ws_markup(o, set, reset, line, len, '-',
1097 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1098 break;
1099 case DIFF_SYMBOL_WORDS_PORCELAIN:
1100 context = diff_get_color_opt(o, DIFF_CONTEXT);
1101 reset = diff_get_color_opt(o, DIFF_RESET);
1102 emit_line(o, context, reset, line, len);
1103 fputs("~\n", o->file);
1104 break;
1105 case DIFF_SYMBOL_WORDS:
1106 context = diff_get_color_opt(o, DIFF_CONTEXT);
1107 reset = diff_get_color_opt(o, DIFF_RESET);
1109 * Skip the prefix character, if any. With
1110 * diff_suppress_blank_empty, there may be
1111 * none.
1113 if (line[0] != '\n') {
1114 line++;
1115 len--;
1117 emit_line(o, context, reset, line, len);
1118 break;
1119 case DIFF_SYMBOL_FILEPAIR_PLUS:
1120 meta = diff_get_color_opt(o, DIFF_METAINFO);
1121 reset = diff_get_color_opt(o, DIFF_RESET);
1122 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1123 line, reset,
1124 strchr(line, ' ') ? "\t" : "");
1125 break;
1126 case DIFF_SYMBOL_FILEPAIR_MINUS:
1127 meta = diff_get_color_opt(o, DIFF_METAINFO);
1128 reset = diff_get_color_opt(o, DIFF_RESET);
1129 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1130 line, reset,
1131 strchr(line, ' ') ? "\t" : "");
1132 break;
1133 case DIFF_SYMBOL_BINARY_FILES:
1134 case DIFF_SYMBOL_HEADER:
1135 fprintf(o->file, "%s", line);
1136 break;
1137 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1138 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1139 break;
1140 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1141 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1142 break;
1143 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1144 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1145 break;
1146 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1147 fputs(diff_line_prefix(o), o->file);
1148 fputc('\n', o->file);
1149 break;
1150 case DIFF_SYMBOL_REWRITE_DIFF:
1151 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1152 reset = diff_get_color_opt(o, DIFF_RESET);
1153 emit_line(o, fraginfo, reset, line, len);
1154 break;
1155 case DIFF_SYMBOL_SUBMODULE_ADD:
1156 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1157 reset = diff_get_color_opt(o, DIFF_RESET);
1158 emit_line(o, set, reset, line, len);
1159 break;
1160 case DIFF_SYMBOL_SUBMODULE_DEL:
1161 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1162 reset = diff_get_color_opt(o, DIFF_RESET);
1163 emit_line(o, set, reset, line, len);
1164 break;
1165 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1166 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1167 diff_line_prefix(o), line);
1168 break;
1169 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1170 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1171 diff_line_prefix(o), line);
1172 break;
1173 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1174 emit_line(o, "", "", " 0 files changed\n",
1175 strlen(" 0 files changed\n"));
1176 break;
1177 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1178 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1179 break;
1180 case DIFF_SYMBOL_WORD_DIFF:
1181 fprintf(o->file, "%.*s", len, line);
1182 break;
1183 case DIFF_SYMBOL_STAT_SEP:
1184 fputs(o->stat_sep, o->file);
1185 break;
1186 default:
1187 die("BUG: unknown diff symbol");
1189 strbuf_release(&sb);
1192 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1193 const char *line, int len, unsigned flags)
1195 struct emitted_diff_symbol e = {line, len, flags, s};
1197 if (o->emitted_symbols)
1198 append_emitted_diff_symbol(o, &e);
1199 else
1200 emit_diff_symbol_from_struct(o, &e);
1203 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1205 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1208 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1210 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1213 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1215 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1216 path, strlen(path), 0);
1219 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1221 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1222 path, strlen(path), 0);
1225 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1227 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1228 header, strlen(header), 0);
1231 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1233 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1236 void diff_emit_submodule_pipethrough(struct diff_options *o,
1237 const char *line, int len)
1239 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1242 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1244 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1245 ecbdata->blank_at_eof_in_preimage &&
1246 ecbdata->blank_at_eof_in_postimage &&
1247 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1248 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1249 return 0;
1250 return ws_blank_line(line, len, ecbdata->ws_rule);
1253 static void emit_add_line(const char *reset,
1254 struct emit_callback *ecbdata,
1255 const char *line, int len)
1257 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1258 if (new_blank_line_at_eof(ecbdata, line, len))
1259 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1261 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1264 static void emit_del_line(const char *reset,
1265 struct emit_callback *ecbdata,
1266 const char *line, int len)
1268 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1269 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1272 static void emit_context_line(const char *reset,
1273 struct emit_callback *ecbdata,
1274 const char *line, int len)
1276 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1277 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1280 static void emit_hunk_header(struct emit_callback *ecbdata,
1281 const char *line, int len)
1283 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1284 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1285 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1286 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1287 static const char atat[2] = { '@', '@' };
1288 const char *cp, *ep;
1289 struct strbuf msgbuf = STRBUF_INIT;
1290 int org_len = len;
1291 int i = 1;
1294 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1295 * it always is at least 10 bytes long.
1297 if (len < 10 ||
1298 memcmp(line, atat, 2) ||
1299 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1300 emit_diff_symbol(ecbdata->opt,
1301 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1302 return;
1304 ep += 2; /* skip over @@ */
1306 /* The hunk header in fraginfo color */
1307 strbuf_addstr(&msgbuf, frag);
1308 strbuf_add(&msgbuf, line, ep - line);
1309 strbuf_addstr(&msgbuf, reset);
1312 * trailing "\r\n"
1314 for ( ; i < 3; i++)
1315 if (line[len - i] == '\r' || line[len - i] == '\n')
1316 len--;
1318 /* blank before the func header */
1319 for (cp = ep; ep - line < len; ep++)
1320 if (*ep != ' ' && *ep != '\t')
1321 break;
1322 if (ep != cp) {
1323 strbuf_addstr(&msgbuf, context);
1324 strbuf_add(&msgbuf, cp, ep - cp);
1325 strbuf_addstr(&msgbuf, reset);
1328 if (ep < line + len) {
1329 strbuf_addstr(&msgbuf, func);
1330 strbuf_add(&msgbuf, ep, line + len - ep);
1331 strbuf_addstr(&msgbuf, reset);
1334 strbuf_add(&msgbuf, line + len, org_len - len);
1335 strbuf_complete_line(&msgbuf);
1336 emit_diff_symbol(ecbdata->opt,
1337 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1338 strbuf_release(&msgbuf);
1341 static struct diff_tempfile *claim_diff_tempfile(void) {
1342 int i;
1343 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1344 if (!diff_temp[i].name)
1345 return diff_temp + i;
1346 die("BUG: diff is failing to clean up its tempfiles");
1349 static void remove_tempfile(void)
1351 int i;
1352 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1353 if (is_tempfile_active(diff_temp[i].tempfile))
1354 delete_tempfile(&diff_temp[i].tempfile);
1355 diff_temp[i].name = NULL;
1359 static void add_line_count(struct strbuf *out, int count)
1361 switch (count) {
1362 case 0:
1363 strbuf_addstr(out, "0,0");
1364 break;
1365 case 1:
1366 strbuf_addstr(out, "1");
1367 break;
1368 default:
1369 strbuf_addf(out, "1,%d", count);
1370 break;
1374 static void emit_rewrite_lines(struct emit_callback *ecb,
1375 int prefix, const char *data, int size)
1377 const char *endp = NULL;
1378 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1380 while (0 < size) {
1381 int len;
1383 endp = memchr(data, '\n', size);
1384 len = endp ? (endp - data + 1) : size;
1385 if (prefix != '+') {
1386 ecb->lno_in_preimage++;
1387 emit_del_line(reset, ecb, data, len);
1388 } else {
1389 ecb->lno_in_postimage++;
1390 emit_add_line(reset, ecb, data, len);
1392 size -= len;
1393 data += len;
1395 if (!endp)
1396 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1399 static void emit_rewrite_diff(const char *name_a,
1400 const char *name_b,
1401 struct diff_filespec *one,
1402 struct diff_filespec *two,
1403 struct userdiff_driver *textconv_one,
1404 struct userdiff_driver *textconv_two,
1405 struct diff_options *o)
1407 int lc_a, lc_b;
1408 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1409 const char *a_prefix, *b_prefix;
1410 char *data_one, *data_two;
1411 size_t size_one, size_two;
1412 struct emit_callback ecbdata;
1413 struct strbuf out = STRBUF_INIT;
1415 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1416 a_prefix = o->b_prefix;
1417 b_prefix = o->a_prefix;
1418 } else {
1419 a_prefix = o->a_prefix;
1420 b_prefix = o->b_prefix;
1423 name_a += (*name_a == '/');
1424 name_b += (*name_b == '/');
1426 strbuf_reset(&a_name);
1427 strbuf_reset(&b_name);
1428 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1429 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1431 size_one = fill_textconv(textconv_one, one, &data_one);
1432 size_two = fill_textconv(textconv_two, two, &data_two);
1434 memset(&ecbdata, 0, sizeof(ecbdata));
1435 ecbdata.color_diff = want_color(o->use_color);
1436 ecbdata.ws_rule = whitespace_rule(name_b);
1437 ecbdata.opt = o;
1438 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1439 mmfile_t mf1, mf2;
1440 mf1.ptr = (char *)data_one;
1441 mf2.ptr = (char *)data_two;
1442 mf1.size = size_one;
1443 mf2.size = size_two;
1444 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1446 ecbdata.lno_in_preimage = 1;
1447 ecbdata.lno_in_postimage = 1;
1449 lc_a = count_lines(data_one, size_one);
1450 lc_b = count_lines(data_two, size_two);
1452 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1453 a_name.buf, a_name.len, 0);
1454 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1455 b_name.buf, b_name.len, 0);
1457 strbuf_addstr(&out, "@@ -");
1458 if (!o->irreversible_delete)
1459 add_line_count(&out, lc_a);
1460 else
1461 strbuf_addstr(&out, "?,?");
1462 strbuf_addstr(&out, " +");
1463 add_line_count(&out, lc_b);
1464 strbuf_addstr(&out, " @@\n");
1465 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1466 strbuf_release(&out);
1468 if (lc_a && !o->irreversible_delete)
1469 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1470 if (lc_b)
1471 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1472 if (textconv_one)
1473 free((char *)data_one);
1474 if (textconv_two)
1475 free((char *)data_two);
1478 struct diff_words_buffer {
1479 mmfile_t text;
1480 unsigned long alloc;
1481 struct diff_words_orig {
1482 const char *begin, *end;
1483 } *orig;
1484 int orig_nr, orig_alloc;
1487 static void diff_words_append(char *line, unsigned long len,
1488 struct diff_words_buffer *buffer)
1490 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1491 line++;
1492 len--;
1493 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1494 buffer->text.size += len;
1495 buffer->text.ptr[buffer->text.size] = '\0';
1498 struct diff_words_style_elem {
1499 const char *prefix;
1500 const char *suffix;
1501 const char *color; /* NULL; filled in by the setup code if
1502 * color is enabled */
1505 struct diff_words_style {
1506 enum diff_words_type type;
1507 struct diff_words_style_elem new_word, old_word, ctx;
1508 const char *newline;
1511 static struct diff_words_style diff_words_styles[] = {
1512 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1513 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1514 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1517 struct diff_words_data {
1518 struct diff_words_buffer minus, plus;
1519 const char *current_plus;
1520 int last_minus;
1521 struct diff_options *opt;
1522 regex_t *word_regex;
1523 enum diff_words_type type;
1524 struct diff_words_style *style;
1527 static int fn_out_diff_words_write_helper(struct diff_options *o,
1528 struct diff_words_style_elem *st_el,
1529 const char *newline,
1530 size_t count, const char *buf)
1532 int print = 0;
1533 struct strbuf sb = STRBUF_INIT;
1535 while (count) {
1536 char *p = memchr(buf, '\n', count);
1537 if (print)
1538 strbuf_addstr(&sb, diff_line_prefix(o));
1540 if (p != buf) {
1541 const char *reset = st_el->color && *st_el->color ?
1542 GIT_COLOR_RESET : NULL;
1543 if (st_el->color && *st_el->color)
1544 strbuf_addstr(&sb, st_el->color);
1545 strbuf_addstr(&sb, st_el->prefix);
1546 strbuf_add(&sb, buf, p ? p - buf : count);
1547 strbuf_addstr(&sb, st_el->suffix);
1548 if (reset)
1549 strbuf_addstr(&sb, reset);
1551 if (!p)
1552 goto out;
1554 strbuf_addstr(&sb, newline);
1555 count -= p + 1 - buf;
1556 buf = p + 1;
1557 print = 1;
1558 if (count) {
1559 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1560 sb.buf, sb.len, 0);
1561 strbuf_reset(&sb);
1565 out:
1566 if (sb.len)
1567 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1568 sb.buf, sb.len, 0);
1569 strbuf_release(&sb);
1570 return 0;
1574 * '--color-words' algorithm can be described as:
1576 * 1. collect the minus/plus lines of a diff hunk, divided into
1577 * minus-lines and plus-lines;
1579 * 2. break both minus-lines and plus-lines into words and
1580 * place them into two mmfile_t with one word for each line;
1582 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1584 * And for the common parts of the both file, we output the plus side text.
1585 * diff_words->current_plus is used to trace the current position of the plus file
1586 * which printed. diff_words->last_minus is used to trace the last minus word
1587 * printed.
1589 * For '--graph' to work with '--color-words', we need to output the graph prefix
1590 * on each line of color words output. Generally, there are two conditions on
1591 * which we should output the prefix.
1593 * 1. diff_words->last_minus == 0 &&
1594 * diff_words->current_plus == diff_words->plus.text.ptr
1596 * that is: the plus text must start as a new line, and if there is no minus
1597 * word printed, a graph prefix must be printed.
1599 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1600 * *(diff_words->current_plus - 1) == '\n'
1602 * that is: a graph prefix must be printed following a '\n'
1604 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1606 if ((diff_words->last_minus == 0 &&
1607 diff_words->current_plus == diff_words->plus.text.ptr) ||
1608 (diff_words->current_plus > diff_words->plus.text.ptr &&
1609 *(diff_words->current_plus - 1) == '\n')) {
1610 return 1;
1611 } else {
1612 return 0;
1616 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
1618 struct diff_words_data *diff_words = priv;
1619 struct diff_words_style *style = diff_words->style;
1620 int minus_first, minus_len, plus_first, plus_len;
1621 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1622 struct diff_options *opt = diff_words->opt;
1623 const char *line_prefix;
1625 if (line[0] != '@' || parse_hunk_header(line, len,
1626 &minus_first, &minus_len, &plus_first, &plus_len))
1627 return;
1629 assert(opt);
1630 line_prefix = diff_line_prefix(opt);
1632 /* POSIX requires that first be decremented by one if len == 0... */
1633 if (minus_len) {
1634 minus_begin = diff_words->minus.orig[minus_first].begin;
1635 minus_end =
1636 diff_words->minus.orig[minus_first + minus_len - 1].end;
1637 } else
1638 minus_begin = minus_end =
1639 diff_words->minus.orig[minus_first].end;
1641 if (plus_len) {
1642 plus_begin = diff_words->plus.orig[plus_first].begin;
1643 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1644 } else
1645 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1647 if (color_words_output_graph_prefix(diff_words)) {
1648 fputs(line_prefix, diff_words->opt->file);
1650 if (diff_words->current_plus != plus_begin) {
1651 fn_out_diff_words_write_helper(diff_words->opt,
1652 &style->ctx, style->newline,
1653 plus_begin - diff_words->current_plus,
1654 diff_words->current_plus);
1656 if (minus_begin != minus_end) {
1657 fn_out_diff_words_write_helper(diff_words->opt,
1658 &style->old_word, style->newline,
1659 minus_end - minus_begin, minus_begin);
1661 if (plus_begin != plus_end) {
1662 fn_out_diff_words_write_helper(diff_words->opt,
1663 &style->new_word, style->newline,
1664 plus_end - plus_begin, plus_begin);
1667 diff_words->current_plus = plus_end;
1668 diff_words->last_minus = minus_first;
1671 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1672 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1673 int *begin, int *end)
1675 if (word_regex && *begin < buffer->size) {
1676 regmatch_t match[1];
1677 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1678 buffer->size - *begin, 1, match, 0)) {
1679 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1680 '\n', match[0].rm_eo - match[0].rm_so);
1681 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1682 *begin += match[0].rm_so;
1683 return *begin >= *end;
1685 return -1;
1688 /* find the next word */
1689 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1690 (*begin)++;
1691 if (*begin >= buffer->size)
1692 return -1;
1694 /* find the end of the word */
1695 *end = *begin + 1;
1696 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1697 (*end)++;
1699 return 0;
1703 * This function splits the words in buffer->text, stores the list with
1704 * newline separator into out, and saves the offsets of the original words
1705 * in buffer->orig.
1707 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1708 regex_t *word_regex)
1710 int i, j;
1711 long alloc = 0;
1713 out->size = 0;
1714 out->ptr = NULL;
1716 /* fake an empty "0th" word */
1717 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1718 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1719 buffer->orig_nr = 1;
1721 for (i = 0; i < buffer->text.size; i++) {
1722 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1723 return;
1725 /* store original boundaries */
1726 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1727 buffer->orig_alloc);
1728 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1729 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1730 buffer->orig_nr++;
1732 /* store one word */
1733 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1734 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1735 out->ptr[out->size + j - i] = '\n';
1736 out->size += j - i + 1;
1738 i = j - 1;
1742 /* this executes the word diff on the accumulated buffers */
1743 static void diff_words_show(struct diff_words_data *diff_words)
1745 xpparam_t xpp;
1746 xdemitconf_t xecfg;
1747 mmfile_t minus, plus;
1748 struct diff_words_style *style = diff_words->style;
1750 struct diff_options *opt = diff_words->opt;
1751 const char *line_prefix;
1753 assert(opt);
1754 line_prefix = diff_line_prefix(opt);
1756 /* special case: only removal */
1757 if (!diff_words->plus.text.size) {
1758 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1759 line_prefix, strlen(line_prefix), 0);
1760 fn_out_diff_words_write_helper(diff_words->opt,
1761 &style->old_word, style->newline,
1762 diff_words->minus.text.size,
1763 diff_words->minus.text.ptr);
1764 diff_words->minus.text.size = 0;
1765 return;
1768 diff_words->current_plus = diff_words->plus.text.ptr;
1769 diff_words->last_minus = 0;
1771 memset(&xpp, 0, sizeof(xpp));
1772 memset(&xecfg, 0, sizeof(xecfg));
1773 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1774 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1775 xpp.flags = 0;
1776 /* as only the hunk header will be parsed, we need a 0-context */
1777 xecfg.ctxlen = 0;
1778 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1779 &xpp, &xecfg))
1780 die("unable to generate word diff");
1781 free(minus.ptr);
1782 free(plus.ptr);
1783 if (diff_words->current_plus != diff_words->plus.text.ptr +
1784 diff_words->plus.text.size) {
1785 if (color_words_output_graph_prefix(diff_words))
1786 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1787 line_prefix, strlen(line_prefix), 0);
1788 fn_out_diff_words_write_helper(diff_words->opt,
1789 &style->ctx, style->newline,
1790 diff_words->plus.text.ptr + diff_words->plus.text.size
1791 - diff_words->current_plus, diff_words->current_plus);
1793 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1796 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1797 static void diff_words_flush(struct emit_callback *ecbdata)
1799 struct diff_options *wo = ecbdata->diff_words->opt;
1801 if (ecbdata->diff_words->minus.text.size ||
1802 ecbdata->diff_words->plus.text.size)
1803 diff_words_show(ecbdata->diff_words);
1805 if (wo->emitted_symbols) {
1806 struct diff_options *o = ecbdata->opt;
1807 struct emitted_diff_symbols *wol = wo->emitted_symbols;
1808 int i;
1811 * NEEDSWORK:
1812 * Instead of appending each, concat all words to a line?
1814 for (i = 0; i < wol->nr; i++)
1815 append_emitted_diff_symbol(o, &wol->buf[i]);
1817 for (i = 0; i < wol->nr; i++)
1818 free((void *)wol->buf[i].line);
1820 wol->nr = 0;
1824 static void diff_filespec_load_driver(struct diff_filespec *one)
1826 /* Use already-loaded driver */
1827 if (one->driver)
1828 return;
1830 if (S_ISREG(one->mode))
1831 one->driver = userdiff_find_by_path(one->path);
1833 /* Fallback to default settings */
1834 if (!one->driver)
1835 one->driver = userdiff_find_by_name("default");
1838 static const char *userdiff_word_regex(struct diff_filespec *one)
1840 diff_filespec_load_driver(one);
1841 return one->driver->word_regex;
1844 static void init_diff_words_data(struct emit_callback *ecbdata,
1845 struct diff_options *orig_opts,
1846 struct diff_filespec *one,
1847 struct diff_filespec *two)
1849 int i;
1850 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1851 memcpy(o, orig_opts, sizeof(struct diff_options));
1853 ecbdata->diff_words =
1854 xcalloc(1, sizeof(struct diff_words_data));
1855 ecbdata->diff_words->type = o->word_diff;
1856 ecbdata->diff_words->opt = o;
1858 if (orig_opts->emitted_symbols)
1859 o->emitted_symbols =
1860 xcalloc(1, sizeof(struct emitted_diff_symbols));
1862 if (!o->word_regex)
1863 o->word_regex = userdiff_word_regex(one);
1864 if (!o->word_regex)
1865 o->word_regex = userdiff_word_regex(two);
1866 if (!o->word_regex)
1867 o->word_regex = diff_word_regex_cfg;
1868 if (o->word_regex) {
1869 ecbdata->diff_words->word_regex = (regex_t *)
1870 xmalloc(sizeof(regex_t));
1871 if (regcomp(ecbdata->diff_words->word_regex,
1872 o->word_regex,
1873 REG_EXTENDED | REG_NEWLINE))
1874 die ("Invalid regular expression: %s",
1875 o->word_regex);
1877 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1878 if (o->word_diff == diff_words_styles[i].type) {
1879 ecbdata->diff_words->style =
1880 &diff_words_styles[i];
1881 break;
1884 if (want_color(o->use_color)) {
1885 struct diff_words_style *st = ecbdata->diff_words->style;
1886 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1887 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1888 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1892 static void free_diff_words_data(struct emit_callback *ecbdata)
1894 if (ecbdata->diff_words) {
1895 diff_words_flush(ecbdata);
1896 free (ecbdata->diff_words->opt->emitted_symbols);
1897 free (ecbdata->diff_words->opt);
1898 free (ecbdata->diff_words->minus.text.ptr);
1899 free (ecbdata->diff_words->minus.orig);
1900 free (ecbdata->diff_words->plus.text.ptr);
1901 free (ecbdata->diff_words->plus.orig);
1902 if (ecbdata->diff_words->word_regex) {
1903 regfree(ecbdata->diff_words->word_regex);
1904 free(ecbdata->diff_words->word_regex);
1906 FREE_AND_NULL(ecbdata->diff_words);
1910 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1912 if (want_color(diff_use_color))
1913 return diff_colors[ix];
1914 return "";
1917 const char *diff_line_prefix(struct diff_options *opt)
1919 struct strbuf *msgbuf;
1920 if (!opt->output_prefix)
1921 return "";
1923 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1924 return msgbuf->buf;
1927 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1929 const char *cp;
1930 unsigned long allot;
1931 size_t l = len;
1933 cp = line;
1934 allot = l;
1935 while (0 < l) {
1936 (void) utf8_width(&cp, &l);
1937 if (!cp)
1938 break; /* truncated in the middle? */
1940 return allot - l;
1943 static void find_lno(const char *line, struct emit_callback *ecbdata)
1945 const char *p;
1946 ecbdata->lno_in_preimage = 0;
1947 ecbdata->lno_in_postimage = 0;
1948 p = strchr(line, '-');
1949 if (!p)
1950 return; /* cannot happen */
1951 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1952 p = strchr(p, '+');
1953 if (!p)
1954 return; /* cannot happen */
1955 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1958 static void fn_out_consume(void *priv, char *line, unsigned long len)
1960 struct emit_callback *ecbdata = priv;
1961 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1962 struct diff_options *o = ecbdata->opt;
1964 o->found_changes = 1;
1966 if (ecbdata->header) {
1967 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
1968 ecbdata->header->buf, ecbdata->header->len, 0);
1969 strbuf_reset(ecbdata->header);
1970 ecbdata->header = NULL;
1973 if (ecbdata->label_path[0]) {
1974 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1975 ecbdata->label_path[0],
1976 strlen(ecbdata->label_path[0]), 0);
1977 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1978 ecbdata->label_path[1],
1979 strlen(ecbdata->label_path[1]), 0);
1980 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1983 if (diff_suppress_blank_empty
1984 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1985 line[0] = '\n';
1986 len = 1;
1989 if (line[0] == '@') {
1990 if (ecbdata->diff_words)
1991 diff_words_flush(ecbdata);
1992 len = sane_truncate_line(ecbdata, line, len);
1993 find_lno(line, ecbdata);
1994 emit_hunk_header(ecbdata, line, len);
1995 return;
1998 if (ecbdata->diff_words) {
1999 enum diff_symbol s =
2000 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2001 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2002 if (line[0] == '-') {
2003 diff_words_append(line, len,
2004 &ecbdata->diff_words->minus);
2005 return;
2006 } else if (line[0] == '+') {
2007 diff_words_append(line, len,
2008 &ecbdata->diff_words->plus);
2009 return;
2010 } else if (starts_with(line, "\\ ")) {
2012 * Eat the "no newline at eof" marker as if we
2013 * saw a "+" or "-" line with nothing on it,
2014 * and return without diff_words_flush() to
2015 * defer processing. If this is the end of
2016 * preimage, more "+" lines may come after it.
2018 return;
2020 diff_words_flush(ecbdata);
2021 emit_diff_symbol(o, s, line, len, 0);
2022 return;
2025 switch (line[0]) {
2026 case '+':
2027 ecbdata->lno_in_postimage++;
2028 emit_add_line(reset, ecbdata, line + 1, len - 1);
2029 break;
2030 case '-':
2031 ecbdata->lno_in_preimage++;
2032 emit_del_line(reset, ecbdata, line + 1, len - 1);
2033 break;
2034 case ' ':
2035 ecbdata->lno_in_postimage++;
2036 ecbdata->lno_in_preimage++;
2037 emit_context_line(reset, ecbdata, line + 1, len - 1);
2038 break;
2039 default:
2040 /* incomplete line at the end */
2041 ecbdata->lno_in_preimage++;
2042 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2043 line, len, 0);
2044 break;
2048 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2050 const char *old_name = a;
2051 const char *new_name = b;
2052 int pfx_length, sfx_length;
2053 int pfx_adjust_for_slash;
2054 int len_a = strlen(a);
2055 int len_b = strlen(b);
2056 int a_midlen, b_midlen;
2057 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2058 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2060 if (qlen_a || qlen_b) {
2061 quote_c_style(a, name, NULL, 0);
2062 strbuf_addstr(name, " => ");
2063 quote_c_style(b, name, NULL, 0);
2064 return;
2067 /* Find common prefix */
2068 pfx_length = 0;
2069 while (*old_name && *new_name && *old_name == *new_name) {
2070 if (*old_name == '/')
2071 pfx_length = old_name - a + 1;
2072 old_name++;
2073 new_name++;
2076 /* Find common suffix */
2077 old_name = a + len_a;
2078 new_name = b + len_b;
2079 sfx_length = 0;
2081 * If there is a common prefix, it must end in a slash. In
2082 * that case we let this loop run 1 into the prefix to see the
2083 * same slash.
2085 * If there is no common prefix, we cannot do this as it would
2086 * underrun the input strings.
2088 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2089 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2090 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2091 *old_name == *new_name) {
2092 if (*old_name == '/')
2093 sfx_length = len_a - (old_name - a);
2094 old_name--;
2095 new_name--;
2099 * pfx{mid-a => mid-b}sfx
2100 * {pfx-a => pfx-b}sfx
2101 * pfx{sfx-a => sfx-b}
2102 * name-a => name-b
2104 a_midlen = len_a - pfx_length - sfx_length;
2105 b_midlen = len_b - pfx_length - sfx_length;
2106 if (a_midlen < 0)
2107 a_midlen = 0;
2108 if (b_midlen < 0)
2109 b_midlen = 0;
2111 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2112 if (pfx_length + sfx_length) {
2113 strbuf_add(name, a, pfx_length);
2114 strbuf_addch(name, '{');
2116 strbuf_add(name, a + pfx_length, a_midlen);
2117 strbuf_addstr(name, " => ");
2118 strbuf_add(name, b + pfx_length, b_midlen);
2119 if (pfx_length + sfx_length) {
2120 strbuf_addch(name, '}');
2121 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2125 struct diffstat_t {
2126 int nr;
2127 int alloc;
2128 struct diffstat_file {
2129 char *from_name;
2130 char *name;
2131 char *print_name;
2132 const char *comments;
2133 unsigned is_unmerged:1;
2134 unsigned is_binary:1;
2135 unsigned is_renamed:1;
2136 unsigned is_interesting:1;
2137 uintmax_t added, deleted;
2138 } **files;
2141 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2142 const char *name_a,
2143 const char *name_b)
2145 struct diffstat_file *x;
2146 x = xcalloc(1, sizeof(*x));
2147 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2148 diffstat->files[diffstat->nr++] = x;
2149 if (name_b) {
2150 x->from_name = xstrdup(name_a);
2151 x->name = xstrdup(name_b);
2152 x->is_renamed = 1;
2154 else {
2155 x->from_name = NULL;
2156 x->name = xstrdup(name_a);
2158 return x;
2161 static void diffstat_consume(void *priv, char *line, unsigned long len)
2163 struct diffstat_t *diffstat = priv;
2164 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2166 if (line[0] == '+')
2167 x->added++;
2168 else if (line[0] == '-')
2169 x->deleted++;
2172 const char mime_boundary_leader[] = "------------";
2174 static int scale_linear(int it, int width, int max_change)
2176 if (!it)
2177 return 0;
2179 * make sure that at least one '-' or '+' is printed if
2180 * there is any change to this path. The easiest way is to
2181 * scale linearly as if the alloted width is one column shorter
2182 * than it is, and then add 1 to the result.
2184 return 1 + (it * (width - 1) / max_change);
2187 static void show_graph(struct strbuf *out, char ch, int cnt,
2188 const char *set, const char *reset)
2190 if (cnt <= 0)
2191 return;
2192 strbuf_addstr(out, set);
2193 strbuf_addchars(out, ch, cnt);
2194 strbuf_addstr(out, reset);
2197 static void fill_print_name(struct diffstat_file *file)
2199 struct strbuf pname = STRBUF_INIT;
2201 if (file->print_name)
2202 return;
2204 if (file->is_renamed)
2205 pprint_rename(&pname, file->from_name, file->name);
2206 else
2207 quote_c_style(file->name, &pname, NULL, 0);
2209 if (file->comments)
2210 strbuf_addf(&pname, " (%s)", file->comments);
2212 file->print_name = strbuf_detach(&pname, NULL);
2215 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2216 int files, int insertions, int deletions)
2218 struct strbuf sb = STRBUF_INIT;
2220 if (!files) {
2221 assert(insertions == 0 && deletions == 0);
2222 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2223 NULL, 0, 0);
2224 return;
2227 strbuf_addf(&sb,
2228 (files == 1) ? " %d file changed" : " %d files changed",
2229 files);
2232 * For binary diff, the caller may want to print "x files
2233 * changed" with insertions == 0 && deletions == 0.
2235 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2236 * is probably less confusing (i.e skip over "2 files changed
2237 * but nothing about added/removed lines? Is this a bug in Git?").
2239 if (insertions || deletions == 0) {
2240 strbuf_addf(&sb,
2241 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2242 insertions);
2245 if (deletions || insertions == 0) {
2246 strbuf_addf(&sb,
2247 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2248 deletions);
2250 strbuf_addch(&sb, '\n');
2251 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2252 sb.buf, sb.len, 0);
2253 strbuf_release(&sb);
2256 void print_stat_summary(FILE *fp, int files,
2257 int insertions, int deletions)
2259 struct diff_options o;
2260 memset(&o, 0, sizeof(o));
2261 o.file = fp;
2263 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2266 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2268 int i, len, add, del, adds = 0, dels = 0;
2269 uintmax_t max_change = 0, max_len = 0;
2270 int total_files = data->nr, count;
2271 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2272 const char *reset, *add_c, *del_c;
2273 int extra_shown = 0;
2274 const char *line_prefix = diff_line_prefix(options);
2275 struct strbuf out = STRBUF_INIT;
2277 if (data->nr == 0)
2278 return;
2280 count = options->stat_count ? options->stat_count : data->nr;
2282 reset = diff_get_color_opt(options, DIFF_RESET);
2283 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2284 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2287 * Find the longest filename and max number of changes
2289 for (i = 0; (i < count) && (i < data->nr); i++) {
2290 struct diffstat_file *file = data->files[i];
2291 uintmax_t change = file->added + file->deleted;
2293 if (!file->is_interesting && (change == 0)) {
2294 count++; /* not shown == room for one more */
2295 continue;
2297 fill_print_name(file);
2298 len = strlen(file->print_name);
2299 if (max_len < len)
2300 max_len = len;
2302 if (file->is_unmerged) {
2303 /* "Unmerged" is 8 characters */
2304 bin_width = bin_width < 8 ? 8 : bin_width;
2305 continue;
2307 if (file->is_binary) {
2308 /* "Bin XXX -> YYY bytes" */
2309 int w = 14 + decimal_width(file->added)
2310 + decimal_width(file->deleted);
2311 bin_width = bin_width < w ? w : bin_width;
2312 /* Display change counts aligned with "Bin" */
2313 number_width = 3;
2314 continue;
2317 if (max_change < change)
2318 max_change = change;
2320 count = i; /* where we can stop scanning in data->files[] */
2323 * We have width = stat_width or term_columns() columns total.
2324 * We want a maximum of min(max_len, stat_name_width) for the name part.
2325 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2326 * We also need 1 for " " and 4 + decimal_width(max_change)
2327 * for " | NNNN " and one the empty column at the end, altogether
2328 * 6 + decimal_width(max_change).
2330 * If there's not enough space, we will use the smaller of
2331 * stat_name_width (if set) and 5/8*width for the filename,
2332 * and the rest for constant elements + graph part, but no more
2333 * than stat_graph_width for the graph part.
2334 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2335 * for the standard terminal size).
2337 * In other words: stat_width limits the maximum width, and
2338 * stat_name_width fixes the maximum width of the filename,
2339 * and is also used to divide available columns if there
2340 * aren't enough.
2342 * Binary files are displayed with "Bin XXX -> YYY bytes"
2343 * instead of the change count and graph. This part is treated
2344 * similarly to the graph part, except that it is not
2345 * "scaled". If total width is too small to accommodate the
2346 * guaranteed minimum width of the filename part and the
2347 * separators and this message, this message will "overflow"
2348 * making the line longer than the maximum width.
2351 if (options->stat_width == -1)
2352 width = term_columns() - strlen(line_prefix);
2353 else
2354 width = options->stat_width ? options->stat_width : 80;
2355 number_width = decimal_width(max_change) > number_width ?
2356 decimal_width(max_change) : number_width;
2358 if (options->stat_graph_width == -1)
2359 options->stat_graph_width = diff_stat_graph_width;
2362 * Guarantee 3/8*16==6 for the graph part
2363 * and 5/8*16==10 for the filename part
2365 if (width < 16 + 6 + number_width)
2366 width = 16 + 6 + number_width;
2369 * First assign sizes that are wanted, ignoring available width.
2370 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2371 * starting from "XXX" should fit in graph_width.
2373 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2374 if (options->stat_graph_width &&
2375 options->stat_graph_width < graph_width)
2376 graph_width = options->stat_graph_width;
2378 name_width = (options->stat_name_width > 0 &&
2379 options->stat_name_width < max_len) ?
2380 options->stat_name_width : max_len;
2383 * Adjust adjustable widths not to exceed maximum width
2385 if (name_width + number_width + 6 + graph_width > width) {
2386 if (graph_width > width * 3/8 - number_width - 6) {
2387 graph_width = width * 3/8 - number_width - 6;
2388 if (graph_width < 6)
2389 graph_width = 6;
2392 if (options->stat_graph_width &&
2393 graph_width > options->stat_graph_width)
2394 graph_width = options->stat_graph_width;
2395 if (name_width > width - number_width - 6 - graph_width)
2396 name_width = width - number_width - 6 - graph_width;
2397 else
2398 graph_width = width - number_width - 6 - name_width;
2402 * From here name_width is the width of the name area,
2403 * and graph_width is the width of the graph area.
2404 * max_change is used to scale graph properly.
2406 for (i = 0; i < count; i++) {
2407 const char *prefix = "";
2408 struct diffstat_file *file = data->files[i];
2409 char *name = file->print_name;
2410 uintmax_t added = file->added;
2411 uintmax_t deleted = file->deleted;
2412 int name_len;
2414 if (!file->is_interesting && (added + deleted == 0))
2415 continue;
2418 * "scale" the filename
2420 len = name_width;
2421 name_len = strlen(name);
2422 if (name_width < name_len) {
2423 char *slash;
2424 prefix = "...";
2425 len -= 3;
2426 name += name_len - len;
2427 slash = strchr(name, '/');
2428 if (slash)
2429 name = slash;
2432 if (file->is_binary) {
2433 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2434 strbuf_addf(&out, " %*s", number_width, "Bin");
2435 if (!added && !deleted) {
2436 strbuf_addch(&out, '\n');
2437 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2438 out.buf, out.len, 0);
2439 strbuf_reset(&out);
2440 continue;
2442 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2443 del_c, deleted, reset);
2444 strbuf_addstr(&out, " -> ");
2445 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2446 add_c, added, reset);
2447 strbuf_addstr(&out, " bytes\n");
2448 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2449 out.buf, out.len, 0);
2450 strbuf_reset(&out);
2451 continue;
2453 else if (file->is_unmerged) {
2454 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2455 strbuf_addstr(&out, " Unmerged\n");
2456 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2457 out.buf, out.len, 0);
2458 strbuf_reset(&out);
2459 continue;
2463 * scale the add/delete
2465 add = added;
2466 del = deleted;
2468 if (graph_width <= max_change) {
2469 int total = scale_linear(add + del, graph_width, max_change);
2470 if (total < 2 && add && del)
2471 /* width >= 2 due to the sanity check */
2472 total = 2;
2473 if (add < del) {
2474 add = scale_linear(add, graph_width, max_change);
2475 del = total - add;
2476 } else {
2477 del = scale_linear(del, graph_width, max_change);
2478 add = total - del;
2481 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2482 strbuf_addf(&out, " %*"PRIuMAX"%s",
2483 number_width, added + deleted,
2484 added + deleted ? " " : "");
2485 show_graph(&out, '+', add, add_c, reset);
2486 show_graph(&out, '-', del, del_c, reset);
2487 strbuf_addch(&out, '\n');
2488 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2489 out.buf, out.len, 0);
2490 strbuf_reset(&out);
2493 for (i = 0; i < data->nr; i++) {
2494 struct diffstat_file *file = data->files[i];
2495 uintmax_t added = file->added;
2496 uintmax_t deleted = file->deleted;
2498 if (file->is_unmerged ||
2499 (!file->is_interesting && (added + deleted == 0))) {
2500 total_files--;
2501 continue;
2504 if (!file->is_binary) {
2505 adds += added;
2506 dels += deleted;
2508 if (i < count)
2509 continue;
2510 if (!extra_shown)
2511 emit_diff_symbol(options,
2512 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2513 NULL, 0, 0);
2514 extra_shown = 1;
2517 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2518 strbuf_release(&out);
2521 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2523 int i, adds = 0, dels = 0, total_files = data->nr;
2525 if (data->nr == 0)
2526 return;
2528 for (i = 0; i < data->nr; i++) {
2529 int added = data->files[i]->added;
2530 int deleted = data->files[i]->deleted;
2532 if (data->files[i]->is_unmerged ||
2533 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2534 total_files--;
2535 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2536 adds += added;
2537 dels += deleted;
2540 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2543 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2545 int i;
2547 if (data->nr == 0)
2548 return;
2550 for (i = 0; i < data->nr; i++) {
2551 struct diffstat_file *file = data->files[i];
2553 fprintf(options->file, "%s", diff_line_prefix(options));
2555 if (file->is_binary)
2556 fprintf(options->file, "-\t-\t");
2557 else
2558 fprintf(options->file,
2559 "%"PRIuMAX"\t%"PRIuMAX"\t",
2560 file->added, file->deleted);
2561 if (options->line_termination) {
2562 fill_print_name(file);
2563 if (!file->is_renamed)
2564 write_name_quoted(file->name, options->file,
2565 options->line_termination);
2566 else {
2567 fputs(file->print_name, options->file);
2568 putc(options->line_termination, options->file);
2570 } else {
2571 if (file->is_renamed) {
2572 putc('\0', options->file);
2573 write_name_quoted(file->from_name, options->file, '\0');
2575 write_name_quoted(file->name, options->file, '\0');
2580 struct dirstat_file {
2581 const char *name;
2582 unsigned long changed;
2585 struct dirstat_dir {
2586 struct dirstat_file *files;
2587 int alloc, nr, permille, cumulative;
2590 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2591 unsigned long changed, const char *base, int baselen)
2593 unsigned long sum_changes = 0;
2594 unsigned int sources = 0;
2595 const char *line_prefix = diff_line_prefix(opt);
2597 while (dir->nr) {
2598 struct dirstat_file *f = dir->files;
2599 int namelen = strlen(f->name);
2600 unsigned long changes;
2601 char *slash;
2603 if (namelen < baselen)
2604 break;
2605 if (memcmp(f->name, base, baselen))
2606 break;
2607 slash = strchr(f->name + baselen, '/');
2608 if (slash) {
2609 int newbaselen = slash + 1 - f->name;
2610 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2611 sources++;
2612 } else {
2613 changes = f->changed;
2614 dir->files++;
2615 dir->nr--;
2616 sources += 2;
2618 sum_changes += changes;
2622 * We don't report dirstat's for
2623 * - the top level
2624 * - or cases where everything came from a single directory
2625 * under this directory (sources == 1).
2627 if (baselen && sources != 1) {
2628 if (sum_changes) {
2629 int permille = sum_changes * 1000 / changed;
2630 if (permille >= dir->permille) {
2631 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2632 permille / 10, permille % 10, baselen, base);
2633 if (!dir->cumulative)
2634 return 0;
2638 return sum_changes;
2641 static int dirstat_compare(const void *_a, const void *_b)
2643 const struct dirstat_file *a = _a;
2644 const struct dirstat_file *b = _b;
2645 return strcmp(a->name, b->name);
2648 static void show_dirstat(struct diff_options *options)
2650 int i;
2651 unsigned long changed;
2652 struct dirstat_dir dir;
2653 struct diff_queue_struct *q = &diff_queued_diff;
2655 dir.files = NULL;
2656 dir.alloc = 0;
2657 dir.nr = 0;
2658 dir.permille = options->dirstat_permille;
2659 dir.cumulative = options->flags.dirstat_cumulative;
2661 changed = 0;
2662 for (i = 0; i < q->nr; i++) {
2663 struct diff_filepair *p = q->queue[i];
2664 const char *name;
2665 unsigned long copied, added, damage;
2666 int content_changed;
2668 name = p->two->path ? p->two->path : p->one->path;
2670 if (p->one->oid_valid && p->two->oid_valid)
2671 content_changed = oidcmp(&p->one->oid, &p->two->oid);
2672 else
2673 content_changed = 1;
2675 if (!content_changed) {
2677 * The SHA1 has not changed, so pre-/post-content is
2678 * identical. We can therefore skip looking at the
2679 * file contents altogether.
2681 damage = 0;
2682 goto found_damage;
2685 if (options->flags.dirstat_by_file) {
2687 * In --dirstat-by-file mode, we don't really need to
2688 * look at the actual file contents at all.
2689 * The fact that the SHA1 changed is enough for us to
2690 * add this file to the list of results
2691 * (with each file contributing equal damage).
2693 damage = 1;
2694 goto found_damage;
2697 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2698 diff_populate_filespec(p->one, 0);
2699 diff_populate_filespec(p->two, 0);
2700 diffcore_count_changes(p->one, p->two, NULL, NULL,
2701 &copied, &added);
2702 diff_free_filespec_data(p->one);
2703 diff_free_filespec_data(p->two);
2704 } else if (DIFF_FILE_VALID(p->one)) {
2705 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2706 copied = added = 0;
2707 diff_free_filespec_data(p->one);
2708 } else if (DIFF_FILE_VALID(p->two)) {
2709 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
2710 copied = 0;
2711 added = p->two->size;
2712 diff_free_filespec_data(p->two);
2713 } else
2714 continue;
2717 * Original minus copied is the removed material,
2718 * added is the new material. They are both damages
2719 * made to the preimage.
2720 * If the resulting damage is zero, we know that
2721 * diffcore_count_changes() considers the two entries to
2722 * be identical, but since content_changed is true, we
2723 * know that there must have been _some_ kind of change,
2724 * so we force all entries to have damage > 0.
2726 damage = (p->one->size - copied) + added;
2727 if (!damage)
2728 damage = 1;
2730 found_damage:
2731 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2732 dir.files[dir.nr].name = name;
2733 dir.files[dir.nr].changed = damage;
2734 changed += damage;
2735 dir.nr++;
2738 /* This can happen even with many files, if everything was renames */
2739 if (!changed)
2740 return;
2742 /* Show all directories with more than x% of the changes */
2743 QSORT(dir.files, dir.nr, dirstat_compare);
2744 gather_dirstat(options, &dir, changed, "", 0);
2747 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2749 int i;
2750 unsigned long changed;
2751 struct dirstat_dir dir;
2753 if (data->nr == 0)
2754 return;
2756 dir.files = NULL;
2757 dir.alloc = 0;
2758 dir.nr = 0;
2759 dir.permille = options->dirstat_permille;
2760 dir.cumulative = options->flags.dirstat_cumulative;
2762 changed = 0;
2763 for (i = 0; i < data->nr; i++) {
2764 struct diffstat_file *file = data->files[i];
2765 unsigned long damage = file->added + file->deleted;
2766 if (file->is_binary)
2768 * binary files counts bytes, not lines. Must find some
2769 * way to normalize binary bytes vs. textual lines.
2770 * The following heuristic assumes that there are 64
2771 * bytes per "line".
2772 * This is stupid and ugly, but very cheap...
2774 damage = DIV_ROUND_UP(damage, 64);
2775 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2776 dir.files[dir.nr].name = file->name;
2777 dir.files[dir.nr].changed = damage;
2778 changed += damage;
2779 dir.nr++;
2782 /* This can happen even with many files, if everything was renames */
2783 if (!changed)
2784 return;
2786 /* Show all directories with more than x% of the changes */
2787 QSORT(dir.files, dir.nr, dirstat_compare);
2788 gather_dirstat(options, &dir, changed, "", 0);
2791 static void free_diffstat_info(struct diffstat_t *diffstat)
2793 int i;
2794 for (i = 0; i < diffstat->nr; i++) {
2795 struct diffstat_file *f = diffstat->files[i];
2796 free(f->print_name);
2797 free(f->name);
2798 free(f->from_name);
2799 free(f);
2801 free(diffstat->files);
2804 struct checkdiff_t {
2805 const char *filename;
2806 int lineno;
2807 int conflict_marker_size;
2808 struct diff_options *o;
2809 unsigned ws_rule;
2810 unsigned status;
2813 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2815 char firstchar;
2816 int cnt;
2818 if (len < marker_size + 1)
2819 return 0;
2820 firstchar = line[0];
2821 switch (firstchar) {
2822 case '=': case '>': case '<': case '|':
2823 break;
2824 default:
2825 return 0;
2827 for (cnt = 1; cnt < marker_size; cnt++)
2828 if (line[cnt] != firstchar)
2829 return 0;
2830 /* line[1] thru line[marker_size-1] are same as firstchar */
2831 if (len < marker_size + 1 || !isspace(line[marker_size]))
2832 return 0;
2833 return 1;
2836 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2838 struct checkdiff_t *data = priv;
2839 int marker_size = data->conflict_marker_size;
2840 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2841 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2842 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2843 char *err;
2844 const char *line_prefix;
2846 assert(data->o);
2847 line_prefix = diff_line_prefix(data->o);
2849 if (line[0] == '+') {
2850 unsigned bad;
2851 data->lineno++;
2852 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2853 data->status |= 1;
2854 fprintf(data->o->file,
2855 "%s%s:%d: leftover conflict marker\n",
2856 line_prefix, data->filename, data->lineno);
2858 bad = ws_check(line + 1, len - 1, data->ws_rule);
2859 if (!bad)
2860 return;
2861 data->status |= bad;
2862 err = whitespace_error_string(bad);
2863 fprintf(data->o->file, "%s%s:%d: %s.\n",
2864 line_prefix, data->filename, data->lineno, err);
2865 free(err);
2866 emit_line(data->o, set, reset, line, 1);
2867 ws_check_emit(line + 1, len - 1, data->ws_rule,
2868 data->o->file, set, reset, ws);
2869 } else if (line[0] == ' ') {
2870 data->lineno++;
2871 } else if (line[0] == '@') {
2872 char *plus = strchr(line, '+');
2873 if (plus)
2874 data->lineno = strtol(plus, NULL, 10) - 1;
2875 else
2876 die("invalid diff");
2880 static unsigned char *deflate_it(char *data,
2881 unsigned long size,
2882 unsigned long *result_size)
2884 int bound;
2885 unsigned char *deflated;
2886 git_zstream stream;
2888 git_deflate_init(&stream, zlib_compression_level);
2889 bound = git_deflate_bound(&stream, size);
2890 deflated = xmalloc(bound);
2891 stream.next_out = deflated;
2892 stream.avail_out = bound;
2894 stream.next_in = (unsigned char *)data;
2895 stream.avail_in = size;
2896 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2897 ; /* nothing */
2898 git_deflate_end(&stream);
2899 *result_size = stream.total_out;
2900 return deflated;
2903 static void emit_binary_diff_body(struct diff_options *o,
2904 mmfile_t *one, mmfile_t *two)
2906 void *cp;
2907 void *delta;
2908 void *deflated;
2909 void *data;
2910 unsigned long orig_size;
2911 unsigned long delta_size;
2912 unsigned long deflate_size;
2913 unsigned long data_size;
2915 /* We could do deflated delta, or we could do just deflated two,
2916 * whichever is smaller.
2918 delta = NULL;
2919 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2920 if (one->size && two->size) {
2921 delta = diff_delta(one->ptr, one->size,
2922 two->ptr, two->size,
2923 &delta_size, deflate_size);
2924 if (delta) {
2925 void *to_free = delta;
2926 orig_size = delta_size;
2927 delta = deflate_it(delta, delta_size, &delta_size);
2928 free(to_free);
2932 if (delta && delta_size < deflate_size) {
2933 char *s = xstrfmt("%lu", orig_size);
2934 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
2935 s, strlen(s), 0);
2936 free(s);
2937 free(deflated);
2938 data = delta;
2939 data_size = delta_size;
2940 } else {
2941 char *s = xstrfmt("%lu", two->size);
2942 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
2943 s, strlen(s), 0);
2944 free(s);
2945 free(delta);
2946 data = deflated;
2947 data_size = deflate_size;
2950 /* emit data encoded in base85 */
2951 cp = data;
2952 while (data_size) {
2953 int len;
2954 int bytes = (52 < data_size) ? 52 : data_size;
2955 char line[71];
2956 data_size -= bytes;
2957 if (bytes <= 26)
2958 line[0] = bytes + 'A' - 1;
2959 else
2960 line[0] = bytes - 26 + 'a' - 1;
2961 encode_85(line + 1, cp, bytes);
2962 cp = (char *) cp + bytes;
2964 len = strlen(line);
2965 line[len++] = '\n';
2966 line[len] = '\0';
2968 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
2969 line, len, 0);
2971 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
2972 free(data);
2975 static void emit_binary_diff(struct diff_options *o,
2976 mmfile_t *one, mmfile_t *two)
2978 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
2979 emit_binary_diff_body(o, one, two);
2980 emit_binary_diff_body(o, two, one);
2983 int diff_filespec_is_binary(struct diff_filespec *one)
2985 if (one->is_binary == -1) {
2986 diff_filespec_load_driver(one);
2987 if (one->driver->binary != -1)
2988 one->is_binary = one->driver->binary;
2989 else {
2990 if (!one->data && DIFF_FILE_VALID(one))
2991 diff_populate_filespec(one, CHECK_BINARY);
2992 if (one->is_binary == -1 && one->data)
2993 one->is_binary = buffer_is_binary(one->data,
2994 one->size);
2995 if (one->is_binary == -1)
2996 one->is_binary = 0;
2999 return one->is_binary;
3002 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
3004 diff_filespec_load_driver(one);
3005 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3008 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3010 if (!options->a_prefix)
3011 options->a_prefix = a;
3012 if (!options->b_prefix)
3013 options->b_prefix = b;
3016 struct userdiff_driver *get_textconv(struct diff_filespec *one)
3018 if (!DIFF_FILE_VALID(one))
3019 return NULL;
3021 diff_filespec_load_driver(one);
3022 return userdiff_get_textconv(one->driver);
3025 static void builtin_diff(const char *name_a,
3026 const char *name_b,
3027 struct diff_filespec *one,
3028 struct diff_filespec *two,
3029 const char *xfrm_msg,
3030 int must_show_header,
3031 struct diff_options *o,
3032 int complete_rewrite)
3034 mmfile_t mf1, mf2;
3035 const char *lbl[2];
3036 char *a_one, *b_two;
3037 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3038 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3039 const char *a_prefix, *b_prefix;
3040 struct userdiff_driver *textconv_one = NULL;
3041 struct userdiff_driver *textconv_two = NULL;
3042 struct strbuf header = STRBUF_INIT;
3043 const char *line_prefix = diff_line_prefix(o);
3045 diff_set_mnemonic_prefix(o, "a/", "b/");
3046 if (o->flags.reverse_diff) {
3047 a_prefix = o->b_prefix;
3048 b_prefix = o->a_prefix;
3049 } else {
3050 a_prefix = o->a_prefix;
3051 b_prefix = o->b_prefix;
3054 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3055 (!one->mode || S_ISGITLINK(one->mode)) &&
3056 (!two->mode || S_ISGITLINK(two->mode))) {
3057 show_submodule_summary(o, one->path ? one->path : two->path,
3058 &one->oid, &two->oid,
3059 two->dirty_submodule);
3060 return;
3061 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3062 (!one->mode || S_ISGITLINK(one->mode)) &&
3063 (!two->mode || S_ISGITLINK(two->mode))) {
3064 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3065 &one->oid, &two->oid,
3066 two->dirty_submodule);
3067 return;
3070 if (o->flags.allow_textconv) {
3071 textconv_one = get_textconv(one);
3072 textconv_two = get_textconv(two);
3075 /* Never use a non-valid filename anywhere if at all possible */
3076 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3077 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3079 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3080 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3081 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3082 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3083 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3084 if (lbl[0][0] == '/') {
3085 /* /dev/null */
3086 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3087 if (xfrm_msg)
3088 strbuf_addstr(&header, xfrm_msg);
3089 must_show_header = 1;
3091 else if (lbl[1][0] == '/') {
3092 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3093 if (xfrm_msg)
3094 strbuf_addstr(&header, xfrm_msg);
3095 must_show_header = 1;
3097 else {
3098 if (one->mode != two->mode) {
3099 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3100 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3101 must_show_header = 1;
3103 if (xfrm_msg)
3104 strbuf_addstr(&header, xfrm_msg);
3107 * we do not run diff between different kind
3108 * of objects.
3110 if ((one->mode ^ two->mode) & S_IFMT)
3111 goto free_ab_and_return;
3112 if (complete_rewrite &&
3113 (textconv_one || !diff_filespec_is_binary(one)) &&
3114 (textconv_two || !diff_filespec_is_binary(two))) {
3115 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3116 header.buf, header.len, 0);
3117 strbuf_reset(&header);
3118 emit_rewrite_diff(name_a, name_b, one, two,
3119 textconv_one, textconv_two, o);
3120 o->found_changes = 1;
3121 goto free_ab_and_return;
3125 if (o->irreversible_delete && lbl[1][0] == '/') {
3126 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3127 header.len, 0);
3128 strbuf_reset(&header);
3129 goto free_ab_and_return;
3130 } else if (!o->flags.text &&
3131 ( (!textconv_one && diff_filespec_is_binary(one)) ||
3132 (!textconv_two && diff_filespec_is_binary(two)) )) {
3133 struct strbuf sb = STRBUF_INIT;
3134 if (!one->data && !two->data &&
3135 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3136 !o->flags.binary) {
3137 if (!oidcmp(&one->oid, &two->oid)) {
3138 if (must_show_header)
3139 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3140 header.buf, header.len,
3142 goto free_ab_and_return;
3144 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3145 header.buf, header.len, 0);
3146 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3147 diff_line_prefix(o), lbl[0], lbl[1]);
3148 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3149 sb.buf, sb.len, 0);
3150 strbuf_release(&sb);
3151 goto free_ab_and_return;
3153 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3154 die("unable to read files to diff");
3155 /* Quite common confusing case */
3156 if (mf1.size == mf2.size &&
3157 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3158 if (must_show_header)
3159 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3160 header.buf, header.len, 0);
3161 goto free_ab_and_return;
3163 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3164 strbuf_reset(&header);
3165 if (o->flags.binary)
3166 emit_binary_diff(o, &mf1, &mf2);
3167 else {
3168 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3169 diff_line_prefix(o), lbl[0], lbl[1]);
3170 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3171 sb.buf, sb.len, 0);
3172 strbuf_release(&sb);
3174 o->found_changes = 1;
3175 } else {
3176 /* Crazy xdl interfaces.. */
3177 const char *diffopts = getenv("GIT_DIFF_OPTS");
3178 const char *v;
3179 xpparam_t xpp;
3180 xdemitconf_t xecfg;
3181 struct emit_callback ecbdata;
3182 const struct userdiff_funcname *pe;
3184 if (must_show_header) {
3185 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3186 header.buf, header.len, 0);
3187 strbuf_reset(&header);
3190 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
3191 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
3193 pe = diff_funcname_pattern(one);
3194 if (!pe)
3195 pe = diff_funcname_pattern(two);
3197 memset(&xpp, 0, sizeof(xpp));
3198 memset(&xecfg, 0, sizeof(xecfg));
3199 memset(&ecbdata, 0, sizeof(ecbdata));
3200 ecbdata.label_path = lbl;
3201 ecbdata.color_diff = want_color(o->use_color);
3202 ecbdata.ws_rule = whitespace_rule(name_b);
3203 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3204 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3205 ecbdata.opt = o;
3206 ecbdata.header = header.len ? &header : NULL;
3207 xpp.flags = o->xdl_opts;
3208 xpp.anchors = o->anchors;
3209 xpp.anchors_nr = o->anchors_nr;
3210 xecfg.ctxlen = o->context;
3211 xecfg.interhunkctxlen = o->interhunkcontext;
3212 xecfg.flags = XDL_EMIT_FUNCNAMES;
3213 if (o->flags.funccontext)
3214 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3215 if (pe)
3216 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3217 if (!diffopts)
3219 else if (skip_prefix(diffopts, "--unified=", &v))
3220 xecfg.ctxlen = strtoul(v, NULL, 10);
3221 else if (skip_prefix(diffopts, "-u", &v))
3222 xecfg.ctxlen = strtoul(v, NULL, 10);
3223 if (o->word_diff)
3224 init_diff_words_data(&ecbdata, o, one, two);
3225 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
3226 &xpp, &xecfg))
3227 die("unable to generate diff for %s", one->path);
3228 if (o->word_diff)
3229 free_diff_words_data(&ecbdata);
3230 if (textconv_one)
3231 free(mf1.ptr);
3232 if (textconv_two)
3233 free(mf2.ptr);
3234 xdiff_clear_find_func(&xecfg);
3237 free_ab_and_return:
3238 strbuf_release(&header);
3239 diff_free_filespec_data(one);
3240 diff_free_filespec_data(two);
3241 free(a_one);
3242 free(b_two);
3243 return;
3246 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3248 if (!is_renamed) {
3249 if (p->status == DIFF_STATUS_ADDED) {
3250 if (S_ISLNK(p->two->mode))
3251 return "new +l";
3252 else if ((p->two->mode & 0777) == 0755)
3253 return "new +x";
3254 else
3255 return "new";
3256 } else if (p->status == DIFF_STATUS_DELETED)
3257 return "gone";
3259 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3260 return "mode -l";
3261 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3262 return "mode +l";
3263 else if ((p->one->mode & 0777) == 0644 &&
3264 (p->two->mode & 0777) == 0755)
3265 return "mode +x";
3266 else if ((p->one->mode & 0777) == 0755 &&
3267 (p->two->mode & 0777) == 0644)
3268 return "mode -x";
3269 return NULL;
3272 static void builtin_diffstat(const char *name_a, const char *name_b,
3273 struct diff_filespec *one,
3274 struct diff_filespec *two,
3275 struct diffstat_t *diffstat,
3276 struct diff_options *o,
3277 struct diff_filepair *p)
3279 mmfile_t mf1, mf2;
3280 struct diffstat_file *data;
3281 int same_contents;
3282 int complete_rewrite = 0;
3284 if (!DIFF_PAIR_UNMERGED(p)) {
3285 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3286 complete_rewrite = 1;
3289 data = diffstat_add(diffstat, name_a, name_b);
3290 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3291 if (o->flags.stat_with_summary)
3292 data->comments = get_compact_summary(p, data->is_renamed);
3294 if (!one || !two) {
3295 data->is_unmerged = 1;
3296 return;
3299 same_contents = !oidcmp(&one->oid, &two->oid);
3301 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
3302 data->is_binary = 1;
3303 if (same_contents) {
3304 data->added = 0;
3305 data->deleted = 0;
3306 } else {
3307 data->added = diff_filespec_size(two);
3308 data->deleted = diff_filespec_size(one);
3312 else if (complete_rewrite) {
3313 diff_populate_filespec(one, 0);
3314 diff_populate_filespec(two, 0);
3315 data->deleted = count_lines(one->data, one->size);
3316 data->added = count_lines(two->data, two->size);
3319 else if (!same_contents) {
3320 /* Crazy xdl interfaces.. */
3321 xpparam_t xpp;
3322 xdemitconf_t xecfg;
3324 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3325 die("unable to read files to diff");
3327 memset(&xpp, 0, sizeof(xpp));
3328 memset(&xecfg, 0, sizeof(xecfg));
3329 xpp.flags = o->xdl_opts;
3330 xpp.anchors = o->anchors;
3331 xpp.anchors_nr = o->anchors_nr;
3332 xecfg.ctxlen = o->context;
3333 xecfg.interhunkctxlen = o->interhunkcontext;
3334 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
3335 &xpp, &xecfg))
3336 die("unable to generate diffstat for %s", one->path);
3339 diff_free_filespec_data(one);
3340 diff_free_filespec_data(two);
3343 static void builtin_checkdiff(const char *name_a, const char *name_b,
3344 const char *attr_path,
3345 struct diff_filespec *one,
3346 struct diff_filespec *two,
3347 struct diff_options *o)
3349 mmfile_t mf1, mf2;
3350 struct checkdiff_t data;
3352 if (!two)
3353 return;
3355 memset(&data, 0, sizeof(data));
3356 data.filename = name_b ? name_b : name_a;
3357 data.lineno = 0;
3358 data.o = o;
3359 data.ws_rule = whitespace_rule(attr_path);
3360 data.conflict_marker_size = ll_merge_marker_size(attr_path);
3362 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3363 die("unable to read files to diff");
3366 * All the other codepaths check both sides, but not checking
3367 * the "old" side here is deliberate. We are checking the newly
3368 * introduced changes, and as long as the "new" side is text, we
3369 * can and should check what it introduces.
3371 if (diff_filespec_is_binary(two))
3372 goto free_and_return;
3373 else {
3374 /* Crazy xdl interfaces.. */
3375 xpparam_t xpp;
3376 xdemitconf_t xecfg;
3378 memset(&xpp, 0, sizeof(xpp));
3379 memset(&xecfg, 0, sizeof(xecfg));
3380 xecfg.ctxlen = 1; /* at least one context line */
3381 xpp.flags = 0;
3382 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
3383 &xpp, &xecfg))
3384 die("unable to generate checkdiff for %s", one->path);
3386 if (data.ws_rule & WS_BLANK_AT_EOF) {
3387 struct emit_callback ecbdata;
3388 int blank_at_eof;
3390 ecbdata.ws_rule = data.ws_rule;
3391 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3392 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3394 if (blank_at_eof) {
3395 static char *err;
3396 if (!err)
3397 err = whitespace_error_string(WS_BLANK_AT_EOF);
3398 fprintf(o->file, "%s:%d: %s.\n",
3399 data.filename, blank_at_eof, err);
3400 data.status = 1; /* report errors */
3404 free_and_return:
3405 diff_free_filespec_data(one);
3406 diff_free_filespec_data(two);
3407 if (data.status)
3408 o->flags.check_failed = 1;
3411 struct diff_filespec *alloc_filespec(const char *path)
3413 struct diff_filespec *spec;
3415 FLEXPTR_ALLOC_STR(spec, path, path);
3416 spec->count = 1;
3417 spec->is_binary = -1;
3418 return spec;
3421 void free_filespec(struct diff_filespec *spec)
3423 if (!--spec->count) {
3424 diff_free_filespec_data(spec);
3425 free(spec);
3429 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3430 int oid_valid, unsigned short mode)
3432 if (mode) {
3433 spec->mode = canon_mode(mode);
3434 oidcpy(&spec->oid, oid);
3435 spec->oid_valid = oid_valid;
3440 * Given a name and sha1 pair, if the index tells us the file in
3441 * the work tree has that object contents, return true, so that
3442 * prepare_temp_file() does not have to inflate and extract.
3444 static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
3446 const struct cache_entry *ce;
3447 struct stat st;
3448 int pos, len;
3451 * We do not read the cache ourselves here, because the
3452 * benchmark with my previous version that always reads cache
3453 * shows that it makes things worse for diff-tree comparing
3454 * two linux-2.6 kernel trees in an already checked out work
3455 * tree. This is because most diff-tree comparisons deal with
3456 * only a small number of files, while reading the cache is
3457 * expensive for a large project, and its cost outweighs the
3458 * savings we get by not inflating the object to a temporary
3459 * file. Practically, this code only helps when we are used
3460 * by diff-cache --cached, which does read the cache before
3461 * calling us.
3463 if (!active_cache)
3464 return 0;
3466 /* We want to avoid the working directory if our caller
3467 * doesn't need the data in a normal file, this system
3468 * is rather slow with its stat/open/mmap/close syscalls,
3469 * and the object is contained in a pack file. The pack
3470 * is probably already open and will be faster to obtain
3471 * the data through than the working directory. Loose
3472 * objects however would tend to be slower as they need
3473 * to be individually opened and inflated.
3475 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
3476 return 0;
3479 * Similarly, if we'd have to convert the file contents anyway, that
3480 * makes the optimization not worthwhile.
3482 if (!want_file && would_convert_to_git(&the_index, name))
3483 return 0;
3485 len = strlen(name);
3486 pos = cache_name_pos(name, len);
3487 if (pos < 0)
3488 return 0;
3489 ce = active_cache[pos];
3492 * This is not the sha1 we are looking for, or
3493 * unreusable because it is not a regular file.
3495 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3496 return 0;
3499 * If ce is marked as "assume unchanged", there is no
3500 * guarantee that work tree matches what we are looking for.
3502 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3503 return 0;
3506 * If ce matches the file in the work tree, we can reuse it.
3508 if (ce_uptodate(ce) ||
3509 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3510 return 1;
3512 return 0;
3515 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3517 struct strbuf buf = STRBUF_INIT;
3518 char *dirty = "";
3520 /* Are we looking at the work tree? */
3521 if (s->dirty_submodule)
3522 dirty = "-dirty";
3524 strbuf_addf(&buf, "Subproject commit %s%s\n",
3525 oid_to_hex(&s->oid), dirty);
3526 s->size = buf.len;
3527 if (size_only) {
3528 s->data = NULL;
3529 strbuf_release(&buf);
3530 } else {
3531 s->data = strbuf_detach(&buf, NULL);
3532 s->should_free = 1;
3534 return 0;
3538 * While doing rename detection and pickaxe operation, we may need to
3539 * grab the data for the blob (or file) for our own in-core comparison.
3540 * diff_filespec has data and size fields for this purpose.
3542 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
3544 int size_only = flags & CHECK_SIZE_ONLY;
3545 int err = 0;
3546 int conv_flags = global_conv_flags_eol;
3548 * demote FAIL to WARN to allow inspecting the situation
3549 * instead of refusing.
3551 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3552 conv_flags = CONV_EOL_RNDTRP_WARN;
3554 if (!DIFF_FILE_VALID(s))
3555 die("internal error: asking to populate invalid file.");
3556 if (S_ISDIR(s->mode))
3557 return -1;
3559 if (s->data)
3560 return 0;
3562 if (size_only && 0 < s->size)
3563 return 0;
3565 if (S_ISGITLINK(s->mode))
3566 return diff_populate_gitlink(s, size_only);
3568 if (!s->oid_valid ||
3569 reuse_worktree_file(s->path, &s->oid, 0)) {
3570 struct strbuf buf = STRBUF_INIT;
3571 struct stat st;
3572 int fd;
3574 if (lstat(s->path, &st) < 0) {
3575 err_empty:
3576 err = -1;
3577 empty:
3578 s->data = (char *)"";
3579 s->size = 0;
3580 return err;
3582 s->size = xsize_t(st.st_size);
3583 if (!s->size)
3584 goto empty;
3585 if (S_ISLNK(st.st_mode)) {
3586 struct strbuf sb = STRBUF_INIT;
3588 if (strbuf_readlink(&sb, s->path, s->size))
3589 goto err_empty;
3590 s->size = sb.len;
3591 s->data = strbuf_detach(&sb, NULL);
3592 s->should_free = 1;
3593 return 0;
3597 * Even if the caller would be happy with getting
3598 * only the size, we cannot return early at this
3599 * point if the path requires us to run the content
3600 * conversion.
3602 if (size_only && !would_convert_to_git(&the_index, s->path))
3603 return 0;
3606 * Note: this check uses xsize_t(st.st_size) that may
3607 * not be the true size of the blob after it goes
3608 * through convert_to_git(). This may not strictly be
3609 * correct, but the whole point of big_file_threshold
3610 * and is_binary check being that we want to avoid
3611 * opening the file and inspecting the contents, this
3612 * is probably fine.
3614 if ((flags & CHECK_BINARY) &&
3615 s->size > big_file_threshold && s->is_binary == -1) {
3616 s->is_binary = 1;
3617 return 0;
3619 fd = open(s->path, O_RDONLY);
3620 if (fd < 0)
3621 goto err_empty;
3622 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3623 close(fd);
3624 s->should_munmap = 1;
3627 * Convert from working tree format to canonical git format
3629 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, conv_flags)) {
3630 size_t size = 0;
3631 munmap(s->data, s->size);
3632 s->should_munmap = 0;
3633 s->data = strbuf_detach(&buf, &size);
3634 s->size = size;
3635 s->should_free = 1;
3638 else {
3639 enum object_type type;
3640 if (size_only || (flags & CHECK_BINARY)) {
3641 type = oid_object_info(&s->oid, &s->size);
3642 if (type < 0)
3643 die("unable to read %s",
3644 oid_to_hex(&s->oid));
3645 if (size_only)
3646 return 0;
3647 if (s->size > big_file_threshold && s->is_binary == -1) {
3648 s->is_binary = 1;
3649 return 0;
3652 s->data = read_object_file(&s->oid, &type, &s->size);
3653 if (!s->data)
3654 die("unable to read %s", oid_to_hex(&s->oid));
3655 s->should_free = 1;
3657 return 0;
3660 void diff_free_filespec_blob(struct diff_filespec *s)
3662 if (s->should_free)
3663 free(s->data);
3664 else if (s->should_munmap)
3665 munmap(s->data, s->size);
3667 if (s->should_free || s->should_munmap) {
3668 s->should_free = s->should_munmap = 0;
3669 s->data = NULL;
3673 void diff_free_filespec_data(struct diff_filespec *s)
3675 diff_free_filespec_blob(s);
3676 FREE_AND_NULL(s->cnt_data);
3679 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
3680 void *blob,
3681 unsigned long size,
3682 const struct object_id *oid,
3683 int mode)
3685 struct strbuf buf = STRBUF_INIT;
3686 struct strbuf tempfile = STRBUF_INIT;
3687 char *path_dup = xstrdup(path);
3688 const char *base = basename(path_dup);
3690 /* Generate "XXXXXX_basename.ext" */
3691 strbuf_addstr(&tempfile, "XXXXXX_");
3692 strbuf_addstr(&tempfile, base);
3694 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
3695 if (!temp->tempfile)
3696 die_errno("unable to create temp-file");
3697 if (convert_to_working_tree(path,
3698 (const char *)blob, (size_t)size, &buf)) {
3699 blob = buf.buf;
3700 size = buf.len;
3702 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
3703 close_tempfile_gently(temp->tempfile))
3704 die_errno("unable to write temp-file");
3705 temp->name = get_tempfile_path(temp->tempfile);
3706 oid_to_hex_r(temp->hex, oid);
3707 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
3708 strbuf_release(&buf);
3709 strbuf_release(&tempfile);
3710 free(path_dup);
3713 static struct diff_tempfile *prepare_temp_file(const char *name,
3714 struct diff_filespec *one)
3716 struct diff_tempfile *temp = claim_diff_tempfile();
3718 if (!DIFF_FILE_VALID(one)) {
3719 not_a_valid_file:
3720 /* A '-' entry produces this for file-2, and
3721 * a '+' entry produces this for file-1.
3723 temp->name = "/dev/null";
3724 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3725 xsnprintf(temp->mode, sizeof(temp->mode), ".");
3726 return temp;
3729 if (!S_ISGITLINK(one->mode) &&
3730 (!one->oid_valid ||
3731 reuse_worktree_file(name, &one->oid, 1))) {
3732 struct stat st;
3733 if (lstat(name, &st) < 0) {
3734 if (errno == ENOENT)
3735 goto not_a_valid_file;
3736 die_errno("stat(%s)", name);
3738 if (S_ISLNK(st.st_mode)) {
3739 struct strbuf sb = STRBUF_INIT;
3740 if (strbuf_readlink(&sb, name, st.st_size) < 0)
3741 die_errno("readlink(%s)", name);
3742 prep_temp_blob(name, temp, sb.buf, sb.len,
3743 (one->oid_valid ?
3744 &one->oid : &null_oid),
3745 (one->oid_valid ?
3746 one->mode : S_IFLNK));
3747 strbuf_release(&sb);
3749 else {
3750 /* we can borrow from the file in the work tree */
3751 temp->name = name;
3752 if (!one->oid_valid)
3753 oid_to_hex_r(temp->hex, &null_oid);
3754 else
3755 oid_to_hex_r(temp->hex, &one->oid);
3756 /* Even though we may sometimes borrow the
3757 * contents from the work tree, we always want
3758 * one->mode. mode is trustworthy even when
3759 * !(one->oid_valid), as long as
3760 * DIFF_FILE_VALID(one).
3762 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
3764 return temp;
3766 else {
3767 if (diff_populate_filespec(one, 0))
3768 die("cannot read data blob for %s", one->path);
3769 prep_temp_blob(name, temp, one->data, one->size,
3770 &one->oid, one->mode);
3772 return temp;
3775 static void add_external_diff_name(struct argv_array *argv,
3776 const char *name,
3777 struct diff_filespec *df)
3779 struct diff_tempfile *temp = prepare_temp_file(name, df);
3780 argv_array_push(argv, temp->name);
3781 argv_array_push(argv, temp->hex);
3782 argv_array_push(argv, temp->mode);
3785 /* An external diff command takes:
3787 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3788 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3791 static void run_external_diff(const char *pgm,
3792 const char *name,
3793 const char *other,
3794 struct diff_filespec *one,
3795 struct diff_filespec *two,
3796 const char *xfrm_msg,
3797 int complete_rewrite,
3798 struct diff_options *o)
3800 struct argv_array argv = ARGV_ARRAY_INIT;
3801 struct argv_array env = ARGV_ARRAY_INIT;
3802 struct diff_queue_struct *q = &diff_queued_diff;
3804 argv_array_push(&argv, pgm);
3805 argv_array_push(&argv, name);
3807 if (one && two) {
3808 add_external_diff_name(&argv, name, one);
3809 if (!other)
3810 add_external_diff_name(&argv, name, two);
3811 else {
3812 add_external_diff_name(&argv, other, two);
3813 argv_array_push(&argv, other);
3814 argv_array_push(&argv, xfrm_msg);
3818 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3819 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3821 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3822 die(_("external diff died, stopping at %s"), name);
3824 remove_tempfile();
3825 argv_array_clear(&argv);
3826 argv_array_clear(&env);
3829 static int similarity_index(struct diff_filepair *p)
3831 return p->score * 100 / MAX_SCORE;
3834 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3836 if (startup_info->have_repository)
3837 return find_unique_abbrev(oid, abbrev);
3838 else {
3839 char *hex = oid_to_hex(oid);
3840 if (abbrev < 0)
3841 abbrev = FALLBACK_DEFAULT_ABBREV;
3842 if (abbrev > GIT_SHA1_HEXSZ)
3843 die("BUG: oid abbreviation out of range: %d", abbrev);
3844 if (abbrev)
3845 hex[abbrev] = '\0';
3846 return hex;
3850 static void fill_metainfo(struct strbuf *msg,
3851 const char *name,
3852 const char *other,
3853 struct diff_filespec *one,
3854 struct diff_filespec *two,
3855 struct diff_options *o,
3856 struct diff_filepair *p,
3857 int *must_show_header,
3858 int use_color)
3860 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3861 const char *reset = diff_get_color(use_color, DIFF_RESET);
3862 const char *line_prefix = diff_line_prefix(o);
3864 *must_show_header = 1;
3865 strbuf_init(msg, PATH_MAX * 2 + 300);
3866 switch (p->status) {
3867 case DIFF_STATUS_COPIED:
3868 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3869 line_prefix, set, similarity_index(p));
3870 strbuf_addf(msg, "%s\n%s%scopy from ",
3871 reset, line_prefix, set);
3872 quote_c_style(name, msg, NULL, 0);
3873 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3874 quote_c_style(other, msg, NULL, 0);
3875 strbuf_addf(msg, "%s\n", reset);
3876 break;
3877 case DIFF_STATUS_RENAMED:
3878 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3879 line_prefix, set, similarity_index(p));
3880 strbuf_addf(msg, "%s\n%s%srename from ",
3881 reset, line_prefix, set);
3882 quote_c_style(name, msg, NULL, 0);
3883 strbuf_addf(msg, "%s\n%s%srename to ",
3884 reset, line_prefix, set);
3885 quote_c_style(other, msg, NULL, 0);
3886 strbuf_addf(msg, "%s\n", reset);
3887 break;
3888 case DIFF_STATUS_MODIFIED:
3889 if (p->score) {
3890 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3891 line_prefix,
3892 set, similarity_index(p), reset);
3893 break;
3895 /* fallthru */
3896 default:
3897 *must_show_header = 0;
3899 if (one && two && oidcmp(&one->oid, &two->oid)) {
3900 int abbrev = o->flags.full_index ? 40 : DEFAULT_ABBREV;
3902 if (o->flags.binary) {
3903 mmfile_t mf;
3904 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3905 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3906 abbrev = 40;
3908 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3909 diff_abbrev_oid(&one->oid, abbrev),
3910 diff_abbrev_oid(&two->oid, abbrev));
3911 if (one->mode == two->mode)
3912 strbuf_addf(msg, " %06o", one->mode);
3913 strbuf_addf(msg, "%s\n", reset);
3917 static void run_diff_cmd(const char *pgm,
3918 const char *name,
3919 const char *other,
3920 const char *attr_path,
3921 struct diff_filespec *one,
3922 struct diff_filespec *two,
3923 struct strbuf *msg,
3924 struct diff_options *o,
3925 struct diff_filepair *p)
3927 const char *xfrm_msg = NULL;
3928 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3929 int must_show_header = 0;
3932 if (o->flags.allow_external) {
3933 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3934 if (drv && drv->external)
3935 pgm = drv->external;
3938 if (msg) {
3940 * don't use colors when the header is intended for an
3941 * external diff driver
3943 fill_metainfo(msg, name, other, one, two, o, p,
3944 &must_show_header,
3945 want_color(o->use_color) && !pgm);
3946 xfrm_msg = msg->len ? msg->buf : NULL;
3949 if (pgm) {
3950 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3951 complete_rewrite, o);
3952 return;
3954 if (one && two)
3955 builtin_diff(name, other ? other : name,
3956 one, two, xfrm_msg, must_show_header,
3957 o, complete_rewrite);
3958 else
3959 fprintf(o->file, "* Unmerged path %s\n", name);
3962 static void diff_fill_oid_info(struct diff_filespec *one)
3964 if (DIFF_FILE_VALID(one)) {
3965 if (!one->oid_valid) {
3966 struct stat st;
3967 if (one->is_stdin) {
3968 oidclr(&one->oid);
3969 return;
3971 if (lstat(one->path, &st) < 0)
3972 die_errno("stat '%s'", one->path);
3973 if (index_path(&one->oid, one->path, &st, 0))
3974 die("cannot hash %s", one->path);
3977 else
3978 oidclr(&one->oid);
3981 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3983 /* Strip the prefix but do not molest /dev/null and absolute paths */
3984 if (*namep && **namep != '/') {
3985 *namep += prefix_length;
3986 if (**namep == '/')
3987 ++*namep;
3989 if (*otherp && **otherp != '/') {
3990 *otherp += prefix_length;
3991 if (**otherp == '/')
3992 ++*otherp;
3996 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3998 const char *pgm = external_diff();
3999 struct strbuf msg;
4000 struct diff_filespec *one = p->one;
4001 struct diff_filespec *two = p->two;
4002 const char *name;
4003 const char *other;
4004 const char *attr_path;
4006 name = one->path;
4007 other = (strcmp(name, two->path) ? two->path : NULL);
4008 attr_path = name;
4009 if (o->prefix_length)
4010 strip_prefix(o->prefix_length, &name, &other);
4012 if (!o->flags.allow_external)
4013 pgm = NULL;
4015 if (DIFF_PAIR_UNMERGED(p)) {
4016 run_diff_cmd(pgm, name, NULL, attr_path,
4017 NULL, NULL, NULL, o, p);
4018 return;
4021 diff_fill_oid_info(one);
4022 diff_fill_oid_info(two);
4024 if (!pgm &&
4025 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4026 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4028 * a filepair that changes between file and symlink
4029 * needs to be split into deletion and creation.
4031 struct diff_filespec *null = alloc_filespec(two->path);
4032 run_diff_cmd(NULL, name, other, attr_path,
4033 one, null, &msg, o, p);
4034 free(null);
4035 strbuf_release(&msg);
4037 null = alloc_filespec(one->path);
4038 run_diff_cmd(NULL, name, other, attr_path,
4039 null, two, &msg, o, p);
4040 free(null);
4042 else
4043 run_diff_cmd(pgm, name, other, attr_path,
4044 one, two, &msg, o, p);
4046 strbuf_release(&msg);
4049 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4050 struct diffstat_t *diffstat)
4052 const char *name;
4053 const char *other;
4055 if (DIFF_PAIR_UNMERGED(p)) {
4056 /* unmerged */
4057 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
4058 return;
4061 name = p->one->path;
4062 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4064 if (o->prefix_length)
4065 strip_prefix(o->prefix_length, &name, &other);
4067 diff_fill_oid_info(p->one);
4068 diff_fill_oid_info(p->two);
4070 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
4073 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4075 const char *name;
4076 const char *other;
4077 const char *attr_path;
4079 if (DIFF_PAIR_UNMERGED(p)) {
4080 /* unmerged */
4081 return;
4084 name = p->one->path;
4085 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4086 attr_path = other ? other : name;
4088 if (o->prefix_length)
4089 strip_prefix(o->prefix_length, &name, &other);
4091 diff_fill_oid_info(p->one);
4092 diff_fill_oid_info(p->two);
4094 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4097 void diff_setup(struct diff_options *options)
4099 memcpy(options, &default_diff_options, sizeof(*options));
4101 options->file = stdout;
4103 options->abbrev = DEFAULT_ABBREV;
4104 options->line_termination = '\n';
4105 options->break_opt = -1;
4106 options->rename_limit = -1;
4107 options->dirstat_permille = diff_dirstat_permille_default;
4108 options->context = diff_context_default;
4109 options->interhunkcontext = diff_interhunk_context_default;
4110 options->ws_error_highlight = ws_error_highlight_default;
4111 options->flags.rename_empty = 1;
4112 options->objfind = NULL;
4114 /* pathchange left =NULL by default */
4115 options->change = diff_change;
4116 options->add_remove = diff_addremove;
4117 options->use_color = diff_use_color_default;
4118 options->detect_rename = diff_detect_rename_default;
4119 options->xdl_opts |= diff_algorithm;
4120 if (diff_indent_heuristic)
4121 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4123 options->orderfile = diff_order_file_cfg;
4125 if (diff_no_prefix) {
4126 options->a_prefix = options->b_prefix = "";
4127 } else if (!diff_mnemonic_prefix) {
4128 options->a_prefix = "a/";
4129 options->b_prefix = "b/";
4132 options->color_moved = diff_color_moved_default;
4135 void diff_setup_done(struct diff_options *options)
4137 unsigned check_mask = DIFF_FORMAT_NAME |
4138 DIFF_FORMAT_NAME_STATUS |
4139 DIFF_FORMAT_CHECKDIFF |
4140 DIFF_FORMAT_NO_OUTPUT;
4142 if (options->set_default)
4143 options->set_default(options);
4145 if (HAS_MULTI_BITS(options->output_format & check_mask))
4146 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4148 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4149 die(_("-G, -S and --find-object are mutually exclusive"));
4152 * Most of the time we can say "there are changes"
4153 * only by checking if there are changed paths, but
4154 * --ignore-whitespace* options force us to look
4155 * inside contents.
4158 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
4159 options->flags.diff_from_contents = 1;
4160 else
4161 options->flags.diff_from_contents = 0;
4163 if (options->flags.find_copies_harder)
4164 options->detect_rename = DIFF_DETECT_COPY;
4166 if (!options->flags.relative_name)
4167 options->prefix = NULL;
4168 if (options->prefix)
4169 options->prefix_length = strlen(options->prefix);
4170 else
4171 options->prefix_length = 0;
4173 if (options->output_format & (DIFF_FORMAT_NAME |
4174 DIFF_FORMAT_NAME_STATUS |
4175 DIFF_FORMAT_CHECKDIFF |
4176 DIFF_FORMAT_NO_OUTPUT))
4177 options->output_format &= ~(DIFF_FORMAT_RAW |
4178 DIFF_FORMAT_NUMSTAT |
4179 DIFF_FORMAT_DIFFSTAT |
4180 DIFF_FORMAT_SHORTSTAT |
4181 DIFF_FORMAT_DIRSTAT |
4182 DIFF_FORMAT_SUMMARY |
4183 DIFF_FORMAT_PATCH);
4186 * These cases always need recursive; we do not drop caller-supplied
4187 * recursive bits for other formats here.
4189 if (options->output_format & (DIFF_FORMAT_PATCH |
4190 DIFF_FORMAT_NUMSTAT |
4191 DIFF_FORMAT_DIFFSTAT |
4192 DIFF_FORMAT_SHORTSTAT |
4193 DIFF_FORMAT_DIRSTAT |
4194 DIFF_FORMAT_SUMMARY |
4195 DIFF_FORMAT_CHECKDIFF))
4196 options->flags.recursive = 1;
4198 * Also pickaxe would not work very well if you do not say recursive
4200 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4201 options->flags.recursive = 1;
4203 * When patches are generated, submodules diffed against the work tree
4204 * must be checked for dirtiness too so it can be shown in the output
4206 if (options->output_format & DIFF_FORMAT_PATCH)
4207 options->flags.dirty_submodules = 1;
4209 if (options->detect_rename && options->rename_limit < 0)
4210 options->rename_limit = diff_rename_limit_default;
4211 if (options->setup & DIFF_SETUP_USE_CACHE) {
4212 if (!active_cache)
4213 /* read-cache does not die even when it fails
4214 * so it is safe for us to do this here. Also
4215 * it does not smudge active_cache or active_nr
4216 * when it fails, so we do not have to worry about
4217 * cleaning it up ourselves either.
4219 read_cache();
4221 if (40 < options->abbrev)
4222 options->abbrev = 40; /* full */
4225 * It does not make sense to show the first hit we happened
4226 * to have found. It does not make sense not to return with
4227 * exit code in such a case either.
4229 if (options->flags.quick) {
4230 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4231 options->flags.exit_with_status = 1;
4234 options->diff_path_counter = 0;
4236 if (options->flags.follow_renames && options->pathspec.nr != 1)
4237 die(_("--follow requires exactly one pathspec"));
4239 if (!options->use_color || external_diff())
4240 options->color_moved = 0;
4243 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4245 char c, *eq;
4246 int len;
4248 if (*arg != '-')
4249 return 0;
4250 c = *++arg;
4251 if (!c)
4252 return 0;
4253 if (c == arg_short) {
4254 c = *++arg;
4255 if (!c)
4256 return 1;
4257 if (val && isdigit(c)) {
4258 char *end;
4259 int n = strtoul(arg, &end, 10);
4260 if (*end)
4261 return 0;
4262 *val = n;
4263 return 1;
4265 return 0;
4267 if (c != '-')
4268 return 0;
4269 arg++;
4270 eq = strchrnul(arg, '=');
4271 len = eq - arg;
4272 if (!len || strncmp(arg, arg_long, len))
4273 return 0;
4274 if (*eq) {
4275 int n;
4276 char *end;
4277 if (!isdigit(*++eq))
4278 return 0;
4279 n = strtoul(eq, &end, 10);
4280 if (*end)
4281 return 0;
4282 *val = n;
4284 return 1;
4287 static int diff_scoreopt_parse(const char *opt);
4289 static inline int short_opt(char opt, const char **argv,
4290 const char **optarg)
4292 const char *arg = argv[0];
4293 if (arg[0] != '-' || arg[1] != opt)
4294 return 0;
4295 if (arg[2] != '\0') {
4296 *optarg = arg + 2;
4297 return 1;
4299 if (!argv[1])
4300 die("Option '%c' requires a value", opt);
4301 *optarg = argv[1];
4302 return 2;
4305 int parse_long_opt(const char *opt, const char **argv,
4306 const char **optarg)
4308 const char *arg = argv[0];
4309 if (!skip_prefix(arg, "--", &arg))
4310 return 0;
4311 if (!skip_prefix(arg, opt, &arg))
4312 return 0;
4313 if (*arg == '=') { /* stuck form: --option=value */
4314 *optarg = arg + 1;
4315 return 1;
4317 if (*arg != '\0')
4318 return 0;
4319 /* separate form: --option value */
4320 if (!argv[1])
4321 die("Option '--%s' requires a value", opt);
4322 *optarg = argv[1];
4323 return 2;
4326 static int stat_opt(struct diff_options *options, const char **av)
4328 const char *arg = av[0];
4329 char *end;
4330 int width = options->stat_width;
4331 int name_width = options->stat_name_width;
4332 int graph_width = options->stat_graph_width;
4333 int count = options->stat_count;
4334 int argcount = 1;
4336 if (!skip_prefix(arg, "--stat", &arg))
4337 die("BUG: stat option does not begin with --stat: %s", arg);
4338 end = (char *)arg;
4340 switch (*arg) {
4341 case '-':
4342 if (skip_prefix(arg, "-width", &arg)) {
4343 if (*arg == '=')
4344 width = strtoul(arg + 1, &end, 10);
4345 else if (!*arg && !av[1])
4346 die_want_option("--stat-width");
4347 else if (!*arg) {
4348 width = strtoul(av[1], &end, 10);
4349 argcount = 2;
4351 } else if (skip_prefix(arg, "-name-width", &arg)) {
4352 if (*arg == '=')
4353 name_width = strtoul(arg + 1, &end, 10);
4354 else if (!*arg && !av[1])
4355 die_want_option("--stat-name-width");
4356 else if (!*arg) {
4357 name_width = strtoul(av[1], &end, 10);
4358 argcount = 2;
4360 } else if (skip_prefix(arg, "-graph-width", &arg)) {
4361 if (*arg == '=')
4362 graph_width = strtoul(arg + 1, &end, 10);
4363 else if (!*arg && !av[1])
4364 die_want_option("--stat-graph-width");
4365 else if (!*arg) {
4366 graph_width = strtoul(av[1], &end, 10);
4367 argcount = 2;
4369 } else if (skip_prefix(arg, "-count", &arg)) {
4370 if (*arg == '=')
4371 count = strtoul(arg + 1, &end, 10);
4372 else if (!*arg && !av[1])
4373 die_want_option("--stat-count");
4374 else if (!*arg) {
4375 count = strtoul(av[1], &end, 10);
4376 argcount = 2;
4379 break;
4380 case '=':
4381 width = strtoul(arg+1, &end, 10);
4382 if (*end == ',')
4383 name_width = strtoul(end+1, &end, 10);
4384 if (*end == ',')
4385 count = strtoul(end+1, &end, 10);
4388 /* Important! This checks all the error cases! */
4389 if (*end)
4390 return 0;
4391 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4392 options->stat_name_width = name_width;
4393 options->stat_graph_width = graph_width;
4394 options->stat_width = width;
4395 options->stat_count = count;
4396 return argcount;
4399 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4401 struct strbuf errmsg = STRBUF_INIT;
4402 if (parse_dirstat_params(options, params, &errmsg))
4403 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4404 errmsg.buf);
4405 strbuf_release(&errmsg);
4407 * The caller knows a dirstat-related option is given from the command
4408 * line; allow it to say "return this_function();"
4410 options->output_format |= DIFF_FORMAT_DIRSTAT;
4411 return 1;
4414 static int parse_submodule_opt(struct diff_options *options, const char *value)
4416 if (parse_submodule_params(options, value))
4417 die(_("Failed to parse --submodule option parameter: '%s'"),
4418 value);
4419 return 1;
4422 static const char diff_status_letters[] = {
4423 DIFF_STATUS_ADDED,
4424 DIFF_STATUS_COPIED,
4425 DIFF_STATUS_DELETED,
4426 DIFF_STATUS_MODIFIED,
4427 DIFF_STATUS_RENAMED,
4428 DIFF_STATUS_TYPE_CHANGED,
4429 DIFF_STATUS_UNKNOWN,
4430 DIFF_STATUS_UNMERGED,
4431 DIFF_STATUS_FILTER_AON,
4432 DIFF_STATUS_FILTER_BROKEN,
4433 '\0',
4436 static unsigned int filter_bit['Z' + 1];
4438 static void prepare_filter_bits(void)
4440 int i;
4442 if (!filter_bit[DIFF_STATUS_ADDED]) {
4443 for (i = 0; diff_status_letters[i]; i++)
4444 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4448 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4450 return opt->filter & filter_bit[(int) status];
4453 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4455 int i, optch;
4457 prepare_filter_bits();
4460 * If there is a negation e.g. 'd' in the input, and we haven't
4461 * initialized the filter field with another --diff-filter, start
4462 * from full set of bits, except for AON.
4464 if (!opt->filter) {
4465 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4466 if (optch < 'a' || 'z' < optch)
4467 continue;
4468 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4469 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4470 break;
4474 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4475 unsigned int bit;
4476 int negate;
4478 if ('a' <= optch && optch <= 'z') {
4479 negate = 1;
4480 optch = toupper(optch);
4481 } else {
4482 negate = 0;
4485 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4486 if (!bit)
4487 return optarg[i];
4488 if (negate)
4489 opt->filter &= ~bit;
4490 else
4491 opt->filter |= bit;
4493 return 0;
4496 static void enable_patch_output(int *fmt) {
4497 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4498 *fmt |= DIFF_FORMAT_PATCH;
4501 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4503 int val = parse_ws_error_highlight(arg);
4505 if (val < 0) {
4506 error("unknown value after ws-error-highlight=%.*s",
4507 -1 - val, arg);
4508 return 0;
4510 opt->ws_error_highlight = val;
4511 return 1;
4514 static int parse_objfind_opt(struct diff_options *opt, const char *arg)
4516 struct object_id oid;
4518 if (get_oid(arg, &oid))
4519 return error("unable to resolve '%s'", arg);
4521 if (!opt->objfind)
4522 opt->objfind = xcalloc(1, sizeof(*opt->objfind));
4524 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4525 opt->flags.recursive = 1;
4526 opt->flags.tree_in_recursive = 1;
4527 oidset_insert(opt->objfind, &oid);
4528 return 1;
4531 int diff_opt_parse(struct diff_options *options,
4532 const char **av, int ac, const char *prefix)
4534 const char *arg = av[0];
4535 const char *optarg;
4536 int argcount;
4538 if (!prefix)
4539 prefix = "";
4541 /* Output format options */
4542 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
4543 || opt_arg(arg, 'U', "unified", &options->context))
4544 enable_patch_output(&options->output_format);
4545 else if (!strcmp(arg, "--raw"))
4546 options->output_format |= DIFF_FORMAT_RAW;
4547 else if (!strcmp(arg, "--patch-with-raw")) {
4548 enable_patch_output(&options->output_format);
4549 options->output_format |= DIFF_FORMAT_RAW;
4550 } else if (!strcmp(arg, "--numstat"))
4551 options->output_format |= DIFF_FORMAT_NUMSTAT;
4552 else if (!strcmp(arg, "--shortstat"))
4553 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4554 else if (skip_prefix(arg, "-X", &arg) ||
4555 skip_to_optional_arg(arg, "--dirstat", &arg))
4556 return parse_dirstat_opt(options, arg);
4557 else if (!strcmp(arg, "--cumulative"))
4558 return parse_dirstat_opt(options, "cumulative");
4559 else if (skip_to_optional_arg(arg, "--dirstat-by-file", &arg)) {
4560 parse_dirstat_opt(options, "files");
4561 return parse_dirstat_opt(options, arg);
4563 else if (!strcmp(arg, "--check"))
4564 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4565 else if (!strcmp(arg, "--summary"))
4566 options->output_format |= DIFF_FORMAT_SUMMARY;
4567 else if (!strcmp(arg, "--patch-with-stat")) {
4568 enable_patch_output(&options->output_format);
4569 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4570 } else if (!strcmp(arg, "--name-only"))
4571 options->output_format |= DIFF_FORMAT_NAME;
4572 else if (!strcmp(arg, "--name-status"))
4573 options->output_format |= DIFF_FORMAT_NAME_STATUS;
4574 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
4575 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4576 else if (starts_with(arg, "--stat"))
4577 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4578 return stat_opt(options, av);
4579 else if (!strcmp(arg, "--compact-summary")) {
4580 options->flags.stat_with_summary = 1;
4581 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4582 } else if (!strcmp(arg, "--no-compact-summary"))
4583 options->flags.stat_with_summary = 0;
4585 /* renames options */
4586 else if (starts_with(arg, "-B") ||
4587 skip_to_optional_arg(arg, "--break-rewrites", NULL)) {
4588 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
4589 return error("invalid argument to -B: %s", arg+2);
4591 else if (starts_with(arg, "-M") ||
4592 skip_to_optional_arg(arg, "--find-renames", NULL)) {
4593 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4594 return error("invalid argument to -M: %s", arg+2);
4595 options->detect_rename = DIFF_DETECT_RENAME;
4597 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
4598 options->irreversible_delete = 1;
4600 else if (starts_with(arg, "-C") ||
4601 skip_to_optional_arg(arg, "--find-copies", NULL)) {
4602 if (options->detect_rename == DIFF_DETECT_COPY)
4603 options->flags.find_copies_harder = 1;
4604 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4605 return error("invalid argument to -C: %s", arg+2);
4606 options->detect_rename = DIFF_DETECT_COPY;
4608 else if (!strcmp(arg, "--no-renames"))
4609 options->detect_rename = 0;
4610 else if (!strcmp(arg, "--rename-empty"))
4611 options->flags.rename_empty = 1;
4612 else if (!strcmp(arg, "--no-rename-empty"))
4613 options->flags.rename_empty = 0;
4614 else if (skip_to_optional_arg_default(arg, "--relative", &arg, NULL)) {
4615 options->flags.relative_name = 1;
4616 if (arg)
4617 options->prefix = arg;
4620 /* xdiff options */
4621 else if (!strcmp(arg, "--minimal"))
4622 DIFF_XDL_SET(options, NEED_MINIMAL);
4623 else if (!strcmp(arg, "--no-minimal"))
4624 DIFF_XDL_CLR(options, NEED_MINIMAL);
4625 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
4626 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
4627 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
4628 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
4629 else if (!strcmp(arg, "--ignore-space-at-eol"))
4630 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
4631 else if (!strcmp(arg, "--ignore-cr-at-eol"))
4632 DIFF_XDL_SET(options, IGNORE_CR_AT_EOL);
4633 else if (!strcmp(arg, "--ignore-blank-lines"))
4634 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
4635 else if (!strcmp(arg, "--indent-heuristic"))
4636 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4637 else if (!strcmp(arg, "--no-indent-heuristic"))
4638 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
4639 else if (!strcmp(arg, "--patience")) {
4640 int i;
4641 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4643 * Both --patience and --anchored use PATIENCE_DIFF
4644 * internally, so remove any anchors previously
4645 * specified.
4647 for (i = 0; i < options->anchors_nr; i++)
4648 free(options->anchors[i]);
4649 options->anchors_nr = 0;
4650 } else if (!strcmp(arg, "--histogram"))
4651 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
4652 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
4653 long value = parse_algorithm_value(optarg);
4654 if (value < 0)
4655 return error("option diff-algorithm accepts \"myers\", "
4656 "\"minimal\", \"patience\" and \"histogram\"");
4657 /* clear out previous settings */
4658 DIFF_XDL_CLR(options, NEED_MINIMAL);
4659 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4660 options->xdl_opts |= value;
4661 return argcount;
4662 } else if (skip_prefix(arg, "--anchored=", &arg)) {
4663 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4664 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4665 options->anchors_alloc);
4666 options->anchors[options->anchors_nr++] = xstrdup(arg);
4669 /* flags options */
4670 else if (!strcmp(arg, "--binary")) {
4671 enable_patch_output(&options->output_format);
4672 options->flags.binary = 1;
4674 else if (!strcmp(arg, "--full-index"))
4675 options->flags.full_index = 1;
4676 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
4677 options->flags.text = 1;
4678 else if (!strcmp(arg, "-R"))
4679 options->flags.reverse_diff = 1;
4680 else if (!strcmp(arg, "--find-copies-harder"))
4681 options->flags.find_copies_harder = 1;
4682 else if (!strcmp(arg, "--follow"))
4683 options->flags.follow_renames = 1;
4684 else if (!strcmp(arg, "--no-follow")) {
4685 options->flags.follow_renames = 0;
4686 options->flags.default_follow_renames = 0;
4687 } else if (skip_to_optional_arg_default(arg, "--color", &arg, "always")) {
4688 int value = git_config_colorbool(NULL, arg);
4689 if (value < 0)
4690 return error("option `color' expects \"always\", \"auto\", or \"never\"");
4691 options->use_color = value;
4693 else if (!strcmp(arg, "--no-color"))
4694 options->use_color = 0;
4695 else if (!strcmp(arg, "--color-moved")) {
4696 if (diff_color_moved_default)
4697 options->color_moved = diff_color_moved_default;
4698 if (options->color_moved == COLOR_MOVED_NO)
4699 options->color_moved = COLOR_MOVED_DEFAULT;
4700 } else if (!strcmp(arg, "--no-color-moved"))
4701 options->color_moved = COLOR_MOVED_NO;
4702 else if (skip_prefix(arg, "--color-moved=", &arg)) {
4703 int cm = parse_color_moved(arg);
4704 if (cm < 0)
4705 die("bad --color-moved argument: %s", arg);
4706 options->color_moved = cm;
4707 } else if (skip_to_optional_arg_default(arg, "--color-words", &options->word_regex, NULL)) {
4708 options->use_color = 1;
4709 options->word_diff = DIFF_WORDS_COLOR;
4711 else if (!strcmp(arg, "--word-diff")) {
4712 if (options->word_diff == DIFF_WORDS_NONE)
4713 options->word_diff = DIFF_WORDS_PLAIN;
4715 else if (skip_prefix(arg, "--word-diff=", &arg)) {
4716 if (!strcmp(arg, "plain"))
4717 options->word_diff = DIFF_WORDS_PLAIN;
4718 else if (!strcmp(arg, "color")) {
4719 options->use_color = 1;
4720 options->word_diff = DIFF_WORDS_COLOR;
4722 else if (!strcmp(arg, "porcelain"))
4723 options->word_diff = DIFF_WORDS_PORCELAIN;
4724 else if (!strcmp(arg, "none"))
4725 options->word_diff = DIFF_WORDS_NONE;
4726 else
4727 die("bad --word-diff argument: %s", arg);
4729 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
4730 if (options->word_diff == DIFF_WORDS_NONE)
4731 options->word_diff = DIFF_WORDS_PLAIN;
4732 options->word_regex = optarg;
4733 return argcount;
4735 else if (!strcmp(arg, "--exit-code"))
4736 options->flags.exit_with_status = 1;
4737 else if (!strcmp(arg, "--quiet"))
4738 options->flags.quick = 1;
4739 else if (!strcmp(arg, "--ext-diff"))
4740 options->flags.allow_external = 1;
4741 else if (!strcmp(arg, "--no-ext-diff"))
4742 options->flags.allow_external = 0;
4743 else if (!strcmp(arg, "--textconv")) {
4744 options->flags.allow_textconv = 1;
4745 options->flags.textconv_set_via_cmdline = 1;
4746 } else if (!strcmp(arg, "--no-textconv"))
4747 options->flags.allow_textconv = 0;
4748 else if (skip_to_optional_arg_default(arg, "--ignore-submodules", &arg, "all")) {
4749 options->flags.override_submodule_config = 1;
4750 handle_ignore_submodules_arg(options, arg);
4751 } else if (skip_to_optional_arg_default(arg, "--submodule", &arg, "log"))
4752 return parse_submodule_opt(options, arg);
4753 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
4754 return parse_ws_error_highlight_opt(options, arg);
4755 else if (!strcmp(arg, "--ita-invisible-in-index"))
4756 options->ita_invisible_in_index = 1;
4757 else if (!strcmp(arg, "--ita-visible-in-index"))
4758 options->ita_invisible_in_index = 0;
4760 /* misc options */
4761 else if (!strcmp(arg, "-z"))
4762 options->line_termination = 0;
4763 else if ((argcount = short_opt('l', av, &optarg))) {
4764 options->rename_limit = strtoul(optarg, NULL, 10);
4765 return argcount;
4767 else if ((argcount = short_opt('S', av, &optarg))) {
4768 options->pickaxe = optarg;
4769 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
4770 return argcount;
4771 } else if ((argcount = short_opt('G', av, &optarg))) {
4772 options->pickaxe = optarg;
4773 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
4774 return argcount;
4776 else if (!strcmp(arg, "--pickaxe-all"))
4777 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
4778 else if (!strcmp(arg, "--pickaxe-regex"))
4779 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
4780 else if ((argcount = short_opt('O', av, &optarg))) {
4781 options->orderfile = prefix_filename(prefix, optarg);
4782 return argcount;
4783 } else if (skip_prefix(arg, "--find-object=", &arg))
4784 return parse_objfind_opt(options, arg);
4785 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
4786 int offending = parse_diff_filter_opt(optarg, options);
4787 if (offending)
4788 die("unknown change class '%c' in --diff-filter=%s",
4789 offending, optarg);
4790 return argcount;
4792 else if (!strcmp(arg, "--no-abbrev"))
4793 options->abbrev = 0;
4794 else if (!strcmp(arg, "--abbrev"))
4795 options->abbrev = DEFAULT_ABBREV;
4796 else if (skip_prefix(arg, "--abbrev=", &arg)) {
4797 options->abbrev = strtoul(arg, NULL, 10);
4798 if (options->abbrev < MINIMUM_ABBREV)
4799 options->abbrev = MINIMUM_ABBREV;
4800 else if (40 < options->abbrev)
4801 options->abbrev = 40;
4803 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
4804 options->a_prefix = optarg;
4805 return argcount;
4807 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
4808 options->line_prefix = optarg;
4809 options->line_prefix_length = strlen(options->line_prefix);
4810 graph_setup_line_prefix(options);
4811 return argcount;
4813 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
4814 options->b_prefix = optarg;
4815 return argcount;
4817 else if (!strcmp(arg, "--no-prefix"))
4818 options->a_prefix = options->b_prefix = "";
4819 else if (opt_arg(arg, '\0', "inter-hunk-context",
4820 &options->interhunkcontext))
4822 else if (!strcmp(arg, "-W"))
4823 options->flags.funccontext = 1;
4824 else if (!strcmp(arg, "--function-context"))
4825 options->flags.funccontext = 1;
4826 else if (!strcmp(arg, "--no-function-context"))
4827 options->flags.funccontext = 0;
4828 else if ((argcount = parse_long_opt("output", av, &optarg))) {
4829 char *path = prefix_filename(prefix, optarg);
4830 options->file = xfopen(path, "w");
4831 options->close_file = 1;
4832 if (options->use_color != GIT_COLOR_ALWAYS)
4833 options->use_color = GIT_COLOR_NEVER;
4834 free(path);
4835 return argcount;
4836 } else
4837 return 0;
4838 return 1;
4841 int parse_rename_score(const char **cp_p)
4843 unsigned long num, scale;
4844 int ch, dot;
4845 const char *cp = *cp_p;
4847 num = 0;
4848 scale = 1;
4849 dot = 0;
4850 for (;;) {
4851 ch = *cp;
4852 if ( !dot && ch == '.' ) {
4853 scale = 1;
4854 dot = 1;
4855 } else if ( ch == '%' ) {
4856 scale = dot ? scale*100 : 100;
4857 cp++; /* % is always at the end */
4858 break;
4859 } else if ( ch >= '0' && ch <= '9' ) {
4860 if ( scale < 100000 ) {
4861 scale *= 10;
4862 num = (num*10) + (ch-'0');
4864 } else {
4865 break;
4867 cp++;
4869 *cp_p = cp;
4871 /* user says num divided by scale and we say internally that
4872 * is MAX_SCORE * num / scale.
4874 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4877 static int diff_scoreopt_parse(const char *opt)
4879 int opt1, opt2, cmd;
4881 if (*opt++ != '-')
4882 return -1;
4883 cmd = *opt++;
4884 if (cmd == '-') {
4885 /* convert the long-form arguments into short-form versions */
4886 if (skip_prefix(opt, "break-rewrites", &opt)) {
4887 if (*opt == 0 || *opt++ == '=')
4888 cmd = 'B';
4889 } else if (skip_prefix(opt, "find-copies", &opt)) {
4890 if (*opt == 0 || *opt++ == '=')
4891 cmd = 'C';
4892 } else if (skip_prefix(opt, "find-renames", &opt)) {
4893 if (*opt == 0 || *opt++ == '=')
4894 cmd = 'M';
4897 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4898 return -1; /* that is not a -M, -C, or -B option */
4900 opt1 = parse_rename_score(&opt);
4901 if (cmd != 'B')
4902 opt2 = 0;
4903 else {
4904 if (*opt == 0)
4905 opt2 = 0;
4906 else if (*opt != '/')
4907 return -1; /* we expect -B80/99 or -B80 */
4908 else {
4909 opt++;
4910 opt2 = parse_rename_score(&opt);
4913 if (*opt != 0)
4914 return -1;
4915 return opt1 | (opt2 << 16);
4918 struct diff_queue_struct diff_queued_diff;
4920 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4922 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4923 queue->queue[queue->nr++] = dp;
4926 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4927 struct diff_filespec *one,
4928 struct diff_filespec *two)
4930 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4931 dp->one = one;
4932 dp->two = two;
4933 if (queue)
4934 diff_q(queue, dp);
4935 return dp;
4938 void diff_free_filepair(struct diff_filepair *p)
4940 free_filespec(p->one);
4941 free_filespec(p->two);
4942 free(p);
4945 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
4947 int abblen;
4948 const char *abbrev;
4950 /* Do we want all 40 hex characters? */
4951 if (len == GIT_SHA1_HEXSZ)
4952 return oid_to_hex(oid);
4954 /* An abbreviated value is fine, possibly followed by an ellipsis. */
4955 abbrev = diff_abbrev_oid(oid, len);
4957 if (!print_sha1_ellipsis())
4958 return abbrev;
4960 abblen = strlen(abbrev);
4963 * In well-behaved cases, where the abbreviated result is the
4964 * same as the requested length, append three dots after the
4965 * abbreviation (hence the whole logic is limited to the case
4966 * where abblen < 37); when the actual abbreviated result is a
4967 * bit longer than the requested length, we reduce the number
4968 * of dots so that they match the well-behaved ones. However,
4969 * if the actual abbreviation is longer than the requested
4970 * length by more than three, we give up on aligning, and add
4971 * three dots anyway, to indicate that the output is not the
4972 * full object name. Yes, this may be suboptimal, but this
4973 * appears only in "diff --raw --abbrev" output and it is not
4974 * worth the effort to change it now. Note that this would
4975 * likely to work fine when the automatic sizing of default
4976 * abbreviation length is used--we would be fed -1 in "len" in
4977 * that case, and will end up always appending three-dots, but
4978 * the automatic sizing is supposed to give abblen that ensures
4979 * uniqueness across all objects (statistically speaking).
4981 if (abblen < GIT_SHA1_HEXSZ - 3) {
4982 static char hex[GIT_MAX_HEXSZ + 1];
4983 if (len < abblen && abblen <= len + 2)
4984 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
4985 else
4986 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
4987 return hex;
4990 return oid_to_hex(oid);
4993 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4995 int line_termination = opt->line_termination;
4996 int inter_name_termination = line_termination ? '\t' : '\0';
4998 fprintf(opt->file, "%s", diff_line_prefix(opt));
4999 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5000 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5001 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5002 fprintf(opt->file, "%s ",
5003 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5005 if (p->score) {
5006 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5007 inter_name_termination);
5008 } else {
5009 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5012 if (p->status == DIFF_STATUS_COPIED ||
5013 p->status == DIFF_STATUS_RENAMED) {
5014 const char *name_a, *name_b;
5015 name_a = p->one->path;
5016 name_b = p->two->path;
5017 strip_prefix(opt->prefix_length, &name_a, &name_b);
5018 write_name_quoted(name_a, opt->file, inter_name_termination);
5019 write_name_quoted(name_b, opt->file, line_termination);
5020 } else {
5021 const char *name_a, *name_b;
5022 name_a = p->one->mode ? p->one->path : p->two->path;
5023 name_b = NULL;
5024 strip_prefix(opt->prefix_length, &name_a, &name_b);
5025 write_name_quoted(name_a, opt->file, line_termination);
5029 int diff_unmodified_pair(struct diff_filepair *p)
5031 /* This function is written stricter than necessary to support
5032 * the currently implemented transformers, but the idea is to
5033 * let transformers to produce diff_filepairs any way they want,
5034 * and filter and clean them up here before producing the output.
5036 struct diff_filespec *one = p->one, *two = p->two;
5038 if (DIFF_PAIR_UNMERGED(p))
5039 return 0; /* unmerged is interesting */
5041 /* deletion, addition, mode or type change
5042 * and rename are all interesting.
5044 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5045 DIFF_PAIR_MODE_CHANGED(p) ||
5046 strcmp(one->path, two->path))
5047 return 0;
5049 /* both are valid and point at the same path. that is, we are
5050 * dealing with a change.
5052 if (one->oid_valid && two->oid_valid &&
5053 !oidcmp(&one->oid, &two->oid) &&
5054 !one->dirty_submodule && !two->dirty_submodule)
5055 return 1; /* no change */
5056 if (!one->oid_valid && !two->oid_valid)
5057 return 1; /* both look at the same file on the filesystem. */
5058 return 0;
5061 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5063 if (diff_unmodified_pair(p))
5064 return;
5066 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5067 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5068 return; /* no tree diffs in patch format */
5070 run_diff(p, o);
5073 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5074 struct diffstat_t *diffstat)
5076 if (diff_unmodified_pair(p))
5077 return;
5079 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5080 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5081 return; /* no useful stat for tree diffs */
5083 run_diffstat(p, o, diffstat);
5086 static void diff_flush_checkdiff(struct diff_filepair *p,
5087 struct diff_options *o)
5089 if (diff_unmodified_pair(p))
5090 return;
5092 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5093 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5094 return; /* nothing to check in tree diffs */
5096 run_checkdiff(p, o);
5099 int diff_queue_is_empty(void)
5101 struct diff_queue_struct *q = &diff_queued_diff;
5102 int i;
5103 for (i = 0; i < q->nr; i++)
5104 if (!diff_unmodified_pair(q->queue[i]))
5105 return 0;
5106 return 1;
5109 #if DIFF_DEBUG
5110 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5112 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5113 x, one ? one : "",
5114 s->path,
5115 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5116 s->mode,
5117 s->oid_valid ? oid_to_hex(&s->oid) : "");
5118 fprintf(stderr, "queue[%d] %s size %lu\n",
5119 x, one ? one : "",
5120 s->size);
5123 void diff_debug_filepair(const struct diff_filepair *p, int i)
5125 diff_debug_filespec(p->one, i, "one");
5126 diff_debug_filespec(p->two, i, "two");
5127 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5128 p->score, p->status ? p->status : '?',
5129 p->one->rename_used, p->broken_pair);
5132 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5134 int i;
5135 if (msg)
5136 fprintf(stderr, "%s\n", msg);
5137 fprintf(stderr, "q->nr = %d\n", q->nr);
5138 for (i = 0; i < q->nr; i++) {
5139 struct diff_filepair *p = q->queue[i];
5140 diff_debug_filepair(p, i);
5143 #endif
5145 static void diff_resolve_rename_copy(void)
5147 int i;
5148 struct diff_filepair *p;
5149 struct diff_queue_struct *q = &diff_queued_diff;
5151 diff_debug_queue("resolve-rename-copy", q);
5153 for (i = 0; i < q->nr; i++) {
5154 p = q->queue[i];
5155 p->status = 0; /* undecided */
5156 if (DIFF_PAIR_UNMERGED(p))
5157 p->status = DIFF_STATUS_UNMERGED;
5158 else if (!DIFF_FILE_VALID(p->one))
5159 p->status = DIFF_STATUS_ADDED;
5160 else if (!DIFF_FILE_VALID(p->two))
5161 p->status = DIFF_STATUS_DELETED;
5162 else if (DIFF_PAIR_TYPE_CHANGED(p))
5163 p->status = DIFF_STATUS_TYPE_CHANGED;
5165 /* from this point on, we are dealing with a pair
5166 * whose both sides are valid and of the same type, i.e.
5167 * either in-place edit or rename/copy edit.
5169 else if (DIFF_PAIR_RENAME(p)) {
5171 * A rename might have re-connected a broken
5172 * pair up, causing the pathnames to be the
5173 * same again. If so, that's not a rename at
5174 * all, just a modification..
5176 * Otherwise, see if this source was used for
5177 * multiple renames, in which case we decrement
5178 * the count, and call it a copy.
5180 if (!strcmp(p->one->path, p->two->path))
5181 p->status = DIFF_STATUS_MODIFIED;
5182 else if (--p->one->rename_used > 0)
5183 p->status = DIFF_STATUS_COPIED;
5184 else
5185 p->status = DIFF_STATUS_RENAMED;
5187 else if (oidcmp(&p->one->oid, &p->two->oid) ||
5188 p->one->mode != p->two->mode ||
5189 p->one->dirty_submodule ||
5190 p->two->dirty_submodule ||
5191 is_null_oid(&p->one->oid))
5192 p->status = DIFF_STATUS_MODIFIED;
5193 else {
5194 /* This is a "no-change" entry and should not
5195 * happen anymore, but prepare for broken callers.
5197 error("feeding unmodified %s to diffcore",
5198 p->one->path);
5199 p->status = DIFF_STATUS_UNKNOWN;
5202 diff_debug_queue("resolve-rename-copy done", q);
5205 static int check_pair_status(struct diff_filepair *p)
5207 switch (p->status) {
5208 case DIFF_STATUS_UNKNOWN:
5209 return 0;
5210 case 0:
5211 die("internal error in diff-resolve-rename-copy");
5212 default:
5213 return 1;
5217 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5219 int fmt = opt->output_format;
5221 if (fmt & DIFF_FORMAT_CHECKDIFF)
5222 diff_flush_checkdiff(p, opt);
5223 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5224 diff_flush_raw(p, opt);
5225 else if (fmt & DIFF_FORMAT_NAME) {
5226 const char *name_a, *name_b;
5227 name_a = p->two->path;
5228 name_b = NULL;
5229 strip_prefix(opt->prefix_length, &name_a, &name_b);
5230 fprintf(opt->file, "%s", diff_line_prefix(opt));
5231 write_name_quoted(name_a, opt->file, opt->line_termination);
5235 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5237 struct strbuf sb = STRBUF_INIT;
5238 if (fs->mode)
5239 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5240 else
5241 strbuf_addf(&sb, " %s ", newdelete);
5243 quote_c_style(fs->path, &sb, NULL, 0);
5244 strbuf_addch(&sb, '\n');
5245 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5246 sb.buf, sb.len, 0);
5247 strbuf_release(&sb);
5250 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5251 int show_name)
5253 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5254 struct strbuf sb = STRBUF_INIT;
5255 strbuf_addf(&sb, " mode change %06o => %06o",
5256 p->one->mode, p->two->mode);
5257 if (show_name) {
5258 strbuf_addch(&sb, ' ');
5259 quote_c_style(p->two->path, &sb, NULL, 0);
5261 strbuf_addch(&sb, '\n');
5262 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5263 sb.buf, sb.len, 0);
5264 strbuf_release(&sb);
5268 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5269 struct diff_filepair *p)
5271 struct strbuf sb = STRBUF_INIT;
5272 struct strbuf names = STRBUF_INIT;
5274 pprint_rename(&names, p->one->path, p->two->path);
5275 strbuf_addf(&sb, " %s %s (%d%%)\n",
5276 renamecopy, names.buf, similarity_index(p));
5277 strbuf_release(&names);
5278 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5279 sb.buf, sb.len, 0);
5280 show_mode_change(opt, p, 0);
5281 strbuf_release(&sb);
5284 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5286 switch(p->status) {
5287 case DIFF_STATUS_DELETED:
5288 show_file_mode_name(opt, "delete", p->one);
5289 break;
5290 case DIFF_STATUS_ADDED:
5291 show_file_mode_name(opt, "create", p->two);
5292 break;
5293 case DIFF_STATUS_COPIED:
5294 show_rename_copy(opt, "copy", p);
5295 break;
5296 case DIFF_STATUS_RENAMED:
5297 show_rename_copy(opt, "rename", p);
5298 break;
5299 default:
5300 if (p->score) {
5301 struct strbuf sb = STRBUF_INIT;
5302 strbuf_addstr(&sb, " rewrite ");
5303 quote_c_style(p->two->path, &sb, NULL, 0);
5304 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5305 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5306 sb.buf, sb.len, 0);
5307 strbuf_release(&sb);
5309 show_mode_change(opt, p, !p->score);
5310 break;
5314 struct patch_id_t {
5315 git_SHA_CTX *ctx;
5316 int patchlen;
5319 static int remove_space(char *line, int len)
5321 int i;
5322 char *dst = line;
5323 unsigned char c;
5325 for (i = 0; i < len; i++)
5326 if (!isspace((c = line[i])))
5327 *dst++ = c;
5329 return dst - line;
5332 static void patch_id_consume(void *priv, char *line, unsigned long len)
5334 struct patch_id_t *data = priv;
5335 int new_len;
5337 /* Ignore line numbers when computing the SHA1 of the patch */
5338 if (starts_with(line, "@@ -"))
5339 return;
5341 new_len = remove_space(line, len);
5343 git_SHA1_Update(data->ctx, line, new_len);
5344 data->patchlen += new_len;
5347 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
5349 git_SHA1_Update(ctx, str, strlen(str));
5352 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
5354 /* large enough for 2^32 in octal */
5355 char buf[12];
5356 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
5357 git_SHA1_Update(ctx, buf, len);
5360 /* returns 0 upon success, and writes result into sha1 */
5361 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5363 struct diff_queue_struct *q = &diff_queued_diff;
5364 int i;
5365 git_SHA_CTX ctx;
5366 struct patch_id_t data;
5368 git_SHA1_Init(&ctx);
5369 memset(&data, 0, sizeof(struct patch_id_t));
5370 data.ctx = &ctx;
5372 for (i = 0; i < q->nr; i++) {
5373 xpparam_t xpp;
5374 xdemitconf_t xecfg;
5375 mmfile_t mf1, mf2;
5376 struct diff_filepair *p = q->queue[i];
5377 int len1, len2;
5379 memset(&xpp, 0, sizeof(xpp));
5380 memset(&xecfg, 0, sizeof(xecfg));
5381 if (p->status == 0)
5382 return error("internal diff status error");
5383 if (p->status == DIFF_STATUS_UNKNOWN)
5384 continue;
5385 if (diff_unmodified_pair(p))
5386 continue;
5387 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5388 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5389 continue;
5390 if (DIFF_PAIR_UNMERGED(p))
5391 continue;
5393 diff_fill_oid_info(p->one);
5394 diff_fill_oid_info(p->two);
5396 len1 = remove_space(p->one->path, strlen(p->one->path));
5397 len2 = remove_space(p->two->path, strlen(p->two->path));
5398 patch_id_add_string(&ctx, "diff--git");
5399 patch_id_add_string(&ctx, "a/");
5400 git_SHA1_Update(&ctx, p->one->path, len1);
5401 patch_id_add_string(&ctx, "b/");
5402 git_SHA1_Update(&ctx, p->two->path, len2);
5404 if (p->one->mode == 0) {
5405 patch_id_add_string(&ctx, "newfilemode");
5406 patch_id_add_mode(&ctx, p->two->mode);
5407 patch_id_add_string(&ctx, "---/dev/null");
5408 patch_id_add_string(&ctx, "+++b/");
5409 git_SHA1_Update(&ctx, p->two->path, len2);
5410 } else if (p->two->mode == 0) {
5411 patch_id_add_string(&ctx, "deletedfilemode");
5412 patch_id_add_mode(&ctx, p->one->mode);
5413 patch_id_add_string(&ctx, "---a/");
5414 git_SHA1_Update(&ctx, p->one->path, len1);
5415 patch_id_add_string(&ctx, "+++/dev/null");
5416 } else {
5417 patch_id_add_string(&ctx, "---a/");
5418 git_SHA1_Update(&ctx, p->one->path, len1);
5419 patch_id_add_string(&ctx, "+++b/");
5420 git_SHA1_Update(&ctx, p->two->path, len2);
5423 if (diff_header_only)
5424 continue;
5426 if (fill_mmfile(&mf1, p->one) < 0 ||
5427 fill_mmfile(&mf2, p->two) < 0)
5428 return error("unable to read files to diff");
5430 if (diff_filespec_is_binary(p->one) ||
5431 diff_filespec_is_binary(p->two)) {
5432 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5433 GIT_SHA1_HEXSZ);
5434 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5435 GIT_SHA1_HEXSZ);
5436 continue;
5439 xpp.flags = 0;
5440 xecfg.ctxlen = 3;
5441 xecfg.flags = 0;
5442 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
5443 &xpp, &xecfg))
5444 return error("unable to generate patch-id diff for %s",
5445 p->one->path);
5448 git_SHA1_Final(oid->hash, &ctx);
5449 return 0;
5452 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5454 struct diff_queue_struct *q = &diff_queued_diff;
5455 int i;
5456 int result = diff_get_patch_id(options, oid, diff_header_only);
5458 for (i = 0; i < q->nr; i++)
5459 diff_free_filepair(q->queue[i]);
5461 free(q->queue);
5462 DIFF_QUEUE_CLEAR(q);
5464 return result;
5467 static int is_summary_empty(const struct diff_queue_struct *q)
5469 int i;
5471 for (i = 0; i < q->nr; i++) {
5472 const struct diff_filepair *p = q->queue[i];
5474 switch (p->status) {
5475 case DIFF_STATUS_DELETED:
5476 case DIFF_STATUS_ADDED:
5477 case DIFF_STATUS_COPIED:
5478 case DIFF_STATUS_RENAMED:
5479 return 0;
5480 default:
5481 if (p->score)
5482 return 0;
5483 if (p->one->mode && p->two->mode &&
5484 p->one->mode != p->two->mode)
5485 return 0;
5486 break;
5489 return 1;
5492 static const char rename_limit_warning[] =
5493 N_("inexact rename detection was skipped due to too many files.");
5495 static const char degrade_cc_to_c_warning[] =
5496 N_("only found copies from modified paths due to too many files.");
5498 static const char rename_limit_advice[] =
5499 N_("you may want to set your %s variable to at least "
5500 "%d and retry the command.");
5502 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
5504 fflush(stdout);
5505 if (degraded_cc)
5506 warning(_(degrade_cc_to_c_warning));
5507 else if (needed)
5508 warning(_(rename_limit_warning));
5509 else
5510 return;
5511 if (0 < needed)
5512 warning(_(rename_limit_advice), varname, needed);
5515 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
5517 int i;
5518 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
5519 struct diff_queue_struct *q = &diff_queued_diff;
5521 if (WSEH_NEW & WS_RULE_MASK)
5522 die("BUG: WS rules bit mask overlaps with diff symbol flags");
5524 if (o->color_moved)
5525 o->emitted_symbols = &esm;
5527 for (i = 0; i < q->nr; i++) {
5528 struct diff_filepair *p = q->queue[i];
5529 if (check_pair_status(p))
5530 diff_flush_patch(p, o);
5533 if (o->emitted_symbols) {
5534 if (o->color_moved) {
5535 struct hashmap add_lines, del_lines;
5537 hashmap_init(&del_lines,
5538 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5539 hashmap_init(&add_lines,
5540 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5542 add_lines_to_move_detection(o, &add_lines, &del_lines);
5543 mark_color_as_moved(o, &add_lines, &del_lines);
5544 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
5545 dim_moved_lines(o);
5547 hashmap_free(&add_lines, 0);
5548 hashmap_free(&del_lines, 0);
5551 for (i = 0; i < esm.nr; i++)
5552 emit_diff_symbol_from_struct(o, &esm.buf[i]);
5554 for (i = 0; i < esm.nr; i++)
5555 free((void *)esm.buf[i].line);
5557 esm.nr = 0;
5560 void diff_flush(struct diff_options *options)
5562 struct diff_queue_struct *q = &diff_queued_diff;
5563 int i, output_format = options->output_format;
5564 int separator = 0;
5565 int dirstat_by_line = 0;
5568 * Order: raw, stat, summary, patch
5569 * or: name/name-status/checkdiff (other bits clear)
5571 if (!q->nr)
5572 goto free_queue;
5574 if (output_format & (DIFF_FORMAT_RAW |
5575 DIFF_FORMAT_NAME |
5576 DIFF_FORMAT_NAME_STATUS |
5577 DIFF_FORMAT_CHECKDIFF)) {
5578 for (i = 0; i < q->nr; i++) {
5579 struct diff_filepair *p = q->queue[i];
5580 if (check_pair_status(p))
5581 flush_one_pair(p, options);
5583 separator++;
5586 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
5587 dirstat_by_line = 1;
5589 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
5590 dirstat_by_line) {
5591 struct diffstat_t diffstat;
5593 memset(&diffstat, 0, sizeof(struct diffstat_t));
5594 for (i = 0; i < q->nr; i++) {
5595 struct diff_filepair *p = q->queue[i];
5596 if (check_pair_status(p))
5597 diff_flush_stat(p, options, &diffstat);
5599 if (output_format & DIFF_FORMAT_NUMSTAT)
5600 show_numstat(&diffstat, options);
5601 if (output_format & DIFF_FORMAT_DIFFSTAT)
5602 show_stats(&diffstat, options);
5603 if (output_format & DIFF_FORMAT_SHORTSTAT)
5604 show_shortstats(&diffstat, options);
5605 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
5606 show_dirstat_by_line(&diffstat, options);
5607 free_diffstat_info(&diffstat);
5608 separator++;
5610 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
5611 show_dirstat(options);
5613 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
5614 for (i = 0; i < q->nr; i++) {
5615 diff_summary(options, q->queue[i]);
5617 separator++;
5620 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
5621 options->flags.exit_with_status &&
5622 options->flags.diff_from_contents) {
5624 * run diff_flush_patch for the exit status. setting
5625 * options->file to /dev/null should be safe, because we
5626 * aren't supposed to produce any output anyway.
5628 if (options->close_file)
5629 fclose(options->file);
5630 options->file = xfopen("/dev/null", "w");
5631 options->close_file = 1;
5632 options->color_moved = 0;
5633 for (i = 0; i < q->nr; i++) {
5634 struct diff_filepair *p = q->queue[i];
5635 if (check_pair_status(p))
5636 diff_flush_patch(p, options);
5637 if (options->found_changes)
5638 break;
5642 if (output_format & DIFF_FORMAT_PATCH) {
5643 if (separator) {
5644 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
5645 if (options->stat_sep)
5646 /* attach patch instead of inline */
5647 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
5648 NULL, 0, 0);
5651 diff_flush_patch_all_file_pairs(options);
5654 if (output_format & DIFF_FORMAT_CALLBACK)
5655 options->format_callback(q, options, options->format_callback_data);
5657 for (i = 0; i < q->nr; i++)
5658 diff_free_filepair(q->queue[i]);
5659 free_queue:
5660 free(q->queue);
5661 DIFF_QUEUE_CLEAR(q);
5662 if (options->close_file)
5663 fclose(options->file);
5666 * Report the content-level differences with HAS_CHANGES;
5667 * diff_addremove/diff_change does not set the bit when
5668 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
5670 if (options->flags.diff_from_contents) {
5671 if (options->found_changes)
5672 options->flags.has_changes = 1;
5673 else
5674 options->flags.has_changes = 0;
5678 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
5680 return (((p->status == DIFF_STATUS_MODIFIED) &&
5681 ((p->score &&
5682 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
5683 (!p->score &&
5684 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
5685 ((p->status != DIFF_STATUS_MODIFIED) &&
5686 filter_bit_tst(p->status, options)));
5689 static void diffcore_apply_filter(struct diff_options *options)
5691 int i;
5692 struct diff_queue_struct *q = &diff_queued_diff;
5693 struct diff_queue_struct outq;
5695 DIFF_QUEUE_CLEAR(&outq);
5697 if (!options->filter)
5698 return;
5700 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
5701 int found;
5702 for (i = found = 0; !found && i < q->nr; i++) {
5703 if (match_filter(options, q->queue[i]))
5704 found++;
5706 if (found)
5707 return;
5709 /* otherwise we will clear the whole queue
5710 * by copying the empty outq at the end of this
5711 * function, but first clear the current entries
5712 * in the queue.
5714 for (i = 0; i < q->nr; i++)
5715 diff_free_filepair(q->queue[i]);
5717 else {
5718 /* Only the matching ones */
5719 for (i = 0; i < q->nr; i++) {
5720 struct diff_filepair *p = q->queue[i];
5721 if (match_filter(options, p))
5722 diff_q(&outq, p);
5723 else
5724 diff_free_filepair(p);
5727 free(q->queue);
5728 *q = outq;
5731 /* Check whether two filespecs with the same mode and size are identical */
5732 static int diff_filespec_is_identical(struct diff_filespec *one,
5733 struct diff_filespec *two)
5735 if (S_ISGITLINK(one->mode))
5736 return 0;
5737 if (diff_populate_filespec(one, 0))
5738 return 0;
5739 if (diff_populate_filespec(two, 0))
5740 return 0;
5741 return !memcmp(one->data, two->data, one->size);
5744 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
5746 if (p->done_skip_stat_unmatch)
5747 return p->skip_stat_unmatch_result;
5749 p->done_skip_stat_unmatch = 1;
5750 p->skip_stat_unmatch_result = 0;
5752 * 1. Entries that come from stat info dirtiness
5753 * always have both sides (iow, not create/delete),
5754 * one side of the object name is unknown, with
5755 * the same mode and size. Keep the ones that
5756 * do not match these criteria. They have real
5757 * differences.
5759 * 2. At this point, the file is known to be modified,
5760 * with the same mode and size, and the object
5761 * name of one side is unknown. Need to inspect
5762 * the identical contents.
5764 if (!DIFF_FILE_VALID(p->one) || /* (1) */
5765 !DIFF_FILE_VALID(p->two) ||
5766 (p->one->oid_valid && p->two->oid_valid) ||
5767 (p->one->mode != p->two->mode) ||
5768 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
5769 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
5770 (p->one->size != p->two->size) ||
5771 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
5772 p->skip_stat_unmatch_result = 1;
5773 return p->skip_stat_unmatch_result;
5776 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
5778 int i;
5779 struct diff_queue_struct *q = &diff_queued_diff;
5780 struct diff_queue_struct outq;
5781 DIFF_QUEUE_CLEAR(&outq);
5783 for (i = 0; i < q->nr; i++) {
5784 struct diff_filepair *p = q->queue[i];
5786 if (diff_filespec_check_stat_unmatch(p))
5787 diff_q(&outq, p);
5788 else {
5790 * The caller can subtract 1 from skip_stat_unmatch
5791 * to determine how many paths were dirty only
5792 * due to stat info mismatch.
5794 if (!diffopt->flags.no_index)
5795 diffopt->skip_stat_unmatch++;
5796 diff_free_filepair(p);
5799 free(q->queue);
5800 *q = outq;
5803 static int diffnamecmp(const void *a_, const void *b_)
5805 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
5806 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
5807 const char *name_a, *name_b;
5809 name_a = a->one ? a->one->path : a->two->path;
5810 name_b = b->one ? b->one->path : b->two->path;
5811 return strcmp(name_a, name_b);
5814 void diffcore_fix_diff_index(struct diff_options *options)
5816 struct diff_queue_struct *q = &diff_queued_diff;
5817 QSORT(q->queue, q->nr, diffnamecmp);
5820 void diffcore_std(struct diff_options *options)
5822 /* NOTE please keep the following in sync with diff_tree_combined() */
5823 if (options->skip_stat_unmatch)
5824 diffcore_skip_stat_unmatch(options);
5825 if (!options->found_follow) {
5826 /* See try_to_follow_renames() in tree-diff.c */
5827 if (options->break_opt != -1)
5828 diffcore_break(options->break_opt);
5829 if (options->detect_rename)
5830 diffcore_rename(options);
5831 if (options->break_opt != -1)
5832 diffcore_merge_broken();
5834 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
5835 diffcore_pickaxe(options);
5836 if (options->orderfile)
5837 diffcore_order(options->orderfile);
5838 if (!options->found_follow)
5839 /* See try_to_follow_renames() in tree-diff.c */
5840 diff_resolve_rename_copy();
5841 diffcore_apply_filter(options);
5843 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
5844 options->flags.has_changes = 1;
5845 else
5846 options->flags.has_changes = 0;
5848 options->found_follow = 0;
5851 int diff_result_code(struct diff_options *opt, int status)
5853 int result = 0;
5855 diff_warn_rename_limit("diff.renameLimit",
5856 opt->needed_rename_limit,
5857 opt->degraded_cc_to_c);
5858 if (!opt->flags.exit_with_status &&
5859 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
5860 return status;
5861 if (opt->flags.exit_with_status &&
5862 opt->flags.has_changes)
5863 result |= 01;
5864 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
5865 opt->flags.check_failed)
5866 result |= 02;
5867 return result;
5870 int diff_can_quit_early(struct diff_options *opt)
5872 return (opt->flags.quick &&
5873 !opt->filter &&
5874 opt->flags.has_changes);
5878 * Shall changes to this submodule be ignored?
5880 * Submodule changes can be configured to be ignored separately for each path,
5881 * but that configuration can be overridden from the command line.
5883 static int is_submodule_ignored(const char *path, struct diff_options *options)
5885 int ignored = 0;
5886 struct diff_flags orig_flags = options->flags;
5887 if (!options->flags.override_submodule_config)
5888 set_diffopt_flags_from_submodule_config(options, path);
5889 if (options->flags.ignore_submodules)
5890 ignored = 1;
5891 options->flags = orig_flags;
5892 return ignored;
5895 void diff_addremove(struct diff_options *options,
5896 int addremove, unsigned mode,
5897 const struct object_id *oid,
5898 int oid_valid,
5899 const char *concatpath, unsigned dirty_submodule)
5901 struct diff_filespec *one, *two;
5903 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
5904 return;
5906 /* This may look odd, but it is a preparation for
5907 * feeding "there are unchanged files which should
5908 * not produce diffs, but when you are doing copy
5909 * detection you would need them, so here they are"
5910 * entries to the diff-core. They will be prefixed
5911 * with something like '=' or '*' (I haven't decided
5912 * which but should not make any difference).
5913 * Feeding the same new and old to diff_change()
5914 * also has the same effect.
5915 * Before the final output happens, they are pruned after
5916 * merged into rename/copy pairs as appropriate.
5918 if (options->flags.reverse_diff)
5919 addremove = (addremove == '+' ? '-' :
5920 addremove == '-' ? '+' : addremove);
5922 if (options->prefix &&
5923 strncmp(concatpath, options->prefix, options->prefix_length))
5924 return;
5926 one = alloc_filespec(concatpath);
5927 two = alloc_filespec(concatpath);
5929 if (addremove != '+')
5930 fill_filespec(one, oid, oid_valid, mode);
5931 if (addremove != '-') {
5932 fill_filespec(two, oid, oid_valid, mode);
5933 two->dirty_submodule = dirty_submodule;
5936 diff_queue(&diff_queued_diff, one, two);
5937 if (!options->flags.diff_from_contents)
5938 options->flags.has_changes = 1;
5941 void diff_change(struct diff_options *options,
5942 unsigned old_mode, unsigned new_mode,
5943 const struct object_id *old_oid,
5944 const struct object_id *new_oid,
5945 int old_oid_valid, int new_oid_valid,
5946 const char *concatpath,
5947 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5949 struct diff_filespec *one, *two;
5950 struct diff_filepair *p;
5952 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
5953 is_submodule_ignored(concatpath, options))
5954 return;
5956 if (options->flags.reverse_diff) {
5957 SWAP(old_mode, new_mode);
5958 SWAP(old_oid, new_oid);
5959 SWAP(old_oid_valid, new_oid_valid);
5960 SWAP(old_dirty_submodule, new_dirty_submodule);
5963 if (options->prefix &&
5964 strncmp(concatpath, options->prefix, options->prefix_length))
5965 return;
5967 one = alloc_filespec(concatpath);
5968 two = alloc_filespec(concatpath);
5969 fill_filespec(one, old_oid, old_oid_valid, old_mode);
5970 fill_filespec(two, new_oid, new_oid_valid, new_mode);
5971 one->dirty_submodule = old_dirty_submodule;
5972 two->dirty_submodule = new_dirty_submodule;
5973 p = diff_queue(&diff_queued_diff, one, two);
5975 if (options->flags.diff_from_contents)
5976 return;
5978 if (options->flags.quick && options->skip_stat_unmatch &&
5979 !diff_filespec_check_stat_unmatch(p))
5980 return;
5982 options->flags.has_changes = 1;
5985 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
5987 struct diff_filepair *pair;
5988 struct diff_filespec *one, *two;
5990 if (options->prefix &&
5991 strncmp(path, options->prefix, options->prefix_length))
5992 return NULL;
5994 one = alloc_filespec(path);
5995 two = alloc_filespec(path);
5996 pair = diff_queue(&diff_queued_diff, one, two);
5997 pair->is_unmerged = 1;
5998 return pair;
6001 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
6002 size_t *outsize)
6004 struct diff_tempfile *temp;
6005 const char *argv[3];
6006 const char **arg = argv;
6007 struct child_process child = CHILD_PROCESS_INIT;
6008 struct strbuf buf = STRBUF_INIT;
6009 int err = 0;
6011 temp = prepare_temp_file(spec->path, spec);
6012 *arg++ = pgm;
6013 *arg++ = temp->name;
6014 *arg = NULL;
6016 child.use_shell = 1;
6017 child.argv = argv;
6018 child.out = -1;
6019 if (start_command(&child)) {
6020 remove_tempfile();
6021 return NULL;
6024 if (strbuf_read(&buf, child.out, 0) < 0)
6025 err = error("error reading from textconv command '%s'", pgm);
6026 close(child.out);
6028 if (finish_command(&child) || err) {
6029 strbuf_release(&buf);
6030 remove_tempfile();
6031 return NULL;
6033 remove_tempfile();
6035 return strbuf_detach(&buf, outsize);
6038 size_t fill_textconv(struct userdiff_driver *driver,
6039 struct diff_filespec *df,
6040 char **outbuf)
6042 size_t size;
6044 if (!driver) {
6045 if (!DIFF_FILE_VALID(df)) {
6046 *outbuf = "";
6047 return 0;
6049 if (diff_populate_filespec(df, 0))
6050 die("unable to read files to diff");
6051 *outbuf = df->data;
6052 return df->size;
6055 if (!driver->textconv)
6056 die("BUG: fill_textconv called with non-textconv driver");
6058 if (driver->textconv_cache && df->oid_valid) {
6059 *outbuf = notes_cache_get(driver->textconv_cache,
6060 &df->oid,
6061 &size);
6062 if (*outbuf)
6063 return size;
6066 *outbuf = run_textconv(driver->textconv, df, &size);
6067 if (!*outbuf)
6068 die("unable to read files to diff");
6070 if (driver->textconv_cache && df->oid_valid) {
6071 /* ignore errors, as we might be in a readonly repository */
6072 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6073 size);
6075 * we could save up changes and flush them all at the end,
6076 * but we would need an extra call after all diffing is done.
6077 * Since generating a cache entry is the slow path anyway,
6078 * this extra overhead probably isn't a big deal.
6080 notes_cache_write(driver->textconv_cache);
6083 return size;
6086 int textconv_object(const char *path,
6087 unsigned mode,
6088 const struct object_id *oid,
6089 int oid_valid,
6090 char **buf,
6091 unsigned long *buf_size)
6093 struct diff_filespec *df;
6094 struct userdiff_driver *textconv;
6096 df = alloc_filespec(path);
6097 fill_filespec(df, oid, oid_valid, mode);
6098 textconv = get_textconv(df);
6099 if (!textconv) {
6100 free_filespec(df);
6101 return 0;
6104 *buf_size = fill_textconv(textconv, df, buf);
6105 free_filespec(df);
6106 return 1;
6109 void setup_diff_pager(struct diff_options *opt)
6112 * If the user asked for our exit code, then either they want --quiet
6113 * or --exit-code. We should definitely not bother with a pager in the
6114 * former case, as we will generate no output. Since we still properly
6115 * report our exit code even when a pager is run, we _could_ run a
6116 * pager with --exit-code. But since we have not done so historically,
6117 * and because it is easy to find people oneline advising "git diff
6118 * --exit-code" in hooks and other scripts, we do not do so.
6120 if (!opt->flags.exit_with_status &&
6121 check_pager_config("diff") != 0)
6122 setup_pager();