archive-*.c: use the right repository
[alt-git.git] / convert.c
blob8acfe8ae457e91908b34febf5cfcf2492334a241
1 #define NO_THE_INDEX_COMPATIBILITY_MACROS
2 #include "cache.h"
3 #include "config.h"
4 #include "object-store.h"
5 #include "attr.h"
6 #include "run-command.h"
7 #include "quote.h"
8 #include "sigchain.h"
9 #include "pkt-line.h"
10 #include "sub-process.h"
11 #include "utf8.h"
14 * convert.c - convert a file when checking it out and checking it in.
16 * This should use the pathname to decide on whether it wants to do some
17 * more interesting conversions (automatic gzip/unzip, general format
18 * conversions etc etc), but by default it just does automatic CRLF<->LF
19 * translation when the "text" attribute or "auto_crlf" option is set.
22 /* Stat bits: When BIN is set, the txt bits are unset */
23 #define CONVERT_STAT_BITS_TXT_LF 0x1
24 #define CONVERT_STAT_BITS_TXT_CRLF 0x2
25 #define CONVERT_STAT_BITS_BIN 0x4
27 enum crlf_action {
28 CRLF_UNDEFINED,
29 CRLF_BINARY,
30 CRLF_TEXT,
31 CRLF_TEXT_INPUT,
32 CRLF_TEXT_CRLF,
33 CRLF_AUTO,
34 CRLF_AUTO_INPUT,
35 CRLF_AUTO_CRLF
38 struct text_stat {
39 /* NUL, CR, LF and CRLF counts */
40 unsigned nul, lonecr, lonelf, crlf;
42 /* These are just approximations! */
43 unsigned printable, nonprintable;
46 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
48 unsigned long i;
50 memset(stats, 0, sizeof(*stats));
52 for (i = 0; i < size; i++) {
53 unsigned char c = buf[i];
54 if (c == '\r') {
55 if (i+1 < size && buf[i+1] == '\n') {
56 stats->crlf++;
57 i++;
58 } else
59 stats->lonecr++;
60 continue;
62 if (c == '\n') {
63 stats->lonelf++;
64 continue;
66 if (c == 127)
67 /* DEL */
68 stats->nonprintable++;
69 else if (c < 32) {
70 switch (c) {
71 /* BS, HT, ESC and FF */
72 case '\b': case '\t': case '\033': case '\014':
73 stats->printable++;
74 break;
75 case 0:
76 stats->nul++;
77 /* fall through */
78 default:
79 stats->nonprintable++;
82 else
83 stats->printable++;
86 /* If file ends with EOF then don't count this EOF as non-printable. */
87 if (size >= 1 && buf[size-1] == '\032')
88 stats->nonprintable--;
92 * The same heuristics as diff.c::mmfile_is_binary()
93 * We treat files with bare CR as binary
95 static int convert_is_binary(unsigned long size, const struct text_stat *stats)
97 if (stats->lonecr)
98 return 1;
99 if (stats->nul)
100 return 1;
101 if ((stats->printable >> 7) < stats->nonprintable)
102 return 1;
103 return 0;
106 static unsigned int gather_convert_stats(const char *data, unsigned long size)
108 struct text_stat stats;
109 int ret = 0;
110 if (!data || !size)
111 return 0;
112 gather_stats(data, size, &stats);
113 if (convert_is_binary(size, &stats))
114 ret |= CONVERT_STAT_BITS_BIN;
115 if (stats.crlf)
116 ret |= CONVERT_STAT_BITS_TXT_CRLF;
117 if (stats.lonelf)
118 ret |= CONVERT_STAT_BITS_TXT_LF;
120 return ret;
123 static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
125 unsigned int convert_stats = gather_convert_stats(data, size);
127 if (convert_stats & CONVERT_STAT_BITS_BIN)
128 return "-text";
129 switch (convert_stats) {
130 case CONVERT_STAT_BITS_TXT_LF:
131 return "lf";
132 case CONVERT_STAT_BITS_TXT_CRLF:
133 return "crlf";
134 case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
135 return "mixed";
136 default:
137 return "none";
141 const char *get_cached_convert_stats_ascii(const struct index_state *istate,
142 const char *path)
144 const char *ret;
145 unsigned long sz;
146 void *data = read_blob_data_from_index(istate, path, &sz);
147 ret = gather_convert_stats_ascii(data, sz);
148 free(data);
149 return ret;
152 const char *get_wt_convert_stats_ascii(const char *path)
154 const char *ret = "";
155 struct strbuf sb = STRBUF_INIT;
156 if (strbuf_read_file(&sb, path, 0) >= 0)
157 ret = gather_convert_stats_ascii(sb.buf, sb.len);
158 strbuf_release(&sb);
159 return ret;
162 static int text_eol_is_crlf(void)
164 if (auto_crlf == AUTO_CRLF_TRUE)
165 return 1;
166 else if (auto_crlf == AUTO_CRLF_INPUT)
167 return 0;
168 if (core_eol == EOL_CRLF)
169 return 1;
170 if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
171 return 1;
172 return 0;
175 static enum eol output_eol(enum crlf_action crlf_action)
177 switch (crlf_action) {
178 case CRLF_BINARY:
179 return EOL_UNSET;
180 case CRLF_TEXT_CRLF:
181 return EOL_CRLF;
182 case CRLF_TEXT_INPUT:
183 return EOL_LF;
184 case CRLF_UNDEFINED:
185 case CRLF_AUTO_CRLF:
186 return EOL_CRLF;
187 case CRLF_AUTO_INPUT:
188 return EOL_LF;
189 case CRLF_TEXT:
190 case CRLF_AUTO:
191 /* fall through */
192 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
194 warning("Illegal crlf_action %d\n", (int)crlf_action);
195 return core_eol;
198 static void check_global_conv_flags_eol(const char *path, enum crlf_action crlf_action,
199 struct text_stat *old_stats, struct text_stat *new_stats,
200 int conv_flags)
202 if (old_stats->crlf && !new_stats->crlf ) {
204 * CRLFs would not be restored by checkout
206 if (conv_flags & CONV_EOL_RNDTRP_DIE)
207 die(_("CRLF would be replaced by LF in %s."), path);
208 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
209 warning(_("CRLF will be replaced by LF in %s.\n"
210 "The file will have its original line"
211 " endings in your working directory."), path);
212 } else if (old_stats->lonelf && !new_stats->lonelf ) {
214 * CRLFs would be added by checkout
216 if (conv_flags & CONV_EOL_RNDTRP_DIE)
217 die(_("LF would be replaced by CRLF in %s"), path);
218 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
219 warning(_("LF will be replaced by CRLF in %s.\n"
220 "The file will have its original line"
221 " endings in your working directory."), path);
225 static int has_crlf_in_index(const struct index_state *istate, const char *path)
227 unsigned long sz;
228 void *data;
229 const char *crp;
230 int has_crlf = 0;
232 data = read_blob_data_from_index(istate, path, &sz);
233 if (!data)
234 return 0;
236 crp = memchr(data, '\r', sz);
237 if (crp) {
238 unsigned int ret_stats;
239 ret_stats = gather_convert_stats(data, sz);
240 if (!(ret_stats & CONVERT_STAT_BITS_BIN) &&
241 (ret_stats & CONVERT_STAT_BITS_TXT_CRLF))
242 has_crlf = 1;
244 free(data);
245 return has_crlf;
248 static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats,
249 enum crlf_action crlf_action)
251 if (output_eol(crlf_action) != EOL_CRLF)
252 return 0;
253 /* No "naked" LF? Nothing to convert, regardless. */
254 if (!stats->lonelf)
255 return 0;
257 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
258 /* If we have any CR or CRLF line endings, we do not touch it */
259 /* This is the new safer autocrlf-handling */
260 if (stats->lonecr || stats->crlf)
261 return 0;
263 if (convert_is_binary(len, stats))
264 return 0;
266 return 1;
270 static int validate_encoding(const char *path, const char *enc,
271 const char *data, size_t len, int die_on_error)
273 /* We only check for UTF here as UTF?? can be an alias for UTF-?? */
274 if (istarts_with(enc, "UTF")) {
276 * Check for detectable errors in UTF encodings
278 if (has_prohibited_utf_bom(enc, data, len)) {
279 const char *error_msg = _(
280 "BOM is prohibited in '%s' if encoded as %s");
282 * This advice is shown for UTF-??BE and UTF-??LE encodings.
283 * We cut off the last two characters of the encoding name
284 * to generate the encoding name suitable for BOMs.
286 const char *advise_msg = _(
287 "The file '%s' contains a byte order "
288 "mark (BOM). Please use UTF-%s as "
289 "working-tree-encoding.");
290 const char *stripped = NULL;
291 char *upper = xstrdup_toupper(enc);
292 upper[strlen(upper)-2] = '\0';
293 if (!skip_prefix(upper, "UTF-", &stripped))
294 skip_prefix(stripped, "UTF", &stripped);
295 advise(advise_msg, path, stripped);
296 free(upper);
297 if (die_on_error)
298 die(error_msg, path, enc);
299 else {
300 return error(error_msg, path, enc);
303 } else if (is_missing_required_utf_bom(enc, data, len)) {
304 const char *error_msg = _(
305 "BOM is required in '%s' if encoded as %s");
306 const char *advise_msg = _(
307 "The file '%s' is missing a byte order "
308 "mark (BOM). Please use UTF-%sBE or UTF-%sLE "
309 "(depending on the byte order) as "
310 "working-tree-encoding.");
311 const char *stripped = NULL;
312 char *upper = xstrdup_toupper(enc);
313 if (!skip_prefix(upper, "UTF-", &stripped))
314 skip_prefix(stripped, "UTF", &stripped);
315 advise(advise_msg, path, stripped, stripped);
316 free(upper);
317 if (die_on_error)
318 die(error_msg, path, enc);
319 else {
320 return error(error_msg, path, enc);
325 return 0;
328 static void trace_encoding(const char *context, const char *path,
329 const char *encoding, const char *buf, size_t len)
331 static struct trace_key coe = TRACE_KEY_INIT(WORKING_TREE_ENCODING);
332 struct strbuf trace = STRBUF_INIT;
333 int i;
335 strbuf_addf(&trace, "%s (%s, considered %s):\n", context, path, encoding);
336 for (i = 0; i < len && buf; ++i) {
337 strbuf_addf(
338 &trace, "| \033[2m%2i:\033[0m %2x \033[2m%c\033[0m%c",
340 (unsigned char) buf[i],
341 (buf[i] > 32 && buf[i] < 127 ? buf[i] : ' '),
342 ((i+1) % 8 && (i+1) < len ? ' ' : '\n')
345 strbuf_addchars(&trace, '\n', 1);
347 trace_strbuf(&coe, &trace);
348 strbuf_release(&trace);
351 static int check_roundtrip(const char *enc_name)
354 * check_roundtrip_encoding contains a string of comma and/or
355 * space separated encodings (eg. "UTF-16, ASCII, CP1125").
356 * Search for the given encoding in that string.
358 const char *found = strcasestr(check_roundtrip_encoding, enc_name);
359 const char *next;
360 int len;
361 if (!found)
362 return 0;
363 next = found + strlen(enc_name);
364 len = strlen(check_roundtrip_encoding);
365 return (found && (
367 * check that the found encoding is at the
368 * beginning of check_roundtrip_encoding or
369 * that it is prefixed with a space or comma
371 found == check_roundtrip_encoding || (
372 (isspace(found[-1]) || found[-1] == ',')
374 ) && (
376 * check that the found encoding is at the
377 * end of check_roundtrip_encoding or
378 * that it is suffixed with a space or comma
380 next == check_roundtrip_encoding + len || (
381 next < check_roundtrip_encoding + len &&
382 (isspace(next[0]) || next[0] == ',')
387 static const char *default_encoding = "UTF-8";
389 static int encode_to_git(const char *path, const char *src, size_t src_len,
390 struct strbuf *buf, const char *enc, int conv_flags)
392 char *dst;
393 int dst_len;
394 int die_on_error = conv_flags & CONV_WRITE_OBJECT;
397 * No encoding is specified or there is nothing to encode.
398 * Tell the caller that the content was not modified.
400 if (!enc || (src && !src_len))
401 return 0;
404 * Looks like we got called from "would_convert_to_git()".
405 * This means Git wants to know if it would encode (= modify!)
406 * the content. Let's answer with "yes", since an encoding was
407 * specified.
409 if (!buf && !src)
410 return 1;
412 if (validate_encoding(path, enc, src, src_len, die_on_error))
413 return 0;
415 trace_encoding("source", path, enc, src, src_len);
416 dst = reencode_string_len(src, src_len, default_encoding, enc,
417 &dst_len);
418 if (!dst) {
420 * We could add the blob "as-is" to Git. However, on checkout
421 * we would try to reencode to the original encoding. This
422 * would fail and we would leave the user with a messed-up
423 * working tree. Let's try to avoid this by screaming loud.
425 const char* msg = _("failed to encode '%s' from %s to %s");
426 if (die_on_error)
427 die(msg, path, enc, default_encoding);
428 else {
429 error(msg, path, enc, default_encoding);
430 return 0;
433 trace_encoding("destination", path, default_encoding, dst, dst_len);
436 * UTF supports lossless conversion round tripping [1] and conversions
437 * between UTF and other encodings are mostly round trip safe as
438 * Unicode aims to be a superset of all other character encodings.
439 * However, certain encodings (e.g. SHIFT-JIS) are known to have round
440 * trip issues [2]. Check the round trip conversion for all encodings
441 * listed in core.checkRoundtripEncoding.
443 * The round trip check is only performed if content is written to Git.
444 * This ensures that no information is lost during conversion to/from
445 * the internal UTF-8 representation.
447 * Please note, the code below is not tested because I was not able to
448 * generate a faulty round trip without an iconv error. Iconv errors
449 * are already caught above.
451 * [1] http://unicode.org/faq/utf_bom.html#gen2
452 * [2] https://support.microsoft.com/en-us/help/170559/prb-conversion-problem-between-shift-jis-and-unicode
454 if (die_on_error && check_roundtrip(enc)) {
455 char *re_src;
456 int re_src_len;
458 re_src = reencode_string_len(dst, dst_len,
459 enc, default_encoding,
460 &re_src_len);
462 trace_printf("Checking roundtrip encoding for %s...\n", enc);
463 trace_encoding("reencoded source", path, enc,
464 re_src, re_src_len);
466 if (!re_src || src_len != re_src_len ||
467 memcmp(src, re_src, src_len)) {
468 const char* msg = _("encoding '%s' from %s to %s and "
469 "back is not the same");
470 die(msg, path, enc, default_encoding);
473 free(re_src);
476 strbuf_attach(buf, dst, dst_len, dst_len + 1);
477 return 1;
480 static int encode_to_worktree(const char *path, const char *src, size_t src_len,
481 struct strbuf *buf, const char *enc)
483 char *dst;
484 int dst_len;
487 * No encoding is specified or there is nothing to encode.
488 * Tell the caller that the content was not modified.
490 if (!enc || (src && !src_len))
491 return 0;
493 dst = reencode_string_len(src, src_len, enc, default_encoding,
494 &dst_len);
495 if (!dst) {
496 error("failed to encode '%s' from %s to %s",
497 path, default_encoding, enc);
498 return 0;
501 strbuf_attach(buf, dst, dst_len, dst_len + 1);
502 return 1;
505 static int crlf_to_git(const struct index_state *istate,
506 const char *path, const char *src, size_t len,
507 struct strbuf *buf,
508 enum crlf_action crlf_action, int conv_flags)
510 struct text_stat stats;
511 char *dst;
512 int convert_crlf_into_lf;
514 if (crlf_action == CRLF_BINARY ||
515 (src && !len))
516 return 0;
519 * If we are doing a dry-run and have no source buffer, there is
520 * nothing to analyze; we must assume we would convert.
522 if (!buf && !src)
523 return 1;
525 gather_stats(src, len, &stats);
526 /* Optimization: No CRLF? Nothing to convert, regardless. */
527 convert_crlf_into_lf = !!stats.crlf;
529 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
530 if (convert_is_binary(len, &stats))
531 return 0;
533 * If the file in the index has any CR in it, do not
534 * convert. This is the new safer autocrlf handling,
535 * unless we want to renormalize in a merge or
536 * cherry-pick.
538 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
539 has_crlf_in_index(istate, path))
540 convert_crlf_into_lf = 0;
542 if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
543 ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
544 struct text_stat new_stats;
545 memcpy(&new_stats, &stats, sizeof(new_stats));
546 /* simulate "git add" */
547 if (convert_crlf_into_lf) {
548 new_stats.lonelf += new_stats.crlf;
549 new_stats.crlf = 0;
551 /* simulate "git checkout" */
552 if (will_convert_lf_to_crlf(len, &new_stats, crlf_action)) {
553 new_stats.crlf += new_stats.lonelf;
554 new_stats.lonelf = 0;
556 check_global_conv_flags_eol(path, crlf_action, &stats, &new_stats, conv_flags);
558 if (!convert_crlf_into_lf)
559 return 0;
562 * At this point all of our source analysis is done, and we are sure we
563 * would convert. If we are in dry-run mode, we can give an answer.
565 if (!buf)
566 return 1;
568 /* only grow if not in place */
569 if (strbuf_avail(buf) + buf->len < len)
570 strbuf_grow(buf, len - buf->len);
571 dst = buf->buf;
572 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
574 * If we guessed, we already know we rejected a file with
575 * lone CR, and we can strip a CR without looking at what
576 * follow it.
578 do {
579 unsigned char c = *src++;
580 if (c != '\r')
581 *dst++ = c;
582 } while (--len);
583 } else {
584 do {
585 unsigned char c = *src++;
586 if (! (c == '\r' && (1 < len && *src == '\n')))
587 *dst++ = c;
588 } while (--len);
590 strbuf_setlen(buf, dst - buf->buf);
591 return 1;
594 static int crlf_to_worktree(const char *path, const char *src, size_t len,
595 struct strbuf *buf, enum crlf_action crlf_action)
597 char *to_free = NULL;
598 struct text_stat stats;
600 if (!len || output_eol(crlf_action) != EOL_CRLF)
601 return 0;
603 gather_stats(src, len, &stats);
604 if (!will_convert_lf_to_crlf(len, &stats, crlf_action))
605 return 0;
607 /* are we "faking" in place editing ? */
608 if (src == buf->buf)
609 to_free = strbuf_detach(buf, NULL);
611 strbuf_grow(buf, len + stats.lonelf);
612 for (;;) {
613 const char *nl = memchr(src, '\n', len);
614 if (!nl)
615 break;
616 if (nl > src && nl[-1] == '\r') {
617 strbuf_add(buf, src, nl + 1 - src);
618 } else {
619 strbuf_add(buf, src, nl - src);
620 strbuf_addstr(buf, "\r\n");
622 len -= nl + 1 - src;
623 src = nl + 1;
625 strbuf_add(buf, src, len);
627 free(to_free);
628 return 1;
631 struct filter_params {
632 const char *src;
633 unsigned long size;
634 int fd;
635 const char *cmd;
636 const char *path;
639 static int filter_buffer_or_fd(int in, int out, void *data)
642 * Spawn cmd and feed the buffer contents through its stdin.
644 struct child_process child_process = CHILD_PROCESS_INIT;
645 struct filter_params *params = (struct filter_params *)data;
646 int write_err, status;
647 const char *argv[] = { NULL, NULL };
649 /* apply % substitution to cmd */
650 struct strbuf cmd = STRBUF_INIT;
651 struct strbuf path = STRBUF_INIT;
652 struct strbuf_expand_dict_entry dict[] = {
653 { "f", NULL, },
654 { NULL, NULL, },
657 /* quote the path to preserve spaces, etc. */
658 sq_quote_buf(&path, params->path);
659 dict[0].value = path.buf;
661 /* expand all %f with the quoted path */
662 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
663 strbuf_release(&path);
665 argv[0] = cmd.buf;
667 child_process.argv = argv;
668 child_process.use_shell = 1;
669 child_process.in = -1;
670 child_process.out = out;
672 if (start_command(&child_process)) {
673 strbuf_release(&cmd);
674 return error("cannot fork to run external filter '%s'", params->cmd);
677 sigchain_push(SIGPIPE, SIG_IGN);
679 if (params->src) {
680 write_err = (write_in_full(child_process.in,
681 params->src, params->size) < 0);
682 if (errno == EPIPE)
683 write_err = 0;
684 } else {
685 write_err = copy_fd(params->fd, child_process.in);
686 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
687 write_err = 0;
690 if (close(child_process.in))
691 write_err = 1;
692 if (write_err)
693 error("cannot feed the input to external filter '%s'", params->cmd);
695 sigchain_pop(SIGPIPE);
697 status = finish_command(&child_process);
698 if (status)
699 error("external filter '%s' failed %d", params->cmd, status);
701 strbuf_release(&cmd);
702 return (write_err || status);
705 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
706 struct strbuf *dst, const char *cmd)
709 * Create a pipeline to have the command filter the buffer's
710 * contents.
712 * (child --> cmd) --> us
714 int err = 0;
715 struct strbuf nbuf = STRBUF_INIT;
716 struct async async;
717 struct filter_params params;
719 memset(&async, 0, sizeof(async));
720 async.proc = filter_buffer_or_fd;
721 async.data = &params;
722 async.out = -1;
723 params.src = src;
724 params.size = len;
725 params.fd = fd;
726 params.cmd = cmd;
727 params.path = path;
729 fflush(NULL);
730 if (start_async(&async))
731 return 0; /* error was already reported */
733 if (strbuf_read(&nbuf, async.out, len) < 0) {
734 err = error("read from external filter '%s' failed", cmd);
736 if (close(async.out)) {
737 err = error("read from external filter '%s' failed", cmd);
739 if (finish_async(&async)) {
740 err = error("external filter '%s' failed", cmd);
743 if (!err) {
744 strbuf_swap(dst, &nbuf);
746 strbuf_release(&nbuf);
747 return !err;
750 #define CAP_CLEAN (1u<<0)
751 #define CAP_SMUDGE (1u<<1)
752 #define CAP_DELAY (1u<<2)
754 struct cmd2process {
755 struct subprocess_entry subprocess; /* must be the first member! */
756 unsigned int supported_capabilities;
759 static int subprocess_map_initialized;
760 static struct hashmap subprocess_map;
762 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
764 static int versions[] = {2, 0};
765 static struct subprocess_capability capabilities[] = {
766 { "clean", CAP_CLEAN },
767 { "smudge", CAP_SMUDGE },
768 { "delay", CAP_DELAY },
769 { NULL, 0 }
771 struct cmd2process *entry = (struct cmd2process *)subprocess;
772 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
773 capabilities,
774 &entry->supported_capabilities);
777 static void handle_filter_error(const struct strbuf *filter_status,
778 struct cmd2process *entry,
779 const unsigned int wanted_capability) {
780 if (!strcmp(filter_status->buf, "error"))
781 ; /* The filter signaled a problem with the file. */
782 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
784 * The filter signaled a permanent problem. Don't try to filter
785 * files with the same command for the lifetime of the current
786 * Git process.
788 entry->supported_capabilities &= ~wanted_capability;
789 } else {
791 * Something went wrong with the protocol filter.
792 * Force shutdown and restart if another blob requires filtering.
794 error("external filter '%s' failed", entry->subprocess.cmd);
795 subprocess_stop(&subprocess_map, &entry->subprocess);
796 free(entry);
800 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
801 int fd, struct strbuf *dst, const char *cmd,
802 const unsigned int wanted_capability,
803 struct delayed_checkout *dco)
805 int err;
806 int can_delay = 0;
807 struct cmd2process *entry;
808 struct child_process *process;
809 struct strbuf nbuf = STRBUF_INIT;
810 struct strbuf filter_status = STRBUF_INIT;
811 const char *filter_type;
813 if (!subprocess_map_initialized) {
814 subprocess_map_initialized = 1;
815 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
816 entry = NULL;
817 } else {
818 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
821 fflush(NULL);
823 if (!entry) {
824 entry = xmalloc(sizeof(*entry));
825 entry->supported_capabilities = 0;
827 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
828 free(entry);
829 return 0;
832 process = &entry->subprocess.process;
834 if (!(entry->supported_capabilities & wanted_capability))
835 return 0;
837 if (wanted_capability & CAP_CLEAN)
838 filter_type = "clean";
839 else if (wanted_capability & CAP_SMUDGE)
840 filter_type = "smudge";
841 else
842 die("unexpected filter type");
844 sigchain_push(SIGPIPE, SIG_IGN);
846 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
847 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
848 if (err)
849 goto done;
851 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
852 if (err) {
853 error("path name too long for external filter");
854 goto done;
857 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
858 if (err)
859 goto done;
861 if ((entry->supported_capabilities & CAP_DELAY) &&
862 dco && dco->state == CE_CAN_DELAY) {
863 can_delay = 1;
864 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
865 if (err)
866 goto done;
869 err = packet_flush_gently(process->in);
870 if (err)
871 goto done;
873 if (fd >= 0)
874 err = write_packetized_from_fd(fd, process->in);
875 else
876 err = write_packetized_from_buf(src, len, process->in);
877 if (err)
878 goto done;
880 err = subprocess_read_status(process->out, &filter_status);
881 if (err)
882 goto done;
884 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
885 string_list_insert(&dco->filters, cmd);
886 string_list_insert(&dco->paths, path);
887 } else {
888 /* The filter got the blob and wants to send us a response. */
889 err = strcmp(filter_status.buf, "success");
890 if (err)
891 goto done;
893 err = read_packetized_to_strbuf(process->out, &nbuf) < 0;
894 if (err)
895 goto done;
897 err = subprocess_read_status(process->out, &filter_status);
898 if (err)
899 goto done;
901 err = strcmp(filter_status.buf, "success");
904 done:
905 sigchain_pop(SIGPIPE);
907 if (err)
908 handle_filter_error(&filter_status, entry, wanted_capability);
909 else
910 strbuf_swap(dst, &nbuf);
911 strbuf_release(&nbuf);
912 return !err;
916 int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
918 int err;
919 char *line;
920 struct cmd2process *entry;
921 struct child_process *process;
922 struct strbuf filter_status = STRBUF_INIT;
924 assert(subprocess_map_initialized);
925 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
926 if (!entry) {
927 error("external filter '%s' is not available anymore although "
928 "not all paths have been filtered", cmd);
929 return 0;
931 process = &entry->subprocess.process;
932 sigchain_push(SIGPIPE, SIG_IGN);
934 err = packet_write_fmt_gently(
935 process->in, "command=list_available_blobs\n");
936 if (err)
937 goto done;
939 err = packet_flush_gently(process->in);
940 if (err)
941 goto done;
943 while ((line = packet_read_line(process->out, NULL))) {
944 const char *path;
945 if (skip_prefix(line, "pathname=", &path))
946 string_list_insert(available_paths, xstrdup(path));
947 else
948 ; /* ignore unknown keys */
951 err = subprocess_read_status(process->out, &filter_status);
952 if (err)
953 goto done;
955 err = strcmp(filter_status.buf, "success");
957 done:
958 sigchain_pop(SIGPIPE);
960 if (err)
961 handle_filter_error(&filter_status, entry, 0);
962 return !err;
965 static struct convert_driver {
966 const char *name;
967 struct convert_driver *next;
968 const char *smudge;
969 const char *clean;
970 const char *process;
971 int required;
972 } *user_convert, **user_convert_tail;
974 static int apply_filter(const char *path, const char *src, size_t len,
975 int fd, struct strbuf *dst, struct convert_driver *drv,
976 const unsigned int wanted_capability,
977 struct delayed_checkout *dco)
979 const char *cmd = NULL;
981 if (!drv)
982 return 0;
984 if (!dst)
985 return 1;
987 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
988 cmd = drv->clean;
989 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
990 cmd = drv->smudge;
992 if (cmd && *cmd)
993 return apply_single_file_filter(path, src, len, fd, dst, cmd);
994 else if (drv->process && *drv->process)
995 return apply_multi_file_filter(path, src, len, fd, dst,
996 drv->process, wanted_capability, dco);
998 return 0;
1001 static int read_convert_config(const char *var, const char *value, void *cb)
1003 const char *key, *name;
1004 int namelen;
1005 struct convert_driver *drv;
1008 * External conversion drivers are configured using
1009 * "filter.<name>.variable".
1011 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
1012 return 0;
1013 for (drv = user_convert; drv; drv = drv->next)
1014 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
1015 break;
1016 if (!drv) {
1017 drv = xcalloc(1, sizeof(struct convert_driver));
1018 drv->name = xmemdupz(name, namelen);
1019 *user_convert_tail = drv;
1020 user_convert_tail = &(drv->next);
1024 * filter.<name>.smudge and filter.<name>.clean specifies
1025 * the command line:
1027 * command-line
1029 * The command-line will not be interpolated in any way.
1032 if (!strcmp("smudge", key))
1033 return git_config_string(&drv->smudge, var, value);
1035 if (!strcmp("clean", key))
1036 return git_config_string(&drv->clean, var, value);
1038 if (!strcmp("process", key))
1039 return git_config_string(&drv->process, var, value);
1041 if (!strcmp("required", key)) {
1042 drv->required = git_config_bool(var, value);
1043 return 0;
1046 return 0;
1049 static int count_ident(const char *cp, unsigned long size)
1052 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
1054 int cnt = 0;
1055 char ch;
1057 while (size) {
1058 ch = *cp++;
1059 size--;
1060 if (ch != '$')
1061 continue;
1062 if (size < 3)
1063 break;
1064 if (memcmp("Id", cp, 2))
1065 continue;
1066 ch = cp[2];
1067 cp += 3;
1068 size -= 3;
1069 if (ch == '$')
1070 cnt++; /* $Id$ */
1071 if (ch != ':')
1072 continue;
1075 * "$Id: ... "; scan up to the closing dollar sign and discard.
1077 while (size) {
1078 ch = *cp++;
1079 size--;
1080 if (ch == '$') {
1081 cnt++;
1082 break;
1084 if (ch == '\n')
1085 break;
1088 return cnt;
1091 static int ident_to_git(const char *path, const char *src, size_t len,
1092 struct strbuf *buf, int ident)
1094 char *dst, *dollar;
1096 if (!ident || (src && !count_ident(src, len)))
1097 return 0;
1099 if (!buf)
1100 return 1;
1102 /* only grow if not in place */
1103 if (strbuf_avail(buf) + buf->len < len)
1104 strbuf_grow(buf, len - buf->len);
1105 dst = buf->buf;
1106 for (;;) {
1107 dollar = memchr(src, '$', len);
1108 if (!dollar)
1109 break;
1110 memmove(dst, src, dollar + 1 - src);
1111 dst += dollar + 1 - src;
1112 len -= dollar + 1 - src;
1113 src = dollar + 1;
1115 if (len > 3 && !memcmp(src, "Id:", 3)) {
1116 dollar = memchr(src + 3, '$', len - 3);
1117 if (!dollar)
1118 break;
1119 if (memchr(src + 3, '\n', dollar - src - 3)) {
1120 /* Line break before the next dollar. */
1121 continue;
1124 memcpy(dst, "Id$", 3);
1125 dst += 3;
1126 len -= dollar + 1 - src;
1127 src = dollar + 1;
1130 memmove(dst, src, len);
1131 strbuf_setlen(buf, dst + len - buf->buf);
1132 return 1;
1135 static int ident_to_worktree(const char *path, const char *src, size_t len,
1136 struct strbuf *buf, int ident)
1138 struct object_id oid;
1139 char *to_free = NULL, *dollar, *spc;
1140 int cnt;
1142 if (!ident)
1143 return 0;
1145 cnt = count_ident(src, len);
1146 if (!cnt)
1147 return 0;
1149 /* are we "faking" in place editing ? */
1150 if (src == buf->buf)
1151 to_free = strbuf_detach(buf, NULL);
1152 hash_object_file(src, len, "blob", &oid);
1154 strbuf_grow(buf, len + cnt * (the_hash_algo->hexsz + 3));
1155 for (;;) {
1156 /* step 1: run to the next '$' */
1157 dollar = memchr(src, '$', len);
1158 if (!dollar)
1159 break;
1160 strbuf_add(buf, src, dollar + 1 - src);
1161 len -= dollar + 1 - src;
1162 src = dollar + 1;
1164 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1165 if (len < 3 || memcmp("Id", src, 2))
1166 continue;
1168 /* step 3: skip over Id$ or Id:xxxxx$ */
1169 if (src[2] == '$') {
1170 src += 3;
1171 len -= 3;
1172 } else if (src[2] == ':') {
1174 * It's possible that an expanded Id has crept its way into the
1175 * repository, we cope with that by stripping the expansion out.
1176 * This is probably not a good idea, since it will cause changes
1177 * on checkout, which won't go away by stash, but let's keep it
1178 * for git-style ids.
1180 dollar = memchr(src + 3, '$', len - 3);
1181 if (!dollar) {
1182 /* incomplete keyword, no more '$', so just quit the loop */
1183 break;
1186 if (memchr(src + 3, '\n', dollar - src - 3)) {
1187 /* Line break before the next dollar. */
1188 continue;
1191 spc = memchr(src + 4, ' ', dollar - src - 4);
1192 if (spc && spc < dollar-1) {
1193 /* There are spaces in unexpected places.
1194 * This is probably an id from some other
1195 * versioning system. Keep it for now.
1197 continue;
1200 len -= dollar + 1 - src;
1201 src = dollar + 1;
1202 } else {
1203 /* it wasn't a "Id$" or "Id:xxxx$" */
1204 continue;
1207 /* step 4: substitute */
1208 strbuf_addstr(buf, "Id: ");
1209 strbuf_addstr(buf, oid_to_hex(&oid));
1210 strbuf_addstr(buf, " $");
1212 strbuf_add(buf, src, len);
1214 free(to_free);
1215 return 1;
1218 static const char *git_path_check_encoding(struct attr_check_item *check)
1220 const char *value = check->value;
1222 if (ATTR_UNSET(value) || !strlen(value))
1223 return NULL;
1225 if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
1226 die(_("true/false are no valid working-tree-encodings"));
1229 /* Don't encode to the default encoding */
1230 if (same_encoding(value, default_encoding))
1231 return NULL;
1233 return value;
1236 static enum crlf_action git_path_check_crlf(struct attr_check_item *check)
1238 const char *value = check->value;
1240 if (ATTR_TRUE(value))
1241 return CRLF_TEXT;
1242 else if (ATTR_FALSE(value))
1243 return CRLF_BINARY;
1244 else if (ATTR_UNSET(value))
1246 else if (!strcmp(value, "input"))
1247 return CRLF_TEXT_INPUT;
1248 else if (!strcmp(value, "auto"))
1249 return CRLF_AUTO;
1250 return CRLF_UNDEFINED;
1253 static enum eol git_path_check_eol(struct attr_check_item *check)
1255 const char *value = check->value;
1257 if (ATTR_UNSET(value))
1259 else if (!strcmp(value, "lf"))
1260 return EOL_LF;
1261 else if (!strcmp(value, "crlf"))
1262 return EOL_CRLF;
1263 return EOL_UNSET;
1266 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
1268 const char *value = check->value;
1269 struct convert_driver *drv;
1271 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1272 return NULL;
1273 for (drv = user_convert; drv; drv = drv->next)
1274 if (!strcmp(value, drv->name))
1275 return drv;
1276 return NULL;
1279 static int git_path_check_ident(struct attr_check_item *check)
1281 const char *value = check->value;
1283 return !!ATTR_TRUE(value);
1286 struct conv_attrs {
1287 struct convert_driver *drv;
1288 enum crlf_action attr_action; /* What attr says */
1289 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
1290 int ident;
1291 const char *working_tree_encoding; /* Supported encoding or default encoding if NULL */
1294 static void convert_attrs(const struct index_state *istate,
1295 struct conv_attrs *ca, const char *path)
1297 static struct attr_check *check;
1299 if (!check) {
1300 check = attr_check_initl("crlf", "ident", "filter",
1301 "eol", "text", "working-tree-encoding",
1302 NULL);
1303 user_convert_tail = &user_convert;
1304 git_config(read_convert_config, NULL);
1307 if (!git_check_attr(istate, path, check)) {
1308 struct attr_check_item *ccheck = check->items;
1309 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1310 if (ca->crlf_action == CRLF_UNDEFINED)
1311 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1312 ca->ident = git_path_check_ident(ccheck + 1);
1313 ca->drv = git_path_check_convert(ccheck + 2);
1314 if (ca->crlf_action != CRLF_BINARY) {
1315 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1316 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1317 ca->crlf_action = CRLF_AUTO_INPUT;
1318 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1319 ca->crlf_action = CRLF_AUTO_CRLF;
1320 else if (eol_attr == EOL_LF)
1321 ca->crlf_action = CRLF_TEXT_INPUT;
1322 else if (eol_attr == EOL_CRLF)
1323 ca->crlf_action = CRLF_TEXT_CRLF;
1325 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
1326 } else {
1327 ca->drv = NULL;
1328 ca->crlf_action = CRLF_UNDEFINED;
1329 ca->ident = 0;
1332 /* Save attr and make a decision for action */
1333 ca->attr_action = ca->crlf_action;
1334 if (ca->crlf_action == CRLF_TEXT)
1335 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1336 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1337 ca->crlf_action = CRLF_BINARY;
1338 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1339 ca->crlf_action = CRLF_AUTO_CRLF;
1340 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1341 ca->crlf_action = CRLF_AUTO_INPUT;
1344 int would_convert_to_git_filter_fd(const struct index_state *istate, const char *path)
1346 struct conv_attrs ca;
1348 convert_attrs(istate, &ca, path);
1349 if (!ca.drv)
1350 return 0;
1353 * Apply a filter to an fd only if the filter is required to succeed.
1354 * We must die if the filter fails, because the original data before
1355 * filtering is not available.
1357 if (!ca.drv->required)
1358 return 0;
1360 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL);
1363 const char *get_convert_attr_ascii(const struct index_state *istate, const char *path)
1365 struct conv_attrs ca;
1367 convert_attrs(istate, &ca, path);
1368 switch (ca.attr_action) {
1369 case CRLF_UNDEFINED:
1370 return "";
1371 case CRLF_BINARY:
1372 return "-text";
1373 case CRLF_TEXT:
1374 return "text";
1375 case CRLF_TEXT_INPUT:
1376 return "text eol=lf";
1377 case CRLF_TEXT_CRLF:
1378 return "text eol=crlf";
1379 case CRLF_AUTO:
1380 return "text=auto";
1381 case CRLF_AUTO_CRLF:
1382 return "text=auto eol=crlf";
1383 case CRLF_AUTO_INPUT:
1384 return "text=auto eol=lf";
1386 return "";
1389 int convert_to_git(const struct index_state *istate,
1390 const char *path, const char *src, size_t len,
1391 struct strbuf *dst, int conv_flags)
1393 int ret = 0;
1394 struct conv_attrs ca;
1396 convert_attrs(istate, &ca, path);
1398 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL);
1399 if (!ret && ca.drv && ca.drv->required)
1400 die("%s: clean filter '%s' failed", path, ca.drv->name);
1402 if (ret && dst) {
1403 src = dst->buf;
1404 len = dst->len;
1407 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1408 if (ret && dst) {
1409 src = dst->buf;
1410 len = dst->len;
1413 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1414 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
1415 if (ret && dst) {
1416 src = dst->buf;
1417 len = dst->len;
1420 return ret | ident_to_git(path, src, len, dst, ca.ident);
1423 void convert_to_git_filter_fd(const struct index_state *istate,
1424 const char *path, int fd, struct strbuf *dst,
1425 int conv_flags)
1427 struct conv_attrs ca;
1428 convert_attrs(istate, &ca, path);
1430 assert(ca.drv);
1431 assert(ca.drv->clean || ca.drv->process);
1433 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL))
1434 die("%s: clean filter '%s' failed", path, ca.drv->name);
1436 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
1437 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
1438 ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
1441 static int convert_to_working_tree_internal(const struct index_state *istate,
1442 const char *path, const char *src,
1443 size_t len, struct strbuf *dst,
1444 int normalizing, struct delayed_checkout *dco)
1446 int ret = 0, ret_filter = 0;
1447 struct conv_attrs ca;
1449 convert_attrs(istate, &ca, path);
1451 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
1452 if (ret) {
1453 src = dst->buf;
1454 len = dst->len;
1457 * CRLF conversion can be skipped if normalizing, unless there
1458 * is a smudge or process filter (even if the process filter doesn't
1459 * support smudge). The filters might expect CRLFs.
1461 if ((ca.drv && (ca.drv->smudge || ca.drv->process)) || !normalizing) {
1462 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
1463 if (ret) {
1464 src = dst->buf;
1465 len = dst->len;
1469 ret |= encode_to_worktree(path, src, len, dst, ca.working_tree_encoding);
1470 if (ret) {
1471 src = dst->buf;
1472 len = dst->len;
1475 ret_filter = apply_filter(
1476 path, src, len, -1, dst, ca.drv, CAP_SMUDGE, dco);
1477 if (!ret_filter && ca.drv && ca.drv->required)
1478 die("%s: smudge filter %s failed", path, ca.drv->name);
1480 return ret | ret_filter;
1483 int async_convert_to_working_tree(const struct index_state *istate,
1484 const char *path, const char *src,
1485 size_t len, struct strbuf *dst,
1486 void *dco)
1488 return convert_to_working_tree_internal(istate, path, src, len, dst, 0, dco);
1491 int convert_to_working_tree(const struct index_state *istate,
1492 const char *path, const char *src,
1493 size_t len, struct strbuf *dst)
1495 return convert_to_working_tree_internal(istate, path, src, len, dst, 0, NULL);
1498 int renormalize_buffer(const struct index_state *istate, const char *path,
1499 const char *src, size_t len, struct strbuf *dst)
1501 int ret = convert_to_working_tree_internal(istate, path, src, len, dst, 1, NULL);
1502 if (ret) {
1503 src = dst->buf;
1504 len = dst->len;
1506 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
1509 /*****************************************************************
1511 * Streaming conversion support
1513 *****************************************************************/
1515 typedef int (*filter_fn)(struct stream_filter *,
1516 const char *input, size_t *isize_p,
1517 char *output, size_t *osize_p);
1518 typedef void (*free_fn)(struct stream_filter *);
1520 struct stream_filter_vtbl {
1521 filter_fn filter;
1522 free_fn free;
1525 struct stream_filter {
1526 struct stream_filter_vtbl *vtbl;
1529 static int null_filter_fn(struct stream_filter *filter,
1530 const char *input, size_t *isize_p,
1531 char *output, size_t *osize_p)
1533 size_t count;
1535 if (!input)
1536 return 0; /* we do not keep any states */
1537 count = *isize_p;
1538 if (*osize_p < count)
1539 count = *osize_p;
1540 if (count) {
1541 memmove(output, input, count);
1542 *isize_p -= count;
1543 *osize_p -= count;
1545 return 0;
1548 static void null_free_fn(struct stream_filter *filter)
1550 ; /* nothing -- null instances are shared */
1553 static struct stream_filter_vtbl null_vtbl = {
1554 null_filter_fn,
1555 null_free_fn,
1558 static struct stream_filter null_filter_singleton = {
1559 &null_vtbl,
1562 int is_null_stream_filter(struct stream_filter *filter)
1564 return filter == &null_filter_singleton;
1569 * LF-to-CRLF filter
1572 struct lf_to_crlf_filter {
1573 struct stream_filter filter;
1574 unsigned has_held:1;
1575 char held;
1578 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1579 const char *input, size_t *isize_p,
1580 char *output, size_t *osize_p)
1582 size_t count, o = 0;
1583 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1586 * We may be holding onto the CR to see if it is followed by a
1587 * LF, in which case we would need to go to the main loop.
1588 * Otherwise, just emit it to the output stream.
1590 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1591 output[o++] = lf_to_crlf->held;
1592 lf_to_crlf->has_held = 0;
1595 /* We are told to drain */
1596 if (!input) {
1597 *osize_p -= o;
1598 return 0;
1601 count = *isize_p;
1602 if (count || lf_to_crlf->has_held) {
1603 size_t i;
1604 int was_cr = 0;
1606 if (lf_to_crlf->has_held) {
1607 was_cr = 1;
1608 lf_to_crlf->has_held = 0;
1611 for (i = 0; o < *osize_p && i < count; i++) {
1612 char ch = input[i];
1614 if (ch == '\n') {
1615 output[o++] = '\r';
1616 } else if (was_cr) {
1618 * Previous round saw CR and it is not followed
1619 * by a LF; emit the CR before processing the
1620 * current character.
1622 output[o++] = '\r';
1626 * We may have consumed the last output slot,
1627 * in which case we need to break out of this
1628 * loop; hold the current character before
1629 * returning.
1631 if (*osize_p <= o) {
1632 lf_to_crlf->has_held = 1;
1633 lf_to_crlf->held = ch;
1634 continue; /* break but increment i */
1637 if (ch == '\r') {
1638 was_cr = 1;
1639 continue;
1642 was_cr = 0;
1643 output[o++] = ch;
1646 *osize_p -= o;
1647 *isize_p -= i;
1649 if (!lf_to_crlf->has_held && was_cr) {
1650 lf_to_crlf->has_held = 1;
1651 lf_to_crlf->held = '\r';
1654 return 0;
1657 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1659 free(filter);
1662 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1663 lf_to_crlf_filter_fn,
1664 lf_to_crlf_free_fn,
1667 static struct stream_filter *lf_to_crlf_filter(void)
1669 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1671 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1672 return (struct stream_filter *)lf_to_crlf;
1676 * Cascade filter
1678 #define FILTER_BUFFER 1024
1679 struct cascade_filter {
1680 struct stream_filter filter;
1681 struct stream_filter *one;
1682 struct stream_filter *two;
1683 char buf[FILTER_BUFFER];
1684 int end, ptr;
1687 static int cascade_filter_fn(struct stream_filter *filter,
1688 const char *input, size_t *isize_p,
1689 char *output, size_t *osize_p)
1691 struct cascade_filter *cas = (struct cascade_filter *) filter;
1692 size_t filled = 0;
1693 size_t sz = *osize_p;
1694 size_t to_feed, remaining;
1697 * input -- (one) --> buf -- (two) --> output
1699 while (filled < sz) {
1700 remaining = sz - filled;
1702 /* do we already have something to feed two with? */
1703 if (cas->ptr < cas->end) {
1704 to_feed = cas->end - cas->ptr;
1705 if (stream_filter(cas->two,
1706 cas->buf + cas->ptr, &to_feed,
1707 output + filled, &remaining))
1708 return -1;
1709 cas->ptr += (cas->end - cas->ptr) - to_feed;
1710 filled = sz - remaining;
1711 continue;
1714 /* feed one from upstream and have it emit into our buffer */
1715 to_feed = input ? *isize_p : 0;
1716 if (input && !to_feed)
1717 break;
1718 remaining = sizeof(cas->buf);
1719 if (stream_filter(cas->one,
1720 input, &to_feed,
1721 cas->buf, &remaining))
1722 return -1;
1723 cas->end = sizeof(cas->buf) - remaining;
1724 cas->ptr = 0;
1725 if (input) {
1726 size_t fed = *isize_p - to_feed;
1727 *isize_p -= fed;
1728 input += fed;
1731 /* do we know that we drained one completely? */
1732 if (input || cas->end)
1733 continue;
1735 /* tell two to drain; we have nothing more to give it */
1736 to_feed = 0;
1737 remaining = sz - filled;
1738 if (stream_filter(cas->two,
1739 NULL, &to_feed,
1740 output + filled, &remaining))
1741 return -1;
1742 if (remaining == (sz - filled))
1743 break; /* completely drained two */
1744 filled = sz - remaining;
1746 *osize_p -= filled;
1747 return 0;
1750 static void cascade_free_fn(struct stream_filter *filter)
1752 struct cascade_filter *cas = (struct cascade_filter *)filter;
1753 free_stream_filter(cas->one);
1754 free_stream_filter(cas->two);
1755 free(filter);
1758 static struct stream_filter_vtbl cascade_vtbl = {
1759 cascade_filter_fn,
1760 cascade_free_fn,
1763 static struct stream_filter *cascade_filter(struct stream_filter *one,
1764 struct stream_filter *two)
1766 struct cascade_filter *cascade;
1768 if (!one || is_null_stream_filter(one))
1769 return two;
1770 if (!two || is_null_stream_filter(two))
1771 return one;
1773 cascade = xmalloc(sizeof(*cascade));
1774 cascade->one = one;
1775 cascade->two = two;
1776 cascade->end = cascade->ptr = 0;
1777 cascade->filter.vtbl = &cascade_vtbl;
1778 return (struct stream_filter *)cascade;
1782 * ident filter
1784 #define IDENT_DRAINING (-1)
1785 #define IDENT_SKIPPING (-2)
1786 struct ident_filter {
1787 struct stream_filter filter;
1788 struct strbuf left;
1789 int state;
1790 char ident[GIT_MAX_HEXSZ + 5]; /* ": x40 $" */
1793 static int is_foreign_ident(const char *str)
1795 int i;
1797 if (!skip_prefix(str, "$Id: ", &str))
1798 return 0;
1799 for (i = 0; str[i]; i++) {
1800 if (isspace(str[i]) && str[i+1] != '$')
1801 return 1;
1803 return 0;
1806 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1808 size_t to_drain = ident->left.len;
1810 if (*osize_p < to_drain)
1811 to_drain = *osize_p;
1812 if (to_drain) {
1813 memcpy(*output_p, ident->left.buf, to_drain);
1814 strbuf_remove(&ident->left, 0, to_drain);
1815 *output_p += to_drain;
1816 *osize_p -= to_drain;
1818 if (!ident->left.len)
1819 ident->state = 0;
1822 static int ident_filter_fn(struct stream_filter *filter,
1823 const char *input, size_t *isize_p,
1824 char *output, size_t *osize_p)
1826 struct ident_filter *ident = (struct ident_filter *)filter;
1827 static const char head[] = "$Id";
1829 if (!input) {
1830 /* drain upon eof */
1831 switch (ident->state) {
1832 default:
1833 strbuf_add(&ident->left, head, ident->state);
1834 /* fallthrough */
1835 case IDENT_SKIPPING:
1836 /* fallthrough */
1837 case IDENT_DRAINING:
1838 ident_drain(ident, &output, osize_p);
1840 return 0;
1843 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1844 int ch;
1846 if (ident->state == IDENT_DRAINING) {
1847 ident_drain(ident, &output, osize_p);
1848 if (!*osize_p)
1849 break;
1850 continue;
1853 ch = *(input++);
1854 (*isize_p)--;
1856 if (ident->state == IDENT_SKIPPING) {
1858 * Skipping until '$' or LF, but keeping them
1859 * in case it is a foreign ident.
1861 strbuf_addch(&ident->left, ch);
1862 if (ch != '\n' && ch != '$')
1863 continue;
1864 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1865 strbuf_setlen(&ident->left, sizeof(head) - 1);
1866 strbuf_addstr(&ident->left, ident->ident);
1868 ident->state = IDENT_DRAINING;
1869 continue;
1872 if (ident->state < sizeof(head) &&
1873 head[ident->state] == ch) {
1874 ident->state++;
1875 continue;
1878 if (ident->state)
1879 strbuf_add(&ident->left, head, ident->state);
1880 if (ident->state == sizeof(head) - 1) {
1881 if (ch != ':' && ch != '$') {
1882 strbuf_addch(&ident->left, ch);
1883 ident->state = 0;
1884 continue;
1887 if (ch == ':') {
1888 strbuf_addch(&ident->left, ch);
1889 ident->state = IDENT_SKIPPING;
1890 } else {
1891 strbuf_addstr(&ident->left, ident->ident);
1892 ident->state = IDENT_DRAINING;
1894 continue;
1897 strbuf_addch(&ident->left, ch);
1898 ident->state = IDENT_DRAINING;
1900 return 0;
1903 static void ident_free_fn(struct stream_filter *filter)
1905 struct ident_filter *ident = (struct ident_filter *)filter;
1906 strbuf_release(&ident->left);
1907 free(filter);
1910 static struct stream_filter_vtbl ident_vtbl = {
1911 ident_filter_fn,
1912 ident_free_fn,
1915 static struct stream_filter *ident_filter(const struct object_id *oid)
1917 struct ident_filter *ident = xmalloc(sizeof(*ident));
1919 xsnprintf(ident->ident, sizeof(ident->ident),
1920 ": %s $", oid_to_hex(oid));
1921 strbuf_init(&ident->left, 0);
1922 ident->filter.vtbl = &ident_vtbl;
1923 ident->state = 0;
1924 return (struct stream_filter *)ident;
1928 * Return an appropriately constructed filter for the path, or NULL if
1929 * the contents cannot be filtered without reading the whole thing
1930 * in-core.
1932 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1933 * large binary blob you would want us not to slurp into the memory!
1935 struct stream_filter *get_stream_filter(const struct index_state *istate,
1936 const char *path,
1937 const struct object_id *oid)
1939 struct conv_attrs ca;
1940 struct stream_filter *filter = NULL;
1942 convert_attrs(istate, &ca, path);
1943 if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
1944 return NULL;
1946 if (ca.working_tree_encoding)
1947 return NULL;
1949 if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1950 return NULL;
1952 if (ca.ident)
1953 filter = ident_filter(oid);
1955 if (output_eol(ca.crlf_action) == EOL_CRLF)
1956 filter = cascade_filter(filter, lf_to_crlf_filter());
1957 else
1958 filter = cascade_filter(filter, &null_filter_singleton);
1960 return filter;
1963 void free_stream_filter(struct stream_filter *filter)
1965 filter->vtbl->free(filter);
1968 int stream_filter(struct stream_filter *filter,
1969 const char *input, size_t *isize_p,
1970 char *output, size_t *osize_p)
1972 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);