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