diff.c: buffer all output if asked to
[git/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,
bd033291 573 DIFF_SYMBOL_WORD_DIFF,
30b7e1e7 574 DIFF_SYMBOL_STAT_SEP,
146fdb0d 575 DIFF_SYMBOL_SUMMARY,
f3597138
SB
576 DIFF_SYMBOL_SUBMODULE_ADD,
577 DIFF_SYMBOL_SUBMODULE_DEL,
578 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
579 DIFF_SYMBOL_SUBMODULE_MODIFIED,
580 DIFF_SYMBOL_SUBMODULE_HEADER,
581 DIFF_SYMBOL_SUBMODULE_ERROR,
582 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
5af6ea95 583 DIFF_SYMBOL_REWRITE_DIFF,
4acaaa7a 584 DIFF_SYMBOL_BINARY_FILES,
a29b0a13 585 DIFF_SYMBOL_HEADER,
3ee8b7bf
SB
586 DIFF_SYMBOL_FILEPAIR_PLUS,
587 DIFF_SYMBOL_FILEPAIR_MINUS,
ff958679
SB
588 DIFF_SYMBOL_WORDS_PORCELAIN,
589 DIFF_SYMBOL_WORDS,
091f8e28 590 DIFF_SYMBOL_CONTEXT,
f2bb1218 591 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
091f8e28
SB
592 DIFF_SYMBOL_PLUS,
593 DIFF_SYMBOL_MINUS,
b9cbfde6 594 DIFF_SYMBOL_NO_LF_EOF,
68abc6f1 595 DIFF_SYMBOL_CONTEXT_FRAGINFO,
c64b420b 596 DIFF_SYMBOL_CONTEXT_MARKER,
36a4cefd
SB
597 DIFF_SYMBOL_SEPARATOR
598};
091f8e28
SB
599/*
600 * Flags for content lines:
601 * 0..12 are whitespace rules
602 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
603 * 16 is marking if the line is blank at EOF
604 */
605#define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
606#define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
607
e6e045f8
SB
608/*
609 * This struct is used when we need to buffer the output of the diff output.
610 *
611 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
612 * into the pre/post image file. This pointer could be a union with the
613 * line pointer. By storing an offset into the file instead of the literal line,
614 * we can decrease the memory footprint for the buffered output. At first we
615 * may want to only have indirection for the content lines, but we could also
616 * enhance the state for emitting prefabricated lines, e.g. the similarity
617 * score line or hunk/file headers would only need to store a number or path
618 * and then the output can be constructed later on depending on state.
619 */
620struct emitted_diff_symbol {
621 const char *line;
622 int len;
623 int flags;
624 enum diff_symbol s;
625};
626#define EMITTED_DIFF_SYMBOL_INIT {NULL}
627
628struct emitted_diff_symbols {
629 struct emitted_diff_symbol *buf;
630 int nr, alloc;
631};
632#define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
633
634static void append_emitted_diff_symbol(struct diff_options *o,
635 struct emitted_diff_symbol *e)
636{
637 struct emitted_diff_symbol *f;
638
639 ALLOC_GROW(o->emitted_symbols->buf,
640 o->emitted_symbols->nr + 1,
641 o->emitted_symbols->alloc);
642 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
643
644 memcpy(f, e, sizeof(struct emitted_diff_symbol));
645 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
646}
647
648
091f8e28
SB
649static void emit_line_ws_markup(struct diff_options *o,
650 const char *set, const char *reset,
651 const char *line, int len, char sign,
652 unsigned ws_rule, int blank_at_eof)
653{
654 const char *ws = NULL;
655
656 if (o->ws_error_highlight & ws_rule) {
657 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
658 if (!*ws)
659 ws = NULL;
660 }
661
662 if (!ws)
663 emit_line_0(o, set, reset, sign, line, len);
664 else if (blank_at_eof)
665 /* Blank line at EOF - paint '+' as well */
666 emit_line_0(o, ws, reset, sign, line, len);
667 else {
668 /* Emit just the prefix, then the rest. */
669 emit_line_0(o, set, reset, sign, "", 0);
670 ws_check_emit(line, len, ws_rule,
671 o->file, set, reset, ws);
672 }
673}
36a4cefd 674
e6e045f8
SB
675static void emit_diff_symbol_from_struct(struct diff_options *o,
676 struct emitted_diff_symbol *eds)
36a4cefd 677{
b9cbfde6 678 static const char *nneof = " No newline at end of file\n";
5af6ea95 679 const char *context, *reset, *set, *meta, *fraginfo;
0911c475 680 struct strbuf sb = STRBUF_INIT;
e6e045f8
SB
681
682 enum diff_symbol s = eds->s;
683 const char *line = eds->line;
684 int len = eds->len;
685 unsigned flags = eds->flags;
686
36a4cefd 687 switch (s) {
b9cbfde6
SB
688 case DIFF_SYMBOL_NO_LF_EOF:
689 context = diff_get_color_opt(o, DIFF_CONTEXT);
690 reset = diff_get_color_opt(o, DIFF_RESET);
691 putc('\n', o->file);
692 emit_line_0(o, context, reset, '\\',
693 nneof, strlen(nneof));
694 break;
f3597138
SB
695 case DIFF_SYMBOL_SUBMODULE_HEADER:
696 case DIFF_SYMBOL_SUBMODULE_ERROR:
697 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
0911c475 698 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
146fdb0d 699 case DIFF_SYMBOL_SUMMARY:
0911c475 700 case DIFF_SYMBOL_STATS_LINE:
4eed0ebd 701 case DIFF_SYMBOL_BINARY_DIFF_BODY:
68abc6f1
SB
702 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
703 emit_line(o, "", "", line, len);
704 break;
f2bb1218 705 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
c64b420b
SB
706 case DIFF_SYMBOL_CONTEXT_MARKER:
707 context = diff_get_color_opt(o, DIFF_CONTEXT);
708 reset = diff_get_color_opt(o, DIFF_RESET);
709 emit_line(o, context, reset, line, len);
710 break;
36a4cefd
SB
711 case DIFF_SYMBOL_SEPARATOR:
712 fprintf(o->file, "%s%c",
713 diff_line_prefix(o),
714 o->line_termination);
715 break;
091f8e28
SB
716 case DIFF_SYMBOL_CONTEXT:
717 set = diff_get_color_opt(o, DIFF_CONTEXT);
718 reset = diff_get_color_opt(o, DIFF_RESET);
719 emit_line_ws_markup(o, set, reset, line, len, ' ',
720 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
721 break;
722 case DIFF_SYMBOL_PLUS:
723 set = diff_get_color_opt(o, DIFF_FILE_NEW);
724 reset = diff_get_color_opt(o, DIFF_RESET);
725 emit_line_ws_markup(o, set, reset, line, len, '+',
726 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
727 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
728 break;
729 case DIFF_SYMBOL_MINUS:
730 set = diff_get_color_opt(o, DIFF_FILE_OLD);
731 reset = diff_get_color_opt(o, DIFF_RESET);
732 emit_line_ws_markup(o, set, reset, line, len, '-',
733 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
734 break;
ff958679
SB
735 case DIFF_SYMBOL_WORDS_PORCELAIN:
736 context = diff_get_color_opt(o, DIFF_CONTEXT);
737 reset = diff_get_color_opt(o, DIFF_RESET);
738 emit_line(o, context, reset, line, len);
739 fputs("~\n", o->file);
740 break;
741 case DIFF_SYMBOL_WORDS:
742 context = diff_get_color_opt(o, DIFF_CONTEXT);
743 reset = diff_get_color_opt(o, DIFF_RESET);
744 /*
745 * Skip the prefix character, if any. With
746 * diff_suppress_blank_empty, there may be
747 * none.
748 */
749 if (line[0] != '\n') {
750 line++;
751 len--;
752 }
753 emit_line(o, context, reset, line, len);
754 break;
3ee8b7bf
SB
755 case DIFF_SYMBOL_FILEPAIR_PLUS:
756 meta = diff_get_color_opt(o, DIFF_METAINFO);
757 reset = diff_get_color_opt(o, DIFF_RESET);
758 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
759 line, reset,
760 strchr(line, ' ') ? "\t" : "");
761 break;
762 case DIFF_SYMBOL_FILEPAIR_MINUS:
763 meta = diff_get_color_opt(o, DIFF_METAINFO);
764 reset = diff_get_color_opt(o, DIFF_RESET);
765 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
766 line, reset,
767 strchr(line, ' ') ? "\t" : "");
768 break;
4acaaa7a 769 case DIFF_SYMBOL_BINARY_FILES:
a29b0a13
SB
770 case DIFF_SYMBOL_HEADER:
771 fprintf(o->file, "%s", line);
772 break;
4eed0ebd
SB
773 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
774 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
775 break;
776 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
777 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
778 break;
779 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
780 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
781 break;
782 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
783 fputs(diff_line_prefix(o), o->file);
784 fputc('\n', o->file);
785 break;
5af6ea95
SB
786 case DIFF_SYMBOL_REWRITE_DIFF:
787 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
788 reset = diff_get_color_opt(o, DIFF_RESET);
789 emit_line(o, fraginfo, reset, line, len);
790 break;
f3597138
SB
791 case DIFF_SYMBOL_SUBMODULE_ADD:
792 set = diff_get_color_opt(o, DIFF_FILE_NEW);
793 reset = diff_get_color_opt(o, DIFF_RESET);
794 emit_line(o, set, reset, line, len);
795 break;
796 case DIFF_SYMBOL_SUBMODULE_DEL:
797 set = diff_get_color_opt(o, DIFF_FILE_OLD);
798 reset = diff_get_color_opt(o, DIFF_RESET);
799 emit_line(o, set, reset, line, len);
800 break;
801 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
802 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
803 diff_line_prefix(o), line);
804 break;
805 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
806 fprintf(o->file, "%sSubmodule %s contains modified content\n",
807 diff_line_prefix(o), line);
808 break;
0911c475
SB
809 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
810 emit_line(o, "", "", " 0 files changed\n",
811 strlen(" 0 files changed\n"));
812 break;
813 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
814 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
815 break;
bd033291
SB
816 case DIFF_SYMBOL_WORD_DIFF:
817 fprintf(o->file, "%.*s", len, line);
818 break;
30b7e1e7
SB
819 case DIFF_SYMBOL_STAT_SEP:
820 fputs(o->stat_sep, o->file);
821 break;
36a4cefd
SB
822 default:
823 die("BUG: unknown diff symbol");
824 }
0911c475 825 strbuf_release(&sb);
36a4cefd
SB
826}
827
e6e045f8
SB
828static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
829 const char *line, int len, unsigned flags)
830{
831 struct emitted_diff_symbol e = {line, len, flags, s};
832
833 if (o->emitted_symbols)
834 append_emitted_diff_symbol(o, &e);
835 else
836 emit_diff_symbol_from_struct(o, &e);
837}
838
f3597138
SB
839void diff_emit_submodule_del(struct diff_options *o, const char *line)
840{
841 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
842}
843
844void diff_emit_submodule_add(struct diff_options *o, const char *line)
845{
846 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
847}
848
849void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
850{
851 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
852 path, strlen(path), 0);
853}
854
855void diff_emit_submodule_modified(struct diff_options *o, const char *path)
856{
857 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
858 path, strlen(path), 0);
859}
860
861void diff_emit_submodule_header(struct diff_options *o, const char *header)
862{
863 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
864 header, strlen(header), 0);
865}
866
867void diff_emit_submodule_error(struct diff_options *o, const char *err)
868{
869 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
870}
871
872void diff_emit_submodule_pipethrough(struct diff_options *o,
873 const char *line, int len)
874{
875 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
876}
877
6957eb9a
JH
878static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
879{
880 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
881 ecbdata->blank_at_eof_in_preimage &&
882 ecbdata->blank_at_eof_in_postimage &&
883 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
884 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
885 return 0;
018cff70 886 return ws_blank_line(line, len, ecbdata->ws_rule);
6957eb9a
JH
887}
888
b8767f79 889static void emit_add_line(const char *reset,
0e383e18
JH
890 struct emit_callback *ecbdata,
891 const char *line, int len)
892{
091f8e28
SB
893 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
894 if (new_blank_line_at_eof(ecbdata, line, len))
895 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
896
897 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
b8767f79 898}
0e383e18 899
b8767f79
JH
900static void emit_del_line(const char *reset,
901 struct emit_callback *ecbdata,
902 const char *line, int len)
903{
091f8e28
SB
904 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
905 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
0e383e18
JH
906}
907
908static void emit_context_line(const char *reset,
909 struct emit_callback *ecbdata,
910 const char *line, int len)
911{
091f8e28
SB
912 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
913 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
0e383e18
JH
914}
915
89cb73a1
BW
916static void emit_hunk_header(struct emit_callback *ecbdata,
917 const char *line, int len)
918{
8dbf3eb6 919 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
89cb73a1
BW
920 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
921 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
922 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
923 static const char atat[2] = { '@', '@' };
924 const char *cp, *ep;
2efcc977
BY
925 struct strbuf msgbuf = STRBUF_INIT;
926 int org_len = len;
927 int i = 1;
89cb73a1
BW
928
929 /*
930 * As a hunk header must begin with "@@ -<old>, +<new> @@",
931 * it always is at least 10 bytes long.
932 */
933 if (len < 10 ||
934 memcmp(line, atat, 2) ||
935 !(ep = memmem(line + 2, len - 2, atat, 2))) {
c64b420b 936 emit_diff_symbol(ecbdata->opt,
091f8e28 937 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
89cb73a1
BW
938 return;
939 }
940 ep += 2; /* skip over @@ */
941
942 /* The hunk header in fraginfo color */
cedc61a9 943 strbuf_addstr(&msgbuf, frag);
2efcc977 944 strbuf_add(&msgbuf, line, ep - line);
cedc61a9 945 strbuf_addstr(&msgbuf, reset);
2efcc977
BY
946
947 /*
948 * trailing "\r\n"
949 */
950 for ( ; i < 3; i++)
951 if (line[len - i] == '\r' || line[len - i] == '\n')
952 len--;
89cb73a1
BW
953
954 /* blank before the func header */
955 for (cp = ep; ep - line < len; ep++)
956 if (*ep != ' ' && *ep != '\t')
957 break;
2efcc977 958 if (ep != cp) {
8dbf3eb6 959 strbuf_addstr(&msgbuf, context);
2efcc977 960 strbuf_add(&msgbuf, cp, ep - cp);
cedc61a9 961 strbuf_addstr(&msgbuf, reset);
2efcc977
BY
962 }
963
964 if (ep < line + len) {
cedc61a9 965 strbuf_addstr(&msgbuf, func);
2efcc977 966 strbuf_add(&msgbuf, ep, line + len - ep);
cedc61a9 967 strbuf_addstr(&msgbuf, reset);
2efcc977 968 }
89cb73a1 969
2efcc977 970 strbuf_add(&msgbuf, line + len, org_len - len);
dfb7728f 971 strbuf_complete_line(&msgbuf);
68abc6f1 972 emit_diff_symbol(ecbdata->opt,
091f8e28 973 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
2efcc977 974 strbuf_release(&msgbuf);
89cb73a1
BW
975}
976
479b0ae8
JK
977static struct diff_tempfile *claim_diff_tempfile(void) {
978 int i;
979 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
980 if (!diff_temp[i].name)
981 return diff_temp + i;
982 die("BUG: diff is failing to clean up its tempfiles");
983}
984
479b0ae8
JK
985static void remove_tempfile(void)
986{
987 int i;
a8344abe 988 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
284098f1
MH
989 if (is_tempfile_active(&diff_temp[i].tempfile))
990 delete_tempfile(&diff_temp[i].tempfile);
a8344abe
NR
991 diff_temp[i].name = NULL;
992 }
479b0ae8
JK
993}
994
5af6ea95 995static void add_line_count(struct strbuf *out, int count)
6973dcae
JH
996{
997 switch (count) {
998 case 0:
5af6ea95 999 strbuf_addstr(out, "0,0");
6973dcae
JH
1000 break;
1001 case 1:
5af6ea95 1002 strbuf_addstr(out, "1");
6973dcae
JH
1003 break;
1004 default:
5af6ea95 1005 strbuf_addf(out, "1,%d", count);
6973dcae
JH
1006 break;
1007 }
1008}
1009
7f7ee2ff
JH
1010static void emit_rewrite_lines(struct emit_callback *ecb,
1011 int prefix, const char *data, int size)
6973dcae 1012{
7f7ee2ff 1013 const char *endp = NULL;
7f7ee2ff
JH
1014 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1015
1016 while (0 < size) {
1017 int len;
1018
1019 endp = memchr(data, '\n', size);
1020 len = endp ? (endp - data + 1) : size;
1021 if (prefix != '+') {
1022 ecb->lno_in_preimage++;
0e383e18 1023 emit_del_line(reset, ecb, data, len);
7f7ee2ff
JH
1024 } else {
1025 ecb->lno_in_postimage++;
1026 emit_add_line(reset, ecb, data, len);
13e36ec5 1027 }
7f7ee2ff
JH
1028 size -= len;
1029 data += len;
1030 }
b9cbfde6 1031 if (!endp)
091f8e28 1032 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
6973dcae
JH
1033}
1034
1035static void emit_rewrite_diff(const char *name_a,
1036 const char *name_b,
1037 struct diff_filespec *one,
13e36ec5 1038 struct diff_filespec *two,
d9bae1a1
JK
1039 struct userdiff_driver *textconv_one,
1040 struct userdiff_driver *textconv_two,
eab9a40b 1041 struct diff_options *o)
6973dcae
JH
1042{
1043 int lc_a, lc_b;
d5625091 1044 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
a5a818ee 1045 const char *a_prefix, *b_prefix;
840383b2 1046 char *data_one, *data_two;
3aa1f7ca 1047 size_t size_one, size_two;
7f7ee2ff 1048 struct emit_callback ecbdata;
5af6ea95 1049 struct strbuf out = STRBUF_INIT;
a5a818ee
JH
1050
1051 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
1052 a_prefix = o->b_prefix;
1053 b_prefix = o->a_prefix;
1054 } else {
1055 a_prefix = o->a_prefix;
1056 b_prefix = o->b_prefix;
1057 }
1a9eb3b9 1058
8a13becc
JH
1059 name_a += (*name_a == '/');
1060 name_b += (*name_b == '/');
1a9eb3b9 1061
d5625091
JH
1062 strbuf_reset(&a_name);
1063 strbuf_reset(&b_name);
a5a818ee
JH
1064 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1065 quote_two_c_style(&b_name, b_prefix, name_b, 0);
d5625091 1066
840383b2
JK
1067 size_one = fill_textconv(textconv_one, one, &data_one);
1068 size_two = fill_textconv(textconv_two, two, &data_two);
3aa1f7ca 1069
d91ba8fa 1070 memset(&ecbdata, 0, sizeof(ecbdata));
daa0c3d9 1071 ecbdata.color_diff = want_color(o->use_color);
c189c4f2 1072 ecbdata.ws_rule = whitespace_rule(name_b);
a3c158d4 1073 ecbdata.opt = o;
d91ba8fa
JH
1074 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1075 mmfile_t mf1, mf2;
1076 mf1.ptr = (char *)data_one;
1077 mf2.ptr = (char *)data_two;
1078 mf1.size = size_one;
1079 mf2.size = size_two;
1080 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1081 }
1082 ecbdata.lno_in_preimage = 1;
1083 ecbdata.lno_in_postimage = 1;
1084
3aa1f7ca
JK
1085 lc_a = count_lines(data_one, size_one);
1086 lc_b = count_lines(data_two, size_two);
3ee8b7bf
SB
1087
1088 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1089 a_name.buf, a_name.len, 0);
1090 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1091 b_name.buf, b_name.len, 0);
1092
5af6ea95 1093 strbuf_addstr(&out, "@@ -");
467ddc14 1094 if (!o->irreversible_delete)
5af6ea95 1095 add_line_count(&out, lc_a);
467ddc14 1096 else
5af6ea95
SB
1097 strbuf_addstr(&out, "?,?");
1098 strbuf_addstr(&out, " +");
1099 add_line_count(&out, lc_b);
1100 strbuf_addstr(&out, " @@\n");
1101 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1102 strbuf_release(&out);
1103
467ddc14 1104 if (lc_a && !o->irreversible_delete)
d91ba8fa 1105 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
6973dcae 1106 if (lc_b)
d91ba8fa 1107 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
b76c056b 1108 if (textconv_one)
aed6ca52 1109 free((char *)data_one);
b76c056b 1110 if (textconv_two)
aed6ca52 1111 free((char *)data_two);
6973dcae
JH
1112}
1113
f59a59e2
JS
1114struct diff_words_buffer {
1115 mmfile_t text;
1116 long alloc;
2e5d2003
JS
1117 struct diff_words_orig {
1118 const char *begin, *end;
1119 } *orig;
1120 int orig_nr, orig_alloc;
f59a59e2
JS
1121};
1122
1123static void diff_words_append(char *line, unsigned long len,
1124 struct diff_words_buffer *buffer)
1125{
23c1575f 1126 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
f59a59e2
JS
1127 line++;
1128 len--;
1129 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1130 buffer->text.size += len;
2b6a5417 1131 buffer->text.ptr[buffer->text.size] = '\0';
f59a59e2
JS
1132}
1133
9cba13ca 1134struct diff_words_style_elem {
882749a0
TR
1135 const char *prefix;
1136 const char *suffix;
1137 const char *color; /* NULL; filled in by the setup code if
1138 * color is enabled */
1139};
1140
9cba13ca 1141struct diff_words_style {
882749a0
TR
1142 enum diff_words_type type;
1143 struct diff_words_style_elem new, old, ctx;
1144 const char *newline;
1145};
1146
c2e86add 1147static struct diff_words_style diff_words_styles[] = {
882749a0
TR
1148 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1149 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1150 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1151};
1152
f59a59e2 1153struct diff_words_data {
f59a59e2 1154 struct diff_words_buffer minus, plus;
2e5d2003 1155 const char *current_plus;
4297c0ae
BY
1156 int last_minus;
1157 struct diff_options *opt;
2b6a5417 1158 regex_t *word_regex;
882749a0
TR
1159 enum diff_words_type type;
1160 struct diff_words_style *style;
f59a59e2
JS
1161};
1162
bd033291 1163static int fn_out_diff_words_write_helper(struct diff_options *o,
882749a0
TR
1164 struct diff_words_style_elem *st_el,
1165 const char *newline,
bd033291 1166 size_t count, const char *buf)
882749a0 1167{
4297c0ae 1168 int print = 0;
bd033291 1169 struct strbuf sb = STRBUF_INIT;
4297c0ae 1170
882749a0
TR
1171 while (count) {
1172 char *p = memchr(buf, '\n', count);
4297c0ae 1173 if (print)
bd033291
SB
1174 strbuf_addstr(&sb, diff_line_prefix(o));
1175
882749a0 1176 if (p != buf) {
bd033291
SB
1177 const char *reset = st_el->color && *st_el->color ?
1178 GIT_COLOR_RESET : NULL;
1179 if (st_el->color && *st_el->color)
1180 strbuf_addstr(&sb, st_el->color);
1181 strbuf_addstr(&sb, st_el->prefix);
1182 strbuf_add(&sb, buf, p ? p - buf : count);
1183 strbuf_addstr(&sb, st_el->suffix);
1184 if (reset)
1185 strbuf_addstr(&sb, reset);
882749a0
TR
1186 }
1187 if (!p)
bd033291
SB
1188 goto out;
1189
1190 strbuf_addstr(&sb, newline);
882749a0
TR
1191 count -= p + 1 - buf;
1192 buf = p + 1;
4297c0ae 1193 print = 1;
bd033291
SB
1194 if (count) {
1195 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1196 sb.buf, sb.len, 0);
1197 strbuf_reset(&sb);
1198 }
882749a0 1199 }
bd033291
SB
1200
1201out:
1202 if (sb.len)
1203 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1204 sb.buf, sb.len, 0);
1205 strbuf_release(&sb);
882749a0
TR
1206 return 0;
1207}
1208
4297c0ae
BY
1209/*
1210 * '--color-words' algorithm can be described as:
1211 *
5621760f 1212 * 1. collect the minus/plus lines of a diff hunk, divided into
4297c0ae
BY
1213 * minus-lines and plus-lines;
1214 *
1215 * 2. break both minus-lines and plus-lines into words and
1216 * place them into two mmfile_t with one word for each line;
1217 *
1218 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1219 *
1220 * And for the common parts of the both file, we output the plus side text.
1221 * diff_words->current_plus is used to trace the current position of the plus file
1222 * which printed. diff_words->last_minus is used to trace the last minus word
1223 * printed.
1224 *
1225 * For '--graph' to work with '--color-words', we need to output the graph prefix
1226 * on each line of color words output. Generally, there are two conditions on
1227 * which we should output the prefix.
1228 *
1229 * 1. diff_words->last_minus == 0 &&
1230 * diff_words->current_plus == diff_words->plus.text.ptr
1231 *
1232 * that is: the plus text must start as a new line, and if there is no minus
1233 * word printed, a graph prefix must be printed.
1234 *
1235 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1236 * *(diff_words->current_plus - 1) == '\n'
1237 *
1238 * that is: a graph prefix must be printed following a '\n'
1239 */
1240static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1241{
1242 if ((diff_words->last_minus == 0 &&
1243 diff_words->current_plus == diff_words->plus.text.ptr) ||
1244 (diff_words->current_plus > diff_words->plus.text.ptr &&
1245 *(diff_words->current_plus - 1) == '\n')) {
1246 return 1;
1247 } else {
1248 return 0;
1249 }
1250}
1251
f59a59e2 1252static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
f59a59e2 1253{
f59a59e2 1254 struct diff_words_data *diff_words = priv;
882749a0 1255 struct diff_words_style *style = diff_words->style;
2e5d2003
JS
1256 int minus_first, minus_len, plus_first, plus_len;
1257 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
4297c0ae 1258 struct diff_options *opt = diff_words->opt;
30997bb8 1259 const char *line_prefix;
f59a59e2 1260
2e5d2003
JS
1261 if (line[0] != '@' || parse_hunk_header(line, len,
1262 &minus_first, &minus_len, &plus_first, &plus_len))
f59a59e2
JS
1263 return;
1264
4297c0ae 1265 assert(opt);
30997bb8 1266 line_prefix = diff_line_prefix(opt);
4297c0ae 1267
2e5d2003
JS
1268 /* POSIX requires that first be decremented by one if len == 0... */
1269 if (minus_len) {
1270 minus_begin = diff_words->minus.orig[minus_first].begin;
1271 minus_end =
1272 diff_words->minus.orig[minus_first + minus_len - 1].end;
1273 } else
1274 minus_begin = minus_end =
1275 diff_words->minus.orig[minus_first].end;
1276
1277 if (plus_len) {
1278 plus_begin = diff_words->plus.orig[plus_first].begin;
1279 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1280 } else
1281 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1282
4297c0ae
BY
1283 if (color_words_output_graph_prefix(diff_words)) {
1284 fputs(line_prefix, diff_words->opt->file);
1285 }
1286 if (diff_words->current_plus != plus_begin) {
bd033291 1287 fn_out_diff_words_write_helper(diff_words->opt,
882749a0
TR
1288 &style->ctx, style->newline,
1289 plus_begin - diff_words->current_plus,
bd033291 1290 diff_words->current_plus);
4297c0ae
BY
1291 }
1292 if (minus_begin != minus_end) {
bd033291 1293 fn_out_diff_words_write_helper(diff_words->opt,
882749a0 1294 &style->old, style->newline,
bd033291 1295 minus_end - minus_begin, minus_begin);
4297c0ae
BY
1296 }
1297 if (plus_begin != plus_end) {
bd033291 1298 fn_out_diff_words_write_helper(diff_words->opt,
882749a0 1299 &style->new, style->newline,
bd033291 1300 plus_end - plus_begin, plus_begin);
4297c0ae 1301 }
2e5d2003
JS
1302
1303 diff_words->current_plus = plus_end;
4297c0ae 1304 diff_words->last_minus = minus_first;
f59a59e2
JS
1305}
1306
2b6a5417
JS
1307/* This function starts looking at *begin, and returns 0 iff a word was found. */
1308static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1309 int *begin, int *end)
1310{
1311 if (word_regex && *begin < buffer->size) {
1312 regmatch_t match[1];
b7d36ffc
JS
1313 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1314 buffer->size - *begin, 1, match, 0)) {
2b6a5417
JS
1315 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1316 '\n', match[0].rm_eo - match[0].rm_so);
1317 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1318 *begin += match[0].rm_so;
1319 return *begin >= *end;
1320 }
1321 return -1;
f59a59e2
JS
1322 }
1323
2b6a5417
JS
1324 /* find the next word */
1325 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1326 (*begin)++;
1327 if (*begin >= buffer->size)
1328 return -1;
f59a59e2 1329
2b6a5417
JS
1330 /* find the end of the word */
1331 *end = *begin + 1;
1332 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1333 (*end)++;
1334
1335 return 0;
f59a59e2
JS
1336}
1337
23c1575f 1338/*
2e5d2003
JS
1339 * This function splits the words in buffer->text, stores the list with
1340 * newline separator into out, and saves the offsets of the original words
1341 * in buffer->orig.
23c1575f 1342 */
2b6a5417
JS
1343static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1344 regex_t *word_regex)
f59a59e2 1345{
2e5d2003 1346 int i, j;
2b6a5417 1347 long alloc = 0;
f59a59e2 1348
2e5d2003 1349 out->size = 0;
2b6a5417 1350 out->ptr = NULL;
f59a59e2 1351
2e5d2003
JS
1352 /* fake an empty "0th" word */
1353 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1354 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1355 buffer->orig_nr = 1;
1356
1357 for (i = 0; i < buffer->text.size; i++) {
2b6a5417
JS
1358 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1359 return;
2e5d2003
JS
1360
1361 /* store original boundaries */
1362 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1363 buffer->orig_alloc);
1364 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1365 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1366 buffer->orig_nr++;
1367
1368 /* store one word */
2b6a5417 1369 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2e5d2003
JS
1370 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1371 out->ptr[out->size + j - i] = '\n';
1372 out->size += j - i + 1;
1373
1374 i = j - 1;
f59a59e2
JS
1375 }
1376}
1377
1378/* this executes the word diff on the accumulated buffers */
1379static void diff_words_show(struct diff_words_data *diff_words)
1380{
1381 xpparam_t xpp;
1382 xdemitconf_t xecfg;
f59a59e2 1383 mmfile_t minus, plus;
882749a0 1384 struct diff_words_style *style = diff_words->style;
f59a59e2 1385
4297c0ae 1386 struct diff_options *opt = diff_words->opt;
30997bb8 1387 const char *line_prefix;
4297c0ae
BY
1388
1389 assert(opt);
30997bb8 1390 line_prefix = diff_line_prefix(opt);
4297c0ae 1391
2e5d2003
JS
1392 /* special case: only removal */
1393 if (!diff_words->plus.text.size) {
bd033291
SB
1394 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1395 line_prefix, strlen(line_prefix), 0);
1396 fn_out_diff_words_write_helper(diff_words->opt,
882749a0 1397 &style->old, style->newline,
4297c0ae 1398 diff_words->minus.text.size,
bd033291 1399 diff_words->minus.text.ptr);
2e5d2003
JS
1400 diff_words->minus.text.size = 0;
1401 return;
1402 }
1403
1404 diff_words->current_plus = diff_words->plus.text.ptr;
4297c0ae 1405 diff_words->last_minus = 0;
f59a59e2 1406
9ccd0a88 1407 memset(&xpp, 0, sizeof(xpp));
30b25010 1408 memset(&xecfg, 0, sizeof(xecfg));
2b6a5417
JS
1409 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1410 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
582aa00b 1411 xpp.flags = 0;
2b6a5417 1412 /* as only the hunk header will be parsed, we need a 0-context */
2e5d2003 1413 xecfg.ctxlen = 0;
3efb9880
JK
1414 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1415 &xpp, &xecfg))
1416 die("unable to generate word diff");
f59a59e2
JS
1417 free(minus.ptr);
1418 free(plus.ptr);
2e5d2003 1419 if (diff_words->current_plus != diff_words->plus.text.ptr +
4297c0ae
BY
1420 diff_words->plus.text.size) {
1421 if (color_words_output_graph_prefix(diff_words))
bd033291
SB
1422 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1423 line_prefix, strlen(line_prefix), 0);
1424 fn_out_diff_words_write_helper(diff_words->opt,
882749a0 1425 &style->ctx, style->newline,
2e5d2003 1426 diff_words->plus.text.ptr + diff_words->plus.text.size
bd033291 1427 - diff_words->current_plus, diff_words->current_plus);
4297c0ae 1428 }
f59a59e2 1429 diff_words->minus.text.size = diff_words->plus.text.size = 0;
f59a59e2
JS
1430}
1431
76fd2828
JH
1432/* In "color-words" mode, show word-diff of words accumulated in the buffer */
1433static void diff_words_flush(struct emit_callback *ecbdata)
1434{
e6e045f8
SB
1435 struct diff_options *wo = ecbdata->diff_words->opt;
1436
76fd2828
JH
1437 if (ecbdata->diff_words->minus.text.size ||
1438 ecbdata->diff_words->plus.text.size)
1439 diff_words_show(ecbdata->diff_words);
e6e045f8
SB
1440
1441 if (wo->emitted_symbols) {
1442 struct diff_options *o = ecbdata->opt;
1443 struct emitted_diff_symbols *wol = wo->emitted_symbols;
1444 int i;
1445
1446 /*
1447 * NEEDSWORK:
1448 * Instead of appending each, concat all words to a line?
1449 */
1450 for (i = 0; i < wol->nr; i++)
1451 append_emitted_diff_symbol(o, &wol->buf[i]);
1452
1453 for (i = 0; i < wol->nr; i++)
1454 free((void *)wol->buf[i].line);
1455
1456 wol->nr = 0;
1457 }
76fd2828
JH
1458}
1459
77d1a520
TR
1460static void diff_filespec_load_driver(struct diff_filespec *one)
1461{
1462 /* Use already-loaded driver */
1463 if (one->driver)
1464 return;
1465
1466 if (S_ISREG(one->mode))
1467 one->driver = userdiff_find_by_path(one->path);
1468
1469 /* Fallback to default settings */
1470 if (!one->driver)
1471 one->driver = userdiff_find_by_name("default");
1472}
1473
1474static const char *userdiff_word_regex(struct diff_filespec *one)
1475{
1476 diff_filespec_load_driver(one);
1477 return one->driver->word_regex;
1478}
1479
1480static void init_diff_words_data(struct emit_callback *ecbdata,
6440d341 1481 struct diff_options *orig_opts,
77d1a520
TR
1482 struct diff_filespec *one,
1483 struct diff_filespec *two)
1484{
1485 int i;
6440d341
TR
1486 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1487 memcpy(o, orig_opts, sizeof(struct diff_options));
77d1a520
TR
1488
1489 ecbdata->diff_words =
1490 xcalloc(1, sizeof(struct diff_words_data));
1491 ecbdata->diff_words->type = o->word_diff;
1492 ecbdata->diff_words->opt = o;
e6e045f8
SB
1493
1494 if (orig_opts->emitted_symbols)
1495 o->emitted_symbols =
1496 xcalloc(1, sizeof(struct emitted_diff_symbols));
1497
77d1a520
TR
1498 if (!o->word_regex)
1499 o->word_regex = userdiff_word_regex(one);
1500 if (!o->word_regex)
1501 o->word_regex = userdiff_word_regex(two);
1502 if (!o->word_regex)
1503 o->word_regex = diff_word_regex_cfg;
1504 if (o->word_regex) {
1505 ecbdata->diff_words->word_regex = (regex_t *)
1506 xmalloc(sizeof(regex_t));
1507 if (regcomp(ecbdata->diff_words->word_regex,
1508 o->word_regex,
1509 REG_EXTENDED | REG_NEWLINE))
1510 die ("Invalid regular expression: %s",
1511 o->word_regex);
1512 }
1513 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1514 if (o->word_diff == diff_words_styles[i].type) {
1515 ecbdata->diff_words->style =
1516 &diff_words_styles[i];
1517 break;
1518 }
1519 }
1520 if (want_color(o->use_color)) {
1521 struct diff_words_style *st = ecbdata->diff_words->style;
1522 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1523 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
8dbf3eb6 1524 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
77d1a520
TR
1525 }
1526}
1527
f59a59e2
JS
1528static void free_diff_words_data(struct emit_callback *ecbdata)
1529{
1530 if (ecbdata->diff_words) {
76fd2828 1531 diff_words_flush(ecbdata);
e6e045f8 1532 free (ecbdata->diff_words->opt->emitted_symbols);
6440d341 1533 free (ecbdata->diff_words->opt);
8e0f7003 1534 free (ecbdata->diff_words->minus.text.ptr);
2e5d2003 1535 free (ecbdata->diff_words->minus.orig);
8e0f7003 1536 free (ecbdata->diff_words->plus.text.ptr);
2e5d2003 1537 free (ecbdata->diff_words->plus.orig);
ef5644ea
BC
1538 if (ecbdata->diff_words->word_regex) {
1539 regfree(ecbdata->diff_words->word_regex);
1540 free(ecbdata->diff_words->word_regex);
1541 }
6a83d902 1542 FREE_AND_NULL(ecbdata->diff_words);
f59a59e2
JS
1543 }
1544}
1545
ce436973 1546const char *diff_get_color(int diff_use_color, enum color_diff ix)
cd112cef 1547{
daa0c3d9 1548 if (want_color(diff_use_color))
50f575fc
LT
1549 return diff_colors[ix];
1550 return "";
cd112cef
JS
1551}
1552
f1922234
JK
1553const char *diff_line_prefix(struct diff_options *opt)
1554{
1555 struct strbuf *msgbuf;
1556 if (!opt->output_prefix)
1557 return "";
1558
1559 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1560 return msgbuf->buf;
1561}
1562
23707811
JH
1563static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1564{
1565 const char *cp;
1566 unsigned long allot;
1567 size_t l = len;
1568
1569 if (ecb->truncate)
1570 return ecb->truncate(line, len);
1571 cp = line;
1572 allot = l;
1573 while (0 < l) {
1574 (void) utf8_width(&cp, &l);
1575 if (!cp)
1576 break; /* truncated in the middle? */
1577 }
1578 return allot - l;
1579}
1580
d68fe26f 1581static void find_lno(const char *line, struct emit_callback *ecbdata)
690ed843 1582{
d68fe26f
JH
1583 const char *p;
1584 ecbdata->lno_in_preimage = 0;
1585 ecbdata->lno_in_postimage = 0;
1586 p = strchr(line, '-');
690ed843 1587 if (!p)
d68fe26f
JH
1588 return; /* cannot happen */
1589 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1590 p = strchr(p, '+');
1591 if (!p)
1592 return; /* cannot happen */
1593 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
690ed843
JH
1594}
1595
cd112cef 1596static void fn_out_consume(void *priv, char *line, unsigned long len)
6973dcae 1597{
6973dcae 1598 struct emit_callback *ecbdata = priv;
ce436973 1599 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
7be57610 1600 struct diff_options *o = ecbdata->opt;
6973dcae 1601
ba16233c
SB
1602 o->found_changes = 1;
1603
3e97c7c6 1604 if (ecbdata->header) {
a29b0a13
SB
1605 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
1606 ecbdata->header->buf, ecbdata->header->len, 0);
3e97c7c6
GB
1607 strbuf_reset(ecbdata->header);
1608 ecbdata->header = NULL;
1609 }
34a5e1a2 1610
6973dcae 1611 if (ecbdata->label_path[0]) {
3ee8b7bf
SB
1612 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1613 ecbdata->label_path[0],
1614 strlen(ecbdata->label_path[0]), 0);
1615 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1616 ecbdata->label_path[1],
1617 strlen(ecbdata->label_path[1]), 0);
6973dcae
JH
1618 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1619 }
cd112cef 1620
a624eaa7
JM
1621 if (diff_suppress_blank_empty
1622 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1623 line[0] = '\n';
1624 len = 1;
1625 }
1626
b8d9c1a6 1627 if (line[0] == '@') {
76fd2828
JH
1628 if (ecbdata->diff_words)
1629 diff_words_flush(ecbdata);
23707811 1630 len = sane_truncate_line(ecbdata, line, len);
d68fe26f 1631 find_lno(line, ecbdata);
89cb73a1 1632 emit_hunk_header(ecbdata, line, len);
448c3ef1 1633 return;
cd112cef 1634 }
448c3ef1 1635
448c3ef1 1636 if (ecbdata->diff_words) {
ff958679
SB
1637 enum diff_symbol s =
1638 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
1639 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
448c3ef1
JH
1640 if (line[0] == '-') {
1641 diff_words_append(line, len,
1642 &ecbdata->diff_words->minus);
1643 return;
1644 } else if (line[0] == '+') {
1645 diff_words_append(line, len,
1646 &ecbdata->diff_words->plus);
1647 return;
59556548 1648 } else if (starts_with(line, "\\ ")) {
c7c2bc0a
TR
1649 /*
1650 * Eat the "no newline at eof" marker as if we
1651 * saw a "+" or "-" line with nothing on it,
1652 * and return without diff_words_flush() to
1653 * defer processing. If this is the end of
1654 * preimage, more "+" lines may come after it.
1655 */
1656 return;
448c3ef1 1657 }
76fd2828 1658 diff_words_flush(ecbdata);
ff958679 1659 emit_diff_symbol(o, s, line, len, 0);
448c3ef1
JH
1660 return;
1661 }
448c3ef1 1662
0e383e18
JH
1663 switch (line[0]) {
1664 case '+':
d68fe26f 1665 ecbdata->lno_in_postimage++;
018cff70 1666 emit_add_line(reset, ecbdata, line + 1, len - 1);
0e383e18
JH
1667 break;
1668 case '-':
1669 ecbdata->lno_in_preimage++;
1670 emit_del_line(reset, ecbdata, line + 1, len - 1);
1671 break;
1672 case ' ':
1673 ecbdata->lno_in_postimage++;
1674 ecbdata->lno_in_preimage++;
1675 emit_context_line(reset, ecbdata, line + 1, len - 1);
1676 break;
1677 default:
1678 /* incomplete line at the end */
1679 ecbdata->lno_in_preimage++;
f2bb1218
SB
1680 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
1681 line, len, 0);
0e383e18 1682 break;
448c3ef1 1683 }
6973dcae
JH
1684}
1685
1686static char *pprint_rename(const char *a, const char *b)
1687{
1688 const char *old = a;
1689 const char *new = b;
f285a2d7 1690 struct strbuf name = STRBUF_INIT;
6973dcae 1691 int pfx_length, sfx_length;
dd281f09 1692 int pfx_adjust_for_slash;
6973dcae
JH
1693 int len_a = strlen(a);
1694 int len_b = strlen(b);
663af342 1695 int a_midlen, b_midlen;
e5bfbf9b
AJ
1696 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1697 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1698
1699 if (qlen_a || qlen_b) {
663af342
PH
1700 quote_c_style(a, &name, NULL, 0);
1701 strbuf_addstr(&name, " => ");
1702 quote_c_style(b, &name, NULL, 0);
b315c5c0 1703 return strbuf_detach(&name, NULL);
e5bfbf9b 1704 }
6973dcae
JH
1705
1706 /* Find common prefix */
1707 pfx_length = 0;
1708 while (*old && *new && *old == *new) {
1709 if (*old == '/')
1710 pfx_length = old - a + 1;
1711 old++;
1712 new++;
1713 }
1714
1715 /* Find common suffix */
1716 old = a + len_a;
1717 new = b + len_b;
1718 sfx_length = 0;
d020e27f 1719 /*
dd281f09
TR
1720 * If there is a common prefix, it must end in a slash. In
1721 * that case we let this loop run 1 into the prefix to see the
1722 * same slash.
1723 *
1724 * If there is no common prefix, we cannot do this as it would
1725 * underrun the input strings.
d020e27f 1726 */
dd281f09
TR
1727 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
1728 while (a + pfx_length - pfx_adjust_for_slash <= old &&
1729 b + pfx_length - pfx_adjust_for_slash <= new &&
d020e27f 1730 *old == *new) {
6973dcae
JH
1731 if (*old == '/')
1732 sfx_length = len_a - (old - a);
1733 old--;
1734 new--;
1735 }
1736
1737 /*
1738 * pfx{mid-a => mid-b}sfx
1739 * {pfx-a => pfx-b}sfx
1740 * pfx{sfx-a => sfx-b}
1741 * name-a => name-b
1742 */
663af342
PH
1743 a_midlen = len_a - pfx_length - sfx_length;
1744 b_midlen = len_b - pfx_length - sfx_length;
1745 if (a_midlen < 0)
1746 a_midlen = 0;
1747 if (b_midlen < 0)
1748 b_midlen = 0;
1749
1750 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
6973dcae 1751 if (pfx_length + sfx_length) {
663af342
PH
1752 strbuf_add(&name, a, pfx_length);
1753 strbuf_addch(&name, '{');
6973dcae 1754 }
663af342
PH
1755 strbuf_add(&name, a + pfx_length, a_midlen);
1756 strbuf_addstr(&name, " => ");
1757 strbuf_add(&name, b + pfx_length, b_midlen);
1758 if (pfx_length + sfx_length) {
1759 strbuf_addch(&name, '}');
1760 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
6973dcae 1761 }
b315c5c0 1762 return strbuf_detach(&name, NULL);
6973dcae
JH
1763}
1764
1765struct diffstat_t {
6973dcae
JH
1766 int nr;
1767 int alloc;
1768 struct diffstat_file {
f604652e 1769 char *from_name;
6973dcae 1770 char *name;
f604652e 1771 char *print_name;
6973dcae
JH
1772 unsigned is_unmerged:1;
1773 unsigned is_binary:1;
1774 unsigned is_renamed:1;
74faaa16 1775 unsigned is_interesting:1;
0974c117 1776 uintmax_t added, deleted;
6973dcae
JH
1777 } **files;
1778};
1779
1780static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1781 const char *name_a,
1782 const char *name_b)
1783{
1784 struct diffstat_file *x;
1a4927c5 1785 x = xcalloc(1, sizeof(*x));
4c960a43 1786 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
6973dcae
JH
1787 diffstat->files[diffstat->nr++] = x;
1788 if (name_b) {
f604652e
JH
1789 x->from_name = xstrdup(name_a);
1790 x->name = xstrdup(name_b);
6973dcae
JH
1791 x->is_renamed = 1;
1792 }
f604652e
JH
1793 else {
1794 x->from_name = NULL;
9befac47 1795 x->name = xstrdup(name_a);
f604652e 1796 }
6973dcae
JH
1797 return x;
1798}
1799
1800static void diffstat_consume(void *priv, char *line, unsigned long len)
1801{
1802 struct diffstat_t *diffstat = priv;
1803 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1804
1805 if (line[0] == '+')
1806 x->added++;
1807 else if (line[0] == '-')
1808 x->deleted++;
1809}
1810
698ce6f8 1811const char mime_boundary_leader[] = "------------";
6973dcae 1812
a2540023
JH
1813static int scale_linear(int it, int width, int max_change)
1814{
2eeeef24
JH
1815 if (!it)
1816 return 0;
a2540023 1817 /*
2eeeef24
JH
1818 * make sure that at least one '-' or '+' is printed if
1819 * there is any change to this path. The easiest way is to
1820 * scale linearly as if the alloted width is one column shorter
1821 * than it is, and then add 1 to the result.
a2540023 1822 */
2eeeef24 1823 return 1 + (it * (width - 1) / max_change);
a2540023
JH
1824}
1825
0911c475
SB
1826static void show_graph(struct strbuf *out, char ch, int cnt,
1827 const char *set, const char *reset)
a2540023
JH
1828{
1829 if (cnt <= 0)
1830 return;
0911c475
SB
1831 strbuf_addstr(out, set);
1832 strbuf_addchars(out, ch, cnt);
1833 strbuf_addstr(out, reset);
a2540023
JH
1834}
1835
f604652e
JH
1836static void fill_print_name(struct diffstat_file *file)
1837{
1838 char *pname;
1839
1840 if (file->print_name)
1841 return;
1842
1843 if (!file->is_renamed) {
f285a2d7 1844 struct strbuf buf = STRBUF_INIT;
f604652e
JH
1845 if (quote_c_style(file->name, &buf, NULL, 0)) {
1846 pname = strbuf_detach(&buf, NULL);
1847 } else {
1848 pname = file->name;
1849 strbuf_release(&buf);
1850 }
1851 } else {
1852 pname = pprint_rename(file->from_name, file->name);
1853 }
1854 file->print_name = pname;
1855}
1856
0911c475
SB
1857static void print_stat_summary_inserts_deletes(struct diff_options *options,
1858 int files, int insertions, int deletions)
7f814632
NTND
1859{
1860 struct strbuf sb = STRBUF_INIT;
7f814632
NTND
1861
1862 if (!files) {
1863 assert(insertions == 0 && deletions == 0);
0911c475
SB
1864 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
1865 NULL, 0, 0);
1866 return;
7f814632
NTND
1867 }
1868
1869 strbuf_addf(&sb,
218adaaa 1870 (files == 1) ? " %d file changed" : " %d files changed",
7f814632
NTND
1871 files);
1872
1873 /*
1874 * For binary diff, the caller may want to print "x files
1875 * changed" with insertions == 0 && deletions == 0.
1876 *
1877 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
1878 * is probably less confusing (i.e skip over "2 files changed
1879 * but nothing about added/removed lines? Is this a bug in Git?").
1880 */
1881 if (insertions || deletions == 0) {
7f814632 1882 strbuf_addf(&sb,
218adaaa 1883 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
7f814632
NTND
1884 insertions);
1885 }
1886
1887 if (deletions || insertions == 0) {
7f814632 1888 strbuf_addf(&sb,
218adaaa 1889 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
7f814632
NTND
1890 deletions);
1891 }
1892 strbuf_addch(&sb, '\n');
0911c475
SB
1893 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
1894 sb.buf, sb.len, 0);
7f814632 1895 strbuf_release(&sb);
0911c475
SB
1896}
1897
1898void print_stat_summary(FILE *fp, int files,
1899 int insertions, int deletions)
1900{
1901 struct diff_options o;
1902 memset(&o, 0, sizeof(o));
1903 o.file = fp;
1904
1905 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
7f814632
NTND
1906}
1907
4b25d091 1908static void show_stats(struct diffstat_t *data, struct diff_options *options)
6973dcae 1909{
eb3a9dd3 1910 int i, len, add, del, adds = 0, dels = 0;
0974c117 1911 uintmax_t max_change = 0, max_len = 0;
dc801e71
ZJS
1912 int total_files = data->nr, count;
1913 int width, name_width, graph_width, number_width = 0, bin_width = 0;
c0aa335c 1914 const char *reset, *add_c, *del_c;
e5f85df8 1915 int extra_shown = 0;
0911c475
SB
1916 const char *line_prefix = diff_line_prefix(options);
1917 struct strbuf out = STRBUF_INIT;
6973dcae
JH
1918
1919 if (data->nr == 0)
1920 return;
1921
808e1db2 1922 count = options->stat_count ? options->stat_count : data->nr;
a2540023 1923
8f67f8ae 1924 reset = diff_get_color_opt(options, DIFF_RESET);
8f67f8ae
PH
1925 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1926 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
785f7432 1927
1b058bc3
ZJS
1928 /*
1929 * Find the longest filename and max number of changes
1930 */
808e1db2 1931 for (i = 0; (i < count) && (i < data->nr); i++) {
6973dcae 1932 struct diffstat_file *file = data->files[i];
0974c117 1933 uintmax_t change = file->added + file->deleted;
af0ed819
JH
1934
1935 if (!file->is_interesting && (change == 0)) {
808e1db2 1936 count++; /* not shown == room for one more */
358e460e
MG
1937 continue;
1938 }
f604652e
JH
1939 fill_print_name(file);
1940 len = strlen(file->print_name);
6973dcae
JH
1941 if (max_len < len)
1942 max_len = len;
1943
dc801e71
ZJS
1944 if (file->is_unmerged) {
1945 /* "Unmerged" is 8 characters */
1946 bin_width = bin_width < 8 ? 8 : bin_width;
6973dcae 1947 continue;
dc801e71
ZJS
1948 }
1949 if (file->is_binary) {
1950 /* "Bin XXX -> YYY bytes" */
1951 int w = 14 + decimal_width(file->added)
1952 + decimal_width(file->deleted);
1953 bin_width = bin_width < w ? w : bin_width;
1954 /* Display change counts aligned with "Bin" */
1955 number_width = 3;
1956 continue;
1957 }
1958
a2540023
JH
1959 if (max_change < change)
1960 max_change = change;
6973dcae 1961 }
a20d3c0d 1962 count = i; /* where we can stop scanning in data->files[] */
6973dcae 1963
1b058bc3
ZJS
1964 /*
1965 * We have width = stat_width or term_columns() columns total.
1966 * We want a maximum of min(max_len, stat_name_width) for the name part.
969fe57b 1967 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1b058bc3
ZJS
1968 * We also need 1 for " " and 4 + decimal_width(max_change)
1969 * for " | NNNN " and one the empty column at the end, altogether
1970 * 6 + decimal_width(max_change).
1971 *
1972 * If there's not enough space, we will use the smaller of
1973 * stat_name_width (if set) and 5/8*width for the filename,
969fe57b
ZJS
1974 * and the rest for constant elements + graph part, but no more
1975 * than stat_graph_width for the graph part.
1b058bc3
ZJS
1976 * (5/8 gives 50 for filename and 30 for the constant parts + graph
1977 * for the standard terminal size).
a2540023 1978 *
1b058bc3
ZJS
1979 * In other words: stat_width limits the maximum width, and
1980 * stat_name_width fixes the maximum width of the filename,
1981 * and is also used to divide available columns if there
1982 * aren't enough.
dc801e71
ZJS
1983 *
1984 * Binary files are displayed with "Bin XXX -> YYY bytes"
1985 * instead of the change count and graph. This part is treated
1986 * similarly to the graph part, except that it is not
41ccfdd9 1987 * "scaled". If total width is too small to accommodate the
dc801e71
ZJS
1988 * guaranteed minimum width of the filename part and the
1989 * separators and this message, this message will "overflow"
1990 * making the line longer than the maximum width.
a2540023 1991 */
1b058bc3
ZJS
1992
1993 if (options->stat_width == -1)
cd48dadb 1994 width = term_columns() - strlen(line_prefix);
a2540023 1995 else
1b058bc3 1996 width = options->stat_width ? options->stat_width : 80;
dc801e71
ZJS
1997 number_width = decimal_width(max_change) > number_width ?
1998 decimal_width(max_change) : number_width;
a2540023 1999
df44483a
ZJS
2000 if (options->stat_graph_width == -1)
2001 options->stat_graph_width = diff_stat_graph_width;
a2540023 2002
1b058bc3
ZJS
2003 /*
2004 * Guarantee 3/8*16==6 for the graph part
2005 * and 5/8*16==10 for the filename part
2006 */
2007 if (width < 16 + 6 + number_width)
2008 width = 16 + 6 + number_width;
2009
2010 /*
2011 * First assign sizes that are wanted, ignoring available width.
dc801e71
ZJS
2012 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2013 * starting from "XXX" should fit in graph_width.
1b058bc3 2014 */
dc801e71
ZJS
2015 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2016 if (options->stat_graph_width &&
2017 options->stat_graph_width < graph_width)
2018 graph_width = options->stat_graph_width;
2019
1b058bc3
ZJS
2020 name_width = (options->stat_name_width > 0 &&
2021 options->stat_name_width < max_len) ?
2022 options->stat_name_width : max_len;
2023
2024 /*
2025 * Adjust adjustable widths not to exceed maximum width
2026 */
2027 if (name_width + number_width + 6 + graph_width > width) {
678c5741 2028 if (graph_width > width * 3/8 - number_width - 6) {
1b058bc3 2029 graph_width = width * 3/8 - number_width - 6;
678c5741
LP
2030 if (graph_width < 6)
2031 graph_width = 6;
2032 }
2033
969fe57b
ZJS
2034 if (options->stat_graph_width &&
2035 graph_width > options->stat_graph_width)
2036 graph_width = options->stat_graph_width;
1b058bc3
ZJS
2037 if (name_width > width - number_width - 6 - graph_width)
2038 name_width = width - number_width - 6 - graph_width;
2039 else
2040 graph_width = width - number_width - 6 - name_width;
2041 }
2042
2043 /*
2044 * From here name_width is the width of the name area,
2045 * and graph_width is the width of the graph area.
2046 * max_change is used to scale graph properly.
2047 */
808e1db2 2048 for (i = 0; i < count; i++) {
d2543b8e 2049 const char *prefix = "";
af0ed819
JH
2050 struct diffstat_file *file = data->files[i];
2051 char *name = file->print_name;
2052 uintmax_t added = file->added;
2053 uintmax_t deleted = file->deleted;
a2540023 2054 int name_len;
6973dcae 2055
a20d3c0d 2056 if (!file->is_interesting && (added + deleted == 0))
358e460e 2057 continue;
a20d3c0d 2058
6973dcae
JH
2059 /*
2060 * "scale" the filename
2061 */
a2540023
JH
2062 len = name_width;
2063 name_len = strlen(name);
2064 if (name_width < name_len) {
6973dcae
JH
2065 char *slash;
2066 prefix = "...";
a2540023
JH
2067 len -= 3;
2068 name += name_len - len;
6973dcae
JH
2069 slash = strchr(name, '/');
2070 if (slash)
2071 name = slash;
2072 }
6973dcae 2073
af0ed819 2074 if (file->is_binary) {
0911c475
SB
2075 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2076 strbuf_addf(&out, " %*s", number_width, "Bin");
e18872b2 2077 if (!added && !deleted) {
0911c475
SB
2078 strbuf_addch(&out, '\n');
2079 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2080 out.buf, out.len, 0);
2081 strbuf_reset(&out);
e18872b2
ZJS
2082 continue;
2083 }
0911c475 2084 strbuf_addf(&out, " %s%"PRIuMAX"%s",
0974c117 2085 del_c, deleted, reset);
0911c475
SB
2086 strbuf_addstr(&out, " -> ");
2087 strbuf_addf(&out, "%s%"PRIuMAX"%s",
0974c117 2088 add_c, added, reset);
0911c475
SB
2089 strbuf_addstr(&out, " bytes\n");
2090 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2091 out.buf, out.len, 0);
2092 strbuf_reset(&out);
f604652e 2093 continue;
6973dcae 2094 }
af0ed819 2095 else if (file->is_unmerged) {
0911c475
SB
2096 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2097 strbuf_addstr(&out, " Unmerged\n");
2098 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2099 out.buf, out.len, 0);
2100 strbuf_reset(&out);
f604652e 2101 continue;
6973dcae 2102 }
6973dcae 2103
a2540023
JH
2104 /*
2105 * scale the add/delete
2106 */
6973dcae
JH
2107 add = added;
2108 del = deleted;
6973dcae 2109
1b058bc3 2110 if (graph_width <= max_change) {
d3c9cf32 2111 int total = scale_linear(add + del, graph_width, max_change);
2eeeef24
JH
2112 if (total < 2 && add && del)
2113 /* width >= 2 due to the sanity check */
2114 total = 2;
2115 if (add < del) {
1b058bc3 2116 add = scale_linear(add, graph_width, max_change);
2eeeef24
JH
2117 del = total - add;
2118 } else {
1b058bc3 2119 del = scale_linear(del, graph_width, max_change);
2eeeef24
JH
2120 add = total - del;
2121 }
6973dcae 2122 }
0911c475
SB
2123 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2124 strbuf_addf(&out, " %*"PRIuMAX"%s",
dc801e71
ZJS
2125 number_width, added + deleted,
2126 added + deleted ? " " : "");
0911c475
SB
2127 show_graph(&out, '+', add, add_c, reset);
2128 show_graph(&out, '-', del, del_c, reset);
2129 strbuf_addch(&out, '\n');
2130 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2131 out.buf, out.len, 0);
2132 strbuf_reset(&out);
c0c77734 2133 }
a20d3c0d
JH
2134
2135 for (i = 0; i < data->nr; i++) {
af0ed819
JH
2136 struct diffstat_file *file = data->files[i];
2137 uintmax_t added = file->added;
2138 uintmax_t deleted = file->deleted;
82dfc2c4
JH
2139
2140 if (file->is_unmerged ||
2141 (!file->is_interesting && (added + deleted == 0))) {
808e1db2
MG
2142 total_files--;
2143 continue;
2144 }
a20d3c0d 2145
82dfc2c4 2146 if (!file->is_binary) {
a20d3c0d
JH
2147 adds += added;
2148 dels += deleted;
2149 }
2150 if (i < count)
2151 continue;
e5f85df8 2152 if (!extra_shown)
0911c475
SB
2153 emit_diff_symbol(options,
2154 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2155 NULL, 0, 0);
e5f85df8 2156 extra_shown = 1;
808e1db2 2157 }
0911c475
SB
2158
2159 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
6973dcae
JH
2160}
2161
2775d92c 2162static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
ebd124c6
NP
2163{
2164 int i, adds = 0, dels = 0, total_files = data->nr;
2165
2166 if (data->nr == 0)
2167 return;
2168
2169 for (i = 0; i < data->nr; i++) {
e18872b2 2170 int added = data->files[i]->added;
0911c475 2171 int deleted = data->files[i]->deleted;
e18872b2 2172
20c8cde4
JH
2173 if (data->files[i]->is_unmerged ||
2174 (!data->files[i]->is_interesting && (added + deleted == 0))) {
e18872b2 2175 total_files--;
de9658b5 2176 } else if (!data->files[i]->is_binary) { /* don't count bytes */
e18872b2
ZJS
2177 adds += added;
2178 dels += deleted;
ebd124c6 2179 }
ebd124c6 2180 }
0911c475 2181 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
ebd124c6
NP
2182}
2183
4b25d091 2184static void show_numstat(struct diffstat_t *data, struct diff_options *options)
74e2abe5
JH
2185{
2186 int i;
2187
f604652e
JH
2188 if (data->nr == 0)
2189 return;
2190
74e2abe5
JH
2191 for (i = 0; i < data->nr; i++) {
2192 struct diffstat_file *file = data->files[i];
2193
30997bb8 2194 fprintf(options->file, "%s", diff_line_prefix(options));
7be57610 2195
bfddbc5e 2196 if (file->is_binary)
c0c77734 2197 fprintf(options->file, "-\t-\t");
bfddbc5e 2198 else
c0c77734 2199 fprintf(options->file,
0974c117
JK
2200 "%"PRIuMAX"\t%"PRIuMAX"\t",
2201 file->added, file->deleted);
f604652e
JH
2202 if (options->line_termination) {
2203 fill_print_name(file);
2204 if (!file->is_renamed)
c0c77734 2205 write_name_quoted(file->name, options->file,
f604652e
JH
2206 options->line_termination);
2207 else {
c0c77734
DB
2208 fputs(file->print_name, options->file);
2209 putc(options->line_termination, options->file);
f604652e 2210 }
663af342 2211 } else {
f604652e 2212 if (file->is_renamed) {
c0c77734
DB
2213 putc('\0', options->file);
2214 write_name_quoted(file->from_name, options->file, '\0');
f604652e 2215 }
c0c77734 2216 write_name_quoted(file->name, options->file, '\0');
663af342 2217 }
74e2abe5
JH
2218 }
2219}
2220
c04a7155
JH
2221struct dirstat_file {
2222 const char *name;
2223 unsigned long changed;
7df7c019
LT
2224};
2225
c04a7155
JH
2226struct dirstat_dir {
2227 struct dirstat_file *files;
712d2c7d 2228 int alloc, nr, permille, cumulative;
c04a7155
JH
2229};
2230
7be57610
BY
2231static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2232 unsigned long changed, const char *base, int baselen)
7df7c019
LT
2233{
2234 unsigned long this_dir = 0;
2235 unsigned int sources = 0;
30997bb8 2236 const char *line_prefix = diff_line_prefix(opt);
7df7c019
LT
2237
2238 while (dir->nr) {
c04a7155 2239 struct dirstat_file *f = dir->files;
7df7c019
LT
2240 int namelen = strlen(f->name);
2241 unsigned long this;
2242 char *slash;
2243
2244 if (namelen < baselen)
2245 break;
2246 if (memcmp(f->name, base, baselen))
2247 break;
2248 slash = strchr(f->name + baselen, '/');
2249 if (slash) {
2250 int newbaselen = slash + 1 - f->name;
7be57610 2251 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
7df7c019
LT
2252 sources++;
2253 } else {
c04a7155 2254 this = f->changed;
7df7c019
LT
2255 dir->files++;
2256 dir->nr--;
2257 sources += 2;
2258 }
2259 this_dir += this;
2260 }
2261
2262 /*
2263 * We don't report dirstat's for
2264 * - the top level
2265 * - or cases where everything came from a single directory
2266 * under this directory (sources == 1).
2267 */
2268 if (baselen && sources != 1) {
58a8756a
JH
2269 if (this_dir) {
2270 int permille = this_dir * 1000 / changed;
712d2c7d 2271 if (permille >= dir->permille) {
7be57610 2272 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
712d2c7d 2273 permille / 10, permille % 10, baselen, base);
7df7c019
LT
2274 if (!dir->cumulative)
2275 return 0;
2276 }
2277 }
2278 }
2279 return this_dir;
2280}
2281
441bca0b
LT
2282static int dirstat_compare(const void *_a, const void *_b)
2283{
2284 const struct dirstat_file *a = _a;
2285 const struct dirstat_file *b = _b;
2286 return strcmp(a->name, b->name);
2287}
2288
c04a7155 2289static void show_dirstat(struct diff_options *options)
7df7c019
LT
2290{
2291 int i;
2292 unsigned long changed;
c04a7155
JH
2293 struct dirstat_dir dir;
2294 struct diff_queue_struct *q = &diff_queued_diff;
2295
2296 dir.files = NULL;
2297 dir.alloc = 0;
2298 dir.nr = 0;
712d2c7d 2299 dir.permille = options->dirstat_permille;
f88d225f 2300 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
7df7c019 2301
7df7c019 2302 changed = 0;
c04a7155
JH
2303 for (i = 0; i < q->nr; i++) {
2304 struct diff_filepair *p = q->queue[i];
2305 const char *name;
2306 unsigned long copied, added, damage;
0133dab7 2307 int content_changed;
c04a7155 2308
2ca86714 2309 name = p->two->path ? p->two->path : p->one->path;
c04a7155 2310
41c9560e 2311 if (p->one->oid_valid && p->two->oid_valid)
a0d12c44 2312 content_changed = oidcmp(&p->one->oid, &p->two->oid);
0133dab7
JH
2313 else
2314 content_changed = 1;
2315
2ff3a803
JH
2316 if (!content_changed) {
2317 /*
2318 * The SHA1 has not changed, so pre-/post-content is
2319 * identical. We can therefore skip looking at the
2320 * file contents altogether.
2321 */
2322 damage = 0;
2323 goto found_damage;
2324 }
2325
0133dab7
JH
2326 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
2327 /*
2328 * In --dirstat-by-file mode, we don't really need to
2329 * look at the actual file contents at all.
2330 * The fact that the SHA1 changed is enough for us to
2331 * add this file to the list of results
2332 * (with each file contributing equal damage).
2333 */
2ff3a803 2334 damage = 1;
0133dab7
JH
2335 goto found_damage;
2336 }
c04a7155
JH
2337
2338 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2339 diff_populate_filespec(p->one, 0);
2340 diff_populate_filespec(p->two, 0);
974e0044 2341 diffcore_count_changes(p->one, p->two, NULL, NULL,
c04a7155
JH
2342 &copied, &added);
2343 diff_free_filespec_data(p->one);
2344 diff_free_filespec_data(p->two);
2345 } else if (DIFF_FILE_VALID(p->one)) {
8e5dd3d6 2346 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
c04a7155
JH
2347 copied = added = 0;
2348 diff_free_filespec_data(p->one);
2349 } else if (DIFF_FILE_VALID(p->two)) {
8e5dd3d6 2350 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
c04a7155
JH
2351 copied = 0;
2352 added = p->two->size;
2353 diff_free_filespec_data(p->two);
2354 } else
2b0b551d 2355 continue;
c04a7155
JH
2356
2357 /*
2358 * Original minus copied is the removed material,
2359 * added is the new material. They are both damages
0133dab7 2360 * made to the preimage.
2ff3a803
JH
2361 * If the resulting damage is zero, we know that
2362 * diffcore_count_changes() considers the two entries to
2363 * be identical, but since content_changed is true, we
2364 * know that there must have been _some_ kind of change,
2365 * so we force all entries to have damage > 0.
c04a7155
JH
2366 */
2367 damage = (p->one->size - copied) + added;
2ff3a803 2368 if (!damage)
fd33777b 2369 damage = 1;
c04a7155 2370
0133dab7 2371found_damage:
c04a7155
JH
2372 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2373 dir.files[dir.nr].name = name;
2374 dir.files[dir.nr].changed = damage;
2375 changed += damage;
2376 dir.nr++;
7df7c019
LT
2377 }
2378
2379 /* This can happen even with many files, if everything was renames */
2380 if (!changed)
2381 return;
2382
2383 /* Show all directories with more than x% of the changes */
9ed0d8d6 2384 QSORT(dir.files, dir.nr, dirstat_compare);
7be57610 2385 gather_dirstat(options, &dir, changed, "", 0);
7df7c019
LT
2386}
2387
1c57a627
JH
2388static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2389{
2390 int i;
2391 unsigned long changed;
2392 struct dirstat_dir dir;
2393
2394 if (data->nr == 0)
2395 return;
2396
2397 dir.files = NULL;
2398 dir.alloc = 0;
2399 dir.nr = 0;
2400 dir.permille = options->dirstat_permille;
2401 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2402
2403 changed = 0;
2404 for (i = 0; i < data->nr; i++) {
2405 struct diffstat_file *file = data->files[i];
2406 unsigned long damage = file->added + file->deleted;
2407 if (file->is_binary)
2408 /*
2409 * binary files counts bytes, not lines. Must find some
2410 * way to normalize binary bytes vs. textual lines.
2411 * The following heuristic assumes that there are 64
2412 * bytes per "line".
2413 * This is stupid and ugly, but very cheap...
2414 */
2415 damage = (damage + 63) / 64;
2416 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2417 dir.files[dir.nr].name = file->name;
2418 dir.files[dir.nr].changed = damage;
2419 changed += damage;
2420 dir.nr++;
2421 }
2422
2423 /* This can happen even with many files, if everything was renames */
2424 if (!changed)
2425 return;
2426
2427 /* Show all directories with more than x% of the changes */
9ed0d8d6 2428 QSORT(dir.files, dir.nr, dirstat_compare);
1c57a627
JH
2429 gather_dirstat(options, &dir, changed, "", 0);
2430}
2431
f604652e
JH
2432static void free_diffstat_info(struct diffstat_t *diffstat)
2433{
2434 int i;
2435 for (i = 0; i < diffstat->nr; i++) {
2436 struct diffstat_file *f = diffstat->files[i];
2437 if (f->name != f->print_name)
2438 free(f->print_name);
2439 free(f->name);
2440 free(f->from_name);
2441 free(f);
2442 }
2443 free(diffstat->files);
2444}
2445
88246898 2446struct checkdiff_t {
88246898 2447 const char *filename;
1ba111d1 2448 int lineno;
a757c646 2449 int conflict_marker_size;
1ba111d1 2450 struct diff_options *o;
cf1b7869 2451 unsigned ws_rule;
62c64895 2452 unsigned status;
88246898
JS
2453};
2454
a757c646 2455static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
04954043
JH
2456{
2457 char firstchar;
2458 int cnt;
2459
a757c646 2460 if (len < marker_size + 1)
04954043
JH
2461 return 0;
2462 firstchar = line[0];
2463 switch (firstchar) {
a757c646 2464 case '=': case '>': case '<': case '|':
04954043
JH
2465 break;
2466 default:
2467 return 0;
2468 }
a757c646 2469 for (cnt = 1; cnt < marker_size; cnt++)
04954043
JH
2470 if (line[cnt] != firstchar)
2471 return 0;
a757c646
JH
2472 /* line[1] thru line[marker_size-1] are same as firstchar */
2473 if (len < marker_size + 1 || !isspace(line[marker_size]))
04954043 2474 return 0;
04954043
JH
2475 return 1;
2476}
2477
88246898
JS
2478static void checkdiff_consume(void *priv, char *line, unsigned long len)
2479{
2480 struct checkdiff_t *data = priv;
a757c646 2481 int marker_size = data->conflict_marker_size;
f1c96261
JK
2482 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2483 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2484 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
c1795bb0 2485 char *err;
30997bb8 2486 const char *line_prefix;
7be57610
BY
2487
2488 assert(data->o);
30997bb8 2489 line_prefix = diff_line_prefix(data->o);
88246898
JS
2490
2491 if (line[0] == '+') {
18374e58 2492 unsigned bad;
0ef617f4 2493 data->lineno++;
a757c646 2494 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
04954043
JH
2495 data->status |= 1;
2496 fprintf(data->o->file,
7be57610
BY
2497 "%s%s:%d: leftover conflict marker\n",
2498 line_prefix, data->filename, data->lineno);
04954043 2499 }
8f8841e9 2500 bad = ws_check(line + 1, len - 1, data->ws_rule);
18374e58 2501 if (!bad)
c1795bb0 2502 return;
18374e58
JH
2503 data->status |= bad;
2504 err = whitespace_error_string(bad);
7be57610
BY
2505 fprintf(data->o->file, "%s%s:%d: %s.\n",
2506 line_prefix, data->filename, data->lineno, err);
c1795bb0 2507 free(err);
a3c158d4 2508 emit_line(data->o, set, reset, line, 1);
8f8841e9 2509 ws_check_emit(line + 1, len - 1, data->ws_rule,
1ba111d1 2510 data->o->file, set, reset, ws);
877f23cc 2511 } else if (line[0] == ' ') {
88246898 2512 data->lineno++;
877f23cc 2513 } else if (line[0] == '@') {
88246898
JS
2514 char *plus = strchr(line, '+');
2515 if (plus)
0ef617f4 2516 data->lineno = strtol(plus, NULL, 10) - 1;
88246898
JS
2517 else
2518 die("invalid diff");
2519 }
2520}
2521
0660626c
JH
2522static unsigned char *deflate_it(char *data,
2523 unsigned long size,
2524 unsigned long *result_size)
051308f6 2525{
0660626c
JH
2526 int bound;
2527 unsigned char *deflated;
ef49a7a0 2528 git_zstream stream;
0660626c 2529
55bb5c91 2530 git_deflate_init(&stream, zlib_compression_level);
225a6f10 2531 bound = git_deflate_bound(&stream, size);
0660626c
JH
2532 deflated = xmalloc(bound);
2533 stream.next_out = deflated;
2534 stream.avail_out = bound;
2535
2536 stream.next_in = (unsigned char *)data;
2537 stream.avail_in = size;
55bb5c91 2538 while (git_deflate(&stream, Z_FINISH) == Z_OK)
0660626c 2539 ; /* nothing */
55bb5c91 2540 git_deflate_end(&stream);
0660626c
JH
2541 *result_size = stream.total_out;
2542 return deflated;
051308f6
JH
2543}
2544
4eed0ebd
SB
2545static void emit_binary_diff_body(struct diff_options *o,
2546 mmfile_t *one, mmfile_t *two)
051308f6 2547{
0660626c
JH
2548 void *cp;
2549 void *delta;
2550 void *deflated;
2551 void *data;
2552 unsigned long orig_size;
2553 unsigned long delta_size;
2554 unsigned long deflate_size;
2555 unsigned long data_size;
051308f6 2556
0660626c
JH
2557 /* We could do deflated delta, or we could do just deflated two,
2558 * whichever is smaller.
051308f6 2559 */
0660626c
JH
2560 delta = NULL;
2561 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2562 if (one->size && two->size) {
2563 delta = diff_delta(one->ptr, one->size,
2564 two->ptr, two->size,
2565 &delta_size, deflate_size);
2566 if (delta) {
2567 void *to_free = delta;
2568 orig_size = delta_size;
2569 delta = deflate_it(delta, delta_size, &delta_size);
2570 free(to_free);
051308f6
JH
2571 }
2572 }
051308f6 2573
0660626c 2574 if (delta && delta_size < deflate_size) {
4eed0ebd
SB
2575 char *s = xstrfmt("%lu", orig_size);
2576 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
2577 s, strlen(s), 0);
2578 free(s);
0660626c
JH
2579 free(deflated);
2580 data = delta;
2581 data_size = delta_size;
4eed0ebd
SB
2582 } else {
2583 char *s = xstrfmt("%lu", two->size);
2584 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
2585 s, strlen(s), 0);
2586 free(s);
0660626c
JH
2587 free(delta);
2588 data = deflated;
2589 data_size = deflate_size;
2590 }
051308f6 2591
0660626c
JH
2592 /* emit data encoded in base85 */
2593 cp = data;
2594 while (data_size) {
4eed0ebd 2595 int len;
0660626c 2596 int bytes = (52 < data_size) ? 52 : data_size;
4eed0ebd 2597 char line[71];
0660626c 2598 data_size -= bytes;
051308f6
JH
2599 if (bytes <= 26)
2600 line[0] = bytes + 'A' - 1;
2601 else
2602 line[0] = bytes - 26 + 'a' - 1;
2603 encode_85(line + 1, cp, bytes);
1d7f171c 2604 cp = (char *) cp + bytes;
4eed0ebd
SB
2605
2606 len = strlen(line);
2607 line[len++] = '\n';
2608 line[len] = '\0';
2609
2610 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
2611 line, len, 0);
051308f6 2612 }
4eed0ebd 2613 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
0660626c 2614 free(data);
051308f6
JH
2615}
2616
4eed0ebd
SB
2617static void emit_binary_diff(struct diff_options *o,
2618 mmfile_t *one, mmfile_t *two)
d4c452f0 2619{
4eed0ebd
SB
2620 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
2621 emit_binary_diff_body(o, one, two);
2622 emit_binary_diff_body(o, two, one);
d4c452f0
JH
2623}
2624
29a3eefd
JH
2625int diff_filespec_is_binary(struct diff_filespec *one)
2626{
122aa6f9
JK
2627 if (one->is_binary == -1) {
2628 diff_filespec_load_driver(one);
2629 if (one->driver->binary != -1)
2630 one->is_binary = one->driver->binary;
2631 else {
2632 if (!one->data && DIFF_FILE_VALID(one))
6bf3b813
NTND
2633 diff_populate_filespec(one, CHECK_BINARY);
2634 if (one->is_binary == -1 && one->data)
122aa6f9
JK
2635 one->is_binary = buffer_is_binary(one->data,
2636 one->size);
2637 if (one->is_binary == -1)
2638 one->is_binary = 0;
2639 }
2640 }
29a3eefd 2641 return one->is_binary;
6973dcae
JH
2642}
2643
be58e70d 2644static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
f258475a 2645{
122aa6f9
JK
2646 diff_filespec_load_driver(one);
2647 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
f258475a
JH
2648}
2649
a5a818ee
JH
2650void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2651{
2652 if (!options->a_prefix)
2653 options->a_prefix = a;
2654 if (!options->b_prefix)
2655 options->b_prefix = b;
2656}
2657
a788d7d5 2658struct userdiff_driver *get_textconv(struct diff_filespec *one)
04427ac8
JK
2659{
2660 if (!DIFF_FILE_VALID(one))
2661 return NULL;
d391c0ff 2662
04427ac8 2663 diff_filespec_load_driver(one);
3813e690 2664 return userdiff_get_textconv(one->driver);
04427ac8
JK
2665}
2666
6973dcae
JH
2667static void builtin_diff(const char *name_a,
2668 const char *name_b,
2669 struct diff_filespec *one,
2670 struct diff_filespec *two,
2671 const char *xfrm_msg,
296c6bb2 2672 int must_show_header,
051308f6 2673 struct diff_options *o,
6973dcae
JH
2674 int complete_rewrite)
2675{
2676 mmfile_t mf1, mf2;
2677 const char *lbl[2];
2678 char *a_one, *b_two;
d9c552f1 2679 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
8f67f8ae 2680 const char *reset = diff_get_color_opt(o, DIFF_RESET);
a5a818ee 2681 const char *a_prefix, *b_prefix;
d9bae1a1
JK
2682 struct userdiff_driver *textconv_one = NULL;
2683 struct userdiff_driver *textconv_two = NULL;
3e97c7c6 2684 struct strbuf header = STRBUF_INIT;
30997bb8 2685 const char *line_prefix = diff_line_prefix(o);
a5a818ee 2686
fd47ae6a
JK
2687 diff_set_mnemonic_prefix(o, "a/", "b/");
2688 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2689 a_prefix = o->b_prefix;
2690 b_prefix = o->a_prefix;
2691 } else {
2692 a_prefix = o->a_prefix;
2693 b_prefix = o->b_prefix;
2694 }
2695
61cfbc05
JK
2696 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
2697 (!one->mode || S_ISGITLINK(one->mode)) &&
2698 (!two->mode || S_ISGITLINK(two->mode))) {
f3597138 2699 show_submodule_summary(o, one->path ? one->path : two->path,
602a283a 2700 &one->oid, &two->oid,
f3597138 2701 two->dirty_submodule);
752c0c24 2702 return;
fd47ae6a
JK
2703 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
2704 (!one->mode || S_ISGITLINK(one->mode)) &&
2705 (!two->mode || S_ISGITLINK(two->mode))) {
f3597138 2706 show_submodule_inline_diff(o, one->path ? one->path : two->path,
fd47ae6a 2707 &one->oid, &two->oid,
f3597138 2708 two->dirty_submodule);
fd47ae6a 2709 return;
752c0c24
JS
2710 }
2711
3aa1f7ca
JK
2712 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2713 textconv_one = get_textconv(one);
2714 textconv_two = get_textconv(two);
2715 }
2716
71b989e7
LT
2717 /* Never use a non-valid filename anywhere if at all possible */
2718 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2719 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2720
a5a818ee
JH
2721 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2722 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
6973dcae
JH
2723 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2724 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
d9c552f1 2725 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
6973dcae
JH
2726 if (lbl[0][0] == '/') {
2727 /* /dev/null */
d9c552f1 2728 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
37466447
BW
2729 if (xfrm_msg)
2730 strbuf_addstr(&header, xfrm_msg);
296c6bb2 2731 must_show_header = 1;
6973dcae
JH
2732 }
2733 else if (lbl[1][0] == '/') {
d9c552f1 2734 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
37466447
BW
2735 if (xfrm_msg)
2736 strbuf_addstr(&header, xfrm_msg);
296c6bb2 2737 must_show_header = 1;
6973dcae
JH
2738 }
2739 else {
2740 if (one->mode != two->mode) {
d9c552f1
JK
2741 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
2742 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
296c6bb2 2743 must_show_header = 1;
cd112cef 2744 }
37466447
BW
2745 if (xfrm_msg)
2746 strbuf_addstr(&header, xfrm_msg);
3e97c7c6 2747
6973dcae
JH
2748 /*
2749 * we do not run diff between different kind
2750 * of objects.
2751 */
2752 if ((one->mode ^ two->mode) & S_IFMT)
2753 goto free_ab_and_return;
0c01857d 2754 if (complete_rewrite &&
3aa1f7ca
JK
2755 (textconv_one || !diff_filespec_is_binary(one)) &&
2756 (textconv_two || !diff_filespec_is_binary(two))) {
a29b0a13
SB
2757 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2758 header.buf, header.len, 0);
3e97c7c6 2759 strbuf_reset(&header);
3aa1f7ca
JK
2760 emit_rewrite_diff(name_a, name_b, one, two,
2761 textconv_one, textconv_two, o);
34a5e1a2 2762 o->found_changes = 1;
6973dcae
JH
2763 goto free_ab_and_return;
2764 }
2765 }
2766
467ddc14 2767 if (o->irreversible_delete && lbl[1][0] == '/') {
a29b0a13
SB
2768 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
2769 header.len, 0);
467ddc14
JH
2770 strbuf_reset(&header);
2771 goto free_ab_and_return;
2772 } else if (!DIFF_OPT_TST(o, TEXT) &&
b3373982
JK
2773 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2774 (!textconv_two && diff_filespec_is_binary(two)) )) {
4acaaa7a 2775 struct strbuf sb = STRBUF_INIT;
1aaf69e6
NTND
2776 if (!one->data && !two->data &&
2777 S_ISREG(one->mode) && S_ISREG(two->mode) &&
2778 !DIFF_OPT_TST(o, BINARY)) {
a0d12c44 2779 if (!oidcmp(&one->oid, &two->oid)) {
1aaf69e6 2780 if (must_show_header)
a29b0a13
SB
2781 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2782 header.buf, header.len,
2783 0);
1aaf69e6
NTND
2784 goto free_ab_and_return;
2785 }
a29b0a13
SB
2786 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2787 header.buf, header.len, 0);
4acaaa7a
SB
2788 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
2789 diff_line_prefix(o), lbl[0], lbl[1]);
2790 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
2791 sb.buf, sb.len, 0);
2792 strbuf_release(&sb);
1aaf69e6
NTND
2793 goto free_ab_and_return;
2794 }
b3373982
JK
2795 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2796 die("unable to read files to diff");
0660626c
JH
2797 /* Quite common confusing case */
2798 if (mf1.size == mf2.size &&
296c6bb2
CC
2799 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2800 if (must_show_header)
a29b0a13
SB
2801 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2802 header.buf, header.len, 0);
0660626c 2803 goto free_ab_and_return;
296c6bb2 2804 }
a29b0a13 2805 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3e97c7c6 2806 strbuf_reset(&header);
8f67f8ae 2807 if (DIFF_OPT_TST(o, BINARY))
4eed0ebd 2808 emit_binary_diff(o, &mf1, &mf2);
4acaaa7a
SB
2809 else {
2810 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
2811 diff_line_prefix(o), lbl[0], lbl[1]);
2812 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
2813 sb.buf, sb.len, 0);
2814 strbuf_release(&sb);
2815 }
34a5e1a2 2816 o->found_changes = 1;
467ddc14 2817 } else {
6973dcae
JH
2818 /* Crazy xdl interfaces.. */
2819 const char *diffopts = getenv("GIT_DIFF_OPTS");
ae021d87 2820 const char *v;
6973dcae
JH
2821 xpparam_t xpp;
2822 xdemitconf_t xecfg;
6973dcae 2823 struct emit_callback ecbdata;
be58e70d 2824 const struct userdiff_funcname *pe;
f258475a 2825
b3f01ff2 2826 if (must_show_header) {
a29b0a13
SB
2827 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2828 header.buf, header.len, 0);
3e97c7c6
GB
2829 strbuf_reset(&header);
2830 }
2831
840383b2
JK
2832 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2833 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
04427ac8 2834
45e7ca0f
BC
2835 pe = diff_funcname_pattern(one);
2836 if (!pe)
2837 pe = diff_funcname_pattern(two);
6973dcae 2838
9ccd0a88 2839 memset(&xpp, 0, sizeof(xpp));
30b25010 2840 memset(&xecfg, 0, sizeof(xecfg));
cd112cef 2841 memset(&ecbdata, 0, sizeof(ecbdata));
6973dcae 2842 ecbdata.label_path = lbl;
daa0c3d9 2843 ecbdata.color_diff = want_color(o->use_color);
c189c4f2 2844 ecbdata.ws_rule = whitespace_rule(name_b);
690ed843 2845 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
d68fe26f 2846 check_blank_at_eof(&mf1, &mf2, &ecbdata);
a3c158d4 2847 ecbdata.opt = o;
3e97c7c6 2848 ecbdata.header = header.len ? &header : NULL;
582aa00b 2849 xpp.flags = o->xdl_opts;
ee1e5412 2850 xecfg.ctxlen = o->context;
6d0e674a 2851 xecfg.interhunkctxlen = o->interhunkcontext;
6973dcae 2852 xecfg.flags = XDL_EMIT_FUNCNAMES;
14937c2c
RS
2853 if (DIFF_OPT_TST(o, FUNCCONTEXT))
2854 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
45e7ca0f 2855 if (pe)
a013585b 2856 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
6973dcae
JH
2857 if (!diffopts)
2858 ;
ae021d87
JK
2859 else if (skip_prefix(diffopts, "--unified=", &v))
2860 xecfg.ctxlen = strtoul(v, NULL, 10);
2861 else if (skip_prefix(diffopts, "-u", &v))
2862 xecfg.ctxlen = strtoul(v, NULL, 10);
77d1a520
TR
2863 if (o->word_diff)
2864 init_diff_words_data(&ecbdata, o, one, two);
3efb9880
JK
2865 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2866 &xpp, &xecfg))
2867 die("unable to generate diff for %s", one->path);
882749a0 2868 if (o->word_diff)
f59a59e2 2869 free_diff_words_data(&ecbdata);
04427ac8
JK
2870 if (textconv_one)
2871 free(mf1.ptr);
2872 if (textconv_two)
2873 free(mf2.ptr);
8cfe5f1c 2874 xdiff_clear_find_func(&xecfg);
6973dcae
JH
2875 }
2876
2877 free_ab_and_return:
3e97c7c6 2878 strbuf_release(&header);
fc3abdf5
JH
2879 diff_free_filespec_data(one);
2880 diff_free_filespec_data(two);
6973dcae
JH
2881 free(a_one);
2882 free(b_two);
2883 return;
2884}
2885
2886static void builtin_diffstat(const char *name_a, const char *name_b,
2887 struct diff_filespec *one,
2888 struct diff_filespec *two,
710158e3 2889 struct diffstat_t *diffstat,
0d21efa5 2890 struct diff_options *o,
74faaa16 2891 struct diff_filepair *p)
6973dcae
JH
2892{
2893 mmfile_t mf1, mf2;
2894 struct diffstat_file *data;
352ca4e1 2895 int same_contents;
74faaa16
LT
2896 int complete_rewrite = 0;
2897
2898 if (!DIFF_PAIR_UNMERGED(p)) {
2899 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2900 complete_rewrite = 1;
2901 }
6973dcae
JH
2902
2903 data = diffstat_add(diffstat, name_a, name_b);
99bfd407 2904 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
6973dcae
JH
2905
2906 if (!one || !two) {
2907 data->is_unmerged = 1;
2908 return;
2909 }
ded0abc7 2910
a0d12c44 2911 same_contents = !oidcmp(&one->oid, &two->oid);
352ca4e1 2912
ded0abc7 2913 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
ded0abc7 2914 data->is_binary = 1;
352ca4e1 2915 if (same_contents) {
e18872b2
ZJS
2916 data->added = 0;
2917 data->deleted = 0;
2918 } else {
2919 data->added = diff_filespec_size(two);
2920 data->deleted = diff_filespec_size(one);
2921 }
ded0abc7
JK
2922 }
2923
2924 else if (complete_rewrite) {
710158e3
JH
2925 diff_populate_filespec(one, 0);
2926 diff_populate_filespec(two, 0);
2927 data->deleted = count_lines(one->data, one->size);
2928 data->added = count_lines(two->data, two->size);
710158e3 2929 }
6973dcae 2930
352ca4e1 2931 else if (!same_contents) {
6973dcae
JH
2932 /* Crazy xdl interfaces.. */
2933 xpparam_t xpp;
2934 xdemitconf_t xecfg;
6973dcae 2935
ded0abc7
JK
2936 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2937 die("unable to read files to diff");
2938
9ccd0a88 2939 memset(&xpp, 0, sizeof(xpp));
30b25010 2940 memset(&xecfg, 0, sizeof(xecfg));
582aa00b 2941 xpp.flags = o->xdl_opts;
f01cae91
JH
2942 xecfg.ctxlen = o->context;
2943 xecfg.interhunkctxlen = o->interhunkcontext;
3efb9880
JK
2944 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2945 &xpp, &xecfg))
2946 die("unable to generate diffstat for %s", one->path);
6973dcae 2947 }
fc3abdf5 2948
fc3abdf5
JH
2949 diff_free_filespec_data(one);
2950 diff_free_filespec_data(two);
6973dcae
JH
2951}
2952
88246898 2953static void builtin_checkdiff(const char *name_a, const char *name_b,
cd676a51 2954 const char *attr_path,
5ff10dd6
JH
2955 struct diff_filespec *one,
2956 struct diff_filespec *two,
2957 struct diff_options *o)
88246898
JS
2958{
2959 mmfile_t mf1, mf2;
2960 struct checkdiff_t data;
2961
2962 if (!two)
2963 return;
2964
2965 memset(&data, 0, sizeof(data));
88246898
JS
2966 data.filename = name_b ? name_b : name_a;
2967 data.lineno = 0;
1ba111d1 2968 data.o = o;
cd676a51 2969 data.ws_rule = whitespace_rule(attr_path);
a757c646 2970 data.conflict_marker_size = ll_merge_marker_size(attr_path);
88246898
JS
2971
2972 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2973 die("unable to read files to diff");
2974
5ff10dd6
JH
2975 /*
2976 * All the other codepaths check both sides, but not checking
2977 * the "old" side here is deliberate. We are checking the newly
2978 * introduced changes, and as long as the "new" side is text, we
2979 * can and should check what it introduces.
2980 */
29a3eefd 2981 if (diff_filespec_is_binary(two))
fc3abdf5 2982 goto free_and_return;
88246898
JS
2983 else {
2984 /* Crazy xdl interfaces.. */
2985 xpparam_t xpp;
2986 xdemitconf_t xecfg;
88246898 2987
9ccd0a88 2988 memset(&xpp, 0, sizeof(xpp));
30b25010 2989 memset(&xecfg, 0, sizeof(xecfg));
c35539eb 2990 xecfg.ctxlen = 1; /* at least one context line */
582aa00b 2991 xpp.flags = 0;
3efb9880
JK
2992 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2993 &xpp, &xecfg))
2994 die("unable to generate checkdiff for %s", one->path);
877f23cc 2995
467babf8 2996 if (data.ws_rule & WS_BLANK_AT_EOF) {
d68fe26f
JH
2997 struct emit_callback ecbdata;
2998 int blank_at_eof;
2999
3000 ecbdata.ws_rule = data.ws_rule;
3001 check_blank_at_eof(&mf1, &mf2, &ecbdata);
8837d335 3002 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
d68fe26f 3003
467babf8
JH
3004 if (blank_at_eof) {
3005 static char *err;
3006 if (!err)
3007 err = whitespace_error_string(WS_BLANK_AT_EOF);
3008 fprintf(o->file, "%s:%d: %s.\n",
3009 data.filename, blank_at_eof, err);
3010 data.status = 1; /* report errors */
3011 }
877f23cc 3012 }
88246898 3013 }
fc3abdf5
JH
3014 free_and_return:
3015 diff_free_filespec_data(one);
3016 diff_free_filespec_data(two);
62c64895
WC
3017 if (data.status)
3018 DIFF_OPT_SET(o, CHECK_FAILED);
88246898
JS
3019}
3020
6973dcae
JH
3021struct diff_filespec *alloc_filespec(const char *path)
3022{
96ffc06f 3023 struct diff_filespec *spec;
6973dcae 3024
96ffc06f 3025 FLEXPTR_ALLOC_STR(spec, path, path);
9fb88419 3026 spec->count = 1;
122aa6f9 3027 spec->is_binary = -1;
6973dcae
JH
3028 return spec;
3029}
3030
9fb88419
LT
3031void free_filespec(struct diff_filespec *spec)
3032{
3033 if (!--spec->count) {
3034 diff_free_filespec_data(spec);
3035 free(spec);
3036 }
3037}
3038
f9704c2d
BW
3039void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3040 int oid_valid, unsigned short mode)
6973dcae
JH
3041{
3042 if (mode) {
3043 spec->mode = canon_mode(mode);
f9704c2d
BW
3044 oidcpy(&spec->oid, oid);
3045 spec->oid_valid = oid_valid;
6973dcae
JH
3046 }
3047}
3048
3049/*
5adf317b 3050 * Given a name and sha1 pair, if the index tells us the file in
6973dcae
JH
3051 * the work tree has that object contents, return true, so that
3052 * prepare_temp_file() does not have to inflate and extract.
3053 */
fb4a1c0d 3054static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
6973dcae 3055{
9c5e6c80 3056 const struct cache_entry *ce;
6973dcae
JH
3057 struct stat st;
3058 int pos, len;
3059
150115ad
JH
3060 /*
3061 * We do not read the cache ourselves here, because the
6973dcae
JH
3062 * benchmark with my previous version that always reads cache
3063 * shows that it makes things worse for diff-tree comparing
3064 * two linux-2.6 kernel trees in an already checked out work
3065 * tree. This is because most diff-tree comparisons deal with
3066 * only a small number of files, while reading the cache is
3067 * expensive for a large project, and its cost outweighs the
3068 * savings we get by not inflating the object to a temporary
3069 * file. Practically, this code only helps when we are used
3070 * by diff-cache --cached, which does read the cache before
3071 * calling us.
3072 */
3073 if (!active_cache)
3074 return 0;
3075
1510fea7
SP
3076 /* We want to avoid the working directory if our caller
3077 * doesn't need the data in a normal file, this system
3078 * is rather slow with its stat/open/mmap/close syscalls,
3079 * and the object is contained in a pack file. The pack
3080 * is probably already open and will be faster to obtain
3081 * the data through than the working directory. Loose
3082 * objects however would tend to be slower as they need
3083 * to be individually opened and inflated.
3084 */
fb4a1c0d 3085 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
1510fea7
SP
3086 return 0;
3087
06dec439
JK
3088 /*
3089 * Similarly, if we'd have to convert the file contents anyway, that
3090 * makes the optimization not worthwhile.
3091 */
82b474e0 3092 if (!want_file && would_convert_to_git(&the_index, name))
06dec439
JK
3093 return 0;
3094
6973dcae
JH
3095 len = strlen(name);
3096 pos = cache_name_pos(name, len);
3097 if (pos < 0)
3098 return 0;
3099 ce = active_cache[pos];
eadb5831
JH
3100
3101 /*
3102 * This is not the sha1 we are looking for, or
3103 * unreusable because it is not a regular file.
3104 */
fb4a1c0d 3105 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
6973dcae 3106 return 0;
eadb5831 3107
150115ad
JH
3108 /*
3109 * If ce is marked as "assume unchanged", there is no
3110 * guarantee that work tree matches what we are looking for.
3111 */
b4d1690d 3112 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
150115ad
JH
3113 return 0;
3114
eadb5831
JH
3115 /*
3116 * If ce matches the file in the work tree, we can reuse it.
6973dcae 3117 */
eadb5831
JH
3118 if (ce_uptodate(ce) ||
3119 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3120 return 1;
3121
3122 return 0;
6973dcae
JH
3123}
3124
04786756
LT
3125static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3126{
b1ddfb91
JK
3127 struct strbuf buf = STRBUF_INIT;
3128 char *dirty = "";
8e08b419
JH
3129
3130 /* Are we looking at the work tree? */
85adbf2f 3131 if (s->dirty_submodule)
8e08b419
JH
3132 dirty = "-dirty";
3133
a0d12c44 3134 strbuf_addf(&buf, "Subproject commit %s%s\n",
3135 oid_to_hex(&s->oid), dirty);
b1ddfb91 3136 s->size = buf.len;
04786756
LT
3137 if (size_only) {
3138 s->data = NULL;
b1ddfb91
JK
3139 strbuf_release(&buf);
3140 } else {
3141 s->data = strbuf_detach(&buf, NULL);
3142 s->should_free = 1;
04786756
LT
3143 }
3144 return 0;
3145}
3146
6973dcae
JH
3147/*
3148 * While doing rename detection and pickaxe operation, we may need to
3149 * grab the data for the blob (or file) for our own in-core comparison.
3150 * diff_filespec has data and size fields for this purpose.
3151 */
8e5dd3d6 3152int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
6973dcae 3153{
8e5dd3d6 3154 int size_only = flags & CHECK_SIZE_ONLY;
6973dcae 3155 int err = 0;
5430bb28
JH
3156 /*
3157 * demote FAIL to WARN to allow inspecting the situation
3158 * instead of refusing.
3159 */
3160 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
3161 ? SAFE_CRLF_WARN
3162 : safe_crlf);
3163
6973dcae
JH
3164 if (!DIFF_FILE_VALID(s))
3165 die("internal error: asking to populate invalid file.");
3166 if (S_ISDIR(s->mode))
3167 return -1;
3168
6973dcae 3169 if (s->data)
fc3abdf5 3170 return 0;
04786756 3171
6e0b8ed6
JH
3172 if (size_only && 0 < s->size)
3173 return 0;
3174
302b9282 3175 if (S_ISGITLINK(s->mode))
04786756
LT
3176 return diff_populate_gitlink(s, size_only);
3177
41c9560e 3178 if (!s->oid_valid ||
fb4a1c0d 3179 reuse_worktree_file(s->path, &s->oid, 0)) {
f285a2d7 3180 struct strbuf buf = STRBUF_INIT;
6973dcae
JH
3181 struct stat st;
3182 int fd;
6c510bee 3183
6973dcae
JH
3184 if (lstat(s->path, &st) < 0) {
3185 if (errno == ENOENT) {
3186 err_empty:
3187 err = -1;
3188 empty:
d2543b8e 3189 s->data = (char *)"";
6973dcae
JH
3190 s->size = 0;
3191 return err;
3192 }
3193 }
dc49cd76 3194 s->size = xsize_t(st.st_size);
6973dcae
JH
3195 if (!s->size)
3196 goto empty;
6973dcae 3197 if (S_ISLNK(st.st_mode)) {
cf219d8c
LT
3198 struct strbuf sb = STRBUF_INIT;
3199
3200 if (strbuf_readlink(&sb, s->path, s->size))
6973dcae 3201 goto err_empty;
0956a6db
RS
3202 s->size = sb.len;
3203 s->data = strbuf_detach(&sb, NULL);
cf219d8c 3204 s->should_free = 1;
6973dcae
JH
3205 return 0;
3206 }
12426e11
JH
3207
3208 /*
3209 * Even if the caller would be happy with getting
3210 * only the size, we cannot return early at this
3211 * point if the path requires us to run the content
3212 * conversion.
3213 */
82b474e0 3214 if (size_only && !would_convert_to_git(&the_index, s->path))
cf219d8c 3215 return 0;
12426e11
JH
3216
3217 /*
3218 * Note: this check uses xsize_t(st.st_size) that may
3219 * not be the true size of the blob after it goes
3220 * through convert_to_git(). This may not strictly be
3221 * correct, but the whole point of big_file_threshold
3222 * and is_binary check being that we want to avoid
3223 * opening the file and inspecting the contents, this
3224 * is probably fine.
3225 */
6bf3b813
NTND
3226 if ((flags & CHECK_BINARY) &&
3227 s->size > big_file_threshold && s->is_binary == -1) {
3228 s->is_binary = 1;
3229 return 0;
3230 }
6973dcae
JH
3231 fd = open(s->path, O_RDONLY);
3232 if (fd < 0)
3233 goto err_empty;
c4712e45 3234 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
6973dcae 3235 close(fd);
6973dcae 3236 s->should_munmap = 1;
6c510bee
LT
3237
3238 /*
3239 * Convert from working tree format to canonical git format
3240 */
82b474e0 3241 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, crlf_warn)) {
c32f749f 3242 size_t size = 0;
6c510bee
LT
3243 munmap(s->data, s->size);
3244 s->should_munmap = 0;
c32f749f
RS
3245 s->data = strbuf_detach(&buf, &size);
3246 s->size = size;
6c510bee
LT
3247 s->should_free = 1;
3248 }
6973dcae
JH
3249 }
3250 else {
21666f1a 3251 enum object_type type;
6bf3b813 3252 if (size_only || (flags & CHECK_BINARY)) {
a0d12c44 3253 type = sha1_object_info(s->oid.hash, &s->size);
c50c4316 3254 if (type < 0)
a0d12c44 3255 die("unable to read %s",
3256 oid_to_hex(&s->oid));
6bf3b813
NTND
3257 if (size_only)
3258 return 0;
3259 if (s->size > big_file_threshold && s->is_binary == -1) {
3260 s->is_binary = 1;
3261 return 0;
3262 }
6973dcae 3263 }
a0d12c44 3264 s->data = read_sha1_file(s->oid.hash, &type, &s->size);
6bf3b813 3265 if (!s->data)
a0d12c44 3266 die("unable to read %s", oid_to_hex(&s->oid));
6bf3b813 3267 s->should_free = 1;
6973dcae
JH
3268 }
3269 return 0;
3270}
3271
8ae92e63 3272void diff_free_filespec_blob(struct diff_filespec *s)
6973dcae
JH
3273{
3274 if (s->should_free)
3275 free(s->data);
3276 else if (s->should_munmap)
3277 munmap(s->data, s->size);
fc3abdf5
JH
3278
3279 if (s->should_free || s->should_munmap) {
3280 s->should_free = s->should_munmap = 0;
3281 s->data = NULL;
3282 }
eede7b7d
JK
3283}
3284
3285void diff_free_filespec_data(struct diff_filespec *s)
3286{
8ae92e63 3287 diff_free_filespec_blob(s);
6a83d902 3288 FREE_AND_NULL(s->cnt_data);
6973dcae
JH
3289}
3290
4e218f54 3291static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
6973dcae
JH
3292 void *blob,
3293 unsigned long size,
09bdff29 3294 const struct object_id *oid,
6973dcae
JH
3295 int mode)
3296{
3297 int fd;
4e218f54 3298 struct strbuf buf = STRBUF_INIT;
003b33a8
DA
3299 struct strbuf template = STRBUF_INIT;
3300 char *path_dup = xstrdup(path);
3301 const char *base = basename(path_dup);
6973dcae 3302
003b33a8
DA
3303 /* Generate "XXXXXX_basename.ext" */
3304 strbuf_addstr(&template, "XXXXXX_");
3305 strbuf_addstr(&template, base);
3306
284098f1 3307 fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
6973dcae 3308 if (fd < 0)
d824cbba 3309 die_errno("unable to create temp-file");
4e218f54
JS
3310 if (convert_to_working_tree(path,
3311 (const char *)blob, (size_t)size, &buf)) {
3312 blob = buf.buf;
3313 size = buf.len;
3314 }
93822c22 3315 if (write_in_full(fd, blob, size) != size)
0721c314 3316 die_errno("unable to write temp-file");
284098f1
MH
3317 close_tempfile(&temp->tempfile);
3318 temp->name = get_tempfile_path(&temp->tempfile);
09bdff29 3319 oid_to_hex_r(temp->hex, oid);
5096d490 3320 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4e218f54 3321 strbuf_release(&buf);
003b33a8
DA
3322 strbuf_release(&template);
3323 free(path_dup);
6973dcae
JH
3324}
3325
479b0ae8
JK
3326static struct diff_tempfile *prepare_temp_file(const char *name,
3327 struct diff_filespec *one)
6973dcae 3328{
479b0ae8
JK
3329 struct diff_tempfile *temp = claim_diff_tempfile();
3330
6973dcae
JH
3331 if (!DIFF_FILE_VALID(one)) {
3332 not_a_valid_file:
3333 /* A '-' entry produces this for file-2, and
3334 * a '+' entry produces this for file-1.
3335 */
3336 temp->name = "/dev/null";
5096d490
JK
3337 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3338 xsnprintf(temp->mode, sizeof(temp->mode), ".");
479b0ae8
JK
3339 return temp;
3340 }
3341
aba47272 3342 if (!S_ISGITLINK(one->mode) &&
41c9560e 3343 (!one->oid_valid ||
fb4a1c0d 3344 reuse_worktree_file(name, &one->oid, 1))) {
6973dcae
JH
3345 struct stat st;
3346 if (lstat(name, &st) < 0) {
3347 if (errno == ENOENT)
3348 goto not_a_valid_file;
d824cbba 3349 die_errno("stat(%s)", name);
6973dcae
JH
3350 }
3351 if (S_ISLNK(st.st_mode)) {
3cd7388d
JK
3352 struct strbuf sb = STRBUF_INIT;
3353 if (strbuf_readlink(&sb, name, st.st_size) < 0)
0721c314 3354 die_errno("readlink(%s)", name);
3cd7388d 3355 prep_temp_blob(name, temp, sb.buf, sb.len,
41c9560e 3356 (one->oid_valid ?
09bdff29 3357 &one->oid : &null_oid),
41c9560e 3358 (one->oid_valid ?
6973dcae 3359 one->mode : S_IFLNK));
3cd7388d 3360 strbuf_release(&sb);
6973dcae
JH
3361 }
3362 else {
3363 /* we can borrow from the file in the work tree */
3364 temp->name = name;
41c9560e 3365 if (!one->oid_valid)
74014152 3366 oid_to_hex_r(temp->hex, &null_oid);
6973dcae 3367 else
2490574d 3368 oid_to_hex_r(temp->hex, &one->oid);
6973dcae
JH
3369 /* Even though we may sometimes borrow the
3370 * contents from the work tree, we always want
3371 * one->mode. mode is trustworthy even when
74014152 3372 * !(one->oid_valid), as long as
6973dcae
JH
3373 * DIFF_FILE_VALID(one).
3374 */
5096d490 3375 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
6973dcae 3376 }
479b0ae8 3377 return temp;
6973dcae
JH
3378 }
3379 else {
3380 if (diff_populate_filespec(one, 0))
3381 die("cannot read data blob for %s", one->path);
4e218f54 3382 prep_temp_blob(name, temp, one->data, one->size,
09bdff29 3383 &one->oid, one->mode);
6973dcae 3384 }
479b0ae8 3385 return temp;
6973dcae
JH
3386}
3387
f3efe787
JK
3388static void add_external_diff_name(struct argv_array *argv,
3389 const char *name,
3390 struct diff_filespec *df)
3391{
3392 struct diff_tempfile *temp = prepare_temp_file(name, df);
3393 argv_array_push(argv, temp->name);
3394 argv_array_push(argv, temp->hex);
3395 argv_array_push(argv, temp->mode);
3396}
3397
6973dcae
JH
3398/* An external diff command takes:
3399 *
3400 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3401 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3402 *
3403 */
3404static void run_external_diff(const char *pgm,
3405 const char *name,
3406 const char *other,
3407 struct diff_filespec *one,
3408 struct diff_filespec *two,
3409 const char *xfrm_msg,
ee7fb0b1
ZK
3410 int complete_rewrite,
3411 struct diff_options *o)
6973dcae 3412{
82fbf269 3413 struct argv_array argv = ARGV_ARRAY_INIT;
ae049c95 3414 struct argv_array env = ARGV_ARRAY_INIT;
ee7fb0b1 3415 struct diff_queue_struct *q = &diff_queued_diff;
6973dcae 3416
0d4217d9
JK
3417 argv_array_push(&argv, pgm);
3418 argv_array_push(&argv, name);
6973dcae 3419
6973dcae 3420 if (one && two) {
f3efe787
JK
3421 add_external_diff_name(&argv, name, one);
3422 if (!other)
3423 add_external_diff_name(&argv, name, two);
3424 else {
3425 add_external_diff_name(&argv, other, two);
82fbf269
JK
3426 argv_array_push(&argv, other);
3427 argv_array_push(&argv, xfrm_msg);
6973dcae 3428 }
6973dcae 3429 }
ee7fb0b1 3430
ae049c95
JK
3431 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3432 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
ee7fb0b1 3433
89294d14
JK
3434 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3435 die(_("external diff died, stopping at %s"), name);
ee7fb0b1 3436
6973dcae 3437 remove_tempfile();
82fbf269 3438 argv_array_clear(&argv);
ae049c95 3439 argv_array_clear(&env);
6973dcae
JH
3440}
3441
b67b9612
JH
3442static int similarity_index(struct diff_filepair *p)
3443{
3444 return p->score * 100 / MAX_SCORE;
3445}
3446
4f03666a
JK
3447static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3448{
3449 if (startup_info->have_repository)
3450 return find_unique_abbrev(oid->hash, abbrev);
3451 else {
3452 char *hex = oid_to_hex(oid);
0d9c527d
JH
3453 if (abbrev < 0)
3454 abbrev = FALLBACK_DEFAULT_ABBREV;
3455 if (abbrev > GIT_SHA1_HEXSZ)
4f03666a 3456 die("BUG: oid abbreviation out of range: %d", abbrev);
43d1948b
JB
3457 if (abbrev)
3458 hex[abbrev] = '\0';
4f03666a
JK
3459 return hex;
3460 }
3461}
3462
b67b9612
JH
3463static void fill_metainfo(struct strbuf *msg,
3464 const char *name,
3465 const char *other,
3466 struct diff_filespec *one,
3467 struct diff_filespec *two,
3468 struct diff_options *o,
37466447 3469 struct diff_filepair *p,
5977744d 3470 int *must_show_header,
37466447 3471 int use_color)
b67b9612 3472{
37466447
BW
3473 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3474 const char *reset = diff_get_color(use_color, DIFF_RESET);
30997bb8 3475 const char *line_prefix = diff_line_prefix(o);
7be57610 3476
296c6bb2 3477 *must_show_header = 1;
b67b9612
JH
3478 strbuf_init(msg, PATH_MAX * 2 + 300);
3479 switch (p->status) {
3480 case DIFF_STATUS_COPIED:
98ad90fb
JH
3481 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3482 line_prefix, set, similarity_index(p));
3483 strbuf_addf(msg, "%s\n%s%scopy from ",
3484 reset, line_prefix, set);
b67b9612 3485 quote_c_style(name, msg, NULL, 0);
98ad90fb 3486 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
b67b9612 3487 quote_c_style(other, msg, NULL, 0);
37466447 3488 strbuf_addf(msg, "%s\n", reset);
b67b9612
JH
3489 break;
3490 case DIFF_STATUS_RENAMED:
98ad90fb
JH
3491 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3492 line_prefix, set, similarity_index(p));
3493 strbuf_addf(msg, "%s\n%s%srename from ",
3494 reset, line_prefix, set);
b67b9612 3495 quote_c_style(name, msg, NULL, 0);
98ad90fb
JH
3496 strbuf_addf(msg, "%s\n%s%srename to ",
3497 reset, line_prefix, set);
b67b9612 3498 quote_c_style(other, msg, NULL, 0);
37466447 3499 strbuf_addf(msg, "%s\n", reset);
b67b9612
JH
3500 break;
3501 case DIFF_STATUS_MODIFIED:
3502 if (p->score) {
98ad90fb
JH
3503 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3504 line_prefix,
37466447 3505 set, similarity_index(p), reset);
b67b9612
JH
3506 break;
3507 }
3508 /* fallthru */
3509 default:
296c6bb2 3510 *must_show_header = 0;
b67b9612 3511 }
a0d12c44 3512 if (one && two && oidcmp(&one->oid, &two->oid)) {
b67b9612
JH
3513 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3514
3515 if (DIFF_OPT_TST(o, BINARY)) {
3516 mmfile_t mf;
3517 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3518 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3519 abbrev = 40;
3520 }
4f03666a
JK
3521 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3522 diff_abbrev_oid(&one->oid, abbrev),
3523 diff_abbrev_oid(&two->oid, abbrev));
b67b9612
JH
3524 if (one->mode == two->mode)
3525 strbuf_addf(msg, " %06o", one->mode);
37466447 3526 strbuf_addf(msg, "%s\n", reset);
b67b9612 3527 }
b67b9612
JH
3528}
3529
6973dcae
JH
3530static void run_diff_cmd(const char *pgm,
3531 const char *name,
3532 const char *other,
cd676a51 3533 const char *attr_path,
6973dcae
JH
3534 struct diff_filespec *one,
3535 struct diff_filespec *two,
b67b9612 3536 struct strbuf *msg,
051308f6 3537 struct diff_options *o,
b67b9612