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