Elffuss BraidHub

kikocis/continue public

80eede9a6f83 · 18.0 KiBRawPermalink
1# coding: utf-8
2
3"""
4 Continue Hub IDE API
5
6 API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
7
8 The version of the OpenAPI document: 1.0.0
9 Generated by OpenAPI Generator (https://openapi-generator.tech)
10
11 Do not edit the class manually.
12""" # noqa: E501
13
14
15import copy
16import http.client as httplib
17import logging
18from logging import FileHandler
19import multiprocessing
20import sys
21from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict, Union
22from typing_extensions import NotRequired, Self
23
24import urllib3
25
26
27JSON_SCHEMA_VALIDATION_KEYWORDS = {
28 'multipleOf', 'maximum', 'exclusiveMaximum',
29 'minimum', 'exclusiveMinimum', 'maxLength',
30 'minLength', 'pattern', 'maxItems', 'minItems'
31}
32
33ServerVariablesT = Dict[str, str]
34
35GenericAuthSetting = TypedDict(
36 "GenericAuthSetting",
37 {
38 "type": str,
39 "in": str,
40 "key": str,
41 "value": str,
42 },
43)
44
45
46OAuth2AuthSetting = TypedDict(
47 "OAuth2AuthSetting",
48 {
49 "type": Literal["oauth2"],
50 "in": Literal["header"],
51 "key": Literal["Authorization"],
52 "value": str,
53 },
54)
55
56
57APIKeyAuthSetting = TypedDict(
58 "APIKeyAuthSetting",
59 {
60 "type": Literal["api_key"],
61 "in": str,
62 "key": str,
63 "value": Optional[str],
64 },
65)
66
67
68BasicAuthSetting = TypedDict(
69 "BasicAuthSetting",
70 {
71 "type": Literal["basic"],
72 "in": Literal["header"],
73 "key": Literal["Authorization"],
74 "value": Optional[str],
75 },
76)
77
78
79BearerFormatAuthSetting = TypedDict(
80 "BearerFormatAuthSetting",
81 {
82 "type": Literal["bearer"],
83 "in": Literal["header"],
84 "format": Literal["JWT"],
85 "key": Literal["Authorization"],
86 "value": str,
87 },
88)
89
90
91BearerAuthSetting = TypedDict(
92 "BearerAuthSetting",
93 {
94 "type": Literal["bearer"],
95 "in": Literal["header"],
96 "key": Literal["Authorization"],
97 "value": str,
98 },
99)
100
101
102HTTPSignatureAuthSetting = TypedDict(
103 "HTTPSignatureAuthSetting",
104 {
105 "type": Literal["http-signature"],
106 "in": Literal["header"],
107 "key": Literal["Authorization"],
108 "value": None,
109 },
110)
111
112
113AuthSettings = TypedDict(
114 "AuthSettings",
115 {
116 "apiKeyAuth": BearerAuthSetting,
117 },
118 total=False,
119)
120
121
122class HostSettingVariable(TypedDict):
123 description: str
124 default_value: str
125 enum_values: List[str]
126
127
128class HostSetting(TypedDict):
129 url: str
130 description: str
131 variables: NotRequired[Dict[str, HostSettingVariable]]
132
133
134class Configuration:
135 """This class contains various settings of the API client.
136
137 :param host: Base url.
138 :param ignore_operation_servers
139 Boolean to ignore operation servers for the API client.
140 Config will use `host` as the base url regardless of the operation servers.
141 :param api_key: Dict to store API key(s).
142 Each entry in the dict specifies an API key.
143 The dict key is the name of the security scheme in the OAS specification.
144 The dict value is the API key secret.
145 :param api_key_prefix: Dict to store API prefix (e.g. Bearer).
146 The dict key is the name of the security scheme in the OAS specification.
147 The dict value is an API key prefix when generating the auth data.
148 :param username: Username for HTTP basic authentication.
149 :param password: Password for HTTP basic authentication.
150 :param access_token: Access token.
151 :param server_index: Index to servers configuration.
152 :param server_variables: Mapping with string values to replace variables in
153 templated server configuration. The validation of enums is performed for
154 variables with defined enum values before.
155 :param server_operation_index: Mapping from operation ID to an index to server
156 configuration.
157 :param server_operation_variables: Mapping from operation ID to a mapping with
158 string values to replace variables in templated server configuration.
159 The validation of enums is performed for variables with defined enum
160 values before.
161 :param ssl_ca_cert: str - the path to a file of concatenated CA certificates
162 in PEM format.
163 :param retries: Number of retries for API requests.
164 :param ca_cert_data: verify the peer using concatenated CA certificate data
165 in PEM (str) or DER (bytes) format.
166
167 :Example:
168 """
169
170 _default: ClassVar[Optional[Self]] = None
171
172 def __init__(
173 self,
174 host: Optional[str]=None,
175 api_key: Optional[Dict[str, str]]=None,
176 api_key_prefix: Optional[Dict[str, str]]=None,
177 username: Optional[str]=None,
178 password: Optional[str]=None,
179 access_token: Optional[str]=None,
180 server_index: Optional[int]=None,
181 server_variables: Optional[ServerVariablesT]=None,
182 server_operation_index: Optional[Dict[int, int]]=None,
183 server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None,
184 ignore_operation_servers: bool=False,
185 ssl_ca_cert: Optional[str]=None,
186 retries: Optional[int] = None,
187 ca_cert_data: Optional[Union[str, bytes]] = None,
188 *,
189 debug: Optional[bool] = None,
190 ) -> None:
191 """Constructor
192 """
193 self._base_path = "https://api.continue.dev" if host is None else host
194 """Default Base url
195 """
196 self.server_index = 0 if server_index is None and host is None else server_index
197 self.server_operation_index = server_operation_index or {}
198 """Default server index
199 """
200 self.server_variables = server_variables or {}
201 self.server_operation_variables = server_operation_variables or {}
202 """Default server variables
203 """
204 self.ignore_operation_servers = ignore_operation_servers
205 """Ignore operation servers
206 """
207 self.temp_folder_path = None
208 """Temp file folder for downloading files
209 """
210 # Authentication Settings
211 self.api_key = {}
212 if api_key:
213 self.api_key = api_key
214 """dict to store API key(s)
215 """
216 self.api_key_prefix = {}
217 if api_key_prefix:
218 self.api_key_prefix = api_key_prefix
219 """dict to store API prefix (e.g. Bearer)
220 """
221 self.refresh_api_key_hook = None
222 """function hook to refresh API key if expired
223 """
224 self.username = username
225 """Username for HTTP basic authentication
226 """
227 self.password = password
228 """Password for HTTP basic authentication
229 """
230 self.access_token = access_token
231 """Access token
232 """
233 self.logger = {}
234 """Logging Settings
235 """
236 self.logger["package_logger"] = logging.getLogger("openapi_client")
237 self.logger["urllib3_logger"] = logging.getLogger("urllib3")
238 self.logger_format = '%(asctime)s %(levelname)s %(message)s'
239 """Log format
240 """
241 self.logger_stream_handler = None
242 """Log stream handler
243 """
244 self.logger_file_handler: Optional[FileHandler] = None
245 """Log file handler
246 """
247 self.logger_file = None
248 """Debug file location
249 """
250 if debug is not None:
251 self.debug = debug
252 else:
253 self.__debug = False
254 """Debug switch
255 """
256
257 self.verify_ssl = True
258 """SSL/TLS verification
259 Set this to false to skip verifying SSL certificate when calling API
260 from https server.
261 """
262 self.ssl_ca_cert = ssl_ca_cert
263 """Set this to customize the certificate file to verify the peer.
264 """
265 self.ca_cert_data = ca_cert_data
266 """Set this to verify the peer using PEM (str) or DER (bytes)
267 certificate data.
268 """
269 self.cert_file = None
270 """client certificate file
271 """
272 self.key_file = None
273 """client key file
274 """
275 self.assert_hostname = None
276 """Set this to True/False to enable/disable SSL hostname verification.
277 """
278 self.tls_server_name = None
279 """SSL/TLS Server Name Indication (SNI)
280 Set this to the SNI value expected by the server.
281 """
282
283 self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
284 """urllib3 connection pool's maximum number of connections saved
285 per pool. urllib3 uses 1 connection as default value, but this is
286 not the best value when you are making a lot of possibly parallel
287 requests to the same host, which is often the case here.
288 cpu_count * 5 is used as default value to increase performance.
289 """
290
291 self.proxy: Optional[str] = None
292 """Proxy URL
293 """
294 self.proxy_headers = None
295 """Proxy headers
296 """
297 self.safe_chars_for_path_param = ''
298 """Safe chars for path_param
299 """
300 self.retries = retries
301 """Adding retries to override urllib3 default value 3
302 """
303 # Enable client side validation
304 self.client_side_validation = True
305
306 self.socket_options = None
307 """Options to pass down to the underlying urllib3 socket
308 """
309
310 self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
311 """datetime format
312 """
313
314 self.date_format = "%Y-%m-%d"
315 """date format
316 """
317
318 def __deepcopy__(self, memo: Dict[int, Any]) -> Self:
319 cls = self.__class__
320 result = cls.__new__(cls)
321 memo[id(self)] = result
322 for k, v in self.__dict__.items():
323 if k not in ('logger', 'logger_file_handler'):
324 setattr(result, k, copy.deepcopy(v, memo))
325 # shallow copy of loggers
326 result.logger = copy.copy(self.logger)
327 # use setters to configure loggers
328 result.logger_file = self.logger_file
329 result.debug = self.debug
330 return result
331
332 def __setattr__(self, name: str, value: Any) -> None:
333 object.__setattr__(self, name, value)
334
335 @classmethod
336 def set_default(cls, default: Optional[Self]) -> None:
337 """Set default instance of configuration.
338
339 It stores default configuration, which can be
340 returned by get_default_copy method.
341
342 :param default: object of Configuration
343 """
344 cls._default = default
345
346 @classmethod
347 def get_default_copy(cls) -> Self:
348 """Deprecated. Please use `get_default` instead.
349
350 Deprecated. Please use `get_default` instead.
351
352 :return: The configuration object.
353 """
354 return cls.get_default()
355
356 @classmethod
357 def get_default(cls) -> Self:
358 """Return the default configuration.
359
360 This method returns newly created, based on default constructor,
361 object of Configuration class or returns a copy of default
362 configuration.
363
364 :return: The configuration object.
365 """
366 if cls._default is None:
367 cls._default = cls()
368 return cls._default
369
370 @property
371 def logger_file(self) -> Optional[str]:
372 """The logger file.
373
374 If the logger_file is None, then add stream handler and remove file
375 handler. Otherwise, add file handler and remove stream handler.
376
377 :param value: The logger_file path.
378 :type: str
379 """
380 return self.__logger_file
381
382 @logger_file.setter
383 def logger_file(self, value: Optional[str]) -> None:
384 """The logger file.
385
386 If the logger_file is None, then add stream handler and remove file
387 handler. Otherwise, add file handler and remove stream handler.
388
389 :param value: The logger_file path.
390 :type: str
391 """
392 self.__logger_file = value
393 if self.__logger_file:
394 # If set logging file,
395 # then add file handler and remove stream handler.
396 self.logger_file_handler = logging.FileHandler(self.__logger_file)
397 self.logger_file_handler.setFormatter(self.logger_formatter)
398 for _, logger in self.logger.items():
399 logger.addHandler(self.logger_file_handler)
400
401 @property
402 def debug(self) -> bool:
403 """Debug status
404
405 :param value: The debug status, True or False.
406 :type: bool
407 """
408 return self.__debug
409
410 @debug.setter
411 def debug(self, value: bool) -> None:
412 """Debug status
413
414 :param value: The debug status, True or False.
415 :type: bool
416 """
417 self.__debug = value
418 if self.__debug:
419 # if debug status is True, turn on debug logging
420 for _, logger in self.logger.items():
421 logger.setLevel(logging.DEBUG)
422 # turn on httplib debug
423 httplib.HTTPConnection.debuglevel = 1
424 else:
425 # if debug status is False, turn off debug logging,
426 # setting log level to default `logging.WARNING`
427 for _, logger in self.logger.items():
428 logger.setLevel(logging.WARNING)
429 # turn off httplib debug
430 httplib.HTTPConnection.debuglevel = 0
431
432 @property
433 def logger_format(self) -> str:
434 """The logger format.
435
436 The logger_formatter will be updated when sets logger_format.
437
438 :param value: The format string.
439 :type: str
440 """
441 return self.__logger_format
442
443 @logger_format.setter
444 def logger_format(self, value: str) -> None:
445 """The logger format.
446
447 The logger_formatter will be updated when sets logger_format.
448
449 :param value: The format string.
450 :type: str
451 """
452 self.__logger_format = value
453 self.logger_formatter = logging.Formatter(self.__logger_format)
454
455 def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]:
456 """Gets API key (with prefix if set).
457
458 :param identifier: The identifier of apiKey.
459 :param alias: The alternative identifier of apiKey.
460 :return: The token for api key authentication.
461 """
462 if self.refresh_api_key_hook is not None:
463 self.refresh_api_key_hook(self)
464 key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
465 if key:
466 prefix = self.api_key_prefix.get(identifier)
467 if prefix:
468 return "%s %s" % (prefix, key)
469 else:
470 return key
471
472 return None
473
474 def get_basic_auth_token(self) -> Optional[str]:
475 """Gets HTTP basic authentication header (string).
476
477 :return: The token for basic HTTP authentication.
478 """
479 username = ""
480 if self.username is not None:
481 username = self.username
482 password = ""
483 if self.password is not None:
484 password = self.password
485 return urllib3.util.make_headers(
486 basic_auth=username + ':' + password
487 ).get('authorization')
488
489 def auth_settings(self)-> AuthSettings:
490 """Gets Auth Settings dict for api client.
491
492 :return: The Auth Settings information dict.
493 """
494 auth: AuthSettings = {}
495 if self.access_token is not None:
496 auth['apiKeyAuth'] = {
497 'type': 'bearer',
498 'in': 'header',
499 'key': 'Authorization',
500 'value': 'Bearer ' + self.access_token
501 }
502 return auth
503
504 def to_debug_report(self) -> str:
505 """Gets the essential information for debugging.
506
507 :return: The report for debugging.
508 """
509 return "Python SDK Debug Report:\n"\
510 "OS: {env}\n"\
511 "Python Version: {pyversion}\n"\
512 "Version of the API: 1.0.0\n"\
513 "SDK Package Version: 1.0.0".\
514 format(env=sys.platform, pyversion=sys.version)
515
516 def get_host_settings(self) -> List[HostSetting]:
517 """Gets an array of host settings
518
519 :return: An array of host settings
520 """
521 return [
522 {
523 'url': "https://api.continue.dev",
524 'description': "Production server",
525 },
526 {
527 'url': "http://localhost:3001",
528 'description': "Local development server",
529 }
530 ]
531
532 def get_host_from_settings(
533 self,
534 index: Optional[int],
535 variables: Optional[ServerVariablesT]=None,
536 servers: Optional[List[HostSetting]]=None,
537 ) -> str:
538 """Gets host URL based on the index and variables
539 :param index: array index of the host settings
540 :param variables: hash of variable and the corresponding value
541 :param servers: an array of host settings or None
542 :return: URL based on host settings
543 """
544 if index is None:
545 return self._base_path
546
547 variables = {} if variables is None else variables
548 servers = self.get_host_settings() if servers is None else servers
549
550 try:
551 server = servers[index]
552 except IndexError:
553 raise ValueError(
554 "Invalid index {0} when selecting the host settings. "
555 "Must be less than {1}".format(index, len(servers)))
556
557 url = server['url']
558
559 # go through variables and replace placeholders
560 for variable_name, variable in server.get('variables', {}).items():
561 used_value = variables.get(
562 variable_name, variable['default_value'])
563
564 if 'enum_values' in variable \
565 and used_value not in variable['enum_values']:
566 raise ValueError(
567 "The variable `{0}` in the host URL has invalid value "
568 "{1}. Must be {2}.".format(
569 variable_name, variables[variable_name],
570 variable['enum_values']))
571
572 url = url.replace("{" + variable_name + "}", used_value)
573
574 return url
575
576 @property
577 def host(self) -> str:
578 """Return generated host."""
579 return self.get_host_from_settings(self.server_index, variables=self.server_variables)
580
581 @host.setter
582 def host(self, value: str) -> None:
583 """Fix base path."""
584 self._base_path = value
585 self.server_index = None