completion: zsh: don't override suffix on _detault
[git/debian.git] / convert.c
blob3520252d3abaf49d4b7682ad083da8b7ae6be4c6
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) ||
200 (src && !len))
201 return 0;
204 * If we are doing a dry-run and have no source buffer, there is
205 * nothing to analyze; we must assume we would convert.
207 if (!buf && !src)
208 return 1;
210 gather_stats(src, len, &stats);
212 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
214 * We're currently not going to even try to convert stuff
215 * that has bare CR characters. Does anybody do that crazy
216 * stuff?
218 if (stats.cr != stats.crlf)
219 return 0;
222 * And add some heuristics for binary vs text, of course...
224 if (is_binary(len, &stats))
225 return 0;
227 if (crlf_action == CRLF_GUESS) {
229 * If the file in the index has any CR in it, do not convert.
230 * This is the new safer autocrlf handling.
232 if (has_cr_in_index(path))
233 return 0;
237 check_safe_crlf(path, crlf_action, &stats, checksafe);
239 /* Optimization: No CR? Nothing to convert, regardless. */
240 if (!stats.cr)
241 return 0;
244 * At this point all of our source analysis is done, and we are sure we
245 * would convert. If we are in dry-run mode, we can give an answer.
247 if (!buf)
248 return 1;
250 /* only grow if not in place */
251 if (strbuf_avail(buf) + buf->len < len)
252 strbuf_grow(buf, len - buf->len);
253 dst = buf->buf;
254 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
256 * If we guessed, we already know we rejected a file with
257 * lone CR, and we can strip a CR without looking at what
258 * follow it.
260 do {
261 unsigned char c = *src++;
262 if (c != '\r')
263 *dst++ = c;
264 } while (--len);
265 } else {
266 do {
267 unsigned char c = *src++;
268 if (! (c == '\r' && (1 < len && *src == '\n')))
269 *dst++ = c;
270 } while (--len);
272 strbuf_setlen(buf, dst - buf->buf);
273 return 1;
276 static int crlf_to_worktree(const char *path, const char *src, size_t len,
277 struct strbuf *buf, enum crlf_action crlf_action)
279 char *to_free = NULL;
280 struct text_stat stats;
282 if (!len || output_eol(crlf_action) != EOL_CRLF)
283 return 0;
285 gather_stats(src, len, &stats);
287 /* No LF? Nothing to convert, regardless. */
288 if (!stats.lf)
289 return 0;
291 /* Was it already in CRLF format? */
292 if (stats.lf == stats.crlf)
293 return 0;
295 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
296 if (crlf_action == CRLF_GUESS) {
297 /* If we have any CR or CRLF line endings, we do not touch it */
298 /* This is the new safer autocrlf-handling */
299 if (stats.cr > 0 || stats.crlf > 0)
300 return 0;
303 /* If we have any bare CR characters, we're not going to touch it */
304 if (stats.cr != stats.crlf)
305 return 0;
307 if (is_binary(len, &stats))
308 return 0;
311 /* are we "faking" in place editing ? */
312 if (src == buf->buf)
313 to_free = strbuf_detach(buf, NULL);
315 strbuf_grow(buf, len + stats.lf - stats.crlf);
316 for (;;) {
317 const char *nl = memchr(src, '\n', len);
318 if (!nl)
319 break;
320 if (nl > src && nl[-1] == '\r') {
321 strbuf_add(buf, src, nl + 1 - src);
322 } else {
323 strbuf_add(buf, src, nl - src);
324 strbuf_addstr(buf, "\r\n");
326 len -= nl + 1 - src;
327 src = nl + 1;
329 strbuf_add(buf, src, len);
331 free(to_free);
332 return 1;
335 struct filter_params {
336 const char *src;
337 unsigned long size;
338 const char *cmd;
339 const char *path;
342 static int filter_buffer(int in, int out, void *data)
345 * Spawn cmd and feed the buffer contents through its stdin.
347 struct child_process child_process;
348 struct filter_params *params = (struct filter_params *)data;
349 int write_err, status;
350 const char *argv[] = { NULL, NULL };
352 /* apply % substitution to cmd */
353 struct strbuf cmd = STRBUF_INIT;
354 struct strbuf path = STRBUF_INIT;
355 struct strbuf_expand_dict_entry dict[] = {
356 { "f", NULL, },
357 { NULL, NULL, },
360 /* quote the path to preserve spaces, etc. */
361 sq_quote_buf(&path, params->path);
362 dict[0].value = path.buf;
364 /* expand all %f with the quoted path */
365 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
366 strbuf_release(&path);
368 argv[0] = cmd.buf;
370 memset(&child_process, 0, sizeof(child_process));
371 child_process.argv = argv;
372 child_process.use_shell = 1;
373 child_process.in = -1;
374 child_process.out = out;
376 if (start_command(&child_process))
377 return error("cannot fork to run external filter %s", params->cmd);
379 sigchain_push(SIGPIPE, SIG_IGN);
381 write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
382 if (close(child_process.in))
383 write_err = 1;
384 if (write_err)
385 error("cannot feed the input to external filter %s", params->cmd);
387 sigchain_pop(SIGPIPE);
389 status = finish_command(&child_process);
390 if (status)
391 error("external filter %s failed %d", params->cmd, status);
393 strbuf_release(&cmd);
394 return (write_err || status);
397 static int apply_filter(const char *path, const char *src, size_t len,
398 struct strbuf *dst, const char *cmd)
401 * Create a pipeline to have the command filter the buffer's
402 * contents.
404 * (child --> cmd) --> us
406 int ret = 1;
407 struct strbuf nbuf = STRBUF_INIT;
408 struct async async;
409 struct filter_params params;
411 if (!cmd)
412 return 0;
414 if (!dst)
415 return 1;
417 memset(&async, 0, sizeof(async));
418 async.proc = filter_buffer;
419 async.data = &params;
420 async.out = -1;
421 params.src = src;
422 params.size = len;
423 params.cmd = cmd;
424 params.path = path;
426 fflush(NULL);
427 if (start_async(&async))
428 return 0; /* error was already reported */
430 if (strbuf_read(&nbuf, async.out, len) < 0) {
431 error("read from external filter %s failed", cmd);
432 ret = 0;
434 if (close(async.out)) {
435 error("read from external filter %s failed", cmd);
436 ret = 0;
438 if (finish_async(&async)) {
439 error("external filter %s failed", cmd);
440 ret = 0;
443 if (ret) {
444 strbuf_swap(dst, &nbuf);
446 strbuf_release(&nbuf);
447 return ret;
450 static struct convert_driver {
451 const char *name;
452 struct convert_driver *next;
453 const char *smudge;
454 const char *clean;
455 int required;
456 } *user_convert, **user_convert_tail;
458 static int read_convert_config(const char *var, const char *value, void *cb)
460 const char *key, *name;
461 int namelen;
462 struct convert_driver *drv;
465 * External conversion drivers are configured using
466 * "filter.<name>.variable".
468 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
469 return 0;
470 for (drv = user_convert; drv; drv = drv->next)
471 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
472 break;
473 if (!drv) {
474 drv = xcalloc(1, sizeof(struct convert_driver));
475 drv->name = xmemdupz(name, namelen);
476 *user_convert_tail = drv;
477 user_convert_tail = &(drv->next);
481 * filter.<name>.smudge and filter.<name>.clean specifies
482 * the command line:
484 * command-line
486 * The command-line will not be interpolated in any way.
489 if (!strcmp("smudge", key))
490 return git_config_string(&drv->smudge, var, value);
492 if (!strcmp("clean", key))
493 return git_config_string(&drv->clean, var, value);
495 if (!strcmp("required", key)) {
496 drv->required = git_config_bool(var, value);
497 return 0;
500 return 0;
503 static int count_ident(const char *cp, unsigned long size)
506 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
508 int cnt = 0;
509 char ch;
511 while (size) {
512 ch = *cp++;
513 size--;
514 if (ch != '$')
515 continue;
516 if (size < 3)
517 break;
518 if (memcmp("Id", cp, 2))
519 continue;
520 ch = cp[2];
521 cp += 3;
522 size -= 3;
523 if (ch == '$')
524 cnt++; /* $Id$ */
525 if (ch != ':')
526 continue;
529 * "$Id: ... "; scan up to the closing dollar sign and discard.
531 while (size) {
532 ch = *cp++;
533 size--;
534 if (ch == '$') {
535 cnt++;
536 break;
538 if (ch == '\n')
539 break;
542 return cnt;
545 static int ident_to_git(const char *path, const char *src, size_t len,
546 struct strbuf *buf, int ident)
548 char *dst, *dollar;
550 if (!ident || (src && !count_ident(src, len)))
551 return 0;
553 if (!buf)
554 return 1;
556 /* only grow if not in place */
557 if (strbuf_avail(buf) + buf->len < len)
558 strbuf_grow(buf, len - buf->len);
559 dst = buf->buf;
560 for (;;) {
561 dollar = memchr(src, '$', len);
562 if (!dollar)
563 break;
564 memmove(dst, src, dollar + 1 - src);
565 dst += dollar + 1 - src;
566 len -= dollar + 1 - src;
567 src = dollar + 1;
569 if (len > 3 && !memcmp(src, "Id:", 3)) {
570 dollar = memchr(src + 3, '$', len - 3);
571 if (!dollar)
572 break;
573 if (memchr(src + 3, '\n', dollar - src - 3)) {
574 /* Line break before the next dollar. */
575 continue;
578 memcpy(dst, "Id$", 3);
579 dst += 3;
580 len -= dollar + 1 - src;
581 src = dollar + 1;
584 memmove(dst, src, len);
585 strbuf_setlen(buf, dst + len - buf->buf);
586 return 1;
589 static int ident_to_worktree(const char *path, const char *src, size_t len,
590 struct strbuf *buf, int ident)
592 unsigned char sha1[20];
593 char *to_free = NULL, *dollar, *spc;
594 int cnt;
596 if (!ident)
597 return 0;
599 cnt = count_ident(src, len);
600 if (!cnt)
601 return 0;
603 /* are we "faking" in place editing ? */
604 if (src == buf->buf)
605 to_free = strbuf_detach(buf, NULL);
606 hash_sha1_file(src, len, "blob", sha1);
608 strbuf_grow(buf, len + cnt * 43);
609 for (;;) {
610 /* step 1: run to the next '$' */
611 dollar = memchr(src, '$', len);
612 if (!dollar)
613 break;
614 strbuf_add(buf, src, dollar + 1 - src);
615 len -= dollar + 1 - src;
616 src = dollar + 1;
618 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
619 if (len < 3 || memcmp("Id", src, 2))
620 continue;
622 /* step 3: skip over Id$ or Id:xxxxx$ */
623 if (src[2] == '$') {
624 src += 3;
625 len -= 3;
626 } else if (src[2] == ':') {
628 * It's possible that an expanded Id has crept its way into the
629 * repository, we cope with that by stripping the expansion out.
630 * This is probably not a good idea, since it will cause changes
631 * on checkout, which won't go away by stash, but let's keep it
632 * for git-style ids.
634 dollar = memchr(src + 3, '$', len - 3);
635 if (!dollar) {
636 /* incomplete keyword, no more '$', so just quit the loop */
637 break;
640 if (memchr(src + 3, '\n', dollar - src - 3)) {
641 /* Line break before the next dollar. */
642 continue;
645 spc = memchr(src + 4, ' ', dollar - src - 4);
646 if (spc && spc < dollar-1) {
647 /* There are spaces in unexpected places.
648 * This is probably an id from some other
649 * versioning system. Keep it for now.
651 continue;
654 len -= dollar + 1 - src;
655 src = dollar + 1;
656 } else {
657 /* it wasn't a "Id$" or "Id:xxxx$" */
658 continue;
661 /* step 4: substitute */
662 strbuf_addstr(buf, "Id: ");
663 strbuf_add(buf, sha1_to_hex(sha1), 40);
664 strbuf_addstr(buf, " $");
666 strbuf_add(buf, src, len);
668 free(to_free);
669 return 1;
672 static enum crlf_action git_path_check_crlf(const char *path, struct git_attr_check *check)
674 const char *value = check->value;
676 if (ATTR_TRUE(value))
677 return CRLF_TEXT;
678 else if (ATTR_FALSE(value))
679 return CRLF_BINARY;
680 else if (ATTR_UNSET(value))
682 else if (!strcmp(value, "input"))
683 return CRLF_INPUT;
684 else if (!strcmp(value, "auto"))
685 return CRLF_AUTO;
686 return CRLF_GUESS;
689 static enum eol git_path_check_eol(const char *path, struct git_attr_check *check)
691 const char *value = check->value;
693 if (ATTR_UNSET(value))
695 else if (!strcmp(value, "lf"))
696 return EOL_LF;
697 else if (!strcmp(value, "crlf"))
698 return EOL_CRLF;
699 return EOL_UNSET;
702 static struct convert_driver *git_path_check_convert(const char *path,
703 struct git_attr_check *check)
705 const char *value = check->value;
706 struct convert_driver *drv;
708 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
709 return NULL;
710 for (drv = user_convert; drv; drv = drv->next)
711 if (!strcmp(value, drv->name))
712 return drv;
713 return NULL;
716 static int git_path_check_ident(const char *path, struct git_attr_check *check)
718 const char *value = check->value;
720 return !!ATTR_TRUE(value);
723 static enum crlf_action input_crlf_action(enum crlf_action text_attr, enum eol eol_attr)
725 if (text_attr == CRLF_BINARY)
726 return CRLF_BINARY;
727 if (eol_attr == EOL_LF)
728 return CRLF_INPUT;
729 if (eol_attr == EOL_CRLF)
730 return CRLF_CRLF;
731 return text_attr;
734 struct conv_attrs {
735 struct convert_driver *drv;
736 enum crlf_action crlf_action;
737 enum eol eol_attr;
738 int ident;
741 static const char *conv_attr_name[] = {
742 "crlf", "ident", "filter", "eol", "text",
744 #define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
746 static void convert_attrs(struct conv_attrs *ca, const char *path)
748 int i;
749 static struct git_attr_check ccheck[NUM_CONV_ATTRS];
751 if (!ccheck[0].attr) {
752 for (i = 0; i < NUM_CONV_ATTRS; i++)
753 ccheck[i].attr = git_attr(conv_attr_name[i]);
754 user_convert_tail = &user_convert;
755 git_config(read_convert_config, NULL);
758 if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
759 ca->crlf_action = git_path_check_crlf(path, ccheck + 4);
760 if (ca->crlf_action == CRLF_GUESS)
761 ca->crlf_action = git_path_check_crlf(path, ccheck + 0);
762 ca->ident = git_path_check_ident(path, ccheck + 1);
763 ca->drv = git_path_check_convert(path, ccheck + 2);
764 ca->eol_attr = git_path_check_eol(path, ccheck + 3);
765 } else {
766 ca->drv = NULL;
767 ca->crlf_action = CRLF_GUESS;
768 ca->eol_attr = EOL_UNSET;
769 ca->ident = 0;
773 int convert_to_git(const char *path, const char *src, size_t len,
774 struct strbuf *dst, enum safe_crlf checksafe)
776 int ret = 0;
777 const char *filter = NULL;
778 int required = 0;
779 struct conv_attrs ca;
781 convert_attrs(&ca, path);
782 if (ca.drv) {
783 filter = ca.drv->clean;
784 required = ca.drv->required;
787 ret |= apply_filter(path, src, len, dst, filter);
788 if (!ret && required)
789 die("%s: clean filter '%s' failed", path, ca.drv->name);
791 if (ret && dst) {
792 src = dst->buf;
793 len = dst->len;
795 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
796 ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
797 if (ret && dst) {
798 src = dst->buf;
799 len = dst->len;
801 return ret | ident_to_git(path, src, len, dst, ca.ident);
804 static int convert_to_working_tree_internal(const char *path, const char *src,
805 size_t len, struct strbuf *dst,
806 int normalizing)
808 int ret = 0, ret_filter = 0;
809 const char *filter = NULL;
810 int required = 0;
811 struct conv_attrs ca;
813 convert_attrs(&ca, path);
814 if (ca.drv) {
815 filter = ca.drv->smudge;
816 required = ca.drv->required;
819 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
820 if (ret) {
821 src = dst->buf;
822 len = dst->len;
825 * CRLF conversion can be skipped if normalizing, unless there
826 * is a smudge filter. The filter might expect CRLFs.
828 if (filter || !normalizing) {
829 ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
830 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
831 if (ret) {
832 src = dst->buf;
833 len = dst->len;
837 ret_filter = apply_filter(path, src, len, dst, filter);
838 if (!ret_filter && required)
839 die("%s: smudge filter %s failed", path, ca.drv->name);
841 return ret | ret_filter;
844 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
846 return convert_to_working_tree_internal(path, src, len, dst, 0);
849 int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
851 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
852 if (ret) {
853 src = dst->buf;
854 len = dst->len;
856 return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_FALSE);
859 /*****************************************************************
861 * Streaming converison support
863 *****************************************************************/
865 typedef int (*filter_fn)(struct stream_filter *,
866 const char *input, size_t *isize_p,
867 char *output, size_t *osize_p);
868 typedef void (*free_fn)(struct stream_filter *);
870 struct stream_filter_vtbl {
871 filter_fn filter;
872 free_fn free;
875 struct stream_filter {
876 struct stream_filter_vtbl *vtbl;
879 static int null_filter_fn(struct stream_filter *filter,
880 const char *input, size_t *isize_p,
881 char *output, size_t *osize_p)
883 size_t count;
885 if (!input)
886 return 0; /* we do not keep any states */
887 count = *isize_p;
888 if (*osize_p < count)
889 count = *osize_p;
890 if (count) {
891 memmove(output, input, count);
892 *isize_p -= count;
893 *osize_p -= count;
895 return 0;
898 static void null_free_fn(struct stream_filter *filter)
900 ; /* nothing -- null instances are shared */
903 static struct stream_filter_vtbl null_vtbl = {
904 null_filter_fn,
905 null_free_fn,
908 static struct stream_filter null_filter_singleton = {
909 &null_vtbl,
912 int is_null_stream_filter(struct stream_filter *filter)
914 return filter == &null_filter_singleton;
919 * LF-to-CRLF filter
922 struct lf_to_crlf_filter {
923 struct stream_filter filter;
924 unsigned has_held:1;
925 char held;
928 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
929 const char *input, size_t *isize_p,
930 char *output, size_t *osize_p)
932 size_t count, o = 0;
933 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
936 * We may be holding onto the CR to see if it is followed by a
937 * LF, in which case we would need to go to the main loop.
938 * Otherwise, just emit it to the output stream.
940 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
941 output[o++] = lf_to_crlf->held;
942 lf_to_crlf->has_held = 0;
945 /* We are told to drain */
946 if (!input) {
947 *osize_p -= o;
948 return 0;
951 count = *isize_p;
952 if (count || lf_to_crlf->has_held) {
953 size_t i;
954 int was_cr = 0;
956 if (lf_to_crlf->has_held) {
957 was_cr = 1;
958 lf_to_crlf->has_held = 0;
961 for (i = 0; o < *osize_p && i < count; i++) {
962 char ch = input[i];
964 if (ch == '\n') {
965 output[o++] = '\r';
966 } else if (was_cr) {
968 * Previous round saw CR and it is not followed
969 * by a LF; emit the CR before processing the
970 * current character.
972 output[o++] = '\r';
976 * We may have consumed the last output slot,
977 * in which case we need to break out of this
978 * loop; hold the current character before
979 * returning.
981 if (*osize_p <= o) {
982 lf_to_crlf->has_held = 1;
983 lf_to_crlf->held = ch;
984 continue; /* break but increment i */
987 if (ch == '\r') {
988 was_cr = 1;
989 continue;
992 was_cr = 0;
993 output[o++] = ch;
996 *osize_p -= o;
997 *isize_p -= i;
999 if (!lf_to_crlf->has_held && was_cr) {
1000 lf_to_crlf->has_held = 1;
1001 lf_to_crlf->held = '\r';
1004 return 0;
1007 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1009 free(filter);
1012 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1013 lf_to_crlf_filter_fn,
1014 lf_to_crlf_free_fn,
1017 static struct stream_filter *lf_to_crlf_filter(void)
1019 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1021 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1022 return (struct stream_filter *)lf_to_crlf;
1026 * Cascade filter
1028 #define FILTER_BUFFER 1024
1029 struct cascade_filter {
1030 struct stream_filter filter;
1031 struct stream_filter *one;
1032 struct stream_filter *two;
1033 char buf[FILTER_BUFFER];
1034 int end, ptr;
1037 static int cascade_filter_fn(struct stream_filter *filter,
1038 const char *input, size_t *isize_p,
1039 char *output, size_t *osize_p)
1041 struct cascade_filter *cas = (struct cascade_filter *) filter;
1042 size_t filled = 0;
1043 size_t sz = *osize_p;
1044 size_t to_feed, remaining;
1047 * input -- (one) --> buf -- (two) --> output
1049 while (filled < sz) {
1050 remaining = sz - filled;
1052 /* do we already have something to feed two with? */
1053 if (cas->ptr < cas->end) {
1054 to_feed = cas->end - cas->ptr;
1055 if (stream_filter(cas->two,
1056 cas->buf + cas->ptr, &to_feed,
1057 output + filled, &remaining))
1058 return -1;
1059 cas->ptr += (cas->end - cas->ptr) - to_feed;
1060 filled = sz - remaining;
1061 continue;
1064 /* feed one from upstream and have it emit into our buffer */
1065 to_feed = input ? *isize_p : 0;
1066 if (input && !to_feed)
1067 break;
1068 remaining = sizeof(cas->buf);
1069 if (stream_filter(cas->one,
1070 input, &to_feed,
1071 cas->buf, &remaining))
1072 return -1;
1073 cas->end = sizeof(cas->buf) - remaining;
1074 cas->ptr = 0;
1075 if (input) {
1076 size_t fed = *isize_p - to_feed;
1077 *isize_p -= fed;
1078 input += fed;
1081 /* do we know that we drained one completely? */
1082 if (input || cas->end)
1083 continue;
1085 /* tell two to drain; we have nothing more to give it */
1086 to_feed = 0;
1087 remaining = sz - filled;
1088 if (stream_filter(cas->two,
1089 NULL, &to_feed,
1090 output + filled, &remaining))
1091 return -1;
1092 if (remaining == (sz - filled))
1093 break; /* completely drained two */
1094 filled = sz - remaining;
1096 *osize_p -= filled;
1097 return 0;
1100 static void cascade_free_fn(struct stream_filter *filter)
1102 struct cascade_filter *cas = (struct cascade_filter *)filter;
1103 free_stream_filter(cas->one);
1104 free_stream_filter(cas->two);
1105 free(filter);
1108 static struct stream_filter_vtbl cascade_vtbl = {
1109 cascade_filter_fn,
1110 cascade_free_fn,
1113 static struct stream_filter *cascade_filter(struct stream_filter *one,
1114 struct stream_filter *two)
1116 struct cascade_filter *cascade;
1118 if (!one || is_null_stream_filter(one))
1119 return two;
1120 if (!two || is_null_stream_filter(two))
1121 return one;
1123 cascade = xmalloc(sizeof(*cascade));
1124 cascade->one = one;
1125 cascade->two = two;
1126 cascade->end = cascade->ptr = 0;
1127 cascade->filter.vtbl = &cascade_vtbl;
1128 return (struct stream_filter *)cascade;
1132 * ident filter
1134 #define IDENT_DRAINING (-1)
1135 #define IDENT_SKIPPING (-2)
1136 struct ident_filter {
1137 struct stream_filter filter;
1138 struct strbuf left;
1139 int state;
1140 char ident[45]; /* ": x40 $" */
1143 static int is_foreign_ident(const char *str)
1145 int i;
1147 if (prefixcmp(str, "$Id: "))
1148 return 0;
1149 for (i = 5; str[i]; i++) {
1150 if (isspace(str[i]) && str[i+1] != '$')
1151 return 1;
1153 return 0;
1156 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1158 size_t to_drain = ident->left.len;
1160 if (*osize_p < to_drain)
1161 to_drain = *osize_p;
1162 if (to_drain) {
1163 memcpy(*output_p, ident->left.buf, to_drain);
1164 strbuf_remove(&ident->left, 0, to_drain);
1165 *output_p += to_drain;
1166 *osize_p -= to_drain;
1168 if (!ident->left.len)
1169 ident->state = 0;
1172 static int ident_filter_fn(struct stream_filter *filter,
1173 const char *input, size_t *isize_p,
1174 char *output, size_t *osize_p)
1176 struct ident_filter *ident = (struct ident_filter *)filter;
1177 static const char head[] = "$Id";
1179 if (!input) {
1180 /* drain upon eof */
1181 switch (ident->state) {
1182 default:
1183 strbuf_add(&ident->left, head, ident->state);
1184 case IDENT_SKIPPING:
1185 /* fallthru */
1186 case IDENT_DRAINING:
1187 ident_drain(ident, &output, osize_p);
1189 return 0;
1192 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1193 int ch;
1195 if (ident->state == IDENT_DRAINING) {
1196 ident_drain(ident, &output, osize_p);
1197 if (!*osize_p)
1198 break;
1199 continue;
1202 ch = *(input++);
1203 (*isize_p)--;
1205 if (ident->state == IDENT_SKIPPING) {
1207 * Skipping until '$' or LF, but keeping them
1208 * in case it is a foreign ident.
1210 strbuf_addch(&ident->left, ch);
1211 if (ch != '\n' && ch != '$')
1212 continue;
1213 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1214 strbuf_setlen(&ident->left, sizeof(head) - 1);
1215 strbuf_addstr(&ident->left, ident->ident);
1217 ident->state = IDENT_DRAINING;
1218 continue;
1221 if (ident->state < sizeof(head) &&
1222 head[ident->state] == ch) {
1223 ident->state++;
1224 continue;
1227 if (ident->state)
1228 strbuf_add(&ident->left, head, ident->state);
1229 if (ident->state == sizeof(head) - 1) {
1230 if (ch != ':' && ch != '$') {
1231 strbuf_addch(&ident->left, ch);
1232 ident->state = 0;
1233 continue;
1236 if (ch == ':') {
1237 strbuf_addch(&ident->left, ch);
1238 ident->state = IDENT_SKIPPING;
1239 } else {
1240 strbuf_addstr(&ident->left, ident->ident);
1241 ident->state = IDENT_DRAINING;
1243 continue;
1246 strbuf_addch(&ident->left, ch);
1247 ident->state = IDENT_DRAINING;
1249 return 0;
1252 static void ident_free_fn(struct stream_filter *filter)
1254 struct ident_filter *ident = (struct ident_filter *)filter;
1255 strbuf_release(&ident->left);
1256 free(filter);
1259 static struct stream_filter_vtbl ident_vtbl = {
1260 ident_filter_fn,
1261 ident_free_fn,
1264 static struct stream_filter *ident_filter(const unsigned char *sha1)
1266 struct ident_filter *ident = xmalloc(sizeof(*ident));
1268 sprintf(ident->ident, ": %s $", sha1_to_hex(sha1));
1269 strbuf_init(&ident->left, 0);
1270 ident->filter.vtbl = &ident_vtbl;
1271 ident->state = 0;
1272 return (struct stream_filter *)ident;
1276 * Return an appropriately constructed filter for the path, or NULL if
1277 * the contents cannot be filtered without reading the whole thing
1278 * in-core.
1280 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1281 * large binary blob you would want us not to slurp into the memory!
1283 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1285 struct conv_attrs ca;
1286 enum crlf_action crlf_action;
1287 struct stream_filter *filter = NULL;
1289 convert_attrs(&ca, path);
1291 if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1292 return filter;
1294 if (ca.ident)
1295 filter = ident_filter(sha1);
1297 crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
1299 if ((crlf_action == CRLF_BINARY) || (crlf_action == CRLF_INPUT) ||
1300 (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE))
1301 filter = cascade_filter(filter, &null_filter_singleton);
1303 else if (output_eol(crlf_action) == EOL_CRLF &&
1304 !(crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS))
1305 filter = cascade_filter(filter, lf_to_crlf_filter());
1307 return filter;
1310 void free_stream_filter(struct stream_filter *filter)
1312 filter->vtbl->free(filter);
1315 int stream_filter(struct stream_filter *filter,
1316 const char *input, size_t *isize_p,
1317 char *output, size_t *osize_p)
1319 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);