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