do not stream large files to pack when filters are in use
[git/jrn.git] / convert.c
blobaa7f72d8a0515bd1b6b4ec018a5604fd5c1549ab
1 #include "cache.h"
2 #include "attr.h"
3 #include "run-command.h"
4 #include "quote.h"
6 /*
7 * convert.c - convert a file when checking it out and checking it in.
9 * This should use the pathname to decide on whether it wants to do some
10 * more interesting conversions (automatic gzip/unzip, general format
11 * conversions etc etc), but by default it just does automatic CRLF<->LF
12 * translation when the "text" attribute or "auto_crlf" option is set.
15 enum crlf_action {
16 CRLF_GUESS = -1,
17 CRLF_BINARY = 0,
18 CRLF_TEXT,
19 CRLF_INPUT,
20 CRLF_CRLF,
21 CRLF_AUTO
24 struct text_stat {
25 /* NUL, CR, LF and CRLF counts */
26 unsigned nul, cr, lf, crlf;
28 /* These are just approximations! */
29 unsigned printable, nonprintable;
32 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
34 unsigned long i;
36 memset(stats, 0, sizeof(*stats));
38 for (i = 0; i < size; i++) {
39 unsigned char c = buf[i];
40 if (c == '\r') {
41 stats->cr++;
42 if (i+1 < size && buf[i+1] == '\n')
43 stats->crlf++;
44 continue;
46 if (c == '\n') {
47 stats->lf++;
48 continue;
50 if (c == 127)
51 /* DEL */
52 stats->nonprintable++;
53 else if (c < 32) {
54 switch (c) {
55 /* BS, HT, ESC and FF */
56 case '\b': case '\t': case '\033': case '\014':
57 stats->printable++;
58 break;
59 case 0:
60 stats->nul++;
61 /* fall through */
62 default:
63 stats->nonprintable++;
66 else
67 stats->printable++;
70 /* If file ends with EOF then don't count this EOF as non-printable. */
71 if (size >= 1 && buf[size-1] == '\032')
72 stats->nonprintable--;
76 * The same heuristics as diff.c::mmfile_is_binary()
78 static int is_binary(unsigned long size, struct text_stat *stats)
81 if (stats->nul)
82 return 1;
83 if ((stats->printable >> 7) < stats->nonprintable)
84 return 1;
86 * Other heuristics? Average line length might be relevant,
87 * as might LF vs CR vs CRLF counts..
89 * NOTE! It might be normal to have a low ratio of CRLF to LF
90 * (somebody starts with a LF-only file and edits it with an editor
91 * that adds CRLF only to lines that are added..). But do we
92 * want to support CR-only? Probably not.
94 return 0;
97 static enum eol output_eol(enum crlf_action crlf_action)
99 switch (crlf_action) {
100 case CRLF_BINARY:
101 return EOL_UNSET;
102 case CRLF_CRLF:
103 return EOL_CRLF;
104 case CRLF_INPUT:
105 return EOL_LF;
106 case CRLF_GUESS:
107 if (!auto_crlf)
108 return EOL_UNSET;
109 /* fall through */
110 case CRLF_TEXT:
111 case CRLF_AUTO:
112 if (auto_crlf == AUTO_CRLF_TRUE)
113 return EOL_CRLF;
114 else if (auto_crlf == AUTO_CRLF_INPUT)
115 return EOL_LF;
116 else if (core_eol == EOL_UNSET)
117 return EOL_NATIVE;
119 return core_eol;
122 static void check_safe_crlf(const char *path, enum crlf_action crlf_action,
123 struct text_stat *stats, enum safe_crlf checksafe)
125 if (!checksafe)
126 return;
128 if (output_eol(crlf_action) == EOL_LF) {
130 * CRLFs would not be restored by checkout:
131 * check if we'd remove CRLFs
133 if (stats->crlf) {
134 if (checksafe == SAFE_CRLF_WARN)
135 warning("CRLF will be replaced by LF in %s.\nThe file will have its original line endings in your working directory.", path);
136 else /* i.e. SAFE_CRLF_FAIL */
137 die("CRLF would be replaced by LF in %s.", path);
139 } else if (output_eol(crlf_action) == EOL_CRLF) {
141 * CRLFs would be added by checkout:
142 * check if we have "naked" LFs
144 if (stats->lf != stats->crlf) {
145 if (checksafe == SAFE_CRLF_WARN)
146 warning("LF will be replaced by CRLF in %s.\nThe file will have its original line endings in your working directory.", path);
147 else /* i.e. SAFE_CRLF_FAIL */
148 die("LF would be replaced by CRLF in %s", path);
153 static int has_cr_in_index(const char *path)
155 int pos, len;
156 unsigned long sz;
157 enum object_type type;
158 void *data;
159 int has_cr;
160 struct index_state *istate = &the_index;
162 len = strlen(path);
163 pos = index_name_pos(istate, path, len);
164 if (pos < 0) {
166 * We might be in the middle of a merge, in which
167 * case we would read stage #2 (ours).
169 int i;
170 for (i = -pos - 1;
171 (pos < 0 && i < istate->cache_nr &&
172 !strcmp(istate->cache[i]->name, path));
173 i++)
174 if (ce_stage(istate->cache[i]) == 2)
175 pos = i;
177 if (pos < 0)
178 return 0;
179 data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
180 if (!data || type != OBJ_BLOB) {
181 free(data);
182 return 0;
185 has_cr = memchr(data, '\r', sz) != NULL;
186 free(data);
187 return has_cr;
190 static int crlf_to_git(const char *path, const char *src, size_t len,
191 struct strbuf *buf,
192 enum crlf_action crlf_action, enum safe_crlf checksafe)
194 struct text_stat stats;
195 char *dst;
197 if (crlf_action == CRLF_BINARY ||
198 (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE) ||
199 (src && !len))
200 return 0;
203 * If we are doing a dry-run and have no source buffer, there is
204 * nothing to analyze; we must assume we would convert.
206 if (!buf && !src)
207 return 1;
209 gather_stats(src, len, &stats);
211 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
213 * We're currently not going to even try to convert stuff
214 * that has bare CR characters. Does anybody do that crazy
215 * stuff?
217 if (stats.cr != stats.crlf)
218 return 0;
221 * And add some heuristics for binary vs text, of course...
223 if (is_binary(len, &stats))
224 return 0;
226 if (crlf_action == CRLF_GUESS) {
228 * If the file in the index has any CR in it, do not convert.
229 * This is the new safer autocrlf handling.
231 if (has_cr_in_index(path))
232 return 0;
236 check_safe_crlf(path, crlf_action, &stats, checksafe);
238 /* Optimization: No CR? Nothing to convert, regardless. */
239 if (!stats.cr)
240 return 0;
243 * At this point all of our source analysis is done, and we are sure we
244 * would convert. If we are in dry-run mode, we can give an answer.
246 if (!buf)
247 return 1;
249 /* only grow if not in place */
250 if (strbuf_avail(buf) + buf->len < len)
251 strbuf_grow(buf, len - buf->len);
252 dst = buf->buf;
253 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
255 * If we guessed, we already know we rejected a file with
256 * lone CR, and we can strip a CR without looking at what
257 * follow it.
259 do {
260 unsigned char c = *src++;
261 if (c != '\r')
262 *dst++ = c;
263 } while (--len);
264 } else {
265 do {
266 unsigned char c = *src++;
267 if (! (c == '\r' && (1 < len && *src == '\n')))
268 *dst++ = c;
269 } while (--len);
271 strbuf_setlen(buf, dst - buf->buf);
272 return 1;
275 static int crlf_to_worktree(const char *path, const char *src, size_t len,
276 struct strbuf *buf, enum crlf_action crlf_action)
278 char *to_free = NULL;
279 struct text_stat stats;
281 if (!len || output_eol(crlf_action) != EOL_CRLF)
282 return 0;
284 gather_stats(src, len, &stats);
286 /* No LF? Nothing to convert, regardless. */
287 if (!stats.lf)
288 return 0;
290 /* Was it already in CRLF format? */
291 if (stats.lf == stats.crlf)
292 return 0;
294 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
295 if (crlf_action == CRLF_GUESS) {
296 /* If we have any CR or CRLF line endings, we do not touch it */
297 /* This is the new safer autocrlf-handling */
298 if (stats.cr > 0 || stats.crlf > 0)
299 return 0;
302 /* If we have any bare CR characters, we're not going to touch it */
303 if (stats.cr != stats.crlf)
304 return 0;
306 if (is_binary(len, &stats))
307 return 0;
310 /* are we "faking" in place editing ? */
311 if (src == buf->buf)
312 to_free = strbuf_detach(buf, NULL);
314 strbuf_grow(buf, len + stats.lf - stats.crlf);
315 for (;;) {
316 const char *nl = memchr(src, '\n', len);
317 if (!nl)
318 break;
319 if (nl > src && nl[-1] == '\r') {
320 strbuf_add(buf, src, nl + 1 - src);
321 } else {
322 strbuf_add(buf, src, nl - src);
323 strbuf_addstr(buf, "\r\n");
325 len -= nl + 1 - src;
326 src = nl + 1;
328 strbuf_add(buf, src, len);
330 free(to_free);
331 return 1;
334 struct filter_params {
335 const char *src;
336 unsigned long size;
337 const char *cmd;
338 const char *path;
341 static int filter_buffer(int in, int out, void *data)
344 * Spawn cmd and feed the buffer contents through its stdin.
346 struct child_process child_process;
347 struct filter_params *params = (struct filter_params *)data;
348 int write_err, status;
349 const char *argv[] = { NULL, NULL };
351 /* apply % substitution to cmd */
352 struct strbuf cmd = STRBUF_INIT;
353 struct strbuf path = STRBUF_INIT;
354 struct strbuf_expand_dict_entry dict[] = {
355 { "f", NULL, },
356 { NULL, NULL, },
359 /* quote the path to preserve spaces, etc. */
360 sq_quote_buf(&path, params->path);
361 dict[0].value = path.buf;
363 /* expand all %f with the quoted path */
364 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
365 strbuf_release(&path);
367 argv[0] = cmd.buf;
369 memset(&child_process, 0, sizeof(child_process));
370 child_process.argv = argv;
371 child_process.use_shell = 1;
372 child_process.in = -1;
373 child_process.out = out;
375 if (start_command(&child_process))
376 return error("cannot fork to run external filter %s", params->cmd);
378 write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
379 if (close(child_process.in))
380 write_err = 1;
381 if (write_err)
382 error("cannot feed the input to external filter %s", params->cmd);
384 status = finish_command(&child_process);
385 if (status)
386 error("external filter %s failed %d", params->cmd, status);
388 strbuf_release(&cmd);
389 return (write_err || status);
392 static int apply_filter(const char *path, const char *src, size_t len,
393 struct strbuf *dst, const char *cmd)
396 * Create a pipeline to have the command filter the buffer's
397 * contents.
399 * (child --> cmd) --> us
401 int ret = 1;
402 struct strbuf nbuf = STRBUF_INIT;
403 struct async async;
404 struct filter_params params;
406 if (!cmd)
407 return 0;
409 if (!dst)
410 return 1;
412 memset(&async, 0, sizeof(async));
413 async.proc = filter_buffer;
414 async.data = &params;
415 async.out = -1;
416 params.src = src;
417 params.size = len;
418 params.cmd = cmd;
419 params.path = path;
421 fflush(NULL);
422 if (start_async(&async))
423 return 0; /* error was already reported */
425 if (strbuf_read(&nbuf, async.out, len) < 0) {
426 error("read from external filter %s failed", cmd);
427 ret = 0;
429 if (close(async.out)) {
430 error("read from external filter %s failed", cmd);
431 ret = 0;
433 if (finish_async(&async)) {
434 error("external filter %s failed", cmd);
435 ret = 0;
438 if (ret) {
439 strbuf_swap(dst, &nbuf);
441 strbuf_release(&nbuf);
442 return ret;
445 static struct convert_driver {
446 const char *name;
447 struct convert_driver *next;
448 const char *smudge;
449 const char *clean;
450 } *user_convert, **user_convert_tail;
452 static int read_convert_config(const char *var, const char *value, void *cb)
454 const char *ep, *name;
455 int namelen;
456 struct convert_driver *drv;
459 * External conversion drivers are configured using
460 * "filter.<name>.variable".
462 if (prefixcmp(var, "filter.") || (ep = strrchr(var, '.')) == var + 6)
463 return 0;
464 name = var + 7;
465 namelen = ep - name;
466 for (drv = user_convert; drv; drv = drv->next)
467 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
468 break;
469 if (!drv) {
470 drv = xcalloc(1, sizeof(struct convert_driver));
471 drv->name = xmemdupz(name, namelen);
472 *user_convert_tail = drv;
473 user_convert_tail = &(drv->next);
476 ep++;
479 * filter.<name>.smudge and filter.<name>.clean specifies
480 * the command line:
482 * command-line
484 * The command-line will not be interpolated in any way.
487 if (!strcmp("smudge", ep))
488 return git_config_string(&drv->smudge, var, value);
490 if (!strcmp("clean", ep))
491 return git_config_string(&drv->clean, var, value);
493 return 0;
496 static int count_ident(const char *cp, unsigned long size)
499 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
501 int cnt = 0;
502 char ch;
504 while (size) {
505 ch = *cp++;
506 size--;
507 if (ch != '$')
508 continue;
509 if (size < 3)
510 break;
511 if (memcmp("Id", cp, 2))
512 continue;
513 ch = cp[2];
514 cp += 3;
515 size -= 3;
516 if (ch == '$')
517 cnt++; /* $Id$ */
518 if (ch != ':')
519 continue;
522 * "$Id: ... "; scan up to the closing dollar sign and discard.
524 while (size) {
525 ch = *cp++;
526 size--;
527 if (ch == '$') {
528 cnt++;
529 break;
531 if (ch == '\n')
532 break;
535 return cnt;
538 static int ident_to_git(const char *path, const char *src, size_t len,
539 struct strbuf *buf, int ident)
541 char *dst, *dollar;
543 if (!ident || (src && !count_ident(src, len)))
544 return 0;
546 if (!buf)
547 return 1;
549 /* only grow if not in place */
550 if (strbuf_avail(buf) + buf->len < len)
551 strbuf_grow(buf, len - buf->len);
552 dst = buf->buf;
553 for (;;) {
554 dollar = memchr(src, '$', len);
555 if (!dollar)
556 break;
557 memmove(dst, src, dollar + 1 - src);
558 dst += dollar + 1 - src;
559 len -= dollar + 1 - src;
560 src = dollar + 1;
562 if (len > 3 && !memcmp(src, "Id:", 3)) {
563 dollar = memchr(src + 3, '$', len - 3);
564 if (!dollar)
565 break;
566 if (memchr(src + 3, '\n', dollar - src - 3)) {
567 /* Line break before the next dollar. */
568 continue;
571 memcpy(dst, "Id$", 3);
572 dst += 3;
573 len -= dollar + 1 - src;
574 src = dollar + 1;
577 memmove(dst, src, len);
578 strbuf_setlen(buf, dst + len - buf->buf);
579 return 1;
582 static int ident_to_worktree(const char *path, const char *src, size_t len,
583 struct strbuf *buf, int ident)
585 unsigned char sha1[20];
586 char *to_free = NULL, *dollar, *spc;
587 int cnt;
589 if (!ident)
590 return 0;
592 cnt = count_ident(src, len);
593 if (!cnt)
594 return 0;
596 /* are we "faking" in place editing ? */
597 if (src == buf->buf)
598 to_free = strbuf_detach(buf, NULL);
599 hash_sha1_file(src, len, "blob", sha1);
601 strbuf_grow(buf, len + cnt * 43);
602 for (;;) {
603 /* step 1: run to the next '$' */
604 dollar = memchr(src, '$', len);
605 if (!dollar)
606 break;
607 strbuf_add(buf, src, dollar + 1 - src);
608 len -= dollar + 1 - src;
609 src = dollar + 1;
611 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
612 if (len < 3 || memcmp("Id", src, 2))
613 continue;
615 /* step 3: skip over Id$ or Id:xxxxx$ */
616 if (src[2] == '$') {
617 src += 3;
618 len -= 3;
619 } else if (src[2] == ':') {
621 * It's possible that an expanded Id has crept its way into the
622 * repository, we cope with that by stripping the expansion out.
623 * This is probably not a good idea, since it will cause changes
624 * on checkout, which won't go away by stash, but let's keep it
625 * for git-style ids.
627 dollar = memchr(src + 3, '$', len - 3);
628 if (!dollar) {
629 /* incomplete keyword, no more '$', so just quit the loop */
630 break;
633 if (memchr(src + 3, '\n', dollar - src - 3)) {
634 /* Line break before the next dollar. */
635 continue;
638 spc = memchr(src + 4, ' ', dollar - src - 4);
639 if (spc && spc < dollar-1) {
640 /* There are spaces in unexpected places.
641 * This is probably an id from some other
642 * versioning system. Keep it for now.
644 continue;
647 len -= dollar + 1 - src;
648 src = dollar + 1;
649 } else {
650 /* it wasn't a "Id$" or "Id:xxxx$" */
651 continue;
654 /* step 4: substitute */
655 strbuf_addstr(buf, "Id: ");
656 strbuf_add(buf, sha1_to_hex(sha1), 40);
657 strbuf_addstr(buf, " $");
659 strbuf_add(buf, src, len);
661 free(to_free);
662 return 1;
665 static enum crlf_action git_path_check_crlf(const char *path, struct git_attr_check *check)
667 const char *value = check->value;
669 if (ATTR_TRUE(value))
670 return CRLF_TEXT;
671 else if (ATTR_FALSE(value))
672 return CRLF_BINARY;
673 else if (ATTR_UNSET(value))
675 else if (!strcmp(value, "input"))
676 return CRLF_INPUT;
677 else if (!strcmp(value, "auto"))
678 return CRLF_AUTO;
679 return CRLF_GUESS;
682 static enum eol git_path_check_eol(const char *path, struct git_attr_check *check)
684 const char *value = check->value;
686 if (ATTR_UNSET(value))
688 else if (!strcmp(value, "lf"))
689 return EOL_LF;
690 else if (!strcmp(value, "crlf"))
691 return EOL_CRLF;
692 return EOL_UNSET;
695 static struct convert_driver *git_path_check_convert(const char *path,
696 struct git_attr_check *check)
698 const char *value = check->value;
699 struct convert_driver *drv;
701 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
702 return NULL;
703 for (drv = user_convert; drv; drv = drv->next)
704 if (!strcmp(value, drv->name))
705 return drv;
706 return NULL;
709 static int git_path_check_ident(const char *path, struct git_attr_check *check)
711 const char *value = check->value;
713 return !!ATTR_TRUE(value);
716 static enum crlf_action input_crlf_action(enum crlf_action text_attr, enum eol eol_attr)
718 if (text_attr == CRLF_BINARY)
719 return CRLF_BINARY;
720 if (eol_attr == EOL_LF)
721 return CRLF_INPUT;
722 if (eol_attr == EOL_CRLF)
723 return CRLF_CRLF;
724 return text_attr;
727 struct conv_attrs {
728 struct convert_driver *drv;
729 enum crlf_action crlf_action;
730 enum eol eol_attr;
731 int ident;
734 static const char *conv_attr_name[] = {
735 "crlf", "ident", "filter", "eol", "text",
737 #define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
739 static void convert_attrs(struct conv_attrs *ca, const char *path)
741 int i;
742 static struct git_attr_check ccheck[NUM_CONV_ATTRS];
744 if (!ccheck[0].attr) {
745 for (i = 0; i < NUM_CONV_ATTRS; i++)
746 ccheck[i].attr = git_attr(conv_attr_name[i]);
747 user_convert_tail = &user_convert;
748 git_config(read_convert_config, NULL);
751 if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
752 ca->crlf_action = git_path_check_crlf(path, ccheck + 4);
753 if (ca->crlf_action == CRLF_GUESS)
754 ca->crlf_action = git_path_check_crlf(path, ccheck + 0);
755 ca->ident = git_path_check_ident(path, ccheck + 1);
756 ca->drv = git_path_check_convert(path, ccheck + 2);
757 ca->eol_attr = git_path_check_eol(path, ccheck + 3);
758 } else {
759 ca->drv = NULL;
760 ca->crlf_action = CRLF_GUESS;
761 ca->eol_attr = EOL_UNSET;
762 ca->ident = 0;
766 int convert_to_git(const char *path, const char *src, size_t len,
767 struct strbuf *dst, enum safe_crlf checksafe)
769 int ret = 0;
770 const char *filter = NULL;
771 struct conv_attrs ca;
773 convert_attrs(&ca, path);
774 if (ca.drv)
775 filter = ca.drv->clean;
777 ret |= apply_filter(path, src, len, dst, filter);
778 if (ret && dst) {
779 src = dst->buf;
780 len = dst->len;
782 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
783 ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
784 if (ret && dst) {
785 src = dst->buf;
786 len = dst->len;
788 return ret | ident_to_git(path, src, len, dst, ca.ident);
791 static int convert_to_working_tree_internal(const char *path, const char *src,
792 size_t len, struct strbuf *dst,
793 int normalizing)
795 int ret = 0;
796 const char *filter = NULL;
797 struct conv_attrs ca;
799 convert_attrs(&ca, path);
800 if (ca.drv)
801 filter = ca.drv->smudge;
803 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
804 if (ret) {
805 src = dst->buf;
806 len = dst->len;
809 * CRLF conversion can be skipped if normalizing, unless there
810 * is a smudge filter. The filter might expect CRLFs.
812 if (filter || !normalizing) {
813 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
814 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
815 if (ret) {
816 src = dst->buf;
817 len = dst->len;
820 return ret | apply_filter(path, src, len, dst, filter);
823 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
825 return convert_to_working_tree_internal(path, src, len, dst, 0);
828 int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
830 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
831 if (ret) {
832 src = dst->buf;
833 len = dst->len;
835 return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_FALSE);
838 /*****************************************************************
840 * Streaming converison support
842 *****************************************************************/
844 typedef int (*filter_fn)(struct stream_filter *,
845 const char *input, size_t *isize_p,
846 char *output, size_t *osize_p);
847 typedef void (*free_fn)(struct stream_filter *);
849 struct stream_filter_vtbl {
850 filter_fn filter;
851 free_fn free;
854 struct stream_filter {
855 struct stream_filter_vtbl *vtbl;
858 static int null_filter_fn(struct stream_filter *filter,
859 const char *input, size_t *isize_p,
860 char *output, size_t *osize_p)
862 size_t count;
864 if (!input)
865 return 0; /* we do not keep any states */
866 count = *isize_p;
867 if (*osize_p < count)
868 count = *osize_p;
869 if (count) {
870 memmove(output, input, count);
871 *isize_p -= count;
872 *osize_p -= count;
874 return 0;
877 static void null_free_fn(struct stream_filter *filter)
879 ; /* nothing -- null instances are shared */
882 static struct stream_filter_vtbl null_vtbl = {
883 null_filter_fn,
884 null_free_fn,
887 static struct stream_filter null_filter_singleton = {
888 &null_vtbl,
891 int is_null_stream_filter(struct stream_filter *filter)
893 return filter == &null_filter_singleton;
898 * LF-to-CRLF filter
901 struct lf_to_crlf_filter {
902 struct stream_filter filter;
903 unsigned has_held:1;
904 char held;
907 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
908 const char *input, size_t *isize_p,
909 char *output, size_t *osize_p)
911 size_t count, o = 0;
912 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
915 * We may be holding onto the CR to see if it is followed by a
916 * LF, in which case we would need to go to the main loop.
917 * Otherwise, just emit it to the output stream.
919 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
920 output[o++] = lf_to_crlf->held;
921 lf_to_crlf->has_held = 0;
924 /* We are told to drain */
925 if (!input) {
926 *osize_p -= o;
927 return 0;
930 count = *isize_p;
931 if (count || lf_to_crlf->has_held) {
932 size_t i;
933 int was_cr = 0;
935 if (lf_to_crlf->has_held) {
936 was_cr = 1;
937 lf_to_crlf->has_held = 0;
940 for (i = 0; o < *osize_p && i < count; i++) {
941 char ch = input[i];
943 if (ch == '\n') {
944 output[o++] = '\r';
945 } else if (was_cr) {
947 * Previous round saw CR and it is not followed
948 * by a LF; emit the CR before processing the
949 * current character.
951 output[o++] = '\r';
955 * We may have consumed the last output slot,
956 * in which case we need to break out of this
957 * loop; hold the current character before
958 * returning.
960 if (*osize_p <= o) {
961 lf_to_crlf->has_held = 1;
962 lf_to_crlf->held = ch;
963 continue; /* break but increment i */
966 if (ch == '\r') {
967 was_cr = 1;
968 continue;
971 was_cr = 0;
972 output[o++] = ch;
975 *osize_p -= o;
976 *isize_p -= i;
978 if (!lf_to_crlf->has_held && was_cr) {
979 lf_to_crlf->has_held = 1;
980 lf_to_crlf->held = '\r';
983 return 0;
986 static void lf_to_crlf_free_fn(struct stream_filter *filter)
988 free(filter);
991 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
992 lf_to_crlf_filter_fn,
993 lf_to_crlf_free_fn,
996 static struct stream_filter *lf_to_crlf_filter(void)
998 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1000 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1001 return (struct stream_filter *)lf_to_crlf;
1005 * Cascade filter
1007 #define FILTER_BUFFER 1024
1008 struct cascade_filter {
1009 struct stream_filter filter;
1010 struct stream_filter *one;
1011 struct stream_filter *two;
1012 char buf[FILTER_BUFFER];
1013 int end, ptr;
1016 static int cascade_filter_fn(struct stream_filter *filter,
1017 const char *input, size_t *isize_p,
1018 char *output, size_t *osize_p)
1020 struct cascade_filter *cas = (struct cascade_filter *) filter;
1021 size_t filled = 0;
1022 size_t sz = *osize_p;
1023 size_t to_feed, remaining;
1026 * input -- (one) --> buf -- (two) --> output
1028 while (filled < sz) {
1029 remaining = sz - filled;
1031 /* do we already have something to feed two with? */
1032 if (cas->ptr < cas->end) {
1033 to_feed = cas->end - cas->ptr;
1034 if (stream_filter(cas->two,
1035 cas->buf + cas->ptr, &to_feed,
1036 output + filled, &remaining))
1037 return -1;
1038 cas->ptr += (cas->end - cas->ptr) - to_feed;
1039 filled = sz - remaining;
1040 continue;
1043 /* feed one from upstream and have it emit into our buffer */
1044 to_feed = input ? *isize_p : 0;
1045 if (input && !to_feed)
1046 break;
1047 remaining = sizeof(cas->buf);
1048 if (stream_filter(cas->one,
1049 input, &to_feed,
1050 cas->buf, &remaining))
1051 return -1;
1052 cas->end = sizeof(cas->buf) - remaining;
1053 cas->ptr = 0;
1054 if (input) {
1055 size_t fed = *isize_p - to_feed;
1056 *isize_p -= fed;
1057 input += fed;
1060 /* do we know that we drained one completely? */
1061 if (input || cas->end)
1062 continue;
1064 /* tell two to drain; we have nothing more to give it */
1065 to_feed = 0;
1066 remaining = sz - filled;
1067 if (stream_filter(cas->two,
1068 NULL, &to_feed,
1069 output + filled, &remaining))
1070 return -1;
1071 if (remaining == (sz - filled))
1072 break; /* completely drained two */
1073 filled = sz - remaining;
1075 *osize_p -= filled;
1076 return 0;
1079 static void cascade_free_fn(struct stream_filter *filter)
1081 struct cascade_filter *cas = (struct cascade_filter *)filter;
1082 free_stream_filter(cas->one);
1083 free_stream_filter(cas->two);
1084 free(filter);
1087 static struct stream_filter_vtbl cascade_vtbl = {
1088 cascade_filter_fn,
1089 cascade_free_fn,
1092 static struct stream_filter *cascade_filter(struct stream_filter *one,
1093 struct stream_filter *two)
1095 struct cascade_filter *cascade;
1097 if (!one || is_null_stream_filter(one))
1098 return two;
1099 if (!two || is_null_stream_filter(two))
1100 return one;
1102 cascade = xmalloc(sizeof(*cascade));
1103 cascade->one = one;
1104 cascade->two = two;
1105 cascade->end = cascade->ptr = 0;
1106 cascade->filter.vtbl = &cascade_vtbl;
1107 return (struct stream_filter *)cascade;
1111 * ident filter
1113 #define IDENT_DRAINING (-1)
1114 #define IDENT_SKIPPING (-2)
1115 struct ident_filter {
1116 struct stream_filter filter;
1117 struct strbuf left;
1118 int state;
1119 char ident[45]; /* ": x40 $" */
1122 static int is_foreign_ident(const char *str)
1124 int i;
1126 if (prefixcmp(str, "$Id: "))
1127 return 0;
1128 for (i = 5; str[i]; i++) {
1129 if (isspace(str[i]) && str[i+1] != '$')
1130 return 1;
1132 return 0;
1135 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1137 size_t to_drain = ident->left.len;
1139 if (*osize_p < to_drain)
1140 to_drain = *osize_p;
1141 if (to_drain) {
1142 memcpy(*output_p, ident->left.buf, to_drain);
1143 strbuf_remove(&ident->left, 0, to_drain);
1144 *output_p += to_drain;
1145 *osize_p -= to_drain;
1147 if (!ident->left.len)
1148 ident->state = 0;
1151 static int ident_filter_fn(struct stream_filter *filter,
1152 const char *input, size_t *isize_p,
1153 char *output, size_t *osize_p)
1155 struct ident_filter *ident = (struct ident_filter *)filter;
1156 static const char head[] = "$Id";
1158 if (!input) {
1159 /* drain upon eof */
1160 switch (ident->state) {
1161 default:
1162 strbuf_add(&ident->left, head, ident->state);
1163 case IDENT_SKIPPING:
1164 /* fallthru */
1165 case IDENT_DRAINING:
1166 ident_drain(ident, &output, osize_p);
1168 return 0;
1171 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1172 int ch;
1174 if (ident->state == IDENT_DRAINING) {
1175 ident_drain(ident, &output, osize_p);
1176 if (!*osize_p)
1177 break;
1178 continue;
1181 ch = *(input++);
1182 (*isize_p)--;
1184 if (ident->state == IDENT_SKIPPING) {
1186 * Skipping until '$' or LF, but keeping them
1187 * in case it is a foreign ident.
1189 strbuf_addch(&ident->left, ch);
1190 if (ch != '\n' && ch != '$')
1191 continue;
1192 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1193 strbuf_setlen(&ident->left, sizeof(head) - 1);
1194 strbuf_addstr(&ident->left, ident->ident);
1196 ident->state = IDENT_DRAINING;
1197 continue;
1200 if (ident->state < sizeof(head) &&
1201 head[ident->state] == ch) {
1202 ident->state++;
1203 continue;
1206 if (ident->state)
1207 strbuf_add(&ident->left, head, ident->state);
1208 if (ident->state == sizeof(head) - 1) {
1209 if (ch != ':' && ch != '$') {
1210 strbuf_addch(&ident->left, ch);
1211 ident->state = 0;
1212 continue;
1215 if (ch == ':') {
1216 strbuf_addch(&ident->left, ch);
1217 ident->state = IDENT_SKIPPING;
1218 } else {
1219 strbuf_addstr(&ident->left, ident->ident);
1220 ident->state = IDENT_DRAINING;
1222 continue;
1225 strbuf_addch(&ident->left, ch);
1226 ident->state = IDENT_DRAINING;
1228 return 0;
1231 static void ident_free_fn(struct stream_filter *filter)
1233 struct ident_filter *ident = (struct ident_filter *)filter;
1234 strbuf_release(&ident->left);
1235 free(filter);
1238 static struct stream_filter_vtbl ident_vtbl = {
1239 ident_filter_fn,
1240 ident_free_fn,
1243 static struct stream_filter *ident_filter(const unsigned char *sha1)
1245 struct ident_filter *ident = xmalloc(sizeof(*ident));
1247 sprintf(ident->ident, ": %s $", sha1_to_hex(sha1));
1248 strbuf_init(&ident->left, 0);
1249 ident->filter.vtbl = &ident_vtbl;
1250 ident->state = 0;
1251 return (struct stream_filter *)ident;
1255 * Return an appropriately constructed filter for the path, or NULL if
1256 * the contents cannot be filtered without reading the whole thing
1257 * in-core.
1259 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1260 * large binary blob you would want us not to slurp into the memory!
1262 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1264 struct conv_attrs ca;
1265 enum crlf_action crlf_action;
1266 struct stream_filter *filter = NULL;
1268 convert_attrs(&ca, path);
1270 if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1271 return filter;
1273 if (ca.ident)
1274 filter = ident_filter(sha1);
1276 crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
1278 if ((crlf_action == CRLF_BINARY) || (crlf_action == CRLF_INPUT) ||
1279 (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE))
1280 filter = cascade_filter(filter, &null_filter_singleton);
1282 else if (output_eol(crlf_action) == EOL_CRLF &&
1283 !(crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS))
1284 filter = cascade_filter(filter, lf_to_crlf_filter());
1286 return filter;
1289 void free_stream_filter(struct stream_filter *filter)
1291 filter->vtbl->free(filter);
1294 int stream_filter(struct stream_filter *filter,
1295 const char *input, size_t *isize_p,
1296 char *output, size_t *osize_p)
1298 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);