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