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