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