The fifteenth batch
[git/debian.git] / convert.c
blobf2b9f01354d0d76e3e2bf117dc3a1e80d280635e
1 #include "git-compat-util.h"
2 #include "advice.h"
3 #include "config.h"
4 #include "convert.h"
5 #include "copy.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "object-store-ll.h"
9 #include "attr.h"
10 #include "run-command.h"
11 #include "quote.h"
12 #include "read-cache-ll.h"
13 #include "sigchain.h"
14 #include "pkt-line.h"
15 #include "sub-process.h"
16 #include "trace.h"
17 #include "utf8.h"
18 #include "merge-ll.h"
21 * convert.c - convert a file when checking it out and checking it in.
23 * This should use the pathname to decide on whether it wants to do some
24 * more interesting conversions (automatic gzip/unzip, general format
25 * conversions etc etc), but by default it just does automatic CRLF<->LF
26 * translation when the "text" attribute or "auto_crlf" option is set.
29 /* Stat bits: When BIN is set, the txt bits are unset */
30 #define CONVERT_STAT_BITS_TXT_LF 0x1
31 #define CONVERT_STAT_BITS_TXT_CRLF 0x2
32 #define CONVERT_STAT_BITS_BIN 0x4
34 struct text_stat {
35 /* NUL, CR, LF and CRLF counts */
36 unsigned nul, lonecr, lonelf, crlf;
38 /* These are just approximations! */
39 unsigned printable, nonprintable;
42 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
44 unsigned long i;
46 memset(stats, 0, sizeof(*stats));
48 for (i = 0; i < size; i++) {
49 unsigned char c = buf[i];
50 if (c == '\r') {
51 if (i+1 < size && buf[i+1] == '\n') {
52 stats->crlf++;
53 i++;
54 } else
55 stats->lonecr++;
56 continue;
58 if (c == '\n') {
59 stats->lonelf++;
60 continue;
62 if (c == 127)
63 /* DEL */
64 stats->nonprintable++;
65 else if (c < 32) {
66 switch (c) {
67 /* BS, HT, ESC and FF */
68 case '\b': case '\t': case '\033': case '\014':
69 stats->printable++;
70 break;
71 case 0:
72 stats->nul++;
73 /* fall through */
74 default:
75 stats->nonprintable++;
78 else
79 stats->printable++;
82 /* If file ends with EOF then don't count this EOF as non-printable. */
83 if (size >= 1 && buf[size-1] == '\032')
84 stats->nonprintable--;
88 * The same heuristics as diff.c::mmfile_is_binary()
89 * We treat files with bare CR as binary
91 static int convert_is_binary(const struct text_stat *stats)
93 if (stats->lonecr)
94 return 1;
95 if (stats->nul)
96 return 1;
97 if ((stats->printable >> 7) < stats->nonprintable)
98 return 1;
99 return 0;
102 static unsigned int gather_convert_stats(const char *data, unsigned long size)
104 struct text_stat stats;
105 int ret = 0;
106 if (!data || !size)
107 return 0;
108 gather_stats(data, size, &stats);
109 if (convert_is_binary(&stats))
110 ret |= CONVERT_STAT_BITS_BIN;
111 if (stats.crlf)
112 ret |= CONVERT_STAT_BITS_TXT_CRLF;
113 if (stats.lonelf)
114 ret |= CONVERT_STAT_BITS_TXT_LF;
116 return ret;
119 static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
121 unsigned int convert_stats = gather_convert_stats(data, size);
123 if (convert_stats & CONVERT_STAT_BITS_BIN)
124 return "-text";
125 switch (convert_stats) {
126 case CONVERT_STAT_BITS_TXT_LF:
127 return "lf";
128 case CONVERT_STAT_BITS_TXT_CRLF:
129 return "crlf";
130 case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
131 return "mixed";
132 default:
133 return "none";
137 const char *get_cached_convert_stats_ascii(struct index_state *istate,
138 const char *path)
140 const char *ret;
141 unsigned long sz;
142 void *data = read_blob_data_from_index(istate, path, &sz);
143 ret = gather_convert_stats_ascii(data, sz);
144 free(data);
145 return ret;
148 const char *get_wt_convert_stats_ascii(const char *path)
150 const char *ret = "";
151 struct strbuf sb = STRBUF_INIT;
152 if (strbuf_read_file(&sb, path, 0) >= 0)
153 ret = gather_convert_stats_ascii(sb.buf, sb.len);
154 strbuf_release(&sb);
155 return ret;
158 static int text_eol_is_crlf(void)
160 if (auto_crlf == AUTO_CRLF_TRUE)
161 return 1;
162 else if (auto_crlf == AUTO_CRLF_INPUT)
163 return 0;
164 if (core_eol == EOL_CRLF)
165 return 1;
166 if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
167 return 1;
168 return 0;
171 static enum eol output_eol(enum convert_crlf_action crlf_action)
173 switch (crlf_action) {
174 case CRLF_BINARY:
175 return EOL_UNSET;
176 case CRLF_TEXT_CRLF:
177 return EOL_CRLF;
178 case CRLF_TEXT_INPUT:
179 return EOL_LF;
180 case CRLF_UNDEFINED:
181 case CRLF_AUTO_CRLF:
182 return EOL_CRLF;
183 case CRLF_AUTO_INPUT:
184 return EOL_LF;
185 case CRLF_TEXT:
186 case CRLF_AUTO:
187 /* fall through */
188 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
190 warning(_("illegal crlf_action %d"), (int)crlf_action);
191 return core_eol;
194 static void check_global_conv_flags_eol(const char *path,
195 struct text_stat *old_stats, struct text_stat *new_stats,
196 int conv_flags)
198 if (old_stats->crlf && !new_stats->crlf ) {
200 * CRLFs would not be restored by checkout
202 if (conv_flags & CONV_EOL_RNDTRP_DIE)
203 die(_("CRLF would be replaced by LF in %s"), path);
204 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
205 warning(_("in the working copy of '%s', CRLF will be"
206 " replaced by LF the next time Git touches"
207 " it"), path);
208 } else if (old_stats->lonelf && !new_stats->lonelf ) {
210 * CRLFs would be added by checkout
212 if (conv_flags & CONV_EOL_RNDTRP_DIE)
213 die(_("LF would be replaced by CRLF in %s"), path);
214 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
215 warning(_("in the working copy of '%s', LF will be"
216 " replaced by CRLF the next time Git touches"
217 " it"), path);
221 static int has_crlf_in_index(struct index_state *istate, const char *path)
223 unsigned long sz;
224 void *data;
225 const char *crp;
226 int has_crlf = 0;
228 data = read_blob_data_from_index(istate, path, &sz);
229 if (!data)
230 return 0;
232 crp = memchr(data, '\r', sz);
233 if (crp) {
234 unsigned int ret_stats;
235 ret_stats = gather_convert_stats(data, sz);
236 if (!(ret_stats & CONVERT_STAT_BITS_BIN) &&
237 (ret_stats & CONVERT_STAT_BITS_TXT_CRLF))
238 has_crlf = 1;
240 free(data);
241 return has_crlf;
244 static int will_convert_lf_to_crlf(struct text_stat *stats,
245 enum convert_crlf_action crlf_action)
247 if (output_eol(crlf_action) != EOL_CRLF)
248 return 0;
249 /* No "naked" LF? Nothing to convert, regardless. */
250 if (!stats->lonelf)
251 return 0;
253 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
254 /* If we have any CR or CRLF line endings, we do not touch it */
255 /* This is the new safer autocrlf-handling */
256 if (stats->lonecr || stats->crlf)
257 return 0;
259 if (convert_is_binary(stats))
260 return 0;
262 return 1;
266 static int validate_encoding(const char *path, const char *enc,
267 const char *data, size_t len, int die_on_error)
269 const char *stripped;
271 /* We only check for UTF here as UTF?? can be an alias for UTF-?? */
272 if (skip_iprefix(enc, "UTF", &stripped)) {
273 skip_prefix(stripped, "-", &stripped);
276 * Check for detectable errors in UTF encodings
278 if (has_prohibited_utf_bom(enc, data, len)) {
279 const char *error_msg = _(
280 "BOM is prohibited in '%s' if encoded as %s");
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.
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 int stripped_len = strlen(stripped) - strlen("BE");
291 advise(advise_msg, path, stripped_len, stripped);
292 if (die_on_error)
293 die(error_msg, path, enc);
294 else {
295 return error(error_msg, path, enc);
298 } else if (is_missing_required_utf_bom(enc, data, len)) {
299 const char *error_msg = _(
300 "BOM is required in '%s' if encoded as %s");
301 const char *advise_msg = _(
302 "The file '%s' is missing a byte order "
303 "mark (BOM). Please use UTF-%sBE or UTF-%sLE "
304 "(depending on the byte order) as "
305 "working-tree-encoding.");
306 advise(advise_msg, path, stripped, stripped);
307 if (die_on_error)
308 die(error_msg, path, enc);
309 else {
310 return error(error_msg, path, enc);
315 return 0;
318 static void trace_encoding(const char *context, const char *path,
319 const char *encoding, const char *buf, size_t len)
321 static struct trace_key coe = TRACE_KEY_INIT(WORKING_TREE_ENCODING);
322 struct strbuf trace = STRBUF_INIT;
323 int i;
325 strbuf_addf(&trace, "%s (%s, considered %s):\n", context, path, encoding);
326 for (i = 0; i < len && buf; ++i) {
327 strbuf_addf(
328 &trace, "| \033[2m%2i:\033[0m %2x \033[2m%c\033[0m%c",
330 (unsigned char) buf[i],
331 (buf[i] > 32 && buf[i] < 127 ? buf[i] : ' '),
332 ((i+1) % 8 && (i+1) < len ? ' ' : '\n')
335 strbuf_addchars(&trace, '\n', 1);
337 trace_strbuf(&coe, &trace);
338 strbuf_release(&trace);
341 static int check_roundtrip(const char *enc_name)
344 * check_roundtrip_encoding contains a string of comma and/or
345 * space separated encodings (eg. "UTF-16, ASCII, CP1125").
346 * Search for the given encoding in that string.
348 const char *encoding = check_roundtrip_encoding ?
349 check_roundtrip_encoding : "SHIFT-JIS";
350 const char *found = strcasestr(encoding, enc_name);
351 const char *next;
352 int len;
353 if (!found)
354 return 0;
355 next = found + strlen(enc_name);
356 len = strlen(encoding);
357 return (found && (
359 * Check that the found encoding is at the beginning of
360 * encoding or that it is prefixed with a space or
361 * comma.
363 found == encoding || (
364 (isspace(found[-1]) || found[-1] == ',')
366 ) && (
368 * Check that the found encoding is at the end of
369 * encoding or that it is suffixed with a space
370 * or comma.
372 next == encoding + len || (
373 next < encoding + len &&
374 (isspace(next[0]) || next[0] == ',')
379 static const char *default_encoding = "UTF-8";
381 static int encode_to_git(const char *path, const char *src, size_t src_len,
382 struct strbuf *buf, const char *enc, int conv_flags)
384 char *dst;
385 size_t dst_len;
386 int die_on_error = conv_flags & CONV_WRITE_OBJECT;
389 * No encoding is specified or there is nothing to encode.
390 * Tell the caller that the content was not modified.
392 if (!enc || (src && !src_len))
393 return 0;
396 * Looks like we got called from "would_convert_to_git()".
397 * This means Git wants to know if it would encode (= modify!)
398 * the content. Let's answer with "yes", since an encoding was
399 * specified.
401 if (!buf && !src)
402 return 1;
404 if (validate_encoding(path, enc, src, src_len, die_on_error))
405 return 0;
407 trace_encoding("source", path, enc, src, src_len);
408 dst = reencode_string_len(src, src_len, default_encoding, enc,
409 &dst_len);
410 if (!dst) {
412 * We could add the blob "as-is" to Git. However, on checkout
413 * we would try to re-encode to the original encoding. This
414 * would fail and we would leave the user with a messed-up
415 * working tree. Let's try to avoid this by screaming loud.
417 const char* msg = _("failed to encode '%s' from %s to %s");
418 if (die_on_error)
419 die(msg, path, enc, default_encoding);
420 else {
421 error(msg, path, enc, default_encoding);
422 return 0;
425 trace_encoding("destination", path, default_encoding, dst, dst_len);
428 * UTF supports lossless conversion round tripping [1] and conversions
429 * between UTF and other encodings are mostly round trip safe as
430 * Unicode aims to be a superset of all other character encodings.
431 * However, certain encodings (e.g. SHIFT-JIS) are known to have round
432 * trip issues [2]. Check the round trip conversion for all encodings
433 * listed in core.checkRoundtripEncoding.
435 * The round trip check is only performed if content is written to Git.
436 * This ensures that no information is lost during conversion to/from
437 * the internal UTF-8 representation.
439 * Please note, the code below is not tested because I was not able to
440 * generate a faulty round trip without an iconv error. Iconv errors
441 * are already caught above.
443 * [1] http://unicode.org/faq/utf_bom.html#gen2
444 * [2] https://support.microsoft.com/en-us/help/170559/prb-conversion-problem-between-shift-jis-and-unicode
446 if (die_on_error && check_roundtrip(enc)) {
447 char *re_src;
448 size_t re_src_len;
450 re_src = reencode_string_len(dst, dst_len,
451 enc, default_encoding,
452 &re_src_len);
454 trace_printf("Checking roundtrip encoding for %s...\n", enc);
455 trace_encoding("reencoded source", path, enc,
456 re_src, re_src_len);
458 if (!re_src || src_len != re_src_len ||
459 memcmp(src, re_src, src_len)) {
460 const char* msg = _("encoding '%s' from %s to %s and "
461 "back is not the same");
462 die(msg, path, enc, default_encoding);
465 free(re_src);
468 strbuf_attach(buf, dst, dst_len, dst_len + 1);
469 return 1;
472 static int encode_to_worktree(const char *path, const char *src, size_t src_len,
473 struct strbuf *buf, const char *enc)
475 char *dst;
476 size_t dst_len;
479 * No encoding is specified or there is nothing to encode.
480 * Tell the caller that the content was not modified.
482 if (!enc || (src && !src_len))
483 return 0;
485 dst = reencode_string_len(src, src_len, enc, default_encoding,
486 &dst_len);
487 if (!dst) {
488 error(_("failed to encode '%s' from %s to %s"),
489 path, default_encoding, enc);
490 return 0;
493 strbuf_attach(buf, dst, dst_len, dst_len + 1);
494 return 1;
497 static int crlf_to_git(struct index_state *istate,
498 const char *path, const char *src, size_t len,
499 struct strbuf *buf,
500 enum convert_crlf_action crlf_action, int conv_flags)
502 struct text_stat stats;
503 char *dst;
504 int convert_crlf_into_lf;
506 if (crlf_action == CRLF_BINARY ||
507 (src && !len))
508 return 0;
511 * If we are doing a dry-run and have no source buffer, there is
512 * nothing to analyze; we must assume we would convert.
514 if (!buf && !src)
515 return 1;
517 gather_stats(src, len, &stats);
518 /* Optimization: No CRLF? Nothing to convert, regardless. */
519 convert_crlf_into_lf = !!stats.crlf;
521 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
522 if (convert_is_binary(&stats))
523 return 0;
525 * If the file in the index has any CR in it, do not
526 * convert. This is the new safer autocrlf handling,
527 * unless we want to renormalize in a merge or
528 * cherry-pick.
530 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
531 has_crlf_in_index(istate, path))
532 convert_crlf_into_lf = 0;
534 if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
535 ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
536 struct text_stat new_stats;
537 memcpy(&new_stats, &stats, sizeof(new_stats));
538 /* simulate "git add" */
539 if (convert_crlf_into_lf) {
540 new_stats.lonelf += new_stats.crlf;
541 new_stats.crlf = 0;
543 /* simulate "git checkout" */
544 if (will_convert_lf_to_crlf(&new_stats, crlf_action)) {
545 new_stats.crlf += new_stats.lonelf;
546 new_stats.lonelf = 0;
548 check_global_conv_flags_eol(path, &stats, &new_stats, conv_flags);
550 if (!convert_crlf_into_lf)
551 return 0;
554 * At this point all of our source analysis is done, and we are sure we
555 * would convert. If we are in dry-run mode, we can give an answer.
557 if (!buf)
558 return 1;
560 /* only grow if not in place */
561 if (strbuf_avail(buf) + buf->len < len)
562 strbuf_grow(buf, len - buf->len);
563 dst = buf->buf;
564 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
566 * If we guessed, we already know we rejected a file with
567 * lone CR, and we can strip a CR without looking at what
568 * follow it.
570 do {
571 unsigned char c = *src++;
572 if (c != '\r')
573 *dst++ = c;
574 } while (--len);
575 } else {
576 do {
577 unsigned char c = *src++;
578 if (! (c == '\r' && (1 < len && *src == '\n')))
579 *dst++ = c;
580 } while (--len);
582 strbuf_setlen(buf, dst - buf->buf);
583 return 1;
586 static int crlf_to_worktree(const char *src, size_t len, struct strbuf *buf,
587 enum convert_crlf_action crlf_action)
589 char *to_free = NULL;
590 struct text_stat stats;
592 if (!len || output_eol(crlf_action) != EOL_CRLF)
593 return 0;
595 gather_stats(src, len, &stats);
596 if (!will_convert_lf_to_crlf(&stats, crlf_action))
597 return 0;
599 /* are we "faking" in place editing ? */
600 if (src == buf->buf)
601 to_free = strbuf_detach(buf, NULL);
603 strbuf_grow(buf, len + stats.lonelf);
604 for (;;) {
605 const char *nl = memchr(src, '\n', len);
606 if (!nl)
607 break;
608 if (nl > src && nl[-1] == '\r') {
609 strbuf_add(buf, src, nl + 1 - src);
610 } else {
611 strbuf_add(buf, src, nl - src);
612 strbuf_addstr(buf, "\r\n");
614 len -= nl + 1 - src;
615 src = nl + 1;
617 strbuf_add(buf, src, len);
619 free(to_free);
620 return 1;
623 struct filter_params {
624 const char *src;
625 size_t size;
626 int fd;
627 const char *cmd;
628 const char *path;
631 static int filter_buffer_or_fd(int in UNUSED, int out, void *data)
634 * Spawn cmd and feed the buffer contents through its stdin.
636 struct child_process child_process = CHILD_PROCESS_INIT;
637 struct filter_params *params = (struct filter_params *)data;
638 const char *format = params->cmd;
639 int write_err, status;
641 /* apply % substitution to cmd */
642 struct strbuf cmd = STRBUF_INIT;
644 /* expand all %f with the quoted path; quote to preserve space, etc. */
645 while (strbuf_expand_step(&cmd, &format)) {
646 if (skip_prefix(format, "%", &format))
647 strbuf_addch(&cmd, '%');
648 else if (skip_prefix(format, "f", &format))
649 sq_quote_buf(&cmd, params->path);
650 else
651 strbuf_addch(&cmd, '%');
654 strvec_push(&child_process.args, cmd.buf);
655 child_process.use_shell = 1;
656 child_process.in = -1;
657 child_process.out = out;
659 if (start_command(&child_process)) {
660 strbuf_release(&cmd);
661 return error(_("cannot fork to run external filter '%s'"),
662 params->cmd);
665 sigchain_push(SIGPIPE, SIG_IGN);
667 if (params->src) {
668 write_err = (write_in_full(child_process.in,
669 params->src, params->size) < 0);
670 if (errno == EPIPE)
671 write_err = 0;
672 } else {
673 write_err = copy_fd(params->fd, child_process.in);
674 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
675 write_err = 0;
678 if (close(child_process.in))
679 write_err = 1;
680 if (write_err)
681 error(_("cannot feed the input to external filter '%s'"),
682 params->cmd);
684 sigchain_pop(SIGPIPE);
686 status = finish_command(&child_process);
687 if (status)
688 error(_("external filter '%s' failed %d"), params->cmd, status);
690 strbuf_release(&cmd);
691 return (write_err || status);
694 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
695 struct strbuf *dst, const char *cmd)
698 * Create a pipeline to have the command filter the buffer's
699 * contents.
701 * (child --> cmd) --> us
703 int err = 0;
704 struct strbuf nbuf = STRBUF_INIT;
705 struct async async;
706 struct filter_params params;
708 memset(&async, 0, sizeof(async));
709 async.proc = filter_buffer_or_fd;
710 async.data = &params;
711 async.out = -1;
712 params.src = src;
713 params.size = len;
714 params.fd = fd;
715 params.cmd = cmd;
716 params.path = path;
718 fflush(NULL);
719 if (start_async(&async))
720 return 0; /* error was already reported */
722 if (strbuf_read(&nbuf, async.out, 0) < 0) {
723 err = error(_("read from external filter '%s' failed"), cmd);
725 if (close(async.out)) {
726 err = error(_("read from external filter '%s' failed"), cmd);
728 if (finish_async(&async)) {
729 err = error(_("external filter '%s' failed"), cmd);
732 if (!err) {
733 strbuf_swap(dst, &nbuf);
735 strbuf_release(&nbuf);
736 return !err;
739 #define CAP_CLEAN (1u<<0)
740 #define CAP_SMUDGE (1u<<1)
741 #define CAP_DELAY (1u<<2)
743 struct cmd2process {
744 struct subprocess_entry subprocess; /* must be the first member! */
745 unsigned int supported_capabilities;
748 static int subprocess_map_initialized;
749 static struct hashmap subprocess_map;
751 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
753 static int versions[] = {2, 0};
754 static struct subprocess_capability capabilities[] = {
755 { "clean", CAP_CLEAN },
756 { "smudge", CAP_SMUDGE },
757 { "delay", CAP_DELAY },
758 { NULL, 0 }
760 struct cmd2process *entry = (struct cmd2process *)subprocess;
761 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
762 capabilities,
763 &entry->supported_capabilities);
766 static void handle_filter_error(const struct strbuf *filter_status,
767 struct cmd2process *entry,
768 const unsigned int wanted_capability)
770 if (!strcmp(filter_status->buf, "error"))
771 ; /* The filter signaled a problem with the file. */
772 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
774 * The filter signaled a permanent problem. Don't try to filter
775 * files with the same command for the lifetime of the current
776 * Git process.
778 entry->supported_capabilities &= ~wanted_capability;
779 } else {
781 * Something went wrong with the protocol filter.
782 * Force shutdown and restart if another blob requires filtering.
784 error(_("external filter '%s' failed"), entry->subprocess.cmd);
785 subprocess_stop(&subprocess_map, &entry->subprocess);
786 free(entry);
790 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
791 int fd, struct strbuf *dst, const char *cmd,
792 const unsigned int wanted_capability,
793 const struct checkout_metadata *meta,
794 struct delayed_checkout *dco)
796 int err;
797 int can_delay = 0;
798 struct cmd2process *entry;
799 struct child_process *process;
800 struct strbuf nbuf = STRBUF_INIT;
801 struct strbuf filter_status = STRBUF_INIT;
802 const char *filter_type;
804 if (!subprocess_map_initialized) {
805 subprocess_map_initialized = 1;
806 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
807 entry = NULL;
808 } else {
809 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
812 fflush(NULL);
814 if (!entry) {
815 entry = xmalloc(sizeof(*entry));
816 entry->supported_capabilities = 0;
818 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
819 free(entry);
820 return 0;
823 process = &entry->subprocess.process;
825 if (!(entry->supported_capabilities & wanted_capability))
826 return 0;
828 if (wanted_capability & CAP_CLEAN)
829 filter_type = "clean";
830 else if (wanted_capability & CAP_SMUDGE)
831 filter_type = "smudge";
832 else
833 die(_("unexpected filter type"));
835 sigchain_push(SIGPIPE, SIG_IGN);
837 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
838 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
839 if (err)
840 goto done;
842 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
843 if (err) {
844 error(_("path name too long for external filter"));
845 goto done;
848 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
849 if (err)
850 goto done;
852 if (meta && meta->refname) {
853 err = packet_write_fmt_gently(process->in, "ref=%s\n", meta->refname);
854 if (err)
855 goto done;
858 if (meta && !is_null_oid(&meta->treeish)) {
859 err = packet_write_fmt_gently(process->in, "treeish=%s\n", oid_to_hex(&meta->treeish));
860 if (err)
861 goto done;
864 if (meta && !is_null_oid(&meta->blob)) {
865 err = packet_write_fmt_gently(process->in, "blob=%s\n", oid_to_hex(&meta->blob));
866 if (err)
867 goto done;
870 if ((entry->supported_capabilities & CAP_DELAY) &&
871 dco && dco->state == CE_CAN_DELAY) {
872 can_delay = 1;
873 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
874 if (err)
875 goto done;
878 err = packet_flush_gently(process->in);
879 if (err)
880 goto done;
882 if (fd >= 0)
883 err = write_packetized_from_fd_no_flush(fd, process->in);
884 else
885 err = write_packetized_from_buf_no_flush(src, len, process->in);
886 if (err)
887 goto done;
889 err = packet_flush_gently(process->in);
890 if (err)
891 goto done;
893 err = subprocess_read_status(process->out, &filter_status);
894 if (err)
895 goto done;
897 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
898 string_list_insert(&dco->filters, cmd);
899 string_list_insert(&dco->paths, path);
900 } else {
901 /* The filter got the blob and wants to send us a response. */
902 err = strcmp(filter_status.buf, "success");
903 if (err)
904 goto done;
906 err = read_packetized_to_strbuf(process->out, &nbuf,
907 PACKET_READ_GENTLE_ON_EOF) < 0;
908 if (err)
909 goto done;
911 err = subprocess_read_status(process->out, &filter_status);
912 if (err)
913 goto done;
915 err = strcmp(filter_status.buf, "success");
918 done:
919 sigchain_pop(SIGPIPE);
921 if (err)
922 handle_filter_error(&filter_status, entry, wanted_capability);
923 else
924 strbuf_swap(dst, &nbuf);
925 strbuf_release(&nbuf);
926 strbuf_release(&filter_status);
927 return !err;
931 int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
933 int err;
934 char *line;
935 struct cmd2process *entry;
936 struct child_process *process;
937 struct strbuf filter_status = STRBUF_INIT;
939 assert(subprocess_map_initialized);
940 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
941 if (!entry) {
942 error(_("external filter '%s' is not available anymore although "
943 "not all paths have been filtered"), cmd);
944 return 0;
946 process = &entry->subprocess.process;
947 sigchain_push(SIGPIPE, SIG_IGN);
949 err = packet_write_fmt_gently(
950 process->in, "command=list_available_blobs\n");
951 if (err)
952 goto done;
954 err = packet_flush_gently(process->in);
955 if (err)
956 goto done;
958 while ((line = packet_read_line(process->out, NULL))) {
959 const char *path;
960 if (skip_prefix(line, "pathname=", &path))
961 string_list_insert(available_paths, xstrdup(path));
962 else
963 ; /* ignore unknown keys */
966 err = subprocess_read_status(process->out, &filter_status);
967 if (err)
968 goto done;
970 err = strcmp(filter_status.buf, "success");
972 done:
973 sigchain_pop(SIGPIPE);
975 if (err)
976 handle_filter_error(&filter_status, entry, 0);
977 strbuf_release(&filter_status);
978 return !err;
981 static struct convert_driver {
982 const char *name;
983 struct convert_driver *next;
984 char *smudge;
985 char *clean;
986 char *process;
987 int required;
988 } *user_convert, **user_convert_tail;
990 static int apply_filter(const char *path, const char *src, size_t len,
991 int fd, struct strbuf *dst, struct convert_driver *drv,
992 const unsigned int wanted_capability,
993 const struct checkout_metadata *meta,
994 struct delayed_checkout *dco)
996 const char *cmd = NULL;
998 if (!drv)
999 return 0;
1001 if (!dst)
1002 return 1;
1004 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
1005 cmd = drv->clean;
1006 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
1007 cmd = drv->smudge;
1009 if (cmd && *cmd)
1010 return apply_single_file_filter(path, src, len, fd, dst, cmd);
1011 else if (drv->process && *drv->process)
1012 return apply_multi_file_filter(path, src, len, fd, dst,
1013 drv->process, wanted_capability, meta, dco);
1015 return 0;
1018 static int read_convert_config(const char *var, const char *value,
1019 const struct config_context *ctx UNUSED,
1020 void *cb UNUSED)
1022 const char *key, *name;
1023 size_t namelen;
1024 struct convert_driver *drv;
1027 * External conversion drivers are configured using
1028 * "filter.<name>.variable".
1030 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
1031 return 0;
1032 for (drv = user_convert; drv; drv = drv->next)
1033 if (!xstrncmpz(drv->name, name, namelen))
1034 break;
1035 if (!drv) {
1036 CALLOC_ARRAY(drv, 1);
1037 drv->name = xmemdupz(name, namelen);
1038 *user_convert_tail = drv;
1039 user_convert_tail = &(drv->next);
1043 * filter.<name>.smudge and filter.<name>.clean specifies
1044 * the command line:
1046 * command-line
1048 * The command-line will not be interpolated in any way.
1051 if (!strcmp("smudge", key))
1052 return git_config_string(&drv->smudge, var, value);
1054 if (!strcmp("clean", key))
1055 return git_config_string(&drv->clean, var, value);
1057 if (!strcmp("process", key))
1058 return git_config_string(&drv->process, var, value);
1060 if (!strcmp("required", key)) {
1061 drv->required = git_config_bool(var, value);
1062 return 0;
1065 return 0;
1068 static int count_ident(const char *cp, unsigned long size)
1071 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
1073 int cnt = 0;
1074 char ch;
1076 while (size) {
1077 ch = *cp++;
1078 size--;
1079 if (ch != '$')
1080 continue;
1081 if (size < 3)
1082 break;
1083 if (memcmp("Id", cp, 2))
1084 continue;
1085 ch = cp[2];
1086 cp += 3;
1087 size -= 3;
1088 if (ch == '$')
1089 cnt++; /* $Id$ */
1090 if (ch != ':')
1091 continue;
1094 * "$Id: ... "; scan up to the closing dollar sign and discard.
1096 while (size) {
1097 ch = *cp++;
1098 size--;
1099 if (ch == '$') {
1100 cnt++;
1101 break;
1103 if (ch == '\n')
1104 break;
1107 return cnt;
1110 static int ident_to_git(const char *src, size_t len,
1111 struct strbuf *buf, int ident)
1113 char *dst, *dollar;
1115 if (!ident || (src && !count_ident(src, len)))
1116 return 0;
1118 if (!buf)
1119 return 1;
1121 /* only grow if not in place */
1122 if (strbuf_avail(buf) + buf->len < len)
1123 strbuf_grow(buf, len - buf->len);
1124 dst = buf->buf;
1125 for (;;) {
1126 dollar = memchr(src, '$', len);
1127 if (!dollar)
1128 break;
1129 memmove(dst, src, dollar + 1 - src);
1130 dst += dollar + 1 - src;
1131 len -= dollar + 1 - src;
1132 src = dollar + 1;
1134 if (len > 3 && !memcmp(src, "Id:", 3)) {
1135 dollar = memchr(src + 3, '$', len - 3);
1136 if (!dollar)
1137 break;
1138 if (memchr(src + 3, '\n', dollar - src - 3)) {
1139 /* Line break before the next dollar. */
1140 continue;
1143 memcpy(dst, "Id$", 3);
1144 dst += 3;
1145 len -= dollar + 1 - src;
1146 src = dollar + 1;
1149 memmove(dst, src, len);
1150 strbuf_setlen(buf, dst + len - buf->buf);
1151 return 1;
1154 static int ident_to_worktree(const char *src, size_t len,
1155 struct strbuf *buf, int ident)
1157 struct object_id oid;
1158 char *to_free = NULL, *dollar, *spc;
1159 int cnt;
1161 if (!ident)
1162 return 0;
1164 cnt = count_ident(src, len);
1165 if (!cnt)
1166 return 0;
1168 /* are we "faking" in place editing ? */
1169 if (src == buf->buf)
1170 to_free = strbuf_detach(buf, NULL);
1171 hash_object_file(the_hash_algo, src, len, OBJ_BLOB, &oid);
1173 strbuf_grow(buf, len + cnt * (the_hash_algo->hexsz + 3));
1174 for (;;) {
1175 /* step 1: run to the next '$' */
1176 dollar = memchr(src, '$', len);
1177 if (!dollar)
1178 break;
1179 strbuf_add(buf, src, dollar + 1 - src);
1180 len -= dollar + 1 - src;
1181 src = dollar + 1;
1183 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1184 if (len < 3 || memcmp("Id", src, 2))
1185 continue;
1187 /* step 3: skip over Id$ or Id:xxxxx$ */
1188 if (src[2] == '$') {
1189 src += 3;
1190 len -= 3;
1191 } else if (src[2] == ':') {
1193 * It's possible that an expanded Id has crept its way into the
1194 * repository, we cope with that by stripping the expansion out.
1195 * This is probably not a good idea, since it will cause changes
1196 * on checkout, which won't go away by stash, but let's keep it
1197 * for git-style ids.
1199 dollar = memchr(src + 3, '$', len - 3);
1200 if (!dollar) {
1201 /* incomplete keyword, no more '$', so just quit the loop */
1202 break;
1205 if (memchr(src + 3, '\n', dollar - src - 3)) {
1206 /* Line break before the next dollar. */
1207 continue;
1210 spc = memchr(src + 4, ' ', dollar - src - 4);
1211 if (spc && spc < dollar-1) {
1212 /* There are spaces in unexpected places.
1213 * This is probably an id from some other
1214 * versioning system. Keep it for now.
1216 continue;
1219 len -= dollar + 1 - src;
1220 src = dollar + 1;
1221 } else {
1222 /* it wasn't a "Id$" or "Id:xxxx$" */
1223 continue;
1226 /* step 4: substitute */
1227 strbuf_addstr(buf, "Id: ");
1228 strbuf_addstr(buf, oid_to_hex(&oid));
1229 strbuf_addstr(buf, " $");
1231 strbuf_add(buf, src, len);
1233 free(to_free);
1234 return 1;
1237 static const char *git_path_check_encoding(struct attr_check_item *check)
1239 const char *value = check->value;
1241 if (ATTR_UNSET(value) || !strlen(value))
1242 return NULL;
1244 if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
1245 die(_("true/false are no valid working-tree-encodings"));
1248 /* Don't encode to the default encoding */
1249 if (same_encoding(value, default_encoding))
1250 return NULL;
1252 return value;
1255 static enum convert_crlf_action git_path_check_crlf(struct attr_check_item *check)
1257 const char *value = check->value;
1259 if (ATTR_TRUE(value))
1260 return CRLF_TEXT;
1261 else if (ATTR_FALSE(value))
1262 return CRLF_BINARY;
1263 else if (ATTR_UNSET(value))
1265 else if (!strcmp(value, "input"))
1266 return CRLF_TEXT_INPUT;
1267 else if (!strcmp(value, "auto"))
1268 return CRLF_AUTO;
1269 return CRLF_UNDEFINED;
1272 static enum eol git_path_check_eol(struct attr_check_item *check)
1274 const char *value = check->value;
1276 if (ATTR_UNSET(value))
1278 else if (!strcmp(value, "lf"))
1279 return EOL_LF;
1280 else if (!strcmp(value, "crlf"))
1281 return EOL_CRLF;
1282 return EOL_UNSET;
1285 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
1287 const char *value = check->value;
1288 struct convert_driver *drv;
1290 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1291 return NULL;
1292 for (drv = user_convert; drv; drv = drv->next)
1293 if (!strcmp(value, drv->name))
1294 return drv;
1295 return NULL;
1298 static int git_path_check_ident(struct attr_check_item *check)
1300 const char *value = check->value;
1302 return !!ATTR_TRUE(value);
1305 static struct attr_check *check;
1307 void convert_attrs(struct index_state *istate,
1308 struct conv_attrs *ca, const char *path)
1310 struct attr_check_item *ccheck = NULL;
1312 if (!check) {
1313 check = attr_check_initl("crlf", "ident", "filter",
1314 "eol", "text", "working-tree-encoding",
1315 NULL);
1316 user_convert_tail = &user_convert;
1317 git_config(read_convert_config, NULL);
1320 git_check_attr(istate, path, check);
1321 ccheck = check->items;
1322 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1323 if (ca->crlf_action == CRLF_UNDEFINED)
1324 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1325 ca->ident = git_path_check_ident(ccheck + 1);
1326 ca->drv = git_path_check_convert(ccheck + 2);
1327 if (ca->crlf_action != CRLF_BINARY) {
1328 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1329 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1330 ca->crlf_action = CRLF_AUTO_INPUT;
1331 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1332 ca->crlf_action = CRLF_AUTO_CRLF;
1333 else if (eol_attr == EOL_LF)
1334 ca->crlf_action = CRLF_TEXT_INPUT;
1335 else if (eol_attr == EOL_CRLF)
1336 ca->crlf_action = CRLF_TEXT_CRLF;
1338 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
1340 /* Save attr and make a decision for action */
1341 ca->attr_action = ca->crlf_action;
1342 if (ca->crlf_action == CRLF_TEXT)
1343 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1344 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1345 ca->crlf_action = CRLF_BINARY;
1346 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1347 ca->crlf_action = CRLF_AUTO_CRLF;
1348 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1349 ca->crlf_action = CRLF_AUTO_INPUT;
1352 void reset_parsed_attributes(void)
1354 struct convert_driver *drv, *next;
1356 attr_check_free(check);
1357 check = NULL;
1358 reset_merge_attributes();
1360 for (drv = user_convert; drv; drv = next) {
1361 next = drv->next;
1362 free((void *)drv->name);
1363 free(drv);
1365 user_convert = NULL;
1366 user_convert_tail = NULL;
1369 int would_convert_to_git_filter_fd(struct index_state *istate, const char *path)
1371 struct conv_attrs ca;
1373 convert_attrs(istate, &ca, path);
1374 if (!ca.drv)
1375 return 0;
1378 * Apply a filter to an fd only if the filter is required to succeed.
1379 * We must die if the filter fails, because the original data before
1380 * filtering is not available.
1382 if (!ca.drv->required)
1383 return 0;
1385 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL, NULL);
1388 const char *get_convert_attr_ascii(struct index_state *istate, const char *path)
1390 struct conv_attrs ca;
1392 convert_attrs(istate, &ca, path);
1393 switch (ca.attr_action) {
1394 case CRLF_UNDEFINED:
1395 return "";
1396 case CRLF_BINARY:
1397 return "-text";
1398 case CRLF_TEXT:
1399 return "text";
1400 case CRLF_TEXT_INPUT:
1401 return "text eol=lf";
1402 case CRLF_TEXT_CRLF:
1403 return "text eol=crlf";
1404 case CRLF_AUTO:
1405 return "text=auto";
1406 case CRLF_AUTO_CRLF:
1407 return "text=auto eol=crlf";
1408 case CRLF_AUTO_INPUT:
1409 return "text=auto eol=lf";
1411 return "";
1414 int convert_to_git(struct index_state *istate,
1415 const char *path, const char *src, size_t len,
1416 struct strbuf *dst, int conv_flags)
1418 int ret = 0;
1419 struct conv_attrs ca;
1421 convert_attrs(istate, &ca, path);
1423 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL, NULL);
1424 if (!ret && ca.drv && ca.drv->required)
1425 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
1427 if (ret && dst) {
1428 src = dst->buf;
1429 len = dst->len;
1432 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1433 if (ret && dst) {
1434 src = dst->buf;
1435 len = dst->len;
1438 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1439 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
1440 if (ret && dst) {
1441 src = dst->buf;
1442 len = dst->len;
1445 return ret | ident_to_git(src, len, dst, ca.ident);
1448 void convert_to_git_filter_fd(struct index_state *istate,
1449 const char *path, int fd, struct strbuf *dst,
1450 int conv_flags)
1452 struct conv_attrs ca;
1453 convert_attrs(istate, &ca, path);
1455 assert(ca.drv);
1457 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL, NULL))
1458 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
1460 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
1461 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
1462 ident_to_git(dst->buf, dst->len, dst, ca.ident);
1465 static int convert_to_working_tree_ca_internal(const struct conv_attrs *ca,
1466 const char *path, const char *src,
1467 size_t len, struct strbuf *dst,
1468 int normalizing,
1469 const struct checkout_metadata *meta,
1470 struct delayed_checkout *dco)
1472 int ret = 0, ret_filter = 0;
1474 ret |= ident_to_worktree(src, len, dst, ca->ident);
1475 if (ret) {
1476 src = dst->buf;
1477 len = dst->len;
1480 * CRLF conversion can be skipped if normalizing, unless there
1481 * is a smudge or process filter (even if the process filter doesn't
1482 * support smudge). The filters might expect CRLFs.
1484 if ((ca->drv && (ca->drv->smudge || ca->drv->process)) || !normalizing) {
1485 ret |= crlf_to_worktree(src, len, dst, ca->crlf_action);
1486 if (ret) {
1487 src = dst->buf;
1488 len = dst->len;
1492 ret |= encode_to_worktree(path, src, len, dst, ca->working_tree_encoding);
1493 if (ret) {
1494 src = dst->buf;
1495 len = dst->len;
1498 ret_filter = apply_filter(
1499 path, src, len, -1, dst, ca->drv, CAP_SMUDGE, meta, dco);
1500 if (!ret_filter && ca->drv && ca->drv->required)
1501 die(_("%s: smudge filter %s failed"), path, ca->drv->name);
1503 return ret | ret_filter;
1506 int async_convert_to_working_tree_ca(const struct conv_attrs *ca,
1507 const char *path, const char *src,
1508 size_t len, struct strbuf *dst,
1509 const struct checkout_metadata *meta,
1510 void *dco)
1512 return convert_to_working_tree_ca_internal(ca, path, src, len, dst, 0,
1513 meta, dco);
1516 int convert_to_working_tree_ca(const struct conv_attrs *ca,
1517 const char *path, const char *src,
1518 size_t len, struct strbuf *dst,
1519 const struct checkout_metadata *meta)
1521 return convert_to_working_tree_ca_internal(ca, path, src, len, dst, 0,
1522 meta, NULL);
1525 int renormalize_buffer(struct index_state *istate, const char *path,
1526 const char *src, size_t len, struct strbuf *dst)
1528 struct conv_attrs ca;
1529 int ret;
1531 convert_attrs(istate, &ca, path);
1532 ret = convert_to_working_tree_ca_internal(&ca, path, src, len, dst, 1,
1533 NULL, NULL);
1534 if (ret) {
1535 src = dst->buf;
1536 len = dst->len;
1538 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
1541 /*****************************************************************
1543 * Streaming conversion support
1545 *****************************************************************/
1547 typedef int (*filter_fn)(struct stream_filter *,
1548 const char *input, size_t *isize_p,
1549 char *output, size_t *osize_p);
1550 typedef void (*free_fn)(struct stream_filter *);
1552 struct stream_filter_vtbl {
1553 filter_fn filter;
1554 free_fn free;
1557 struct stream_filter {
1558 struct stream_filter_vtbl *vtbl;
1561 static int null_filter_fn(struct stream_filter *filter UNUSED,
1562 const char *input, size_t *isize_p,
1563 char *output, size_t *osize_p)
1565 size_t count;
1567 if (!input)
1568 return 0; /* we do not keep any states */
1569 count = *isize_p;
1570 if (*osize_p < count)
1571 count = *osize_p;
1572 if (count) {
1573 memmove(output, input, count);
1574 *isize_p -= count;
1575 *osize_p -= count;
1577 return 0;
1580 static void null_free_fn(struct stream_filter *filter UNUSED)
1582 ; /* nothing -- null instances are shared */
1585 static struct stream_filter_vtbl null_vtbl = {
1586 .filter = null_filter_fn,
1587 .free = null_free_fn,
1590 static struct stream_filter null_filter_singleton = {
1591 .vtbl = &null_vtbl,
1594 int is_null_stream_filter(struct stream_filter *filter)
1596 return filter == &null_filter_singleton;
1601 * LF-to-CRLF filter
1604 struct lf_to_crlf_filter {
1605 struct stream_filter filter;
1606 unsigned has_held:1;
1607 char held;
1610 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1611 const char *input, size_t *isize_p,
1612 char *output, size_t *osize_p)
1614 size_t count, o = 0;
1615 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1618 * We may be holding onto the CR to see if it is followed by a
1619 * LF, in which case we would need to go to the main loop.
1620 * Otherwise, just emit it to the output stream.
1622 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1623 output[o++] = lf_to_crlf->held;
1624 lf_to_crlf->has_held = 0;
1627 /* We are told to drain */
1628 if (!input) {
1629 *osize_p -= o;
1630 return 0;
1633 count = *isize_p;
1634 if (count || lf_to_crlf->has_held) {
1635 size_t i;
1636 int was_cr = 0;
1638 if (lf_to_crlf->has_held) {
1639 was_cr = 1;
1640 lf_to_crlf->has_held = 0;
1643 for (i = 0; o < *osize_p && i < count; i++) {
1644 char ch = input[i];
1646 if (ch == '\n') {
1647 output[o++] = '\r';
1648 } else if (was_cr) {
1650 * Previous round saw CR and it is not followed
1651 * by a LF; emit the CR before processing the
1652 * current character.
1654 output[o++] = '\r';
1658 * We may have consumed the last output slot,
1659 * in which case we need to break out of this
1660 * loop; hold the current character before
1661 * returning.
1663 if (*osize_p <= o) {
1664 lf_to_crlf->has_held = 1;
1665 lf_to_crlf->held = ch;
1666 continue; /* break but increment i */
1669 if (ch == '\r') {
1670 was_cr = 1;
1671 continue;
1674 was_cr = 0;
1675 output[o++] = ch;
1678 *osize_p -= o;
1679 *isize_p -= i;
1681 if (!lf_to_crlf->has_held && was_cr) {
1682 lf_to_crlf->has_held = 1;
1683 lf_to_crlf->held = '\r';
1686 return 0;
1689 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1691 free(filter);
1694 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1695 .filter = lf_to_crlf_filter_fn,
1696 .free = lf_to_crlf_free_fn,
1699 static struct stream_filter *lf_to_crlf_filter(void)
1701 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1703 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1704 return (struct stream_filter *)lf_to_crlf;
1708 * Cascade filter
1710 #define FILTER_BUFFER 1024
1711 struct cascade_filter {
1712 struct stream_filter filter;
1713 struct stream_filter *one;
1714 struct stream_filter *two;
1715 char buf[FILTER_BUFFER];
1716 int end, ptr;
1719 static int cascade_filter_fn(struct stream_filter *filter,
1720 const char *input, size_t *isize_p,
1721 char *output, size_t *osize_p)
1723 struct cascade_filter *cas = (struct cascade_filter *) filter;
1724 size_t filled = 0;
1725 size_t sz = *osize_p;
1726 size_t to_feed, remaining;
1729 * input -- (one) --> buf -- (two) --> output
1731 while (filled < sz) {
1732 remaining = sz - filled;
1734 /* do we already have something to feed two with? */
1735 if (cas->ptr < cas->end) {
1736 to_feed = cas->end - cas->ptr;
1737 if (stream_filter(cas->two,
1738 cas->buf + cas->ptr, &to_feed,
1739 output + filled, &remaining))
1740 return -1;
1741 cas->ptr += (cas->end - cas->ptr) - to_feed;
1742 filled = sz - remaining;
1743 continue;
1746 /* feed one from upstream and have it emit into our buffer */
1747 to_feed = input ? *isize_p : 0;
1748 if (input && !to_feed)
1749 break;
1750 remaining = sizeof(cas->buf);
1751 if (stream_filter(cas->one,
1752 input, &to_feed,
1753 cas->buf, &remaining))
1754 return -1;
1755 cas->end = sizeof(cas->buf) - remaining;
1756 cas->ptr = 0;
1757 if (input) {
1758 size_t fed = *isize_p - to_feed;
1759 *isize_p -= fed;
1760 input += fed;
1763 /* do we know that we drained one completely? */
1764 if (input || cas->end)
1765 continue;
1767 /* tell two to drain; we have nothing more to give it */
1768 to_feed = 0;
1769 remaining = sz - filled;
1770 if (stream_filter(cas->two,
1771 NULL, &to_feed,
1772 output + filled, &remaining))
1773 return -1;
1774 if (remaining == (sz - filled))
1775 break; /* completely drained two */
1776 filled = sz - remaining;
1778 *osize_p -= filled;
1779 return 0;
1782 static void cascade_free_fn(struct stream_filter *filter)
1784 struct cascade_filter *cas = (struct cascade_filter *)filter;
1785 free_stream_filter(cas->one);
1786 free_stream_filter(cas->two);
1787 free(filter);
1790 static struct stream_filter_vtbl cascade_vtbl = {
1791 .filter = cascade_filter_fn,
1792 .free = cascade_free_fn,
1795 static struct stream_filter *cascade_filter(struct stream_filter *one,
1796 struct stream_filter *two)
1798 struct cascade_filter *cascade;
1800 if (!one || is_null_stream_filter(one))
1801 return two;
1802 if (!two || is_null_stream_filter(two))
1803 return one;
1805 cascade = xmalloc(sizeof(*cascade));
1806 cascade->one = one;
1807 cascade->two = two;
1808 cascade->end = cascade->ptr = 0;
1809 cascade->filter.vtbl = &cascade_vtbl;
1810 return (struct stream_filter *)cascade;
1814 * ident filter
1816 #define IDENT_DRAINING (-1)
1817 #define IDENT_SKIPPING (-2)
1818 struct ident_filter {
1819 struct stream_filter filter;
1820 struct strbuf left;
1821 int state;
1822 char ident[GIT_MAX_HEXSZ + 5]; /* ": x40 $" */
1825 static int is_foreign_ident(const char *str)
1827 int i;
1829 if (!skip_prefix(str, "$Id: ", &str))
1830 return 0;
1831 for (i = 0; str[i]; i++) {
1832 if (isspace(str[i]) && str[i+1] != '$')
1833 return 1;
1835 return 0;
1838 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1840 size_t to_drain = ident->left.len;
1842 if (*osize_p < to_drain)
1843 to_drain = *osize_p;
1844 if (to_drain) {
1845 memcpy(*output_p, ident->left.buf, to_drain);
1846 strbuf_remove(&ident->left, 0, to_drain);
1847 *output_p += to_drain;
1848 *osize_p -= to_drain;
1850 if (!ident->left.len)
1851 ident->state = 0;
1854 static int ident_filter_fn(struct stream_filter *filter,
1855 const char *input, size_t *isize_p,
1856 char *output, size_t *osize_p)
1858 struct ident_filter *ident = (struct ident_filter *)filter;
1859 static const char head[] = "$Id";
1861 if (!input) {
1862 /* drain upon eof */
1863 switch (ident->state) {
1864 default:
1865 strbuf_add(&ident->left, head, ident->state);
1866 /* fallthrough */
1867 case IDENT_SKIPPING:
1868 /* fallthrough */
1869 case IDENT_DRAINING:
1870 ident_drain(ident, &output, osize_p);
1872 return 0;
1875 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1876 int ch;
1878 if (ident->state == IDENT_DRAINING) {
1879 ident_drain(ident, &output, osize_p);
1880 if (!*osize_p)
1881 break;
1882 continue;
1885 ch = *(input++);
1886 (*isize_p)--;
1888 if (ident->state == IDENT_SKIPPING) {
1890 * Skipping until '$' or LF, but keeping them
1891 * in case it is a foreign ident.
1893 strbuf_addch(&ident->left, ch);
1894 if (ch != '\n' && ch != '$')
1895 continue;
1896 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1897 strbuf_setlen(&ident->left, sizeof(head) - 1);
1898 strbuf_addstr(&ident->left, ident->ident);
1900 ident->state = IDENT_DRAINING;
1901 continue;
1904 if (ident->state < sizeof(head) &&
1905 head[ident->state] == ch) {
1906 ident->state++;
1907 continue;
1910 if (ident->state)
1911 strbuf_add(&ident->left, head, ident->state);
1912 if (ident->state == sizeof(head) - 1) {
1913 if (ch != ':' && ch != '$') {
1914 strbuf_addch(&ident->left, ch);
1915 ident->state = 0;
1916 continue;
1919 if (ch == ':') {
1920 strbuf_addch(&ident->left, ch);
1921 ident->state = IDENT_SKIPPING;
1922 } else {
1923 strbuf_addstr(&ident->left, ident->ident);
1924 ident->state = IDENT_DRAINING;
1926 continue;
1929 strbuf_addch(&ident->left, ch);
1930 ident->state = IDENT_DRAINING;
1932 return 0;
1935 static void ident_free_fn(struct stream_filter *filter)
1937 struct ident_filter *ident = (struct ident_filter *)filter;
1938 strbuf_release(&ident->left);
1939 free(filter);
1942 static struct stream_filter_vtbl ident_vtbl = {
1943 .filter = ident_filter_fn,
1944 .free = ident_free_fn,
1947 static struct stream_filter *ident_filter(const struct object_id *oid)
1949 struct ident_filter *ident = xmalloc(sizeof(*ident));
1951 xsnprintf(ident->ident, sizeof(ident->ident),
1952 ": %s $", oid_to_hex(oid));
1953 strbuf_init(&ident->left, 0);
1954 ident->filter.vtbl = &ident_vtbl;
1955 ident->state = 0;
1956 return (struct stream_filter *)ident;
1960 * Return an appropriately constructed filter for the given ca, or NULL if
1961 * the contents cannot be filtered without reading the whole thing
1962 * in-core.
1964 * Note that you would be crazy to set CRLF, smudge/clean or ident to a
1965 * large binary blob you would want us not to slurp into the memory!
1967 struct stream_filter *get_stream_filter_ca(const struct conv_attrs *ca,
1968 const struct object_id *oid)
1970 struct stream_filter *filter = NULL;
1972 if (classify_conv_attrs(ca) != CA_CLASS_STREAMABLE)
1973 return NULL;
1975 if (ca->ident)
1976 filter = ident_filter(oid);
1978 if (output_eol(ca->crlf_action) == EOL_CRLF)
1979 filter = cascade_filter(filter, lf_to_crlf_filter());
1980 else
1981 filter = cascade_filter(filter, &null_filter_singleton);
1983 return filter;
1986 struct stream_filter *get_stream_filter(struct index_state *istate,
1987 const char *path,
1988 const struct object_id *oid)
1990 struct conv_attrs ca;
1991 convert_attrs(istate, &ca, path);
1992 return get_stream_filter_ca(&ca, oid);
1995 void free_stream_filter(struct stream_filter *filter)
1997 filter->vtbl->free(filter);
2000 int stream_filter(struct stream_filter *filter,
2001 const char *input, size_t *isize_p,
2002 char *output, size_t *osize_p)
2004 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
2007 void init_checkout_metadata(struct checkout_metadata *meta, const char *refname,
2008 const struct object_id *treeish,
2009 const struct object_id *blob)
2011 memset(meta, 0, sizeof(*meta));
2012 if (refname)
2013 meta->refname = refname;
2014 if (treeish)
2015 oidcpy(&meta->treeish, treeish);
2016 if (blob)
2017 oidcpy(&meta->blob, blob);
2020 void clone_checkout_metadata(struct checkout_metadata *dst,
2021 const struct checkout_metadata *src,
2022 const struct object_id *blob)
2024 memcpy(dst, src, sizeof(*dst));
2025 if (blob)
2026 oidcpy(&dst->blob, blob);
2029 enum conv_attrs_classification classify_conv_attrs(const struct conv_attrs *ca)
2031 if (ca->drv) {
2032 if (ca->drv->process)
2033 return CA_CLASS_INCORE_PROCESS;
2034 if (ca->drv->smudge || ca->drv->clean)
2035 return CA_CLASS_INCORE_FILTER;
2038 if (ca->working_tree_encoding)
2039 return CA_CLASS_INCORE;
2041 if (ca->crlf_action == CRLF_AUTO || ca->crlf_action == CRLF_AUTO_CRLF)
2042 return CA_CLASS_INCORE;
2044 return CA_CLASS_STREAMABLE;