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