convert.c: use text_eol_is_crlf()
[git/debian.git] / convert.c
blob557e574da60fee6302140fbcb9e154e1cafd5253
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 /* Stat bits: When BIN is set, the txt bits are unset */
17 #define CONVERT_STAT_BITS_TXT_LF 0x1
18 #define CONVERT_STAT_BITS_TXT_CRLF 0x2
19 #define CONVERT_STAT_BITS_BIN 0x4
21 enum crlf_action {
22 CRLF_GUESS = -1,
23 CRLF_BINARY = 0,
24 CRLF_TEXT,
25 CRLF_INPUT,
26 CRLF_CRLF,
27 CRLF_AUTO
30 struct text_stat {
31 /* NUL, CR, LF and CRLF counts */
32 unsigned nul, cr, lf, crlf;
34 /* These are just approximations! */
35 unsigned printable, nonprintable;
38 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
40 unsigned long i;
42 memset(stats, 0, sizeof(*stats));
44 for (i = 0; i < size; i++) {
45 unsigned char c = buf[i];
46 if (c == '\r') {
47 stats->cr++;
48 if (i+1 < size && buf[i+1] == '\n')
49 stats->crlf++;
50 continue;
52 if (c == '\n') {
53 stats->lf++;
54 continue;
56 if (c == 127)
57 /* DEL */
58 stats->nonprintable++;
59 else if (c < 32) {
60 switch (c) {
61 /* BS, HT, ESC and FF */
62 case '\b': case '\t': case '\033': case '\014':
63 stats->printable++;
64 break;
65 case 0:
66 stats->nul++;
67 /* fall through */
68 default:
69 stats->nonprintable++;
72 else
73 stats->printable++;
76 /* If file ends with EOF then don't count this EOF as non-printable. */
77 if (size >= 1 && buf[size-1] == '\032')
78 stats->nonprintable--;
82 * The same heuristics as diff.c::mmfile_is_binary()
83 * We treat files with bare CR as binary
85 static int convert_is_binary(unsigned long size, const struct text_stat *stats)
87 if (stats->cr != stats->crlf)
88 return 1;
89 if (stats->nul)
90 return 1;
91 if ((stats->printable >> 7) < stats->nonprintable)
92 return 1;
93 return 0;
96 static unsigned int gather_convert_stats(const char *data, unsigned long size)
98 struct text_stat stats;
99 if (!data || !size)
100 return 0;
101 gather_stats(data, size, &stats);
102 if (convert_is_binary(size, &stats))
103 return CONVERT_STAT_BITS_BIN;
104 else if (stats.crlf && stats.crlf == stats.lf)
105 return CONVERT_STAT_BITS_TXT_CRLF;
106 else if (stats.crlf && stats.lf)
107 return CONVERT_STAT_BITS_TXT_CRLF | CONVERT_STAT_BITS_TXT_LF;
108 else if (stats.lf)
109 return CONVERT_STAT_BITS_TXT_LF;
110 else
111 return 0;
114 static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
116 unsigned int convert_stats = gather_convert_stats(data, size);
118 if (convert_stats & CONVERT_STAT_BITS_BIN)
119 return "-text";
120 switch (convert_stats) {
121 case CONVERT_STAT_BITS_TXT_LF:
122 return "lf";
123 case CONVERT_STAT_BITS_TXT_CRLF:
124 return "crlf";
125 case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
126 return "mixed";
127 default:
128 return "none";
132 const char *get_cached_convert_stats_ascii(const char *path)
134 const char *ret;
135 unsigned long sz;
136 void *data = read_blob_data_from_cache(path, &sz);
137 ret = gather_convert_stats_ascii(data, sz);
138 free(data);
139 return ret;
142 const char *get_wt_convert_stats_ascii(const char *path)
144 const char *ret = "";
145 struct strbuf sb = STRBUF_INIT;
146 if (strbuf_read_file(&sb, path, 0) >= 0)
147 ret = gather_convert_stats_ascii(sb.buf, sb.len);
148 strbuf_release(&sb);
149 return ret;
152 static int text_eol_is_crlf(void)
154 if (auto_crlf == AUTO_CRLF_TRUE)
155 return 1;
156 else if (auto_crlf == AUTO_CRLF_INPUT)
157 return 0;
158 if (core_eol == EOL_CRLF)
159 return 1;
160 if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
161 return 1;
162 return 0;
165 static enum eol output_eol(enum crlf_action crlf_action)
167 switch (crlf_action) {
168 case CRLF_BINARY:
169 return EOL_UNSET;
170 case CRLF_CRLF:
171 return EOL_CRLF;
172 case CRLF_INPUT:
173 return EOL_LF;
174 case CRLF_GUESS:
175 if (!auto_crlf)
176 return EOL_UNSET;
177 /* fall through */
178 case CRLF_TEXT:
179 case CRLF_AUTO:
180 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
182 return core_eol;
185 static void check_safe_crlf(const char *path, enum crlf_action crlf_action,
186 struct text_stat *stats, enum safe_crlf checksafe)
188 if (!checksafe)
189 return;
191 if (output_eol(crlf_action) == EOL_LF) {
193 * CRLFs would not be restored by checkout:
194 * check if we'd remove CRLFs
196 if (stats->crlf) {
197 if (checksafe == SAFE_CRLF_WARN)
198 warning("CRLF will be replaced by LF in %s.\nThe file will have its original line endings in your working directory.", path);
199 else /* i.e. SAFE_CRLF_FAIL */
200 die("CRLF would be replaced by LF in %s.", path);
202 } else if (output_eol(crlf_action) == EOL_CRLF) {
204 * CRLFs would be added by checkout:
205 * check if we have "naked" LFs
207 if (stats->lf != stats->crlf) {
208 if (checksafe == SAFE_CRLF_WARN)
209 warning("LF will be replaced by CRLF in %s.\nThe file will have its original line endings in your working directory.", path);
210 else /* i.e. SAFE_CRLF_FAIL */
211 die("LF would be replaced by CRLF in %s", path);
216 static int has_cr_in_index(const char *path)
218 unsigned long sz;
219 void *data;
220 int has_cr;
222 data = read_blob_data_from_cache(path, &sz);
223 if (!data)
224 return 0;
225 has_cr = memchr(data, '\r', sz) != NULL;
226 free(data);
227 return has_cr;
230 static int crlf_to_git(const char *path, const char *src, size_t len,
231 struct strbuf *buf,
232 enum crlf_action crlf_action, enum safe_crlf checksafe)
234 struct text_stat stats;
235 char *dst;
237 if (crlf_action == CRLF_BINARY ||
238 (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE) ||
239 (src && !len))
240 return 0;
243 * If we are doing a dry-run and have no source buffer, there is
244 * nothing to analyze; we must assume we would convert.
246 if (!buf && !src)
247 return 1;
249 gather_stats(src, len, &stats);
251 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
252 if (convert_is_binary(len, &stats))
253 return 0;
255 if (crlf_action == CRLF_GUESS) {
257 * If the file in the index has any CR in it, do not convert.
258 * This is the new safer autocrlf handling.
260 if (has_cr_in_index(path))
261 return 0;
265 check_safe_crlf(path, crlf_action, &stats, checksafe);
267 /* Optimization: No CR? Nothing to convert, regardless. */
268 if (!stats.cr)
269 return 0;
272 * At this point all of our source analysis is done, and we are sure we
273 * would convert. If we are in dry-run mode, we can give an answer.
275 if (!buf)
276 return 1;
278 /* only grow if not in place */
279 if (strbuf_avail(buf) + buf->len < len)
280 strbuf_grow(buf, len - buf->len);
281 dst = buf->buf;
282 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
284 * If we guessed, we already know we rejected a file with
285 * lone CR, and we can strip a CR without looking at what
286 * follow it.
288 do {
289 unsigned char c = *src++;
290 if (c != '\r')
291 *dst++ = c;
292 } while (--len);
293 } else {
294 do {
295 unsigned char c = *src++;
296 if (! (c == '\r' && (1 < len && *src == '\n')))
297 *dst++ = c;
298 } while (--len);
300 strbuf_setlen(buf, dst - buf->buf);
301 return 1;
304 static int crlf_to_worktree(const char *path, const char *src, size_t len,
305 struct strbuf *buf, enum crlf_action crlf_action)
307 char *to_free = NULL;
308 struct text_stat stats;
310 if (!len || output_eol(crlf_action) != EOL_CRLF)
311 return 0;
313 gather_stats(src, len, &stats);
315 /* No LF? Nothing to convert, regardless. */
316 if (!stats.lf)
317 return 0;
319 /* Was it already in CRLF format? */
320 if (stats.lf == stats.crlf)
321 return 0;
323 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
324 if (crlf_action == CRLF_GUESS) {
325 /* If we have any CR or CRLF line endings, we do not touch it */
326 /* This is the new safer autocrlf-handling */
327 if (stats.cr > 0 || stats.crlf > 0)
328 return 0;
331 if (convert_is_binary(len, &stats))
332 return 0;
335 /* are we "faking" in place editing ? */
336 if (src == buf->buf)
337 to_free = strbuf_detach(buf, NULL);
339 strbuf_grow(buf, len + stats.lf - stats.crlf);
340 for (;;) {
341 const char *nl = memchr(src, '\n', len);
342 if (!nl)
343 break;
344 if (nl > src && nl[-1] == '\r') {
345 strbuf_add(buf, src, nl + 1 - src);
346 } else {
347 strbuf_add(buf, src, nl - src);
348 strbuf_addstr(buf, "\r\n");
350 len -= nl + 1 - src;
351 src = nl + 1;
353 strbuf_add(buf, src, len);
355 free(to_free);
356 return 1;
359 struct filter_params {
360 const char *src;
361 unsigned long size;
362 int fd;
363 const char *cmd;
364 const char *path;
367 static int filter_buffer_or_fd(int in, int out, void *data)
370 * Spawn cmd and feed the buffer contents through its stdin.
372 struct child_process child_process = CHILD_PROCESS_INIT;
373 struct filter_params *params = (struct filter_params *)data;
374 int write_err, status;
375 const char *argv[] = { NULL, NULL };
377 /* apply % substitution to cmd */
378 struct strbuf cmd = STRBUF_INIT;
379 struct strbuf path = STRBUF_INIT;
380 struct strbuf_expand_dict_entry dict[] = {
381 { "f", NULL, },
382 { NULL, NULL, },
385 /* quote the path to preserve spaces, etc. */
386 sq_quote_buf(&path, params->path);
387 dict[0].value = path.buf;
389 /* expand all %f with the quoted path */
390 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
391 strbuf_release(&path);
393 argv[0] = cmd.buf;
395 child_process.argv = argv;
396 child_process.use_shell = 1;
397 child_process.in = -1;
398 child_process.out = out;
400 if (start_command(&child_process))
401 return error("cannot fork to run external filter %s", params->cmd);
403 sigchain_push(SIGPIPE, SIG_IGN);
405 if (params->src) {
406 write_err = (write_in_full(child_process.in,
407 params->src, params->size) < 0);
408 if (errno == EPIPE)
409 write_err = 0;
410 } else {
411 write_err = copy_fd(params->fd, child_process.in);
412 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
413 write_err = 0;
416 if (close(child_process.in))
417 write_err = 1;
418 if (write_err)
419 error("cannot feed the input to external filter %s", params->cmd);
421 sigchain_pop(SIGPIPE);
423 status = finish_command(&child_process);
424 if (status)
425 error("external filter %s failed %d", params->cmd, status);
427 strbuf_release(&cmd);
428 return (write_err || status);
431 static int apply_filter(const char *path, const char *src, size_t len, int fd,
432 struct strbuf *dst, const char *cmd)
435 * Create a pipeline to have the command filter the buffer's
436 * contents.
438 * (child --> cmd) --> us
440 int ret = 1;
441 struct strbuf nbuf = STRBUF_INIT;
442 struct async async;
443 struct filter_params params;
445 if (!cmd)
446 return 0;
448 if (!dst)
449 return 1;
451 memset(&async, 0, sizeof(async));
452 async.proc = filter_buffer_or_fd;
453 async.data = &params;
454 async.out = -1;
455 params.src = src;
456 params.size = len;
457 params.fd = fd;
458 params.cmd = cmd;
459 params.path = path;
461 fflush(NULL);
462 if (start_async(&async))
463 return 0; /* error was already reported */
465 if (strbuf_read(&nbuf, async.out, len) < 0) {
466 error("read from external filter %s failed", cmd);
467 ret = 0;
469 if (close(async.out)) {
470 error("read from external filter %s failed", cmd);
471 ret = 0;
473 if (finish_async(&async)) {
474 error("external filter %s failed", cmd);
475 ret = 0;
478 if (ret) {
479 strbuf_swap(dst, &nbuf);
481 strbuf_release(&nbuf);
482 return ret;
485 static struct convert_driver {
486 const char *name;
487 struct convert_driver *next;
488 const char *smudge;
489 const char *clean;
490 int required;
491 } *user_convert, **user_convert_tail;
493 static int read_convert_config(const char *var, const char *value, void *cb)
495 const char *key, *name;
496 int namelen;
497 struct convert_driver *drv;
500 * External conversion drivers are configured using
501 * "filter.<name>.variable".
503 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
504 return 0;
505 for (drv = user_convert; drv; drv = drv->next)
506 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
507 break;
508 if (!drv) {
509 drv = xcalloc(1, sizeof(struct convert_driver));
510 drv->name = xmemdupz(name, namelen);
511 *user_convert_tail = drv;
512 user_convert_tail = &(drv->next);
516 * filter.<name>.smudge and filter.<name>.clean specifies
517 * the command line:
519 * command-line
521 * The command-line will not be interpolated in any way.
524 if (!strcmp("smudge", key))
525 return git_config_string(&drv->smudge, var, value);
527 if (!strcmp("clean", key))
528 return git_config_string(&drv->clean, var, value);
530 if (!strcmp("required", key)) {
531 drv->required = git_config_bool(var, value);
532 return 0;
535 return 0;
538 static int count_ident(const char *cp, unsigned long size)
541 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
543 int cnt = 0;
544 char ch;
546 while (size) {
547 ch = *cp++;
548 size--;
549 if (ch != '$')
550 continue;
551 if (size < 3)
552 break;
553 if (memcmp("Id", cp, 2))
554 continue;
555 ch = cp[2];
556 cp += 3;
557 size -= 3;
558 if (ch == '$')
559 cnt++; /* $Id$ */
560 if (ch != ':')
561 continue;
564 * "$Id: ... "; scan up to the closing dollar sign and discard.
566 while (size) {
567 ch = *cp++;
568 size--;
569 if (ch == '$') {
570 cnt++;
571 break;
573 if (ch == '\n')
574 break;
577 return cnt;
580 static int ident_to_git(const char *path, const char *src, size_t len,
581 struct strbuf *buf, int ident)
583 char *dst, *dollar;
585 if (!ident || (src && !count_ident(src, len)))
586 return 0;
588 if (!buf)
589 return 1;
591 /* only grow if not in place */
592 if (strbuf_avail(buf) + buf->len < len)
593 strbuf_grow(buf, len - buf->len);
594 dst = buf->buf;
595 for (;;) {
596 dollar = memchr(src, '$', len);
597 if (!dollar)
598 break;
599 memmove(dst, src, dollar + 1 - src);
600 dst += dollar + 1 - src;
601 len -= dollar + 1 - src;
602 src = dollar + 1;
604 if (len > 3 && !memcmp(src, "Id:", 3)) {
605 dollar = memchr(src + 3, '$', len - 3);
606 if (!dollar)
607 break;
608 if (memchr(src + 3, '\n', dollar - src - 3)) {
609 /* Line break before the next dollar. */
610 continue;
613 memcpy(dst, "Id$", 3);
614 dst += 3;
615 len -= dollar + 1 - src;
616 src = dollar + 1;
619 memmove(dst, src, len);
620 strbuf_setlen(buf, dst + len - buf->buf);
621 return 1;
624 static int ident_to_worktree(const char *path, const char *src, size_t len,
625 struct strbuf *buf, int ident)
627 unsigned char sha1[20];
628 char *to_free = NULL, *dollar, *spc;
629 int cnt;
631 if (!ident)
632 return 0;
634 cnt = count_ident(src, len);
635 if (!cnt)
636 return 0;
638 /* are we "faking" in place editing ? */
639 if (src == buf->buf)
640 to_free = strbuf_detach(buf, NULL);
641 hash_sha1_file(src, len, "blob", sha1);
643 strbuf_grow(buf, len + cnt * 43);
644 for (;;) {
645 /* step 1: run to the next '$' */
646 dollar = memchr(src, '$', len);
647 if (!dollar)
648 break;
649 strbuf_add(buf, src, dollar + 1 - src);
650 len -= dollar + 1 - src;
651 src = dollar + 1;
653 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
654 if (len < 3 || memcmp("Id", src, 2))
655 continue;
657 /* step 3: skip over Id$ or Id:xxxxx$ */
658 if (src[2] == '$') {
659 src += 3;
660 len -= 3;
661 } else if (src[2] == ':') {
663 * It's possible that an expanded Id has crept its way into the
664 * repository, we cope with that by stripping the expansion out.
665 * This is probably not a good idea, since it will cause changes
666 * on checkout, which won't go away by stash, but let's keep it
667 * for git-style ids.
669 dollar = memchr(src + 3, '$', len - 3);
670 if (!dollar) {
671 /* incomplete keyword, no more '$', so just quit the loop */
672 break;
675 if (memchr(src + 3, '\n', dollar - src - 3)) {
676 /* Line break before the next dollar. */
677 continue;
680 spc = memchr(src + 4, ' ', dollar - src - 4);
681 if (spc && spc < dollar-1) {
682 /* There are spaces in unexpected places.
683 * This is probably an id from some other
684 * versioning system. Keep it for now.
686 continue;
689 len -= dollar + 1 - src;
690 src = dollar + 1;
691 } else {
692 /* it wasn't a "Id$" or "Id:xxxx$" */
693 continue;
696 /* step 4: substitute */
697 strbuf_addstr(buf, "Id: ");
698 strbuf_add(buf, sha1_to_hex(sha1), 40);
699 strbuf_addstr(buf, " $");
701 strbuf_add(buf, src, len);
703 free(to_free);
704 return 1;
707 static enum crlf_action git_path_check_crlf(struct git_attr_check *check)
709 const char *value = check->value;
711 if (ATTR_TRUE(value))
712 return CRLF_TEXT;
713 else if (ATTR_FALSE(value))
714 return CRLF_BINARY;
715 else if (ATTR_UNSET(value))
717 else if (!strcmp(value, "input"))
718 return CRLF_INPUT;
719 else if (!strcmp(value, "auto"))
720 return CRLF_AUTO;
721 return CRLF_GUESS;
724 static enum eol git_path_check_eol(struct git_attr_check *check)
726 const char *value = check->value;
728 if (ATTR_UNSET(value))
730 else if (!strcmp(value, "lf"))
731 return EOL_LF;
732 else if (!strcmp(value, "crlf"))
733 return EOL_CRLF;
734 return EOL_UNSET;
737 static struct convert_driver *git_path_check_convert(struct git_attr_check *check)
739 const char *value = check->value;
740 struct convert_driver *drv;
742 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
743 return NULL;
744 for (drv = user_convert; drv; drv = drv->next)
745 if (!strcmp(value, drv->name))
746 return drv;
747 return NULL;
750 static int git_path_check_ident(struct git_attr_check *check)
752 const char *value = check->value;
754 return !!ATTR_TRUE(value);
757 struct conv_attrs {
758 struct convert_driver *drv;
759 enum crlf_action attr_action; /* What attr says */
760 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
761 int ident;
764 static const char *conv_attr_name[] = {
765 "crlf", "ident", "filter", "eol", "text",
767 #define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
769 static void convert_attrs(struct conv_attrs *ca, const char *path)
771 int i;
772 static struct git_attr_check ccheck[NUM_CONV_ATTRS];
774 if (!ccheck[0].attr) {
775 for (i = 0; i < NUM_CONV_ATTRS; i++)
776 ccheck[i].attr = git_attr(conv_attr_name[i]);
777 user_convert_tail = &user_convert;
778 git_config(read_convert_config, NULL);
781 if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
782 enum eol eol_attr;
783 ca->crlf_action = git_path_check_crlf(ccheck + 4);
784 if (ca->crlf_action == CRLF_GUESS)
785 ca->crlf_action = git_path_check_crlf(ccheck + 0);
786 ca->attr_action = ca->crlf_action;
787 ca->ident = git_path_check_ident(ccheck + 1);
788 ca->drv = git_path_check_convert(ccheck + 2);
789 if (ca->crlf_action == CRLF_BINARY)
790 return;
791 eol_attr = git_path_check_eol(ccheck + 3);
792 if (eol_attr == EOL_LF)
793 ca->crlf_action = CRLF_INPUT;
794 else if (eol_attr == EOL_CRLF)
795 ca->crlf_action = CRLF_CRLF;
796 } else {
797 ca->drv = NULL;
798 ca->crlf_action = CRLF_GUESS;
799 ca->ident = 0;
803 int would_convert_to_git_filter_fd(const char *path)
805 struct conv_attrs ca;
807 convert_attrs(&ca, path);
808 if (!ca.drv)
809 return 0;
812 * Apply a filter to an fd only if the filter is required to succeed.
813 * We must die if the filter fails, because the original data before
814 * filtering is not available.
816 if (!ca.drv->required)
817 return 0;
819 return apply_filter(path, NULL, 0, -1, NULL, ca.drv->clean);
822 const char *get_convert_attr_ascii(const char *path)
824 struct conv_attrs ca;
826 convert_attrs(&ca, path);
827 switch (ca.attr_action) {
828 case CRLF_GUESS:
829 return "";
830 case CRLF_BINARY:
831 return "-text";
832 case CRLF_TEXT:
833 return "text";
834 case CRLF_INPUT:
835 return "text eol=lf";
836 case CRLF_CRLF:
837 return "text=auto eol=crlf";
838 case CRLF_AUTO:
839 return "text=auto";
841 return "";
844 int convert_to_git(const char *path, const char *src, size_t len,
845 struct strbuf *dst, enum safe_crlf checksafe)
847 int ret = 0;
848 const char *filter = NULL;
849 int required = 0;
850 struct conv_attrs ca;
852 convert_attrs(&ca, path);
853 if (ca.drv) {
854 filter = ca.drv->clean;
855 required = ca.drv->required;
858 ret |= apply_filter(path, src, len, -1, dst, filter);
859 if (!ret && required)
860 die("%s: clean filter '%s' failed", path, ca.drv->name);
862 if (ret && dst) {
863 src = dst->buf;
864 len = dst->len;
866 ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
867 if (ret && dst) {
868 src = dst->buf;
869 len = dst->len;
871 return ret | ident_to_git(path, src, len, dst, ca.ident);
874 void convert_to_git_filter_fd(const char *path, int fd, struct strbuf *dst,
875 enum safe_crlf checksafe)
877 struct conv_attrs ca;
878 convert_attrs(&ca, path);
880 assert(ca.drv);
881 assert(ca.drv->clean);
883 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv->clean))
884 die("%s: clean filter '%s' failed", path, ca.drv->name);
886 crlf_to_git(path, dst->buf, dst->len, dst, ca.crlf_action, checksafe);
887 ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
890 static int convert_to_working_tree_internal(const char *path, const char *src,
891 size_t len, struct strbuf *dst,
892 int normalizing)
894 int ret = 0, ret_filter = 0;
895 const char *filter = NULL;
896 int required = 0;
897 struct conv_attrs ca;
899 convert_attrs(&ca, path);
900 if (ca.drv) {
901 filter = ca.drv->smudge;
902 required = ca.drv->required;
905 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
906 if (ret) {
907 src = dst->buf;
908 len = dst->len;
911 * CRLF conversion can be skipped if normalizing, unless there
912 * is a smudge filter. The filter might expect CRLFs.
914 if (filter || !normalizing) {
915 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
916 if (ret) {
917 src = dst->buf;
918 len = dst->len;
922 ret_filter = apply_filter(path, src, len, -1, dst, filter);
923 if (!ret_filter && required)
924 die("%s: smudge filter %s failed", path, ca.drv->name);
926 return ret | ret_filter;
929 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
931 return convert_to_working_tree_internal(path, src, len, dst, 0);
934 int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
936 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
937 if (ret) {
938 src = dst->buf;
939 len = dst->len;
941 return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_FALSE);
944 /*****************************************************************
946 * Streaming conversion support
948 *****************************************************************/
950 typedef int (*filter_fn)(struct stream_filter *,
951 const char *input, size_t *isize_p,
952 char *output, size_t *osize_p);
953 typedef void (*free_fn)(struct stream_filter *);
955 struct stream_filter_vtbl {
956 filter_fn filter;
957 free_fn free;
960 struct stream_filter {
961 struct stream_filter_vtbl *vtbl;
964 static int null_filter_fn(struct stream_filter *filter,
965 const char *input, size_t *isize_p,
966 char *output, size_t *osize_p)
968 size_t count;
970 if (!input)
971 return 0; /* we do not keep any states */
972 count = *isize_p;
973 if (*osize_p < count)
974 count = *osize_p;
975 if (count) {
976 memmove(output, input, count);
977 *isize_p -= count;
978 *osize_p -= count;
980 return 0;
983 static void null_free_fn(struct stream_filter *filter)
985 ; /* nothing -- null instances are shared */
988 static struct stream_filter_vtbl null_vtbl = {
989 null_filter_fn,
990 null_free_fn,
993 static struct stream_filter null_filter_singleton = {
994 &null_vtbl,
997 int is_null_stream_filter(struct stream_filter *filter)
999 return filter == &null_filter_singleton;
1004 * LF-to-CRLF filter
1007 struct lf_to_crlf_filter {
1008 struct stream_filter filter;
1009 unsigned has_held:1;
1010 char held;
1013 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1014 const char *input, size_t *isize_p,
1015 char *output, size_t *osize_p)
1017 size_t count, o = 0;
1018 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1021 * We may be holding onto the CR to see if it is followed by a
1022 * LF, in which case we would need to go to the main loop.
1023 * Otherwise, just emit it to the output stream.
1025 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1026 output[o++] = lf_to_crlf->held;
1027 lf_to_crlf->has_held = 0;
1030 /* We are told to drain */
1031 if (!input) {
1032 *osize_p -= o;
1033 return 0;
1036 count = *isize_p;
1037 if (count || lf_to_crlf->has_held) {
1038 size_t i;
1039 int was_cr = 0;
1041 if (lf_to_crlf->has_held) {
1042 was_cr = 1;
1043 lf_to_crlf->has_held = 0;
1046 for (i = 0; o < *osize_p && i < count; i++) {
1047 char ch = input[i];
1049 if (ch == '\n') {
1050 output[o++] = '\r';
1051 } else if (was_cr) {
1053 * Previous round saw CR and it is not followed
1054 * by a LF; emit the CR before processing the
1055 * current character.
1057 output[o++] = '\r';
1061 * We may have consumed the last output slot,
1062 * in which case we need to break out of this
1063 * loop; hold the current character before
1064 * returning.
1066 if (*osize_p <= o) {
1067 lf_to_crlf->has_held = 1;
1068 lf_to_crlf->held = ch;
1069 continue; /* break but increment i */
1072 if (ch == '\r') {
1073 was_cr = 1;
1074 continue;
1077 was_cr = 0;
1078 output[o++] = ch;
1081 *osize_p -= o;
1082 *isize_p -= i;
1084 if (!lf_to_crlf->has_held && was_cr) {
1085 lf_to_crlf->has_held = 1;
1086 lf_to_crlf->held = '\r';
1089 return 0;
1092 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1094 free(filter);
1097 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1098 lf_to_crlf_filter_fn,
1099 lf_to_crlf_free_fn,
1102 static struct stream_filter *lf_to_crlf_filter(void)
1104 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1106 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1107 return (struct stream_filter *)lf_to_crlf;
1111 * Cascade filter
1113 #define FILTER_BUFFER 1024
1114 struct cascade_filter {
1115 struct stream_filter filter;
1116 struct stream_filter *one;
1117 struct stream_filter *two;
1118 char buf[FILTER_BUFFER];
1119 int end, ptr;
1122 static int cascade_filter_fn(struct stream_filter *filter,
1123 const char *input, size_t *isize_p,
1124 char *output, size_t *osize_p)
1126 struct cascade_filter *cas = (struct cascade_filter *) filter;
1127 size_t filled = 0;
1128 size_t sz = *osize_p;
1129 size_t to_feed, remaining;
1132 * input -- (one) --> buf -- (two) --> output
1134 while (filled < sz) {
1135 remaining = sz - filled;
1137 /* do we already have something to feed two with? */
1138 if (cas->ptr < cas->end) {
1139 to_feed = cas->end - cas->ptr;
1140 if (stream_filter(cas->two,
1141 cas->buf + cas->ptr, &to_feed,
1142 output + filled, &remaining))
1143 return -1;
1144 cas->ptr += (cas->end - cas->ptr) - to_feed;
1145 filled = sz - remaining;
1146 continue;
1149 /* feed one from upstream and have it emit into our buffer */
1150 to_feed = input ? *isize_p : 0;
1151 if (input && !to_feed)
1152 break;
1153 remaining = sizeof(cas->buf);
1154 if (stream_filter(cas->one,
1155 input, &to_feed,
1156 cas->buf, &remaining))
1157 return -1;
1158 cas->end = sizeof(cas->buf) - remaining;
1159 cas->ptr = 0;
1160 if (input) {
1161 size_t fed = *isize_p - to_feed;
1162 *isize_p -= fed;
1163 input += fed;
1166 /* do we know that we drained one completely? */
1167 if (input || cas->end)
1168 continue;
1170 /* tell two to drain; we have nothing more to give it */
1171 to_feed = 0;
1172 remaining = sz - filled;
1173 if (stream_filter(cas->two,
1174 NULL, &to_feed,
1175 output + filled, &remaining))
1176 return -1;
1177 if (remaining == (sz - filled))
1178 break; /* completely drained two */
1179 filled = sz - remaining;
1181 *osize_p -= filled;
1182 return 0;
1185 static void cascade_free_fn(struct stream_filter *filter)
1187 struct cascade_filter *cas = (struct cascade_filter *)filter;
1188 free_stream_filter(cas->one);
1189 free_stream_filter(cas->two);
1190 free(filter);
1193 static struct stream_filter_vtbl cascade_vtbl = {
1194 cascade_filter_fn,
1195 cascade_free_fn,
1198 static struct stream_filter *cascade_filter(struct stream_filter *one,
1199 struct stream_filter *two)
1201 struct cascade_filter *cascade;
1203 if (!one || is_null_stream_filter(one))
1204 return two;
1205 if (!two || is_null_stream_filter(two))
1206 return one;
1208 cascade = xmalloc(sizeof(*cascade));
1209 cascade->one = one;
1210 cascade->two = two;
1211 cascade->end = cascade->ptr = 0;
1212 cascade->filter.vtbl = &cascade_vtbl;
1213 return (struct stream_filter *)cascade;
1217 * ident filter
1219 #define IDENT_DRAINING (-1)
1220 #define IDENT_SKIPPING (-2)
1221 struct ident_filter {
1222 struct stream_filter filter;
1223 struct strbuf left;
1224 int state;
1225 char ident[45]; /* ": x40 $" */
1228 static int is_foreign_ident(const char *str)
1230 int i;
1232 if (!skip_prefix(str, "$Id: ", &str))
1233 return 0;
1234 for (i = 0; str[i]; i++) {
1235 if (isspace(str[i]) && str[i+1] != '$')
1236 return 1;
1238 return 0;
1241 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1243 size_t to_drain = ident->left.len;
1245 if (*osize_p < to_drain)
1246 to_drain = *osize_p;
1247 if (to_drain) {
1248 memcpy(*output_p, ident->left.buf, to_drain);
1249 strbuf_remove(&ident->left, 0, to_drain);
1250 *output_p += to_drain;
1251 *osize_p -= to_drain;
1253 if (!ident->left.len)
1254 ident->state = 0;
1257 static int ident_filter_fn(struct stream_filter *filter,
1258 const char *input, size_t *isize_p,
1259 char *output, size_t *osize_p)
1261 struct ident_filter *ident = (struct ident_filter *)filter;
1262 static const char head[] = "$Id";
1264 if (!input) {
1265 /* drain upon eof */
1266 switch (ident->state) {
1267 default:
1268 strbuf_add(&ident->left, head, ident->state);
1269 case IDENT_SKIPPING:
1270 /* fallthru */
1271 case IDENT_DRAINING:
1272 ident_drain(ident, &output, osize_p);
1274 return 0;
1277 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1278 int ch;
1280 if (ident->state == IDENT_DRAINING) {
1281 ident_drain(ident, &output, osize_p);
1282 if (!*osize_p)
1283 break;
1284 continue;
1287 ch = *(input++);
1288 (*isize_p)--;
1290 if (ident->state == IDENT_SKIPPING) {
1292 * Skipping until '$' or LF, but keeping them
1293 * in case it is a foreign ident.
1295 strbuf_addch(&ident->left, ch);
1296 if (ch != '\n' && ch != '$')
1297 continue;
1298 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1299 strbuf_setlen(&ident->left, sizeof(head) - 1);
1300 strbuf_addstr(&ident->left, ident->ident);
1302 ident->state = IDENT_DRAINING;
1303 continue;
1306 if (ident->state < sizeof(head) &&
1307 head[ident->state] == ch) {
1308 ident->state++;
1309 continue;
1312 if (ident->state)
1313 strbuf_add(&ident->left, head, ident->state);
1314 if (ident->state == sizeof(head) - 1) {
1315 if (ch != ':' && ch != '$') {
1316 strbuf_addch(&ident->left, ch);
1317 ident->state = 0;
1318 continue;
1321 if (ch == ':') {
1322 strbuf_addch(&ident->left, ch);
1323 ident->state = IDENT_SKIPPING;
1324 } else {
1325 strbuf_addstr(&ident->left, ident->ident);
1326 ident->state = IDENT_DRAINING;
1328 continue;
1331 strbuf_addch(&ident->left, ch);
1332 ident->state = IDENT_DRAINING;
1334 return 0;
1337 static void ident_free_fn(struct stream_filter *filter)
1339 struct ident_filter *ident = (struct ident_filter *)filter;
1340 strbuf_release(&ident->left);
1341 free(filter);
1344 static struct stream_filter_vtbl ident_vtbl = {
1345 ident_filter_fn,
1346 ident_free_fn,
1349 static struct stream_filter *ident_filter(const unsigned char *sha1)
1351 struct ident_filter *ident = xmalloc(sizeof(*ident));
1353 xsnprintf(ident->ident, sizeof(ident->ident),
1354 ": %s $", sha1_to_hex(sha1));
1355 strbuf_init(&ident->left, 0);
1356 ident->filter.vtbl = &ident_vtbl;
1357 ident->state = 0;
1358 return (struct stream_filter *)ident;
1362 * Return an appropriately constructed filter for the path, or NULL if
1363 * the contents cannot be filtered without reading the whole thing
1364 * in-core.
1366 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1367 * large binary blob you would want us not to slurp into the memory!
1369 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1371 struct conv_attrs ca;
1372 enum crlf_action crlf_action;
1373 struct stream_filter *filter = NULL;
1375 convert_attrs(&ca, path);
1377 if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1378 return filter;
1380 if (ca.ident)
1381 filter = ident_filter(sha1);
1383 crlf_action = ca.crlf_action;
1385 if ((crlf_action == CRLF_BINARY) || (crlf_action == CRLF_INPUT) ||
1386 (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE))
1387 filter = cascade_filter(filter, &null_filter_singleton);
1389 else if (output_eol(crlf_action) == EOL_CRLF &&
1390 !(crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS))
1391 filter = cascade_filter(filter, lf_to_crlf_filter());
1393 return filter;
1396 void free_stream_filter(struct stream_filter *filter)
1398 filter->vtbl->free(filter);
1401 int stream_filter(struct stream_filter *filter,
1402 const char *input, size_t *isize_p,
1403 char *output, size_t *osize_p)
1405 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);