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