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