Merge tag 'l10n-2.46.0-rnd2' of https://github.com/git-l10n/git-po
[git/gitster.git] / convert.c
blobd8737fe0f2d60ff372140194bc88e6a1999450e4
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "advice.h"
5 #include "config.h"
6 #include "convert.h"
7 #include "copy.h"
8 #include "gettext.h"
9 #include "hex.h"
10 #include "object-store-ll.h"
11 #include "attr.h"
12 #include "run-command.h"
13 #include "quote.h"
14 #include "read-cache-ll.h"
15 #include "sigchain.h"
16 #include "pkt-line.h"
17 #include "sub-process.h"
18 #include "trace.h"
19 #include "utf8.h"
20 #include "merge-ll.h"
23 * convert.c - convert a file when checking it out and checking it in.
25 * This should use the pathname to decide on whether it wants to do some
26 * more interesting conversions (automatic gzip/unzip, general format
27 * conversions etc etc), but by default it just does automatic CRLF<->LF
28 * translation when the "text" attribute or "auto_crlf" option is set.
31 /* Stat bits: When BIN is set, the txt bits are unset */
32 #define CONVERT_STAT_BITS_TXT_LF 0x1
33 #define CONVERT_STAT_BITS_TXT_CRLF 0x2
34 #define CONVERT_STAT_BITS_BIN 0x4
36 struct text_stat {
37 /* NUL, CR, LF and CRLF counts */
38 unsigned nul, lonecr, lonelf, crlf;
40 /* These are just approximations! */
41 unsigned printable, nonprintable;
44 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
46 unsigned long i;
48 memset(stats, 0, sizeof(*stats));
50 for (i = 0; i < size; i++) {
51 unsigned char c = buf[i];
52 if (c == '\r') {
53 if (i+1 < size && buf[i+1] == '\n') {
54 stats->crlf++;
55 i++;
56 } else
57 stats->lonecr++;
58 continue;
60 if (c == '\n') {
61 stats->lonelf++;
62 continue;
64 if (c == 127)
65 /* DEL */
66 stats->nonprintable++;
67 else if (c < 32) {
68 switch (c) {
69 /* BS, HT, ESC and FF */
70 case '\b': case '\t': case '\033': case '\014':
71 stats->printable++;
72 break;
73 case 0:
74 stats->nul++;
75 /* fall through */
76 default:
77 stats->nonprintable++;
80 else
81 stats->printable++;
84 /* If file ends with EOF then don't count this EOF as non-printable. */
85 if (size >= 1 && buf[size-1] == '\032')
86 stats->nonprintable--;
90 * The same heuristics as diff.c::mmfile_is_binary()
91 * We treat files with bare CR as binary
93 static int convert_is_binary(const struct text_stat *stats)
95 if (stats->lonecr)
96 return 1;
97 if (stats->nul)
98 return 1;
99 if ((stats->printable >> 7) < stats->nonprintable)
100 return 1;
101 return 0;
104 static unsigned int gather_convert_stats(const char *data, unsigned long size)
106 struct text_stat stats;
107 int ret = 0;
108 if (!data || !size)
109 return 0;
110 gather_stats(data, size, &stats);
111 if (convert_is_binary(&stats))
112 ret |= CONVERT_STAT_BITS_BIN;
113 if (stats.crlf)
114 ret |= CONVERT_STAT_BITS_TXT_CRLF;
115 if (stats.lonelf)
116 ret |= CONVERT_STAT_BITS_TXT_LF;
118 return ret;
121 static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
123 unsigned int convert_stats = gather_convert_stats(data, size);
125 if (convert_stats & CONVERT_STAT_BITS_BIN)
126 return "-text";
127 switch (convert_stats) {
128 case CONVERT_STAT_BITS_TXT_LF:
129 return "lf";
130 case CONVERT_STAT_BITS_TXT_CRLF:
131 return "crlf";
132 case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
133 return "mixed";
134 default:
135 return "none";
139 const char *get_cached_convert_stats_ascii(struct index_state *istate,
140 const char *path)
142 const char *ret;
143 unsigned long sz;
144 void *data = read_blob_data_from_index(istate, path, &sz);
145 ret = gather_convert_stats_ascii(data, sz);
146 free(data);
147 return ret;
150 const char *get_wt_convert_stats_ascii(const char *path)
152 const char *ret = "";
153 struct strbuf sb = STRBUF_INIT;
154 if (strbuf_read_file(&sb, path, 0) >= 0)
155 ret = gather_convert_stats_ascii(sb.buf, sb.len);
156 strbuf_release(&sb);
157 return ret;
160 static int text_eol_is_crlf(void)
162 if (auto_crlf == AUTO_CRLF_TRUE)
163 return 1;
164 else if (auto_crlf == AUTO_CRLF_INPUT)
165 return 0;
166 if (core_eol == EOL_CRLF)
167 return 1;
168 if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
169 return 1;
170 return 0;
173 static enum eol output_eol(enum convert_crlf_action crlf_action)
175 switch (crlf_action) {
176 case CRLF_BINARY:
177 return EOL_UNSET;
178 case CRLF_TEXT_CRLF:
179 return EOL_CRLF;
180 case CRLF_TEXT_INPUT:
181 return EOL_LF;
182 case CRLF_UNDEFINED:
183 case CRLF_AUTO_CRLF:
184 return EOL_CRLF;
185 case CRLF_AUTO_INPUT:
186 return EOL_LF;
187 case CRLF_TEXT:
188 case CRLF_AUTO:
189 /* fall through */
190 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
192 warning(_("illegal crlf_action %d"), (int)crlf_action);
193 return core_eol;
196 static void check_global_conv_flags_eol(const char *path,
197 struct text_stat *old_stats, struct text_stat *new_stats,
198 int conv_flags)
200 if (old_stats->crlf && !new_stats->crlf ) {
202 * CRLFs would not be restored by checkout
204 if (conv_flags & CONV_EOL_RNDTRP_DIE)
205 die(_("CRLF would be replaced by LF in %s"), path);
206 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
207 warning(_("in the working copy of '%s', CRLF will be"
208 " replaced by LF the next time Git touches"
209 " it"), path);
210 } else if (old_stats->lonelf && !new_stats->lonelf ) {
212 * CRLFs would be added by checkout
214 if (conv_flags & CONV_EOL_RNDTRP_DIE)
215 die(_("LF would be replaced by CRLF in %s"), path);
216 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
217 warning(_("in the working copy of '%s', LF will be"
218 " replaced by CRLF the next time Git touches"
219 " it"), path);
223 static int has_crlf_in_index(struct index_state *istate, const char *path)
225 unsigned long sz;
226 void *data;
227 const char *crp;
228 int has_crlf = 0;
230 data = read_blob_data_from_index(istate, path, &sz);
231 if (!data)
232 return 0;
234 crp = memchr(data, '\r', sz);
235 if (crp) {
236 unsigned int ret_stats;
237 ret_stats = gather_convert_stats(data, sz);
238 if (!(ret_stats & CONVERT_STAT_BITS_BIN) &&
239 (ret_stats & CONVERT_STAT_BITS_TXT_CRLF))
240 has_crlf = 1;
242 free(data);
243 return has_crlf;
246 static int will_convert_lf_to_crlf(struct text_stat *stats,
247 enum convert_crlf_action crlf_action)
249 if (output_eol(crlf_action) != EOL_CRLF)
250 return 0;
251 /* No "naked" LF? Nothing to convert, regardless. */
252 if (!stats->lonelf)
253 return 0;
255 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
256 /* If we have any CR or CRLF line endings, we do not touch it */
257 /* This is the new safer autocrlf-handling */
258 if (stats->lonecr || stats->crlf)
259 return 0;
261 if (convert_is_binary(stats))
262 return 0;
264 return 1;
268 static int validate_encoding(const char *path, const char *enc,
269 const char *data, size_t len, int die_on_error)
271 const char *stripped;
273 /* We only check for UTF here as UTF?? can be an alias for UTF-?? */
274 if (skip_iprefix(enc, "UTF", &stripped)) {
275 skip_prefix(stripped, "-", &stripped);
278 * Check for detectable errors in UTF encodings
280 if (has_prohibited_utf_bom(enc, data, len)) {
281 const char *error_msg = _(
282 "BOM is prohibited in '%s' if encoded as %s");
284 * This advice is shown for UTF-??BE and UTF-??LE encodings.
285 * We cut off the last two characters of the encoding name
286 * to generate the encoding name suitable for BOMs.
288 const char *advise_msg = _(
289 "The file '%s' contains a byte order "
290 "mark (BOM). Please use UTF-%.*s as "
291 "working-tree-encoding.");
292 int stripped_len = strlen(stripped) - strlen("BE");
293 advise(advise_msg, path, stripped_len, stripped);
294 if (die_on_error)
295 die(error_msg, path, enc);
296 else {
297 return error(error_msg, path, enc);
300 } else if (is_missing_required_utf_bom(enc, data, len)) {
301 const char *error_msg = _(
302 "BOM is required in '%s' if encoded as %s");
303 const char *advise_msg = _(
304 "The file '%s' is missing a byte order "
305 "mark (BOM). Please use UTF-%sBE or UTF-%sLE "
306 "(depending on the byte order) as "
307 "working-tree-encoding.");
308 advise(advise_msg, path, stripped, stripped);
309 if (die_on_error)
310 die(error_msg, path, enc);
311 else {
312 return error(error_msg, path, enc);
317 return 0;
320 static void trace_encoding(const char *context, const char *path,
321 const char *encoding, const char *buf, size_t len)
323 static struct trace_key coe = TRACE_KEY_INIT(WORKING_TREE_ENCODING);
324 struct strbuf trace = STRBUF_INIT;
325 int i;
327 strbuf_addf(&trace, "%s (%s, considered %s):\n", context, path, encoding);
328 for (i = 0; i < len && buf; ++i) {
329 strbuf_addf(
330 &trace, "| \033[2m%2i:\033[0m %2x \033[2m%c\033[0m%c",
332 (unsigned char) buf[i],
333 (buf[i] > 32 && buf[i] < 127 ? buf[i] : ' '),
334 ((i+1) % 8 && (i+1) < len ? ' ' : '\n')
337 strbuf_addchars(&trace, '\n', 1);
339 trace_strbuf(&coe, &trace);
340 strbuf_release(&trace);
343 static int check_roundtrip(const char *enc_name)
346 * check_roundtrip_encoding contains a string of comma and/or
347 * space separated encodings (eg. "UTF-16, ASCII, CP1125").
348 * Search for the given encoding in that string.
350 const char *encoding = check_roundtrip_encoding ?
351 check_roundtrip_encoding : "SHIFT-JIS";
352 const char *found = strcasestr(encoding, enc_name);
353 const char *next;
354 int len;
355 if (!found)
356 return 0;
357 next = found + strlen(enc_name);
358 len = strlen(encoding);
359 return (found && (
361 * Check that the found encoding is at the beginning of
362 * encoding or that it is prefixed with a space or
363 * comma.
365 found == encoding || (
366 (isspace(found[-1]) || found[-1] == ',')
368 ) && (
370 * Check that the found encoding is at the end of
371 * encoding or that it is suffixed with a space
372 * or comma.
374 next == encoding + len || (
375 next < encoding + len &&
376 (isspace(next[0]) || next[0] == ',')
381 static const char *default_encoding = "UTF-8";
383 static int encode_to_git(const char *path, const char *src, size_t src_len,
384 struct strbuf *buf, const char *enc, int conv_flags)
386 char *dst;
387 size_t dst_len;
388 int die_on_error = conv_flags & CONV_WRITE_OBJECT;
391 * No encoding is specified or there is nothing to encode.
392 * Tell the caller that the content was not modified.
394 if (!enc || (src && !src_len))
395 return 0;
398 * Looks like we got called from "would_convert_to_git()".
399 * This means Git wants to know if it would encode (= modify!)
400 * the content. Let's answer with "yes", since an encoding was
401 * specified.
403 if (!buf && !src)
404 return 1;
406 if (validate_encoding(path, enc, src, src_len, die_on_error))
407 return 0;
409 trace_encoding("source", path, enc, src, src_len);
410 dst = reencode_string_len(src, src_len, default_encoding, enc,
411 &dst_len);
412 if (!dst) {
414 * We could add the blob "as-is" to Git. However, on checkout
415 * we would try to re-encode to the original encoding. This
416 * would fail and we would leave the user with a messed-up
417 * working tree. Let's try to avoid this by screaming loud.
419 const char* msg = _("failed to encode '%s' from %s to %s");
420 if (die_on_error)
421 die(msg, path, enc, default_encoding);
422 else {
423 error(msg, path, enc, default_encoding);
424 return 0;
427 trace_encoding("destination", path, default_encoding, dst, dst_len);
430 * UTF supports lossless conversion round tripping [1] and conversions
431 * between UTF and other encodings are mostly round trip safe as
432 * Unicode aims to be a superset of all other character encodings.
433 * However, certain encodings (e.g. SHIFT-JIS) are known to have round
434 * trip issues [2]. Check the round trip conversion for all encodings
435 * listed in core.checkRoundtripEncoding.
437 * The round trip check is only performed if content is written to Git.
438 * This ensures that no information is lost during conversion to/from
439 * the internal UTF-8 representation.
441 * Please note, the code below is not tested because I was not able to
442 * generate a faulty round trip without an iconv error. Iconv errors
443 * are already caught above.
445 * [1] http://unicode.org/faq/utf_bom.html#gen2
446 * [2] https://support.microsoft.com/en-us/help/170559/prb-conversion-problem-between-shift-jis-and-unicode
448 if (die_on_error && check_roundtrip(enc)) {
449 char *re_src;
450 size_t re_src_len;
452 re_src = reencode_string_len(dst, dst_len,
453 enc, default_encoding,
454 &re_src_len);
456 trace_printf("Checking roundtrip encoding for %s...\n", enc);
457 trace_encoding("reencoded source", path, enc,
458 re_src, re_src_len);
460 if (!re_src || src_len != re_src_len ||
461 memcmp(src, re_src, src_len)) {
462 const char* msg = _("encoding '%s' from %s to %s and "
463 "back is not the same");
464 die(msg, path, enc, default_encoding);
467 free(re_src);
470 strbuf_attach(buf, dst, dst_len, dst_len + 1);
471 return 1;
474 static int encode_to_worktree(const char *path, const char *src, size_t src_len,
475 struct strbuf *buf, const char *enc)
477 char *dst;
478 size_t dst_len;
481 * No encoding is specified or there is nothing to encode.
482 * Tell the caller that the content was not modified.
484 if (!enc || (src && !src_len))
485 return 0;
487 dst = reencode_string_len(src, src_len, enc, default_encoding,
488 &dst_len);
489 if (!dst) {
490 error(_("failed to encode '%s' from %s to %s"),
491 path, default_encoding, enc);
492 return 0;
495 strbuf_attach(buf, dst, dst_len, dst_len + 1);
496 return 1;
499 static int crlf_to_git(struct index_state *istate,
500 const char *path, const char *src, size_t len,
501 struct strbuf *buf,
502 enum convert_crlf_action crlf_action, int conv_flags)
504 struct text_stat stats;
505 char *dst;
506 int convert_crlf_into_lf;
508 if (crlf_action == CRLF_BINARY ||
509 (src && !len))
510 return 0;
513 * If we are doing a dry-run and have no source buffer, there is
514 * nothing to analyze; we must assume we would convert.
516 if (!buf && !src)
517 return 1;
519 gather_stats(src, len, &stats);
520 /* Optimization: No CRLF? Nothing to convert, regardless. */
521 convert_crlf_into_lf = !!stats.crlf;
523 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
524 if (convert_is_binary(&stats))
525 return 0;
527 * If the file in the index has any CR in it, do not
528 * convert. This is the new safer autocrlf handling,
529 * unless we want to renormalize in a merge or
530 * cherry-pick.
532 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
533 has_crlf_in_index(istate, path))
534 convert_crlf_into_lf = 0;
536 if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
537 ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
538 struct text_stat new_stats;
539 memcpy(&new_stats, &stats, sizeof(new_stats));
540 /* simulate "git add" */
541 if (convert_crlf_into_lf) {
542 new_stats.lonelf += new_stats.crlf;
543 new_stats.crlf = 0;
545 /* simulate "git checkout" */
546 if (will_convert_lf_to_crlf(&new_stats, crlf_action)) {
547 new_stats.crlf += new_stats.lonelf;
548 new_stats.lonelf = 0;
550 check_global_conv_flags_eol(path, &stats, &new_stats, conv_flags);
552 if (!convert_crlf_into_lf)
553 return 0;
556 * At this point all of our source analysis is done, and we are sure we
557 * would convert. If we are in dry-run mode, we can give an answer.
559 if (!buf)
560 return 1;
562 /* only grow if not in place */
563 if (strbuf_avail(buf) + buf->len < len)
564 strbuf_grow(buf, len - buf->len);
565 dst = buf->buf;
566 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
568 * If we guessed, we already know we rejected a file with
569 * lone CR, and we can strip a CR without looking at what
570 * follow it.
572 do {
573 unsigned char c = *src++;
574 if (c != '\r')
575 *dst++ = c;
576 } while (--len);
577 } else {
578 do {
579 unsigned char c = *src++;
580 if (! (c == '\r' && (1 < len && *src == '\n')))
581 *dst++ = c;
582 } while (--len);
584 strbuf_setlen(buf, dst - buf->buf);
585 return 1;
588 static int crlf_to_worktree(const char *src, size_t len, struct strbuf *buf,
589 enum convert_crlf_action crlf_action)
591 char *to_free = NULL;
592 struct text_stat stats;
594 if (!len || output_eol(crlf_action) != EOL_CRLF)
595 return 0;
597 gather_stats(src, len, &stats);
598 if (!will_convert_lf_to_crlf(&stats, crlf_action))
599 return 0;
601 /* are we "faking" in place editing ? */
602 if (src == buf->buf)
603 to_free = strbuf_detach(buf, NULL);
605 strbuf_grow(buf, len + stats.lonelf);
606 for (;;) {
607 const char *nl = memchr(src, '\n', len);
608 if (!nl)
609 break;
610 if (nl > src && nl[-1] == '\r') {
611 strbuf_add(buf, src, nl + 1 - src);
612 } else {
613 strbuf_add(buf, src, nl - src);
614 strbuf_addstr(buf, "\r\n");
616 len -= nl + 1 - src;
617 src = nl + 1;
619 strbuf_add(buf, src, len);
621 free(to_free);
622 return 1;
625 struct filter_params {
626 const char *src;
627 size_t size;
628 int fd;
629 const char *cmd;
630 const char *path;
633 static int filter_buffer_or_fd(int in UNUSED, int out, void *data)
636 * Spawn cmd and feed the buffer contents through its stdin.
638 struct child_process child_process = CHILD_PROCESS_INIT;
639 struct filter_params *params = (struct filter_params *)data;
640 const char *format = params->cmd;
641 int write_err, status;
643 /* apply % substitution to cmd */
644 struct strbuf cmd = STRBUF_INIT;
646 /* expand all %f with the quoted path; quote to preserve space, etc. */
647 while (strbuf_expand_step(&cmd, &format)) {
648 if (skip_prefix(format, "%", &format))
649 strbuf_addch(&cmd, '%');
650 else if (skip_prefix(format, "f", &format))
651 sq_quote_buf(&cmd, params->path);
652 else
653 strbuf_addch(&cmd, '%');
656 strvec_push(&child_process.args, cmd.buf);
657 child_process.use_shell = 1;
658 child_process.in = -1;
659 child_process.out = out;
661 if (start_command(&child_process)) {
662 strbuf_release(&cmd);
663 return error(_("cannot fork to run external filter '%s'"),
664 params->cmd);
667 sigchain_push(SIGPIPE, SIG_IGN);
669 if (params->src) {
670 write_err = (write_in_full(child_process.in,
671 params->src, params->size) < 0);
672 if (errno == EPIPE)
673 write_err = 0;
674 } else {
675 write_err = copy_fd(params->fd, child_process.in);
676 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
677 write_err = 0;
680 if (close(child_process.in))
681 write_err = 1;
682 if (write_err)
683 error(_("cannot feed the input to external filter '%s'"),
684 params->cmd);
686 sigchain_pop(SIGPIPE);
688 status = finish_command(&child_process);
689 if (status)
690 error(_("external filter '%s' failed %d"), params->cmd, status);
692 strbuf_release(&cmd);
693 return (write_err || status);
696 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
697 struct strbuf *dst, const char *cmd)
700 * Create a pipeline to have the command filter the buffer's
701 * contents.
703 * (child --> cmd) --> us
705 int err = 0;
706 struct strbuf nbuf = STRBUF_INIT;
707 struct async async;
708 struct filter_params params;
710 memset(&async, 0, sizeof(async));
711 async.proc = filter_buffer_or_fd;
712 async.data = &params;
713 async.out = -1;
714 params.src = src;
715 params.size = len;
716 params.fd = fd;
717 params.cmd = cmd;
718 params.path = path;
720 fflush(NULL);
721 if (start_async(&async))
722 return 0; /* error was already reported */
724 if (strbuf_read(&nbuf, async.out, 0) < 0) {
725 err = error(_("read from external filter '%s' failed"), cmd);
727 if (close(async.out)) {
728 err = error(_("read from external filter '%s' failed"), cmd);
730 if (finish_async(&async)) {
731 err = error(_("external filter '%s' failed"), cmd);
734 if (!err) {
735 strbuf_swap(dst, &nbuf);
737 strbuf_release(&nbuf);
738 return !err;
741 #define CAP_CLEAN (1u<<0)
742 #define CAP_SMUDGE (1u<<1)
743 #define CAP_DELAY (1u<<2)
745 struct cmd2process {
746 struct subprocess_entry subprocess; /* must be the first member! */
747 unsigned int supported_capabilities;
750 static int subprocess_map_initialized;
751 static struct hashmap subprocess_map;
753 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
755 static int versions[] = {2, 0};
756 static struct subprocess_capability capabilities[] = {
757 { "clean", CAP_CLEAN },
758 { "smudge", CAP_SMUDGE },
759 { "delay", CAP_DELAY },
760 { NULL, 0 }
762 struct cmd2process *entry = (struct cmd2process *)subprocess;
763 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
764 capabilities,
765 &entry->supported_capabilities);
768 static void handle_filter_error(const struct strbuf *filter_status,
769 struct cmd2process *entry,
770 const unsigned int wanted_capability)
772 if (!strcmp(filter_status->buf, "error"))
773 ; /* The filter signaled a problem with the file. */
774 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
776 * The filter signaled a permanent problem. Don't try to filter
777 * files with the same command for the lifetime of the current
778 * Git process.
780 entry->supported_capabilities &= ~wanted_capability;
781 } else {
783 * Something went wrong with the protocol filter.
784 * Force shutdown and restart if another blob requires filtering.
786 error(_("external filter '%s' failed"), entry->subprocess.cmd);
787 subprocess_stop(&subprocess_map, &entry->subprocess);
788 free(entry);
792 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
793 int fd, struct strbuf *dst, const char *cmd,
794 const unsigned int wanted_capability,
795 const struct checkout_metadata *meta,
796 struct delayed_checkout *dco)
798 int err;
799 int can_delay = 0;
800 struct cmd2process *entry;
801 struct child_process *process;
802 struct strbuf nbuf = STRBUF_INIT;
803 struct strbuf filter_status = STRBUF_INIT;
804 const char *filter_type;
806 if (!subprocess_map_initialized) {
807 subprocess_map_initialized = 1;
808 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
809 entry = NULL;
810 } else {
811 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
814 fflush(NULL);
816 if (!entry) {
817 entry = xmalloc(sizeof(*entry));
818 entry->supported_capabilities = 0;
820 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
821 free(entry);
822 return 0;
825 process = &entry->subprocess.process;
827 if (!(entry->supported_capabilities & wanted_capability))
828 return 0;
830 if (wanted_capability & CAP_CLEAN)
831 filter_type = "clean";
832 else if (wanted_capability & CAP_SMUDGE)
833 filter_type = "smudge";
834 else
835 die(_("unexpected filter type"));
837 sigchain_push(SIGPIPE, SIG_IGN);
839 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
840 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
841 if (err)
842 goto done;
844 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
845 if (err) {
846 error(_("path name too long for external filter"));
847 goto done;
850 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
851 if (err)
852 goto done;
854 if (meta && meta->refname) {
855 err = packet_write_fmt_gently(process->in, "ref=%s\n", meta->refname);
856 if (err)
857 goto done;
860 if (meta && !is_null_oid(&meta->treeish)) {
861 err = packet_write_fmt_gently(process->in, "treeish=%s\n", oid_to_hex(&meta->treeish));
862 if (err)
863 goto done;
866 if (meta && !is_null_oid(&meta->blob)) {
867 err = packet_write_fmt_gently(process->in, "blob=%s\n", oid_to_hex(&meta->blob));
868 if (err)
869 goto done;
872 if ((entry->supported_capabilities & CAP_DELAY) &&
873 dco && dco->state == CE_CAN_DELAY) {
874 can_delay = 1;
875 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
876 if (err)
877 goto done;
880 err = packet_flush_gently(process->in);
881 if (err)
882 goto done;
884 if (fd >= 0)
885 err = write_packetized_from_fd_no_flush(fd, process->in);
886 else
887 err = write_packetized_from_buf_no_flush(src, len, process->in);
888 if (err)
889 goto done;
891 err = packet_flush_gently(process->in);
892 if (err)
893 goto done;
895 err = subprocess_read_status(process->out, &filter_status);
896 if (err)
897 goto done;
899 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
900 string_list_insert(&dco->filters, cmd);
901 string_list_insert(&dco->paths, path);
902 } else {
903 /* The filter got the blob and wants to send us a response. */
904 err = strcmp(filter_status.buf, "success");
905 if (err)
906 goto done;
908 err = read_packetized_to_strbuf(process->out, &nbuf,
909 PACKET_READ_GENTLE_ON_EOF) < 0;
910 if (err)
911 goto done;
913 err = subprocess_read_status(process->out, &filter_status);
914 if (err)
915 goto done;
917 err = strcmp(filter_status.buf, "success");
920 done:
921 sigchain_pop(SIGPIPE);
923 if (err)
924 handle_filter_error(&filter_status, entry, wanted_capability);
925 else
926 strbuf_swap(dst, &nbuf);
927 strbuf_release(&nbuf);
928 strbuf_release(&filter_status);
929 return !err;
933 int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
935 int err;
936 char *line;
937 struct cmd2process *entry;
938 struct child_process *process;
939 struct strbuf filter_status = STRBUF_INIT;
941 assert(subprocess_map_initialized);
942 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
943 if (!entry) {
944 error(_("external filter '%s' is not available anymore although "
945 "not all paths have been filtered"), cmd);
946 return 0;
948 process = &entry->subprocess.process;
949 sigchain_push(SIGPIPE, SIG_IGN);
951 err = packet_write_fmt_gently(
952 process->in, "command=list_available_blobs\n");
953 if (err)
954 goto done;
956 err = packet_flush_gently(process->in);
957 if (err)
958 goto done;
960 while ((line = packet_read_line(process->out, NULL))) {
961 const char *path;
962 if (skip_prefix(line, "pathname=", &path))
963 string_list_insert(available_paths, xstrdup(path));
964 else
965 ; /* ignore unknown keys */
968 err = subprocess_read_status(process->out, &filter_status);
969 if (err)
970 goto done;
972 err = strcmp(filter_status.buf, "success");
974 done:
975 sigchain_pop(SIGPIPE);
977 if (err)
978 handle_filter_error(&filter_status, entry, 0);
979 strbuf_release(&filter_status);
980 return !err;
983 static struct convert_driver {
984 const char *name;
985 struct convert_driver *next;
986 char *smudge;
987 char *clean;
988 char *process;
989 int required;
990 } *user_convert, **user_convert_tail;
992 static int apply_filter(const char *path, const char *src, size_t len,
993 int fd, struct strbuf *dst, struct convert_driver *drv,
994 const unsigned int wanted_capability,
995 const struct checkout_metadata *meta,
996 struct delayed_checkout *dco)
998 const char *cmd = NULL;
1000 if (!drv)
1001 return 0;
1003 if (!dst)
1004 return 1;
1006 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
1007 cmd = drv->clean;
1008 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
1009 cmd = drv->smudge;
1011 if (cmd && *cmd)
1012 return apply_single_file_filter(path, src, len, fd, dst, cmd);
1013 else if (drv->process && *drv->process)
1014 return apply_multi_file_filter(path, src, len, fd, dst,
1015 drv->process, wanted_capability, meta, dco);
1017 return 0;
1020 static int read_convert_config(const char *var, const char *value,
1021 const struct config_context *ctx UNUSED,
1022 void *cb UNUSED)
1024 const char *key, *name;
1025 size_t namelen;
1026 struct convert_driver *drv;
1029 * External conversion drivers are configured using
1030 * "filter.<name>.variable".
1032 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
1033 return 0;
1034 for (drv = user_convert; drv; drv = drv->next)
1035 if (!xstrncmpz(drv->name, name, namelen))
1036 break;
1037 if (!drv) {
1038 CALLOC_ARRAY(drv, 1);
1039 drv->name = xmemdupz(name, namelen);
1040 *user_convert_tail = drv;
1041 user_convert_tail = &(drv->next);
1045 * filter.<name>.smudge and filter.<name>.clean specifies
1046 * the command line:
1048 * command-line
1050 * The command-line will not be interpolated in any way.
1053 if (!strcmp("smudge", key))
1054 return git_config_string(&drv->smudge, var, value);
1056 if (!strcmp("clean", key))
1057 return git_config_string(&drv->clean, var, value);
1059 if (!strcmp("process", key))
1060 return git_config_string(&drv->process, var, value);
1062 if (!strcmp("required", key)) {
1063 drv->required = git_config_bool(var, value);
1064 return 0;
1067 return 0;
1070 static int count_ident(const char *cp, unsigned long size)
1073 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
1075 int cnt = 0;
1076 char ch;
1078 while (size) {
1079 ch = *cp++;
1080 size--;
1081 if (ch != '$')
1082 continue;
1083 if (size < 3)
1084 break;
1085 if (memcmp("Id", cp, 2))
1086 continue;
1087 ch = cp[2];
1088 cp += 3;
1089 size -= 3;
1090 if (ch == '$')
1091 cnt++; /* $Id$ */
1092 if (ch != ':')
1093 continue;
1096 * "$Id: ... "; scan up to the closing dollar sign and discard.
1098 while (size) {
1099 ch = *cp++;
1100 size--;
1101 if (ch == '$') {
1102 cnt++;
1103 break;
1105 if (ch == '\n')
1106 break;
1109 return cnt;
1112 static int ident_to_git(const char *src, size_t len,
1113 struct strbuf *buf, int ident)
1115 char *dst, *dollar;
1117 if (!ident || (src && !count_ident(src, len)))
1118 return 0;
1120 if (!buf)
1121 return 1;
1123 /* only grow if not in place */
1124 if (strbuf_avail(buf) + buf->len < len)
1125 strbuf_grow(buf, len - buf->len);
1126 dst = buf->buf;
1127 for (;;) {
1128 dollar = memchr(src, '$', len);
1129 if (!dollar)
1130 break;
1131 memmove(dst, src, dollar + 1 - src);
1132 dst += dollar + 1 - src;
1133 len -= dollar + 1 - src;
1134 src = dollar + 1;
1136 if (len > 3 && !memcmp(src, "Id:", 3)) {
1137 dollar = memchr(src + 3, '$', len - 3);
1138 if (!dollar)
1139 break;
1140 if (memchr(src + 3, '\n', dollar - src - 3)) {
1141 /* Line break before the next dollar. */
1142 continue;
1145 memcpy(dst, "Id$", 3);
1146 dst += 3;
1147 len -= dollar + 1 - src;
1148 src = dollar + 1;
1151 memmove(dst, src, len);
1152 strbuf_setlen(buf, dst + len - buf->buf);
1153 return 1;
1156 static int ident_to_worktree(const char *src, size_t len,
1157 struct strbuf *buf, int ident)
1159 struct object_id oid;
1160 char *to_free = NULL, *dollar, *spc;
1161 int cnt;
1163 if (!ident)
1164 return 0;
1166 cnt = count_ident(src, len);
1167 if (!cnt)
1168 return 0;
1170 /* are we "faking" in place editing ? */
1171 if (src == buf->buf)
1172 to_free = strbuf_detach(buf, NULL);
1173 hash_object_file(the_hash_algo, src, len, OBJ_BLOB, &oid);
1175 strbuf_grow(buf, len + cnt * (the_hash_algo->hexsz + 3));
1176 for (;;) {
1177 /* step 1: run to the next '$' */
1178 dollar = memchr(src, '$', len);
1179 if (!dollar)
1180 break;
1181 strbuf_add(buf, src, dollar + 1 - src);
1182 len -= dollar + 1 - src;
1183 src = dollar + 1;
1185 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1186 if (len < 3 || memcmp("Id", src, 2))
1187 continue;
1189 /* step 3: skip over Id$ or Id:xxxxx$ */
1190 if (src[2] == '$') {
1191 src += 3;
1192 len -= 3;
1193 } else if (src[2] == ':') {
1195 * It's possible that an expanded Id has crept its way into the
1196 * repository, we cope with that by stripping the expansion out.
1197 * This is probably not a good idea, since it will cause changes
1198 * on checkout, which won't go away by stash, but let's keep it
1199 * for git-style ids.
1201 dollar = memchr(src + 3, '$', len - 3);
1202 if (!dollar) {
1203 /* incomplete keyword, no more '$', so just quit the loop */
1204 break;
1207 if (memchr(src + 3, '\n', dollar - src - 3)) {
1208 /* Line break before the next dollar. */
1209 continue;
1212 spc = memchr(src + 4, ' ', dollar - src - 4);
1213 if (spc && spc < dollar-1) {
1214 /* There are spaces in unexpected places.
1215 * This is probably an id from some other
1216 * versioning system. Keep it for now.
1218 continue;
1221 len -= dollar + 1 - src;
1222 src = dollar + 1;
1223 } else {
1224 /* it wasn't a "Id$" or "Id:xxxx$" */
1225 continue;
1228 /* step 4: substitute */
1229 strbuf_addstr(buf, "Id: ");
1230 strbuf_addstr(buf, oid_to_hex(&oid));
1231 strbuf_addstr(buf, " $");
1233 strbuf_add(buf, src, len);
1235 free(to_free);
1236 return 1;
1239 static const char *git_path_check_encoding(struct attr_check_item *check)
1241 const char *value = check->value;
1243 if (ATTR_UNSET(value) || !strlen(value))
1244 return NULL;
1246 if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
1247 die(_("true/false are no valid working-tree-encodings"));
1250 /* Don't encode to the default encoding */
1251 if (same_encoding(value, default_encoding))
1252 return NULL;
1254 return value;
1257 static enum convert_crlf_action git_path_check_crlf(struct attr_check_item *check)
1259 const char *value = check->value;
1261 if (ATTR_TRUE(value))
1262 return CRLF_TEXT;
1263 else if (ATTR_FALSE(value))
1264 return CRLF_BINARY;
1265 else if (ATTR_UNSET(value))
1267 else if (!strcmp(value, "input"))
1268 return CRLF_TEXT_INPUT;
1269 else if (!strcmp(value, "auto"))
1270 return CRLF_AUTO;
1271 return CRLF_UNDEFINED;
1274 static enum eol git_path_check_eol(struct attr_check_item *check)
1276 const char *value = check->value;
1278 if (ATTR_UNSET(value))
1280 else if (!strcmp(value, "lf"))
1281 return EOL_LF;
1282 else if (!strcmp(value, "crlf"))
1283 return EOL_CRLF;
1284 return EOL_UNSET;
1287 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
1289 const char *value = check->value;
1290 struct convert_driver *drv;
1292 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1293 return NULL;
1294 for (drv = user_convert; drv; drv = drv->next)
1295 if (!strcmp(value, drv->name))
1296 return drv;
1297 return NULL;
1300 static int git_path_check_ident(struct attr_check_item *check)
1302 const char *value = check->value;
1304 return !!ATTR_TRUE(value);
1307 static struct attr_check *check;
1309 void convert_attrs(struct index_state *istate,
1310 struct conv_attrs *ca, const char *path)
1312 struct attr_check_item *ccheck = NULL;
1314 if (!check) {
1315 check = attr_check_initl("crlf", "ident", "filter",
1316 "eol", "text", "working-tree-encoding",
1317 NULL);
1318 user_convert_tail = &user_convert;
1319 git_config(read_convert_config, NULL);
1322 git_check_attr(istate, path, check);
1323 ccheck = check->items;
1324 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1325 if (ca->crlf_action == CRLF_UNDEFINED)
1326 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1327 ca->ident = git_path_check_ident(ccheck + 1);
1328 ca->drv = git_path_check_convert(ccheck + 2);
1329 if (ca->crlf_action != CRLF_BINARY) {
1330 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1331 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1332 ca->crlf_action = CRLF_AUTO_INPUT;
1333 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1334 ca->crlf_action = CRLF_AUTO_CRLF;
1335 else if (eol_attr == EOL_LF)
1336 ca->crlf_action = CRLF_TEXT_INPUT;
1337 else if (eol_attr == EOL_CRLF)
1338 ca->crlf_action = CRLF_TEXT_CRLF;
1340 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
1342 /* Save attr and make a decision for action */
1343 ca->attr_action = ca->crlf_action;
1344 if (ca->crlf_action == CRLF_TEXT)
1345 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1346 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1347 ca->crlf_action = CRLF_BINARY;
1348 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1349 ca->crlf_action = CRLF_AUTO_CRLF;
1350 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1351 ca->crlf_action = CRLF_AUTO_INPUT;
1354 void reset_parsed_attributes(void)
1356 struct convert_driver *drv, *next;
1358 attr_check_free(check);
1359 check = NULL;
1360 reset_merge_attributes();
1362 for (drv = user_convert; drv; drv = next) {
1363 next = drv->next;
1364 free((void *)drv->name);
1365 free(drv);
1367 user_convert = NULL;
1368 user_convert_tail = NULL;
1371 int would_convert_to_git_filter_fd(struct index_state *istate, const char *path)
1373 struct conv_attrs ca;
1375 convert_attrs(istate, &ca, path);
1376 if (!ca.drv)
1377 return 0;
1380 * Apply a filter to an fd only if the filter is required to succeed.
1381 * We must die if the filter fails, because the original data before
1382 * filtering is not available.
1384 if (!ca.drv->required)
1385 return 0;
1387 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL, NULL);
1390 const char *get_convert_attr_ascii(struct index_state *istate, const char *path)
1392 struct conv_attrs ca;
1394 convert_attrs(istate, &ca, path);
1395 switch (ca.attr_action) {
1396 case CRLF_UNDEFINED:
1397 return "";
1398 case CRLF_BINARY:
1399 return "-text";
1400 case CRLF_TEXT:
1401 return "text";
1402 case CRLF_TEXT_INPUT:
1403 return "text eol=lf";
1404 case CRLF_TEXT_CRLF:
1405 return "text eol=crlf";
1406 case CRLF_AUTO:
1407 return "text=auto";
1408 case CRLF_AUTO_CRLF:
1409 return "text=auto eol=crlf";
1410 case CRLF_AUTO_INPUT:
1411 return "text=auto eol=lf";
1413 return "";
1416 int convert_to_git(struct index_state *istate,
1417 const char *path, const char *src, size_t len,
1418 struct strbuf *dst, int conv_flags)
1420 int ret = 0;
1421 struct conv_attrs ca;
1423 convert_attrs(istate, &ca, path);
1425 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL, NULL);
1426 if (!ret && ca.drv && ca.drv->required)
1427 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
1429 if (ret && dst) {
1430 src = dst->buf;
1431 len = dst->len;
1434 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1435 if (ret && dst) {
1436 src = dst->buf;
1437 len = dst->len;
1440 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1441 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
1442 if (ret && dst) {
1443 src = dst->buf;
1444 len = dst->len;
1447 return ret | ident_to_git(src, len, dst, ca.ident);
1450 void convert_to_git_filter_fd(struct index_state *istate,
1451 const char *path, int fd, struct strbuf *dst,
1452 int conv_flags)
1454 struct conv_attrs ca;
1455 convert_attrs(istate, &ca, path);
1457 assert(ca.drv);
1459 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL, NULL))
1460 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
1462 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
1463 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
1464 ident_to_git(dst->buf, dst->len, dst, ca.ident);
1467 static int convert_to_working_tree_ca_internal(const struct conv_attrs *ca,
1468 const char *path, const char *src,
1469 size_t len, struct strbuf *dst,
1470 int normalizing,
1471 const struct checkout_metadata *meta,
1472 struct delayed_checkout *dco)
1474 int ret = 0, ret_filter = 0;
1476 ret |= ident_to_worktree(src, len, dst, ca->ident);
1477 if (ret) {
1478 src = dst->buf;
1479 len = dst->len;
1482 * CRLF conversion can be skipped if normalizing, unless there
1483 * is a smudge or process filter (even if the process filter doesn't
1484 * support smudge). The filters might expect CRLFs.
1486 if ((ca->drv && (ca->drv->smudge || ca->drv->process)) || !normalizing) {
1487 ret |= crlf_to_worktree(src, len, dst, ca->crlf_action);
1488 if (ret) {
1489 src = dst->buf;
1490 len = dst->len;
1494 ret |= encode_to_worktree(path, src, len, dst, ca->working_tree_encoding);
1495 if (ret) {
1496 src = dst->buf;
1497 len = dst->len;
1500 ret_filter = apply_filter(
1501 path, src, len, -1, dst, ca->drv, CAP_SMUDGE, meta, dco);
1502 if (!ret_filter && ca->drv && ca->drv->required)
1503 die(_("%s: smudge filter %s failed"), path, ca->drv->name);
1505 return ret | ret_filter;
1508 int async_convert_to_working_tree_ca(const struct conv_attrs *ca,
1509 const char *path, const char *src,
1510 size_t len, struct strbuf *dst,
1511 const struct checkout_metadata *meta,
1512 void *dco)
1514 return convert_to_working_tree_ca_internal(ca, path, src, len, dst, 0,
1515 meta, dco);
1518 int convert_to_working_tree_ca(const struct conv_attrs *ca,
1519 const char *path, const char *src,
1520 size_t len, struct strbuf *dst,
1521 const struct checkout_metadata *meta)
1523 return convert_to_working_tree_ca_internal(ca, path, src, len, dst, 0,
1524 meta, NULL);
1527 int renormalize_buffer(struct index_state *istate, const char *path,
1528 const char *src, size_t len, struct strbuf *dst)
1530 struct conv_attrs ca;
1531 int ret;
1533 convert_attrs(istate, &ca, path);
1534 ret = convert_to_working_tree_ca_internal(&ca, path, src, len, dst, 1,
1535 NULL, NULL);
1536 if (ret) {
1537 src = dst->buf;
1538 len = dst->len;
1540 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
1543 /*****************************************************************
1545 * Streaming conversion support
1547 *****************************************************************/
1549 typedef int (*filter_fn)(struct stream_filter *,
1550 const char *input, size_t *isize_p,
1551 char *output, size_t *osize_p);
1552 typedef void (*free_fn)(struct stream_filter *);
1554 struct stream_filter_vtbl {
1555 filter_fn filter;
1556 free_fn free;
1559 struct stream_filter {
1560 struct stream_filter_vtbl *vtbl;
1563 static int null_filter_fn(struct stream_filter *filter UNUSED,
1564 const char *input, size_t *isize_p,
1565 char *output, size_t *osize_p)
1567 size_t count;
1569 if (!input)
1570 return 0; /* we do not keep any states */
1571 count = *isize_p;
1572 if (*osize_p < count)
1573 count = *osize_p;
1574 if (count) {
1575 memmove(output, input, count);
1576 *isize_p -= count;
1577 *osize_p -= count;
1579 return 0;
1582 static void null_free_fn(struct stream_filter *filter UNUSED)
1584 ; /* nothing -- null instances are shared */
1587 static struct stream_filter_vtbl null_vtbl = {
1588 .filter = null_filter_fn,
1589 .free = null_free_fn,
1592 static struct stream_filter null_filter_singleton = {
1593 .vtbl = &null_vtbl,
1596 int is_null_stream_filter(struct stream_filter *filter)
1598 return filter == &null_filter_singleton;
1603 * LF-to-CRLF filter
1606 struct lf_to_crlf_filter {
1607 struct stream_filter filter;
1608 unsigned has_held:1;
1609 char held;
1612 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1613 const char *input, size_t *isize_p,
1614 char *output, size_t *osize_p)
1616 size_t count, o = 0;
1617 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1620 * We may be holding onto the CR to see if it is followed by a
1621 * LF, in which case we would need to go to the main loop.
1622 * Otherwise, just emit it to the output stream.
1624 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1625 output[o++] = lf_to_crlf->held;
1626 lf_to_crlf->has_held = 0;
1629 /* We are told to drain */
1630 if (!input) {
1631 *osize_p -= o;
1632 return 0;
1635 count = *isize_p;
1636 if (count || lf_to_crlf->has_held) {
1637 size_t i;
1638 int was_cr = 0;
1640 if (lf_to_crlf->has_held) {
1641 was_cr = 1;
1642 lf_to_crlf->has_held = 0;
1645 for (i = 0; o < *osize_p && i < count; i++) {
1646 char ch = input[i];
1648 if (ch == '\n') {
1649 output[o++] = '\r';
1650 } else if (was_cr) {
1652 * Previous round saw CR and it is not followed
1653 * by a LF; emit the CR before processing the
1654 * current character.
1656 output[o++] = '\r';
1660 * We may have consumed the last output slot,
1661 * in which case we need to break out of this
1662 * loop; hold the current character before
1663 * returning.
1665 if (*osize_p <= o) {
1666 lf_to_crlf->has_held = 1;
1667 lf_to_crlf->held = ch;
1668 continue; /* break but increment i */
1671 if (ch == '\r') {
1672 was_cr = 1;
1673 continue;
1676 was_cr = 0;
1677 output[o++] = ch;
1680 *osize_p -= o;
1681 *isize_p -= i;
1683 if (!lf_to_crlf->has_held && was_cr) {
1684 lf_to_crlf->has_held = 1;
1685 lf_to_crlf->held = '\r';
1688 return 0;
1691 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1693 free(filter);
1696 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1697 .filter = lf_to_crlf_filter_fn,
1698 .free = lf_to_crlf_free_fn,
1701 static struct stream_filter *lf_to_crlf_filter(void)
1703 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1705 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1706 return (struct stream_filter *)lf_to_crlf;
1710 * Cascade filter
1712 #define FILTER_BUFFER 1024
1713 struct cascade_filter {
1714 struct stream_filter filter;
1715 struct stream_filter *one;
1716 struct stream_filter *two;
1717 char buf[FILTER_BUFFER];
1718 int end, ptr;
1721 static int cascade_filter_fn(struct stream_filter *filter,
1722 const char *input, size_t *isize_p,
1723 char *output, size_t *osize_p)
1725 struct cascade_filter *cas = (struct cascade_filter *) filter;
1726 size_t filled = 0;
1727 size_t sz = *osize_p;
1728 size_t to_feed, remaining;
1731 * input -- (one) --> buf -- (two) --> output
1733 while (filled < sz) {
1734 remaining = sz - filled;
1736 /* do we already have something to feed two with? */
1737 if (cas->ptr < cas->end) {
1738 to_feed = cas->end - cas->ptr;
1739 if (stream_filter(cas->two,
1740 cas->buf + cas->ptr, &to_feed,
1741 output + filled, &remaining))
1742 return -1;
1743 cas->ptr += (cas->end - cas->ptr) - to_feed;
1744 filled = sz - remaining;
1745 continue;
1748 /* feed one from upstream and have it emit into our buffer */
1749 to_feed = input ? *isize_p : 0;
1750 if (input && !to_feed)
1751 break;
1752 remaining = sizeof(cas->buf);
1753 if (stream_filter(cas->one,
1754 input, &to_feed,
1755 cas->buf, &remaining))
1756 return -1;
1757 cas->end = sizeof(cas->buf) - remaining;
1758 cas->ptr = 0;
1759 if (input) {
1760 size_t fed = *isize_p - to_feed;
1761 *isize_p -= fed;
1762 input += fed;
1765 /* do we know that we drained one completely? */
1766 if (input || cas->end)
1767 continue;
1769 /* tell two to drain; we have nothing more to give it */
1770 to_feed = 0;
1771 remaining = sz - filled;
1772 if (stream_filter(cas->two,
1773 NULL, &to_feed,
1774 output + filled, &remaining))
1775 return -1;
1776 if (remaining == (sz - filled))
1777 break; /* completely drained two */
1778 filled = sz - remaining;
1780 *osize_p -= filled;
1781 return 0;
1784 static void cascade_free_fn(struct stream_filter *filter)
1786 struct cascade_filter *cas = (struct cascade_filter *)filter;
1787 free_stream_filter(cas->one);
1788 free_stream_filter(cas->two);
1789 free(filter);
1792 static struct stream_filter_vtbl cascade_vtbl = {
1793 .filter = cascade_filter_fn,
1794 .free = cascade_free_fn,
1797 static struct stream_filter *cascade_filter(struct stream_filter *one,
1798 struct stream_filter *two)
1800 struct cascade_filter *cascade;
1802 if (!one || is_null_stream_filter(one))
1803 return two;
1804 if (!two || is_null_stream_filter(two))
1805 return one;
1807 cascade = xmalloc(sizeof(*cascade));
1808 cascade->one = one;
1809 cascade->two = two;
1810 cascade->end = cascade->ptr = 0;
1811 cascade->filter.vtbl = &cascade_vtbl;
1812 return (struct stream_filter *)cascade;
1816 * ident filter
1818 #define IDENT_DRAINING (-1)
1819 #define IDENT_SKIPPING (-2)
1820 struct ident_filter {
1821 struct stream_filter filter;
1822 struct strbuf left;
1823 int state;
1824 char ident[GIT_MAX_HEXSZ + 5]; /* ": x40 $" */
1827 static int is_foreign_ident(const char *str)
1829 int i;
1831 if (!skip_prefix(str, "$Id: ", &str))
1832 return 0;
1833 for (i = 0; str[i]; i++) {
1834 if (isspace(str[i]) && str[i+1] != '$')
1835 return 1;
1837 return 0;
1840 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1842 size_t to_drain = ident->left.len;
1844 if (*osize_p < to_drain)
1845 to_drain = *osize_p;
1846 if (to_drain) {
1847 memcpy(*output_p, ident->left.buf, to_drain);
1848 strbuf_remove(&ident->left, 0, to_drain);
1849 *output_p += to_drain;
1850 *osize_p -= to_drain;
1852 if (!ident->left.len)
1853 ident->state = 0;
1856 static int ident_filter_fn(struct stream_filter *filter,
1857 const char *input, size_t *isize_p,
1858 char *output, size_t *osize_p)
1860 struct ident_filter *ident = (struct ident_filter *)filter;
1861 static const char head[] = "$Id";
1863 if (!input) {
1864 /* drain upon eof */
1865 switch (ident->state) {
1866 default:
1867 strbuf_add(&ident->left, head, ident->state);
1868 /* fallthrough */
1869 case IDENT_SKIPPING:
1870 /* fallthrough */
1871 case IDENT_DRAINING:
1872 ident_drain(ident, &output, osize_p);
1874 return 0;
1877 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1878 int ch;
1880 if (ident->state == IDENT_DRAINING) {
1881 ident_drain(ident, &output, osize_p);
1882 if (!*osize_p)
1883 break;
1884 continue;
1887 ch = *(input++);
1888 (*isize_p)--;
1890 if (ident->state == IDENT_SKIPPING) {
1892 * Skipping until '$' or LF, but keeping them
1893 * in case it is a foreign ident.
1895 strbuf_addch(&ident->left, ch);
1896 if (ch != '\n' && ch != '$')
1897 continue;
1898 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1899 strbuf_setlen(&ident->left, sizeof(head) - 1);
1900 strbuf_addstr(&ident->left, ident->ident);
1902 ident->state = IDENT_DRAINING;
1903 continue;
1906 if (ident->state < sizeof(head) &&
1907 head[ident->state] == ch) {
1908 ident->state++;
1909 continue;
1912 if (ident->state)
1913 strbuf_add(&ident->left, head, ident->state);
1914 if (ident->state == sizeof(head) - 1) {
1915 if (ch != ':' && ch != '$') {
1916 strbuf_addch(&ident->left, ch);
1917 ident->state = 0;
1918 continue;
1921 if (ch == ':') {
1922 strbuf_addch(&ident->left, ch);
1923 ident->state = IDENT_SKIPPING;
1924 } else {
1925 strbuf_addstr(&ident->left, ident->ident);
1926 ident->state = IDENT_DRAINING;
1928 continue;
1931 strbuf_addch(&ident->left, ch);
1932 ident->state = IDENT_DRAINING;
1934 return 0;
1937 static void ident_free_fn(struct stream_filter *filter)
1939 struct ident_filter *ident = (struct ident_filter *)filter;
1940 strbuf_release(&ident->left);
1941 free(filter);
1944 static struct stream_filter_vtbl ident_vtbl = {
1945 .filter = ident_filter_fn,
1946 .free = ident_free_fn,
1949 static struct stream_filter *ident_filter(const struct object_id *oid)
1951 struct ident_filter *ident = xmalloc(sizeof(*ident));
1953 xsnprintf(ident->ident, sizeof(ident->ident),
1954 ": %s $", oid_to_hex(oid));
1955 strbuf_init(&ident->left, 0);
1956 ident->filter.vtbl = &ident_vtbl;
1957 ident->state = 0;
1958 return (struct stream_filter *)ident;
1962 * Return an appropriately constructed filter for the given ca, or NULL if
1963 * the contents cannot be filtered without reading the whole thing
1964 * in-core.
1966 * Note that you would be crazy to set CRLF, smudge/clean or ident to a
1967 * large binary blob you would want us not to slurp into the memory!
1969 struct stream_filter *get_stream_filter_ca(const struct conv_attrs *ca,
1970 const struct object_id *oid)
1972 struct stream_filter *filter = NULL;
1974 if (classify_conv_attrs(ca) != CA_CLASS_STREAMABLE)
1975 return NULL;
1977 if (ca->ident)
1978 filter = ident_filter(oid);
1980 if (output_eol(ca->crlf_action) == EOL_CRLF)
1981 filter = cascade_filter(filter, lf_to_crlf_filter());
1982 else
1983 filter = cascade_filter(filter, &null_filter_singleton);
1985 return filter;
1988 struct stream_filter *get_stream_filter(struct index_state *istate,
1989 const char *path,
1990 const struct object_id *oid)
1992 struct conv_attrs ca;
1993 convert_attrs(istate, &ca, path);
1994 return get_stream_filter_ca(&ca, oid);
1997 void free_stream_filter(struct stream_filter *filter)
1999 filter->vtbl->free(filter);
2002 int stream_filter(struct stream_filter *filter,
2003 const char *input, size_t *isize_p,
2004 char *output, size_t *osize_p)
2006 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
2009 void init_checkout_metadata(struct checkout_metadata *meta, const char *refname,
2010 const struct object_id *treeish,
2011 const struct object_id *blob)
2013 memset(meta, 0, sizeof(*meta));
2014 if (refname)
2015 meta->refname = refname;
2016 if (treeish)
2017 oidcpy(&meta->treeish, treeish);
2018 if (blob)
2019 oidcpy(&meta->blob, blob);
2022 void clone_checkout_metadata(struct checkout_metadata *dst,
2023 const struct checkout_metadata *src,
2024 const struct object_id *blob)
2026 memcpy(dst, src, sizeof(*dst));
2027 if (blob)
2028 oidcpy(&dst->blob, blob);
2031 enum conv_attrs_classification classify_conv_attrs(const struct conv_attrs *ca)
2033 if (ca->drv) {
2034 if (ca->drv->process)
2035 return CA_CLASS_INCORE_PROCESS;
2036 if (ca->drv->smudge || ca->drv->clean)
2037 return CA_CLASS_INCORE_FILTER;
2040 if (ca->working_tree_encoding)
2041 return CA_CLASS_INCORE;
2043 if (ca->crlf_action == CRLF_AUTO || ca->crlf_action == CRLF_AUTO_CRLF)
2044 return CA_CLASS_INCORE;
2046 return CA_CLASS_STREAMABLE;