convert.c: remove duplicate code
[alt-git.git] / convert.c
blob5b164baf241f022bd21133159c8a05a21dd91b97
1 #include "cache.h"
2 #include "attr.h"
3 #include "run-command.h"
4 #include "quote.h"
5 #include "sigchain.h"
7 /*
8 * convert.c - convert a file when checking it out and checking it in.
10 * This should use the pathname to decide on whether it wants to do some
11 * more interesting conversions (automatic gzip/unzip, general format
12 * conversions etc etc), but by default it just does automatic CRLF<->LF
13 * translation when the "text" attribute or "auto_crlf" option is set.
16 enum crlf_action {
17 CRLF_GUESS = -1,
18 CRLF_BINARY = 0,
19 CRLF_TEXT,
20 CRLF_INPUT,
21 CRLF_CRLF,
22 CRLF_AUTO
25 struct text_stat {
26 /* NUL, CR, LF and CRLF counts */
27 unsigned nul, cr, lf, crlf;
29 /* These are just approximations! */
30 unsigned printable, nonprintable;
33 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
35 unsigned long i;
37 memset(stats, 0, sizeof(*stats));
39 for (i = 0; i < size; i++) {
40 unsigned char c = buf[i];
41 if (c == '\r') {
42 stats->cr++;
43 if (i+1 < size && buf[i+1] == '\n')
44 stats->crlf++;
45 continue;
47 if (c == '\n') {
48 stats->lf++;
49 continue;
51 if (c == 127)
52 /* DEL */
53 stats->nonprintable++;
54 else if (c < 32) {
55 switch (c) {
56 /* BS, HT, ESC and FF */
57 case '\b': case '\t': case '\033': case '\014':
58 stats->printable++;
59 break;
60 case 0:
61 stats->nul++;
62 /* fall through */
63 default:
64 stats->nonprintable++;
67 else
68 stats->printable++;
71 /* If file ends with EOF then don't count this EOF as non-printable. */
72 if (size >= 1 && buf[size-1] == '\032')
73 stats->nonprintable--;
77 * The same heuristics as diff.c::mmfile_is_binary()
79 static int is_binary(unsigned long size, struct text_stat *stats)
82 if (stats->nul)
83 return 1;
84 if ((stats->printable >> 7) < stats->nonprintable)
85 return 1;
87 * Other heuristics? Average line length might be relevant,
88 * as might LF vs CR vs CRLF counts..
90 * NOTE! It might be normal to have a low ratio of CRLF to LF
91 * (somebody starts with a LF-only file and edits it with an editor
92 * that adds CRLF only to lines that are added..). But do we
93 * want to support CR-only? Probably not.
95 return 0;
98 static enum eol output_eol(enum crlf_action crlf_action)
100 switch (crlf_action) {
101 case CRLF_BINARY:
102 return EOL_UNSET;
103 case CRLF_CRLF:
104 return EOL_CRLF;
105 case CRLF_INPUT:
106 return EOL_LF;
107 case CRLF_GUESS:
108 if (!auto_crlf)
109 return EOL_UNSET;
110 /* fall through */
111 case CRLF_TEXT:
112 case CRLF_AUTO:
113 if (auto_crlf == AUTO_CRLF_TRUE)
114 return EOL_CRLF;
115 else if (auto_crlf == AUTO_CRLF_INPUT)
116 return EOL_LF;
117 else if (core_eol == EOL_UNSET)
118 return EOL_NATIVE;
120 return core_eol;
123 static void check_safe_crlf(const char *path, enum crlf_action crlf_action,
124 struct text_stat *stats, enum safe_crlf checksafe)
126 if (!checksafe)
127 return;
129 if (output_eol(crlf_action) == EOL_LF) {
131 * CRLFs would not be restored by checkout:
132 * check if we'd remove CRLFs
134 if (stats->crlf) {
135 if (checksafe == SAFE_CRLF_WARN)
136 warning("CRLF will be replaced by LF in %s.\nThe file will have its original line endings in your working directory.", path);
137 else /* i.e. SAFE_CRLF_FAIL */
138 die("CRLF would be replaced by LF in %s.", path);
140 } else if (output_eol(crlf_action) == EOL_CRLF) {
142 * CRLFs would be added by checkout:
143 * check if we have "naked" LFs
145 if (stats->lf != stats->crlf) {
146 if (checksafe == SAFE_CRLF_WARN)
147 warning("LF will be replaced by CRLF in %s.\nThe file will have its original line endings in your working directory.", path);
148 else /* i.e. SAFE_CRLF_FAIL */
149 die("LF would be replaced by CRLF in %s", path);
154 static int has_cr_in_index(const char *path)
156 unsigned long sz;
157 void *data;
158 int has_cr;
160 data = read_blob_data_from_cache(path, &sz);
161 if (!data)
162 return 0;
163 has_cr = memchr(data, '\r', sz) != NULL;
164 free(data);
165 return has_cr;
168 static int crlf_to_git(const char *path, const char *src, size_t len,
169 struct strbuf *buf,
170 enum crlf_action crlf_action, enum safe_crlf checksafe)
172 struct text_stat stats;
173 char *dst;
175 if (crlf_action == CRLF_BINARY ||
176 (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE) ||
177 (src && !len))
178 return 0;
181 * If we are doing a dry-run and have no source buffer, there is
182 * nothing to analyze; we must assume we would convert.
184 if (!buf && !src)
185 return 1;
187 gather_stats(src, len, &stats);
189 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
191 * We're currently not going to even try to convert stuff
192 * that has bare CR characters. Does anybody do that crazy
193 * stuff?
195 if (stats.cr != stats.crlf)
196 return 0;
199 * And add some heuristics for binary vs text, of course...
201 if (is_binary(len, &stats))
202 return 0;
204 if (crlf_action == CRLF_GUESS) {
206 * If the file in the index has any CR in it, do not convert.
207 * This is the new safer autocrlf handling.
209 if (has_cr_in_index(path))
210 return 0;
214 check_safe_crlf(path, crlf_action, &stats, checksafe);
216 /* Optimization: No CR? Nothing to convert, regardless. */
217 if (!stats.cr)
218 return 0;
221 * At this point all of our source analysis is done, and we are sure we
222 * would convert. If we are in dry-run mode, we can give an answer.
224 if (!buf)
225 return 1;
227 /* only grow if not in place */
228 if (strbuf_avail(buf) + buf->len < len)
229 strbuf_grow(buf, len - buf->len);
230 dst = buf->buf;
231 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
233 * If we guessed, we already know we rejected a file with
234 * lone CR, and we can strip a CR without looking at what
235 * follow it.
237 do {
238 unsigned char c = *src++;
239 if (c != '\r')
240 *dst++ = c;
241 } while (--len);
242 } else {
243 do {
244 unsigned char c = *src++;
245 if (! (c == '\r' && (1 < len && *src == '\n')))
246 *dst++ = c;
247 } while (--len);
249 strbuf_setlen(buf, dst - buf->buf);
250 return 1;
253 static int crlf_to_worktree(const char *path, const char *src, size_t len,
254 struct strbuf *buf, enum crlf_action crlf_action)
256 char *to_free = NULL;
257 struct text_stat stats;
259 if (!len || output_eol(crlf_action) != EOL_CRLF)
260 return 0;
262 gather_stats(src, len, &stats);
264 /* No LF? Nothing to convert, regardless. */
265 if (!stats.lf)
266 return 0;
268 /* Was it already in CRLF format? */
269 if (stats.lf == stats.crlf)
270 return 0;
272 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
273 if (crlf_action == CRLF_GUESS) {
274 /* If we have any CR or CRLF line endings, we do not touch it */
275 /* This is the new safer autocrlf-handling */
276 if (stats.cr > 0 || stats.crlf > 0)
277 return 0;
280 /* If we have any bare CR characters, we're not going to touch it */
281 if (stats.cr != stats.crlf)
282 return 0;
284 if (is_binary(len, &stats))
285 return 0;
288 /* are we "faking" in place editing ? */
289 if (src == buf->buf)
290 to_free = strbuf_detach(buf, NULL);
292 strbuf_grow(buf, len + stats.lf - stats.crlf);
293 for (;;) {
294 const char *nl = memchr(src, '\n', len);
295 if (!nl)
296 break;
297 if (nl > src && nl[-1] == '\r') {
298 strbuf_add(buf, src, nl + 1 - src);
299 } else {
300 strbuf_add(buf, src, nl - src);
301 strbuf_addstr(buf, "\r\n");
303 len -= nl + 1 - src;
304 src = nl + 1;
306 strbuf_add(buf, src, len);
308 free(to_free);
309 return 1;
312 struct filter_params {
313 const char *src;
314 unsigned long size;
315 const char *cmd;
316 const char *path;
319 static int filter_buffer(int in, int out, void *data)
322 * Spawn cmd and feed the buffer contents through its stdin.
324 struct child_process child_process;
325 struct filter_params *params = (struct filter_params *)data;
326 int write_err, status;
327 const char *argv[] = { NULL, NULL };
329 /* apply % substitution to cmd */
330 struct strbuf cmd = STRBUF_INIT;
331 struct strbuf path = STRBUF_INIT;
332 struct strbuf_expand_dict_entry dict[] = {
333 { "f", NULL, },
334 { NULL, NULL, },
337 /* quote the path to preserve spaces, etc. */
338 sq_quote_buf(&path, params->path);
339 dict[0].value = path.buf;
341 /* expand all %f with the quoted path */
342 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
343 strbuf_release(&path);
345 argv[0] = cmd.buf;
347 memset(&child_process, 0, sizeof(child_process));
348 child_process.argv = argv;
349 child_process.use_shell = 1;
350 child_process.in = -1;
351 child_process.out = out;
353 if (start_command(&child_process))
354 return error("cannot fork to run external filter %s", params->cmd);
356 sigchain_push(SIGPIPE, SIG_IGN);
358 write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
359 if (close(child_process.in))
360 write_err = 1;
361 if (write_err)
362 error("cannot feed the input to external filter %s", params->cmd);
364 sigchain_pop(SIGPIPE);
366 status = finish_command(&child_process);
367 if (status)
368 error("external filter %s failed %d", params->cmd, status);
370 strbuf_release(&cmd);
371 return (write_err || status);
374 static int apply_filter(const char *path, const char *src, size_t len,
375 struct strbuf *dst, const char *cmd)
378 * Create a pipeline to have the command filter the buffer's
379 * contents.
381 * (child --> cmd) --> us
383 int ret = 1;
384 struct strbuf nbuf = STRBUF_INIT;
385 struct async async;
386 struct filter_params params;
388 if (!cmd)
389 return 0;
391 if (!dst)
392 return 1;
394 memset(&async, 0, sizeof(async));
395 async.proc = filter_buffer;
396 async.data = &params;
397 async.out = -1;
398 params.src = src;
399 params.size = len;
400 params.cmd = cmd;
401 params.path = path;
403 fflush(NULL);
404 if (start_async(&async))
405 return 0; /* error was already reported */
407 if (strbuf_read(&nbuf, async.out, len) < 0) {
408 error("read from external filter %s failed", cmd);
409 ret = 0;
411 if (close(async.out)) {
412 error("read from external filter %s failed", cmd);
413 ret = 0;
415 if (finish_async(&async)) {
416 error("external filter %s failed", cmd);
417 ret = 0;
420 if (ret) {
421 strbuf_swap(dst, &nbuf);
423 strbuf_release(&nbuf);
424 return ret;
427 static struct convert_driver {
428 const char *name;
429 struct convert_driver *next;
430 const char *smudge;
431 const char *clean;
432 int required;
433 } *user_convert, **user_convert_tail;
435 static int read_convert_config(const char *var, const char *value, void *cb)
437 const char *ep, *name;
438 int namelen;
439 struct convert_driver *drv;
442 * External conversion drivers are configured using
443 * "filter.<name>.variable".
445 if (prefixcmp(var, "filter.") || (ep = strrchr(var, '.')) == var + 6)
446 return 0;
447 name = var + 7;
448 namelen = ep - name;
449 for (drv = user_convert; drv; drv = drv->next)
450 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
451 break;
452 if (!drv) {
453 drv = xcalloc(1, sizeof(struct convert_driver));
454 drv->name = xmemdupz(name, namelen);
455 *user_convert_tail = drv;
456 user_convert_tail = &(drv->next);
459 ep++;
462 * filter.<name>.smudge and filter.<name>.clean specifies
463 * the command line:
465 * command-line
467 * The command-line will not be interpolated in any way.
470 if (!strcmp("smudge", ep))
471 return git_config_string(&drv->smudge, var, value);
473 if (!strcmp("clean", ep))
474 return git_config_string(&drv->clean, var, value);
476 if (!strcmp("required", ep)) {
477 drv->required = git_config_bool(var, value);
478 return 0;
481 return 0;
484 static int count_ident(const char *cp, unsigned long size)
487 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
489 int cnt = 0;
490 char ch;
492 while (size) {
493 ch = *cp++;
494 size--;
495 if (ch != '$')
496 continue;
497 if (size < 3)
498 break;
499 if (memcmp("Id", cp, 2))
500 continue;
501 ch = cp[2];
502 cp += 3;
503 size -= 3;
504 if (ch == '$')
505 cnt++; /* $Id$ */
506 if (ch != ':')
507 continue;
510 * "$Id: ... "; scan up to the closing dollar sign and discard.
512 while (size) {
513 ch = *cp++;
514 size--;
515 if (ch == '$') {
516 cnt++;
517 break;
519 if (ch == '\n')
520 break;
523 return cnt;
526 static int ident_to_git(const char *path, const char *src, size_t len,
527 struct strbuf *buf, int ident)
529 char *dst, *dollar;
531 if (!ident || (src && !count_ident(src, len)))
532 return 0;
534 if (!buf)
535 return 1;
537 /* only grow if not in place */
538 if (strbuf_avail(buf) + buf->len < len)
539 strbuf_grow(buf, len - buf->len);
540 dst = buf->buf;
541 for (;;) {
542 dollar = memchr(src, '$', len);
543 if (!dollar)
544 break;
545 memmove(dst, src, dollar + 1 - src);
546 dst += dollar + 1 - src;
547 len -= dollar + 1 - src;
548 src = dollar + 1;
550 if (len > 3 && !memcmp(src, "Id:", 3)) {
551 dollar = memchr(src + 3, '$', len - 3);
552 if (!dollar)
553 break;
554 if (memchr(src + 3, '\n', dollar - src - 3)) {
555 /* Line break before the next dollar. */
556 continue;
559 memcpy(dst, "Id$", 3);
560 dst += 3;
561 len -= dollar + 1 - src;
562 src = dollar + 1;
565 memmove(dst, src, len);
566 strbuf_setlen(buf, dst + len - buf->buf);
567 return 1;
570 static int ident_to_worktree(const char *path, const char *src, size_t len,
571 struct strbuf *buf, int ident)
573 unsigned char sha1[20];
574 char *to_free = NULL, *dollar, *spc;
575 int cnt;
577 if (!ident)
578 return 0;
580 cnt = count_ident(src, len);
581 if (!cnt)
582 return 0;
584 /* are we "faking" in place editing ? */
585 if (src == buf->buf)
586 to_free = strbuf_detach(buf, NULL);
587 hash_sha1_file(src, len, "blob", sha1);
589 strbuf_grow(buf, len + cnt * 43);
590 for (;;) {
591 /* step 1: run to the next '$' */
592 dollar = memchr(src, '$', len);
593 if (!dollar)
594 break;
595 strbuf_add(buf, src, dollar + 1 - src);
596 len -= dollar + 1 - src;
597 src = dollar + 1;
599 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
600 if (len < 3 || memcmp("Id", src, 2))
601 continue;
603 /* step 3: skip over Id$ or Id:xxxxx$ */
604 if (src[2] == '$') {
605 src += 3;
606 len -= 3;
607 } else if (src[2] == ':') {
609 * It's possible that an expanded Id has crept its way into the
610 * repository, we cope with that by stripping the expansion out.
611 * This is probably not a good idea, since it will cause changes
612 * on checkout, which won't go away by stash, but let's keep it
613 * for git-style ids.
615 dollar = memchr(src + 3, '$', len - 3);
616 if (!dollar) {
617 /* incomplete keyword, no more '$', so just quit the loop */
618 break;
621 if (memchr(src + 3, '\n', dollar - src - 3)) {
622 /* Line break before the next dollar. */
623 continue;
626 spc = memchr(src + 4, ' ', dollar - src - 4);
627 if (spc && spc < dollar-1) {
628 /* There are spaces in unexpected places.
629 * This is probably an id from some other
630 * versioning system. Keep it for now.
632 continue;
635 len -= dollar + 1 - src;
636 src = dollar + 1;
637 } else {
638 /* it wasn't a "Id$" or "Id:xxxx$" */
639 continue;
642 /* step 4: substitute */
643 strbuf_addstr(buf, "Id: ");
644 strbuf_add(buf, sha1_to_hex(sha1), 40);
645 strbuf_addstr(buf, " $");
647 strbuf_add(buf, src, len);
649 free(to_free);
650 return 1;
653 static enum crlf_action git_path_check_crlf(const char *path, struct git_attr_check *check)
655 const char *value = check->value;
657 if (ATTR_TRUE(value))
658 return CRLF_TEXT;
659 else if (ATTR_FALSE(value))
660 return CRLF_BINARY;
661 else if (ATTR_UNSET(value))
663 else if (!strcmp(value, "input"))
664 return CRLF_INPUT;
665 else if (!strcmp(value, "auto"))
666 return CRLF_AUTO;
667 return CRLF_GUESS;
670 static enum eol git_path_check_eol(const char *path, struct git_attr_check *check)
672 const char *value = check->value;
674 if (ATTR_UNSET(value))
676 else if (!strcmp(value, "lf"))
677 return EOL_LF;
678 else if (!strcmp(value, "crlf"))
679 return EOL_CRLF;
680 return EOL_UNSET;
683 static struct convert_driver *git_path_check_convert(const char *path,
684 struct git_attr_check *check)
686 const char *value = check->value;
687 struct convert_driver *drv;
689 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
690 return NULL;
691 for (drv = user_convert; drv; drv = drv->next)
692 if (!strcmp(value, drv->name))
693 return drv;
694 return NULL;
697 static int git_path_check_ident(const char *path, struct git_attr_check *check)
699 const char *value = check->value;
701 return !!ATTR_TRUE(value);
704 static enum crlf_action input_crlf_action(enum crlf_action text_attr, enum eol eol_attr)
706 if (text_attr == CRLF_BINARY)
707 return CRLF_BINARY;
708 if (eol_attr == EOL_LF)
709 return CRLF_INPUT;
710 if (eol_attr == EOL_CRLF)
711 return CRLF_CRLF;
712 return text_attr;
715 struct conv_attrs {
716 struct convert_driver *drv;
717 enum crlf_action crlf_action;
718 enum eol eol_attr;
719 int ident;
722 static const char *conv_attr_name[] = {
723 "crlf", "ident", "filter", "eol", "text",
725 #define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
727 static void convert_attrs(struct conv_attrs *ca, const char *path)
729 int i;
730 static struct git_attr_check ccheck[NUM_CONV_ATTRS];
732 if (!ccheck[0].attr) {
733 for (i = 0; i < NUM_CONV_ATTRS; i++)
734 ccheck[i].attr = git_attr(conv_attr_name[i]);
735 user_convert_tail = &user_convert;
736 git_config(read_convert_config, NULL);
739 if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
740 ca->crlf_action = git_path_check_crlf(path, ccheck + 4);
741 if (ca->crlf_action == CRLF_GUESS)
742 ca->crlf_action = git_path_check_crlf(path, ccheck + 0);
743 ca->ident = git_path_check_ident(path, ccheck + 1);
744 ca->drv = git_path_check_convert(path, ccheck + 2);
745 ca->eol_attr = git_path_check_eol(path, ccheck + 3);
746 } else {
747 ca->drv = NULL;
748 ca->crlf_action = CRLF_GUESS;
749 ca->eol_attr = EOL_UNSET;
750 ca->ident = 0;
754 int convert_to_git(const char *path, const char *src, size_t len,
755 struct strbuf *dst, enum safe_crlf checksafe)
757 int ret = 0;
758 const char *filter = NULL;
759 int required = 0;
760 struct conv_attrs ca;
762 convert_attrs(&ca, path);
763 if (ca.drv) {
764 filter = ca.drv->clean;
765 required = ca.drv->required;
768 ret |= apply_filter(path, src, len, dst, filter);
769 if (!ret && required)
770 die("%s: clean filter '%s' failed", path, ca.drv->name);
772 if (ret && dst) {
773 src = dst->buf;
774 len = dst->len;
776 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
777 ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
778 if (ret && dst) {
779 src = dst->buf;
780 len = dst->len;
782 return ret | ident_to_git(path, src, len, dst, ca.ident);
785 static int convert_to_working_tree_internal(const char *path, const char *src,
786 size_t len, struct strbuf *dst,
787 int normalizing)
789 int ret = 0, ret_filter = 0;
790 const char *filter = NULL;
791 int required = 0;
792 struct conv_attrs ca;
794 convert_attrs(&ca, path);
795 if (ca.drv) {
796 filter = ca.drv->smudge;
797 required = ca.drv->required;
800 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
801 if (ret) {
802 src = dst->buf;
803 len = dst->len;
806 * CRLF conversion can be skipped if normalizing, unless there
807 * is a smudge filter. The filter might expect CRLFs.
809 if (filter || !normalizing) {
810 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
811 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
812 if (ret) {
813 src = dst->buf;
814 len = dst->len;
818 ret_filter = apply_filter(path, src, len, dst, filter);
819 if (!ret_filter && required)
820 die("%s: smudge filter %s failed", path, ca.drv->name);
822 return ret | ret_filter;
825 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
827 return convert_to_working_tree_internal(path, src, len, dst, 0);
830 int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
832 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
833 if (ret) {
834 src = dst->buf;
835 len = dst->len;
837 return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_FALSE);
840 /*****************************************************************
842 * Streaming converison support
844 *****************************************************************/
846 typedef int (*filter_fn)(struct stream_filter *,
847 const char *input, size_t *isize_p,
848 char *output, size_t *osize_p);
849 typedef void (*free_fn)(struct stream_filter *);
851 struct stream_filter_vtbl {
852 filter_fn filter;
853 free_fn free;
856 struct stream_filter {
857 struct stream_filter_vtbl *vtbl;
860 static int null_filter_fn(struct stream_filter *filter,
861 const char *input, size_t *isize_p,
862 char *output, size_t *osize_p)
864 size_t count;
866 if (!input)
867 return 0; /* we do not keep any states */
868 count = *isize_p;
869 if (*osize_p < count)
870 count = *osize_p;
871 if (count) {
872 memmove(output, input, count);
873 *isize_p -= count;
874 *osize_p -= count;
876 return 0;
879 static void null_free_fn(struct stream_filter *filter)
881 ; /* nothing -- null instances are shared */
884 static struct stream_filter_vtbl null_vtbl = {
885 null_filter_fn,
886 null_free_fn,
889 static struct stream_filter null_filter_singleton = {
890 &null_vtbl,
893 int is_null_stream_filter(struct stream_filter *filter)
895 return filter == &null_filter_singleton;
900 * LF-to-CRLF filter
903 struct lf_to_crlf_filter {
904 struct stream_filter filter;
905 unsigned has_held:1;
906 char held;
909 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
910 const char *input, size_t *isize_p,
911 char *output, size_t *osize_p)
913 size_t count, o = 0;
914 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
917 * We may be holding onto the CR to see if it is followed by a
918 * LF, in which case we would need to go to the main loop.
919 * Otherwise, just emit it to the output stream.
921 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
922 output[o++] = lf_to_crlf->held;
923 lf_to_crlf->has_held = 0;
926 /* We are told to drain */
927 if (!input) {
928 *osize_p -= o;
929 return 0;
932 count = *isize_p;
933 if (count || lf_to_crlf->has_held) {
934 size_t i;
935 int was_cr = 0;
937 if (lf_to_crlf->has_held) {
938 was_cr = 1;
939 lf_to_crlf->has_held = 0;
942 for (i = 0; o < *osize_p && i < count; i++) {
943 char ch = input[i];
945 if (ch == '\n') {
946 output[o++] = '\r';
947 } else if (was_cr) {
949 * Previous round saw CR and it is not followed
950 * by a LF; emit the CR before processing the
951 * current character.
953 output[o++] = '\r';
957 * We may have consumed the last output slot,
958 * in which case we need to break out of this
959 * loop; hold the current character before
960 * returning.
962 if (*osize_p <= o) {
963 lf_to_crlf->has_held = 1;
964 lf_to_crlf->held = ch;
965 continue; /* break but increment i */
968 if (ch == '\r') {
969 was_cr = 1;
970 continue;
973 was_cr = 0;
974 output[o++] = ch;
977 *osize_p -= o;
978 *isize_p -= i;
980 if (!lf_to_crlf->has_held && was_cr) {
981 lf_to_crlf->has_held = 1;
982 lf_to_crlf->held = '\r';
985 return 0;
988 static void lf_to_crlf_free_fn(struct stream_filter *filter)
990 free(filter);
993 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
994 lf_to_crlf_filter_fn,
995 lf_to_crlf_free_fn,
998 static struct stream_filter *lf_to_crlf_filter(void)
1000 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1002 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1003 return (struct stream_filter *)lf_to_crlf;
1007 * Cascade filter
1009 #define FILTER_BUFFER 1024
1010 struct cascade_filter {
1011 struct stream_filter filter;
1012 struct stream_filter *one;
1013 struct stream_filter *two;
1014 char buf[FILTER_BUFFER];
1015 int end, ptr;
1018 static int cascade_filter_fn(struct stream_filter *filter,
1019 const char *input, size_t *isize_p,
1020 char *output, size_t *osize_p)
1022 struct cascade_filter *cas = (struct cascade_filter *) filter;
1023 size_t filled = 0;
1024 size_t sz = *osize_p;
1025 size_t to_feed, remaining;
1028 * input -- (one) --> buf -- (two) --> output
1030 while (filled < sz) {
1031 remaining = sz - filled;
1033 /* do we already have something to feed two with? */
1034 if (cas->ptr < cas->end) {
1035 to_feed = cas->end - cas->ptr;
1036 if (stream_filter(cas->two,
1037 cas->buf + cas->ptr, &to_feed,
1038 output + filled, &remaining))
1039 return -1;
1040 cas->ptr += (cas->end - cas->ptr) - to_feed;
1041 filled = sz - remaining;
1042 continue;
1045 /* feed one from upstream and have it emit into our buffer */
1046 to_feed = input ? *isize_p : 0;
1047 if (input && !to_feed)
1048 break;
1049 remaining = sizeof(cas->buf);
1050 if (stream_filter(cas->one,
1051 input, &to_feed,
1052 cas->buf, &remaining))
1053 return -1;
1054 cas->end = sizeof(cas->buf) - remaining;
1055 cas->ptr = 0;
1056 if (input) {
1057 size_t fed = *isize_p - to_feed;
1058 *isize_p -= fed;
1059 input += fed;
1062 /* do we know that we drained one completely? */
1063 if (input || cas->end)
1064 continue;
1066 /* tell two to drain; we have nothing more to give it */
1067 to_feed = 0;
1068 remaining = sz - filled;
1069 if (stream_filter(cas->two,
1070 NULL, &to_feed,
1071 output + filled, &remaining))
1072 return -1;
1073 if (remaining == (sz - filled))
1074 break; /* completely drained two */
1075 filled = sz - remaining;
1077 *osize_p -= filled;
1078 return 0;
1081 static void cascade_free_fn(struct stream_filter *filter)
1083 struct cascade_filter *cas = (struct cascade_filter *)filter;
1084 free_stream_filter(cas->one);
1085 free_stream_filter(cas->two);
1086 free(filter);
1089 static struct stream_filter_vtbl cascade_vtbl = {
1090 cascade_filter_fn,
1091 cascade_free_fn,
1094 static struct stream_filter *cascade_filter(struct stream_filter *one,
1095 struct stream_filter *two)
1097 struct cascade_filter *cascade;
1099 if (!one || is_null_stream_filter(one))
1100 return two;
1101 if (!two || is_null_stream_filter(two))
1102 return one;
1104 cascade = xmalloc(sizeof(*cascade));
1105 cascade->one = one;
1106 cascade->two = two;
1107 cascade->end = cascade->ptr = 0;
1108 cascade->filter.vtbl = &cascade_vtbl;
1109 return (struct stream_filter *)cascade;
1113 * ident filter
1115 #define IDENT_DRAINING (-1)
1116 #define IDENT_SKIPPING (-2)
1117 struct ident_filter {
1118 struct stream_filter filter;
1119 struct strbuf left;
1120 int state;
1121 char ident[45]; /* ": x40 $" */
1124 static int is_foreign_ident(const char *str)
1126 int i;
1128 if (prefixcmp(str, "$Id: "))
1129 return 0;
1130 for (i = 5; str[i]; i++) {
1131 if (isspace(str[i]) && str[i+1] != '$')
1132 return 1;
1134 return 0;
1137 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1139 size_t to_drain = ident->left.len;
1141 if (*osize_p < to_drain)
1142 to_drain = *osize_p;
1143 if (to_drain) {
1144 memcpy(*output_p, ident->left.buf, to_drain);
1145 strbuf_remove(&ident->left, 0, to_drain);
1146 *output_p += to_drain;
1147 *osize_p -= to_drain;
1149 if (!ident->left.len)
1150 ident->state = 0;
1153 static int ident_filter_fn(struct stream_filter *filter,
1154 const char *input, size_t *isize_p,
1155 char *output, size_t *osize_p)
1157 struct ident_filter *ident = (struct ident_filter *)filter;
1158 static const char head[] = "$Id";
1160 if (!input) {
1161 /* drain upon eof */
1162 switch (ident->state) {
1163 default:
1164 strbuf_add(&ident->left, head, ident->state);
1165 case IDENT_SKIPPING:
1166 /* fallthru */
1167 case IDENT_DRAINING:
1168 ident_drain(ident, &output, osize_p);
1170 return 0;
1173 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1174 int ch;
1176 if (ident->state == IDENT_DRAINING) {
1177 ident_drain(ident, &output, osize_p);
1178 if (!*osize_p)
1179 break;
1180 continue;
1183 ch = *(input++);
1184 (*isize_p)--;
1186 if (ident->state == IDENT_SKIPPING) {
1188 * Skipping until '$' or LF, but keeping them
1189 * in case it is a foreign ident.
1191 strbuf_addch(&ident->left, ch);
1192 if (ch != '\n' && ch != '$')
1193 continue;
1194 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1195 strbuf_setlen(&ident->left, sizeof(head) - 1);
1196 strbuf_addstr(&ident->left, ident->ident);
1198 ident->state = IDENT_DRAINING;
1199 continue;
1202 if (ident->state < sizeof(head) &&
1203 head[ident->state] == ch) {
1204 ident->state++;
1205 continue;
1208 if (ident->state)
1209 strbuf_add(&ident->left, head, ident->state);
1210 if (ident->state == sizeof(head) - 1) {
1211 if (ch != ':' && ch != '$') {
1212 strbuf_addch(&ident->left, ch);
1213 ident->state = 0;
1214 continue;
1217 if (ch == ':') {
1218 strbuf_addch(&ident->left, ch);
1219 ident->state = IDENT_SKIPPING;
1220 } else {
1221 strbuf_addstr(&ident->left, ident->ident);
1222 ident->state = IDENT_DRAINING;
1224 continue;
1227 strbuf_addch(&ident->left, ch);
1228 ident->state = IDENT_DRAINING;
1230 return 0;
1233 static void ident_free_fn(struct stream_filter *filter)
1235 struct ident_filter *ident = (struct ident_filter *)filter;
1236 strbuf_release(&ident->left);
1237 free(filter);
1240 static struct stream_filter_vtbl ident_vtbl = {
1241 ident_filter_fn,
1242 ident_free_fn,
1245 static struct stream_filter *ident_filter(const unsigned char *sha1)
1247 struct ident_filter *ident = xmalloc(sizeof(*ident));
1249 sprintf(ident->ident, ": %s $", sha1_to_hex(sha1));
1250 strbuf_init(&ident->left, 0);
1251 ident->filter.vtbl = &ident_vtbl;
1252 ident->state = 0;
1253 return (struct stream_filter *)ident;
1257 * Return an appropriately constructed filter for the path, or NULL if
1258 * the contents cannot be filtered without reading the whole thing
1259 * in-core.
1261 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1262 * large binary blob you would want us not to slurp into the memory!
1264 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1266 struct conv_attrs ca;
1267 enum crlf_action crlf_action;
1268 struct stream_filter *filter = NULL;
1270 convert_attrs(&ca, path);
1272 if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1273 return filter;
1275 if (ca.ident)
1276 filter = ident_filter(sha1);
1278 crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
1280 if ((crlf_action == CRLF_BINARY) || (crlf_action == CRLF_INPUT) ||
1281 (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE))
1282 filter = cascade_filter(filter, &null_filter_singleton);
1284 else if (output_eol(crlf_action) == EOL_CRLF &&
1285 !(crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS))
1286 filter = cascade_filter(filter, lf_to_crlf_filter());
1288 return filter;
1291 void free_stream_filter(struct stream_filter *filter)
1293 filter->vtbl->free(filter);
1296 int stream_filter(struct stream_filter *filter,
1297 const char *input, size_t *isize_p,
1298 char *output, size_t *osize_p)
1300 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);