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