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