config.c: rename label unlock_and_out
[git/raj.git] / convert.c
blob67d69b5c0e22a74e6dc46764beaff9978a78b85a
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 *stats, enum safe_crlf checksafe)
194 if (!checksafe)
195 return;
197 if (output_eol(crlf_action) == EOL_LF) {
199 * CRLFs would not be restored by checkout:
200 * check if we'd remove CRLFs
202 if (stats->crlf) {
203 if (checksafe == SAFE_CRLF_WARN)
204 warning("CRLF will be replaced by LF in %s.\nThe file will have its original line endings in your working directory.", path);
205 else /* i.e. SAFE_CRLF_FAIL */
206 die("CRLF would be replaced by LF in %s.", path);
208 } else if (output_eol(crlf_action) == EOL_CRLF) {
210 * CRLFs would be added by checkout:
211 * check if we have "naked" LFs
213 if (stats->lonelf) {
214 if (checksafe == SAFE_CRLF_WARN)
215 warning("LF will be replaced by CRLF in %s.\nThe file will have its original line endings in your working directory.", path);
216 else /* i.e. SAFE_CRLF_FAIL */
217 die("LF would be replaced by CRLF in %s", path);
222 static int has_cr_in_index(const char *path)
224 unsigned long sz;
225 void *data;
226 int has_cr;
228 data = read_blob_data_from_cache(path, &sz);
229 if (!data)
230 return 0;
231 has_cr = memchr(data, '\r', sz) != NULL;
232 free(data);
233 return has_cr;
236 static int crlf_to_git(const char *path, const char *src, size_t len,
237 struct strbuf *buf,
238 enum crlf_action crlf_action, enum safe_crlf checksafe)
240 struct text_stat stats;
241 char *dst;
243 if (crlf_action == CRLF_BINARY ||
244 (src && !len))
245 return 0;
248 * If we are doing a dry-run and have no source buffer, there is
249 * nothing to analyze; we must assume we would convert.
251 if (!buf && !src)
252 return 1;
254 gather_stats(src, len, &stats);
256 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
257 if (convert_is_binary(len, &stats))
258 return 0;
260 * If the file in the index has any CR in it, do not convert.
261 * This is the new safer autocrlf handling.
263 if (checksafe == SAFE_CRLF_RENORMALIZE)
264 checksafe = SAFE_CRLF_FALSE;
265 else if (has_cr_in_index(path))
266 return 0;
268 check_safe_crlf(path, crlf_action, &stats, checksafe);
270 /* Optimization: No CRLF? Nothing to convert, regardless. */
271 if (!stats.crlf)
272 return 0;
275 * At this point all of our source analysis is done, and we are sure we
276 * would convert. If we are in dry-run mode, we can give an answer.
278 if (!buf)
279 return 1;
281 /* only grow if not in place */
282 if (strbuf_avail(buf) + buf->len < len)
283 strbuf_grow(buf, len - buf->len);
284 dst = buf->buf;
285 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
287 * If we guessed, we already know we rejected a file with
288 * lone CR, and we can strip a CR without looking at what
289 * follow it.
291 do {
292 unsigned char c = *src++;
293 if (c != '\r')
294 *dst++ = c;
295 } while (--len);
296 } else {
297 do {
298 unsigned char c = *src++;
299 if (! (c == '\r' && (1 < len && *src == '\n')))
300 *dst++ = c;
301 } while (--len);
303 strbuf_setlen(buf, dst - buf->buf);
304 return 1;
307 static int crlf_to_worktree(const char *path, const char *src, size_t len,
308 struct strbuf *buf, enum crlf_action crlf_action)
310 char *to_free = NULL;
311 struct text_stat stats;
313 if (!len || output_eol(crlf_action) != EOL_CRLF)
314 return 0;
316 gather_stats(src, len, &stats);
318 /* No "naked" LF? Nothing to convert, regardless. */
319 if (!stats.lonelf)
320 return 0;
322 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
323 /* If we have any CR or CRLF line endings, we do not touch it */
324 /* This is the new safer autocrlf-handling */
325 if (stats.lonecr || stats.crlf )
326 return 0;
328 if (convert_is_binary(len, &stats))
329 return 0;
332 /* are we "faking" in place editing ? */
333 if (src == buf->buf)
334 to_free = strbuf_detach(buf, NULL);
336 strbuf_grow(buf, len + stats.lonelf);
337 for (;;) {
338 const char *nl = memchr(src, '\n', len);
339 if (!nl)
340 break;
341 if (nl > src && nl[-1] == '\r') {
342 strbuf_add(buf, src, nl + 1 - src);
343 } else {
344 strbuf_add(buf, src, nl - src);
345 strbuf_addstr(buf, "\r\n");
347 len -= nl + 1 - src;
348 src = nl + 1;
350 strbuf_add(buf, src, len);
352 free(to_free);
353 return 1;
356 struct filter_params {
357 const char *src;
358 unsigned long size;
359 int fd;
360 const char *cmd;
361 const char *path;
364 static int filter_buffer_or_fd(int in, int out, void *data)
367 * Spawn cmd and feed the buffer contents through its stdin.
369 struct child_process child_process = CHILD_PROCESS_INIT;
370 struct filter_params *params = (struct filter_params *)data;
371 int write_err, status;
372 const char *argv[] = { NULL, NULL };
374 /* apply % substitution to cmd */
375 struct strbuf cmd = STRBUF_INIT;
376 struct strbuf path = STRBUF_INIT;
377 struct strbuf_expand_dict_entry dict[] = {
378 { "f", NULL, },
379 { NULL, NULL, },
382 /* quote the path to preserve spaces, etc. */
383 sq_quote_buf(&path, params->path);
384 dict[0].value = path.buf;
386 /* expand all %f with the quoted path */
387 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
388 strbuf_release(&path);
390 argv[0] = cmd.buf;
392 child_process.argv = argv;
393 child_process.use_shell = 1;
394 child_process.in = -1;
395 child_process.out = out;
397 if (start_command(&child_process))
398 return error("cannot fork to run external filter %s", params->cmd);
400 sigchain_push(SIGPIPE, SIG_IGN);
402 if (params->src) {
403 write_err = (write_in_full(child_process.in,
404 params->src, params->size) < 0);
405 if (errno == EPIPE)
406 write_err = 0;
407 } else {
408 write_err = copy_fd(params->fd, child_process.in);
409 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
410 write_err = 0;
413 if (close(child_process.in))
414 write_err = 1;
415 if (write_err)
416 error("cannot feed the input to external filter %s", params->cmd);
418 sigchain_pop(SIGPIPE);
420 status = finish_command(&child_process);
421 if (status)
422 error("external filter %s failed %d", params->cmd, status);
424 strbuf_release(&cmd);
425 return (write_err || status);
428 static int apply_filter(const char *path, const char *src, size_t len, int fd,
429 struct strbuf *dst, const char *cmd)
432 * Create a pipeline to have the command filter the buffer's
433 * contents.
435 * (child --> cmd) --> us
437 int ret = 1;
438 struct strbuf nbuf = STRBUF_INIT;
439 struct async async;
440 struct filter_params params;
442 if (!cmd || !*cmd)
443 return 0;
445 if (!dst)
446 return 1;
448 memset(&async, 0, sizeof(async));
449 async.proc = filter_buffer_or_fd;
450 async.data = &params;
451 async.out = -1;
452 params.src = src;
453 params.size = len;
454 params.fd = fd;
455 params.cmd = cmd;
456 params.path = path;
458 fflush(NULL);
459 if (start_async(&async))
460 return 0; /* error was already reported */
462 if (strbuf_read(&nbuf, async.out, len) < 0) {
463 error("read from external filter %s failed", cmd);
464 ret = 0;
466 if (close(async.out)) {
467 error("read from external filter %s failed", cmd);
468 ret = 0;
470 if (finish_async(&async)) {
471 error("external filter %s failed", cmd);
472 ret = 0;
475 if (ret) {
476 strbuf_swap(dst, &nbuf);
478 strbuf_release(&nbuf);
479 return ret;
482 static struct convert_driver {
483 const char *name;
484 struct convert_driver *next;
485 const char *smudge;
486 const char *clean;
487 int required;
488 } *user_convert, **user_convert_tail;
490 static int read_convert_config(const char *var, const char *value, void *cb)
492 const char *key, *name;
493 int namelen;
494 struct convert_driver *drv;
497 * External conversion drivers are configured using
498 * "filter.<name>.variable".
500 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
501 return 0;
502 for (drv = user_convert; drv; drv = drv->next)
503 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
504 break;
505 if (!drv) {
506 drv = xcalloc(1, sizeof(struct convert_driver));
507 drv->name = xmemdupz(name, namelen);
508 *user_convert_tail = drv;
509 user_convert_tail = &(drv->next);
513 * filter.<name>.smudge and filter.<name>.clean specifies
514 * the command line:
516 * command-line
518 * The command-line will not be interpolated in any way.
521 if (!strcmp("smudge", key))
522 return git_config_string(&drv->smudge, var, value);
524 if (!strcmp("clean", key))
525 return git_config_string(&drv->clean, var, value);
527 if (!strcmp("required", key)) {
528 drv->required = git_config_bool(var, value);
529 return 0;
532 return 0;
535 static int count_ident(const char *cp, unsigned long size)
538 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
540 int cnt = 0;
541 char ch;
543 while (size) {
544 ch = *cp++;
545 size--;
546 if (ch != '$')
547 continue;
548 if (size < 3)
549 break;
550 if (memcmp("Id", cp, 2))
551 continue;
552 ch = cp[2];
553 cp += 3;
554 size -= 3;
555 if (ch == '$')
556 cnt++; /* $Id$ */
557 if (ch != ':')
558 continue;
561 * "$Id: ... "; scan up to the closing dollar sign and discard.
563 while (size) {
564 ch = *cp++;
565 size--;
566 if (ch == '$') {
567 cnt++;
568 break;
570 if (ch == '\n')
571 break;
574 return cnt;
577 static int ident_to_git(const char *path, const char *src, size_t len,
578 struct strbuf *buf, int ident)
580 char *dst, *dollar;
582 if (!ident || (src && !count_ident(src, len)))
583 return 0;
585 if (!buf)
586 return 1;
588 /* only grow if not in place */
589 if (strbuf_avail(buf) + buf->len < len)
590 strbuf_grow(buf, len - buf->len);
591 dst = buf->buf;
592 for (;;) {
593 dollar = memchr(src, '$', len);
594 if (!dollar)
595 break;
596 memmove(dst, src, dollar + 1 - src);
597 dst += dollar + 1 - src;
598 len -= dollar + 1 - src;
599 src = dollar + 1;
601 if (len > 3 && !memcmp(src, "Id:", 3)) {
602 dollar = memchr(src + 3, '$', len - 3);
603 if (!dollar)
604 break;
605 if (memchr(src + 3, '\n', dollar - src - 3)) {
606 /* Line break before the next dollar. */
607 continue;
610 memcpy(dst, "Id$", 3);
611 dst += 3;
612 len -= dollar + 1 - src;
613 src = dollar + 1;
616 memmove(dst, src, len);
617 strbuf_setlen(buf, dst + len - buf->buf);
618 return 1;
621 static int ident_to_worktree(const char *path, const char *src, size_t len,
622 struct strbuf *buf, int ident)
624 unsigned char sha1[20];
625 char *to_free = NULL, *dollar, *spc;
626 int cnt;
628 if (!ident)
629 return 0;
631 cnt = count_ident(src, len);
632 if (!cnt)
633 return 0;
635 /* are we "faking" in place editing ? */
636 if (src == buf->buf)
637 to_free = strbuf_detach(buf, NULL);
638 hash_sha1_file(src, len, "blob", sha1);
640 strbuf_grow(buf, len + cnt * 43);
641 for (;;) {
642 /* step 1: run to the next '$' */
643 dollar = memchr(src, '$', len);
644 if (!dollar)
645 break;
646 strbuf_add(buf, src, dollar + 1 - src);
647 len -= dollar + 1 - src;
648 src = dollar + 1;
650 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
651 if (len < 3 || memcmp("Id", src, 2))
652 continue;
654 /* step 3: skip over Id$ or Id:xxxxx$ */
655 if (src[2] == '$') {
656 src += 3;
657 len -= 3;
658 } else if (src[2] == ':') {
660 * It's possible that an expanded Id has crept its way into the
661 * repository, we cope with that by stripping the expansion out.
662 * This is probably not a good idea, since it will cause changes
663 * on checkout, which won't go away by stash, but let's keep it
664 * for git-style ids.
666 dollar = memchr(src + 3, '$', len - 3);
667 if (!dollar) {
668 /* incomplete keyword, no more '$', so just quit the loop */
669 break;
672 if (memchr(src + 3, '\n', dollar - src - 3)) {
673 /* Line break before the next dollar. */
674 continue;
677 spc = memchr(src + 4, ' ', dollar - src - 4);
678 if (spc && spc < dollar-1) {
679 /* There are spaces in unexpected places.
680 * This is probably an id from some other
681 * versioning system. Keep it for now.
683 continue;
686 len -= dollar + 1 - src;
687 src = dollar + 1;
688 } else {
689 /* it wasn't a "Id$" or "Id:xxxx$" */
690 continue;
693 /* step 4: substitute */
694 strbuf_addstr(buf, "Id: ");
695 strbuf_add(buf, sha1_to_hex(sha1), 40);
696 strbuf_addstr(buf, " $");
698 strbuf_add(buf, src, len);
700 free(to_free);
701 return 1;
704 static enum crlf_action git_path_check_crlf(struct git_attr_check *check)
706 const char *value = check->value;
708 if (ATTR_TRUE(value))
709 return CRLF_TEXT;
710 else if (ATTR_FALSE(value))
711 return CRLF_BINARY;
712 else if (ATTR_UNSET(value))
714 else if (!strcmp(value, "input"))
715 return CRLF_TEXT_INPUT;
716 else if (!strcmp(value, "auto"))
717 return CRLF_AUTO;
718 return CRLF_UNDEFINED;
721 static enum eol git_path_check_eol(struct git_attr_check *check)
723 const char *value = check->value;
725 if (ATTR_UNSET(value))
727 else if (!strcmp(value, "lf"))
728 return EOL_LF;
729 else if (!strcmp(value, "crlf"))
730 return EOL_CRLF;
731 return EOL_UNSET;
734 static struct convert_driver *git_path_check_convert(struct git_attr_check *check)
736 const char *value = check->value;
737 struct convert_driver *drv;
739 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
740 return NULL;
741 for (drv = user_convert; drv; drv = drv->next)
742 if (!strcmp(value, drv->name))
743 return drv;
744 return NULL;
747 static int git_path_check_ident(struct git_attr_check *check)
749 const char *value = check->value;
751 return !!ATTR_TRUE(value);
754 struct conv_attrs {
755 struct convert_driver *drv;
756 enum crlf_action attr_action; /* What attr says */
757 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
758 int ident;
761 static const char *conv_attr_name[] = {
762 "crlf", "ident", "filter", "eol", "text",
764 #define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
766 static void convert_attrs(struct conv_attrs *ca, const char *path)
768 int i;
769 static struct git_attr_check ccheck[NUM_CONV_ATTRS];
771 if (!ccheck[0].attr) {
772 for (i = 0; i < NUM_CONV_ATTRS; i++)
773 ccheck[i].attr = git_attr(conv_attr_name[i]);
774 user_convert_tail = &user_convert;
775 git_config(read_convert_config, NULL);
778 if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
779 ca->crlf_action = git_path_check_crlf(ccheck + 4);
780 if (ca->crlf_action == CRLF_UNDEFINED)
781 ca->crlf_action = git_path_check_crlf(ccheck + 0);
782 ca->attr_action = ca->crlf_action;
783 ca->ident = git_path_check_ident(ccheck + 1);
784 ca->drv = git_path_check_convert(ccheck + 2);
785 if (ca->crlf_action != CRLF_BINARY) {
786 enum eol eol_attr = git_path_check_eol(ccheck + 3);
787 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
788 ca->crlf_action = CRLF_AUTO_INPUT;
789 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
790 ca->crlf_action = CRLF_AUTO_CRLF;
791 else if (eol_attr == EOL_LF)
792 ca->crlf_action = CRLF_TEXT_INPUT;
793 else if (eol_attr == EOL_CRLF)
794 ca->crlf_action = CRLF_TEXT_CRLF;
796 ca->attr_action = ca->crlf_action;
797 } else {
798 ca->drv = NULL;
799 ca->crlf_action = CRLF_UNDEFINED;
800 ca->ident = 0;
802 if (ca->crlf_action == CRLF_TEXT)
803 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
804 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
805 ca->crlf_action = CRLF_BINARY;
806 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
807 ca->crlf_action = CRLF_AUTO_CRLF;
808 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
809 ca->crlf_action = CRLF_AUTO_INPUT;
812 int would_convert_to_git_filter_fd(const char *path)
814 struct conv_attrs ca;
816 convert_attrs(&ca, path);
817 if (!ca.drv)
818 return 0;
821 * Apply a filter to an fd only if the filter is required to succeed.
822 * We must die if the filter fails, because the original data before
823 * filtering is not available.
825 if (!ca.drv->required)
826 return 0;
828 return apply_filter(path, NULL, 0, -1, NULL, ca.drv->clean);
831 const char *get_convert_attr_ascii(const char *path)
833 struct conv_attrs ca;
835 convert_attrs(&ca, path);
836 switch (ca.attr_action) {
837 case CRLF_UNDEFINED:
838 return "";
839 case CRLF_BINARY:
840 return "-text";
841 case CRLF_TEXT:
842 return "text";
843 case CRLF_TEXT_INPUT:
844 return "text eol=lf";
845 case CRLF_TEXT_CRLF:
846 return "text eol=crlf";
847 case CRLF_AUTO:
848 return "text=auto";
849 case CRLF_AUTO_CRLF:
850 return "text=auto eol=crlf";
851 case CRLF_AUTO_INPUT:
852 return "text=auto eol=lf";
854 return "";
857 int convert_to_git(const char *path, const char *src, size_t len,
858 struct strbuf *dst, enum safe_crlf checksafe)
860 int ret = 0;
861 const char *filter = NULL;
862 int required = 0;
863 struct conv_attrs ca;
865 convert_attrs(&ca, path);
866 if (ca.drv) {
867 filter = ca.drv->clean;
868 required = ca.drv->required;
871 ret |= apply_filter(path, src, len, -1, dst, filter);
872 if (!ret && required)
873 die("%s: clean filter '%s' failed", path, ca.drv->name);
875 if (ret && dst) {
876 src = dst->buf;
877 len = dst->len;
879 ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
880 if (ret && dst) {
881 src = dst->buf;
882 len = dst->len;
884 return ret | ident_to_git(path, src, len, dst, ca.ident);
887 void convert_to_git_filter_fd(const char *path, int fd, struct strbuf *dst,
888 enum safe_crlf checksafe)
890 struct conv_attrs ca;
891 convert_attrs(&ca, path);
893 assert(ca.drv);
894 assert(ca.drv->clean);
896 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv->clean))
897 die("%s: clean filter '%s' failed", path, ca.drv->name);
899 crlf_to_git(path, dst->buf, dst->len, dst, ca.crlf_action, checksafe);
900 ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
903 static int convert_to_working_tree_internal(const char *path, const char *src,
904 size_t len, struct strbuf *dst,
905 int normalizing)
907 int ret = 0, ret_filter = 0;
908 const char *filter = NULL;
909 int required = 0;
910 struct conv_attrs ca;
912 convert_attrs(&ca, path);
913 if (ca.drv) {
914 filter = ca.drv->smudge;
915 required = ca.drv->required;
918 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
919 if (ret) {
920 src = dst->buf;
921 len = dst->len;
924 * CRLF conversion can be skipped if normalizing, unless there
925 * is a smudge filter. The filter might expect CRLFs.
927 if (filter || !normalizing) {
928 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
929 if (ret) {
930 src = dst->buf;
931 len = dst->len;
935 ret_filter = apply_filter(path, src, len, -1, dst, filter);
936 if (!ret_filter && required)
937 die("%s: smudge filter %s failed", path, ca.drv->name);
939 return ret | ret_filter;
942 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
944 return convert_to_working_tree_internal(path, src, len, dst, 0);
947 int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
949 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
950 if (ret) {
951 src = dst->buf;
952 len = dst->len;
954 return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_RENORMALIZE);
957 /*****************************************************************
959 * Streaming conversion support
961 *****************************************************************/
963 typedef int (*filter_fn)(struct stream_filter *,
964 const char *input, size_t *isize_p,
965 char *output, size_t *osize_p);
966 typedef void (*free_fn)(struct stream_filter *);
968 struct stream_filter_vtbl {
969 filter_fn filter;
970 free_fn free;
973 struct stream_filter {
974 struct stream_filter_vtbl *vtbl;
977 static int null_filter_fn(struct stream_filter *filter,
978 const char *input, size_t *isize_p,
979 char *output, size_t *osize_p)
981 size_t count;
983 if (!input)
984 return 0; /* we do not keep any states */
985 count = *isize_p;
986 if (*osize_p < count)
987 count = *osize_p;
988 if (count) {
989 memmove(output, input, count);
990 *isize_p -= count;
991 *osize_p -= count;
993 return 0;
996 static void null_free_fn(struct stream_filter *filter)
998 ; /* nothing -- null instances are shared */
1001 static struct stream_filter_vtbl null_vtbl = {
1002 null_filter_fn,
1003 null_free_fn,
1006 static struct stream_filter null_filter_singleton = {
1007 &null_vtbl,
1010 int is_null_stream_filter(struct stream_filter *filter)
1012 return filter == &null_filter_singleton;
1017 * LF-to-CRLF filter
1020 struct lf_to_crlf_filter {
1021 struct stream_filter filter;
1022 unsigned has_held:1;
1023 char held;
1026 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1027 const char *input, size_t *isize_p,
1028 char *output, size_t *osize_p)
1030 size_t count, o = 0;
1031 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1034 * We may be holding onto the CR to see if it is followed by a
1035 * LF, in which case we would need to go to the main loop.
1036 * Otherwise, just emit it to the output stream.
1038 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1039 output[o++] = lf_to_crlf->held;
1040 lf_to_crlf->has_held = 0;
1043 /* We are told to drain */
1044 if (!input) {
1045 *osize_p -= o;
1046 return 0;
1049 count = *isize_p;
1050 if (count || lf_to_crlf->has_held) {
1051 size_t i;
1052 int was_cr = 0;
1054 if (lf_to_crlf->has_held) {
1055 was_cr = 1;
1056 lf_to_crlf->has_held = 0;
1059 for (i = 0; o < *osize_p && i < count; i++) {
1060 char ch = input[i];
1062 if (ch == '\n') {
1063 output[o++] = '\r';
1064 } else if (was_cr) {
1066 * Previous round saw CR and it is not followed
1067 * by a LF; emit the CR before processing the
1068 * current character.
1070 output[o++] = '\r';
1074 * We may have consumed the last output slot,
1075 * in which case we need to break out of this
1076 * loop; hold the current character before
1077 * returning.
1079 if (*osize_p <= o) {
1080 lf_to_crlf->has_held = 1;
1081 lf_to_crlf->held = ch;
1082 continue; /* break but increment i */
1085 if (ch == '\r') {
1086 was_cr = 1;
1087 continue;
1090 was_cr = 0;
1091 output[o++] = ch;
1094 *osize_p -= o;
1095 *isize_p -= i;
1097 if (!lf_to_crlf->has_held && was_cr) {
1098 lf_to_crlf->has_held = 1;
1099 lf_to_crlf->held = '\r';
1102 return 0;
1105 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1107 free(filter);
1110 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1111 lf_to_crlf_filter_fn,
1112 lf_to_crlf_free_fn,
1115 static struct stream_filter *lf_to_crlf_filter(void)
1117 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1119 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1120 return (struct stream_filter *)lf_to_crlf;
1124 * Cascade filter
1126 #define FILTER_BUFFER 1024
1127 struct cascade_filter {
1128 struct stream_filter filter;
1129 struct stream_filter *one;
1130 struct stream_filter *two;
1131 char buf[FILTER_BUFFER];
1132 int end, ptr;
1135 static int cascade_filter_fn(struct stream_filter *filter,
1136 const char *input, size_t *isize_p,
1137 char *output, size_t *osize_p)
1139 struct cascade_filter *cas = (struct cascade_filter *) filter;
1140 size_t filled = 0;
1141 size_t sz = *osize_p;
1142 size_t to_feed, remaining;
1145 * input -- (one) --> buf -- (two) --> output
1147 while (filled < sz) {
1148 remaining = sz - filled;
1150 /* do we already have something to feed two with? */
1151 if (cas->ptr < cas->end) {
1152 to_feed = cas->end - cas->ptr;
1153 if (stream_filter(cas->two,
1154 cas->buf + cas->ptr, &to_feed,
1155 output + filled, &remaining))
1156 return -1;
1157 cas->ptr += (cas->end - cas->ptr) - to_feed;
1158 filled = sz - remaining;
1159 continue;
1162 /* feed one from upstream and have it emit into our buffer */
1163 to_feed = input ? *isize_p : 0;
1164 if (input && !to_feed)
1165 break;
1166 remaining = sizeof(cas->buf);
1167 if (stream_filter(cas->one,
1168 input, &to_feed,
1169 cas->buf, &remaining))
1170 return -1;
1171 cas->end = sizeof(cas->buf) - remaining;
1172 cas->ptr = 0;
1173 if (input) {
1174 size_t fed = *isize_p - to_feed;
1175 *isize_p -= fed;
1176 input += fed;
1179 /* do we know that we drained one completely? */
1180 if (input || cas->end)
1181 continue;
1183 /* tell two to drain; we have nothing more to give it */
1184 to_feed = 0;
1185 remaining = sz - filled;
1186 if (stream_filter(cas->two,
1187 NULL, &to_feed,
1188 output + filled, &remaining))
1189 return -1;
1190 if (remaining == (sz - filled))
1191 break; /* completely drained two */
1192 filled = sz - remaining;
1194 *osize_p -= filled;
1195 return 0;
1198 static void cascade_free_fn(struct stream_filter *filter)
1200 struct cascade_filter *cas = (struct cascade_filter *)filter;
1201 free_stream_filter(cas->one);
1202 free_stream_filter(cas->two);
1203 free(filter);
1206 static struct stream_filter_vtbl cascade_vtbl = {
1207 cascade_filter_fn,
1208 cascade_free_fn,
1211 static struct stream_filter *cascade_filter(struct stream_filter *one,
1212 struct stream_filter *two)
1214 struct cascade_filter *cascade;
1216 if (!one || is_null_stream_filter(one))
1217 return two;
1218 if (!two || is_null_stream_filter(two))
1219 return one;
1221 cascade = xmalloc(sizeof(*cascade));
1222 cascade->one = one;
1223 cascade->two = two;
1224 cascade->end = cascade->ptr = 0;
1225 cascade->filter.vtbl = &cascade_vtbl;
1226 return (struct stream_filter *)cascade;
1230 * ident filter
1232 #define IDENT_DRAINING (-1)
1233 #define IDENT_SKIPPING (-2)
1234 struct ident_filter {
1235 struct stream_filter filter;
1236 struct strbuf left;
1237 int state;
1238 char ident[45]; /* ": x40 $" */
1241 static int is_foreign_ident(const char *str)
1243 int i;
1245 if (!skip_prefix(str, "$Id: ", &str))
1246 return 0;
1247 for (i = 0; str[i]; i++) {
1248 if (isspace(str[i]) && str[i+1] != '$')
1249 return 1;
1251 return 0;
1254 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1256 size_t to_drain = ident->left.len;
1258 if (*osize_p < to_drain)
1259 to_drain = *osize_p;
1260 if (to_drain) {
1261 memcpy(*output_p, ident->left.buf, to_drain);
1262 strbuf_remove(&ident->left, 0, to_drain);
1263 *output_p += to_drain;
1264 *osize_p -= to_drain;
1266 if (!ident->left.len)
1267 ident->state = 0;
1270 static int ident_filter_fn(struct stream_filter *filter,
1271 const char *input, size_t *isize_p,
1272 char *output, size_t *osize_p)
1274 struct ident_filter *ident = (struct ident_filter *)filter;
1275 static const char head[] = "$Id";
1277 if (!input) {
1278 /* drain upon eof */
1279 switch (ident->state) {
1280 default:
1281 strbuf_add(&ident->left, head, ident->state);
1282 case IDENT_SKIPPING:
1283 /* fallthru */
1284 case IDENT_DRAINING:
1285 ident_drain(ident, &output, osize_p);
1287 return 0;
1290 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1291 int ch;
1293 if (ident->state == IDENT_DRAINING) {
1294 ident_drain(ident, &output, osize_p);
1295 if (!*osize_p)
1296 break;
1297 continue;
1300 ch = *(input++);
1301 (*isize_p)--;
1303 if (ident->state == IDENT_SKIPPING) {
1305 * Skipping until '$' or LF, but keeping them
1306 * in case it is a foreign ident.
1308 strbuf_addch(&ident->left, ch);
1309 if (ch != '\n' && ch != '$')
1310 continue;
1311 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1312 strbuf_setlen(&ident->left, sizeof(head) - 1);
1313 strbuf_addstr(&ident->left, ident->ident);
1315 ident->state = IDENT_DRAINING;
1316 continue;
1319 if (ident->state < sizeof(head) &&
1320 head[ident->state] == ch) {
1321 ident->state++;
1322 continue;
1325 if (ident->state)
1326 strbuf_add(&ident->left, head, ident->state);
1327 if (ident->state == sizeof(head) - 1) {
1328 if (ch != ':' && ch != '$') {
1329 strbuf_addch(&ident->left, ch);
1330 ident->state = 0;
1331 continue;
1334 if (ch == ':') {
1335 strbuf_addch(&ident->left, ch);
1336 ident->state = IDENT_SKIPPING;
1337 } else {
1338 strbuf_addstr(&ident->left, ident->ident);
1339 ident->state = IDENT_DRAINING;
1341 continue;
1344 strbuf_addch(&ident->left, ch);
1345 ident->state = IDENT_DRAINING;
1347 return 0;
1350 static void ident_free_fn(struct stream_filter *filter)
1352 struct ident_filter *ident = (struct ident_filter *)filter;
1353 strbuf_release(&ident->left);
1354 free(filter);
1357 static struct stream_filter_vtbl ident_vtbl = {
1358 ident_filter_fn,
1359 ident_free_fn,
1362 static struct stream_filter *ident_filter(const unsigned char *sha1)
1364 struct ident_filter *ident = xmalloc(sizeof(*ident));
1366 xsnprintf(ident->ident, sizeof(ident->ident),
1367 ": %s $", sha1_to_hex(sha1));
1368 strbuf_init(&ident->left, 0);
1369 ident->filter.vtbl = &ident_vtbl;
1370 ident->state = 0;
1371 return (struct stream_filter *)ident;
1375 * Return an appropriately constructed filter for the path, or NULL if
1376 * the contents cannot be filtered without reading the whole thing
1377 * in-core.
1379 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1380 * large binary blob you would want us not to slurp into the memory!
1382 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1384 struct conv_attrs ca;
1385 struct stream_filter *filter = NULL;
1387 convert_attrs(&ca, path);
1388 if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1389 return NULL;
1391 if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1392 return NULL;
1394 if (ca.ident)
1395 filter = ident_filter(sha1);
1397 if (output_eol(ca.crlf_action) == EOL_CRLF)
1398 filter = cascade_filter(filter, lf_to_crlf_filter());
1399 else
1400 filter = cascade_filter(filter, &null_filter_singleton);
1402 return filter;
1405 void free_stream_filter(struct stream_filter *filter)
1407 filter->vtbl->free(filter);
1410 int stream_filter(struct stream_filter *filter,
1411 const char *input, size_t *isize_p,
1412 char *output, size_t *osize_p)
1414 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);