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 int validate_encoding(const char *path, const char *enc,
270 const char *data, size_t len, int die_on_error)
272 /* We only check for UTF here as UTF?? can be an alias for UTF-?? */
273 if (istarts_with(enc, "UTF")) {
275 * Check for detectable errors in UTF encodings
277 if (has_prohibited_utf_bom(enc, data, len)) {
278 const char *error_msg = _(
279 "BOM is prohibited in '%s' if encoded as %s");
281 * This advice is shown for UTF-??BE and UTF-??LE encodings.
282 * We cut off the last two characters of the encoding name
283 * to generate the encoding name suitable for BOMs.
285 const char *advise_msg = _(
286 "The file '%s' contains a byte order "
287 "mark (BOM). Please use UTF-%s as "
288 "working-tree-encoding.");
289 const char *stripped = NULL;
290 char *upper = xstrdup_toupper(enc);
291 upper[strlen(upper)-2] = '\0';
292 if (!skip_prefix(upper, "UTF-", &stripped))
293 skip_prefix(stripped, "UTF", &stripped);
294 advise(advise_msg, path, stripped);
297 die(error_msg, path, enc);
299 return error(error_msg, path, enc);
302 } else if (is_missing_required_utf_bom(enc, data, len)) {
303 const char *error_msg = _(
304 "BOM is required in '%s' if encoded as %s");
305 const char *advise_msg = _(
306 "The file '%s' is missing a byte order "
307 "mark (BOM). Please use UTF-%sBE or UTF-%sLE "
308 "(depending on the byte order) as "
309 "working-tree-encoding.");
310 const char *stripped = NULL;
311 char *upper = xstrdup_toupper(enc);
312 if (!skip_prefix(upper, "UTF-", &stripped))
313 skip_prefix(stripped, "UTF", &stripped);
314 advise(advise_msg, path, stripped, stripped);
317 die(error_msg, path, enc);
319 return error(error_msg, path, enc);
327 static void trace_encoding(const char *context, const char *path,
328 const char *encoding, const char *buf, size_t len)
330 static struct trace_key coe = TRACE_KEY_INIT(WORKING_TREE_ENCODING);
331 struct strbuf trace = STRBUF_INIT;
334 strbuf_addf(&trace, "%s (%s, considered %s):\n", context, path, encoding);
335 for (i = 0; i < len && buf; ++i) {
337 &trace,"| \e[2m%2i:\e[0m %2x \e[2m%c\e[0m%c",
339 (unsigned char) buf[i],
340 (buf[i] > 32 && buf[i] < 127 ? buf[i] : ' '),
341 ((i+1) % 8 && (i+1) < len ? ' ' : '\n')
344 strbuf_addchars(&trace, '\n', 1);
346 trace_strbuf(&coe, &trace);
347 strbuf_release(&trace);
350 static const char *default_encoding = "UTF-8";
352 static int encode_to_git(const char *path, const char *src, size_t src_len,
353 struct strbuf *buf, const char *enc, int conv_flags)
357 int die_on_error = conv_flags & CONV_WRITE_OBJECT;
360 * No encoding is specified or there is nothing to encode.
361 * Tell the caller that the content was not modified.
363 if (!enc || (src && !src_len))
367 * Looks like we got called from "would_convert_to_git()".
368 * This means Git wants to know if it would encode (= modify!)
369 * the content. Let's answer with "yes", since an encoding was
375 if (validate_encoding(path, enc, src, src_len, die_on_error))
378 trace_encoding("source", path, enc, src, src_len);
379 dst = reencode_string_len(src, src_len, default_encoding, enc,
383 * We could add the blob "as-is" to Git. However, on checkout
384 * we would try to reencode to the original encoding. This
385 * would fail and we would leave the user with a messed-up
386 * working tree. Let's try to avoid this by screaming loud.
388 const char* msg = _("failed to encode '%s' from %s to %s");
390 die(msg, path, enc, default_encoding);
392 error(msg, path, enc, default_encoding);
396 trace_encoding("destination", path, default_encoding, dst, dst_len);
398 strbuf_attach(buf, dst, dst_len, dst_len + 1);
402 static int encode_to_worktree(const char *path, const char *src, size_t src_len,
403 struct strbuf *buf, const char *enc)
409 * No encoding is specified or there is nothing to encode.
410 * Tell the caller that the content was not modified.
412 if (!enc || (src && !src_len))
415 dst = reencode_string_len(src, src_len, enc, default_encoding,
418 error("failed to encode '%s' from %s to %s",
419 path, default_encoding, enc);
423 strbuf_attach(buf, dst, dst_len, dst_len + 1);
427 static int crlf_to_git(const struct index_state *istate,
428 const char *path, const char *src, size_t len,
430 enum crlf_action crlf_action, int conv_flags)
432 struct text_stat stats;
434 int convert_crlf_into_lf;
436 if (crlf_action == CRLF_BINARY ||
441 * If we are doing a dry-run and have no source buffer, there is
442 * nothing to analyze; we must assume we would convert.
447 gather_stats(src, len, &stats);
448 /* Optimization: No CRLF? Nothing to convert, regardless. */
449 convert_crlf_into_lf = !!stats.crlf;
451 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
452 if (convert_is_binary(len, &stats))
455 * If the file in the index has any CR in it, do not
456 * convert. This is the new safer autocrlf handling,
457 * unless we want to renormalize in a merge or
460 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
461 has_crlf_in_index(istate, path))
462 convert_crlf_into_lf = 0;
464 if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
465 ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
466 struct text_stat new_stats;
467 memcpy(&new_stats, &stats, sizeof(new_stats));
468 /* simulate "git add" */
469 if (convert_crlf_into_lf) {
470 new_stats.lonelf += new_stats.crlf;
473 /* simulate "git checkout" */
474 if (will_convert_lf_to_crlf(len, &new_stats, crlf_action)) {
475 new_stats.crlf += new_stats.lonelf;
476 new_stats.lonelf = 0;
478 check_global_conv_flags_eol(path, crlf_action, &stats, &new_stats, conv_flags);
480 if (!convert_crlf_into_lf)
484 * At this point all of our source analysis is done, and we are sure we
485 * would convert. If we are in dry-run mode, we can give an answer.
490 /* only grow if not in place */
491 if (strbuf_avail(buf) + buf->len < len)
492 strbuf_grow(buf, len - buf->len);
494 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
496 * If we guessed, we already know we rejected a file with
497 * lone CR, and we can strip a CR without looking at what
501 unsigned char c = *src++;
507 unsigned char c = *src++;
508 if (! (c == '\r' && (1 < len && *src == '\n')))
512 strbuf_setlen(buf, dst - buf->buf);
516 static int crlf_to_worktree(const char *path, const char *src, size_t len,
517 struct strbuf *buf, enum crlf_action crlf_action)
519 char *to_free = NULL;
520 struct text_stat stats;
522 if (!len || output_eol(crlf_action) != EOL_CRLF)
525 gather_stats(src, len, &stats);
526 if (!will_convert_lf_to_crlf(len, &stats, crlf_action))
529 /* are we "faking" in place editing ? */
531 to_free = strbuf_detach(buf, NULL);
533 strbuf_grow(buf, len + stats.lonelf);
535 const char *nl = memchr(src, '\n', len);
538 if (nl > src && nl[-1] == '\r') {
539 strbuf_add(buf, src, nl + 1 - src);
541 strbuf_add(buf, src, nl - src);
542 strbuf_addstr(buf, "\r\n");
547 strbuf_add(buf, src, len);
553 struct filter_params {
561 static int filter_buffer_or_fd(int in, int out, void *data)
564 * Spawn cmd and feed the buffer contents through its stdin.
566 struct child_process child_process = CHILD_PROCESS_INIT;
567 struct filter_params *params = (struct filter_params *)data;
568 int write_err, status;
569 const char *argv[] = { NULL, NULL };
571 /* apply % substitution to cmd */
572 struct strbuf cmd = STRBUF_INIT;
573 struct strbuf path = STRBUF_INIT;
574 struct strbuf_expand_dict_entry dict[] = {
579 /* quote the path to preserve spaces, etc. */
580 sq_quote_buf(&path, params->path);
581 dict[0].value = path.buf;
583 /* expand all %f with the quoted path */
584 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
585 strbuf_release(&path);
589 child_process.argv = argv;
590 child_process.use_shell = 1;
591 child_process.in = -1;
592 child_process.out = out;
594 if (start_command(&child_process)) {
595 strbuf_release(&cmd);
596 return error("cannot fork to run external filter '%s'", params->cmd);
599 sigchain_push(SIGPIPE, SIG_IGN);
602 write_err = (write_in_full(child_process.in,
603 params->src, params->size) < 0);
607 write_err = copy_fd(params->fd, child_process.in);
608 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
612 if (close(child_process.in))
615 error("cannot feed the input to external filter '%s'", params->cmd);
617 sigchain_pop(SIGPIPE);
619 status = finish_command(&child_process);
621 error("external filter '%s' failed %d", params->cmd, status);
623 strbuf_release(&cmd);
624 return (write_err || status);
627 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
628 struct strbuf *dst, const char *cmd)
631 * Create a pipeline to have the command filter the buffer's
634 * (child --> cmd) --> us
637 struct strbuf nbuf = STRBUF_INIT;
639 struct filter_params params;
641 memset(&async, 0, sizeof(async));
642 async.proc = filter_buffer_or_fd;
643 async.data = ¶ms;
652 if (start_async(&async))
653 return 0; /* error was already reported */
655 if (strbuf_read(&nbuf, async.out, len) < 0) {
656 err = error("read from external filter '%s' failed", cmd);
658 if (close(async.out)) {
659 err = error("read from external filter '%s' failed", cmd);
661 if (finish_async(&async)) {
662 err = error("external filter '%s' failed", cmd);
666 strbuf_swap(dst, &nbuf);
668 strbuf_release(&nbuf);
672 #define CAP_CLEAN (1u<<0)
673 #define CAP_SMUDGE (1u<<1)
674 #define CAP_DELAY (1u<<2)
677 struct subprocess_entry subprocess; /* must be the first member! */
678 unsigned int supported_capabilities;
681 static int subprocess_map_initialized;
682 static struct hashmap subprocess_map;
684 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
686 static int versions[] = {2, 0};
687 static struct subprocess_capability capabilities[] = {
688 { "clean", CAP_CLEAN },
689 { "smudge", CAP_SMUDGE },
690 { "delay", CAP_DELAY },
693 struct cmd2process *entry = (struct cmd2process *)subprocess;
694 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
696 &entry->supported_capabilities);
699 static void handle_filter_error(const struct strbuf *filter_status,
700 struct cmd2process *entry,
701 const unsigned int wanted_capability) {
702 if (!strcmp(filter_status->buf, "error"))
703 ; /* The filter signaled a problem with the file. */
704 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
706 * The filter signaled a permanent problem. Don't try to filter
707 * files with the same command for the lifetime of the current
710 entry->supported_capabilities &= ~wanted_capability;
713 * Something went wrong with the protocol filter.
714 * Force shutdown and restart if another blob requires filtering.
716 error("external filter '%s' failed", entry->subprocess.cmd);
717 subprocess_stop(&subprocess_map, &entry->subprocess);
722 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
723 int fd, struct strbuf *dst, const char *cmd,
724 const unsigned int wanted_capability,
725 struct delayed_checkout *dco)
729 struct cmd2process *entry;
730 struct child_process *process;
731 struct strbuf nbuf = STRBUF_INIT;
732 struct strbuf filter_status = STRBUF_INIT;
733 const char *filter_type;
735 if (!subprocess_map_initialized) {
736 subprocess_map_initialized = 1;
737 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
740 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
746 entry = xmalloc(sizeof(*entry));
747 entry->supported_capabilities = 0;
749 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
754 process = &entry->subprocess.process;
756 if (!(entry->supported_capabilities & wanted_capability))
759 if (wanted_capability & CAP_CLEAN)
760 filter_type = "clean";
761 else if (wanted_capability & CAP_SMUDGE)
762 filter_type = "smudge";
764 die("unexpected filter type");
766 sigchain_push(SIGPIPE, SIG_IGN);
768 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
769 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
773 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
775 error("path name too long for external filter");
779 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
783 if ((entry->supported_capabilities & CAP_DELAY) &&
784 dco && dco->state == CE_CAN_DELAY) {
786 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
791 err = packet_flush_gently(process->in);
796 err = write_packetized_from_fd(fd, process->in);
798 err = write_packetized_from_buf(src, len, process->in);
802 err = subprocess_read_status(process->out, &filter_status);
806 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
807 string_list_insert(&dco->filters, cmd);
808 string_list_insert(&dco->paths, path);
810 /* The filter got the blob and wants to send us a response. */
811 err = strcmp(filter_status.buf, "success");
815 err = read_packetized_to_strbuf(process->out, &nbuf) < 0;
819 err = subprocess_read_status(process->out, &filter_status);
823 err = strcmp(filter_status.buf, "success");
827 sigchain_pop(SIGPIPE);
830 handle_filter_error(&filter_status, entry, wanted_capability);
832 strbuf_swap(dst, &nbuf);
833 strbuf_release(&nbuf);
838 int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
842 struct cmd2process *entry;
843 struct child_process *process;
844 struct strbuf filter_status = STRBUF_INIT;
846 assert(subprocess_map_initialized);
847 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
849 error("external filter '%s' is not available anymore although "
850 "not all paths have been filtered", cmd);
853 process = &entry->subprocess.process;
854 sigchain_push(SIGPIPE, SIG_IGN);
856 err = packet_write_fmt_gently(
857 process->in, "command=list_available_blobs\n");
861 err = packet_flush_gently(process->in);
865 while ((line = packet_read_line(process->out, NULL))) {
867 if (skip_prefix(line, "pathname=", &path))
868 string_list_insert(available_paths, xstrdup(path));
870 ; /* ignore unknown keys */
873 err = subprocess_read_status(process->out, &filter_status);
877 err = strcmp(filter_status.buf, "success");
880 sigchain_pop(SIGPIPE);
883 handle_filter_error(&filter_status, entry, 0);
887 static struct convert_driver {
889 struct convert_driver *next;
894 } *user_convert, **user_convert_tail;
896 static int apply_filter(const char *path, const char *src, size_t len,
897 int fd, struct strbuf *dst, struct convert_driver *drv,
898 const unsigned int wanted_capability,
899 struct delayed_checkout *dco)
901 const char *cmd = NULL;
909 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
911 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
915 return apply_single_file_filter(path, src, len, fd, dst, cmd);
916 else if (drv->process && *drv->process)
917 return apply_multi_file_filter(path, src, len, fd, dst,
918 drv->process, wanted_capability, dco);
923 static int read_convert_config(const char *var, const char *value, void *cb)
925 const char *key, *name;
927 struct convert_driver *drv;
930 * External conversion drivers are configured using
931 * "filter.<name>.variable".
933 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
935 for (drv = user_convert; drv; drv = drv->next)
936 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
939 drv = xcalloc(1, sizeof(struct convert_driver));
940 drv->name = xmemdupz(name, namelen);
941 *user_convert_tail = drv;
942 user_convert_tail = &(drv->next);
946 * filter.<name>.smudge and filter.<name>.clean specifies
951 * The command-line will not be interpolated in any way.
954 if (!strcmp("smudge", key))
955 return git_config_string(&drv->smudge, var, value);
957 if (!strcmp("clean", key))
958 return git_config_string(&drv->clean, var, value);
960 if (!strcmp("process", key))
961 return git_config_string(&drv->process, var, value);
963 if (!strcmp("required", key)) {
964 drv->required = git_config_bool(var, value);
971 static int count_ident(const char *cp, unsigned long size)
974 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
986 if (memcmp("Id", cp, 2))
997 * "$Id: ... "; scan up to the closing dollar sign and discard.
1013 static int ident_to_git(const char *path, const char *src, size_t len,
1014 struct strbuf *buf, int ident)
1018 if (!ident || (src && !count_ident(src, len)))
1024 /* only grow if not in place */
1025 if (strbuf_avail(buf) + buf->len < len)
1026 strbuf_grow(buf, len - buf->len);
1029 dollar = memchr(src, '$', len);
1032 memmove(dst, src, dollar + 1 - src);
1033 dst += dollar + 1 - src;
1034 len -= dollar + 1 - src;
1037 if (len > 3 && !memcmp(src, "Id:", 3)) {
1038 dollar = memchr(src + 3, '$', len - 3);
1041 if (memchr(src + 3, '\n', dollar - src - 3)) {
1042 /* Line break before the next dollar. */
1046 memcpy(dst, "Id$", 3);
1048 len -= dollar + 1 - src;
1052 memmove(dst, src, len);
1053 strbuf_setlen(buf, dst + len - buf->buf);
1057 static int ident_to_worktree(const char *path, const char *src, size_t len,
1058 struct strbuf *buf, int ident)
1060 unsigned char sha1[20];
1061 char *to_free = NULL, *dollar, *spc;
1067 cnt = count_ident(src, len);
1071 /* are we "faking" in place editing ? */
1072 if (src == buf->buf)
1073 to_free = strbuf_detach(buf, NULL);
1074 hash_sha1_file(src, len, "blob", sha1);
1076 strbuf_grow(buf, len + cnt * 43);
1078 /* step 1: run to the next '$' */
1079 dollar = memchr(src, '$', len);
1082 strbuf_add(buf, src, dollar + 1 - src);
1083 len -= dollar + 1 - src;
1086 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1087 if (len < 3 || memcmp("Id", src, 2))
1090 /* step 3: skip over Id$ or Id:xxxxx$ */
1091 if (src[2] == '$') {
1094 } else if (src[2] == ':') {
1096 * It's possible that an expanded Id has crept its way into the
1097 * repository, we cope with that by stripping the expansion out.
1098 * This is probably not a good idea, since it will cause changes
1099 * on checkout, which won't go away by stash, but let's keep it
1100 * for git-style ids.
1102 dollar = memchr(src + 3, '$', len - 3);
1104 /* incomplete keyword, no more '$', so just quit the loop */
1108 if (memchr(src + 3, '\n', dollar - src - 3)) {
1109 /* Line break before the next dollar. */
1113 spc = memchr(src + 4, ' ', dollar - src - 4);
1114 if (spc && spc < dollar-1) {
1115 /* There are spaces in unexpected places.
1116 * This is probably an id from some other
1117 * versioning system. Keep it for now.
1122 len -= dollar + 1 - src;
1125 /* it wasn't a "Id$" or "Id:xxxx$" */
1129 /* step 4: substitute */
1130 strbuf_addstr(buf, "Id: ");
1131 strbuf_add(buf, sha1_to_hex(sha1), 40);
1132 strbuf_addstr(buf, " $");
1134 strbuf_add(buf, src, len);
1140 static const char *git_path_check_encoding(struct attr_check_item *check)
1142 const char *value = check->value;
1144 if (ATTR_UNSET(value) || !strlen(value))
1147 if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
1148 die(_("true/false are no valid working-tree-encodings"));
1151 /* Don't encode to the default encoding */
1152 if (same_encoding(value, default_encoding))
1158 static enum crlf_action git_path_check_crlf(struct attr_check_item *check)
1160 const char *value = check->value;
1162 if (ATTR_TRUE(value))
1164 else if (ATTR_FALSE(value))
1166 else if (ATTR_UNSET(value))
1168 else if (!strcmp(value, "input"))
1169 return CRLF_TEXT_INPUT;
1170 else if (!strcmp(value, "auto"))
1172 return CRLF_UNDEFINED;
1175 static enum eol git_path_check_eol(struct attr_check_item *check)
1177 const char *value = check->value;
1179 if (ATTR_UNSET(value))
1181 else if (!strcmp(value, "lf"))
1183 else if (!strcmp(value, "crlf"))
1188 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
1190 const char *value = check->value;
1191 struct convert_driver *drv;
1193 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1195 for (drv = user_convert; drv; drv = drv->next)
1196 if (!strcmp(value, drv->name))
1201 static int git_path_check_ident(struct attr_check_item *check)
1203 const char *value = check->value;
1205 return !!ATTR_TRUE(value);
1209 struct convert_driver *drv;
1210 enum crlf_action attr_action; /* What attr says */
1211 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
1213 const char *working_tree_encoding; /* Supported encoding or default encoding if NULL */
1216 static void convert_attrs(struct conv_attrs *ca, const char *path)
1218 static struct attr_check *check;
1221 check = attr_check_initl("crlf", "ident", "filter",
1222 "eol", "text", "working-tree-encoding",
1224 user_convert_tail = &user_convert;
1225 git_config(read_convert_config, NULL);
1228 if (!git_check_attr(path, check)) {
1229 struct attr_check_item *ccheck = check->items;
1230 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1231 if (ca->crlf_action == CRLF_UNDEFINED)
1232 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1233 ca->ident = git_path_check_ident(ccheck + 1);
1234 ca->drv = git_path_check_convert(ccheck + 2);
1235 if (ca->crlf_action != CRLF_BINARY) {
1236 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1237 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1238 ca->crlf_action = CRLF_AUTO_INPUT;
1239 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1240 ca->crlf_action = CRLF_AUTO_CRLF;
1241 else if (eol_attr == EOL_LF)
1242 ca->crlf_action = CRLF_TEXT_INPUT;
1243 else if (eol_attr == EOL_CRLF)
1244 ca->crlf_action = CRLF_TEXT_CRLF;
1246 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
1249 ca->crlf_action = CRLF_UNDEFINED;
1253 /* Save attr and make a decision for action */
1254 ca->attr_action = ca->crlf_action;
1255 if (ca->crlf_action == CRLF_TEXT)
1256 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1257 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1258 ca->crlf_action = CRLF_BINARY;
1259 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1260 ca->crlf_action = CRLF_AUTO_CRLF;
1261 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1262 ca->crlf_action = CRLF_AUTO_INPUT;
1265 int would_convert_to_git_filter_fd(const char *path)
1267 struct conv_attrs ca;
1269 convert_attrs(&ca, path);
1274 * Apply a filter to an fd only if the filter is required to succeed.
1275 * We must die if the filter fails, because the original data before
1276 * filtering is not available.
1278 if (!ca.drv->required)
1281 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL);
1284 const char *get_convert_attr_ascii(const char *path)
1286 struct conv_attrs ca;
1288 convert_attrs(&ca, path);
1289 switch (ca.attr_action) {
1290 case CRLF_UNDEFINED:
1296 case CRLF_TEXT_INPUT:
1297 return "text eol=lf";
1298 case CRLF_TEXT_CRLF:
1299 return "text eol=crlf";
1302 case CRLF_AUTO_CRLF:
1303 return "text=auto eol=crlf";
1304 case CRLF_AUTO_INPUT:
1305 return "text=auto eol=lf";
1310 int convert_to_git(const struct index_state *istate,
1311 const char *path, const char *src, size_t len,
1312 struct strbuf *dst, int conv_flags)
1315 struct conv_attrs ca;
1317 convert_attrs(&ca, path);
1319 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL);
1320 if (!ret && ca.drv && ca.drv->required)
1321 die("%s: clean filter '%s' failed", path, ca.drv->name);
1328 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1334 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1335 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
1341 return ret | ident_to_git(path, src, len, dst, ca.ident);
1344 void convert_to_git_filter_fd(const struct index_state *istate,
1345 const char *path, int fd, struct strbuf *dst,
1348 struct conv_attrs ca;
1349 convert_attrs(&ca, path);
1352 assert(ca.drv->clean || ca.drv->process);
1354 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL))
1355 die("%s: clean filter '%s' failed", path, ca.drv->name);
1357 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
1358 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
1359 ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
1362 static int convert_to_working_tree_internal(const char *path, const char *src,
1363 size_t len, struct strbuf *dst,
1364 int normalizing, struct delayed_checkout *dco)
1366 int ret = 0, ret_filter = 0;
1367 struct conv_attrs ca;
1369 convert_attrs(&ca, path);
1371 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
1377 * CRLF conversion can be skipped if normalizing, unless there
1378 * is a smudge or process filter (even if the process filter doesn't
1379 * support smudge). The filters might expect CRLFs.
1381 if ((ca.drv && (ca.drv->smudge || ca.drv->process)) || !normalizing) {
1382 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
1389 ret |= encode_to_worktree(path, src, len, dst, ca.working_tree_encoding);
1395 ret_filter = apply_filter(
1396 path, src, len, -1, dst, ca.drv, CAP_SMUDGE, dco);
1397 if (!ret_filter && ca.drv && ca.drv->required)
1398 die("%s: smudge filter %s failed", path, ca.drv->name);
1400 return ret | ret_filter;
1403 int async_convert_to_working_tree(const char *path, const char *src,
1404 size_t len, struct strbuf *dst,
1407 return convert_to_working_tree_internal(path, src, len, dst, 0, dco);
1410 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
1412 return convert_to_working_tree_internal(path, src, len, dst, 0, NULL);
1415 int renormalize_buffer(const struct index_state *istate, const char *path,
1416 const char *src, size_t len, struct strbuf *dst)
1418 int ret = convert_to_working_tree_internal(path, src, len, dst, 1, NULL);
1423 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
1426 /*****************************************************************
1428 * Streaming conversion support
1430 *****************************************************************/
1432 typedef int (*filter_fn)(struct stream_filter *,
1433 const char *input, size_t *isize_p,
1434 char *output, size_t *osize_p);
1435 typedef void (*free_fn)(struct stream_filter *);
1437 struct stream_filter_vtbl {
1442 struct stream_filter {
1443 struct stream_filter_vtbl *vtbl;
1446 static int null_filter_fn(struct stream_filter *filter,
1447 const char *input, size_t *isize_p,
1448 char *output, size_t *osize_p)
1453 return 0; /* we do not keep any states */
1455 if (*osize_p < count)
1458 memmove(output, input, count);
1465 static void null_free_fn(struct stream_filter *filter)
1467 ; /* nothing -- null instances are shared */
1470 static struct stream_filter_vtbl null_vtbl = {
1475 static struct stream_filter null_filter_singleton = {
1479 int is_null_stream_filter(struct stream_filter *filter)
1481 return filter == &null_filter_singleton;
1489 struct lf_to_crlf_filter {
1490 struct stream_filter filter;
1491 unsigned has_held:1;
1495 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1496 const char *input, size_t *isize_p,
1497 char *output, size_t *osize_p)
1499 size_t count, o = 0;
1500 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1503 * We may be holding onto the CR to see if it is followed by a
1504 * LF, in which case we would need to go to the main loop.
1505 * Otherwise, just emit it to the output stream.
1507 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1508 output[o++] = lf_to_crlf->held;
1509 lf_to_crlf->has_held = 0;
1512 /* We are told to drain */
1519 if (count || lf_to_crlf->has_held) {
1523 if (lf_to_crlf->has_held) {
1525 lf_to_crlf->has_held = 0;
1528 for (i = 0; o < *osize_p && i < count; i++) {
1533 } else if (was_cr) {
1535 * Previous round saw CR and it is not followed
1536 * by a LF; emit the CR before processing the
1537 * current character.
1543 * We may have consumed the last output slot,
1544 * in which case we need to break out of this
1545 * loop; hold the current character before
1548 if (*osize_p <= o) {
1549 lf_to_crlf->has_held = 1;
1550 lf_to_crlf->held = ch;
1551 continue; /* break but increment i */
1566 if (!lf_to_crlf->has_held && was_cr) {
1567 lf_to_crlf->has_held = 1;
1568 lf_to_crlf->held = '\r';
1574 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1579 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1580 lf_to_crlf_filter_fn,
1584 static struct stream_filter *lf_to_crlf_filter(void)
1586 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1588 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1589 return (struct stream_filter *)lf_to_crlf;
1595 #define FILTER_BUFFER 1024
1596 struct cascade_filter {
1597 struct stream_filter filter;
1598 struct stream_filter *one;
1599 struct stream_filter *two;
1600 char buf[FILTER_BUFFER];
1604 static int cascade_filter_fn(struct stream_filter *filter,
1605 const char *input, size_t *isize_p,
1606 char *output, size_t *osize_p)
1608 struct cascade_filter *cas = (struct cascade_filter *) filter;
1610 size_t sz = *osize_p;
1611 size_t to_feed, remaining;
1614 * input -- (one) --> buf -- (two) --> output
1616 while (filled < sz) {
1617 remaining = sz - filled;
1619 /* do we already have something to feed two with? */
1620 if (cas->ptr < cas->end) {
1621 to_feed = cas->end - cas->ptr;
1622 if (stream_filter(cas->two,
1623 cas->buf + cas->ptr, &to_feed,
1624 output + filled, &remaining))
1626 cas->ptr += (cas->end - cas->ptr) - to_feed;
1627 filled = sz - remaining;
1631 /* feed one from upstream and have it emit into our buffer */
1632 to_feed = input ? *isize_p : 0;
1633 if (input && !to_feed)
1635 remaining = sizeof(cas->buf);
1636 if (stream_filter(cas->one,
1638 cas->buf, &remaining))
1640 cas->end = sizeof(cas->buf) - remaining;
1643 size_t fed = *isize_p - to_feed;
1648 /* do we know that we drained one completely? */
1649 if (input || cas->end)
1652 /* tell two to drain; we have nothing more to give it */
1654 remaining = sz - filled;
1655 if (stream_filter(cas->two,
1657 output + filled, &remaining))
1659 if (remaining == (sz - filled))
1660 break; /* completely drained two */
1661 filled = sz - remaining;
1667 static void cascade_free_fn(struct stream_filter *filter)
1669 struct cascade_filter *cas = (struct cascade_filter *)filter;
1670 free_stream_filter(cas->one);
1671 free_stream_filter(cas->two);
1675 static struct stream_filter_vtbl cascade_vtbl = {
1680 static struct stream_filter *cascade_filter(struct stream_filter *one,
1681 struct stream_filter *two)
1683 struct cascade_filter *cascade;
1685 if (!one || is_null_stream_filter(one))
1687 if (!two || is_null_stream_filter(two))
1690 cascade = xmalloc(sizeof(*cascade));
1693 cascade->end = cascade->ptr = 0;
1694 cascade->filter.vtbl = &cascade_vtbl;
1695 return (struct stream_filter *)cascade;
1701 #define IDENT_DRAINING (-1)
1702 #define IDENT_SKIPPING (-2)
1703 struct ident_filter {
1704 struct stream_filter filter;
1707 char ident[45]; /* ": x40 $" */
1710 static int is_foreign_ident(const char *str)
1714 if (!skip_prefix(str, "$Id: ", &str))
1716 for (i = 0; str[i]; i++) {
1717 if (isspace(str[i]) && str[i+1] != '$')
1723 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1725 size_t to_drain = ident->left.len;
1727 if (*osize_p < to_drain)
1728 to_drain = *osize_p;
1730 memcpy(*output_p, ident->left.buf, to_drain);
1731 strbuf_remove(&ident->left, 0, to_drain);
1732 *output_p += to_drain;
1733 *osize_p -= to_drain;
1735 if (!ident->left.len)
1739 static int ident_filter_fn(struct stream_filter *filter,
1740 const char *input, size_t *isize_p,
1741 char *output, size_t *osize_p)
1743 struct ident_filter *ident = (struct ident_filter *)filter;
1744 static const char head[] = "$Id";
1747 /* drain upon eof */
1748 switch (ident->state) {
1750 strbuf_add(&ident->left, head, ident->state);
1752 case IDENT_SKIPPING:
1754 case IDENT_DRAINING:
1755 ident_drain(ident, &output, osize_p);
1760 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1763 if (ident->state == IDENT_DRAINING) {
1764 ident_drain(ident, &output, osize_p);
1773 if (ident->state == IDENT_SKIPPING) {
1775 * Skipping until '$' or LF, but keeping them
1776 * in case it is a foreign ident.
1778 strbuf_addch(&ident->left, ch);
1779 if (ch != '\n' && ch != '$')
1781 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1782 strbuf_setlen(&ident->left, sizeof(head) - 1);
1783 strbuf_addstr(&ident->left, ident->ident);
1785 ident->state = IDENT_DRAINING;
1789 if (ident->state < sizeof(head) &&
1790 head[ident->state] == ch) {
1796 strbuf_add(&ident->left, head, ident->state);
1797 if (ident->state == sizeof(head) - 1) {
1798 if (ch != ':' && ch != '$') {
1799 strbuf_addch(&ident->left, ch);
1805 strbuf_addch(&ident->left, ch);
1806 ident->state = IDENT_SKIPPING;
1808 strbuf_addstr(&ident->left, ident->ident);
1809 ident->state = IDENT_DRAINING;
1814 strbuf_addch(&ident->left, ch);
1815 ident->state = IDENT_DRAINING;
1820 static void ident_free_fn(struct stream_filter *filter)
1822 struct ident_filter *ident = (struct ident_filter *)filter;
1823 strbuf_release(&ident->left);
1827 static struct stream_filter_vtbl ident_vtbl = {
1832 static struct stream_filter *ident_filter(const unsigned char *sha1)
1834 struct ident_filter *ident = xmalloc(sizeof(*ident));
1836 xsnprintf(ident->ident, sizeof(ident->ident),
1837 ": %s $", sha1_to_hex(sha1));
1838 strbuf_init(&ident->left, 0);
1839 ident->filter.vtbl = &ident_vtbl;
1841 return (struct stream_filter *)ident;
1845 * Return an appropriately constructed filter for the path, or NULL if
1846 * the contents cannot be filtered without reading the whole thing
1849 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1850 * large binary blob you would want us not to slurp into the memory!
1852 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1854 struct conv_attrs ca;
1855 struct stream_filter *filter = NULL;
1857 convert_attrs(&ca, path);
1858 if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
1861 if (ca.working_tree_encoding)
1864 if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1868 filter = ident_filter(sha1);
1870 if (output_eol(ca.crlf_action) == EOL_CRLF)
1871 filter = cascade_filter(filter, lf_to_crlf_filter());
1873 filter = cascade_filter(filter, &null_filter_singleton);
1878 void free_stream_filter(struct stream_filter *filter)
1880 filter->vtbl->free(filter);
1883 int stream_filter(struct stream_filter *filter,
1884 const char *input, size_t *isize_p,
1885 char *output, size_t *osize_p)
1887 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);