comparison env/lib/python3.9/site-packages/virtualenv/config/convert.py @ 0:4f3585e2f14b draft default tip

"planemo upload commit 60cee0fc7c0cda8592644e1aad72851dec82c959"
author shellac
date Mon, 22 Mar 2021 18:12:50 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4f3585e2f14b
1 from __future__ import absolute_import, unicode_literals
2
3 import logging
4 import os
5
6
7 class TypeData(object):
8 def __init__(self, default_type, as_type):
9 self.default_type = default_type
10 self.as_type = as_type
11
12 def __repr__(self):
13 return "{}(base={}, as={})".format(self.__class__.__name__, self.default_type, self.as_type)
14
15 def convert(self, value):
16 return self.default_type(value)
17
18
19 class BoolType(TypeData):
20 BOOLEAN_STATES = {
21 "1": True,
22 "yes": True,
23 "true": True,
24 "on": True,
25 "0": False,
26 "no": False,
27 "false": False,
28 "off": False,
29 }
30
31 def convert(self, value):
32 if value.lower() not in self.BOOLEAN_STATES:
33 raise ValueError("Not a boolean: %s" % value)
34 return self.BOOLEAN_STATES[value.lower()]
35
36
37 class NoneType(TypeData):
38 def convert(self, value):
39 if not value:
40 return None
41 return str(value)
42
43
44 class ListType(TypeData):
45 def _validate(self):
46 """"""
47
48 def convert(self, value, flatten=True):
49 values = self.split_values(value)
50 result = []
51 for value in values:
52 sub_values = value.split(os.pathsep)
53 result.extend(sub_values)
54 converted = [self.as_type(i) for i in result]
55 return converted
56
57 def split_values(self, value):
58 """Split the provided value into a list.
59
60 First this is done by newlines. If there were no newlines in the text,
61 then we next try to split by comma.
62 """
63 if isinstance(value, (str, bytes)):
64 # Use `splitlines` rather than a custom check for whether there is
65 # more than one line. This ensures that the full `splitlines()`
66 # logic is supported here.
67 values = value.splitlines()
68 if len(values) <= 1:
69 values = value.split(",")
70 values = filter(None, [x.strip() for x in values])
71 else:
72 values = list(value)
73
74 return values
75
76
77 def convert(value, as_type, source):
78 """Convert the value as a given type where the value comes from the given source"""
79 try:
80 return as_type.convert(value)
81 except Exception as exception:
82 logging.warning("%s failed to convert %r as %r because %r", source, value, as_type, exception)
83 raise
84
85
86 _CONVERT = {bool: BoolType, type(None): NoneType, list: ListType}
87
88
89 def get_type(action):
90 default_type = type(action.default)
91 as_type = default_type if action.type is None else action.type
92 return _CONVERT.get(default_type, TypeData)(default_type, as_type)
93
94
95 __all__ = (
96 "convert",
97 "get_type",
98 )