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