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