pretty: avoid double negative in format_commit_item()
[git/debian.git] / convert.c
blob455d05cf6b30690b8b76bbe086d03b921fd59500
1 #include "cache.h"
2 #include "advice.h"
3 #include "config.h"
4 #include "convert.h"
5 #include "copy.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "object-store.h"
9 #include "attr.h"
10 #include "run-command.h"
11 #include "quote.h"
12 #include "sigchain.h"
13 #include "pkt-line.h"
14 #include "sub-process.h"
15 #include "trace.h"
16 #include "utf8.h"
17 #include "ll-merge.h"
18 #include "wrapper.h"
21 * convert.c - convert a file when checking it out and checking it in.
23 * This should use the pathname to decide on whether it wants to do some
24 * more interesting conversions (automatic gzip/unzip, general format
25 * conversions etc etc), but by default it just does automatic CRLF<->LF
26 * translation when the "text" attribute or "auto_crlf" option is set.
29 /* Stat bits: When BIN is set, the txt bits are unset */
30 #define CONVERT_STAT_BITS_TXT_LF 0x1
31 #define CONVERT_STAT_BITS_TXT_CRLF 0x2
32 #define CONVERT_STAT_BITS_BIN 0x4
34 struct text_stat {
35 /* NUL, CR, LF and CRLF counts */
36 unsigned nul, lonecr, lonelf, crlf;
38 /* These are just approximations! */
39 unsigned printable, nonprintable;
42 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
44 unsigned long i;
46 memset(stats, 0, sizeof(*stats));
48 for (i = 0; i < size; i++) {
49 unsigned char c = buf[i];
50 if (c == '\r') {
51 if (i+1 < size && buf[i+1] == '\n') {
52 stats->crlf++;
53 i++;
54 } else
55 stats->lonecr++;
56 continue;
58 if (c == '\n') {
59 stats->lonelf++;
60 continue;
62 if (c == 127)
63 /* DEL */
64 stats->nonprintable++;
65 else if (c < 32) {
66 switch (c) {
67 /* BS, HT, ESC and FF */
68 case '\b': case '\t': case '\033': case '\014':
69 stats->printable++;
70 break;
71 case 0:
72 stats->nul++;
73 /* fall through */
74 default:
75 stats->nonprintable++;
78 else
79 stats->printable++;
82 /* If file ends with EOF then don't count this EOF as non-printable. */
83 if (size >= 1 && buf[size-1] == '\032')
84 stats->nonprintable--;
88 * The same heuristics as diff.c::mmfile_is_binary()
89 * We treat files with bare CR as binary
91 static int convert_is_binary(const struct text_stat *stats)
93 if (stats->lonecr)
94 return 1;
95 if (stats->nul)
96 return 1;
97 if ((stats->printable >> 7) < stats->nonprintable)
98 return 1;
99 return 0;
102 static unsigned int gather_convert_stats(const char *data, unsigned long size)
104 struct text_stat stats;
105 int ret = 0;
106 if (!data || !size)
107 return 0;
108 gather_stats(data, size, &stats);
109 if (convert_is_binary(&stats))
110 ret |= CONVERT_STAT_BITS_BIN;
111 if (stats.crlf)
112 ret |= CONVERT_STAT_BITS_TXT_CRLF;
113 if (stats.lonelf)
114 ret |= CONVERT_STAT_BITS_TXT_LF;
116 return ret;
119 static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
121 unsigned int convert_stats = gather_convert_stats(data, size);
123 if (convert_stats & CONVERT_STAT_BITS_BIN)
124 return "-text";
125 switch (convert_stats) {
126 case CONVERT_STAT_BITS_TXT_LF:
127 return "lf";
128 case CONVERT_STAT_BITS_TXT_CRLF:
129 return "crlf";
130 case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
131 return "mixed";
132 default:
133 return "none";
137 const char *get_cached_convert_stats_ascii(struct index_state *istate,
138 const char *path)
140 const char *ret;
141 unsigned long sz;
142 void *data = read_blob_data_from_index(istate, path, &sz);
143 ret = gather_convert_stats_ascii(data, sz);
144 free(data);
145 return ret;
148 const char *get_wt_convert_stats_ascii(const char *path)
150 const char *ret = "";
151 struct strbuf sb = STRBUF_INIT;
152 if (strbuf_read_file(&sb, path, 0) >= 0)
153 ret = gather_convert_stats_ascii(sb.buf, sb.len);
154 strbuf_release(&sb);
155 return ret;
158 static int text_eol_is_crlf(void)
160 if (auto_crlf == AUTO_CRLF_TRUE)
161 return 1;
162 else if (auto_crlf == AUTO_CRLF_INPUT)
163 return 0;
164 if (core_eol == EOL_CRLF)
165 return 1;
166 if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
167 return 1;
168 return 0;
171 static enum eol output_eol(enum convert_crlf_action crlf_action)
173 switch (crlf_action) {
174 case CRLF_BINARY:
175 return EOL_UNSET;
176 case CRLF_TEXT_CRLF:
177 return EOL_CRLF;
178 case CRLF_TEXT_INPUT:
179 return EOL_LF;
180 case CRLF_UNDEFINED:
181 case CRLF_AUTO_CRLF:
182 return EOL_CRLF;
183 case CRLF_AUTO_INPUT:
184 return EOL_LF;
185 case CRLF_TEXT:
186 case CRLF_AUTO:
187 /* fall through */
188 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
190 warning(_("illegal crlf_action %d"), (int)crlf_action);
191 return core_eol;
194 static void check_global_conv_flags_eol(const char *path,
195 struct text_stat *old_stats, struct text_stat *new_stats,
196 int conv_flags)
198 if (old_stats->crlf && !new_stats->crlf ) {
200 * CRLFs would not be restored by checkout
202 if (conv_flags & CONV_EOL_RNDTRP_DIE)
203 die(_("CRLF would be replaced by LF in %s"), path);
204 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
205 warning(_("in the working copy of '%s', CRLF will be"
206 " replaced by LF the next time Git touches"
207 " it"), path);
208 } else if (old_stats->lonelf && !new_stats->lonelf ) {
210 * CRLFs would be added by checkout
212 if (conv_flags & CONV_EOL_RNDTRP_DIE)
213 die(_("LF would be replaced by CRLF in %s"), path);
214 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
215 warning(_("in the working copy of '%s', LF will be"
216 " replaced by CRLF the next time Git touches"
217 " it"), path);
221 static int has_crlf_in_index(struct index_state *istate, const char *path)
223 unsigned long sz;
224 void *data;
225 const char *crp;
226 int has_crlf = 0;
228 data = read_blob_data_from_index(istate, path, &sz);
229 if (!data)
230 return 0;
232 crp = memchr(data, '\r', sz);
233 if (crp) {
234 unsigned int ret_stats;
235 ret_stats = gather_convert_stats(data, sz);
236 if (!(ret_stats & CONVERT_STAT_BITS_BIN) &&
237 (ret_stats & CONVERT_STAT_BITS_TXT_CRLF))
238 has_crlf = 1;
240 free(data);
241 return has_crlf;
244 static int will_convert_lf_to_crlf(struct text_stat *stats,
245 enum convert_crlf_action crlf_action)
247 if (output_eol(crlf_action) != EOL_CRLF)
248 return 0;
249 /* No "naked" LF? Nothing to convert, regardless. */
250 if (!stats->lonelf)
251 return 0;
253 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
254 /* If we have any CR or CRLF line endings, we do not touch it */
255 /* This is the new safer autocrlf-handling */
256 if (stats->lonecr || stats->crlf)
257 return 0;
259 if (convert_is_binary(stats))
260 return 0;
262 return 1;
266 static int validate_encoding(const char *path, const char *enc,
267 const char *data, size_t len, int die_on_error)
269 const char *stripped;
271 /* We only check for UTF here as UTF?? can be an alias for UTF-?? */
272 if (skip_iprefix(enc, "UTF", &stripped)) {
273 skip_prefix(stripped, "-", &stripped);
276 * Check for detectable errors in UTF encodings
278 if (has_prohibited_utf_bom(enc, data, len)) {
279 const char *error_msg = _(
280 "BOM is prohibited in '%s' if encoded as %s");
282 * This advice is shown for UTF-??BE and UTF-??LE encodings.
283 * We cut off the last two characters of the encoding name
284 * to generate the encoding name suitable for BOMs.
286 const char *advise_msg = _(
287 "The file '%s' contains a byte order "
288 "mark (BOM). Please use UTF-%.*s as "
289 "working-tree-encoding.");
290 int stripped_len = strlen(stripped) - strlen("BE");
291 advise(advise_msg, path, stripped_len, stripped);
292 if (die_on_error)
293 die(error_msg, path, enc);
294 else {
295 return error(error_msg, path, enc);
298 } else if (is_missing_required_utf_bom(enc, data, len)) {
299 const char *error_msg = _(
300 "BOM is required in '%s' if encoded as %s");
301 const char *advise_msg = _(
302 "The file '%s' is missing a byte order "
303 "mark (BOM). Please use UTF-%sBE or UTF-%sLE "
304 "(depending on the byte order) as "
305 "working-tree-encoding.");
306 advise(advise_msg, path, stripped, stripped);
307 if (die_on_error)
308 die(error_msg, path, enc);
309 else {
310 return error(error_msg, path, enc);
315 return 0;
318 static void trace_encoding(const char *context, const char *path,
319 const char *encoding, const char *buf, size_t len)
321 static struct trace_key coe = TRACE_KEY_INIT(WORKING_TREE_ENCODING);
322 struct strbuf trace = STRBUF_INIT;
323 int i;
325 strbuf_addf(&trace, "%s (%s, considered %s):\n", context, path, encoding);
326 for (i = 0; i < len && buf; ++i) {
327 strbuf_addf(
328 &trace, "| \033[2m%2i:\033[0m %2x \033[2m%c\033[0m%c",
330 (unsigned char) buf[i],
331 (buf[i] > 32 && buf[i] < 127 ? buf[i] : ' '),
332 ((i+1) % 8 && (i+1) < len ? ' ' : '\n')
335 strbuf_addchars(&trace, '\n', 1);
337 trace_strbuf(&coe, &trace);
338 strbuf_release(&trace);
341 static int check_roundtrip(const char *enc_name)
344 * check_roundtrip_encoding contains a string of comma and/or
345 * space separated encodings (eg. "UTF-16, ASCII, CP1125").
346 * Search for the given encoding in that string.
348 const char *found = strcasestr(check_roundtrip_encoding, enc_name);
349 const char *next;
350 int len;
351 if (!found)
352 return 0;
353 next = found + strlen(enc_name);
354 len = strlen(check_roundtrip_encoding);
355 return (found && (
357 * check that the found encoding is at the
358 * beginning of check_roundtrip_encoding or
359 * that it is prefixed with a space or comma
361 found == check_roundtrip_encoding || (
362 (isspace(found[-1]) || found[-1] == ',')
364 ) && (
366 * check that the found encoding is at the
367 * end of check_roundtrip_encoding or
368 * that it is suffixed with a space or comma
370 next == check_roundtrip_encoding + len || (
371 next < check_roundtrip_encoding + len &&
372 (isspace(next[0]) || next[0] == ',')
377 static const char *default_encoding = "UTF-8";
379 static int encode_to_git(const char *path, const char *src, size_t src_len,
380 struct strbuf *buf, const char *enc, int conv_flags)
382 char *dst;
383 size_t dst_len;
384 int die_on_error = conv_flags & CONV_WRITE_OBJECT;
387 * No encoding is specified or there is nothing to encode.
388 * Tell the caller that the content was not modified.
390 if (!enc || (src && !src_len))
391 return 0;
394 * Looks like we got called from "would_convert_to_git()".
395 * This means Git wants to know if it would encode (= modify!)
396 * the content. Let's answer with "yes", since an encoding was
397 * specified.
399 if (!buf && !src)
400 return 1;
402 if (validate_encoding(path, enc, src, src_len, die_on_error))
403 return 0;
405 trace_encoding("source", path, enc, src, src_len);
406 dst = reencode_string_len(src, src_len, default_encoding, enc,
407 &dst_len);
408 if (!dst) {
410 * We could add the blob "as-is" to Git. However, on checkout
411 * we would try to re-encode to the original encoding. This
412 * would fail and we would leave the user with a messed-up
413 * working tree. Let's try to avoid this by screaming loud.
415 const char* msg = _("failed to encode '%s' from %s to %s");
416 if (die_on_error)
417 die(msg, path, enc, default_encoding);
418 else {
419 error(msg, path, enc, default_encoding);
420 return 0;
423 trace_encoding("destination", path, default_encoding, dst, dst_len);
426 * UTF supports lossless conversion round tripping [1] and conversions
427 * between UTF and other encodings are mostly round trip safe as
428 * Unicode aims to be a superset of all other character encodings.
429 * However, certain encodings (e.g. SHIFT-JIS) are known to have round
430 * trip issues [2]. Check the round trip conversion for all encodings
431 * listed in core.checkRoundtripEncoding.
433 * The round trip check is only performed if content is written to Git.
434 * This ensures that no information is lost during conversion to/from
435 * the internal UTF-8 representation.
437 * Please note, the code below is not tested because I was not able to
438 * generate a faulty round trip without an iconv error. Iconv errors
439 * are already caught above.
441 * [1] http://unicode.org/faq/utf_bom.html#gen2
442 * [2] https://support.microsoft.com/en-us/help/170559/prb-conversion-problem-between-shift-jis-and-unicode
444 if (die_on_error && check_roundtrip(enc)) {
445 char *re_src;
446 size_t re_src_len;
448 re_src = reencode_string_len(dst, dst_len,
449 enc, default_encoding,
450 &re_src_len);
452 trace_printf("Checking roundtrip encoding for %s...\n", enc);
453 trace_encoding("reencoded source", path, enc,
454 re_src, re_src_len);
456 if (!re_src || src_len != re_src_len ||
457 memcmp(src, re_src, src_len)) {
458 const char* msg = _("encoding '%s' from %s to %s and "
459 "back is not the same");
460 die(msg, path, enc, default_encoding);
463 free(re_src);
466 strbuf_attach(buf, dst, dst_len, dst_len + 1);
467 return 1;
470 static int encode_to_worktree(const char *path, const char *src, size_t src_len,
471 struct strbuf *buf, const char *enc)
473 char *dst;
474 size_t dst_len;
477 * No encoding is specified or there is nothing to encode.
478 * Tell the caller that the content was not modified.
480 if (!enc || (src && !src_len))
481 return 0;
483 dst = reencode_string_len(src, src_len, enc, default_encoding,
484 &dst_len);
485 if (!dst) {
486 error(_("failed to encode '%s' from %s to %s"),
487 path, default_encoding, enc);
488 return 0;
491 strbuf_attach(buf, dst, dst_len, dst_len + 1);
492 return 1;
495 static int crlf_to_git(struct index_state *istate,
496 const char *path, const char *src, size_t len,
497 struct strbuf *buf,
498 enum convert_crlf_action crlf_action, int conv_flags)
500 struct text_stat stats;
501 char *dst;
502 int convert_crlf_into_lf;
504 if (crlf_action == CRLF_BINARY ||
505 (src && !len))
506 return 0;
509 * If we are doing a dry-run and have no source buffer, there is
510 * nothing to analyze; we must assume we would convert.
512 if (!buf && !src)
513 return 1;
515 gather_stats(src, len, &stats);
516 /* Optimization: No CRLF? Nothing to convert, regardless. */
517 convert_crlf_into_lf = !!stats.crlf;
519 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
520 if (convert_is_binary(&stats))
521 return 0;
523 * If the file in the index has any CR in it, do not
524 * convert. This is the new safer autocrlf handling,
525 * unless we want to renormalize in a merge or
526 * cherry-pick.
528 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
529 has_crlf_in_index(istate, path))
530 convert_crlf_into_lf = 0;
532 if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
533 ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
534 struct text_stat new_stats;
535 memcpy(&new_stats, &stats, sizeof(new_stats));
536 /* simulate "git add" */
537 if (convert_crlf_into_lf) {
538 new_stats.lonelf += new_stats.crlf;
539 new_stats.crlf = 0;
541 /* simulate "git checkout" */
542 if (will_convert_lf_to_crlf(&new_stats, crlf_action)) {
543 new_stats.crlf += new_stats.lonelf;
544 new_stats.lonelf = 0;
546 check_global_conv_flags_eol(path, &stats, &new_stats, conv_flags);
548 if (!convert_crlf_into_lf)
549 return 0;
552 * At this point all of our source analysis is done, and we are sure we
553 * would convert. If we are in dry-run mode, we can give an answer.
555 if (!buf)
556 return 1;
558 /* only grow if not in place */
559 if (strbuf_avail(buf) + buf->len < len)
560 strbuf_grow(buf, len - buf->len);
561 dst = buf->buf;
562 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
564 * If we guessed, we already know we rejected a file with
565 * lone CR, and we can strip a CR without looking at what
566 * follow it.
568 do {
569 unsigned char c = *src++;
570 if (c != '\r')
571 *dst++ = c;
572 } while (--len);
573 } else {
574 do {
575 unsigned char c = *src++;
576 if (! (c == '\r' && (1 < len && *src == '\n')))
577 *dst++ = c;
578 } while (--len);
580 strbuf_setlen(buf, dst - buf->buf);
581 return 1;
584 static int crlf_to_worktree(const char *src, size_t len, struct strbuf *buf,
585 enum convert_crlf_action crlf_action)
587 char *to_free = NULL;
588 struct text_stat stats;
590 if (!len || output_eol(crlf_action) != EOL_CRLF)
591 return 0;
593 gather_stats(src, len, &stats);
594 if (!will_convert_lf_to_crlf(&stats, crlf_action))
595 return 0;
597 /* are we "faking" in place editing ? */
598 if (src == buf->buf)
599 to_free = strbuf_detach(buf, NULL);
601 strbuf_grow(buf, len + stats.lonelf);
602 for (;;) {
603 const char *nl = memchr(src, '\n', len);
604 if (!nl)
605 break;
606 if (nl > src && nl[-1] == '\r') {
607 strbuf_add(buf, src, nl + 1 - src);
608 } else {
609 strbuf_add(buf, src, nl - src);
610 strbuf_addstr(buf, "\r\n");
612 len -= nl + 1 - src;
613 src = nl + 1;
615 strbuf_add(buf, src, len);
617 free(to_free);
618 return 1;
621 struct filter_params {
622 const char *src;
623 size_t size;
624 int fd;
625 const char *cmd;
626 const char *path;
629 static int filter_buffer_or_fd(int in UNUSED, int out, void *data)
632 * Spawn cmd and feed the buffer contents through its stdin.
634 struct child_process child_process = CHILD_PROCESS_INIT;
635 struct filter_params *params = (struct filter_params *)data;
636 const char *format = params->cmd;
637 int write_err, status;
639 /* apply % substitution to cmd */
640 struct strbuf cmd = STRBUF_INIT;
642 /* expand all %f with the quoted path; quote to preserve space, etc. */
643 while (strbuf_expand_step(&cmd, &format)) {
644 if (skip_prefix(format, "%", &format))
645 strbuf_addch(&cmd, '%');
646 else if (skip_prefix(format, "f", &format))
647 sq_quote_buf(&cmd, params->path);
648 else
649 strbuf_addch(&cmd, '%');
652 strvec_push(&child_process.args, cmd.buf);
653 child_process.use_shell = 1;
654 child_process.in = -1;
655 child_process.out = out;
657 if (start_command(&child_process)) {
658 strbuf_release(&cmd);
659 return error(_("cannot fork to run external filter '%s'"),
660 params->cmd);
663 sigchain_push(SIGPIPE, SIG_IGN);
665 if (params->src) {
666 write_err = (write_in_full(child_process.in,
667 params->src, params->size) < 0);
668 if (errno == EPIPE)
669 write_err = 0;
670 } else {
671 write_err = copy_fd(params->fd, child_process.in);
672 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
673 write_err = 0;
676 if (close(child_process.in))
677 write_err = 1;
678 if (write_err)
679 error(_("cannot feed the input to external filter '%s'"),
680 params->cmd);
682 sigchain_pop(SIGPIPE);
684 status = finish_command(&child_process);
685 if (status)
686 error(_("external filter '%s' failed %d"), params->cmd, status);
688 strbuf_release(&cmd);
689 return (write_err || status);
692 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
693 struct strbuf *dst, const char *cmd)
696 * Create a pipeline to have the command filter the buffer's
697 * contents.
699 * (child --> cmd) --> us
701 int err = 0;
702 struct strbuf nbuf = STRBUF_INIT;
703 struct async async;
704 struct filter_params params;
706 memset(&async, 0, sizeof(async));
707 async.proc = filter_buffer_or_fd;
708 async.data = &params;
709 async.out = -1;
710 params.src = src;
711 params.size = len;
712 params.fd = fd;
713 params.cmd = cmd;
714 params.path = path;
716 fflush(NULL);
717 if (start_async(&async))
718 return 0; /* error was already reported */
720 if (strbuf_read(&nbuf, async.out, 0) < 0) {
721 err = error(_("read from external filter '%s' failed"), cmd);
723 if (close(async.out)) {
724 err = error(_("read from external filter '%s' failed"), cmd);
726 if (finish_async(&async)) {
727 err = error(_("external filter '%s' failed"), cmd);
730 if (!err) {
731 strbuf_swap(dst, &nbuf);
733 strbuf_release(&nbuf);
734 return !err;
737 #define CAP_CLEAN (1u<<0)
738 #define CAP_SMUDGE (1u<<1)
739 #define CAP_DELAY (1u<<2)
741 struct cmd2process {
742 struct subprocess_entry subprocess; /* must be the first member! */
743 unsigned int supported_capabilities;
746 static int subprocess_map_initialized;
747 static struct hashmap subprocess_map;
749 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
751 static int versions[] = {2, 0};
752 static struct subprocess_capability capabilities[] = {
753 { "clean", CAP_CLEAN },
754 { "smudge", CAP_SMUDGE },
755 { "delay", CAP_DELAY },
756 { NULL, 0 }
758 struct cmd2process *entry = (struct cmd2process *)subprocess;
759 return subprocess_handshake(subprocess, "git-filter", versions, NULL,
760 capabilities,
761 &entry->supported_capabilities);
764 static void handle_filter_error(const struct strbuf *filter_status,
765 struct cmd2process *entry,
766 const unsigned int wanted_capability)
768 if (!strcmp(filter_status->buf, "error"))
769 ; /* The filter signaled a problem with the file. */
770 else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
772 * The filter signaled a permanent problem. Don't try to filter
773 * files with the same command for the lifetime of the current
774 * Git process.
776 entry->supported_capabilities &= ~wanted_capability;
777 } else {
779 * Something went wrong with the protocol filter.
780 * Force shutdown and restart if another blob requires filtering.
782 error(_("external filter '%s' failed"), entry->subprocess.cmd);
783 subprocess_stop(&subprocess_map, &entry->subprocess);
784 free(entry);
788 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
789 int fd, struct strbuf *dst, const char *cmd,
790 const unsigned int wanted_capability,
791 const struct checkout_metadata *meta,
792 struct delayed_checkout *dco)
794 int err;
795 int can_delay = 0;
796 struct cmd2process *entry;
797 struct child_process *process;
798 struct strbuf nbuf = STRBUF_INIT;
799 struct strbuf filter_status = STRBUF_INIT;
800 const char *filter_type;
802 if (!subprocess_map_initialized) {
803 subprocess_map_initialized = 1;
804 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
805 entry = NULL;
806 } else {
807 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
810 fflush(NULL);
812 if (!entry) {
813 entry = xmalloc(sizeof(*entry));
814 entry->supported_capabilities = 0;
816 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
817 free(entry);
818 return 0;
821 process = &entry->subprocess.process;
823 if (!(entry->supported_capabilities & wanted_capability))
824 return 0;
826 if (wanted_capability & CAP_CLEAN)
827 filter_type = "clean";
828 else if (wanted_capability & CAP_SMUDGE)
829 filter_type = "smudge";
830 else
831 die(_("unexpected filter type"));
833 sigchain_push(SIGPIPE, SIG_IGN);
835 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
836 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
837 if (err)
838 goto done;
840 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
841 if (err) {
842 error(_("path name too long for external filter"));
843 goto done;
846 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
847 if (err)
848 goto done;
850 if (meta && meta->refname) {
851 err = packet_write_fmt_gently(process->in, "ref=%s\n", meta->refname);
852 if (err)
853 goto done;
856 if (meta && !is_null_oid(&meta->treeish)) {
857 err = packet_write_fmt_gently(process->in, "treeish=%s\n", oid_to_hex(&meta->treeish));
858 if (err)
859 goto done;
862 if (meta && !is_null_oid(&meta->blob)) {
863 err = packet_write_fmt_gently(process->in, "blob=%s\n", oid_to_hex(&meta->blob));
864 if (err)
865 goto done;
868 if ((entry->supported_capabilities & CAP_DELAY) &&
869 dco && dco->state == CE_CAN_DELAY) {
870 can_delay = 1;
871 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
872 if (err)
873 goto done;
876 err = packet_flush_gently(process->in);
877 if (err)
878 goto done;
880 if (fd >= 0)
881 err = write_packetized_from_fd_no_flush(fd, process->in);
882 else
883 err = write_packetized_from_buf_no_flush(src, len, process->in);
884 if (err)
885 goto done;
887 err = packet_flush_gently(process->in);
888 if (err)
889 goto done;
891 err = subprocess_read_status(process->out, &filter_status);
892 if (err)
893 goto done;
895 if (can_delay && !strcmp(filter_status.buf, "delayed")) {
896 string_list_insert(&dco->filters, cmd);
897 string_list_insert(&dco->paths, path);
898 } else {
899 /* The filter got the blob and wants to send us a response. */
900 err = strcmp(filter_status.buf, "success");
901 if (err)
902 goto done;
904 err = read_packetized_to_strbuf(process->out, &nbuf,
905 PACKET_READ_GENTLE_ON_EOF) < 0;
906 if (err)
907 goto done;
909 err = subprocess_read_status(process->out, &filter_status);
910 if (err)
911 goto done;
913 err = strcmp(filter_status.buf, "success");
916 done:
917 sigchain_pop(SIGPIPE);
919 if (err)
920 handle_filter_error(&filter_status, entry, wanted_capability);
921 else
922 strbuf_swap(dst, &nbuf);
923 strbuf_release(&nbuf);
924 strbuf_release(&filter_status);
925 return !err;
929 int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
931 int err;
932 char *line;
933 struct cmd2process *entry;
934 struct child_process *process;
935 struct strbuf filter_status = STRBUF_INIT;
937 assert(subprocess_map_initialized);
938 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
939 if (!entry) {
940 error(_("external filter '%s' is not available anymore although "
941 "not all paths have been filtered"), cmd);
942 return 0;
944 process = &entry->subprocess.process;
945 sigchain_push(SIGPIPE, SIG_IGN);
947 err = packet_write_fmt_gently(
948 process->in, "command=list_available_blobs\n");
949 if (err)
950 goto done;
952 err = packet_flush_gently(process->in);
953 if (err)
954 goto done;
956 while ((line = packet_read_line(process->out, NULL))) {
957 const char *path;
958 if (skip_prefix(line, "pathname=", &path))
959 string_list_insert(available_paths, xstrdup(path));
960 else
961 ; /* ignore unknown keys */
964 err = subprocess_read_status(process->out, &filter_status);
965 if (err)
966 goto done;
968 err = strcmp(filter_status.buf, "success");
970 done:
971 sigchain_pop(SIGPIPE);
973 if (err)
974 handle_filter_error(&filter_status, entry, 0);
975 strbuf_release(&filter_status);
976 return !err;
979 static struct convert_driver {
980 const char *name;
981 struct convert_driver *next;
982 const char *smudge;
983 const char *clean;
984 const char *process;
985 int required;
986 } *user_convert, **user_convert_tail;
988 static int apply_filter(const char *path, const char *src, size_t len,
989 int fd, struct strbuf *dst, struct convert_driver *drv,
990 const unsigned int wanted_capability,
991 const struct checkout_metadata *meta,
992 struct delayed_checkout *dco)
994 const char *cmd = NULL;
996 if (!drv)
997 return 0;
999 if (!dst)
1000 return 1;
1002 if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
1003 cmd = drv->clean;
1004 else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
1005 cmd = drv->smudge;
1007 if (cmd && *cmd)
1008 return apply_single_file_filter(path, src, len, fd, dst, cmd);
1009 else if (drv->process && *drv->process)
1010 return apply_multi_file_filter(path, src, len, fd, dst,
1011 drv->process, wanted_capability, meta, dco);
1013 return 0;
1016 static int read_convert_config(const char *var, const char *value, void *cb UNUSED)
1018 const char *key, *name;
1019 size_t namelen;
1020 struct convert_driver *drv;
1023 * External conversion drivers are configured using
1024 * "filter.<name>.variable".
1026 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
1027 return 0;
1028 for (drv = user_convert; drv; drv = drv->next)
1029 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
1030 break;
1031 if (!drv) {
1032 CALLOC_ARRAY(drv, 1);
1033 drv->name = xmemdupz(name, namelen);
1034 *user_convert_tail = drv;
1035 user_convert_tail = &(drv->next);
1039 * filter.<name>.smudge and filter.<name>.clean specifies
1040 * the command line:
1042 * command-line
1044 * The command-line will not be interpolated in any way.
1047 if (!strcmp("smudge", key))
1048 return git_config_string(&drv->smudge, var, value);
1050 if (!strcmp("clean", key))
1051 return git_config_string(&drv->clean, var, value);
1053 if (!strcmp("process", key))
1054 return git_config_string(&drv->process, var, value);
1056 if (!strcmp("required", key)) {
1057 drv->required = git_config_bool(var, value);
1058 return 0;
1061 return 0;
1064 static int count_ident(const char *cp, unsigned long size)
1067 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
1069 int cnt = 0;
1070 char ch;
1072 while (size) {
1073 ch = *cp++;
1074 size--;
1075 if (ch != '$')
1076 continue;
1077 if (size < 3)
1078 break;
1079 if (memcmp("Id", cp, 2))
1080 continue;
1081 ch = cp[2];
1082 cp += 3;
1083 size -= 3;
1084 if (ch == '$')
1085 cnt++; /* $Id$ */
1086 if (ch != ':')
1087 continue;
1090 * "$Id: ... "; scan up to the closing dollar sign and discard.
1092 while (size) {
1093 ch = *cp++;
1094 size--;
1095 if (ch == '$') {
1096 cnt++;
1097 break;
1099 if (ch == '\n')
1100 break;
1103 return cnt;
1106 static int ident_to_git(const char *src, size_t len,
1107 struct strbuf *buf, int ident)
1109 char *dst, *dollar;
1111 if (!ident || (src && !count_ident(src, len)))
1112 return 0;
1114 if (!buf)
1115 return 1;
1117 /* only grow if not in place */
1118 if (strbuf_avail(buf) + buf->len < len)
1119 strbuf_grow(buf, len - buf->len);
1120 dst = buf->buf;
1121 for (;;) {
1122 dollar = memchr(src, '$', len);
1123 if (!dollar)
1124 break;
1125 memmove(dst, src, dollar + 1 - src);
1126 dst += dollar + 1 - src;
1127 len -= dollar + 1 - src;
1128 src = dollar + 1;
1130 if (len > 3 && !memcmp(src, "Id:", 3)) {
1131 dollar = memchr(src + 3, '$', len - 3);
1132 if (!dollar)
1133 break;
1134 if (memchr(src + 3, '\n', dollar - src - 3)) {
1135 /* Line break before the next dollar. */
1136 continue;
1139 memcpy(dst, "Id$", 3);
1140 dst += 3;
1141 len -= dollar + 1 - src;
1142 src = dollar + 1;
1145 memmove(dst, src, len);
1146 strbuf_setlen(buf, dst + len - buf->buf);
1147 return 1;
1150 static int ident_to_worktree(const char *src, size_t len,
1151 struct strbuf *buf, int ident)
1153 struct object_id oid;
1154 char *to_free = NULL, *dollar, *spc;
1155 int cnt;
1157 if (!ident)
1158 return 0;
1160 cnt = count_ident(src, len);
1161 if (!cnt)
1162 return 0;
1164 /* are we "faking" in place editing ? */
1165 if (src == buf->buf)
1166 to_free = strbuf_detach(buf, NULL);
1167 hash_object_file(the_hash_algo, src, len, OBJ_BLOB, &oid);
1169 strbuf_grow(buf, len + cnt * (the_hash_algo->hexsz + 3));
1170 for (;;) {
1171 /* step 1: run to the next '$' */
1172 dollar = memchr(src, '$', len);
1173 if (!dollar)
1174 break;
1175 strbuf_add(buf, src, dollar + 1 - src);
1176 len -= dollar + 1 - src;
1177 src = dollar + 1;
1179 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1180 if (len < 3 || memcmp("Id", src, 2))
1181 continue;
1183 /* step 3: skip over Id$ or Id:xxxxx$ */
1184 if (src[2] == '$') {
1185 src += 3;
1186 len -= 3;
1187 } else if (src[2] == ':') {
1189 * It's possible that an expanded Id has crept its way into the
1190 * repository, we cope with that by stripping the expansion out.
1191 * This is probably not a good idea, since it will cause changes
1192 * on checkout, which won't go away by stash, but let's keep it
1193 * for git-style ids.
1195 dollar = memchr(src + 3, '$', len - 3);
1196 if (!dollar) {
1197 /* incomplete keyword, no more '$', so just quit the loop */
1198 break;
1201 if (memchr(src + 3, '\n', dollar - src - 3)) {
1202 /* Line break before the next dollar. */
1203 continue;
1206 spc = memchr(src + 4, ' ', dollar - src - 4);
1207 if (spc && spc < dollar-1) {
1208 /* There are spaces in unexpected places.
1209 * This is probably an id from some other
1210 * versioning system. Keep it for now.
1212 continue;
1215 len -= dollar + 1 - src;
1216 src = dollar + 1;
1217 } else {
1218 /* it wasn't a "Id$" or "Id:xxxx$" */
1219 continue;
1222 /* step 4: substitute */
1223 strbuf_addstr(buf, "Id: ");
1224 strbuf_addstr(buf, oid_to_hex(&oid));
1225 strbuf_addstr(buf, " $");
1227 strbuf_add(buf, src, len);
1229 free(to_free);
1230 return 1;
1233 static const char *git_path_check_encoding(struct attr_check_item *check)
1235 const char *value = check->value;
1237 if (ATTR_UNSET(value) || !strlen(value))
1238 return NULL;
1240 if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
1241 die(_("true/false are no valid working-tree-encodings"));
1244 /* Don't encode to the default encoding */
1245 if (same_encoding(value, default_encoding))
1246 return NULL;
1248 return value;
1251 static enum convert_crlf_action git_path_check_crlf(struct attr_check_item *check)
1253 const char *value = check->value;
1255 if (ATTR_TRUE(value))
1256 return CRLF_TEXT;
1257 else if (ATTR_FALSE(value))
1258 return CRLF_BINARY;
1259 else if (ATTR_UNSET(value))
1261 else if (!strcmp(value, "input"))
1262 return CRLF_TEXT_INPUT;
1263 else if (!strcmp(value, "auto"))
1264 return CRLF_AUTO;
1265 return CRLF_UNDEFINED;
1268 static enum eol git_path_check_eol(struct attr_check_item *check)
1270 const char *value = check->value;
1272 if (ATTR_UNSET(value))
1274 else if (!strcmp(value, "lf"))
1275 return EOL_LF;
1276 else if (!strcmp(value, "crlf"))
1277 return EOL_CRLF;
1278 return EOL_UNSET;
1281 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
1283 const char *value = check->value;
1284 struct convert_driver *drv;
1286 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1287 return NULL;
1288 for (drv = user_convert; drv; drv = drv->next)
1289 if (!strcmp(value, drv->name))
1290 return drv;
1291 return NULL;
1294 static int git_path_check_ident(struct attr_check_item *check)
1296 const char *value = check->value;
1298 return !!ATTR_TRUE(value);
1301 static struct attr_check *check;
1303 void convert_attrs(struct index_state *istate,
1304 struct conv_attrs *ca, const char *path)
1306 struct attr_check_item *ccheck = NULL;
1308 if (!check) {
1309 check = attr_check_initl("crlf", "ident", "filter",
1310 "eol", "text", "working-tree-encoding",
1311 NULL);
1312 user_convert_tail = &user_convert;
1313 git_config(read_convert_config, NULL);
1316 git_check_attr(istate, path, check);
1317 ccheck = check->items;
1318 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1319 if (ca->crlf_action == CRLF_UNDEFINED)
1320 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1321 ca->ident = git_path_check_ident(ccheck + 1);
1322 ca->drv = git_path_check_convert(ccheck + 2);
1323 if (ca->crlf_action != CRLF_BINARY) {
1324 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1325 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1326 ca->crlf_action = CRLF_AUTO_INPUT;
1327 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1328 ca->crlf_action = CRLF_AUTO_CRLF;
1329 else if (eol_attr == EOL_LF)
1330 ca->crlf_action = CRLF_TEXT_INPUT;
1331 else if (eol_attr == EOL_CRLF)
1332 ca->crlf_action = CRLF_TEXT_CRLF;
1334 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
1336 /* Save attr and make a decision for action */
1337 ca->attr_action = ca->crlf_action;
1338 if (ca->crlf_action == CRLF_TEXT)
1339 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1340 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1341 ca->crlf_action = CRLF_BINARY;
1342 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1343 ca->crlf_action = CRLF_AUTO_CRLF;
1344 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1345 ca->crlf_action = CRLF_AUTO_INPUT;
1348 void reset_parsed_attributes(void)
1350 struct convert_driver *drv, *next;
1352 attr_check_free(check);
1353 check = NULL;
1354 reset_merge_attributes();
1356 for (drv = user_convert; drv; drv = next) {
1357 next = drv->next;
1358 free((void *)drv->name);
1359 free(drv);
1361 user_convert = NULL;
1362 user_convert_tail = NULL;
1365 int would_convert_to_git_filter_fd(struct index_state *istate, const char *path)
1367 struct conv_attrs ca;
1369 convert_attrs(istate, &ca, path);
1370 if (!ca.drv)
1371 return 0;
1374 * Apply a filter to an fd only if the filter is required to succeed.
1375 * We must die if the filter fails, because the original data before
1376 * filtering is not available.
1378 if (!ca.drv->required)
1379 return 0;
1381 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL, NULL);
1384 const char *get_convert_attr_ascii(struct index_state *istate, const char *path)
1386 struct conv_attrs ca;
1388 convert_attrs(istate, &ca, path);
1389 switch (ca.attr_action) {
1390 case CRLF_UNDEFINED:
1391 return "";
1392 case CRLF_BINARY:
1393 return "-text";
1394 case CRLF_TEXT:
1395 return "text";
1396 case CRLF_TEXT_INPUT:
1397 return "text eol=lf";
1398 case CRLF_TEXT_CRLF:
1399 return "text eol=crlf";
1400 case CRLF_AUTO:
1401 return "text=auto";
1402 case CRLF_AUTO_CRLF:
1403 return "text=auto eol=crlf";
1404 case CRLF_AUTO_INPUT:
1405 return "text=auto eol=lf";
1407 return "";
1410 int convert_to_git(struct index_state *istate,
1411 const char *path, const char *src, size_t len,
1412 struct strbuf *dst, int conv_flags)
1414 int ret = 0;
1415 struct conv_attrs ca;
1417 convert_attrs(istate, &ca, path);
1419 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL, NULL);
1420 if (!ret && ca.drv && ca.drv->required)
1421 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
1423 if (ret && dst) {
1424 src = dst->buf;
1425 len = dst->len;
1428 ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1429 if (ret && dst) {
1430 src = dst->buf;
1431 len = dst->len;
1434 if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1435 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
1436 if (ret && dst) {
1437 src = dst->buf;
1438 len = dst->len;
1441 return ret | ident_to_git(src, len, dst, ca.ident);
1444 void convert_to_git_filter_fd(struct index_state *istate,
1445 const char *path, int fd, struct strbuf *dst,
1446 int conv_flags)
1448 struct conv_attrs ca;
1449 convert_attrs(istate, &ca, path);
1451 assert(ca.drv);
1453 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL, NULL))
1454 die(_("%s: clean filter '%s' failed"), path, ca.drv->name);
1456 encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
1457 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
1458 ident_to_git(dst->buf, dst->len, dst, ca.ident);
1461 static int convert_to_working_tree_ca_internal(const struct conv_attrs *ca,
1462 const char *path, const char *src,
1463 size_t len, struct strbuf *dst,
1464 int normalizing,
1465 const struct checkout_metadata *meta,
1466 struct delayed_checkout *dco)
1468 int ret = 0, ret_filter = 0;
1470 ret |= ident_to_worktree(src, len, dst, ca->ident);
1471 if (ret) {
1472 src = dst->buf;
1473 len = dst->len;
1476 * CRLF conversion can be skipped if normalizing, unless there
1477 * is a smudge or process filter (even if the process filter doesn't
1478 * support smudge). The filters might expect CRLFs.
1480 if ((ca->drv && (ca->drv->smudge || ca->drv->process)) || !normalizing) {
1481 ret |= crlf_to_worktree(src, len, dst, ca->crlf_action);
1482 if (ret) {
1483 src = dst->buf;
1484 len = dst->len;
1488 ret |= encode_to_worktree(path, src, len, dst, ca->working_tree_encoding);
1489 if (ret) {
1490 src = dst->buf;
1491 len = dst->len;
1494 ret_filter = apply_filter(
1495 path, src, len, -1, dst, ca->drv, CAP_SMUDGE, meta, dco);
1496 if (!ret_filter && ca->drv && ca->drv->required)
1497 die(_("%s: smudge filter %s failed"), path, ca->drv->name);
1499 return ret | ret_filter;
1502 int async_convert_to_working_tree_ca(const struct conv_attrs *ca,
1503 const char *path, const char *src,
1504 size_t len, struct strbuf *dst,
1505 const struct checkout_metadata *meta,
1506 void *dco)
1508 return convert_to_working_tree_ca_internal(ca, path, src, len, dst, 0,
1509 meta, dco);
1512 int convert_to_working_tree_ca(const struct conv_attrs *ca,
1513 const char *path, const char *src,
1514 size_t len, struct strbuf *dst,
1515 const struct checkout_metadata *meta)
1517 return convert_to_working_tree_ca_internal(ca, path, src, len, dst, 0,
1518 meta, NULL);
1521 int renormalize_buffer(struct index_state *istate, const char *path,
1522 const char *src, size_t len, struct strbuf *dst)
1524 struct conv_attrs ca;
1525 int ret;
1527 convert_attrs(istate, &ca, path);
1528 ret = convert_to_working_tree_ca_internal(&ca, path, src, len, dst, 1,
1529 NULL, NULL);
1530 if (ret) {
1531 src = dst->buf;
1532 len = dst->len;
1534 return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
1537 /*****************************************************************
1539 * Streaming conversion support
1541 *****************************************************************/
1543 typedef int (*filter_fn)(struct stream_filter *,
1544 const char *input, size_t *isize_p,
1545 char *output, size_t *osize_p);
1546 typedef void (*free_fn)(struct stream_filter *);
1548 struct stream_filter_vtbl {
1549 filter_fn filter;
1550 free_fn free;
1553 struct stream_filter {
1554 struct stream_filter_vtbl *vtbl;
1557 static int null_filter_fn(struct stream_filter *filter UNUSED,
1558 const char *input, size_t *isize_p,
1559 char *output, size_t *osize_p)
1561 size_t count;
1563 if (!input)
1564 return 0; /* we do not keep any states */
1565 count = *isize_p;
1566 if (*osize_p < count)
1567 count = *osize_p;
1568 if (count) {
1569 memmove(output, input, count);
1570 *isize_p -= count;
1571 *osize_p -= count;
1573 return 0;
1576 static void null_free_fn(struct stream_filter *filter UNUSED)
1578 ; /* nothing -- null instances are shared */
1581 static struct stream_filter_vtbl null_vtbl = {
1582 .filter = null_filter_fn,
1583 .free = null_free_fn,
1586 static struct stream_filter null_filter_singleton = {
1587 .vtbl = &null_vtbl,
1590 int is_null_stream_filter(struct stream_filter *filter)
1592 return filter == &null_filter_singleton;
1597 * LF-to-CRLF filter
1600 struct lf_to_crlf_filter {
1601 struct stream_filter filter;
1602 unsigned has_held:1;
1603 char held;
1606 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1607 const char *input, size_t *isize_p,
1608 char *output, size_t *osize_p)
1610 size_t count, o = 0;
1611 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1614 * We may be holding onto the CR to see if it is followed by a
1615 * LF, in which case we would need to go to the main loop.
1616 * Otherwise, just emit it to the output stream.
1618 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1619 output[o++] = lf_to_crlf->held;
1620 lf_to_crlf->has_held = 0;
1623 /* We are told to drain */
1624 if (!input) {
1625 *osize_p -= o;
1626 return 0;
1629 count = *isize_p;
1630 if (count || lf_to_crlf->has_held) {
1631 size_t i;
1632 int was_cr = 0;
1634 if (lf_to_crlf->has_held) {
1635 was_cr = 1;
1636 lf_to_crlf->has_held = 0;
1639 for (i = 0; o < *osize_p && i < count; i++) {
1640 char ch = input[i];
1642 if (ch == '\n') {
1643 output[o++] = '\r';
1644 } else if (was_cr) {
1646 * Previous round saw CR and it is not followed
1647 * by a LF; emit the CR before processing the
1648 * current character.
1650 output[o++] = '\r';
1654 * We may have consumed the last output slot,
1655 * in which case we need to break out of this
1656 * loop; hold the current character before
1657 * returning.
1659 if (*osize_p <= o) {
1660 lf_to_crlf->has_held = 1;
1661 lf_to_crlf->held = ch;
1662 continue; /* break but increment i */
1665 if (ch == '\r') {
1666 was_cr = 1;
1667 continue;
1670 was_cr = 0;
1671 output[o++] = ch;
1674 *osize_p -= o;
1675 *isize_p -= i;
1677 if (!lf_to_crlf->has_held && was_cr) {
1678 lf_to_crlf->has_held = 1;
1679 lf_to_crlf->held = '\r';
1682 return 0;
1685 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1687 free(filter);
1690 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1691 .filter = lf_to_crlf_filter_fn,
1692 .free = lf_to_crlf_free_fn,
1695 static struct stream_filter *lf_to_crlf_filter(void)
1697 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1699 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1700 return (struct stream_filter *)lf_to_crlf;
1704 * Cascade filter
1706 #define FILTER_BUFFER 1024
1707 struct cascade_filter {
1708 struct stream_filter filter;
1709 struct stream_filter *one;
1710 struct stream_filter *two;
1711 char buf[FILTER_BUFFER];
1712 int end, ptr;
1715 static int cascade_filter_fn(struct stream_filter *filter,
1716 const char *input, size_t *isize_p,
1717 char *output, size_t *osize_p)
1719 struct cascade_filter *cas = (struct cascade_filter *) filter;
1720 size_t filled = 0;
1721 size_t sz = *osize_p;
1722 size_t to_feed, remaining;
1725 * input -- (one) --> buf -- (two) --> output
1727 while (filled < sz) {
1728 remaining = sz - filled;
1730 /* do we already have something to feed two with? */
1731 if (cas->ptr < cas->end) {
1732 to_feed = cas->end - cas->ptr;
1733 if (stream_filter(cas->two,
1734 cas->buf + cas->ptr, &to_feed,
1735 output + filled, &remaining))
1736 return -1;
1737 cas->ptr += (cas->end - cas->ptr) - to_feed;
1738 filled = sz - remaining;
1739 continue;
1742 /* feed one from upstream and have it emit into our buffer */
1743 to_feed = input ? *isize_p : 0;
1744 if (input && !to_feed)
1745 break;
1746 remaining = sizeof(cas->buf);
1747 if (stream_filter(cas->one,
1748 input, &to_feed,
1749 cas->buf, &remaining))
1750 return -1;
1751 cas->end = sizeof(cas->buf) - remaining;
1752 cas->ptr = 0;
1753 if (input) {
1754 size_t fed = *isize_p - to_feed;
1755 *isize_p -= fed;
1756 input += fed;
1759 /* do we know that we drained one completely? */
1760 if (input || cas->end)
1761 continue;
1763 /* tell two to drain; we have nothing more to give it */
1764 to_feed = 0;
1765 remaining = sz - filled;
1766 if (stream_filter(cas->two,
1767 NULL, &to_feed,
1768 output + filled, &remaining))
1769 return -1;
1770 if (remaining == (sz - filled))
1771 break; /* completely drained two */
1772 filled = sz - remaining;
1774 *osize_p -= filled;
1775 return 0;
1778 static void cascade_free_fn(struct stream_filter *filter)
1780 struct cascade_filter *cas = (struct cascade_filter *)filter;
1781 free_stream_filter(cas->one);
1782 free_stream_filter(cas->two);
1783 free(filter);
1786 static struct stream_filter_vtbl cascade_vtbl = {
1787 .filter = cascade_filter_fn,
1788 .free = cascade_free_fn,
1791 static struct stream_filter *cascade_filter(struct stream_filter *one,
1792 struct stream_filter *two)
1794 struct cascade_filter *cascade;
1796 if (!one || is_null_stream_filter(one))
1797 return two;
1798 if (!two || is_null_stream_filter(two))
1799 return one;
1801 cascade = xmalloc(sizeof(*cascade));
1802 cascade->one = one;
1803 cascade->two = two;
1804 cascade->end = cascade->ptr = 0;
1805 cascade->filter.vtbl = &cascade_vtbl;
1806 return (struct stream_filter *)cascade;
1810 * ident filter
1812 #define IDENT_DRAINING (-1)
1813 #define IDENT_SKIPPING (-2)
1814 struct ident_filter {
1815 struct stream_filter filter;
1816 struct strbuf left;
1817 int state;
1818 char ident[GIT_MAX_HEXSZ + 5]; /* ": x40 $" */
1821 static int is_foreign_ident(const char *str)
1823 int i;
1825 if (!skip_prefix(str, "$Id: ", &str))
1826 return 0;
1827 for (i = 0; str[i]; i++) {
1828 if (isspace(str[i]) && str[i+1] != '$')
1829 return 1;
1831 return 0;
1834 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1836 size_t to_drain = ident->left.len;
1838 if (*osize_p < to_drain)
1839 to_drain = *osize_p;
1840 if (to_drain) {
1841 memcpy(*output_p, ident->left.buf, to_drain);
1842 strbuf_remove(&ident->left, 0, to_drain);
1843 *output_p += to_drain;
1844 *osize_p -= to_drain;
1846 if (!ident->left.len)
1847 ident->state = 0;
1850 static int ident_filter_fn(struct stream_filter *filter,
1851 const char *input, size_t *isize_p,
1852 char *output, size_t *osize_p)
1854 struct ident_filter *ident = (struct ident_filter *)filter;
1855 static const char head[] = "$Id";
1857 if (!input) {
1858 /* drain upon eof */
1859 switch (ident->state) {
1860 default:
1861 strbuf_add(&ident->left, head, ident->state);
1862 /* fallthrough */
1863 case IDENT_SKIPPING:
1864 /* fallthrough */
1865 case IDENT_DRAINING:
1866 ident_drain(ident, &output, osize_p);
1868 return 0;
1871 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1872 int ch;
1874 if (ident->state == IDENT_DRAINING) {
1875 ident_drain(ident, &output, osize_p);
1876 if (!*osize_p)
1877 break;
1878 continue;
1881 ch = *(input++);
1882 (*isize_p)--;
1884 if (ident->state == IDENT_SKIPPING) {
1886 * Skipping until '$' or LF, but keeping them
1887 * in case it is a foreign ident.
1889 strbuf_addch(&ident->left, ch);
1890 if (ch != '\n' && ch != '$')
1891 continue;
1892 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1893 strbuf_setlen(&ident->left, sizeof(head) - 1);
1894 strbuf_addstr(&ident->left, ident->ident);
1896 ident->state = IDENT_DRAINING;
1897 continue;
1900 if (ident->state < sizeof(head) &&
1901 head[ident->state] == ch) {
1902 ident->state++;
1903 continue;
1906 if (ident->state)
1907 strbuf_add(&ident->left, head, ident->state);
1908 if (ident->state == sizeof(head) - 1) {
1909 if (ch != ':' && ch != '$') {
1910 strbuf_addch(&ident->left, ch);
1911 ident->state = 0;
1912 continue;
1915 if (ch == ':') {
1916 strbuf_addch(&ident->left, ch);
1917 ident->state = IDENT_SKIPPING;
1918 } else {
1919 strbuf_addstr(&ident->left, ident->ident);
1920 ident->state = IDENT_DRAINING;
1922 continue;
1925 strbuf_addch(&ident->left, ch);
1926 ident->state = IDENT_DRAINING;
1928 return 0;
1931 static void ident_free_fn(struct stream_filter *filter)
1933 struct ident_filter *ident = (struct ident_filter *)filter;
1934 strbuf_release(&ident->left);
1935 free(filter);
1938 static struct stream_filter_vtbl ident_vtbl = {
1939 .filter = ident_filter_fn,
1940 .free = ident_free_fn,
1943 static struct stream_filter *ident_filter(const struct object_id *oid)
1945 struct ident_filter *ident = xmalloc(sizeof(*ident));
1947 xsnprintf(ident->ident, sizeof(ident->ident),
1948 ": %s $", oid_to_hex(oid));
1949 strbuf_init(&ident->left, 0);
1950 ident->filter.vtbl = &ident_vtbl;
1951 ident->state = 0;
1952 return (struct stream_filter *)ident;
1956 * Return an appropriately constructed filter for the given ca, or NULL if
1957 * the contents cannot be filtered without reading the whole thing
1958 * in-core.
1960 * Note that you would be crazy to set CRLF, smudge/clean or ident to a
1961 * large binary blob you would want us not to slurp into the memory!
1963 struct stream_filter *get_stream_filter_ca(const struct conv_attrs *ca,
1964 const struct object_id *oid)
1966 struct stream_filter *filter = NULL;
1968 if (classify_conv_attrs(ca) != CA_CLASS_STREAMABLE)
1969 return NULL;
1971 if (ca->ident)
1972 filter = ident_filter(oid);
1974 if (output_eol(ca->crlf_action) == EOL_CRLF)
1975 filter = cascade_filter(filter, lf_to_crlf_filter());
1976 else
1977 filter = cascade_filter(filter, &null_filter_singleton);
1979 return filter;
1982 struct stream_filter *get_stream_filter(struct index_state *istate,
1983 const char *path,
1984 const struct object_id *oid)
1986 struct conv_attrs ca;
1987 convert_attrs(istate, &ca, path);
1988 return get_stream_filter_ca(&ca, oid);
1991 void free_stream_filter(struct stream_filter *filter)
1993 filter->vtbl->free(filter);
1996 int stream_filter(struct stream_filter *filter,
1997 const char *input, size_t *isize_p,
1998 char *output, size_t *osize_p)
2000 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
2003 void init_checkout_metadata(struct checkout_metadata *meta, const char *refname,
2004 const struct object_id *treeish,
2005 const struct object_id *blob)
2007 memset(meta, 0, sizeof(*meta));
2008 if (refname)
2009 meta->refname = refname;
2010 if (treeish)
2011 oidcpy(&meta->treeish, treeish);
2012 if (blob)
2013 oidcpy(&meta->blob, blob);
2016 void clone_checkout_metadata(struct checkout_metadata *dst,
2017 const struct checkout_metadata *src,
2018 const struct object_id *blob)
2020 memcpy(dst, src, sizeof(*dst));
2021 if (blob)
2022 oidcpy(&dst->blob, blob);
2025 enum conv_attrs_classification classify_conv_attrs(const struct conv_attrs *ca)
2027 if (ca->drv) {
2028 if (ca->drv->process)
2029 return CA_CLASS_INCORE_PROCESS;
2030 if (ca->drv->smudge || ca->drv->clean)
2031 return CA_CLASS_INCORE_FILTER;
2034 if (ca->working_tree_encoding)
2035 return CA_CLASS_INCORE;
2037 if (ca->crlf_action == CRLF_AUTO || ca->crlf_action == CRLF_AUTO_CRLF)
2038 return CA_CLASS_INCORE;
2040 return CA_CLASS_STREAMABLE;