commit: add repository argument to commit_graft_pos
[git.git] / diff.c
blob18d478c5190324a8777f43a92736199ad2867908
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 "object-store.h"
17 #include "userdiff.h"
18 #include "submodule-config.h"
19 #include "submodule.h"
20 #include "hashmap.h"
21 #include "ll-merge.h"
22 #include "string-list.h"
23 #include "argv-array.h"
24 #include "graph.h"
25 #include "packfile.h"
27 #ifdef NO_FAST_WORKING_DIRECTORY
28 #define FAST_WORKING_DIRECTORY 0
29 #else
30 #define FAST_WORKING_DIRECTORY 1
31 #endif
33 static int diff_detect_rename_default;
34 static int diff_indent_heuristic = 1;
35 static int diff_rename_limit_default = 400;
36 static int diff_suppress_blank_empty;
37 static int diff_use_color_default = -1;
38 static int diff_color_moved_default;
39 static int diff_context_default = 3;
40 static int diff_interhunk_context_default;
41 static const char *diff_word_regex_cfg;
42 static const char *external_diff_cmd_cfg;
43 static const char *diff_order_file_cfg;
44 int diff_auto_refresh_index = 1;
45 static int diff_mnemonic_prefix;
46 static int diff_no_prefix;
47 static int diff_stat_graph_width;
48 static int diff_dirstat_permille_default = 30;
49 static struct diff_options default_diff_options;
50 static long diff_algorithm;
51 static unsigned ws_error_highlight_default = WSEH_NEW;
53 static char diff_colors[][COLOR_MAXLEN] = {
54 GIT_COLOR_RESET,
55 GIT_COLOR_NORMAL, /* CONTEXT */
56 GIT_COLOR_BOLD, /* METAINFO */
57 GIT_COLOR_CYAN, /* FRAGINFO */
58 GIT_COLOR_RED, /* OLD */
59 GIT_COLOR_GREEN, /* NEW */
60 GIT_COLOR_YELLOW, /* COMMIT */
61 GIT_COLOR_BG_RED, /* WHITESPACE */
62 GIT_COLOR_NORMAL, /* FUNCINFO */
63 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
64 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
65 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
66 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
67 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
68 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
69 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
70 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
73 static NORETURN void die_want_option(const char *option_name)
75 die(_("option '%s' requires a value"), option_name);
78 static int parse_diff_color_slot(const char *var)
80 if (!strcasecmp(var, "context") || !strcasecmp(var, "plain"))
81 return DIFF_CONTEXT;
82 if (!strcasecmp(var, "meta"))
83 return DIFF_METAINFO;
84 if (!strcasecmp(var, "frag"))
85 return DIFF_FRAGINFO;
86 if (!strcasecmp(var, "old"))
87 return DIFF_FILE_OLD;
88 if (!strcasecmp(var, "new"))
89 return DIFF_FILE_NEW;
90 if (!strcasecmp(var, "commit"))
91 return DIFF_COMMIT;
92 if (!strcasecmp(var, "whitespace"))
93 return DIFF_WHITESPACE;
94 if (!strcasecmp(var, "func"))
95 return DIFF_FUNCINFO;
96 if (!strcasecmp(var, "oldmoved"))
97 return DIFF_FILE_OLD_MOVED;
98 if (!strcasecmp(var, "oldmovedalternative"))
99 return DIFF_FILE_OLD_MOVED_ALT;
100 if (!strcasecmp(var, "oldmoveddimmed"))
101 return DIFF_FILE_OLD_MOVED_DIM;
102 if (!strcasecmp(var, "oldmovedalternativedimmed"))
103 return DIFF_FILE_OLD_MOVED_ALT_DIM;
104 if (!strcasecmp(var, "newmoved"))
105 return DIFF_FILE_NEW_MOVED;
106 if (!strcasecmp(var, "newmovedalternative"))
107 return DIFF_FILE_NEW_MOVED_ALT;
108 if (!strcasecmp(var, "newmoveddimmed"))
109 return DIFF_FILE_NEW_MOVED_DIM;
110 if (!strcasecmp(var, "newmovedalternativedimmed"))
111 return DIFF_FILE_NEW_MOVED_ALT_DIM;
112 return -1;
115 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
116 struct strbuf *errmsg)
118 char *params_copy = xstrdup(params_string);
119 struct string_list params = STRING_LIST_INIT_NODUP;
120 int ret = 0;
121 int i;
123 if (*params_copy)
124 string_list_split_in_place(&params, params_copy, ',', -1);
125 for (i = 0; i < params.nr; i++) {
126 const char *p = params.items[i].string;
127 if (!strcmp(p, "changes")) {
128 options->flags.dirstat_by_line = 0;
129 options->flags.dirstat_by_file = 0;
130 } else if (!strcmp(p, "lines")) {
131 options->flags.dirstat_by_line = 1;
132 options->flags.dirstat_by_file = 0;
133 } else if (!strcmp(p, "files")) {
134 options->flags.dirstat_by_line = 0;
135 options->flags.dirstat_by_file = 1;
136 } else if (!strcmp(p, "noncumulative")) {
137 options->flags.dirstat_cumulative = 0;
138 } else if (!strcmp(p, "cumulative")) {
139 options->flags.dirstat_cumulative = 1;
140 } else if (isdigit(*p)) {
141 char *end;
142 int permille = strtoul(p, &end, 10) * 10;
143 if (*end == '.' && isdigit(*++end)) {
144 /* only use first digit */
145 permille += *end - '0';
146 /* .. and ignore any further digits */
147 while (isdigit(*++end))
148 ; /* nothing */
150 if (!*end)
151 options->dirstat_permille = permille;
152 else {
153 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
155 ret++;
157 } else {
158 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
159 ret++;
163 string_list_clear(&params, 0);
164 free(params_copy);
165 return ret;
168 static int parse_submodule_params(struct diff_options *options, const char *value)
170 if (!strcmp(value, "log"))
171 options->submodule_format = DIFF_SUBMODULE_LOG;
172 else if (!strcmp(value, "short"))
173 options->submodule_format = DIFF_SUBMODULE_SHORT;
174 else if (!strcmp(value, "diff"))
175 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
176 else
177 return -1;
178 return 0;
181 static int git_config_rename(const char *var, const char *value)
183 if (!value)
184 return DIFF_DETECT_RENAME;
185 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
186 return DIFF_DETECT_COPY;
187 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
190 long parse_algorithm_value(const char *value)
192 if (!value)
193 return -1;
194 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
195 return 0;
196 else if (!strcasecmp(value, "minimal"))
197 return XDF_NEED_MINIMAL;
198 else if (!strcasecmp(value, "patience"))
199 return XDF_PATIENCE_DIFF;
200 else if (!strcasecmp(value, "histogram"))
201 return XDF_HISTOGRAM_DIFF;
202 return -1;
205 static int parse_one_token(const char **arg, const char *token)
207 const char *rest;
208 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
209 *arg = rest;
210 return 1;
212 return 0;
215 static int parse_ws_error_highlight(const char *arg)
217 const char *orig_arg = arg;
218 unsigned val = 0;
220 while (*arg) {
221 if (parse_one_token(&arg, "none"))
222 val = 0;
223 else if (parse_one_token(&arg, "default"))
224 val = WSEH_NEW;
225 else if (parse_one_token(&arg, "all"))
226 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
227 else if (parse_one_token(&arg, "new"))
228 val |= WSEH_NEW;
229 else if (parse_one_token(&arg, "old"))
230 val |= WSEH_OLD;
231 else if (parse_one_token(&arg, "context"))
232 val |= WSEH_CONTEXT;
233 else {
234 return -1 - (int)(arg - orig_arg);
236 if (*arg)
237 arg++;
239 return val;
243 * These are to give UI layer defaults.
244 * The core-level commands such as git-diff-files should
245 * never be affected by the setting of diff.renames
246 * the user happens to have in the configuration file.
248 void init_diff_ui_defaults(void)
250 diff_detect_rename_default = DIFF_DETECT_RENAME;
253 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
255 if (!strcmp(var, "diff.indentheuristic"))
256 diff_indent_heuristic = git_config_bool(var, value);
257 return 0;
260 static int parse_color_moved(const char *arg)
262 switch (git_parse_maybe_bool(arg)) {
263 case 0:
264 return COLOR_MOVED_NO;
265 case 1:
266 return COLOR_MOVED_DEFAULT;
267 default:
268 break;
271 if (!strcmp(arg, "no"))
272 return COLOR_MOVED_NO;
273 else if (!strcmp(arg, "plain"))
274 return COLOR_MOVED_PLAIN;
275 else if (!strcmp(arg, "zebra"))
276 return COLOR_MOVED_ZEBRA;
277 else if (!strcmp(arg, "default"))
278 return COLOR_MOVED_DEFAULT;
279 else if (!strcmp(arg, "dimmed_zebra"))
280 return COLOR_MOVED_ZEBRA_DIM;
281 else
282 return error(_("color moved setting must be one of 'no', 'default', 'zebra', 'dimmed_zebra', 'plain'"));
285 int git_diff_ui_config(const char *var, const char *value, void *cb)
287 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
288 diff_use_color_default = git_config_colorbool(var, value);
289 return 0;
291 if (!strcmp(var, "diff.colormoved")) {
292 int cm = parse_color_moved(value);
293 if (cm < 0)
294 return -1;
295 diff_color_moved_default = cm;
296 return 0;
298 if (!strcmp(var, "diff.context")) {
299 diff_context_default = git_config_int(var, value);
300 if (diff_context_default < 0)
301 return -1;
302 return 0;
304 if (!strcmp(var, "diff.interhunkcontext")) {
305 diff_interhunk_context_default = git_config_int(var, value);
306 if (diff_interhunk_context_default < 0)
307 return -1;
308 return 0;
310 if (!strcmp(var, "diff.renames")) {
311 diff_detect_rename_default = git_config_rename(var, value);
312 return 0;
314 if (!strcmp(var, "diff.autorefreshindex")) {
315 diff_auto_refresh_index = git_config_bool(var, value);
316 return 0;
318 if (!strcmp(var, "diff.mnemonicprefix")) {
319 diff_mnemonic_prefix = git_config_bool(var, value);
320 return 0;
322 if (!strcmp(var, "diff.noprefix")) {
323 diff_no_prefix = git_config_bool(var, value);
324 return 0;
326 if (!strcmp(var, "diff.statgraphwidth")) {
327 diff_stat_graph_width = git_config_int(var, value);
328 return 0;
330 if (!strcmp(var, "diff.external"))
331 return git_config_string(&external_diff_cmd_cfg, var, value);
332 if (!strcmp(var, "diff.wordregex"))
333 return git_config_string(&diff_word_regex_cfg, var, value);
334 if (!strcmp(var, "diff.orderfile"))
335 return git_config_pathname(&diff_order_file_cfg, var, value);
337 if (!strcmp(var, "diff.ignoresubmodules"))
338 handle_ignore_submodules_arg(&default_diff_options, value);
340 if (!strcmp(var, "diff.submodule")) {
341 if (parse_submodule_params(&default_diff_options, value))
342 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
343 value);
344 return 0;
347 if (!strcmp(var, "diff.algorithm")) {
348 diff_algorithm = parse_algorithm_value(value);
349 if (diff_algorithm < 0)
350 return -1;
351 return 0;
354 if (!strcmp(var, "diff.wserrorhighlight")) {
355 int val = parse_ws_error_highlight(value);
356 if (val < 0)
357 return -1;
358 ws_error_highlight_default = val;
359 return 0;
362 if (git_color_config(var, value, cb) < 0)
363 return -1;
365 return git_diff_basic_config(var, value, cb);
368 int git_diff_basic_config(const char *var, const char *value, void *cb)
370 const char *name;
372 if (!strcmp(var, "diff.renamelimit")) {
373 diff_rename_limit_default = git_config_int(var, value);
374 return 0;
377 if (userdiff_config(var, value) < 0)
378 return -1;
380 if (skip_prefix(var, "diff.color.", &name) ||
381 skip_prefix(var, "color.diff.", &name)) {
382 int slot = parse_diff_color_slot(name);
383 if (slot < 0)
384 return 0;
385 if (!value)
386 return config_error_nonbool(var);
387 return color_parse(value, diff_colors[slot]);
390 /* like GNU diff's --suppress-blank-empty option */
391 if (!strcmp(var, "diff.suppressblankempty") ||
392 /* for backwards compatibility */
393 !strcmp(var, "diff.suppress-blank-empty")) {
394 diff_suppress_blank_empty = git_config_bool(var, value);
395 return 0;
398 if (!strcmp(var, "diff.dirstat")) {
399 struct strbuf errmsg = STRBUF_INIT;
400 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
401 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
402 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
403 errmsg.buf);
404 strbuf_release(&errmsg);
405 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
406 return 0;
409 if (git_diff_heuristic_config(var, value, cb) < 0)
410 return -1;
412 return git_default_config(var, value, cb);
415 static char *quote_two(const char *one, const char *two)
417 int need_one = quote_c_style(one, NULL, NULL, 1);
418 int need_two = quote_c_style(two, NULL, NULL, 1);
419 struct strbuf res = STRBUF_INIT;
421 if (need_one + need_two) {
422 strbuf_addch(&res, '"');
423 quote_c_style(one, &res, NULL, 1);
424 quote_c_style(two, &res, NULL, 1);
425 strbuf_addch(&res, '"');
426 } else {
427 strbuf_addstr(&res, one);
428 strbuf_addstr(&res, two);
430 return strbuf_detach(&res, NULL);
433 static const char *external_diff(void)
435 static const char *external_diff_cmd = NULL;
436 static int done_preparing = 0;
438 if (done_preparing)
439 return external_diff_cmd;
440 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
441 if (!external_diff_cmd)
442 external_diff_cmd = external_diff_cmd_cfg;
443 done_preparing = 1;
444 return external_diff_cmd;
448 * Keep track of files used for diffing. Sometimes such an entry
449 * refers to a temporary file, sometimes to an existing file, and
450 * sometimes to "/dev/null".
452 static struct diff_tempfile {
454 * filename external diff should read from, or NULL if this
455 * entry is currently not in use:
457 const char *name;
459 char hex[GIT_MAX_HEXSZ + 1];
460 char mode[10];
463 * If this diff_tempfile instance refers to a temporary file,
464 * this tempfile object is used to manage its lifetime.
466 struct tempfile *tempfile;
467 } diff_temp[2];
469 struct emit_callback {
470 int color_diff;
471 unsigned ws_rule;
472 int blank_at_eof_in_preimage;
473 int blank_at_eof_in_postimage;
474 int lno_in_preimage;
475 int lno_in_postimage;
476 const char **label_path;
477 struct diff_words_data *diff_words;
478 struct diff_options *opt;
479 struct strbuf *header;
482 static int count_lines(const char *data, int size)
484 int count, ch, completely_empty = 1, nl_just_seen = 0;
485 count = 0;
486 while (0 < size--) {
487 ch = *data++;
488 if (ch == '\n') {
489 count++;
490 nl_just_seen = 1;
491 completely_empty = 0;
493 else {
494 nl_just_seen = 0;
495 completely_empty = 0;
498 if (completely_empty)
499 return 0;
500 if (!nl_just_seen)
501 count++; /* no trailing newline */
502 return count;
505 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
507 if (!DIFF_FILE_VALID(one)) {
508 mf->ptr = (char *)""; /* does not matter */
509 mf->size = 0;
510 return 0;
512 else if (diff_populate_filespec(one, 0))
513 return -1;
515 mf->ptr = one->data;
516 mf->size = one->size;
517 return 0;
520 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
521 static unsigned long diff_filespec_size(struct diff_filespec *one)
523 if (!DIFF_FILE_VALID(one))
524 return 0;
525 diff_populate_filespec(one, CHECK_SIZE_ONLY);
526 return one->size;
529 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
531 char *ptr = mf->ptr;
532 long size = mf->size;
533 int cnt = 0;
535 if (!size)
536 return cnt;
537 ptr += size - 1; /* pointing at the very end */
538 if (*ptr != '\n')
539 ; /* incomplete line */
540 else
541 ptr--; /* skip the last LF */
542 while (mf->ptr < ptr) {
543 char *prev_eol;
544 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
545 if (*prev_eol == '\n')
546 break;
547 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
548 break;
549 cnt++;
550 ptr = prev_eol - 1;
552 return cnt;
555 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
556 struct emit_callback *ecbdata)
558 int l1, l2, at;
559 unsigned ws_rule = ecbdata->ws_rule;
560 l1 = count_trailing_blank(mf1, ws_rule);
561 l2 = count_trailing_blank(mf2, ws_rule);
562 if (l2 <= l1) {
563 ecbdata->blank_at_eof_in_preimage = 0;
564 ecbdata->blank_at_eof_in_postimage = 0;
565 return;
567 at = count_lines(mf1->ptr, mf1->size);
568 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
570 at = count_lines(mf2->ptr, mf2->size);
571 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
574 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
575 int first, const char *line, int len)
577 int has_trailing_newline, has_trailing_carriage_return;
578 int nofirst;
579 FILE *file = o->file;
581 fputs(diff_line_prefix(o), file);
583 if (len == 0) {
584 has_trailing_newline = (first == '\n');
585 has_trailing_carriage_return = (!has_trailing_newline &&
586 (first == '\r'));
587 nofirst = has_trailing_newline || has_trailing_carriage_return;
588 } else {
589 has_trailing_newline = (len > 0 && line[len-1] == '\n');
590 if (has_trailing_newline)
591 len--;
592 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
593 if (has_trailing_carriage_return)
594 len--;
595 nofirst = 0;
598 if (len || !nofirst) {
599 fputs(set, file);
600 if (!nofirst)
601 fputc(first, file);
602 fwrite(line, len, 1, file);
603 fputs(reset, file);
605 if (has_trailing_carriage_return)
606 fputc('\r', file);
607 if (has_trailing_newline)
608 fputc('\n', file);
611 static void emit_line(struct diff_options *o, const char *set, const char *reset,
612 const char *line, int len)
614 emit_line_0(o, set, reset, line[0], line+1, len-1);
617 enum diff_symbol {
618 DIFF_SYMBOL_BINARY_DIFF_HEADER,
619 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
620 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
621 DIFF_SYMBOL_BINARY_DIFF_BODY,
622 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
623 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
624 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
625 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
626 DIFF_SYMBOL_STATS_LINE,
627 DIFF_SYMBOL_WORD_DIFF,
628 DIFF_SYMBOL_STAT_SEP,
629 DIFF_SYMBOL_SUMMARY,
630 DIFF_SYMBOL_SUBMODULE_ADD,
631 DIFF_SYMBOL_SUBMODULE_DEL,
632 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
633 DIFF_SYMBOL_SUBMODULE_MODIFIED,
634 DIFF_SYMBOL_SUBMODULE_HEADER,
635 DIFF_SYMBOL_SUBMODULE_ERROR,
636 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
637 DIFF_SYMBOL_REWRITE_DIFF,
638 DIFF_SYMBOL_BINARY_FILES,
639 DIFF_SYMBOL_HEADER,
640 DIFF_SYMBOL_FILEPAIR_PLUS,
641 DIFF_SYMBOL_FILEPAIR_MINUS,
642 DIFF_SYMBOL_WORDS_PORCELAIN,
643 DIFF_SYMBOL_WORDS,
644 DIFF_SYMBOL_CONTEXT,
645 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
646 DIFF_SYMBOL_PLUS,
647 DIFF_SYMBOL_MINUS,
648 DIFF_SYMBOL_NO_LF_EOF,
649 DIFF_SYMBOL_CONTEXT_FRAGINFO,
650 DIFF_SYMBOL_CONTEXT_MARKER,
651 DIFF_SYMBOL_SEPARATOR
654 * Flags for content lines:
655 * 0..12 are whitespace rules
656 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
657 * 16 is marking if the line is blank at EOF
659 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
660 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
661 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
662 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
663 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
666 * This struct is used when we need to buffer the output of the diff output.
668 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
669 * into the pre/post image file. This pointer could be a union with the
670 * line pointer. By storing an offset into the file instead of the literal line,
671 * we can decrease the memory footprint for the buffered output. At first we
672 * may want to only have indirection for the content lines, but we could also
673 * enhance the state for emitting prefabricated lines, e.g. the similarity
674 * score line or hunk/file headers would only need to store a number or path
675 * and then the output can be constructed later on depending on state.
677 struct emitted_diff_symbol {
678 const char *line;
679 int len;
680 int flags;
681 enum diff_symbol s;
683 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
685 struct emitted_diff_symbols {
686 struct emitted_diff_symbol *buf;
687 int nr, alloc;
689 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
691 static void append_emitted_diff_symbol(struct diff_options *o,
692 struct emitted_diff_symbol *e)
694 struct emitted_diff_symbol *f;
696 ALLOC_GROW(o->emitted_symbols->buf,
697 o->emitted_symbols->nr + 1,
698 o->emitted_symbols->alloc);
699 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
701 memcpy(f, e, sizeof(struct emitted_diff_symbol));
702 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
705 struct moved_entry {
706 struct hashmap_entry ent;
707 const struct emitted_diff_symbol *es;
708 struct moved_entry *next_line;
711 static int moved_entry_cmp(const struct diff_options *diffopt,
712 const struct moved_entry *a,
713 const struct moved_entry *b,
714 const void *keydata)
716 return !xdiff_compare_lines(a->es->line, a->es->len,
717 b->es->line, b->es->len,
718 diffopt->xdl_opts);
721 static struct moved_entry *prepare_entry(struct diff_options *o,
722 int line_no)
724 struct moved_entry *ret = xmalloc(sizeof(*ret));
725 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
727 ret->ent.hash = xdiff_hash_string(l->line, l->len, o->xdl_opts);
728 ret->es = l;
729 ret->next_line = NULL;
731 return ret;
734 static void add_lines_to_move_detection(struct diff_options *o,
735 struct hashmap *add_lines,
736 struct hashmap *del_lines)
738 struct moved_entry *prev_line = NULL;
740 int n;
741 for (n = 0; n < o->emitted_symbols->nr; n++) {
742 struct hashmap *hm;
743 struct moved_entry *key;
745 switch (o->emitted_symbols->buf[n].s) {
746 case DIFF_SYMBOL_PLUS:
747 hm = add_lines;
748 break;
749 case DIFF_SYMBOL_MINUS:
750 hm = del_lines;
751 break;
752 default:
753 prev_line = NULL;
754 continue;
757 key = prepare_entry(o, n);
758 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
759 prev_line->next_line = key;
761 hashmap_add(hm, key);
762 prev_line = key;
766 static int shrink_potential_moved_blocks(struct moved_entry **pmb,
767 int pmb_nr)
769 int lp, rp;
771 /* Shrink the set of potential block to the remaining running */
772 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
773 while (lp < pmb_nr && pmb[lp])
774 lp++;
775 /* lp points at the first NULL now */
777 while (rp > -1 && !pmb[rp])
778 rp--;
779 /* rp points at the last non-NULL */
781 if (lp < pmb_nr && rp > -1 && lp < rp) {
782 pmb[lp] = pmb[rp];
783 pmb[rp] = NULL;
784 rp--;
785 lp++;
789 /* Remember the number of running sets */
790 return rp + 1;
794 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
796 * Otherwise, if the last block has fewer alphanumeric characters than
797 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
798 * that block.
800 * The last block consists of the (n - block_length)'th line up to but not
801 * including the nth line.
803 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
804 * Think of a way to unify them.
806 static void adjust_last_block(struct diff_options *o, int n, int block_length)
808 int i, alnum_count = 0;
809 if (o->color_moved == COLOR_MOVED_PLAIN)
810 return;
811 for (i = 1; i < block_length + 1; i++) {
812 const char *c = o->emitted_symbols->buf[n - i].line;
813 for (; *c; c++) {
814 if (!isalnum(*c))
815 continue;
816 alnum_count++;
817 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
818 return;
821 for (i = 1; i < block_length + 1; i++)
822 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
825 /* Find blocks of moved code, delegate actual coloring decision to helper */
826 static void mark_color_as_moved(struct diff_options *o,
827 struct hashmap *add_lines,
828 struct hashmap *del_lines)
830 struct moved_entry **pmb = NULL; /* potentially moved blocks */
831 int pmb_nr = 0, pmb_alloc = 0;
832 int n, flipped_block = 1, block_length = 0;
835 for (n = 0; n < o->emitted_symbols->nr; n++) {
836 struct hashmap *hm = NULL;
837 struct moved_entry *key;
838 struct moved_entry *match = NULL;
839 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
840 int i;
842 switch (l->s) {
843 case DIFF_SYMBOL_PLUS:
844 hm = del_lines;
845 key = prepare_entry(o, n);
846 match = hashmap_get(hm, key, o);
847 free(key);
848 break;
849 case DIFF_SYMBOL_MINUS:
850 hm = add_lines;
851 key = prepare_entry(o, n);
852 match = hashmap_get(hm, key, o);
853 free(key);
854 break;
855 default:
856 flipped_block = 1;
859 if (!match) {
860 adjust_last_block(o, n, block_length);
861 pmb_nr = 0;
862 block_length = 0;
863 continue;
866 l->flags |= DIFF_SYMBOL_MOVED_LINE;
868 if (o->color_moved == COLOR_MOVED_PLAIN)
869 continue;
871 /* Check any potential block runs, advance each or nullify */
872 for (i = 0; i < pmb_nr; i++) {
873 struct moved_entry *p = pmb[i];
874 struct moved_entry *pnext = (p && p->next_line) ?
875 p->next_line : NULL;
876 if (pnext && !hm->cmpfn(o, pnext, match, NULL)) {
877 pmb[i] = p->next_line;
878 } else {
879 pmb[i] = NULL;
883 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
885 if (pmb_nr == 0) {
887 * The current line is the start of a new block.
888 * Setup the set of potential blocks.
890 for (; match; match = hashmap_get_next(hm, match)) {
891 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
892 pmb[pmb_nr++] = match;
895 flipped_block = (flipped_block + 1) % 2;
897 adjust_last_block(o, n, block_length);
898 block_length = 0;
901 block_length++;
903 if (flipped_block)
904 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
906 adjust_last_block(o, n, block_length);
908 free(pmb);
911 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
912 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
913 static void dim_moved_lines(struct diff_options *o)
915 int n;
916 for (n = 0; n < o->emitted_symbols->nr; n++) {
917 struct emitted_diff_symbol *prev = (n != 0) ?
918 &o->emitted_symbols->buf[n - 1] : NULL;
919 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
920 struct emitted_diff_symbol *next =
921 (n < o->emitted_symbols->nr - 1) ?
922 &o->emitted_symbols->buf[n + 1] : NULL;
924 /* Not a plus or minus line? */
925 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
926 continue;
928 /* Not a moved line? */
929 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
930 continue;
933 * If prev or next are not a plus or minus line,
934 * pretend they don't exist
936 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
937 prev->s != DIFF_SYMBOL_MINUS)
938 prev = NULL;
939 if (next && next->s != DIFF_SYMBOL_PLUS &&
940 next->s != DIFF_SYMBOL_MINUS)
941 next = NULL;
943 /* Inside a block? */
944 if ((prev &&
945 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
946 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
947 (next &&
948 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
949 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
950 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
951 continue;
954 /* Check if we are at an interesting bound: */
955 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
956 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
957 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
958 continue;
959 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
960 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
961 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
962 continue;
965 * The boundary to prev and next are not interesting,
966 * so this line is not interesting as a whole
968 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
972 static void emit_line_ws_markup(struct diff_options *o,
973 const char *set, const char *reset,
974 const char *line, int len, char sign,
975 unsigned ws_rule, int blank_at_eof)
977 const char *ws = NULL;
979 if (o->ws_error_highlight & ws_rule) {
980 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
981 if (!*ws)
982 ws = NULL;
985 if (!ws)
986 emit_line_0(o, set, reset, sign, line, len);
987 else if (blank_at_eof)
988 /* Blank line at EOF - paint '+' as well */
989 emit_line_0(o, ws, reset, sign, line, len);
990 else {
991 /* Emit just the prefix, then the rest. */
992 emit_line_0(o, set, reset, sign, "", 0);
993 ws_check_emit(line, len, ws_rule,
994 o->file, set, reset, ws);
998 static void emit_diff_symbol_from_struct(struct diff_options *o,
999 struct emitted_diff_symbol *eds)
1001 static const char *nneof = " No newline at end of file\n";
1002 const char *context, *reset, *set, *meta, *fraginfo;
1003 struct strbuf sb = STRBUF_INIT;
1005 enum diff_symbol s = eds->s;
1006 const char *line = eds->line;
1007 int len = eds->len;
1008 unsigned flags = eds->flags;
1010 switch (s) {
1011 case DIFF_SYMBOL_NO_LF_EOF:
1012 context = diff_get_color_opt(o, DIFF_CONTEXT);
1013 reset = diff_get_color_opt(o, DIFF_RESET);
1014 putc('\n', o->file);
1015 emit_line_0(o, context, reset, '\\',
1016 nneof, strlen(nneof));
1017 break;
1018 case DIFF_SYMBOL_SUBMODULE_HEADER:
1019 case DIFF_SYMBOL_SUBMODULE_ERROR:
1020 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1021 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1022 case DIFF_SYMBOL_SUMMARY:
1023 case DIFF_SYMBOL_STATS_LINE:
1024 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1025 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1026 emit_line(o, "", "", line, len);
1027 break;
1028 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1029 case DIFF_SYMBOL_CONTEXT_MARKER:
1030 context = diff_get_color_opt(o, DIFF_CONTEXT);
1031 reset = diff_get_color_opt(o, DIFF_RESET);
1032 emit_line(o, context, reset, line, len);
1033 break;
1034 case DIFF_SYMBOL_SEPARATOR:
1035 fprintf(o->file, "%s%c",
1036 diff_line_prefix(o),
1037 o->line_termination);
1038 break;
1039 case DIFF_SYMBOL_CONTEXT:
1040 set = diff_get_color_opt(o, DIFF_CONTEXT);
1041 reset = diff_get_color_opt(o, DIFF_RESET);
1042 emit_line_ws_markup(o, set, reset, line, len, ' ',
1043 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1044 break;
1045 case DIFF_SYMBOL_PLUS:
1046 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1047 DIFF_SYMBOL_MOVED_LINE_ALT |
1048 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1049 case DIFF_SYMBOL_MOVED_LINE |
1050 DIFF_SYMBOL_MOVED_LINE_ALT |
1051 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1052 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1053 break;
1054 case DIFF_SYMBOL_MOVED_LINE |
1055 DIFF_SYMBOL_MOVED_LINE_ALT:
1056 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1057 break;
1058 case DIFF_SYMBOL_MOVED_LINE |
1059 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1060 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1061 break;
1062 case DIFF_SYMBOL_MOVED_LINE:
1063 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1064 break;
1065 default:
1066 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1068 reset = diff_get_color_opt(o, DIFF_RESET);
1069 emit_line_ws_markup(o, set, reset, line, len, '+',
1070 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1071 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1072 break;
1073 case DIFF_SYMBOL_MINUS:
1074 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1075 DIFF_SYMBOL_MOVED_LINE_ALT |
1076 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1077 case DIFF_SYMBOL_MOVED_LINE |
1078 DIFF_SYMBOL_MOVED_LINE_ALT |
1079 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1080 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1081 break;
1082 case DIFF_SYMBOL_MOVED_LINE |
1083 DIFF_SYMBOL_MOVED_LINE_ALT:
1084 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1085 break;
1086 case DIFF_SYMBOL_MOVED_LINE |
1087 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1088 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1089 break;
1090 case DIFF_SYMBOL_MOVED_LINE:
1091 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1092 break;
1093 default:
1094 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1096 reset = diff_get_color_opt(o, DIFF_RESET);
1097 emit_line_ws_markup(o, set, reset, line, len, '-',
1098 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1099 break;
1100 case DIFF_SYMBOL_WORDS_PORCELAIN:
1101 context = diff_get_color_opt(o, DIFF_CONTEXT);
1102 reset = diff_get_color_opt(o, DIFF_RESET);
1103 emit_line(o, context, reset, line, len);
1104 fputs("~\n", o->file);
1105 break;
1106 case DIFF_SYMBOL_WORDS:
1107 context = diff_get_color_opt(o, DIFF_CONTEXT);
1108 reset = diff_get_color_opt(o, DIFF_RESET);
1110 * Skip the prefix character, if any. With
1111 * diff_suppress_blank_empty, there may be
1112 * none.
1114 if (line[0] != '\n') {
1115 line++;
1116 len--;
1118 emit_line(o, context, reset, line, len);
1119 break;
1120 case DIFF_SYMBOL_FILEPAIR_PLUS:
1121 meta = diff_get_color_opt(o, DIFF_METAINFO);
1122 reset = diff_get_color_opt(o, DIFF_RESET);
1123 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1124 line, reset,
1125 strchr(line, ' ') ? "\t" : "");
1126 break;
1127 case DIFF_SYMBOL_FILEPAIR_MINUS:
1128 meta = diff_get_color_opt(o, DIFF_METAINFO);
1129 reset = diff_get_color_opt(o, DIFF_RESET);
1130 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1131 line, reset,
1132 strchr(line, ' ') ? "\t" : "");
1133 break;
1134 case DIFF_SYMBOL_BINARY_FILES:
1135 case DIFF_SYMBOL_HEADER:
1136 fprintf(o->file, "%s", line);
1137 break;
1138 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1139 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1140 break;
1141 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1142 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1143 break;
1144 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1145 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1146 break;
1147 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1148 fputs(diff_line_prefix(o), o->file);
1149 fputc('\n', o->file);
1150 break;
1151 case DIFF_SYMBOL_REWRITE_DIFF:
1152 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1153 reset = diff_get_color_opt(o, DIFF_RESET);
1154 emit_line(o, fraginfo, reset, line, len);
1155 break;
1156 case DIFF_SYMBOL_SUBMODULE_ADD:
1157 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1158 reset = diff_get_color_opt(o, DIFF_RESET);
1159 emit_line(o, set, reset, line, len);
1160 break;
1161 case DIFF_SYMBOL_SUBMODULE_DEL:
1162 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1163 reset = diff_get_color_opt(o, DIFF_RESET);
1164 emit_line(o, set, reset, line, len);
1165 break;
1166 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1167 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1168 diff_line_prefix(o), line);
1169 break;
1170 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1171 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1172 diff_line_prefix(o), line);
1173 break;
1174 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1175 emit_line(o, "", "", " 0 files changed\n",
1176 strlen(" 0 files changed\n"));
1177 break;
1178 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1179 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1180 break;
1181 case DIFF_SYMBOL_WORD_DIFF:
1182 fprintf(o->file, "%.*s", len, line);
1183 break;
1184 case DIFF_SYMBOL_STAT_SEP:
1185 fputs(o->stat_sep, o->file);
1186 break;
1187 default:
1188 die("BUG: unknown diff symbol");
1190 strbuf_release(&sb);
1193 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1194 const char *line, int len, unsigned flags)
1196 struct emitted_diff_symbol e = {line, len, flags, s};
1198 if (o->emitted_symbols)
1199 append_emitted_diff_symbol(o, &e);
1200 else
1201 emit_diff_symbol_from_struct(o, &e);
1204 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1206 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1209 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1211 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1214 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1216 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1217 path, strlen(path), 0);
1220 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1222 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1223 path, strlen(path), 0);
1226 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1228 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1229 header, strlen(header), 0);
1232 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1234 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1237 void diff_emit_submodule_pipethrough(struct diff_options *o,
1238 const char *line, int len)
1240 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1243 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1245 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1246 ecbdata->blank_at_eof_in_preimage &&
1247 ecbdata->blank_at_eof_in_postimage &&
1248 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1249 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1250 return 0;
1251 return ws_blank_line(line, len, ecbdata->ws_rule);
1254 static void emit_add_line(const char *reset,
1255 struct emit_callback *ecbdata,
1256 const char *line, int len)
1258 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1259 if (new_blank_line_at_eof(ecbdata, line, len))
1260 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1262 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1265 static void emit_del_line(const char *reset,
1266 struct emit_callback *ecbdata,
1267 const char *line, int len)
1269 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1270 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1273 static void emit_context_line(const char *reset,
1274 struct emit_callback *ecbdata,
1275 const char *line, int len)
1277 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1278 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1281 static void emit_hunk_header(struct emit_callback *ecbdata,
1282 const char *line, int len)
1284 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1285 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1286 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1287 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1288 static const char atat[2] = { '@', '@' };
1289 const char *cp, *ep;
1290 struct strbuf msgbuf = STRBUF_INIT;
1291 int org_len = len;
1292 int i = 1;
1295 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1296 * it always is at least 10 bytes long.
1298 if (len < 10 ||
1299 memcmp(line, atat, 2) ||
1300 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1301 emit_diff_symbol(ecbdata->opt,
1302 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1303 return;
1305 ep += 2; /* skip over @@ */
1307 /* The hunk header in fraginfo color */
1308 strbuf_addstr(&msgbuf, frag);
1309 strbuf_add(&msgbuf, line, ep - line);
1310 strbuf_addstr(&msgbuf, reset);
1313 * trailing "\r\n"
1315 for ( ; i < 3; i++)
1316 if (line[len - i] == '\r' || line[len - i] == '\n')
1317 len--;
1319 /* blank before the func header */
1320 for (cp = ep; ep - line < len; ep++)
1321 if (*ep != ' ' && *ep != '\t')
1322 break;
1323 if (ep != cp) {
1324 strbuf_addstr(&msgbuf, context);
1325 strbuf_add(&msgbuf, cp, ep - cp);
1326 strbuf_addstr(&msgbuf, reset);
1329 if (ep < line + len) {
1330 strbuf_addstr(&msgbuf, func);
1331 strbuf_add(&msgbuf, ep, line + len - ep);
1332 strbuf_addstr(&msgbuf, reset);
1335 strbuf_add(&msgbuf, line + len, org_len - len);
1336 strbuf_complete_line(&msgbuf);
1337 emit_diff_symbol(ecbdata->opt,
1338 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1339 strbuf_release(&msgbuf);
1342 static struct diff_tempfile *claim_diff_tempfile(void) {
1343 int i;
1344 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1345 if (!diff_temp[i].name)
1346 return diff_temp + i;
1347 die("BUG: diff is failing to clean up its tempfiles");
1350 static void remove_tempfile(void)
1352 int i;
1353 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1354 if (is_tempfile_active(diff_temp[i].tempfile))
1355 delete_tempfile(&diff_temp[i].tempfile);
1356 diff_temp[i].name = NULL;
1360 static void add_line_count(struct strbuf *out, int count)
1362 switch (count) {
1363 case 0:
1364 strbuf_addstr(out, "0,0");
1365 break;
1366 case 1:
1367 strbuf_addstr(out, "1");
1368 break;
1369 default:
1370 strbuf_addf(out, "1,%d", count);
1371 break;
1375 static void emit_rewrite_lines(struct emit_callback *ecb,
1376 int prefix, const char *data, int size)
1378 const char *endp = NULL;
1379 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1381 while (0 < size) {
1382 int len;
1384 endp = memchr(data, '\n', size);
1385 len = endp ? (endp - data + 1) : size;
1386 if (prefix != '+') {
1387 ecb->lno_in_preimage++;
1388 emit_del_line(reset, ecb, data, len);
1389 } else {
1390 ecb->lno_in_postimage++;
1391 emit_add_line(reset, ecb, data, len);
1393 size -= len;
1394 data += len;
1396 if (!endp)
1397 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1400 static void emit_rewrite_diff(const char *name_a,
1401 const char *name_b,
1402 struct diff_filespec *one,
1403 struct diff_filespec *two,
1404 struct userdiff_driver *textconv_one,
1405 struct userdiff_driver *textconv_two,
1406 struct diff_options *o)
1408 int lc_a, lc_b;
1409 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1410 const char *a_prefix, *b_prefix;
1411 char *data_one, *data_two;
1412 size_t size_one, size_two;
1413 struct emit_callback ecbdata;
1414 struct strbuf out = STRBUF_INIT;
1416 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1417 a_prefix = o->b_prefix;
1418 b_prefix = o->a_prefix;
1419 } else {
1420 a_prefix = o->a_prefix;
1421 b_prefix = o->b_prefix;
1424 name_a += (*name_a == '/');
1425 name_b += (*name_b == '/');
1427 strbuf_reset(&a_name);
1428 strbuf_reset(&b_name);
1429 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1430 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1432 size_one = fill_textconv(textconv_one, one, &data_one);
1433 size_two = fill_textconv(textconv_two, two, &data_two);
1435 memset(&ecbdata, 0, sizeof(ecbdata));
1436 ecbdata.color_diff = want_color(o->use_color);
1437 ecbdata.ws_rule = whitespace_rule(name_b);
1438 ecbdata.opt = o;
1439 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1440 mmfile_t mf1, mf2;
1441 mf1.ptr = (char *)data_one;
1442 mf2.ptr = (char *)data_two;
1443 mf1.size = size_one;
1444 mf2.size = size_two;
1445 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1447 ecbdata.lno_in_preimage = 1;
1448 ecbdata.lno_in_postimage = 1;
1450 lc_a = count_lines(data_one, size_one);
1451 lc_b = count_lines(data_two, size_two);
1453 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1454 a_name.buf, a_name.len, 0);
1455 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1456 b_name.buf, b_name.len, 0);
1458 strbuf_addstr(&out, "@@ -");
1459 if (!o->irreversible_delete)
1460 add_line_count(&out, lc_a);
1461 else
1462 strbuf_addstr(&out, "?,?");
1463 strbuf_addstr(&out, " +");
1464 add_line_count(&out, lc_b);
1465 strbuf_addstr(&out, " @@\n");
1466 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1467 strbuf_release(&out);
1469 if (lc_a && !o->irreversible_delete)
1470 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1471 if (lc_b)
1472 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1473 if (textconv_one)
1474 free((char *)data_one);
1475 if (textconv_two)
1476 free((char *)data_two);
1479 struct diff_words_buffer {
1480 mmfile_t text;
1481 unsigned long alloc;
1482 struct diff_words_orig {
1483 const char *begin, *end;
1484 } *orig;
1485 int orig_nr, orig_alloc;
1488 static void diff_words_append(char *line, unsigned long len,
1489 struct diff_words_buffer *buffer)
1491 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1492 line++;
1493 len--;
1494 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1495 buffer->text.size += len;
1496 buffer->text.ptr[buffer->text.size] = '\0';
1499 struct diff_words_style_elem {
1500 const char *prefix;
1501 const char *suffix;
1502 const char *color; /* NULL; filled in by the setup code if
1503 * color is enabled */
1506 struct diff_words_style {
1507 enum diff_words_type type;
1508 struct diff_words_style_elem new_word, old_word, ctx;
1509 const char *newline;
1512 static struct diff_words_style diff_words_styles[] = {
1513 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1514 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1515 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1518 struct diff_words_data {
1519 struct diff_words_buffer minus, plus;
1520 const char *current_plus;
1521 int last_minus;
1522 struct diff_options *opt;
1523 regex_t *word_regex;
1524 enum diff_words_type type;
1525 struct diff_words_style *style;
1528 static int fn_out_diff_words_write_helper(struct diff_options *o,
1529 struct diff_words_style_elem *st_el,
1530 const char *newline,
1531 size_t count, const char *buf)
1533 int print = 0;
1534 struct strbuf sb = STRBUF_INIT;
1536 while (count) {
1537 char *p = memchr(buf, '\n', count);
1538 if (print)
1539 strbuf_addstr(&sb, diff_line_prefix(o));
1541 if (p != buf) {
1542 const char *reset = st_el->color && *st_el->color ?
1543 GIT_COLOR_RESET : NULL;
1544 if (st_el->color && *st_el->color)
1545 strbuf_addstr(&sb, st_el->color);
1546 strbuf_addstr(&sb, st_el->prefix);
1547 strbuf_add(&sb, buf, p ? p - buf : count);
1548 strbuf_addstr(&sb, st_el->suffix);
1549 if (reset)
1550 strbuf_addstr(&sb, reset);
1552 if (!p)
1553 goto out;
1555 strbuf_addstr(&sb, newline);
1556 count -= p + 1 - buf;
1557 buf = p + 1;
1558 print = 1;
1559 if (count) {
1560 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1561 sb.buf, sb.len, 0);
1562 strbuf_reset(&sb);
1566 out:
1567 if (sb.len)
1568 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1569 sb.buf, sb.len, 0);
1570 strbuf_release(&sb);
1571 return 0;
1575 * '--color-words' algorithm can be described as:
1577 * 1. collect the minus/plus lines of a diff hunk, divided into
1578 * minus-lines and plus-lines;
1580 * 2. break both minus-lines and plus-lines into words and
1581 * place them into two mmfile_t with one word for each line;
1583 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1585 * And for the common parts of the both file, we output the plus side text.
1586 * diff_words->current_plus is used to trace the current position of the plus file
1587 * which printed. diff_words->last_minus is used to trace the last minus word
1588 * printed.
1590 * For '--graph' to work with '--color-words', we need to output the graph prefix
1591 * on each line of color words output. Generally, there are two conditions on
1592 * which we should output the prefix.
1594 * 1. diff_words->last_minus == 0 &&
1595 * diff_words->current_plus == diff_words->plus.text.ptr
1597 * that is: the plus text must start as a new line, and if there is no minus
1598 * word printed, a graph prefix must be printed.
1600 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1601 * *(diff_words->current_plus - 1) == '\n'
1603 * that is: a graph prefix must be printed following a '\n'
1605 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1607 if ((diff_words->last_minus == 0 &&
1608 diff_words->current_plus == diff_words->plus.text.ptr) ||
1609 (diff_words->current_plus > diff_words->plus.text.ptr &&
1610 *(diff_words->current_plus - 1) == '\n')) {
1611 return 1;
1612 } else {
1613 return 0;
1617 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
1619 struct diff_words_data *diff_words = priv;
1620 struct diff_words_style *style = diff_words->style;
1621 int minus_first, minus_len, plus_first, plus_len;
1622 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1623 struct diff_options *opt = diff_words->opt;
1624 const char *line_prefix;
1626 if (line[0] != '@' || parse_hunk_header(line, len,
1627 &minus_first, &minus_len, &plus_first, &plus_len))
1628 return;
1630 assert(opt);
1631 line_prefix = diff_line_prefix(opt);
1633 /* POSIX requires that first be decremented by one if len == 0... */
1634 if (minus_len) {
1635 minus_begin = diff_words->minus.orig[minus_first].begin;
1636 minus_end =
1637 diff_words->minus.orig[minus_first + minus_len - 1].end;
1638 } else
1639 minus_begin = minus_end =
1640 diff_words->minus.orig[minus_first].end;
1642 if (plus_len) {
1643 plus_begin = diff_words->plus.orig[plus_first].begin;
1644 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1645 } else
1646 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1648 if (color_words_output_graph_prefix(diff_words)) {
1649 fputs(line_prefix, diff_words->opt->file);
1651 if (diff_words->current_plus != plus_begin) {
1652 fn_out_diff_words_write_helper(diff_words->opt,
1653 &style->ctx, style->newline,
1654 plus_begin - diff_words->current_plus,
1655 diff_words->current_plus);
1657 if (minus_begin != minus_end) {
1658 fn_out_diff_words_write_helper(diff_words->opt,
1659 &style->old_word, style->newline,
1660 minus_end - minus_begin, minus_begin);
1662 if (plus_begin != plus_end) {
1663 fn_out_diff_words_write_helper(diff_words->opt,
1664 &style->new_word, style->newline,
1665 plus_end - plus_begin, plus_begin);
1668 diff_words->current_plus = plus_end;
1669 diff_words->last_minus = minus_first;
1672 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1673 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1674 int *begin, int *end)
1676 if (word_regex && *begin < buffer->size) {
1677 regmatch_t match[1];
1678 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1679 buffer->size - *begin, 1, match, 0)) {
1680 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1681 '\n', match[0].rm_eo - match[0].rm_so);
1682 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1683 *begin += match[0].rm_so;
1684 return *begin >= *end;
1686 return -1;
1689 /* find the next word */
1690 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1691 (*begin)++;
1692 if (*begin >= buffer->size)
1693 return -1;
1695 /* find the end of the word */
1696 *end = *begin + 1;
1697 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1698 (*end)++;
1700 return 0;
1704 * This function splits the words in buffer->text, stores the list with
1705 * newline separator into out, and saves the offsets of the original words
1706 * in buffer->orig.
1708 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1709 regex_t *word_regex)
1711 int i, j;
1712 long alloc = 0;
1714 out->size = 0;
1715 out->ptr = NULL;
1717 /* fake an empty "0th" word */
1718 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1719 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1720 buffer->orig_nr = 1;
1722 for (i = 0; i < buffer->text.size; i++) {
1723 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1724 return;
1726 /* store original boundaries */
1727 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1728 buffer->orig_alloc);
1729 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1730 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1731 buffer->orig_nr++;
1733 /* store one word */
1734 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1735 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1736 out->ptr[out->size + j - i] = '\n';
1737 out->size += j - i + 1;
1739 i = j - 1;
1743 /* this executes the word diff on the accumulated buffers */
1744 static void diff_words_show(struct diff_words_data *diff_words)
1746 xpparam_t xpp;
1747 xdemitconf_t xecfg;
1748 mmfile_t minus, plus;
1749 struct diff_words_style *style = diff_words->style;
1751 struct diff_options *opt = diff_words->opt;
1752 const char *line_prefix;
1754 assert(opt);
1755 line_prefix = diff_line_prefix(opt);
1757 /* special case: only removal */
1758 if (!diff_words->plus.text.size) {
1759 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1760 line_prefix, strlen(line_prefix), 0);
1761 fn_out_diff_words_write_helper(diff_words->opt,
1762 &style->old_word, style->newline,
1763 diff_words->minus.text.size,
1764 diff_words->minus.text.ptr);
1765 diff_words->minus.text.size = 0;
1766 return;
1769 diff_words->current_plus = diff_words->plus.text.ptr;
1770 diff_words->last_minus = 0;
1772 memset(&xpp, 0, sizeof(xpp));
1773 memset(&xecfg, 0, sizeof(xecfg));
1774 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1775 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1776 xpp.flags = 0;
1777 /* as only the hunk header will be parsed, we need a 0-context */
1778 xecfg.ctxlen = 0;
1779 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1780 &xpp, &xecfg))
1781 die("unable to generate word diff");
1782 free(minus.ptr);
1783 free(plus.ptr);
1784 if (diff_words->current_plus != diff_words->plus.text.ptr +
1785 diff_words->plus.text.size) {
1786 if (color_words_output_graph_prefix(diff_words))
1787 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1788 line_prefix, strlen(line_prefix), 0);
1789 fn_out_diff_words_write_helper(diff_words->opt,
1790 &style->ctx, style->newline,
1791 diff_words->plus.text.ptr + diff_words->plus.text.size
1792 - diff_words->current_plus, diff_words->current_plus);
1794 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1797 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1798 static void diff_words_flush(struct emit_callback *ecbdata)
1800 struct diff_options *wo = ecbdata->diff_words->opt;
1802 if (ecbdata->diff_words->minus.text.size ||
1803 ecbdata->diff_words->plus.text.size)
1804 diff_words_show(ecbdata->diff_words);
1806 if (wo->emitted_symbols) {
1807 struct diff_options *o = ecbdata->opt;
1808 struct emitted_diff_symbols *wol = wo->emitted_symbols;
1809 int i;
1812 * NEEDSWORK:
1813 * Instead of appending each, concat all words to a line?
1815 for (i = 0; i < wol->nr; i++)
1816 append_emitted_diff_symbol(o, &wol->buf[i]);
1818 for (i = 0; i < wol->nr; i++)
1819 free((void *)wol->buf[i].line);
1821 wol->nr = 0;
1825 static void diff_filespec_load_driver(struct diff_filespec *one)
1827 /* Use already-loaded driver */
1828 if (one->driver)
1829 return;
1831 if (S_ISREG(one->mode))
1832 one->driver = userdiff_find_by_path(one->path);
1834 /* Fallback to default settings */
1835 if (!one->driver)
1836 one->driver = userdiff_find_by_name("default");
1839 static const char *userdiff_word_regex(struct diff_filespec *one)
1841 diff_filespec_load_driver(one);
1842 return one->driver->word_regex;
1845 static void init_diff_words_data(struct emit_callback *ecbdata,
1846 struct diff_options *orig_opts,
1847 struct diff_filespec *one,
1848 struct diff_filespec *two)
1850 int i;
1851 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1852 memcpy(o, orig_opts, sizeof(struct diff_options));
1854 ecbdata->diff_words =
1855 xcalloc(1, sizeof(struct diff_words_data));
1856 ecbdata->diff_words->type = o->word_diff;
1857 ecbdata->diff_words->opt = o;
1859 if (orig_opts->emitted_symbols)
1860 o->emitted_symbols =
1861 xcalloc(1, sizeof(struct emitted_diff_symbols));
1863 if (!o->word_regex)
1864 o->word_regex = userdiff_word_regex(one);
1865 if (!o->word_regex)
1866 o->word_regex = userdiff_word_regex(two);
1867 if (!o->word_regex)
1868 o->word_regex = diff_word_regex_cfg;
1869 if (o->word_regex) {
1870 ecbdata->diff_words->word_regex = (regex_t *)
1871 xmalloc(sizeof(regex_t));
1872 if (regcomp(ecbdata->diff_words->word_regex,
1873 o->word_regex,
1874 REG_EXTENDED | REG_NEWLINE))
1875 die ("Invalid regular expression: %s",
1876 o->word_regex);
1878 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1879 if (o->word_diff == diff_words_styles[i].type) {
1880 ecbdata->diff_words->style =
1881 &diff_words_styles[i];
1882 break;
1885 if (want_color(o->use_color)) {
1886 struct diff_words_style *st = ecbdata->diff_words->style;
1887 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1888 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1889 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1893 static void free_diff_words_data(struct emit_callback *ecbdata)
1895 if (ecbdata->diff_words) {
1896 diff_words_flush(ecbdata);
1897 free (ecbdata->diff_words->opt->emitted_symbols);
1898 free (ecbdata->diff_words->opt);
1899 free (ecbdata->diff_words->minus.text.ptr);
1900 free (ecbdata->diff_words->minus.orig);
1901 free (ecbdata->diff_words->plus.text.ptr);
1902 free (ecbdata->diff_words->plus.orig);
1903 if (ecbdata->diff_words->word_regex) {
1904 regfree(ecbdata->diff_words->word_regex);
1905 free(ecbdata->diff_words->word_regex);
1907 FREE_AND_NULL(ecbdata->diff_words);
1911 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1913 if (want_color(diff_use_color))
1914 return diff_colors[ix];
1915 return "";
1918 const char *diff_line_prefix(struct diff_options *opt)
1920 struct strbuf *msgbuf;
1921 if (!opt->output_prefix)
1922 return "";
1924 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1925 return msgbuf->buf;
1928 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1930 const char *cp;
1931 unsigned long allot;
1932 size_t l = len;
1934 cp = line;
1935 allot = l;
1936 while (0 < l) {
1937 (void) utf8_width(&cp, &l);
1938 if (!cp)
1939 break; /* truncated in the middle? */
1941 return allot - l;
1944 static void find_lno(const char *line, struct emit_callback *ecbdata)
1946 const char *p;
1947 ecbdata->lno_in_preimage = 0;
1948 ecbdata->lno_in_postimage = 0;
1949 p = strchr(line, '-');
1950 if (!p)
1951 return; /* cannot happen */
1952 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1953 p = strchr(p, '+');
1954 if (!p)
1955 return; /* cannot happen */
1956 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1959 static void fn_out_consume(void *priv, char *line, unsigned long len)
1961 struct emit_callback *ecbdata = priv;
1962 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1963 struct diff_options *o = ecbdata->opt;
1965 o->found_changes = 1;
1967 if (ecbdata->header) {
1968 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
1969 ecbdata->header->buf, ecbdata->header->len, 0);
1970 strbuf_reset(ecbdata->header);
1971 ecbdata->header = NULL;
1974 if (ecbdata->label_path[0]) {
1975 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1976 ecbdata->label_path[0],
1977 strlen(ecbdata->label_path[0]), 0);
1978 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1979 ecbdata->label_path[1],
1980 strlen(ecbdata->label_path[1]), 0);
1981 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1984 if (diff_suppress_blank_empty
1985 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1986 line[0] = '\n';
1987 len = 1;
1990 if (line[0] == '@') {
1991 if (ecbdata->diff_words)
1992 diff_words_flush(ecbdata);
1993 len = sane_truncate_line(ecbdata, line, len);
1994 find_lno(line, ecbdata);
1995 emit_hunk_header(ecbdata, line, len);
1996 return;
1999 if (ecbdata->diff_words) {
2000 enum diff_symbol s =
2001 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2002 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2003 if (line[0] == '-') {
2004 diff_words_append(line, len,
2005 &ecbdata->diff_words->minus);
2006 return;
2007 } else if (line[0] == '+') {
2008 diff_words_append(line, len,
2009 &ecbdata->diff_words->plus);
2010 return;
2011 } else if (starts_with(line, "\\ ")) {
2013 * Eat the "no newline at eof" marker as if we
2014 * saw a "+" or "-" line with nothing on it,
2015 * and return without diff_words_flush() to
2016 * defer processing. If this is the end of
2017 * preimage, more "+" lines may come after it.
2019 return;
2021 diff_words_flush(ecbdata);
2022 emit_diff_symbol(o, s, line, len, 0);
2023 return;
2026 switch (line[0]) {
2027 case '+':
2028 ecbdata->lno_in_postimage++;
2029 emit_add_line(reset, ecbdata, line + 1, len - 1);
2030 break;
2031 case '-':
2032 ecbdata->lno_in_preimage++;
2033 emit_del_line(reset, ecbdata, line + 1, len - 1);
2034 break;
2035 case ' ':
2036 ecbdata->lno_in_postimage++;
2037 ecbdata->lno_in_preimage++;
2038 emit_context_line(reset, ecbdata, line + 1, len - 1);
2039 break;
2040 default:
2041 /* incomplete line at the end */
2042 ecbdata->lno_in_preimage++;
2043 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2044 line, len, 0);
2045 break;
2049 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2051 const char *old_name = a;
2052 const char *new_name = b;
2053 int pfx_length, sfx_length;
2054 int pfx_adjust_for_slash;
2055 int len_a = strlen(a);
2056 int len_b = strlen(b);
2057 int a_midlen, b_midlen;
2058 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2059 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2061 if (qlen_a || qlen_b) {
2062 quote_c_style(a, name, NULL, 0);
2063 strbuf_addstr(name, " => ");
2064 quote_c_style(b, name, NULL, 0);
2065 return;
2068 /* Find common prefix */
2069 pfx_length = 0;
2070 while (*old_name && *new_name && *old_name == *new_name) {
2071 if (*old_name == '/')
2072 pfx_length = old_name - a + 1;
2073 old_name++;
2074 new_name++;
2077 /* Find common suffix */
2078 old_name = a + len_a;
2079 new_name = b + len_b;
2080 sfx_length = 0;
2082 * If there is a common prefix, it must end in a slash. In
2083 * that case we let this loop run 1 into the prefix to see the
2084 * same slash.
2086 * If there is no common prefix, we cannot do this as it would
2087 * underrun the input strings.
2089 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2090 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2091 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2092 *old_name == *new_name) {
2093 if (*old_name == '/')
2094 sfx_length = len_a - (old_name - a);
2095 old_name--;
2096 new_name--;
2100 * pfx{mid-a => mid-b}sfx
2101 * {pfx-a => pfx-b}sfx
2102 * pfx{sfx-a => sfx-b}
2103 * name-a => name-b
2105 a_midlen = len_a - pfx_length - sfx_length;
2106 b_midlen = len_b - pfx_length - sfx_length;
2107 if (a_midlen < 0)
2108 a_midlen = 0;
2109 if (b_midlen < 0)
2110 b_midlen = 0;
2112 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2113 if (pfx_length + sfx_length) {
2114 strbuf_add(name, a, pfx_length);
2115 strbuf_addch(name, '{');
2117 strbuf_add(name, a + pfx_length, a_midlen);
2118 strbuf_addstr(name, " => ");
2119 strbuf_add(name, b + pfx_length, b_midlen);
2120 if (pfx_length + sfx_length) {
2121 strbuf_addch(name, '}');
2122 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2126 struct diffstat_t {
2127 int nr;
2128 int alloc;
2129 struct diffstat_file {
2130 char *from_name;
2131 char *name;
2132 char *print_name;
2133 const char *comments;
2134 unsigned is_unmerged:1;
2135 unsigned is_binary:1;
2136 unsigned is_renamed:1;
2137 unsigned is_interesting:1;
2138 uintmax_t added, deleted;
2139 } **files;
2142 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2143 const char *name_a,
2144 const char *name_b)
2146 struct diffstat_file *x;
2147 x = xcalloc(1, sizeof(*x));
2148 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2149 diffstat->files[diffstat->nr++] = x;
2150 if (name_b) {
2151 x->from_name = xstrdup(name_a);
2152 x->name = xstrdup(name_b);
2153 x->is_renamed = 1;
2155 else {
2156 x->from_name = NULL;
2157 x->name = xstrdup(name_a);
2159 return x;
2162 static void diffstat_consume(void *priv, char *line, unsigned long len)
2164 struct diffstat_t *diffstat = priv;
2165 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2167 if (line[0] == '+')
2168 x->added++;
2169 else if (line[0] == '-')
2170 x->deleted++;
2173 const char mime_boundary_leader[] = "------------";
2175 static int scale_linear(int it, int width, int max_change)
2177 if (!it)
2178 return 0;
2180 * make sure that at least one '-' or '+' is printed if
2181 * there is any change to this path. The easiest way is to
2182 * scale linearly as if the alloted width is one column shorter
2183 * than it is, and then add 1 to the result.
2185 return 1 + (it * (width - 1) / max_change);
2188 static void show_graph(struct strbuf *out, char ch, int cnt,
2189 const char *set, const char *reset)
2191 if (cnt <= 0)
2192 return;
2193 strbuf_addstr(out, set);
2194 strbuf_addchars(out, ch, cnt);
2195 strbuf_addstr(out, reset);
2198 static void fill_print_name(struct diffstat_file *file)
2200 struct strbuf pname = STRBUF_INIT;
2202 if (file->print_name)
2203 return;
2205 if (file->is_renamed)
2206 pprint_rename(&pname, file->from_name, file->name);
2207 else
2208 quote_c_style(file->name, &pname, NULL, 0);
2210 if (file->comments)
2211 strbuf_addf(&pname, " (%s)", file->comments);
2213 file->print_name = strbuf_detach(&pname, NULL);
2216 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2217 int files, int insertions, int deletions)
2219 struct strbuf sb = STRBUF_INIT;
2221 if (!files) {
2222 assert(insertions == 0 && deletions == 0);
2223 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2224 NULL, 0, 0);
2225 return;
2228 strbuf_addf(&sb,
2229 (files == 1) ? " %d file changed" : " %d files changed",
2230 files);
2233 * For binary diff, the caller may want to print "x files
2234 * changed" with insertions == 0 && deletions == 0.
2236 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2237 * is probably less confusing (i.e skip over "2 files changed
2238 * but nothing about added/removed lines? Is this a bug in Git?").
2240 if (insertions || deletions == 0) {
2241 strbuf_addf(&sb,
2242 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2243 insertions);
2246 if (deletions || insertions == 0) {
2247 strbuf_addf(&sb,
2248 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2249 deletions);
2251 strbuf_addch(&sb, '\n');
2252 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2253 sb.buf, sb.len, 0);
2254 strbuf_release(&sb);
2257 void print_stat_summary(FILE *fp, int files,
2258 int insertions, int deletions)
2260 struct diff_options o;
2261 memset(&o, 0, sizeof(o));
2262 o.file = fp;
2264 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2267 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2269 int i, len, add, del, adds = 0, dels = 0;
2270 uintmax_t max_change = 0, max_len = 0;
2271 int total_files = data->nr, count;
2272 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2273 const char *reset, *add_c, *del_c;
2274 int extra_shown = 0;
2275 const char *line_prefix = diff_line_prefix(options);
2276 struct strbuf out = STRBUF_INIT;
2278 if (data->nr == 0)
2279 return;
2281 count = options->stat_count ? options->stat_count : data->nr;
2283 reset = diff_get_color_opt(options, DIFF_RESET);
2284 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2285 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2288 * Find the longest filename and max number of changes
2290 for (i = 0; (i < count) && (i < data->nr); i++) {
2291 struct diffstat_file *file = data->files[i];
2292 uintmax_t change = file->added + file->deleted;
2294 if (!file->is_interesting && (change == 0)) {
2295 count++; /* not shown == room for one more */
2296 continue;
2298 fill_print_name(file);
2299 len = strlen(file->print_name);
2300 if (max_len < len)
2301 max_len = len;
2303 if (file->is_unmerged) {
2304 /* "Unmerged" is 8 characters */
2305 bin_width = bin_width < 8 ? 8 : bin_width;
2306 continue;
2308 if (file->is_binary) {
2309 /* "Bin XXX -> YYY bytes" */
2310 int w = 14 + decimal_width(file->added)
2311 + decimal_width(file->deleted);
2312 bin_width = bin_width < w ? w : bin_width;
2313 /* Display change counts aligned with "Bin" */
2314 number_width = 3;
2315 continue;
2318 if (max_change < change)
2319 max_change = change;
2321 count = i; /* where we can stop scanning in data->files[] */
2324 * We have width = stat_width or term_columns() columns total.
2325 * We want a maximum of min(max_len, stat_name_width) for the name part.
2326 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2327 * We also need 1 for " " and 4 + decimal_width(max_change)
2328 * for " | NNNN " and one the empty column at the end, altogether
2329 * 6 + decimal_width(max_change).
2331 * If there's not enough space, we will use the smaller of
2332 * stat_name_width (if set) and 5/8*width for the filename,
2333 * and the rest for constant elements + graph part, but no more
2334 * than stat_graph_width for the graph part.
2335 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2336 * for the standard terminal size).
2338 * In other words: stat_width limits the maximum width, and
2339 * stat_name_width fixes the maximum width of the filename,
2340 * and is also used to divide available columns if there
2341 * aren't enough.
2343 * Binary files are displayed with "Bin XXX -> YYY bytes"
2344 * instead of the change count and graph. This part is treated
2345 * similarly to the graph part, except that it is not
2346 * "scaled". If total width is too small to accommodate the
2347 * guaranteed minimum width of the filename part and the
2348 * separators and this message, this message will "overflow"
2349 * making the line longer than the maximum width.
2352 if (options->stat_width == -1)
2353 width = term_columns() - strlen(line_prefix);
2354 else
2355 width = options->stat_width ? options->stat_width : 80;
2356 number_width = decimal_width(max_change) > number_width ?
2357 decimal_width(max_change) : number_width;
2359 if (options->stat_graph_width == -1)
2360 options->stat_graph_width = diff_stat_graph_width;
2363 * Guarantee 3/8*16==6 for the graph part
2364 * and 5/8*16==10 for the filename part
2366 if (width < 16 + 6 + number_width)
2367 width = 16 + 6 + number_width;
2370 * First assign sizes that are wanted, ignoring available width.
2371 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2372 * starting from "XXX" should fit in graph_width.
2374 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2375 if (options->stat_graph_width &&
2376 options->stat_graph_width < graph_width)
2377 graph_width = options->stat_graph_width;
2379 name_width = (options->stat_name_width > 0 &&
2380 options->stat_name_width < max_len) ?
2381 options->stat_name_width : max_len;
2384 * Adjust adjustable widths not to exceed maximum width
2386 if (name_width + number_width + 6 + graph_width > width) {
2387 if (graph_width > width * 3/8 - number_width - 6) {
2388 graph_width = width * 3/8 - number_width - 6;
2389 if (graph_width < 6)
2390 graph_width = 6;
2393 if (options->stat_graph_width &&
2394 graph_width > options->stat_graph_width)
2395 graph_width = options->stat_graph_width;
2396 if (name_width > width - number_width - 6 - graph_width)
2397 name_width = width - number_width - 6 - graph_width;
2398 else
2399 graph_width = width - number_width - 6 - name_width;
2403 * From here name_width is the width of the name area,
2404 * and graph_width is the width of the graph area.
2405 * max_change is used to scale graph properly.
2407 for (i = 0; i < count; i++) {
2408 const char *prefix = "";
2409 struct diffstat_file *file = data->files[i];
2410 char *name = file->print_name;
2411 uintmax_t added = file->added;
2412 uintmax_t deleted = file->deleted;
2413 int name_len;
2415 if (!file->is_interesting && (added + deleted == 0))
2416 continue;
2419 * "scale" the filename
2421 len = name_width;
2422 name_len = strlen(name);
2423 if (name_width < name_len) {
2424 char *slash;
2425 prefix = "...";
2426 len -= 3;
2427 name += name_len - len;
2428 slash = strchr(name, '/');
2429 if (slash)
2430 name = slash;
2433 if (file->is_binary) {
2434 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2435 strbuf_addf(&out, " %*s", number_width, "Bin");
2436 if (!added && !deleted) {
2437 strbuf_addch(&out, '\n');
2438 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2439 out.buf, out.len, 0);
2440 strbuf_reset(&out);
2441 continue;
2443 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2444 del_c, deleted, reset);
2445 strbuf_addstr(&out, " -> ");
2446 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2447 add_c, added, reset);
2448 strbuf_addstr(&out, " bytes\n");
2449 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2450 out.buf, out.len, 0);
2451 strbuf_reset(&out);
2452 continue;
2454 else if (file->is_unmerged) {
2455 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2456 strbuf_addstr(&out, " Unmerged\n");
2457 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2458 out.buf, out.len, 0);
2459 strbuf_reset(&out);
2460 continue;
2464 * scale the add/delete
2466 add = added;
2467 del = deleted;
2469 if (graph_width <= max_change) {
2470 int total = scale_linear(add + del, graph_width, max_change);
2471 if (total < 2 && add && del)
2472 /* width >= 2 due to the sanity check */
2473 total = 2;
2474 if (add < del) {
2475 add = scale_linear(add, graph_width, max_change);
2476 del = total - add;
2477 } else {
2478 del = scale_linear(del, graph_width, max_change);
2479 add = total - del;
2482 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2483 strbuf_addf(&out, " %*"PRIuMAX"%s",
2484 number_width, added + deleted,
2485 added + deleted ? " " : "");
2486 show_graph(&out, '+', add, add_c, reset);
2487 show_graph(&out, '-', del, del_c, reset);
2488 strbuf_addch(&out, '\n');
2489 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2490 out.buf, out.len, 0);
2491 strbuf_reset(&out);
2494 for (i = 0; i < data->nr; i++) {
2495 struct diffstat_file *file = data->files[i];
2496 uintmax_t added = file->added;
2497 uintmax_t deleted = file->deleted;
2499 if (file->is_unmerged ||
2500 (!file->is_interesting && (added + deleted == 0))) {
2501 total_files--;
2502 continue;
2505 if (!file->is_binary) {
2506 adds += added;
2507 dels += deleted;
2509 if (i < count)
2510 continue;
2511 if (!extra_shown)
2512 emit_diff_symbol(options,
2513 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2514 NULL, 0, 0);
2515 extra_shown = 1;
2518 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2519 strbuf_release(&out);
2522 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2524 int i, adds = 0, dels = 0, total_files = data->nr;
2526 if (data->nr == 0)
2527 return;
2529 for (i = 0; i < data->nr; i++) {
2530 int added = data->files[i]->added;
2531 int deleted = data->files[i]->deleted;
2533 if (data->files[i]->is_unmerged ||
2534 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2535 total_files--;
2536 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2537 adds += added;
2538 dels += deleted;
2541 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2544 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2546 int i;
2548 if (data->nr == 0)
2549 return;
2551 for (i = 0; i < data->nr; i++) {
2552 struct diffstat_file *file = data->files[i];
2554 fprintf(options->file, "%s", diff_line_prefix(options));
2556 if (file->is_binary)
2557 fprintf(options->file, "-\t-\t");
2558 else
2559 fprintf(options->file,
2560 "%"PRIuMAX"\t%"PRIuMAX"\t",
2561 file->added, file->deleted);
2562 if (options->line_termination) {
2563 fill_print_name(file);
2564 if (!file->is_renamed)
2565 write_name_quoted(file->name, options->file,
2566 options->line_termination);
2567 else {
2568 fputs(file->print_name, options->file);
2569 putc(options->line_termination, options->file);
2571 } else {
2572 if (file->is_renamed) {
2573 putc('\0', options->file);
2574 write_name_quoted(file->from_name, options->file, '\0');
2576 write_name_quoted(file->name, options->file, '\0');
2581 struct dirstat_file {
2582 const char *name;
2583 unsigned long changed;
2586 struct dirstat_dir {
2587 struct dirstat_file *files;
2588 int alloc, nr, permille, cumulative;
2591 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2592 unsigned long changed, const char *base, int baselen)
2594 unsigned long sum_changes = 0;
2595 unsigned int sources = 0;
2596 const char *line_prefix = diff_line_prefix(opt);
2598 while (dir->nr) {
2599 struct dirstat_file *f = dir->files;
2600 int namelen = strlen(f->name);
2601 unsigned long changes;
2602 char *slash;
2604 if (namelen < baselen)
2605 break;
2606 if (memcmp(f->name, base, baselen))
2607 break;
2608 slash = strchr(f->name + baselen, '/');
2609 if (slash) {
2610 int newbaselen = slash + 1 - f->name;
2611 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2612 sources++;
2613 } else {
2614 changes = f->changed;
2615 dir->files++;
2616 dir->nr--;
2617 sources += 2;
2619 sum_changes += changes;
2623 * We don't report dirstat's for
2624 * - the top level
2625 * - or cases where everything came from a single directory
2626 * under this directory (sources == 1).
2628 if (baselen && sources != 1) {
2629 if (sum_changes) {
2630 int permille = sum_changes * 1000 / changed;
2631 if (permille >= dir->permille) {
2632 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2633 permille / 10, permille % 10, baselen, base);
2634 if (!dir->cumulative)
2635 return 0;
2639 return sum_changes;
2642 static int dirstat_compare(const void *_a, const void *_b)
2644 const struct dirstat_file *a = _a;
2645 const struct dirstat_file *b = _b;
2646 return strcmp(a->name, b->name);
2649 static void show_dirstat(struct diff_options *options)
2651 int i;
2652 unsigned long changed;
2653 struct dirstat_dir dir;
2654 struct diff_queue_struct *q = &diff_queued_diff;
2656 dir.files = NULL;
2657 dir.alloc = 0;
2658 dir.nr = 0;
2659 dir.permille = options->dirstat_permille;
2660 dir.cumulative = options->flags.dirstat_cumulative;
2662 changed = 0;
2663 for (i = 0; i < q->nr; i++) {
2664 struct diff_filepair *p = q->queue[i];
2665 const char *name;
2666 unsigned long copied, added, damage;
2667 int content_changed;
2669 name = p->two->path ? p->two->path : p->one->path;
2671 if (p->one->oid_valid && p->two->oid_valid)
2672 content_changed = oidcmp(&p->one->oid, &p->two->oid);
2673 else
2674 content_changed = 1;
2676 if (!content_changed) {
2678 * The SHA1 has not changed, so pre-/post-content is
2679 * identical. We can therefore skip looking at the
2680 * file contents altogether.
2682 damage = 0;
2683 goto found_damage;
2686 if (options->flags.dirstat_by_file) {
2688 * In --dirstat-by-file mode, we don't really need to
2689 * look at the actual file contents at all.
2690 * The fact that the SHA1 changed is enough for us to
2691 * add this file to the list of results
2692 * (with each file contributing equal damage).
2694 damage = 1;
2695 goto found_damage;
2698 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2699 diff_populate_filespec(p->one, 0);
2700 diff_populate_filespec(p->two, 0);
2701 diffcore_count_changes(p->one, p->two, NULL, NULL,
2702 &copied, &added);
2703 diff_free_filespec_data(p->one);
2704 diff_free_filespec_data(p->two);
2705 } else if (DIFF_FILE_VALID(p->one)) {
2706 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2707 copied = added = 0;
2708 diff_free_filespec_data(p->one);
2709 } else if (DIFF_FILE_VALID(p->two)) {
2710 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
2711 copied = 0;
2712 added = p->two->size;
2713 diff_free_filespec_data(p->two);
2714 } else
2715 continue;
2718 * Original minus copied is the removed material,
2719 * added is the new material. They are both damages
2720 * made to the preimage.
2721 * If the resulting damage is zero, we know that
2722 * diffcore_count_changes() considers the two entries to
2723 * be identical, but since content_changed is true, we
2724 * know that there must have been _some_ kind of change,
2725 * so we force all entries to have damage > 0.
2727 damage = (p->one->size - copied) + added;
2728 if (!damage)
2729 damage = 1;
2731 found_damage:
2732 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2733 dir.files[dir.nr].name = name;
2734 dir.files[dir.nr].changed = damage;
2735 changed += damage;
2736 dir.nr++;
2739 /* This can happen even with many files, if everything was renames */
2740 if (!changed)
2741 return;
2743 /* Show all directories with more than x% of the changes */
2744 QSORT(dir.files, dir.nr, dirstat_compare);
2745 gather_dirstat(options, &dir, changed, "", 0);
2748 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2750 int i;
2751 unsigned long changed;
2752 struct dirstat_dir dir;
2754 if (data->nr == 0)
2755 return;
2757 dir.files = NULL;
2758 dir.alloc = 0;
2759 dir.nr = 0;
2760 dir.permille = options->dirstat_permille;
2761 dir.cumulative = options->flags.dirstat_cumulative;
2763 changed = 0;
2764 for (i = 0; i < data->nr; i++) {
2765 struct diffstat_file *file = data->files[i];
2766 unsigned long damage = file->added + file->deleted;
2767 if (file->is_binary)
2769 * binary files counts bytes, not lines. Must find some
2770 * way to normalize binary bytes vs. textual lines.
2771 * The following heuristic assumes that there are 64
2772 * bytes per "line".
2773 * This is stupid and ugly, but very cheap...
2775 damage = DIV_ROUND_UP(damage, 64);
2776 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2777 dir.files[dir.nr].name = file->name;
2778 dir.files[dir.nr].changed = damage;
2779 changed += damage;
2780 dir.nr++;
2783 /* This can happen even with many files, if everything was renames */
2784 if (!changed)
2785 return;
2787 /* Show all directories with more than x% of the changes */
2788 QSORT(dir.files, dir.nr, dirstat_compare);
2789 gather_dirstat(options, &dir, changed, "", 0);
2792 static void free_diffstat_info(struct diffstat_t *diffstat)
2794 int i;
2795 for (i = 0; i < diffstat->nr; i++) {
2796 struct diffstat_file *f = diffstat->files[i];
2797 free(f->print_name);
2798 free(f->name);
2799 free(f->from_name);
2800 free(f);
2802 free(diffstat->files);
2805 struct checkdiff_t {
2806 const char *filename;
2807 int lineno;
2808 int conflict_marker_size;
2809 struct diff_options *o;
2810 unsigned ws_rule;
2811 unsigned status;
2814 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2816 char firstchar;
2817 int cnt;
2819 if (len < marker_size + 1)
2820 return 0;
2821 firstchar = line[0];
2822 switch (firstchar) {
2823 case '=': case '>': case '<': case '|':
2824 break;
2825 default:
2826 return 0;
2828 for (cnt = 1; cnt < marker_size; cnt++)
2829 if (line[cnt] != firstchar)
2830 return 0;
2831 /* line[1] thru line[marker_size-1] are same as firstchar */
2832 if (len < marker_size + 1 || !isspace(line[marker_size]))
2833 return 0;
2834 return 1;
2837 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2839 struct checkdiff_t *data = priv;
2840 int marker_size = data->conflict_marker_size;
2841 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2842 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2843 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2844 char *err;
2845 const char *line_prefix;
2847 assert(data->o);
2848 line_prefix = diff_line_prefix(data->o);
2850 if (line[0] == '+') {
2851 unsigned bad;
2852 data->lineno++;
2853 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2854 data->status |= 1;
2855 fprintf(data->o->file,
2856 "%s%s:%d: leftover conflict marker\n",
2857 line_prefix, data->filename, data->lineno);
2859 bad = ws_check(line + 1, len - 1, data->ws_rule);
2860 if (!bad)
2861 return;
2862 data->status |= bad;
2863 err = whitespace_error_string(bad);
2864 fprintf(data->o->file, "%s%s:%d: %s.\n",
2865 line_prefix, data->filename, data->lineno, err);
2866 free(err);
2867 emit_line(data->o, set, reset, line, 1);
2868 ws_check_emit(line + 1, len - 1, data->ws_rule,
2869 data->o->file, set, reset, ws);
2870 } else if (line[0] == ' ') {
2871 data->lineno++;
2872 } else if (line[0] == '@') {
2873 char *plus = strchr(line, '+');
2874 if (plus)
2875 data->lineno = strtol(plus, NULL, 10) - 1;
2876 else
2877 die("invalid diff");
2881 static unsigned char *deflate_it(char *data,
2882 unsigned long size,
2883 unsigned long *result_size)
2885 int bound;
2886 unsigned char *deflated;
2887 git_zstream stream;
2889 git_deflate_init(&stream, zlib_compression_level);
2890 bound = git_deflate_bound(&stream, size);
2891 deflated = xmalloc(bound);
2892 stream.next_out = deflated;
2893 stream.avail_out = bound;
2895 stream.next_in = (unsigned char *)data;
2896 stream.avail_in = size;
2897 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2898 ; /* nothing */
2899 git_deflate_end(&stream);
2900 *result_size = stream.total_out;
2901 return deflated;
2904 static void emit_binary_diff_body(struct diff_options *o,
2905 mmfile_t *one, mmfile_t *two)
2907 void *cp;
2908 void *delta;
2909 void *deflated;
2910 void *data;
2911 unsigned long orig_size;
2912 unsigned long delta_size;
2913 unsigned long deflate_size;
2914 unsigned long data_size;
2916 /* We could do deflated delta, or we could do just deflated two,
2917 * whichever is smaller.
2919 delta = NULL;
2920 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2921 if (one->size && two->size) {
2922 delta = diff_delta(one->ptr, one->size,
2923 two->ptr, two->size,
2924 &delta_size, deflate_size);
2925 if (delta) {
2926 void *to_free = delta;
2927 orig_size = delta_size;
2928 delta = deflate_it(delta, delta_size, &delta_size);
2929 free(to_free);
2933 if (delta && delta_size < deflate_size) {
2934 char *s = xstrfmt("%lu", orig_size);
2935 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
2936 s, strlen(s), 0);
2937 free(s);
2938 free(deflated);
2939 data = delta;
2940 data_size = delta_size;
2941 } else {
2942 char *s = xstrfmt("%lu", two->size);
2943 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
2944 s, strlen(s), 0);
2945 free(s);
2946 free(delta);
2947 data = deflated;
2948 data_size = deflate_size;
2951 /* emit data encoded in base85 */
2952 cp = data;
2953 while (data_size) {
2954 int len;
2955 int bytes = (52 < data_size) ? 52 : data_size;
2956 char line[71];
2957 data_size -= bytes;
2958 if (bytes <= 26)
2959 line[0] = bytes + 'A' - 1;
2960 else
2961 line[0] = bytes - 26 + 'a' - 1;
2962 encode_85(line + 1, cp, bytes);
2963 cp = (char *) cp + bytes;
2965 len = strlen(line);
2966 line[len++] = '\n';
2967 line[len] = '\0';
2969 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
2970 line, len, 0);
2972 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
2973 free(data);
2976 static void emit_binary_diff(struct diff_options *o,
2977 mmfile_t *one, mmfile_t *two)
2979 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
2980 emit_binary_diff_body(o, one, two);
2981 emit_binary_diff_body(o, two, one);
2984 int diff_filespec_is_binary(struct diff_filespec *one)
2986 if (one->is_binary == -1) {
2987 diff_filespec_load_driver(one);
2988 if (one->driver->binary != -1)
2989 one->is_binary = one->driver->binary;
2990 else {
2991 if (!one->data && DIFF_FILE_VALID(one))
2992 diff_populate_filespec(one, CHECK_BINARY);
2993 if (one->is_binary == -1 && one->data)
2994 one->is_binary = buffer_is_binary(one->data,
2995 one->size);
2996 if (one->is_binary == -1)
2997 one->is_binary = 0;
3000 return one->is_binary;
3003 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
3005 diff_filespec_load_driver(one);
3006 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3009 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3011 if (!options->a_prefix)
3012 options->a_prefix = a;
3013 if (!options->b_prefix)
3014 options->b_prefix = b;
3017 struct userdiff_driver *get_textconv(struct diff_filespec *one)
3019 if (!DIFF_FILE_VALID(one))
3020 return NULL;
3022 diff_filespec_load_driver(one);
3023 return userdiff_get_textconv(one->driver);
3026 static void builtin_diff(const char *name_a,
3027 const char *name_b,
3028 struct diff_filespec *one,
3029 struct diff_filespec *two,
3030 const char *xfrm_msg,
3031 int must_show_header,
3032 struct diff_options *o,
3033 int complete_rewrite)
3035 mmfile_t mf1, mf2;
3036 const char *lbl[2];
3037 char *a_one, *b_two;
3038 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3039 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3040 const char *a_prefix, *b_prefix;
3041 struct userdiff_driver *textconv_one = NULL;
3042 struct userdiff_driver *textconv_two = NULL;
3043 struct strbuf header = STRBUF_INIT;
3044 const char *line_prefix = diff_line_prefix(o);
3046 diff_set_mnemonic_prefix(o, "a/", "b/");
3047 if (o->flags.reverse_diff) {
3048 a_prefix = o->b_prefix;
3049 b_prefix = o->a_prefix;
3050 } else {
3051 a_prefix = o->a_prefix;
3052 b_prefix = o->b_prefix;
3055 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3056 (!one->mode || S_ISGITLINK(one->mode)) &&
3057 (!two->mode || S_ISGITLINK(two->mode))) {
3058 show_submodule_summary(o, one->path ? one->path : two->path,
3059 &one->oid, &two->oid,
3060 two->dirty_submodule);
3061 return;
3062 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3063 (!one->mode || S_ISGITLINK(one->mode)) &&
3064 (!two->mode || S_ISGITLINK(two->mode))) {
3065 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3066 &one->oid, &two->oid,
3067 two->dirty_submodule);
3068 return;
3071 if (o->flags.allow_textconv) {
3072 textconv_one = get_textconv(one);
3073 textconv_two = get_textconv(two);
3076 /* Never use a non-valid filename anywhere if at all possible */
3077 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3078 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3080 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3081 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3082 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3083 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3084 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3085 if (lbl[0][0] == '/') {
3086 /* /dev/null */
3087 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3088 if (xfrm_msg)
3089 strbuf_addstr(&header, xfrm_msg);
3090 must_show_header = 1;
3092 else if (lbl[1][0] == '/') {
3093 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3094 if (xfrm_msg)
3095 strbuf_addstr(&header, xfrm_msg);
3096 must_show_header = 1;
3098 else {
3099 if (one->mode != two->mode) {
3100 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3101 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3102 must_show_header = 1;
3104 if (xfrm_msg)
3105 strbuf_addstr(&header, xfrm_msg);
3108 * we do not run diff between different kind
3109 * of objects.
3111 if ((one->mode ^ two->mode) & S_IFMT)
3112 goto free_ab_and_return;
3113 if (complete_rewrite &&
3114 (textconv_one || !diff_filespec_is_binary(one)) &&
3115 (textconv_two || !diff_filespec_is_binary(two))) {
3116 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3117 header.buf, header.len, 0);
3118 strbuf_reset(&header);
3119 emit_rewrite_diff(name_a, name_b, one, two,
3120 textconv_one, textconv_two, o);
3121 o->found_changes = 1;
3122 goto free_ab_and_return;
3126 if (o->irreversible_delete && lbl[1][0] == '/') {
3127 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3128 header.len, 0);
3129 strbuf_reset(&header);
3130 goto free_ab_and_return;
3131 } else if (!o->flags.text &&
3132 ( (!textconv_one && diff_filespec_is_binary(one)) ||
3133 (!textconv_two && diff_filespec_is_binary(two)) )) {
3134 struct strbuf sb = STRBUF_INIT;
3135 if (!one->data && !two->data &&
3136 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3137 !o->flags.binary) {
3138 if (!oidcmp(&one->oid, &two->oid)) {
3139 if (must_show_header)
3140 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3141 header.buf, header.len,
3143 goto free_ab_and_return;
3145 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3146 header.buf, header.len, 0);
3147 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3148 diff_line_prefix(o), lbl[0], lbl[1]);
3149 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3150 sb.buf, sb.len, 0);
3151 strbuf_release(&sb);
3152 goto free_ab_and_return;
3154 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3155 die("unable to read files to diff");
3156 /* Quite common confusing case */
3157 if (mf1.size == mf2.size &&
3158 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3159 if (must_show_header)
3160 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3161 header.buf, header.len, 0);
3162 goto free_ab_and_return;
3164 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3165 strbuf_reset(&header);
3166 if (o->flags.binary)
3167 emit_binary_diff(o, &mf1, &mf2);
3168 else {
3169 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3170 diff_line_prefix(o), lbl[0], lbl[1]);
3171 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3172 sb.buf, sb.len, 0);
3173 strbuf_release(&sb);
3175 o->found_changes = 1;
3176 } else {
3177 /* Crazy xdl interfaces.. */
3178 const char *diffopts = getenv("GIT_DIFF_OPTS");
3179 const char *v;
3180 xpparam_t xpp;
3181 xdemitconf_t xecfg;
3182 struct emit_callback ecbdata;
3183 const struct userdiff_funcname *pe;
3185 if (must_show_header) {
3186 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3187 header.buf, header.len, 0);
3188 strbuf_reset(&header);
3191 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
3192 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
3194 pe = diff_funcname_pattern(one);
3195 if (!pe)
3196 pe = diff_funcname_pattern(two);
3198 memset(&xpp, 0, sizeof(xpp));
3199 memset(&xecfg, 0, sizeof(xecfg));
3200 memset(&ecbdata, 0, sizeof(ecbdata));
3201 ecbdata.label_path = lbl;
3202 ecbdata.color_diff = want_color(o->use_color);
3203 ecbdata.ws_rule = whitespace_rule(name_b);
3204 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3205 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3206 ecbdata.opt = o;
3207 ecbdata.header = header.len ? &header : NULL;
3208 xpp.flags = o->xdl_opts;
3209 xpp.anchors = o->anchors;
3210 xpp.anchors_nr = o->anchors_nr;
3211 xecfg.ctxlen = o->context;
3212 xecfg.interhunkctxlen = o->interhunkcontext;
3213 xecfg.flags = XDL_EMIT_FUNCNAMES;
3214 if (o->flags.funccontext)
3215 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3216 if (pe)
3217 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3218 if (!diffopts)
3220 else if (skip_prefix(diffopts, "--unified=", &v))
3221 xecfg.ctxlen = strtoul(v, NULL, 10);
3222 else if (skip_prefix(diffopts, "-u", &v))
3223 xecfg.ctxlen = strtoul(v, NULL, 10);
3224 if (o->word_diff)
3225 init_diff_words_data(&ecbdata, o, one, two);
3226 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
3227 &xpp, &xecfg))
3228 die("unable to generate diff for %s", one->path);
3229 if (o->word_diff)
3230 free_diff_words_data(&ecbdata);
3231 if (textconv_one)
3232 free(mf1.ptr);
3233 if (textconv_two)
3234 free(mf2.ptr);
3235 xdiff_clear_find_func(&xecfg);
3238 free_ab_and_return:
3239 strbuf_release(&header);
3240 diff_free_filespec_data(one);
3241 diff_free_filespec_data(two);
3242 free(a_one);
3243 free(b_two);
3244 return;
3247 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3249 if (!is_renamed) {
3250 if (p->status == DIFF_STATUS_ADDED) {
3251 if (S_ISLNK(p->two->mode))
3252 return "new +l";
3253 else if ((p->two->mode & 0777) == 0755)
3254 return "new +x";
3255 else
3256 return "new";
3257 } else if (p->status == DIFF_STATUS_DELETED)
3258 return "gone";
3260 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3261 return "mode -l";
3262 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3263 return "mode +l";
3264 else if ((p->one->mode & 0777) == 0644 &&
3265 (p->two->mode & 0777) == 0755)
3266 return "mode +x";
3267 else if ((p->one->mode & 0777) == 0755 &&
3268 (p->two->mode & 0777) == 0644)
3269 return "mode -x";
3270 return NULL;
3273 static void builtin_diffstat(const char *name_a, const char *name_b,
3274 struct diff_filespec *one,
3275 struct diff_filespec *two,
3276 struct diffstat_t *diffstat,
3277 struct diff_options *o,
3278 struct diff_filepair *p)
3280 mmfile_t mf1, mf2;
3281 struct diffstat_file *data;
3282 int same_contents;
3283 int complete_rewrite = 0;
3285 if (!DIFF_PAIR_UNMERGED(p)) {
3286 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3287 complete_rewrite = 1;
3290 data = diffstat_add(diffstat, name_a, name_b);
3291 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3292 if (o->flags.stat_with_summary)
3293 data->comments = get_compact_summary(p, data->is_renamed);
3295 if (!one || !two) {
3296 data->is_unmerged = 1;
3297 return;
3300 same_contents = !oidcmp(&one->oid, &two->oid);
3302 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
3303 data->is_binary = 1;
3304 if (same_contents) {
3305 data->added = 0;
3306 data->deleted = 0;
3307 } else {
3308 data->added = diff_filespec_size(two);
3309 data->deleted = diff_filespec_size(one);
3313 else if (complete_rewrite) {
3314 diff_populate_filespec(one, 0);
3315 diff_populate_filespec(two, 0);
3316 data->deleted = count_lines(one->data, one->size);
3317 data->added = count_lines(two->data, two->size);
3320 else if (!same_contents) {
3321 /* Crazy xdl interfaces.. */
3322 xpparam_t xpp;
3323 xdemitconf_t xecfg;
3325 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3326 die("unable to read files to diff");
3328 memset(&xpp, 0, sizeof(xpp));
3329 memset(&xecfg, 0, sizeof(xecfg));
3330 xpp.flags = o->xdl_opts;
3331 xpp.anchors = o->anchors;
3332 xpp.anchors_nr = o->anchors_nr;
3333 xecfg.ctxlen = o->context;
3334 xecfg.interhunkctxlen = o->interhunkcontext;
3335 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
3336 &xpp, &xecfg))
3337 die("unable to generate diffstat for %s", one->path);
3340 diff_free_filespec_data(one);
3341 diff_free_filespec_data(two);
3344 static void builtin_checkdiff(const char *name_a, const char *name_b,
3345 const char *attr_path,
3346 struct diff_filespec *one,
3347 struct diff_filespec *two,
3348 struct diff_options *o)
3350 mmfile_t mf1, mf2;
3351 struct checkdiff_t data;
3353 if (!two)
3354 return;
3356 memset(&data, 0, sizeof(data));
3357 data.filename = name_b ? name_b : name_a;
3358 data.lineno = 0;
3359 data.o = o;
3360 data.ws_rule = whitespace_rule(attr_path);
3361 data.conflict_marker_size = ll_merge_marker_size(attr_path);
3363 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3364 die("unable to read files to diff");
3367 * All the other codepaths check both sides, but not checking
3368 * the "old" side here is deliberate. We are checking the newly
3369 * introduced changes, and as long as the "new" side is text, we
3370 * can and should check what it introduces.
3372 if (diff_filespec_is_binary(two))
3373 goto free_and_return;
3374 else {
3375 /* Crazy xdl interfaces.. */
3376 xpparam_t xpp;
3377 xdemitconf_t xecfg;
3379 memset(&xpp, 0, sizeof(xpp));
3380 memset(&xecfg, 0, sizeof(xecfg));
3381 xecfg.ctxlen = 1; /* at least one context line */
3382 xpp.flags = 0;
3383 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
3384 &xpp, &xecfg))
3385 die("unable to generate checkdiff for %s", one->path);
3387 if (data.ws_rule & WS_BLANK_AT_EOF) {
3388 struct emit_callback ecbdata;
3389 int blank_at_eof;
3391 ecbdata.ws_rule = data.ws_rule;
3392 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3393 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3395 if (blank_at_eof) {
3396 static char *err;
3397 if (!err)
3398 err = whitespace_error_string(WS_BLANK_AT_EOF);
3399 fprintf(o->file, "%s:%d: %s.\n",
3400 data.filename, blank_at_eof, err);
3401 data.status = 1; /* report errors */
3405 free_and_return:
3406 diff_free_filespec_data(one);
3407 diff_free_filespec_data(two);
3408 if (data.status)
3409 o->flags.check_failed = 1;
3412 struct diff_filespec *alloc_filespec(const char *path)
3414 struct diff_filespec *spec;
3416 FLEXPTR_ALLOC_STR(spec, path, path);
3417 spec->count = 1;
3418 spec->is_binary = -1;
3419 return spec;
3422 void free_filespec(struct diff_filespec *spec)
3424 if (!--spec->count) {
3425 diff_free_filespec_data(spec);
3426 free(spec);
3430 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3431 int oid_valid, unsigned short mode)
3433 if (mode) {
3434 spec->mode = canon_mode(mode);
3435 oidcpy(&spec->oid, oid);
3436 spec->oid_valid = oid_valid;
3441 * Given a name and sha1 pair, if the index tells us the file in
3442 * the work tree has that object contents, return true, so that
3443 * prepare_temp_file() does not have to inflate and extract.
3445 static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
3447 const struct cache_entry *ce;
3448 struct stat st;
3449 int pos, len;
3452 * We do not read the cache ourselves here, because the
3453 * benchmark with my previous version that always reads cache
3454 * shows that it makes things worse for diff-tree comparing
3455 * two linux-2.6 kernel trees in an already checked out work
3456 * tree. This is because most diff-tree comparisons deal with
3457 * only a small number of files, while reading the cache is
3458 * expensive for a large project, and its cost outweighs the
3459 * savings we get by not inflating the object to a temporary
3460 * file. Practically, this code only helps when we are used
3461 * by diff-cache --cached, which does read the cache before
3462 * calling us.
3464 if (!active_cache)
3465 return 0;
3467 /* We want to avoid the working directory if our caller
3468 * doesn't need the data in a normal file, this system
3469 * is rather slow with its stat/open/mmap/close syscalls,
3470 * and the object is contained in a pack file. The pack
3471 * is probably already open and will be faster to obtain
3472 * the data through than the working directory. Loose
3473 * objects however would tend to be slower as they need
3474 * to be individually opened and inflated.
3476 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
3477 return 0;
3480 * Similarly, if we'd have to convert the file contents anyway, that
3481 * makes the optimization not worthwhile.
3483 if (!want_file && would_convert_to_git(&the_index, name))
3484 return 0;
3486 len = strlen(name);
3487 pos = cache_name_pos(name, len);
3488 if (pos < 0)
3489 return 0;
3490 ce = active_cache[pos];
3493 * This is not the sha1 we are looking for, or
3494 * unreusable because it is not a regular file.
3496 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3497 return 0;
3500 * If ce is marked as "assume unchanged", there is no
3501 * guarantee that work tree matches what we are looking for.
3503 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3504 return 0;
3507 * If ce matches the file in the work tree, we can reuse it.
3509 if (ce_uptodate(ce) ||
3510 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3511 return 1;
3513 return 0;
3516 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3518 struct strbuf buf = STRBUF_INIT;
3519 char *dirty = "";
3521 /* Are we looking at the work tree? */
3522 if (s->dirty_submodule)
3523 dirty = "-dirty";
3525 strbuf_addf(&buf, "Subproject commit %s%s\n",
3526 oid_to_hex(&s->oid), dirty);
3527 s->size = buf.len;
3528 if (size_only) {
3529 s->data = NULL;
3530 strbuf_release(&buf);
3531 } else {
3532 s->data = strbuf_detach(&buf, NULL);
3533 s->should_free = 1;
3535 return 0;
3539 * While doing rename detection and pickaxe operation, we may need to
3540 * grab the data for the blob (or file) for our own in-core comparison.
3541 * diff_filespec has data and size fields for this purpose.
3543 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
3545 int size_only = flags & CHECK_SIZE_ONLY;
3546 int err = 0;
3547 int conv_flags = global_conv_flags_eol;
3549 * demote FAIL to WARN to allow inspecting the situation
3550 * instead of refusing.
3552 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3553 conv_flags = CONV_EOL_RNDTRP_WARN;
3555 if (!DIFF_FILE_VALID(s))
3556 die("internal error: asking to populate invalid file.");
3557 if (S_ISDIR(s->mode))
3558 return -1;
3560 if (s->data)
3561 return 0;
3563 if (size_only && 0 < s->size)
3564 return 0;
3566 if (S_ISGITLINK(s->mode))
3567 return diff_populate_gitlink(s, size_only);
3569 if (!s->oid_valid ||
3570 reuse_worktree_file(s->path, &s->oid, 0)) {
3571 struct strbuf buf = STRBUF_INIT;
3572 struct stat st;
3573 int fd;
3575 if (lstat(s->path, &st) < 0) {
3576 err_empty:
3577 err = -1;
3578 empty:
3579 s->data = (char *)"";
3580 s->size = 0;
3581 return err;
3583 s->size = xsize_t(st.st_size);
3584 if (!s->size)
3585 goto empty;
3586 if (S_ISLNK(st.st_mode)) {
3587 struct strbuf sb = STRBUF_INIT;
3589 if (strbuf_readlink(&sb, s->path, s->size))
3590 goto err_empty;
3591 s->size = sb.len;
3592 s->data = strbuf_detach(&sb, NULL);
3593 s->should_free = 1;
3594 return 0;
3598 * Even if the caller would be happy with getting
3599 * only the size, we cannot return early at this
3600 * point if the path requires us to run the content
3601 * conversion.
3603 if (size_only && !would_convert_to_git(&the_index, s->path))
3604 return 0;
3607 * Note: this check uses xsize_t(st.st_size) that may
3608 * not be the true size of the blob after it goes
3609 * through convert_to_git(). This may not strictly be
3610 * correct, but the whole point of big_file_threshold
3611 * and is_binary check being that we want to avoid
3612 * opening the file and inspecting the contents, this
3613 * is probably fine.
3615 if ((flags & CHECK_BINARY) &&
3616 s->size > big_file_threshold && s->is_binary == -1) {
3617 s->is_binary = 1;
3618 return 0;
3620 fd = open(s->path, O_RDONLY);
3621 if (fd < 0)
3622 goto err_empty;
3623 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3624 close(fd);
3625 s->should_munmap = 1;
3628 * Convert from working tree format to canonical git format
3630 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, conv_flags)) {
3631 size_t size = 0;
3632 munmap(s->data, s->size);
3633 s->should_munmap = 0;
3634 s->data = strbuf_detach(&buf, &size);
3635 s->size = size;
3636 s->should_free = 1;
3639 else {
3640 enum object_type type;
3641 if (size_only || (flags & CHECK_BINARY)) {
3642 type = oid_object_info(the_repository, &s->oid,
3643 &s->size);
3644 if (type < 0)
3645 die("unable to read %s",
3646 oid_to_hex(&s->oid));
3647 if (size_only)
3648 return 0;
3649 if (s->size > big_file_threshold && s->is_binary == -1) {
3650 s->is_binary = 1;
3651 return 0;
3654 s->data = read_object_file(&s->oid, &type, &s->size);
3655 if (!s->data)
3656 die("unable to read %s", oid_to_hex(&s->oid));
3657 s->should_free = 1;
3659 return 0;
3662 void diff_free_filespec_blob(struct diff_filespec *s)
3664 if (s->should_free)
3665 free(s->data);
3666 else if (s->should_munmap)
3667 munmap(s->data, s->size);
3669 if (s->should_free || s->should_munmap) {
3670 s->should_free = s->should_munmap = 0;
3671 s->data = NULL;
3675 void diff_free_filespec_data(struct diff_filespec *s)
3677 diff_free_filespec_blob(s);
3678 FREE_AND_NULL(s->cnt_data);
3681 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
3682 void *blob,
3683 unsigned long size,
3684 const struct object_id *oid,
3685 int mode)
3687 struct strbuf buf = STRBUF_INIT;
3688 struct strbuf tempfile = STRBUF_INIT;
3689 char *path_dup = xstrdup(path);
3690 const char *base = basename(path_dup);
3692 /* Generate "XXXXXX_basename.ext" */
3693 strbuf_addstr(&tempfile, "XXXXXX_");
3694 strbuf_addstr(&tempfile, base);
3696 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
3697 if (!temp->tempfile)
3698 die_errno("unable to create temp-file");
3699 if (convert_to_working_tree(path,
3700 (const char *)blob, (size_t)size, &buf)) {
3701 blob = buf.buf;
3702 size = buf.len;
3704 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
3705 close_tempfile_gently(temp->tempfile))
3706 die_errno("unable to write temp-file");
3707 temp->name = get_tempfile_path(temp->tempfile);
3708 oid_to_hex_r(temp->hex, oid);
3709 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
3710 strbuf_release(&buf);
3711 strbuf_release(&tempfile);
3712 free(path_dup);
3715 static struct diff_tempfile *prepare_temp_file(const char *name,
3716 struct diff_filespec *one)
3718 struct diff_tempfile *temp = claim_diff_tempfile();
3720 if (!DIFF_FILE_VALID(one)) {
3721 not_a_valid_file:
3722 /* A '-' entry produces this for file-2, and
3723 * a '+' entry produces this for file-1.
3725 temp->name = "/dev/null";
3726 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3727 xsnprintf(temp->mode, sizeof(temp->mode), ".");
3728 return temp;
3731 if (!S_ISGITLINK(one->mode) &&
3732 (!one->oid_valid ||
3733 reuse_worktree_file(name, &one->oid, 1))) {
3734 struct stat st;
3735 if (lstat(name, &st) < 0) {
3736 if (errno == ENOENT)
3737 goto not_a_valid_file;
3738 die_errno("stat(%s)", name);
3740 if (S_ISLNK(st.st_mode)) {
3741 struct strbuf sb = STRBUF_INIT;
3742 if (strbuf_readlink(&sb, name, st.st_size) < 0)
3743 die_errno("readlink(%s)", name);
3744 prep_temp_blob(name, temp, sb.buf, sb.len,
3745 (one->oid_valid ?
3746 &one->oid : &null_oid),
3747 (one->oid_valid ?
3748 one->mode : S_IFLNK));
3749 strbuf_release(&sb);
3751 else {
3752 /* we can borrow from the file in the work tree */
3753 temp->name = name;
3754 if (!one->oid_valid)
3755 oid_to_hex_r(temp->hex, &null_oid);
3756 else
3757 oid_to_hex_r(temp->hex, &one->oid);
3758 /* Even though we may sometimes borrow the
3759 * contents from the work tree, we always want
3760 * one->mode. mode is trustworthy even when
3761 * !(one->oid_valid), as long as
3762 * DIFF_FILE_VALID(one).
3764 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
3766 return temp;
3768 else {
3769 if (diff_populate_filespec(one, 0))
3770 die("cannot read data blob for %s", one->path);
3771 prep_temp_blob(name, temp, one->data, one->size,
3772 &one->oid, one->mode);
3774 return temp;
3777 static void add_external_diff_name(struct argv_array *argv,
3778 const char *name,
3779 struct diff_filespec *df)
3781 struct diff_tempfile *temp = prepare_temp_file(name, df);
3782 argv_array_push(argv, temp->name);
3783 argv_array_push(argv, temp->hex);
3784 argv_array_push(argv, temp->mode);
3787 /* An external diff command takes:
3789 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3790 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3793 static void run_external_diff(const char *pgm,
3794 const char *name,
3795 const char *other,
3796 struct diff_filespec *one,
3797 struct diff_filespec *two,
3798 const char *xfrm_msg,
3799 int complete_rewrite,
3800 struct diff_options *o)
3802 struct argv_array argv = ARGV_ARRAY_INIT;
3803 struct argv_array env = ARGV_ARRAY_INIT;
3804 struct diff_queue_struct *q = &diff_queued_diff;
3806 argv_array_push(&argv, pgm);
3807 argv_array_push(&argv, name);
3809 if (one && two) {
3810 add_external_diff_name(&argv, name, one);
3811 if (!other)
3812 add_external_diff_name(&argv, name, two);
3813 else {
3814 add_external_diff_name(&argv, other, two);
3815 argv_array_push(&argv, other);
3816 argv_array_push(&argv, xfrm_msg);
3820 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3821 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3823 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3824 die(_("external diff died, stopping at %s"), name);
3826 remove_tempfile();
3827 argv_array_clear(&argv);
3828 argv_array_clear(&env);
3831 static int similarity_index(struct diff_filepair *p)
3833 return p->score * 100 / MAX_SCORE;
3836 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3838 if (startup_info->have_repository)
3839 return find_unique_abbrev(oid, abbrev);
3840 else {
3841 char *hex = oid_to_hex(oid);
3842 if (abbrev < 0)
3843 abbrev = FALLBACK_DEFAULT_ABBREV;
3844 if (abbrev > GIT_SHA1_HEXSZ)
3845 die("BUG: oid abbreviation out of range: %d", abbrev);
3846 if (abbrev)
3847 hex[abbrev] = '\0';
3848 return hex;
3852 static void fill_metainfo(struct strbuf *msg,
3853 const char *name,
3854 const char *other,
3855 struct diff_filespec *one,
3856 struct diff_filespec *two,
3857 struct diff_options *o,
3858 struct diff_filepair *p,
3859 int *must_show_header,
3860 int use_color)
3862 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3863 const char *reset = diff_get_color(use_color, DIFF_RESET);
3864 const char *line_prefix = diff_line_prefix(o);
3866 *must_show_header = 1;
3867 strbuf_init(msg, PATH_MAX * 2 + 300);
3868 switch (p->status) {
3869 case DIFF_STATUS_COPIED:
3870 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3871 line_prefix, set, similarity_index(p));
3872 strbuf_addf(msg, "%s\n%s%scopy from ",
3873 reset, line_prefix, set);
3874 quote_c_style(name, msg, NULL, 0);
3875 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3876 quote_c_style(other, msg, NULL, 0);
3877 strbuf_addf(msg, "%s\n", reset);
3878 break;
3879 case DIFF_STATUS_RENAMED:
3880 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3881 line_prefix, set, similarity_index(p));
3882 strbuf_addf(msg, "%s\n%s%srename from ",
3883 reset, line_prefix, set);
3884 quote_c_style(name, msg, NULL, 0);
3885 strbuf_addf(msg, "%s\n%s%srename to ",
3886 reset, line_prefix, set);
3887 quote_c_style(other, msg, NULL, 0);
3888 strbuf_addf(msg, "%s\n", reset);
3889 break;
3890 case DIFF_STATUS_MODIFIED:
3891 if (p->score) {
3892 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3893 line_prefix,
3894 set, similarity_index(p), reset);
3895 break;
3897 /* fallthru */
3898 default:
3899 *must_show_header = 0;
3901 if (one && two && oidcmp(&one->oid, &two->oid)) {
3902 int abbrev = o->flags.full_index ? 40 : DEFAULT_ABBREV;
3904 if (o->flags.binary) {
3905 mmfile_t mf;
3906 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3907 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3908 abbrev = 40;
3910 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3911 diff_abbrev_oid(&one->oid, abbrev),
3912 diff_abbrev_oid(&two->oid, abbrev));
3913 if (one->mode == two->mode)
3914 strbuf_addf(msg, " %06o", one->mode);
3915 strbuf_addf(msg, "%s\n", reset);
3919 static void run_diff_cmd(const char *pgm,
3920 const char *name,
3921 const char *other,
3922 const char *attr_path,
3923 struct diff_filespec *one,
3924 struct diff_filespec *two,
3925 struct strbuf *msg,
3926 struct diff_options *o,
3927 struct diff_filepair *p)
3929 const char *xfrm_msg = NULL;
3930 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3931 int must_show_header = 0;
3934 if (o->flags.allow_external) {
3935 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3936 if (drv && drv->external)
3937 pgm = drv->external;
3940 if (msg) {
3942 * don't use colors when the header is intended for an
3943 * external diff driver
3945 fill_metainfo(msg, name, other, one, two, o, p,
3946 &must_show_header,
3947 want_color(o->use_color) && !pgm);
3948 xfrm_msg = msg->len ? msg->buf : NULL;
3951 if (pgm) {
3952 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3953 complete_rewrite, o);
3954 return;
3956 if (one && two)
3957 builtin_diff(name, other ? other : name,
3958 one, two, xfrm_msg, must_show_header,
3959 o, complete_rewrite);
3960 else
3961 fprintf(o->file, "* Unmerged path %s\n", name);
3964 static void diff_fill_oid_info(struct diff_filespec *one)
3966 if (DIFF_FILE_VALID(one)) {
3967 if (!one->oid_valid) {
3968 struct stat st;
3969 if (one->is_stdin) {
3970 oidclr(&one->oid);
3971 return;
3973 if (lstat(one->path, &st) < 0)
3974 die_errno("stat '%s'", one->path);
3975 if (index_path(&one->oid, one->path, &st, 0))
3976 die("cannot hash %s", one->path);
3979 else
3980 oidclr(&one->oid);
3983 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3985 /* Strip the prefix but do not molest /dev/null and absolute paths */
3986 if (*namep && **namep != '/') {
3987 *namep += prefix_length;
3988 if (**namep == '/')
3989 ++*namep;
3991 if (*otherp && **otherp != '/') {
3992 *otherp += prefix_length;
3993 if (**otherp == '/')
3994 ++*otherp;
3998 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4000 const char *pgm = external_diff();
4001 struct strbuf msg;
4002 struct diff_filespec *one = p->one;
4003 struct diff_filespec *two = p->two;
4004 const char *name;
4005 const char *other;
4006 const char *attr_path;
4008 name = one->path;
4009 other = (strcmp(name, two->path) ? two->path : NULL);
4010 attr_path = name;
4011 if (o->prefix_length)
4012 strip_prefix(o->prefix_length, &name, &other);
4014 if (!o->flags.allow_external)
4015 pgm = NULL;
4017 if (DIFF_PAIR_UNMERGED(p)) {
4018 run_diff_cmd(pgm, name, NULL, attr_path,
4019 NULL, NULL, NULL, o, p);
4020 return;
4023 diff_fill_oid_info(one);
4024 diff_fill_oid_info(two);
4026 if (!pgm &&
4027 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4028 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4030 * a filepair that changes between file and symlink
4031 * needs to be split into deletion and creation.
4033 struct diff_filespec *null = alloc_filespec(two->path);
4034 run_diff_cmd(NULL, name, other, attr_path,
4035 one, null, &msg, o, p);
4036 free(null);
4037 strbuf_release(&msg);
4039 null = alloc_filespec(one->path);
4040 run_diff_cmd(NULL, name, other, attr_path,
4041 null, two, &msg, o, p);
4042 free(null);
4044 else
4045 run_diff_cmd(pgm, name, other, attr_path,
4046 one, two, &msg, o, p);
4048 strbuf_release(&msg);
4051 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4052 struct diffstat_t *diffstat)
4054 const char *name;
4055 const char *other;
4057 if (DIFF_PAIR_UNMERGED(p)) {
4058 /* unmerged */
4059 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
4060 return;
4063 name = p->one->path;
4064 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4066 if (o->prefix_length)
4067 strip_prefix(o->prefix_length, &name, &other);
4069 diff_fill_oid_info(p->one);
4070 diff_fill_oid_info(p->two);
4072 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
4075 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4077 const char *name;
4078 const char *other;
4079 const char *attr_path;
4081 if (DIFF_PAIR_UNMERGED(p)) {
4082 /* unmerged */
4083 return;
4086 name = p->one->path;
4087 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4088 attr_path = other ? other : name;
4090 if (o->prefix_length)
4091 strip_prefix(o->prefix_length, &name, &other);
4093 diff_fill_oid_info(p->one);
4094 diff_fill_oid_info(p->two);
4096 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4099 void diff_setup(struct diff_options *options)
4101 memcpy(options, &default_diff_options, sizeof(*options));
4103 options->file = stdout;
4105 options->abbrev = DEFAULT_ABBREV;
4106 options->line_termination = '\n';
4107 options->break_opt = -1;
4108 options->rename_limit = -1;
4109 options->dirstat_permille = diff_dirstat_permille_default;
4110 options->context = diff_context_default;
4111 options->interhunkcontext = diff_interhunk_context_default;
4112 options->ws_error_highlight = ws_error_highlight_default;
4113 options->flags.rename_empty = 1;
4114 options->objfind = NULL;
4116 /* pathchange left =NULL by default */
4117 options->change = diff_change;
4118 options->add_remove = diff_addremove;
4119 options->use_color = diff_use_color_default;
4120 options->detect_rename = diff_detect_rename_default;
4121 options->xdl_opts |= diff_algorithm;
4122 if (diff_indent_heuristic)
4123 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4125 options->orderfile = diff_order_file_cfg;
4127 if (diff_no_prefix) {
4128 options->a_prefix = options->b_prefix = "";
4129 } else if (!diff_mnemonic_prefix) {
4130 options->a_prefix = "a/";
4131 options->b_prefix = "b/";
4134 options->color_moved = diff_color_moved_default;
4137 void diff_setup_done(struct diff_options *options)
4139 unsigned check_mask = DIFF_FORMAT_NAME |
4140 DIFF_FORMAT_NAME_STATUS |
4141 DIFF_FORMAT_CHECKDIFF |
4142 DIFF_FORMAT_NO_OUTPUT;
4144 if (options->set_default)
4145 options->set_default(options);
4147 if (HAS_MULTI_BITS(options->output_format & check_mask))
4148 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4150 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4151 die(_("-G, -S and --find-object are mutually exclusive"));
4154 * Most of the time we can say "there are changes"
4155 * only by checking if there are changed paths, but
4156 * --ignore-whitespace* options force us to look
4157 * inside contents.
4160 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
4161 options->flags.diff_from_contents = 1;
4162 else
4163 options->flags.diff_from_contents = 0;
4165 if (options->flags.find_copies_harder)
4166 options->detect_rename = DIFF_DETECT_COPY;
4168 if (!options->flags.relative_name)
4169 options->prefix = NULL;
4170 if (options->prefix)
4171 options->prefix_length = strlen(options->prefix);
4172 else
4173 options->prefix_length = 0;
4175 if (options->output_format & (DIFF_FORMAT_NAME |
4176 DIFF_FORMAT_NAME_STATUS |
4177 DIFF_FORMAT_CHECKDIFF |
4178 DIFF_FORMAT_NO_OUTPUT))
4179 options->output_format &= ~(DIFF_FORMAT_RAW |
4180 DIFF_FORMAT_NUMSTAT |
4181 DIFF_FORMAT_DIFFSTAT |
4182 DIFF_FORMAT_SHORTSTAT |
4183 DIFF_FORMAT_DIRSTAT |
4184 DIFF_FORMAT_SUMMARY |
4185 DIFF_FORMAT_PATCH);
4188 * These cases always need recursive; we do not drop caller-supplied
4189 * recursive bits for other formats here.
4191 if (options->output_format & (DIFF_FORMAT_PATCH |
4192 DIFF_FORMAT_NUMSTAT |
4193 DIFF_FORMAT_DIFFSTAT |
4194 DIFF_FORMAT_SHORTSTAT |
4195 DIFF_FORMAT_DIRSTAT |
4196 DIFF_FORMAT_SUMMARY |
4197 DIFF_FORMAT_CHECKDIFF))
4198 options->flags.recursive = 1;
4200 * Also pickaxe would not work very well if you do not say recursive
4202 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4203 options->flags.recursive = 1;
4205 * When patches are generated, submodules diffed against the work tree
4206 * must be checked for dirtiness too so it can be shown in the output
4208 if (options->output_format & DIFF_FORMAT_PATCH)
4209 options->flags.dirty_submodules = 1;
4211 if (options->detect_rename && options->rename_limit < 0)
4212 options->rename_limit = diff_rename_limit_default;
4213 if (options->setup & DIFF_SETUP_USE_CACHE) {
4214 if (!active_cache)
4215 /* read-cache does not die even when it fails
4216 * so it is safe for us to do this here. Also
4217 * it does not smudge active_cache or active_nr
4218 * when it fails, so we do not have to worry about
4219 * cleaning it up ourselves either.
4221 read_cache();
4223 if (40 < options->abbrev)
4224 options->abbrev = 40; /* full */
4227 * It does not make sense to show the first hit we happened
4228 * to have found. It does not make sense not to return with
4229 * exit code in such a case either.
4231 if (options->flags.quick) {
4232 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4233 options->flags.exit_with_status = 1;
4236 options->diff_path_counter = 0;
4238 if (options->flags.follow_renames && options->pathspec.nr != 1)
4239 die(_("--follow requires exactly one pathspec"));
4241 if (!options->use_color || external_diff())
4242 options->color_moved = 0;
4245 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4247 char c, *eq;
4248 int len;
4250 if (*arg != '-')
4251 return 0;
4252 c = *++arg;
4253 if (!c)
4254 return 0;
4255 if (c == arg_short) {
4256 c = *++arg;
4257 if (!c)
4258 return 1;
4259 if (val && isdigit(c)) {
4260 char *end;
4261 int n = strtoul(arg, &end, 10);
4262 if (*end)
4263 return 0;
4264 *val = n;
4265 return 1;
4267 return 0;
4269 if (c != '-')
4270 return 0;
4271 arg++;
4272 eq = strchrnul(arg, '=');
4273 len = eq - arg;
4274 if (!len || strncmp(arg, arg_long, len))
4275 return 0;
4276 if (*eq) {
4277 int n;
4278 char *end;
4279 if (!isdigit(*++eq))
4280 return 0;
4281 n = strtoul(eq, &end, 10);
4282 if (*end)
4283 return 0;
4284 *val = n;
4286 return 1;
4289 static int diff_scoreopt_parse(const char *opt);
4291 static inline int short_opt(char opt, const char **argv,
4292 const char **optarg)
4294 const char *arg = argv[0];
4295 if (arg[0] != '-' || arg[1] != opt)
4296 return 0;
4297 if (arg[2] != '\0') {
4298 *optarg = arg + 2;
4299 return 1;
4301 if (!argv[1])
4302 die("Option '%c' requires a value", opt);
4303 *optarg = argv[1];
4304 return 2;
4307 int parse_long_opt(const char *opt, const char **argv,
4308 const char **optarg)
4310 const char *arg = argv[0];
4311 if (!skip_prefix(arg, "--", &arg))
4312 return 0;
4313 if (!skip_prefix(arg, opt, &arg))
4314 return 0;
4315 if (*arg == '=') { /* stuck form: --option=value */
4316 *optarg = arg + 1;
4317 return 1;
4319 if (*arg != '\0')
4320 return 0;
4321 /* separate form: --option value */
4322 if (!argv[1])
4323 die("Option '--%s' requires a value", opt);
4324 *optarg = argv[1];
4325 return 2;
4328 static int stat_opt(struct diff_options *options, const char **av)
4330 const char *arg = av[0];
4331 char *end;
4332 int width = options->stat_width;
4333 int name_width = options->stat_name_width;
4334 int graph_width = options->stat_graph_width;
4335 int count = options->stat_count;
4336 int argcount = 1;
4338 if (!skip_prefix(arg, "--stat", &arg))
4339 die("BUG: stat option does not begin with --stat: %s", arg);
4340 end = (char *)arg;
4342 switch (*arg) {
4343 case '-':
4344 if (skip_prefix(arg, "-width", &arg)) {
4345 if (*arg == '=')
4346 width = strtoul(arg + 1, &end, 10);
4347 else if (!*arg && !av[1])
4348 die_want_option("--stat-width");
4349 else if (!*arg) {
4350 width = strtoul(av[1], &end, 10);
4351 argcount = 2;
4353 } else if (skip_prefix(arg, "-name-width", &arg)) {
4354 if (*arg == '=')
4355 name_width = strtoul(arg + 1, &end, 10);
4356 else if (!*arg && !av[1])
4357 die_want_option("--stat-name-width");
4358 else if (!*arg) {
4359 name_width = strtoul(av[1], &end, 10);
4360 argcount = 2;
4362 } else if (skip_prefix(arg, "-graph-width", &arg)) {
4363 if (*arg == '=')
4364 graph_width = strtoul(arg + 1, &end, 10);
4365 else if (!*arg && !av[1])
4366 die_want_option("--stat-graph-width");
4367 else if (!*arg) {
4368 graph_width = strtoul(av[1], &end, 10);
4369 argcount = 2;
4371 } else if (skip_prefix(arg, "-count", &arg)) {
4372 if (*arg == '=')
4373 count = strtoul(arg + 1, &end, 10);
4374 else if (!*arg && !av[1])
4375 die_want_option("--stat-count");
4376 else if (!*arg) {
4377 count = strtoul(av[1], &end, 10);
4378 argcount = 2;
4381 break;
4382 case '=':
4383 width = strtoul(arg+1, &end, 10);
4384 if (*end == ',')
4385 name_width = strtoul(end+1, &end, 10);
4386 if (*end == ',')
4387 count = strtoul(end+1, &end, 10);
4390 /* Important! This checks all the error cases! */
4391 if (*end)
4392 return 0;
4393 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4394 options->stat_name_width = name_width;
4395 options->stat_graph_width = graph_width;
4396 options->stat_width = width;
4397 options->stat_count = count;
4398 return argcount;
4401 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4403 struct strbuf errmsg = STRBUF_INIT;
4404 if (parse_dirstat_params(options, params, &errmsg))
4405 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4406 errmsg.buf);
4407 strbuf_release(&errmsg);
4409 * The caller knows a dirstat-related option is given from the command
4410 * line; allow it to say "return this_function();"
4412 options->output_format |= DIFF_FORMAT_DIRSTAT;
4413 return 1;
4416 static int parse_submodule_opt(struct diff_options *options, const char *value)
4418 if (parse_submodule_params(options, value))
4419 die(_("Failed to parse --submodule option parameter: '%s'"),
4420 value);
4421 return 1;
4424 static const char diff_status_letters[] = {
4425 DIFF_STATUS_ADDED,
4426 DIFF_STATUS_COPIED,
4427 DIFF_STATUS_DELETED,
4428 DIFF_STATUS_MODIFIED,
4429 DIFF_STATUS_RENAMED,
4430 DIFF_STATUS_TYPE_CHANGED,
4431 DIFF_STATUS_UNKNOWN,
4432 DIFF_STATUS_UNMERGED,
4433 DIFF_STATUS_FILTER_AON,
4434 DIFF_STATUS_FILTER_BROKEN,
4435 '\0',
4438 static unsigned int filter_bit['Z' + 1];
4440 static void prepare_filter_bits(void)
4442 int i;
4444 if (!filter_bit[DIFF_STATUS_ADDED]) {
4445 for (i = 0; diff_status_letters[i]; i++)
4446 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4450 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4452 return opt->filter & filter_bit[(int) status];
4455 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4457 int i, optch;
4459 prepare_filter_bits();
4462 * If there is a negation e.g. 'd' in the input, and we haven't
4463 * initialized the filter field with another --diff-filter, start
4464 * from full set of bits, except for AON.
4466 if (!opt->filter) {
4467 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4468 if (optch < 'a' || 'z' < optch)
4469 continue;
4470 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4471 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4472 break;
4476 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4477 unsigned int bit;
4478 int negate;
4480 if ('a' <= optch && optch <= 'z') {
4481 negate = 1;
4482 optch = toupper(optch);
4483 } else {
4484 negate = 0;
4487 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4488 if (!bit)
4489 return optarg[i];
4490 if (negate)
4491 opt->filter &= ~bit;
4492 else
4493 opt->filter |= bit;
4495 return 0;
4498 static void enable_patch_output(int *fmt) {
4499 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4500 *fmt |= DIFF_FORMAT_PATCH;
4503 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4505 int val = parse_ws_error_highlight(arg);
4507 if (val < 0) {
4508 error("unknown value after ws-error-highlight=%.*s",
4509 -1 - val, arg);
4510 return 0;
4512 opt->ws_error_highlight = val;
4513 return 1;
4516 static int parse_objfind_opt(struct diff_options *opt, const char *arg)
4518 struct object_id oid;
4520 if (get_oid(arg, &oid))
4521 return error("unable to resolve '%s'", arg);
4523 if (!opt->objfind)
4524 opt->objfind = xcalloc(1, sizeof(*opt->objfind));
4526 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4527 opt->flags.recursive = 1;
4528 opt->flags.tree_in_recursive = 1;
4529 oidset_insert(opt->objfind, &oid);
4530 return 1;
4533 int diff_opt_parse(struct diff_options *options,
4534 const char **av, int ac, const char *prefix)
4536 const char *arg = av[0];
4537 const char *optarg;
4538 int argcount;
4540 if (!prefix)
4541 prefix = "";
4543 /* Output format options */
4544 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
4545 || opt_arg(arg, 'U', "unified", &options->context))
4546 enable_patch_output(&options->output_format);
4547 else if (!strcmp(arg, "--raw"))
4548 options->output_format |= DIFF_FORMAT_RAW;
4549 else if (!strcmp(arg, "--patch-with-raw")) {
4550 enable_patch_output(&options->output_format);
4551 options->output_format |= DIFF_FORMAT_RAW;
4552 } else if (!strcmp(arg, "--numstat"))
4553 options->output_format |= DIFF_FORMAT_NUMSTAT;
4554 else if (!strcmp(arg, "--shortstat"))
4555 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4556 else if (skip_prefix(arg, "-X", &arg) ||
4557 skip_to_optional_arg(arg, "--dirstat", &arg))
4558 return parse_dirstat_opt(options, arg);
4559 else if (!strcmp(arg, "--cumulative"))
4560 return parse_dirstat_opt(options, "cumulative");
4561 else if (skip_to_optional_arg(arg, "--dirstat-by-file", &arg)) {
4562 parse_dirstat_opt(options, "files");
4563 return parse_dirstat_opt(options, arg);
4565 else if (!strcmp(arg, "--check"))
4566 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4567 else if (!strcmp(arg, "--summary"))
4568 options->output_format |= DIFF_FORMAT_SUMMARY;
4569 else if (!strcmp(arg, "--patch-with-stat")) {
4570 enable_patch_output(&options->output_format);
4571 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4572 } else if (!strcmp(arg, "--name-only"))
4573 options->output_format |= DIFF_FORMAT_NAME;
4574 else if (!strcmp(arg, "--name-status"))
4575 options->output_format |= DIFF_FORMAT_NAME_STATUS;
4576 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
4577 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4578 else if (starts_with(arg, "--stat"))
4579 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4580 return stat_opt(options, av);
4581 else if (!strcmp(arg, "--compact-summary")) {
4582 options->flags.stat_with_summary = 1;
4583 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4584 } else if (!strcmp(arg, "--no-compact-summary"))
4585 options->flags.stat_with_summary = 0;
4587 /* renames options */
4588 else if (starts_with(arg, "-B") ||
4589 skip_to_optional_arg(arg, "--break-rewrites", NULL)) {
4590 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
4591 return error("invalid argument to -B: %s", arg+2);
4593 else if (starts_with(arg, "-M") ||
4594 skip_to_optional_arg(arg, "--find-renames", NULL)) {
4595 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4596 return error("invalid argument to -M: %s", arg+2);
4597 options->detect_rename = DIFF_DETECT_RENAME;
4599 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
4600 options->irreversible_delete = 1;
4602 else if (starts_with(arg, "-C") ||
4603 skip_to_optional_arg(arg, "--find-copies", NULL)) {
4604 if (options->detect_rename == DIFF_DETECT_COPY)
4605 options->flags.find_copies_harder = 1;
4606 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4607 return error("invalid argument to -C: %s", arg+2);
4608 options->detect_rename = DIFF_DETECT_COPY;
4610 else if (!strcmp(arg, "--no-renames"))
4611 options->detect_rename = 0;
4612 else if (!strcmp(arg, "--rename-empty"))
4613 options->flags.rename_empty = 1;
4614 else if (!strcmp(arg, "--no-rename-empty"))
4615 options->flags.rename_empty = 0;
4616 else if (skip_to_optional_arg_default(arg, "--relative", &arg, NULL)) {
4617 options->flags.relative_name = 1;
4618 if (arg)
4619 options->prefix = arg;
4622 /* xdiff options */
4623 else if (!strcmp(arg, "--minimal"))
4624 DIFF_XDL_SET(options, NEED_MINIMAL);
4625 else if (!strcmp(arg, "--no-minimal"))
4626 DIFF_XDL_CLR(options, NEED_MINIMAL);
4627 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
4628 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
4629 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
4630 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
4631 else if (!strcmp(arg, "--ignore-space-at-eol"))
4632 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
4633 else if (!strcmp(arg, "--ignore-cr-at-eol"))
4634 DIFF_XDL_SET(options, IGNORE_CR_AT_EOL);
4635 else if (!strcmp(arg, "--ignore-blank-lines"))
4636 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
4637 else if (!strcmp(arg, "--indent-heuristic"))
4638 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4639 else if (!strcmp(arg, "--no-indent-heuristic"))
4640 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
4641 else if (!strcmp(arg, "--patience")) {
4642 int i;
4643 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4645 * Both --patience and --anchored use PATIENCE_DIFF
4646 * internally, so remove any anchors previously
4647 * specified.
4649 for (i = 0; i < options->anchors_nr; i++)
4650 free(options->anchors[i]);
4651 options->anchors_nr = 0;
4652 } else if (!strcmp(arg, "--histogram"))
4653 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
4654 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
4655 long value = parse_algorithm_value(optarg);
4656 if (value < 0)
4657 return error("option diff-algorithm accepts \"myers\", "
4658 "\"minimal\", \"patience\" and \"histogram\"");
4659 /* clear out previous settings */
4660 DIFF_XDL_CLR(options, NEED_MINIMAL);
4661 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4662 options->xdl_opts |= value;
4663 return argcount;
4664 } else if (skip_prefix(arg, "--anchored=", &arg)) {
4665 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4666 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4667 options->anchors_alloc);
4668 options->anchors[options->anchors_nr++] = xstrdup(arg);
4671 /* flags options */
4672 else if (!strcmp(arg, "--binary")) {
4673 enable_patch_output(&options->output_format);
4674 options->flags.binary = 1;
4676 else if (!strcmp(arg, "--full-index"))
4677 options->flags.full_index = 1;
4678 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
4679 options->flags.text = 1;
4680 else if (!strcmp(arg, "-R"))
4681 options->flags.reverse_diff = 1;
4682 else if (!strcmp(arg, "--find-copies-harder"))
4683 options->flags.find_copies_harder = 1;
4684 else if (!strcmp(arg, "--follow"))
4685 options->flags.follow_renames = 1;
4686 else if (!strcmp(arg, "--no-follow")) {
4687 options->flags.follow_renames = 0;
4688 options->flags.default_follow_renames = 0;
4689 } else if (skip_to_optional_arg_default(arg, "--color", &arg, "always")) {
4690 int value = git_config_colorbool(NULL, arg);
4691 if (value < 0)
4692 return error("option `color' expects \"always\", \"auto\", or \"never\"");
4693 options->use_color = value;
4695 else if (!strcmp(arg, "--no-color"))
4696 options->use_color = 0;
4697 else if (!strcmp(arg, "--color-moved")) {
4698 if (diff_color_moved_default)
4699 options->color_moved = diff_color_moved_default;
4700 if (options->color_moved == COLOR_MOVED_NO)
4701 options->color_moved = COLOR_MOVED_DEFAULT;
4702 } else if (!strcmp(arg, "--no-color-moved"))
4703 options->color_moved = COLOR_MOVED_NO;
4704 else if (skip_prefix(arg, "--color-moved=", &arg)) {
4705 int cm = parse_color_moved(arg);
4706 if (cm < 0)
4707 die("bad --color-moved argument: %s", arg);
4708 options->color_moved = cm;
4709 } else if (skip_to_optional_arg_default(arg, "--color-words", &options->word_regex, NULL)) {
4710 options->use_color = 1;
4711 options->word_diff = DIFF_WORDS_COLOR;
4713 else if (!strcmp(arg, "--word-diff")) {
4714 if (options->word_diff == DIFF_WORDS_NONE)
4715 options->word_diff = DIFF_WORDS_PLAIN;
4717 else if (skip_prefix(arg, "--word-diff=", &arg)) {
4718 if (!strcmp(arg, "plain"))
4719 options->word_diff = DIFF_WORDS_PLAIN;
4720 else if (!strcmp(arg, "color")) {
4721 options->use_color = 1;
4722 options->word_diff = DIFF_WORDS_COLOR;
4724 else if (!strcmp(arg, "porcelain"))
4725 options->word_diff = DIFF_WORDS_PORCELAIN;
4726 else if (!strcmp(arg, "none"))
4727 options->word_diff = DIFF_WORDS_NONE;
4728 else
4729 die("bad --word-diff argument: %s", arg);
4731 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
4732 if (options->word_diff == DIFF_WORDS_NONE)
4733 options->word_diff = DIFF_WORDS_PLAIN;
4734 options->word_regex = optarg;
4735 return argcount;
4737 else if (!strcmp(arg, "--exit-code"))
4738 options->flags.exit_with_status = 1;
4739 else if (!strcmp(arg, "--quiet"))
4740 options->flags.quick = 1;
4741 else if (!strcmp(arg, "--ext-diff"))
4742 options->flags.allow_external = 1;
4743 else if (!strcmp(arg, "--no-ext-diff"))
4744 options->flags.allow_external = 0;
4745 else if (!strcmp(arg, "--textconv")) {
4746 options->flags.allow_textconv = 1;
4747 options->flags.textconv_set_via_cmdline = 1;
4748 } else if (!strcmp(arg, "--no-textconv"))
4749 options->flags.allow_textconv = 0;
4750 else if (skip_to_optional_arg_default(arg, "--ignore-submodules", &arg, "all")) {
4751 options->flags.override_submodule_config = 1;
4752 handle_ignore_submodules_arg(options, arg);
4753 } else if (skip_to_optional_arg_default(arg, "--submodule", &arg, "log"))
4754 return parse_submodule_opt(options, arg);
4755 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
4756 return parse_ws_error_highlight_opt(options, arg);
4757 else if (!strcmp(arg, "--ita-invisible-in-index"))
4758 options->ita_invisible_in_index = 1;
4759 else if (!strcmp(arg, "--ita-visible-in-index"))
4760 options->ita_invisible_in_index = 0;
4762 /* misc options */
4763 else if (!strcmp(arg, "-z"))
4764 options->line_termination = 0;
4765 else if ((argcount = short_opt('l', av, &optarg))) {
4766 options->rename_limit = strtoul(optarg, NULL, 10);
4767 return argcount;
4769 else if ((argcount = short_opt('S', av, &optarg))) {
4770 options->pickaxe = optarg;
4771 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
4772 return argcount;
4773 } else if ((argcount = short_opt('G', av, &optarg))) {
4774 options->pickaxe = optarg;
4775 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
4776 return argcount;
4778 else if (!strcmp(arg, "--pickaxe-all"))
4779 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
4780 else if (!strcmp(arg, "--pickaxe-regex"))
4781 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
4782 else if ((argcount = short_opt('O', av, &optarg))) {
4783 options->orderfile = prefix_filename(prefix, optarg);
4784 return argcount;
4785 } else if (skip_prefix(arg, "--find-object=", &arg))
4786 return parse_objfind_opt(options, arg);
4787 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
4788 int offending = parse_diff_filter_opt(optarg, options);
4789 if (offending)
4790 die("unknown change class '%c' in --diff-filter=%s",
4791 offending, optarg);
4792 return argcount;
4794 else if (!strcmp(arg, "--no-abbrev"))
4795 options->abbrev = 0;
4796 else if (!strcmp(arg, "--abbrev"))
4797 options->abbrev = DEFAULT_ABBREV;
4798 else if (skip_prefix(arg, "--abbrev=", &arg)) {
4799 options->abbrev = strtoul(arg, NULL, 10);
4800 if (options->abbrev < MINIMUM_ABBREV)
4801 options->abbrev = MINIMUM_ABBREV;
4802 else if (40 < options->abbrev)
4803 options->abbrev = 40;
4805 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
4806 options->a_prefix = optarg;
4807 return argcount;
4809 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
4810 options->line_prefix = optarg;
4811 options->line_prefix_length = strlen(options->line_prefix);
4812 graph_setup_line_prefix(options);
4813 return argcount;
4815 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
4816 options->b_prefix = optarg;
4817 return argcount;
4819 else if (!strcmp(arg, "--no-prefix"))
4820 options->a_prefix = options->b_prefix = "";
4821 else if (opt_arg(arg, '\0', "inter-hunk-context",
4822 &options->interhunkcontext))
4824 else if (!strcmp(arg, "-W"))
4825 options->flags.funccontext = 1;
4826 else if (!strcmp(arg, "--function-context"))
4827 options->flags.funccontext = 1;
4828 else if (!strcmp(arg, "--no-function-context"))
4829 options->flags.funccontext = 0;
4830 else if ((argcount = parse_long_opt("output", av, &optarg))) {
4831 char *path = prefix_filename(prefix, optarg);
4832 options->file = xfopen(path, "w");
4833 options->close_file = 1;
4834 if (options->use_color != GIT_COLOR_ALWAYS)
4835 options->use_color = GIT_COLOR_NEVER;
4836 free(path);
4837 return argcount;
4838 } else
4839 return 0;
4840 return 1;
4843 int parse_rename_score(const char **cp_p)
4845 unsigned long num, scale;
4846 int ch, dot;
4847 const char *cp = *cp_p;
4849 num = 0;
4850 scale = 1;
4851 dot = 0;
4852 for (;;) {
4853 ch = *cp;
4854 if ( !dot && ch == '.' ) {
4855 scale = 1;
4856 dot = 1;
4857 } else if ( ch == '%' ) {
4858 scale = dot ? scale*100 : 100;
4859 cp++; /* % is always at the end */
4860 break;
4861 } else if ( ch >= '0' && ch <= '9' ) {
4862 if ( scale < 100000 ) {
4863 scale *= 10;
4864 num = (num*10) + (ch-'0');
4866 } else {
4867 break;
4869 cp++;
4871 *cp_p = cp;
4873 /* user says num divided by scale and we say internally that
4874 * is MAX_SCORE * num / scale.
4876 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4879 static int diff_scoreopt_parse(const char *opt)
4881 int opt1, opt2, cmd;
4883 if (*opt++ != '-')
4884 return -1;
4885 cmd = *opt++;
4886 if (cmd == '-') {
4887 /* convert the long-form arguments into short-form versions */
4888 if (skip_prefix(opt, "break-rewrites", &opt)) {
4889 if (*opt == 0 || *opt++ == '=')
4890 cmd = 'B';
4891 } else if (skip_prefix(opt, "find-copies", &opt)) {
4892 if (*opt == 0 || *opt++ == '=')
4893 cmd = 'C';
4894 } else if (skip_prefix(opt, "find-renames", &opt)) {
4895 if (*opt == 0 || *opt++ == '=')
4896 cmd = 'M';
4899 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4900 return -1; /* that is not a -M, -C, or -B option */
4902 opt1 = parse_rename_score(&opt);
4903 if (cmd != 'B')
4904 opt2 = 0;
4905 else {
4906 if (*opt == 0)
4907 opt2 = 0;
4908 else if (*opt != '/')
4909 return -1; /* we expect -B80/99 or -B80 */
4910 else {
4911 opt++;
4912 opt2 = parse_rename_score(&opt);
4915 if (*opt != 0)
4916 return -1;
4917 return opt1 | (opt2 << 16);
4920 struct diff_queue_struct diff_queued_diff;
4922 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4924 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4925 queue->queue[queue->nr++] = dp;
4928 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4929 struct diff_filespec *one,
4930 struct diff_filespec *two)
4932 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4933 dp->one = one;
4934 dp->two = two;
4935 if (queue)
4936 diff_q(queue, dp);
4937 return dp;
4940 void diff_free_filepair(struct diff_filepair *p)
4942 free_filespec(p->one);
4943 free_filespec(p->two);
4944 free(p);
4947 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
4949 int abblen;
4950 const char *abbrev;
4952 /* Do we want all 40 hex characters? */
4953 if (len == GIT_SHA1_HEXSZ)
4954 return oid_to_hex(oid);
4956 /* An abbreviated value is fine, possibly followed by an ellipsis. */
4957 abbrev = diff_abbrev_oid(oid, len);
4959 if (!print_sha1_ellipsis())
4960 return abbrev;
4962 abblen = strlen(abbrev);
4965 * In well-behaved cases, where the abbreviated result is the
4966 * same as the requested length, append three dots after the
4967 * abbreviation (hence the whole logic is limited to the case
4968 * where abblen < 37); when the actual abbreviated result is a
4969 * bit longer than the requested length, we reduce the number
4970 * of dots so that they match the well-behaved ones. However,
4971 * if the actual abbreviation is longer than the requested
4972 * length by more than three, we give up on aligning, and add
4973 * three dots anyway, to indicate that the output is not the
4974 * full object name. Yes, this may be suboptimal, but this
4975 * appears only in "diff --raw --abbrev" output and it is not
4976 * worth the effort to change it now. Note that this would
4977 * likely to work fine when the automatic sizing of default
4978 * abbreviation length is used--we would be fed -1 in "len" in
4979 * that case, and will end up always appending three-dots, but
4980 * the automatic sizing is supposed to give abblen that ensures
4981 * uniqueness across all objects (statistically speaking).
4983 if (abblen < GIT_SHA1_HEXSZ - 3) {
4984 static char hex[GIT_MAX_HEXSZ + 1];
4985 if (len < abblen && abblen <= len + 2)
4986 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
4987 else
4988 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
4989 return hex;
4992 return oid_to_hex(oid);
4995 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4997 int line_termination = opt->line_termination;
4998 int inter_name_termination = line_termination ? '\t' : '\0';
5000 fprintf(opt->file, "%s", diff_line_prefix(opt));
5001 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5002 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5003 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5004 fprintf(opt->file, "%s ",
5005 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5007 if (p->score) {
5008 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5009 inter_name_termination);
5010 } else {
5011 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5014 if (p->status == DIFF_STATUS_COPIED ||
5015 p->status == DIFF_STATUS_RENAMED) {
5016 const char *name_a, *name_b;
5017 name_a = p->one->path;
5018 name_b = p->two->path;
5019 strip_prefix(opt->prefix_length, &name_a, &name_b);
5020 write_name_quoted(name_a, opt->file, inter_name_termination);
5021 write_name_quoted(name_b, opt->file, line_termination);
5022 } else {
5023 const char *name_a, *name_b;
5024 name_a = p->one->mode ? p->one->path : p->two->path;
5025 name_b = NULL;
5026 strip_prefix(opt->prefix_length, &name_a, &name_b);
5027 write_name_quoted(name_a, opt->file, line_termination);
5031 int diff_unmodified_pair(struct diff_filepair *p)
5033 /* This function is written stricter than necessary to support
5034 * the currently implemented transformers, but the idea is to
5035 * let transformers to produce diff_filepairs any way they want,
5036 * and filter and clean them up here before producing the output.
5038 struct diff_filespec *one = p->one, *two = p->two;
5040 if (DIFF_PAIR_UNMERGED(p))
5041 return 0; /* unmerged is interesting */
5043 /* deletion, addition, mode or type change
5044 * and rename are all interesting.
5046 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5047 DIFF_PAIR_MODE_CHANGED(p) ||
5048 strcmp(one->path, two->path))
5049 return 0;
5051 /* both are valid and point at the same path. that is, we are
5052 * dealing with a change.
5054 if (one->oid_valid && two->oid_valid &&
5055 !oidcmp(&one->oid, &two->oid) &&
5056 !one->dirty_submodule && !two->dirty_submodule)
5057 return 1; /* no change */
5058 if (!one->oid_valid && !two->oid_valid)
5059 return 1; /* both look at the same file on the filesystem. */
5060 return 0;
5063 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5065 if (diff_unmodified_pair(p))
5066 return;
5068 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5069 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5070 return; /* no tree diffs in patch format */
5072 run_diff(p, o);
5075 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5076 struct diffstat_t *diffstat)
5078 if (diff_unmodified_pair(p))
5079 return;
5081 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5082 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5083 return; /* no useful stat for tree diffs */
5085 run_diffstat(p, o, diffstat);
5088 static void diff_flush_checkdiff(struct diff_filepair *p,
5089 struct diff_options *o)
5091 if (diff_unmodified_pair(p))
5092 return;
5094 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5095 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5096 return; /* nothing to check in tree diffs */
5098 run_checkdiff(p, o);
5101 int diff_queue_is_empty(void)
5103 struct diff_queue_struct *q = &diff_queued_diff;
5104 int i;
5105 for (i = 0; i < q->nr; i++)
5106 if (!diff_unmodified_pair(q->queue[i]))
5107 return 0;
5108 return 1;
5111 #if DIFF_DEBUG
5112 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5114 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5115 x, one ? one : "",
5116 s->path,
5117 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5118 s->mode,
5119 s->oid_valid ? oid_to_hex(&s->oid) : "");
5120 fprintf(stderr, "queue[%d] %s size %lu\n",
5121 x, one ? one : "",
5122 s->size);
5125 void diff_debug_filepair(const struct diff_filepair *p, int i)
5127 diff_debug_filespec(p->one, i, "one");
5128 diff_debug_filespec(p->two, i, "two");
5129 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5130 p->score, p->status ? p->status : '?',
5131 p->one->rename_used, p->broken_pair);
5134 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5136 int i;
5137 if (msg)
5138 fprintf(stderr, "%s\n", msg);
5139 fprintf(stderr, "q->nr = %d\n", q->nr);
5140 for (i = 0; i < q->nr; i++) {
5141 struct diff_filepair *p = q->queue[i];
5142 diff_debug_filepair(p, i);
5145 #endif
5147 static void diff_resolve_rename_copy(void)
5149 int i;
5150 struct diff_filepair *p;
5151 struct diff_queue_struct *q = &diff_queued_diff;
5153 diff_debug_queue("resolve-rename-copy", q);
5155 for (i = 0; i < q->nr; i++) {
5156 p = q->queue[i];
5157 p->status = 0; /* undecided */
5158 if (DIFF_PAIR_UNMERGED(p))
5159 p->status = DIFF_STATUS_UNMERGED;
5160 else if (!DIFF_FILE_VALID(p->one))
5161 p->status = DIFF_STATUS_ADDED;
5162 else if (!DIFF_FILE_VALID(p->two))
5163 p->status = DIFF_STATUS_DELETED;
5164 else if (DIFF_PAIR_TYPE_CHANGED(p))
5165 p->status = DIFF_STATUS_TYPE_CHANGED;
5167 /* from this point on, we are dealing with a pair
5168 * whose both sides are valid and of the same type, i.e.
5169 * either in-place edit or rename/copy edit.
5171 else if (DIFF_PAIR_RENAME(p)) {
5173 * A rename might have re-connected a broken
5174 * pair up, causing the pathnames to be the
5175 * same again. If so, that's not a rename at
5176 * all, just a modification..
5178 * Otherwise, see if this source was used for
5179 * multiple renames, in which case we decrement
5180 * the count, and call it a copy.
5182 if (!strcmp(p->one->path, p->two->path))
5183 p->status = DIFF_STATUS_MODIFIED;
5184 else if (--p->one->rename_used > 0)
5185 p->status = DIFF_STATUS_COPIED;
5186 else
5187 p->status = DIFF_STATUS_RENAMED;
5189 else if (oidcmp(&p->one->oid, &p->two->oid) ||
5190 p->one->mode != p->two->mode ||
5191 p->one->dirty_submodule ||
5192 p->two->dirty_submodule ||
5193 is_null_oid(&p->one->oid))
5194 p->status = DIFF_STATUS_MODIFIED;
5195 else {
5196 /* This is a "no-change" entry and should not
5197 * happen anymore, but prepare for broken callers.
5199 error("feeding unmodified %s to diffcore",
5200 p->one->path);
5201 p->status = DIFF_STATUS_UNKNOWN;
5204 diff_debug_queue("resolve-rename-copy done", q);
5207 static int check_pair_status(struct diff_filepair *p)
5209 switch (p->status) {
5210 case DIFF_STATUS_UNKNOWN:
5211 return 0;
5212 case 0:
5213 die("internal error in diff-resolve-rename-copy");
5214 default:
5215 return 1;
5219 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5221 int fmt = opt->output_format;
5223 if (fmt & DIFF_FORMAT_CHECKDIFF)
5224 diff_flush_checkdiff(p, opt);
5225 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5226 diff_flush_raw(p, opt);
5227 else if (fmt & DIFF_FORMAT_NAME) {
5228 const char *name_a, *name_b;
5229 name_a = p->two->path;
5230 name_b = NULL;
5231 strip_prefix(opt->prefix_length, &name_a, &name_b);
5232 fprintf(opt->file, "%s", diff_line_prefix(opt));
5233 write_name_quoted(name_a, opt->file, opt->line_termination);
5237 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5239 struct strbuf sb = STRBUF_INIT;
5240 if (fs->mode)
5241 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5242 else
5243 strbuf_addf(&sb, " %s ", newdelete);
5245 quote_c_style(fs->path, &sb, NULL, 0);
5246 strbuf_addch(&sb, '\n');
5247 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5248 sb.buf, sb.len, 0);
5249 strbuf_release(&sb);
5252 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5253 int show_name)
5255 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5256 struct strbuf sb = STRBUF_INIT;
5257 strbuf_addf(&sb, " mode change %06o => %06o",
5258 p->one->mode, p->two->mode);
5259 if (show_name) {
5260 strbuf_addch(&sb, ' ');
5261 quote_c_style(p->two->path, &sb, NULL, 0);
5263 strbuf_addch(&sb, '\n');
5264 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5265 sb.buf, sb.len, 0);
5266 strbuf_release(&sb);
5270 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5271 struct diff_filepair *p)
5273 struct strbuf sb = STRBUF_INIT;
5274 struct strbuf names = STRBUF_INIT;
5276 pprint_rename(&names, p->one->path, p->two->path);
5277 strbuf_addf(&sb, " %s %s (%d%%)\n",
5278 renamecopy, names.buf, similarity_index(p));
5279 strbuf_release(&names);
5280 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5281 sb.buf, sb.len, 0);
5282 show_mode_change(opt, p, 0);
5283 strbuf_release(&sb);
5286 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5288 switch(p->status) {
5289 case DIFF_STATUS_DELETED:
5290 show_file_mode_name(opt, "delete", p->one);
5291 break;
5292 case DIFF_STATUS_ADDED:
5293 show_file_mode_name(opt, "create", p->two);
5294 break;
5295 case DIFF_STATUS_COPIED:
5296 show_rename_copy(opt, "copy", p);
5297 break;
5298 case DIFF_STATUS_RENAMED:
5299 show_rename_copy(opt, "rename", p);
5300 break;
5301 default:
5302 if (p->score) {
5303 struct strbuf sb = STRBUF_INIT;
5304 strbuf_addstr(&sb, " rewrite ");
5305 quote_c_style(p->two->path, &sb, NULL, 0);
5306 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5307 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5308 sb.buf, sb.len, 0);
5309 strbuf_release(&sb);
5311 show_mode_change(opt, p, !p->score);
5312 break;
5316 struct patch_id_t {
5317 git_SHA_CTX *ctx;
5318 int patchlen;
5321 static int remove_space(char *line, int len)
5323 int i;
5324 char *dst = line;
5325 unsigned char c;
5327 for (i = 0; i < len; i++)
5328 if (!isspace((c = line[i])))
5329 *dst++ = c;
5331 return dst - line;
5334 static void patch_id_consume(void *priv, char *line, unsigned long len)
5336 struct patch_id_t *data = priv;
5337 int new_len;
5339 /* Ignore line numbers when computing the SHA1 of the patch */
5340 if (starts_with(line, "@@ -"))
5341 return;
5343 new_len = remove_space(line, len);
5345 git_SHA1_Update(data->ctx, line, new_len);
5346 data->patchlen += new_len;
5349 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
5351 git_SHA1_Update(ctx, str, strlen(str));
5354 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
5356 /* large enough for 2^32 in octal */
5357 char buf[12];
5358 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
5359 git_SHA1_Update(ctx, buf, len);
5362 /* returns 0 upon success, and writes result into sha1 */
5363 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5365 struct diff_queue_struct *q = &diff_queued_diff;
5366 int i;
5367 git_SHA_CTX ctx;
5368 struct patch_id_t data;
5370 git_SHA1_Init(&ctx);
5371 memset(&data, 0, sizeof(struct patch_id_t));
5372 data.ctx = &ctx;
5374 for (i = 0; i < q->nr; i++) {
5375 xpparam_t xpp;
5376 xdemitconf_t xecfg;
5377 mmfile_t mf1, mf2;
5378 struct diff_filepair *p = q->queue[i];
5379 int len1, len2;
5381 memset(&xpp, 0, sizeof(xpp));
5382 memset(&xecfg, 0, sizeof(xecfg));
5383 if (p->status == 0)
5384 return error("internal diff status error");
5385 if (p->status == DIFF_STATUS_UNKNOWN)
5386 continue;
5387 if (diff_unmodified_pair(p))
5388 continue;
5389 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5390 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5391 continue;
5392 if (DIFF_PAIR_UNMERGED(p))
5393 continue;
5395 diff_fill_oid_info(p->one);
5396 diff_fill_oid_info(p->two);
5398 len1 = remove_space(p->one->path, strlen(p->one->path));
5399 len2 = remove_space(p->two->path, strlen(p->two->path));
5400 patch_id_add_string(&ctx, "diff--git");
5401 patch_id_add_string(&ctx, "a/");
5402 git_SHA1_Update(&ctx, p->one->path, len1);
5403 patch_id_add_string(&ctx, "b/");
5404 git_SHA1_Update(&ctx, p->two->path, len2);
5406 if (p->one->mode == 0) {
5407 patch_id_add_string(&ctx, "newfilemode");
5408 patch_id_add_mode(&ctx, p->two->mode);
5409 patch_id_add_string(&ctx, "---/dev/null");
5410 patch_id_add_string(&ctx, "+++b/");
5411 git_SHA1_Update(&ctx, p->two->path, len2);
5412 } else if (p->two->mode == 0) {
5413 patch_id_add_string(&ctx, "deletedfilemode");
5414 patch_id_add_mode(&ctx, p->one->mode);
5415 patch_id_add_string(&ctx, "---a/");
5416 git_SHA1_Update(&ctx, p->one->path, len1);
5417 patch_id_add_string(&ctx, "+++/dev/null");
5418 } else {
5419 patch_id_add_string(&ctx, "---a/");
5420 git_SHA1_Update(&ctx, p->one->path, len1);
5421 patch_id_add_string(&ctx, "+++b/");
5422 git_SHA1_Update(&ctx, p->two->path, len2);
5425 if (diff_header_only)
5426 continue;
5428 if (fill_mmfile(&mf1, p->one) < 0 ||
5429 fill_mmfile(&mf2, p->two) < 0)
5430 return error("unable to read files to diff");
5432 if (diff_filespec_is_binary(p->one) ||
5433 diff_filespec_is_binary(p->two)) {
5434 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5435 GIT_SHA1_HEXSZ);
5436 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5437 GIT_SHA1_HEXSZ);
5438 continue;
5441 xpp.flags = 0;
5442 xecfg.ctxlen = 3;
5443 xecfg.flags = 0;
5444 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
5445 &xpp, &xecfg))
5446 return error("unable to generate patch-id diff for %s",
5447 p->one->path);
5450 git_SHA1_Final(oid->hash, &ctx);
5451 return 0;
5454 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5456 struct diff_queue_struct *q = &diff_queued_diff;
5457 int i;
5458 int result = diff_get_patch_id(options, oid, diff_header_only);
5460 for (i = 0; i < q->nr; i++)
5461 diff_free_filepair(q->queue[i]);
5463 free(q->queue);
5464 DIFF_QUEUE_CLEAR(q);
5466 return result;
5469 static int is_summary_empty(const struct diff_queue_struct *q)
5471 int i;
5473 for (i = 0; i < q->nr; i++) {
5474 const struct diff_filepair *p = q->queue[i];
5476 switch (p->status) {
5477 case DIFF_STATUS_DELETED:
5478 case DIFF_STATUS_ADDED:
5479 case DIFF_STATUS_COPIED:
5480 case DIFF_STATUS_RENAMED:
5481 return 0;
5482 default:
5483 if (p->score)
5484 return 0;
5485 if (p->one->mode && p->two->mode &&
5486 p->one->mode != p->two->mode)
5487 return 0;
5488 break;
5491 return 1;
5494 static const char rename_limit_warning[] =
5495 N_("inexact rename detection was skipped due to too many files.");
5497 static const char degrade_cc_to_c_warning[] =
5498 N_("only found copies from modified paths due to too many files.");
5500 static const char rename_limit_advice[] =
5501 N_("you may want to set your %s variable to at least "
5502 "%d and retry the command.");
5504 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
5506 fflush(stdout);
5507 if (degraded_cc)
5508 warning(_(degrade_cc_to_c_warning));
5509 else if (needed)
5510 warning(_(rename_limit_warning));
5511 else
5512 return;
5513 if (0 < needed)
5514 warning(_(rename_limit_advice), varname, needed);
5517 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
5519 int i;
5520 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
5521 struct diff_queue_struct *q = &diff_queued_diff;
5523 if (WSEH_NEW & WS_RULE_MASK)
5524 die("BUG: WS rules bit mask overlaps with diff symbol flags");
5526 if (o->color_moved)
5527 o->emitted_symbols = &esm;
5529 for (i = 0; i < q->nr; i++) {
5530 struct diff_filepair *p = q->queue[i];
5531 if (check_pair_status(p))
5532 diff_flush_patch(p, o);
5535 if (o->emitted_symbols) {
5536 if (o->color_moved) {
5537 struct hashmap add_lines, del_lines;
5539 hashmap_init(&del_lines,
5540 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5541 hashmap_init(&add_lines,
5542 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5544 add_lines_to_move_detection(o, &add_lines, &del_lines);
5545 mark_color_as_moved(o, &add_lines, &del_lines);
5546 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
5547 dim_moved_lines(o);
5549 hashmap_free(&add_lines, 0);
5550 hashmap_free(&del_lines, 0);
5553 for (i = 0; i < esm.nr; i++)
5554 emit_diff_symbol_from_struct(o, &esm.buf[i]);
5556 for (i = 0; i < esm.nr; i++)
5557 free((void *)esm.buf[i].line);
5559 esm.nr = 0;
5562 void diff_flush(struct diff_options *options)
5564 struct diff_queue_struct *q = &diff_queued_diff;
5565 int i, output_format = options->output_format;
5566 int separator = 0;
5567 int dirstat_by_line = 0;
5570 * Order: raw, stat, summary, patch
5571 * or: name/name-status/checkdiff (other bits clear)
5573 if (!q->nr)
5574 goto free_queue;
5576 if (output_format & (DIFF_FORMAT_RAW |
5577 DIFF_FORMAT_NAME |
5578 DIFF_FORMAT_NAME_STATUS |
5579 DIFF_FORMAT_CHECKDIFF)) {
5580 for (i = 0; i < q->nr; i++) {
5581 struct diff_filepair *p = q->queue[i];
5582 if (check_pair_status(p))
5583 flush_one_pair(p, options);
5585 separator++;
5588 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
5589 dirstat_by_line = 1;
5591 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
5592 dirstat_by_line) {
5593 struct diffstat_t diffstat;
5595 memset(&diffstat, 0, sizeof(struct diffstat_t));
5596 for (i = 0; i < q->nr; i++) {
5597 struct diff_filepair *p = q->queue[i];
5598 if (check_pair_status(p))
5599 diff_flush_stat(p, options, &diffstat);
5601 if (output_format & DIFF_FORMAT_NUMSTAT)
5602 show_numstat(&diffstat, options);
5603 if (output_format & DIFF_FORMAT_DIFFSTAT)
5604 show_stats(&diffstat, options);
5605 if (output_format & DIFF_FORMAT_SHORTSTAT)
5606 show_shortstats(&diffstat, options);
5607 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
5608 show_dirstat_by_line(&diffstat, options);
5609 free_diffstat_info(&diffstat);
5610 separator++;
5612 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
5613 show_dirstat(options);
5615 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
5616 for (i = 0; i < q->nr; i++) {
5617 diff_summary(options, q->queue[i]);
5619 separator++;
5622 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
5623 options->flags.exit_with_status &&
5624 options->flags.diff_from_contents) {
5626 * run diff_flush_patch for the exit status. setting
5627 * options->file to /dev/null should be safe, because we
5628 * aren't supposed to produce any output anyway.
5630 if (options->close_file)
5631 fclose(options->file);
5632 options->file = xfopen("/dev/null", "w");
5633 options->close_file = 1;
5634 options->color_moved = 0;
5635 for (i = 0; i < q->nr; i++) {
5636 struct diff_filepair *p = q->queue[i];
5637 if (check_pair_status(p))
5638 diff_flush_patch(p, options);
5639 if (options->found_changes)
5640 break;
5644 if (output_format & DIFF_FORMAT_PATCH) {
5645 if (separator) {
5646 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
5647 if (options->stat_sep)
5648 /* attach patch instead of inline */
5649 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
5650 NULL, 0, 0);
5653 diff_flush_patch_all_file_pairs(options);
5656 if (output_format & DIFF_FORMAT_CALLBACK)
5657 options->format_callback(q, options, options->format_callback_data);
5659 for (i = 0; i < q->nr; i++)
5660 diff_free_filepair(q->queue[i]);
5661 free_queue:
5662 free(q->queue);
5663 DIFF_QUEUE_CLEAR(q);
5664 if (options->close_file)
5665 fclose(options->file);
5668 * Report the content-level differences with HAS_CHANGES;
5669 * diff_addremove/diff_change does not set the bit when
5670 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
5672 if (options->flags.diff_from_contents) {
5673 if (options->found_changes)
5674 options->flags.has_changes = 1;
5675 else
5676 options->flags.has_changes = 0;
5680 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
5682 return (((p->status == DIFF_STATUS_MODIFIED) &&
5683 ((p->score &&
5684 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
5685 (!p->score &&
5686 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
5687 ((p->status != DIFF_STATUS_MODIFIED) &&
5688 filter_bit_tst(p->status, options)));
5691 static void diffcore_apply_filter(struct diff_options *options)
5693 int i;
5694 struct diff_queue_struct *q = &diff_queued_diff;
5695 struct diff_queue_struct outq;
5697 DIFF_QUEUE_CLEAR(&outq);
5699 if (!options->filter)
5700 return;
5702 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
5703 int found;
5704 for (i = found = 0; !found && i < q->nr; i++) {
5705 if (match_filter(options, q->queue[i]))
5706 found++;
5708 if (found)
5709 return;
5711 /* otherwise we will clear the whole queue
5712 * by copying the empty outq at the end of this
5713 * function, but first clear the current entries
5714 * in the queue.
5716 for (i = 0; i < q->nr; i++)
5717 diff_free_filepair(q->queue[i]);
5719 else {
5720 /* Only the matching ones */
5721 for (i = 0; i < q->nr; i++) {
5722 struct diff_filepair *p = q->queue[i];
5723 if (match_filter(options, p))
5724 diff_q(&outq, p);
5725 else
5726 diff_free_filepair(p);
5729 free(q->queue);
5730 *q = outq;
5733 /* Check whether two filespecs with the same mode and size are identical */
5734 static int diff_filespec_is_identical(struct diff_filespec *one,
5735 struct diff_filespec *two)
5737 if (S_ISGITLINK(one->mode))
5738 return 0;
5739 if (diff_populate_filespec(one, 0))
5740 return 0;
5741 if (diff_populate_filespec(two, 0))
5742 return 0;
5743 return !memcmp(one->data, two->data, one->size);
5746 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
5748 if (p->done_skip_stat_unmatch)
5749 return p->skip_stat_unmatch_result;
5751 p->done_skip_stat_unmatch = 1;
5752 p->skip_stat_unmatch_result = 0;
5754 * 1. Entries that come from stat info dirtiness
5755 * always have both sides (iow, not create/delete),
5756 * one side of the object name is unknown, with
5757 * the same mode and size. Keep the ones that
5758 * do not match these criteria. They have real
5759 * differences.
5761 * 2. At this point, the file is known to be modified,
5762 * with the same mode and size, and the object
5763 * name of one side is unknown. Need to inspect
5764 * the identical contents.
5766 if (!DIFF_FILE_VALID(p->one) || /* (1) */
5767 !DIFF_FILE_VALID(p->two) ||
5768 (p->one->oid_valid && p->two->oid_valid) ||
5769 (p->one->mode != p->two->mode) ||
5770 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
5771 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
5772 (p->one->size != p->two->size) ||
5773 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
5774 p->skip_stat_unmatch_result = 1;
5775 return p->skip_stat_unmatch_result;
5778 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
5780 int i;
5781 struct diff_queue_struct *q = &diff_queued_diff;
5782 struct diff_queue_struct outq;
5783 DIFF_QUEUE_CLEAR(&outq);
5785 for (i = 0; i < q->nr; i++) {
5786 struct diff_filepair *p = q->queue[i];
5788 if (diff_filespec_check_stat_unmatch(p))
5789 diff_q(&outq, p);
5790 else {
5792 * The caller can subtract 1 from skip_stat_unmatch
5793 * to determine how many paths were dirty only
5794 * due to stat info mismatch.
5796 if (!diffopt->flags.no_index)
5797 diffopt->skip_stat_unmatch++;
5798 diff_free_filepair(p);
5801 free(q->queue);
5802 *q = outq;
5805 static int diffnamecmp(const void *a_, const void *b_)
5807 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
5808 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
5809 const char *name_a, *name_b;
5811 name_a = a->one ? a->one->path : a->two->path;
5812 name_b = b->one ? b->one->path : b->two->path;
5813 return strcmp(name_a, name_b);
5816 void diffcore_fix_diff_index(struct diff_options *options)
5818 struct diff_queue_struct *q = &diff_queued_diff;
5819 QSORT(q->queue, q->nr, diffnamecmp);
5822 void diffcore_std(struct diff_options *options)
5824 /* NOTE please keep the following in sync with diff_tree_combined() */
5825 if (options->skip_stat_unmatch)
5826 diffcore_skip_stat_unmatch(options);
5827 if (!options->found_follow) {
5828 /* See try_to_follow_renames() in tree-diff.c */
5829 if (options->break_opt != -1)
5830 diffcore_break(options->break_opt);
5831 if (options->detect_rename)
5832 diffcore_rename(options);
5833 if (options->break_opt != -1)
5834 diffcore_merge_broken();
5836 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
5837 diffcore_pickaxe(options);
5838 if (options->orderfile)
5839 diffcore_order(options->orderfile);
5840 if (!options->found_follow)
5841 /* See try_to_follow_renames() in tree-diff.c */
5842 diff_resolve_rename_copy();
5843 diffcore_apply_filter(options);
5845 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
5846 options->flags.has_changes = 1;
5847 else
5848 options->flags.has_changes = 0;
5850 options->found_follow = 0;
5853 int diff_result_code(struct diff_options *opt, int status)
5855 int result = 0;
5857 diff_warn_rename_limit("diff.renameLimit",
5858 opt->needed_rename_limit,
5859 opt->degraded_cc_to_c);
5860 if (!opt->flags.exit_with_status &&
5861 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
5862 return status;
5863 if (opt->flags.exit_with_status &&
5864 opt->flags.has_changes)
5865 result |= 01;
5866 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
5867 opt->flags.check_failed)
5868 result |= 02;
5869 return result;
5872 int diff_can_quit_early(struct diff_options *opt)
5874 return (opt->flags.quick &&
5875 !opt->filter &&
5876 opt->flags.has_changes);
5880 * Shall changes to this submodule be ignored?
5882 * Submodule changes can be configured to be ignored separately for each path,
5883 * but that configuration can be overridden from the command line.
5885 static int is_submodule_ignored(const char *path, struct diff_options *options)
5887 int ignored = 0;
5888 struct diff_flags orig_flags = options->flags;
5889 if (!options->flags.override_submodule_config)
5890 set_diffopt_flags_from_submodule_config(options, path);
5891 if (options->flags.ignore_submodules)
5892 ignored = 1;
5893 options->flags = orig_flags;
5894 return ignored;
5897 void diff_addremove(struct diff_options *options,
5898 int addremove, unsigned mode,
5899 const struct object_id *oid,
5900 int oid_valid,
5901 const char *concatpath, unsigned dirty_submodule)
5903 struct diff_filespec *one, *two;
5905 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
5906 return;
5908 /* This may look odd, but it is a preparation for
5909 * feeding "there are unchanged files which should
5910 * not produce diffs, but when you are doing copy
5911 * detection you would need them, so here they are"
5912 * entries to the diff-core. They will be prefixed
5913 * with something like '=' or '*' (I haven't decided
5914 * which but should not make any difference).
5915 * Feeding the same new and old to diff_change()
5916 * also has the same effect.
5917 * Before the final output happens, they are pruned after
5918 * merged into rename/copy pairs as appropriate.
5920 if (options->flags.reverse_diff)
5921 addremove = (addremove == '+' ? '-' :
5922 addremove == '-' ? '+' : addremove);
5924 if (options->prefix &&
5925 strncmp(concatpath, options->prefix, options->prefix_length))
5926 return;
5928 one = alloc_filespec(concatpath);
5929 two = alloc_filespec(concatpath);
5931 if (addremove != '+')
5932 fill_filespec(one, oid, oid_valid, mode);
5933 if (addremove != '-') {
5934 fill_filespec(two, oid, oid_valid, mode);
5935 two->dirty_submodule = dirty_submodule;
5938 diff_queue(&diff_queued_diff, one, two);
5939 if (!options->flags.diff_from_contents)
5940 options->flags.has_changes = 1;
5943 void diff_change(struct diff_options *options,
5944 unsigned old_mode, unsigned new_mode,
5945 const struct object_id *old_oid,
5946 const struct object_id *new_oid,
5947 int old_oid_valid, int new_oid_valid,
5948 const char *concatpath,
5949 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5951 struct diff_filespec *one, *two;
5952 struct diff_filepair *p;
5954 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
5955 is_submodule_ignored(concatpath, options))
5956 return;
5958 if (options->flags.reverse_diff) {
5959 SWAP(old_mode, new_mode);
5960 SWAP(old_oid, new_oid);
5961 SWAP(old_oid_valid, new_oid_valid);
5962 SWAP(old_dirty_submodule, new_dirty_submodule);
5965 if (options->prefix &&
5966 strncmp(concatpath, options->prefix, options->prefix_length))
5967 return;
5969 one = alloc_filespec(concatpath);
5970 two = alloc_filespec(concatpath);
5971 fill_filespec(one, old_oid, old_oid_valid, old_mode);
5972 fill_filespec(two, new_oid, new_oid_valid, new_mode);
5973 one->dirty_submodule = old_dirty_submodule;
5974 two->dirty_submodule = new_dirty_submodule;
5975 p = diff_queue(&diff_queued_diff, one, two);
5977 if (options->flags.diff_from_contents)
5978 return;
5980 if (options->flags.quick && options->skip_stat_unmatch &&
5981 !diff_filespec_check_stat_unmatch(p))
5982 return;
5984 options->flags.has_changes = 1;
5987 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
5989 struct diff_filepair *pair;
5990 struct diff_filespec *one, *two;
5992 if (options->prefix &&
5993 strncmp(path, options->prefix, options->prefix_length))
5994 return NULL;
5996 one = alloc_filespec(path);
5997 two = alloc_filespec(path);
5998 pair = diff_queue(&diff_queued_diff, one, two);
5999 pair->is_unmerged = 1;
6000 return pair;
6003 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
6004 size_t *outsize)
6006 struct diff_tempfile *temp;
6007 const char *argv[3];
6008 const char **arg = argv;
6009 struct child_process child = CHILD_PROCESS_INIT;
6010 struct strbuf buf = STRBUF_INIT;
6011 int err = 0;
6013 temp = prepare_temp_file(spec->path, spec);
6014 *arg++ = pgm;
6015 *arg++ = temp->name;
6016 *arg = NULL;
6018 child.use_shell = 1;
6019 child.argv = argv;
6020 child.out = -1;
6021 if (start_command(&child)) {
6022 remove_tempfile();
6023 return NULL;
6026 if (strbuf_read(&buf, child.out, 0) < 0)
6027 err = error("error reading from textconv command '%s'", pgm);
6028 close(child.out);
6030 if (finish_command(&child) || err) {
6031 strbuf_release(&buf);
6032 remove_tempfile();
6033 return NULL;
6035 remove_tempfile();
6037 return strbuf_detach(&buf, outsize);
6040 size_t fill_textconv(struct userdiff_driver *driver,
6041 struct diff_filespec *df,
6042 char **outbuf)
6044 size_t size;
6046 if (!driver) {
6047 if (!DIFF_FILE_VALID(df)) {
6048 *outbuf = "";
6049 return 0;
6051 if (diff_populate_filespec(df, 0))
6052 die("unable to read files to diff");
6053 *outbuf = df->data;
6054 return df->size;
6057 if (!driver->textconv)
6058 die("BUG: fill_textconv called with non-textconv driver");
6060 if (driver->textconv_cache && df->oid_valid) {
6061 *outbuf = notes_cache_get(driver->textconv_cache,
6062 &df->oid,
6063 &size);
6064 if (*outbuf)
6065 return size;
6068 *outbuf = run_textconv(driver->textconv, df, &size);
6069 if (!*outbuf)
6070 die("unable to read files to diff");
6072 if (driver->textconv_cache && df->oid_valid) {
6073 /* ignore errors, as we might be in a readonly repository */
6074 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6075 size);
6077 * we could save up changes and flush them all at the end,
6078 * but we would need an extra call after all diffing is done.
6079 * Since generating a cache entry is the slow path anyway,
6080 * this extra overhead probably isn't a big deal.
6082 notes_cache_write(driver->textconv_cache);
6085 return size;
6088 int textconv_object(const char *path,
6089 unsigned mode,
6090 const struct object_id *oid,
6091 int oid_valid,
6092 char **buf,
6093 unsigned long *buf_size)
6095 struct diff_filespec *df;
6096 struct userdiff_driver *textconv;
6098 df = alloc_filespec(path);
6099 fill_filespec(df, oid, oid_valid, mode);
6100 textconv = get_textconv(df);
6101 if (!textconv) {
6102 free_filespec(df);
6103 return 0;
6106 *buf_size = fill_textconv(textconv, df, buf);
6107 free_filespec(df);
6108 return 1;
6111 void setup_diff_pager(struct diff_options *opt)
6114 * If the user asked for our exit code, then either they want --quiet
6115 * or --exit-code. We should definitely not bother with a pager in the
6116 * former case, as we will generate no output. Since we still properly
6117 * report our exit code even when a pager is run, we _could_ run a
6118 * pager with --exit-code. But since we have not done so historically,
6119 * and because it is easy to find people oneline advising "git diff
6120 * --exit-code" in hooks and other scripts, we do not do so.
6122 if (!opt->flags.exit_with_status &&
6123 check_pager_config("diff") != 0)
6124 setup_pager();