|
41 | 41 | ConfigPaths = Union[None, FilePath, Sequence[FilePath]]
|
42 | 42 |
|
43 | 43 |
|
| 44 | +_token_pattern = re.compile(r'%(.)') |
| 45 | +_env_pattern = re.compile(r'\${(.*)}') |
| 46 | + |
| 47 | + |
44 | 48 | def _exec(cmd: str) -> bool:
|
45 | 49 | """Execute a command and return if exit status is 0"""
|
46 | 50 |
|
@@ -93,36 +97,38 @@ def _set_tokens(self) -> None:
|
93 | 97 |
|
94 | 98 | raise NotImplementedError
|
95 | 99 |
|
96 |
| - def _expand_val(self, value: str) -> str: |
97 |
| - """Perform percent token expansion on a string""" |
| 100 | + def _expand_token(self, match): |
| 101 | + """Expand a percent token reference""" |
| 102 | + |
| 103 | + try: |
| 104 | + token = match.group(1) |
| 105 | + return self._tokens[token] |
| 106 | + except KeyError: |
| 107 | + if token == 'd': |
| 108 | + raise ConfigParseError('Home directory is ' |
| 109 | + 'not available') from None |
| 110 | + elif token == 'i': |
| 111 | + raise ConfigParseError('User id not available') from None |
| 112 | + else: |
| 113 | + raise ConfigParseError('Invalid token expansion: ' + |
| 114 | + token) from None |
98 | 115 |
|
99 |
| - last_idx = 0 |
100 |
| - result: List[str] = [] |
| 116 | + @staticmethod |
| 117 | + def _expand_env(match): |
| 118 | + """Expand an environment variable reference""" |
101 | 119 |
|
102 |
| - for match in re.finditer(r'%', value): |
103 |
| - idx = match.start() |
| 120 | + try: |
| 121 | + var = match.group(1) |
| 122 | + return os.environ[var] |
| 123 | + except KeyError: |
| 124 | + raise ConfigParseError('Invalid environment expansion: ' + |
| 125 | + var) from None |
104 | 126 |
|
105 |
| - if idx < last_idx: |
106 |
| - continue |
| 127 | + def _expand_val(self, value: str) -> str: |
| 128 | + """Perform percent token and environment expansion on a string""" |
107 | 129 |
|
108 |
| - try: |
109 |
| - token = value[idx+1] |
110 |
| - result.extend([value[last_idx:idx], self._tokens[token]]) |
111 |
| - last_idx = idx + 2 |
112 |
| - except IndexError: |
113 |
| - raise ConfigParseError('Invalid token substitution') from None |
114 |
| - except KeyError: |
115 |
| - if token == 'd': |
116 |
| - raise ConfigParseError('Home directory is ' |
117 |
| - 'not available') from None |
118 |
| - elif token == 'i': |
119 |
| - raise ConfigParseError('User id not available') from None |
120 |
| - else: |
121 |
| - raise ConfigParseError('Invalid token substitution: ' + |
122 |
| - value[idx+1]) from None |
123 |
| - |
124 |
| - result.append(value[last_idx:]) |
125 |
| - return ''.join(result) |
| 130 | + return _env_pattern.sub(self._expand_env, |
| 131 | + _token_pattern.sub(self._expand_token, value)) |
126 | 132 |
|
127 | 133 | def _include(self, option: str, args: List[str]) -> None:
|
128 | 134 | """Read config from a list of other config files"""
|
|
0 commit comments