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