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