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