The sixteenth batch
[git/gitster.git] / convert.c
blobb5f7cf6306c3c3ef3cfec1a5169acc2b8a0d89a8
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
4 #include "git-compat-util.h"
5 #include "advice.h"
6 #include "config.h"
7 #include "convert.h"
8 #include "copy.h"
9 #include "gettext.h"
10 #include "hex.h"
11 #include "object-file.h"
12 #include "attr.h"
13 #include "run-command.h"
14 #include "quote.h"
15 #include "read-cache-ll.h"
16 #include "sigchain.h"
17 #include "pkt-line.h"
18 #include "sub-process.h"
19 #include "trace.h"
20 #include "utf8.h"
21 #include "merge-ll.h"
24 * convert.c - convert a file when checking it out and checking it in.
26 * This should use the pathname to decide on whether it wants to do some
27 * more interesting conversions (automatic gzip/unzip, general format
28 * conversions etc etc), but by default it just does automatic CRLF<->LF
29 * translation when the "text" attribute or "auto_crlf" option is set.
32 /* Stat bits: When BIN is set, the txt bits are unset */
33 #define CONVERT_STAT_BITS_TXT_LF 0x1
34 #define CONVERT_STAT_BITS_TXT_CRLF 0x2
35 #define CONVERT_STAT_BITS_BIN 0x4
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(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(&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(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 convert_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"), (int)crlf_action);
194 return core_eol;
197 static void check_global_conv_flags_eol(const char *path,
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(_("in the working copy of '%s', CRLF will be"
209 " replaced by LF the next time Git touches"
210 " it"), 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(_("in the working copy of '%s', LF will be"
219 " replaced by CRLF the next time Git touches"
220 " it"), path);
224 static int has_crlf_in_index(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(struct text_stat *stats,
248 enum convert_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(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 const char *stripped;
274 /* We only check for UTF here as UTF?? can be an alias for UTF-?? */
275 if (skip_iprefix(enc, "UTF", &stripped)) {
276 skip_prefix(stripped, "-", &stripped);
279 * Check for detectable errors in UTF encodings
281 if (has_prohibited_utf_bom(enc, data, len)) {
282 const char *error_msg = _(
283 "BOM is prohibited in '%s' if encoded as %s");
285 * This advice is shown for UTF-??BE and UTF-??LE encodings.
286 * We cut off the last two characters of the encoding name
287 * to generate the encoding name suitable for BOMs.
289 const char *advise_msg = _(
290 "The file '%s' contains a byte order "
291 "mark (BOM). Please use UTF-%.*s as "
292 "working-tree-encoding.");
293 int stripped_len = strlen(stripped) - strlen("BE");
294 advise(advise_msg, path, stripped_len, stripped);
295 if (die_on_error)
296 die(error_msg, path, enc);
297 else {
298 return error(error_msg, path, enc);
301 } else if (is_missing_required_utf_bom(enc, data, len)) {
302 const char *error_msg = _(
303 "BOM is required in '%s' if encoded as %s");
304 const char *advise_msg = _(
305 "The file '%s' is missing a byte order "
306 "mark (BOM). Please use UTF-%sBE or UTF-%sLE "
307 "(depending on the byte order) as "
308 "working-tree-encoding.");
309 advise(advise_msg, path, stripped, stripped);
310 if (die_on_error)
311 die(error_msg, path, enc);
312 else {
313 return error(error_msg, path, enc);
318 return 0;
321 static void trace_encoding(const char *context, const char *path,
322 const char *encoding, const char *buf, size_t len)
324 static struct trace_key coe = TRACE_KEY_INIT(WORKING_TREE_ENCODING);
325 struct strbuf trace = STRBUF_INIT;
326 int i;
328 if (!trace_want(&coe))
329 return;
331 strbuf_addf(&trace, "%s (%s, considered %s):\n", context, path, encoding);
332 for (i = 0; i < len && buf; ++i) {
333 strbuf_addf(
334 &trace, "| \033[2m%2i:\033[0m %2x \033[2m%c\033[0m%c",
336 (unsigned char) buf[i],
337 (buf[i] > 32 && buf[i] < 127 ? buf[i] : ' '),
338 ((i+1) % 8 && (i+1) < len ? ' ' : '\n')
341 strbuf_addchars(&trace, '\n', 1);
343 trace_strbuf(&coe, &trace);
344 strbuf_release(&trace);
347 static int check_roundtrip(const char *enc_name)
350 * check_roundtrip_encoding contains a string of comma and/or
351 * space separated encodings (eg. "UTF-16, ASCII, CP1125").
352 * Search for the given encoding in that string.
354 const char *encoding = check_roundtrip_encoding ?
355 check_roundtrip_encoding : "SHIFT-JIS";
356 const char *found = strcasestr(encoding, enc_name);
357 const char *next;
358 int len;
359 if (!found)
360 return 0;
361 next = found + strlen(enc_name);
362 len = strlen(encoding);
363 return (found && (
365 * Check that the found encoding is at the beginning of
366 * encoding or that it is prefixed with a space or
367 * comma.
369 found == encoding || (
370 (isspace(found[-1]) || found[-1] == ',')
372 ) && (
374 * Check that the found encoding is at the end of
375 * encoding or that it is suffixed with a space
376 * or comma.
378 next == encoding + len || (
379 next < encoding + len &&
380 (isspace(next[0]) || next[0] == ',')
385 static const char *default_encoding = "UTF-8";
387 static int encode_to_git(const char *path, const char *src, size_t src_len,
388 struct strbuf *buf, const char *enc, int conv_flags)
390 char *dst;
391 size_t dst_len;
392 int die_on_error = conv_flags & CONV_WRITE_OBJECT;
395 * No encoding is specified or there is nothing to encode.
396 * Tell the caller that the content was not modified.
398 if (!enc || (src && !src_len))
399 return 0;
402 * Looks like we got called from "would_convert_to_git()".
403 * This means Git wants to know if it would encode (= modify!)
404 * the content. Let's answer with "yes", since an encoding was
405 * specified.
407 if (!buf && !src)
408 return 1;
410 if (validate_encoding(path, enc, src, src_len, die_on_error))
411 return 0;
413 trace_encoding("source", path, enc, src, src_len);
414 dst = reencode_string_len(src, src_len, default_encoding, enc,
415 &dst_len);
416 if (!dst) {
418 * We could add the blob "as-is" to Git. However, on checkout
419 * we would try to re-encode to the original encoding. This
420 * would fail and we would leave the user with a messed-up
421 * working tree. Let's try to avoid this by screaming loud.
423 const char* msg = _("failed to encode '%s' from %s to %s");
424 if (die_on_error)
425 die(msg, path, enc, default_encoding);
426 else {
427 error(msg, path, enc, default_encoding);
428 return 0;
431 trace_encoding("destination", path, default_encoding, dst, dst_len);
434 * UTF supports lossless conversion round tripping [1] and conversions
435 * between UTF and other encodings are mostly round trip safe as
436 * Unicode aims to be a superset of all other character encodings.
437 * However, certain encodings (e.g. SHIFT-JIS) are known to have round
438 * trip issues [2]. Check the round trip conversion for all encodings
439 * listed in core.checkRoundtripEncoding.
441 * The round trip check is only performed if content is written to Git.
442 * This ensures that no information is lost during conversion to/from
443 * the internal UTF-8 representation.
445 * Please note, the code below is not tested because I was not able to
446 * generate a faulty round trip without an iconv error. Iconv errors
447 * are already caught above.
449 * [1] http://unicode.org/faq/utf_bom.html#gen2
450 * [2] https://support.microsoft.com/en-us/help/170559/prb-conversion-problem-between-shift-jis-and-unicode
452 if (die_on_error && check_roundtrip(enc)) {
453 char *re_src;
454 size_t re_src_len;
456 re_src = reencode_string_len(dst, dst_len,
457 enc, default_encoding,
458 &re_src_len);
460 trace_printf("Checking roundtrip encoding for %s...\n", enc);
461 trace_encoding("reencoded source", path, enc,
462 re_src, re_src_len);
464 if (!re_src || src_len != re_src_len ||
465 memcmp(src, re_src, src_len)) {
466 const char* msg = _("encoding '%s' from %s to %s and "
467 "back is not the same");
468 die(msg, path, enc, default_encoding);
471 free(re_src);
474 strbuf_attach(buf, dst, dst_len, dst_len + 1);
475 return 1;
478 static int encode_to_worktree(const char *path, const char *src, size_t src_len,
479 struct strbuf *buf, const char *enc)
481 char *dst;
482 size_t dst_len;
485 * No encoding is specified or there is nothing to encode.
486 * Tell the caller that the content was not modified.
488 if (!enc || (src && !src_len))
489 return 0;
491 dst = reencode_string_len(src, src_len, enc, default_encoding,
492 &dst_len);
493 if (!dst) {
494 error(_("failed to encode '%s' from %s to %s"),
495 path, default_encoding, enc);
496 return 0;
499 strbuf_attach(buf, dst, dst_len, dst_len + 1);
500 return 1;
503 static int crlf_to_git(struct index_state *istate,
504 const char *path, const char *src, size_t len,
505 struct strbuf *buf,
506 enum convert_crlf_action crlf_action, int conv_flags)
508 struct text_stat stats;
509 char *dst;
510 int convert_crlf_into_lf;
512 if (crlf_action == CRLF_BINARY ||
513 (src && !len))
514 return 0;
517 * If we are doing a dry-run and have no source buffer, there is
518 * nothing to analyze; we must assume we would convert.
520 if (!buf && !src)
521 return 1;
523 gather_stats(src, len, &stats);
524 /* Optimization: No CRLF? Nothing to convert, regardless. */
525 convert_crlf_into_lf = !!stats.crlf;
527 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
528 if (convert_is_binary(&stats))
529 return 0;
531 * If the file in the index has any CR in it, do not
532 * convert. This is the new safer autocrlf handling,
533 * unless we want to renormalize in a merge or
534 * cherry-pick.
536 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
537 has_crlf_in_index(istate, path))
538 convert_crlf_into_lf = 0;
540 if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
541 ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
542 struct text_stat new_stats;
543 memcpy(&new_stats, &stats, sizeof(new_stats));
544 /* simulate "git add" */
545 if (convert_crlf_into_lf) {
546 new_stats.lonelf += new_stats.crlf;
547 new_stats.crlf = 0;
549 /* simulate "git checkout" */
550 if (will_convert_lf_to_crlf(&new_stats, crlf_action)) {
551 new_stats.crlf += new_stats.lonelf;
552 new_stats.lonelf = 0;
554 check_global_conv_flags_eol(path, &stats, &new_stats, conv_flags);
556 if (!convert_crlf_into_lf)
557 return 0;
560 * At this point all of our source analysis is done, and we are sure we
561 * would convert. If we are in dry-run mode, we can give an answer.
563 if (!buf)
564 return 1;
566 /* only grow if not in place */
567 if (strbuf_avail(buf) + buf->len < len)
568 strbuf_grow(buf, len - buf->len);
569 dst = buf->buf;
570 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
572 * If we guessed, we already know we rejected a file with
573 * lone CR, and we can strip a CR without looking at what
574 * follow it.
576 do {
577 unsigned char c = *src++;
578 if (c != '\r')
579 *dst++ = c;
580 } while (--len);
581 } else {
582 do {
583 unsigned char c = *src++;
584 if (! (c == '\r' && (1 < len && *src == '\n')))
585 *dst++ = c;
586 } while (--len);
588 strbuf_setlen(buf, dst - buf->buf);
589 return 1;
592 static int crlf_to_worktree(const char *src, size_t len, struct strbuf *buf,
593 enum convert_crlf_action crlf_action)
595 char *to_free = NULL;
596 struct text_stat stats;
598 if (!len || output_eol(crlf_action) != EOL_CRLF)
599 return 0;
601 gather_stats(src, len, &stats);
602 if (!will_convert_lf_to_crlf(&stats, crlf_action))
603 return 0;
605 /* are we "faking" in place editing ? */
606 if (src == buf->buf)
607 to_free = strbuf_detach(buf, NULL);
609 strbuf_grow(buf, len + stats.lonelf);
610 for (;;) {
611 const char *nl = memchr(src, '\n', len);
612 if (!nl)
613 break;
614 if (nl > src && nl[-1] == '\r') {
615 strbuf_add(buf, src, nl + 1 - src);
616 } else {
617 strbuf_add(buf, src, nl - src);
618 strbuf_addstr(buf, "\r\n");
620 len -= nl + 1 - src;
621 src = nl + 1;
623 strbuf_add(buf, src, len);
625 free(to_free);
626 return 1;
629 struct filter_params {
630 const char *src;
631 size_t size;
632 int fd;
633 const char *cmd;
634 const char *path;
637 static int filter_buffer_or_fd(int in UNUSED, int out, void *data)
640 * Spawn cmd and feed the buffer contents through its stdin.
642 struct child_process child_process = CHILD_PROCESS_INIT;
643 struct filter_params *params = (struct filter_params *)data;
644 const char *format = params->cmd;
645 int write_err, status;
647 /* apply % substitution to cmd */
648 struct strbuf cmd = STRBUF_INIT;
650 /* expand all %f with the quoted path; quote to preserve space, etc. */
651 while (strbuf_expand_step(&cmd, &format)) {
652 if (skip_prefix(format, "%", &format))
653 strbuf_addch(&cmd, '%');
654 else if (skip_prefix(format, "f", &format))
655 sq_quote_buf(&cmd, params->path);
656 else
657 strbuf_addch(&cmd, '%');
660 strvec_push(&child_process.args, cmd.buf);
661 child_process.use_shell = 1;
662 child_process.in = -1;
663 child_process.out = out;
665 if (start_command(&child_process)) {
666 strbuf_release(&cmd);
667 return error(_("cannot fork to run external filter '%s'"),
668 params->cmd);
671 sigchain_push(SIGPIPE, SIG_IGN);
673 if (params->src) {
674 write_err = (write_in_full(child_process.in,
675 params->src, params->size) < 0);
676 if (errno == EPIPE)
677 write_err = 0;
678 } else {
679 write_err = copy_fd(params->fd, child_process.in);
680 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
681 write_err = 0;
684 if (close(child_process.in))
685 write_err = 1;
686 if (write_err)
687 error(_("cannot feed the input to external filter '%s'"),
688 params->cmd);
690 sigchain_pop(SIGPIPE);
692 status = finish_command(&child_process);
693 if (status)
694 error(_("external filter '%s' failed %d"), params->cmd, status);
696 strbuf_release(&cmd);
697 return (write_err || status);
700 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
701 struct strbuf *dst, const char *cmd)
704 * Create a pipeline to have the command filter the buffer's
705 * contents.
707 * (child --> cmd) --> us
709 int err = 0;
710 struct strbuf nbuf = STRBUF_INIT;
711 struct async async;
712 struct filter_params params;
714 memset(&async, 0, sizeof(async));
715 async.proc = filter_buffer_or_fd;
716 async.data = &params;
717 async.out = -1;
718 params.src = src;
719 params.size = len;
720 params.fd = fd;
721 params.cmd = cmd;
722 params.path = path;
724 fflush(NULL);
725 if (start_async(&async))
726 return 0; /* error was already reported */
728 if (strbuf_read(&nbuf, async.out, 0) < 0) {
729 err = error(_("read from external filter '%s' failed"), cmd);
731 if (close(async.out)) {
732 err = error(_("read from external filter '%s' failed"), cmd);
734 if (finish_async(&async)) {
735 err = error(_("external filter '%s' failed"), cmd);
738 if (!err) {
739 strbuf_swap(dst, &nbuf);
741 strbuf_release(&nbuf);
742 return !err;
745 #define CAP_CLEAN (1u<<0)
746 #define CAP_SMUDGE (1u<<1)
747 #define CAP_DELAY (1u<<2)
749 struct cmd2process {
750 struct subprocess_entry subprocess; /* must be the first member! */
751 unsigned int supported_capabilities;
754 static int subprocess_map_initialized;
755 static struct hashmap subprocess_map;
757 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
759 static int versions[] = {2, 0};
760 static struct subprocess_capability capabilities[] = {
761 { "clean", CAP_CLEAN },
762 { "smudge", CAP_SMUDGE },
763 { "delay", CAP_DELAY },
764 { NULL, 0 }
766 struct cmd2process *entry = (struct cmd2process *)subprocess;
767 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
768 capabilities,
769 &entry->supported_capabilities);
772 static void handle_filter_error(const struct strbuf *filter_status,
773 struct cmd2process *entry,
774 const unsigned int wanted_capability)
776 if (!strcmp(filter_status->buf, "error"))
777 ; /* The filter signaled a problem with the file. */
778 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
780 * The filter signaled a permanent problem. Don't try to filter
781 * files with the same command for the lifetime of the current
782 * Git process.
784 entry->supported_capabilities &= ~wanted_capability;
785 } else {
787 * Something went wrong with the protocol filter.
788 * Force shutdown and restart if another blob requires filtering.
790 error(_("external filter '%s' failed"), entry->subprocess.cmd);
791 subprocess_stop(&subprocess_map, &entry->subprocess);
792 free(entry);
796 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
797 int fd, struct strbuf *dst, const char *cmd,
798 const unsigned int wanted_capability,
799 const struct checkout_metadata *meta,
800 struct delayed_checkout *dco)
802 int err;
803 int can_delay = 0;
804 struct cmd2process *entry;
805 struct child_process *process;
806 struct strbuf nbuf = STRBUF_INIT;
807 struct strbuf filter_status = STRBUF_INIT;
808 const char *filter_type;
810 if (!subprocess_map_initialized) {
811 subprocess_map_initialized = 1;
812 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
813 entry = NULL;
814 } else {
815 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
818 fflush(NULL);
820 if (!entry) {
821 entry = xmalloc(sizeof(*entry));
822 entry->supported_capabilities = 0;
824 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
825 free(entry);
826 return 0;
829 process = &entry->subprocess.process;
831 if (!(entry->supported_capabilities & wanted_capability))
832 return 0;
834 if (wanted_capability & CAP_CLEAN)
835 filter_type = "clean";
836 else if (wanted_capability & CAP_SMUDGE)
837 filter_type = "smudge";
838 else
839 die(_("unexpected filter type"));
841 sigchain_push(SIGPIPE, SIG_IGN);
843 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
844 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
845 if (err)
846 goto done;
848 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
849 if (err) {
850 error(_("path name too long for external filter"));
851 goto done;
854 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
855 if (err)
856 goto done;
858 if (meta && meta->refname) {
859 err = packet_write_fmt_gently(process->in, "ref=%s\n", meta->refname);
860 if (err)
861 goto done;
864 if (meta && !is_null_oid(&meta->treeish)) {
865 err = packet_write_fmt_gently(process->in, "treeish=%s\n", oid_to_hex(&meta->treeish));
866 if (err)
867 goto done;
870 if (meta && !is_null_oid(&meta->blob)) {
871 err = packet_write_fmt_gently(process->in, "blob=%s\n", oid_to_hex(&meta->blob));
872 if (err)
873 goto done;
876 if ((entry->supported_capabilities & CAP_DELAY) &&
877 dco && dco->state == CE_CAN_DELAY) {
878 can_delay = 1;
879 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
880 if (err)
881 goto done;
884 err = packet_flush_gently(process->in);
885 if (err)
886 goto done;
888 if (fd >= 0)
889 err = write_packetized_from_fd_no_flush(fd, process->in);
890 else
891 err = write_packetized_from_buf_no_flush(src, len, process->in);
892 if (err)
893 goto done;
895 err = packet_flush_gently(process->in);
896 if (err)
897 goto done;
899 err = subprocess_read_status(process->out, &filter_status);
900 if (err)
901 goto done;
903 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
904 string_list_insert(&dco->filters, cmd);
905 string_list_insert(&dco->paths, path);
906 } else {
907 /* The filter got the blob and wants to send us a response. */
908 err = strcmp(filter_status.buf, "success");
909 if (err)
910 goto done;
912 err = read_packetized_to_strbuf(process->out, &nbuf,
913 PACKET_READ_GENTLE_ON_EOF) < 0;
914 if (err)
915 goto done;
917 err = subprocess_read_status(process->out, &filter_status);
918 if (err)
919 goto done;
921 err = strcmp(filter_status.buf, "success");
924 done:
925 sigchain_pop(SIGPIPE);
927 if (err)
928 handle_filter_error(&filter_status, entry, wanted_capability);
929 else
930 strbuf_swap(dst, &nbuf);
931 strbuf_release(&nbuf);
932 strbuf_release(&filter_status);
933 return !err;
937 int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
939 int err;
940 char *line;
941 struct cmd2process *entry;
942 struct child_process *process;
943 struct strbuf filter_status = STRBUF_INIT;
945 assert(subprocess_map_initialized);
946 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
947 if (!entry) {
948 error(_("external filter '%s' is not available anymore although "
949 "not all paths have been filtered"), cmd);
950 return 0;
952 process = &entry->subprocess.process;
953 sigchain_push(SIGPIPE, SIG_IGN);
955 err = packet_write_fmt_gently(
956 process->in, "command=list_available_blobs\n");
957 if (err)
958 goto done;
960 err = packet_flush_gently(process->in);
961 if (err)
962 goto done;
964 while ((line = packet_read_line(process->out, NULL))) {
965 const char *path;
966 if (skip_prefix(line, "pathname=", &path))
967 string_list_insert(available_paths, path);
968 else
969 ; /* ignore unknown keys */
972 err = subprocess_read_status(process->out, &filter_status);
973 if (err)
974 goto done;
976 err = strcmp(filter_status.buf, "success");
978 done:
979 sigchain_pop(SIGPIPE);
981 if (err)
982 handle_filter_error(&filter_status, entry, 0);
983 strbuf_release(&filter_status);
984 return !err;
987 static struct convert_driver {
988 const char *name;
989 struct convert_driver *next;
990 char *smudge;
991 char *clean;
992 char *process;
993 int required;
994 } *user_convert, **user_convert_tail;
996 static int apply_filter(const char *path, const char *src, size_t len,
997 int fd, struct strbuf *dst, struct convert_driver *drv,
998 const unsigned int wanted_capability,
999 const struct checkout_metadata *meta,
1000 struct delayed_checkout *dco)
1002 const char *cmd = NULL;
1004 if (!drv)
1005 return 0;
1007 if (!dst)
1008 return 1;
1010 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
1011 cmd = drv->clean;
1012 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
1013 cmd = drv->smudge;
1015 if (cmd && *cmd)
1016 return apply_single_file_filter(path, src, len, fd, dst, cmd);
1017 else if (drv->process && *drv->process)
1018 return apply_multi_file_filter(path, src, len, fd, dst,
1019 drv->process, wanted_capability, meta, dco);
1021 return 0;
1024 static int read_convert_config(const char *var, const char *value,
1025 const struct config_context *ctx UNUSED,
1026 void *cb UNUSED)
1028 const char *key, *name;
1029 size_t namelen;
1030 struct convert_driver *drv;
1033 * External conversion drivers are configured using
1034 * "filter.<name>.variable".
1036 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
1037 return 0;
1038 for (drv = user_convert; drv; drv = drv->next)
1039 if (!xstrncmpz(drv->name, name, namelen))
1040 break;
1041 if (!drv) {
1042 CALLOC_ARRAY(drv, 1);
1043 drv->name = xmemdupz(name, namelen);
1044 *user_convert_tail = drv;
1045 user_convert_tail = &(drv->next);
1049 * filter.<name>.smudge and filter.<name>.clean specifies
1050 * the command line:
1052 * command-line
1054 * The command-line will not be interpolated in any way.
1057 if (!strcmp("smudge", key)) {
1058 FREE_AND_NULL(drv->smudge);
1059 return git_config_string(&drv->smudge, var, value);
1062 if (!strcmp("clean", key)) {
1063 FREE_AND_NULL(drv->clean);
1064 return git_config_string(&drv->clean, var, value);
1067 if (!strcmp("process", key)) {
1068 FREE_AND_NULL(drv->process);
1069 return git_config_string(&drv->process, var, value);
1072 if (!strcmp("required", key)) {
1073 drv->required = git_config_bool(var, value);
1074 return 0;
1077 return 0;
1080 static int count_ident(const char *cp, unsigned long size)
1083 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
1085 int cnt = 0;
1086 char ch;
1088 while (size) {
1089 ch = *cp++;
1090 size--;
1091 if (ch != '$')
1092 continue;
1093 if (size < 3)
1094 break;
1095 if (memcmp("Id", cp, 2))
1096 continue;
1097 ch = cp[2];
1098 cp += 3;
1099 size -= 3;
1100 if (ch == '$')
1101 cnt++; /* $Id$ */
1102 if (ch != ':')
1103 continue;
1106 * "$Id: ... "; scan up to the closing dollar sign and discard.
1108 while (size) {
1109 ch = *cp++;
1110 size--;
1111 if (ch == '$') {
1112 cnt++;
1113 break;
1115 if (ch == '\n')
1116 break;
1119 return cnt;
1122 static int ident_to_git(const char *src, size_t len,
1123 struct strbuf *buf, int ident)
1125 char *dst, *dollar;
1127 if (!ident || (src && !count_ident(src, len)))
1128 return 0;
1130 if (!buf)
1131 return 1;
1133 /* only grow if not in place */
1134 if (strbuf_avail(buf) + buf->len < len)
1135 strbuf_grow(buf, len - buf->len);
1136 dst = buf->buf;
1137 for (;;) {
1138 dollar = memchr(src, '$', len);
1139 if (!dollar)
1140 break;
1141 memmove(dst, src, dollar + 1 - src);
1142 dst += dollar + 1 - src;
1143 len -= dollar + 1 - src;
1144 src = dollar + 1;
1146 if (len > 3 && !memcmp(src, "Id:", 3)) {
1147 dollar = memchr(src + 3, '$', len - 3);
1148 if (!dollar)
1149 break;
1150 if (memchr(src + 3, '\n', dollar - src - 3)) {
1151 /* Line break before the next dollar. */
1152 continue;
1155 memcpy(dst, "Id$", 3);
1156 dst += 3;
1157 len -= dollar + 1 - src;
1158 src = dollar + 1;
1161 memmove(dst, src, len);
1162 strbuf_setlen(buf, dst + len - buf->buf);
1163 return 1;
1166 static int ident_to_worktree(const char *src, size_t len,
1167 struct strbuf *buf, int ident)
1169 struct object_id oid;
1170 char *to_free = NULL, *dollar, *spc;
1171 int cnt;
1173 if (!ident)
1174 return 0;
1176 cnt = count_ident(src, len);
1177 if (!cnt)
1178 return 0;
1180 /* are we "faking" in place editing ? */
1181 if (src == buf->buf)
1182 to_free = strbuf_detach(buf, NULL);
1183 hash_object_file(the_hash_algo, src, len, OBJ_BLOB, &oid);
1185 strbuf_grow(buf, len + cnt * (the_hash_algo->hexsz + 3));
1186 for (;;) {
1187 /* step 1: run to the next '$' */
1188 dollar = memchr(src, '$', len);
1189 if (!dollar)
1190 break;
1191 strbuf_add(buf, src, dollar + 1 - src);
1192 len -= dollar + 1 - src;
1193 src = dollar + 1;
1195 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1196 if (len < 3 || memcmp("Id", src, 2))
1197 continue;
1199 /* step 3: skip over Id$ or Id:xxxxx$ */
1200 if (src[2] == '$') {
1201 src += 3;
1202 len -= 3;
1203 } else if (src[2] == ':') {
1205 * It's possible that an expanded Id has crept its way into the
1206 * repository, we cope with that by stripping the expansion out.
1207 * This is probably not a good idea, since it will cause changes
1208 * on checkout, which won't go away by stash, but let's keep it
1209 * for git-style ids.
1211 dollar = memchr(src + 3, '$', len - 3);
1212 if (!dollar) {
1213 /* incomplete keyword, no more '$', so just quit the loop */
1214 break;
1217 if (memchr(src + 3, '\n', dollar - src - 3)) {
1218 /* Line break before the next dollar. */
1219 continue;
1222 spc = memchr(src + 4, ' ', dollar - src - 4);
1223 if (spc && spc < dollar-1) {
1224 /* There are spaces in unexpected places.
1225 * This is probably an id from some other
1226 * versioning system. Keep it for now.
1228 continue;
1231 len -= dollar + 1 - src;
1232 src = dollar + 1;
1233 } else {
1234 /* it wasn't a "Id$" or "Id:xxxx$" */
1235 continue;
1238 /* step 4: substitute */
1239 strbuf_addstr(buf, "Id: ");
1240 strbuf_addstr(buf, oid_to_hex(&oid));
1241 strbuf_addstr(buf, " $");
1243 strbuf_add(buf, src, len);
1245 free(to_free);
1246 return 1;
1249 static const char *git_path_check_encoding(struct attr_check_item *check)
1251 const char *value = check->value;
1253 if (ATTR_UNSET(value) || !strlen(value))
1254 return NULL;
1256 if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
1257 die(_("true/false are no valid working-tree-encodings"));
1260 /* Don't encode to the default encoding */
1261 if (same_encoding(value, default_encoding))
1262 return NULL;
1264 return value;
1267 static enum convert_crlf_action git_path_check_crlf(struct attr_check_item *check)
1269 const char *value = check->value;
1271 if (ATTR_TRUE(value))
1272 return CRLF_TEXT;
1273 else if (ATTR_FALSE(value))
1274 return CRLF_BINARY;
1275 else if (ATTR_UNSET(value))
1277 else if (!strcmp(value, "input"))
1278 return CRLF_TEXT_INPUT;
1279 else if (!strcmp(value, "auto"))
1280 return CRLF_AUTO;
1281 return CRLF_UNDEFINED;
1284 static enum eol git_path_check_eol(struct attr_check_item *check)
1286 const char *value = check->value;
1288 if (ATTR_UNSET(value))
1290 else if (!strcmp(value, "lf"))
1291 return EOL_LF;
1292 else if (!strcmp(value, "crlf"))
1293 return EOL_CRLF;
1294 return EOL_UNSET;
1297 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
1299 const char *value = check->value;
1300 struct convert_driver *drv;
1302 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1303 return NULL;
1304 for (drv = user_convert; drv; drv = drv->next)
1305 if (!strcmp(value, drv->name))
1306 return drv;
1307 return NULL;
1310 static int git_path_check_ident(struct attr_check_item *check)
1312 const char *value = check->value;
1314 return !!ATTR_TRUE(value);
1317 static struct attr_check *check;
1319 void convert_attrs(struct index_state *istate,
1320 struct conv_attrs *ca, const char *path)
1322 struct attr_check_item *ccheck = NULL;
1324 if (!check) {
1325 check = attr_check_initl("crlf", "ident", "filter",
1326 "eol", "text", "working-tree-encoding",
1327 NULL);
1328 user_convert_tail = &user_convert;
1329 git_config(read_convert_config, NULL);
1332 git_check_attr(istate, path, check);
1333 ccheck = check->items;
1334 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1335 if (ca->crlf_action == CRLF_UNDEFINED)
1336 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1337 ca->ident = git_path_check_ident(ccheck + 1);
1338 ca->drv = git_path_check_convert(ccheck + 2);
1339 if (ca->crlf_action != CRLF_BINARY) {
1340 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1341 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1342 ca->crlf_action = CRLF_AUTO_INPUT;
1343 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1344 ca->crlf_action = CRLF_AUTO_CRLF;
1345 else if (eol_attr == EOL_LF)
1346 ca->crlf_action = CRLF_TEXT_INPUT;
1347 else if (eol_attr == EOL_CRLF)
1348 ca->crlf_action = CRLF_TEXT_CRLF;
1350 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
1352 /* Save attr and make a decision for action */
1353 ca->attr_action = ca->crlf_action;
1354 if (ca->crlf_action == CRLF_TEXT)
1355 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1356 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1357 ca->crlf_action = CRLF_BINARY;
1358 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1359 ca->crlf_action = CRLF_AUTO_CRLF;
1360 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1361 ca->crlf_action = CRLF_AUTO_INPUT;
1364 void reset_parsed_attributes(void)
1366 struct convert_driver *drv, *next;
1368 attr_check_free(check);
1369 check = NULL;
1370 reset_merge_attributes();
1372 for (drv = user_convert; drv; drv = next) {
1373 next = drv->next;
1374 free((void *)drv->name);
1375 free((void *)drv->smudge);
1376 free((void *)drv->clean);
1377 free((void *)drv->process);
1378 free(drv);
1380 user_convert = NULL;
1381 user_convert_tail = NULL;
1384 int would_convert_to_git_filter_fd(struct index_state *istate, const char *path)
1386 struct conv_attrs ca;
1388 convert_attrs(istate, &ca, path);
1389 if (!ca.drv)
1390 return 0;
1393 * Apply a filter to an fd only if the filter is required to succeed.
1394 * We must die if the filter fails, because the original data before
1395 * filtering is not available.
1397 if (!ca.drv->required)
1398 return 0;
1400 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL, NULL);
1403 const char *get_convert_attr_ascii(struct index_state *istate, const char *path)
1405 struct conv_attrs ca;
1407 convert_attrs(istate, &ca, path);
1408 switch (ca.attr_action) {
1409 case CRLF_UNDEFINED:
1410 return "";
1411 case CRLF_BINARY:
1412 return "-text";
1413 case CRLF_TEXT:
1414 return "text";
1415 case CRLF_TEXT_INPUT:
1416 return "text eol=lf";
1417 case CRLF_TEXT_CRLF:
1418 return "text eol=crlf";
1419 case CRLF_AUTO:
1420 return "text=auto";
1421 case CRLF_AUTO_CRLF:
1422 return "text=auto eol=crlf";
1423 case CRLF_AUTO_INPUT:
1424 return "text=auto eol=lf";
1426 return "";
1429 int convert_to_git(struct index_state *istate,
1430 const char *path, const char *src, size_t len,
1431 struct strbuf *dst, int conv_flags)
1433 int ret = 0;
1434 struct conv_attrs ca;
1436 convert_attrs(istate, &ca, path);
1438 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL, NULL);
1439 if (!ret && ca.drv && ca.drv->required)
1440 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
1442 if (ret && dst) {
1443 src = dst->buf;
1444 len = dst->len;
1447 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1448 if (ret && dst) {
1449 src = dst->buf;
1450 len = dst->len;
1453 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1454 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
1455 if (ret && dst) {
1456 src = dst->buf;
1457 len = dst->len;
1460 return ret | ident_to_git(src, len, dst, ca.ident);
1463 void convert_to_git_filter_fd(struct index_state *istate,
1464 const char *path, int fd, struct strbuf *dst,
1465 int conv_flags)
1467 struct conv_attrs ca;
1468 convert_attrs(istate, &ca, path);
1470 assert(ca.drv);
1472 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL, NULL))
1473 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
1475 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
1476 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
1477 ident_to_git(dst->buf, dst->len, dst, ca.ident);
1480 static int convert_to_working_tree_ca_internal(const struct conv_attrs *ca,
1481 const char *path, const char *src,
1482 size_t len, struct strbuf *dst,
1483 int normalizing,
1484 const struct checkout_metadata *meta,
1485 struct delayed_checkout *dco)
1487 int ret = 0, ret_filter = 0;
1489 ret |= ident_to_worktree(src, len, dst, ca->ident);
1490 if (ret) {
1491 src = dst->buf;
1492 len = dst->len;
1495 * CRLF conversion can be skipped if normalizing, unless there
1496 * is a smudge or process filter (even if the process filter doesn't
1497 * support smudge). The filters might expect CRLFs.
1499 if ((ca->drv && (ca->drv->smudge || ca->drv->process)) || !normalizing) {
1500 ret |= crlf_to_worktree(src, len, dst, ca->crlf_action);
1501 if (ret) {
1502 src = dst->buf;
1503 len = dst->len;
1507 ret |= encode_to_worktree(path, src, len, dst, ca->working_tree_encoding);
1508 if (ret) {
1509 src = dst->buf;
1510 len = dst->len;
1513 ret_filter = apply_filter(
1514 path, src, len, -1, dst, ca->drv, CAP_SMUDGE, meta, dco);
1515 if (!ret_filter && ca->drv && ca->drv->required)
1516 die(_("%s: smudge filter %s failed"), path, ca->drv->name);
1518 return ret | ret_filter;
1521 int async_convert_to_working_tree_ca(const struct conv_attrs *ca,
1522 const char *path, const char *src,
1523 size_t len, struct strbuf *dst,
1524 const struct checkout_metadata *meta,
1525 void *dco)
1527 return convert_to_working_tree_ca_internal(ca, path, src, len, dst, 0,
1528 meta, dco);
1531 int convert_to_working_tree_ca(const struct conv_attrs *ca,
1532 const char *path, const char *src,
1533 size_t len, struct strbuf *dst,
1534 const struct checkout_metadata *meta)
1536 return convert_to_working_tree_ca_internal(ca, path, src, len, dst, 0,
1537 meta, NULL);
1540 int renormalize_buffer(struct index_state *istate, const char *path,
1541 const char *src, size_t len, struct strbuf *dst)
1543 struct conv_attrs ca;
1544 int ret;
1546 convert_attrs(istate, &ca, path);
1547 ret = convert_to_working_tree_ca_internal(&ca, path, src, len, dst, 1,
1548 NULL, NULL);
1549 if (ret) {
1550 src = dst->buf;
1551 len = dst->len;
1553 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
1556 /*****************************************************************
1558 * Streaming conversion support
1560 *****************************************************************/
1562 typedef int (*filter_fn)(struct stream_filter *,
1563 const char *input, size_t *isize_p,
1564 char *output, size_t *osize_p);
1565 typedef void (*free_fn)(struct stream_filter *);
1567 struct stream_filter_vtbl {
1568 filter_fn filter;
1569 free_fn free;
1572 struct stream_filter {
1573 struct stream_filter_vtbl *vtbl;
1576 static int null_filter_fn(struct stream_filter *filter UNUSED,
1577 const char *input, size_t *isize_p,
1578 char *output, size_t *osize_p)
1580 size_t count;
1582 if (!input)
1583 return 0; /* we do not keep any states */
1584 count = *isize_p;
1585 if (*osize_p < count)
1586 count = *osize_p;
1587 if (count) {
1588 memmove(output, input, count);
1589 *isize_p -= count;
1590 *osize_p -= count;
1592 return 0;
1595 static void null_free_fn(struct stream_filter *filter UNUSED)
1597 ; /* nothing -- null instances are shared */
1600 static struct stream_filter_vtbl null_vtbl = {
1601 .filter = null_filter_fn,
1602 .free = null_free_fn,
1605 static struct stream_filter null_filter_singleton = {
1606 .vtbl = &null_vtbl,
1609 int is_null_stream_filter(struct stream_filter *filter)
1611 return filter == &null_filter_singleton;
1616 * LF-to-CRLF filter
1619 struct lf_to_crlf_filter {
1620 struct stream_filter filter;
1621 unsigned has_held:1;
1622 char held;
1625 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1626 const char *input, size_t *isize_p,
1627 char *output, size_t *osize_p)
1629 size_t count, o = 0;
1630 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1633 * We may be holding onto the CR to see if it is followed by a
1634 * LF, in which case we would need to go to the main loop.
1635 * Otherwise, just emit it to the output stream.
1637 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1638 output[o++] = lf_to_crlf->held;
1639 lf_to_crlf->has_held = 0;
1642 /* We are told to drain */
1643 if (!input) {
1644 *osize_p -= o;
1645 return 0;
1648 count = *isize_p;
1649 if (count || lf_to_crlf->has_held) {
1650 size_t i;
1651 int was_cr = 0;
1653 if (lf_to_crlf->has_held) {
1654 was_cr = 1;
1655 lf_to_crlf->has_held = 0;
1658 for (i = 0; o < *osize_p && i < count; i++) {
1659 char ch = input[i];
1661 if (ch == '\n') {
1662 output[o++] = '\r';
1663 } else if (was_cr) {
1665 * Previous round saw CR and it is not followed
1666 * by a LF; emit the CR before processing the
1667 * current character.
1669 output[o++] = '\r';
1673 * We may have consumed the last output slot,
1674 * in which case we need to break out of this
1675 * loop; hold the current character before
1676 * returning.
1678 if (*osize_p <= o) {
1679 lf_to_crlf->has_held = 1;
1680 lf_to_crlf->held = ch;
1681 continue; /* break but increment i */
1684 if (ch == '\r') {
1685 was_cr = 1;
1686 continue;
1689 was_cr = 0;
1690 output[o++] = ch;
1693 *osize_p -= o;
1694 *isize_p -= i;
1696 if (!lf_to_crlf->has_held && was_cr) {
1697 lf_to_crlf->has_held = 1;
1698 lf_to_crlf->held = '\r';
1701 return 0;
1704 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1706 free(filter);
1709 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1710 .filter = lf_to_crlf_filter_fn,
1711 .free = lf_to_crlf_free_fn,
1714 static struct stream_filter *lf_to_crlf_filter(void)
1716 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1718 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1719 return (struct stream_filter *)lf_to_crlf;
1723 * Cascade filter
1725 #define FILTER_BUFFER 1024
1726 struct cascade_filter {
1727 struct stream_filter filter;
1728 struct stream_filter *one;
1729 struct stream_filter *two;
1730 char buf[FILTER_BUFFER];
1731 int end, ptr;
1734 static int cascade_filter_fn(struct stream_filter *filter,
1735 const char *input, size_t *isize_p,
1736 char *output, size_t *osize_p)
1738 struct cascade_filter *cas = (struct cascade_filter *) filter;
1739 size_t filled = 0;
1740 size_t sz = *osize_p;
1741 size_t to_feed, remaining;
1744 * input -- (one) --> buf -- (two) --> output
1746 while (filled < sz) {
1747 remaining = sz - filled;
1749 /* do we already have something to feed two with? */
1750 if (cas->ptr < cas->end) {
1751 to_feed = cas->end - cas->ptr;
1752 if (stream_filter(cas->two,
1753 cas->buf + cas->ptr, &to_feed,
1754 output + filled, &remaining))
1755 return -1;
1756 cas->ptr += (cas->end - cas->ptr) - to_feed;
1757 filled = sz - remaining;
1758 continue;
1761 /* feed one from upstream and have it emit into our buffer */
1762 to_feed = input ? *isize_p : 0;
1763 if (input && !to_feed)
1764 break;
1765 remaining = sizeof(cas->buf);
1766 if (stream_filter(cas->one,
1767 input, &to_feed,
1768 cas->buf, &remaining))
1769 return -1;
1770 cas->end = sizeof(cas->buf) - remaining;
1771 cas->ptr = 0;
1772 if (input) {
1773 size_t fed = *isize_p - to_feed;
1774 *isize_p -= fed;
1775 input += fed;
1778 /* do we know that we drained one completely? */
1779 if (input || cas->end)
1780 continue;
1782 /* tell two to drain; we have nothing more to give it */
1783 to_feed = 0;
1784 remaining = sz - filled;
1785 if (stream_filter(cas->two,
1786 NULL, &to_feed,
1787 output + filled, &remaining))
1788 return -1;
1789 if (remaining == (sz - filled))
1790 break; /* completely drained two */
1791 filled = sz - remaining;
1793 *osize_p -= filled;
1794 return 0;
1797 static void cascade_free_fn(struct stream_filter *filter)
1799 struct cascade_filter *cas = (struct cascade_filter *)filter;
1800 free_stream_filter(cas->one);
1801 free_stream_filter(cas->two);
1802 free(filter);
1805 static struct stream_filter_vtbl cascade_vtbl = {
1806 .filter = cascade_filter_fn,
1807 .free = cascade_free_fn,
1810 static struct stream_filter *cascade_filter(struct stream_filter *one,
1811 struct stream_filter *two)
1813 struct cascade_filter *cascade;
1815 if (!one || is_null_stream_filter(one))
1816 return two;
1817 if (!two || is_null_stream_filter(two))
1818 return one;
1820 cascade = xmalloc(sizeof(*cascade));
1821 cascade->one = one;
1822 cascade->two = two;
1823 cascade->end = cascade->ptr = 0;
1824 cascade->filter.vtbl = &cascade_vtbl;
1825 return (struct stream_filter *)cascade;
1829 * ident filter
1831 #define IDENT_DRAINING (-1)
1832 #define IDENT_SKIPPING (-2)
1833 struct ident_filter {
1834 struct stream_filter filter;
1835 struct strbuf left;
1836 int state;
1837 char ident[GIT_MAX_HEXSZ + 5]; /* ": x40 $" */
1840 static int is_foreign_ident(const char *str)
1842 int i;
1844 if (!skip_prefix(str, "$Id: ", &str))
1845 return 0;
1846 for (i = 0; str[i]; i++) {
1847 if (isspace(str[i]) && str[i+1] != '$')
1848 return 1;
1850 return 0;
1853 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1855 size_t to_drain = ident->left.len;
1857 if (*osize_p < to_drain)
1858 to_drain = *osize_p;
1859 if (to_drain) {
1860 memcpy(*output_p, ident->left.buf, to_drain);
1861 strbuf_remove(&ident->left, 0, to_drain);
1862 *output_p += to_drain;
1863 *osize_p -= to_drain;
1865 if (!ident->left.len)
1866 ident->state = 0;
1869 static int ident_filter_fn(struct stream_filter *filter,
1870 const char *input, size_t *isize_p,
1871 char *output, size_t *osize_p)
1873 struct ident_filter *ident = (struct ident_filter *)filter;
1874 static const char head[] = "$Id";
1876 if (!input) {
1877 /* drain upon eof */
1878 switch (ident->state) {
1879 default:
1880 strbuf_add(&ident->left, head, ident->state);
1881 /* fallthrough */
1882 case IDENT_SKIPPING:
1883 /* fallthrough */
1884 case IDENT_DRAINING:
1885 ident_drain(ident, &output, osize_p);
1887 return 0;
1890 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1891 int ch;
1893 if (ident->state == IDENT_DRAINING) {
1894 ident_drain(ident, &output, osize_p);
1895 if (!*osize_p)
1896 break;
1897 continue;
1900 ch = *(input++);
1901 (*isize_p)--;
1903 if (ident->state == IDENT_SKIPPING) {
1905 * Skipping until '$' or LF, but keeping them
1906 * in case it is a foreign ident.
1908 strbuf_addch(&ident->left, ch);
1909 if (ch != '\n' && ch != '$')
1910 continue;
1911 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1912 strbuf_setlen(&ident->left, sizeof(head) - 1);
1913 strbuf_addstr(&ident->left, ident->ident);
1915 ident->state = IDENT_DRAINING;
1916 continue;
1919 if (ident->state < sizeof(head) &&
1920 head[ident->state] == ch) {
1921 ident->state++;
1922 continue;
1925 if (ident->state)
1926 strbuf_add(&ident->left, head, ident->state);
1927 if (ident->state == sizeof(head) - 1) {
1928 if (ch != ':' && ch != '$') {
1929 strbuf_addch(&ident->left, ch);
1930 ident->state = 0;
1931 continue;
1934 if (ch == ':') {
1935 strbuf_addch(&ident->left, ch);
1936 ident->state = IDENT_SKIPPING;
1937 } else {
1938 strbuf_addstr(&ident->left, ident->ident);
1939 ident->state = IDENT_DRAINING;
1941 continue;
1944 strbuf_addch(&ident->left, ch);
1945 ident->state = IDENT_DRAINING;
1947 return 0;
1950 static void ident_free_fn(struct stream_filter *filter)
1952 struct ident_filter *ident = (struct ident_filter *)filter;
1953 strbuf_release(&ident->left);
1954 free(filter);
1957 static struct stream_filter_vtbl ident_vtbl = {
1958 .filter = ident_filter_fn,
1959 .free = ident_free_fn,
1962 static struct stream_filter *ident_filter(const struct object_id *oid)
1964 struct ident_filter *ident = xmalloc(sizeof(*ident));
1966 xsnprintf(ident->ident, sizeof(ident->ident),
1967 ": %s $", oid_to_hex(oid));
1968 strbuf_init(&ident->left, 0);
1969 ident->filter.vtbl = &ident_vtbl;
1970 ident->state = 0;
1971 return (struct stream_filter *)ident;
1975 * Return an appropriately constructed filter for the given ca, or NULL if
1976 * the contents cannot be filtered without reading the whole thing
1977 * in-core.
1979 * Note that you would be crazy to set CRLF, smudge/clean or ident to a
1980 * large binary blob you would want us not to slurp into the memory!
1982 struct stream_filter *get_stream_filter_ca(const struct conv_attrs *ca,
1983 const struct object_id *oid)
1985 struct stream_filter *filter = NULL;
1987 if (classify_conv_attrs(ca) != CA_CLASS_STREAMABLE)
1988 return NULL;
1990 if (ca->ident)
1991 filter = ident_filter(oid);
1993 if (output_eol(ca->crlf_action) == EOL_CRLF)
1994 filter = cascade_filter(filter, lf_to_crlf_filter());
1995 else
1996 filter = cascade_filter(filter, &null_filter_singleton);
1998 return filter;
2001 struct stream_filter *get_stream_filter(struct index_state *istate,
2002 const char *path,
2003 const struct object_id *oid)
2005 struct conv_attrs ca;
2006 convert_attrs(istate, &ca, path);
2007 return get_stream_filter_ca(&ca, oid);
2010 void free_stream_filter(struct stream_filter *filter)
2012 filter->vtbl->free(filter);
2015 int stream_filter(struct stream_filter *filter,
2016 const char *input, size_t *isize_p,
2017 char *output, size_t *osize_p)
2019 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
2022 void init_checkout_metadata(struct checkout_metadata *meta, const char *refname,
2023 const struct object_id *treeish,
2024 const struct object_id *blob)
2026 memset(meta, 0, sizeof(*meta));
2027 if (refname)
2028 meta->refname = refname;
2029 if (treeish)
2030 oidcpy(&meta->treeish, treeish);
2031 if (blob)
2032 oidcpy(&meta->blob, blob);
2035 void clone_checkout_metadata(struct checkout_metadata *dst,
2036 const struct checkout_metadata *src,
2037 const struct object_id *blob)
2039 memcpy(dst, src, sizeof(*dst));
2040 if (blob)
2041 oidcpy(&dst->blob, blob);
2044 enum conv_attrs_classification classify_conv_attrs(const struct conv_attrs *ca)
2046 if (ca->drv) {
2047 if (ca->drv->process)
2048 return CA_CLASS_INCORE_PROCESS;
2049 if (ca->drv->smudge || ca->drv->clean)
2050 return CA_CLASS_INCORE_FILTER;
2053 if (ca->working_tree_encoding)
2054 return CA_CLASS_INCORE;
2056 if (ca->crlf_action == CRLF_AUTO || ca->crlf_action == CRLF_AUTO_CRLF)
2057 return CA_CLASS_INCORE;
2059 return CA_CLASS_STREAMABLE;