forked from code-kern-ai/bricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cms.py
235 lines (212 loc) · 9.39 KB
/
cms.py
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
import os
import json
from dotenv import load_dotenv
import requests
from importlib import import_module
from typing import Dict, Any
from util.paths import (
camel_case_to_snake_case,
snake_case_to_camel_case,
get_module_folders,
)
from util.enums import State
import fire
from wasabi import msg
load_dotenv()
CMS_BASE_URI = os.getenv("CMS_BASE_URI")
CMS_API_KEY = os.getenv("CMS_API_KEY")
class CMS:
"""Synchronizes this repository with a CMS instance.
How to use:
- Get a list of new modules that are not yet in the CMS: `python cms.py ls_private`
- Publish new modules to the CMS: `python cms.py publish`
- Update existing modules in the CMS: `python cms.py update <module_dir>`
"""
def ls_private(self) -> None:
"""Fetches all modules from the CMS and lists all modules that are not yet in the CMS."""
drafts = []
ready_to_publish = []
for moduleType in ["classifiers", "extractors", "generators"]:
for executionType in get_module_folders(moduleType):
relative_dir = os.path.join(
f"{moduleType}", f"{camel_case_to_snake_case(executionType)}"
)
for sub_dir in os.listdir(relative_dir):
config_path = os.path.join(relative_dir, sub_dir, "config.py")
if os.path.exists(config_path):
config_module = import_module(
f"{moduleType}.{camel_case_to_snake_case(executionType)}.{sub_dir}.config"
)
config, state = config_module.get_config()
module_exists, _ = check_module_exists(config)
if not module_exists:
if state == State.PUBLIC.value:
ready_to_publish.append(config["name"])
else:
drafts.append(config["name"])
if len(drafts) > 0:
print("Drafts:")
for draft in drafts:
print(f"\t{draft}")
else:
msg.info("No drafts found")
if len(ready_to_publish) > 0:
print("Ready to publish:")
for module in ready_to_publish:
print(f"\t{module}")
else:
msg.info("No modules ready to publish found")
def publish(self, verbose: bool = True) -> None:
"""Publishes new modules to the CMS, if their state is PUBLIC.
Args:
verbose: If True, prints more information.
"""
for moduleType in ["classifiers", "extractors", "generators"]:
for executionType in get_module_folders(moduleType):
relative_dir = os.path.join(
f"{moduleType}", f"{camel_case_to_snake_case(executionType)}"
)
for sub_dir in os.listdir(relative_dir):
config_path = os.path.join(relative_dir, sub_dir, "config.py")
if os.path.exists(config_path):
print(f"Processing {config_path}")
config_module = import_module(
f"{moduleType}.{camel_case_to_snake_case(executionType)}.{sub_dir}.config"
)
config, state = config_module.get_config()
if state == State.PUBLIC.value:
module_exists, _ = check_module_exists(config)
if not module_exists:
print("Posting module to CMS")
if verbose:
print(json.dumps(config, indent=4))
response = post_module(config)
if response.status_code == 200:
msg.good("Success")
else:
msg.fail("Failed")
print(response.text)
else:
if verbose:
print(f"Module '{config['name']}' already exists")
else:
if verbose:
print(f"Skipping, because state is '{state}'")
if verbose:
print()
def update(self, module_dir: str, verbose: bool = True) -> None:
"""Updates existing modules in the CMS, if their state is PUBLIC.
Args:
module_dir: The directory of the module to update.
verbose: If True, prints more information.
"""
moduleType = module_dir.split("/")[0][:-1] # remove the trailing 's'
executionType = snake_case_to_camel_case(module_dir.split("/")[1])
sub_dir = module_dir.split("/")[2]
config_path = os.path.join(module_dir, "config.py")
if os.path.exists(config_path):
print(f"Processing {config_path}")
config_module = import_module(
f"{moduleType}s.{camel_case_to_snake_case(executionType)}.{sub_dir}.config"
)
config, state = config_module.get_config()
if state == State.PUBLIC.value:
module_exists, module_data = check_module_exists(config)
if module_exists:
module_data = module_data[0]
print("Updating module in CMS")
config["id"] = module_data["id"]
if verbose:
print(json.dumps(config, indent=4))
response = update_module(config)
if response.status_code == 200:
msg.good("Success")
else:
msg.fail("Failed")
print(response.text)
else:
if verbose:
print(f"Module '{config['name']}' does not exist")
else:
if verbose:
print(f"Skipping, because state is '{state}'")
if verbose:
print()
def post_module(config: Dict[str, Any]):
response = requests.post(
f"{CMS_BASE_URI}/api/modules",
json={
"data": {
"name": config["name"],
"description": config["description"],
"moduleType": config["moduleType"],
"executionType": config["executionType"],
"endpoint": config["endpoint"],
"inputExample": config["inputExample"],
"issueId": config["issueId"],
"tablerIcon": config["tablerIcon"],
"registeredDate": config["registeredDate"],
"markdownDescription": config["markdownDescription"],
"sourceCodeRefinery": config["sourceCodeRefinery"],
"sourceCodeCommon": config["sourceCodeCommon"],
"minRefineryVersion": config["minRefineryVersion"],
"gdprCompliant": config["gdprCompliant"],
"kernTokenProxyUsable": config["kernTokenProxyUsable"],
"dockerImage": config["dockerImage"],
"availableFor": config["availableFor"],
"partOfGroup": config["partOfGroup"],
"integratorInputs": config["integratorInputs"],
}
},
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {CMS_API_KEY}",
},
)
return response
def update_module(config: Dict[str, Any]):
response = requests.put(
f"{CMS_BASE_URI}/api/modules/{config['id']}",
json={
"data": {
"name": config["name"],
"description": config["description"],
"moduleType": config["moduleType"],
"executionType": config["executionType"],
"endpoint": config["endpoint"],
"inputExample": config["inputExample"],
"issueId": config["issueId"],
"tablerIcon": config["tablerIcon"],
"registeredDate": config["registeredDate"],
"markdownDescription": config["markdownDescription"],
"sourceCodeRefinery": config["sourceCodeRefinery"],
"sourceCodeCommon": config["sourceCodeCommon"],
"minRefineryVersion": config["minRefineryVersion"], #
"gdprCompliant": config["gdprCompliant"],
"kernTokenProxyUsable": config["kernTokenProxyUsable"],
"dockerImage": config["dockerImage"],
"availableFor": config["availableFor"],
"partOfGroup": config["partOfGroup"],
"integratorInputs": config["integratorInputs"],
}
},
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {CMS_API_KEY}",
},
)
return response
def check_module_exists(config: Dict[str, Any]):
response = requests.get(
f"{CMS_BASE_URI}/api/modules?filters[name][$eq]={config['name']}",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {CMS_API_KEY}",
},
)
if response.status_code == 200:
return response.json()["data"] != [], response.json()["data"]
else:
raise Exception(response.text)
if __name__ == "__main__":
fire.Fire(CMS)