convert: check for detectable errors in UTF encodings
[git.git] / convert.c
blob0e7930c1542baaaac82c55f3005ce344b74e7114
1 #define NO_THE_INDEX_COMPATIBILITY_MACROS
2 #include "cache.h"
3 #include "config.h"
4 #include "attr.h"
5 #include "run-command.h"
6 #include "quote.h"
7 #include "sigchain.h"
8 #include "pkt-line.h"
9 #include "sub-process.h"
10 #include "utf8.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
26 enum crlf_action {
27 CRLF_UNDEFINED,
28 CRLF_BINARY,
29 CRLF_TEXT,
30 CRLF_TEXT_INPUT,
31 CRLF_TEXT_CRLF,
32 CRLF_AUTO,
33 CRLF_AUTO_INPUT,
34 CRLF_AUTO_CRLF
37 struct text_stat {
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)
47 unsigned long i;
49 memset(stats, 0, sizeof(*stats));
51 for (i = 0; i < size; i++) {
52 unsigned char c = buf[i];
53 if (c == '\r') {
54 if (i+1 < size && buf[i+1] == '\n') {
55 stats->crlf++;
56 i++;
57 } else
58 stats->lonecr++;
59 continue;
61 if (c == '\n') {
62 stats->lonelf++;
63 continue;
65 if (c == 127)
66 /* DEL */
67 stats->nonprintable++;
68 else if (c < 32) {
69 switch (c) {
70 /* BS, HT, ESC and FF */
71 case '\b': case '\t': case '\033': case '\014':
72 stats->printable++;
73 break;
74 case 0:
75 stats->nul++;
76 /* fall through */
77 default:
78 stats->nonprintable++;
81 else
82 stats->printable++;
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)
96 if (stats->lonecr)
97 return 1;
98 if (stats->nul)
99 return 1;
100 if ((stats->printable >> 7) < stats->nonprintable)
101 return 1;
102 return 0;
105 static unsigned int gather_convert_stats(const char *data, unsigned long size)
107 struct text_stat stats;
108 int ret = 0;
109 if (!data || !size)
110 return 0;
111 gather_stats(data, size, &stats);
112 if (convert_is_binary(size, &stats))
113 ret |= CONVERT_STAT_BITS_BIN;
114 if (stats.crlf)
115 ret |= CONVERT_STAT_BITS_TXT_CRLF;
116 if (stats.lonelf)
117 ret |= CONVERT_STAT_BITS_TXT_LF;
119 return ret;
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)
127 return "-text";
128 switch (convert_stats) {
129 case CONVERT_STAT_BITS_TXT_LF:
130 return "lf";
131 case CONVERT_STAT_BITS_TXT_CRLF:
132 return "crlf";
133 case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
134 return "mixed";
135 default:
136 return "none";
140 const char *get_cached_convert_stats_ascii(const struct index_state *istate,
141 const char *path)
143 const char *ret;
144 unsigned long sz;
145 void *data = read_blob_data_from_index(istate, path, &sz);
146 ret = gather_convert_stats_ascii(data, sz);
147 free(data);
148 return ret;
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);
157 strbuf_release(&sb);
158 return ret;
161 static int text_eol_is_crlf(void)
163 if (auto_crlf == AUTO_CRLF_TRUE)
164 return 1;
165 else if (auto_crlf == AUTO_CRLF_INPUT)
166 return 0;
167 if (core_eol == EOL_CRLF)
168 return 1;
169 if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
170 return 1;
171 return 0;
174 static enum eol output_eol(enum crlf_action crlf_action)
176 switch (crlf_action) {
177 case CRLF_BINARY:
178 return EOL_UNSET;
179 case CRLF_TEXT_CRLF:
180 return EOL_CRLF;
181 case CRLF_TEXT_INPUT:
182 return EOL_LF;
183 case CRLF_UNDEFINED:
184 case CRLF_AUTO_CRLF:
185 return EOL_CRLF;
186 case CRLF_AUTO_INPUT:
187 return EOL_LF;
188 case CRLF_TEXT:
189 case CRLF_AUTO:
190 /* fall through */
191 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
193 warning("Illegal crlf_action %d\n", (int)crlf_action);
194 return core_eol;
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,
199 int conv_flags)
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)
226 unsigned long sz;
227 void *data;
228 const char *crp;
229 int has_crlf = 0;
231 data = read_blob_data_from_index(istate, path, &sz);
232 if (!data)
233 return 0;
235 crp = memchr(data, '\r', sz);
236 if (crp) {
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))
241 has_crlf = 1;
243 free(data);
244 return has_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)
251 return 0;
252 /* No "naked" LF? Nothing to convert, regardless. */
253 if (!stats->lonelf)
254 return 0;
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)
260 return 0;
262 if (convert_is_binary(len, stats))
263 return 0;
265 return 1;
269 static int validate_encoding(const char *path, const char *enc,
270 const char *data, size_t len, int die_on_error)
272 /* We only check for UTF here as UTF?? can be an alias for UTF-?? */
273 if (istarts_with(enc, "UTF")) {
275 * Check for detectable errors in UTF encodings
277 if (has_prohibited_utf_bom(enc, data, len)) {
278 const char *error_msg = _(
279 "BOM is prohibited in '%s' if encoded as %s");
281 * This advice is shown for UTF-??BE and UTF-??LE encodings.
282 * We cut off the last two characters of the encoding name
283 * to generate the encoding name suitable for BOMs.
285 const char *advise_msg = _(
286 "The file '%s' contains a byte order "
287 "mark (BOM). Please use UTF-%s as "
288 "working-tree-encoding.");
289 const char *stripped = NULL;
290 char *upper = xstrdup_toupper(enc);
291 upper[strlen(upper)-2] = '\0';
292 if (!skip_prefix(upper, "UTF-", &stripped))
293 skip_prefix(stripped, "UTF", &stripped);
294 advise(advise_msg, path, stripped);
295 free(upper);
296 if (die_on_error)
297 die(error_msg, path, enc);
298 else {
299 return error(error_msg, path, enc);
302 } else if (is_missing_required_utf_bom(enc, data, len)) {
303 const char *error_msg = _(
304 "BOM is required in '%s' if encoded as %s");
305 const char *advise_msg = _(
306 "The file '%s' is missing a byte order "
307 "mark (BOM). Please use UTF-%sBE or UTF-%sLE "
308 "(depending on the byte order) as "
309 "working-tree-encoding.");
310 const char *stripped = NULL;
311 char *upper = xstrdup_toupper(enc);
312 if (!skip_prefix(upper, "UTF-", &stripped))
313 skip_prefix(stripped, "UTF", &stripped);
314 advise(advise_msg, path, stripped, stripped);
315 free(upper);
316 if (die_on_error)
317 die(error_msg, path, enc);
318 else {
319 return error(error_msg, path, enc);
324 return 0;
327 static const char *default_encoding = "UTF-8";
329 static int encode_to_git(const char *path, const char *src, size_t src_len,
330 struct strbuf *buf, const char *enc, int conv_flags)
332 char *dst;
333 int dst_len;
334 int die_on_error = conv_flags & CONV_WRITE_OBJECT;
337 * No encoding is specified or there is nothing to encode.
338 * Tell the caller that the content was not modified.
340 if (!enc || (src && !src_len))
341 return 0;
344 * Looks like we got called from "would_convert_to_git()".
345 * This means Git wants to know if it would encode (= modify!)
346 * the content. Let's answer with "yes", since an encoding was
347 * specified.
349 if (!buf && !src)
350 return 1;
352 if (validate_encoding(path, enc, src, src_len, die_on_error))
353 return 0;
355 dst = reencode_string_len(src, src_len, default_encoding, enc,
356 &dst_len);
357 if (!dst) {
359 * We could add the blob "as-is" to Git. However, on checkout
360 * we would try to reencode to the original encoding. This
361 * would fail and we would leave the user with a messed-up
362 * working tree. Let's try to avoid this by screaming loud.
364 const char* msg = _("failed to encode '%s' from %s to %s");
365 if (die_on_error)
366 die(msg, path, enc, default_encoding);
367 else {
368 error(msg, path, enc, default_encoding);
369 return 0;
373 strbuf_attach(buf, dst, dst_len, dst_len + 1);
374 return 1;
377 static int encode_to_worktree(const char *path, const char *src, size_t src_len,
378 struct strbuf *buf, const char *enc)
380 char *dst;
381 int dst_len;
384 * No encoding is specified or there is nothing to encode.
385 * Tell the caller that the content was not modified.
387 if (!enc || (src && !src_len))
388 return 0;
390 dst = reencode_string_len(src, src_len, enc, default_encoding,
391 &dst_len);
392 if (!dst) {
393 error("failed to encode '%s' from %s to %s",
394 path, default_encoding, enc);
395 return 0;
398 strbuf_attach(buf, dst, dst_len, dst_len + 1);
399 return 1;
402 static int crlf_to_git(const struct index_state *istate,
403 const char *path, const char *src, size_t len,
404 struct strbuf *buf,
405 enum crlf_action crlf_action, int conv_flags)
407 struct text_stat stats;
408 char *dst;
409 int convert_crlf_into_lf;
411 if (crlf_action == CRLF_BINARY ||
412 (src && !len))
413 return 0;
416 * If we are doing a dry-run and have no source buffer, there is
417 * nothing to analyze; we must assume we would convert.
419 if (!buf && !src)
420 return 1;
422 gather_stats(src, len, &stats);
423 /* Optimization: No CRLF? Nothing to convert, regardless. */
424 convert_crlf_into_lf = !!stats.crlf;
426 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
427 if (convert_is_binary(len, &stats))
428 return 0;
430 * If the file in the index has any CR in it, do not
431 * convert. This is the new safer autocrlf handling,
432 * unless we want to renormalize in a merge or
433 * cherry-pick.
435 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
436 has_crlf_in_index(istate, path))
437 convert_crlf_into_lf = 0;
439 if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
440 ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
441 struct text_stat new_stats;
442 memcpy(&new_stats, &stats, sizeof(new_stats));
443 /* simulate "git add" */
444 if (convert_crlf_into_lf) {
445 new_stats.lonelf += new_stats.crlf;
446 new_stats.crlf = 0;
448 /* simulate "git checkout" */
449 if (will_convert_lf_to_crlf(len, &new_stats, crlf_action)) {
450 new_stats.crlf += new_stats.lonelf;
451 new_stats.lonelf = 0;
453 check_global_conv_flags_eol(path, crlf_action, &stats, &new_stats, conv_flags);
455 if (!convert_crlf_into_lf)
456 return 0;
459 * At this point all of our source analysis is done, and we are sure we
460 * would convert. If we are in dry-run mode, we can give an answer.
462 if (!buf)
463 return 1;
465 /* only grow if not in place */
466 if (strbuf_avail(buf) + buf->len < len)
467 strbuf_grow(buf, len - buf->len);
468 dst = buf->buf;
469 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
471 * If we guessed, we already know we rejected a file with
472 * lone CR, and we can strip a CR without looking at what
473 * follow it.
475 do {
476 unsigned char c = *src++;
477 if (c != '\r')
478 *dst++ = c;
479 } while (--len);
480 } else {
481 do {
482 unsigned char c = *src++;
483 if (! (c == '\r' && (1 < len && *src == '\n')))
484 *dst++ = c;
485 } while (--len);
487 strbuf_setlen(buf, dst - buf->buf);
488 return 1;
491 static int crlf_to_worktree(const char *path, const char *src, size_t len,
492 struct strbuf *buf, enum crlf_action crlf_action)
494 char *to_free = NULL;
495 struct text_stat stats;
497 if (!len || output_eol(crlf_action) != EOL_CRLF)
498 return 0;
500 gather_stats(src, len, &stats);
501 if (!will_convert_lf_to_crlf(len, &stats, crlf_action))
502 return 0;
504 /* are we "faking" in place editing ? */
505 if (src == buf->buf)
506 to_free = strbuf_detach(buf, NULL);
508 strbuf_grow(buf, len + stats.lonelf);
509 for (;;) {
510 const char *nl = memchr(src, '\n', len);
511 if (!nl)
512 break;
513 if (nl > src && nl[-1] == '\r') {
514 strbuf_add(buf, src, nl + 1 - src);
515 } else {
516 strbuf_add(buf, src, nl - src);
517 strbuf_addstr(buf, "\r\n");
519 len -= nl + 1 - src;
520 src = nl + 1;
522 strbuf_add(buf, src, len);
524 free(to_free);
525 return 1;
528 struct filter_params {
529 const char *src;
530 unsigned long size;
531 int fd;
532 const char *cmd;
533 const char *path;
536 static int filter_buffer_or_fd(int in, int out, void *data)
539 * Spawn cmd and feed the buffer contents through its stdin.
541 struct child_process child_process = CHILD_PROCESS_INIT;
542 struct filter_params *params = (struct filter_params *)data;
543 int write_err, status;
544 const char *argv[] = { NULL, NULL };
546 /* apply % substitution to cmd */
547 struct strbuf cmd = STRBUF_INIT;
548 struct strbuf path = STRBUF_INIT;
549 struct strbuf_expand_dict_entry dict[] = {
550 { "f", NULL, },
551 { NULL, NULL, },
554 /* quote the path to preserve spaces, etc. */
555 sq_quote_buf(&path, params->path);
556 dict[0].value = path.buf;
558 /* expand all %f with the quoted path */
559 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
560 strbuf_release(&path);
562 argv[0] = cmd.buf;
564 child_process.argv = argv;
565 child_process.use_shell = 1;
566 child_process.in = -1;
567 child_process.out = out;
569 if (start_command(&child_process)) {
570 strbuf_release(&cmd);
571 return error("cannot fork to run external filter '%s'", params->cmd);
574 sigchain_push(SIGPIPE, SIG_IGN);
576 if (params->src) {
577 write_err = (write_in_full(child_process.in,
578 params->src, params->size) < 0);
579 if (errno == EPIPE)
580 write_err = 0;
581 } else {
582 write_err = copy_fd(params->fd, child_process.in);
583 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
584 write_err = 0;
587 if (close(child_process.in))
588 write_err = 1;
589 if (write_err)
590 error("cannot feed the input to external filter '%s'", params->cmd);
592 sigchain_pop(SIGPIPE);
594 status = finish_command(&child_process);
595 if (status)
596 error("external filter '%s' failed %d", params->cmd, status);
598 strbuf_release(&cmd);
599 return (write_err || status);
602 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
603 struct strbuf *dst, const char *cmd)
606 * Create a pipeline to have the command filter the buffer's
607 * contents.
609 * (child --> cmd) --> us
611 int err = 0;
612 struct strbuf nbuf = STRBUF_INIT;
613 struct async async;
614 struct filter_params params;
616 memset(&async, 0, sizeof(async));
617 async.proc = filter_buffer_or_fd;
618 async.data = &params;
619 async.out = -1;
620 params.src = src;
621 params.size = len;
622 params.fd = fd;
623 params.cmd = cmd;
624 params.path = path;
626 fflush(NULL);
627 if (start_async(&async))
628 return 0; /* error was already reported */
630 if (strbuf_read(&nbuf, async.out, len) < 0) {
631 err = error("read from external filter '%s' failed", cmd);
633 if (close(async.out)) {
634 err = error("read from external filter '%s' failed", cmd);
636 if (finish_async(&async)) {
637 err = error("external filter '%s' failed", cmd);
640 if (!err) {
641 strbuf_swap(dst, &nbuf);
643 strbuf_release(&nbuf);
644 return !err;
647 #define CAP_CLEAN (1u<<0)
648 #define CAP_SMUDGE (1u<<1)
649 #define CAP_DELAY (1u<<2)
651 struct cmd2process {
652 struct subprocess_entry subprocess; /* must be the first member! */
653 unsigned int supported_capabilities;
656 static int subprocess_map_initialized;
657 static struct hashmap subprocess_map;
659 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
661 static int versions[] = {2, 0};
662 static struct subprocess_capability capabilities[] = {
663 { "clean", CAP_CLEAN },
664 { "smudge", CAP_SMUDGE },
665 { "delay", CAP_DELAY },
666 { NULL, 0 }
668 struct cmd2process *entry = (struct cmd2process *)subprocess;
669 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
670 capabilities,
671 &entry->supported_capabilities);
674 static void handle_filter_error(const struct strbuf *filter_status,
675 struct cmd2process *entry,
676 const unsigned int wanted_capability) {
677 if (!strcmp(filter_status->buf, "error"))
678 ; /* The filter signaled a problem with the file. */
679 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
681 * The filter signaled a permanent problem. Don't try to filter
682 * files with the same command for the lifetime of the current
683 * Git process.
685 entry->supported_capabilities &= ~wanted_capability;
686 } else {
688 * Something went wrong with the protocol filter.
689 * Force shutdown and restart if another blob requires filtering.
691 error("external filter '%s' failed", entry->subprocess.cmd);
692 subprocess_stop(&subprocess_map, &entry->subprocess);
693 free(entry);
697 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
698 int fd, struct strbuf *dst, const char *cmd,
699 const unsigned int wanted_capability,
700 struct delayed_checkout *dco)
702 int err;
703 int can_delay = 0;
704 struct cmd2process *entry;
705 struct child_process *process;
706 struct strbuf nbuf = STRBUF_INIT;
707 struct strbuf filter_status = STRBUF_INIT;
708 const char *filter_type;
710 if (!subprocess_map_initialized) {
711 subprocess_map_initialized = 1;
712 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
713 entry = NULL;
714 } else {
715 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
718 fflush(NULL);
720 if (!entry) {
721 entry = xmalloc(sizeof(*entry));
722 entry->supported_capabilities = 0;
724 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
725 free(entry);
726 return 0;
729 process = &entry->subprocess.process;
731 if (!(entry->supported_capabilities & wanted_capability))
732 return 0;
734 if (wanted_capability & CAP_CLEAN)
735 filter_type = "clean";
736 else if (wanted_capability & CAP_SMUDGE)
737 filter_type = "smudge";
738 else
739 die("unexpected filter type");
741 sigchain_push(SIGPIPE, SIG_IGN);
743 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
744 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
745 if (err)
746 goto done;
748 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
749 if (err) {
750 error("path name too long for external filter");
751 goto done;
754 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
755 if (err)
756 goto done;
758 if ((entry->supported_capabilities & CAP_DELAY) &&
759 dco && dco->state == CE_CAN_DELAY) {
760 can_delay = 1;
761 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
762 if (err)
763 goto done;
766 err = packet_flush_gently(process->in);
767 if (err)
768 goto done;
770 if (fd >= 0)
771 err = write_packetized_from_fd(fd, process->in);
772 else
773 err = write_packetized_from_buf(src, len, process->in);
774 if (err)
775 goto done;
777 err = subprocess_read_status(process->out, &filter_status);
778 if (err)
779 goto done;
781 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
782 string_list_insert(&dco->filters, cmd);
783 string_list_insert(&dco->paths, path);
784 } else {
785 /* The filter got the blob and wants to send us a response. */
786 err = strcmp(filter_status.buf, "success");
787 if (err)
788 goto done;
790 err = read_packetized_to_strbuf(process->out, &nbuf) < 0;
791 if (err)
792 goto done;
794 err = subprocess_read_status(process->out, &filter_status);
795 if (err)
796 goto done;
798 err = strcmp(filter_status.buf, "success");
801 done:
802 sigchain_pop(SIGPIPE);
804 if (err)
805 handle_filter_error(&filter_status, entry, wanted_capability);
806 else
807 strbuf_swap(dst, &nbuf);
808 strbuf_release(&nbuf);
809 return !err;
813 int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
815 int err;
816 char *line;
817 struct cmd2process *entry;
818 struct child_process *process;
819 struct strbuf filter_status = STRBUF_INIT;
821 assert(subprocess_map_initialized);
822 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
823 if (!entry) {
824 error("external filter '%s' is not available anymore although "
825 "not all paths have been filtered", cmd);
826 return 0;
828 process = &entry->subprocess.process;
829 sigchain_push(SIGPIPE, SIG_IGN);
831 err = packet_write_fmt_gently(
832 process->in, "command=list_available_blobs\n");
833 if (err)
834 goto done;
836 err = packet_flush_gently(process->in);
837 if (err)
838 goto done;
840 while ((line = packet_read_line(process->out, NULL))) {
841 const char *path;
842 if (skip_prefix(line, "pathname=", &path))
843 string_list_insert(available_paths, xstrdup(path));
844 else
845 ; /* ignore unknown keys */
848 err = subprocess_read_status(process->out, &filter_status);
849 if (err)
850 goto done;
852 err = strcmp(filter_status.buf, "success");
854 done:
855 sigchain_pop(SIGPIPE);
857 if (err)
858 handle_filter_error(&filter_status, entry, 0);
859 return !err;
862 static struct convert_driver {
863 const char *name;
864 struct convert_driver *next;
865 const char *smudge;
866 const char *clean;
867 const char *process;
868 int required;
869 } *user_convert, **user_convert_tail;
871 static int apply_filter(const char *path, const char *src, size_t len,
872 int fd, struct strbuf *dst, struct convert_driver *drv,
873 const unsigned int wanted_capability,
874 struct delayed_checkout *dco)
876 const char *cmd = NULL;
878 if (!drv)
879 return 0;
881 if (!dst)
882 return 1;
884 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
885 cmd = drv->clean;
886 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
887 cmd = drv->smudge;
889 if (cmd && *cmd)
890 return apply_single_file_filter(path, src, len, fd, dst, cmd);
891 else if (drv->process && *drv->process)
892 return apply_multi_file_filter(path, src, len, fd, dst,
893 drv->process, wanted_capability, dco);
895 return 0;
898 static int read_convert_config(const char *var, const char *value, void *cb)
900 const char *key, *name;
901 int namelen;
902 struct convert_driver *drv;
905 * External conversion drivers are configured using
906 * "filter.<name>.variable".
908 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
909 return 0;
910 for (drv = user_convert; drv; drv = drv->next)
911 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
912 break;
913 if (!drv) {
914 drv = xcalloc(1, sizeof(struct convert_driver));
915 drv->name = xmemdupz(name, namelen);
916 *user_convert_tail = drv;
917 user_convert_tail = &(drv->next);
921 * filter.<name>.smudge and filter.<name>.clean specifies
922 * the command line:
924 * command-line
926 * The command-line will not be interpolated in any way.
929 if (!strcmp("smudge", key))
930 return git_config_string(&drv->smudge, var, value);
932 if (!strcmp("clean", key))
933 return git_config_string(&drv->clean, var, value);
935 if (!strcmp("process", key))
936 return git_config_string(&drv->process, var, value);
938 if (!strcmp("required", key)) {
939 drv->required = git_config_bool(var, value);
940 return 0;
943 return 0;
946 static int count_ident(const char *cp, unsigned long size)
949 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
951 int cnt = 0;
952 char ch;
954 while (size) {
955 ch = *cp++;
956 size--;
957 if (ch != '$')
958 continue;
959 if (size < 3)
960 break;
961 if (memcmp("Id", cp, 2))
962 continue;
963 ch = cp[2];
964 cp += 3;
965 size -= 3;
966 if (ch == '$')
967 cnt++; /* $Id$ */
968 if (ch != ':')
969 continue;
972 * "$Id: ... "; scan up to the closing dollar sign and discard.
974 while (size) {
975 ch = *cp++;
976 size--;
977 if (ch == '$') {
978 cnt++;
979 break;
981 if (ch == '\n')
982 break;
985 return cnt;
988 static int ident_to_git(const char *path, const char *src, size_t len,
989 struct strbuf *buf, int ident)
991 char *dst, *dollar;
993 if (!ident || (src && !count_ident(src, len)))
994 return 0;
996 if (!buf)
997 return 1;
999 /* only grow if not in place */
1000 if (strbuf_avail(buf) + buf->len < len)
1001 strbuf_grow(buf, len - buf->len);
1002 dst = buf->buf;
1003 for (;;) {
1004 dollar = memchr(src, '$', len);
1005 if (!dollar)
1006 break;
1007 memmove(dst, src, dollar + 1 - src);
1008 dst += dollar + 1 - src;
1009 len -= dollar + 1 - src;
1010 src = dollar + 1;
1012 if (len > 3 && !memcmp(src, "Id:", 3)) {
1013 dollar = memchr(src + 3, '$', len - 3);
1014 if (!dollar)
1015 break;
1016 if (memchr(src + 3, '\n', dollar - src - 3)) {
1017 /* Line break before the next dollar. */
1018 continue;
1021 memcpy(dst, "Id$", 3);
1022 dst += 3;
1023 len -= dollar + 1 - src;
1024 src = dollar + 1;
1027 memmove(dst, src, len);
1028 strbuf_setlen(buf, dst + len - buf->buf);
1029 return 1;
1032 static int ident_to_worktree(const char *path, const char *src, size_t len,
1033 struct strbuf *buf, int ident)
1035 unsigned char sha1[20];
1036 char *to_free = NULL, *dollar, *spc;
1037 int cnt;
1039 if (!ident)
1040 return 0;
1042 cnt = count_ident(src, len);
1043 if (!cnt)
1044 return 0;
1046 /* are we "faking" in place editing ? */
1047 if (src == buf->buf)
1048 to_free = strbuf_detach(buf, NULL);
1049 hash_sha1_file(src, len, "blob", sha1);
1051 strbuf_grow(buf, len + cnt * 43);
1052 for (;;) {
1053 /* step 1: run to the next '$' */
1054 dollar = memchr(src, '$', len);
1055 if (!dollar)
1056 break;
1057 strbuf_add(buf, src, dollar + 1 - src);
1058 len -= dollar + 1 - src;
1059 src = dollar + 1;
1061 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1062 if (len < 3 || memcmp("Id", src, 2))
1063 continue;
1065 /* step 3: skip over Id$ or Id:xxxxx$ */
1066 if (src[2] == '$') {
1067 src += 3;
1068 len -= 3;
1069 } else if (src[2] == ':') {
1071 * It's possible that an expanded Id has crept its way into the
1072 * repository, we cope with that by stripping the expansion out.
1073 * This is probably not a good idea, since it will cause changes
1074 * on checkout, which won't go away by stash, but let's keep it
1075 * for git-style ids.
1077 dollar = memchr(src + 3, '$', len - 3);
1078 if (!dollar) {
1079 /* incomplete keyword, no more '$', so just quit the loop */
1080 break;
1083 if (memchr(src + 3, '\n', dollar - src - 3)) {
1084 /* Line break before the next dollar. */
1085 continue;
1088 spc = memchr(src + 4, ' ', dollar - src - 4);
1089 if (spc && spc < dollar-1) {
1090 /* There are spaces in unexpected places.
1091 * This is probably an id from some other
1092 * versioning system. Keep it for now.
1094 continue;
1097 len -= dollar + 1 - src;
1098 src = dollar + 1;
1099 } else {
1100 /* it wasn't a "Id$" or "Id:xxxx$" */
1101 continue;
1104 /* step 4: substitute */
1105 strbuf_addstr(buf, "Id: ");
1106 strbuf_add(buf, sha1_to_hex(sha1), 40);
1107 strbuf_addstr(buf, " $");
1109 strbuf_add(buf, src, len);
1111 free(to_free);
1112 return 1;
1115 static const char *git_path_check_encoding(struct attr_check_item *check)
1117 const char *value = check->value;
1119 if (ATTR_UNSET(value) || !strlen(value))
1120 return NULL;
1122 if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
1123 die(_("true/false are no valid working-tree-encodings"));
1126 /* Don't encode to the default encoding */
1127 if (same_encoding(value, default_encoding))
1128 return NULL;
1130 return value;
1133 static enum crlf_action git_path_check_crlf(struct attr_check_item *check)
1135 const char *value = check->value;
1137 if (ATTR_TRUE(value))
1138 return CRLF_TEXT;
1139 else if (ATTR_FALSE(value))
1140 return CRLF_BINARY;
1141 else if (ATTR_UNSET(value))
1143 else if (!strcmp(value, "input"))
1144 return CRLF_TEXT_INPUT;
1145 else if (!strcmp(value, "auto"))
1146 return CRLF_AUTO;
1147 return CRLF_UNDEFINED;
1150 static enum eol git_path_check_eol(struct attr_check_item *check)
1152 const char *value = check->value;
1154 if (ATTR_UNSET(value))
1156 else if (!strcmp(value, "lf"))
1157 return EOL_LF;
1158 else if (!strcmp(value, "crlf"))
1159 return EOL_CRLF;
1160 return EOL_UNSET;
1163 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
1165 const char *value = check->value;
1166 struct convert_driver *drv;
1168 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1169 return NULL;
1170 for (drv = user_convert; drv; drv = drv->next)
1171 if (!strcmp(value, drv->name))
1172 return drv;
1173 return NULL;
1176 static int git_path_check_ident(struct attr_check_item *check)
1178 const char *value = check->value;
1180 return !!ATTR_TRUE(value);
1183 struct conv_attrs {
1184 struct convert_driver *drv;
1185 enum crlf_action attr_action; /* What attr says */
1186 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
1187 int ident;
1188 const char *working_tree_encoding; /* Supported encoding or default encoding if NULL */
1191 static void convert_attrs(struct conv_attrs *ca, const char *path)
1193 static struct attr_check *check;
1195 if (!check) {
1196 check = attr_check_initl("crlf", "ident", "filter",
1197 "eol", "text", "working-tree-encoding",
1198 NULL);
1199 user_convert_tail = &user_convert;
1200 git_config(read_convert_config, NULL);
1203 if (!git_check_attr(path, check)) {
1204 struct attr_check_item *ccheck = check->items;
1205 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1206 if (ca->crlf_action == CRLF_UNDEFINED)
1207 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1208 ca->ident = git_path_check_ident(ccheck + 1);
1209 ca->drv = git_path_check_convert(ccheck + 2);
1210 if (ca->crlf_action != CRLF_BINARY) {
1211 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1212 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1213 ca->crlf_action = CRLF_AUTO_INPUT;
1214 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1215 ca->crlf_action = CRLF_AUTO_CRLF;
1216 else if (eol_attr == EOL_LF)
1217 ca->crlf_action = CRLF_TEXT_INPUT;
1218 else if (eol_attr == EOL_CRLF)
1219 ca->crlf_action = CRLF_TEXT_CRLF;
1221 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
1222 } else {
1223 ca->drv = NULL;
1224 ca->crlf_action = CRLF_UNDEFINED;
1225 ca->ident = 0;
1228 /* Save attr and make a decision for action */
1229 ca->attr_action = ca->crlf_action;
1230 if (ca->crlf_action == CRLF_TEXT)
1231 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1232 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1233 ca->crlf_action = CRLF_BINARY;
1234 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1235 ca->crlf_action = CRLF_AUTO_CRLF;
1236 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1237 ca->crlf_action = CRLF_AUTO_INPUT;
1240 int would_convert_to_git_filter_fd(const char *path)
1242 struct conv_attrs ca;
1244 convert_attrs(&ca, path);
1245 if (!ca.drv)
1246 return 0;
1249 * Apply a filter to an fd only if the filter is required to succeed.
1250 * We must die if the filter fails, because the original data before
1251 * filtering is not available.
1253 if (!ca.drv->required)
1254 return 0;
1256 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL);
1259 const char *get_convert_attr_ascii(const char *path)
1261 struct conv_attrs ca;
1263 convert_attrs(&ca, path);
1264 switch (ca.attr_action) {
1265 case CRLF_UNDEFINED:
1266 return "";
1267 case CRLF_BINARY:
1268 return "-text";
1269 case CRLF_TEXT:
1270 return "text";
1271 case CRLF_TEXT_INPUT:
1272 return "text eol=lf";
1273 case CRLF_TEXT_CRLF:
1274 return "text eol=crlf";
1275 case CRLF_AUTO:
1276 return "text=auto";
1277 case CRLF_AUTO_CRLF:
1278 return "text=auto eol=crlf";
1279 case CRLF_AUTO_INPUT:
1280 return "text=auto eol=lf";
1282 return "";
1285 int convert_to_git(const struct index_state *istate,
1286 const char *path, const char *src, size_t len,
1287 struct strbuf *dst, int conv_flags)
1289 int ret = 0;
1290 struct conv_attrs ca;
1292 convert_attrs(&ca, path);
1294 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL);
1295 if (!ret && ca.drv && ca.drv->required)
1296 die("%s: clean filter '%s' failed", path, ca.drv->name);
1298 if (ret && dst) {
1299 src = dst->buf;
1300 len = dst->len;
1303 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1304 if (ret && dst) {
1305 src = dst->buf;
1306 len = dst->len;
1309 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1310 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
1311 if (ret && dst) {
1312 src = dst->buf;
1313 len = dst->len;
1316 return ret | ident_to_git(path, src, len, dst, ca.ident);
1319 void convert_to_git_filter_fd(const struct index_state *istate,
1320 const char *path, int fd, struct strbuf *dst,
1321 int conv_flags)
1323 struct conv_attrs ca;
1324 convert_attrs(&ca, path);
1326 assert(ca.drv);
1327 assert(ca.drv->clean || ca.drv->process);
1329 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL))
1330 die("%s: clean filter '%s' failed", path, ca.drv->name);
1332 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
1333 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
1334 ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
1337 static int convert_to_working_tree_internal(const char *path, const char *src,
1338 size_t len, struct strbuf *dst,
1339 int normalizing, struct delayed_checkout *dco)
1341 int ret = 0, ret_filter = 0;
1342 struct conv_attrs ca;
1344 convert_attrs(&ca, path);
1346 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
1347 if (ret) {
1348 src = dst->buf;
1349 len = dst->len;
1352 * CRLF conversion can be skipped if normalizing, unless there
1353 * is a smudge or process filter (even if the process filter doesn't
1354 * support smudge). The filters might expect CRLFs.
1356 if ((ca.drv && (ca.drv->smudge || ca.drv->process)) || !normalizing) {
1357 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
1358 if (ret) {
1359 src = dst->buf;
1360 len = dst->len;
1364 ret |= encode_to_worktree(path, src, len, dst, ca.working_tree_encoding);
1365 if (ret) {
1366 src = dst->buf;
1367 len = dst->len;
1370 ret_filter = apply_filter(
1371 path, src, len, -1, dst, ca.drv, CAP_SMUDGE, dco);
1372 if (!ret_filter && ca.drv && ca.drv->required)
1373 die("%s: smudge filter %s failed", path, ca.drv->name);
1375 return ret | ret_filter;
1378 int async_convert_to_working_tree(const char *path, const char *src,
1379 size_t len, struct strbuf *dst,
1380 void *dco)
1382 return convert_to_working_tree_internal(path, src, len, dst, 0, dco);
1385 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
1387 return convert_to_working_tree_internal(path, src, len, dst, 0, NULL);
1390 int renormalize_buffer(const struct index_state *istate, const char *path,
1391 const char *src, size_t len, struct strbuf *dst)
1393 int ret = convert_to_working_tree_internal(path, src, len, dst, 1, NULL);
1394 if (ret) {
1395 src = dst->buf;
1396 len = dst->len;
1398 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
1401 /*****************************************************************
1403 * Streaming conversion support
1405 *****************************************************************/
1407 typedef int (*filter_fn)(struct stream_filter *,
1408 const char *input, size_t *isize_p,
1409 char *output, size_t *osize_p);
1410 typedef void (*free_fn)(struct stream_filter *);
1412 struct stream_filter_vtbl {
1413 filter_fn filter;
1414 free_fn free;
1417 struct stream_filter {
1418 struct stream_filter_vtbl *vtbl;
1421 static int null_filter_fn(struct stream_filter *filter,
1422 const char *input, size_t *isize_p,
1423 char *output, size_t *osize_p)
1425 size_t count;
1427 if (!input)
1428 return 0; /* we do not keep any states */
1429 count = *isize_p;
1430 if (*osize_p < count)
1431 count = *osize_p;
1432 if (count) {
1433 memmove(output, input, count);
1434 *isize_p -= count;
1435 *osize_p -= count;
1437 return 0;
1440 static void null_free_fn(struct stream_filter *filter)
1442 ; /* nothing -- null instances are shared */
1445 static struct stream_filter_vtbl null_vtbl = {
1446 null_filter_fn,
1447 null_free_fn,
1450 static struct stream_filter null_filter_singleton = {
1451 &null_vtbl,
1454 int is_null_stream_filter(struct stream_filter *filter)
1456 return filter == &null_filter_singleton;
1461 * LF-to-CRLF filter
1464 struct lf_to_crlf_filter {
1465 struct stream_filter filter;
1466 unsigned has_held:1;
1467 char held;
1470 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1471 const char *input, size_t *isize_p,
1472 char *output, size_t *osize_p)
1474 size_t count, o = 0;
1475 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1478 * We may be holding onto the CR to see if it is followed by a
1479 * LF, in which case we would need to go to the main loop.
1480 * Otherwise, just emit it to the output stream.
1482 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1483 output[o++] = lf_to_crlf->held;
1484 lf_to_crlf->has_held = 0;
1487 /* We are told to drain */
1488 if (!input) {
1489 *osize_p -= o;
1490 return 0;
1493 count = *isize_p;
1494 if (count || lf_to_crlf->has_held) {
1495 size_t i;
1496 int was_cr = 0;
1498 if (lf_to_crlf->has_held) {
1499 was_cr = 1;
1500 lf_to_crlf->has_held = 0;
1503 for (i = 0; o < *osize_p && i < count; i++) {
1504 char ch = input[i];
1506 if (ch == '\n') {
1507 output[o++] = '\r';
1508 } else if (was_cr) {
1510 * Previous round saw CR and it is not followed
1511 * by a LF; emit the CR before processing the
1512 * current character.
1514 output[o++] = '\r';
1518 * We may have consumed the last output slot,
1519 * in which case we need to break out of this
1520 * loop; hold the current character before
1521 * returning.
1523 if (*osize_p <= o) {
1524 lf_to_crlf->has_held = 1;
1525 lf_to_crlf->held = ch;
1526 continue; /* break but increment i */
1529 if (ch == '\r') {
1530 was_cr = 1;
1531 continue;
1534 was_cr = 0;
1535 output[o++] = ch;
1538 *osize_p -= o;
1539 *isize_p -= i;
1541 if (!lf_to_crlf->has_held && was_cr) {
1542 lf_to_crlf->has_held = 1;
1543 lf_to_crlf->held = '\r';
1546 return 0;
1549 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1551 free(filter);
1554 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1555 lf_to_crlf_filter_fn,
1556 lf_to_crlf_free_fn,
1559 static struct stream_filter *lf_to_crlf_filter(void)
1561 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1563 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1564 return (struct stream_filter *)lf_to_crlf;
1568 * Cascade filter
1570 #define FILTER_BUFFER 1024
1571 struct cascade_filter {
1572 struct stream_filter filter;
1573 struct stream_filter *one;
1574 struct stream_filter *two;
1575 char buf[FILTER_BUFFER];
1576 int end, ptr;
1579 static int cascade_filter_fn(struct stream_filter *filter,
1580 const char *input, size_t *isize_p,
1581 char *output, size_t *osize_p)
1583 struct cascade_filter *cas = (struct cascade_filter *) filter;
1584 size_t filled = 0;
1585 size_t sz = *osize_p;
1586 size_t to_feed, remaining;
1589 * input -- (one) --> buf -- (two) --> output
1591 while (filled < sz) {
1592 remaining = sz - filled;
1594 /* do we already have something to feed two with? */
1595 if (cas->ptr < cas->end) {
1596 to_feed = cas->end - cas->ptr;
1597 if (stream_filter(cas->two,
1598 cas->buf + cas->ptr, &to_feed,
1599 output + filled, &remaining))
1600 return -1;
1601 cas->ptr += (cas->end - cas->ptr) - to_feed;
1602 filled = sz - remaining;
1603 continue;
1606 /* feed one from upstream and have it emit into our buffer */
1607 to_feed = input ? *isize_p : 0;
1608 if (input && !to_feed)
1609 break;
1610 remaining = sizeof(cas->buf);
1611 if (stream_filter(cas->one,
1612 input, &to_feed,
1613 cas->buf, &remaining))
1614 return -1;
1615 cas->end = sizeof(cas->buf) - remaining;
1616 cas->ptr = 0;
1617 if (input) {
1618 size_t fed = *isize_p - to_feed;
1619 *isize_p -= fed;
1620 input += fed;
1623 /* do we know that we drained one completely? */
1624 if (input || cas->end)
1625 continue;
1627 /* tell two to drain; we have nothing more to give it */
1628 to_feed = 0;
1629 remaining = sz - filled;
1630 if (stream_filter(cas->two,
1631 NULL, &to_feed,
1632 output + filled, &remaining))
1633 return -1;
1634 if (remaining == (sz - filled))
1635 break; /* completely drained two */
1636 filled = sz - remaining;
1638 *osize_p -= filled;
1639 return 0;
1642 static void cascade_free_fn(struct stream_filter *filter)
1644 struct cascade_filter *cas = (struct cascade_filter *)filter;
1645 free_stream_filter(cas->one);
1646 free_stream_filter(cas->two);
1647 free(filter);
1650 static struct stream_filter_vtbl cascade_vtbl = {
1651 cascade_filter_fn,
1652 cascade_free_fn,
1655 static struct stream_filter *cascade_filter(struct stream_filter *one,
1656 struct stream_filter *two)
1658 struct cascade_filter *cascade;
1660 if (!one || is_null_stream_filter(one))
1661 return two;
1662 if (!two || is_null_stream_filter(two))
1663 return one;
1665 cascade = xmalloc(sizeof(*cascade));
1666 cascade->one = one;
1667 cascade->two = two;
1668 cascade->end = cascade->ptr = 0;
1669 cascade->filter.vtbl = &cascade_vtbl;
1670 return (struct stream_filter *)cascade;
1674 * ident filter
1676 #define IDENT_DRAINING (-1)
1677 #define IDENT_SKIPPING (-2)
1678 struct ident_filter {
1679 struct stream_filter filter;
1680 struct strbuf left;
1681 int state;
1682 char ident[45]; /* ": x40 $" */
1685 static int is_foreign_ident(const char *str)
1687 int i;
1689 if (!skip_prefix(str, "$Id: ", &str))
1690 return 0;
1691 for (i = 0; str[i]; i++) {
1692 if (isspace(str[i]) && str[i+1] != '$')
1693 return 1;
1695 return 0;
1698 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1700 size_t to_drain = ident->left.len;
1702 if (*osize_p < to_drain)
1703 to_drain = *osize_p;
1704 if (to_drain) {
1705 memcpy(*output_p, ident->left.buf, to_drain);
1706 strbuf_remove(&ident->left, 0, to_drain);
1707 *output_p += to_drain;
1708 *osize_p -= to_drain;
1710 if (!ident->left.len)
1711 ident->state = 0;
1714 static int ident_filter_fn(struct stream_filter *filter,
1715 const char *input, size_t *isize_p,
1716 char *output, size_t *osize_p)
1718 struct ident_filter *ident = (struct ident_filter *)filter;
1719 static const char head[] = "$Id";
1721 if (!input) {
1722 /* drain upon eof */
1723 switch (ident->state) {
1724 default:
1725 strbuf_add(&ident->left, head, ident->state);
1726 /* fallthrough */
1727 case IDENT_SKIPPING:
1728 /* fallthrough */
1729 case IDENT_DRAINING:
1730 ident_drain(ident, &output, osize_p);
1732 return 0;
1735 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1736 int ch;
1738 if (ident->state == IDENT_DRAINING) {
1739 ident_drain(ident, &output, osize_p);
1740 if (!*osize_p)
1741 break;
1742 continue;
1745 ch = *(input++);
1746 (*isize_p)--;
1748 if (ident->state == IDENT_SKIPPING) {
1750 * Skipping until '$' or LF, but keeping them
1751 * in case it is a foreign ident.
1753 strbuf_addch(&ident->left, ch);
1754 if (ch != '\n' && ch != '$')
1755 continue;
1756 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1757 strbuf_setlen(&ident->left, sizeof(head) - 1);
1758 strbuf_addstr(&ident->left, ident->ident);
1760 ident->state = IDENT_DRAINING;
1761 continue;
1764 if (ident->state < sizeof(head) &&
1765 head[ident->state] == ch) {
1766 ident->state++;
1767 continue;
1770 if (ident->state)
1771 strbuf_add(&ident->left, head, ident->state);
1772 if (ident->state == sizeof(head) - 1) {
1773 if (ch != ':' && ch != '$') {
1774 strbuf_addch(&ident->left, ch);
1775 ident->state = 0;
1776 continue;
1779 if (ch == ':') {
1780 strbuf_addch(&ident->left, ch);
1781 ident->state = IDENT_SKIPPING;
1782 } else {
1783 strbuf_addstr(&ident->left, ident->ident);
1784 ident->state = IDENT_DRAINING;
1786 continue;
1789 strbuf_addch(&ident->left, ch);
1790 ident->state = IDENT_DRAINING;
1792 return 0;
1795 static void ident_free_fn(struct stream_filter *filter)
1797 struct ident_filter *ident = (struct ident_filter *)filter;
1798 strbuf_release(&ident->left);
1799 free(filter);
1802 static struct stream_filter_vtbl ident_vtbl = {
1803 ident_filter_fn,
1804 ident_free_fn,
1807 static struct stream_filter *ident_filter(const unsigned char *sha1)
1809 struct ident_filter *ident = xmalloc(sizeof(*ident));
1811 xsnprintf(ident->ident, sizeof(ident->ident),
1812 ": %s $", sha1_to_hex(sha1));
1813 strbuf_init(&ident->left, 0);
1814 ident->filter.vtbl = &ident_vtbl;
1815 ident->state = 0;
1816 return (struct stream_filter *)ident;
1820 * Return an appropriately constructed filter for the path, or NULL if
1821 * the contents cannot be filtered without reading the whole thing
1822 * in-core.
1824 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1825 * large binary blob you would want us not to slurp into the memory!
1827 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1829 struct conv_attrs ca;
1830 struct stream_filter *filter = NULL;
1832 convert_attrs(&ca, path);
1833 if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
1834 return NULL;
1836 if (ca.working_tree_encoding)
1837 return NULL;
1839 if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1840 return NULL;
1842 if (ca.ident)
1843 filter = ident_filter(sha1);
1845 if (output_eol(ca.crlf_action) == EOL_CRLF)
1846 filter = cascade_filter(filter, lf_to_crlf_filter());
1847 else
1848 filter = cascade_filter(filter, &null_filter_singleton);
1850 return filter;
1853 void free_stream_filter(struct stream_filter *filter)
1855 filter->vtbl->free(filter);
1858 int stream_filter(struct stream_filter *filter,
1859 const char *input, size_t *isize_p,
1860 char *output, size_t *osize_p)
1862 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);