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