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