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