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