1 #define NO_THE_INDEX_COMPATIBILITY_MACROS
5 #include "run-command.h"
9 #include "sub-process.h"
13 * convert.c - convert a file when checking it out and checking it in.
15 * This should use the pathname to decide on whether it wants to do some
16 * more interesting conversions (automatic gzip/unzip, general format
17 * conversions etc etc), but by default it just does automatic CRLF<->LF
18 * translation when the "text" attribute or "auto_crlf" option is set.
21 /* Stat bits: When BIN is set, the txt bits are unset */
22 #define CONVERT_STAT_BITS_TXT_LF 0x1
23 #define CONVERT_STAT_BITS_TXT_CRLF 0x2
24 #define CONVERT_STAT_BITS_BIN 0x4
38 /* NUL, CR, LF and CRLF counts */
39 unsigned nul, lonecr, lonelf, crlf;
41 /* These are just approximations! */
42 unsigned printable, nonprintable;
45 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
49 memset(stats, 0, sizeof(*stats));
51 for (i = 0; i < size; i++) {
52 unsigned char c = buf[i];
54 if (i+1 < size && buf[i+1] == '\n') {
67 stats->nonprintable++;
70 /* BS, HT, ESC and FF */
71 case '\b': case '\t': case '\033': case '\014':
78 stats->nonprintable++;
85 /* If file ends with EOF then don't count this EOF as non-printable. */
86 if (size >= 1 && buf[size-1] == '\032')
87 stats->nonprintable--;
91 * The same heuristics as diff.c::mmfile_is_binary()
92 * We treat files with bare CR as binary
94 static int convert_is_binary(unsigned long size, const struct text_stat *stats)
100 if ((stats->printable >> 7) < stats->nonprintable)
105 static unsigned int gather_convert_stats(const char *data, unsigned long size)
107 struct text_stat stats;
111 gather_stats(data, size, &stats);
112 if (convert_is_binary(size, &stats))
113 ret |= CONVERT_STAT_BITS_BIN;
115 ret |= CONVERT_STAT_BITS_TXT_CRLF;
117 ret |= CONVERT_STAT_BITS_TXT_LF;
122 static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
124 unsigned int convert_stats = gather_convert_stats(data, size);
126 if (convert_stats & CONVERT_STAT_BITS_BIN)
128 switch (convert_stats) {
129 case CONVERT_STAT_BITS_TXT_LF:
131 case CONVERT_STAT_BITS_TXT_CRLF:
133 case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
140 const char *get_cached_convert_stats_ascii(const struct index_state *istate,
145 void *data = read_blob_data_from_index(istate, path, &sz);
146 ret = gather_convert_stats_ascii(data, sz);
151 const char *get_wt_convert_stats_ascii(const char *path)
153 const char *ret = "";
154 struct strbuf sb = STRBUF_INIT;
155 if (strbuf_read_file(&sb, path, 0) >= 0)
156 ret = gather_convert_stats_ascii(sb.buf, sb.len);
161 static int text_eol_is_crlf(void)
163 if (auto_crlf == AUTO_CRLF_TRUE)
165 else if (auto_crlf == AUTO_CRLF_INPUT)
167 if (core_eol == EOL_CRLF)
169 if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
174 static enum eol output_eol(enum crlf_action crlf_action)
176 switch (crlf_action) {
181 case CRLF_TEXT_INPUT:
186 case CRLF_AUTO_INPUT:
191 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
193 warning("Illegal crlf_action %d\n", (int)crlf_action);
197 static void check_global_conv_flags_eol(const char *path, enum crlf_action crlf_action,
198 struct text_stat *old_stats, struct text_stat *new_stats,
201 if (old_stats->crlf && !new_stats->crlf ) {
203 * CRLFs would not be restored by checkout
205 if (conv_flags & CONV_EOL_RNDTRP_DIE)
206 die(_("CRLF would be replaced by LF in %s."), path);
207 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
208 warning(_("CRLF will be replaced by LF in %s.\n"
209 "The file will have its original line"
210 " endings in your working directory."), path);
211 } else if (old_stats->lonelf && !new_stats->lonelf ) {
213 * CRLFs would be added by checkout
215 if (conv_flags & CONV_EOL_RNDTRP_DIE)
216 die(_("LF would be replaced by CRLF in %s"), path);
217 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
218 warning(_("LF will be replaced by CRLF in %s.\n"
219 "The file will have its original line"
220 " endings in your working directory."), path);
224 static int has_crlf_in_index(const struct index_state *istate, const char *path)
231 data = read_blob_data_from_index(istate, path, &sz);
235 crp = memchr(data, '\r', sz);
237 unsigned int ret_stats;
238 ret_stats = gather_convert_stats(data, sz);
239 if (!(ret_stats & CONVERT_STAT_BITS_BIN) &&
240 (ret_stats & CONVERT_STAT_BITS_TXT_CRLF))
247 static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats,
248 enum crlf_action crlf_action)
250 if (output_eol(crlf_action) != EOL_CRLF)
252 /* No "naked" LF? Nothing to convert, regardless. */
256 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
257 /* If we have any CR or CRLF line endings, we do not touch it */
258 /* This is the new safer autocrlf-handling */
259 if (stats->lonecr || stats->crlf)
262 if (convert_is_binary(len, stats))
269 static const char *default_encoding = "UTF-8";
271 static int encode_to_git(const char *path, const char *src, size_t src_len,
272 struct strbuf *buf, const char *enc, int conv_flags)
276 int die_on_error = conv_flags & CONV_WRITE_OBJECT;
279 * No encoding is specified or there is nothing to encode.
280 * Tell the caller that the content was not modified.
282 if (!enc || (src && !src_len))
286 * Looks like we got called from "would_convert_to_git()".
287 * This means Git wants to know if it would encode (= modify!)
288 * the content. Let's answer with "yes", since an encoding was
294 dst = reencode_string_len(src, src_len, default_encoding, enc,
298 * We could add the blob "as-is" to Git. However, on checkout
299 * we would try to reencode to the original encoding. This
300 * would fail and we would leave the user with a messed-up
301 * working tree. Let's try to avoid this by screaming loud.
303 const char* msg = _("failed to encode '%s' from %s to %s");
305 die(msg, path, enc, default_encoding);
307 error(msg, path, enc, default_encoding);
312 strbuf_attach(buf, dst, dst_len, dst_len + 1);
316 static int encode_to_worktree(const char *path, const char *src, size_t src_len,
317 struct strbuf *buf, const char *enc)
323 * No encoding is specified or there is nothing to encode.
324 * Tell the caller that the content was not modified.
326 if (!enc || (src && !src_len))
329 dst = reencode_string_len(src, src_len, enc, default_encoding,
332 error("failed to encode '%s' from %s to %s",
333 path, default_encoding, enc);
337 strbuf_attach(buf, dst, dst_len, dst_len + 1);
341 static int crlf_to_git(const struct index_state *istate,
342 const char *path, const char *src, size_t len,
344 enum crlf_action crlf_action, int conv_flags)
346 struct text_stat stats;
348 int convert_crlf_into_lf;
350 if (crlf_action == CRLF_BINARY ||
355 * If we are doing a dry-run and have no source buffer, there is
356 * nothing to analyze; we must assume we would convert.
361 gather_stats(src, len, &stats);
362 /* Optimization: No CRLF? Nothing to convert, regardless. */
363 convert_crlf_into_lf = !!stats.crlf;
365 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
366 if (convert_is_binary(len, &stats))
369 * If the file in the index has any CR in it, do not
370 * convert. This is the new safer autocrlf handling,
371 * unless we want to renormalize in a merge or
374 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
375 has_crlf_in_index(istate, path))
376 convert_crlf_into_lf = 0;
378 if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
379 ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
380 struct text_stat new_stats;
381 memcpy(&new_stats, &stats, sizeof(new_stats));
382 /* simulate "git add" */
383 if (convert_crlf_into_lf) {
384 new_stats.lonelf += new_stats.crlf;
387 /* simulate "git checkout" */
388 if (will_convert_lf_to_crlf(len, &new_stats, crlf_action)) {
389 new_stats.crlf += new_stats.lonelf;
390 new_stats.lonelf = 0;
392 check_global_conv_flags_eol(path, crlf_action, &stats, &new_stats, conv_flags);
394 if (!convert_crlf_into_lf)
398 * At this point all of our source analysis is done, and we are sure we
399 * would convert. If we are in dry-run mode, we can give an answer.
404 /* only grow if not in place */
405 if (strbuf_avail(buf) + buf->len < len)
406 strbuf_grow(buf, len - buf->len);
408 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
410 * If we guessed, we already know we rejected a file with
411 * lone CR, and we can strip a CR without looking at what
415 unsigned char c = *src++;
421 unsigned char c = *src++;
422 if (! (c == '\r' && (1 < len && *src == '\n')))
426 strbuf_setlen(buf, dst - buf->buf);
430 static int crlf_to_worktree(const char *path, const char *src, size_t len,
431 struct strbuf *buf, enum crlf_action crlf_action)
433 char *to_free = NULL;
434 struct text_stat stats;
436 if (!len || output_eol(crlf_action) != EOL_CRLF)
439 gather_stats(src, len, &stats);
440 if (!will_convert_lf_to_crlf(len, &stats, crlf_action))
443 /* are we "faking" in place editing ? */
445 to_free = strbuf_detach(buf, NULL);
447 strbuf_grow(buf, len + stats.lonelf);
449 const char *nl = memchr(src, '\n', len);
452 if (nl > src && nl[-1] == '\r') {
453 strbuf_add(buf, src, nl + 1 - src);
455 strbuf_add(buf, src, nl - src);
456 strbuf_addstr(buf, "\r\n");
461 strbuf_add(buf, src, len);
467 struct filter_params {
475 static int filter_buffer_or_fd(int in, int out, void *data)
478 * Spawn cmd and feed the buffer contents through its stdin.
480 struct child_process child_process = CHILD_PROCESS_INIT;
481 struct filter_params *params = (struct filter_params *)data;
482 int write_err, status;
483 const char *argv[] = { NULL, NULL };
485 /* apply % substitution to cmd */
486 struct strbuf cmd = STRBUF_INIT;
487 struct strbuf path = STRBUF_INIT;
488 struct strbuf_expand_dict_entry dict[] = {
493 /* quote the path to preserve spaces, etc. */
494 sq_quote_buf(&path, params->path);
495 dict[0].value = path.buf;
497 /* expand all %f with the quoted path */
498 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
499 strbuf_release(&path);
503 child_process.argv = argv;
504 child_process.use_shell = 1;
505 child_process.in = -1;
506 child_process.out = out;
508 if (start_command(&child_process)) {
509 strbuf_release(&cmd);
510 return error("cannot fork to run external filter '%s'", params->cmd);
513 sigchain_push(SIGPIPE, SIG_IGN);
516 write_err = (write_in_full(child_process.in,
517 params->src, params->size) < 0);
521 write_err = copy_fd(params->fd, child_process.in);
522 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
526 if (close(child_process.in))
529 error("cannot feed the input to external filter '%s'", params->cmd);
531 sigchain_pop(SIGPIPE);
533 status = finish_command(&child_process);
535 error("external filter '%s' failed %d", params->cmd, status);
537 strbuf_release(&cmd);
538 return (write_err || status);
541 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
542 struct strbuf *dst, const char *cmd)
545 * Create a pipeline to have the command filter the buffer's
548 * (child --> cmd) --> us
551 struct strbuf nbuf = STRBUF_INIT;
553 struct filter_params params;
555 memset(&async, 0, sizeof(async));
556 async.proc = filter_buffer_or_fd;
557 async.data = ¶ms;
566 if (start_async(&async))
567 return 0; /* error was already reported */
569 if (strbuf_read(&nbuf, async.out, len) < 0) {
570 err = error("read from external filter '%s' failed", cmd);
572 if (close(async.out)) {
573 err = error("read from external filter '%s' failed", cmd);
575 if (finish_async(&async)) {
576 err = error("external filter '%s' failed", cmd);
580 strbuf_swap(dst, &nbuf);
582 strbuf_release(&nbuf);
586 #define CAP_CLEAN (1u<<0)
587 #define CAP_SMUDGE (1u<<1)
588 #define CAP_DELAY (1u<<2)
591 struct subprocess_entry subprocess; /* must be the first member! */
592 unsigned int supported_capabilities;
595 static int subprocess_map_initialized;
596 static struct hashmap subprocess_map;
598 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
600 static int versions[] = {2, 0};
601 static struct subprocess_capability capabilities[] = {
602 { "clean", CAP_CLEAN },
603 { "smudge", CAP_SMUDGE },
604 { "delay", CAP_DELAY },
607 struct cmd2process *entry = (struct cmd2process *)subprocess;
608 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
610 &entry->supported_capabilities);
613 static void handle_filter_error(const struct strbuf *filter_status,
614 struct cmd2process *entry,
615 const unsigned int wanted_capability) {
616 if (!strcmp(filter_status->buf, "error"))
617 ; /* The filter signaled a problem with the file. */
618 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
620 * The filter signaled a permanent problem. Don't try to filter
621 * files with the same command for the lifetime of the current
624 entry->supported_capabilities &= ~wanted_capability;
627 * Something went wrong with the protocol filter.
628 * Force shutdown and restart if another blob requires filtering.
630 error("external filter '%s' failed", entry->subprocess.cmd);
631 subprocess_stop(&subprocess_map, &entry->subprocess);
636 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
637 int fd, struct strbuf *dst, const char *cmd,
638 const unsigned int wanted_capability,
639 struct delayed_checkout *dco)
643 struct cmd2process *entry;
644 struct child_process *process;
645 struct strbuf nbuf = STRBUF_INIT;
646 struct strbuf filter_status = STRBUF_INIT;
647 const char *filter_type;
649 if (!subprocess_map_initialized) {
650 subprocess_map_initialized = 1;
651 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
654 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
660 entry = xmalloc(sizeof(*entry));
661 entry->supported_capabilities = 0;
663 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
668 process = &entry->subprocess.process;
670 if (!(entry->supported_capabilities & wanted_capability))
673 if (wanted_capability & CAP_CLEAN)
674 filter_type = "clean";
675 else if (wanted_capability & CAP_SMUDGE)
676 filter_type = "smudge";
678 die("unexpected filter type");
680 sigchain_push(SIGPIPE, SIG_IGN);
682 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
683 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
687 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
689 error("path name too long for external filter");
693 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
697 if ((entry->supported_capabilities & CAP_DELAY) &&
698 dco && dco->state == CE_CAN_DELAY) {
700 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
705 err = packet_flush_gently(process->in);
710 err = write_packetized_from_fd(fd, process->in);
712 err = write_packetized_from_buf(src, len, process->in);
716 err = subprocess_read_status(process->out, &filter_status);
720 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
721 string_list_insert(&dco->filters, cmd);
722 string_list_insert(&dco->paths, path);
724 /* The filter got the blob and wants to send us a response. */
725 err = strcmp(filter_status.buf, "success");
729 err = read_packetized_to_strbuf(process->out, &nbuf) < 0;
733 err = subprocess_read_status(process->out, &filter_status);
737 err = strcmp(filter_status.buf, "success");
741 sigchain_pop(SIGPIPE);
744 handle_filter_error(&filter_status, entry, wanted_capability);
746 strbuf_swap(dst, &nbuf);
747 strbuf_release(&nbuf);
752 int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
756 struct cmd2process *entry;
757 struct child_process *process;
758 struct strbuf filter_status = STRBUF_INIT;
760 assert(subprocess_map_initialized);
761 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
763 error("external filter '%s' is not available anymore although "
764 "not all paths have been filtered", cmd);
767 process = &entry->subprocess.process;
768 sigchain_push(SIGPIPE, SIG_IGN);
770 err = packet_write_fmt_gently(
771 process->in, "command=list_available_blobs\n");
775 err = packet_flush_gently(process->in);
779 while ((line = packet_read_line(process->out, NULL))) {
781 if (skip_prefix(line, "pathname=", &path))
782 string_list_insert(available_paths, xstrdup(path));
784 ; /* ignore unknown keys */
787 err = subprocess_read_status(process->out, &filter_status);
791 err = strcmp(filter_status.buf, "success");
794 sigchain_pop(SIGPIPE);
797 handle_filter_error(&filter_status, entry, 0);
801 static struct convert_driver {
803 struct convert_driver *next;
808 } *user_convert, **user_convert_tail;
810 static int apply_filter(const char *path, const char *src, size_t len,
811 int fd, struct strbuf *dst, struct convert_driver *drv,
812 const unsigned int wanted_capability,
813 struct delayed_checkout *dco)
815 const char *cmd = NULL;
823 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
825 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
829 return apply_single_file_filter(path, src, len, fd, dst, cmd);
830 else if (drv->process && *drv->process)
831 return apply_multi_file_filter(path, src, len, fd, dst,
832 drv->process, wanted_capability, dco);
837 static int read_convert_config(const char *var, const char *value, void *cb)
839 const char *key, *name;
841 struct convert_driver *drv;
844 * External conversion drivers are configured using
845 * "filter.<name>.variable".
847 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
849 for (drv = user_convert; drv; drv = drv->next)
850 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
853 drv = xcalloc(1, sizeof(struct convert_driver));
854 drv->name = xmemdupz(name, namelen);
855 *user_convert_tail = drv;
856 user_convert_tail = &(drv->next);
860 * filter.<name>.smudge and filter.<name>.clean specifies
865 * The command-line will not be interpolated in any way.
868 if (!strcmp("smudge", key))
869 return git_config_string(&drv->smudge, var, value);
871 if (!strcmp("clean", key))
872 return git_config_string(&drv->clean, var, value);
874 if (!strcmp("process", key))
875 return git_config_string(&drv->process, var, value);
877 if (!strcmp("required", key)) {
878 drv->required = git_config_bool(var, value);
885 static int count_ident(const char *cp, unsigned long size)
888 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
900 if (memcmp("Id", cp, 2))
911 * "$Id: ... "; scan up to the closing dollar sign and discard.
927 static int ident_to_git(const char *path, const char *src, size_t len,
928 struct strbuf *buf, int ident)
932 if (!ident || (src && !count_ident(src, len)))
938 /* only grow if not in place */
939 if (strbuf_avail(buf) + buf->len < len)
940 strbuf_grow(buf, len - buf->len);
943 dollar = memchr(src, '$', len);
946 memmove(dst, src, dollar + 1 - src);
947 dst += dollar + 1 - src;
948 len -= dollar + 1 - src;
951 if (len > 3 && !memcmp(src, "Id:", 3)) {
952 dollar = memchr(src + 3, '$', len - 3);
955 if (memchr(src + 3, '\n', dollar - src - 3)) {
956 /* Line break before the next dollar. */
960 memcpy(dst, "Id$", 3);
962 len -= dollar + 1 - src;
966 memmove(dst, src, len);
967 strbuf_setlen(buf, dst + len - buf->buf);
971 static int ident_to_worktree(const char *path, const char *src, size_t len,
972 struct strbuf *buf, int ident)
974 unsigned char sha1[20];
975 char *to_free = NULL, *dollar, *spc;
981 cnt = count_ident(src, len);
985 /* are we "faking" in place editing ? */
987 to_free = strbuf_detach(buf, NULL);
988 hash_sha1_file(src, len, "blob", sha1);
990 strbuf_grow(buf, len + cnt * 43);
992 /* step 1: run to the next '$' */
993 dollar = memchr(src, '$', len);
996 strbuf_add(buf, src, dollar + 1 - src);
997 len -= dollar + 1 - src;
1000 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1001 if (len < 3 || memcmp("Id", src, 2))
1004 /* step 3: skip over Id$ or Id:xxxxx$ */
1005 if (src[2] == '$') {
1008 } else if (src[2] == ':') {
1010 * It's possible that an expanded Id has crept its way into the
1011 * repository, we cope with that by stripping the expansion out.
1012 * This is probably not a good idea, since it will cause changes
1013 * on checkout, which won't go away by stash, but let's keep it
1014 * for git-style ids.
1016 dollar = memchr(src + 3, '$', len - 3);
1018 /* incomplete keyword, no more '$', so just quit the loop */
1022 if (memchr(src + 3, '\n', dollar - src - 3)) {
1023 /* Line break before the next dollar. */
1027 spc = memchr(src + 4, ' ', dollar - src - 4);
1028 if (spc && spc < dollar-1) {
1029 /* There are spaces in unexpected places.
1030 * This is probably an id from some other
1031 * versioning system. Keep it for now.
1036 len -= dollar + 1 - src;
1039 /* it wasn't a "Id$" or "Id:xxxx$" */
1043 /* step 4: substitute */
1044 strbuf_addstr(buf, "Id: ");
1045 strbuf_add(buf, sha1_to_hex(sha1), 40);
1046 strbuf_addstr(buf, " $");
1048 strbuf_add(buf, src, len);
1054 static const char *git_path_check_encoding(struct attr_check_item *check)
1056 const char *value = check->value;
1058 if (ATTR_UNSET(value) || !strlen(value))
1061 if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
1062 die(_("true/false are no valid working-tree-encodings"));
1065 /* Don't encode to the default encoding */
1066 if (same_encoding(value, default_encoding))
1072 static enum crlf_action git_path_check_crlf(struct attr_check_item *check)
1074 const char *value = check->value;
1076 if (ATTR_TRUE(value))
1078 else if (ATTR_FALSE(value))
1080 else if (ATTR_UNSET(value))
1082 else if (!strcmp(value, "input"))
1083 return CRLF_TEXT_INPUT;
1084 else if (!strcmp(value, "auto"))
1086 return CRLF_UNDEFINED;
1089 static enum eol git_path_check_eol(struct attr_check_item *check)
1091 const char *value = check->value;
1093 if (ATTR_UNSET(value))
1095 else if (!strcmp(value, "lf"))
1097 else if (!strcmp(value, "crlf"))
1102 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
1104 const char *value = check->value;
1105 struct convert_driver *drv;
1107 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1109 for (drv = user_convert; drv; drv = drv->next)
1110 if (!strcmp(value, drv->name))
1115 static int git_path_check_ident(struct attr_check_item *check)
1117 const char *value = check->value;
1119 return !!ATTR_TRUE(value);
1123 struct convert_driver *drv;
1124 enum crlf_action attr_action; /* What attr says */
1125 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
1127 const char *working_tree_encoding; /* Supported encoding or default encoding if NULL */
1130 static void convert_attrs(struct conv_attrs *ca, const char *path)
1132 static struct attr_check *check;
1135 check = attr_check_initl("crlf", "ident", "filter",
1136 "eol", "text", "working-tree-encoding",
1138 user_convert_tail = &user_convert;
1139 git_config(read_convert_config, NULL);
1142 if (!git_check_attr(path, check)) {
1143 struct attr_check_item *ccheck = check->items;
1144 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1145 if (ca->crlf_action == CRLF_UNDEFINED)
1146 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1147 ca->ident = git_path_check_ident(ccheck + 1);
1148 ca->drv = git_path_check_convert(ccheck + 2);
1149 if (ca->crlf_action != CRLF_BINARY) {
1150 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1151 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1152 ca->crlf_action = CRLF_AUTO_INPUT;
1153 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1154 ca->crlf_action = CRLF_AUTO_CRLF;
1155 else if (eol_attr == EOL_LF)
1156 ca->crlf_action = CRLF_TEXT_INPUT;
1157 else if (eol_attr == EOL_CRLF)
1158 ca->crlf_action = CRLF_TEXT_CRLF;
1160 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
1163 ca->crlf_action = CRLF_UNDEFINED;
1167 /* Save attr and make a decision for action */
1168 ca->attr_action = ca->crlf_action;
1169 if (ca->crlf_action == CRLF_TEXT)
1170 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1171 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1172 ca->crlf_action = CRLF_BINARY;
1173 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1174 ca->crlf_action = CRLF_AUTO_CRLF;
1175 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1176 ca->crlf_action = CRLF_AUTO_INPUT;
1179 int would_convert_to_git_filter_fd(const char *path)
1181 struct conv_attrs ca;
1183 convert_attrs(&ca, path);
1188 * Apply a filter to an fd only if the filter is required to succeed.
1189 * We must die if the filter fails, because the original data before
1190 * filtering is not available.
1192 if (!ca.drv->required)
1195 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL);
1198 const char *get_convert_attr_ascii(const char *path)
1200 struct conv_attrs ca;
1202 convert_attrs(&ca, path);
1203 switch (ca.attr_action) {
1204 case CRLF_UNDEFINED:
1210 case CRLF_TEXT_INPUT:
1211 return "text eol=lf";
1212 case CRLF_TEXT_CRLF:
1213 return "text eol=crlf";
1216 case CRLF_AUTO_CRLF:
1217 return "text=auto eol=crlf";
1218 case CRLF_AUTO_INPUT:
1219 return "text=auto eol=lf";
1224 int convert_to_git(const struct index_state *istate,
1225 const char *path, const char *src, size_t len,
1226 struct strbuf *dst, int conv_flags)
1229 struct conv_attrs ca;
1231 convert_attrs(&ca, path);
1233 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL);
1234 if (!ret && ca.drv && ca.drv->required)
1235 die("%s: clean filter '%s' failed", path, ca.drv->name);
1242 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1248 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1249 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
1255 return ret | ident_to_git(path, src, len, dst, ca.ident);
1258 void convert_to_git_filter_fd(const struct index_state *istate,
1259 const char *path, int fd, struct strbuf *dst,
1262 struct conv_attrs ca;
1263 convert_attrs(&ca, path);
1266 assert(ca.drv->clean || ca.drv->process);
1268 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL))
1269 die("%s: clean filter '%s' failed", path, ca.drv->name);
1271 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
1272 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
1273 ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
1276 static int convert_to_working_tree_internal(const char *path, const char *src,
1277 size_t len, struct strbuf *dst,
1278 int normalizing, struct delayed_checkout *dco)
1280 int ret = 0, ret_filter = 0;
1281 struct conv_attrs ca;
1283 convert_attrs(&ca, path);
1285 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
1291 * CRLF conversion can be skipped if normalizing, unless there
1292 * is a smudge or process filter (even if the process filter doesn't
1293 * support smudge). The filters might expect CRLFs.
1295 if ((ca.drv && (ca.drv->smudge || ca.drv->process)) || !normalizing) {
1296 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
1303 ret |= encode_to_worktree(path, src, len, dst, ca.working_tree_encoding);
1309 ret_filter = apply_filter(
1310 path, src, len, -1, dst, ca.drv, CAP_SMUDGE, dco);
1311 if (!ret_filter && ca.drv && ca.drv->required)
1312 die("%s: smudge filter %s failed", path, ca.drv->name);
1314 return ret | ret_filter;
1317 int async_convert_to_working_tree(const char *path, const char *src,
1318 size_t len, struct strbuf *dst,
1321 return convert_to_working_tree_internal(path, src, len, dst, 0, dco);
1324 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
1326 return convert_to_working_tree_internal(path, src, len, dst, 0, NULL);
1329 int renormalize_buffer(const struct index_state *istate, const char *path,
1330 const char *src, size_t len, struct strbuf *dst)
1332 int ret = convert_to_working_tree_internal(path, src, len, dst, 1, NULL);
1337 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
1340 /*****************************************************************
1342 * Streaming conversion support
1344 *****************************************************************/
1346 typedef int (*filter_fn)(struct stream_filter *,
1347 const char *input, size_t *isize_p,
1348 char *output, size_t *osize_p);
1349 typedef void (*free_fn)(struct stream_filter *);
1351 struct stream_filter_vtbl {
1356 struct stream_filter {
1357 struct stream_filter_vtbl *vtbl;
1360 static int null_filter_fn(struct stream_filter *filter,
1361 const char *input, size_t *isize_p,
1362 char *output, size_t *osize_p)
1367 return 0; /* we do not keep any states */
1369 if (*osize_p < count)
1372 memmove(output, input, count);
1379 static void null_free_fn(struct stream_filter *filter)
1381 ; /* nothing -- null instances are shared */
1384 static struct stream_filter_vtbl null_vtbl = {
1389 static struct stream_filter null_filter_singleton = {
1393 int is_null_stream_filter(struct stream_filter *filter)
1395 return filter == &null_filter_singleton;
1403 struct lf_to_crlf_filter {
1404 struct stream_filter filter;
1405 unsigned has_held:1;
1409 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1410 const char *input, size_t *isize_p,
1411 char *output, size_t *osize_p)
1413 size_t count, o = 0;
1414 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1417 * We may be holding onto the CR to see if it is followed by a
1418 * LF, in which case we would need to go to the main loop.
1419 * Otherwise, just emit it to the output stream.
1421 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1422 output[o++] = lf_to_crlf->held;
1423 lf_to_crlf->has_held = 0;
1426 /* We are told to drain */
1433 if (count || lf_to_crlf->has_held) {
1437 if (lf_to_crlf->has_held) {
1439 lf_to_crlf->has_held = 0;
1442 for (i = 0; o < *osize_p && i < count; i++) {
1447 } else if (was_cr) {
1449 * Previous round saw CR and it is not followed
1450 * by a LF; emit the CR before processing the
1451 * current character.
1457 * We may have consumed the last output slot,
1458 * in which case we need to break out of this
1459 * loop; hold the current character before
1462 if (*osize_p <= o) {
1463 lf_to_crlf->has_held = 1;
1464 lf_to_crlf->held = ch;
1465 continue; /* break but increment i */
1480 if (!lf_to_crlf->has_held && was_cr) {
1481 lf_to_crlf->has_held = 1;
1482 lf_to_crlf->held = '\r';
1488 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1493 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1494 lf_to_crlf_filter_fn,
1498 static struct stream_filter *lf_to_crlf_filter(void)
1500 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1502 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1503 return (struct stream_filter *)lf_to_crlf;
1509 #define FILTER_BUFFER 1024
1510 struct cascade_filter {
1511 struct stream_filter filter;
1512 struct stream_filter *one;
1513 struct stream_filter *two;
1514 char buf[FILTER_BUFFER];
1518 static int cascade_filter_fn(struct stream_filter *filter,
1519 const char *input, size_t *isize_p,
1520 char *output, size_t *osize_p)
1522 struct cascade_filter *cas = (struct cascade_filter *) filter;
1524 size_t sz = *osize_p;
1525 size_t to_feed, remaining;
1528 * input -- (one) --> buf -- (two) --> output
1530 while (filled < sz) {
1531 remaining = sz - filled;
1533 /* do we already have something to feed two with? */
1534 if (cas->ptr < cas->end) {
1535 to_feed = cas->end - cas->ptr;
1536 if (stream_filter(cas->two,
1537 cas->buf + cas->ptr, &to_feed,
1538 output + filled, &remaining))
1540 cas->ptr += (cas->end - cas->ptr) - to_feed;
1541 filled = sz - remaining;
1545 /* feed one from upstream and have it emit into our buffer */
1546 to_feed = input ? *isize_p : 0;
1547 if (input && !to_feed)
1549 remaining = sizeof(cas->buf);
1550 if (stream_filter(cas->one,
1552 cas->buf, &remaining))
1554 cas->end = sizeof(cas->buf) - remaining;
1557 size_t fed = *isize_p - to_feed;
1562 /* do we know that we drained one completely? */
1563 if (input || cas->end)
1566 /* tell two to drain; we have nothing more to give it */
1568 remaining = sz - filled;
1569 if (stream_filter(cas->two,
1571 output + filled, &remaining))
1573 if (remaining == (sz - filled))
1574 break; /* completely drained two */
1575 filled = sz - remaining;
1581 static void cascade_free_fn(struct stream_filter *filter)
1583 struct cascade_filter *cas = (struct cascade_filter *)filter;
1584 free_stream_filter(cas->one);
1585 free_stream_filter(cas->two);
1589 static struct stream_filter_vtbl cascade_vtbl = {
1594 static struct stream_filter *cascade_filter(struct stream_filter *one,
1595 struct stream_filter *two)
1597 struct cascade_filter *cascade;
1599 if (!one || is_null_stream_filter(one))
1601 if (!two || is_null_stream_filter(two))
1604 cascade = xmalloc(sizeof(*cascade));
1607 cascade->end = cascade->ptr = 0;
1608 cascade->filter.vtbl = &cascade_vtbl;
1609 return (struct stream_filter *)cascade;
1615 #define IDENT_DRAINING (-1)
1616 #define IDENT_SKIPPING (-2)
1617 struct ident_filter {
1618 struct stream_filter filter;
1621 char ident[45]; /* ": x40 $" */
1624 static int is_foreign_ident(const char *str)
1628 if (!skip_prefix(str, "$Id: ", &str))
1630 for (i = 0; str[i]; i++) {
1631 if (isspace(str[i]) && str[i+1] != '$')
1637 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1639 size_t to_drain = ident->left.len;
1641 if (*osize_p < to_drain)
1642 to_drain = *osize_p;
1644 memcpy(*output_p, ident->left.buf, to_drain);
1645 strbuf_remove(&ident->left, 0, to_drain);
1646 *output_p += to_drain;
1647 *osize_p -= to_drain;
1649 if (!ident->left.len)
1653 static int ident_filter_fn(struct stream_filter *filter,
1654 const char *input, size_t *isize_p,
1655 char *output, size_t *osize_p)
1657 struct ident_filter *ident = (struct ident_filter *)filter;
1658 static const char head[] = "$Id";
1661 /* drain upon eof */
1662 switch (ident->state) {
1664 strbuf_add(&ident->left, head, ident->state);
1666 case IDENT_SKIPPING:
1668 case IDENT_DRAINING:
1669 ident_drain(ident, &output, osize_p);
1674 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1677 if (ident->state == IDENT_DRAINING) {
1678 ident_drain(ident, &output, osize_p);
1687 if (ident->state == IDENT_SKIPPING) {
1689 * Skipping until '$' or LF, but keeping them
1690 * in case it is a foreign ident.
1692 strbuf_addch(&ident->left, ch);
1693 if (ch != '\n' && ch != '$')
1695 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1696 strbuf_setlen(&ident->left, sizeof(head) - 1);
1697 strbuf_addstr(&ident->left, ident->ident);
1699 ident->state = IDENT_DRAINING;
1703 if (ident->state < sizeof(head) &&
1704 head[ident->state] == ch) {
1710 strbuf_add(&ident->left, head, ident->state);
1711 if (ident->state == sizeof(head) - 1) {
1712 if (ch != ':' && ch != '$') {
1713 strbuf_addch(&ident->left, ch);
1719 strbuf_addch(&ident->left, ch);
1720 ident->state = IDENT_SKIPPING;
1722 strbuf_addstr(&ident->left, ident->ident);
1723 ident->state = IDENT_DRAINING;
1728 strbuf_addch(&ident->left, ch);
1729 ident->state = IDENT_DRAINING;
1734 static void ident_free_fn(struct stream_filter *filter)
1736 struct ident_filter *ident = (struct ident_filter *)filter;
1737 strbuf_release(&ident->left);
1741 static struct stream_filter_vtbl ident_vtbl = {
1746 static struct stream_filter *ident_filter(const unsigned char *sha1)
1748 struct ident_filter *ident = xmalloc(sizeof(*ident));
1750 xsnprintf(ident->ident, sizeof(ident->ident),
1751 ": %s $", sha1_to_hex(sha1));
1752 strbuf_init(&ident->left, 0);
1753 ident->filter.vtbl = &ident_vtbl;
1755 return (struct stream_filter *)ident;
1759 * Return an appropriately constructed filter for the path, or NULL if
1760 * the contents cannot be filtered without reading the whole thing
1763 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1764 * large binary blob you would want us not to slurp into the memory!
1766 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1768 struct conv_attrs ca;
1769 struct stream_filter *filter = NULL;
1771 convert_attrs(&ca, path);
1772 if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
1775 if (ca.working_tree_encoding)
1778 if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1782 filter = ident_filter(sha1);
1784 if (output_eol(ca.crlf_action) == EOL_CRLF)
1785 filter = cascade_filter(filter, lf_to_crlf_filter());
1787 filter = cascade_filter(filter, &null_filter_singleton);
1792 void free_stream_filter(struct stream_filter *filter)
1794 filter->vtbl->free(filter);
1797 int stream_filter(struct stream_filter *filter,
1798 const char *input, size_t *isize_p,
1799 char *output, size_t *osize_p)
1801 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);