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