-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconfig.py
More file actions
166 lines (129 loc) · 4.6 KB
/
Copy pathconfig.py
File metadata and controls
166 lines (129 loc) · 4.6 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
"""
config
~~~~~~~~~~
Configuration, caching and profile management for nextcode sdk.
"""
import os
import logging
import yaml
import json
import copy
from pathlib import Path
from typing import Dict, Tuple, Sequence, Optional
from .utils import root_url_from_api_key
from .exceptions import InvalidProfile
root_config_folder = Path(os.path.expanduser("~/.nextcode"))
log = logging.getLogger(__name__)
DEFAULT_PROFILE_NAME = "default"
def load_cache(name: str) -> Optional[Dict]:
if os.environ.get("NEXTCODE_DISABLE_CACHE"):
return None
cache_file = root_config_folder.joinpath("cache", name + ".cache")
try:
contents = json.load(cache_file.open("r"))
log.info("Loaded contents from cache %s", cache_file)
return contents
except FileNotFoundError:
pass
except Exception:
log.exception("Could not load from cache %s" % cache_file)
return None
def save_cache(name: str, contents: Dict) -> None:
if os.environ.get("NEXTCODE_DISABLE_CACHE"):
return
try:
cache_folder = root_config_folder.joinpath("cache")
os.makedirs(cache_folder, exist_ok=True)
cache_file = root_config_folder.joinpath(cache_folder, name + ".cache")
json.dump(contents, cache_file.open("w"))
log.info("Dumped contents into cache %s", cache_file)
except Exception:
log.exception("Could not save cache %s" % cache_file)
class Config:
"""
Borg pattern Config class see:
http://code.activestate.com/recipes/66531-singleton-we-dont-need-no-stinkin-singleton-the-bo/
Example usage:
>>> config = Config({'my': 'config'})
"""
shared_state: Dict = {}
data: Dict = {}
def __init__(self, data: Optional[Dict] = None):
self.__dict__ = self.shared_state
self.set(data)
def dict(self) -> Dict:
return self.data
def set(self, data: Optional[Dict]) -> None:
if data is None:
data = {}
self.data.update(data)
def get(self, key: str, default=None):
return self.data.get(key, default)
def _load_config() -> Dict:
config_file = root_config_folder.joinpath("config.yaml")
try:
content = yaml.safe_load(config_file.open())
if not isinstance(content, dict):
raise Exception("Invalid config")
return content
except Exception:
log.info("Config file not found or invalid")
return {}
def save_config() -> None:
config = Config()
config_file = root_config_folder.joinpath("config.yaml")
log.debug(
"Saving config with %s profiles to %s", len(config.get("profiles")), config_file
)
os.makedirs(root_config_folder, exist_ok=True)
yaml.safe_dump(config.dict(), config_file.open("w"))
def _init_config() -> None:
config = Config()
config.set({"default_profile": None, "profiles": []})
content = _load_config()
if "profiles" not in content:
content["profiles"] = {}
for name, profile in content["profiles"].copy().items():
profile = _prepare_profile(profile)
if not profile:
log.info("Profile '%s' is invalid and will be ignored", name)
del content["profiles"][name]
config.set(content)
def _prepare_profile(profile):
ret = {}
try:
ret["api_key"] = profile.get("api_key")
ret["root_url"] = root_url_from_api_key(ret["api_key"])
if profile.get("root_url"):
ret["root_url"] = profile["root_url"]
except Exception:
return None
return ret
def create_profile(name: str, api_key: str, root_url: Optional[str] = None) -> None:
"""
Create a new profile from api key and persist to disk
:param name: Unique name of the profile for referencing later
:param api_key: API Key from keycloak for the server
:param root_url: root url of the server. If not set, the url from the api key is used
:raises: InvalidProfile
"""
profile = _prepare_profile({"api_key": api_key, "root_url": root_url})
if not profile:
raise InvalidProfile("Profile does not contain a valid api_key")
config = Config()
profiles = config.get("profiles")
profiles[name] = profile
config.set({"profiles": profiles})
save_config()
def set_default_profile(name: str) -> None:
"""
Set a named profile as the default one if no profile is specified or GOR_API_KEY is not set
:param name: Name of the profile
:raises: InvalidProfile
"""
config = Config()
if name not in config.get("profiles"):
raise InvalidProfile("Profile does not exist")
config.set({"default_profile": name})
save_config()
_init_config()