builtin.h: remove unneccessary includes
[git.git] / convert.c
blob89aeb9e72b9e483c676af97a9d7e7c632fe3a8fa
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.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 "ll-merge.h"
19 #include "wrapper.h"
22 * convert.c - convert a file when checking it out and checking it in.
24 * This should use the pathname to decide on whether it wants to do some
25 * more interesting conversions (automatic gzip/unzip, general format
26 * conversions etc etc), but by default it just does automatic CRLF<->LF
27 * translation when the "text" attribute or "auto_crlf" option is set.
30 /* Stat bits: When BIN is set, the txt bits are unset */
31 #define CONVERT_STAT_BITS_TXT_LF 0x1
32 #define CONVERT_STAT_BITS_TXT_CRLF 0x2
33 #define CONVERT_STAT_BITS_BIN 0x4
35 struct text_stat {
36 /* NUL, CR, LF and CRLF counts */
37 unsigned nul, lonecr, lonelf, crlf;
39 /* These are just approximations! */
40 unsigned printable, nonprintable;
43 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
45 unsigned long i;
47 memset(stats, 0, sizeof(*stats));
49 for (i = 0; i < size; i++) {
50 unsigned char c = buf[i];
51 if (c == '\r') {
52 if (i+1 < size && buf[i+1] == '\n') {
53 stats->crlf++;
54 i++;
55 } else
56 stats->lonecr++;
57 continue;
59 if (c == '\n') {
60 stats->lonelf++;
61 continue;
63 if (c == 127)
64 /* DEL */
65 stats->nonprintable++;
66 else if (c < 32) {
67 switch (c) {
68 /* BS, HT, ESC and FF */
69 case '\b': case '\t': case '\033': case '\014':
70 stats->printable++;
71 break;
72 case 0:
73 stats->nul++;
74 /* fall through */
75 default:
76 stats->nonprintable++;
79 else
80 stats->printable++;
83 /* If file ends with EOF then don't count this EOF as non-printable. */
84 if (size >= 1 && buf[size-1] == '\032')
85 stats->nonprintable--;
89 * The same heuristics as diff.c::mmfile_is_binary()
90 * We treat files with bare CR as binary
92 static int convert_is_binary(const struct text_stat *stats)
94 if (stats->lonecr)
95 return 1;
96 if (stats->nul)
97 return 1;
98 if ((stats->printable >> 7) < stats->nonprintable)
99 return 1;
100 return 0;
103 static unsigned int gather_convert_stats(const char *data, unsigned long size)
105 struct text_stat stats;
106 int ret = 0;
107 if (!data || !size)
108 return 0;
109 gather_stats(data, size, &stats);
110 if (convert_is_binary(&stats))
111 ret |= CONVERT_STAT_BITS_BIN;
112 if (stats.crlf)
113 ret |= CONVERT_STAT_BITS_TXT_CRLF;
114 if (stats.lonelf)
115 ret |= CONVERT_STAT_BITS_TXT_LF;
117 return ret;
120 static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
122 unsigned int convert_stats = gather_convert_stats(data, size);
124 if (convert_stats & CONVERT_STAT_BITS_BIN)
125 return "-text";
126 switch (convert_stats) {
127 case CONVERT_STAT_BITS_TXT_LF:
128 return "lf";
129 case CONVERT_STAT_BITS_TXT_CRLF:
130 return "crlf";
131 case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
132 return "mixed";
133 default:
134 return "none";
138 const char *get_cached_convert_stats_ascii(struct index_state *istate,
139 const char *path)
141 const char *ret;
142 unsigned long sz;
143 void *data = read_blob_data_from_index(istate, path, &sz);
144 ret = gather_convert_stats_ascii(data, sz);
145 free(data);
146 return ret;
149 const char *get_wt_convert_stats_ascii(const char *path)
151 const char *ret = "";
152 struct strbuf sb = STRBUF_INIT;
153 if (strbuf_read_file(&sb, path, 0) >= 0)
154 ret = gather_convert_stats_ascii(sb.buf, sb.len);
155 strbuf_release(&sb);
156 return ret;
159 static int text_eol_is_crlf(void)
161 if (auto_crlf == AUTO_CRLF_TRUE)
162 return 1;
163 else if (auto_crlf == AUTO_CRLF_INPUT)
164 return 0;
165 if (core_eol == EOL_CRLF)
166 return 1;
167 if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
168 return 1;
169 return 0;
172 static enum eol output_eol(enum convert_crlf_action crlf_action)
174 switch (crlf_action) {
175 case CRLF_BINARY:
176 return EOL_UNSET;
177 case CRLF_TEXT_CRLF:
178 return EOL_CRLF;
179 case CRLF_TEXT_INPUT:
180 return EOL_LF;
181 case CRLF_UNDEFINED:
182 case CRLF_AUTO_CRLF:
183 return EOL_CRLF;
184 case CRLF_AUTO_INPUT:
185 return EOL_LF;
186 case CRLF_TEXT:
187 case CRLF_AUTO:
188 /* fall through */
189 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
191 warning(_("illegal crlf_action %d"), (int)crlf_action);
192 return core_eol;
195 static void check_global_conv_flags_eol(const char *path,
196 struct text_stat *old_stats, struct text_stat *new_stats,
197 int conv_flags)
199 if (old_stats->crlf && !new_stats->crlf ) {
201 * CRLFs would not be restored by checkout
203 if (conv_flags & CONV_EOL_RNDTRP_DIE)
204 die(_("CRLF would be replaced by LF in %s"), path);
205 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
206 warning(_("in the working copy of '%s', CRLF will be"
207 " replaced by LF the next time Git touches"
208 " it"), path);
209 } else if (old_stats->lonelf && !new_stats->lonelf ) {
211 * CRLFs would be added by checkout
213 if (conv_flags & CONV_EOL_RNDTRP_DIE)
214 die(_("LF would be replaced by CRLF in %s"), path);
215 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
216 warning(_("in the working copy of '%s', LF will be"
217 " replaced by CRLF the next time Git touches"
218 " it"), path);
222 static int has_crlf_in_index(struct index_state *istate, const char *path)
224 unsigned long sz;
225 void *data;
226 const char *crp;
227 int has_crlf = 0;
229 data = read_blob_data_from_index(istate, path, &sz);
230 if (!data)
231 return 0;
233 crp = memchr(data, '\r', sz);
234 if (crp) {
235 unsigned int ret_stats;
236 ret_stats = gather_convert_stats(data, sz);
237 if (!(ret_stats & CONVERT_STAT_BITS_BIN) &&
238 (ret_stats & CONVERT_STAT_BITS_TXT_CRLF))
239 has_crlf = 1;
241 free(data);
242 return has_crlf;
245 static int will_convert_lf_to_crlf(struct text_stat *stats,
246 enum convert_crlf_action crlf_action)
248 if (output_eol(crlf_action) != EOL_CRLF)
249 return 0;
250 /* No "naked" LF? Nothing to convert, regardless. */
251 if (!stats->lonelf)
252 return 0;
254 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
255 /* If we have any CR or CRLF line endings, we do not touch it */
256 /* This is the new safer autocrlf-handling */
257 if (stats->lonecr || stats->crlf)
258 return 0;
260 if (convert_is_binary(stats))
261 return 0;
263 return 1;
267 static int validate_encoding(const char *path, const char *enc,
268 const char *data, size_t len, int die_on_error)
270 const char *stripped;
272 /* We only check for UTF here as UTF?? can be an alias for UTF-?? */
273 if (skip_iprefix(enc, "UTF", &stripped)) {
274 skip_prefix(stripped, "-", &stripped);
277 * Check for detectable errors in UTF encodings
279 if (has_prohibited_utf_bom(enc, data, len)) {
280 const char *error_msg = _(
281 "BOM is prohibited in '%s' if encoded as %s");
283 * This advice is shown for UTF-??BE and UTF-??LE encodings.
284 * We cut off the last two characters of the encoding name
285 * to generate the encoding name suitable for BOMs.
287 const char *advise_msg = _(
288 "The file '%s' contains a byte order "
289 "mark (BOM). Please use UTF-%.*s as "
290 "working-tree-encoding.");
291 int stripped_len = strlen(stripped) - strlen("BE");
292 advise(advise_msg, path, stripped_len, stripped);
293 if (die_on_error)
294 die(error_msg, path, enc);
295 else {
296 return error(error_msg, path, enc);
299 } else if (is_missing_required_utf_bom(enc, data, len)) {
300 const char *error_msg = _(
301 "BOM is required in '%s' if encoded as %s");
302 const char *advise_msg = _(
303 "The file '%s' is missing a byte order "
304 "mark (BOM). Please use UTF-%sBE or UTF-%sLE "
305 "(depending on the byte order) as "
306 "working-tree-encoding.");
307 advise(advise_msg, path, stripped, stripped);
308 if (die_on_error)
309 die(error_msg, path, enc);
310 else {
311 return error(error_msg, path, enc);
316 return 0;
319 static void trace_encoding(const char *context, const char *path,
320 const char *encoding, const char *buf, size_t len)
322 static struct trace_key coe = TRACE_KEY_INIT(WORKING_TREE_ENCODING);
323 struct strbuf trace = STRBUF_INIT;
324 int i;
326 strbuf_addf(&trace, "%s (%s, considered %s):\n", context, path, encoding);
327 for (i = 0; i < len && buf; ++i) {
328 strbuf_addf(
329 &trace, "| \033[2m%2i:\033[0m %2x \033[2m%c\033[0m%c",
331 (unsigned char) buf[i],
332 (buf[i] > 32 && buf[i] < 127 ? buf[i] : ' '),
333 ((i+1) % 8 && (i+1) < len ? ' ' : '\n')
336 strbuf_addchars(&trace, '\n', 1);
338 trace_strbuf(&coe, &trace);
339 strbuf_release(&trace);
342 static int check_roundtrip(const char *enc_name)
345 * check_roundtrip_encoding contains a string of comma and/or
346 * space separated encodings (eg. "UTF-16, ASCII, CP1125").
347 * Search for the given encoding in that string.
349 const char *found = strcasestr(check_roundtrip_encoding, enc_name);
350 const char *next;
351 int len;
352 if (!found)
353 return 0;
354 next = found + strlen(enc_name);
355 len = strlen(check_roundtrip_encoding);
356 return (found && (
358 * check that the found encoding is at the
359 * beginning of check_roundtrip_encoding or
360 * that it is prefixed with a space or comma
362 found == check_roundtrip_encoding || (
363 (isspace(found[-1]) || found[-1] == ',')
365 ) && (
367 * check that the found encoding is at the
368 * end of check_roundtrip_encoding or
369 * that it is suffixed with a space or comma
371 next == check_roundtrip_encoding + len || (
372 next < check_roundtrip_encoding + len &&
373 (isspace(next[0]) || next[0] == ',')
378 static const char *default_encoding = "UTF-8";
380 static int encode_to_git(const char *path, const char *src, size_t src_len,
381 struct strbuf *buf, const char *enc, int conv_flags)
383 char *dst;
384 size_t dst_len;
385 int die_on_error = conv_flags & CONV_WRITE_OBJECT;
388 * No encoding is specified or there is nothing to encode.
389 * Tell the caller that the content was not modified.
391 if (!enc || (src && !src_len))
392 return 0;
395 * Looks like we got called from "would_convert_to_git()".
396 * This means Git wants to know if it would encode (= modify!)
397 * the content. Let's answer with "yes", since an encoding was
398 * specified.
400 if (!buf && !src)
401 return 1;
403 if (validate_encoding(path, enc, src, src_len, die_on_error))
404 return 0;
406 trace_encoding("source", path, enc, src, src_len);
407 dst = reencode_string_len(src, src_len, default_encoding, enc,
408 &dst_len);
409 if (!dst) {
411 * We could add the blob "as-is" to Git. However, on checkout
412 * we would try to re-encode to the original encoding. This
413 * would fail and we would leave the user with a messed-up
414 * working tree. Let's try to avoid this by screaming loud.
416 const char* msg = _("failed to encode '%s' from %s to %s");
417 if (die_on_error)
418 die(msg, path, enc, default_encoding);
419 else {
420 error(msg, path, enc, default_encoding);
421 return 0;
424 trace_encoding("destination", path, default_encoding, dst, dst_len);
427 * UTF supports lossless conversion round tripping [1] and conversions
428 * between UTF and other encodings are mostly round trip safe as
429 * Unicode aims to be a superset of all other character encodings.
430 * However, certain encodings (e.g. SHIFT-JIS) are known to have round
431 * trip issues [2]. Check the round trip conversion for all encodings
432 * listed in core.checkRoundtripEncoding.
434 * The round trip check is only performed if content is written to Git.
435 * This ensures that no information is lost during conversion to/from
436 * the internal UTF-8 representation.
438 * Please note, the code below is not tested because I was not able to
439 * generate a faulty round trip without an iconv error. Iconv errors
440 * are already caught above.
442 * [1] http://unicode.org/faq/utf_bom.html#gen2
443 * [2] https://support.microsoft.com/en-us/help/170559/prb-conversion-problem-between-shift-jis-and-unicode
445 if (die_on_error && check_roundtrip(enc)) {
446 char *re_src;
447 size_t re_src_len;
449 re_src = reencode_string_len(dst, dst_len,
450 enc, default_encoding,
451 &re_src_len);
453 trace_printf("Checking roundtrip encoding for %s...\n", enc);
454 trace_encoding("reencoded source", path, enc,
455 re_src, re_src_len);
457 if (!re_src || src_len != re_src_len ||
458 memcmp(src, re_src, src_len)) {
459 const char* msg = _("encoding '%s' from %s to %s and "
460 "back is not the same");
461 die(msg, path, enc, default_encoding);
464 free(re_src);
467 strbuf_attach(buf, dst, dst_len, dst_len + 1);
468 return 1;
471 static int encode_to_worktree(const char *path, const char *src, size_t src_len,
472 struct strbuf *buf, const char *enc)
474 char *dst;
475 size_t dst_len;
478 * No encoding is specified or there is nothing to encode.
479 * Tell the caller that the content was not modified.
481 if (!enc || (src && !src_len))
482 return 0;
484 dst = reencode_string_len(src, src_len, enc, default_encoding,
485 &dst_len);
486 if (!dst) {
487 error(_("failed to encode '%s' from %s to %s"),
488 path, default_encoding, enc);
489 return 0;
492 strbuf_attach(buf, dst, dst_len, dst_len + 1);
493 return 1;
496 static int crlf_to_git(struct index_state *istate,
497 const char *path, const char *src, size_t len,
498 struct strbuf *buf,
499 enum convert_crlf_action crlf_action, int conv_flags)
501 struct text_stat stats;
502 char *dst;
503 int convert_crlf_into_lf;
505 if (crlf_action == CRLF_BINARY ||
506 (src && !len))
507 return 0;
510 * If we are doing a dry-run and have no source buffer, there is
511 * nothing to analyze; we must assume we would convert.
513 if (!buf && !src)
514 return 1;
516 gather_stats(src, len, &stats);
517 /* Optimization: No CRLF? Nothing to convert, regardless. */
518 convert_crlf_into_lf = !!stats.crlf;
520 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
521 if (convert_is_binary(&stats))
522 return 0;
524 * If the file in the index has any CR in it, do not
525 * convert. This is the new safer autocrlf handling,
526 * unless we want to renormalize in a merge or
527 * cherry-pick.
529 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
530 has_crlf_in_index(istate, path))
531 convert_crlf_into_lf = 0;
533 if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
534 ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
535 struct text_stat new_stats;
536 memcpy(&new_stats, &stats, sizeof(new_stats));
537 /* simulate "git add" */
538 if (convert_crlf_into_lf) {
539 new_stats.lonelf += new_stats.crlf;
540 new_stats.crlf = 0;
542 /* simulate "git checkout" */
543 if (will_convert_lf_to_crlf(&new_stats, crlf_action)) {
544 new_stats.crlf += new_stats.lonelf;
545 new_stats.lonelf = 0;
547 check_global_conv_flags_eol(path, &stats, &new_stats, conv_flags);
549 if (!convert_crlf_into_lf)
550 return 0;
553 * At this point all of our source analysis is done, and we are sure we
554 * would convert. If we are in dry-run mode, we can give an answer.
556 if (!buf)
557 return 1;
559 /* only grow if not in place */
560 if (strbuf_avail(buf) + buf->len < len)
561 strbuf_grow(buf, len - buf->len);
562 dst = buf->buf;
563 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
565 * If we guessed, we already know we rejected a file with
566 * lone CR, and we can strip a CR without looking at what
567 * follow it.
569 do {
570 unsigned char c = *src++;
571 if (c != '\r')
572 *dst++ = c;
573 } while (--len);
574 } else {
575 do {
576 unsigned char c = *src++;
577 if (! (c == '\r' && (1 < len && *src == '\n')))
578 *dst++ = c;
579 } while (--len);
581 strbuf_setlen(buf, dst - buf->buf);
582 return 1;
585 static int crlf_to_worktree(const char *src, size_t len, struct strbuf *buf,
586 enum convert_crlf_action crlf_action)
588 char *to_free = NULL;
589 struct text_stat stats;
591 if (!len || output_eol(crlf_action) != EOL_CRLF)
592 return 0;
594 gather_stats(src, len, &stats);
595 if (!will_convert_lf_to_crlf(&stats, crlf_action))
596 return 0;
598 /* are we "faking" in place editing ? */
599 if (src == buf->buf)
600 to_free = strbuf_detach(buf, NULL);
602 strbuf_grow(buf, len + stats.lonelf);
603 for (;;) {
604 const char *nl = memchr(src, '\n', len);
605 if (!nl)
606 break;
607 if (nl > src && nl[-1] == '\r') {
608 strbuf_add(buf, src, nl + 1 - src);
609 } else {
610 strbuf_add(buf, src, nl - src);
611 strbuf_addstr(buf, "\r\n");
613 len -= nl + 1 - src;
614 src = nl + 1;
616 strbuf_add(buf, src, len);
618 free(to_free);
619 return 1;
622 struct filter_params {
623 const char *src;
624 size_t size;
625 int fd;
626 const char *cmd;
627 const char *path;
630 static int filter_buffer_or_fd(int in UNUSED, int out, void *data)
633 * Spawn cmd and feed the buffer contents through its stdin.
635 struct child_process child_process = CHILD_PROCESS_INIT;
636 struct filter_params *params = (struct filter_params *)data;
637 int write_err, status;
639 /* apply % substitution to cmd */
640 struct strbuf cmd = STRBUF_INIT;
641 struct strbuf path = STRBUF_INIT;
642 struct strbuf_expand_dict_entry dict[] = {
643 { "f", NULL, },
644 { NULL, NULL, },
647 /* quote the path to preserve spaces, etc. */
648 sq_quote_buf(&path, params->path);
649 dict[0].value = path.buf;
651 /* expand all %f with the quoted path */
652 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
653 strbuf_release(&path);
655 strvec_push(&child_process.args, cmd.buf);
656 child_process.use_shell = 1;
657 child_process.in = -1;
658 child_process.out = out;
660 if (start_command(&child_process)) {
661 strbuf_release(&cmd);
662 return error(_("cannot fork to run external filter '%s'"),
663 params->cmd);
666 sigchain_push(SIGPIPE, SIG_IGN);
668 if (params->src) {
669 write_err = (write_in_full(child_process.in,
670 params->src, params->size) < 0);
671 if (errno == EPIPE)
672 write_err = 0;
673 } else {
674 write_err = copy_fd(params->fd, child_process.in);
675 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
676 write_err = 0;
679 if (close(child_process.in))
680 write_err = 1;
681 if (write_err)
682 error(_("cannot feed the input to external filter '%s'"),
683 params->cmd);
685 sigchain_pop(SIGPIPE);
687 status = finish_command(&child_process);
688 if (status)
689 error(_("external filter '%s' failed %d"), params->cmd, status);
691 strbuf_release(&cmd);
692 return (write_err || status);
695 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
696 struct strbuf *dst, const char *cmd)
699 * Create a pipeline to have the command filter the buffer's
700 * contents.
702 * (child --> cmd) --> us
704 int err = 0;
705 struct strbuf nbuf = STRBUF_INIT;
706 struct async async;
707 struct filter_params params;
709 memset(&async, 0, sizeof(async));
710 async.proc = filter_buffer_or_fd;
711 async.data = &params;
712 async.out = -1;
713 params.src = src;
714 params.size = len;
715 params.fd = fd;
716 params.cmd = cmd;
717 params.path = path;
719 fflush(NULL);
720 if (start_async(&async))
721 return 0; /* error was already reported */
723 if (strbuf_read(&nbuf, async.out, 0) < 0) {
724 err = error(_("read from external filter '%s' failed"), cmd);
726 if (close(async.out)) {
727 err = error(_("read from external filter '%s' failed"), cmd);
729 if (finish_async(&async)) {
730 err = error(_("external filter '%s' failed"), cmd);
733 if (!err) {
734 strbuf_swap(dst, &nbuf);
736 strbuf_release(&nbuf);
737 return !err;
740 #define CAP_CLEAN (1u<<0)
741 #define CAP_SMUDGE (1u<<1)
742 #define CAP_DELAY (1u<<2)
744 struct cmd2process {
745 struct subprocess_entry subprocess; /* must be the first member! */
746 unsigned int supported_capabilities;
749 static int subprocess_map_initialized;
750 static struct hashmap subprocess_map;
752 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
754 static int versions[] = {2, 0};
755 static struct subprocess_capability capabilities[] = {
756 { "clean", CAP_CLEAN },
757 { "smudge", CAP_SMUDGE },
758 { "delay", CAP_DELAY },
759 { NULL, 0 }
761 struct cmd2process *entry = (struct cmd2process *)subprocess;
762 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
763 capabilities,
764 &entry->supported_capabilities);
767 static void handle_filter_error(const struct strbuf *filter_status,
768 struct cmd2process *entry,
769 const unsigned int wanted_capability)
771 if (!strcmp(filter_status->buf, "error"))
772 ; /* The filter signaled a problem with the file. */
773 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
775 * The filter signaled a permanent problem. Don't try to filter
776 * files with the same command for the lifetime of the current
777 * Git process.
779 entry->supported_capabilities &= ~wanted_capability;
780 } else {
782 * Something went wrong with the protocol filter.
783 * Force shutdown and restart if another blob requires filtering.
785 error(_("external filter '%s' failed"), entry->subprocess.cmd);
786 subprocess_stop(&subprocess_map, &entry->subprocess);
787 free(entry);
791 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
792 int fd, struct strbuf *dst, const char *cmd,
793 const unsigned int wanted_capability,
794 const struct checkout_metadata *meta,
795 struct delayed_checkout *dco)
797 int err;
798 int can_delay = 0;
799 struct cmd2process *entry;
800 struct child_process *process;
801 struct strbuf nbuf = STRBUF_INIT;
802 struct strbuf filter_status = STRBUF_INIT;
803 const char *filter_type;
805 if (!subprocess_map_initialized) {
806 subprocess_map_initialized = 1;
807 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
808 entry = NULL;
809 } else {
810 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
813 fflush(NULL);
815 if (!entry) {
816 entry = xmalloc(sizeof(*entry));
817 entry->supported_capabilities = 0;
819 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
820 free(entry);
821 return 0;
824 process = &entry->subprocess.process;
826 if (!(entry->supported_capabilities & wanted_capability))
827 return 0;
829 if (wanted_capability & CAP_CLEAN)
830 filter_type = "clean";
831 else if (wanted_capability & CAP_SMUDGE)
832 filter_type = "smudge";
833 else
834 die(_("unexpected filter type"));
836 sigchain_push(SIGPIPE, SIG_IGN);
838 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
839 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
840 if (err)
841 goto done;
843 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
844 if (err) {
845 error(_("path name too long for external filter"));
846 goto done;
849 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
850 if (err)
851 goto done;
853 if (meta && meta->refname) {
854 err = packet_write_fmt_gently(process->in, "ref=%s\n", meta->refname);
855 if (err)
856 goto done;
859 if (meta && !is_null_oid(&meta->treeish)) {
860 err = packet_write_fmt_gently(process->in, "treeish=%s\n", oid_to_hex(&meta->treeish));
861 if (err)
862 goto done;
865 if (meta && !is_null_oid(&meta->blob)) {
866 err = packet_write_fmt_gently(process->in, "blob=%s\n", oid_to_hex(&meta->blob));
867 if (err)
868 goto done;
871 if ((entry->supported_capabilities & CAP_DELAY) &&
872 dco && dco->state == CE_CAN_DELAY) {
873 can_delay = 1;
874 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
875 if (err)
876 goto done;
879 err = packet_flush_gently(process->in);
880 if (err)
881 goto done;
883 if (fd >= 0)
884 err = write_packetized_from_fd_no_flush(fd, process->in);
885 else
886 err = write_packetized_from_buf_no_flush(src, len, process->in);
887 if (err)
888 goto done;
890 err = packet_flush_gently(process->in);
891 if (err)
892 goto done;
894 err = subprocess_read_status(process->out, &filter_status);
895 if (err)
896 goto done;
898 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
899 string_list_insert(&dco->filters, cmd);
900 string_list_insert(&dco->paths, path);
901 } else {
902 /* The filter got the blob and wants to send us a response. */
903 err = strcmp(filter_status.buf, "success");
904 if (err)
905 goto done;
907 err = read_packetized_to_strbuf(process->out, &nbuf,
908 PACKET_READ_GENTLE_ON_EOF) < 0;
909 if (err)
910 goto done;
912 err = subprocess_read_status(process->out, &filter_status);
913 if (err)
914 goto done;
916 err = strcmp(filter_status.buf, "success");
919 done:
920 sigchain_pop(SIGPIPE);
922 if (err)
923 handle_filter_error(&filter_status, entry, wanted_capability);
924 else
925 strbuf_swap(dst, &nbuf);
926 strbuf_release(&nbuf);
927 strbuf_release(&filter_status);
928 return !err;
932 int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
934 int err;
935 char *line;
936 struct cmd2process *entry;
937 struct child_process *process;
938 struct strbuf filter_status = STRBUF_INIT;
940 assert(subprocess_map_initialized);
941 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
942 if (!entry) {
943 error(_("external filter '%s' is not available anymore although "
944 "not all paths have been filtered"), cmd);
945 return 0;
947 process = &entry->subprocess.process;
948 sigchain_push(SIGPIPE, SIG_IGN);
950 err = packet_write_fmt_gently(
951 process->in, "command=list_available_blobs\n");
952 if (err)
953 goto done;
955 err = packet_flush_gently(process->in);
956 if (err)
957 goto done;
959 while ((line = packet_read_line(process->out, NULL))) {
960 const char *path;
961 if (skip_prefix(line, "pathname=", &path))
962 string_list_insert(available_paths, xstrdup(path));
963 else
964 ; /* ignore unknown keys */
967 err = subprocess_read_status(process->out, &filter_status);
968 if (err)
969 goto done;
971 err = strcmp(filter_status.buf, "success");
973 done:
974 sigchain_pop(SIGPIPE);
976 if (err)
977 handle_filter_error(&filter_status, entry, 0);
978 strbuf_release(&filter_status);
979 return !err;
982 static struct convert_driver {
983 const char *name;
984 struct convert_driver *next;
985 const char *smudge;
986 const char *clean;
987 const char *process;
988 int required;
989 } *user_convert, **user_convert_tail;
991 static int apply_filter(const char *path, const char *src, size_t len,
992 int fd, struct strbuf *dst, struct convert_driver *drv,
993 const unsigned int wanted_capability,
994 const struct checkout_metadata *meta,
995 struct delayed_checkout *dco)
997 const char *cmd = NULL;
999 if (!drv)
1000 return 0;
1002 if (!dst)
1003 return 1;
1005 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
1006 cmd = drv->clean;
1007 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
1008 cmd = drv->smudge;
1010 if (cmd && *cmd)
1011 return apply_single_file_filter(path, src, len, fd, dst, cmd);
1012 else if (drv->process && *drv->process)
1013 return apply_multi_file_filter(path, src, len, fd, dst,
1014 drv->process, wanted_capability, meta, dco);
1016 return 0;
1019 static int read_convert_config(const char *var, const char *value, void *cb UNUSED)
1021 const char *key, *name;
1022 size_t namelen;
1023 struct convert_driver *drv;
1026 * External conversion drivers are configured using
1027 * "filter.<name>.variable".
1029 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
1030 return 0;
1031 for (drv = user_convert; drv; drv = drv->next)
1032 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
1033 break;
1034 if (!drv) {
1035 CALLOC_ARRAY(drv, 1);
1036 drv->name = xmemdupz(name, namelen);
1037 *user_convert_tail = drv;
1038 user_convert_tail = &(drv->next);
1042 * filter.<name>.smudge and filter.<name>.clean specifies
1043 * the command line:
1045 * command-line
1047 * The command-line will not be interpolated in any way.
1050 if (!strcmp("smudge", key))
1051 return git_config_string(&drv->smudge, var, value);
1053 if (!strcmp("clean", key))
1054 return git_config_string(&drv->clean, var, value);
1056 if (!strcmp("process", key))
1057 return git_config_string(&drv->process, var, value);
1059 if (!strcmp("required", key)) {
1060 drv->required = git_config_bool(var, value);
1061 return 0;
1064 return 0;
1067 static int count_ident(const char *cp, unsigned long size)
1070 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
1072 int cnt = 0;
1073 char ch;
1075 while (size) {
1076 ch = *cp++;
1077 size--;
1078 if (ch != '$')
1079 continue;
1080 if (size < 3)
1081 break;
1082 if (memcmp("Id", cp, 2))
1083 continue;
1084 ch = cp[2];
1085 cp += 3;
1086 size -= 3;
1087 if (ch == '$')
1088 cnt++; /* $Id$ */
1089 if (ch != ':')
1090 continue;
1093 * "$Id: ... "; scan up to the closing dollar sign and discard.
1095 while (size) {
1096 ch = *cp++;
1097 size--;
1098 if (ch == '$') {
1099 cnt++;
1100 break;
1102 if (ch == '\n')
1103 break;
1106 return cnt;
1109 static int ident_to_git(const char *src, size_t len,
1110 struct strbuf *buf, int ident)
1112 char *dst, *dollar;
1114 if (!ident || (src && !count_ident(src, len)))
1115 return 0;
1117 if (!buf)
1118 return 1;
1120 /* only grow if not in place */
1121 if (strbuf_avail(buf) + buf->len < len)
1122 strbuf_grow(buf, len - buf->len);
1123 dst = buf->buf;
1124 for (;;) {
1125 dollar = memchr(src, '$', len);
1126 if (!dollar)
1127 break;
1128 memmove(dst, src, dollar + 1 - src);
1129 dst += dollar + 1 - src;
1130 len -= dollar + 1 - src;
1131 src = dollar + 1;
1133 if (len > 3 && !memcmp(src, "Id:", 3)) {
1134 dollar = memchr(src + 3, '$', len - 3);
1135 if (!dollar)
1136 break;
1137 if (memchr(src + 3, '\n', dollar - src - 3)) {
1138 /* Line break before the next dollar. */
1139 continue;
1142 memcpy(dst, "Id$", 3);
1143 dst += 3;
1144 len -= dollar + 1 - src;
1145 src = dollar + 1;
1148 memmove(dst, src, len);
1149 strbuf_setlen(buf, dst + len - buf->buf);
1150 return 1;
1153 static int ident_to_worktree(const char *src, size_t len,
1154 struct strbuf *buf, int ident)
1156 struct object_id oid;
1157 char *to_free = NULL, *dollar, *spc;
1158 int cnt;
1160 if (!ident)
1161 return 0;
1163 cnt = count_ident(src, len);
1164 if (!cnt)
1165 return 0;
1167 /* are we "faking" in place editing ? */
1168 if (src == buf->buf)
1169 to_free = strbuf_detach(buf, NULL);
1170 hash_object_file(the_hash_algo, src, len, OBJ_BLOB, &oid);
1172 strbuf_grow(buf, len + cnt * (the_hash_algo->hexsz + 3));
1173 for (;;) {
1174 /* step 1: run to the next '$' */
1175 dollar = memchr(src, '$', len);
1176 if (!dollar)
1177 break;
1178 strbuf_add(buf, src, dollar + 1 - src);
1179 len -= dollar + 1 - src;
1180 src = dollar + 1;
1182 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1183 if (len < 3 || memcmp("Id", src, 2))
1184 continue;
1186 /* step 3: skip over Id$ or Id:xxxxx$ */
1187 if (src[2] == '$') {
1188 src += 3;
1189 len -= 3;
1190 } else if (src[2] == ':') {
1192 * It's possible that an expanded Id has crept its way into the
1193 * repository, we cope with that by stripping the expansion out.
1194 * This is probably not a good idea, since it will cause changes
1195 * on checkout, which won't go away by stash, but let's keep it
1196 * for git-style ids.
1198 dollar = memchr(src + 3, '$', len - 3);
1199 if (!dollar) {
1200 /* incomplete keyword, no more '$', so just quit the loop */
1201 break;
1204 if (memchr(src + 3, '\n', dollar - src - 3)) {
1205 /* Line break before the next dollar. */
1206 continue;
1209 spc = memchr(src + 4, ' ', dollar - src - 4);
1210 if (spc && spc < dollar-1) {
1211 /* There are spaces in unexpected places.
1212 * This is probably an id from some other
1213 * versioning system. Keep it for now.
1215 continue;
1218 len -= dollar + 1 - src;
1219 src = dollar + 1;
1220 } else {
1221 /* it wasn't a "Id$" or "Id:xxxx$" */
1222 continue;
1225 /* step 4: substitute */
1226 strbuf_addstr(buf, "Id: ");
1227 strbuf_addstr(buf, oid_to_hex(&oid));
1228 strbuf_addstr(buf, " $");
1230 strbuf_add(buf, src, len);
1232 free(to_free);
1233 return 1;
1236 static const char *git_path_check_encoding(struct attr_check_item *check)
1238 const char *value = check->value;
1240 if (ATTR_UNSET(value) || !strlen(value))
1241 return NULL;
1243 if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
1244 die(_("true/false are no valid working-tree-encodings"));
1247 /* Don't encode to the default encoding */
1248 if (same_encoding(value, default_encoding))
1249 return NULL;
1251 return value;
1254 static enum convert_crlf_action git_path_check_crlf(struct attr_check_item *check)
1256 const char *value = check->value;
1258 if (ATTR_TRUE(value))
1259 return CRLF_TEXT;
1260 else if (ATTR_FALSE(value))
1261 return CRLF_BINARY;
1262 else if (ATTR_UNSET(value))
1264 else if (!strcmp(value, "input"))
1265 return CRLF_TEXT_INPUT;
1266 else if (!strcmp(value, "auto"))
1267 return CRLF_AUTO;
1268 return CRLF_UNDEFINED;
1271 static enum eol git_path_check_eol(struct attr_check_item *check)
1273 const char *value = check->value;
1275 if (ATTR_UNSET(value))
1277 else if (!strcmp(value, "lf"))
1278 return EOL_LF;
1279 else if (!strcmp(value, "crlf"))
1280 return EOL_CRLF;
1281 return EOL_UNSET;
1284 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
1286 const char *value = check->value;
1287 struct convert_driver *drv;
1289 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1290 return NULL;
1291 for (drv = user_convert; drv; drv = drv->next)
1292 if (!strcmp(value, drv->name))
1293 return drv;
1294 return NULL;
1297 static int git_path_check_ident(struct attr_check_item *check)
1299 const char *value = check->value;
1301 return !!ATTR_TRUE(value);
1304 static struct attr_check *check;
1306 void convert_attrs(struct index_state *istate,
1307 struct conv_attrs *ca, const char *path)
1309 struct attr_check_item *ccheck = NULL;
1311 if (!check) {
1312 check = attr_check_initl("crlf", "ident", "filter",
1313 "eol", "text", "working-tree-encoding",
1314 NULL);
1315 user_convert_tail = &user_convert;
1316 git_config(read_convert_config, NULL);
1319 git_check_attr(istate, path, check);
1320 ccheck = check->items;
1321 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1322 if (ca->crlf_action == CRLF_UNDEFINED)
1323 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1324 ca->ident = git_path_check_ident(ccheck + 1);
1325 ca->drv = git_path_check_convert(ccheck + 2);
1326 if (ca->crlf_action != CRLF_BINARY) {
1327 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1328 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1329 ca->crlf_action = CRLF_AUTO_INPUT;
1330 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1331 ca->crlf_action = CRLF_AUTO_CRLF;
1332 else if (eol_attr == EOL_LF)
1333 ca->crlf_action = CRLF_TEXT_INPUT;
1334 else if (eol_attr == EOL_CRLF)
1335 ca->crlf_action = CRLF_TEXT_CRLF;
1337 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
1339 /* Save attr and make a decision for action */
1340 ca->attr_action = ca->crlf_action;
1341 if (ca->crlf_action == CRLF_TEXT)
1342 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1343 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1344 ca->crlf_action = CRLF_BINARY;
1345 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1346 ca->crlf_action = CRLF_AUTO_CRLF;
1347 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1348 ca->crlf_action = CRLF_AUTO_INPUT;
1351 void reset_parsed_attributes(void)
1353 struct convert_driver *drv, *next;
1355 attr_check_free(check);
1356 check = NULL;
1357 reset_merge_attributes();
1359 for (drv = user_convert; drv; drv = next) {
1360 next = drv->next;
1361 free((void *)drv->name);
1362 free(drv);
1364 user_convert = NULL;
1365 user_convert_tail = NULL;
1368 int would_convert_to_git_filter_fd(struct index_state *istate, const char *path)
1370 struct conv_attrs ca;
1372 convert_attrs(istate, &ca, path);
1373 if (!ca.drv)
1374 return 0;
1377 * Apply a filter to an fd only if the filter is required to succeed.
1378 * We must die if the filter fails, because the original data before
1379 * filtering is not available.
1381 if (!ca.drv->required)
1382 return 0;
1384 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL, NULL);
1387 const char *get_convert_attr_ascii(struct index_state *istate, const char *path)
1389 struct conv_attrs ca;
1391 convert_attrs(istate, &ca, path);
1392 switch (ca.attr_action) {
1393 case CRLF_UNDEFINED:
1394 return "";
1395 case CRLF_BINARY:
1396 return "-text";
1397 case CRLF_TEXT:
1398 return "text";
1399 case CRLF_TEXT_INPUT:
1400 return "text eol=lf";
1401 case CRLF_TEXT_CRLF:
1402 return "text eol=crlf";
1403 case CRLF_AUTO:
1404 return "text=auto";
1405 case CRLF_AUTO_CRLF:
1406 return "text=auto eol=crlf";
1407 case CRLF_AUTO_INPUT:
1408 return "text=auto eol=lf";
1410 return "";
1413 int convert_to_git(struct index_state *istate,
1414 const char *path, const char *src, size_t len,
1415 struct strbuf *dst, int conv_flags)
1417 int ret = 0;
1418 struct conv_attrs ca;
1420 convert_attrs(istate, &ca, path);
1422 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL, NULL);
1423 if (!ret && ca.drv && ca.drv->required)
1424 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
1426 if (ret && dst) {
1427 src = dst->buf;
1428 len = dst->len;
1431 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1432 if (ret && dst) {
1433 src = dst->buf;
1434 len = dst->len;
1437 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1438 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
1439 if (ret && dst) {
1440 src = dst->buf;
1441 len = dst->len;
1444 return ret | ident_to_git(src, len, dst, ca.ident);
1447 void convert_to_git_filter_fd(struct index_state *istate,
1448 const char *path, int fd, struct strbuf *dst,
1449 int conv_flags)
1451 struct conv_attrs ca;
1452 convert_attrs(istate, &ca, path);
1454 assert(ca.drv);
1456 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL, NULL))
1457 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
1459 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
1460 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
1461 ident_to_git(dst->buf, dst->len, dst, ca.ident);
1464 static int convert_to_working_tree_ca_internal(const struct conv_attrs *ca,
1465 const char *path, const char *src,
1466 size_t len, struct strbuf *dst,
1467 int normalizing,
1468 const struct checkout_metadata *meta,
1469 struct delayed_checkout *dco)
1471 int ret = 0, ret_filter = 0;
1473 ret |= ident_to_worktree(src, len, dst, ca->ident);
1474 if (ret) {
1475 src = dst->buf;
1476 len = dst->len;
1479 * CRLF conversion can be skipped if normalizing, unless there
1480 * is a smudge or process filter (even if the process filter doesn't
1481 * support smudge). The filters might expect CRLFs.
1483 if ((ca->drv && (ca->drv->smudge || ca->drv->process)) || !normalizing) {
1484 ret |= crlf_to_worktree(src, len, dst, ca->crlf_action);
1485 if (ret) {
1486 src = dst->buf;
1487 len = dst->len;
1491 ret |= encode_to_worktree(path, src, len, dst, ca->working_tree_encoding);
1492 if (ret) {
1493 src = dst->buf;
1494 len = dst->len;
1497 ret_filter = apply_filter(
1498 path, src, len, -1, dst, ca->drv, CAP_SMUDGE, meta, dco);
1499 if (!ret_filter && ca->drv && ca->drv->required)
1500 die(_("%s: smudge filter %s failed"), path, ca->drv->name);
1502 return ret | ret_filter;
1505 int async_convert_to_working_tree_ca(const struct conv_attrs *ca,
1506 const char *path, const char *src,
1507 size_t len, struct strbuf *dst,
1508 const struct checkout_metadata *meta,
1509 void *dco)
1511 return convert_to_working_tree_ca_internal(ca, path, src, len, dst, 0,
1512 meta, dco);
1515 int convert_to_working_tree_ca(const struct conv_attrs *ca,
1516 const char *path, const char *src,
1517 size_t len, struct strbuf *dst,
1518 const struct checkout_metadata *meta)
1520 return convert_to_working_tree_ca_internal(ca, path, src, len, dst, 0,
1521 meta, NULL);
1524 int renormalize_buffer(struct index_state *istate, const char *path,
1525 const char *src, size_t len, struct strbuf *dst)
1527 struct conv_attrs ca;
1528 int ret;
1530 convert_attrs(istate, &ca, path);
1531 ret = convert_to_working_tree_ca_internal(&ca, path, src, len, dst, 1,
1532 NULL, NULL);
1533 if (ret) {
1534 src = dst->buf;
1535 len = dst->len;
1537 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
1540 /*****************************************************************
1542 * Streaming conversion support
1544 *****************************************************************/
1546 typedef int (*filter_fn)(struct stream_filter *,
1547 const char *input, size_t *isize_p,
1548 char *output, size_t *osize_p);
1549 typedef void (*free_fn)(struct stream_filter *);
1551 struct stream_filter_vtbl {
1552 filter_fn filter;
1553 free_fn free;
1556 struct stream_filter {
1557 struct stream_filter_vtbl *vtbl;
1560 static int null_filter_fn(struct stream_filter *filter UNUSED,
1561 const char *input, size_t *isize_p,
1562 char *output, size_t *osize_p)
1564 size_t count;
1566 if (!input)
1567 return 0; /* we do not keep any states */
1568 count = *isize_p;
1569 if (*osize_p < count)
1570 count = *osize_p;
1571 if (count) {
1572 memmove(output, input, count);
1573 *isize_p -= count;
1574 *osize_p -= count;
1576 return 0;
1579 static void null_free_fn(struct stream_filter *filter UNUSED)
1581 ; /* nothing -- null instances are shared */
1584 static struct stream_filter_vtbl null_vtbl = {
1585 .filter = null_filter_fn,
1586 .free = null_free_fn,
1589 static struct stream_filter null_filter_singleton = {
1590 .vtbl = &null_vtbl,
1593 int is_null_stream_filter(struct stream_filter *filter)
1595 return filter == &null_filter_singleton;
1600 * LF-to-CRLF filter
1603 struct lf_to_crlf_filter {
1604 struct stream_filter filter;
1605 unsigned has_held:1;
1606 char held;
1609 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1610 const char *input, size_t *isize_p,
1611 char *output, size_t *osize_p)
1613 size_t count, o = 0;
1614 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1617 * We may be holding onto the CR to see if it is followed by a
1618 * LF, in which case we would need to go to the main loop.
1619 * Otherwise, just emit it to the output stream.
1621 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1622 output[o++] = lf_to_crlf->held;
1623 lf_to_crlf->has_held = 0;
1626 /* We are told to drain */
1627 if (!input) {
1628 *osize_p -= o;
1629 return 0;
1632 count = *isize_p;
1633 if (count || lf_to_crlf->has_held) {
1634 size_t i;
1635 int was_cr = 0;
1637 if (lf_to_crlf->has_held) {
1638 was_cr = 1;
1639 lf_to_crlf->has_held = 0;
1642 for (i = 0; o < *osize_p && i < count; i++) {
1643 char ch = input[i];
1645 if (ch == '\n') {
1646 output[o++] = '\r';
1647 } else if (was_cr) {
1649 * Previous round saw CR and it is not followed
1650 * by a LF; emit the CR before processing the
1651 * current character.
1653 output[o++] = '\r';
1657 * We may have consumed the last output slot,
1658 * in which case we need to break out of this
1659 * loop; hold the current character before
1660 * returning.
1662 if (*osize_p <= o) {
1663 lf_to_crlf->has_held = 1;
1664 lf_to_crlf->held = ch;
1665 continue; /* break but increment i */
1668 if (ch == '\r') {
1669 was_cr = 1;
1670 continue;
1673 was_cr = 0;
1674 output[o++] = ch;
1677 *osize_p -= o;
1678 *isize_p -= i;
1680 if (!lf_to_crlf->has_held && was_cr) {
1681 lf_to_crlf->has_held = 1;
1682 lf_to_crlf->held = '\r';
1685 return 0;
1688 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1690 free(filter);
1693 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1694 .filter = lf_to_crlf_filter_fn,
1695 .free = lf_to_crlf_free_fn,
1698 static struct stream_filter *lf_to_crlf_filter(void)
1700 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1702 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1703 return (struct stream_filter *)lf_to_crlf;
1707 * Cascade filter
1709 #define FILTER_BUFFER 1024
1710 struct cascade_filter {
1711 struct stream_filter filter;
1712 struct stream_filter *one;
1713 struct stream_filter *two;
1714 char buf[FILTER_BUFFER];
1715 int end, ptr;
1718 static int cascade_filter_fn(struct stream_filter *filter,
1719 const char *input, size_t *isize_p,
1720 char *output, size_t *osize_p)
1722 struct cascade_filter *cas = (struct cascade_filter *) filter;
1723 size_t filled = 0;
1724 size_t sz = *osize_p;
1725 size_t to_feed, remaining;
1728 * input -- (one) --> buf -- (two) --> output
1730 while (filled < sz) {
1731 remaining = sz - filled;
1733 /* do we already have something to feed two with? */
1734 if (cas->ptr < cas->end) {
1735 to_feed = cas->end - cas->ptr;
1736 if (stream_filter(cas->two,
1737 cas->buf + cas->ptr, &to_feed,
1738 output + filled, &remaining))
1739 return -1;
1740 cas->ptr += (cas->end - cas->ptr) - to_feed;
1741 filled = sz - remaining;
1742 continue;
1745 /* feed one from upstream and have it emit into our buffer */
1746 to_feed = input ? *isize_p : 0;
1747 if (input && !to_feed)
1748 break;
1749 remaining = sizeof(cas->buf);
1750 if (stream_filter(cas->one,
1751 input, &to_feed,
1752 cas->buf, &remaining))
1753 return -1;
1754 cas->end = sizeof(cas->buf) - remaining;
1755 cas->ptr = 0;
1756 if (input) {
1757 size_t fed = *isize_p - to_feed;
1758 *isize_p -= fed;
1759 input += fed;
1762 /* do we know that we drained one completely? */
1763 if (input || cas->end)
1764 continue;
1766 /* tell two to drain; we have nothing more to give it */
1767 to_feed = 0;
1768 remaining = sz - filled;
1769 if (stream_filter(cas->two,
1770 NULL, &to_feed,
1771 output + filled, &remaining))
1772 return -1;
1773 if (remaining == (sz - filled))
1774 break; /* completely drained two */
1775 filled = sz - remaining;
1777 *osize_p -= filled;
1778 return 0;
1781 static void cascade_free_fn(struct stream_filter *filter)
1783 struct cascade_filter *cas = (struct cascade_filter *)filter;
1784 free_stream_filter(cas->one);
1785 free_stream_filter(cas->two);
1786 free(filter);
1789 static struct stream_filter_vtbl cascade_vtbl = {
1790 .filter = cascade_filter_fn,
1791 .free = cascade_free_fn,
1794 static struct stream_filter *cascade_filter(struct stream_filter *one,
1795 struct stream_filter *two)
1797 struct cascade_filter *cascade;
1799 if (!one || is_null_stream_filter(one))
1800 return two;
1801 if (!two || is_null_stream_filter(two))
1802 return one;
1804 cascade = xmalloc(sizeof(*cascade));
1805 cascade->one = one;
1806 cascade->two = two;
1807 cascade->end = cascade->ptr = 0;
1808 cascade->filter.vtbl = &cascade_vtbl;
1809 return (struct stream_filter *)cascade;
1813 * ident filter
1815 #define IDENT_DRAINING (-1)
1816 #define IDENT_SKIPPING (-2)
1817 struct ident_filter {
1818 struct stream_filter filter;
1819 struct strbuf left;
1820 int state;
1821 char ident[GIT_MAX_HEXSZ + 5]; /* ": x40 $" */
1824 static int is_foreign_ident(const char *str)
1826 int i;
1828 if (!skip_prefix(str, "$Id: ", &str))
1829 return 0;
1830 for (i = 0; str[i]; i++) {
1831 if (isspace(str[i]) && str[i+1] != '$')
1832 return 1;
1834 return 0;
1837 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1839 size_t to_drain = ident->left.len;
1841 if (*osize_p < to_drain)
1842 to_drain = *osize_p;
1843 if (to_drain) {
1844 memcpy(*output_p, ident->left.buf, to_drain);
1845 strbuf_remove(&ident->left, 0, to_drain);
1846 *output_p += to_drain;
1847 *osize_p -= to_drain;
1849 if (!ident->left.len)
1850 ident->state = 0;
1853 static int ident_filter_fn(struct stream_filter *filter,
1854 const char *input, size_t *isize_p,
1855 char *output, size_t *osize_p)
1857 struct ident_filter *ident = (struct ident_filter *)filter;
1858 static const char head[] = "$Id";
1860 if (!input) {
1861 /* drain upon eof */
1862 switch (ident->state) {
1863 default:
1864 strbuf_add(&ident->left, head, ident->state);
1865 /* fallthrough */
1866 case IDENT_SKIPPING:
1867 /* fallthrough */
1868 case IDENT_DRAINING:
1869 ident_drain(ident, &output, osize_p);
1871 return 0;
1874 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1875 int ch;
1877 if (ident->state == IDENT_DRAINING) {
1878 ident_drain(ident, &output, osize_p);
1879 if (!*osize_p)
1880 break;
1881 continue;
1884 ch = *(input++);
1885 (*isize_p)--;
1887 if (ident->state == IDENT_SKIPPING) {
1889 * Skipping until '$' or LF, but keeping them
1890 * in case it is a foreign ident.
1892 strbuf_addch(&ident->left, ch);
1893 if (ch != '\n' && ch != '$')
1894 continue;
1895 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1896 strbuf_setlen(&ident->left, sizeof(head) - 1);
1897 strbuf_addstr(&ident->left, ident->ident);
1899 ident->state = IDENT_DRAINING;
1900 continue;
1903 if (ident->state < sizeof(head) &&
1904 head[ident->state] == ch) {
1905 ident->state++;
1906 continue;
1909 if (ident->state)
1910 strbuf_add(&ident->left, head, ident->state);
1911 if (ident->state == sizeof(head) - 1) {
1912 if (ch != ':' && ch != '$') {
1913 strbuf_addch(&ident->left, ch);
1914 ident->state = 0;
1915 continue;
1918 if (ch == ':') {
1919 strbuf_addch(&ident->left, ch);
1920 ident->state = IDENT_SKIPPING;
1921 } else {
1922 strbuf_addstr(&ident->left, ident->ident);
1923 ident->state = IDENT_DRAINING;
1925 continue;
1928 strbuf_addch(&ident->left, ch);
1929 ident->state = IDENT_DRAINING;
1931 return 0;
1934 static void ident_free_fn(struct stream_filter *filter)
1936 struct ident_filter *ident = (struct ident_filter *)filter;
1937 strbuf_release(&ident->left);
1938 free(filter);
1941 static struct stream_filter_vtbl ident_vtbl = {
1942 .filter = ident_filter_fn,
1943 .free = ident_free_fn,
1946 static struct stream_filter *ident_filter(const struct object_id *oid)
1948 struct ident_filter *ident = xmalloc(sizeof(*ident));
1950 xsnprintf(ident->ident, sizeof(ident->ident),
1951 ": %s $", oid_to_hex(oid));
1952 strbuf_init(&ident->left, 0);
1953 ident->filter.vtbl = &ident_vtbl;
1954 ident->state = 0;
1955 return (struct stream_filter *)ident;
1959 * Return an appropriately constructed filter for the given ca, or NULL if
1960 * the contents cannot be filtered without reading the whole thing
1961 * in-core.
1963 * Note that you would be crazy to set CRLF, smudge/clean or ident to a
1964 * large binary blob you would want us not to slurp into the memory!
1966 struct stream_filter *get_stream_filter_ca(const struct conv_attrs *ca,
1967 const struct object_id *oid)
1969 struct stream_filter *filter = NULL;
1971 if (classify_conv_attrs(ca) != CA_CLASS_STREAMABLE)
1972 return NULL;
1974 if (ca->ident)
1975 filter = ident_filter(oid);
1977 if (output_eol(ca->crlf_action) == EOL_CRLF)
1978 filter = cascade_filter(filter, lf_to_crlf_filter());
1979 else
1980 filter = cascade_filter(filter, &null_filter_singleton);
1982 return filter;
1985 struct stream_filter *get_stream_filter(struct index_state *istate,
1986 const char *path,
1987 const struct object_id *oid)
1989 struct conv_attrs ca;
1990 convert_attrs(istate, &ca, path);
1991 return get_stream_filter_ca(&ca, oid);
1994 void free_stream_filter(struct stream_filter *filter)
1996 filter->vtbl->free(filter);
1999 int stream_filter(struct stream_filter *filter,
2000 const char *input, size_t *isize_p,
2001 char *output, size_t *osize_p)
2003 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
2006 void init_checkout_metadata(struct checkout_metadata *meta, const char *refname,
2007 const struct object_id *treeish,
2008 const struct object_id *blob)
2010 memset(meta, 0, sizeof(*meta));
2011 if (refname)
2012 meta->refname = refname;
2013 if (treeish)
2014 oidcpy(&meta->treeish, treeish);
2015 if (blob)
2016 oidcpy(&meta->blob, blob);
2019 void clone_checkout_metadata(struct checkout_metadata *dst,
2020 const struct checkout_metadata *src,
2021 const struct object_id *blob)
2023 memcpy(dst, src, sizeof(*dst));
2024 if (blob)
2025 oidcpy(&dst->blob, blob);
2028 enum conv_attrs_classification classify_conv_attrs(const struct conv_attrs *ca)
2030 if (ca->drv) {
2031 if (ca->drv->process)
2032 return CA_CLASS_INCORE_PROCESS;
2033 if (ca->drv->smudge || ca->drv->clean)
2034 return CA_CLASS_INCORE_FILTER;
2037 if (ca->working_tree_encoding)
2038 return CA_CLASS_INCORE;
2040 if (ca->crlf_action == CRLF_AUTO || ca->crlf_action == CRLF_AUTO_CRLF)
2041 return CA_CLASS_INCORE;
2043 return CA_CLASS_STREAMABLE;