Merge branch 'jc/am-3-nonstandard-popt' into next
[git/dscho.git] / convert.c
blob5d312cb10edc44dc8407d166f89e2cf0813f52f9
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 int pos, len;
157 unsigned long sz;
158 enum object_type type;
159 void *data;
160 int has_cr;
161 struct index_state *istate = &the_index;
163 len = strlen(path);
164 pos = index_name_pos(istate, path, len);
165 if (pos < 0) {
167 * We might be in the middle of a merge, in which
168 * case we would read stage #2 (ours).
170 int i;
171 for (i = -pos - 1;
172 (pos < 0 && i < istate->cache_nr &&
173 !strcmp(istate->cache[i]->name, path));
174 i++)
175 if (ce_stage(istate->cache[i]) == 2)
176 pos = i;
178 if (pos < 0)
179 return 0;
180 data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
181 if (!data || type != OBJ_BLOB) {
182 free(data);
183 return 0;
186 has_cr = memchr(data, '\r', sz) != NULL;
187 free(data);
188 return has_cr;
191 static int crlf_to_git(const char *path, const char *src, size_t len,
192 struct strbuf *buf,
193 enum crlf_action crlf_action, enum safe_crlf checksafe)
195 struct text_stat stats;
196 char *dst;
198 if (crlf_action == CRLF_BINARY ||
199 (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE) || !len)
200 return 0;
202 gather_stats(src, len, &stats);
204 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
206 * We're currently not going to even try to convert stuff
207 * that has bare CR characters. Does anybody do that crazy
208 * stuff?
210 if (stats.cr != stats.crlf)
211 return 0;
214 * And add some heuristics for binary vs text, of course...
216 if (is_binary(len, &stats))
217 return 0;
219 if (crlf_action == CRLF_GUESS) {
221 * If the file in the index has any CR in it, do not convert.
222 * This is the new safer autocrlf handling.
224 if (has_cr_in_index(path))
225 return 0;
229 check_safe_crlf(path, crlf_action, &stats, checksafe);
231 /* Optimization: No CR? Nothing to convert, regardless. */
232 if (!stats.cr)
233 return 0;
235 /* only grow if not in place */
236 if (strbuf_avail(buf) + buf->len < len)
237 strbuf_grow(buf, len - buf->len);
238 dst = buf->buf;
239 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
241 * If we guessed, we already know we rejected a file with
242 * lone CR, and we can strip a CR without looking at what
243 * follow it.
245 do {
246 unsigned char c = *src++;
247 if (c != '\r')
248 *dst++ = c;
249 } while (--len);
250 } else {
251 do {
252 unsigned char c = *src++;
253 if (! (c == '\r' && (1 < len && *src == '\n')))
254 *dst++ = c;
255 } while (--len);
257 strbuf_setlen(buf, dst - buf->buf);
258 return 1;
261 static int crlf_to_worktree(const char *path, const char *src, size_t len,
262 struct strbuf *buf, enum crlf_action crlf_action)
264 char *to_free = NULL;
265 struct text_stat stats;
267 if (!len || output_eol(crlf_action) != EOL_CRLF)
268 return 0;
270 gather_stats(src, len, &stats);
272 /* No LF? Nothing to convert, regardless. */
273 if (!stats.lf)
274 return 0;
276 /* Was it already in CRLF format? */
277 if (stats.lf == stats.crlf)
278 return 0;
280 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
281 if (crlf_action == CRLF_GUESS) {
282 /* If we have any CR or CRLF line endings, we do not touch it */
283 /* This is the new safer autocrlf-handling */
284 if (stats.cr > 0 || stats.crlf > 0)
285 return 0;
288 /* If we have any bare CR characters, we're not going to touch it */
289 if (stats.cr != stats.crlf)
290 return 0;
292 if (is_binary(len, &stats))
293 return 0;
296 /* are we "faking" in place editing ? */
297 if (src == buf->buf)
298 to_free = strbuf_detach(buf, NULL);
300 strbuf_grow(buf, len + stats.lf - stats.crlf);
301 for (;;) {
302 const char *nl = memchr(src, '\n', len);
303 if (!nl)
304 break;
305 if (nl > src && nl[-1] == '\r') {
306 strbuf_add(buf, src, nl + 1 - src);
307 } else {
308 strbuf_add(buf, src, nl - src);
309 strbuf_addstr(buf, "\r\n");
311 len -= nl + 1 - src;
312 src = nl + 1;
314 strbuf_add(buf, src, len);
316 free(to_free);
317 return 1;
320 struct filter_params {
321 const char *src;
322 unsigned long size;
323 const char *cmd;
324 const char *path;
327 static int filter_buffer(int in, int out, void *data)
330 * Spawn cmd and feed the buffer contents through its stdin.
332 struct child_process child_process;
333 struct filter_params *params = (struct filter_params *)data;
334 int write_err, status;
335 const char *argv[] = { NULL, NULL };
337 /* apply % substitution to cmd */
338 struct strbuf cmd = STRBUF_INIT;
339 struct strbuf path = STRBUF_INIT;
340 struct strbuf_expand_dict_entry dict[] = {
341 { "f", NULL, },
342 { NULL, NULL, },
345 /* quote the path to preserve spaces, etc. */
346 sq_quote_buf(&path, params->path);
347 dict[0].value = path.buf;
349 /* expand all %f with the quoted path */
350 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
351 strbuf_release(&path);
353 argv[0] = cmd.buf;
355 memset(&child_process, 0, sizeof(child_process));
356 child_process.argv = argv;
357 child_process.use_shell = 1;
358 child_process.in = -1;
359 child_process.out = out;
361 if (start_command(&child_process))
362 return error("cannot fork to run external filter %s", params->cmd);
364 sigchain_push(SIGPIPE, SIG_IGN);
366 write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
367 if (close(child_process.in))
368 write_err = 1;
369 if (write_err)
370 error("cannot feed the input to external filter %s", params->cmd);
372 sigchain_pop(SIGPIPE);
374 status = finish_command(&child_process);
375 if (status)
376 error("external filter %s failed %d", params->cmd, status);
378 strbuf_release(&cmd);
379 return (write_err || status);
382 static int apply_filter(const char *path, const char *src, size_t len,
383 struct strbuf *dst, const char *cmd)
386 * Create a pipeline to have the command filter the buffer's
387 * contents.
389 * (child --> cmd) --> us
391 int ret = 1;
392 struct strbuf nbuf = STRBUF_INIT;
393 struct async async;
394 struct filter_params params;
396 if (!cmd)
397 return 0;
399 memset(&async, 0, sizeof(async));
400 async.proc = filter_buffer;
401 async.data = &params;
402 async.out = -1;
403 params.src = src;
404 params.size = len;
405 params.cmd = cmd;
406 params.path = path;
408 fflush(NULL);
409 if (start_async(&async))
410 return 0; /* error was already reported */
412 if (strbuf_read(&nbuf, async.out, len) < 0) {
413 error("read from external filter %s failed", cmd);
414 ret = 0;
416 if (close(async.out)) {
417 error("read from external filter %s failed", cmd);
418 ret = 0;
420 if (finish_async(&async)) {
421 error("external filter %s failed", cmd);
422 ret = 0;
425 if (ret) {
426 strbuf_swap(dst, &nbuf);
428 strbuf_release(&nbuf);
429 return ret;
432 static struct convert_driver {
433 const char *name;
434 struct convert_driver *next;
435 const char *smudge;
436 const char *clean;
437 int required;
438 } *user_convert, **user_convert_tail;
440 static int read_convert_config(const char *var, const char *value, void *cb)
442 const char *ep, *name;
443 int namelen;
444 struct convert_driver *drv;
447 * External conversion drivers are configured using
448 * "filter.<name>.variable".
450 if (prefixcmp(var, "filter.") || (ep = strrchr(var, '.')) == var + 6)
451 return 0;
452 name = var + 7;
453 namelen = ep - name;
454 for (drv = user_convert; drv; drv = drv->next)
455 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
456 break;
457 if (!drv) {
458 drv = xcalloc(1, sizeof(struct convert_driver));
459 drv->name = xmemdupz(name, namelen);
460 *user_convert_tail = drv;
461 user_convert_tail = &(drv->next);
464 ep++;
467 * filter.<name>.smudge and filter.<name>.clean specifies
468 * the command line:
470 * command-line
472 * The command-line will not be interpolated in any way.
475 if (!strcmp("smudge", ep))
476 return git_config_string(&drv->smudge, var, value);
478 if (!strcmp("clean", ep))
479 return git_config_string(&drv->clean, var, value);
481 if (!strcmp("required", ep)) {
482 drv->required = git_config_bool(var, value);
483 return 0;
486 return 0;
489 static int count_ident(const char *cp, unsigned long size)
492 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
494 int cnt = 0;
495 char ch;
497 while (size) {
498 ch = *cp++;
499 size--;
500 if (ch != '$')
501 continue;
502 if (size < 3)
503 break;
504 if (memcmp("Id", cp, 2))
505 continue;
506 ch = cp[2];
507 cp += 3;
508 size -= 3;
509 if (ch == '$')
510 cnt++; /* $Id$ */
511 if (ch != ':')
512 continue;
515 * "$Id: ... "; scan up to the closing dollar sign and discard.
517 while (size) {
518 ch = *cp++;
519 size--;
520 if (ch == '$') {
521 cnt++;
522 break;
524 if (ch == '\n')
525 break;
528 return cnt;
531 static int ident_to_git(const char *path, const char *src, size_t len,
532 struct strbuf *buf, int ident)
534 char *dst, *dollar;
536 if (!ident || !count_ident(src, len))
537 return 0;
539 /* only grow if not in place */
540 if (strbuf_avail(buf) + buf->len < len)
541 strbuf_grow(buf, len - buf->len);
542 dst = buf->buf;
543 for (;;) {
544 dollar = memchr(src, '$', len);
545 if (!dollar)
546 break;
547 memmove(dst, src, dollar + 1 - src);
548 dst += dollar + 1 - src;
549 len -= dollar + 1 - src;
550 src = dollar + 1;
552 if (len > 3 && !memcmp(src, "Id:", 3)) {
553 dollar = memchr(src + 3, '$', len - 3);
554 if (!dollar)
555 break;
556 if (memchr(src + 3, '\n', dollar - src - 3)) {
557 /* Line break before the next dollar. */
558 continue;
561 memcpy(dst, "Id$", 3);
562 dst += 3;
563 len -= dollar + 1 - src;
564 src = dollar + 1;
567 memmove(dst, src, len);
568 strbuf_setlen(buf, dst + len - buf->buf);
569 return 1;
572 static int ident_to_worktree(const char *path, const char *src, size_t len,
573 struct strbuf *buf, int ident)
575 unsigned char sha1[20];
576 char *to_free = NULL, *dollar, *spc;
577 int cnt;
579 if (!ident)
580 return 0;
582 cnt = count_ident(src, len);
583 if (!cnt)
584 return 0;
586 /* are we "faking" in place editing ? */
587 if (src == buf->buf)
588 to_free = strbuf_detach(buf, NULL);
589 hash_sha1_file(src, len, "blob", sha1);
591 strbuf_grow(buf, len + cnt * 43);
592 for (;;) {
593 /* step 1: run to the next '$' */
594 dollar = memchr(src, '$', len);
595 if (!dollar)
596 break;
597 strbuf_add(buf, src, dollar + 1 - src);
598 len -= dollar + 1 - src;
599 src = dollar + 1;
601 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
602 if (len < 3 || memcmp("Id", src, 2))
603 continue;
605 /* step 3: skip over Id$ or Id:xxxxx$ */
606 if (src[2] == '$') {
607 src += 3;
608 len -= 3;
609 } else if (src[2] == ':') {
611 * It's possible that an expanded Id has crept its way into the
612 * repository, we cope with that by stripping the expansion out.
613 * This is probably not a good idea, since it will cause changes
614 * on checkout, which won't go away by stash, but let's keep it
615 * for git-style ids.
617 dollar = memchr(src + 3, '$', len - 3);
618 if (!dollar) {
619 /* incomplete keyword, no more '$', so just quit the loop */
620 break;
623 if (memchr(src + 3, '\n', dollar - src - 3)) {
624 /* Line break before the next dollar. */
625 continue;
628 spc = memchr(src + 4, ' ', dollar - src - 4);
629 if (spc && spc < dollar-1) {
630 /* There are spaces in unexpected places.
631 * This is probably an id from some other
632 * versioning system. Keep it for now.
634 continue;
637 len -= dollar + 1 - src;
638 src = dollar + 1;
639 } else {
640 /* it wasn't a "Id$" or "Id:xxxx$" */
641 continue;
644 /* step 4: substitute */
645 strbuf_addstr(buf, "Id: ");
646 strbuf_add(buf, sha1_to_hex(sha1), 40);
647 strbuf_addstr(buf, " $");
649 strbuf_add(buf, src, len);
651 free(to_free);
652 return 1;
655 static enum crlf_action git_path_check_crlf(const char *path, struct git_attr_check *check)
657 const char *value = check->value;
659 if (ATTR_TRUE(value))
660 return CRLF_TEXT;
661 else if (ATTR_FALSE(value))
662 return CRLF_BINARY;
663 else if (ATTR_UNSET(value))
665 else if (!strcmp(value, "input"))
666 return CRLF_INPUT;
667 else if (!strcmp(value, "auto"))
668 return CRLF_AUTO;
669 return CRLF_GUESS;
672 static enum eol git_path_check_eol(const char *path, struct git_attr_check *check)
674 const char *value = check->value;
676 if (ATTR_UNSET(value))
678 else if (!strcmp(value, "lf"))
679 return EOL_LF;
680 else if (!strcmp(value, "crlf"))
681 return EOL_CRLF;
682 return EOL_UNSET;
685 static struct convert_driver *git_path_check_convert(const char *path,
686 struct git_attr_check *check)
688 const char *value = check->value;
689 struct convert_driver *drv;
691 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
692 return NULL;
693 for (drv = user_convert; drv; drv = drv->next)
694 if (!strcmp(value, drv->name))
695 return drv;
696 return NULL;
699 static int git_path_check_ident(const char *path, struct git_attr_check *check)
701 const char *value = check->value;
703 return !!ATTR_TRUE(value);
706 static enum crlf_action input_crlf_action(enum crlf_action text_attr, enum eol eol_attr)
708 if (text_attr == CRLF_BINARY)
709 return CRLF_BINARY;
710 if (eol_attr == EOL_LF)
711 return CRLF_INPUT;
712 if (eol_attr == EOL_CRLF)
713 return CRLF_CRLF;
714 return text_attr;
717 struct conv_attrs {
718 struct convert_driver *drv;
719 enum crlf_action crlf_action;
720 enum eol eol_attr;
721 int ident;
724 static const char *conv_attr_name[] = {
725 "crlf", "ident", "filter", "eol", "text",
727 #define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
729 static void convert_attrs(struct conv_attrs *ca, const char *path)
731 int i;
732 static struct git_attr_check ccheck[NUM_CONV_ATTRS];
734 if (!ccheck[0].attr) {
735 for (i = 0; i < NUM_CONV_ATTRS; i++)
736 ccheck[i].attr = git_attr(conv_attr_name[i]);
737 user_convert_tail = &user_convert;
738 git_config(read_convert_config, NULL);
741 if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
742 ca->crlf_action = git_path_check_crlf(path, ccheck + 4);
743 if (ca->crlf_action == CRLF_GUESS)
744 ca->crlf_action = git_path_check_crlf(path, ccheck + 0);
745 ca->ident = git_path_check_ident(path, ccheck + 1);
746 ca->drv = git_path_check_convert(path, ccheck + 2);
747 ca->eol_attr = git_path_check_eol(path, ccheck + 3);
748 } else {
749 ca->drv = NULL;
750 ca->crlf_action = CRLF_GUESS;
751 ca->eol_attr = EOL_UNSET;
752 ca->ident = 0;
756 int convert_to_git(const char *path, const char *src, size_t len,
757 struct strbuf *dst, enum safe_crlf checksafe)
759 int ret = 0;
760 const char *filter = NULL;
761 int required = 0;
762 struct conv_attrs ca;
764 convert_attrs(&ca, path);
765 if (ca.drv) {
766 filter = ca.drv->clean;
767 required = ca.drv->required;
770 ret |= apply_filter(path, src, len, dst, filter);
771 if (!ret && required)
772 die("%s: clean filter '%s' failed", path, ca.drv->name);
774 if (ret) {
775 src = dst->buf;
776 len = dst->len;
778 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
779 ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
780 if (ret) {
781 src = dst->buf;
782 len = dst->len;
784 return ret | ident_to_git(path, src, len, dst, ca.ident);
787 static int convert_to_working_tree_internal(const char *path, const char *src,
788 size_t len, struct strbuf *dst,
789 int normalizing)
791 int ret = 0, ret_filter = 0;
792 const char *filter = NULL;
793 int required = 0;
794 struct conv_attrs ca;
796 convert_attrs(&ca, path);
797 if (ca.drv) {
798 filter = ca.drv->smudge;
799 required = ca.drv->required;
802 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
803 if (ret) {
804 src = dst->buf;
805 len = dst->len;
808 * CRLF conversion can be skipped if normalizing, unless there
809 * is a smudge filter. The filter might expect CRLFs.
811 if (filter || !normalizing) {
812 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
813 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
814 if (ret) {
815 src = dst->buf;
816 len = dst->len;
820 ret_filter = apply_filter(path, src, len, dst, filter);
821 if (!ret_filter && required)
822 die("%s: smudge filter %s failed", path, ca.drv->name);
824 return ret | ret_filter;
827 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
829 return convert_to_working_tree_internal(path, src, len, dst, 0);
832 int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
834 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
835 if (ret) {
836 src = dst->buf;
837 len = dst->len;
839 return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_FALSE);
842 /*****************************************************************
844 * Streaming converison support
846 *****************************************************************/
848 typedef int (*filter_fn)(struct stream_filter *,
849 const char *input, size_t *isize_p,
850 char *output, size_t *osize_p);
851 typedef void (*free_fn)(struct stream_filter *);
853 struct stream_filter_vtbl {
854 filter_fn filter;
855 free_fn free;
858 struct stream_filter {
859 struct stream_filter_vtbl *vtbl;
862 static int null_filter_fn(struct stream_filter *filter,
863 const char *input, size_t *isize_p,
864 char *output, size_t *osize_p)
866 size_t count;
868 if (!input)
869 return 0; /* we do not keep any states */
870 count = *isize_p;
871 if (*osize_p < count)
872 count = *osize_p;
873 if (count) {
874 memmove(output, input, count);
875 *isize_p -= count;
876 *osize_p -= count;
878 return 0;
881 static void null_free_fn(struct stream_filter *filter)
883 ; /* nothing -- null instances are shared */
886 static struct stream_filter_vtbl null_vtbl = {
887 null_filter_fn,
888 null_free_fn,
891 static struct stream_filter null_filter_singleton = {
892 &null_vtbl,
895 int is_null_stream_filter(struct stream_filter *filter)
897 return filter == &null_filter_singleton;
902 * LF-to-CRLF filter
905 struct lf_to_crlf_filter {
906 struct stream_filter filter;
907 unsigned has_held:1;
908 char held;
911 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
912 const char *input, size_t *isize_p,
913 char *output, size_t *osize_p)
915 size_t count, o = 0;
916 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
919 * We may be holding onto the CR to see if it is followed by a
920 * LF, in which case we would need to go to the main loop.
921 * Otherwise, just emit it to the output stream.
923 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
924 output[o++] = lf_to_crlf->held;
925 lf_to_crlf->has_held = 0;
928 /* We are told to drain */
929 if (!input) {
930 *osize_p -= o;
931 return 0;
934 count = *isize_p;
935 if (count || lf_to_crlf->has_held) {
936 size_t i;
937 int was_cr = 0;
939 if (lf_to_crlf->has_held) {
940 was_cr = 1;
941 lf_to_crlf->has_held = 0;
944 for (i = 0; o < *osize_p && i < count; i++) {
945 char ch = input[i];
947 if (ch == '\n') {
948 output[o++] = '\r';
949 } else if (was_cr) {
951 * Previous round saw CR and it is not followed
952 * by a LF; emit the CR before processing the
953 * current character.
955 output[o++] = '\r';
959 * We may have consumed the last output slot,
960 * in which case we need to break out of this
961 * loop; hold the current character before
962 * returning.
964 if (*osize_p <= o) {
965 lf_to_crlf->has_held = 1;
966 lf_to_crlf->held = ch;
967 continue; /* break but increment i */
970 if (ch == '\r') {
971 was_cr = 1;
972 continue;
975 was_cr = 0;
976 output[o++] = ch;
979 *osize_p -= o;
980 *isize_p -= i;
982 if (!lf_to_crlf->has_held && was_cr) {
983 lf_to_crlf->has_held = 1;
984 lf_to_crlf->held = '\r';
987 return 0;
990 static void lf_to_crlf_free_fn(struct stream_filter *filter)
992 free(filter);
995 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
996 lf_to_crlf_filter_fn,
997 lf_to_crlf_free_fn,
1000 static struct stream_filter *lf_to_crlf_filter(void)
1002 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1004 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1005 return (struct stream_filter *)lf_to_crlf;
1009 * Cascade filter
1011 #define FILTER_BUFFER 1024
1012 struct cascade_filter {
1013 struct stream_filter filter;
1014 struct stream_filter *one;
1015 struct stream_filter *two;
1016 char buf[FILTER_BUFFER];
1017 int end, ptr;
1020 static int cascade_filter_fn(struct stream_filter *filter,
1021 const char *input, size_t *isize_p,
1022 char *output, size_t *osize_p)
1024 struct cascade_filter *cas = (struct cascade_filter *) filter;
1025 size_t filled = 0;
1026 size_t sz = *osize_p;
1027 size_t to_feed, remaining;
1030 * input -- (one) --> buf -- (two) --> output
1032 while (filled < sz) {
1033 remaining = sz - filled;
1035 /* do we already have something to feed two with? */
1036 if (cas->ptr < cas->end) {
1037 to_feed = cas->end - cas->ptr;
1038 if (stream_filter(cas->two,
1039 cas->buf + cas->ptr, &to_feed,
1040 output + filled, &remaining))
1041 return -1;
1042 cas->ptr += (cas->end - cas->ptr) - to_feed;
1043 filled = sz - remaining;
1044 continue;
1047 /* feed one from upstream and have it emit into our buffer */
1048 to_feed = input ? *isize_p : 0;
1049 if (input && !to_feed)
1050 break;
1051 remaining = sizeof(cas->buf);
1052 if (stream_filter(cas->one,
1053 input, &to_feed,
1054 cas->buf, &remaining))
1055 return -1;
1056 cas->end = sizeof(cas->buf) - remaining;
1057 cas->ptr = 0;
1058 if (input) {
1059 size_t fed = *isize_p - to_feed;
1060 *isize_p -= fed;
1061 input += fed;
1064 /* do we know that we drained one completely? */
1065 if (input || cas->end)
1066 continue;
1068 /* tell two to drain; we have nothing more to give it */
1069 to_feed = 0;
1070 remaining = sz - filled;
1071 if (stream_filter(cas->two,
1072 NULL, &to_feed,
1073 output + filled, &remaining))
1074 return -1;
1075 if (remaining == (sz - filled))
1076 break; /* completely drained two */
1077 filled = sz - remaining;
1079 *osize_p -= filled;
1080 return 0;
1083 static void cascade_free_fn(struct stream_filter *filter)
1085 struct cascade_filter *cas = (struct cascade_filter *)filter;
1086 free_stream_filter(cas->one);
1087 free_stream_filter(cas->two);
1088 free(filter);
1091 static struct stream_filter_vtbl cascade_vtbl = {
1092 cascade_filter_fn,
1093 cascade_free_fn,
1096 static struct stream_filter *cascade_filter(struct stream_filter *one,
1097 struct stream_filter *two)
1099 struct cascade_filter *cascade;
1101 if (!one || is_null_stream_filter(one))
1102 return two;
1103 if (!two || is_null_stream_filter(two))
1104 return one;
1106 cascade = xmalloc(sizeof(*cascade));
1107 cascade->one = one;
1108 cascade->two = two;
1109 cascade->end = cascade->ptr = 0;
1110 cascade->filter.vtbl = &cascade_vtbl;
1111 return (struct stream_filter *)cascade;
1115 * ident filter
1117 #define IDENT_DRAINING (-1)
1118 #define IDENT_SKIPPING (-2)
1119 struct ident_filter {
1120 struct stream_filter filter;
1121 struct strbuf left;
1122 int state;
1123 char ident[45]; /* ": x40 $" */
1126 static int is_foreign_ident(const char *str)
1128 int i;
1130 if (prefixcmp(str, "$Id: "))
1131 return 0;
1132 for (i = 5; str[i]; i++) {
1133 if (isspace(str[i]) && str[i+1] != '$')
1134 return 1;
1136 return 0;
1139 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1141 size_t to_drain = ident->left.len;
1143 if (*osize_p < to_drain)
1144 to_drain = *osize_p;
1145 if (to_drain) {
1146 memcpy(*output_p, ident->left.buf, to_drain);
1147 strbuf_remove(&ident->left, 0, to_drain);
1148 *output_p += to_drain;
1149 *osize_p -= to_drain;
1151 if (!ident->left.len)
1152 ident->state = 0;
1155 static int ident_filter_fn(struct stream_filter *filter,
1156 const char *input, size_t *isize_p,
1157 char *output, size_t *osize_p)
1159 struct ident_filter *ident = (struct ident_filter *)filter;
1160 static const char head[] = "$Id";
1162 if (!input) {
1163 /* drain upon eof */
1164 switch (ident->state) {
1165 default:
1166 strbuf_add(&ident->left, head, ident->state);
1167 case IDENT_SKIPPING:
1168 /* fallthru */
1169 case IDENT_DRAINING:
1170 ident_drain(ident, &output, osize_p);
1172 return 0;
1175 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1176 int ch;
1178 if (ident->state == IDENT_DRAINING) {
1179 ident_drain(ident, &output, osize_p);
1180 if (!*osize_p)
1181 break;
1182 continue;
1185 ch = *(input++);
1186 (*isize_p)--;
1188 if (ident->state == IDENT_SKIPPING) {
1190 * Skipping until '$' or LF, but keeping them
1191 * in case it is a foreign ident.
1193 strbuf_addch(&ident->left, ch);
1194 if (ch != '\n' && ch != '$')
1195 continue;
1196 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1197 strbuf_setlen(&ident->left, sizeof(head) - 1);
1198 strbuf_addstr(&ident->left, ident->ident);
1200 ident->state = IDENT_DRAINING;
1201 continue;
1204 if (ident->state < sizeof(head) &&
1205 head[ident->state] == ch) {
1206 ident->state++;
1207 continue;
1210 if (ident->state)
1211 strbuf_add(&ident->left, head, ident->state);
1212 if (ident->state == sizeof(head) - 1) {
1213 if (ch != ':' && ch != '$') {
1214 strbuf_addch(&ident->left, ch);
1215 ident->state = 0;
1216 continue;
1219 if (ch == ':') {
1220 strbuf_addch(&ident->left, ch);
1221 ident->state = IDENT_SKIPPING;
1222 } else {
1223 strbuf_addstr(&ident->left, ident->ident);
1224 ident->state = IDENT_DRAINING;
1226 continue;
1229 strbuf_addch(&ident->left, ch);
1230 ident->state = IDENT_DRAINING;
1232 return 0;
1235 static void ident_free_fn(struct stream_filter *filter)
1237 struct ident_filter *ident = (struct ident_filter *)filter;
1238 strbuf_release(&ident->left);
1239 free(filter);
1242 static struct stream_filter_vtbl ident_vtbl = {
1243 ident_filter_fn,
1244 ident_free_fn,
1247 static struct stream_filter *ident_filter(const unsigned char *sha1)
1249 struct ident_filter *ident = xmalloc(sizeof(*ident));
1251 sprintf(ident->ident, ": %s $", sha1_to_hex(sha1));
1252 strbuf_init(&ident->left, 0);
1253 ident->filter.vtbl = &ident_vtbl;
1254 ident->state = 0;
1255 return (struct stream_filter *)ident;
1259 * Return an appropriately constructed filter for the path, or NULL if
1260 * the contents cannot be filtered without reading the whole thing
1261 * in-core.
1263 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1264 * large binary blob you would want us not to slurp into the memory!
1266 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1268 struct conv_attrs ca;
1269 enum crlf_action crlf_action;
1270 struct stream_filter *filter = NULL;
1272 convert_attrs(&ca, path);
1274 if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1275 return filter;
1277 if (ca.ident)
1278 filter = ident_filter(sha1);
1280 crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
1282 if ((crlf_action == CRLF_BINARY) || (crlf_action == CRLF_INPUT) ||
1283 (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE))
1284 filter = cascade_filter(filter, &null_filter_singleton);
1286 else if (output_eol(crlf_action) == EOL_CRLF &&
1287 !(crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS))
1288 filter = cascade_filter(filter, lf_to_crlf_filter());
1290 return filter;
1293 void free_stream_filter(struct stream_filter *filter)
1295 filter->vtbl->free(filter);
1298 int stream_filter(struct stream_filter *filter,
1299 const char *input, size_t *isize_p,
1300 char *output, size_t *osize_p)
1302 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);