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