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