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