]> git.ipfire.org Git - thirdparty/git.git/blame - convert.c
The sixth batch
[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
8462ff43 198static void check_global_conv_flags_eol(const char *path, enum crlf_action crlf_action,
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 }
8462ff43 550 check_global_conv_flags_eol(path, crlf_action, &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
GV
641 const char *argv[] = { NULL, NULL };
642
a2b665de
PW
643 /* apply % substitution to cmd */
644 struct strbuf cmd = STRBUF_INIT;
645 struct strbuf path = STRBUF_INIT;
646 struct strbuf_expand_dict_entry dict[] = {
647 { "f", NULL, },
648 { NULL, NULL, },
649 };
650
651 /* quote the path to preserve spaces, etc. */
652 sq_quote_buf(&path, params->path);
653 dict[0].value = path.buf;
654
655 /* expand all %f with the quoted path */
656 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
657 strbuf_release(&path);
658
659 argv[0] = cmd.buf;
aa4ed402 660
dc1bfdcd 661 child_process.argv = argv;
ac0ba18d 662 child_process.use_shell = 1;
dc1bfdcd 663 child_process.in = -1;
ae6a5609 664 child_process.out = out;
aa4ed402 665
f31f1d39
RS
666 if (start_command(&child_process)) {
667 strbuf_release(&cmd);
d26a328e
NTND
668 return error(_("cannot fork to run external filter '%s'"),
669 params->cmd);
f31f1d39 670 }
aa4ed402 671
6424c2ad
JB
672 sigchain_push(SIGPIPE, SIG_IGN);
673
9035d75a 674 if (params->src) {
0c4dd67a
JH
675 write_err = (write_in_full(child_process.in,
676 params->src, params->size) < 0);
677 if (errno == EPIPE)
678 write_err = 0;
9035d75a
SP
679 } else {
680 write_err = copy_fd(params->fd, child_process.in);
0c4dd67a
JH
681 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
682 write_err = 0;
9035d75a
SP
683 }
684
dc1bfdcd 685 if (close(child_process.in))
aa4ed402
JH
686 write_err = 1;
687 if (write_err)
d26a328e
NTND
688 error(_("cannot feed the input to external filter '%s'"),
689 params->cmd);
aa4ed402 690
6424c2ad
JB
691 sigchain_pop(SIGPIPE);
692
aa4ed402
JH
693 status = finish_command(&child_process);
694 if (status)
d26a328e 695 error(_("external filter '%s' failed %d"), params->cmd, status);
a2b665de
PW
696
697 strbuf_release(&cmd);
aa4ed402
JH
698 return (write_err || status);
699}
700
234fa07e 701static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
ec36c42a 702 struct strbuf *dst, const char *cmd)
aa4ed402
JH
703{
704 /*
705 * Create a pipeline to have the command filter the buffer's
706 * contents.
707 *
708 * (child --> cmd) --> us
709 */
b84be553 710 int err = 0;
f285a2d7 711 struct strbuf nbuf = STRBUF_INIT;
546bb582
JS
712 struct async async;
713 struct filter_params params;
aa4ed402 714
546bb582 715 memset(&async, 0, sizeof(async));
9035d75a 716 async.proc = filter_buffer_or_fd;
546bb582 717 async.data = &params;
ae6a5609 718 async.out = -1;
546bb582
JS
719 params.src = src;
720 params.size = len;
9035d75a 721 params.fd = fd;
546bb582 722 params.cmd = cmd;
a2b665de 723 params.path = path;
aa4ed402
JH
724
725 fflush(NULL);
546bb582
JS
726 if (start_async(&async))
727 return 0; /* error was already reported */
aa4ed402 728
02156ab0 729 if (strbuf_read(&nbuf, async.out, 0) < 0) {
d26a328e 730 err = error(_("read from external filter '%s' failed"), cmd);
aa4ed402 731 }
546bb582 732 if (close(async.out)) {
d26a328e 733 err = error(_("read from external filter '%s' failed"), cmd);
aa4ed402 734 }
546bb582 735 if (finish_async(&async)) {
d26a328e 736 err = error(_("external filter '%s' failed"), cmd);
aa4ed402
JH
737 }
738
b84be553 739 if (!err) {
90d16ec0 740 strbuf_swap(dst, &nbuf);
5ecd293d 741 }
90d16ec0 742 strbuf_release(&nbuf);
b84be553 743 return !err;
aa4ed402
JH
744}
745
234fa07e
LS
746#define CAP_CLEAN (1u<<0)
747#define CAP_SMUDGE (1u<<1)
2841e8f8 748#define CAP_DELAY (1u<<2)
234fa07e 749
1b0b46ee
BP
750struct cmd2process {
751 struct subprocess_entry subprocess; /* must be the first member! */
752 unsigned int supported_capabilities;
753};
754
f514d7d1
BP
755static int subprocess_map_initialized;
756static struct hashmap subprocess_map;
edcc8581 757
7ddb9b2c 758static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
edcc8581 759{
fa64a2fd
JT
760 static int versions[] = {2, 0};
761 static struct subprocess_capability capabilities[] = {
1514c8ed
LS
762 { "clean", CAP_CLEAN },
763 { "smudge", CAP_SMUDGE },
2841e8f8 764 { "delay", CAP_DELAY },
fa64a2fd 765 { NULL, 0 }
1514c8ed 766 };
fa64a2fd
JT
767 struct cmd2process *entry = (struct cmd2process *)subprocess;
768 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
769 capabilities,
770 &entry->supported_capabilities);
a810ea99
BP
771}
772
9364fc29
LS
773static void handle_filter_error(const struct strbuf *filter_status,
774 struct cmd2process *entry,
3b335762
NTND
775 const unsigned int wanted_capability)
776{
9364fc29
LS
777 if (!strcmp(filter_status->buf, "error"))
778 ; /* The filter signaled a problem with the file. */
779 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
780 /*
781 * The filter signaled a permanent problem. Don't try to filter
782 * files with the same command for the lifetime of the current
783 * Git process.
784 */
785 entry->supported_capabilities &= ~wanted_capability;
786 } else {
787 /*
788 * Something went wrong with the protocol filter.
789 * Force shutdown and restart if another blob requires filtering.
790 */
d26a328e 791 error(_("external filter '%s' failed"), entry->subprocess.cmd);
9364fc29
LS
792 subprocess_stop(&subprocess_map, &entry->subprocess);
793 free(entry);
794 }
795}
796
edcc8581
LS
797static int apply_multi_file_filter(const char *path, const char *src, size_t len,
798 int fd, struct strbuf *dst, const char *cmd,
2841e8f8 799 const unsigned int wanted_capability,
ab90ecae 800 const struct checkout_metadata *meta,
2841e8f8 801 struct delayed_checkout *dco)
edcc8581
LS
802{
803 int err;
2841e8f8 804 int can_delay = 0;
edcc8581
LS
805 struct cmd2process *entry;
806 struct child_process *process;
807 struct strbuf nbuf = STRBUF_INIT;
808 struct strbuf filter_status = STRBUF_INIT;
809 const char *filter_type;
810
f514d7d1
BP
811 if (!subprocess_map_initialized) {
812 subprocess_map_initialized = 1;
9ab42958 813 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
edcc8581
LS
814 entry = NULL;
815 } else {
f514d7d1 816 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
edcc8581
LS
817 }
818
819 fflush(NULL);
820
821 if (!entry) {
7ddb9b2c
BP
822 entry = xmalloc(sizeof(*entry));
823 entry->supported_capabilities = 0;
824
f514d7d1 825 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
7ddb9b2c 826 free(entry);
edcc8581 827 return 0;
7ddb9b2c 828 }
edcc8581 829 }
1b0b46ee 830 process = &entry->subprocess.process;
edcc8581 831
42b0a86c 832 if (!(entry->supported_capabilities & wanted_capability))
edcc8581
LS
833 return 0;
834
42b0a86c 835 if (wanted_capability & CAP_CLEAN)
edcc8581 836 filter_type = "clean";
42b0a86c 837 else if (wanted_capability & CAP_SMUDGE)
edcc8581
LS
838 filter_type = "smudge";
839 else
d26a328e 840 die(_("unexpected filter type"));
edcc8581
LS
841
842 sigchain_push(SIGPIPE, SIG_IGN);
843
844 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
845 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
846 if (err)
847 goto done;
848
849 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
850 if (err) {
d26a328e 851 error(_("path name too long for external filter"));
edcc8581
LS
852 goto done;
853 }
854
855 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
856 if (err)
857 goto done;
858
ab90ecae 859 if (meta && meta->refname) {
860 err = packet_write_fmt_gently(process->in, "ref=%s\n", meta->refname);
861 if (err)
862 goto done;
863 }
864
865 if (meta && !is_null_oid(&meta->treeish)) {
866 err = packet_write_fmt_gently(process->in, "treeish=%s\n", oid_to_hex(&meta->treeish));
867 if (err)
868 goto done;
869 }
870
871 if (meta && !is_null_oid(&meta->blob)) {
872 err = packet_write_fmt_gently(process->in, "blob=%s\n", oid_to_hex(&meta->blob));
873 if (err)
874 goto done;
875 }
876
2841e8f8
LS
877 if ((entry->supported_capabilities & CAP_DELAY) &&
878 dco && dco->state == CE_CAN_DELAY) {
879 can_delay = 1;
880 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
881 if (err)
882 goto done;
883 }
884
edcc8581
LS
885 err = packet_flush_gently(process->in);
886 if (err)
887 goto done;
888
889 if (fd >= 0)
890 err = write_packetized_from_fd(fd, process->in);
891 else
892 err = write_packetized_from_buf(src, len, process->in);
893 if (err)
894 goto done;
895
4f2a2e9f
BP
896 err = subprocess_read_status(process->out, &filter_status);
897 if (err)
898 goto done;
899
2841e8f8
LS
900 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
901 string_list_insert(&dco->filters, cmd);
902 string_list_insert(&dco->paths, path);
903 } else {
904 /* The filter got the blob and wants to send us a response. */
905 err = strcmp(filter_status.buf, "success");
906 if (err)
907 goto done;
908
909 err = read_packetized_to_strbuf(process->out, &nbuf) < 0;
910 if (err)
911 goto done;
912
913 err = subprocess_read_status(process->out, &filter_status);
914 if (err)
915 goto done;
916
917 err = strcmp(filter_status.buf, "success");
918 }
919
920done:
921 sigchain_pop(SIGPIPE);
922
923 if (err)
924 handle_filter_error(&filter_status, entry, wanted_capability);
925 else
926 strbuf_swap(dst, &nbuf);
927 strbuf_release(&nbuf);
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);
edcc8581 978 return !err;
aa4ed402
JH
979}
980
981static struct convert_driver {
982 const char *name;
983 struct convert_driver *next;
cd8be6c9
BH
984 const char *smudge;
985 const char *clean;
edcc8581 986 const char *process;
36daaaca 987 int required;
aa4ed402
JH
988} *user_convert, **user_convert_tail;
989
234fa07e
LS
990static int apply_filter(const char *path, const char *src, size_t len,
991 int fd, struct strbuf *dst, struct convert_driver *drv,
2841e8f8 992 const unsigned int wanted_capability,
ab90ecae 993 const struct checkout_metadata *meta,
2841e8f8 994 struct delayed_checkout *dco)
234fa07e
LS
995{
996 const char *cmd = NULL;
997
998 if (!drv)
999 return 0;
1000
1001 if (!dst)
1002 return 1;
1003
42b0a86c 1004 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
234fa07e 1005 cmd = drv->clean;
42b0a86c 1006 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
234fa07e
LS
1007 cmd = drv->smudge;
1008
1009 if (cmd && *cmd)
1010 return apply_single_file_filter(path, src, len, fd, dst, cmd);
edcc8581 1011 else if (drv->process && *drv->process)
2841e8f8 1012 return apply_multi_file_filter(path, src, len, fd, dst,
ab90ecae 1013 drv->process, wanted_capability, meta, dco);
234fa07e
LS
1014
1015 return 0;
1016}
1017
ef90d6d4 1018static int read_convert_config(const char *var, const char *value, void *cb)
aa4ed402 1019{
d731f0ad 1020 const char *key, *name;
f5914f4b 1021 size_t namelen;
aa4ed402
JH
1022 struct convert_driver *drv;
1023
1024 /*
1025 * External conversion drivers are configured using
1026 * "filter.<name>.variable".
1027 */
d731f0ad 1028 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
aa4ed402 1029 return 0;
aa4ed402
JH
1030 for (drv = user_convert; drv; drv = drv->next)
1031 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
1032 break;
1033 if (!drv) {
aa4ed402 1034 drv = xcalloc(1, sizeof(struct convert_driver));
182af834 1035 drv->name = xmemdupz(name, namelen);
aa4ed402
JH
1036 *user_convert_tail = drv;
1037 user_convert_tail = &(drv->next);
1038 }
1039
aa4ed402
JH
1040 /*
1041 * filter.<name>.smudge and filter.<name>.clean specifies
1042 * the command line:
1043 *
1044 * command-line
1045 *
1046 * The command-line will not be interpolated in any way.
1047 */
1048
d731f0ad 1049 if (!strcmp("smudge", key))
cd8be6c9
BH
1050 return git_config_string(&drv->smudge, var, value);
1051
d731f0ad 1052 if (!strcmp("clean", key))
cd8be6c9 1053 return git_config_string(&drv->clean, var, value);
aa4ed402 1054
edcc8581
LS
1055 if (!strcmp("process", key))
1056 return git_config_string(&drv->process, var, value);
1057
d731f0ad 1058 if (!strcmp("required", key)) {
36daaaca
JB
1059 drv->required = git_config_bool(var, value);
1060 return 0;
1061 }
1062
aa4ed402
JH
1063 return 0;
1064}
1065
3fed15f5
JH
1066static int count_ident(const char *cp, unsigned long size)
1067{
1068 /*
af9b54bb 1069 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
3fed15f5
JH
1070 */
1071 int cnt = 0;
1072 char ch;
1073
1074 while (size) {
1075 ch = *cp++;
1076 size--;
1077 if (ch != '$')
1078 continue;
af9b54bb 1079 if (size < 3)
3fed15f5 1080 break;
af9b54bb 1081 if (memcmp("Id", cp, 2))
3fed15f5 1082 continue;
af9b54bb
AP
1083 ch = cp[2];
1084 cp += 3;
1085 size -= 3;
3fed15f5 1086 if (ch == '$')
af9b54bb 1087 cnt++; /* $Id$ */
3fed15f5
JH
1088 if (ch != ':')
1089 continue;
1090
1091 /*
af9b54bb 1092 * "$Id: ... "; scan up to the closing dollar sign and discard.
3fed15f5
JH
1093 */
1094 while (size) {
1095 ch = *cp++;
1096 size--;
1097 if (ch == '$') {
1098 cnt++;
1099 break;
1100 }
a9f3049f
HG
1101 if (ch == '\n')
1102 break;
3fed15f5
JH
1103 }
1104 }
1105 return cnt;
1106}
1107
55ad152c 1108static int ident_to_git(const char *src, size_t len,
ec36c42a 1109 struct strbuf *buf, int ident)
3fed15f5 1110{
5ecd293d 1111 char *dst, *dollar;
3fed15f5 1112
4c3b57b9 1113 if (!ident || (src && !count_ident(src, len)))
5ecd293d
PH
1114 return 0;
1115
92ac3197
JK
1116 if (!buf)
1117 return 1;
1118
90d16ec0
PH
1119 /* only grow if not in place */
1120 if (strbuf_avail(buf) + buf->len < len)
1121 strbuf_grow(buf, len - buf->len);
5ecd293d
PH
1122 dst = buf->buf;
1123 for (;;) {
1124 dollar = memchr(src, '$', len);
1125 if (!dollar)
1126 break;
77321184 1127 memmove(dst, src, dollar + 1 - src);
5ecd293d
PH
1128 dst += dollar + 1 - src;
1129 len -= dollar + 1 - src;
1130 src = dollar + 1;
1131
1132 if (len > 3 && !memcmp(src, "Id:", 3)) {
1133 dollar = memchr(src + 3, '$', len - 3);
1134 if (!dollar)
1135 break;
a9f3049f
HG
1136 if (memchr(src + 3, '\n', dollar - src - 3)) {
1137 /* Line break before the next dollar. */
1138 continue;
1139 }
1140
af9b54bb
AP
1141 memcpy(dst, "Id$", 3);
1142 dst += 3;
5ecd293d
PH
1143 len -= dollar + 1 - src;
1144 src = dollar + 1;
3fed15f5
JH
1145 }
1146 }
77321184 1147 memmove(dst, src, len);
5ecd293d
PH
1148 strbuf_setlen(buf, dst + len - buf->buf);
1149 return 1;
3fed15f5
JH
1150}
1151
55ad152c 1152static int ident_to_worktree(const char *src, size_t len,
ec36c42a 1153 struct strbuf *buf, int ident)
3fed15f5 1154{
f070facc 1155 struct object_id oid;
07814d90 1156 char *to_free = NULL, *dollar, *spc;
5ecd293d 1157 int cnt;
3fed15f5
JH
1158
1159 if (!ident)
5ecd293d 1160 return 0;
3fed15f5 1161
5ecd293d 1162 cnt = count_ident(src, len);
3fed15f5 1163 if (!cnt)
5ecd293d 1164 return 0;
3fed15f5 1165
5ecd293d
PH
1166 /* are we "faking" in place editing ? */
1167 if (src == buf->buf)
b315c5c0 1168 to_free = strbuf_detach(buf, NULL);
2dcde20e 1169 hash_object_file(the_hash_algo, src, len, "blob", &oid);
3fed15f5 1170
1a750441 1171 strbuf_grow(buf, len + cnt * (the_hash_algo->hexsz + 3));
5ecd293d
PH
1172 for (;;) {
1173 /* step 1: run to the next '$' */
1174 dollar = memchr(src, '$', len);
1175 if (!dollar)
1176 break;
1177 strbuf_add(buf, src, dollar + 1 - src);
1178 len -= dollar + 1 - src;
1179 src = dollar + 1;
c23290d5 1180
5ecd293d
PH
1181 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1182 if (len < 3 || memcmp("Id", src, 2))
3fed15f5
JH
1183 continue;
1184
5ecd293d
PH
1185 /* step 3: skip over Id$ or Id:xxxxx$ */
1186 if (src[2] == '$') {
1187 src += 3;
1188 len -= 3;
1189 } else if (src[2] == ':') {
1190 /*
1191 * It's possible that an expanded Id has crept its way into the
07814d90
HG
1192 * repository, we cope with that by stripping the expansion out.
1193 * This is probably not a good idea, since it will cause changes
1194 * on checkout, which won't go away by stash, but let's keep it
1195 * for git-style ids.
5ecd293d
PH
1196 */
1197 dollar = memchr(src + 3, '$', len - 3);
1198 if (!dollar) {
1199 /* incomplete keyword, no more '$', so just quit the loop */
1200 break;
1201 }
c23290d5 1202
a9f3049f
HG
1203 if (memchr(src + 3, '\n', dollar - src - 3)) {
1204 /* Line break before the next dollar. */
1205 continue;
1206 }
1207
07814d90
HG
1208 spc = memchr(src + 4, ' ', dollar - src - 4);
1209 if (spc && spc < dollar-1) {
1210 /* There are spaces in unexpected places.
1211 * This is probably an id from some other
1212 * versioning system. Keep it for now.
1213 */
1214 continue;
1215 }
1216
5ecd293d
PH
1217 len -= dollar + 1 - src;
1218 src = dollar + 1;
1219 } else {
1220 /* it wasn't a "Id$" or "Id:xxxx$" */
1221 continue;
1222 }
c23290d5 1223
5ecd293d
PH
1224 /* step 4: substitute */
1225 strbuf_addstr(buf, "Id: ");
f070facc 1226 strbuf_addstr(buf, oid_to_hex(&oid));
5ecd293d 1227 strbuf_addstr(buf, " $");
3fed15f5 1228 }
5ecd293d 1229 strbuf_add(buf, src, len);
3fed15f5 1230
5ecd293d
PH
1231 free(to_free);
1232 return 1;
35ebfd6a
JH
1233}
1234
107642fe
LS
1235static const char *git_path_check_encoding(struct attr_check_item *check)
1236{
1237 const char *value = check->value;
1238
1239 if (ATTR_UNSET(value) || !strlen(value))
1240 return NULL;
1241
1242 if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
1243 die(_("true/false are no valid working-tree-encodings"));
1244 }
1245
1246 /* Don't encode to the default encoding */
1247 if (same_encoding(value, default_encoding))
1248 return NULL;
1249
1250 return value;
1251}
1252
7bd18054 1253static enum crlf_action git_path_check_crlf(struct attr_check_item *check)
35ebfd6a 1254{
6073ee85
JH
1255 const char *value = check->value;
1256
1257 if (ATTR_TRUE(value))
1258 return CRLF_TEXT;
1259 else if (ATTR_FALSE(value))
1260 return CRLF_BINARY;
1261 else if (ATTR_UNSET(value))
1262 ;
1263 else if (!strcmp(value, "input"))
df747b81 1264 return CRLF_TEXT_INPUT;
fd6cce9e
EB
1265 else if (!strcmp(value, "auto"))
1266 return CRLF_AUTO;
df747b81 1267 return CRLF_UNDEFINED;
35ebfd6a
JH
1268}
1269
7bd18054 1270static enum eol git_path_check_eol(struct attr_check_item *check)
fd6cce9e
EB
1271{
1272 const char *value = check->value;
1273
1274 if (ATTR_UNSET(value))
1275 ;
1276 else if (!strcmp(value, "lf"))
1277 return EOL_LF;
1278 else if (!strcmp(value, "crlf"))
1279 return EOL_CRLF;
1280 return EOL_UNSET;
1281}
1282
7bd18054 1283static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
aa4ed402
JH
1284{
1285 const char *value = check->value;
1286 struct convert_driver *drv;
1287
1288 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1289 return NULL;
1290 for (drv = user_convert; drv; drv = drv->next)
1291 if (!strcmp(value, drv->name))
1292 return drv;
1293 return NULL;
1294}
1295
7bd18054 1296static int git_path_check_ident(struct attr_check_item *check)
3fed15f5
JH
1297{
1298 const char *value = check->value;
1299
1300 return !!ATTR_TRUE(value);
1301}
1302
3bfba20d
JH
1303struct conv_attrs {
1304 struct convert_driver *drv;
bb211b4d
TB
1305 enum crlf_action attr_action; /* What attr says */
1306 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
3bfba20d 1307 int ident;
107642fe 1308 const char *working_tree_encoding; /* Supported encoding or default encoding if NULL */
3bfba20d
JH
1309};
1310
2c65d90f 1311static struct attr_check *check;
1312
7f944e26
NTND
1313static void convert_attrs(const struct index_state *istate,
1314 struct conv_attrs *ca, const char *path)
83295964 1315{
d64324cb 1316 struct attr_check_item *ccheck = NULL;
83295964 1317
2aef63d3
JH
1318 if (!check) {
1319 check = attr_check_initl("crlf", "ident", "filter",
107642fe
LS
1320 "eol", "text", "working-tree-encoding",
1321 NULL);
83295964
JH
1322 user_convert_tail = &user_convert;
1323 git_config(read_convert_config, NULL);
1324 }
3bfba20d 1325
d64324cb
TB
1326 git_check_attr(istate, path, check);
1327 ccheck = check->items;
1328 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1329 if (ca->crlf_action == CRLF_UNDEFINED)
1330 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1331 ca->ident = git_path_check_ident(ccheck + 1);
1332 ca->drv = git_path_check_convert(ccheck + 2);
1333 if (ca->crlf_action != CRLF_BINARY) {
1334 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1335 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1336 ca->crlf_action = CRLF_AUTO_INPUT;
1337 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1338 ca->crlf_action = CRLF_AUTO_CRLF;
1339 else if (eol_attr == EOL_LF)
1340 ca->crlf_action = CRLF_TEXT_INPUT;
1341 else if (eol_attr == EOL_CRLF)
1342 ca->crlf_action = CRLF_TEXT_CRLF;
3bfba20d 1343 }
d64324cb 1344 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
5c94c93d
1345
1346 /* Save attr and make a decision for action */
1347 ca->attr_action = ca->crlf_action;
df747b81
TB
1348 if (ca->crlf_action == CRLF_TEXT)
1349 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1350 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1351 ca->crlf_action = CRLF_BINARY;
1352 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1353 ca->crlf_action = CRLF_AUTO_CRLF;
1354 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1355 ca->crlf_action = CRLF_AUTO_INPUT;
83295964
JH
1356}
1357
2c65d90f 1358void reset_parsed_attributes(void)
1359{
1360 struct convert_driver *drv, *next;
1361
1362 attr_check_free(check);
1363 check = NULL;
1364 reset_merge_attributes();
1365
1366 for (drv = user_convert; drv; drv = next) {
1367 next = drv->next;
1368 free((void *)drv->name);
1369 free(drv);
1370 }
1371 user_convert = NULL;
1372 user_convert_tail = NULL;
1373}
1374
7f944e26 1375int would_convert_to_git_filter_fd(const struct index_state *istate, const char *path)
9035d75a
SP
1376{
1377 struct conv_attrs ca;
1378
7f944e26 1379 convert_attrs(istate, &ca, path);
9035d75a
SP
1380 if (!ca.drv)
1381 return 0;
1382
1383 /*
1384 * Apply a filter to an fd only if the filter is required to succeed.
1385 * We must die if the filter fails, because the original data before
1386 * filtering is not available.
1387 */
1388 if (!ca.drv->required)
1389 return 0;
1390
ab90ecae 1391 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL, NULL);
9035d75a
SP
1392}
1393
7f944e26 1394const char *get_convert_attr_ascii(const struct index_state *istate, const char *path)
a7630bd4
TB
1395{
1396 struct conv_attrs ca;
a7630bd4 1397
7f944e26 1398 convert_attrs(istate, &ca, path);
bb211b4d 1399 switch (ca.attr_action) {
df747b81 1400 case CRLF_UNDEFINED:
a7630bd4
TB
1401 return "";
1402 case CRLF_BINARY:
1403 return "-text";
1404 case CRLF_TEXT:
1405 return "text";
df747b81 1406 case CRLF_TEXT_INPUT:
a7630bd4 1407 return "text eol=lf";
df747b81
TB
1408 case CRLF_TEXT_CRLF:
1409 return "text eol=crlf";
a7630bd4
TB
1410 case CRLF_AUTO:
1411 return "text=auto";
df747b81 1412 case CRLF_AUTO_CRLF:
65237284 1413 return "text=auto eol=crlf";
df747b81 1414 case CRLF_AUTO_INPUT:
65237284 1415 return "text=auto eol=lf";
a7630bd4
TB
1416 }
1417 return "";
1418}
1419
82b474e0
BW
1420int convert_to_git(const struct index_state *istate,
1421 const char *path, const char *src, size_t len,
8462ff43 1422 struct strbuf *dst, int conv_flags)
35ebfd6a 1423{
3bfba20d 1424 int ret = 0;
3bfba20d 1425 struct conv_attrs ca;
6073ee85 1426
7f944e26 1427 convert_attrs(istate, &ca, path);
3fed15f5 1428
ab90ecae 1429 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL, NULL);
234fa07e 1430 if (!ret && ca.drv && ca.drv->required)
d26a328e 1431 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
36daaaca 1432
92ac3197 1433 if (ret && dst) {
5ecd293d
PH
1434 src = dst->buf;
1435 len = dst->len;
aa4ed402 1436 }
107642fe
LS
1437
1438 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1439 if (ret && dst) {
1440 src = dst->buf;
1441 len = dst->len;
1442 }
1443
8462ff43
TB
1444 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1445 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
2fea9de6
TB
1446 if (ret && dst) {
1447 src = dst->buf;
1448 len = dst->len;
1449 }
6073ee85 1450 }
55ad152c 1451 return ret | ident_to_git(src, len, dst, ca.ident);
35ebfd6a
JH
1452}
1453
d6c41c20
BW
1454void convert_to_git_filter_fd(const struct index_state *istate,
1455 const char *path, int fd, struct strbuf *dst,
8462ff43 1456 int conv_flags)
9035d75a
SP
1457{
1458 struct conv_attrs ca;
7f944e26 1459 convert_attrs(istate, &ca, path);
9035d75a
SP
1460
1461 assert(ca.drv);
edcc8581 1462 assert(ca.drv->clean || ca.drv->process);
9035d75a 1463
ab90ecae 1464 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL, NULL))
d26a328e 1465 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
9035d75a 1466
107642fe 1467 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
8462ff43 1468 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
55ad152c 1469 ident_to_git(dst->buf, dst->len, dst, ca.ident);
9035d75a
SP
1470}
1471
7f944e26
NTND
1472static int convert_to_working_tree_internal(const struct index_state *istate,
1473 const char *path, const char *src,
43dd2332 1474 size_t len, struct strbuf *dst,
ab90ecae 1475 int normalizing,
1476 const struct checkout_metadata *meta,
1477 struct delayed_checkout *dco)
35ebfd6a 1478{
36daaaca 1479 int ret = 0, ret_filter = 0;
3bfba20d 1480 struct conv_attrs ca;
6073ee85 1481
7f944e26 1482 convert_attrs(istate, &ca, path);
3fed15f5 1483
55ad152c 1484 ret |= ident_to_worktree(src, len, dst, ca.ident);
5ecd293d
PH
1485 if (ret) {
1486 src = dst->buf;
1487 len = dst->len;
3fed15f5 1488 }
43dd2332
EB
1489 /*
1490 * CRLF conversion can be skipped if normalizing, unless there
edcc8581
LS
1491 * is a smudge or process filter (even if the process filter doesn't
1492 * support smudge). The filters might expect CRLFs.
43dd2332 1493 */
edcc8581 1494 if ((ca.drv && (ca.drv->smudge || ca.drv->process)) || !normalizing) {
55ad152c 1495 ret |= crlf_to_worktree(src, len, dst, ca.crlf_action);
43dd2332
EB
1496 if (ret) {
1497 src = dst->buf;
1498 len = dst->len;
1499 }
aa4ed402 1500 }
36daaaca 1501
107642fe
LS
1502 ret |= encode_to_worktree(path, src, len, dst, ca.working_tree_encoding);
1503 if (ret) {
1504 src = dst->buf;
1505 len = dst->len;
1506 }
1507
2841e8f8 1508 ret_filter = apply_filter(
ab90ecae 1509 path, src, len, -1, dst, ca.drv, CAP_SMUDGE, meta, dco);
234fa07e 1510 if (!ret_filter && ca.drv && ca.drv->required)
d26a328e 1511 die(_("%s: smudge filter %s failed"), path, ca.drv->name);
36daaaca
JB
1512
1513 return ret | ret_filter;
35ebfd6a 1514}
f217f0e8 1515
7f944e26
NTND
1516int async_convert_to_working_tree(const struct index_state *istate,
1517 const char *path, const char *src,
2841e8f8 1518 size_t len, struct strbuf *dst,
ab90ecae 1519 const struct checkout_metadata *meta,
2841e8f8
LS
1520 void *dco)
1521{
ab90ecae 1522 return convert_to_working_tree_internal(istate, path, src, len, dst, 0, meta, dco);
2841e8f8
LS
1523}
1524
7f944e26
NTND
1525int convert_to_working_tree(const struct index_state *istate,
1526 const char *path, const char *src,
ab90ecae 1527 size_t len, struct strbuf *dst,
1528 const struct checkout_metadata *meta)
43dd2332 1529{
ab90ecae 1530 return convert_to_working_tree_internal(istate, path, src, len, dst, 0, meta, NULL);
43dd2332
EB
1531}
1532
a33e0b2a
BW
1533int renormalize_buffer(const struct index_state *istate, const char *path,
1534 const char *src, size_t len, struct strbuf *dst)
f217f0e8 1535{
ab90ecae 1536 int ret = convert_to_working_tree_internal(istate, path, src, len, dst, 1, NULL, NULL);
f217f0e8
EB
1537 if (ret) {
1538 src = dst->buf;
1539 len = dst->len;
1540 }
8462ff43 1541 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
f217f0e8 1542}
dd8e9121 1543
b6691092
JH
1544/*****************************************************************
1545 *
749f763d 1546 * Streaming conversion support
b6691092
JH
1547 *
1548 *****************************************************************/
1549
1550typedef int (*filter_fn)(struct stream_filter *,
1551 const char *input, size_t *isize_p,
1552 char *output, size_t *osize_p);
1553typedef void (*free_fn)(struct stream_filter *);
1554
1555struct stream_filter_vtbl {
1556 filter_fn filter;
1557 free_fn free;
1558};
1559
1560struct stream_filter {
1561 struct stream_filter_vtbl *vtbl;
1562};
1563
1564static int null_filter_fn(struct stream_filter *filter,
1565 const char *input, size_t *isize_p,
1566 char *output, size_t *osize_p)
1567{
4ae66704
JH
1568 size_t count;
1569
1570 if (!input)
1571 return 0; /* we do not keep any states */
1572 count = *isize_p;
b6691092
JH
1573 if (*osize_p < count)
1574 count = *osize_p;
1575 if (count) {
1576 memmove(output, input, count);
1577 *isize_p -= count;
1578 *osize_p -= count;
1579 }
1580 return 0;
1581}
1582
1583static void null_free_fn(struct stream_filter *filter)
1584{
1585 ; /* nothing -- null instances are shared */
1586}
1587
1588static struct stream_filter_vtbl null_vtbl = {
1589 null_filter_fn,
1590 null_free_fn,
1591};
1592
1593static struct stream_filter null_filter_singleton = {
1594 &null_vtbl,
1595};
1596
1597int is_null_stream_filter(struct stream_filter *filter)
1598{
1599 return filter == &null_filter_singleton;
1600}
1601
b84c7839
JH
1602
1603/*
1604 * LF-to-CRLF filter
1605 */
284e3d28
CMN
1606
1607struct lf_to_crlf_filter {
1608 struct stream_filter filter;
8496f568
JH
1609 unsigned has_held:1;
1610 char held;
284e3d28
CMN
1611};
1612
e322ee38
JH
1613static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1614 const char *input, size_t *isize_p,
1615 char *output, size_t *osize_p)
1616{
284e3d28
CMN
1617 size_t count, o = 0;
1618 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1619
8496f568
JH
1620 /*
1621 * We may be holding onto the CR to see if it is followed by a
1622 * LF, in which case we would need to go to the main loop.
1623 * Otherwise, just emit it to the output stream.
1624 */
1625 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1626 output[o++] = lf_to_crlf->held;
1627 lf_to_crlf->has_held = 0;
284e3d28 1628 }
e322ee38 1629
87afe9a5
JH
1630 /* We are told to drain */
1631 if (!input) {
1632 *osize_p -= o;
1633 return 0;
1634 }
e322ee38 1635
e322ee38 1636 count = *isize_p;
8496f568 1637 if (count || lf_to_crlf->has_held) {
284e3d28 1638 size_t i;
8496f568
JH
1639 int was_cr = 0;
1640
1641 if (lf_to_crlf->has_held) {
1642 was_cr = 1;
1643 lf_to_crlf->has_held = 0;
1644 }
1645
284e3d28 1646 for (i = 0; o < *osize_p && i < count; i++) {
e322ee38 1647 char ch = input[i];
8496f568 1648
e322ee38 1649 if (ch == '\n') {
284e3d28 1650 output[o++] = '\r';
8496f568
JH
1651 } else if (was_cr) {
1652 /*
1653 * Previous round saw CR and it is not followed
1654 * by a LF; emit the CR before processing the
1655 * current character.
1656 */
1657 output[o++] = '\r';
e322ee38 1658 }
8496f568
JH
1659
1660 /*
1661 * We may have consumed the last output slot,
1662 * in which case we need to break out of this
1663 * loop; hold the current character before
1664 * returning.
1665 */
1666 if (*osize_p <= o) {
1667 lf_to_crlf->has_held = 1;
1668 lf_to_crlf->held = ch;
1669 continue; /* break but increment i */
1670 }
1671
1672 if (ch == '\r') {
1673 was_cr = 1;
1674 continue;
1675 }
1676
1677 was_cr = 0;
e322ee38
JH
1678 output[o++] = ch;
1679 }
1680
1681 *osize_p -= o;
1682 *isize_p -= i;
8496f568
JH
1683
1684 if (!lf_to_crlf->has_held && was_cr) {
1685 lf_to_crlf->has_held = 1;
1686 lf_to_crlf->held = '\r';
1687 }
e322ee38
JH
1688 }
1689 return 0;
1690}
1691
284e3d28
CMN
1692static void lf_to_crlf_free_fn(struct stream_filter *filter)
1693{
1694 free(filter);
1695}
1696
e322ee38
JH
1697static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1698 lf_to_crlf_filter_fn,
284e3d28 1699 lf_to_crlf_free_fn,
e322ee38
JH
1700};
1701
284e3d28
CMN
1702static struct stream_filter *lf_to_crlf_filter(void)
1703{
87afe9a5 1704 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
e322ee38 1705
284e3d28 1706 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
284e3d28
CMN
1707 return (struct stream_filter *)lf_to_crlf;
1708}
b84c7839 1709
a265a7f9
JH
1710/*
1711 * Cascade filter
1712 */
1713#define FILTER_BUFFER 1024
1714struct cascade_filter {
1715 struct stream_filter filter;
1716 struct stream_filter *one;
1717 struct stream_filter *two;
1718 char buf[FILTER_BUFFER];
1719 int end, ptr;
1720};
1721
1722static int cascade_filter_fn(struct stream_filter *filter,
1723 const char *input, size_t *isize_p,
1724 char *output, size_t *osize_p)
1725{
1726 struct cascade_filter *cas = (struct cascade_filter *) filter;
1727 size_t filled = 0;
1728 size_t sz = *osize_p;
1729 size_t to_feed, remaining;
1730
1731 /*
1732 * input -- (one) --> buf -- (two) --> output
1733 */
1734 while (filled < sz) {
1735 remaining = sz - filled;
1736
1737 /* do we already have something to feed two with? */
1738 if (cas->ptr < cas->end) {
1739 to_feed = cas->end - cas->ptr;
1740 if (stream_filter(cas->two,
1741 cas->buf + cas->ptr, &to_feed,
1742 output + filled, &remaining))
1743 return -1;
1744 cas->ptr += (cas->end - cas->ptr) - to_feed;
1745 filled = sz - remaining;
1746 continue;
1747 }
1748
1749 /* feed one from upstream and have it emit into our buffer */
1750 to_feed = input ? *isize_p : 0;
1751 if (input && !to_feed)
1752 break;
1753 remaining = sizeof(cas->buf);
1754 if (stream_filter(cas->one,
1755 input, &to_feed,
1756 cas->buf, &remaining))
1757 return -1;
1758 cas->end = sizeof(cas->buf) - remaining;
1759 cas->ptr = 0;
1760 if (input) {
1761 size_t fed = *isize_p - to_feed;
1762 *isize_p -= fed;
1763 input += fed;
1764 }
1765
1766 /* do we know that we drained one completely? */
1767 if (input || cas->end)
1768 continue;
1769
1770 /* tell two to drain; we have nothing more to give it */
1771 to_feed = 0;
1772 remaining = sz - filled;
1773 if (stream_filter(cas->two,
1774 NULL, &to_feed,
1775 output + filled, &remaining))
1776 return -1;
1777 if (remaining == (sz - filled))
1778 break; /* completely drained two */
1779 filled = sz - remaining;
1780 }
1781 *osize_p -= filled;
1782 return 0;
1783}
1784
1785static void cascade_free_fn(struct stream_filter *filter)
1786{
1787 struct cascade_filter *cas = (struct cascade_filter *)filter;
1788 free_stream_filter(cas->one);
1789 free_stream_filter(cas->two);
1790 free(filter);
1791}
1792
1793static struct stream_filter_vtbl cascade_vtbl = {
1794 cascade_filter_fn,
1795 cascade_free_fn,
1796};
1797
1798static struct stream_filter *cascade_filter(struct stream_filter *one,
1799 struct stream_filter *two)
1800{
1801 struct cascade_filter *cascade;
1802
1803 if (!one || is_null_stream_filter(one))
1804 return two;
1805 if (!two || is_null_stream_filter(two))
1806 return one;
1807
1808 cascade = xmalloc(sizeof(*cascade));
1809 cascade->one = one;
1810 cascade->two = two;
1811 cascade->end = cascade->ptr = 0;
1812 cascade->filter.vtbl = &cascade_vtbl;
1813 return (struct stream_filter *)cascade;
1814}
1815
b84c7839
JH
1816/*
1817 * ident filter
1818 */
1819#define IDENT_DRAINING (-1)
1820#define IDENT_SKIPPING (-2)
1821struct ident_filter {
1822 struct stream_filter filter;
1823 struct strbuf left;
1824 int state;
1a750441 1825 char ident[GIT_MAX_HEXSZ + 5]; /* ": x40 $" */
b84c7839
JH
1826};
1827
1828static int is_foreign_ident(const char *str)
1829{
1830 int i;
1831
ae021d87 1832 if (!skip_prefix(str, "$Id: ", &str))
b84c7839 1833 return 0;
ae021d87 1834 for (i = 0; str[i]; i++) {
b84c7839
JH
1835 if (isspace(str[i]) && str[i+1] != '$')
1836 return 1;
1837 }
1838 return 0;
1839}
1840
1841static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1842{
1843 size_t to_drain = ident->left.len;
1844
1845 if (*osize_p < to_drain)
1846 to_drain = *osize_p;
1847 if (to_drain) {
1848 memcpy(*output_p, ident->left.buf, to_drain);
1849 strbuf_remove(&ident->left, 0, to_drain);
1850 *output_p += to_drain;
1851 *osize_p -= to_drain;
1852 }
1853 if (!ident->left.len)
1854 ident->state = 0;
1855}
1856
1857static int ident_filter_fn(struct stream_filter *filter,
1858 const char *input, size_t *isize_p,
1859 char *output, size_t *osize_p)
1860{
1861 struct ident_filter *ident = (struct ident_filter *)filter;
1862 static const char head[] = "$Id";
1863
1864 if (!input) {
1865 /* drain upon eof */
1866 switch (ident->state) {
1867 default:
1868 strbuf_add(&ident->left, head, ident->state);
1cf01a34 1869 /* fallthrough */
b84c7839 1870 case IDENT_SKIPPING:
1cf01a34 1871 /* fallthrough */
b84c7839
JH
1872 case IDENT_DRAINING:
1873 ident_drain(ident, &output, osize_p);
1874 }
1875 return 0;
1876 }
1877
1878 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1879 int ch;
1880
1881 if (ident->state == IDENT_DRAINING) {
1882 ident_drain(ident, &output, osize_p);
1883 if (!*osize_p)
1884 break;
1885 continue;
1886 }
1887
1888 ch = *(input++);
1889 (*isize_p)--;
1890
1891 if (ident->state == IDENT_SKIPPING) {
1892 /*
1893 * Skipping until '$' or LF, but keeping them
1894 * in case it is a foreign ident.
1895 */
1896 strbuf_addch(&ident->left, ch);
1897 if (ch != '\n' && ch != '$')
1898 continue;
1899 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1900 strbuf_setlen(&ident->left, sizeof(head) - 1);
1901 strbuf_addstr(&ident->left, ident->ident);
1902 }
1903 ident->state = IDENT_DRAINING;
1904 continue;
1905 }
1906
1907 if (ident->state < sizeof(head) &&
1908 head[ident->state] == ch) {
1909 ident->state++;
1910 continue;
1911 }
1912
1913 if (ident->state)
1914 strbuf_add(&ident->left, head, ident->state);
1915 if (ident->state == sizeof(head) - 1) {
1916 if (ch != ':' && ch != '$') {
1917 strbuf_addch(&ident->left, ch);
1918 ident->state = 0;
1919 continue;
1920 }
1921
1922 if (ch == ':') {
1923 strbuf_addch(&ident->left, ch);
1924 ident->state = IDENT_SKIPPING;
1925 } else {
1926 strbuf_addstr(&ident->left, ident->ident);
1927 ident->state = IDENT_DRAINING;
1928 }
1929 continue;
1930 }
1931
1932 strbuf_addch(&ident->left, ch);
1933 ident->state = IDENT_DRAINING;
1934 }
1935 return 0;
1936}
1937
1938static void ident_free_fn(struct stream_filter *filter)
1939{
1940 struct ident_filter *ident = (struct ident_filter *)filter;
1941 strbuf_release(&ident->left);
1942 free(filter);
1943}
1944
1945static struct stream_filter_vtbl ident_vtbl = {
1946 ident_filter_fn,
1947 ident_free_fn,
1948};
1949
1a750441 1950static struct stream_filter *ident_filter(const struct object_id *oid)
b84c7839
JH
1951{
1952 struct ident_filter *ident = xmalloc(sizeof(*ident));
1953
5096d490 1954 xsnprintf(ident->ident, sizeof(ident->ident),
1a750441 1955 ": %s $", oid_to_hex(oid));
b84c7839
JH
1956 strbuf_init(&ident->left, 0);
1957 ident->filter.vtbl = &ident_vtbl;
1958 ident->state = 0;
1959 return (struct stream_filter *)ident;
1960}
1961
dd8e9121 1962/*
b6691092
JH
1963 * Return an appropriately constructed filter for the path, or NULL if
1964 * the contents cannot be filtered without reading the whole thing
1965 * in-core.
1966 *
2b0f19fa 1967 * Note that you would be crazy to set CRLF, smudge/clean or ident to a
b6691092 1968 * large binary blob you would want us not to slurp into the memory!
dd8e9121 1969 */
7f944e26
NTND
1970struct stream_filter *get_stream_filter(const struct index_state *istate,
1971 const char *path,
1972 const struct object_id *oid)
dd8e9121
JH
1973{
1974 struct conv_attrs ca;
b84c7839 1975 struct stream_filter *filter = NULL;
dd8e9121 1976
7f944e26 1977 convert_attrs(istate, &ca, path);
edcc8581 1978 if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
caa47adc
TB
1979 return NULL;
1980
107642fe
LS
1981 if (ca.working_tree_encoding)
1982 return NULL;
1983
caa47adc
TB
1984 if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1985 return NULL;
b84c7839
JH
1986
1987 if (ca.ident)
1a750441 1988 filter = ident_filter(oid);
dd8e9121 1989
caa47adc 1990 if (output_eol(ca.crlf_action) == EOL_CRLF)
284e3d28 1991 filter = cascade_filter(filter, lf_to_crlf_filter());
caa47adc
TB
1992 else
1993 filter = cascade_filter(filter, &null_filter_singleton);
e322ee38 1994
b84c7839 1995 return filter;
b6691092
JH
1996}
1997
1998void free_stream_filter(struct stream_filter *filter)
1999{
2000 filter->vtbl->free(filter);
2001}
2002
2003int stream_filter(struct stream_filter *filter,
2004 const char *input, size_t *isize_p,
2005 char *output, size_t *osize_p)
2006{
2007 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
dd8e9121 2008}
c397aac0 2009
2010void init_checkout_metadata(struct checkout_metadata *meta, const char *refname,
2011 const struct object_id *treeish,
2012 const struct object_id *blob)
2013{
2014 memset(meta, 0, sizeof(*meta));
2015 if (refname)
2016 meta->refname = refname;
2017 if (treeish)
2018 oidcpy(&meta->treeish, treeish);
2019 if (blob)
2020 oidcpy(&meta->blob, blob);
2021}
2022
2023void clone_checkout_metadata(struct checkout_metadata *dst,
2024 const struct checkout_metadata *src,
2025 const struct object_id *blob)
2026{
2027 memcpy(dst, src, sizeof(*dst));
2028 if (blob)
2029 oidcpy(&dst->blob, blob);
2030}