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