Add a setting to require a filter to be successful
[git/dscho.git] / convert.c
blobc06309f5e102c36f5751fce8cb83229ff9acca42
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) || !len)
199 return 0;
201 gather_stats(src, len, &stats);
203 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
205 * We're currently not going to even try to convert stuff
206 * that has bare CR characters. Does anybody do that crazy
207 * stuff?
209 if (stats.cr != stats.crlf)
210 return 0;
213 * And add some heuristics for binary vs text, of course...
215 if (is_binary(len, &stats))
216 return 0;
218 if (crlf_action == CRLF_GUESS) {
220 * If the file in the index has any CR in it, do not convert.
221 * This is the new safer autocrlf handling.
223 if (has_cr_in_index(path))
224 return 0;
228 check_safe_crlf(path, crlf_action, &stats, checksafe);
230 /* Optimization: No CR? Nothing to convert, regardless. */
231 if (!stats.cr)
232 return 0;
234 /* only grow if not in place */
235 if (strbuf_avail(buf) + buf->len < len)
236 strbuf_grow(buf, len - buf->len);
237 dst = buf->buf;
238 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
240 * If we guessed, we already know we rejected a file with
241 * lone CR, and we can strip a CR without looking at what
242 * follow it.
244 do {
245 unsigned char c = *src++;
246 if (c != '\r')
247 *dst++ = c;
248 } while (--len);
249 } else {
250 do {
251 unsigned char c = *src++;
252 if (! (c == '\r' && (1 < len && *src == '\n')))
253 *dst++ = c;
254 } while (--len);
256 strbuf_setlen(buf, dst - buf->buf);
257 return 1;
260 static int crlf_to_worktree(const char *path, const char *src, size_t len,
261 struct strbuf *buf, enum crlf_action crlf_action)
263 char *to_free = NULL;
264 struct text_stat stats;
266 if (!len || output_eol(crlf_action) != EOL_CRLF)
267 return 0;
269 gather_stats(src, len, &stats);
271 /* No LF? Nothing to convert, regardless. */
272 if (!stats.lf)
273 return 0;
275 /* Was it already in CRLF format? */
276 if (stats.lf == stats.crlf)
277 return 0;
279 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
280 if (crlf_action == CRLF_GUESS) {
281 /* If we have any CR or CRLF line endings, we do not touch it */
282 /* This is the new safer autocrlf-handling */
283 if (stats.cr > 0 || stats.crlf > 0)
284 return 0;
287 /* If we have any bare CR characters, we're not going to touch it */
288 if (stats.cr != stats.crlf)
289 return 0;
291 if (is_binary(len, &stats))
292 return 0;
295 /* are we "faking" in place editing ? */
296 if (src == buf->buf)
297 to_free = strbuf_detach(buf, NULL);
299 strbuf_grow(buf, len + stats.lf - stats.crlf);
300 for (;;) {
301 const char *nl = memchr(src, '\n', len);
302 if (!nl)
303 break;
304 if (nl > src && nl[-1] == '\r') {
305 strbuf_add(buf, src, nl + 1 - src);
306 } else {
307 strbuf_add(buf, src, nl - src);
308 strbuf_addstr(buf, "\r\n");
310 len -= nl + 1 - src;
311 src = nl + 1;
313 strbuf_add(buf, src, len);
315 free(to_free);
316 return 1;
319 struct filter_params {
320 const char *src;
321 unsigned long size;
322 const char *cmd;
323 const char *path;
326 static int filter_buffer(int in, int out, void *data)
329 * Spawn cmd and feed the buffer contents through its stdin.
331 struct child_process child_process;
332 struct filter_params *params = (struct filter_params *)data;
333 int write_err, status;
334 const char *argv[] = { NULL, NULL };
336 /* apply % substitution to cmd */
337 struct strbuf cmd = STRBUF_INIT;
338 struct strbuf path = STRBUF_INIT;
339 struct strbuf_expand_dict_entry dict[] = {
340 { "f", NULL, },
341 { NULL, NULL, },
344 /* quote the path to preserve spaces, etc. */
345 sq_quote_buf(&path, params->path);
346 dict[0].value = path.buf;
348 /* expand all %f with the quoted path */
349 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
350 strbuf_release(&path);
352 argv[0] = cmd.buf;
354 memset(&child_process, 0, sizeof(child_process));
355 child_process.argv = argv;
356 child_process.use_shell = 1;
357 child_process.in = -1;
358 child_process.out = out;
360 if (start_command(&child_process))
361 return error("cannot fork to run external filter %s", params->cmd);
363 write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
364 if (close(child_process.in))
365 write_err = 1;
366 if (write_err)
367 error("cannot feed the input to external filter %s", params->cmd);
369 status = finish_command(&child_process);
370 if (status)
371 error("external filter %s failed %d", params->cmd, status);
373 strbuf_release(&cmd);
374 return (write_err || status);
377 static int apply_filter(const char *path, const char *src, size_t len,
378 struct strbuf *dst, const char *cmd)
381 * Create a pipeline to have the command filter the buffer's
382 * contents.
384 * (child --> cmd) --> us
386 int ret = 1;
387 struct strbuf nbuf = STRBUF_INIT;
388 struct async async;
389 struct filter_params params;
391 if (!cmd)
392 return 0;
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 || !count_ident(src, len))
532 return 0;
534 /* only grow if not in place */
535 if (strbuf_avail(buf) + buf->len < len)
536 strbuf_grow(buf, len - buf->len);
537 dst = buf->buf;
538 for (;;) {
539 dollar = memchr(src, '$', len);
540 if (!dollar)
541 break;
542 memmove(dst, src, dollar + 1 - src);
543 dst += dollar + 1 - src;
544 len -= dollar + 1 - src;
545 src = dollar + 1;
547 if (len > 3 && !memcmp(src, "Id:", 3)) {
548 dollar = memchr(src + 3, '$', len - 3);
549 if (!dollar)
550 break;
551 if (memchr(src + 3, '\n', dollar - src - 3)) {
552 /* Line break before the next dollar. */
553 continue;
556 memcpy(dst, "Id$", 3);
557 dst += 3;
558 len -= dollar + 1 - src;
559 src = dollar + 1;
562 memmove(dst, src, len);
563 strbuf_setlen(buf, dst + len - buf->buf);
564 return 1;
567 static int ident_to_worktree(const char *path, const char *src, size_t len,
568 struct strbuf *buf, int ident)
570 unsigned char sha1[20];
571 char *to_free = NULL, *dollar, *spc;
572 int cnt;
574 if (!ident)
575 return 0;
577 cnt = count_ident(src, len);
578 if (!cnt)
579 return 0;
581 /* are we "faking" in place editing ? */
582 if (src == buf->buf)
583 to_free = strbuf_detach(buf, NULL);
584 hash_sha1_file(src, len, "blob", sha1);
586 strbuf_grow(buf, len + cnt * 43);
587 for (;;) {
588 /* step 1: run to the next '$' */
589 dollar = memchr(src, '$', len);
590 if (!dollar)
591 break;
592 strbuf_add(buf, src, dollar + 1 - src);
593 len -= dollar + 1 - src;
594 src = dollar + 1;
596 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
597 if (len < 3 || memcmp("Id", src, 2))
598 continue;
600 /* step 3: skip over Id$ or Id:xxxxx$ */
601 if (src[2] == '$') {
602 src += 3;
603 len -= 3;
604 } else if (src[2] == ':') {
606 * It's possible that an expanded Id has crept its way into the
607 * repository, we cope with that by stripping the expansion out.
608 * This is probably not a good idea, since it will cause changes
609 * on checkout, which won't go away by stash, but let's keep it
610 * for git-style ids.
612 dollar = memchr(src + 3, '$', len - 3);
613 if (!dollar) {
614 /* incomplete keyword, no more '$', so just quit the loop */
615 break;
618 if (memchr(src + 3, '\n', dollar - src - 3)) {
619 /* Line break before the next dollar. */
620 continue;
623 spc = memchr(src + 4, ' ', dollar - src - 4);
624 if (spc && spc < dollar-1) {
625 /* There are spaces in unexpected places.
626 * This is probably an id from some other
627 * versioning system. Keep it for now.
629 continue;
632 len -= dollar + 1 - src;
633 src = dollar + 1;
634 } else {
635 /* it wasn't a "Id$" or "Id:xxxx$" */
636 continue;
639 /* step 4: substitute */
640 strbuf_addstr(buf, "Id: ");
641 strbuf_add(buf, sha1_to_hex(sha1), 40);
642 strbuf_addstr(buf, " $");
644 strbuf_add(buf, src, len);
646 free(to_free);
647 return 1;
650 static enum crlf_action git_path_check_crlf(const char *path, struct git_attr_check *check)
652 const char *value = check->value;
654 if (ATTR_TRUE(value))
655 return CRLF_TEXT;
656 else if (ATTR_FALSE(value))
657 return CRLF_BINARY;
658 else if (ATTR_UNSET(value))
660 else if (!strcmp(value, "input"))
661 return CRLF_INPUT;
662 else if (!strcmp(value, "auto"))
663 return CRLF_AUTO;
664 return CRLF_GUESS;
667 static enum eol git_path_check_eol(const char *path, struct git_attr_check *check)
669 const char *value = check->value;
671 if (ATTR_UNSET(value))
673 else if (!strcmp(value, "lf"))
674 return EOL_LF;
675 else if (!strcmp(value, "crlf"))
676 return EOL_CRLF;
677 return EOL_UNSET;
680 static struct convert_driver *git_path_check_convert(const char *path,
681 struct git_attr_check *check)
683 const char *value = check->value;
684 struct convert_driver *drv;
686 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
687 return NULL;
688 for (drv = user_convert; drv; drv = drv->next)
689 if (!strcmp(value, drv->name))
690 return drv;
691 return NULL;
694 static int git_path_check_ident(const char *path, struct git_attr_check *check)
696 const char *value = check->value;
698 return !!ATTR_TRUE(value);
701 static enum crlf_action input_crlf_action(enum crlf_action text_attr, enum eol eol_attr)
703 if (text_attr == CRLF_BINARY)
704 return CRLF_BINARY;
705 if (eol_attr == EOL_LF)
706 return CRLF_INPUT;
707 if (eol_attr == EOL_CRLF)
708 return CRLF_CRLF;
709 return text_attr;
712 struct conv_attrs {
713 struct convert_driver *drv;
714 enum crlf_action crlf_action;
715 enum eol eol_attr;
716 int ident;
719 static const char *conv_attr_name[] = {
720 "crlf", "ident", "filter", "eol", "text",
722 #define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
724 static void convert_attrs(struct conv_attrs *ca, const char *path)
726 int i;
727 static struct git_attr_check ccheck[NUM_CONV_ATTRS];
729 if (!ccheck[0].attr) {
730 for (i = 0; i < NUM_CONV_ATTRS; i++)
731 ccheck[i].attr = git_attr(conv_attr_name[i]);
732 user_convert_tail = &user_convert;
733 git_config(read_convert_config, NULL);
736 if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
737 ca->crlf_action = git_path_check_crlf(path, ccheck + 4);
738 if (ca->crlf_action == CRLF_GUESS)
739 ca->crlf_action = git_path_check_crlf(path, ccheck + 0);
740 ca->ident = git_path_check_ident(path, ccheck + 1);
741 ca->drv = git_path_check_convert(path, ccheck + 2);
742 ca->eol_attr = git_path_check_eol(path, ccheck + 3);
743 } else {
744 ca->drv = NULL;
745 ca->crlf_action = CRLF_GUESS;
746 ca->eol_attr = EOL_UNSET;
747 ca->ident = 0;
751 int convert_to_git(const char *path, const char *src, size_t len,
752 struct strbuf *dst, enum safe_crlf checksafe)
754 int ret = 0;
755 const char *filter = NULL;
756 int required = 0;
757 struct conv_attrs ca;
759 convert_attrs(&ca, path);
760 if (ca.drv) {
761 filter = ca.drv->clean;
762 required = ca.drv->required;
765 ret |= apply_filter(path, src, len, dst, filter);
766 if (!ret && required)
767 die("%s: clean filter '%s' failed", path, ca.drv->name);
769 if (ret) {
770 src = dst->buf;
771 len = dst->len;
773 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
774 ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
775 if (ret) {
776 src = dst->buf;
777 len = dst->len;
779 return ret | ident_to_git(path, src, len, dst, ca.ident);
782 static int convert_to_working_tree_internal(const char *path, const char *src,
783 size_t len, struct strbuf *dst,
784 int normalizing)
786 int ret = 0, ret_filter = 0;
787 const char *filter = NULL;
788 int required = 0;
789 struct conv_attrs ca;
791 convert_attrs(&ca, path);
792 if (ca.drv) {
793 filter = ca.drv->smudge;
794 required = ca.drv->required;
797 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
798 if (ret) {
799 src = dst->buf;
800 len = dst->len;
803 * CRLF conversion can be skipped if normalizing, unless there
804 * is a smudge filter. The filter might expect CRLFs.
806 if (filter || !normalizing) {
807 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
808 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
809 if (ret) {
810 src = dst->buf;
811 len = dst->len;
815 ret_filter = apply_filter(path, src, len, dst, filter);
816 if (!ret_filter && required)
817 die("%s: smudge filter %s failed", path, ca.drv->name);
819 return ret | ret_filter;
822 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
824 return convert_to_working_tree_internal(path, src, len, dst, 0);
827 int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
829 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
830 if (ret) {
831 src = dst->buf;
832 len = dst->len;
834 return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_FALSE);
837 /*****************************************************************
839 * Streaming converison support
841 *****************************************************************/
843 typedef int (*filter_fn)(struct stream_filter *,
844 const char *input, size_t *isize_p,
845 char *output, size_t *osize_p);
846 typedef void (*free_fn)(struct stream_filter *);
848 struct stream_filter_vtbl {
849 filter_fn filter;
850 free_fn free;
853 struct stream_filter {
854 struct stream_filter_vtbl *vtbl;
857 static int null_filter_fn(struct stream_filter *filter,
858 const char *input, size_t *isize_p,
859 char *output, size_t *osize_p)
861 size_t count;
863 if (!input)
864 return 0; /* we do not keep any states */
865 count = *isize_p;
866 if (*osize_p < count)
867 count = *osize_p;
868 if (count) {
869 memmove(output, input, count);
870 *isize_p -= count;
871 *osize_p -= count;
873 return 0;
876 static void null_free_fn(struct stream_filter *filter)
878 ; /* nothing -- null instances are shared */
881 static struct stream_filter_vtbl null_vtbl = {
882 null_filter_fn,
883 null_free_fn,
886 static struct stream_filter null_filter_singleton = {
887 &null_vtbl,
890 int is_null_stream_filter(struct stream_filter *filter)
892 return filter == &null_filter_singleton;
897 * LF-to-CRLF filter
900 struct lf_to_crlf_filter {
901 struct stream_filter filter;
902 unsigned has_held:1;
903 char held;
906 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
907 const char *input, size_t *isize_p,
908 char *output, size_t *osize_p)
910 size_t count, o = 0;
911 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
914 * We may be holding onto the CR to see if it is followed by a
915 * LF, in which case we would need to go to the main loop.
916 * Otherwise, just emit it to the output stream.
918 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
919 output[o++] = lf_to_crlf->held;
920 lf_to_crlf->has_held = 0;
923 /* We are told to drain */
924 if (!input) {
925 *osize_p -= o;
926 return 0;
929 count = *isize_p;
930 if (count || lf_to_crlf->has_held) {
931 size_t i;
932 int was_cr = 0;
934 if (lf_to_crlf->has_held) {
935 was_cr = 1;
936 lf_to_crlf->has_held = 0;
939 for (i = 0; o < *osize_p && i < count; i++) {
940 char ch = input[i];
942 if (ch == '\n') {
943 output[o++] = '\r';
944 } else if (was_cr) {
946 * Previous round saw CR and it is not followed
947 * by a LF; emit the CR before processing the
948 * current character.
950 output[o++] = '\r';
954 * We may have consumed the last output slot,
955 * in which case we need to break out of this
956 * loop; hold the current character before
957 * returning.
959 if (*osize_p <= o) {
960 lf_to_crlf->has_held = 1;
961 lf_to_crlf->held = ch;
962 continue; /* break but increment i */
965 if (ch == '\r') {
966 was_cr = 1;
967 continue;
970 was_cr = 0;
971 output[o++] = ch;
974 *osize_p -= o;
975 *isize_p -= i;
977 if (!lf_to_crlf->has_held && was_cr) {
978 lf_to_crlf->has_held = 1;
979 lf_to_crlf->held = '\r';
982 return 0;
985 static void lf_to_crlf_free_fn(struct stream_filter *filter)
987 free(filter);
990 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
991 lf_to_crlf_filter_fn,
992 lf_to_crlf_free_fn,
995 static struct stream_filter *lf_to_crlf_filter(void)
997 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
999 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1000 return (struct stream_filter *)lf_to_crlf;
1004 * Cascade filter
1006 #define FILTER_BUFFER 1024
1007 struct cascade_filter {
1008 struct stream_filter filter;
1009 struct stream_filter *one;
1010 struct stream_filter *two;
1011 char buf[FILTER_BUFFER];
1012 int end, ptr;
1015 static int cascade_filter_fn(struct stream_filter *filter,
1016 const char *input, size_t *isize_p,
1017 char *output, size_t *osize_p)
1019 struct cascade_filter *cas = (struct cascade_filter *) filter;
1020 size_t filled = 0;
1021 size_t sz = *osize_p;
1022 size_t to_feed, remaining;
1025 * input -- (one) --> buf -- (two) --> output
1027 while (filled < sz) {
1028 remaining = sz - filled;
1030 /* do we already have something to feed two with? */
1031 if (cas->ptr < cas->end) {
1032 to_feed = cas->end - cas->ptr;
1033 if (stream_filter(cas->two,
1034 cas->buf + cas->ptr, &to_feed,
1035 output + filled, &remaining))
1036 return -1;
1037 cas->ptr += (cas->end - cas->ptr) - to_feed;
1038 filled = sz - remaining;
1039 continue;
1042 /* feed one from upstream and have it emit into our buffer */
1043 to_feed = input ? *isize_p : 0;
1044 if (input && !to_feed)
1045 break;
1046 remaining = sizeof(cas->buf);
1047 if (stream_filter(cas->one,
1048 input, &to_feed,
1049 cas->buf, &remaining))
1050 return -1;
1051 cas->end = sizeof(cas->buf) - remaining;
1052 cas->ptr = 0;
1053 if (input) {
1054 size_t fed = *isize_p - to_feed;
1055 *isize_p -= fed;
1056 input += fed;
1059 /* do we know that we drained one completely? */
1060 if (input || cas->end)
1061 continue;
1063 /* tell two to drain; we have nothing more to give it */
1064 to_feed = 0;
1065 remaining = sz - filled;
1066 if (stream_filter(cas->two,
1067 NULL, &to_feed,
1068 output + filled, &remaining))
1069 return -1;
1070 if (remaining == (sz - filled))
1071 break; /* completely drained two */
1072 filled = sz - remaining;
1074 *osize_p -= filled;
1075 return 0;
1078 static void cascade_free_fn(struct stream_filter *filter)
1080 struct cascade_filter *cas = (struct cascade_filter *)filter;
1081 free_stream_filter(cas->one);
1082 free_stream_filter(cas->two);
1083 free(filter);
1086 static struct stream_filter_vtbl cascade_vtbl = {
1087 cascade_filter_fn,
1088 cascade_free_fn,
1091 static struct stream_filter *cascade_filter(struct stream_filter *one,
1092 struct stream_filter *two)
1094 struct cascade_filter *cascade;
1096 if (!one || is_null_stream_filter(one))
1097 return two;
1098 if (!two || is_null_stream_filter(two))
1099 return one;
1101 cascade = xmalloc(sizeof(*cascade));
1102 cascade->one = one;
1103 cascade->two = two;
1104 cascade->end = cascade->ptr = 0;
1105 cascade->filter.vtbl = &cascade_vtbl;
1106 return (struct stream_filter *)cascade;
1110 * ident filter
1112 #define IDENT_DRAINING (-1)
1113 #define IDENT_SKIPPING (-2)
1114 struct ident_filter {
1115 struct stream_filter filter;
1116 struct strbuf left;
1117 int state;
1118 char ident[45]; /* ": x40 $" */
1121 static int is_foreign_ident(const char *str)
1123 int i;
1125 if (prefixcmp(str, "$Id: "))
1126 return 0;
1127 for (i = 5; str[i]; i++) {
1128 if (isspace(str[i]) && str[i+1] != '$')
1129 return 1;
1131 return 0;
1134 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1136 size_t to_drain = ident->left.len;
1138 if (*osize_p < to_drain)
1139 to_drain = *osize_p;
1140 if (to_drain) {
1141 memcpy(*output_p, ident->left.buf, to_drain);
1142 strbuf_remove(&ident->left, 0, to_drain);
1143 *output_p += to_drain;
1144 *osize_p -= to_drain;
1146 if (!ident->left.len)
1147 ident->state = 0;
1150 static int ident_filter_fn(struct stream_filter *filter,
1151 const char *input, size_t *isize_p,
1152 char *output, size_t *osize_p)
1154 struct ident_filter *ident = (struct ident_filter *)filter;
1155 static const char head[] = "$Id";
1157 if (!input) {
1158 /* drain upon eof */
1159 switch (ident->state) {
1160 default:
1161 strbuf_add(&ident->left, head, ident->state);
1162 case IDENT_SKIPPING:
1163 /* fallthru */
1164 case IDENT_DRAINING:
1165 ident_drain(ident, &output, osize_p);
1167 return 0;
1170 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1171 int ch;
1173 if (ident->state == IDENT_DRAINING) {
1174 ident_drain(ident, &output, osize_p);
1175 if (!*osize_p)
1176 break;
1177 continue;
1180 ch = *(input++);
1181 (*isize_p)--;
1183 if (ident->state == IDENT_SKIPPING) {
1185 * Skipping until '$' or LF, but keeping them
1186 * in case it is a foreign ident.
1188 strbuf_addch(&ident->left, ch);
1189 if (ch != '\n' && ch != '$')
1190 continue;
1191 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1192 strbuf_setlen(&ident->left, sizeof(head) - 1);
1193 strbuf_addstr(&ident->left, ident->ident);
1195 ident->state = IDENT_DRAINING;
1196 continue;
1199 if (ident->state < sizeof(head) &&
1200 head[ident->state] == ch) {
1201 ident->state++;
1202 continue;
1205 if (ident->state)
1206 strbuf_add(&ident->left, head, ident->state);
1207 if (ident->state == sizeof(head) - 1) {
1208 if (ch != ':' && ch != '$') {
1209 strbuf_addch(&ident->left, ch);
1210 ident->state = 0;
1211 continue;
1214 if (ch == ':') {
1215 strbuf_addch(&ident->left, ch);
1216 ident->state = IDENT_SKIPPING;
1217 } else {
1218 strbuf_addstr(&ident->left, ident->ident);
1219 ident->state = IDENT_DRAINING;
1221 continue;
1224 strbuf_addch(&ident->left, ch);
1225 ident->state = IDENT_DRAINING;
1227 return 0;
1230 static void ident_free_fn(struct stream_filter *filter)
1232 struct ident_filter *ident = (struct ident_filter *)filter;
1233 strbuf_release(&ident->left);
1234 free(filter);
1237 static struct stream_filter_vtbl ident_vtbl = {
1238 ident_filter_fn,
1239 ident_free_fn,
1242 static struct stream_filter *ident_filter(const unsigned char *sha1)
1244 struct ident_filter *ident = xmalloc(sizeof(*ident));
1246 sprintf(ident->ident, ": %s $", sha1_to_hex(sha1));
1247 strbuf_init(&ident->left, 0);
1248 ident->filter.vtbl = &ident_vtbl;
1249 ident->state = 0;
1250 return (struct stream_filter *)ident;
1254 * Return an appropriately constructed filter for the path, or NULL if
1255 * the contents cannot be filtered without reading the whole thing
1256 * in-core.
1258 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1259 * large binary blob you would want us not to slurp into the memory!
1261 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1263 struct conv_attrs ca;
1264 enum crlf_action crlf_action;
1265 struct stream_filter *filter = NULL;
1267 convert_attrs(&ca, path);
1269 if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1270 return filter;
1272 if (ca.ident)
1273 filter = ident_filter(sha1);
1275 crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
1277 if ((crlf_action == CRLF_BINARY) || (crlf_action == CRLF_INPUT) ||
1278 (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE))
1279 filter = cascade_filter(filter, &null_filter_singleton);
1281 else if (output_eol(crlf_action) == EOL_CRLF &&
1282 !(crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS))
1283 filter = cascade_filter(filter, lf_to_crlf_filter());
1285 return filter;
1288 void free_stream_filter(struct stream_filter *filter)
1290 filter->vtbl->free(filter);
1293 int stream_filter(struct stream_filter *filter,
1294 const char *input, size_t *isize_p,
1295 char *output, size_t *osize_p)
1297 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);