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