sha1_name: make wraparound of the index into ring-buffer explicit
[git.git] / convert.c
blob0ad39b16cc40c27ef9af493d95542c52c60439a0
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_UNDEFINED,
23 CRLF_BINARY,
24 CRLF_TEXT,
25 CRLF_TEXT_INPUT,
26 CRLF_TEXT_CRLF,
27 CRLF_AUTO,
28 CRLF_AUTO_INPUT,
29 CRLF_AUTO_CRLF
32 struct text_stat {
33 /* NUL, CR, LF and CRLF counts */
34 unsigned nul, lonecr, lonelf, crlf;
36 /* These are just approximations! */
37 unsigned printable, nonprintable;
40 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
42 unsigned long i;
44 memset(stats, 0, sizeof(*stats));
46 for (i = 0; i < size; i++) {
47 unsigned char c = buf[i];
48 if (c == '\r') {
49 if (i+1 < size && buf[i+1] == '\n') {
50 stats->crlf++;
51 i++;
52 } else
53 stats->lonecr++;
54 continue;
56 if (c == '\n') {
57 stats->lonelf++;
58 continue;
60 if (c == 127)
61 /* DEL */
62 stats->nonprintable++;
63 else if (c < 32) {
64 switch (c) {
65 /* BS, HT, ESC and FF */
66 case '\b': case '\t': case '\033': case '\014':
67 stats->printable++;
68 break;
69 case 0:
70 stats->nul++;
71 /* fall through */
72 default:
73 stats->nonprintable++;
76 else
77 stats->printable++;
80 /* If file ends with EOF then don't count this EOF as non-printable. */
81 if (size >= 1 && buf[size-1] == '\032')
82 stats->nonprintable--;
86 * The same heuristics as diff.c::mmfile_is_binary()
87 * We treat files with bare CR as binary
89 static int convert_is_binary(unsigned long size, const struct text_stat *stats)
91 if (stats->lonecr)
92 return 1;
93 if (stats->nul)
94 return 1;
95 if ((stats->printable >> 7) < stats->nonprintable)
96 return 1;
97 return 0;
100 static unsigned int gather_convert_stats(const char *data, unsigned long size)
102 struct text_stat stats;
103 int ret = 0;
104 if (!data || !size)
105 return 0;
106 gather_stats(data, size, &stats);
107 if (convert_is_binary(size, &stats))
108 ret |= CONVERT_STAT_BITS_BIN;
109 if (stats.crlf)
110 ret |= CONVERT_STAT_BITS_TXT_CRLF;
111 if (stats.lonelf)
112 ret |= CONVERT_STAT_BITS_TXT_LF;
114 return ret;
117 static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
119 unsigned int convert_stats = gather_convert_stats(data, size);
121 if (convert_stats & CONVERT_STAT_BITS_BIN)
122 return "-text";
123 switch (convert_stats) {
124 case CONVERT_STAT_BITS_TXT_LF:
125 return "lf";
126 case CONVERT_STAT_BITS_TXT_CRLF:
127 return "crlf";
128 case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
129 return "mixed";
130 default:
131 return "none";
135 const char *get_cached_convert_stats_ascii(const char *path)
137 const char *ret;
138 unsigned long sz;
139 void *data = read_blob_data_from_cache(path, &sz);
140 ret = gather_convert_stats_ascii(data, sz);
141 free(data);
142 return ret;
145 const char *get_wt_convert_stats_ascii(const char *path)
147 const char *ret = "";
148 struct strbuf sb = STRBUF_INIT;
149 if (strbuf_read_file(&sb, path, 0) >= 0)
150 ret = gather_convert_stats_ascii(sb.buf, sb.len);
151 strbuf_release(&sb);
152 return ret;
155 static int text_eol_is_crlf(void)
157 if (auto_crlf == AUTO_CRLF_TRUE)
158 return 1;
159 else if (auto_crlf == AUTO_CRLF_INPUT)
160 return 0;
161 if (core_eol == EOL_CRLF)
162 return 1;
163 if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
164 return 1;
165 return 0;
168 static enum eol output_eol(enum crlf_action crlf_action)
170 switch (crlf_action) {
171 case CRLF_BINARY:
172 return EOL_UNSET;
173 case CRLF_TEXT_CRLF:
174 return EOL_CRLF;
175 case CRLF_TEXT_INPUT:
176 return EOL_LF;
177 case CRLF_UNDEFINED:
178 case CRLF_AUTO_CRLF:
179 return EOL_CRLF;
180 case CRLF_AUTO_INPUT:
181 return EOL_LF;
182 case CRLF_TEXT:
183 case CRLF_AUTO:
184 /* fall through */
185 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
187 warning("Illegal crlf_action %d\n", (int)crlf_action);
188 return core_eol;
191 static void check_safe_crlf(const char *path, enum crlf_action crlf_action,
192 struct text_stat *old_stats, struct text_stat *new_stats,
193 enum safe_crlf checksafe)
195 if (old_stats->crlf && !new_stats->crlf ) {
197 * CRLFs would not be restored by checkout
199 if (checksafe == SAFE_CRLF_WARN)
200 warning(_("CRLF will be replaced by LF in %s.\n"
201 "The file will have its original line"
202 " endings in your working directory."), path);
203 else /* i.e. SAFE_CRLF_FAIL */
204 die(_("CRLF would be replaced by LF in %s."), path);
205 } else if (old_stats->lonelf && !new_stats->lonelf ) {
207 * CRLFs would be added by checkout
209 if (checksafe == SAFE_CRLF_WARN)
210 warning(_("LF will be replaced by CRLF in %s.\n"
211 "The file will have its original line"
212 " endings in your working directory."), path);
213 else /* i.e. SAFE_CRLF_FAIL */
214 die(_("LF would be replaced by CRLF in %s"), path);
218 static int has_cr_in_index(const char *path)
220 unsigned long sz;
221 void *data;
222 int has_cr;
224 data = read_blob_data_from_cache(path, &sz);
225 if (!data)
226 return 0;
227 has_cr = memchr(data, '\r', sz) != NULL;
228 free(data);
229 return has_cr;
232 static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats,
233 enum crlf_action crlf_action)
235 if (output_eol(crlf_action) != EOL_CRLF)
236 return 0;
237 /* No "naked" LF? Nothing to convert, regardless. */
238 if (!stats->lonelf)
239 return 0;
241 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
242 /* If we have any CR or CRLF line endings, we do not touch it */
243 /* This is the new safer autocrlf-handling */
244 if (stats->lonecr || stats->crlf)
245 return 0;
247 if (convert_is_binary(len, stats))
248 return 0;
250 return 1;
254 static int crlf_to_git(const char *path, const char *src, size_t len,
255 struct strbuf *buf,
256 enum crlf_action crlf_action, enum safe_crlf checksafe)
258 struct text_stat stats;
259 char *dst;
260 int convert_crlf_into_lf;
262 if (crlf_action == CRLF_BINARY ||
263 (src && !len))
264 return 0;
267 * If we are doing a dry-run and have no source buffer, there is
268 * nothing to analyze; we must assume we would convert.
270 if (!buf && !src)
271 return 1;
273 gather_stats(src, len, &stats);
274 /* Optimization: No CRLF? Nothing to convert, regardless. */
275 convert_crlf_into_lf = !!stats.crlf;
277 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
278 if (convert_is_binary(len, &stats))
279 return 0;
281 * If the file in the index has any CR in it, do not convert.
282 * This is the new safer autocrlf handling.
284 if (checksafe == SAFE_CRLF_RENORMALIZE)
285 checksafe = SAFE_CRLF_FALSE;
286 else if (has_cr_in_index(path))
287 convert_crlf_into_lf = 0;
289 if (checksafe && len) {
290 struct text_stat new_stats;
291 memcpy(&new_stats, &stats, sizeof(new_stats));
292 /* simulate "git add" */
293 if (convert_crlf_into_lf) {
294 new_stats.lonelf += new_stats.crlf;
295 new_stats.crlf = 0;
297 /* simulate "git checkout" */
298 if (will_convert_lf_to_crlf(len, &new_stats, crlf_action)) {
299 new_stats.crlf += new_stats.lonelf;
300 new_stats.lonelf = 0;
302 check_safe_crlf(path, crlf_action, &stats, &new_stats, checksafe);
304 if (!convert_crlf_into_lf)
305 return 0;
308 * At this point all of our source analysis is done, and we are sure we
309 * would convert. If we are in dry-run mode, we can give an answer.
311 if (!buf)
312 return 1;
314 /* only grow if not in place */
315 if (strbuf_avail(buf) + buf->len < len)
316 strbuf_grow(buf, len - buf->len);
317 dst = buf->buf;
318 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
320 * If we guessed, we already know we rejected a file with
321 * lone CR, and we can strip a CR without looking at what
322 * follow it.
324 do {
325 unsigned char c = *src++;
326 if (c != '\r')
327 *dst++ = c;
328 } while (--len);
329 } else {
330 do {
331 unsigned char c = *src++;
332 if (! (c == '\r' && (1 < len && *src == '\n')))
333 *dst++ = c;
334 } while (--len);
336 strbuf_setlen(buf, dst - buf->buf);
337 return 1;
340 static int crlf_to_worktree(const char *path, const char *src, size_t len,
341 struct strbuf *buf, enum crlf_action crlf_action)
343 char *to_free = NULL;
344 struct text_stat stats;
346 if (!len || output_eol(crlf_action) != EOL_CRLF)
347 return 0;
349 gather_stats(src, len, &stats);
350 if (!will_convert_lf_to_crlf(len, &stats, crlf_action))
351 return 0;
353 /* are we "faking" in place editing ? */
354 if (src == buf->buf)
355 to_free = strbuf_detach(buf, NULL);
357 strbuf_grow(buf, len + stats.lonelf);
358 for (;;) {
359 const char *nl = memchr(src, '\n', len);
360 if (!nl)
361 break;
362 if (nl > src && nl[-1] == '\r') {
363 strbuf_add(buf, src, nl + 1 - src);
364 } else {
365 strbuf_add(buf, src, nl - src);
366 strbuf_addstr(buf, "\r\n");
368 len -= nl + 1 - src;
369 src = nl + 1;
371 strbuf_add(buf, src, len);
373 free(to_free);
374 return 1;
377 struct filter_params {
378 const char *src;
379 unsigned long size;
380 int fd;
381 const char *cmd;
382 const char *path;
385 static int filter_buffer_or_fd(int in, int out, void *data)
388 * Spawn cmd and feed the buffer contents through its stdin.
390 struct child_process child_process = CHILD_PROCESS_INIT;
391 struct filter_params *params = (struct filter_params *)data;
392 int write_err, status;
393 const char *argv[] = { NULL, NULL };
395 /* apply % substitution to cmd */
396 struct strbuf cmd = STRBUF_INIT;
397 struct strbuf path = STRBUF_INIT;
398 struct strbuf_expand_dict_entry dict[] = {
399 { "f", NULL, },
400 { NULL, NULL, },
403 /* quote the path to preserve spaces, etc. */
404 sq_quote_buf(&path, params->path);
405 dict[0].value = path.buf;
407 /* expand all %f with the quoted path */
408 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
409 strbuf_release(&path);
411 argv[0] = cmd.buf;
413 child_process.argv = argv;
414 child_process.use_shell = 1;
415 child_process.in = -1;
416 child_process.out = out;
418 if (start_command(&child_process))
419 return error("cannot fork to run external filter %s", params->cmd);
421 sigchain_push(SIGPIPE, SIG_IGN);
423 if (params->src) {
424 write_err = (write_in_full(child_process.in,
425 params->src, params->size) < 0);
426 if (errno == EPIPE)
427 write_err = 0;
428 } else {
429 write_err = copy_fd(params->fd, child_process.in);
430 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
431 write_err = 0;
434 if (close(child_process.in))
435 write_err = 1;
436 if (write_err)
437 error("cannot feed the input to external filter %s", params->cmd);
439 sigchain_pop(SIGPIPE);
441 status = finish_command(&child_process);
442 if (status)
443 error("external filter %s failed %d", params->cmd, status);
445 strbuf_release(&cmd);
446 return (write_err || status);
449 static int apply_filter(const char *path, const char *src, size_t len, int fd,
450 struct strbuf *dst, const char *cmd)
453 * Create a pipeline to have the command filter the buffer's
454 * contents.
456 * (child --> cmd) --> us
458 int ret = 1;
459 struct strbuf nbuf = STRBUF_INIT;
460 struct async async;
461 struct filter_params params;
463 if (!cmd || !*cmd)
464 return 0;
466 if (!dst)
467 return 1;
469 memset(&async, 0, sizeof(async));
470 async.proc = filter_buffer_or_fd;
471 async.data = &params;
472 async.out = -1;
473 params.src = src;
474 params.size = len;
475 params.fd = fd;
476 params.cmd = cmd;
477 params.path = path;
479 fflush(NULL);
480 if (start_async(&async))
481 return 0; /* error was already reported */
483 if (strbuf_read(&nbuf, async.out, len) < 0) {
484 error("read from external filter %s failed", cmd);
485 ret = 0;
487 if (close(async.out)) {
488 error("read from external filter %s failed", cmd);
489 ret = 0;
491 if (finish_async(&async)) {
492 error("external filter %s failed", cmd);
493 ret = 0;
496 if (ret) {
497 strbuf_swap(dst, &nbuf);
499 strbuf_release(&nbuf);
500 return ret;
503 static struct convert_driver {
504 const char *name;
505 struct convert_driver *next;
506 const char *smudge;
507 const char *clean;
508 int required;
509 } *user_convert, **user_convert_tail;
511 static int read_convert_config(const char *var, const char *value, void *cb)
513 const char *key, *name;
514 int namelen;
515 struct convert_driver *drv;
518 * External conversion drivers are configured using
519 * "filter.<name>.variable".
521 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
522 return 0;
523 for (drv = user_convert; drv; drv = drv->next)
524 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
525 break;
526 if (!drv) {
527 drv = xcalloc(1, sizeof(struct convert_driver));
528 drv->name = xmemdupz(name, namelen);
529 *user_convert_tail = drv;
530 user_convert_tail = &(drv->next);
534 * filter.<name>.smudge and filter.<name>.clean specifies
535 * the command line:
537 * command-line
539 * The command-line will not be interpolated in any way.
542 if (!strcmp("smudge", key))
543 return git_config_string(&drv->smudge, var, value);
545 if (!strcmp("clean", key))
546 return git_config_string(&drv->clean, var, value);
548 if (!strcmp("required", key)) {
549 drv->required = git_config_bool(var, value);
550 return 0;
553 return 0;
556 static int count_ident(const char *cp, unsigned long size)
559 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
561 int cnt = 0;
562 char ch;
564 while (size) {
565 ch = *cp++;
566 size--;
567 if (ch != '$')
568 continue;
569 if (size < 3)
570 break;
571 if (memcmp("Id", cp, 2))
572 continue;
573 ch = cp[2];
574 cp += 3;
575 size -= 3;
576 if (ch == '$')
577 cnt++; /* $Id$ */
578 if (ch != ':')
579 continue;
582 * "$Id: ... "; scan up to the closing dollar sign and discard.
584 while (size) {
585 ch = *cp++;
586 size--;
587 if (ch == '$') {
588 cnt++;
589 break;
591 if (ch == '\n')
592 break;
595 return cnt;
598 static int ident_to_git(const char *path, const char *src, size_t len,
599 struct strbuf *buf, int ident)
601 char *dst, *dollar;
603 if (!ident || (src && !count_ident(src, len)))
604 return 0;
606 if (!buf)
607 return 1;
609 /* only grow if not in place */
610 if (strbuf_avail(buf) + buf->len < len)
611 strbuf_grow(buf, len - buf->len);
612 dst = buf->buf;
613 for (;;) {
614 dollar = memchr(src, '$', len);
615 if (!dollar)
616 break;
617 memmove(dst, src, dollar + 1 - src);
618 dst += dollar + 1 - src;
619 len -= dollar + 1 - src;
620 src = dollar + 1;
622 if (len > 3 && !memcmp(src, "Id:", 3)) {
623 dollar = memchr(src + 3, '$', len - 3);
624 if (!dollar)
625 break;
626 if (memchr(src + 3, '\n', dollar - src - 3)) {
627 /* Line break before the next dollar. */
628 continue;
631 memcpy(dst, "Id$", 3);
632 dst += 3;
633 len -= dollar + 1 - src;
634 src = dollar + 1;
637 memmove(dst, src, len);
638 strbuf_setlen(buf, dst + len - buf->buf);
639 return 1;
642 static int ident_to_worktree(const char *path, const char *src, size_t len,
643 struct strbuf *buf, int ident)
645 unsigned char sha1[20];
646 char *to_free = NULL, *dollar, *spc;
647 int cnt;
649 if (!ident)
650 return 0;
652 cnt = count_ident(src, len);
653 if (!cnt)
654 return 0;
656 /* are we "faking" in place editing ? */
657 if (src == buf->buf)
658 to_free = strbuf_detach(buf, NULL);
659 hash_sha1_file(src, len, "blob", sha1);
661 strbuf_grow(buf, len + cnt * 43);
662 for (;;) {
663 /* step 1: run to the next '$' */
664 dollar = memchr(src, '$', len);
665 if (!dollar)
666 break;
667 strbuf_add(buf, src, dollar + 1 - src);
668 len -= dollar + 1 - src;
669 src = dollar + 1;
671 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
672 if (len < 3 || memcmp("Id", src, 2))
673 continue;
675 /* step 3: skip over Id$ or Id:xxxxx$ */
676 if (src[2] == '$') {
677 src += 3;
678 len -= 3;
679 } else if (src[2] == ':') {
681 * It's possible that an expanded Id has crept its way into the
682 * repository, we cope with that by stripping the expansion out.
683 * This is probably not a good idea, since it will cause changes
684 * on checkout, which won't go away by stash, but let's keep it
685 * for git-style ids.
687 dollar = memchr(src + 3, '$', len - 3);
688 if (!dollar) {
689 /* incomplete keyword, no more '$', so just quit the loop */
690 break;
693 if (memchr(src + 3, '\n', dollar - src - 3)) {
694 /* Line break before the next dollar. */
695 continue;
698 spc = memchr(src + 4, ' ', dollar - src - 4);
699 if (spc && spc < dollar-1) {
700 /* There are spaces in unexpected places.
701 * This is probably an id from some other
702 * versioning system. Keep it for now.
704 continue;
707 len -= dollar + 1 - src;
708 src = dollar + 1;
709 } else {
710 /* it wasn't a "Id$" or "Id:xxxx$" */
711 continue;
714 /* step 4: substitute */
715 strbuf_addstr(buf, "Id: ");
716 strbuf_add(buf, sha1_to_hex(sha1), 40);
717 strbuf_addstr(buf, " $");
719 strbuf_add(buf, src, len);
721 free(to_free);
722 return 1;
725 static enum crlf_action git_path_check_crlf(struct git_attr_check *check)
727 const char *value = check->value;
729 if (ATTR_TRUE(value))
730 return CRLF_TEXT;
731 else if (ATTR_FALSE(value))
732 return CRLF_BINARY;
733 else if (ATTR_UNSET(value))
735 else if (!strcmp(value, "input"))
736 return CRLF_TEXT_INPUT;
737 else if (!strcmp(value, "auto"))
738 return CRLF_AUTO;
739 return CRLF_UNDEFINED;
742 static enum eol git_path_check_eol(struct git_attr_check *check)
744 const char *value = check->value;
746 if (ATTR_UNSET(value))
748 else if (!strcmp(value, "lf"))
749 return EOL_LF;
750 else if (!strcmp(value, "crlf"))
751 return EOL_CRLF;
752 return EOL_UNSET;
755 static struct convert_driver *git_path_check_convert(struct git_attr_check *check)
757 const char *value = check->value;
758 struct convert_driver *drv;
760 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
761 return NULL;
762 for (drv = user_convert; drv; drv = drv->next)
763 if (!strcmp(value, drv->name))
764 return drv;
765 return NULL;
768 static int git_path_check_ident(struct git_attr_check *check)
770 const char *value = check->value;
772 return !!ATTR_TRUE(value);
775 struct conv_attrs {
776 struct convert_driver *drv;
777 enum crlf_action attr_action; /* What attr says */
778 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
779 int ident;
782 static const char *conv_attr_name[] = {
783 "crlf", "ident", "filter", "eol", "text",
785 #define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
787 static void convert_attrs(struct conv_attrs *ca, const char *path)
789 int i;
790 static struct git_attr_check ccheck[NUM_CONV_ATTRS];
792 if (!ccheck[0].attr) {
793 for (i = 0; i < NUM_CONV_ATTRS; i++)
794 ccheck[i].attr = git_attr(conv_attr_name[i]);
795 user_convert_tail = &user_convert;
796 git_config(read_convert_config, NULL);
799 if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
800 ca->crlf_action = git_path_check_crlf(ccheck + 4);
801 if (ca->crlf_action == CRLF_UNDEFINED)
802 ca->crlf_action = git_path_check_crlf(ccheck + 0);
803 ca->attr_action = ca->crlf_action;
804 ca->ident = git_path_check_ident(ccheck + 1);
805 ca->drv = git_path_check_convert(ccheck + 2);
806 if (ca->crlf_action != CRLF_BINARY) {
807 enum eol eol_attr = git_path_check_eol(ccheck + 3);
808 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
809 ca->crlf_action = CRLF_AUTO_INPUT;
810 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
811 ca->crlf_action = CRLF_AUTO_CRLF;
812 else if (eol_attr == EOL_LF)
813 ca->crlf_action = CRLF_TEXT_INPUT;
814 else if (eol_attr == EOL_CRLF)
815 ca->crlf_action = CRLF_TEXT_CRLF;
817 ca->attr_action = ca->crlf_action;
818 } else {
819 ca->drv = NULL;
820 ca->crlf_action = CRLF_UNDEFINED;
821 ca->ident = 0;
823 if (ca->crlf_action == CRLF_TEXT)
824 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
825 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
826 ca->crlf_action = CRLF_BINARY;
827 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
828 ca->crlf_action = CRLF_AUTO_CRLF;
829 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
830 ca->crlf_action = CRLF_AUTO_INPUT;
833 int would_convert_to_git_filter_fd(const char *path)
835 struct conv_attrs ca;
837 convert_attrs(&ca, path);
838 if (!ca.drv)
839 return 0;
842 * Apply a filter to an fd only if the filter is required to succeed.
843 * We must die if the filter fails, because the original data before
844 * filtering is not available.
846 if (!ca.drv->required)
847 return 0;
849 return apply_filter(path, NULL, 0, -1, NULL, ca.drv->clean);
852 const char *get_convert_attr_ascii(const char *path)
854 struct conv_attrs ca;
856 convert_attrs(&ca, path);
857 switch (ca.attr_action) {
858 case CRLF_UNDEFINED:
859 return "";
860 case CRLF_BINARY:
861 return "-text";
862 case CRLF_TEXT:
863 return "text";
864 case CRLF_TEXT_INPUT:
865 return "text eol=lf";
866 case CRLF_TEXT_CRLF:
867 return "text eol=crlf";
868 case CRLF_AUTO:
869 return "text=auto";
870 case CRLF_AUTO_CRLF:
871 return "text=auto eol=crlf";
872 case CRLF_AUTO_INPUT:
873 return "text=auto eol=lf";
875 return "";
878 int convert_to_git(const char *path, const char *src, size_t len,
879 struct strbuf *dst, enum safe_crlf checksafe)
881 int ret = 0;
882 const char *filter = NULL;
883 int required = 0;
884 struct conv_attrs ca;
886 convert_attrs(&ca, path);
887 if (ca.drv) {
888 filter = ca.drv->clean;
889 required = ca.drv->required;
892 ret |= apply_filter(path, src, len, -1, dst, filter);
893 if (!ret && required)
894 die("%s: clean filter '%s' failed", path, ca.drv->name);
896 if (ret && dst) {
897 src = dst->buf;
898 len = dst->len;
900 ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
901 if (ret && dst) {
902 src = dst->buf;
903 len = dst->len;
905 return ret | ident_to_git(path, src, len, dst, ca.ident);
908 void convert_to_git_filter_fd(const char *path, int fd, struct strbuf *dst,
909 enum safe_crlf checksafe)
911 struct conv_attrs ca;
912 convert_attrs(&ca, path);
914 assert(ca.drv);
915 assert(ca.drv->clean);
917 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv->clean))
918 die("%s: clean filter '%s' failed", path, ca.drv->name);
920 crlf_to_git(path, dst->buf, dst->len, dst, ca.crlf_action, checksafe);
921 ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
924 static int convert_to_working_tree_internal(const char *path, const char *src,
925 size_t len, struct strbuf *dst,
926 int normalizing)
928 int ret = 0, ret_filter = 0;
929 const char *filter = NULL;
930 int required = 0;
931 struct conv_attrs ca;
933 convert_attrs(&ca, path);
934 if (ca.drv) {
935 filter = ca.drv->smudge;
936 required = ca.drv->required;
939 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
940 if (ret) {
941 src = dst->buf;
942 len = dst->len;
945 * CRLF conversion can be skipped if normalizing, unless there
946 * is a smudge filter. The filter might expect CRLFs.
948 if (filter || !normalizing) {
949 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
950 if (ret) {
951 src = dst->buf;
952 len = dst->len;
956 ret_filter = apply_filter(path, src, len, -1, dst, filter);
957 if (!ret_filter && required)
958 die("%s: smudge filter %s failed", path, ca.drv->name);
960 return ret | ret_filter;
963 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
965 return convert_to_working_tree_internal(path, src, len, dst, 0);
968 int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
970 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
971 if (ret) {
972 src = dst->buf;
973 len = dst->len;
975 return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_RENORMALIZE);
978 /*****************************************************************
980 * Streaming conversion support
982 *****************************************************************/
984 typedef int (*filter_fn)(struct stream_filter *,
985 const char *input, size_t *isize_p,
986 char *output, size_t *osize_p);
987 typedef void (*free_fn)(struct stream_filter *);
989 struct stream_filter_vtbl {
990 filter_fn filter;
991 free_fn free;
994 struct stream_filter {
995 struct stream_filter_vtbl *vtbl;
998 static int null_filter_fn(struct stream_filter *filter,
999 const char *input, size_t *isize_p,
1000 char *output, size_t *osize_p)
1002 size_t count;
1004 if (!input)
1005 return 0; /* we do not keep any states */
1006 count = *isize_p;
1007 if (*osize_p < count)
1008 count = *osize_p;
1009 if (count) {
1010 memmove(output, input, count);
1011 *isize_p -= count;
1012 *osize_p -= count;
1014 return 0;
1017 static void null_free_fn(struct stream_filter *filter)
1019 ; /* nothing -- null instances are shared */
1022 static struct stream_filter_vtbl null_vtbl = {
1023 null_filter_fn,
1024 null_free_fn,
1027 static struct stream_filter null_filter_singleton = {
1028 &null_vtbl,
1031 int is_null_stream_filter(struct stream_filter *filter)
1033 return filter == &null_filter_singleton;
1038 * LF-to-CRLF filter
1041 struct lf_to_crlf_filter {
1042 struct stream_filter filter;
1043 unsigned has_held:1;
1044 char held;
1047 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1048 const char *input, size_t *isize_p,
1049 char *output, size_t *osize_p)
1051 size_t count, o = 0;
1052 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1055 * We may be holding onto the CR to see if it is followed by a
1056 * LF, in which case we would need to go to the main loop.
1057 * Otherwise, just emit it to the output stream.
1059 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1060 output[o++] = lf_to_crlf->held;
1061 lf_to_crlf->has_held = 0;
1064 /* We are told to drain */
1065 if (!input) {
1066 *osize_p -= o;
1067 return 0;
1070 count = *isize_p;
1071 if (count || lf_to_crlf->has_held) {
1072 size_t i;
1073 int was_cr = 0;
1075 if (lf_to_crlf->has_held) {
1076 was_cr = 1;
1077 lf_to_crlf->has_held = 0;
1080 for (i = 0; o < *osize_p && i < count; i++) {
1081 char ch = input[i];
1083 if (ch == '\n') {
1084 output[o++] = '\r';
1085 } else if (was_cr) {
1087 * Previous round saw CR and it is not followed
1088 * by a LF; emit the CR before processing the
1089 * current character.
1091 output[o++] = '\r';
1095 * We may have consumed the last output slot,
1096 * in which case we need to break out of this
1097 * loop; hold the current character before
1098 * returning.
1100 if (*osize_p <= o) {
1101 lf_to_crlf->has_held = 1;
1102 lf_to_crlf->held = ch;
1103 continue; /* break but increment i */
1106 if (ch == '\r') {
1107 was_cr = 1;
1108 continue;
1111 was_cr = 0;
1112 output[o++] = ch;
1115 *osize_p -= o;
1116 *isize_p -= i;
1118 if (!lf_to_crlf->has_held && was_cr) {
1119 lf_to_crlf->has_held = 1;
1120 lf_to_crlf->held = '\r';
1123 return 0;
1126 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1128 free(filter);
1131 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1132 lf_to_crlf_filter_fn,
1133 lf_to_crlf_free_fn,
1136 static struct stream_filter *lf_to_crlf_filter(void)
1138 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1140 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1141 return (struct stream_filter *)lf_to_crlf;
1145 * Cascade filter
1147 #define FILTER_BUFFER 1024
1148 struct cascade_filter {
1149 struct stream_filter filter;
1150 struct stream_filter *one;
1151 struct stream_filter *two;
1152 char buf[FILTER_BUFFER];
1153 int end, ptr;
1156 static int cascade_filter_fn(struct stream_filter *filter,
1157 const char *input, size_t *isize_p,
1158 char *output, size_t *osize_p)
1160 struct cascade_filter *cas = (struct cascade_filter *) filter;
1161 size_t filled = 0;
1162 size_t sz = *osize_p;
1163 size_t to_feed, remaining;
1166 * input -- (one) --> buf -- (two) --> output
1168 while (filled < sz) {
1169 remaining = sz - filled;
1171 /* do we already have something to feed two with? */
1172 if (cas->ptr < cas->end) {
1173 to_feed = cas->end - cas->ptr;
1174 if (stream_filter(cas->two,
1175 cas->buf + cas->ptr, &to_feed,
1176 output + filled, &remaining))
1177 return -1;
1178 cas->ptr += (cas->end - cas->ptr) - to_feed;
1179 filled = sz - remaining;
1180 continue;
1183 /* feed one from upstream and have it emit into our buffer */
1184 to_feed = input ? *isize_p : 0;
1185 if (input && !to_feed)
1186 break;
1187 remaining = sizeof(cas->buf);
1188 if (stream_filter(cas->one,
1189 input, &to_feed,
1190 cas->buf, &remaining))
1191 return -1;
1192 cas->end = sizeof(cas->buf) - remaining;
1193 cas->ptr = 0;
1194 if (input) {
1195 size_t fed = *isize_p - to_feed;
1196 *isize_p -= fed;
1197 input += fed;
1200 /* do we know that we drained one completely? */
1201 if (input || cas->end)
1202 continue;
1204 /* tell two to drain; we have nothing more to give it */
1205 to_feed = 0;
1206 remaining = sz - filled;
1207 if (stream_filter(cas->two,
1208 NULL, &to_feed,
1209 output + filled, &remaining))
1210 return -1;
1211 if (remaining == (sz - filled))
1212 break; /* completely drained two */
1213 filled = sz - remaining;
1215 *osize_p -= filled;
1216 return 0;
1219 static void cascade_free_fn(struct stream_filter *filter)
1221 struct cascade_filter *cas = (struct cascade_filter *)filter;
1222 free_stream_filter(cas->one);
1223 free_stream_filter(cas->two);
1224 free(filter);
1227 static struct stream_filter_vtbl cascade_vtbl = {
1228 cascade_filter_fn,
1229 cascade_free_fn,
1232 static struct stream_filter *cascade_filter(struct stream_filter *one,
1233 struct stream_filter *two)
1235 struct cascade_filter *cascade;
1237 if (!one || is_null_stream_filter(one))
1238 return two;
1239 if (!two || is_null_stream_filter(two))
1240 return one;
1242 cascade = xmalloc(sizeof(*cascade));
1243 cascade->one = one;
1244 cascade->two = two;
1245 cascade->end = cascade->ptr = 0;
1246 cascade->filter.vtbl = &cascade_vtbl;
1247 return (struct stream_filter *)cascade;
1251 * ident filter
1253 #define IDENT_DRAINING (-1)
1254 #define IDENT_SKIPPING (-2)
1255 struct ident_filter {
1256 struct stream_filter filter;
1257 struct strbuf left;
1258 int state;
1259 char ident[45]; /* ": x40 $" */
1262 static int is_foreign_ident(const char *str)
1264 int i;
1266 if (!skip_prefix(str, "$Id: ", &str))
1267 return 0;
1268 for (i = 0; str[i]; i++) {
1269 if (isspace(str[i]) && str[i+1] != '$')
1270 return 1;
1272 return 0;
1275 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1277 size_t to_drain = ident->left.len;
1279 if (*osize_p < to_drain)
1280 to_drain = *osize_p;
1281 if (to_drain) {
1282 memcpy(*output_p, ident->left.buf, to_drain);
1283 strbuf_remove(&ident->left, 0, to_drain);
1284 *output_p += to_drain;
1285 *osize_p -= to_drain;
1287 if (!ident->left.len)
1288 ident->state = 0;
1291 static int ident_filter_fn(struct stream_filter *filter,
1292 const char *input, size_t *isize_p,
1293 char *output, size_t *osize_p)
1295 struct ident_filter *ident = (struct ident_filter *)filter;
1296 static const char head[] = "$Id";
1298 if (!input) {
1299 /* drain upon eof */
1300 switch (ident->state) {
1301 default:
1302 strbuf_add(&ident->left, head, ident->state);
1303 case IDENT_SKIPPING:
1304 /* fallthru */
1305 case IDENT_DRAINING:
1306 ident_drain(ident, &output, osize_p);
1308 return 0;
1311 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1312 int ch;
1314 if (ident->state == IDENT_DRAINING) {
1315 ident_drain(ident, &output, osize_p);
1316 if (!*osize_p)
1317 break;
1318 continue;
1321 ch = *(input++);
1322 (*isize_p)--;
1324 if (ident->state == IDENT_SKIPPING) {
1326 * Skipping until '$' or LF, but keeping them
1327 * in case it is a foreign ident.
1329 strbuf_addch(&ident->left, ch);
1330 if (ch != '\n' && ch != '$')
1331 continue;
1332 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1333 strbuf_setlen(&ident->left, sizeof(head) - 1);
1334 strbuf_addstr(&ident->left, ident->ident);
1336 ident->state = IDENT_DRAINING;
1337 continue;
1340 if (ident->state < sizeof(head) &&
1341 head[ident->state] == ch) {
1342 ident->state++;
1343 continue;
1346 if (ident->state)
1347 strbuf_add(&ident->left, head, ident->state);
1348 if (ident->state == sizeof(head) - 1) {
1349 if (ch != ':' && ch != '$') {
1350 strbuf_addch(&ident->left, ch);
1351 ident->state = 0;
1352 continue;
1355 if (ch == ':') {
1356 strbuf_addch(&ident->left, ch);
1357 ident->state = IDENT_SKIPPING;
1358 } else {
1359 strbuf_addstr(&ident->left, ident->ident);
1360 ident->state = IDENT_DRAINING;
1362 continue;
1365 strbuf_addch(&ident->left, ch);
1366 ident->state = IDENT_DRAINING;
1368 return 0;
1371 static void ident_free_fn(struct stream_filter *filter)
1373 struct ident_filter *ident = (struct ident_filter *)filter;
1374 strbuf_release(&ident->left);
1375 free(filter);
1378 static struct stream_filter_vtbl ident_vtbl = {
1379 ident_filter_fn,
1380 ident_free_fn,
1383 static struct stream_filter *ident_filter(const unsigned char *sha1)
1385 struct ident_filter *ident = xmalloc(sizeof(*ident));
1387 xsnprintf(ident->ident, sizeof(ident->ident),
1388 ": %s $", sha1_to_hex(sha1));
1389 strbuf_init(&ident->left, 0);
1390 ident->filter.vtbl = &ident_vtbl;
1391 ident->state = 0;
1392 return (struct stream_filter *)ident;
1396 * Return an appropriately constructed filter for the path, or NULL if
1397 * the contents cannot be filtered without reading the whole thing
1398 * in-core.
1400 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1401 * large binary blob you would want us not to slurp into the memory!
1403 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1405 struct conv_attrs ca;
1406 struct stream_filter *filter = NULL;
1408 convert_attrs(&ca, path);
1409 if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1410 return NULL;
1412 if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1413 return NULL;
1415 if (ca.ident)
1416 filter = ident_filter(sha1);
1418 if (output_eol(ca.crlf_action) == EOL_CRLF)
1419 filter = cascade_filter(filter, lf_to_crlf_filter());
1420 else
1421 filter = cascade_filter(filter, &null_filter_singleton);
1423 return filter;
1426 void free_stream_filter(struct stream_filter *filter)
1428 filter->vtbl->free(filter);
1431 int stream_filter(struct stream_filter *filter,
1432 const char *input, size_t *isize_p,
1433 char *output, size_t *osize_p)
1435 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);