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 void trace_encoding(const char *context, const char *path,
270 const char *encoding, const char *buf, size_t len)
272 static struct trace_key coe = TRACE_KEY_INIT(WORKING_TREE_ENCODING);
273 struct strbuf trace = STRBUF_INIT;
276 strbuf_addf(&trace, "%s (%s, considered %s):\n", context, path, encoding);
277 for (i = 0; i < len && buf; ++i) {
279 &trace,"| \e[2m%2i:\e[0m %2x \e[2m%c\e[0m%c",
281 (unsigned char) buf[i],
282 (buf[i] > 32 && buf[i] < 127 ? buf[i] : ' '),
283 ((i+1) % 8 && (i+1) < len ? ' ' : '\n')
286 strbuf_addchars(&trace, '\n', 1);
288 trace_strbuf(&coe, &trace);
289 strbuf_release(&trace);
292 static int check_roundtrip(const char* enc_name)
295 * check_roundtrip_encoding contains a string of space and/or
296 * comma separated encodings (eg. "UTF-16, ASCII, CP1125").
297 * Search for the given encoding in that string.
299 const char *found = strcasestr(check_roundtrip_encoding, enc_name);
300 const char *next = found + strlen(enc_name);
301 int len = strlen(check_roundtrip_encoding);
304 * check that the found encoding is at the
305 * beginning of check_roundtrip_encoding or
306 * that it is prefixed with a space or comma
308 found == check_roundtrip_encoding || (
309 found > check_roundtrip_encoding &&
310 (*(found-1) == ' ' || *(found-1) == ',')
314 * check that the found encoding is at the
315 * end of check_roundtrip_encoding or
316 * that it is suffixed with a space or comma
318 next == check_roundtrip_encoding + len || (
319 next < check_roundtrip_encoding + len &&
320 (*next == ' ' || *next == ',')
325 static struct encoding {
327 struct encoding *next;
328 } *encoding, **encoding_tail;
329 static const char *default_encoding = "UTF-8";
331 static int encode_to_git(const char *path, const char *src, size_t src_len,
332 struct strbuf *buf, struct encoding *enc, int conv_flags)
338 * No encoding is specified or there is nothing to encode.
339 * Tell the caller that the content was not modified.
341 if (!enc || (src && !src_len))
345 * Looks like we got called from "would_convert_to_git()".
346 * This means Git wants to know if it would encode (= modify!)
347 * the content. Let's answer with "yes", since an encoding was
353 if (has_prohibited_utf_bom(enc->name, src, src_len)) {
354 const char *error_msg = _(
355 "BOM is prohibited in '%s' if encoded as %s");
357 * This advise is shown for UTF-??BE and UTF-??LE encodings.
358 * We truncate the encoding name to 6 chars with %.6s to cut
359 * off the last two "byte order" characters.
361 const char *advise_msg = _(
362 "The file '%s' contains a byte order mark (BOM). "
363 "Please use %.6s as working-tree-encoding.");
364 advise(advise_msg, path, enc->name);
365 if (conv_flags & CONV_WRITE_OBJECT)
366 die(error_msg, path, enc->name);
368 error(error_msg, path, enc->name);
370 } else if (is_missing_required_utf_bom(enc->name, src, src_len)) {
371 const char *error_msg = _(
372 "BOM is required in '%s' if encoded as %s");
373 const char *advise_msg = _(
374 "The file '%s' is missing a byte order mark (BOM). "
375 "Please use %sBE or %sLE (depending on the byte order) "
376 "as working-tree-encoding.");
377 advise(advise_msg, path, enc->name, enc->name);
378 if (conv_flags & CONV_WRITE_OBJECT)
379 die(error_msg, path, enc->name);
381 error(error_msg, path, enc->name);
384 trace_encoding("source", path, enc->name, src, src_len);
385 dst = reencode_string_len(src, src_len, default_encoding, enc->name,
389 * We could add the blob "as-is" to Git. However, on checkout
390 * we would try to reencode to the original encoding. This
391 * would fail and we would leave the user with a messed-up
392 * working tree. Let's try to avoid this by screaming loud.
394 const char* msg = _("failed to encode '%s' from %s to %s");
395 if (conv_flags & CONV_WRITE_OBJECT)
396 die(msg, path, enc->name, default_encoding);
398 error(msg, path, enc->name, default_encoding);
400 trace_encoding("destination", path, default_encoding, dst, dst_len);
403 * UTF supports lossless conversion round tripping [1] and conversions
404 * between UTF and other encodings are mostly round trip safe as
405 * Unicode aims to be a superset of all other character encodings.
406 * However, certain encodings (e.g. SHIFT-JIS) are known to have round
407 * trip issues [2]. Check the round trip conversion for all encodings
408 * listed in core.checkRoundtripEncoding.
410 * The round trip check is only performed if content is written to Git.
411 * This ensures that no information is lost during conversion to/from
412 * the internal UTF-8 representation.
414 * Please note, the code below is not tested because I was not able to
415 * generate a faulty round trip without an iconv error. Iconv errors
416 * are already caught above.
418 * [1] http://unicode.org/faq/utf_bom.html#gen2
419 * [2] https://support.microsoft.com/en-us/help/170559/prb-conversion-problem-between-shift-jis-and-unicode
421 if ((conv_flags & CONV_WRITE_OBJECT) && check_roundtrip(enc->name)) {
425 re_src = reencode_string_len(dst, dst_len,
426 enc->name, default_encoding,
429 trace_printf("Checking roundtrip encoding for %s...\n", enc->name);
430 trace_encoding("reencoded source", path, enc->name,
433 if (!re_src || src_len != re_src_len ||
434 memcmp(src, re_src, src_len)) {
435 const char* msg = _("encoding '%s' from %s to %s and "
436 "back is not the same");
437 die(msg, path, enc->name, default_encoding);
443 strbuf_attach(buf, dst, dst_len, dst_len + 1);
447 static int encode_to_worktree(const char *path, const char *src, size_t src_len,
448 struct strbuf *buf, struct encoding *enc)
454 * No encoding is specified or there is nothing to encode.
455 * Tell the caller that the content was not modified.
457 if (!enc || (src && !src_len))
460 dst = reencode_string_len(src, src_len, enc->name, default_encoding,
463 error("failed to encode '%s' from %s to %s",
464 path, enc->name, default_encoding);
468 strbuf_attach(buf, dst, dst_len, dst_len + 1);
472 static int crlf_to_git(const struct index_state *istate,
473 const char *path, const char *src, size_t len,
475 enum crlf_action crlf_action, int conv_flags)
477 struct text_stat stats;
479 int convert_crlf_into_lf;
481 if (crlf_action == CRLF_BINARY ||
486 * If we are doing a dry-run and have no source buffer, there is
487 * nothing to analyze; we must assume we would convert.
492 gather_stats(src, len, &stats);
493 /* Optimization: No CRLF? Nothing to convert, regardless. */
494 convert_crlf_into_lf = !!stats.crlf;
496 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
497 if (convert_is_binary(len, &stats))
500 * If the file in the index has any CR in it, do not
501 * convert. This is the new safer autocrlf handling,
502 * unless we want to renormalize in a merge or
505 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
506 has_crlf_in_index(istate, path))
507 convert_crlf_into_lf = 0;
509 if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
510 ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
511 struct text_stat new_stats;
512 memcpy(&new_stats, &stats, sizeof(new_stats));
513 /* simulate "git add" */
514 if (convert_crlf_into_lf) {
515 new_stats.lonelf += new_stats.crlf;
518 /* simulate "git checkout" */
519 if (will_convert_lf_to_crlf(len, &new_stats, crlf_action)) {
520 new_stats.crlf += new_stats.lonelf;
521 new_stats.lonelf = 0;
523 check_global_conv_flags_eol(path, crlf_action, &stats, &new_stats, conv_flags);
525 if (!convert_crlf_into_lf)
529 * At this point all of our source analysis is done, and we are sure we
530 * would convert. If we are in dry-run mode, we can give an answer.
535 /* only grow if not in place */
536 if (strbuf_avail(buf) + buf->len < len)
537 strbuf_grow(buf, len - buf->len);
539 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
541 * If we guessed, we already know we rejected a file with
542 * lone CR, and we can strip a CR without looking at what
546 unsigned char c = *src++;
552 unsigned char c = *src++;
553 if (! (c == '\r' && (1 < len && *src == '\n')))
557 strbuf_setlen(buf, dst - buf->buf);
561 static int crlf_to_worktree(const char *path, const char *src, size_t len,
562 struct strbuf *buf, enum crlf_action crlf_action)
564 char *to_free = NULL;
565 struct text_stat stats;
567 if (!len || output_eol(crlf_action) != EOL_CRLF)
570 gather_stats(src, len, &stats);
571 if (!will_convert_lf_to_crlf(len, &stats, crlf_action))
574 /* are we "faking" in place editing ? */
576 to_free = strbuf_detach(buf, NULL);
578 strbuf_grow(buf, len + stats.lonelf);
580 const char *nl = memchr(src, '\n', len);
583 if (nl > src && nl[-1] == '\r') {
584 strbuf_add(buf, src, nl + 1 - src);
586 strbuf_add(buf, src, nl - src);
587 strbuf_addstr(buf, "\r\n");
592 strbuf_add(buf, src, len);
598 struct filter_params {
606 static int filter_buffer_or_fd(int in, int out, void *data)
609 * Spawn cmd and feed the buffer contents through its stdin.
611 struct child_process child_process = CHILD_PROCESS_INIT;
612 struct filter_params *params = (struct filter_params *)data;
613 int write_err, status;
614 const char *argv[] = { NULL, NULL };
616 /* apply % substitution to cmd */
617 struct strbuf cmd = STRBUF_INIT;
618 struct strbuf path = STRBUF_INIT;
619 struct strbuf_expand_dict_entry dict[] = {
624 /* quote the path to preserve spaces, etc. */
625 sq_quote_buf(&path, params->path);
626 dict[0].value = path.buf;
628 /* expand all %f with the quoted path */
629 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
630 strbuf_release(&path);
634 child_process.argv = argv;
635 child_process.use_shell = 1;
636 child_process.in = -1;
637 child_process.out = out;
639 if (start_command(&child_process)) {
640 strbuf_release(&cmd);
641 return error("cannot fork to run external filter '%s'", params->cmd);
644 sigchain_push(SIGPIPE, SIG_IGN);
647 write_err = (write_in_full(child_process.in,
648 params->src, params->size) < 0);
652 write_err = copy_fd(params->fd, child_process.in);
653 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
657 if (close(child_process.in))
660 error("cannot feed the input to external filter '%s'", params->cmd);
662 sigchain_pop(SIGPIPE);
664 status = finish_command(&child_process);
666 error("external filter '%s' failed %d", params->cmd, status);
668 strbuf_release(&cmd);
669 return (write_err || status);
672 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
673 struct strbuf *dst, const char *cmd)
676 * Create a pipeline to have the command filter the buffer's
679 * (child --> cmd) --> us
682 struct strbuf nbuf = STRBUF_INIT;
684 struct filter_params params;
686 memset(&async, 0, sizeof(async));
687 async.proc = filter_buffer_or_fd;
688 async.data = ¶ms;
697 if (start_async(&async))
698 return 0; /* error was already reported */
700 if (strbuf_read(&nbuf, async.out, len) < 0) {
701 err = error("read from external filter '%s' failed", cmd);
703 if (close(async.out)) {
704 err = error("read from external filter '%s' failed", cmd);
706 if (finish_async(&async)) {
707 err = error("external filter '%s' failed", cmd);
711 strbuf_swap(dst, &nbuf);
713 strbuf_release(&nbuf);
717 #define CAP_CLEAN (1u<<0)
718 #define CAP_SMUDGE (1u<<1)
719 #define CAP_DELAY (1u<<2)
722 struct subprocess_entry subprocess; /* must be the first member! */
723 unsigned int supported_capabilities;
726 static int subprocess_map_initialized;
727 static struct hashmap subprocess_map;
729 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
731 static int versions[] = {2, 0};
732 static struct subprocess_capability capabilities[] = {
733 { "clean", CAP_CLEAN },
734 { "smudge", CAP_SMUDGE },
735 { "delay", CAP_DELAY },
738 struct cmd2process *entry = (struct cmd2process *)subprocess;
739 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
741 &entry->supported_capabilities);
744 static void handle_filter_error(const struct strbuf *filter_status,
745 struct cmd2process *entry,
746 const unsigned int wanted_capability) {
747 if (!strcmp(filter_status->buf, "error"))
748 ; /* The filter signaled a problem with the file. */
749 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
751 * The filter signaled a permanent problem. Don't try to filter
752 * files with the same command for the lifetime of the current
755 entry->supported_capabilities &= ~wanted_capability;
758 * Something went wrong with the protocol filter.
759 * Force shutdown and restart if another blob requires filtering.
761 error("external filter '%s' failed", entry->subprocess.cmd);
762 subprocess_stop(&subprocess_map, &entry->subprocess);
767 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
768 int fd, struct strbuf *dst, const char *cmd,
769 const unsigned int wanted_capability,
770 struct delayed_checkout *dco)
774 struct cmd2process *entry;
775 struct child_process *process;
776 struct strbuf nbuf = STRBUF_INIT;
777 struct strbuf filter_status = STRBUF_INIT;
778 const char *filter_type;
780 if (!subprocess_map_initialized) {
781 subprocess_map_initialized = 1;
782 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
785 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
791 entry = xmalloc(sizeof(*entry));
792 entry->supported_capabilities = 0;
794 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
799 process = &entry->subprocess.process;
801 if (!(entry->supported_capabilities & wanted_capability))
804 if (wanted_capability & CAP_CLEAN)
805 filter_type = "clean";
806 else if (wanted_capability & CAP_SMUDGE)
807 filter_type = "smudge";
809 die("unexpected filter type");
811 sigchain_push(SIGPIPE, SIG_IGN);
813 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
814 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
818 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
820 error("path name too long for external filter");
824 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
828 if ((entry->supported_capabilities & CAP_DELAY) &&
829 dco && dco->state == CE_CAN_DELAY) {
831 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
836 err = packet_flush_gently(process->in);
841 err = write_packetized_from_fd(fd, process->in);
843 err = write_packetized_from_buf(src, len, process->in);
847 err = subprocess_read_status(process->out, &filter_status);
851 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
852 string_list_insert(&dco->filters, cmd);
853 string_list_insert(&dco->paths, path);
855 /* The filter got the blob and wants to send us a response. */
856 err = strcmp(filter_status.buf, "success");
860 err = read_packetized_to_strbuf(process->out, &nbuf) < 0;
864 err = subprocess_read_status(process->out, &filter_status);
868 err = strcmp(filter_status.buf, "success");
872 sigchain_pop(SIGPIPE);
875 handle_filter_error(&filter_status, entry, wanted_capability);
877 strbuf_swap(dst, &nbuf);
878 strbuf_release(&nbuf);
883 int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
887 struct cmd2process *entry;
888 struct child_process *process;
889 struct strbuf filter_status = STRBUF_INIT;
891 assert(subprocess_map_initialized);
892 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
894 error("external filter '%s' is not available anymore although "
895 "not all paths have been filtered", cmd);
898 process = &entry->subprocess.process;
899 sigchain_push(SIGPIPE, SIG_IGN);
901 err = packet_write_fmt_gently(
902 process->in, "command=list_available_blobs\n");
906 err = packet_flush_gently(process->in);
910 while ((line = packet_read_line(process->out, NULL))) {
912 if (skip_prefix(line, "pathname=", &path))
913 string_list_insert(available_paths, xstrdup(path));
915 ; /* ignore unknown keys */
918 err = subprocess_read_status(process->out, &filter_status);
922 err = strcmp(filter_status.buf, "success");
925 sigchain_pop(SIGPIPE);
928 handle_filter_error(&filter_status, entry, 0);
932 static struct convert_driver {
934 struct convert_driver *next;
939 } *user_convert, **user_convert_tail;
941 static int apply_filter(const char *path, const char *src, size_t len,
942 int fd, struct strbuf *dst, struct convert_driver *drv,
943 const unsigned int wanted_capability,
944 struct delayed_checkout *dco)
946 const char *cmd = NULL;
954 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
956 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
960 return apply_single_file_filter(path, src, len, fd, dst, cmd);
961 else if (drv->process && *drv->process)
962 return apply_multi_file_filter(path, src, len, fd, dst,
963 drv->process, wanted_capability, dco);
968 static int read_convert_config(const char *var, const char *value, void *cb)
970 const char *key, *name;
972 struct convert_driver *drv;
975 * External conversion drivers are configured using
976 * "filter.<name>.variable".
978 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
980 for (drv = user_convert; drv; drv = drv->next)
981 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
984 drv = xcalloc(1, sizeof(struct convert_driver));
985 drv->name = xmemdupz(name, namelen);
986 *user_convert_tail = drv;
987 user_convert_tail = &(drv->next);
991 * filter.<name>.smudge and filter.<name>.clean specifies
996 * The command-line will not be interpolated in any way.
999 if (!strcmp("smudge", key))
1000 return git_config_string(&drv->smudge, var, value);
1002 if (!strcmp("clean", key))
1003 return git_config_string(&drv->clean, var, value);
1005 if (!strcmp("process", key))
1006 return git_config_string(&drv->process, var, value);
1008 if (!strcmp("required", key)) {
1009 drv->required = git_config_bool(var, value);
1016 static int count_ident(const char *cp, unsigned long size)
1019 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
1031 if (memcmp("Id", cp, 2))
1042 * "$Id: ... "; scan up to the closing dollar sign and discard.
1058 static int ident_to_git(const char *path, const char *src, size_t len,
1059 struct strbuf *buf, int ident)
1063 if (!ident || (src && !count_ident(src, len)))
1069 /* only grow if not in place */
1070 if (strbuf_avail(buf) + buf->len < len)
1071 strbuf_grow(buf, len - buf->len);
1074 dollar = memchr(src, '$', len);
1077 memmove(dst, src, dollar + 1 - src);
1078 dst += dollar + 1 - src;
1079 len -= dollar + 1 - src;
1082 if (len > 3 && !memcmp(src, "Id:", 3)) {
1083 dollar = memchr(src + 3, '$', len - 3);
1086 if (memchr(src + 3, '\n', dollar - src - 3)) {
1087 /* Line break before the next dollar. */
1091 memcpy(dst, "Id$", 3);
1093 len -= dollar + 1 - src;
1097 memmove(dst, src, len);
1098 strbuf_setlen(buf, dst + len - buf->buf);
1102 static int ident_to_worktree(const char *path, const char *src, size_t len,
1103 struct strbuf *buf, int ident)
1105 struct object_id oid;
1106 char *to_free = NULL, *dollar, *spc;
1112 cnt = count_ident(src, len);
1116 /* are we "faking" in place editing ? */
1117 if (src == buf->buf)
1118 to_free = strbuf_detach(buf, NULL);
1119 hash_object_file(src, len, "blob", &oid);
1121 strbuf_grow(buf, len + cnt * 43);
1123 /* step 1: run to the next '$' */
1124 dollar = memchr(src, '$', len);
1127 strbuf_add(buf, src, dollar + 1 - src);
1128 len -= dollar + 1 - src;
1131 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1132 if (len < 3 || memcmp("Id", src, 2))
1135 /* step 3: skip over Id$ or Id:xxxxx$ */
1136 if (src[2] == '$') {
1139 } else if (src[2] == ':') {
1141 * It's possible that an expanded Id has crept its way into the
1142 * repository, we cope with that by stripping the expansion out.
1143 * This is probably not a good idea, since it will cause changes
1144 * on checkout, which won't go away by stash, but let's keep it
1145 * for git-style ids.
1147 dollar = memchr(src + 3, '$', len - 3);
1149 /* incomplete keyword, no more '$', so just quit the loop */
1153 if (memchr(src + 3, '\n', dollar - src - 3)) {
1154 /* Line break before the next dollar. */
1158 spc = memchr(src + 4, ' ', dollar - src - 4);
1159 if (spc && spc < dollar-1) {
1160 /* There are spaces in unexpected places.
1161 * This is probably an id from some other
1162 * versioning system. Keep it for now.
1167 len -= dollar + 1 - src;
1170 /* it wasn't a "Id$" or "Id:xxxx$" */
1174 /* step 4: substitute */
1175 strbuf_addstr(buf, "Id: ");
1176 strbuf_addstr(buf, oid_to_hex(&oid));
1177 strbuf_addstr(buf, " $");
1179 strbuf_add(buf, src, len);
1185 static struct encoding *git_path_check_encoding(struct attr_check_item *check)
1187 const char *value = check->value;
1188 struct encoding *enc;
1190 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value) ||
1194 for (enc = encoding; enc; enc = enc->next)
1195 if (!strcasecmp(value, enc->name))
1198 /* Don't encode to the default encoding */
1199 if (!strcasecmp(value, default_encoding))
1202 enc = xcalloc(1, sizeof(*enc));
1204 * Ensure encoding names are always upper case (e.g. UTF-8) to
1205 * simplify subsequent string comparisons.
1207 enc->name = xstrdup_toupper(value);
1208 *encoding_tail = enc;
1209 encoding_tail = &(enc->next);
1214 static enum crlf_action git_path_check_crlf(struct attr_check_item *check)
1216 const char *value = check->value;
1218 if (ATTR_TRUE(value))
1220 else if (ATTR_FALSE(value))
1222 else if (ATTR_UNSET(value))
1224 else if (!strcmp(value, "input"))
1225 return CRLF_TEXT_INPUT;
1226 else if (!strcmp(value, "auto"))
1228 return CRLF_UNDEFINED;
1231 static enum eol git_path_check_eol(struct attr_check_item *check)
1233 const char *value = check->value;
1235 if (ATTR_UNSET(value))
1237 else if (!strcmp(value, "lf"))
1239 else if (!strcmp(value, "crlf"))
1244 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
1246 const char *value = check->value;
1247 struct convert_driver *drv;
1249 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1251 for (drv = user_convert; drv; drv = drv->next)
1252 if (!strcmp(value, drv->name))
1257 static int git_path_check_ident(struct attr_check_item *check)
1259 const char *value = check->value;
1261 return !!ATTR_TRUE(value);
1265 struct convert_driver *drv;
1266 enum crlf_action attr_action; /* What attr says */
1267 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
1269 struct encoding *working_tree_encoding; /* Supported encoding or default encoding if NULL */
1272 static void convert_attrs(struct conv_attrs *ca, const char *path)
1274 static struct attr_check *check;
1277 check = attr_check_initl("crlf", "ident", "filter",
1278 "eol", "text", "working-tree-encoding",
1280 user_convert_tail = &user_convert;
1281 encoding_tail = &encoding;
1282 git_config(read_convert_config, NULL);
1285 if (!git_check_attr(path, check)) {
1286 struct attr_check_item *ccheck = check->items;
1287 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1288 if (ca->crlf_action == CRLF_UNDEFINED)
1289 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1290 ca->ident = git_path_check_ident(ccheck + 1);
1291 ca->drv = git_path_check_convert(ccheck + 2);
1292 if (ca->crlf_action != CRLF_BINARY) {
1293 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1294 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1295 ca->crlf_action = CRLF_AUTO_INPUT;
1296 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1297 ca->crlf_action = CRLF_AUTO_CRLF;
1298 else if (eol_attr == EOL_LF)
1299 ca->crlf_action = CRLF_TEXT_INPUT;
1300 else if (eol_attr == EOL_CRLF)
1301 ca->crlf_action = CRLF_TEXT_CRLF;
1303 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
1306 ca->crlf_action = CRLF_UNDEFINED;
1310 /* Save attr and make a decision for action */
1311 ca->attr_action = ca->crlf_action;
1312 if (ca->crlf_action == CRLF_TEXT)
1313 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1314 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1315 ca->crlf_action = CRLF_BINARY;
1316 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1317 ca->crlf_action = CRLF_AUTO_CRLF;
1318 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1319 ca->crlf_action = CRLF_AUTO_INPUT;
1322 int would_convert_to_git_filter_fd(const char *path)
1324 struct conv_attrs ca;
1326 convert_attrs(&ca, path);
1331 * Apply a filter to an fd only if the filter is required to succeed.
1332 * We must die if the filter fails, because the original data before
1333 * filtering is not available.
1335 if (!ca.drv->required)
1338 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL);
1341 const char *get_convert_attr_ascii(const char *path)
1343 struct conv_attrs ca;
1345 convert_attrs(&ca, path);
1346 switch (ca.attr_action) {
1347 case CRLF_UNDEFINED:
1353 case CRLF_TEXT_INPUT:
1354 return "text eol=lf";
1355 case CRLF_TEXT_CRLF:
1356 return "text eol=crlf";
1359 case CRLF_AUTO_CRLF:
1360 return "text=auto eol=crlf";
1361 case CRLF_AUTO_INPUT:
1362 return "text=auto eol=lf";
1367 int convert_to_git(const struct index_state *istate,
1368 const char *path, const char *src, size_t len,
1369 struct strbuf *dst, int conv_flags)
1372 struct conv_attrs ca;
1374 convert_attrs(&ca, path);
1376 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL);
1377 if (!ret && ca.drv && ca.drv->required)
1378 die("%s: clean filter '%s' failed", path, ca.drv->name);
1385 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1391 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1392 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
1398 return ret | ident_to_git(path, src, len, dst, ca.ident);
1401 void convert_to_git_filter_fd(const struct index_state *istate,
1402 const char *path, int fd, struct strbuf *dst,
1405 struct conv_attrs ca;
1406 convert_attrs(&ca, path);
1409 assert(ca.drv->clean || ca.drv->process);
1411 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL))
1412 die("%s: clean filter '%s' failed", path, ca.drv->name);
1414 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
1415 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
1416 ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
1419 static int convert_to_working_tree_internal(const char *path, const char *src,
1420 size_t len, struct strbuf *dst,
1421 int normalizing, struct delayed_checkout *dco)
1423 int ret = 0, ret_filter = 0;
1424 struct conv_attrs ca;
1426 convert_attrs(&ca, path);
1428 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
1434 * CRLF conversion can be skipped if normalizing, unless there
1435 * is a smudge or process filter (even if the process filter doesn't
1436 * support smudge). The filters might expect CRLFs.
1438 if ((ca.drv && (ca.drv->smudge || ca.drv->process)) || !normalizing) {
1439 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
1446 ret |= encode_to_worktree(path, src, len, dst, ca.working_tree_encoding);
1452 ret_filter = apply_filter(
1453 path, src, len, -1, dst, ca.drv, CAP_SMUDGE, dco);
1454 if (!ret_filter && ca.drv && ca.drv->required)
1455 die("%s: smudge filter %s failed", path, ca.drv->name);
1457 return ret | ret_filter;
1460 int async_convert_to_working_tree(const char *path, const char *src,
1461 size_t len, struct strbuf *dst,
1464 return convert_to_working_tree_internal(path, src, len, dst, 0, dco);
1467 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
1469 return convert_to_working_tree_internal(path, src, len, dst, 0, NULL);
1472 int renormalize_buffer(const struct index_state *istate, const char *path,
1473 const char *src, size_t len, struct strbuf *dst)
1475 int ret = convert_to_working_tree_internal(path, src, len, dst, 1, NULL);
1480 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
1483 /*****************************************************************
1485 * Streaming conversion support
1487 *****************************************************************/
1489 typedef int (*filter_fn)(struct stream_filter *,
1490 const char *input, size_t *isize_p,
1491 char *output, size_t *osize_p);
1492 typedef void (*free_fn)(struct stream_filter *);
1494 struct stream_filter_vtbl {
1499 struct stream_filter {
1500 struct stream_filter_vtbl *vtbl;
1503 static int null_filter_fn(struct stream_filter *filter,
1504 const char *input, size_t *isize_p,
1505 char *output, size_t *osize_p)
1510 return 0; /* we do not keep any states */
1512 if (*osize_p < count)
1515 memmove(output, input, count);
1522 static void null_free_fn(struct stream_filter *filter)
1524 ; /* nothing -- null instances are shared */
1527 static struct stream_filter_vtbl null_vtbl = {
1532 static struct stream_filter null_filter_singleton = {
1536 int is_null_stream_filter(struct stream_filter *filter)
1538 return filter == &null_filter_singleton;
1546 struct lf_to_crlf_filter {
1547 struct stream_filter filter;
1548 unsigned has_held:1;
1552 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1553 const char *input, size_t *isize_p,
1554 char *output, size_t *osize_p)
1556 size_t count, o = 0;
1557 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1560 * We may be holding onto the CR to see if it is followed by a
1561 * LF, in which case we would need to go to the main loop.
1562 * Otherwise, just emit it to the output stream.
1564 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1565 output[o++] = lf_to_crlf->held;
1566 lf_to_crlf->has_held = 0;
1569 /* We are told to drain */
1576 if (count || lf_to_crlf->has_held) {
1580 if (lf_to_crlf->has_held) {
1582 lf_to_crlf->has_held = 0;
1585 for (i = 0; o < *osize_p && i < count; i++) {
1590 } else if (was_cr) {
1592 * Previous round saw CR and it is not followed
1593 * by a LF; emit the CR before processing the
1594 * current character.
1600 * We may have consumed the last output slot,
1601 * in which case we need to break out of this
1602 * loop; hold the current character before
1605 if (*osize_p <= o) {
1606 lf_to_crlf->has_held = 1;
1607 lf_to_crlf->held = ch;
1608 continue; /* break but increment i */
1623 if (!lf_to_crlf->has_held && was_cr) {
1624 lf_to_crlf->has_held = 1;
1625 lf_to_crlf->held = '\r';
1631 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1636 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1637 lf_to_crlf_filter_fn,
1641 static struct stream_filter *lf_to_crlf_filter(void)
1643 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1645 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1646 return (struct stream_filter *)lf_to_crlf;
1652 #define FILTER_BUFFER 1024
1653 struct cascade_filter {
1654 struct stream_filter filter;
1655 struct stream_filter *one;
1656 struct stream_filter *two;
1657 char buf[FILTER_BUFFER];
1661 static int cascade_filter_fn(struct stream_filter *filter,
1662 const char *input, size_t *isize_p,
1663 char *output, size_t *osize_p)
1665 struct cascade_filter *cas = (struct cascade_filter *) filter;
1667 size_t sz = *osize_p;
1668 size_t to_feed, remaining;
1671 * input -- (one) --> buf -- (two) --> output
1673 while (filled < sz) {
1674 remaining = sz - filled;
1676 /* do we already have something to feed two with? */
1677 if (cas->ptr < cas->end) {
1678 to_feed = cas->end - cas->ptr;
1679 if (stream_filter(cas->two,
1680 cas->buf + cas->ptr, &to_feed,
1681 output + filled, &remaining))
1683 cas->ptr += (cas->end - cas->ptr) - to_feed;
1684 filled = sz - remaining;
1688 /* feed one from upstream and have it emit into our buffer */
1689 to_feed = input ? *isize_p : 0;
1690 if (input && !to_feed)
1692 remaining = sizeof(cas->buf);
1693 if (stream_filter(cas->one,
1695 cas->buf, &remaining))
1697 cas->end = sizeof(cas->buf) - remaining;
1700 size_t fed = *isize_p - to_feed;
1705 /* do we know that we drained one completely? */
1706 if (input || cas->end)
1709 /* tell two to drain; we have nothing more to give it */
1711 remaining = sz - filled;
1712 if (stream_filter(cas->two,
1714 output + filled, &remaining))
1716 if (remaining == (sz - filled))
1717 break; /* completely drained two */
1718 filled = sz - remaining;
1724 static void cascade_free_fn(struct stream_filter *filter)
1726 struct cascade_filter *cas = (struct cascade_filter *)filter;
1727 free_stream_filter(cas->one);
1728 free_stream_filter(cas->two);
1732 static struct stream_filter_vtbl cascade_vtbl = {
1737 static struct stream_filter *cascade_filter(struct stream_filter *one,
1738 struct stream_filter *two)
1740 struct cascade_filter *cascade;
1742 if (!one || is_null_stream_filter(one))
1744 if (!two || is_null_stream_filter(two))
1747 cascade = xmalloc(sizeof(*cascade));
1750 cascade->end = cascade->ptr = 0;
1751 cascade->filter.vtbl = &cascade_vtbl;
1752 return (struct stream_filter *)cascade;
1758 #define IDENT_DRAINING (-1)
1759 #define IDENT_SKIPPING (-2)
1760 struct ident_filter {
1761 struct stream_filter filter;
1764 char ident[45]; /* ": x40 $" */
1767 static int is_foreign_ident(const char *str)
1771 if (!skip_prefix(str, "$Id: ", &str))
1773 for (i = 0; str[i]; i++) {
1774 if (isspace(str[i]) && str[i+1] != '$')
1780 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1782 size_t to_drain = ident->left.len;
1784 if (*osize_p < to_drain)
1785 to_drain = *osize_p;
1787 memcpy(*output_p, ident->left.buf, to_drain);
1788 strbuf_remove(&ident->left, 0, to_drain);
1789 *output_p += to_drain;
1790 *osize_p -= to_drain;
1792 if (!ident->left.len)
1796 static int ident_filter_fn(struct stream_filter *filter,
1797 const char *input, size_t *isize_p,
1798 char *output, size_t *osize_p)
1800 struct ident_filter *ident = (struct ident_filter *)filter;
1801 static const char head[] = "$Id";
1804 /* drain upon eof */
1805 switch (ident->state) {
1807 strbuf_add(&ident->left, head, ident->state);
1809 case IDENT_SKIPPING:
1811 case IDENT_DRAINING:
1812 ident_drain(ident, &output, osize_p);
1817 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1820 if (ident->state == IDENT_DRAINING) {
1821 ident_drain(ident, &output, osize_p);
1830 if (ident->state == IDENT_SKIPPING) {
1832 * Skipping until '$' or LF, but keeping them
1833 * in case it is a foreign ident.
1835 strbuf_addch(&ident->left, ch);
1836 if (ch != '\n' && ch != '$')
1838 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1839 strbuf_setlen(&ident->left, sizeof(head) - 1);
1840 strbuf_addstr(&ident->left, ident->ident);
1842 ident->state = IDENT_DRAINING;
1846 if (ident->state < sizeof(head) &&
1847 head[ident->state] == ch) {
1853 strbuf_add(&ident->left, head, ident->state);
1854 if (ident->state == sizeof(head) - 1) {
1855 if (ch != ':' && ch != '$') {
1856 strbuf_addch(&ident->left, ch);
1862 strbuf_addch(&ident->left, ch);
1863 ident->state = IDENT_SKIPPING;
1865 strbuf_addstr(&ident->left, ident->ident);
1866 ident->state = IDENT_DRAINING;
1871 strbuf_addch(&ident->left, ch);
1872 ident->state = IDENT_DRAINING;
1877 static void ident_free_fn(struct stream_filter *filter)
1879 struct ident_filter *ident = (struct ident_filter *)filter;
1880 strbuf_release(&ident->left);
1884 static struct stream_filter_vtbl ident_vtbl = {
1889 static struct stream_filter *ident_filter(const unsigned char *sha1)
1891 struct ident_filter *ident = xmalloc(sizeof(*ident));
1893 xsnprintf(ident->ident, sizeof(ident->ident),
1894 ": %s $", sha1_to_hex(sha1));
1895 strbuf_init(&ident->left, 0);
1896 ident->filter.vtbl = &ident_vtbl;
1898 return (struct stream_filter *)ident;
1902 * Return an appropriately constructed filter for the path, or NULL if
1903 * the contents cannot be filtered without reading the whole thing
1906 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1907 * large binary blob you would want us not to slurp into the memory!
1909 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1911 struct conv_attrs ca;
1912 struct stream_filter *filter = NULL;
1914 convert_attrs(&ca, path);
1915 if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
1918 if (ca.working_tree_encoding)
1921 if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1925 filter = ident_filter(sha1);
1927 if (output_eol(ca.crlf_action) == EOL_CRLF)
1928 filter = cascade_filter(filter, lf_to_crlf_filter());
1930 filter = cascade_filter(filter, &null_filter_singleton);
1935 void free_stream_filter(struct stream_filter *filter)
1937 filter->vtbl->free(filter);
1940 int stream_filter(struct stream_filter *filter,
1941 const char *input, size_t *isize_p,
1942 char *output, size_t *osize_p)
1944 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);