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