convert: check for detectable errors in UTF encodings
[git/git.git] / convert.c
CommitLineData
a33e0b2a 1#define NO_THE_INDEX_COMPATIBILITY_MACROS
6c510bee 2#include "cache.h"
b2141fc1 3#include "config.h"
35ebfd6a 4#include "attr.h"
3fed15f5 5#include "run-command.h"
a2b665de 6#include "quote.h"
6424c2ad 7#include "sigchain.h"
edcc8581 8#include "pkt-line.h"
99605d62 9#include "sub-process.h"
107642fe 10#include "utf8.h"
35ebfd6a 11
6c510bee
LT
12/*
13 * convert.c - convert a file when checking it out and checking it in.
14 *
15 * This should use the pathname to decide on whether it wants to do some
16 * more interesting conversions (automatic gzip/unzip, general format
17 * conversions etc etc), but by default it just does automatic CRLF<->LF
942e7747 18 * translation when the "text" attribute or "auto_crlf" option is set.
6c510bee
LT
19 */
20
a7630bd4
TB
21/* Stat bits: When BIN is set, the txt bits are unset */
22#define CONVERT_STAT_BITS_TXT_LF 0x1
23#define CONVERT_STAT_BITS_TXT_CRLF 0x2
24#define CONVERT_STAT_BITS_BIN 0x4
25
c61dcff9 26enum crlf_action {
df747b81
TB
27 CRLF_UNDEFINED,
28 CRLF_BINARY,
fd6cce9e 29 CRLF_TEXT,
df747b81
TB
30 CRLF_TEXT_INPUT,
31 CRLF_TEXT_CRLF,
32 CRLF_AUTO,
33 CRLF_AUTO_INPUT,
34 CRLF_AUTO_CRLF
fd6cce9e 35};
163b9591 36
6c510bee 37struct text_stat {
28624193 38 /* NUL, CR, LF and CRLF counts */
6e336a53 39 unsigned nul, lonecr, lonelf, crlf;
6c510bee
LT
40
41 /* These are just approximations! */
42 unsigned printable, nonprintable;
43};
44
45static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
46{
47 unsigned long i;
48
49 memset(stats, 0, sizeof(*stats));
50
51 for (i = 0; i < size; i++) {
52 unsigned char c = buf[i];
53 if (c == '\r') {
6e336a53 54 if (i+1 < size && buf[i+1] == '\n') {
6c510bee 55 stats->crlf++;
6e336a53
TB
56 i++;
57 } else
58 stats->lonecr++;
6c510bee
LT
59 continue;
60 }
61 if (c == '\n') {
6e336a53 62 stats->lonelf++;
6c510bee
LT
63 continue;
64 }
65 if (c == 127)
66 /* DEL */
67 stats->nonprintable++;
68 else if (c < 32) {
69 switch (c) {
70 /* BS, HT, ESC and FF */
71 case '\b': case '\t': case '\033': case '\014':
72 stats->printable++;
73 break;
28624193
DP
74 case 0:
75 stats->nul++;
76 /* fall through */
6c510bee
LT
77 default:
78 stats->nonprintable++;
79 }
80 }
81 else
82 stats->printable++;
83 }
f9dd4bf4
DK
84
85 /* If file ends with EOF then don't count this EOF as non-printable. */
86 if (size >= 1 && buf[size-1] == '\032')
87 stats->nonprintable--;
6c510bee
LT
88}
89
90/*
91 * The same heuristics as diff.c::mmfile_is_binary()
a7630bd4 92 * We treat files with bare CR as binary
6c510bee 93 */
a7630bd4 94static int convert_is_binary(unsigned long size, const struct text_stat *stats)
6c510bee 95{
6e336a53 96 if (stats->lonecr)
a7630bd4 97 return 1;
28624193
DP
98 if (stats->nul)
99 return 1;
6c510bee
LT
100 if ((stats->printable >> 7) < stats->nonprintable)
101 return 1;
6c510bee
LT
102 return 0;
103}
104
a7630bd4
TB
105static unsigned int gather_convert_stats(const char *data, unsigned long size)
106{
107 struct text_stat stats;
6e336a53 108 int ret = 0;
a7630bd4
TB
109 if (!data || !size)
110 return 0;
111 gather_stats(data, size, &stats);
112 if (convert_is_binary(size, &stats))
6e336a53
TB
113 ret |= CONVERT_STAT_BITS_BIN;
114 if (stats.crlf)
115 ret |= CONVERT_STAT_BITS_TXT_CRLF;
116 if (stats.lonelf)
117 ret |= CONVERT_STAT_BITS_TXT_LF;
118
119 return ret;
a7630bd4
TB
120}
121
122static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
123{
124 unsigned int convert_stats = gather_convert_stats(data, size);
125
126 if (convert_stats & CONVERT_STAT_BITS_BIN)
127 return "-text";
128 switch (convert_stats) {
129 case CONVERT_STAT_BITS_TXT_LF:
130 return "lf";
131 case CONVERT_STAT_BITS_TXT_CRLF:
132 return "crlf";
133 case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
134 return "mixed";
135 default:
136 return "none";
137 }
138}
139
a7609c54
BW
140const char *get_cached_convert_stats_ascii(const struct index_state *istate,
141 const char *path)
a7630bd4
TB
142{
143 const char *ret;
144 unsigned long sz;
a7609c54 145 void *data = read_blob_data_from_index(istate, path, &sz);
a7630bd4
TB
146 ret = gather_convert_stats_ascii(data, sz);
147 free(data);
148 return ret;
149}
150
151const char *get_wt_convert_stats_ascii(const char *path)
152{
153 const char *ret = "";
154 struct strbuf sb = STRBUF_INIT;
155 if (strbuf_read_file(&sb, path, 0) >= 0)
156 ret = gather_convert_stats_ascii(sb.buf, sb.len);
157 strbuf_release(&sb);
158 return ret;
159}
160
4b4024f5
TB
161static int text_eol_is_crlf(void)
162{
163 if (auto_crlf == AUTO_CRLF_TRUE)
164 return 1;
165 else if (auto_crlf == AUTO_CRLF_INPUT)
166 return 0;
167 if (core_eol == EOL_CRLF)
168 return 1;
169 if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
170 return 1;
171 return 0;
172}
173
c61dcff9 174static enum eol output_eol(enum crlf_action crlf_action)
f217f0e8 175{
c61dcff9 176 switch (crlf_action) {
942e7747
EB
177 case CRLF_BINARY:
178 return EOL_UNSET;
df747b81 179 case CRLF_TEXT_CRLF:
942e7747 180 return EOL_CRLF;
df747b81 181 case CRLF_TEXT_INPUT:
942e7747 182 return EOL_LF;
df747b81
TB
183 case CRLF_UNDEFINED:
184 case CRLF_AUTO_CRLF:
65237284 185 return EOL_CRLF;
df747b81 186 case CRLF_AUTO_INPUT:
65237284 187 return EOL_LF;
942e7747
EB
188 case CRLF_TEXT:
189 case CRLF_AUTO:
df747b81 190 /* fall through */
4b4024f5 191 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
942e7747 192 }
df747b81 193 warning("Illegal crlf_action %d\n", (int)crlf_action);
ec70f52f 194 return core_eol;
942e7747
EB
195}
196
8462ff43 197static void check_global_conv_flags_eol(const char *path, enum crlf_action crlf_action,
a0ad53c1 198 struct text_stat *old_stats, struct text_stat *new_stats,
8462ff43 199 int conv_flags)
21e5ad50 200{
a0ad53c1 201 if (old_stats->crlf && !new_stats->crlf ) {
21e5ad50 202 /*
a0ad53c1 203 * CRLFs would not be restored by checkout
21e5ad50 204 */
8462ff43
TB
205 if (conv_flags & CONV_EOL_RNDTRP_DIE)
206 die(_("CRLF would be replaced by LF in %s."), path);
207 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
87cb7845
VA
208 warning(_("CRLF will be replaced by LF in %s.\n"
209 "The file will have its original line"
210 " endings in your working directory."), path);
a0ad53c1 211 } else if (old_stats->lonelf && !new_stats->lonelf ) {
21e5ad50 212 /*
a0ad53c1 213 * CRLFs would be added by checkout
21e5ad50 214 */
8462ff43
TB
215 if (conv_flags & CONV_EOL_RNDTRP_DIE)
216 die(_("LF would be replaced by CRLF in %s"), path);
217 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
87cb7845
VA
218 warning(_("LF will be replaced by CRLF in %s.\n"
219 "The file will have its original line"
220 " endings in your working directory."), path);
21e5ad50
SP
221 }
222}
223
86ff70a0 224static int has_crlf_in_index(const struct index_state *istate, const char *path)
c4805393 225{
c4805393 226 unsigned long sz;
c4805393 227 void *data;
86ff70a0
TB
228 const char *crp;
229 int has_crlf = 0;
c4805393 230
49a6d31f 231 data = read_blob_data_from_index(istate, path, &sz);
4982fd78 232 if (!data)
c4805393 233 return 0;
86ff70a0
TB
234
235 crp = memchr(data, '\r', sz);
236 if (crp) {
237 unsigned int ret_stats;
238 ret_stats = gather_convert_stats(data, sz);
239 if (!(ret_stats & CONVERT_STAT_BITS_BIN) &&
240 (ret_stats & CONVERT_STAT_BITS_TXT_CRLF))
241 has_crlf = 1;
242 }
c4805393 243 free(data);
86ff70a0 244 return has_crlf;
c4805393
FAG
245}
246
a0ad53c1
TB
247static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats,
248 enum crlf_action crlf_action)
249{
250 if (output_eol(crlf_action) != EOL_CRLF)
251 return 0;
252 /* No "naked" LF? Nothing to convert, regardless. */
253 if (!stats->lonelf)
254 return 0;
255
256 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
257 /* If we have any CR or CRLF line endings, we do not touch it */
258 /* This is the new safer autocrlf-handling */
259 if (stats->lonecr || stats->crlf)
260 return 0;
261
262 if (convert_is_binary(len, stats))
263 return 0;
264 }
265 return 1;
266
267}
268
7a17918c
LS
269static int validate_encoding(const char *path, const char *enc,
270 const char *data, size_t len, int die_on_error)
271{
272 /* We only check for UTF here as UTF?? can be an alias for UTF-?? */
273 if (istarts_with(enc, "UTF")) {
274 /*
275 * Check for detectable errors in UTF encodings
276 */
277 if (has_prohibited_utf_bom(enc, data, len)) {
278 const char *error_msg = _(
279 "BOM is prohibited in '%s' if encoded as %s");
280 /*
281 * This advice is shown for UTF-??BE and UTF-??LE encodings.
282 * We cut off the last two characters of the encoding name
283 * to generate the encoding name suitable for BOMs.
284 */
285 const char *advise_msg = _(
286 "The file '%s' contains a byte order "
287 "mark (BOM). Please use UTF-%s as "
288 "working-tree-encoding.");
289 const char *stripped = NULL;
290 char *upper = xstrdup_toupper(enc);
291 upper[strlen(upper)-2] = '\0';
292 if (!skip_prefix(upper, "UTF-", &stripped))
293 skip_prefix(stripped, "UTF", &stripped);
294 advise(advise_msg, path, stripped);
295 free(upper);
296 if (die_on_error)
297 die(error_msg, path, enc);
298 else {
299 return error(error_msg, path, enc);
300 }
301
302 } else if (is_missing_required_utf_bom(enc, data, len)) {
303 const char *error_msg = _(
304 "BOM is required in '%s' if encoded as %s");
305 const char *advise_msg = _(
306 "The file '%s' is missing a byte order "
307 "mark (BOM). Please use UTF-%sBE or UTF-%sLE "
308 "(depending on the byte order) as "
309 "working-tree-encoding.");
310 const char *stripped = NULL;
311 char *upper = xstrdup_toupper(enc);
312 if (!skip_prefix(upper, "UTF-", &stripped))
313 skip_prefix(stripped, "UTF", &stripped);
314 advise(advise_msg, path, stripped, stripped);
315 free(upper);
316 if (die_on_error)
317 die(error_msg, path, enc);
318 else {
319 return error(error_msg, path, enc);
320 }
321 }
322
323 }
324 return 0;
325}
326
107642fe
LS
327static const char *default_encoding = "UTF-8";
328
329static int encode_to_git(const char *path, const char *src, size_t src_len,
330 struct strbuf *buf, const char *enc, int conv_flags)
331{
332 char *dst;
333 int dst_len;
334 int die_on_error = conv_flags & CONV_WRITE_OBJECT;
335
336 /*
337 * No encoding is specified or there is nothing to encode.
338 * Tell the caller that the content was not modified.
339 */
340 if (!enc || (src && !src_len))
341 return 0;
342
343 /*
344 * Looks like we got called from "would_convert_to_git()".
345 * This means Git wants to know if it would encode (= modify!)
346 * the content. Let's answer with "yes", since an encoding was
347 * specified.
348 */
349 if (!buf && !src)
350 return 1;
351
7a17918c
LS
352 if (validate_encoding(path, enc, src, src_len, die_on_error))
353 return 0;
354
107642fe
LS
355 dst = reencode_string_len(src, src_len, default_encoding, enc,
356 &dst_len);
357 if (!dst) {
358 /*
359 * We could add the blob "as-is" to Git. However, on checkout
360 * we would try to reencode to the original encoding. This
361 * would fail and we would leave the user with a messed-up
362 * working tree. Let's try to avoid this by screaming loud.
363 */
364 const char* msg = _("failed to encode '%s' from %s to %s");
365 if (die_on_error)
366 die(msg, path, enc, default_encoding);
367 else {
368 error(msg, path, enc, default_encoding);
369 return 0;
370 }
371 }
372
373 strbuf_attach(buf, dst, dst_len, dst_len + 1);
374 return 1;
375}
376
377static int encode_to_worktree(const char *path, const char *src, size_t src_len,
378 struct strbuf *buf, const char *enc)
379{
380 char *dst;
381 int dst_len;
382
383 /*
384 * No encoding is specified or there is nothing to encode.
385 * Tell the caller that the content was not modified.
386 */
387 if (!enc || (src && !src_len))
388 return 0;
389
390 dst = reencode_string_len(src, src_len, enc, default_encoding,
391 &dst_len);
392 if (!dst) {
393 error("failed to encode '%s' from %s to %s",
394 path, default_encoding, enc);
395 return 0;
396 }
397
398 strbuf_attach(buf, dst, dst_len, dst_len + 1);
399 return 1;
400}
401
49a6d31f
BW
402static int crlf_to_git(const struct index_state *istate,
403 const char *path, const char *src, size_t len,
c61dcff9 404 struct strbuf *buf,
8462ff43 405 enum crlf_action crlf_action, int conv_flags)
6c510bee 406{
6c510bee 407 struct text_stat stats;
5ecd293d 408 char *dst;
a0ad53c1 409 int convert_crlf_into_lf;
6c510bee 410
c61dcff9 411 if (crlf_action == CRLF_BINARY ||
4c3b57b9 412 (src && !len))
5ecd293d 413 return 0;
6c510bee 414
4c3b57b9
JK
415 /*
416 * If we are doing a dry-run and have no source buffer, there is
417 * nothing to analyze; we must assume we would convert.
418 */
419 if (!buf && !src)
420 return 1;
421
5ecd293d 422 gather_stats(src, len, &stats);
a0ad53c1
TB
423 /* Optimization: No CRLF? Nothing to convert, regardless. */
424 convert_crlf_into_lf = !!stats.crlf;
6c510bee 425
df747b81 426 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
a7630bd4 427 if (convert_is_binary(len, &stats))
5ecd293d 428 return 0;
65237284 429 /*
1c25d2d8
TB
430 * If the file in the index has any CR in it, do not
431 * convert. This is the new safer autocrlf handling,
432 * unless we want to renormalize in a merge or
433 * cherry-pick.
65237284 434 */
8462ff43 435 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
86ff70a0 436 has_crlf_in_index(istate, path))
a0ad53c1 437 convert_crlf_into_lf = 0;
201ac8ef 438 }
8462ff43
TB
439 if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
440 ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
a0ad53c1
TB
441 struct text_stat new_stats;
442 memcpy(&new_stats, &stats, sizeof(new_stats));
443 /* simulate "git add" */
444 if (convert_crlf_into_lf) {
445 new_stats.lonelf += new_stats.crlf;
446 new_stats.crlf = 0;
447 }
448 /* simulate "git checkout" */
449 if (will_convert_lf_to_crlf(len, &new_stats, crlf_action)) {
450 new_stats.crlf += new_stats.lonelf;
451 new_stats.lonelf = 0;
452 }
8462ff43 453 check_global_conv_flags_eol(path, crlf_action, &stats, &new_stats, conv_flags);
a0ad53c1
TB
454 }
455 if (!convert_crlf_into_lf)
21e5ad50
SP
456 return 0;
457
92ac3197
JK
458 /*
459 * At this point all of our source analysis is done, and we are sure we
460 * would convert. If we are in dry-run mode, we can give an answer.
461 */
462 if (!buf)
463 return 1;
464
90d16ec0
PH
465 /* only grow if not in place */
466 if (strbuf_avail(buf) + buf->len < len)
467 strbuf_grow(buf, len - buf->len);
5ecd293d 468 dst = buf->buf;
df747b81 469 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
163b9591
JH
470 /*
471 * If we guessed, we already know we rejected a file with
472 * lone CR, and we can strip a CR without looking at what
473 * follow it.
474 */
201ac8ef 475 do {
ac78e548 476 unsigned char c = *src++;
201ac8ef 477 if (c != '\r')
ac78e548 478 *dst++ = c;
5ecd293d 479 } while (--len);
201ac8ef
JH
480 } else {
481 do {
ac78e548 482 unsigned char c = *src++;
5ecd293d 483 if (! (c == '\r' && (1 < len && *src == '\n')))
ac78e548 484 *dst++ = c;
5ecd293d 485 } while (--len);
201ac8ef 486 }
5ecd293d
PH
487 strbuf_setlen(buf, dst - buf->buf);
488 return 1;
6c510bee
LT
489}
490
5ecd293d 491static int crlf_to_worktree(const char *path, const char *src, size_t len,
c61dcff9 492 struct strbuf *buf, enum crlf_action crlf_action)
6c510bee 493{
5ecd293d 494 char *to_free = NULL;
6c510bee 495 struct text_stat stats;
6c510bee 496
c61dcff9 497 if (!len || output_eol(crlf_action) != EOL_CRLF)
5ecd293d 498 return 0;
6c510bee 499
5ecd293d 500 gather_stats(src, len, &stats);
a0ad53c1 501 if (!will_convert_lf_to_crlf(len, &stats, crlf_action))
5ecd293d 502 return 0;
6c510bee 503
5ecd293d
PH
504 /* are we "faking" in place editing ? */
505 if (src == buf->buf)
b315c5c0 506 to_free = strbuf_detach(buf, NULL);
5ecd293d 507
6e336a53 508 strbuf_grow(buf, len + stats.lonelf);
5ecd293d
PH
509 for (;;) {
510 const char *nl = memchr(src, '\n', len);
511 if (!nl)
512 break;
513 if (nl > src && nl[-1] == '\r') {
514 strbuf_add(buf, src, nl + 1 - src);
515 } else {
516 strbuf_add(buf, src, nl - src);
517 strbuf_addstr(buf, "\r\n");
518 }
519 len -= nl + 1 - src;
520 src = nl + 1;
521 }
522 strbuf_add(buf, src, len);
523
524 free(to_free);
525 return 1;
6c510bee 526}
35ebfd6a 527
546bb582
JS
528struct filter_params {
529 const char *src;
530 unsigned long size;
9035d75a 531 int fd;
546bb582 532 const char *cmd;
a2b665de 533 const char *path;
546bb582
JS
534};
535
9035d75a 536static int filter_buffer_or_fd(int in, int out, void *data)
aa4ed402
JH
537{
538 /*
539 * Spawn cmd and feed the buffer contents through its stdin.
540 */
d3180279 541 struct child_process child_process = CHILD_PROCESS_INIT;
546bb582 542 struct filter_params *params = (struct filter_params *)data;
aa4ed402 543 int write_err, status;
66dbfd55
GV
544 const char *argv[] = { NULL, NULL };
545
a2b665de
PW
546 /* apply % substitution to cmd */
547 struct strbuf cmd = STRBUF_INIT;
548 struct strbuf path = STRBUF_INIT;
549 struct strbuf_expand_dict_entry dict[] = {
550 { "f", NULL, },
551 { NULL, NULL, },
552 };
553
554 /* quote the path to preserve spaces, etc. */
555 sq_quote_buf(&path, params->path);
556 dict[0].value = path.buf;
557
558 /* expand all %f with the quoted path */
559 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
560 strbuf_release(&path);
561
562 argv[0] = cmd.buf;
aa4ed402 563
dc1bfdcd 564 child_process.argv = argv;
ac0ba18d 565 child_process.use_shell = 1;
dc1bfdcd 566 child_process.in = -1;
ae6a5609 567 child_process.out = out;
aa4ed402 568
f31f1d39
RS
569 if (start_command(&child_process)) {
570 strbuf_release(&cmd);
255f04d6 571 return error("cannot fork to run external filter '%s'", params->cmd);
f31f1d39 572 }
aa4ed402 573
6424c2ad
JB
574 sigchain_push(SIGPIPE, SIG_IGN);
575
9035d75a 576 if (params->src) {
0c4dd67a
JH
577 write_err = (write_in_full(child_process.in,
578 params->src, params->size) < 0);
579 if (errno == EPIPE)
580 write_err = 0;
9035d75a
SP
581 } else {
582 write_err = copy_fd(params->fd, child_process.in);
0c4dd67a
JH
583 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
584 write_err = 0;
9035d75a
SP
585 }
586
dc1bfdcd 587 if (close(child_process.in))
aa4ed402
JH
588 write_err = 1;
589 if (write_err)
255f04d6 590 error("cannot feed the input to external filter '%s'", params->cmd);
aa4ed402 591
6424c2ad
JB
592 sigchain_pop(SIGPIPE);
593
aa4ed402
JH
594 status = finish_command(&child_process);
595 if (status)
255f04d6 596 error("external filter '%s' failed %d", params->cmd, status);
a2b665de
PW
597
598 strbuf_release(&cmd);
aa4ed402
JH
599 return (write_err || status);
600}
601
234fa07e 602static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
5ecd293d 603 struct strbuf *dst, const char *cmd)
aa4ed402
JH
604{
605 /*
606 * Create a pipeline to have the command filter the buffer's
607 * contents.
608 *
609 * (child --> cmd) --> us
610 */
b84be553 611 int err = 0;
f285a2d7 612 struct strbuf nbuf = STRBUF_INIT;
546bb582
JS
613 struct async async;
614 struct filter_params params;
aa4ed402 615
546bb582 616 memset(&async, 0, sizeof(async));
9035d75a 617 async.proc = filter_buffer_or_fd;
546bb582 618 async.data = &params;
ae6a5609 619 async.out = -1;
546bb582
JS
620 params.src = src;
621 params.size = len;
9035d75a 622 params.fd = fd;
546bb582 623 params.cmd = cmd;
a2b665de 624 params.path = path;
aa4ed402
JH
625
626 fflush(NULL);
546bb582
JS
627 if (start_async(&async))
628 return 0; /* error was already reported */
aa4ed402 629
546bb582 630 if (strbuf_read(&nbuf, async.out, len) < 0) {
b84be553 631 err = error("read from external filter '%s' failed", cmd);
aa4ed402 632 }
546bb582 633 if (close(async.out)) {
b84be553 634 err = error("read from external filter '%s' failed", cmd);
aa4ed402 635 }
546bb582 636 if (finish_async(&async)) {
b84be553 637 err = error("external filter '%s' failed", cmd);
aa4ed402
JH
638 }
639
b84be553 640 if (!err) {
90d16ec0 641 strbuf_swap(dst, &nbuf);
5ecd293d 642 }
90d16ec0 643 strbuf_release(&nbuf);
b84be553 644 return !err;
aa4ed402
JH
645}
646
234fa07e
LS
647#define CAP_CLEAN (1u<<0)
648#define CAP_SMUDGE (1u<<1)
2841e8f8 649#define CAP_DELAY (1u<<2)
234fa07e 650
1b0b46ee
BP
651struct cmd2process {
652 struct subprocess_entry subprocess; /* must be the first member! */
653 unsigned int supported_capabilities;
654};
655
f514d7d1
BP
656static int subprocess_map_initialized;
657static struct hashmap subprocess_map;
edcc8581 658
7ddb9b2c 659static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
edcc8581 660{
fa64a2fd
JT
661 static int versions[] = {2, 0};
662 static struct subprocess_capability capabilities[] = {
1514c8ed
LS
663 { "clean", CAP_CLEAN },
664 { "smudge", CAP_SMUDGE },
2841e8f8 665 { "delay", CAP_DELAY },
fa64a2fd 666 { NULL, 0 }
1514c8ed 667 };
fa64a2fd
JT
668 struct cmd2process *entry = (struct cmd2process *)subprocess;
669 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
670 capabilities,
671 &entry->supported_capabilities);
a810ea99
BP
672}
673
9364fc29
LS
674static void handle_filter_error(const struct strbuf *filter_status,
675 struct cmd2process *entry,
676 const unsigned int wanted_capability) {
677 if (!strcmp(filter_status->buf, "error"))
678 ; /* The filter signaled a problem with the file. */
679 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
680 /*
681 * The filter signaled a permanent problem. Don't try to filter
682 * files with the same command for the lifetime of the current
683 * Git process.
684 */
685 entry->supported_capabilities &= ~wanted_capability;
686 } else {
687 /*
688 * Something went wrong with the protocol filter.
689 * Force shutdown and restart if another blob requires filtering.
690 */
691 error("external filter '%s' failed", entry->subprocess.cmd);
692 subprocess_stop(&subprocess_map, &entry->subprocess);
693 free(entry);
694 }
695}
696
edcc8581
LS
697static int apply_multi_file_filter(const char *path, const char *src, size_t len,
698 int fd, struct strbuf *dst, const char *cmd,
2841e8f8
LS
699 const unsigned int wanted_capability,
700 struct delayed_checkout *dco)
edcc8581
LS
701{
702 int err;
2841e8f8 703 int can_delay = 0;
edcc8581
LS
704 struct cmd2process *entry;
705 struct child_process *process;
706 struct strbuf nbuf = STRBUF_INIT;
707 struct strbuf filter_status = STRBUF_INIT;
708 const char *filter_type;
709
f514d7d1
BP
710 if (!subprocess_map_initialized) {
711 subprocess_map_initialized = 1;
9ab42958 712 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
edcc8581
LS
713 entry = NULL;
714 } else {
f514d7d1 715 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
edcc8581
LS
716 }
717
718 fflush(NULL);
719
720 if (!entry) {
7ddb9b2c
BP
721 entry = xmalloc(sizeof(*entry));
722 entry->supported_capabilities = 0;
723
f514d7d1 724 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
7ddb9b2c 725 free(entry);
edcc8581 726 return 0;
7ddb9b2c 727 }
edcc8581 728 }
1b0b46ee 729 process = &entry->subprocess.process;
edcc8581 730
42b0a86c 731 if (!(entry->supported_capabilities & wanted_capability))
edcc8581
LS
732 return 0;
733
42b0a86c 734 if (wanted_capability & CAP_CLEAN)
edcc8581 735 filter_type = "clean";
42b0a86c 736 else if (wanted_capability & CAP_SMUDGE)
edcc8581
LS
737 filter_type = "smudge";
738 else
739 die("unexpected filter type");
740
741 sigchain_push(SIGPIPE, SIG_IGN);
742
743 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
744 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
745 if (err)
746 goto done;
747
748 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
749 if (err) {
750 error("path name too long for external filter");
751 goto done;
752 }
753
754 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
755 if (err)
756 goto done;
757
2841e8f8
LS
758 if ((entry->supported_capabilities & CAP_DELAY) &&
759 dco && dco->state == CE_CAN_DELAY) {
760 can_delay = 1;
761 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
762 if (err)
763 goto done;
764 }
765
edcc8581
LS
766 err = packet_flush_gently(process->in);
767 if (err)
768 goto done;
769
770 if (fd >= 0)
771 err = write_packetized_from_fd(fd, process->in);
772 else
773 err = write_packetized_from_buf(src, len, process->in);
774 if (err)
775 goto done;
776
4f2a2e9f
BP
777 err = subprocess_read_status(process->out, &filter_status);
778 if (err)
779 goto done;
780
2841e8f8
LS
781 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
782 string_list_insert(&dco->filters, cmd);
783 string_list_insert(&dco->paths, path);
784 } else {
785 /* The filter got the blob and wants to send us a response. */
786 err = strcmp(filter_status.buf, "success");
787 if (err)
788 goto done;
789
790 err = read_packetized_to_strbuf(process->out, &nbuf) < 0;
791 if (err)
792 goto done;
793
794 err = subprocess_read_status(process->out, &filter_status);
795 if (err)
796 goto done;
797
798 err = strcmp(filter_status.buf, "success");
799 }
800
801done:
802 sigchain_pop(SIGPIPE);
803
804 if (err)
805 handle_filter_error(&filter_status, entry, wanted_capability);
806 else
807 strbuf_swap(dst, &nbuf);
808 strbuf_release(&nbuf);
809 return !err;
810}
811
812
813int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
814{
815 int err;
816 char *line;
817 struct cmd2process *entry;
818 struct child_process *process;
819 struct strbuf filter_status = STRBUF_INIT;
820
821 assert(subprocess_map_initialized);
822 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
823 if (!entry) {
824 error("external filter '%s' is not available anymore although "
825 "not all paths have been filtered", cmd);
826 return 0;
827 }
828 process = &entry->subprocess.process;
829 sigchain_push(SIGPIPE, SIG_IGN);
830
831 err = packet_write_fmt_gently(
832 process->in, "command=list_available_blobs\n");
edcc8581
LS
833 if (err)
834 goto done;
835
2841e8f8 836 err = packet_flush_gently(process->in);
edcc8581
LS
837 if (err)
838 goto done;
839
2841e8f8
LS
840 while ((line = packet_read_line(process->out, NULL))) {
841 const char *path;
842 if (skip_prefix(line, "pathname=", &path))
843 string_list_insert(available_paths, xstrdup(path));
844 else
845 ; /* ignore unknown keys */
846 }
847
4f2a2e9f
BP
848 err = subprocess_read_status(process->out, &filter_status);
849 if (err)
850 goto done;
851
edcc8581
LS
852 err = strcmp(filter_status.buf, "success");
853
854done:
855 sigchain_pop(SIGPIPE);
856
9364fc29 857 if (err)
2841e8f8 858 handle_filter_error(&filter_status, entry, 0);
edcc8581 859 return !err;
aa4ed402
JH
860}
861
862static struct convert_driver {
863 const char *name;
864 struct convert_driver *next;
cd8be6c9
BH
865 const char *smudge;
866 const char *clean;
edcc8581 867 const char *process;
36daaaca 868 int required;
aa4ed402
JH
869} *user_convert, **user_convert_tail;
870
234fa07e
LS
871static int apply_filter(const char *path, const char *src, size_t len,
872 int fd, struct strbuf *dst, struct convert_driver *drv,
2841e8f8
LS
873 const unsigned int wanted_capability,
874 struct delayed_checkout *dco)
234fa07e
LS
875{
876 const char *cmd = NULL;
877
878 if (!drv)
879 return 0;
880
881 if (!dst)
882 return 1;
883
42b0a86c 884 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
234fa07e 885 cmd = drv->clean;
42b0a86c 886 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
234fa07e
LS
887 cmd = drv->smudge;
888
889 if (cmd && *cmd)
890 return apply_single_file_filter(path, src, len, fd, dst, cmd);
edcc8581 891 else if (drv->process && *drv->process)
2841e8f8
LS
892 return apply_multi_file_filter(path, src, len, fd, dst,
893 drv->process, wanted_capability, dco);
234fa07e
LS
894
895 return 0;
896}
897
ef90d6d4 898static int read_convert_config(const char *var, const char *value, void *cb)
aa4ed402 899{
d731f0ad 900 const char *key, *name;
aa4ed402
JH
901 int namelen;
902 struct convert_driver *drv;
903
904 /*
905 * External conversion drivers are configured using
906 * "filter.<name>.variable".
907 */
d731f0ad 908 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
aa4ed402 909 return 0;
aa4ed402
JH
910 for (drv = user_convert; drv; drv = drv->next)
911 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
912 break;
913 if (!drv) {
aa4ed402 914 drv = xcalloc(1, sizeof(struct convert_driver));
182af834 915 drv->name = xmemdupz(name, namelen);
aa4ed402
JH
916 *user_convert_tail = drv;
917 user_convert_tail = &(drv->next);
918 }
919
aa4ed402
JH
920 /*
921 * filter.<name>.smudge and filter.<name>.clean specifies
922 * the command line:
923 *
924 * command-line
925 *
926 * The command-line will not be interpolated in any way.
927 */
928
d731f0ad 929 if (!strcmp("smudge", key))
cd8be6c9
BH
930 return git_config_string(&drv->smudge, var, value);
931
d731f0ad 932 if (!strcmp("clean", key))
cd8be6c9 933 return git_config_string(&drv->clean, var, value);
aa4ed402 934
edcc8581
LS
935 if (!strcmp("process", key))
936 return git_config_string(&drv->process, var, value);
937
d731f0ad 938 if (!strcmp("required", key)) {
36daaaca
JB
939 drv->required = git_config_bool(var, value);
940 return 0;
941 }
942
aa4ed402
JH
943 return 0;
944}
945
3fed15f5
JH
946static int count_ident(const char *cp, unsigned long size)
947{
948 /*
af9b54bb 949 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
3fed15f5
JH
950 */
951 int cnt = 0;
952 char ch;
953
954 while (size) {
955 ch = *cp++;
956 size--;
957 if (ch != '$')
958 continue;
af9b54bb 959 if (size < 3)
3fed15f5 960 break;
af9b54bb 961 if (memcmp("Id", cp, 2))
3fed15f5 962 continue;
af9b54bb
AP
963 ch = cp[2];
964 cp += 3;
965 size -= 3;
3fed15f5 966 if (ch == '$')
af9b54bb 967 cnt++; /* $Id$ */
3fed15f5
JH
968 if (ch != ':')
969 continue;
970
971 /*
af9b54bb 972 * "$Id: ... "; scan up to the closing dollar sign and discard.
3fed15f5
JH
973 */
974 while (size) {
975 ch = *cp++;
976 size--;
977 if (ch == '$') {
978 cnt++;
979 break;
980 }
a9f3049f
HG
981 if (ch == '\n')
982 break;
3fed15f5
JH
983 }
984 }
985 return cnt;
986}
987
5ecd293d
PH
988static int ident_to_git(const char *path, const char *src, size_t len,
989 struct strbuf *buf, int ident)
3fed15f5 990{
5ecd293d 991 char *dst, *dollar;
3fed15f5 992
4c3b57b9 993 if (!ident || (src && !count_ident(src, len)))
5ecd293d
PH
994 return 0;
995
92ac3197
JK
996 if (!buf)
997 return 1;
998
90d16ec0
PH
999 /* only grow if not in place */
1000 if (strbuf_avail(buf) + buf->len < len)
1001 strbuf_grow(buf, len - buf->len);
5ecd293d
PH
1002 dst = buf->buf;
1003 for (;;) {
1004 dollar = memchr(src, '$', len);
1005 if (!dollar)
1006 break;
77321184 1007 memmove(dst, src, dollar + 1 - src);
5ecd293d
PH
1008 dst += dollar + 1 - src;
1009 len -= dollar + 1 - src;
1010 src = dollar + 1;
1011
1012 if (len > 3 && !memcmp(src, "Id:", 3)) {
1013 dollar = memchr(src + 3, '$', len - 3);
1014 if (!dollar)
1015 break;
a9f3049f
HG
1016 if (memchr(src + 3, '\n', dollar - src - 3)) {
1017 /* Line break before the next dollar. */
1018 continue;
1019 }
1020
af9b54bb
AP
1021 memcpy(dst, "Id$", 3);
1022 dst += 3;
5ecd293d
PH
1023 len -= dollar + 1 - src;
1024 src = dollar + 1;
3fed15f5
JH
1025 }
1026 }
77321184 1027 memmove(dst, src, len);
5ecd293d
PH
1028 strbuf_setlen(buf, dst + len - buf->buf);
1029 return 1;
3fed15f5
JH
1030}
1031
5ecd293d
PH
1032static int ident_to_worktree(const char *path, const char *src, size_t len,
1033 struct strbuf *buf, int ident)
3fed15f5 1034{
3fed15f5 1035 unsigned char sha1[20];
07814d90 1036 char *to_free = NULL, *dollar, *spc;
5ecd293d 1037 int cnt;
3fed15f5
JH
1038
1039 if (!ident)
5ecd293d 1040 return 0;
3fed15f5 1041
5ecd293d 1042 cnt = count_ident(src, len);
3fed15f5 1043 if (!cnt)
5ecd293d 1044 return 0;
3fed15f5 1045
5ecd293d
PH
1046 /* are we "faking" in place editing ? */
1047 if (src == buf->buf)
b315c5c0 1048 to_free = strbuf_detach(buf, NULL);
5ecd293d 1049 hash_sha1_file(src, len, "blob", sha1);
3fed15f5 1050
5ecd293d
PH
1051 strbuf_grow(buf, len + cnt * 43);
1052 for (;;) {
1053 /* step 1: run to the next '$' */
1054 dollar = memchr(src, '$', len);
1055 if (!dollar)
1056 break;
1057 strbuf_add(buf, src, dollar + 1 - src);
1058 len -= dollar + 1 - src;
1059 src = dollar + 1;
c23290d5 1060
5ecd293d
PH
1061 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1062 if (len < 3 || memcmp("Id", src, 2))
3fed15f5
JH
1063 continue;
1064
5ecd293d
PH
1065 /* step 3: skip over Id$ or Id:xxxxx$ */
1066 if (src[2] == '$') {
1067 src += 3;
1068 len -= 3;
1069 } else if (src[2] == ':') {
1070 /*
1071 * It's possible that an expanded Id has crept its way into the
07814d90
HG
1072 * repository, we cope with that by stripping the expansion out.
1073 * This is probably not a good idea, since it will cause changes
1074 * on checkout, which won't go away by stash, but let's keep it
1075 * for git-style ids.
5ecd293d
PH
1076 */
1077 dollar = memchr(src + 3, '$', len - 3);
1078 if (!dollar) {
1079 /* incomplete keyword, no more '$', so just quit the loop */
1080 break;
1081 }
c23290d5 1082
a9f3049f
HG
1083 if (memchr(src + 3, '\n', dollar - src - 3)) {
1084 /* Line break before the next dollar. */
1085 continue;
1086 }
1087
07814d90
HG
1088 spc = memchr(src + 4, ' ', dollar - src - 4);
1089 if (spc && spc < dollar-1) {
1090 /* There are spaces in unexpected places.
1091 * This is probably an id from some other
1092 * versioning system. Keep it for now.
1093 */
1094 continue;
1095 }
1096
5ecd293d
PH
1097 len -= dollar + 1 - src;
1098 src = dollar + 1;
1099 } else {
1100 /* it wasn't a "Id$" or "Id:xxxx$" */
1101 continue;
1102 }
c23290d5 1103
5ecd293d
PH
1104 /* step 4: substitute */
1105 strbuf_addstr(buf, "Id: ");
1106 strbuf_add(buf, sha1_to_hex(sha1), 40);
1107 strbuf_addstr(buf, " $");
3fed15f5 1108 }
5ecd293d 1109 strbuf_add(buf, src, len);
3fed15f5 1110
5ecd293d
PH
1111 free(to_free);
1112 return 1;
35ebfd6a
JH
1113}
1114
107642fe
LS
1115static const char *git_path_check_encoding(struct attr_check_item *check)
1116{
1117 const char *value = check->value;
1118
1119 if (ATTR_UNSET(value) || !strlen(value))
1120 return NULL;
1121
1122 if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
1123 die(_("true/false are no valid working-tree-encodings"));
1124 }
1125
1126 /* Don't encode to the default encoding */
1127 if (same_encoding(value, default_encoding))
1128 return NULL;
1129
1130 return value;
1131}
1132
7bd18054 1133static enum crlf_action git_path_check_crlf(struct attr_check_item *check)
35ebfd6a 1134{
6073ee85
JH
1135 const char *value = check->value;
1136
1137 if (ATTR_TRUE(value))
1138 return CRLF_TEXT;
1139 else if (ATTR_FALSE(value))
1140 return CRLF_BINARY;
1141 else if (ATTR_UNSET(value))
1142 ;
1143 else if (!strcmp(value, "input"))
df747b81 1144 return CRLF_TEXT_INPUT;
fd6cce9e
EB
1145 else if (!strcmp(value, "auto"))
1146 return CRLF_AUTO;
df747b81 1147 return CRLF_UNDEFINED;
35ebfd6a
JH
1148}
1149
7bd18054 1150static enum eol git_path_check_eol(struct attr_check_item *check)
fd6cce9e
EB
1151{
1152 const char *value = check->value;
1153
1154 if (ATTR_UNSET(value))
1155 ;
1156 else if (!strcmp(value, "lf"))
1157 return EOL_LF;
1158 else if (!strcmp(value, "crlf"))
1159 return EOL_CRLF;
1160 return EOL_UNSET;
1161}
1162
7bd18054 1163static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
aa4ed402
JH
1164{
1165 const char *value = check->value;
1166 struct convert_driver *drv;
1167
1168 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1169 return NULL;
1170 for (drv = user_convert; drv; drv = drv->next)
1171 if (!strcmp(value, drv->name))
1172 return drv;
1173 return NULL;
1174}
1175
7bd18054 1176static int git_path_check_ident(struct attr_check_item *check)
3fed15f5
JH
1177{
1178 const char *value = check->value;
1179
1180 return !!ATTR_TRUE(value);
1181}
1182
3bfba20d
JH
1183struct conv_attrs {
1184 struct convert_driver *drv;
bb211b4d
TB
1185 enum crlf_action attr_action; /* What attr says */
1186 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
3bfba20d 1187 int ident;
107642fe 1188 const char *working_tree_encoding; /* Supported encoding or default encoding if NULL */
3bfba20d
JH
1189};
1190
3bfba20d 1191static void convert_attrs(struct conv_attrs *ca, const char *path)
83295964 1192{
2aef63d3 1193 static struct attr_check *check;
83295964 1194
2aef63d3
JH
1195 if (!check) {
1196 check = attr_check_initl("crlf", "ident", "filter",
107642fe
LS
1197 "eol", "text", "working-tree-encoding",
1198 NULL);
83295964
JH
1199 user_convert_tail = &user_convert;
1200 git_config(read_convert_config, NULL);
1201 }
3bfba20d 1202
2aef63d3
JH
1203 if (!git_check_attr(path, check)) {
1204 struct attr_check_item *ccheck = check->items;
bb211b4d 1205 ca->crlf_action = git_path_check_crlf(ccheck + 4);
df747b81 1206 if (ca->crlf_action == CRLF_UNDEFINED)
92cce135
TB
1207 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1208 ca->ident = git_path_check_ident(ccheck + 1);
1209 ca->drv = git_path_check_convert(ccheck + 2);
817a0c79
TB
1210 if (ca->crlf_action != CRLF_BINARY) {
1211 enum eol eol_attr = git_path_check_eol(ccheck + 3);
65237284
TB
1212 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1213 ca->crlf_action = CRLF_AUTO_INPUT;
1214 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1215 ca->crlf_action = CRLF_AUTO_CRLF;
1216 else if (eol_attr == EOL_LF)
817a0c79
TB
1217 ca->crlf_action = CRLF_TEXT_INPUT;
1218 else if (eol_attr == EOL_CRLF)
1219 ca->crlf_action = CRLF_TEXT_CRLF;
1220 }
107642fe 1221 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
3bfba20d
JH
1222 } else {
1223 ca->drv = NULL;
df747b81 1224 ca->crlf_action = CRLF_UNDEFINED;
3bfba20d
JH
1225 ca->ident = 0;
1226 }
5c94c93d
1227
1228 /* Save attr and make a decision for action */
1229 ca->attr_action = ca->crlf_action;
df747b81
TB
1230 if (ca->crlf_action == CRLF_TEXT)
1231 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1232 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1233 ca->crlf_action = CRLF_BINARY;
1234 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1235 ca->crlf_action = CRLF_AUTO_CRLF;
1236 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1237 ca->crlf_action = CRLF_AUTO_INPUT;
83295964
JH
1238}
1239
9035d75a
SP
1240int would_convert_to_git_filter_fd(const char *path)
1241{
1242 struct conv_attrs ca;
1243
1244 convert_attrs(&ca, path);
1245 if (!ca.drv)
1246 return 0;
1247
1248 /*
1249 * Apply a filter to an fd only if the filter is required to succeed.
1250 * We must die if the filter fails, because the original data before
1251 * filtering is not available.
1252 */
1253 if (!ca.drv->required)
1254 return 0;
1255
2841e8f8 1256 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL);
9035d75a
SP
1257}
1258
a7630bd4
TB
1259const char *get_convert_attr_ascii(const char *path)
1260{
1261 struct conv_attrs ca;
a7630bd4
TB
1262
1263 convert_attrs(&ca, path);
bb211b4d 1264 switch (ca.attr_action) {
df747b81 1265 case CRLF_UNDEFINED:
a7630bd4
TB
1266 return "";
1267 case CRLF_BINARY:
1268 return "-text";
1269 case CRLF_TEXT:
1270 return "text";
df747b81 1271 case CRLF_TEXT_INPUT:
a7630bd4 1272 return "text eol=lf";
df747b81
TB
1273 case CRLF_TEXT_CRLF:
1274 return "text eol=crlf";
a7630bd4
TB
1275 case CRLF_AUTO:
1276 return "text=auto";
df747b81 1277 case CRLF_AUTO_CRLF:
65237284 1278 return "text=auto eol=crlf";
df747b81 1279 case CRLF_AUTO_INPUT:
65237284 1280 return "text=auto eol=lf";
a7630bd4
TB
1281 }
1282 return "";
1283}
1284
82b474e0
BW
1285int convert_to_git(const struct index_state *istate,
1286 const char *path, const char *src, size_t len,
8462ff43 1287 struct strbuf *dst, int conv_flags)
35ebfd6a 1288{
3bfba20d 1289 int ret = 0;
3bfba20d 1290 struct conv_attrs ca;
6073ee85 1291
3bfba20d 1292 convert_attrs(&ca, path);
3fed15f5 1293
2841e8f8 1294 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL);
234fa07e 1295 if (!ret && ca.drv && ca.drv->required)
36daaaca
JB
1296 die("%s: clean filter '%s' failed", path, ca.drv->name);
1297
92ac3197 1298 if (ret && dst) {
5ecd293d
PH
1299 src = dst->buf;
1300 len = dst->len;
aa4ed402 1301 }
107642fe
LS
1302
1303 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1304 if (ret && dst) {
1305 src = dst->buf;
1306 len = dst->len;
1307 }
1308
8462ff43
TB
1309 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1310 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
2fea9de6
TB
1311 if (ret && dst) {
1312 src = dst->buf;
1313 len = dst->len;
1314 }
6073ee85 1315 }
3bfba20d 1316 return ret | ident_to_git(path, src, len, dst, ca.ident);
35ebfd6a
JH
1317}
1318
d6c41c20
BW
1319void convert_to_git_filter_fd(const struct index_state *istate,
1320 const char *path, int fd, struct strbuf *dst,
8462ff43 1321 int conv_flags)
9035d75a
SP
1322{
1323 struct conv_attrs ca;
1324 convert_attrs(&ca, path);
1325
1326 assert(ca.drv);
edcc8581 1327 assert(ca.drv->clean || ca.drv->process);
9035d75a 1328
2841e8f8 1329 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL))
9035d75a
SP
1330 die("%s: clean filter '%s' failed", path, ca.drv->name);
1331
107642fe 1332 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
8462ff43 1333 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
9035d75a
SP
1334 ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
1335}
1336
43dd2332
EB
1337static int convert_to_working_tree_internal(const char *path, const char *src,
1338 size_t len, struct strbuf *dst,
2841e8f8 1339 int normalizing, struct delayed_checkout *dco)
35ebfd6a 1340{
36daaaca 1341 int ret = 0, ret_filter = 0;
3bfba20d 1342 struct conv_attrs ca;
6073ee85 1343
3bfba20d 1344 convert_attrs(&ca, path);
3fed15f5 1345
3bfba20d 1346 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
5ecd293d
PH
1347 if (ret) {
1348 src = dst->buf;
1349 len = dst->len;
3fed15f5 1350 }
43dd2332
EB
1351 /*
1352 * CRLF conversion can be skipped if normalizing, unless there
edcc8581
LS
1353 * is a smudge or process filter (even if the process filter doesn't
1354 * support smudge). The filters might expect CRLFs.
43dd2332 1355 */
edcc8581 1356 if ((ca.drv && (ca.drv->smudge || ca.drv->process)) || !normalizing) {
3bfba20d 1357 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
43dd2332
EB
1358 if (ret) {
1359 src = dst->buf;
1360 len = dst->len;
1361 }
aa4ed402 1362 }
36daaaca 1363
107642fe
LS
1364 ret |= encode_to_worktree(path, src, len, dst, ca.working_tree_encoding);
1365 if (ret) {
1366 src = dst->buf;
1367 len = dst->len;
1368 }
1369
2841e8f8
LS
1370 ret_filter = apply_filter(
1371 path, src, len, -1, dst, ca.drv, CAP_SMUDGE, dco);
234fa07e 1372 if (!ret_filter && ca.drv && ca.drv->required)
36daaaca
JB
1373 die("%s: smudge filter %s failed", path, ca.drv->name);
1374
1375 return ret | ret_filter;
35ebfd6a 1376}
f217f0e8 1377
2841e8f8
LS
1378int async_convert_to_working_tree(const char *path, const char *src,
1379 size_t len, struct strbuf *dst,
1380 void *dco)
1381{
1382 return convert_to_working_tree_internal(path, src, len, dst, 0, dco);
1383}
1384
43dd2332
EB
1385int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
1386{
2841e8f8 1387 return convert_to_working_tree_internal(path, src, len, dst, 0, NULL);
43dd2332
EB
1388}
1389
a33e0b2a
BW
1390int renormalize_buffer(const struct index_state *istate, const char *path,
1391 const char *src, size_t len, struct strbuf *dst)
f217f0e8 1392{
2841e8f8 1393 int ret = convert_to_working_tree_internal(path, src, len, dst, 1, NULL);
f217f0e8
EB
1394 if (ret) {
1395 src = dst->buf;
1396 len = dst->len;
1397 }
8462ff43 1398 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
f217f0e8 1399}
dd8e9121 1400
b6691092
JH
1401/*****************************************************************
1402 *
749f763d 1403 * Streaming conversion support
b6691092
JH
1404 *
1405 *****************************************************************/
1406
1407typedef int (*filter_fn)(struct stream_filter *,
1408 const char *input, size_t *isize_p,
1409 char *output, size_t *osize_p);
1410typedef void (*free_fn)(struct stream_filter *);
1411
1412struct stream_filter_vtbl {
1413 filter_fn filter;
1414 free_fn free;
1415};
1416
1417struct stream_filter {
1418 struct stream_filter_vtbl *vtbl;
1419};
1420
1421static int null_filter_fn(struct stream_filter *filter,
1422 const char *input, size_t *isize_p,
1423 char *output, size_t *osize_p)
1424{
4ae66704
JH
1425 size_t count;
1426
1427 if (!input)
1428 return 0; /* we do not keep any states */
1429 count = *isize_p;
b6691092
JH
1430 if (*osize_p < count)
1431 count = *osize_p;
1432 if (count) {
1433 memmove(output, input, count);
1434 *isize_p -= count;
1435 *osize_p -= count;
1436 }
1437 return 0;
1438}
1439
1440static void null_free_fn(struct stream_filter *filter)
1441{
1442 ; /* nothing -- null instances are shared */
1443}
1444
1445static struct stream_filter_vtbl null_vtbl = {
1446 null_filter_fn,
1447 null_free_fn,
1448};
1449
1450static struct stream_filter null_filter_singleton = {
1451 &null_vtbl,
1452};
1453
1454int is_null_stream_filter(struct stream_filter *filter)
1455{
1456 return filter == &null_filter_singleton;
1457}
1458
b84c7839
JH
1459
1460/*
1461 * LF-to-CRLF filter
1462 */
284e3d28
CMN
1463
1464struct lf_to_crlf_filter {
1465 struct stream_filter filter;
8496f568
JH
1466 unsigned has_held:1;
1467 char held;
284e3d28
CMN
1468};
1469
e322ee38
JH
1470static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1471 const char *input, size_t *isize_p,
1472 char *output, size_t *osize_p)
1473{
284e3d28
CMN
1474 size_t count, o = 0;
1475 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1476
8496f568
JH
1477 /*
1478 * We may be holding onto the CR to see if it is followed by a
1479 * LF, in which case we would need to go to the main loop.
1480 * Otherwise, just emit it to the output stream.
1481 */
1482 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1483 output[o++] = lf_to_crlf->held;
1484 lf_to_crlf->has_held = 0;
284e3d28 1485 }
e322ee38 1486
87afe9a5
JH
1487 /* We are told to drain */
1488 if (!input) {
1489 *osize_p -= o;
1490 return 0;
1491 }
e322ee38 1492
e322ee38 1493 count = *isize_p;
8496f568 1494 if (count || lf_to_crlf->has_held) {
284e3d28 1495 size_t i;
8496f568
JH
1496 int was_cr = 0;
1497
1498 if (lf_to_crlf->has_held) {
1499 was_cr = 1;
1500 lf_to_crlf->has_held = 0;
1501 }
1502
284e3d28 1503 for (i = 0; o < *osize_p && i < count; i++) {
e322ee38 1504 char ch = input[i];
8496f568 1505
e322ee38 1506 if (ch == '\n') {
284e3d28 1507 output[o++] = '\r';
8496f568
JH
1508 } else if (was_cr) {
1509 /*
1510 * Previous round saw CR and it is not followed
1511 * by a LF; emit the CR before processing the
1512 * current character.
1513 */
1514 output[o++] = '\r';
e322ee38 1515 }
8496f568
JH
1516
1517 /*
1518 * We may have consumed the last output slot,
1519 * in which case we need to break out of this
1520 * loop; hold the current character before
1521 * returning.
1522 */
1523 if (*osize_p <= o) {
1524 lf_to_crlf->has_held = 1;
1525 lf_to_crlf->held = ch;
1526 continue; /* break but increment i */
1527 }
1528
1529 if (ch == '\r') {
1530 was_cr = 1;
1531 continue;
1532 }
1533
1534 was_cr = 0;
e322ee38
JH
1535 output[o++] = ch;
1536 }
1537
1538 *osize_p -= o;
1539 *isize_p -= i;
8496f568
JH
1540
1541 if (!lf_to_crlf->has_held && was_cr) {
1542 lf_to_crlf->has_held = 1;
1543 lf_to_crlf->held = '\r';
1544 }
e322ee38
JH
1545 }
1546 return 0;
1547}
1548
284e3d28
CMN
1549static void lf_to_crlf_free_fn(struct stream_filter *filter)
1550{
1551 free(filter);
1552}
1553
e322ee38
JH
1554static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1555 lf_to_crlf_filter_fn,
284e3d28 1556 lf_to_crlf_free_fn,
e322ee38
JH
1557};
1558
284e3d28
CMN
1559static struct stream_filter *lf_to_crlf_filter(void)
1560{
87afe9a5 1561 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
e322ee38 1562
284e3d28 1563 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
284e3d28
CMN
1564 return (struct stream_filter *)lf_to_crlf;
1565}
b84c7839 1566
a265a7f9
JH
1567/*
1568 * Cascade filter
1569 */
1570#define FILTER_BUFFER 1024
1571struct cascade_filter {
1572 struct stream_filter filter;
1573 struct stream_filter *one;
1574 struct stream_filter *two;
1575 char buf[FILTER_BUFFER];
1576 int end, ptr;
1577};
1578
1579static int cascade_filter_fn(struct stream_filter *filter,
1580 const char *input, size_t *isize_p,
1581 char *output, size_t *osize_p)
1582{
1583 struct cascade_filter *cas = (struct cascade_filter *) filter;
1584 size_t filled = 0;
1585 size_t sz = *osize_p;
1586 size_t to_feed, remaining;
1587
1588 /*
1589 * input -- (one) --> buf -- (two) --> output
1590 */
1591 while (filled < sz) {
1592 remaining = sz - filled;
1593
1594 /* do we already have something to feed two with? */
1595 if (cas->ptr < cas->end) {
1596 to_feed = cas->end - cas->ptr;
1597 if (stream_filter(cas->two,
1598 cas->buf + cas->ptr, &to_feed,
1599 output + filled, &remaining))
1600 return -1;
1601 cas->ptr += (cas->end - cas->ptr) - to_feed;
1602 filled = sz - remaining;
1603 continue;
1604 }
1605
1606 /* feed one from upstream and have it emit into our buffer */
1607 to_feed = input ? *isize_p : 0;
1608 if (input && !to_feed)
1609 break;
1610 remaining = sizeof(cas->buf);
1611 if (stream_filter(cas->one,
1612 input, &to_feed,
1613 cas->buf, &remaining))
1614 return -1;
1615 cas->end = sizeof(cas->buf) - remaining;
1616 cas->ptr = 0;
1617 if (input) {
1618 size_t fed = *isize_p - to_feed;
1619 *isize_p -= fed;
1620 input += fed;
1621 }
1622
1623 /* do we know that we drained one completely? */
1624 if (input || cas->end)
1625 continue;
1626
1627 /* tell two to drain; we have nothing more to give it */
1628 to_feed = 0;
1629 remaining = sz - filled;
1630 if (stream_filter(cas->two,
1631 NULL, &to_feed,
1632 output + filled, &remaining))
1633 return -1;
1634 if (remaining == (sz - filled))
1635 break; /* completely drained two */
1636 filled = sz - remaining;
1637 }
1638 *osize_p -= filled;
1639 return 0;
1640}
1641
1642static void cascade_free_fn(struct stream_filter *filter)
1643{
1644 struct cascade_filter *cas = (struct cascade_filter *)filter;
1645 free_stream_filter(cas->one);
1646 free_stream_filter(cas->two);
1647 free(filter);
1648}
1649
1650static struct stream_filter_vtbl cascade_vtbl = {
1651 cascade_filter_fn,
1652 cascade_free_fn,
1653};
1654
1655static struct stream_filter *cascade_filter(struct stream_filter *one,
1656 struct stream_filter *two)
1657{
1658 struct cascade_filter *cascade;
1659
1660 if (!one || is_null_stream_filter(one))
1661 return two;
1662 if (!two || is_null_stream_filter(two))
1663 return one;
1664
1665 cascade = xmalloc(sizeof(*cascade));
1666 cascade->one = one;
1667 cascade->two = two;
1668 cascade->end = cascade->ptr = 0;
1669 cascade->filter.vtbl = &cascade_vtbl;
1670 return (struct stream_filter *)cascade;
1671}
1672
b84c7839
JH
1673/*
1674 * ident filter
1675 */
1676#define IDENT_DRAINING (-1)
1677#define IDENT_SKIPPING (-2)
1678struct ident_filter {
1679 struct stream_filter filter;
1680 struct strbuf left;
1681 int state;
1682 char ident[45]; /* ": x40 $" */
1683};
1684
1685static int is_foreign_ident(const char *str)
1686{
1687 int i;
1688
ae021d87 1689 if (!skip_prefix(str, "$Id: ", &str))
b84c7839 1690 return 0;
ae021d87 1691 for (i = 0; str[i]; i++) {
b84c7839
JH
1692 if (isspace(str[i]) && str[i+1] != '$')
1693 return 1;
1694 }
1695 return 0;
1696}
1697
1698static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1699{
1700 size_t to_drain = ident->left.len;
1701
1702 if (*osize_p < to_drain)
1703 to_drain = *osize_p;
1704 if (to_drain) {
1705 memcpy(*output_p, ident->left.buf, to_drain);
1706 strbuf_remove(&ident->left, 0, to_drain);
1707 *output_p += to_drain;
1708 *osize_p -= to_drain;
1709 }
1710 if (!ident->left.len)
1711 ident->state = 0;
1712}
1713
1714static int ident_filter_fn(struct stream_filter *filter,
1715 const char *input, size_t *isize_p,
1716 char *output, size_t *osize_p)
1717{
1718 struct ident_filter *ident = (struct ident_filter *)filter;
1719 static const char head[] = "$Id";
1720
1721 if (!input) {
1722 /* drain upon eof */
1723 switch (ident->state) {
1724 default:
1725 strbuf_add(&ident->left, head, ident->state);
1cf01a34 1726 /* fallthrough */
b84c7839 1727 case IDENT_SKIPPING:
1cf01a34 1728 /* fallthrough */
b84c7839
JH
1729 case IDENT_DRAINING:
1730 ident_drain(ident, &output, osize_p);
1731 }
1732 return 0;
1733 }
1734
1735 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1736 int ch;
1737
1738 if (ident->state == IDENT_DRAINING) {
1739 ident_drain(ident, &output, osize_p);
1740 if (!*osize_p)
1741 break;
1742 continue;
1743 }
1744
1745 ch = *(input++);
1746 (*isize_p)--;
1747
1748 if (ident->state == IDENT_SKIPPING) {
1749 /*
1750 * Skipping until '$' or LF, but keeping them
1751 * in case it is a foreign ident.
1752 */
1753 strbuf_addch(&ident->left, ch);
1754 if (ch != '\n' && ch != '$')
1755 continue;
1756 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1757 strbuf_setlen(&ident->left, sizeof(head) - 1);
1758 strbuf_addstr(&ident->left, ident->ident);
1759 }
1760 ident->state = IDENT_DRAINING;
1761 continue;
1762 }
1763
1764 if (ident->state < sizeof(head) &&
1765 head[ident->state] == ch) {
1766 ident->state++;
1767 continue;
1768 }
1769
1770 if (ident->state)
1771 strbuf_add(&ident->left, head, ident->state);
1772 if (ident->state == sizeof(head) - 1) {
1773 if (ch != ':' && ch != '$') {
1774 strbuf_addch(&ident->left, ch);
1775 ident->state = 0;
1776 continue;
1777 }
1778
1779 if (ch == ':') {
1780 strbuf_addch(&ident->left, ch);
1781 ident->state = IDENT_SKIPPING;
1782 } else {
1783 strbuf_addstr(&ident->left, ident->ident);
1784 ident->state = IDENT_DRAINING;
1785 }
1786 continue;
1787 }
1788
1789 strbuf_addch(&ident->left, ch);
1790 ident->state = IDENT_DRAINING;
1791 }
1792 return 0;
1793}
1794
1795static void ident_free_fn(struct stream_filter *filter)
1796{
1797 struct ident_filter *ident = (struct ident_filter *)filter;
1798 strbuf_release(&ident->left);
1799 free(filter);
1800}
1801
1802static struct stream_filter_vtbl ident_vtbl = {
1803 ident_filter_fn,
1804 ident_free_fn,
1805};
1806
1807static struct stream_filter *ident_filter(const unsigned char *sha1)
1808{
1809 struct ident_filter *ident = xmalloc(sizeof(*ident));
1810
5096d490
JK
1811 xsnprintf(ident->ident, sizeof(ident->ident),
1812 ": %s $", sha1_to_hex(sha1));
b84c7839
JH
1813 strbuf_init(&ident->left, 0);
1814 ident->filter.vtbl = &ident_vtbl;
1815 ident->state = 0;
1816 return (struct stream_filter *)ident;
1817}
1818
dd8e9121 1819/*
b6691092
JH
1820 * Return an appropriately constructed filter for the path, or NULL if
1821 * the contents cannot be filtered without reading the whole thing
1822 * in-core.
1823 *
1824 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1825 * large binary blob you would want us not to slurp into the memory!
dd8e9121 1826 */
b6691092 1827struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
dd8e9121
JH
1828{
1829 struct conv_attrs ca;
b84c7839 1830 struct stream_filter *filter = NULL;
dd8e9121
JH
1831
1832 convert_attrs(&ca, path);
edcc8581 1833 if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
caa47adc
TB
1834 return NULL;
1835
107642fe
LS
1836 if (ca.working_tree_encoding)
1837 return NULL;
1838
caa47adc
TB
1839 if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1840 return NULL;
b84c7839
JH
1841
1842 if (ca.ident)
1843 filter = ident_filter(sha1);
dd8e9121 1844
caa47adc 1845 if (output_eol(ca.crlf_action) == EOL_CRLF)
284e3d28 1846 filter = cascade_filter(filter, lf_to_crlf_filter());
caa47adc
TB
1847 else
1848 filter = cascade_filter(filter, &null_filter_singleton);
e322ee38 1849
b84c7839 1850 return filter;
b6691092
JH
1851}
1852
1853void free_stream_filter(struct stream_filter *filter)
1854{
1855 filter->vtbl->free(filter);
1856}
1857
1858int stream_filter(struct stream_filter *filter,
1859 const char *input, size_t *isize_p,
1860 char *output, size_t *osize_p)
1861{
1862 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
dd8e9121 1863}