-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathconfig.py
More file actions
430 lines (342 loc) · 12.8 KB
/
config.py
File metadata and controls
430 lines (342 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
"""CLI - Configuration."""
import os
import re
import threading
import click
from click_configfile import ConfigFileReader, Param, SectionSchema, matches_section
from ..core.utils import get_data_path, read_file
from . import utils, validators
OPTIONS = threading.local()
class ConfigParam(Param):
# For compatibility with click>=7.0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ctx = None
def parse(self, text):
if text:
text = text.strip()
if self.type.name == "boolean":
if not text:
return None
return super().parse(text)
def get_error_hint(self, ctx):
if self.ctx:
files = []
for path in self.ctx.config_searchpath:
for filename in self.ctx.config_files:
files.append(os.path.join(path, filename))
files = " or ".join(files)
msg = f"{self.name} in {files}"
else:
msg = f"{self.name} in a config file"
return msg
def get_default_config_path():
"""Get the default path to cloudsmith config files."""
return click.get_app_dir("cloudsmith") # only returns a single path
_CFG_SEARCH_PATHS = (
".",
get_default_config_path(),
os.path.expanduser("~/.cloudsmith"),
)
class ConfigSchema:
"""Schema for standard configuration."""
@matches_section("default")
class Default(SectionSchema):
"""Default configuration schema."""
api_headers = ConfigParam(name="api_headers", type=str)
api_host = ConfigParam(name="api_host", type=str)
api_proxy = ConfigParam(name="api_proxy", type=str)
api_ssl_verify = ConfigParam(name="api_ssl_verify", type=bool, default=True)
api_user_agent = ConfigParam(name="api_user_agent", type=str)
@matches_section("profile:*")
class Profile(Default):
"""Profile-specific configuration schema."""
class ConfigReader(ConfigFileReader):
"""Reader for standard configuration."""
config_files = ["config.ini"]
config_name = "standard"
config_searchpath = list(_CFG_SEARCH_PATHS)
config_section_schemas = [ConfigSchema.Default, ConfigSchema.Profile]
@classmethod
def select_config_schema_for(cls, section_name):
section_schema = super().select_config_schema_for(section_name)
for v in section_schema.__dict__.values():
if isinstance(v, ConfigParam):
v.ctx = cls
return section_schema
@classmethod
def get_storage_name_for(cls, section_name):
"""Get storage name for a configuration section."""
if not section_name or section_name == "default":
return "default"
return section_name
@classmethod
def get_default_filepath(cls):
"""Get the default filepath for the configuration file."""
if not cls.config_files:
return None
if not cls.config_searchpath:
return None
filename = cls.config_files[0]
filepath = cls.config_searchpath[0]
return os.path.join(filepath, filename)
@classmethod
def create_default_file(cls, data=None, mode=None):
"""Create a config file and override data if specified."""
filepath = cls.get_default_filepath()
if not filepath:
return False
filename = os.path.basename(filepath)
config = read_file(get_data_path(), filename)
# Find and replace data in default config
data = data or {}
for k, v in data.items():
v = v or ""
config = re.sub(
rf"^({k})\s*=\s*$",
f"{k} = {v}",
config,
flags=re.MULTILINE,
)
dirpath = os.path.dirname(filepath)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
with click.open_file(filepath, "w+") as f:
f.write(config)
if mode is not None:
os.chmod(filepath, mode)
return True
@classmethod
def has_default_file(cls):
"""Check if a configuration file exists."""
for filename in cls.config_files:
for searchpath in cls.config_searchpath:
path = os.path.join(searchpath, filename)
if os.path.exists(path):
return True
return False
@classmethod
def load_config(cls, opts, path=None, profile=None):
"""Load a configuration file into an options object."""
if path and os.path.exists(path):
if os.path.isdir(path):
cls.config_searchpath.insert(0, path)
else:
cls.config_files.insert(0, path)
config = cls.read_config()
values = config.get("default", {})
cls._load_values_into_opts(opts, values)
if profile and profile != "default":
values = config.get("profile:%s" % profile, {})
cls._load_values_into_opts(opts, values)
return values
@staticmethod
def _load_values_into_opts(opts, values):
for k, v in values.items():
if v is None:
continue
if isinstance(v, str):
if v.startswith('"') or v.startswith("'"):
v = v[1:]
if v.endswith('"') or v.endswith("'"):
v = v[:-1]
if not v:
continue
else:
if v is None:
continue
setattr(opts, k, v)
class CredentialsSchema:
"""Schema for credentials configuration."""
@matches_section("default")
class Default(SectionSchema):
"""Default configuration schema."""
api_key = ConfigParam(name="api_key", type=str)
@matches_section("profile:*")
class Profile(Default):
"""Profile-specific configuration schema."""
class CredentialsReader(ConfigReader):
"""Reader for credentials configuration."""
config_files = ["credentials.ini"]
config_name = "credentials"
config_searchpath = list(_CFG_SEARCH_PATHS)
config_section_schemas = [CredentialsSchema.Default, CredentialsSchema.Profile]
class Options:
"""Options object that holds config for the application."""
def __init__(self, *args, **kwargs):
"""Initialise a new Options object."""
super().__init__(*args, **kwargs)
self.opts = {}
for k, v in kwargs.items():
setattr(self, k, v)
@staticmethod
def get_config_reader():
"""Get the non-credentials config reader class."""
return ConfigReader
@staticmethod
def get_creds_reader():
"""Get the credentials config reader class."""
return CredentialsReader
def load_config_file(self, path, profile=None):
"""Load the standard config file."""
config_cls = self.get_config_reader()
return config_cls.load_config(self, path, profile=profile)
def load_creds_file(self, path, profile=None):
"""Load the credentials config file."""
config_cls = self.get_creds_reader()
return config_cls.load_config(self, path, profile=profile)
@property
def api_config(self):
"""Get value for API config dictionary."""
return self._get_option("api_config")
@api_config.setter
def api_config(self, value):
"""Set value for API config dictionary."""
self._set_option("api_config", value)
@property
def api_headers(self):
"""Get value for API headers."""
return self._get_option("api_headers")
@api_headers.setter
def api_headers(self, value):
"""Set value for API headers."""
value = validators.validate_api_headers("api_headers", value)
self._set_option("api_headers", value)
@property
def api_host(self):
"""Get value for API host."""
return self._get_option("api_host")
@api_host.setter
def api_host(self, value):
"""Set value for API host."""
self._set_option("api_host", value)
@property
def api_key(self):
"""Get value for API key."""
return self._get_option("api_key")
@api_key.setter
def api_key(self, value):
"""Set value for API key."""
self._set_option("api_key", value)
@property
def api_proxy(self):
"""Get value for API proxy."""
return self._get_option("api_proxy")
@api_proxy.setter
def api_proxy(self, value):
"""Set value for API proxy."""
self._set_option("api_proxy", value)
@property
def api_ssl_verify(self):
"""Get value for API SSL verify."""
return self._get_option("api_ssl_verify", default=True)
@api_ssl_verify.setter
def api_ssl_verify(self, value):
"""Set value for API SSL verify."""
self._set_option("api_ssl_verify", value, allow_clear=False)
@property
def api_user_agent(self):
"""Get value for API user agent."""
return utils.make_user_agent(prefix=self._get_option("api_user_agent"))
@api_user_agent.setter
def api_user_agent(self, value):
"""Set value for API user agent."""
self._set_option("api_user_agent", value)
@property
def rate_limit(self):
"""Get value for rate limiting."""
return self._get_option("rate_limit", default=True)
@rate_limit.setter
def rate_limit(self, value):
"""Set value for rate limiting."""
self._set_option("rate_limit", value)
@property
def rate_limit_warning(self):
"""Get value for rate limiting warning (in seconds)."""
return self._get_option("rate_limit_warning", default=10)
@rate_limit_warning.setter
def rate_limit_warning(self, value):
"""Set value for rate limiting warning (in seconds)."""
self._set_option("rate_limit_warning", value)
@property
def always_show_rate_limit(self):
"""Get value for rate limiting warning (in seconds)."""
return self._get_option("always_show_rate_limit", default=False)
@always_show_rate_limit.setter
def always_show_rate_limit(self, value):
"""Set value for rate limiting warning (in seconds)."""
self._set_option("always_show_rate_limit", value)
@property
def debug(self):
"""Get value for debug flag."""
return self._get_option("debug", default=False)
@debug.setter
def debug(self, value):
"""Set value for debug flag."""
self._set_option("debug", bool(value))
@property
def output(self):
"""Get value for output format."""
return self._get_option("output")
@output.setter
def output(self, value):
"""Set value for output format."""
self._set_option("output", value)
@property
def verbose(self):
"""Get value for verbose flag."""
return self._get_option("verbose", default=False)
@verbose.setter
def verbose(self, value):
"""Set value for verbose flag."""
self._set_option("verbose", bool(value))
@property
def error_retry_max(self):
"""Get value for error_retry_max."""
return self._get_option("error_retry_max", default=5)
@error_retry_max.setter
def error_retry_max(self, value):
"""Set value for error_retry_max."""
self._set_option("error_retry_max", int(value))
@property
def error_retry_backoff(self):
"""Get value for error_retry_backoff."""
return self._get_option("error_retry_backoff", default=0.23)
@error_retry_backoff.setter
def error_retry_backoff(self, value):
"""Set value for error_retry_backoff."""
self._set_option("error_retry_backoff", float(value))
@property
def error_retry_codes(self):
"""Get value for error_retry_codes."""
return self._get_option("error_retry_codes", default=[500, 502, 503, 504])
@error_retry_codes.setter
def error_retry_codes(self, value):
"""Set value for error_retry_codes."""
if isinstance(value, str):
value = [int(x) for x in value.split(",")]
self._set_option("error_retry_codes", value)
def _get_option(self, name, default=None):
"""Get value for an option."""
value = self.opts.get(name)
if value is None:
return default
return value
def _set_option(self, name, value, allow_clear=False):
"""Set value for an option."""
if not allow_clear:
# Prevent clears if value was set
try:
current_value = self._get_option(name)
if value is None and current_value is not None:
return
except AttributeError:
pass
self.opts[name] = value
def get_or_create_options(ctx):
"""Get or create the options object."""
try:
return OPTIONS.value
except AttributeError:
OPTIONS.value = ctx.ensure_object(Options)
return OPTIONS.value