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