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