tests: disallow the use of abbreviated options (by default)
[git/raj.git] / diff.c
blobec5c095199b3953cc74dabdfccf4536d4c6df831
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"
26 #include "parse-options.h"
27 #include "help.h"
29 #ifdef NO_FAST_WORKING_DIRECTORY
30 #define FAST_WORKING_DIRECTORY 0
31 #else
32 #define FAST_WORKING_DIRECTORY 1
33 #endif
35 static int diff_detect_rename_default;
36 static int diff_indent_heuristic = 1;
37 static int diff_rename_limit_default = 400;
38 static int diff_suppress_blank_empty;
39 static int diff_use_color_default = -1;
40 static int diff_color_moved_default;
41 static int diff_color_moved_ws_default;
42 static int diff_context_default = 3;
43 static int diff_interhunk_context_default;
44 static const char *diff_word_regex_cfg;
45 static const char *external_diff_cmd_cfg;
46 static const char *diff_order_file_cfg;
47 int diff_auto_refresh_index = 1;
48 static int diff_mnemonic_prefix;
49 static int diff_no_prefix;
50 static int diff_stat_graph_width;
51 static int diff_dirstat_permille_default = 30;
52 static struct diff_options default_diff_options;
53 static long diff_algorithm;
54 static unsigned ws_error_highlight_default = WSEH_NEW;
56 static char diff_colors[][COLOR_MAXLEN] = {
57 GIT_COLOR_RESET,
58 GIT_COLOR_NORMAL, /* CONTEXT */
59 GIT_COLOR_BOLD, /* METAINFO */
60 GIT_COLOR_CYAN, /* FRAGINFO */
61 GIT_COLOR_RED, /* OLD */
62 GIT_COLOR_GREEN, /* NEW */
63 GIT_COLOR_YELLOW, /* COMMIT */
64 GIT_COLOR_BG_RED, /* WHITESPACE */
65 GIT_COLOR_NORMAL, /* FUNCINFO */
66 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
67 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
68 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
69 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
70 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
71 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
72 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
73 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
74 GIT_COLOR_FAINT, /* CONTEXT_DIM */
75 GIT_COLOR_FAINT_RED, /* OLD_DIM */
76 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
77 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
78 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
79 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
82 static const char *color_diff_slots[] = {
83 [DIFF_CONTEXT] = "context",
84 [DIFF_METAINFO] = "meta",
85 [DIFF_FRAGINFO] = "frag",
86 [DIFF_FILE_OLD] = "old",
87 [DIFF_FILE_NEW] = "new",
88 [DIFF_COMMIT] = "commit",
89 [DIFF_WHITESPACE] = "whitespace",
90 [DIFF_FUNCINFO] = "func",
91 [DIFF_FILE_OLD_MOVED] = "oldMoved",
92 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
93 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
94 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
95 [DIFF_FILE_NEW_MOVED] = "newMoved",
96 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
97 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
98 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
99 [DIFF_CONTEXT_DIM] = "contextDimmed",
100 [DIFF_FILE_OLD_DIM] = "oldDimmed",
101 [DIFF_FILE_NEW_DIM] = "newDimmed",
102 [DIFF_CONTEXT_BOLD] = "contextBold",
103 [DIFF_FILE_OLD_BOLD] = "oldBold",
104 [DIFF_FILE_NEW_BOLD] = "newBold",
107 define_list_config_array_extra(color_diff_slots, {"plain"});
109 static int parse_diff_color_slot(const char *var)
111 if (!strcasecmp(var, "plain"))
112 return DIFF_CONTEXT;
113 return LOOKUP_CONFIG(color_diff_slots, var);
116 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
117 struct strbuf *errmsg)
119 char *params_copy = xstrdup(params_string);
120 struct string_list params = STRING_LIST_INIT_NODUP;
121 int ret = 0;
122 int i;
124 if (*params_copy)
125 string_list_split_in_place(&params, params_copy, ',', -1);
126 for (i = 0; i < params.nr; i++) {
127 const char *p = params.items[i].string;
128 if (!strcmp(p, "changes")) {
129 options->flags.dirstat_by_line = 0;
130 options->flags.dirstat_by_file = 0;
131 } else if (!strcmp(p, "lines")) {
132 options->flags.dirstat_by_line = 1;
133 options->flags.dirstat_by_file = 0;
134 } else if (!strcmp(p, "files")) {
135 options->flags.dirstat_by_line = 0;
136 options->flags.dirstat_by_file = 1;
137 } else if (!strcmp(p, "noncumulative")) {
138 options->flags.dirstat_cumulative = 0;
139 } else if (!strcmp(p, "cumulative")) {
140 options->flags.dirstat_cumulative = 1;
141 } else if (isdigit(*p)) {
142 char *end;
143 int permille = strtoul(p, &end, 10) * 10;
144 if (*end == '.' && isdigit(*++end)) {
145 /* only use first digit */
146 permille += *end - '0';
147 /* .. and ignore any further digits */
148 while (isdigit(*++end))
149 ; /* nothing */
151 if (!*end)
152 options->dirstat_permille = permille;
153 else {
154 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
156 ret++;
158 } else {
159 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
160 ret++;
164 string_list_clear(&params, 0);
165 free(params_copy);
166 return ret;
169 static int parse_submodule_params(struct diff_options *options, const char *value)
171 if (!strcmp(value, "log"))
172 options->submodule_format = DIFF_SUBMODULE_LOG;
173 else if (!strcmp(value, "short"))
174 options->submodule_format = DIFF_SUBMODULE_SHORT;
175 else if (!strcmp(value, "diff"))
176 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
178 * Please update $__git_diff_submodule_formats in
179 * git-completion.bash when you add new formats.
181 else
182 return -1;
183 return 0;
186 int git_config_rename(const char *var, const char *value)
188 if (!value)
189 return DIFF_DETECT_RENAME;
190 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
191 return DIFF_DETECT_COPY;
192 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
195 long parse_algorithm_value(const char *value)
197 if (!value)
198 return -1;
199 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
200 return 0;
201 else if (!strcasecmp(value, "minimal"))
202 return XDF_NEED_MINIMAL;
203 else if (!strcasecmp(value, "patience"))
204 return XDF_PATIENCE_DIFF;
205 else if (!strcasecmp(value, "histogram"))
206 return XDF_HISTOGRAM_DIFF;
208 * Please update $__git_diff_algorithms in git-completion.bash
209 * when you add new algorithms.
211 return -1;
214 static int parse_one_token(const char **arg, const char *token)
216 const char *rest;
217 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
218 *arg = rest;
219 return 1;
221 return 0;
224 static int parse_ws_error_highlight(const char *arg)
226 const char *orig_arg = arg;
227 unsigned val = 0;
229 while (*arg) {
230 if (parse_one_token(&arg, "none"))
231 val = 0;
232 else if (parse_one_token(&arg, "default"))
233 val = WSEH_NEW;
234 else if (parse_one_token(&arg, "all"))
235 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
236 else if (parse_one_token(&arg, "new"))
237 val |= WSEH_NEW;
238 else if (parse_one_token(&arg, "old"))
239 val |= WSEH_OLD;
240 else if (parse_one_token(&arg, "context"))
241 val |= WSEH_CONTEXT;
242 else {
243 return -1 - (int)(arg - orig_arg);
245 if (*arg)
246 arg++;
248 return val;
252 * These are to give UI layer defaults.
253 * The core-level commands such as git-diff-files should
254 * never be affected by the setting of diff.renames
255 * the user happens to have in the configuration file.
257 void init_diff_ui_defaults(void)
259 diff_detect_rename_default = DIFF_DETECT_RENAME;
262 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
264 if (!strcmp(var, "diff.indentheuristic"))
265 diff_indent_heuristic = git_config_bool(var, value);
266 return 0;
269 static int parse_color_moved(const char *arg)
271 switch (git_parse_maybe_bool(arg)) {
272 case 0:
273 return COLOR_MOVED_NO;
274 case 1:
275 return COLOR_MOVED_DEFAULT;
276 default:
277 break;
280 if (!strcmp(arg, "no"))
281 return COLOR_MOVED_NO;
282 else if (!strcmp(arg, "plain"))
283 return COLOR_MOVED_PLAIN;
284 else if (!strcmp(arg, "blocks"))
285 return COLOR_MOVED_BLOCKS;
286 else if (!strcmp(arg, "zebra"))
287 return COLOR_MOVED_ZEBRA;
288 else if (!strcmp(arg, "default"))
289 return COLOR_MOVED_DEFAULT;
290 else if (!strcmp(arg, "dimmed-zebra"))
291 return COLOR_MOVED_ZEBRA_DIM;
292 else if (!strcmp(arg, "dimmed_zebra"))
293 return COLOR_MOVED_ZEBRA_DIM;
294 else
295 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
298 static unsigned parse_color_moved_ws(const char *arg)
300 int ret = 0;
301 struct string_list l = STRING_LIST_INIT_DUP;
302 struct string_list_item *i;
304 string_list_split(&l, arg, ',', -1);
306 for_each_string_list_item(i, &l) {
307 struct strbuf sb = STRBUF_INIT;
308 strbuf_addstr(&sb, i->string);
309 strbuf_trim(&sb);
311 if (!strcmp(sb.buf, "no"))
312 ret = 0;
313 else if (!strcmp(sb.buf, "ignore-space-change"))
314 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
315 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
316 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
317 else if (!strcmp(sb.buf, "ignore-all-space"))
318 ret |= XDF_IGNORE_WHITESPACE;
319 else if (!strcmp(sb.buf, "allow-indentation-change"))
320 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
321 else {
322 ret |= COLOR_MOVED_WS_ERROR;
323 error(_("unknown color-moved-ws mode '%s', possible values are 'ignore-space-change', 'ignore-space-at-eol', 'ignore-all-space', 'allow-indentation-change'"), sb.buf);
326 strbuf_release(&sb);
329 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
330 (ret & XDF_WHITESPACE_FLAGS)) {
331 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
332 ret |= COLOR_MOVED_WS_ERROR;
335 string_list_clear(&l, 0);
337 return ret;
340 int git_diff_ui_config(const char *var, const char *value, void *cb)
342 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
343 diff_use_color_default = git_config_colorbool(var, value);
344 return 0;
346 if (!strcmp(var, "diff.colormoved")) {
347 int cm = parse_color_moved(value);
348 if (cm < 0)
349 return -1;
350 diff_color_moved_default = cm;
351 return 0;
353 if (!strcmp(var, "diff.colormovedws")) {
354 unsigned cm = parse_color_moved_ws(value);
355 if (cm & COLOR_MOVED_WS_ERROR)
356 return -1;
357 diff_color_moved_ws_default = cm;
358 return 0;
360 if (!strcmp(var, "diff.context")) {
361 diff_context_default = git_config_int(var, value);
362 if (diff_context_default < 0)
363 return -1;
364 return 0;
366 if (!strcmp(var, "diff.interhunkcontext")) {
367 diff_interhunk_context_default = git_config_int(var, value);
368 if (diff_interhunk_context_default < 0)
369 return -1;
370 return 0;
372 if (!strcmp(var, "diff.renames")) {
373 diff_detect_rename_default = git_config_rename(var, value);
374 return 0;
376 if (!strcmp(var, "diff.autorefreshindex")) {
377 diff_auto_refresh_index = git_config_bool(var, value);
378 return 0;
380 if (!strcmp(var, "diff.mnemonicprefix")) {
381 diff_mnemonic_prefix = git_config_bool(var, value);
382 return 0;
384 if (!strcmp(var, "diff.noprefix")) {
385 diff_no_prefix = git_config_bool(var, value);
386 return 0;
388 if (!strcmp(var, "diff.statgraphwidth")) {
389 diff_stat_graph_width = git_config_int(var, value);
390 return 0;
392 if (!strcmp(var, "diff.external"))
393 return git_config_string(&external_diff_cmd_cfg, var, value);
394 if (!strcmp(var, "diff.wordregex"))
395 return git_config_string(&diff_word_regex_cfg, var, value);
396 if (!strcmp(var, "diff.orderfile"))
397 return git_config_pathname(&diff_order_file_cfg, var, value);
399 if (!strcmp(var, "diff.ignoresubmodules"))
400 handle_ignore_submodules_arg(&default_diff_options, value);
402 if (!strcmp(var, "diff.submodule")) {
403 if (parse_submodule_params(&default_diff_options, value))
404 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
405 value);
406 return 0;
409 if (!strcmp(var, "diff.algorithm")) {
410 diff_algorithm = parse_algorithm_value(value);
411 if (diff_algorithm < 0)
412 return -1;
413 return 0;
416 if (!strcmp(var, "diff.wserrorhighlight")) {
417 int val = parse_ws_error_highlight(value);
418 if (val < 0)
419 return -1;
420 ws_error_highlight_default = val;
421 return 0;
424 if (git_color_config(var, value, cb) < 0)
425 return -1;
427 return git_diff_basic_config(var, value, cb);
430 int git_diff_basic_config(const char *var, const char *value, void *cb)
432 const char *name;
434 if (!strcmp(var, "diff.renamelimit")) {
435 diff_rename_limit_default = git_config_int(var, value);
436 return 0;
439 if (userdiff_config(var, value) < 0)
440 return -1;
442 if (skip_prefix(var, "diff.color.", &name) ||
443 skip_prefix(var, "color.diff.", &name)) {
444 int slot = parse_diff_color_slot(name);
445 if (slot < 0)
446 return 0;
447 if (!value)
448 return config_error_nonbool(var);
449 return color_parse(value, diff_colors[slot]);
452 /* like GNU diff's --suppress-blank-empty option */
453 if (!strcmp(var, "diff.suppressblankempty") ||
454 /* for backwards compatibility */
455 !strcmp(var, "diff.suppress-blank-empty")) {
456 diff_suppress_blank_empty = git_config_bool(var, value);
457 return 0;
460 if (!strcmp(var, "diff.dirstat")) {
461 struct strbuf errmsg = STRBUF_INIT;
462 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
463 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
464 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
465 errmsg.buf);
466 strbuf_release(&errmsg);
467 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
468 return 0;
471 if (git_diff_heuristic_config(var, value, cb) < 0)
472 return -1;
474 return git_default_config(var, value, cb);
477 static char *quote_two(const char *one, const char *two)
479 int need_one = quote_c_style(one, NULL, NULL, 1);
480 int need_two = quote_c_style(two, NULL, NULL, 1);
481 struct strbuf res = STRBUF_INIT;
483 if (need_one + need_two) {
484 strbuf_addch(&res, '"');
485 quote_c_style(one, &res, NULL, 1);
486 quote_c_style(two, &res, NULL, 1);
487 strbuf_addch(&res, '"');
488 } else {
489 strbuf_addstr(&res, one);
490 strbuf_addstr(&res, two);
492 return strbuf_detach(&res, NULL);
495 static const char *external_diff(void)
497 static const char *external_diff_cmd = NULL;
498 static int done_preparing = 0;
500 if (done_preparing)
501 return external_diff_cmd;
502 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
503 if (!external_diff_cmd)
504 external_diff_cmd = external_diff_cmd_cfg;
505 done_preparing = 1;
506 return external_diff_cmd;
510 * Keep track of files used for diffing. Sometimes such an entry
511 * refers to a temporary file, sometimes to an existing file, and
512 * sometimes to "/dev/null".
514 static struct diff_tempfile {
516 * filename external diff should read from, or NULL if this
517 * entry is currently not in use:
519 const char *name;
521 char hex[GIT_MAX_HEXSZ + 1];
522 char mode[10];
525 * If this diff_tempfile instance refers to a temporary file,
526 * this tempfile object is used to manage its lifetime.
528 struct tempfile *tempfile;
529 } diff_temp[2];
531 struct emit_callback {
532 int color_diff;
533 unsigned ws_rule;
534 int blank_at_eof_in_preimage;
535 int blank_at_eof_in_postimage;
536 int lno_in_preimage;
537 int lno_in_postimage;
538 const char **label_path;
539 struct diff_words_data *diff_words;
540 struct diff_options *opt;
541 struct strbuf *header;
544 static int count_lines(const char *data, int size)
546 int count, ch, completely_empty = 1, nl_just_seen = 0;
547 count = 0;
548 while (0 < size--) {
549 ch = *data++;
550 if (ch == '\n') {
551 count++;
552 nl_just_seen = 1;
553 completely_empty = 0;
555 else {
556 nl_just_seen = 0;
557 completely_empty = 0;
560 if (completely_empty)
561 return 0;
562 if (!nl_just_seen)
563 count++; /* no trailing newline */
564 return count;
567 static int fill_mmfile(struct repository *r, mmfile_t *mf,
568 struct diff_filespec *one)
570 if (!DIFF_FILE_VALID(one)) {
571 mf->ptr = (char *)""; /* does not matter */
572 mf->size = 0;
573 return 0;
575 else if (diff_populate_filespec(r, one, 0))
576 return -1;
578 mf->ptr = one->data;
579 mf->size = one->size;
580 return 0;
583 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
584 static unsigned long diff_filespec_size(struct repository *r,
585 struct diff_filespec *one)
587 if (!DIFF_FILE_VALID(one))
588 return 0;
589 diff_populate_filespec(r, one, CHECK_SIZE_ONLY);
590 return one->size;
593 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
595 char *ptr = mf->ptr;
596 long size = mf->size;
597 int cnt = 0;
599 if (!size)
600 return cnt;
601 ptr += size - 1; /* pointing at the very end */
602 if (*ptr != '\n')
603 ; /* incomplete line */
604 else
605 ptr--; /* skip the last LF */
606 while (mf->ptr < ptr) {
607 char *prev_eol;
608 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
609 if (*prev_eol == '\n')
610 break;
611 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
612 break;
613 cnt++;
614 ptr = prev_eol - 1;
616 return cnt;
619 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
620 struct emit_callback *ecbdata)
622 int l1, l2, at;
623 unsigned ws_rule = ecbdata->ws_rule;
624 l1 = count_trailing_blank(mf1, ws_rule);
625 l2 = count_trailing_blank(mf2, ws_rule);
626 if (l2 <= l1) {
627 ecbdata->blank_at_eof_in_preimage = 0;
628 ecbdata->blank_at_eof_in_postimage = 0;
629 return;
631 at = count_lines(mf1->ptr, mf1->size);
632 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
634 at = count_lines(mf2->ptr, mf2->size);
635 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
638 static void emit_line_0(struct diff_options *o,
639 const char *set_sign, const char *set, unsigned reverse, const char *reset,
640 int first, const char *line, int len)
642 int has_trailing_newline, has_trailing_carriage_return;
643 int needs_reset = 0; /* at the end of the line */
644 FILE *file = o->file;
646 fputs(diff_line_prefix(o), file);
648 has_trailing_newline = (len > 0 && line[len-1] == '\n');
649 if (has_trailing_newline)
650 len--;
652 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
653 if (has_trailing_carriage_return)
654 len--;
656 if (!len && !first)
657 goto end_of_line;
659 if (reverse && want_color(o->use_color)) {
660 fputs(GIT_COLOR_REVERSE, file);
661 needs_reset = 1;
664 if (set_sign) {
665 fputs(set_sign, file);
666 needs_reset = 1;
669 if (first)
670 fputc(first, file);
672 if (!len)
673 goto end_of_line;
675 if (set) {
676 if (set_sign && set != set_sign)
677 fputs(reset, file);
678 fputs(set, file);
679 needs_reset = 1;
681 fwrite(line, len, 1, file);
682 needs_reset = 1; /* 'line' may contain color codes. */
684 end_of_line:
685 if (needs_reset)
686 fputs(reset, file);
687 if (has_trailing_carriage_return)
688 fputc('\r', file);
689 if (has_trailing_newline)
690 fputc('\n', file);
693 static void emit_line(struct diff_options *o, const char *set, const char *reset,
694 const char *line, int len)
696 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
699 enum diff_symbol {
700 DIFF_SYMBOL_BINARY_DIFF_HEADER,
701 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
702 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
703 DIFF_SYMBOL_BINARY_DIFF_BODY,
704 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
705 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
706 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
707 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
708 DIFF_SYMBOL_STATS_LINE,
709 DIFF_SYMBOL_WORD_DIFF,
710 DIFF_SYMBOL_STAT_SEP,
711 DIFF_SYMBOL_SUMMARY,
712 DIFF_SYMBOL_SUBMODULE_ADD,
713 DIFF_SYMBOL_SUBMODULE_DEL,
714 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
715 DIFF_SYMBOL_SUBMODULE_MODIFIED,
716 DIFF_SYMBOL_SUBMODULE_HEADER,
717 DIFF_SYMBOL_SUBMODULE_ERROR,
718 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
719 DIFF_SYMBOL_REWRITE_DIFF,
720 DIFF_SYMBOL_BINARY_FILES,
721 DIFF_SYMBOL_HEADER,
722 DIFF_SYMBOL_FILEPAIR_PLUS,
723 DIFF_SYMBOL_FILEPAIR_MINUS,
724 DIFF_SYMBOL_WORDS_PORCELAIN,
725 DIFF_SYMBOL_WORDS,
726 DIFF_SYMBOL_CONTEXT,
727 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
728 DIFF_SYMBOL_PLUS,
729 DIFF_SYMBOL_MINUS,
730 DIFF_SYMBOL_NO_LF_EOF,
731 DIFF_SYMBOL_CONTEXT_FRAGINFO,
732 DIFF_SYMBOL_CONTEXT_MARKER,
733 DIFF_SYMBOL_SEPARATOR
736 * Flags for content lines:
737 * 0..12 are whitespace rules
738 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
739 * 16 is marking if the line is blank at EOF
741 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
742 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
743 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
744 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
745 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
748 * This struct is used when we need to buffer the output of the diff output.
750 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
751 * into the pre/post image file. This pointer could be a union with the
752 * line pointer. By storing an offset into the file instead of the literal line,
753 * we can decrease the memory footprint for the buffered output. At first we
754 * may want to only have indirection for the content lines, but we could also
755 * enhance the state for emitting prefabricated lines, e.g. the similarity
756 * score line or hunk/file headers would only need to store a number or path
757 * and then the output can be constructed later on depending on state.
759 struct emitted_diff_symbol {
760 const char *line;
761 int len;
762 int flags;
763 int indent_off; /* Offset to first non-whitespace character */
764 int indent_width; /* The visual width of the indentation */
765 enum diff_symbol s;
767 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
769 struct emitted_diff_symbols {
770 struct emitted_diff_symbol *buf;
771 int nr, alloc;
773 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
775 static void append_emitted_diff_symbol(struct diff_options *o,
776 struct emitted_diff_symbol *e)
778 struct emitted_diff_symbol *f;
780 ALLOC_GROW(o->emitted_symbols->buf,
781 o->emitted_symbols->nr + 1,
782 o->emitted_symbols->alloc);
783 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
785 memcpy(f, e, sizeof(struct emitted_diff_symbol));
786 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
789 struct moved_entry {
790 struct hashmap_entry ent;
791 const struct emitted_diff_symbol *es;
792 struct moved_entry *next_line;
795 struct moved_block {
796 struct moved_entry *match;
797 int wsd; /* The whitespace delta of this block */
800 static void moved_block_clear(struct moved_block *b)
802 memset(b, 0, sizeof(*b));
805 #define INDENT_BLANKLINE INT_MIN
807 static void fill_es_indent_data(struct emitted_diff_symbol *es)
809 unsigned int off = 0, i;
810 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
811 const char *s = es->line;
812 const int len = es->len;
814 /* skip any \v \f \r at start of indentation */
815 while (s[off] == '\f' || s[off] == '\v' ||
816 (s[off] == '\r' && off < len - 1))
817 off++;
819 /* calculate the visual width of indentation */
820 while(1) {
821 if (s[off] == ' ') {
822 width++;
823 off++;
824 } else if (s[off] == '\t') {
825 width += tab_width - (width % tab_width);
826 while (s[++off] == '\t')
827 width += tab_width;
828 } else {
829 break;
833 /* check if this line is blank */
834 for (i = off; i < len; i++)
835 if (!isspace(s[i]))
836 break;
838 if (i == len) {
839 es->indent_width = INDENT_BLANKLINE;
840 es->indent_off = len;
841 } else {
842 es->indent_off = off;
843 es->indent_width = width;
847 static int compute_ws_delta(const struct emitted_diff_symbol *a,
848 const struct emitted_diff_symbol *b,
849 int *out)
851 int a_len = a->len,
852 b_len = b->len,
853 a_off = a->indent_off,
854 a_width = a->indent_width,
855 b_off = b->indent_off,
856 b_width = b->indent_width;
857 int delta;
859 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE) {
860 *out = INDENT_BLANKLINE;
861 return 1;
864 if (a->s == DIFF_SYMBOL_PLUS)
865 delta = a_width - b_width;
866 else
867 delta = b_width - a_width;
869 if (a_len - a_off != b_len - b_off ||
870 memcmp(a->line + a_off, b->line + b_off, a_len - a_off))
871 return 0;
873 *out = delta;
875 return 1;
878 static int cmp_in_block_with_wsd(const struct diff_options *o,
879 const struct moved_entry *cur,
880 const struct moved_entry *match,
881 struct moved_block *pmb,
882 int n)
884 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
885 int al = cur->es->len, bl = match->es->len, cl = l->len;
886 const char *a = cur->es->line,
887 *b = match->es->line,
888 *c = l->line;
889 int a_off = cur->es->indent_off,
890 a_width = cur->es->indent_width,
891 c_off = l->indent_off,
892 c_width = l->indent_width;
893 int delta;
896 * We need to check if 'cur' is equal to 'match'. As those
897 * are from the same (+/-) side, we do not need to adjust for
898 * indent changes. However these were found using fuzzy
899 * matching so we do have to check if they are equal. Here we
900 * just check the lengths. We delay calling memcmp() to check
901 * the contents until later as if the length comparison for a
902 * and c fails we can avoid the call all together.
904 if (al != bl)
905 return 1;
907 /* If 'l' and 'cur' are both blank then they match. */
908 if (a_width == INDENT_BLANKLINE && c_width == INDENT_BLANKLINE)
909 return 0;
912 * The indent changes of the block are known and stored in pmb->wsd;
913 * however we need to check if the indent changes of the current line
914 * match those of the current block and that the text of 'l' and 'cur'
915 * after the indentation match.
917 if (cur->es->s == DIFF_SYMBOL_PLUS)
918 delta = a_width - c_width;
919 else
920 delta = c_width - a_width;
923 * If the previous lines of this block were all blank then set its
924 * whitespace delta.
926 if (pmb->wsd == INDENT_BLANKLINE)
927 pmb->wsd = delta;
929 return !(delta == pmb->wsd && al - a_off == cl - c_off &&
930 !memcmp(a, b, al) && !
931 memcmp(a + a_off, c + c_off, al - a_off));
934 static int moved_entry_cmp(const void *hashmap_cmp_fn_data,
935 const void *entry,
936 const void *entry_or_key,
937 const void *keydata)
939 const struct diff_options *diffopt = hashmap_cmp_fn_data;
940 const struct moved_entry *a = entry;
941 const struct moved_entry *b = entry_or_key;
942 unsigned flags = diffopt->color_moved_ws_handling
943 & XDF_WHITESPACE_FLAGS;
945 if (diffopt->color_moved_ws_handling &
946 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
948 * As there is not specific white space config given,
949 * we'd need to check for a new block, so ignore all
950 * white space. The setup of the white space
951 * configuration for the next block is done else where
953 flags |= XDF_IGNORE_WHITESPACE;
955 return !xdiff_compare_lines(a->es->line, a->es->len,
956 b->es->line, b->es->len,
957 flags);
960 static struct moved_entry *prepare_entry(struct diff_options *o,
961 int line_no)
963 struct moved_entry *ret = xmalloc(sizeof(*ret));
964 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
965 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
967 ret->ent.hash = xdiff_hash_string(l->line, l->len, flags);
968 ret->es = l;
969 ret->next_line = NULL;
971 return ret;
974 static void add_lines_to_move_detection(struct diff_options *o,
975 struct hashmap *add_lines,
976 struct hashmap *del_lines)
978 struct moved_entry *prev_line = NULL;
980 int n;
981 for (n = 0; n < o->emitted_symbols->nr; n++) {
982 struct hashmap *hm;
983 struct moved_entry *key;
985 switch (o->emitted_symbols->buf[n].s) {
986 case DIFF_SYMBOL_PLUS:
987 hm = add_lines;
988 break;
989 case DIFF_SYMBOL_MINUS:
990 hm = del_lines;
991 break;
992 default:
993 prev_line = NULL;
994 continue;
997 if (o->color_moved_ws_handling &
998 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
999 fill_es_indent_data(&o->emitted_symbols->buf[n]);
1000 key = prepare_entry(o, n);
1001 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
1002 prev_line->next_line = key;
1004 hashmap_add(hm, key);
1005 prev_line = key;
1009 static void pmb_advance_or_null(struct diff_options *o,
1010 struct moved_entry *match,
1011 struct hashmap *hm,
1012 struct moved_block *pmb,
1013 int pmb_nr)
1015 int i;
1016 for (i = 0; i < pmb_nr; i++) {
1017 struct moved_entry *prev = pmb[i].match;
1018 struct moved_entry *cur = (prev && prev->next_line) ?
1019 prev->next_line : NULL;
1020 if (cur && !hm->cmpfn(o, cur, match, NULL)) {
1021 pmb[i].match = cur;
1022 } else {
1023 pmb[i].match = NULL;
1028 static void pmb_advance_or_null_multi_match(struct diff_options *o,
1029 struct moved_entry *match,
1030 struct hashmap *hm,
1031 struct moved_block *pmb,
1032 int pmb_nr, int n)
1034 int i;
1035 char *got_match = xcalloc(1, pmb_nr);
1037 for (; match; match = hashmap_get_next(hm, match)) {
1038 for (i = 0; i < pmb_nr; i++) {
1039 struct moved_entry *prev = pmb[i].match;
1040 struct moved_entry *cur = (prev && prev->next_line) ?
1041 prev->next_line : NULL;
1042 if (!cur)
1043 continue;
1044 if (!cmp_in_block_with_wsd(o, cur, match, &pmb[i], n))
1045 got_match[i] |= 1;
1049 for (i = 0; i < pmb_nr; i++) {
1050 if (got_match[i]) {
1051 /* Advance to the next line */
1052 pmb[i].match = pmb[i].match->next_line;
1053 } else {
1054 moved_block_clear(&pmb[i]);
1058 free(got_match);
1061 static int shrink_potential_moved_blocks(struct moved_block *pmb,
1062 int pmb_nr)
1064 int lp, rp;
1066 /* Shrink the set of potential block to the remaining running */
1067 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
1068 while (lp < pmb_nr && pmb[lp].match)
1069 lp++;
1070 /* lp points at the first NULL now */
1072 while (rp > -1 && !pmb[rp].match)
1073 rp--;
1074 /* rp points at the last non-NULL */
1076 if (lp < pmb_nr && rp > -1 && lp < rp) {
1077 pmb[lp] = pmb[rp];
1078 memset(&pmb[rp], 0, sizeof(pmb[rp]));
1079 rp--;
1080 lp++;
1084 /* Remember the number of running sets */
1085 return rp + 1;
1089 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1091 * Otherwise, if the last block has fewer alphanumeric characters than
1092 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1093 * that block.
1095 * The last block consists of the (n - block_length)'th line up to but not
1096 * including the nth line.
1098 * Returns 0 if the last block is empty or is unset by this function, non zero
1099 * otherwise.
1101 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1102 * Think of a way to unify them.
1104 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1106 int i, alnum_count = 0;
1107 if (o->color_moved == COLOR_MOVED_PLAIN)
1108 return block_length;
1109 for (i = 1; i < block_length + 1; i++) {
1110 const char *c = o->emitted_symbols->buf[n - i].line;
1111 for (; *c; c++) {
1112 if (!isalnum(*c))
1113 continue;
1114 alnum_count++;
1115 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1116 return 1;
1119 for (i = 1; i < block_length + 1; i++)
1120 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
1121 return 0;
1124 /* Find blocks of moved code, delegate actual coloring decision to helper */
1125 static void mark_color_as_moved(struct diff_options *o,
1126 struct hashmap *add_lines,
1127 struct hashmap *del_lines)
1129 struct moved_block *pmb = NULL; /* potentially moved blocks */
1130 int pmb_nr = 0, pmb_alloc = 0;
1131 int n, flipped_block = 0, block_length = 0;
1134 for (n = 0; n < o->emitted_symbols->nr; n++) {
1135 struct hashmap *hm = NULL;
1136 struct moved_entry *key;
1137 struct moved_entry *match = NULL;
1138 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1139 enum diff_symbol last_symbol = 0;
1141 switch (l->s) {
1142 case DIFF_SYMBOL_PLUS:
1143 hm = del_lines;
1144 key = prepare_entry(o, n);
1145 match = hashmap_get(hm, key, NULL);
1146 free(key);
1147 break;
1148 case DIFF_SYMBOL_MINUS:
1149 hm = add_lines;
1150 key = prepare_entry(o, n);
1151 match = hashmap_get(hm, key, NULL);
1152 free(key);
1153 break;
1154 default:
1155 flipped_block = 0;
1158 if (!match) {
1159 int i;
1161 adjust_last_block(o, n, block_length);
1162 for(i = 0; i < pmb_nr; i++)
1163 moved_block_clear(&pmb[i]);
1164 pmb_nr = 0;
1165 block_length = 0;
1166 flipped_block = 0;
1167 last_symbol = l->s;
1168 continue;
1171 if (o->color_moved == COLOR_MOVED_PLAIN) {
1172 last_symbol = l->s;
1173 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1174 continue;
1177 if (o->color_moved_ws_handling &
1178 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1179 pmb_advance_or_null_multi_match(o, match, hm, pmb, pmb_nr, n);
1180 else
1181 pmb_advance_or_null(o, match, hm, pmb, pmb_nr);
1183 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
1185 if (pmb_nr == 0) {
1187 * The current line is the start of a new block.
1188 * Setup the set of potential blocks.
1190 for (; match; match = hashmap_get_next(hm, match)) {
1191 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1192 if (o->color_moved_ws_handling &
1193 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) {
1194 if (compute_ws_delta(l, match->es,
1195 &pmb[pmb_nr].wsd))
1196 pmb[pmb_nr++].match = match;
1197 } else {
1198 pmb[pmb_nr].wsd = 0;
1199 pmb[pmb_nr++].match = match;
1203 if (adjust_last_block(o, n, block_length) &&
1204 pmb_nr && last_symbol != l->s)
1205 flipped_block = (flipped_block + 1) % 2;
1206 else
1207 flipped_block = 0;
1209 block_length = 0;
1212 if (pmb_nr) {
1213 block_length++;
1214 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1215 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1216 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1218 last_symbol = l->s;
1220 adjust_last_block(o, n, block_length);
1222 for(n = 0; n < pmb_nr; n++)
1223 moved_block_clear(&pmb[n]);
1224 free(pmb);
1227 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1228 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1229 static void dim_moved_lines(struct diff_options *o)
1231 int n;
1232 for (n = 0; n < o->emitted_symbols->nr; n++) {
1233 struct emitted_diff_symbol *prev = (n != 0) ?
1234 &o->emitted_symbols->buf[n - 1] : NULL;
1235 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1236 struct emitted_diff_symbol *next =
1237 (n < o->emitted_symbols->nr - 1) ?
1238 &o->emitted_symbols->buf[n + 1] : NULL;
1240 /* Not a plus or minus line? */
1241 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1242 continue;
1244 /* Not a moved line? */
1245 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1246 continue;
1249 * If prev or next are not a plus or minus line,
1250 * pretend they don't exist
1252 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1253 prev->s != DIFF_SYMBOL_MINUS)
1254 prev = NULL;
1255 if (next && next->s != DIFF_SYMBOL_PLUS &&
1256 next->s != DIFF_SYMBOL_MINUS)
1257 next = NULL;
1259 /* Inside a block? */
1260 if ((prev &&
1261 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1262 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1263 (next &&
1264 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1265 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1266 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1267 continue;
1270 /* Check if we are at an interesting bound: */
1271 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1272 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1273 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1274 continue;
1275 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1276 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1277 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1278 continue;
1281 * The boundary to prev and next are not interesting,
1282 * so this line is not interesting as a whole
1284 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1288 static void emit_line_ws_markup(struct diff_options *o,
1289 const char *set_sign, const char *set,
1290 const char *reset,
1291 int sign_index, const char *line, int len,
1292 unsigned ws_rule, int blank_at_eof)
1294 const char *ws = NULL;
1295 int sign = o->output_indicators[sign_index];
1297 if (o->ws_error_highlight & ws_rule) {
1298 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1299 if (!*ws)
1300 ws = NULL;
1303 if (!ws && !set_sign)
1304 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1305 else if (!ws) {
1306 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1307 } else if (blank_at_eof)
1308 /* Blank line at EOF - paint '+' as well */
1309 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1310 else {
1311 /* Emit just the prefix, then the rest. */
1312 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1313 sign, "", 0);
1314 ws_check_emit(line, len, ws_rule,
1315 o->file, set, reset, ws);
1319 static void emit_diff_symbol_from_struct(struct diff_options *o,
1320 struct emitted_diff_symbol *eds)
1322 static const char *nneof = " No newline at end of file\n";
1323 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1324 struct strbuf sb = STRBUF_INIT;
1326 enum diff_symbol s = eds->s;
1327 const char *line = eds->line;
1328 int len = eds->len;
1329 unsigned flags = eds->flags;
1331 switch (s) {
1332 case DIFF_SYMBOL_NO_LF_EOF:
1333 context = diff_get_color_opt(o, DIFF_CONTEXT);
1334 reset = diff_get_color_opt(o, DIFF_RESET);
1335 putc('\n', o->file);
1336 emit_line_0(o, context, NULL, 0, reset, '\\',
1337 nneof, strlen(nneof));
1338 break;
1339 case DIFF_SYMBOL_SUBMODULE_HEADER:
1340 case DIFF_SYMBOL_SUBMODULE_ERROR:
1341 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1342 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1343 case DIFF_SYMBOL_SUMMARY:
1344 case DIFF_SYMBOL_STATS_LINE:
1345 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1346 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1347 emit_line(o, "", "", line, len);
1348 break;
1349 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1350 case DIFF_SYMBOL_CONTEXT_MARKER:
1351 context = diff_get_color_opt(o, DIFF_CONTEXT);
1352 reset = diff_get_color_opt(o, DIFF_RESET);
1353 emit_line(o, context, reset, line, len);
1354 break;
1355 case DIFF_SYMBOL_SEPARATOR:
1356 fprintf(o->file, "%s%c",
1357 diff_line_prefix(o),
1358 o->line_termination);
1359 break;
1360 case DIFF_SYMBOL_CONTEXT:
1361 set = diff_get_color_opt(o, DIFF_CONTEXT);
1362 reset = diff_get_color_opt(o, DIFF_RESET);
1363 set_sign = NULL;
1364 if (o->flags.dual_color_diffed_diffs) {
1365 char c = !len ? 0 : line[0];
1367 if (c == '+')
1368 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1369 else if (c == '@')
1370 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1371 else if (c == '-')
1372 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1374 emit_line_ws_markup(o, set_sign, set, reset,
1375 OUTPUT_INDICATOR_CONTEXT, line, len,
1376 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1377 break;
1378 case DIFF_SYMBOL_PLUS:
1379 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1380 DIFF_SYMBOL_MOVED_LINE_ALT |
1381 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1382 case DIFF_SYMBOL_MOVED_LINE |
1383 DIFF_SYMBOL_MOVED_LINE_ALT |
1384 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1385 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1386 break;
1387 case DIFF_SYMBOL_MOVED_LINE |
1388 DIFF_SYMBOL_MOVED_LINE_ALT:
1389 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1390 break;
1391 case DIFF_SYMBOL_MOVED_LINE |
1392 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1393 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1394 break;
1395 case DIFF_SYMBOL_MOVED_LINE:
1396 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1397 break;
1398 default:
1399 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1401 reset = diff_get_color_opt(o, DIFF_RESET);
1402 if (!o->flags.dual_color_diffed_diffs)
1403 set_sign = NULL;
1404 else {
1405 char c = !len ? 0 : line[0];
1407 set_sign = set;
1408 if (c == '-')
1409 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1410 else if (c == '@')
1411 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1412 else if (c == '+')
1413 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1414 else
1415 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1416 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1418 emit_line_ws_markup(o, set_sign, set, reset,
1419 OUTPUT_INDICATOR_NEW, line, len,
1420 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1421 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1422 break;
1423 case DIFF_SYMBOL_MINUS:
1424 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1425 DIFF_SYMBOL_MOVED_LINE_ALT |
1426 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1427 case DIFF_SYMBOL_MOVED_LINE |
1428 DIFF_SYMBOL_MOVED_LINE_ALT |
1429 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1430 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1431 break;
1432 case DIFF_SYMBOL_MOVED_LINE |
1433 DIFF_SYMBOL_MOVED_LINE_ALT:
1434 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1435 break;
1436 case DIFF_SYMBOL_MOVED_LINE |
1437 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1438 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1439 break;
1440 case DIFF_SYMBOL_MOVED_LINE:
1441 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1442 break;
1443 default:
1444 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1446 reset = diff_get_color_opt(o, DIFF_RESET);
1447 if (!o->flags.dual_color_diffed_diffs)
1448 set_sign = NULL;
1449 else {
1450 char c = !len ? 0 : line[0];
1452 set_sign = set;
1453 if (c == '+')
1454 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1455 else if (c == '@')
1456 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1457 else if (c == '-')
1458 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1459 else
1460 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1462 emit_line_ws_markup(o, set_sign, set, reset,
1463 OUTPUT_INDICATOR_OLD, line, len,
1464 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1465 break;
1466 case DIFF_SYMBOL_WORDS_PORCELAIN:
1467 context = diff_get_color_opt(o, DIFF_CONTEXT);
1468 reset = diff_get_color_opt(o, DIFF_RESET);
1469 emit_line(o, context, reset, line, len);
1470 fputs("~\n", o->file);
1471 break;
1472 case DIFF_SYMBOL_WORDS:
1473 context = diff_get_color_opt(o, DIFF_CONTEXT);
1474 reset = diff_get_color_opt(o, DIFF_RESET);
1476 * Skip the prefix character, if any. With
1477 * diff_suppress_blank_empty, there may be
1478 * none.
1480 if (line[0] != '\n') {
1481 line++;
1482 len--;
1484 emit_line(o, context, reset, line, len);
1485 break;
1486 case DIFF_SYMBOL_FILEPAIR_PLUS:
1487 meta = diff_get_color_opt(o, DIFF_METAINFO);
1488 reset = diff_get_color_opt(o, DIFF_RESET);
1489 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1490 line, reset,
1491 strchr(line, ' ') ? "\t" : "");
1492 break;
1493 case DIFF_SYMBOL_FILEPAIR_MINUS:
1494 meta = diff_get_color_opt(o, DIFF_METAINFO);
1495 reset = diff_get_color_opt(o, DIFF_RESET);
1496 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1497 line, reset,
1498 strchr(line, ' ') ? "\t" : "");
1499 break;
1500 case DIFF_SYMBOL_BINARY_FILES:
1501 case DIFF_SYMBOL_HEADER:
1502 fprintf(o->file, "%s", line);
1503 break;
1504 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1505 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1506 break;
1507 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1508 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1509 break;
1510 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1511 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1512 break;
1513 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1514 fputs(diff_line_prefix(o), o->file);
1515 fputc('\n', o->file);
1516 break;
1517 case DIFF_SYMBOL_REWRITE_DIFF:
1518 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1519 reset = diff_get_color_opt(o, DIFF_RESET);
1520 emit_line(o, fraginfo, reset, line, len);
1521 break;
1522 case DIFF_SYMBOL_SUBMODULE_ADD:
1523 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1524 reset = diff_get_color_opt(o, DIFF_RESET);
1525 emit_line(o, set, reset, line, len);
1526 break;
1527 case DIFF_SYMBOL_SUBMODULE_DEL:
1528 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1529 reset = diff_get_color_opt(o, DIFF_RESET);
1530 emit_line(o, set, reset, line, len);
1531 break;
1532 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1533 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1534 diff_line_prefix(o), line);
1535 break;
1536 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1537 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1538 diff_line_prefix(o), line);
1539 break;
1540 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1541 emit_line(o, "", "", " 0 files changed\n",
1542 strlen(" 0 files changed\n"));
1543 break;
1544 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1545 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1546 break;
1547 case DIFF_SYMBOL_WORD_DIFF:
1548 fprintf(o->file, "%.*s", len, line);
1549 break;
1550 case DIFF_SYMBOL_STAT_SEP:
1551 fputs(o->stat_sep, o->file);
1552 break;
1553 default:
1554 BUG("unknown diff symbol");
1556 strbuf_release(&sb);
1559 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1560 const char *line, int len, unsigned flags)
1562 struct emitted_diff_symbol e = {line, len, flags, 0, 0, s};
1564 if (o->emitted_symbols)
1565 append_emitted_diff_symbol(o, &e);
1566 else
1567 emit_diff_symbol_from_struct(o, &e);
1570 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1572 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1575 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1577 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1580 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1582 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1583 path, strlen(path), 0);
1586 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1588 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1589 path, strlen(path), 0);
1592 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1594 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1595 header, strlen(header), 0);
1598 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1600 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1603 void diff_emit_submodule_pipethrough(struct diff_options *o,
1604 const char *line, int len)
1606 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1609 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1611 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1612 ecbdata->blank_at_eof_in_preimage &&
1613 ecbdata->blank_at_eof_in_postimage &&
1614 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1615 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1616 return 0;
1617 return ws_blank_line(line, len, ecbdata->ws_rule);
1620 static void emit_add_line(struct emit_callback *ecbdata,
1621 const char *line, int len)
1623 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1624 if (new_blank_line_at_eof(ecbdata, line, len))
1625 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1627 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1630 static void emit_del_line(struct emit_callback *ecbdata,
1631 const char *line, int len)
1633 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1634 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1637 static void emit_context_line(struct emit_callback *ecbdata,
1638 const char *line, int len)
1640 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1641 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1644 static void emit_hunk_header(struct emit_callback *ecbdata,
1645 const char *line, int len)
1647 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1648 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1649 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1650 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1651 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1652 static const char atat[2] = { '@', '@' };
1653 const char *cp, *ep;
1654 struct strbuf msgbuf = STRBUF_INIT;
1655 int org_len = len;
1656 int i = 1;
1659 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1660 * it always is at least 10 bytes long.
1662 if (len < 10 ||
1663 memcmp(line, atat, 2) ||
1664 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1665 emit_diff_symbol(ecbdata->opt,
1666 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1667 return;
1669 ep += 2; /* skip over @@ */
1671 /* The hunk header in fraginfo color */
1672 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1673 strbuf_addstr(&msgbuf, reverse);
1674 strbuf_addstr(&msgbuf, frag);
1675 strbuf_add(&msgbuf, line, ep - line);
1676 strbuf_addstr(&msgbuf, reset);
1679 * trailing "\r\n"
1681 for ( ; i < 3; i++)
1682 if (line[len - i] == '\r' || line[len - i] == '\n')
1683 len--;
1685 /* blank before the func header */
1686 for (cp = ep; ep - line < len; ep++)
1687 if (*ep != ' ' && *ep != '\t')
1688 break;
1689 if (ep != cp) {
1690 strbuf_addstr(&msgbuf, context);
1691 strbuf_add(&msgbuf, cp, ep - cp);
1692 strbuf_addstr(&msgbuf, reset);
1695 if (ep < line + len) {
1696 strbuf_addstr(&msgbuf, func);
1697 strbuf_add(&msgbuf, ep, line + len - ep);
1698 strbuf_addstr(&msgbuf, reset);
1701 strbuf_add(&msgbuf, line + len, org_len - len);
1702 strbuf_complete_line(&msgbuf);
1703 emit_diff_symbol(ecbdata->opt,
1704 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1705 strbuf_release(&msgbuf);
1708 static struct diff_tempfile *claim_diff_tempfile(void)
1710 int i;
1711 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1712 if (!diff_temp[i].name)
1713 return diff_temp + i;
1714 BUG("diff is failing to clean up its tempfiles");
1717 static void remove_tempfile(void)
1719 int i;
1720 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1721 if (is_tempfile_active(diff_temp[i].tempfile))
1722 delete_tempfile(&diff_temp[i].tempfile);
1723 diff_temp[i].name = NULL;
1727 static void add_line_count(struct strbuf *out, int count)
1729 switch (count) {
1730 case 0:
1731 strbuf_addstr(out, "0,0");
1732 break;
1733 case 1:
1734 strbuf_addstr(out, "1");
1735 break;
1736 default:
1737 strbuf_addf(out, "1,%d", count);
1738 break;
1742 static void emit_rewrite_lines(struct emit_callback *ecb,
1743 int prefix, const char *data, int size)
1745 const char *endp = NULL;
1747 while (0 < size) {
1748 int len;
1750 endp = memchr(data, '\n', size);
1751 len = endp ? (endp - data + 1) : size;
1752 if (prefix != '+') {
1753 ecb->lno_in_preimage++;
1754 emit_del_line(ecb, data, len);
1755 } else {
1756 ecb->lno_in_postimage++;
1757 emit_add_line(ecb, data, len);
1759 size -= len;
1760 data += len;
1762 if (!endp)
1763 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1766 static void emit_rewrite_diff(const char *name_a,
1767 const char *name_b,
1768 struct diff_filespec *one,
1769 struct diff_filespec *two,
1770 struct userdiff_driver *textconv_one,
1771 struct userdiff_driver *textconv_two,
1772 struct diff_options *o)
1774 int lc_a, lc_b;
1775 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1776 const char *a_prefix, *b_prefix;
1777 char *data_one, *data_two;
1778 size_t size_one, size_two;
1779 struct emit_callback ecbdata;
1780 struct strbuf out = STRBUF_INIT;
1782 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1783 a_prefix = o->b_prefix;
1784 b_prefix = o->a_prefix;
1785 } else {
1786 a_prefix = o->a_prefix;
1787 b_prefix = o->b_prefix;
1790 name_a += (*name_a == '/');
1791 name_b += (*name_b == '/');
1793 strbuf_reset(&a_name);
1794 strbuf_reset(&b_name);
1795 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1796 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1798 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1799 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1801 memset(&ecbdata, 0, sizeof(ecbdata));
1802 ecbdata.color_diff = want_color(o->use_color);
1803 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1804 ecbdata.opt = o;
1805 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1806 mmfile_t mf1, mf2;
1807 mf1.ptr = (char *)data_one;
1808 mf2.ptr = (char *)data_two;
1809 mf1.size = size_one;
1810 mf2.size = size_two;
1811 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1813 ecbdata.lno_in_preimage = 1;
1814 ecbdata.lno_in_postimage = 1;
1816 lc_a = count_lines(data_one, size_one);
1817 lc_b = count_lines(data_two, size_two);
1819 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1820 a_name.buf, a_name.len, 0);
1821 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1822 b_name.buf, b_name.len, 0);
1824 strbuf_addstr(&out, "@@ -");
1825 if (!o->irreversible_delete)
1826 add_line_count(&out, lc_a);
1827 else
1828 strbuf_addstr(&out, "?,?");
1829 strbuf_addstr(&out, " +");
1830 add_line_count(&out, lc_b);
1831 strbuf_addstr(&out, " @@\n");
1832 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1833 strbuf_release(&out);
1835 if (lc_a && !o->irreversible_delete)
1836 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1837 if (lc_b)
1838 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1839 if (textconv_one)
1840 free((char *)data_one);
1841 if (textconv_two)
1842 free((char *)data_two);
1845 struct diff_words_buffer {
1846 mmfile_t text;
1847 unsigned long alloc;
1848 struct diff_words_orig {
1849 const char *begin, *end;
1850 } *orig;
1851 int orig_nr, orig_alloc;
1854 static void diff_words_append(char *line, unsigned long len,
1855 struct diff_words_buffer *buffer)
1857 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1858 line++;
1859 len--;
1860 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1861 buffer->text.size += len;
1862 buffer->text.ptr[buffer->text.size] = '\0';
1865 struct diff_words_style_elem {
1866 const char *prefix;
1867 const char *suffix;
1868 const char *color; /* NULL; filled in by the setup code if
1869 * color is enabled */
1872 struct diff_words_style {
1873 enum diff_words_type type;
1874 struct diff_words_style_elem new_word, old_word, ctx;
1875 const char *newline;
1878 static struct diff_words_style diff_words_styles[] = {
1879 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1880 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1881 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1884 struct diff_words_data {
1885 struct diff_words_buffer minus, plus;
1886 const char *current_plus;
1887 int last_minus;
1888 struct diff_options *opt;
1889 regex_t *word_regex;
1890 enum diff_words_type type;
1891 struct diff_words_style *style;
1894 static int fn_out_diff_words_write_helper(struct diff_options *o,
1895 struct diff_words_style_elem *st_el,
1896 const char *newline,
1897 size_t count, const char *buf)
1899 int print = 0;
1900 struct strbuf sb = STRBUF_INIT;
1902 while (count) {
1903 char *p = memchr(buf, '\n', count);
1904 if (print)
1905 strbuf_addstr(&sb, diff_line_prefix(o));
1907 if (p != buf) {
1908 const char *reset = st_el->color && *st_el->color ?
1909 GIT_COLOR_RESET : NULL;
1910 if (st_el->color && *st_el->color)
1911 strbuf_addstr(&sb, st_el->color);
1912 strbuf_addstr(&sb, st_el->prefix);
1913 strbuf_add(&sb, buf, p ? p - buf : count);
1914 strbuf_addstr(&sb, st_el->suffix);
1915 if (reset)
1916 strbuf_addstr(&sb, reset);
1918 if (!p)
1919 goto out;
1921 strbuf_addstr(&sb, newline);
1922 count -= p + 1 - buf;
1923 buf = p + 1;
1924 print = 1;
1925 if (count) {
1926 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1927 sb.buf, sb.len, 0);
1928 strbuf_reset(&sb);
1932 out:
1933 if (sb.len)
1934 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1935 sb.buf, sb.len, 0);
1936 strbuf_release(&sb);
1937 return 0;
1941 * '--color-words' algorithm can be described as:
1943 * 1. collect the minus/plus lines of a diff hunk, divided into
1944 * minus-lines and plus-lines;
1946 * 2. break both minus-lines and plus-lines into words and
1947 * place them into two mmfile_t with one word for each line;
1949 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1951 * And for the common parts of the both file, we output the plus side text.
1952 * diff_words->current_plus is used to trace the current position of the plus file
1953 * which printed. diff_words->last_minus is used to trace the last minus word
1954 * printed.
1956 * For '--graph' to work with '--color-words', we need to output the graph prefix
1957 * on each line of color words output. Generally, there are two conditions on
1958 * which we should output the prefix.
1960 * 1. diff_words->last_minus == 0 &&
1961 * diff_words->current_plus == diff_words->plus.text.ptr
1963 * that is: the plus text must start as a new line, and if there is no minus
1964 * word printed, a graph prefix must be printed.
1966 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1967 * *(diff_words->current_plus - 1) == '\n'
1969 * that is: a graph prefix must be printed following a '\n'
1971 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1973 if ((diff_words->last_minus == 0 &&
1974 diff_words->current_plus == diff_words->plus.text.ptr) ||
1975 (diff_words->current_plus > diff_words->plus.text.ptr &&
1976 *(diff_words->current_plus - 1) == '\n')) {
1977 return 1;
1978 } else {
1979 return 0;
1983 static void fn_out_diff_words_aux(void *priv,
1984 long minus_first, long minus_len,
1985 long plus_first, long plus_len,
1986 const char *func, long funclen)
1988 struct diff_words_data *diff_words = priv;
1989 struct diff_words_style *style = diff_words->style;
1990 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1991 struct diff_options *opt = diff_words->opt;
1992 const char *line_prefix;
1994 assert(opt);
1995 line_prefix = diff_line_prefix(opt);
1997 /* POSIX requires that first be decremented by one if len == 0... */
1998 if (minus_len) {
1999 minus_begin = diff_words->minus.orig[minus_first].begin;
2000 minus_end =
2001 diff_words->minus.orig[minus_first + minus_len - 1].end;
2002 } else
2003 minus_begin = minus_end =
2004 diff_words->minus.orig[minus_first].end;
2006 if (plus_len) {
2007 plus_begin = diff_words->plus.orig[plus_first].begin;
2008 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2009 } else
2010 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2012 if (color_words_output_graph_prefix(diff_words)) {
2013 fputs(line_prefix, diff_words->opt->file);
2015 if (diff_words->current_plus != plus_begin) {
2016 fn_out_diff_words_write_helper(diff_words->opt,
2017 &style->ctx, style->newline,
2018 plus_begin - diff_words->current_plus,
2019 diff_words->current_plus);
2021 if (minus_begin != minus_end) {
2022 fn_out_diff_words_write_helper(diff_words->opt,
2023 &style->old_word, style->newline,
2024 minus_end - minus_begin, minus_begin);
2026 if (plus_begin != plus_end) {
2027 fn_out_diff_words_write_helper(diff_words->opt,
2028 &style->new_word, style->newline,
2029 plus_end - plus_begin, plus_begin);
2032 diff_words->current_plus = plus_end;
2033 diff_words->last_minus = minus_first;
2036 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2037 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2038 int *begin, int *end)
2040 if (word_regex && *begin < buffer->size) {
2041 regmatch_t match[1];
2042 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2043 buffer->size - *begin, 1, match, 0)) {
2044 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2045 '\n', match[0].rm_eo - match[0].rm_so);
2046 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2047 *begin += match[0].rm_so;
2048 return *begin >= *end;
2050 return -1;
2053 /* find the next word */
2054 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2055 (*begin)++;
2056 if (*begin >= buffer->size)
2057 return -1;
2059 /* find the end of the word */
2060 *end = *begin + 1;
2061 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2062 (*end)++;
2064 return 0;
2068 * This function splits the words in buffer->text, stores the list with
2069 * newline separator into out, and saves the offsets of the original words
2070 * in buffer->orig.
2072 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2073 regex_t *word_regex)
2075 int i, j;
2076 long alloc = 0;
2078 out->size = 0;
2079 out->ptr = NULL;
2081 /* fake an empty "0th" word */
2082 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2083 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2084 buffer->orig_nr = 1;
2086 for (i = 0; i < buffer->text.size; i++) {
2087 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2088 return;
2090 /* store original boundaries */
2091 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2092 buffer->orig_alloc);
2093 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2094 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2095 buffer->orig_nr++;
2097 /* store one word */
2098 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2099 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2100 out->ptr[out->size + j - i] = '\n';
2101 out->size += j - i + 1;
2103 i = j - 1;
2107 /* this executes the word diff on the accumulated buffers */
2108 static void diff_words_show(struct diff_words_data *diff_words)
2110 xpparam_t xpp;
2111 xdemitconf_t xecfg;
2112 mmfile_t minus, plus;
2113 struct diff_words_style *style = diff_words->style;
2115 struct diff_options *opt = diff_words->opt;
2116 const char *line_prefix;
2118 assert(opt);
2119 line_prefix = diff_line_prefix(opt);
2121 /* special case: only removal */
2122 if (!diff_words->plus.text.size) {
2123 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2124 line_prefix, strlen(line_prefix), 0);
2125 fn_out_diff_words_write_helper(diff_words->opt,
2126 &style->old_word, style->newline,
2127 diff_words->minus.text.size,
2128 diff_words->minus.text.ptr);
2129 diff_words->minus.text.size = 0;
2130 return;
2133 diff_words->current_plus = diff_words->plus.text.ptr;
2134 diff_words->last_minus = 0;
2136 memset(&xpp, 0, sizeof(xpp));
2137 memset(&xecfg, 0, sizeof(xecfg));
2138 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2139 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2140 xpp.flags = 0;
2141 /* as only the hunk header will be parsed, we need a 0-context */
2142 xecfg.ctxlen = 0;
2143 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2144 diff_words, &xpp, &xecfg))
2145 die("unable to generate word diff");
2146 free(minus.ptr);
2147 free(plus.ptr);
2148 if (diff_words->current_plus != diff_words->plus.text.ptr +
2149 diff_words->plus.text.size) {
2150 if (color_words_output_graph_prefix(diff_words))
2151 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2152 line_prefix, strlen(line_prefix), 0);
2153 fn_out_diff_words_write_helper(diff_words->opt,
2154 &style->ctx, style->newline,
2155 diff_words->plus.text.ptr + diff_words->plus.text.size
2156 - diff_words->current_plus, diff_words->current_plus);
2158 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2161 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2162 static void diff_words_flush(struct emit_callback *ecbdata)
2164 struct diff_options *wo = ecbdata->diff_words->opt;
2166 if (ecbdata->diff_words->minus.text.size ||
2167 ecbdata->diff_words->plus.text.size)
2168 diff_words_show(ecbdata->diff_words);
2170 if (wo->emitted_symbols) {
2171 struct diff_options *o = ecbdata->opt;
2172 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2173 int i;
2176 * NEEDSWORK:
2177 * Instead of appending each, concat all words to a line?
2179 for (i = 0; i < wol->nr; i++)
2180 append_emitted_diff_symbol(o, &wol->buf[i]);
2182 for (i = 0; i < wol->nr; i++)
2183 free((void *)wol->buf[i].line);
2185 wol->nr = 0;
2189 static void diff_filespec_load_driver(struct diff_filespec *one,
2190 struct index_state *istate)
2192 /* Use already-loaded driver */
2193 if (one->driver)
2194 return;
2196 if (S_ISREG(one->mode))
2197 one->driver = userdiff_find_by_path(istate, one->path);
2199 /* Fallback to default settings */
2200 if (!one->driver)
2201 one->driver = userdiff_find_by_name("default");
2204 static const char *userdiff_word_regex(struct diff_filespec *one,
2205 struct index_state *istate)
2207 diff_filespec_load_driver(one, istate);
2208 return one->driver->word_regex;
2211 static void init_diff_words_data(struct emit_callback *ecbdata,
2212 struct diff_options *orig_opts,
2213 struct diff_filespec *one,
2214 struct diff_filespec *two)
2216 int i;
2217 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2218 memcpy(o, orig_opts, sizeof(struct diff_options));
2220 ecbdata->diff_words =
2221 xcalloc(1, sizeof(struct diff_words_data));
2222 ecbdata->diff_words->type = o->word_diff;
2223 ecbdata->diff_words->opt = o;
2225 if (orig_opts->emitted_symbols)
2226 o->emitted_symbols =
2227 xcalloc(1, sizeof(struct emitted_diff_symbols));
2229 if (!o->word_regex)
2230 o->word_regex = userdiff_word_regex(one, o->repo->index);
2231 if (!o->word_regex)
2232 o->word_regex = userdiff_word_regex(two, o->repo->index);
2233 if (!o->word_regex)
2234 o->word_regex = diff_word_regex_cfg;
2235 if (o->word_regex) {
2236 ecbdata->diff_words->word_regex = (regex_t *)
2237 xmalloc(sizeof(regex_t));
2238 if (regcomp(ecbdata->diff_words->word_regex,
2239 o->word_regex,
2240 REG_EXTENDED | REG_NEWLINE))
2241 die("invalid regular expression: %s",
2242 o->word_regex);
2244 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2245 if (o->word_diff == diff_words_styles[i].type) {
2246 ecbdata->diff_words->style =
2247 &diff_words_styles[i];
2248 break;
2251 if (want_color(o->use_color)) {
2252 struct diff_words_style *st = ecbdata->diff_words->style;
2253 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2254 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2255 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2259 static void free_diff_words_data(struct emit_callback *ecbdata)
2261 if (ecbdata->diff_words) {
2262 diff_words_flush(ecbdata);
2263 free (ecbdata->diff_words->opt->emitted_symbols);
2264 free (ecbdata->diff_words->opt);
2265 free (ecbdata->diff_words->minus.text.ptr);
2266 free (ecbdata->diff_words->minus.orig);
2267 free (ecbdata->diff_words->plus.text.ptr);
2268 free (ecbdata->diff_words->plus.orig);
2269 if (ecbdata->diff_words->word_regex) {
2270 regfree(ecbdata->diff_words->word_regex);
2271 free(ecbdata->diff_words->word_regex);
2273 FREE_AND_NULL(ecbdata->diff_words);
2277 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2279 if (want_color(diff_use_color))
2280 return diff_colors[ix];
2281 return "";
2284 const char *diff_line_prefix(struct diff_options *opt)
2286 struct strbuf *msgbuf;
2287 if (!opt->output_prefix)
2288 return "";
2290 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2291 return msgbuf->buf;
2294 static unsigned long sane_truncate_line(char *line, unsigned long len)
2296 const char *cp;
2297 unsigned long allot;
2298 size_t l = len;
2300 cp = line;
2301 allot = l;
2302 while (0 < l) {
2303 (void) utf8_width(&cp, &l);
2304 if (!cp)
2305 break; /* truncated in the middle? */
2307 return allot - l;
2310 static void find_lno(const char *line, struct emit_callback *ecbdata)
2312 const char *p;
2313 ecbdata->lno_in_preimage = 0;
2314 ecbdata->lno_in_postimage = 0;
2315 p = strchr(line, '-');
2316 if (!p)
2317 return; /* cannot happen */
2318 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2319 p = strchr(p, '+');
2320 if (!p)
2321 return; /* cannot happen */
2322 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2325 static void fn_out_consume(void *priv, char *line, unsigned long len)
2327 struct emit_callback *ecbdata = priv;
2328 struct diff_options *o = ecbdata->opt;
2330 o->found_changes = 1;
2332 if (ecbdata->header) {
2333 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2334 ecbdata->header->buf, ecbdata->header->len, 0);
2335 strbuf_reset(ecbdata->header);
2336 ecbdata->header = NULL;
2339 if (ecbdata->label_path[0]) {
2340 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2341 ecbdata->label_path[0],
2342 strlen(ecbdata->label_path[0]), 0);
2343 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2344 ecbdata->label_path[1],
2345 strlen(ecbdata->label_path[1]), 0);
2346 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2349 if (diff_suppress_blank_empty
2350 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2351 line[0] = '\n';
2352 len = 1;
2355 if (line[0] == '@') {
2356 if (ecbdata->diff_words)
2357 diff_words_flush(ecbdata);
2358 len = sane_truncate_line(line, len);
2359 find_lno(line, ecbdata);
2360 emit_hunk_header(ecbdata, line, len);
2361 return;
2364 if (ecbdata->diff_words) {
2365 enum diff_symbol s =
2366 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2367 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2368 if (line[0] == '-') {
2369 diff_words_append(line, len,
2370 &ecbdata->diff_words->minus);
2371 return;
2372 } else if (line[0] == '+') {
2373 diff_words_append(line, len,
2374 &ecbdata->diff_words->plus);
2375 return;
2376 } else if (starts_with(line, "\\ ")) {
2378 * Eat the "no newline at eof" marker as if we
2379 * saw a "+" or "-" line with nothing on it,
2380 * and return without diff_words_flush() to
2381 * defer processing. If this is the end of
2382 * preimage, more "+" lines may come after it.
2384 return;
2386 diff_words_flush(ecbdata);
2387 emit_diff_symbol(o, s, line, len, 0);
2388 return;
2391 switch (line[0]) {
2392 case '+':
2393 ecbdata->lno_in_postimage++;
2394 emit_add_line(ecbdata, line + 1, len - 1);
2395 break;
2396 case '-':
2397 ecbdata->lno_in_preimage++;
2398 emit_del_line(ecbdata, line + 1, len - 1);
2399 break;
2400 case ' ':
2401 ecbdata->lno_in_postimage++;
2402 ecbdata->lno_in_preimage++;
2403 emit_context_line(ecbdata, line + 1, len - 1);
2404 break;
2405 default:
2406 /* incomplete line at the end */
2407 ecbdata->lno_in_preimage++;
2408 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2409 line, len, 0);
2410 break;
2414 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2416 const char *old_name = a;
2417 const char *new_name = b;
2418 int pfx_length, sfx_length;
2419 int pfx_adjust_for_slash;
2420 int len_a = strlen(a);
2421 int len_b = strlen(b);
2422 int a_midlen, b_midlen;
2423 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2424 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2426 if (qlen_a || qlen_b) {
2427 quote_c_style(a, name, NULL, 0);
2428 strbuf_addstr(name, " => ");
2429 quote_c_style(b, name, NULL, 0);
2430 return;
2433 /* Find common prefix */
2434 pfx_length = 0;
2435 while (*old_name && *new_name && *old_name == *new_name) {
2436 if (*old_name == '/')
2437 pfx_length = old_name - a + 1;
2438 old_name++;
2439 new_name++;
2442 /* Find common suffix */
2443 old_name = a + len_a;
2444 new_name = b + len_b;
2445 sfx_length = 0;
2447 * If there is a common prefix, it must end in a slash. In
2448 * that case we let this loop run 1 into the prefix to see the
2449 * same slash.
2451 * If there is no common prefix, we cannot do this as it would
2452 * underrun the input strings.
2454 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2455 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2456 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2457 *old_name == *new_name) {
2458 if (*old_name == '/')
2459 sfx_length = len_a - (old_name - a);
2460 old_name--;
2461 new_name--;
2465 * pfx{mid-a => mid-b}sfx
2466 * {pfx-a => pfx-b}sfx
2467 * pfx{sfx-a => sfx-b}
2468 * name-a => name-b
2470 a_midlen = len_a - pfx_length - sfx_length;
2471 b_midlen = len_b - pfx_length - sfx_length;
2472 if (a_midlen < 0)
2473 a_midlen = 0;
2474 if (b_midlen < 0)
2475 b_midlen = 0;
2477 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2478 if (pfx_length + sfx_length) {
2479 strbuf_add(name, a, pfx_length);
2480 strbuf_addch(name, '{');
2482 strbuf_add(name, a + pfx_length, a_midlen);
2483 strbuf_addstr(name, " => ");
2484 strbuf_add(name, b + pfx_length, b_midlen);
2485 if (pfx_length + sfx_length) {
2486 strbuf_addch(name, '}');
2487 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2491 struct diffstat_t {
2492 int nr;
2493 int alloc;
2494 struct diffstat_file {
2495 char *from_name;
2496 char *name;
2497 char *print_name;
2498 const char *comments;
2499 unsigned is_unmerged:1;
2500 unsigned is_binary:1;
2501 unsigned is_renamed:1;
2502 unsigned is_interesting:1;
2503 uintmax_t added, deleted;
2504 } **files;
2507 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2508 const char *name_a,
2509 const char *name_b)
2511 struct diffstat_file *x;
2512 x = xcalloc(1, sizeof(*x));
2513 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2514 diffstat->files[diffstat->nr++] = x;
2515 if (name_b) {
2516 x->from_name = xstrdup(name_a);
2517 x->name = xstrdup(name_b);
2518 x->is_renamed = 1;
2520 else {
2521 x->from_name = NULL;
2522 x->name = xstrdup(name_a);
2524 return x;
2527 static void diffstat_consume(void *priv, char *line, unsigned long len)
2529 struct diffstat_t *diffstat = priv;
2530 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2532 if (line[0] == '+')
2533 x->added++;
2534 else if (line[0] == '-')
2535 x->deleted++;
2538 const char mime_boundary_leader[] = "------------";
2540 static int scale_linear(int it, int width, int max_change)
2542 if (!it)
2543 return 0;
2545 * make sure that at least one '-' or '+' is printed if
2546 * there is any change to this path. The easiest way is to
2547 * scale linearly as if the alloted width is one column shorter
2548 * than it is, and then add 1 to the result.
2550 return 1 + (it * (width - 1) / max_change);
2553 static void show_graph(struct strbuf *out, char ch, int cnt,
2554 const char *set, const char *reset)
2556 if (cnt <= 0)
2557 return;
2558 strbuf_addstr(out, set);
2559 strbuf_addchars(out, ch, cnt);
2560 strbuf_addstr(out, reset);
2563 static void fill_print_name(struct diffstat_file *file)
2565 struct strbuf pname = STRBUF_INIT;
2567 if (file->print_name)
2568 return;
2570 if (file->is_renamed)
2571 pprint_rename(&pname, file->from_name, file->name);
2572 else
2573 quote_c_style(file->name, &pname, NULL, 0);
2575 if (file->comments)
2576 strbuf_addf(&pname, " (%s)", file->comments);
2578 file->print_name = strbuf_detach(&pname, NULL);
2581 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2582 int files, int insertions, int deletions)
2584 struct strbuf sb = STRBUF_INIT;
2586 if (!files) {
2587 assert(insertions == 0 && deletions == 0);
2588 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2589 NULL, 0, 0);
2590 return;
2593 strbuf_addf(&sb,
2594 (files == 1) ? " %d file changed" : " %d files changed",
2595 files);
2598 * For binary diff, the caller may want to print "x files
2599 * changed" with insertions == 0 && deletions == 0.
2601 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2602 * is probably less confusing (i.e skip over "2 files changed
2603 * but nothing about added/removed lines? Is this a bug in Git?").
2605 if (insertions || deletions == 0) {
2606 strbuf_addf(&sb,
2607 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2608 insertions);
2611 if (deletions || insertions == 0) {
2612 strbuf_addf(&sb,
2613 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2614 deletions);
2616 strbuf_addch(&sb, '\n');
2617 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2618 sb.buf, sb.len, 0);
2619 strbuf_release(&sb);
2622 void print_stat_summary(FILE *fp, int files,
2623 int insertions, int deletions)
2625 struct diff_options o;
2626 memset(&o, 0, sizeof(o));
2627 o.file = fp;
2629 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2632 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2634 int i, len, add, del, adds = 0, dels = 0;
2635 uintmax_t max_change = 0, max_len = 0;
2636 int total_files = data->nr, count;
2637 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2638 const char *reset, *add_c, *del_c;
2639 int extra_shown = 0;
2640 const char *line_prefix = diff_line_prefix(options);
2641 struct strbuf out = STRBUF_INIT;
2643 if (data->nr == 0)
2644 return;
2646 count = options->stat_count ? options->stat_count : data->nr;
2648 reset = diff_get_color_opt(options, DIFF_RESET);
2649 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2650 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2653 * Find the longest filename and max number of changes
2655 for (i = 0; (i < count) && (i < data->nr); i++) {
2656 struct diffstat_file *file = data->files[i];
2657 uintmax_t change = file->added + file->deleted;
2659 if (!file->is_interesting && (change == 0)) {
2660 count++; /* not shown == room for one more */
2661 continue;
2663 fill_print_name(file);
2664 len = strlen(file->print_name);
2665 if (max_len < len)
2666 max_len = len;
2668 if (file->is_unmerged) {
2669 /* "Unmerged" is 8 characters */
2670 bin_width = bin_width < 8 ? 8 : bin_width;
2671 continue;
2673 if (file->is_binary) {
2674 /* "Bin XXX -> YYY bytes" */
2675 int w = 14 + decimal_width(file->added)
2676 + decimal_width(file->deleted);
2677 bin_width = bin_width < w ? w : bin_width;
2678 /* Display change counts aligned with "Bin" */
2679 number_width = 3;
2680 continue;
2683 if (max_change < change)
2684 max_change = change;
2686 count = i; /* where we can stop scanning in data->files[] */
2689 * We have width = stat_width or term_columns() columns total.
2690 * We want a maximum of min(max_len, stat_name_width) for the name part.
2691 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2692 * We also need 1 for " " and 4 + decimal_width(max_change)
2693 * for " | NNNN " and one the empty column at the end, altogether
2694 * 6 + decimal_width(max_change).
2696 * If there's not enough space, we will use the smaller of
2697 * stat_name_width (if set) and 5/8*width for the filename,
2698 * and the rest for constant elements + graph part, but no more
2699 * than stat_graph_width for the graph part.
2700 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2701 * for the standard terminal size).
2703 * In other words: stat_width limits the maximum width, and
2704 * stat_name_width fixes the maximum width of the filename,
2705 * and is also used to divide available columns if there
2706 * aren't enough.
2708 * Binary files are displayed with "Bin XXX -> YYY bytes"
2709 * instead of the change count and graph. This part is treated
2710 * similarly to the graph part, except that it is not
2711 * "scaled". If total width is too small to accommodate the
2712 * guaranteed minimum width of the filename part and the
2713 * separators and this message, this message will "overflow"
2714 * making the line longer than the maximum width.
2717 if (options->stat_width == -1)
2718 width = term_columns() - strlen(line_prefix);
2719 else
2720 width = options->stat_width ? options->stat_width : 80;
2721 number_width = decimal_width(max_change) > number_width ?
2722 decimal_width(max_change) : number_width;
2724 if (options->stat_graph_width == -1)
2725 options->stat_graph_width = diff_stat_graph_width;
2728 * Guarantee 3/8*16==6 for the graph part
2729 * and 5/8*16==10 for the filename part
2731 if (width < 16 + 6 + number_width)
2732 width = 16 + 6 + number_width;
2735 * First assign sizes that are wanted, ignoring available width.
2736 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2737 * starting from "XXX" should fit in graph_width.
2739 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2740 if (options->stat_graph_width &&
2741 options->stat_graph_width < graph_width)
2742 graph_width = options->stat_graph_width;
2744 name_width = (options->stat_name_width > 0 &&
2745 options->stat_name_width < max_len) ?
2746 options->stat_name_width : max_len;
2749 * Adjust adjustable widths not to exceed maximum width
2751 if (name_width + number_width + 6 + graph_width > width) {
2752 if (graph_width > width * 3/8 - number_width - 6) {
2753 graph_width = width * 3/8 - number_width - 6;
2754 if (graph_width < 6)
2755 graph_width = 6;
2758 if (options->stat_graph_width &&
2759 graph_width > options->stat_graph_width)
2760 graph_width = options->stat_graph_width;
2761 if (name_width > width - number_width - 6 - graph_width)
2762 name_width = width - number_width - 6 - graph_width;
2763 else
2764 graph_width = width - number_width - 6 - name_width;
2768 * From here name_width is the width of the name area,
2769 * and graph_width is the width of the graph area.
2770 * max_change is used to scale graph properly.
2772 for (i = 0; i < count; i++) {
2773 const char *prefix = "";
2774 struct diffstat_file *file = data->files[i];
2775 char *name = file->print_name;
2776 uintmax_t added = file->added;
2777 uintmax_t deleted = file->deleted;
2778 int name_len;
2780 if (!file->is_interesting && (added + deleted == 0))
2781 continue;
2784 * "scale" the filename
2786 len = name_width;
2787 name_len = strlen(name);
2788 if (name_width < name_len) {
2789 char *slash;
2790 prefix = "...";
2791 len -= 3;
2792 name += name_len - len;
2793 slash = strchr(name, '/');
2794 if (slash)
2795 name = slash;
2798 if (file->is_binary) {
2799 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2800 strbuf_addf(&out, " %*s", number_width, "Bin");
2801 if (!added && !deleted) {
2802 strbuf_addch(&out, '\n');
2803 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2804 out.buf, out.len, 0);
2805 strbuf_reset(&out);
2806 continue;
2808 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2809 del_c, deleted, reset);
2810 strbuf_addstr(&out, " -> ");
2811 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2812 add_c, added, reset);
2813 strbuf_addstr(&out, " bytes\n");
2814 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2815 out.buf, out.len, 0);
2816 strbuf_reset(&out);
2817 continue;
2819 else if (file->is_unmerged) {
2820 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2821 strbuf_addstr(&out, " Unmerged\n");
2822 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2823 out.buf, out.len, 0);
2824 strbuf_reset(&out);
2825 continue;
2829 * scale the add/delete
2831 add = added;
2832 del = deleted;
2834 if (graph_width <= max_change) {
2835 int total = scale_linear(add + del, graph_width, max_change);
2836 if (total < 2 && add && del)
2837 /* width >= 2 due to the sanity check */
2838 total = 2;
2839 if (add < del) {
2840 add = scale_linear(add, graph_width, max_change);
2841 del = total - add;
2842 } else {
2843 del = scale_linear(del, graph_width, max_change);
2844 add = total - del;
2847 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2848 strbuf_addf(&out, " %*"PRIuMAX"%s",
2849 number_width, added + deleted,
2850 added + deleted ? " " : "");
2851 show_graph(&out, '+', add, add_c, reset);
2852 show_graph(&out, '-', del, del_c, reset);
2853 strbuf_addch(&out, '\n');
2854 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2855 out.buf, out.len, 0);
2856 strbuf_reset(&out);
2859 for (i = 0; i < data->nr; i++) {
2860 struct diffstat_file *file = data->files[i];
2861 uintmax_t added = file->added;
2862 uintmax_t deleted = file->deleted;
2864 if (file->is_unmerged ||
2865 (!file->is_interesting && (added + deleted == 0))) {
2866 total_files--;
2867 continue;
2870 if (!file->is_binary) {
2871 adds += added;
2872 dels += deleted;
2874 if (i < count)
2875 continue;
2876 if (!extra_shown)
2877 emit_diff_symbol(options,
2878 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2879 NULL, 0, 0);
2880 extra_shown = 1;
2883 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2884 strbuf_release(&out);
2887 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2889 int i, adds = 0, dels = 0, total_files = data->nr;
2891 if (data->nr == 0)
2892 return;
2894 for (i = 0; i < data->nr; i++) {
2895 int added = data->files[i]->added;
2896 int deleted = data->files[i]->deleted;
2898 if (data->files[i]->is_unmerged ||
2899 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2900 total_files--;
2901 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2902 adds += added;
2903 dels += deleted;
2906 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2909 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2911 int i;
2913 if (data->nr == 0)
2914 return;
2916 for (i = 0; i < data->nr; i++) {
2917 struct diffstat_file *file = data->files[i];
2919 fprintf(options->file, "%s", diff_line_prefix(options));
2921 if (file->is_binary)
2922 fprintf(options->file, "-\t-\t");
2923 else
2924 fprintf(options->file,
2925 "%"PRIuMAX"\t%"PRIuMAX"\t",
2926 file->added, file->deleted);
2927 if (options->line_termination) {
2928 fill_print_name(file);
2929 if (!file->is_renamed)
2930 write_name_quoted(file->name, options->file,
2931 options->line_termination);
2932 else {
2933 fputs(file->print_name, options->file);
2934 putc(options->line_termination, options->file);
2936 } else {
2937 if (file->is_renamed) {
2938 putc('\0', options->file);
2939 write_name_quoted(file->from_name, options->file, '\0');
2941 write_name_quoted(file->name, options->file, '\0');
2946 struct dirstat_file {
2947 const char *name;
2948 unsigned long changed;
2951 struct dirstat_dir {
2952 struct dirstat_file *files;
2953 int alloc, nr, permille, cumulative;
2956 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2957 unsigned long changed, const char *base, int baselen)
2959 unsigned long sum_changes = 0;
2960 unsigned int sources = 0;
2961 const char *line_prefix = diff_line_prefix(opt);
2963 while (dir->nr) {
2964 struct dirstat_file *f = dir->files;
2965 int namelen = strlen(f->name);
2966 unsigned long changes;
2967 char *slash;
2969 if (namelen < baselen)
2970 break;
2971 if (memcmp(f->name, base, baselen))
2972 break;
2973 slash = strchr(f->name + baselen, '/');
2974 if (slash) {
2975 int newbaselen = slash + 1 - f->name;
2976 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2977 sources++;
2978 } else {
2979 changes = f->changed;
2980 dir->files++;
2981 dir->nr--;
2982 sources += 2;
2984 sum_changes += changes;
2988 * We don't report dirstat's for
2989 * - the top level
2990 * - or cases where everything came from a single directory
2991 * under this directory (sources == 1).
2993 if (baselen && sources != 1) {
2994 if (sum_changes) {
2995 int permille = sum_changes * 1000 / changed;
2996 if (permille >= dir->permille) {
2997 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2998 permille / 10, permille % 10, baselen, base);
2999 if (!dir->cumulative)
3000 return 0;
3004 return sum_changes;
3007 static int dirstat_compare(const void *_a, const void *_b)
3009 const struct dirstat_file *a = _a;
3010 const struct dirstat_file *b = _b;
3011 return strcmp(a->name, b->name);
3014 static void show_dirstat(struct diff_options *options)
3016 int i;
3017 unsigned long changed;
3018 struct dirstat_dir dir;
3019 struct diff_queue_struct *q = &diff_queued_diff;
3021 dir.files = NULL;
3022 dir.alloc = 0;
3023 dir.nr = 0;
3024 dir.permille = options->dirstat_permille;
3025 dir.cumulative = options->flags.dirstat_cumulative;
3027 changed = 0;
3028 for (i = 0; i < q->nr; i++) {
3029 struct diff_filepair *p = q->queue[i];
3030 const char *name;
3031 unsigned long copied, added, damage;
3033 name = p->two->path ? p->two->path : p->one->path;
3035 if (p->one->oid_valid && p->two->oid_valid &&
3036 oideq(&p->one->oid, &p->two->oid)) {
3038 * The SHA1 has not changed, so pre-/post-content is
3039 * identical. We can therefore skip looking at the
3040 * file contents altogether.
3042 damage = 0;
3043 goto found_damage;
3046 if (options->flags.dirstat_by_file) {
3048 * In --dirstat-by-file mode, we don't really need to
3049 * look at the actual file contents at all.
3050 * The fact that the SHA1 changed is enough for us to
3051 * add this file to the list of results
3052 * (with each file contributing equal damage).
3054 damage = 1;
3055 goto found_damage;
3058 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3059 diff_populate_filespec(options->repo, p->one, 0);
3060 diff_populate_filespec(options->repo, p->two, 0);
3061 diffcore_count_changes(options->repo,
3062 p->one, p->two, NULL, NULL,
3063 &copied, &added);
3064 diff_free_filespec_data(p->one);
3065 diff_free_filespec_data(p->two);
3066 } else if (DIFF_FILE_VALID(p->one)) {
3067 diff_populate_filespec(options->repo, p->one, CHECK_SIZE_ONLY);
3068 copied = added = 0;
3069 diff_free_filespec_data(p->one);
3070 } else if (DIFF_FILE_VALID(p->two)) {
3071 diff_populate_filespec(options->repo, p->two, CHECK_SIZE_ONLY);
3072 copied = 0;
3073 added = p->two->size;
3074 diff_free_filespec_data(p->two);
3075 } else
3076 continue;
3079 * Original minus copied is the removed material,
3080 * added is the new material. They are both damages
3081 * made to the preimage.
3082 * If the resulting damage is zero, we know that
3083 * diffcore_count_changes() considers the two entries to
3084 * be identical, but since the oid changed, we
3085 * know that there must have been _some_ kind of change,
3086 * so we force all entries to have damage > 0.
3088 damage = (p->one->size - copied) + added;
3089 if (!damage)
3090 damage = 1;
3092 found_damage:
3093 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3094 dir.files[dir.nr].name = name;
3095 dir.files[dir.nr].changed = damage;
3096 changed += damage;
3097 dir.nr++;
3100 /* This can happen even with many files, if everything was renames */
3101 if (!changed)
3102 return;
3104 /* Show all directories with more than x% of the changes */
3105 QSORT(dir.files, dir.nr, dirstat_compare);
3106 gather_dirstat(options, &dir, changed, "", 0);
3109 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3111 int i;
3112 unsigned long changed;
3113 struct dirstat_dir dir;
3115 if (data->nr == 0)
3116 return;
3118 dir.files = NULL;
3119 dir.alloc = 0;
3120 dir.nr = 0;
3121 dir.permille = options->dirstat_permille;
3122 dir.cumulative = options->flags.dirstat_cumulative;
3124 changed = 0;
3125 for (i = 0; i < data->nr; i++) {
3126 struct diffstat_file *file = data->files[i];
3127 unsigned long damage = file->added + file->deleted;
3128 if (file->is_binary)
3130 * binary files counts bytes, not lines. Must find some
3131 * way to normalize binary bytes vs. textual lines.
3132 * The following heuristic assumes that there are 64
3133 * bytes per "line".
3134 * This is stupid and ugly, but very cheap...
3136 damage = DIV_ROUND_UP(damage, 64);
3137 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3138 dir.files[dir.nr].name = file->name;
3139 dir.files[dir.nr].changed = damage;
3140 changed += damage;
3141 dir.nr++;
3144 /* This can happen even with many files, if everything was renames */
3145 if (!changed)
3146 return;
3148 /* Show all directories with more than x% of the changes */
3149 QSORT(dir.files, dir.nr, dirstat_compare);
3150 gather_dirstat(options, &dir, changed, "", 0);
3153 static void free_diffstat_info(struct diffstat_t *diffstat)
3155 int i;
3156 for (i = 0; i < diffstat->nr; i++) {
3157 struct diffstat_file *f = diffstat->files[i];
3158 free(f->print_name);
3159 free(f->name);
3160 free(f->from_name);
3161 free(f);
3163 free(diffstat->files);
3166 struct checkdiff_t {
3167 const char *filename;
3168 int lineno;
3169 int conflict_marker_size;
3170 struct diff_options *o;
3171 unsigned ws_rule;
3172 unsigned status;
3175 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3177 char firstchar;
3178 int cnt;
3180 if (len < marker_size + 1)
3181 return 0;
3182 firstchar = line[0];
3183 switch (firstchar) {
3184 case '=': case '>': case '<': case '|':
3185 break;
3186 default:
3187 return 0;
3189 for (cnt = 1; cnt < marker_size; cnt++)
3190 if (line[cnt] != firstchar)
3191 return 0;
3192 /* line[1] thru line[marker_size-1] are same as firstchar */
3193 if (len < marker_size + 1 || !isspace(line[marker_size]))
3194 return 0;
3195 return 1;
3198 static void checkdiff_consume_hunk(void *priv,
3199 long ob, long on, long nb, long nn,
3200 const char *func, long funclen)
3203 struct checkdiff_t *data = priv;
3204 data->lineno = nb - 1;
3207 static void checkdiff_consume(void *priv, char *line, unsigned long len)
3209 struct checkdiff_t *data = priv;
3210 int marker_size = data->conflict_marker_size;
3211 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3212 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3213 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3214 char *err;
3215 const char *line_prefix;
3217 assert(data->o);
3218 line_prefix = diff_line_prefix(data->o);
3220 if (line[0] == '+') {
3221 unsigned bad;
3222 data->lineno++;
3223 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3224 data->status |= 1;
3225 fprintf(data->o->file,
3226 "%s%s:%d: leftover conflict marker\n",
3227 line_prefix, data->filename, data->lineno);
3229 bad = ws_check(line + 1, len - 1, data->ws_rule);
3230 if (!bad)
3231 return;
3232 data->status |= bad;
3233 err = whitespace_error_string(bad);
3234 fprintf(data->o->file, "%s%s:%d: %s.\n",
3235 line_prefix, data->filename, data->lineno, err);
3236 free(err);
3237 emit_line(data->o, set, reset, line, 1);
3238 ws_check_emit(line + 1, len - 1, data->ws_rule,
3239 data->o->file, set, reset, ws);
3240 } else if (line[0] == ' ') {
3241 data->lineno++;
3245 static unsigned char *deflate_it(char *data,
3246 unsigned long size,
3247 unsigned long *result_size)
3249 int bound;
3250 unsigned char *deflated;
3251 git_zstream stream;
3253 git_deflate_init(&stream, zlib_compression_level);
3254 bound = git_deflate_bound(&stream, size);
3255 deflated = xmalloc(bound);
3256 stream.next_out = deflated;
3257 stream.avail_out = bound;
3259 stream.next_in = (unsigned char *)data;
3260 stream.avail_in = size;
3261 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3262 ; /* nothing */
3263 git_deflate_end(&stream);
3264 *result_size = stream.total_out;
3265 return deflated;
3268 static void emit_binary_diff_body(struct diff_options *o,
3269 mmfile_t *one, mmfile_t *two)
3271 void *cp;
3272 void *delta;
3273 void *deflated;
3274 void *data;
3275 unsigned long orig_size;
3276 unsigned long delta_size;
3277 unsigned long deflate_size;
3278 unsigned long data_size;
3280 /* We could do deflated delta, or we could do just deflated two,
3281 * whichever is smaller.
3283 delta = NULL;
3284 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3285 if (one->size && two->size) {
3286 delta = diff_delta(one->ptr, one->size,
3287 two->ptr, two->size,
3288 &delta_size, deflate_size);
3289 if (delta) {
3290 void *to_free = delta;
3291 orig_size = delta_size;
3292 delta = deflate_it(delta, delta_size, &delta_size);
3293 free(to_free);
3297 if (delta && delta_size < deflate_size) {
3298 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3299 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3300 s, strlen(s), 0);
3301 free(s);
3302 free(deflated);
3303 data = delta;
3304 data_size = delta_size;
3305 } else {
3306 char *s = xstrfmt("%lu", two->size);
3307 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3308 s, strlen(s), 0);
3309 free(s);
3310 free(delta);
3311 data = deflated;
3312 data_size = deflate_size;
3315 /* emit data encoded in base85 */
3316 cp = data;
3317 while (data_size) {
3318 int len;
3319 int bytes = (52 < data_size) ? 52 : data_size;
3320 char line[71];
3321 data_size -= bytes;
3322 if (bytes <= 26)
3323 line[0] = bytes + 'A' - 1;
3324 else
3325 line[0] = bytes - 26 + 'a' - 1;
3326 encode_85(line + 1, cp, bytes);
3327 cp = (char *) cp + bytes;
3329 len = strlen(line);
3330 line[len++] = '\n';
3331 line[len] = '\0';
3333 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3334 line, len, 0);
3336 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3337 free(data);
3340 static void emit_binary_diff(struct diff_options *o,
3341 mmfile_t *one, mmfile_t *two)
3343 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3344 emit_binary_diff_body(o, one, two);
3345 emit_binary_diff_body(o, two, one);
3348 int diff_filespec_is_binary(struct repository *r,
3349 struct diff_filespec *one)
3351 if (one->is_binary == -1) {
3352 diff_filespec_load_driver(one, r->index);
3353 if (one->driver->binary != -1)
3354 one->is_binary = one->driver->binary;
3355 else {
3356 if (!one->data && DIFF_FILE_VALID(one))
3357 diff_populate_filespec(r, one, CHECK_BINARY);
3358 if (one->is_binary == -1 && one->data)
3359 one->is_binary = buffer_is_binary(one->data,
3360 one->size);
3361 if (one->is_binary == -1)
3362 one->is_binary = 0;
3365 return one->is_binary;
3368 static const struct userdiff_funcname *
3369 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3371 diff_filespec_load_driver(one, o->repo->index);
3372 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3375 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3377 if (!options->a_prefix)
3378 options->a_prefix = a;
3379 if (!options->b_prefix)
3380 options->b_prefix = b;
3383 struct userdiff_driver *get_textconv(struct repository *r,
3384 struct diff_filespec *one)
3386 if (!DIFF_FILE_VALID(one))
3387 return NULL;
3389 diff_filespec_load_driver(one, r->index);
3390 return userdiff_get_textconv(r, one->driver);
3393 static void builtin_diff(const char *name_a,
3394 const char *name_b,
3395 struct diff_filespec *one,
3396 struct diff_filespec *two,
3397 const char *xfrm_msg,
3398 int must_show_header,
3399 struct diff_options *o,
3400 int complete_rewrite)
3402 mmfile_t mf1, mf2;
3403 const char *lbl[2];
3404 char *a_one, *b_two;
3405 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3406 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3407 const char *a_prefix, *b_prefix;
3408 struct userdiff_driver *textconv_one = NULL;
3409 struct userdiff_driver *textconv_two = NULL;
3410 struct strbuf header = STRBUF_INIT;
3411 const char *line_prefix = diff_line_prefix(o);
3413 diff_set_mnemonic_prefix(o, "a/", "b/");
3414 if (o->flags.reverse_diff) {
3415 a_prefix = o->b_prefix;
3416 b_prefix = o->a_prefix;
3417 } else {
3418 a_prefix = o->a_prefix;
3419 b_prefix = o->b_prefix;
3422 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3423 (!one->mode || S_ISGITLINK(one->mode)) &&
3424 (!two->mode || S_ISGITLINK(two->mode))) {
3425 show_submodule_summary(o, one->path ? one->path : two->path,
3426 &one->oid, &two->oid,
3427 two->dirty_submodule);
3428 return;
3429 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3430 (!one->mode || S_ISGITLINK(one->mode)) &&
3431 (!two->mode || S_ISGITLINK(two->mode))) {
3432 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3433 &one->oid, &two->oid,
3434 two->dirty_submodule);
3435 return;
3438 if (o->flags.allow_textconv) {
3439 textconv_one = get_textconv(o->repo, one);
3440 textconv_two = get_textconv(o->repo, two);
3443 /* Never use a non-valid filename anywhere if at all possible */
3444 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3445 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3447 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3448 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3449 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3450 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3451 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3452 if (lbl[0][0] == '/') {
3453 /* /dev/null */
3454 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3455 if (xfrm_msg)
3456 strbuf_addstr(&header, xfrm_msg);
3457 must_show_header = 1;
3459 else if (lbl[1][0] == '/') {
3460 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3461 if (xfrm_msg)
3462 strbuf_addstr(&header, xfrm_msg);
3463 must_show_header = 1;
3465 else {
3466 if (one->mode != two->mode) {
3467 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3468 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3469 must_show_header = 1;
3471 if (xfrm_msg)
3472 strbuf_addstr(&header, xfrm_msg);
3475 * we do not run diff between different kind
3476 * of objects.
3478 if ((one->mode ^ two->mode) & S_IFMT)
3479 goto free_ab_and_return;
3480 if (complete_rewrite &&
3481 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3482 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3483 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3484 header.buf, header.len, 0);
3485 strbuf_reset(&header);
3486 emit_rewrite_diff(name_a, name_b, one, two,
3487 textconv_one, textconv_two, o);
3488 o->found_changes = 1;
3489 goto free_ab_and_return;
3493 if (o->irreversible_delete && lbl[1][0] == '/') {
3494 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3495 header.len, 0);
3496 strbuf_reset(&header);
3497 goto free_ab_and_return;
3498 } else if (!o->flags.text &&
3499 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3500 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3501 struct strbuf sb = STRBUF_INIT;
3502 if (!one->data && !two->data &&
3503 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3504 !o->flags.binary) {
3505 if (oideq(&one->oid, &two->oid)) {
3506 if (must_show_header)
3507 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3508 header.buf, header.len,
3510 goto free_ab_and_return;
3512 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3513 header.buf, header.len, 0);
3514 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3515 diff_line_prefix(o), lbl[0], lbl[1]);
3516 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3517 sb.buf, sb.len, 0);
3518 strbuf_release(&sb);
3519 goto free_ab_and_return;
3521 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3522 fill_mmfile(o->repo, &mf2, two) < 0)
3523 die("unable to read files to diff");
3524 /* Quite common confusing case */
3525 if (mf1.size == mf2.size &&
3526 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3527 if (must_show_header)
3528 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3529 header.buf, header.len, 0);
3530 goto free_ab_and_return;
3532 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3533 strbuf_reset(&header);
3534 if (o->flags.binary)
3535 emit_binary_diff(o, &mf1, &mf2);
3536 else {
3537 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3538 diff_line_prefix(o), lbl[0], lbl[1]);
3539 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3540 sb.buf, sb.len, 0);
3541 strbuf_release(&sb);
3543 o->found_changes = 1;
3544 } else {
3545 /* Crazy xdl interfaces.. */
3546 const char *diffopts;
3547 const char *v;
3548 xpparam_t xpp;
3549 xdemitconf_t xecfg;
3550 struct emit_callback ecbdata;
3551 const struct userdiff_funcname *pe;
3553 if (must_show_header) {
3554 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3555 header.buf, header.len, 0);
3556 strbuf_reset(&header);
3559 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3560 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3562 pe = diff_funcname_pattern(o, one);
3563 if (!pe)
3564 pe = diff_funcname_pattern(o, two);
3566 memset(&xpp, 0, sizeof(xpp));
3567 memset(&xecfg, 0, sizeof(xecfg));
3568 memset(&ecbdata, 0, sizeof(ecbdata));
3569 if (o->flags.suppress_diff_headers)
3570 lbl[0] = NULL;
3571 ecbdata.label_path = lbl;
3572 ecbdata.color_diff = want_color(o->use_color);
3573 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3574 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3575 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3576 ecbdata.opt = o;
3577 if (header.len && !o->flags.suppress_diff_headers)
3578 ecbdata.header = &header;
3579 xpp.flags = o->xdl_opts;
3580 xpp.anchors = o->anchors;
3581 xpp.anchors_nr = o->anchors_nr;
3582 xecfg.ctxlen = o->context;
3583 xecfg.interhunkctxlen = o->interhunkcontext;
3584 xecfg.flags = XDL_EMIT_FUNCNAMES;
3585 if (o->flags.funccontext)
3586 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3587 if (pe)
3588 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3590 diffopts = getenv("GIT_DIFF_OPTS");
3591 if (!diffopts)
3593 else if (skip_prefix(diffopts, "--unified=", &v))
3594 xecfg.ctxlen = strtoul(v, NULL, 10);
3595 else if (skip_prefix(diffopts, "-u", &v))
3596 xecfg.ctxlen = strtoul(v, NULL, 10);
3598 if (o->word_diff)
3599 init_diff_words_data(&ecbdata, o, one, two);
3600 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3601 &ecbdata, &xpp, &xecfg))
3602 die("unable to generate diff for %s", one->path);
3603 if (o->word_diff)
3604 free_diff_words_data(&ecbdata);
3605 if (textconv_one)
3606 free(mf1.ptr);
3607 if (textconv_two)
3608 free(mf2.ptr);
3609 xdiff_clear_find_func(&xecfg);
3612 free_ab_and_return:
3613 strbuf_release(&header);
3614 diff_free_filespec_data(one);
3615 diff_free_filespec_data(two);
3616 free(a_one);
3617 free(b_two);
3618 return;
3621 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3623 if (!is_renamed) {
3624 if (p->status == DIFF_STATUS_ADDED) {
3625 if (S_ISLNK(p->two->mode))
3626 return "new +l";
3627 else if ((p->two->mode & 0777) == 0755)
3628 return "new +x";
3629 else
3630 return "new";
3631 } else if (p->status == DIFF_STATUS_DELETED)
3632 return "gone";
3634 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3635 return "mode -l";
3636 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3637 return "mode +l";
3638 else if ((p->one->mode & 0777) == 0644 &&
3639 (p->two->mode & 0777) == 0755)
3640 return "mode +x";
3641 else if ((p->one->mode & 0777) == 0755 &&
3642 (p->two->mode & 0777) == 0644)
3643 return "mode -x";
3644 return NULL;
3647 static void builtin_diffstat(const char *name_a, const char *name_b,
3648 struct diff_filespec *one,
3649 struct diff_filespec *two,
3650 struct diffstat_t *diffstat,
3651 struct diff_options *o,
3652 struct diff_filepair *p)
3654 mmfile_t mf1, mf2;
3655 struct diffstat_file *data;
3656 int same_contents;
3657 int complete_rewrite = 0;
3659 if (!DIFF_PAIR_UNMERGED(p)) {
3660 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3661 complete_rewrite = 1;
3664 data = diffstat_add(diffstat, name_a, name_b);
3665 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3666 if (o->flags.stat_with_summary)
3667 data->comments = get_compact_summary(p, data->is_renamed);
3669 if (!one || !two) {
3670 data->is_unmerged = 1;
3671 return;
3674 same_contents = oideq(&one->oid, &two->oid);
3676 if (diff_filespec_is_binary(o->repo, one) ||
3677 diff_filespec_is_binary(o->repo, two)) {
3678 data->is_binary = 1;
3679 if (same_contents) {
3680 data->added = 0;
3681 data->deleted = 0;
3682 } else {
3683 data->added = diff_filespec_size(o->repo, two);
3684 data->deleted = diff_filespec_size(o->repo, one);
3688 else if (complete_rewrite) {
3689 diff_populate_filespec(o->repo, one, 0);
3690 diff_populate_filespec(o->repo, two, 0);
3691 data->deleted = count_lines(one->data, one->size);
3692 data->added = count_lines(two->data, two->size);
3695 else if (!same_contents) {
3696 /* Crazy xdl interfaces.. */
3697 xpparam_t xpp;
3698 xdemitconf_t xecfg;
3700 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3701 fill_mmfile(o->repo, &mf2, two) < 0)
3702 die("unable to read files to diff");
3704 memset(&xpp, 0, sizeof(xpp));
3705 memset(&xecfg, 0, sizeof(xecfg));
3706 xpp.flags = o->xdl_opts;
3707 xpp.anchors = o->anchors;
3708 xpp.anchors_nr = o->anchors_nr;
3709 xecfg.ctxlen = o->context;
3710 xecfg.interhunkctxlen = o->interhunkcontext;
3711 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
3712 diffstat_consume, diffstat, &xpp, &xecfg))
3713 die("unable to generate diffstat for %s", one->path);
3716 diff_free_filespec_data(one);
3717 diff_free_filespec_data(two);
3720 static void builtin_checkdiff(const char *name_a, const char *name_b,
3721 const char *attr_path,
3722 struct diff_filespec *one,
3723 struct diff_filespec *two,
3724 struct diff_options *o)
3726 mmfile_t mf1, mf2;
3727 struct checkdiff_t data;
3729 if (!two)
3730 return;
3732 memset(&data, 0, sizeof(data));
3733 data.filename = name_b ? name_b : name_a;
3734 data.lineno = 0;
3735 data.o = o;
3736 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3737 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3739 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3740 fill_mmfile(o->repo, &mf2, two) < 0)
3741 die("unable to read files to diff");
3744 * All the other codepaths check both sides, but not checking
3745 * the "old" side here is deliberate. We are checking the newly
3746 * introduced changes, and as long as the "new" side is text, we
3747 * can and should check what it introduces.
3749 if (diff_filespec_is_binary(o->repo, two))
3750 goto free_and_return;
3751 else {
3752 /* Crazy xdl interfaces.. */
3753 xpparam_t xpp;
3754 xdemitconf_t xecfg;
3756 memset(&xpp, 0, sizeof(xpp));
3757 memset(&xecfg, 0, sizeof(xecfg));
3758 xecfg.ctxlen = 1; /* at least one context line */
3759 xpp.flags = 0;
3760 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3761 checkdiff_consume, &data,
3762 &xpp, &xecfg))
3763 die("unable to generate checkdiff for %s", one->path);
3765 if (data.ws_rule & WS_BLANK_AT_EOF) {
3766 struct emit_callback ecbdata;
3767 int blank_at_eof;
3769 ecbdata.ws_rule = data.ws_rule;
3770 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3771 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3773 if (blank_at_eof) {
3774 static char *err;
3775 if (!err)
3776 err = whitespace_error_string(WS_BLANK_AT_EOF);
3777 fprintf(o->file, "%s:%d: %s.\n",
3778 data.filename, blank_at_eof, err);
3779 data.status = 1; /* report errors */
3783 free_and_return:
3784 diff_free_filespec_data(one);
3785 diff_free_filespec_data(two);
3786 if (data.status)
3787 o->flags.check_failed = 1;
3790 struct diff_filespec *alloc_filespec(const char *path)
3792 struct diff_filespec *spec;
3794 FLEXPTR_ALLOC_STR(spec, path, path);
3795 spec->count = 1;
3796 spec->is_binary = -1;
3797 return spec;
3800 void free_filespec(struct diff_filespec *spec)
3802 if (!--spec->count) {
3803 diff_free_filespec_data(spec);
3804 free(spec);
3808 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3809 int oid_valid, unsigned short mode)
3811 if (mode) {
3812 spec->mode = canon_mode(mode);
3813 oidcpy(&spec->oid, oid);
3814 spec->oid_valid = oid_valid;
3819 * Given a name and sha1 pair, if the index tells us the file in
3820 * the work tree has that object contents, return true, so that
3821 * prepare_temp_file() does not have to inflate and extract.
3823 static int reuse_worktree_file(struct index_state *istate,
3824 const char *name,
3825 const struct object_id *oid,
3826 int want_file)
3828 const struct cache_entry *ce;
3829 struct stat st;
3830 int pos, len;
3833 * We do not read the cache ourselves here, because the
3834 * benchmark with my previous version that always reads cache
3835 * shows that it makes things worse for diff-tree comparing
3836 * two linux-2.6 kernel trees in an already checked out work
3837 * tree. This is because most diff-tree comparisons deal with
3838 * only a small number of files, while reading the cache is
3839 * expensive for a large project, and its cost outweighs the
3840 * savings we get by not inflating the object to a temporary
3841 * file. Practically, this code only helps when we are used
3842 * by diff-cache --cached, which does read the cache before
3843 * calling us.
3845 if (!istate->cache)
3846 return 0;
3848 /* We want to avoid the working directory if our caller
3849 * doesn't need the data in a normal file, this system
3850 * is rather slow with its stat/open/mmap/close syscalls,
3851 * and the object is contained in a pack file. The pack
3852 * is probably already open and will be faster to obtain
3853 * the data through than the working directory. Loose
3854 * objects however would tend to be slower as they need
3855 * to be individually opened and inflated.
3857 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3858 return 0;
3861 * Similarly, if we'd have to convert the file contents anyway, that
3862 * makes the optimization not worthwhile.
3864 if (!want_file && would_convert_to_git(istate, name))
3865 return 0;
3867 len = strlen(name);
3868 pos = index_name_pos(istate, name, len);
3869 if (pos < 0)
3870 return 0;
3871 ce = istate->cache[pos];
3874 * This is not the sha1 we are looking for, or
3875 * unreusable because it is not a regular file.
3877 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3878 return 0;
3881 * If ce is marked as "assume unchanged", there is no
3882 * guarantee that work tree matches what we are looking for.
3884 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3885 return 0;
3888 * If ce matches the file in the work tree, we can reuse it.
3890 if (ce_uptodate(ce) ||
3891 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3892 return 1;
3894 return 0;
3897 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3899 struct strbuf buf = STRBUF_INIT;
3900 char *dirty = "";
3902 /* Are we looking at the work tree? */
3903 if (s->dirty_submodule)
3904 dirty = "-dirty";
3906 strbuf_addf(&buf, "Subproject commit %s%s\n",
3907 oid_to_hex(&s->oid), dirty);
3908 s->size = buf.len;
3909 if (size_only) {
3910 s->data = NULL;
3911 strbuf_release(&buf);
3912 } else {
3913 s->data = strbuf_detach(&buf, NULL);
3914 s->should_free = 1;
3916 return 0;
3920 * While doing rename detection and pickaxe operation, we may need to
3921 * grab the data for the blob (or file) for our own in-core comparison.
3922 * diff_filespec has data and size fields for this purpose.
3924 int diff_populate_filespec(struct repository *r,
3925 struct diff_filespec *s,
3926 unsigned int flags)
3928 int size_only = flags & CHECK_SIZE_ONLY;
3929 int err = 0;
3930 int conv_flags = global_conv_flags_eol;
3932 * demote FAIL to WARN to allow inspecting the situation
3933 * instead of refusing.
3935 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3936 conv_flags = CONV_EOL_RNDTRP_WARN;
3938 if (!DIFF_FILE_VALID(s))
3939 die("internal error: asking to populate invalid file.");
3940 if (S_ISDIR(s->mode))
3941 return -1;
3943 if (s->data)
3944 return 0;
3946 if (size_only && 0 < s->size)
3947 return 0;
3949 if (S_ISGITLINK(s->mode))
3950 return diff_populate_gitlink(s, size_only);
3952 if (!s->oid_valid ||
3953 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
3954 struct strbuf buf = STRBUF_INIT;
3955 struct stat st;
3956 int fd;
3958 if (lstat(s->path, &st) < 0) {
3959 err_empty:
3960 err = -1;
3961 empty:
3962 s->data = (char *)"";
3963 s->size = 0;
3964 return err;
3966 s->size = xsize_t(st.st_size);
3967 if (!s->size)
3968 goto empty;
3969 if (S_ISLNK(st.st_mode)) {
3970 struct strbuf sb = STRBUF_INIT;
3972 if (strbuf_readlink(&sb, s->path, s->size))
3973 goto err_empty;
3974 s->size = sb.len;
3975 s->data = strbuf_detach(&sb, NULL);
3976 s->should_free = 1;
3977 return 0;
3981 * Even if the caller would be happy with getting
3982 * only the size, we cannot return early at this
3983 * point if the path requires us to run the content
3984 * conversion.
3986 if (size_only && !would_convert_to_git(r->index, s->path))
3987 return 0;
3990 * Note: this check uses xsize_t(st.st_size) that may
3991 * not be the true size of the blob after it goes
3992 * through convert_to_git(). This may not strictly be
3993 * correct, but the whole point of big_file_threshold
3994 * and is_binary check being that we want to avoid
3995 * opening the file and inspecting the contents, this
3996 * is probably fine.
3998 if ((flags & CHECK_BINARY) &&
3999 s->size > big_file_threshold && s->is_binary == -1) {
4000 s->is_binary = 1;
4001 return 0;
4003 fd = open(s->path, O_RDONLY);
4004 if (fd < 0)
4005 goto err_empty;
4006 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4007 close(fd);
4008 s->should_munmap = 1;
4011 * Convert from working tree format to canonical git format
4013 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4014 size_t size = 0;
4015 munmap(s->data, s->size);
4016 s->should_munmap = 0;
4017 s->data = strbuf_detach(&buf, &size);
4018 s->size = size;
4019 s->should_free = 1;
4022 else {
4023 enum object_type type;
4024 if (size_only || (flags & CHECK_BINARY)) {
4025 type = oid_object_info(r, &s->oid, &s->size);
4026 if (type < 0)
4027 die("unable to read %s",
4028 oid_to_hex(&s->oid));
4029 if (size_only)
4030 return 0;
4031 if (s->size > big_file_threshold && s->is_binary == -1) {
4032 s->is_binary = 1;
4033 return 0;
4036 s->data = read_object_file(&s->oid, &type, &s->size);
4037 if (!s->data)
4038 die("unable to read %s", oid_to_hex(&s->oid));
4039 s->should_free = 1;
4041 return 0;
4044 void diff_free_filespec_blob(struct diff_filespec *s)
4046 if (s->should_free)
4047 free(s->data);
4048 else if (s->should_munmap)
4049 munmap(s->data, s->size);
4051 if (s->should_free || s->should_munmap) {
4052 s->should_free = s->should_munmap = 0;
4053 s->data = NULL;
4057 void diff_free_filespec_data(struct diff_filespec *s)
4059 diff_free_filespec_blob(s);
4060 FREE_AND_NULL(s->cnt_data);
4063 static void prep_temp_blob(struct index_state *istate,
4064 const char *path, struct diff_tempfile *temp,
4065 void *blob,
4066 unsigned long size,
4067 const struct object_id *oid,
4068 int mode)
4070 struct strbuf buf = STRBUF_INIT;
4071 struct strbuf tempfile = STRBUF_INIT;
4072 char *path_dup = xstrdup(path);
4073 const char *base = basename(path_dup);
4075 /* Generate "XXXXXX_basename.ext" */
4076 strbuf_addstr(&tempfile, "XXXXXX_");
4077 strbuf_addstr(&tempfile, base);
4079 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
4080 if (!temp->tempfile)
4081 die_errno("unable to create temp-file");
4082 if (convert_to_working_tree(istate, path,
4083 (const char *)blob, (size_t)size, &buf)) {
4084 blob = buf.buf;
4085 size = buf.len;
4087 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4088 close_tempfile_gently(temp->tempfile))
4089 die_errno("unable to write temp-file");
4090 temp->name = get_tempfile_path(temp->tempfile);
4091 oid_to_hex_r(temp->hex, oid);
4092 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4093 strbuf_release(&buf);
4094 strbuf_release(&tempfile);
4095 free(path_dup);
4098 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4099 const char *name,
4100 struct diff_filespec *one)
4102 struct diff_tempfile *temp = claim_diff_tempfile();
4104 if (!DIFF_FILE_VALID(one)) {
4105 not_a_valid_file:
4106 /* A '-' entry produces this for file-2, and
4107 * a '+' entry produces this for file-1.
4109 temp->name = "/dev/null";
4110 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4111 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4112 return temp;
4115 if (!S_ISGITLINK(one->mode) &&
4116 (!one->oid_valid ||
4117 reuse_worktree_file(r->index, name, &one->oid, 1))) {
4118 struct stat st;
4119 if (lstat(name, &st) < 0) {
4120 if (errno == ENOENT)
4121 goto not_a_valid_file;
4122 die_errno("stat(%s)", name);
4124 if (S_ISLNK(st.st_mode)) {
4125 struct strbuf sb = STRBUF_INIT;
4126 if (strbuf_readlink(&sb, name, st.st_size) < 0)
4127 die_errno("readlink(%s)", name);
4128 prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
4129 (one->oid_valid ?
4130 &one->oid : &null_oid),
4131 (one->oid_valid ?
4132 one->mode : S_IFLNK));
4133 strbuf_release(&sb);
4135 else {
4136 /* we can borrow from the file in the work tree */
4137 temp->name = name;
4138 if (!one->oid_valid)
4139 oid_to_hex_r(temp->hex, &null_oid);
4140 else
4141 oid_to_hex_r(temp->hex, &one->oid);
4142 /* Even though we may sometimes borrow the
4143 * contents from the work tree, we always want
4144 * one->mode. mode is trustworthy even when
4145 * !(one->oid_valid), as long as
4146 * DIFF_FILE_VALID(one).
4148 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4150 return temp;
4152 else {
4153 if (diff_populate_filespec(r, one, 0))
4154 die("cannot read data blob for %s", one->path);
4155 prep_temp_blob(r->index, name, temp,
4156 one->data, one->size,
4157 &one->oid, one->mode);
4159 return temp;
4162 static void add_external_diff_name(struct repository *r,
4163 struct argv_array *argv,
4164 const char *name,
4165 struct diff_filespec *df)
4167 struct diff_tempfile *temp = prepare_temp_file(r, name, df);
4168 argv_array_push(argv, temp->name);
4169 argv_array_push(argv, temp->hex);
4170 argv_array_push(argv, temp->mode);
4173 /* An external diff command takes:
4175 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4176 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4179 static void run_external_diff(const char *pgm,
4180 const char *name,
4181 const char *other,
4182 struct diff_filespec *one,
4183 struct diff_filespec *two,
4184 const char *xfrm_msg,
4185 struct diff_options *o)
4187 struct argv_array argv = ARGV_ARRAY_INIT;
4188 struct argv_array env = ARGV_ARRAY_INIT;
4189 struct diff_queue_struct *q = &diff_queued_diff;
4191 argv_array_push(&argv, pgm);
4192 argv_array_push(&argv, name);
4194 if (one && two) {
4195 add_external_diff_name(o->repo, &argv, name, one);
4196 if (!other)
4197 add_external_diff_name(o->repo, &argv, name, two);
4198 else {
4199 add_external_diff_name(o->repo, &argv, other, two);
4200 argv_array_push(&argv, other);
4201 argv_array_push(&argv, xfrm_msg);
4205 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4206 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4208 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
4209 die(_("external diff died, stopping at %s"), name);
4211 remove_tempfile();
4212 argv_array_clear(&argv);
4213 argv_array_clear(&env);
4216 static int similarity_index(struct diff_filepair *p)
4218 return p->score * 100 / MAX_SCORE;
4221 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4223 if (startup_info->have_repository)
4224 return find_unique_abbrev(oid, abbrev);
4225 else {
4226 char *hex = oid_to_hex(oid);
4227 if (abbrev < 0)
4228 abbrev = FALLBACK_DEFAULT_ABBREV;
4229 if (abbrev > the_hash_algo->hexsz)
4230 BUG("oid abbreviation out of range: %d", abbrev);
4231 if (abbrev)
4232 hex[abbrev] = '\0';
4233 return hex;
4237 static void fill_metainfo(struct strbuf *msg,
4238 const char *name,
4239 const char *other,
4240 struct diff_filespec *one,
4241 struct diff_filespec *two,
4242 struct diff_options *o,
4243 struct diff_filepair *p,
4244 int *must_show_header,
4245 int use_color)
4247 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4248 const char *reset = diff_get_color(use_color, DIFF_RESET);
4249 const char *line_prefix = diff_line_prefix(o);
4251 *must_show_header = 1;
4252 strbuf_init(msg, PATH_MAX * 2 + 300);
4253 switch (p->status) {
4254 case DIFF_STATUS_COPIED:
4255 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4256 line_prefix, set, similarity_index(p));
4257 strbuf_addf(msg, "%s\n%s%scopy from ",
4258 reset, line_prefix, set);
4259 quote_c_style(name, msg, NULL, 0);
4260 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4261 quote_c_style(other, msg, NULL, 0);
4262 strbuf_addf(msg, "%s\n", reset);
4263 break;
4264 case DIFF_STATUS_RENAMED:
4265 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4266 line_prefix, set, similarity_index(p));
4267 strbuf_addf(msg, "%s\n%s%srename from ",
4268 reset, line_prefix, set);
4269 quote_c_style(name, msg, NULL, 0);
4270 strbuf_addf(msg, "%s\n%s%srename to ",
4271 reset, line_prefix, set);
4272 quote_c_style(other, msg, NULL, 0);
4273 strbuf_addf(msg, "%s\n", reset);
4274 break;
4275 case DIFF_STATUS_MODIFIED:
4276 if (p->score) {
4277 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4278 line_prefix,
4279 set, similarity_index(p), reset);
4280 break;
4282 /* fallthru */
4283 default:
4284 *must_show_header = 0;
4286 if (one && two && !oideq(&one->oid, &two->oid)) {
4287 const unsigned hexsz = the_hash_algo->hexsz;
4288 int abbrev = o->flags.full_index ? hexsz : DEFAULT_ABBREV;
4290 if (o->flags.binary) {
4291 mmfile_t mf;
4292 if ((!fill_mmfile(o->repo, &mf, one) &&
4293 diff_filespec_is_binary(o->repo, one)) ||
4294 (!fill_mmfile(o->repo, &mf, two) &&
4295 diff_filespec_is_binary(o->repo, two)))
4296 abbrev = hexsz;
4298 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4299 diff_abbrev_oid(&one->oid, abbrev),
4300 diff_abbrev_oid(&two->oid, abbrev));
4301 if (one->mode == two->mode)
4302 strbuf_addf(msg, " %06o", one->mode);
4303 strbuf_addf(msg, "%s\n", reset);
4307 static void run_diff_cmd(const char *pgm,
4308 const char *name,
4309 const char *other,
4310 const char *attr_path,
4311 struct diff_filespec *one,
4312 struct diff_filespec *two,
4313 struct strbuf *msg,
4314 struct diff_options *o,
4315 struct diff_filepair *p)
4317 const char *xfrm_msg = NULL;
4318 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4319 int must_show_header = 0;
4322 if (o->flags.allow_external) {
4323 struct userdiff_driver *drv;
4325 drv = userdiff_find_by_path(o->repo->index, attr_path);
4326 if (drv && drv->external)
4327 pgm = drv->external;
4330 if (msg) {
4332 * don't use colors when the header is intended for an
4333 * external diff driver
4335 fill_metainfo(msg, name, other, one, two, o, p,
4336 &must_show_header,
4337 want_color(o->use_color) && !pgm);
4338 xfrm_msg = msg->len ? msg->buf : NULL;
4341 if (pgm) {
4342 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4343 return;
4345 if (one && two)
4346 builtin_diff(name, other ? other : name,
4347 one, two, xfrm_msg, must_show_header,
4348 o, complete_rewrite);
4349 else
4350 fprintf(o->file, "* Unmerged path %s\n", name);
4353 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4355 if (DIFF_FILE_VALID(one)) {
4356 if (!one->oid_valid) {
4357 struct stat st;
4358 if (one->is_stdin) {
4359 oidclr(&one->oid);
4360 return;
4362 if (lstat(one->path, &st) < 0)
4363 die_errno("stat '%s'", one->path);
4364 if (index_path(istate, &one->oid, one->path, &st, 0))
4365 die("cannot hash %s", one->path);
4368 else
4369 oidclr(&one->oid);
4372 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4374 /* Strip the prefix but do not molest /dev/null and absolute paths */
4375 if (*namep && !is_absolute_path(*namep)) {
4376 *namep += prefix_length;
4377 if (**namep == '/')
4378 ++*namep;
4380 if (*otherp && !is_absolute_path(*otherp)) {
4381 *otherp += prefix_length;
4382 if (**otherp == '/')
4383 ++*otherp;
4387 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4389 const char *pgm = external_diff();
4390 struct strbuf msg;
4391 struct diff_filespec *one = p->one;
4392 struct diff_filespec *two = p->two;
4393 const char *name;
4394 const char *other;
4395 const char *attr_path;
4397 name = one->path;
4398 other = (strcmp(name, two->path) ? two->path : NULL);
4399 attr_path = name;
4400 if (o->prefix_length)
4401 strip_prefix(o->prefix_length, &name, &other);
4403 if (!o->flags.allow_external)
4404 pgm = NULL;
4406 if (DIFF_PAIR_UNMERGED(p)) {
4407 run_diff_cmd(pgm, name, NULL, attr_path,
4408 NULL, NULL, NULL, o, p);
4409 return;
4412 diff_fill_oid_info(one, o->repo->index);
4413 diff_fill_oid_info(two, o->repo->index);
4415 if (!pgm &&
4416 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4417 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4419 * a filepair that changes between file and symlink
4420 * needs to be split into deletion and creation.
4422 struct diff_filespec *null = alloc_filespec(two->path);
4423 run_diff_cmd(NULL, name, other, attr_path,
4424 one, null, &msg,
4425 o, p);
4426 free(null);
4427 strbuf_release(&msg);
4429 null = alloc_filespec(one->path);
4430 run_diff_cmd(NULL, name, other, attr_path,
4431 null, two, &msg, o, p);
4432 free(null);
4434 else
4435 run_diff_cmd(pgm, name, other, attr_path,
4436 one, two, &msg, o, p);
4438 strbuf_release(&msg);
4441 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4442 struct diffstat_t *diffstat)
4444 const char *name;
4445 const char *other;
4447 if (DIFF_PAIR_UNMERGED(p)) {
4448 /* unmerged */
4449 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4450 diffstat, o, p);
4451 return;
4454 name = p->one->path;
4455 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4457 if (o->prefix_length)
4458 strip_prefix(o->prefix_length, &name, &other);
4460 diff_fill_oid_info(p->one, o->repo->index);
4461 diff_fill_oid_info(p->two, o->repo->index);
4463 builtin_diffstat(name, other, p->one, p->two,
4464 diffstat, o, p);
4467 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4469 const char *name;
4470 const char *other;
4471 const char *attr_path;
4473 if (DIFF_PAIR_UNMERGED(p)) {
4474 /* unmerged */
4475 return;
4478 name = p->one->path;
4479 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4480 attr_path = other ? other : name;
4482 if (o->prefix_length)
4483 strip_prefix(o->prefix_length, &name, &other);
4485 diff_fill_oid_info(p->one, o->repo->index);
4486 diff_fill_oid_info(p->two, o->repo->index);
4488 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4491 static void prep_parse_options(struct diff_options *options);
4493 void repo_diff_setup(struct repository *r, struct diff_options *options)
4495 memcpy(options, &default_diff_options, sizeof(*options));
4497 options->file = stdout;
4498 options->repo = r;
4500 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4501 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4502 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4503 options->abbrev = DEFAULT_ABBREV;
4504 options->line_termination = '\n';
4505 options->break_opt = -1;
4506 options->rename_limit = -1;
4507 options->dirstat_permille = diff_dirstat_permille_default;
4508 options->context = diff_context_default;
4509 options->interhunkcontext = diff_interhunk_context_default;
4510 options->ws_error_highlight = ws_error_highlight_default;
4511 options->flags.rename_empty = 1;
4512 options->objfind = NULL;
4514 /* pathchange left =NULL by default */
4515 options->change = diff_change;
4516 options->add_remove = diff_addremove;
4517 options->use_color = diff_use_color_default;
4518 options->detect_rename = diff_detect_rename_default;
4519 options->xdl_opts |= diff_algorithm;
4520 if (diff_indent_heuristic)
4521 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4523 options->orderfile = diff_order_file_cfg;
4525 if (diff_no_prefix) {
4526 options->a_prefix = options->b_prefix = "";
4527 } else if (!diff_mnemonic_prefix) {
4528 options->a_prefix = "a/";
4529 options->b_prefix = "b/";
4532 options->color_moved = diff_color_moved_default;
4533 options->color_moved_ws_handling = diff_color_moved_ws_default;
4535 prep_parse_options(options);
4538 void diff_setup_done(struct diff_options *options)
4540 unsigned check_mask = DIFF_FORMAT_NAME |
4541 DIFF_FORMAT_NAME_STATUS |
4542 DIFF_FORMAT_CHECKDIFF |
4543 DIFF_FORMAT_NO_OUTPUT;
4545 * This must be signed because we're comparing against a potentially
4546 * negative value.
4548 const int hexsz = the_hash_algo->hexsz;
4550 if (options->set_default)
4551 options->set_default(options);
4553 if (HAS_MULTI_BITS(options->output_format & check_mask))
4554 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4556 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4557 die(_("-G, -S and --find-object are mutually exclusive"));
4560 * Most of the time we can say "there are changes"
4561 * only by checking if there are changed paths, but
4562 * --ignore-whitespace* options force us to look
4563 * inside contents.
4566 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
4567 options->flags.diff_from_contents = 1;
4568 else
4569 options->flags.diff_from_contents = 0;
4571 if (options->flags.find_copies_harder)
4572 options->detect_rename = DIFF_DETECT_COPY;
4574 if (!options->flags.relative_name)
4575 options->prefix = NULL;
4576 if (options->prefix)
4577 options->prefix_length = strlen(options->prefix);
4578 else
4579 options->prefix_length = 0;
4581 if (options->output_format & (DIFF_FORMAT_NAME |
4582 DIFF_FORMAT_NAME_STATUS |
4583 DIFF_FORMAT_CHECKDIFF |
4584 DIFF_FORMAT_NO_OUTPUT))
4585 options->output_format &= ~(DIFF_FORMAT_RAW |
4586 DIFF_FORMAT_NUMSTAT |
4587 DIFF_FORMAT_DIFFSTAT |
4588 DIFF_FORMAT_SHORTSTAT |
4589 DIFF_FORMAT_DIRSTAT |
4590 DIFF_FORMAT_SUMMARY |
4591 DIFF_FORMAT_PATCH);
4594 * These cases always need recursive; we do not drop caller-supplied
4595 * recursive bits for other formats here.
4597 if (options->output_format & (DIFF_FORMAT_PATCH |
4598 DIFF_FORMAT_NUMSTAT |
4599 DIFF_FORMAT_DIFFSTAT |
4600 DIFF_FORMAT_SHORTSTAT |
4601 DIFF_FORMAT_DIRSTAT |
4602 DIFF_FORMAT_SUMMARY |
4603 DIFF_FORMAT_CHECKDIFF))
4604 options->flags.recursive = 1;
4606 * Also pickaxe would not work very well if you do not say recursive
4608 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4609 options->flags.recursive = 1;
4611 * When patches are generated, submodules diffed against the work tree
4612 * must be checked for dirtiness too so it can be shown in the output
4614 if (options->output_format & DIFF_FORMAT_PATCH)
4615 options->flags.dirty_submodules = 1;
4617 if (options->detect_rename && options->rename_limit < 0)
4618 options->rename_limit = diff_rename_limit_default;
4619 if (hexsz < options->abbrev)
4620 options->abbrev = hexsz; /* full */
4623 * It does not make sense to show the first hit we happened
4624 * to have found. It does not make sense not to return with
4625 * exit code in such a case either.
4627 if (options->flags.quick) {
4628 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4629 options->flags.exit_with_status = 1;
4632 options->diff_path_counter = 0;
4634 if (options->flags.follow_renames && options->pathspec.nr != 1)
4635 die(_("--follow requires exactly one pathspec"));
4637 if (!options->use_color || external_diff())
4638 options->color_moved = 0;
4640 FREE_AND_NULL(options->parseopts);
4643 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4645 char c, *eq;
4646 int len;
4648 if (*arg != '-')
4649 return 0;
4650 c = *++arg;
4651 if (!c)
4652 return 0;
4653 if (c == arg_short) {
4654 c = *++arg;
4655 if (!c)
4656 return 1;
4657 if (val && isdigit(c)) {
4658 char *end;
4659 int n = strtoul(arg, &end, 10);
4660 if (*end)
4661 return 0;
4662 *val = n;
4663 return 1;
4665 return 0;
4667 if (c != '-')
4668 return 0;
4669 arg++;
4670 eq = strchrnul(arg, '=');
4671 len = eq - arg;
4672 if (!len || strncmp(arg, arg_long, len))
4673 return 0;
4674 if (*eq) {
4675 int n;
4676 char *end;
4677 if (!isdigit(*++eq))
4678 return 0;
4679 n = strtoul(eq, &end, 10);
4680 if (*end)
4681 return 0;
4682 *val = n;
4684 return 1;
4687 static inline int short_opt(char opt, const char **argv,
4688 const char **optarg)
4690 const char *arg = argv[0];
4691 if (arg[0] != '-' || arg[1] != opt)
4692 return 0;
4693 if (arg[2] != '\0') {
4694 *optarg = arg + 2;
4695 return 1;
4697 if (!argv[1])
4698 die("Option '%c' requires a value", opt);
4699 *optarg = argv[1];
4700 return 2;
4703 int parse_long_opt(const char *opt, const char **argv,
4704 const char **optarg)
4706 const char *arg = argv[0];
4707 if (!skip_prefix(arg, "--", &arg))
4708 return 0;
4709 if (!skip_prefix(arg, opt, &arg))
4710 return 0;
4711 if (*arg == '=') { /* stuck form: --option=value */
4712 *optarg = arg + 1;
4713 return 1;
4715 if (*arg != '\0')
4716 return 0;
4717 /* separate form: --option value */
4718 if (!argv[1])
4719 die("Option '--%s' requires a value", opt);
4720 *optarg = argv[1];
4721 return 2;
4724 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4726 struct diff_options *options = opt->value;
4727 int width = options->stat_width;
4728 int name_width = options->stat_name_width;
4729 int graph_width = options->stat_graph_width;
4730 int count = options->stat_count;
4731 char *end;
4733 BUG_ON_OPT_NEG(unset);
4735 if (!strcmp(opt->long_name, "stat")) {
4736 if (value) {
4737 width = strtoul(value, &end, 10);
4738 if (*end == ',')
4739 name_width = strtoul(end+1, &end, 10);
4740 if (*end == ',')
4741 count = strtoul(end+1, &end, 10);
4742 if (*end)
4743 return error(_("invalid --stat value: %s"), value);
4745 } else if (!strcmp(opt->long_name, "stat-width")) {
4746 width = strtoul(value, &end, 10);
4747 if (*end)
4748 return error(_("%s expects a numerical value"),
4749 opt->long_name);
4750 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4751 name_width = strtoul(value, &end, 10);
4752 if (*end)
4753 return error(_("%s expects a numerical value"),
4754 opt->long_name);
4755 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4756 graph_width = strtoul(value, &end, 10);
4757 if (*end)
4758 return error(_("%s expects a numerical value"),
4759 opt->long_name);
4760 } else if (!strcmp(opt->long_name, "stat-count")) {
4761 count = strtoul(value, &end, 10);
4762 if (*end)
4763 return error(_("%s expects a numerical value"),
4764 opt->long_name);
4765 } else
4766 BUG("%s should not get here", opt->long_name);
4768 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4769 options->stat_name_width = name_width;
4770 options->stat_graph_width = graph_width;
4771 options->stat_width = width;
4772 options->stat_count = count;
4773 return 0;
4776 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4778 struct strbuf errmsg = STRBUF_INIT;
4779 if (parse_dirstat_params(options, params, &errmsg))
4780 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4781 errmsg.buf);
4782 strbuf_release(&errmsg);
4784 * The caller knows a dirstat-related option is given from the command
4785 * line; allow it to say "return this_function();"
4787 options->output_format |= DIFF_FORMAT_DIRSTAT;
4788 return 1;
4791 static int parse_submodule_opt(struct diff_options *options, const char *value)
4793 if (parse_submodule_params(options, value))
4794 die(_("Failed to parse --submodule option parameter: '%s'"),
4795 value);
4796 return 1;
4799 static const char diff_status_letters[] = {
4800 DIFF_STATUS_ADDED,
4801 DIFF_STATUS_COPIED,
4802 DIFF_STATUS_DELETED,
4803 DIFF_STATUS_MODIFIED,
4804 DIFF_STATUS_RENAMED,
4805 DIFF_STATUS_TYPE_CHANGED,
4806 DIFF_STATUS_UNKNOWN,
4807 DIFF_STATUS_UNMERGED,
4808 DIFF_STATUS_FILTER_AON,
4809 DIFF_STATUS_FILTER_BROKEN,
4810 '\0',
4813 static unsigned int filter_bit['Z' + 1];
4815 static void prepare_filter_bits(void)
4817 int i;
4819 if (!filter_bit[DIFF_STATUS_ADDED]) {
4820 for (i = 0; diff_status_letters[i]; i++)
4821 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4825 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4827 return opt->filter & filter_bit[(int) status];
4830 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4832 int i, optch;
4834 prepare_filter_bits();
4837 * If there is a negation e.g. 'd' in the input, and we haven't
4838 * initialized the filter field with another --diff-filter, start
4839 * from full set of bits, except for AON.
4841 if (!opt->filter) {
4842 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4843 if (optch < 'a' || 'z' < optch)
4844 continue;
4845 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4846 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4847 break;
4851 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4852 unsigned int bit;
4853 int negate;
4855 if ('a' <= optch && optch <= 'z') {
4856 negate = 1;
4857 optch = toupper(optch);
4858 } else {
4859 negate = 0;
4862 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4863 if (!bit)
4864 return optarg[i];
4865 if (negate)
4866 opt->filter &= ~bit;
4867 else
4868 opt->filter |= bit;
4870 return 0;
4873 static void enable_patch_output(int *fmt)
4875 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4876 *fmt |= DIFF_FORMAT_PATCH;
4879 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4881 int val = parse_ws_error_highlight(arg);
4883 if (val < 0) {
4884 error("unknown value after ws-error-highlight=%.*s",
4885 -1 - val, arg);
4886 return 0;
4888 opt->ws_error_highlight = val;
4889 return 1;
4892 static int parse_objfind_opt(struct diff_options *opt, const char *arg)
4894 struct object_id oid;
4896 if (get_oid(arg, &oid))
4897 return error("unable to resolve '%s'", arg);
4899 if (!opt->objfind)
4900 opt->objfind = xcalloc(1, sizeof(*opt->objfind));
4902 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4903 opt->flags.recursive = 1;
4904 opt->flags.tree_in_recursive = 1;
4905 oidset_insert(opt->objfind, &oid);
4906 return 1;
4909 static int diff_opt_break_rewrites(const struct option *opt,
4910 const char *arg, int unset)
4912 int *break_opt = opt->value;
4913 int opt1, opt2;
4915 BUG_ON_OPT_NEG(unset);
4916 if (!arg)
4917 arg = "";
4918 opt1 = parse_rename_score(&arg);
4919 if (*arg == 0)
4920 opt2 = 0;
4921 else if (*arg != '/')
4922 return error(_("%s expects <n>/<m> form"), opt->long_name);
4923 else {
4924 arg++;
4925 opt2 = parse_rename_score(&arg);
4927 if (*arg != 0)
4928 return error(_("%s expects <n>/<m> form"), opt->long_name);
4929 *break_opt = opt1 | (opt2 << 16);
4930 return 0;
4933 static int diff_opt_char(const struct option *opt,
4934 const char *arg, int unset)
4936 char *value = opt->value;
4938 BUG_ON_OPT_NEG(unset);
4939 if (arg[1])
4940 return error(_("%s expects a character, got '%s'"),
4941 opt->long_name, arg);
4942 *value = arg[0];
4943 return 0;
4946 static int diff_opt_compact_summary(const struct option *opt,
4947 const char *arg, int unset)
4949 struct diff_options *options = opt->value;
4951 BUG_ON_OPT_ARG(arg);
4952 if (unset) {
4953 options->flags.stat_with_summary = 0;
4954 } else {
4955 options->flags.stat_with_summary = 1;
4956 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4958 return 0;
4961 static int diff_opt_dirstat(const struct option *opt,
4962 const char *arg, int unset)
4964 struct diff_options *options = opt->value;
4966 BUG_ON_OPT_NEG(unset);
4967 if (!strcmp(opt->long_name, "cumulative")) {
4968 if (arg)
4969 BUG("how come --cumulative take a value?");
4970 arg = "cumulative";
4971 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
4972 parse_dirstat_opt(options, "files");
4973 parse_dirstat_opt(options, arg ? arg : "");
4974 return 0;
4977 static int diff_opt_find_copies(const struct option *opt,
4978 const char *arg, int unset)
4980 struct diff_options *options = opt->value;
4982 BUG_ON_OPT_NEG(unset);
4983 if (!arg)
4984 arg = "";
4985 options->rename_score = parse_rename_score(&arg);
4986 if (*arg != 0)
4987 return error(_("invalid argument to %s"), opt->long_name);
4989 if (options->detect_rename == DIFF_DETECT_COPY)
4990 options->flags.find_copies_harder = 1;
4991 else
4992 options->detect_rename = DIFF_DETECT_COPY;
4994 return 0;
4997 static int diff_opt_find_renames(const struct option *opt,
4998 const char *arg, int unset)
5000 struct diff_options *options = opt->value;
5002 BUG_ON_OPT_NEG(unset);
5003 if (!arg)
5004 arg = "";
5005 options->rename_score = parse_rename_score(&arg);
5006 if (*arg != 0)
5007 return error(_("invalid argument to %s"), opt->long_name);
5009 options->detect_rename = DIFF_DETECT_RENAME;
5010 return 0;
5013 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5014 const struct option *opt,
5015 const char *arg, int unset)
5017 struct diff_options *options = opt->value;
5018 char *path;
5020 BUG_ON_OPT_NEG(unset);
5021 path = prefix_filename(ctx->prefix, arg);
5022 options->file = xfopen(path, "w");
5023 options->close_file = 1;
5024 if (options->use_color != GIT_COLOR_ALWAYS)
5025 options->use_color = GIT_COLOR_NEVER;
5026 free(path);
5027 return 0;
5030 static int diff_opt_relative(const struct option *opt,
5031 const char *arg, int unset)
5033 struct diff_options *options = opt->value;
5035 BUG_ON_OPT_NEG(unset);
5036 options->flags.relative_name = 1;
5037 if (arg)
5038 options->prefix = arg;
5039 return 0;
5042 static int diff_opt_unified(const struct option *opt,
5043 const char *arg, int unset)
5045 struct diff_options *options = opt->value;
5046 char *s;
5048 BUG_ON_OPT_NEG(unset);
5050 options->context = strtol(arg, &s, 10);
5051 if (*s)
5052 return error(_("%s expects a numerical value"), "--unified");
5053 enable_patch_output(&options->output_format);
5055 return 0;
5058 static void prep_parse_options(struct diff_options *options)
5060 struct option parseopts[] = {
5061 OPT_GROUP(N_("Diff output format options")),
5062 OPT_BITOP('p', "patch", &options->output_format,
5063 N_("generate patch"),
5064 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5065 OPT_BIT_F('s', "no-patch", &options->output_format,
5066 N_("suppress diff output"),
5067 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5068 OPT_BITOP('u', NULL, &options->output_format,
5069 N_("generate patch"),
5070 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5071 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5072 N_("generate diffs with <n> lines context"),
5073 PARSE_OPT_NONEG, diff_opt_unified),
5074 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5075 N_("generate diffs with <n> lines context")),
5076 OPT_BIT_F(0, "raw", &options->output_format,
5077 N_("generate the diff in raw format"),
5078 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5079 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5080 N_("synonym for '-p --raw'"),
5081 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5082 DIFF_FORMAT_NO_OUTPUT),
5083 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5084 N_("synonym for '-p --stat'"),
5085 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5086 DIFF_FORMAT_NO_OUTPUT),
5087 OPT_BIT_F(0, "numstat", &options->output_format,
5088 N_("machine friendly --stat"),
5089 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5090 OPT_BIT_F(0, "shortstat", &options->output_format,
5091 N_("output only the last line of --stat"),
5092 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5093 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5094 N_("output the distribution of relative amount of changes for each sub-directory"),
5095 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5096 diff_opt_dirstat),
5097 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5098 N_("synonym for --dirstat=cumulative"),
5099 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5100 diff_opt_dirstat),
5101 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5102 N_("synonym for --dirstat=files,param1,param2..."),
5103 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5104 diff_opt_dirstat),
5105 OPT_BIT_F(0, "check", &options->output_format,
5106 N_("warn if changes introduce conflict markers or whitespace errors"),
5107 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5108 OPT_BIT_F(0, "summary", &options->output_format,
5109 N_("condensed summary such as creations, renames and mode changes"),
5110 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5111 OPT_BIT_F(0, "name-only", &options->output_format,
5112 N_("show only names of changed files"),
5113 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5114 OPT_BIT_F(0, "name-status", &options->output_format,
5115 N_("show only names and status of changed files"),
5116 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5117 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5118 N_("generate diffstat"),
5119 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5120 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5121 N_("generate diffstat with a given width"),
5122 PARSE_OPT_NONEG, diff_opt_stat),
5123 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5124 N_("generate diffstat with a given name width"),
5125 PARSE_OPT_NONEG, diff_opt_stat),
5126 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5127 N_("generate diffstat with a given graph width"),
5128 PARSE_OPT_NONEG, diff_opt_stat),
5129 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5130 N_("generate diffstat with limited lines"),
5131 PARSE_OPT_NONEG, diff_opt_stat),
5132 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5133 N_("generate compact summary in diffstat"),
5134 PARSE_OPT_NOARG, diff_opt_compact_summary),
5135 OPT_CALLBACK_F(0, "output-indicator-new",
5136 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5137 N_("<char>"),
5138 N_("specify the character to indicate a new line instead of '+'"),
5139 PARSE_OPT_NONEG, diff_opt_char),
5140 OPT_CALLBACK_F(0, "output-indicator-old",
5141 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5142 N_("<char>"),
5143 N_("specify the character to indicate an old line instead of '-'"),
5144 PARSE_OPT_NONEG, diff_opt_char),
5145 OPT_CALLBACK_F(0, "output-indicator-context",
5146 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5147 N_("<char>"),
5148 N_("specify the character to indicate a context instead of ' '"),
5149 PARSE_OPT_NONEG, diff_opt_char),
5151 OPT_GROUP(N_("Diff rename options")),
5152 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5153 N_("break complete rewrite changes into pairs of delete and create"),
5154 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5155 diff_opt_break_rewrites),
5156 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5157 N_("detect renames"),
5158 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5159 diff_opt_find_renames),
5160 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5161 N_("omit the preimage for deletes"),
5162 1, PARSE_OPT_NONEG),
5163 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5164 N_("detect copies"),
5165 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5166 diff_opt_find_copies),
5167 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5168 N_("use unmodified files as source to find copies")),
5169 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5170 N_("disable rename detection"),
5171 0, PARSE_OPT_NONEG),
5172 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5173 N_("use empty blobs as rename source")),
5175 OPT_GROUP(N_("Diff algorithm options")),
5176 OPT_BIT(0, "minimal", &options->xdl_opts,
5177 N_("produce the smallest possible diff"),
5178 XDF_NEED_MINIMAL),
5179 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5180 N_("ignore whitespace when comparing lines"),
5181 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5182 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5183 N_("ignore changes in amount of whitespace"),
5184 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5185 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5186 N_("ignore changes in whitespace at EOL"),
5187 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5188 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5189 N_("ignore carrier-return at the end of line"),
5190 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5191 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5192 N_("ignore changes whose lines are all blank"),
5193 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5195 OPT_GROUP(N_("Diff other options")),
5196 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5197 N_("when run from subdir, exclude changes outside and show relative paths"),
5198 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5199 diff_opt_relative),
5200 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5201 N_("Output to a specific file"),
5202 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5204 OPT_END()
5207 ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
5208 memcpy(options->parseopts, parseopts, sizeof(parseopts));
5211 int diff_opt_parse(struct diff_options *options,
5212 const char **av, int ac, const char *prefix)
5214 const char *arg = av[0];
5215 const char *optarg;
5216 int argcount;
5218 if (!prefix)
5219 prefix = "";
5221 ac = parse_options(ac, av, prefix, options->parseopts, NULL,
5222 PARSE_OPT_KEEP_DASHDASH |
5223 PARSE_OPT_KEEP_UNKNOWN |
5224 PARSE_OPT_NO_INTERNAL_HELP |
5225 PARSE_OPT_ONE_SHOT |
5226 PARSE_OPT_STOP_AT_NON_OPTION);
5228 if (ac)
5229 return ac;
5231 /* xdiff options */
5232 if (!strcmp(arg, "--indent-heuristic"))
5233 DIFF_XDL_SET(options, INDENT_HEURISTIC);
5234 else if (!strcmp(arg, "--no-indent-heuristic"))
5235 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
5236 else if (!strcmp(arg, "--patience")) {
5237 int i;
5238 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5240 * Both --patience and --anchored use PATIENCE_DIFF
5241 * internally, so remove any anchors previously
5242 * specified.
5244 for (i = 0; i < options->anchors_nr; i++)
5245 free(options->anchors[i]);
5246 options->anchors_nr = 0;
5247 } else if (!strcmp(arg, "--histogram"))
5248 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
5249 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
5250 long value = parse_algorithm_value(optarg);
5251 if (value < 0)
5252 return error("option diff-algorithm accepts \"myers\", "
5253 "\"minimal\", \"patience\" and \"histogram\"");
5254 /* clear out previous settings */
5255 DIFF_XDL_CLR(options, NEED_MINIMAL);
5256 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
5257 options->xdl_opts |= value;
5258 return argcount;
5259 } else if (skip_prefix(arg, "--anchored=", &arg)) {
5260 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5261 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5262 options->anchors_alloc);
5263 options->anchors[options->anchors_nr++] = xstrdup(arg);
5266 /* flags options */
5267 else if (!strcmp(arg, "--binary")) {
5268 enable_patch_output(&options->output_format);
5269 options->flags.binary = 1;
5271 else if (!strcmp(arg, "--full-index"))
5272 options->flags.full_index = 1;
5273 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
5274 options->flags.text = 1;
5275 else if (!strcmp(arg, "-R"))
5276 options->flags.reverse_diff = 1;
5277 else if (!strcmp(arg, "--follow"))
5278 options->flags.follow_renames = 1;
5279 else if (!strcmp(arg, "--no-follow")) {
5280 options->flags.follow_renames = 0;
5281 options->flags.default_follow_renames = 0;
5282 } else if (skip_to_optional_arg_default(arg, "--color", &arg, "always")) {
5283 int value = git_config_colorbool(NULL, arg);
5284 if (value < 0)
5285 return error("option `color' expects \"always\", \"auto\", or \"never\"");
5286 options->use_color = value;
5288 else if (!strcmp(arg, "--no-color"))
5289 options->use_color = 0;
5290 else if (!strcmp(arg, "--color-moved")) {
5291 if (diff_color_moved_default)
5292 options->color_moved = diff_color_moved_default;
5293 if (options->color_moved == COLOR_MOVED_NO)
5294 options->color_moved = COLOR_MOVED_DEFAULT;
5295 } else if (!strcmp(arg, "--no-color-moved"))
5296 options->color_moved = COLOR_MOVED_NO;
5297 else if (skip_prefix(arg, "--color-moved=", &arg)) {
5298 int cm = parse_color_moved(arg);
5299 if (cm < 0)
5300 return error("bad --color-moved argument: %s", arg);
5301 options->color_moved = cm;
5302 } else if (!strcmp(arg, "--no-color-moved-ws")) {
5303 options->color_moved_ws_handling = 0;
5304 } else if (skip_prefix(arg, "--color-moved-ws=", &arg)) {
5305 unsigned cm = parse_color_moved_ws(arg);
5306 if (cm & COLOR_MOVED_WS_ERROR)
5307 return -1;
5308 options->color_moved_ws_handling = cm;
5309 } else if (skip_to_optional_arg_default(arg, "--color-words", &options->word_regex, NULL)) {
5310 options->use_color = 1;
5311 options->word_diff = DIFF_WORDS_COLOR;
5313 else if (!strcmp(arg, "--word-diff")) {
5314 if (options->word_diff == DIFF_WORDS_NONE)
5315 options->word_diff = DIFF_WORDS_PLAIN;
5317 else if (skip_prefix(arg, "--word-diff=", &arg)) {
5318 if (!strcmp(arg, "plain"))
5319 options->word_diff = DIFF_WORDS_PLAIN;
5320 else if (!strcmp(arg, "color")) {
5321 options->use_color = 1;
5322 options->word_diff = DIFF_WORDS_COLOR;
5324 else if (!strcmp(arg, "porcelain"))
5325 options->word_diff = DIFF_WORDS_PORCELAIN;
5326 else if (!strcmp(arg, "none"))
5327 options->word_diff = DIFF_WORDS_NONE;
5328 else
5329 die("bad --word-diff argument: %s", arg);
5331 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
5332 if (options->word_diff == DIFF_WORDS_NONE)
5333 options->word_diff = DIFF_WORDS_PLAIN;
5334 options->word_regex = optarg;
5335 return argcount;
5337 else if (!strcmp(arg, "--exit-code"))
5338 options->flags.exit_with_status = 1;
5339 else if (!strcmp(arg, "--quiet"))
5340 options->flags.quick = 1;
5341 else if (!strcmp(arg, "--ext-diff"))
5342 options->flags.allow_external = 1;
5343 else if (!strcmp(arg, "--no-ext-diff"))
5344 options->flags.allow_external = 0;
5345 else if (!strcmp(arg, "--textconv")) {
5346 options->flags.allow_textconv = 1;
5347 options->flags.textconv_set_via_cmdline = 1;
5348 } else if (!strcmp(arg, "--no-textconv"))
5349 options->flags.allow_textconv = 0;
5350 else if (skip_to_optional_arg_default(arg, "--ignore-submodules", &arg, "all")) {
5351 options->flags.override_submodule_config = 1;
5352 handle_ignore_submodules_arg(options, arg);
5353 } else if (skip_to_optional_arg_default(arg, "--submodule", &arg, "log"))
5354 return parse_submodule_opt(options, arg);
5355 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
5356 return parse_ws_error_highlight_opt(options, arg);
5357 else if (!strcmp(arg, "--ita-invisible-in-index"))
5358 options->ita_invisible_in_index = 1;
5359 else if (!strcmp(arg, "--ita-visible-in-index"))
5360 options->ita_invisible_in_index = 0;
5362 /* misc options */
5363 else if (!strcmp(arg, "-z"))
5364 options->line_termination = 0;
5365 else if ((argcount = short_opt('l', av, &optarg))) {
5366 options->rename_limit = strtoul(optarg, NULL, 10);
5367 return argcount;
5369 else if ((argcount = short_opt('S', av, &optarg))) {
5370 options->pickaxe = optarg;
5371 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5372 return argcount;
5373 } else if ((argcount = short_opt('G', av, &optarg))) {
5374 options->pickaxe = optarg;
5375 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5376 return argcount;
5378 else if (!strcmp(arg, "--pickaxe-all"))
5379 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
5380 else if (!strcmp(arg, "--pickaxe-regex"))
5381 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
5382 else if ((argcount = short_opt('O', av, &optarg))) {
5383 options->orderfile = prefix_filename(prefix, optarg);
5384 return argcount;
5385 } else if (skip_prefix(arg, "--find-object=", &arg))
5386 return parse_objfind_opt(options, arg);
5387 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
5388 int offending = parse_diff_filter_opt(optarg, options);
5389 if (offending)
5390 die("unknown change class '%c' in --diff-filter=%s",
5391 offending, optarg);
5392 return argcount;
5394 else if (!strcmp(arg, "--no-abbrev"))
5395 options->abbrev = 0;
5396 else if (!strcmp(arg, "--abbrev"))
5397 options->abbrev = DEFAULT_ABBREV;
5398 else if (skip_prefix(arg, "--abbrev=", &arg)) {
5399 options->abbrev = strtoul(arg, NULL, 10);
5400 if (options->abbrev < MINIMUM_ABBREV)
5401 options->abbrev = MINIMUM_ABBREV;
5402 else if (the_hash_algo->hexsz < options->abbrev)
5403 options->abbrev = the_hash_algo->hexsz;
5405 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
5406 options->a_prefix = optarg;
5407 return argcount;
5409 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
5410 options->line_prefix = optarg;
5411 options->line_prefix_length = strlen(options->line_prefix);
5412 graph_setup_line_prefix(options);
5413 return argcount;
5415 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
5416 options->b_prefix = optarg;
5417 return argcount;
5419 else if (!strcmp(arg, "--no-prefix"))
5420 options->a_prefix = options->b_prefix = "";
5421 else if (opt_arg(arg, '\0', "inter-hunk-context",
5422 &options->interhunkcontext))
5424 else
5425 return 0;
5426 return 1;
5429 int parse_rename_score(const char **cp_p)
5431 unsigned long num, scale;
5432 int ch, dot;
5433 const char *cp = *cp_p;
5435 num = 0;
5436 scale = 1;
5437 dot = 0;
5438 for (;;) {
5439 ch = *cp;
5440 if ( !dot && ch == '.' ) {
5441 scale = 1;
5442 dot = 1;
5443 } else if ( ch == '%' ) {
5444 scale = dot ? scale*100 : 100;
5445 cp++; /* % is always at the end */
5446 break;
5447 } else if ( ch >= '0' && ch <= '9' ) {
5448 if ( scale < 100000 ) {
5449 scale *= 10;
5450 num = (num*10) + (ch-'0');
5452 } else {
5453 break;
5455 cp++;
5457 *cp_p = cp;
5459 /* user says num divided by scale and we say internally that
5460 * is MAX_SCORE * num / scale.
5462 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5465 struct diff_queue_struct diff_queued_diff;
5467 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5469 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5470 queue->queue[queue->nr++] = dp;
5473 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5474 struct diff_filespec *one,
5475 struct diff_filespec *two)
5477 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5478 dp->one = one;
5479 dp->two = two;
5480 if (queue)
5481 diff_q(queue, dp);
5482 return dp;
5485 void diff_free_filepair(struct diff_filepair *p)
5487 free_filespec(p->one);
5488 free_filespec(p->two);
5489 free(p);
5492 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5494 int abblen;
5495 const char *abbrev;
5497 /* Do we want all 40 hex characters? */
5498 if (len == the_hash_algo->hexsz)
5499 return oid_to_hex(oid);
5501 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5502 abbrev = diff_abbrev_oid(oid, len);
5504 if (!print_sha1_ellipsis())
5505 return abbrev;
5507 abblen = strlen(abbrev);
5510 * In well-behaved cases, where the abbreviated result is the
5511 * same as the requested length, append three dots after the
5512 * abbreviation (hence the whole logic is limited to the case
5513 * where abblen < 37); when the actual abbreviated result is a
5514 * bit longer than the requested length, we reduce the number
5515 * of dots so that they match the well-behaved ones. However,
5516 * if the actual abbreviation is longer than the requested
5517 * length by more than three, we give up on aligning, and add
5518 * three dots anyway, to indicate that the output is not the
5519 * full object name. Yes, this may be suboptimal, but this
5520 * appears only in "diff --raw --abbrev" output and it is not
5521 * worth the effort to change it now. Note that this would
5522 * likely to work fine when the automatic sizing of default
5523 * abbreviation length is used--we would be fed -1 in "len" in
5524 * that case, and will end up always appending three-dots, but
5525 * the automatic sizing is supposed to give abblen that ensures
5526 * uniqueness across all objects (statistically speaking).
5528 if (abblen < the_hash_algo->hexsz - 3) {
5529 static char hex[GIT_MAX_HEXSZ + 1];
5530 if (len < abblen && abblen <= len + 2)
5531 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5532 else
5533 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5534 return hex;
5537 return oid_to_hex(oid);
5540 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5542 int line_termination = opt->line_termination;
5543 int inter_name_termination = line_termination ? '\t' : '\0';
5545 fprintf(opt->file, "%s", diff_line_prefix(opt));
5546 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5547 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5548 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5549 fprintf(opt->file, "%s ",
5550 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5552 if (p->score) {
5553 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5554 inter_name_termination);
5555 } else {
5556 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5559 if (p->status == DIFF_STATUS_COPIED ||
5560 p->status == DIFF_STATUS_RENAMED) {
5561 const char *name_a, *name_b;
5562 name_a = p->one->path;
5563 name_b = p->two->path;
5564 strip_prefix(opt->prefix_length, &name_a, &name_b);
5565 write_name_quoted(name_a, opt->file, inter_name_termination);
5566 write_name_quoted(name_b, opt->file, line_termination);
5567 } else {
5568 const char *name_a, *name_b;
5569 name_a = p->one->mode ? p->one->path : p->two->path;
5570 name_b = NULL;
5571 strip_prefix(opt->prefix_length, &name_a, &name_b);
5572 write_name_quoted(name_a, opt->file, line_termination);
5576 int diff_unmodified_pair(struct diff_filepair *p)
5578 /* This function is written stricter than necessary to support
5579 * the currently implemented transformers, but the idea is to
5580 * let transformers to produce diff_filepairs any way they want,
5581 * and filter and clean them up here before producing the output.
5583 struct diff_filespec *one = p->one, *two = p->two;
5585 if (DIFF_PAIR_UNMERGED(p))
5586 return 0; /* unmerged is interesting */
5588 /* deletion, addition, mode or type change
5589 * and rename are all interesting.
5591 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5592 DIFF_PAIR_MODE_CHANGED(p) ||
5593 strcmp(one->path, two->path))
5594 return 0;
5596 /* both are valid and point at the same path. that is, we are
5597 * dealing with a change.
5599 if (one->oid_valid && two->oid_valid &&
5600 oideq(&one->oid, &two->oid) &&
5601 !one->dirty_submodule && !two->dirty_submodule)
5602 return 1; /* no change */
5603 if (!one->oid_valid && !two->oid_valid)
5604 return 1; /* both look at the same file on the filesystem. */
5605 return 0;
5608 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5610 if (diff_unmodified_pair(p))
5611 return;
5613 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5614 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5615 return; /* no tree diffs in patch format */
5617 run_diff(p, o);
5620 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5621 struct diffstat_t *diffstat)
5623 if (diff_unmodified_pair(p))
5624 return;
5626 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5627 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5628 return; /* no useful stat for tree diffs */
5630 run_diffstat(p, o, diffstat);
5633 static void diff_flush_checkdiff(struct diff_filepair *p,
5634 struct diff_options *o)
5636 if (diff_unmodified_pair(p))
5637 return;
5639 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5640 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5641 return; /* nothing to check in tree diffs */
5643 run_checkdiff(p, o);
5646 int diff_queue_is_empty(void)
5648 struct diff_queue_struct *q = &diff_queued_diff;
5649 int i;
5650 for (i = 0; i < q->nr; i++)
5651 if (!diff_unmodified_pair(q->queue[i]))
5652 return 0;
5653 return 1;
5656 #if DIFF_DEBUG
5657 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5659 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5660 x, one ? one : "",
5661 s->path,
5662 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5663 s->mode,
5664 s->oid_valid ? oid_to_hex(&s->oid) : "");
5665 fprintf(stderr, "queue[%d] %s size %lu\n",
5666 x, one ? one : "",
5667 s->size);
5670 void diff_debug_filepair(const struct diff_filepair *p, int i)
5672 diff_debug_filespec(p->one, i, "one");
5673 diff_debug_filespec(p->two, i, "two");
5674 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5675 p->score, p->status ? p->status : '?',
5676 p->one->rename_used, p->broken_pair);
5679 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5681 int i;
5682 if (msg)
5683 fprintf(stderr, "%s\n", msg);
5684 fprintf(stderr, "q->nr = %d\n", q->nr);
5685 for (i = 0; i < q->nr; i++) {
5686 struct diff_filepair *p = q->queue[i];
5687 diff_debug_filepair(p, i);
5690 #endif
5692 static void diff_resolve_rename_copy(void)
5694 int i;
5695 struct diff_filepair *p;
5696 struct diff_queue_struct *q = &diff_queued_diff;
5698 diff_debug_queue("resolve-rename-copy", q);
5700 for (i = 0; i < q->nr; i++) {
5701 p = q->queue[i];
5702 p->status = 0; /* undecided */
5703 if (DIFF_PAIR_UNMERGED(p))
5704 p->status = DIFF_STATUS_UNMERGED;
5705 else if (!DIFF_FILE_VALID(p->one))
5706 p->status = DIFF_STATUS_ADDED;
5707 else if (!DIFF_FILE_VALID(p->two))
5708 p->status = DIFF_STATUS_DELETED;
5709 else if (DIFF_PAIR_TYPE_CHANGED(p))
5710 p->status = DIFF_STATUS_TYPE_CHANGED;
5712 /* from this point on, we are dealing with a pair
5713 * whose both sides are valid and of the same type, i.e.
5714 * either in-place edit or rename/copy edit.
5716 else if (DIFF_PAIR_RENAME(p)) {
5718 * A rename might have re-connected a broken
5719 * pair up, causing the pathnames to be the
5720 * same again. If so, that's not a rename at
5721 * all, just a modification..
5723 * Otherwise, see if this source was used for
5724 * multiple renames, in which case we decrement
5725 * the count, and call it a copy.
5727 if (!strcmp(p->one->path, p->two->path))
5728 p->status = DIFF_STATUS_MODIFIED;
5729 else if (--p->one->rename_used > 0)
5730 p->status = DIFF_STATUS_COPIED;
5731 else
5732 p->status = DIFF_STATUS_RENAMED;
5734 else if (!oideq(&p->one->oid, &p->two->oid) ||
5735 p->one->mode != p->two->mode ||
5736 p->one->dirty_submodule ||
5737 p->two->dirty_submodule ||
5738 is_null_oid(&p->one->oid))
5739 p->status = DIFF_STATUS_MODIFIED;
5740 else {
5741 /* This is a "no-change" entry and should not
5742 * happen anymore, but prepare for broken callers.
5744 error("feeding unmodified %s to diffcore",
5745 p->one->path);
5746 p->status = DIFF_STATUS_UNKNOWN;
5749 diff_debug_queue("resolve-rename-copy done", q);
5752 static int check_pair_status(struct diff_filepair *p)
5754 switch (p->status) {
5755 case DIFF_STATUS_UNKNOWN:
5756 return 0;
5757 case 0:
5758 die("internal error in diff-resolve-rename-copy");
5759 default:
5760 return 1;
5764 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5766 int fmt = opt->output_format;
5768 if (fmt & DIFF_FORMAT_CHECKDIFF)
5769 diff_flush_checkdiff(p, opt);
5770 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5771 diff_flush_raw(p, opt);
5772 else if (fmt & DIFF_FORMAT_NAME) {
5773 const char *name_a, *name_b;
5774 name_a = p->two->path;
5775 name_b = NULL;
5776 strip_prefix(opt->prefix_length, &name_a, &name_b);
5777 fprintf(opt->file, "%s", diff_line_prefix(opt));
5778 write_name_quoted(name_a, opt->file, opt->line_termination);
5782 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5784 struct strbuf sb = STRBUF_INIT;
5785 if (fs->mode)
5786 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5787 else
5788 strbuf_addf(&sb, " %s ", newdelete);
5790 quote_c_style(fs->path, &sb, NULL, 0);
5791 strbuf_addch(&sb, '\n');
5792 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5793 sb.buf, sb.len, 0);
5794 strbuf_release(&sb);
5797 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5798 int show_name)
5800 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5801 struct strbuf sb = STRBUF_INIT;
5802 strbuf_addf(&sb, " mode change %06o => %06o",
5803 p->one->mode, p->two->mode);
5804 if (show_name) {
5805 strbuf_addch(&sb, ' ');
5806 quote_c_style(p->two->path, &sb, NULL, 0);
5808 strbuf_addch(&sb, '\n');
5809 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5810 sb.buf, sb.len, 0);
5811 strbuf_release(&sb);
5815 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5816 struct diff_filepair *p)
5818 struct strbuf sb = STRBUF_INIT;
5819 struct strbuf names = STRBUF_INIT;
5821 pprint_rename(&names, p->one->path, p->two->path);
5822 strbuf_addf(&sb, " %s %s (%d%%)\n",
5823 renamecopy, names.buf, similarity_index(p));
5824 strbuf_release(&names);
5825 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5826 sb.buf, sb.len, 0);
5827 show_mode_change(opt, p, 0);
5828 strbuf_release(&sb);
5831 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5833 switch(p->status) {
5834 case DIFF_STATUS_DELETED:
5835 show_file_mode_name(opt, "delete", p->one);
5836 break;
5837 case DIFF_STATUS_ADDED:
5838 show_file_mode_name(opt, "create", p->two);
5839 break;
5840 case DIFF_STATUS_COPIED:
5841 show_rename_copy(opt, "copy", p);
5842 break;
5843 case DIFF_STATUS_RENAMED:
5844 show_rename_copy(opt, "rename", p);
5845 break;
5846 default:
5847 if (p->score) {
5848 struct strbuf sb = STRBUF_INIT;
5849 strbuf_addstr(&sb, " rewrite ");
5850 quote_c_style(p->two->path, &sb, NULL, 0);
5851 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5852 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5853 sb.buf, sb.len, 0);
5854 strbuf_release(&sb);
5856 show_mode_change(opt, p, !p->score);
5857 break;
5861 struct patch_id_t {
5862 git_SHA_CTX *ctx;
5863 int patchlen;
5866 static int remove_space(char *line, int len)
5868 int i;
5869 char *dst = line;
5870 unsigned char c;
5872 for (i = 0; i < len; i++)
5873 if (!isspace((c = line[i])))
5874 *dst++ = c;
5876 return dst - line;
5879 static void patch_id_consume(void *priv, char *line, unsigned long len)
5881 struct patch_id_t *data = priv;
5882 int new_len;
5884 new_len = remove_space(line, len);
5886 git_SHA1_Update(data->ctx, line, new_len);
5887 data->patchlen += new_len;
5890 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
5892 git_SHA1_Update(ctx, str, strlen(str));
5895 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
5897 /* large enough for 2^32 in octal */
5898 char buf[12];
5899 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
5900 git_SHA1_Update(ctx, buf, len);
5903 /* returns 0 upon success, and writes result into sha1 */
5904 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5906 struct diff_queue_struct *q = &diff_queued_diff;
5907 int i;
5908 git_SHA_CTX ctx;
5909 struct patch_id_t data;
5911 git_SHA1_Init(&ctx);
5912 memset(&data, 0, sizeof(struct patch_id_t));
5913 data.ctx = &ctx;
5915 for (i = 0; i < q->nr; i++) {
5916 xpparam_t xpp;
5917 xdemitconf_t xecfg;
5918 mmfile_t mf1, mf2;
5919 struct diff_filepair *p = q->queue[i];
5920 int len1, len2;
5922 memset(&xpp, 0, sizeof(xpp));
5923 memset(&xecfg, 0, sizeof(xecfg));
5924 if (p->status == 0)
5925 return error("internal diff status error");
5926 if (p->status == DIFF_STATUS_UNKNOWN)
5927 continue;
5928 if (diff_unmodified_pair(p))
5929 continue;
5930 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5931 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5932 continue;
5933 if (DIFF_PAIR_UNMERGED(p))
5934 continue;
5936 diff_fill_oid_info(p->one, options->repo->index);
5937 diff_fill_oid_info(p->two, options->repo->index);
5939 len1 = remove_space(p->one->path, strlen(p->one->path));
5940 len2 = remove_space(p->two->path, strlen(p->two->path));
5941 patch_id_add_string(&ctx, "diff--git");
5942 patch_id_add_string(&ctx, "a/");
5943 git_SHA1_Update(&ctx, p->one->path, len1);
5944 patch_id_add_string(&ctx, "b/");
5945 git_SHA1_Update(&ctx, p->two->path, len2);
5947 if (p->one->mode == 0) {
5948 patch_id_add_string(&ctx, "newfilemode");
5949 patch_id_add_mode(&ctx, p->two->mode);
5950 patch_id_add_string(&ctx, "---/dev/null");
5951 patch_id_add_string(&ctx, "+++b/");
5952 git_SHA1_Update(&ctx, p->two->path, len2);
5953 } else if (p->two->mode == 0) {
5954 patch_id_add_string(&ctx, "deletedfilemode");
5955 patch_id_add_mode(&ctx, p->one->mode);
5956 patch_id_add_string(&ctx, "---a/");
5957 git_SHA1_Update(&ctx, p->one->path, len1);
5958 patch_id_add_string(&ctx, "+++/dev/null");
5959 } else {
5960 patch_id_add_string(&ctx, "---a/");
5961 git_SHA1_Update(&ctx, p->one->path, len1);
5962 patch_id_add_string(&ctx, "+++b/");
5963 git_SHA1_Update(&ctx, p->two->path, len2);
5966 if (diff_header_only)
5967 continue;
5969 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
5970 fill_mmfile(options->repo, &mf2, p->two) < 0)
5971 return error("unable to read files to diff");
5973 if (diff_filespec_is_binary(options->repo, p->one) ||
5974 diff_filespec_is_binary(options->repo, p->two)) {
5975 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5976 GIT_SHA1_HEXSZ);
5977 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5978 GIT_SHA1_HEXSZ);
5979 continue;
5982 xpp.flags = 0;
5983 xecfg.ctxlen = 3;
5984 xecfg.flags = 0;
5985 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
5986 patch_id_consume, &data, &xpp, &xecfg))
5987 return error("unable to generate patch-id diff for %s",
5988 p->one->path);
5991 git_SHA1_Final(oid->hash, &ctx);
5992 return 0;
5995 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5997 struct diff_queue_struct *q = &diff_queued_diff;
5998 int i;
5999 int result = diff_get_patch_id(options, oid, diff_header_only);
6001 for (i = 0; i < q->nr; i++)
6002 diff_free_filepair(q->queue[i]);
6004 free(q->queue);
6005 DIFF_QUEUE_CLEAR(q);
6007 return result;
6010 static int is_summary_empty(const struct diff_queue_struct *q)
6012 int i;
6014 for (i = 0; i < q->nr; i++) {
6015 const struct diff_filepair *p = q->queue[i];
6017 switch (p->status) {
6018 case DIFF_STATUS_DELETED:
6019 case DIFF_STATUS_ADDED:
6020 case DIFF_STATUS_COPIED:
6021 case DIFF_STATUS_RENAMED:
6022 return 0;
6023 default:
6024 if (p->score)
6025 return 0;
6026 if (p->one->mode && p->two->mode &&
6027 p->one->mode != p->two->mode)
6028 return 0;
6029 break;
6032 return 1;
6035 static const char rename_limit_warning[] =
6036 N_("inexact rename detection was skipped due to too many files.");
6038 static const char degrade_cc_to_c_warning[] =
6039 N_("only found copies from modified paths due to too many files.");
6041 static const char rename_limit_advice[] =
6042 N_("you may want to set your %s variable to at least "
6043 "%d and retry the command.");
6045 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6047 fflush(stdout);
6048 if (degraded_cc)
6049 warning(_(degrade_cc_to_c_warning));
6050 else if (needed)
6051 warning(_(rename_limit_warning));
6052 else
6053 return;
6054 if (0 < needed)
6055 warning(_(rename_limit_advice), varname, needed);
6058 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6060 int i;
6061 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6062 struct diff_queue_struct *q = &diff_queued_diff;
6064 if (WSEH_NEW & WS_RULE_MASK)
6065 BUG("WS rules bit mask overlaps with diff symbol flags");
6067 if (o->color_moved)
6068 o->emitted_symbols = &esm;
6070 for (i = 0; i < q->nr; i++) {
6071 struct diff_filepair *p = q->queue[i];
6072 if (check_pair_status(p))
6073 diff_flush_patch(p, o);
6076 if (o->emitted_symbols) {
6077 if (o->color_moved) {
6078 struct hashmap add_lines, del_lines;
6080 if (o->color_moved_ws_handling &
6081 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
6082 o->color_moved_ws_handling |= XDF_IGNORE_WHITESPACE;
6084 hashmap_init(&del_lines, moved_entry_cmp, o, 0);
6085 hashmap_init(&add_lines, moved_entry_cmp, o, 0);
6087 add_lines_to_move_detection(o, &add_lines, &del_lines);
6088 mark_color_as_moved(o, &add_lines, &del_lines);
6089 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6090 dim_moved_lines(o);
6092 hashmap_free(&add_lines, 1);
6093 hashmap_free(&del_lines, 1);
6096 for (i = 0; i < esm.nr; i++)
6097 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6099 for (i = 0; i < esm.nr; i++)
6100 free((void *)esm.buf[i].line);
6101 esm.nr = 0;
6103 o->emitted_symbols = NULL;
6107 void diff_flush(struct diff_options *options)
6109 struct diff_queue_struct *q = &diff_queued_diff;
6110 int i, output_format = options->output_format;
6111 int separator = 0;
6112 int dirstat_by_line = 0;
6115 * Order: raw, stat, summary, patch
6116 * or: name/name-status/checkdiff (other bits clear)
6118 if (!q->nr)
6119 goto free_queue;
6121 if (output_format & (DIFF_FORMAT_RAW |
6122 DIFF_FORMAT_NAME |
6123 DIFF_FORMAT_NAME_STATUS |
6124 DIFF_FORMAT_CHECKDIFF)) {
6125 for (i = 0; i < q->nr; i++) {
6126 struct diff_filepair *p = q->queue[i];
6127 if (check_pair_status(p))
6128 flush_one_pair(p, options);
6130 separator++;
6133 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6134 dirstat_by_line = 1;
6136 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6137 dirstat_by_line) {
6138 struct diffstat_t diffstat;
6140 memset(&diffstat, 0, sizeof(struct diffstat_t));
6141 for (i = 0; i < q->nr; i++) {
6142 struct diff_filepair *p = q->queue[i];
6143 if (check_pair_status(p))
6144 diff_flush_stat(p, options, &diffstat);
6146 if (output_format & DIFF_FORMAT_NUMSTAT)
6147 show_numstat(&diffstat, options);
6148 if (output_format & DIFF_FORMAT_DIFFSTAT)
6149 show_stats(&diffstat, options);
6150 if (output_format & DIFF_FORMAT_SHORTSTAT)
6151 show_shortstats(&diffstat, options);
6152 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6153 show_dirstat_by_line(&diffstat, options);
6154 free_diffstat_info(&diffstat);
6155 separator++;
6157 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6158 show_dirstat(options);
6160 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6161 for (i = 0; i < q->nr; i++) {
6162 diff_summary(options, q->queue[i]);
6164 separator++;
6167 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6168 options->flags.exit_with_status &&
6169 options->flags.diff_from_contents) {
6171 * run diff_flush_patch for the exit status. setting
6172 * options->file to /dev/null should be safe, because we
6173 * aren't supposed to produce any output anyway.
6175 if (options->close_file)
6176 fclose(options->file);
6177 options->file = xfopen("/dev/null", "w");
6178 options->close_file = 1;
6179 options->color_moved = 0;
6180 for (i = 0; i < q->nr; i++) {
6181 struct diff_filepair *p = q->queue[i];
6182 if (check_pair_status(p))
6183 diff_flush_patch(p, options);
6184 if (options->found_changes)
6185 break;
6189 if (output_format & DIFF_FORMAT_PATCH) {
6190 if (separator) {
6191 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6192 if (options->stat_sep)
6193 /* attach patch instead of inline */
6194 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6195 NULL, 0, 0);
6198 diff_flush_patch_all_file_pairs(options);
6201 if (output_format & DIFF_FORMAT_CALLBACK)
6202 options->format_callback(q, options, options->format_callback_data);
6204 for (i = 0; i < q->nr; i++)
6205 diff_free_filepair(q->queue[i]);
6206 free_queue:
6207 free(q->queue);
6208 DIFF_QUEUE_CLEAR(q);
6209 if (options->close_file)
6210 fclose(options->file);
6213 * Report the content-level differences with HAS_CHANGES;
6214 * diff_addremove/diff_change does not set the bit when
6215 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6217 if (options->flags.diff_from_contents) {
6218 if (options->found_changes)
6219 options->flags.has_changes = 1;
6220 else
6221 options->flags.has_changes = 0;
6225 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6227 return (((p->status == DIFF_STATUS_MODIFIED) &&
6228 ((p->score &&
6229 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6230 (!p->score &&
6231 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6232 ((p->status != DIFF_STATUS_MODIFIED) &&
6233 filter_bit_tst(p->status, options)));
6236 static void diffcore_apply_filter(struct diff_options *options)
6238 int i;
6239 struct diff_queue_struct *q = &diff_queued_diff;
6240 struct diff_queue_struct outq;
6242 DIFF_QUEUE_CLEAR(&outq);
6244 if (!options->filter)
6245 return;
6247 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6248 int found;
6249 for (i = found = 0; !found && i < q->nr; i++) {
6250 if (match_filter(options, q->queue[i]))
6251 found++;
6253 if (found)
6254 return;
6256 /* otherwise we will clear the whole queue
6257 * by copying the empty outq at the end of this
6258 * function, but first clear the current entries
6259 * in the queue.
6261 for (i = 0; i < q->nr; i++)
6262 diff_free_filepair(q->queue[i]);
6264 else {
6265 /* Only the matching ones */
6266 for (i = 0; i < q->nr; i++) {
6267 struct diff_filepair *p = q->queue[i];
6268 if (match_filter(options, p))
6269 diff_q(&outq, p);
6270 else
6271 diff_free_filepair(p);
6274 free(q->queue);
6275 *q = outq;
6278 /* Check whether two filespecs with the same mode and size are identical */
6279 static int diff_filespec_is_identical(struct repository *r,
6280 struct diff_filespec *one,
6281 struct diff_filespec *two)
6283 if (S_ISGITLINK(one->mode))
6284 return 0;
6285 if (diff_populate_filespec(r, one, 0))
6286 return 0;
6287 if (diff_populate_filespec(r, two, 0))
6288 return 0;
6289 return !memcmp(one->data, two->data, one->size);
6292 static int diff_filespec_check_stat_unmatch(struct repository *r,
6293 struct diff_filepair *p)
6295 if (p->done_skip_stat_unmatch)
6296 return p->skip_stat_unmatch_result;
6298 p->done_skip_stat_unmatch = 1;
6299 p->skip_stat_unmatch_result = 0;
6301 * 1. Entries that come from stat info dirtiness
6302 * always have both sides (iow, not create/delete),
6303 * one side of the object name is unknown, with
6304 * the same mode and size. Keep the ones that
6305 * do not match these criteria. They have real
6306 * differences.
6308 * 2. At this point, the file is known to be modified,
6309 * with the same mode and size, and the object
6310 * name of one side is unknown. Need to inspect
6311 * the identical contents.
6313 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6314 !DIFF_FILE_VALID(p->two) ||
6315 (p->one->oid_valid && p->two->oid_valid) ||
6316 (p->one->mode != p->two->mode) ||
6317 diff_populate_filespec(r, p->one, CHECK_SIZE_ONLY) ||
6318 diff_populate_filespec(r, p->two, CHECK_SIZE_ONLY) ||
6319 (p->one->size != p->two->size) ||
6320 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6321 p->skip_stat_unmatch_result = 1;
6322 return p->skip_stat_unmatch_result;
6325 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6327 int i;
6328 struct diff_queue_struct *q = &diff_queued_diff;
6329 struct diff_queue_struct outq;
6330 DIFF_QUEUE_CLEAR(&outq);
6332 for (i = 0; i < q->nr; i++) {
6333 struct diff_filepair *p = q->queue[i];
6335 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6336 diff_q(&outq, p);
6337 else {
6339 * The caller can subtract 1 from skip_stat_unmatch
6340 * to determine how many paths were dirty only
6341 * due to stat info mismatch.
6343 if (!diffopt->flags.no_index)
6344 diffopt->skip_stat_unmatch++;
6345 diff_free_filepair(p);
6348 free(q->queue);
6349 *q = outq;
6352 static int diffnamecmp(const void *a_, const void *b_)
6354 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6355 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6356 const char *name_a, *name_b;
6358 name_a = a->one ? a->one->path : a->two->path;
6359 name_b = b->one ? b->one->path : b->two->path;
6360 return strcmp(name_a, name_b);
6363 void diffcore_fix_diff_index(void)
6365 struct diff_queue_struct *q = &diff_queued_diff;
6366 QSORT(q->queue, q->nr, diffnamecmp);
6369 void diffcore_std(struct diff_options *options)
6371 /* NOTE please keep the following in sync with diff_tree_combined() */
6372 if (options->skip_stat_unmatch)
6373 diffcore_skip_stat_unmatch(options);
6374 if (!options->found_follow) {
6375 /* See try_to_follow_renames() in tree-diff.c */
6376 if (options->break_opt != -1)
6377 diffcore_break(options->repo,
6378 options->break_opt);
6379 if (options->detect_rename)
6380 diffcore_rename(options);
6381 if (options->break_opt != -1)
6382 diffcore_merge_broken();
6384 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6385 diffcore_pickaxe(options);
6386 if (options->orderfile)
6387 diffcore_order(options->orderfile);
6388 if (!options->found_follow)
6389 /* See try_to_follow_renames() in tree-diff.c */
6390 diff_resolve_rename_copy();
6391 diffcore_apply_filter(options);
6393 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6394 options->flags.has_changes = 1;
6395 else
6396 options->flags.has_changes = 0;
6398 options->found_follow = 0;
6401 int diff_result_code(struct diff_options *opt, int status)
6403 int result = 0;
6405 diff_warn_rename_limit("diff.renameLimit",
6406 opt->needed_rename_limit,
6407 opt->degraded_cc_to_c);
6408 if (!opt->flags.exit_with_status &&
6409 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6410 return status;
6411 if (opt->flags.exit_with_status &&
6412 opt->flags.has_changes)
6413 result |= 01;
6414 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6415 opt->flags.check_failed)
6416 result |= 02;
6417 return result;
6420 int diff_can_quit_early(struct diff_options *opt)
6422 return (opt->flags.quick &&
6423 !opt->filter &&
6424 opt->flags.has_changes);
6428 * Shall changes to this submodule be ignored?
6430 * Submodule changes can be configured to be ignored separately for each path,
6431 * but that configuration can be overridden from the command line.
6433 static int is_submodule_ignored(const char *path, struct diff_options *options)
6435 int ignored = 0;
6436 struct diff_flags orig_flags = options->flags;
6437 if (!options->flags.override_submodule_config)
6438 set_diffopt_flags_from_submodule_config(options, path);
6439 if (options->flags.ignore_submodules)
6440 ignored = 1;
6441 options->flags = orig_flags;
6442 return ignored;
6445 void diff_addremove(struct diff_options *options,
6446 int addremove, unsigned mode,
6447 const struct object_id *oid,
6448 int oid_valid,
6449 const char *concatpath, unsigned dirty_submodule)
6451 struct diff_filespec *one, *two;
6453 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6454 return;
6456 /* This may look odd, but it is a preparation for
6457 * feeding "there are unchanged files which should
6458 * not produce diffs, but when you are doing copy
6459 * detection you would need them, so here they are"
6460 * entries to the diff-core. They will be prefixed
6461 * with something like '=' or '*' (I haven't decided
6462 * which but should not make any difference).
6463 * Feeding the same new and old to diff_change()
6464 * also has the same effect.
6465 * Before the final output happens, they are pruned after
6466 * merged into rename/copy pairs as appropriate.
6468 if (options->flags.reverse_diff)
6469 addremove = (addremove == '+' ? '-' :
6470 addremove == '-' ? '+' : addremove);
6472 if (options->prefix &&
6473 strncmp(concatpath, options->prefix, options->prefix_length))
6474 return;
6476 one = alloc_filespec(concatpath);
6477 two = alloc_filespec(concatpath);
6479 if (addremove != '+')
6480 fill_filespec(one, oid, oid_valid, mode);
6481 if (addremove != '-') {
6482 fill_filespec(two, oid, oid_valid, mode);
6483 two->dirty_submodule = dirty_submodule;
6486 diff_queue(&diff_queued_diff, one, two);
6487 if (!options->flags.diff_from_contents)
6488 options->flags.has_changes = 1;
6491 void diff_change(struct diff_options *options,
6492 unsigned old_mode, unsigned new_mode,
6493 const struct object_id *old_oid,
6494 const struct object_id *new_oid,
6495 int old_oid_valid, int new_oid_valid,
6496 const char *concatpath,
6497 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6499 struct diff_filespec *one, *two;
6500 struct diff_filepair *p;
6502 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6503 is_submodule_ignored(concatpath, options))
6504 return;
6506 if (options->flags.reverse_diff) {
6507 SWAP(old_mode, new_mode);
6508 SWAP(old_oid, new_oid);
6509 SWAP(old_oid_valid, new_oid_valid);
6510 SWAP(old_dirty_submodule, new_dirty_submodule);
6513 if (options->prefix &&
6514 strncmp(concatpath, options->prefix, options->prefix_length))
6515 return;
6517 one = alloc_filespec(concatpath);
6518 two = alloc_filespec(concatpath);
6519 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6520 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6521 one->dirty_submodule = old_dirty_submodule;
6522 two->dirty_submodule = new_dirty_submodule;
6523 p = diff_queue(&diff_queued_diff, one, two);
6525 if (options->flags.diff_from_contents)
6526 return;
6528 if (options->flags.quick && options->skip_stat_unmatch &&
6529 !diff_filespec_check_stat_unmatch(options->repo, p))
6530 return;
6532 options->flags.has_changes = 1;
6535 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6537 struct diff_filepair *pair;
6538 struct diff_filespec *one, *two;
6540 if (options->prefix &&
6541 strncmp(path, options->prefix, options->prefix_length))
6542 return NULL;
6544 one = alloc_filespec(path);
6545 two = alloc_filespec(path);
6546 pair = diff_queue(&diff_queued_diff, one, two);
6547 pair->is_unmerged = 1;
6548 return pair;
6551 static char *run_textconv(struct repository *r,
6552 const char *pgm,
6553 struct diff_filespec *spec,
6554 size_t *outsize)
6556 struct diff_tempfile *temp;
6557 const char *argv[3];
6558 const char **arg = argv;
6559 struct child_process child = CHILD_PROCESS_INIT;
6560 struct strbuf buf = STRBUF_INIT;
6561 int err = 0;
6563 temp = prepare_temp_file(r, spec->path, spec);
6564 *arg++ = pgm;
6565 *arg++ = temp->name;
6566 *arg = NULL;
6568 child.use_shell = 1;
6569 child.argv = argv;
6570 child.out = -1;
6571 if (start_command(&child)) {
6572 remove_tempfile();
6573 return NULL;
6576 if (strbuf_read(&buf, child.out, 0) < 0)
6577 err = error("error reading from textconv command '%s'", pgm);
6578 close(child.out);
6580 if (finish_command(&child) || err) {
6581 strbuf_release(&buf);
6582 remove_tempfile();
6583 return NULL;
6585 remove_tempfile();
6587 return strbuf_detach(&buf, outsize);
6590 size_t fill_textconv(struct repository *r,
6591 struct userdiff_driver *driver,
6592 struct diff_filespec *df,
6593 char **outbuf)
6595 size_t size;
6597 if (!driver) {
6598 if (!DIFF_FILE_VALID(df)) {
6599 *outbuf = "";
6600 return 0;
6602 if (diff_populate_filespec(r, df, 0))
6603 die("unable to read files to diff");
6604 *outbuf = df->data;
6605 return df->size;
6608 if (!driver->textconv)
6609 BUG("fill_textconv called with non-textconv driver");
6611 if (driver->textconv_cache && df->oid_valid) {
6612 *outbuf = notes_cache_get(driver->textconv_cache,
6613 &df->oid,
6614 &size);
6615 if (*outbuf)
6616 return size;
6619 *outbuf = run_textconv(r, driver->textconv, df, &size);
6620 if (!*outbuf)
6621 die("unable to read files to diff");
6623 if (driver->textconv_cache && df->oid_valid) {
6624 /* ignore errors, as we might be in a readonly repository */
6625 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6626 size);
6628 * we could save up changes and flush them all at the end,
6629 * but we would need an extra call after all diffing is done.
6630 * Since generating a cache entry is the slow path anyway,
6631 * this extra overhead probably isn't a big deal.
6633 notes_cache_write(driver->textconv_cache);
6636 return size;
6639 int textconv_object(struct repository *r,
6640 const char *path,
6641 unsigned mode,
6642 const struct object_id *oid,
6643 int oid_valid,
6644 char **buf,
6645 unsigned long *buf_size)
6647 struct diff_filespec *df;
6648 struct userdiff_driver *textconv;
6650 df = alloc_filespec(path);
6651 fill_filespec(df, oid, oid_valid, mode);
6652 textconv = get_textconv(r, df);
6653 if (!textconv) {
6654 free_filespec(df);
6655 return 0;
6658 *buf_size = fill_textconv(r, textconv, df, buf);
6659 free_filespec(df);
6660 return 1;
6663 void setup_diff_pager(struct diff_options *opt)
6666 * If the user asked for our exit code, then either they want --quiet
6667 * or --exit-code. We should definitely not bother with a pager in the
6668 * former case, as we will generate no output. Since we still properly
6669 * report our exit code even when a pager is run, we _could_ run a
6670 * pager with --exit-code. But since we have not done so historically,
6671 * and because it is easy to find people oneline advising "git diff
6672 * --exit-code" in hooks and other scripts, we do not do so.
6674 if (!opt->flags.exit_with_status &&
6675 check_pager_config("diff") != 0)
6676 setup_pager();