teach convert_to_git a "dry run" mode
[git/mingw.git] / convert.c
blob65fa9d5eda94749559cd183437a5a108c6a174db
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;
235 * At this point all of our source analysis is done, and we are sure we
236 * would convert. If we are in dry-run mode, we can give an answer.
238 if (!buf)
239 return 1;
241 /* only grow if not in place */
242 if (strbuf_avail(buf) + buf->len < len)
243 strbuf_grow(buf, len - buf->len);
244 dst = buf->buf;
245 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
247 * If we guessed, we already know we rejected a file with
248 * lone CR, and we can strip a CR without looking at what
249 * follow it.
251 do {
252 unsigned char c = *src++;
253 if (c != '\r')
254 *dst++ = c;
255 } while (--len);
256 } else {
257 do {
258 unsigned char c = *src++;
259 if (! (c == '\r' && (1 < len && *src == '\n')))
260 *dst++ = c;
261 } while (--len);
263 strbuf_setlen(buf, dst - buf->buf);
264 return 1;
267 static int crlf_to_worktree(const char *path, const char *src, size_t len,
268 struct strbuf *buf, enum crlf_action crlf_action)
270 char *to_free = NULL;
271 struct text_stat stats;
273 if (!len || output_eol(crlf_action) != EOL_CRLF)
274 return 0;
276 gather_stats(src, len, &stats);
278 /* No LF? Nothing to convert, regardless. */
279 if (!stats.lf)
280 return 0;
282 /* Was it already in CRLF format? */
283 if (stats.lf == stats.crlf)
284 return 0;
286 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
287 if (crlf_action == CRLF_GUESS) {
288 /* If we have any CR or CRLF line endings, we do not touch it */
289 /* This is the new safer autocrlf-handling */
290 if (stats.cr > 0 || stats.crlf > 0)
291 return 0;
294 /* If we have any bare CR characters, we're not going to touch it */
295 if (stats.cr != stats.crlf)
296 return 0;
298 if (is_binary(len, &stats))
299 return 0;
302 /* are we "faking" in place editing ? */
303 if (src == buf->buf)
304 to_free = strbuf_detach(buf, NULL);
306 strbuf_grow(buf, len + stats.lf - stats.crlf);
307 for (;;) {
308 const char *nl = memchr(src, '\n', len);
309 if (!nl)
310 break;
311 if (nl > src && nl[-1] == '\r') {
312 strbuf_add(buf, src, nl + 1 - src);
313 } else {
314 strbuf_add(buf, src, nl - src);
315 strbuf_addstr(buf, "\r\n");
317 len -= nl + 1 - src;
318 src = nl + 1;
320 strbuf_add(buf, src, len);
322 free(to_free);
323 return 1;
326 struct filter_params {
327 const char *src;
328 unsigned long size;
329 const char *cmd;
330 const char *path;
333 static int filter_buffer(int in, int out, void *data)
336 * Spawn cmd and feed the buffer contents through its stdin.
338 struct child_process child_process;
339 struct filter_params *params = (struct filter_params *)data;
340 int write_err, status;
341 const char *argv[] = { NULL, NULL };
343 /* apply % substitution to cmd */
344 struct strbuf cmd = STRBUF_INIT;
345 struct strbuf path = STRBUF_INIT;
346 struct strbuf_expand_dict_entry dict[] = {
347 { "f", NULL, },
348 { NULL, NULL, },
351 /* quote the path to preserve spaces, etc. */
352 sq_quote_buf(&path, params->path);
353 dict[0].value = path.buf;
355 /* expand all %f with the quoted path */
356 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
357 strbuf_release(&path);
359 argv[0] = cmd.buf;
361 memset(&child_process, 0, sizeof(child_process));
362 child_process.argv = argv;
363 child_process.use_shell = 1;
364 child_process.in = -1;
365 child_process.out = out;
367 if (start_command(&child_process))
368 return error("cannot fork to run external filter %s", params->cmd);
370 write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
371 if (close(child_process.in))
372 write_err = 1;
373 if (write_err)
374 error("cannot feed the input to external filter %s", params->cmd);
376 status = finish_command(&child_process);
377 if (status)
378 error("external filter %s failed %d", params->cmd, status);
380 strbuf_release(&cmd);
381 return (write_err || status);
384 static int apply_filter(const char *path, const char *src, size_t len,
385 struct strbuf *dst, const char *cmd)
388 * Create a pipeline to have the command filter the buffer's
389 * contents.
391 * (child --> cmd) --> us
393 int ret = 1;
394 struct strbuf nbuf = STRBUF_INIT;
395 struct async async;
396 struct filter_params params;
398 if (!cmd)
399 return 0;
401 if (!dst)
402 return 1;
404 memset(&async, 0, sizeof(async));
405 async.proc = filter_buffer;
406 async.data = &params;
407 async.out = -1;
408 params.src = src;
409 params.size = len;
410 params.cmd = cmd;
411 params.path = path;
413 fflush(NULL);
414 if (start_async(&async))
415 return 0; /* error was already reported */
417 if (strbuf_read(&nbuf, async.out, len) < 0) {
418 error("read from external filter %s failed", cmd);
419 ret = 0;
421 if (close(async.out)) {
422 error("read from external filter %s failed", cmd);
423 ret = 0;
425 if (finish_async(&async)) {
426 error("external filter %s failed", cmd);
427 ret = 0;
430 if (ret) {
431 strbuf_swap(dst, &nbuf);
433 strbuf_release(&nbuf);
434 return ret;
437 static struct convert_driver {
438 const char *name;
439 struct convert_driver *next;
440 const char *smudge;
441 const char *clean;
442 } *user_convert, **user_convert_tail;
444 static int read_convert_config(const char *var, const char *value, void *cb)
446 const char *ep, *name;
447 int namelen;
448 struct convert_driver *drv;
451 * External conversion drivers are configured using
452 * "filter.<name>.variable".
454 if (prefixcmp(var, "filter.") || (ep = strrchr(var, '.')) == var + 6)
455 return 0;
456 name = var + 7;
457 namelen = ep - name;
458 for (drv = user_convert; drv; drv = drv->next)
459 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
460 break;
461 if (!drv) {
462 drv = xcalloc(1, sizeof(struct convert_driver));
463 drv->name = xmemdupz(name, namelen);
464 *user_convert_tail = drv;
465 user_convert_tail = &(drv->next);
468 ep++;
471 * filter.<name>.smudge and filter.<name>.clean specifies
472 * the command line:
474 * command-line
476 * The command-line will not be interpolated in any way.
479 if (!strcmp("smudge", ep))
480 return git_config_string(&drv->smudge, var, value);
482 if (!strcmp("clean", ep))
483 return git_config_string(&drv->clean, var, value);
485 return 0;
488 static int count_ident(const char *cp, unsigned long size)
491 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
493 int cnt = 0;
494 char ch;
496 while (size) {
497 ch = *cp++;
498 size--;
499 if (ch != '$')
500 continue;
501 if (size < 3)
502 break;
503 if (memcmp("Id", cp, 2))
504 continue;
505 ch = cp[2];
506 cp += 3;
507 size -= 3;
508 if (ch == '$')
509 cnt++; /* $Id$ */
510 if (ch != ':')
511 continue;
514 * "$Id: ... "; scan up to the closing dollar sign and discard.
516 while (size) {
517 ch = *cp++;
518 size--;
519 if (ch == '$') {
520 cnt++;
521 break;
523 if (ch == '\n')
524 break;
527 return cnt;
530 static int ident_to_git(const char *path, const char *src, size_t len,
531 struct strbuf *buf, int ident)
533 char *dst, *dollar;
535 if (!ident || !count_ident(src, len))
536 return 0;
538 if (!buf)
539 return 1;
541 /* only grow if not in place */
542 if (strbuf_avail(buf) + buf->len < len)
543 strbuf_grow(buf, len - buf->len);
544 dst = buf->buf;
545 for (;;) {
546 dollar = memchr(src, '$', len);
547 if (!dollar)
548 break;
549 memmove(dst, src, dollar + 1 - src);
550 dst += dollar + 1 - src;
551 len -= dollar + 1 - src;
552 src = dollar + 1;
554 if (len > 3 && !memcmp(src, "Id:", 3)) {
555 dollar = memchr(src + 3, '$', len - 3);
556 if (!dollar)
557 break;
558 if (memchr(src + 3, '\n', dollar - src - 3)) {
559 /* Line break before the next dollar. */
560 continue;
563 memcpy(dst, "Id$", 3);
564 dst += 3;
565 len -= dollar + 1 - src;
566 src = dollar + 1;
569 memmove(dst, src, len);
570 strbuf_setlen(buf, dst + len - buf->buf);
571 return 1;
574 static int ident_to_worktree(const char *path, const char *src, size_t len,
575 struct strbuf *buf, int ident)
577 unsigned char sha1[20];
578 char *to_free = NULL, *dollar, *spc;
579 int cnt;
581 if (!ident)
582 return 0;
584 cnt = count_ident(src, len);
585 if (!cnt)
586 return 0;
588 /* are we "faking" in place editing ? */
589 if (src == buf->buf)
590 to_free = strbuf_detach(buf, NULL);
591 hash_sha1_file(src, len, "blob", sha1);
593 strbuf_grow(buf, len + cnt * 43);
594 for (;;) {
595 /* step 1: run to the next '$' */
596 dollar = memchr(src, '$', len);
597 if (!dollar)
598 break;
599 strbuf_add(buf, src, dollar + 1 - src);
600 len -= dollar + 1 - src;
601 src = dollar + 1;
603 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
604 if (len < 3 || memcmp("Id", src, 2))
605 continue;
607 /* step 3: skip over Id$ or Id:xxxxx$ */
608 if (src[2] == '$') {
609 src += 3;
610 len -= 3;
611 } else if (src[2] == ':') {
613 * It's possible that an expanded Id has crept its way into the
614 * repository, we cope with that by stripping the expansion out.
615 * This is probably not a good idea, since it will cause changes
616 * on checkout, which won't go away by stash, but let's keep it
617 * for git-style ids.
619 dollar = memchr(src + 3, '$', len - 3);
620 if (!dollar) {
621 /* incomplete keyword, no more '$', so just quit the loop */
622 break;
625 if (memchr(src + 3, '\n', dollar - src - 3)) {
626 /* Line break before the next dollar. */
627 continue;
630 spc = memchr(src + 4, ' ', dollar - src - 4);
631 if (spc && spc < dollar-1) {
632 /* There are spaces in unexpected places.
633 * This is probably an id from some other
634 * versioning system. Keep it for now.
636 continue;
639 len -= dollar + 1 - src;
640 src = dollar + 1;
641 } else {
642 /* it wasn't a "Id$" or "Id:xxxx$" */
643 continue;
646 /* step 4: substitute */
647 strbuf_addstr(buf, "Id: ");
648 strbuf_add(buf, sha1_to_hex(sha1), 40);
649 strbuf_addstr(buf, " $");
651 strbuf_add(buf, src, len);
653 free(to_free);
654 return 1;
657 static enum crlf_action git_path_check_crlf(const char *path, struct git_attr_check *check)
659 const char *value = check->value;
661 if (ATTR_TRUE(value))
662 return CRLF_TEXT;
663 else if (ATTR_FALSE(value))
664 return CRLF_BINARY;
665 else if (ATTR_UNSET(value))
667 else if (!strcmp(value, "input"))
668 return CRLF_INPUT;
669 else if (!strcmp(value, "auto"))
670 return CRLF_AUTO;
671 return CRLF_GUESS;
674 static enum eol git_path_check_eol(const char *path, struct git_attr_check *check)
676 const char *value = check->value;
678 if (ATTR_UNSET(value))
680 else if (!strcmp(value, "lf"))
681 return EOL_LF;
682 else if (!strcmp(value, "crlf"))
683 return EOL_CRLF;
684 return EOL_UNSET;
687 static struct convert_driver *git_path_check_convert(const char *path,
688 struct git_attr_check *check)
690 const char *value = check->value;
691 struct convert_driver *drv;
693 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
694 return NULL;
695 for (drv = user_convert; drv; drv = drv->next)
696 if (!strcmp(value, drv->name))
697 return drv;
698 return NULL;
701 static int git_path_check_ident(const char *path, struct git_attr_check *check)
703 const char *value = check->value;
705 return !!ATTR_TRUE(value);
708 static enum crlf_action input_crlf_action(enum crlf_action text_attr, enum eol eol_attr)
710 if (text_attr == CRLF_BINARY)
711 return CRLF_BINARY;
712 if (eol_attr == EOL_LF)
713 return CRLF_INPUT;
714 if (eol_attr == EOL_CRLF)
715 return CRLF_CRLF;
716 return text_attr;
719 struct conv_attrs {
720 struct convert_driver *drv;
721 enum crlf_action crlf_action;
722 enum eol eol_attr;
723 int ident;
726 static const char *conv_attr_name[] = {
727 "crlf", "ident", "filter", "eol", "text",
729 #define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
731 static void convert_attrs(struct conv_attrs *ca, const char *path)
733 int i;
734 static struct git_attr_check ccheck[NUM_CONV_ATTRS];
736 if (!ccheck[0].attr) {
737 for (i = 0; i < NUM_CONV_ATTRS; i++)
738 ccheck[i].attr = git_attr(conv_attr_name[i]);
739 user_convert_tail = &user_convert;
740 git_config(read_convert_config, NULL);
743 if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
744 ca->crlf_action = git_path_check_crlf(path, ccheck + 4);
745 if (ca->crlf_action == CRLF_GUESS)
746 ca->crlf_action = git_path_check_crlf(path, ccheck + 0);
747 ca->ident = git_path_check_ident(path, ccheck + 1);
748 ca->drv = git_path_check_convert(path, ccheck + 2);
749 ca->eol_attr = git_path_check_eol(path, ccheck + 3);
750 } else {
751 ca->drv = NULL;
752 ca->crlf_action = CRLF_GUESS;
753 ca->eol_attr = EOL_UNSET;
754 ca->ident = 0;
758 int convert_to_git(const char *path, const char *src, size_t len,
759 struct strbuf *dst, enum safe_crlf checksafe)
761 int ret = 0;
762 const char *filter = NULL;
763 struct conv_attrs ca;
765 convert_attrs(&ca, path);
766 if (ca.drv)
767 filter = ca.drv->clean;
769 ret |= apply_filter(path, src, len, dst, filter);
770 if (ret && dst) {
771 src = dst->buf;
772 len = dst->len;
774 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
775 ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
776 if (ret && dst) {
777 src = dst->buf;
778 len = dst->len;
780 return ret | ident_to_git(path, src, len, dst, ca.ident);
783 static int convert_to_working_tree_internal(const char *path, const char *src,
784 size_t len, struct strbuf *dst,
785 int normalizing)
787 int ret = 0;
788 const char *filter = NULL;
789 struct conv_attrs ca;
791 convert_attrs(&ca, path);
792 if (ca.drv)
793 filter = ca.drv->smudge;
795 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
796 if (ret) {
797 src = dst->buf;
798 len = dst->len;
801 * CRLF conversion can be skipped if normalizing, unless there
802 * is a smudge filter. The filter might expect CRLFs.
804 if (filter || !normalizing) {
805 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
806 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
807 if (ret) {
808 src = dst->buf;
809 len = dst->len;
812 return ret | apply_filter(path, src, len, dst, filter);
815 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
817 return convert_to_working_tree_internal(path, src, len, dst, 0);
820 int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
822 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
823 if (ret) {
824 src = dst->buf;
825 len = dst->len;
827 return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_FALSE);
830 /*****************************************************************
832 * Streaming converison support
834 *****************************************************************/
836 typedef int (*filter_fn)(struct stream_filter *,
837 const char *input, size_t *isize_p,
838 char *output, size_t *osize_p);
839 typedef void (*free_fn)(struct stream_filter *);
841 struct stream_filter_vtbl {
842 filter_fn filter;
843 free_fn free;
846 struct stream_filter {
847 struct stream_filter_vtbl *vtbl;
850 static int null_filter_fn(struct stream_filter *filter,
851 const char *input, size_t *isize_p,
852 char *output, size_t *osize_p)
854 size_t count;
856 if (!input)
857 return 0; /* we do not keep any states */
858 count = *isize_p;
859 if (*osize_p < count)
860 count = *osize_p;
861 if (count) {
862 memmove(output, input, count);
863 *isize_p -= count;
864 *osize_p -= count;
866 return 0;
869 static void null_free_fn(struct stream_filter *filter)
871 ; /* nothing -- null instances are shared */
874 static struct stream_filter_vtbl null_vtbl = {
875 null_filter_fn,
876 null_free_fn,
879 static struct stream_filter null_filter_singleton = {
880 &null_vtbl,
883 int is_null_stream_filter(struct stream_filter *filter)
885 return filter == &null_filter_singleton;
890 * LF-to-CRLF filter
893 struct lf_to_crlf_filter {
894 struct stream_filter filter;
895 unsigned has_held:1;
896 char held;
899 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
900 const char *input, size_t *isize_p,
901 char *output, size_t *osize_p)
903 size_t count, o = 0;
904 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
907 * We may be holding onto the CR to see if it is followed by a
908 * LF, in which case we would need to go to the main loop.
909 * Otherwise, just emit it to the output stream.
911 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
912 output[o++] = lf_to_crlf->held;
913 lf_to_crlf->has_held = 0;
916 /* We are told to drain */
917 if (!input) {
918 *osize_p -= o;
919 return 0;
922 count = *isize_p;
923 if (count || lf_to_crlf->has_held) {
924 size_t i;
925 int was_cr = 0;
927 if (lf_to_crlf->has_held) {
928 was_cr = 1;
929 lf_to_crlf->has_held = 0;
932 for (i = 0; o < *osize_p && i < count; i++) {
933 char ch = input[i];
935 if (ch == '\n') {
936 output[o++] = '\r';
937 } else if (was_cr) {
939 * Previous round saw CR and it is not followed
940 * by a LF; emit the CR before processing the
941 * current character.
943 output[o++] = '\r';
947 * We may have consumed the last output slot,
948 * in which case we need to break out of this
949 * loop; hold the current character before
950 * returning.
952 if (*osize_p <= o) {
953 lf_to_crlf->has_held = 1;
954 lf_to_crlf->held = ch;
955 continue; /* break but increment i */
958 if (ch == '\r') {
959 was_cr = 1;
960 continue;
963 was_cr = 0;
964 output[o++] = ch;
967 *osize_p -= o;
968 *isize_p -= i;
970 if (!lf_to_crlf->has_held && was_cr) {
971 lf_to_crlf->has_held = 1;
972 lf_to_crlf->held = '\r';
975 return 0;
978 static void lf_to_crlf_free_fn(struct stream_filter *filter)
980 free(filter);
983 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
984 lf_to_crlf_filter_fn,
985 lf_to_crlf_free_fn,
988 static struct stream_filter *lf_to_crlf_filter(void)
990 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
992 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
993 return (struct stream_filter *)lf_to_crlf;
997 * Cascade filter
999 #define FILTER_BUFFER 1024
1000 struct cascade_filter {
1001 struct stream_filter filter;
1002 struct stream_filter *one;
1003 struct stream_filter *two;
1004 char buf[FILTER_BUFFER];
1005 int end, ptr;
1008 static int cascade_filter_fn(struct stream_filter *filter,
1009 const char *input, size_t *isize_p,
1010 char *output, size_t *osize_p)
1012 struct cascade_filter *cas = (struct cascade_filter *) filter;
1013 size_t filled = 0;
1014 size_t sz = *osize_p;
1015 size_t to_feed, remaining;
1018 * input -- (one) --> buf -- (two) --> output
1020 while (filled < sz) {
1021 remaining = sz - filled;
1023 /* do we already have something to feed two with? */
1024 if (cas->ptr < cas->end) {
1025 to_feed = cas->end - cas->ptr;
1026 if (stream_filter(cas->two,
1027 cas->buf + cas->ptr, &to_feed,
1028 output + filled, &remaining))
1029 return -1;
1030 cas->ptr += (cas->end - cas->ptr) - to_feed;
1031 filled = sz - remaining;
1032 continue;
1035 /* feed one from upstream and have it emit into our buffer */
1036 to_feed = input ? *isize_p : 0;
1037 if (input && !to_feed)
1038 break;
1039 remaining = sizeof(cas->buf);
1040 if (stream_filter(cas->one,
1041 input, &to_feed,
1042 cas->buf, &remaining))
1043 return -1;
1044 cas->end = sizeof(cas->buf) - remaining;
1045 cas->ptr = 0;
1046 if (input) {
1047 size_t fed = *isize_p - to_feed;
1048 *isize_p -= fed;
1049 input += fed;
1052 /* do we know that we drained one completely? */
1053 if (input || cas->end)
1054 continue;
1056 /* tell two to drain; we have nothing more to give it */
1057 to_feed = 0;
1058 remaining = sz - filled;
1059 if (stream_filter(cas->two,
1060 NULL, &to_feed,
1061 output + filled, &remaining))
1062 return -1;
1063 if (remaining == (sz - filled))
1064 break; /* completely drained two */
1065 filled = sz - remaining;
1067 *osize_p -= filled;
1068 return 0;
1071 static void cascade_free_fn(struct stream_filter *filter)
1073 struct cascade_filter *cas = (struct cascade_filter *)filter;
1074 free_stream_filter(cas->one);
1075 free_stream_filter(cas->two);
1076 free(filter);
1079 static struct stream_filter_vtbl cascade_vtbl = {
1080 cascade_filter_fn,
1081 cascade_free_fn,
1084 static struct stream_filter *cascade_filter(struct stream_filter *one,
1085 struct stream_filter *two)
1087 struct cascade_filter *cascade;
1089 if (!one || is_null_stream_filter(one))
1090 return two;
1091 if (!two || is_null_stream_filter(two))
1092 return one;
1094 cascade = xmalloc(sizeof(*cascade));
1095 cascade->one = one;
1096 cascade->two = two;
1097 cascade->end = cascade->ptr = 0;
1098 cascade->filter.vtbl = &cascade_vtbl;
1099 return (struct stream_filter *)cascade;
1103 * ident filter
1105 #define IDENT_DRAINING (-1)
1106 #define IDENT_SKIPPING (-2)
1107 struct ident_filter {
1108 struct stream_filter filter;
1109 struct strbuf left;
1110 int state;
1111 char ident[45]; /* ": x40 $" */
1114 static int is_foreign_ident(const char *str)
1116 int i;
1118 if (prefixcmp(str, "$Id: "))
1119 return 0;
1120 for (i = 5; str[i]; i++) {
1121 if (isspace(str[i]) && str[i+1] != '$')
1122 return 1;
1124 return 0;
1127 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1129 size_t to_drain = ident->left.len;
1131 if (*osize_p < to_drain)
1132 to_drain = *osize_p;
1133 if (to_drain) {
1134 memcpy(*output_p, ident->left.buf, to_drain);
1135 strbuf_remove(&ident->left, 0, to_drain);
1136 *output_p += to_drain;
1137 *osize_p -= to_drain;
1139 if (!ident->left.len)
1140 ident->state = 0;
1143 static int ident_filter_fn(struct stream_filter *filter,
1144 const char *input, size_t *isize_p,
1145 char *output, size_t *osize_p)
1147 struct ident_filter *ident = (struct ident_filter *)filter;
1148 static const char head[] = "$Id";
1150 if (!input) {
1151 /* drain upon eof */
1152 switch (ident->state) {
1153 default:
1154 strbuf_add(&ident->left, head, ident->state);
1155 case IDENT_SKIPPING:
1156 /* fallthru */
1157 case IDENT_DRAINING:
1158 ident_drain(ident, &output, osize_p);
1160 return 0;
1163 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1164 int ch;
1166 if (ident->state == IDENT_DRAINING) {
1167 ident_drain(ident, &output, osize_p);
1168 if (!*osize_p)
1169 break;
1170 continue;
1173 ch = *(input++);
1174 (*isize_p)--;
1176 if (ident->state == IDENT_SKIPPING) {
1178 * Skipping until '$' or LF, but keeping them
1179 * in case it is a foreign ident.
1181 strbuf_addch(&ident->left, ch);
1182 if (ch != '\n' && ch != '$')
1183 continue;
1184 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1185 strbuf_setlen(&ident->left, sizeof(head) - 1);
1186 strbuf_addstr(&ident->left, ident->ident);
1188 ident->state = IDENT_DRAINING;
1189 continue;
1192 if (ident->state < sizeof(head) &&
1193 head[ident->state] == ch) {
1194 ident->state++;
1195 continue;
1198 if (ident->state)
1199 strbuf_add(&ident->left, head, ident->state);
1200 if (ident->state == sizeof(head) - 1) {
1201 if (ch != ':' && ch != '$') {
1202 strbuf_addch(&ident->left, ch);
1203 ident->state = 0;
1204 continue;
1207 if (ch == ':') {
1208 strbuf_addch(&ident->left, ch);
1209 ident->state = IDENT_SKIPPING;
1210 } else {
1211 strbuf_addstr(&ident->left, ident->ident);
1212 ident->state = IDENT_DRAINING;
1214 continue;
1217 strbuf_addch(&ident->left, ch);
1218 ident->state = IDENT_DRAINING;
1220 return 0;
1223 static void ident_free_fn(struct stream_filter *filter)
1225 struct ident_filter *ident = (struct ident_filter *)filter;
1226 strbuf_release(&ident->left);
1227 free(filter);
1230 static struct stream_filter_vtbl ident_vtbl = {
1231 ident_filter_fn,
1232 ident_free_fn,
1235 static struct stream_filter *ident_filter(const unsigned char *sha1)
1237 struct ident_filter *ident = xmalloc(sizeof(*ident));
1239 sprintf(ident->ident, ": %s $", sha1_to_hex(sha1));
1240 strbuf_init(&ident->left, 0);
1241 ident->filter.vtbl = &ident_vtbl;
1242 ident->state = 0;
1243 return (struct stream_filter *)ident;
1247 * Return an appropriately constructed filter for the path, or NULL if
1248 * the contents cannot be filtered without reading the whole thing
1249 * in-core.
1251 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1252 * large binary blob you would want us not to slurp into the memory!
1254 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1256 struct conv_attrs ca;
1257 enum crlf_action crlf_action;
1258 struct stream_filter *filter = NULL;
1260 convert_attrs(&ca, path);
1262 if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1263 return filter;
1265 if (ca.ident)
1266 filter = ident_filter(sha1);
1268 crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
1270 if ((crlf_action == CRLF_BINARY) || (crlf_action == CRLF_INPUT) ||
1271 (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE))
1272 filter = cascade_filter(filter, &null_filter_singleton);
1274 else if (output_eol(crlf_action) == EOL_CRLF &&
1275 !(crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS))
1276 filter = cascade_filter(filter, lf_to_crlf_filter());
1278 return filter;
1281 void free_stream_filter(struct stream_filter *filter)
1283 filter->vtbl->free(filter);
1286 int stream_filter(struct stream_filter *filter,
1287 const char *input, size_t *isize_p,
1288 char *output, size_t *osize_p)
1290 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);