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