forked from openwallet-foundation/acapy-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repo_manager.py
322 lines (261 loc) · 11.7 KB
/
repo_manager.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
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
import os
import shutil
from copy import deepcopy
from enum import Enum
from typing import Optional
GLOBAL_PLUGIN_DIR = 'plugin_globals'
class PluginInfo:
def __init__(
self,
name: str,
version: Optional[str] = None,
description: Optional[str] = None,
):
self.name = name
self.version = version
self.description = description
class MangagedPoetrySections(str, Enum):
META = '[tool.poetry]'
DEPS = '[tool.poetry.dependencies]'
DEV_DEPS = '[tool.poetry.dev-dependencies]'
INT_DEPS = '[tool.poetry.group.integration.dependencies]'
RUFF = '[tool.ruff]'
RUFF_LINT = '[tool.ruff.lint]'
RUFF_FILES = '[tool.ruff.per-file-ignores]'
PYTEST = '[tool.pytest.ini_options]'
COVERAGE = '[tool.coverage.run]'
COVERAGE_REPORT = '[tool.coverage.report]'
COVERAGE_XML = '[tool.coverage.xml]'
BUILD = '[build-system]'
EXTRAS = '[tool.poetry.extras]'
sections = {
'META': [],
'DEPS': [],
'DEV_DEPS': [],
'INT_DEPS': [],
'RUFF': [],
'RUFF_LINT': [],
'RUFF_FILES': [],
'PYTEST': [],
'COVERAGE': [],
'COVERAGE_REPORT': [],
'COVERAGE_XML': [],
'BUILD': [],
'EXTRAS': []
}
class NEW_PLUGIN_FOLDERS(Enum):
DOCKER = 'docker'
INTEGRATION = 'integration'
DEVCONTAINER = '.devcontainer'
VSCODE = '.vscode'
class NEW_PLUGIN_FILES(Enum):
PYPROJECT = 'pyproject.toml'
README = 'README.md'
DEFINITION = 'definition.py'
class TAGGED_FILES(Enum):
DOCKER_DEFAULT = 'docker/default.yml'
DOCKERFILE = 'docker/Dockerfile'
DOCKER_INTEGRATION = 'docker/integration.yml'
PYPROJECT = 'pyproject.toml'
PYPROJECT_INTEGRATION = 'integration/pyproject.toml'
DEVCONTAINER = '.devcontainer/devcontainer.json'
VSCODE = '.vscode/launch.json'
def replace_plugin_tag(path: str, info: PluginInfo):
with open(path, 'r') as file:
filedata = file.read()
filedata = filedata.replace(GLOBAL_PLUGIN_DIR, info.name)
with open(path, 'w') as file:
file.write(filedata)
def copy_all_common_files_for_new_plugin(info: PluginInfo) -> None:
for folder in list(NEW_PLUGIN_FOLDERS):
shutil.copytree(
f'./{GLOBAL_PLUGIN_DIR}/{folder.value}',
f'./{info.name}/{folder.value}'
)
for file in list(NEW_PLUGIN_FILES):
file_location = f'./{info.name}/{file.value}' if not file == NEW_PLUGIN_FILES.DEFINITION else f'./{info.name}/{info.name}/{file.value}'
shutil.copyfile(
f'./{GLOBAL_PLUGIN_DIR}/{file.value}',
file_location
)
for file in list(TAGGED_FILES):
replace_plugin_tag(
f'./{info.name}/{file.value}', info)
def combine_dependenices(plugin_dependencies, global_dependencies) -> None:
"""Add the plugin dependencies to the global dependencies if they are plugin specific."""
for p_dep in plugin_dependencies:
if (p_dep.split('=')[0].strip() not in [g_dep.split('=')[0].strip() for g_dep in global_dependencies]):
global_dependencies.append(p_dep)
def is_end_of_section(line: str, current_section: str) -> bool:
str_line = line.strip()
return str_line in [section.value for section in MangagedPoetrySections] and str_line != current_section
def get_section(i: int, filedata: list, arr: list, current_section: str) -> int:
"""Put the section into the array and return the number of lines in the section."""
j = i
while j < len(filedata) and not is_end_of_section(filedata[j], current_section):
arr.append(filedata[j])
j += 1
# Remove the last empty line
if arr[-1] == '':
arr.pop()
return j - i
def extract_common_sections(filedata: str, sections: dict) -> None:
"""Go through the file by line and extract the section into the sections object."""
filedata = filedata.split('\n')
for i in range(len(filedata)):
line = filedata[i]
for section in MangagedPoetrySections:
if line.startswith(section.value):
i += get_section(i + 1, filedata,
sections[section.name], section.value)
def get_section_output(i: int, content: list, output: list, section: list, current_section: str) -> int:
"""
Get a config section based off of an empty line of length of file.
Args:
i: The current line number
content: The file content
output: The output list
section: The section to process
Returns: The number of lines in the section
"""
j = i
output.append(content[j])
while (j < len(content) - 1 and not is_end_of_section(content[j], current_section)):
j += 1
while (len(section) > 0):
output.append(section.pop(0) + '\n')
output.append('\n')
return j - i
def get_and_combine_main_poetry_sections(name: str) -> (dict, dict):
"""Get the global main sections and combine them with the plugin specific sections."""
global_sections = deepcopy(sections)
plugin_sections = deepcopy(sections)
with open(f'./{GLOBAL_PLUGIN_DIR}/{TAGGED_FILES.PYPROJECT.value}', 'r') as file:
filedata = file.read()
extract_common_sections(filedata, global_sections)
with open(f'./{name}/{TAGGED_FILES.PYPROJECT.value}', 'r') as file:
filedata = file.read()
extract_common_sections(filedata, plugin_sections)
combine_dependenices(plugin_sections['DEPS'], global_sections['DEPS'])
combine_dependenices(plugin_sections['DEV_DEPS'],
global_sections['DEV_DEPS'])
combine_dependenices(plugin_sections['INT_DEPS'],
global_sections['INT_DEPS'])
return global_sections, plugin_sections
def process_main_config_sections(name: str, plugin_sections: dict, global_sections: dict) -> None:
"""Process the main config sections and write them to the plugins pyproject.toml file."""
with open(f'./{GLOBAL_PLUGIN_DIR}/{TAGGED_FILES.PYPROJECT.value}', 'r') as in_file:
content = in_file.readlines()
sections = [section.value for section in MangagedPoetrySections]
output = []
with open(f'./{name}/{TAGGED_FILES.PYPROJECT.value}', 'w') as out_file:
i = 0
while i < len(content):
if content[i].startswith(MangagedPoetrySections.META.value):
output.append(MangagedPoetrySections.META.value + '\n')
[output.append(line + '\n')
for line in plugin_sections['META']]
output.append('\n')
i += 1
for section in sections:
if (content[i].startswith(section)):
i += get_section_output(i, content,
output, global_sections[MangagedPoetrySections(content[i].strip()).name], content[i])
else:
i += 1
out_file.writelines(output)
replace_plugin_tag(
f'./{name}/{TAGGED_FILES.PYPROJECT.value}', PluginInfo(name))
def get_and_combine_integration_poetry_sections(name: str) -> (dict, dict):
"""Get the global integration sections and combine them with the plugin specific sections."""
global_sections = deepcopy(sections)
plugin_sections = deepcopy(sections)
with open(f'./{GLOBAL_PLUGIN_DIR}/{TAGGED_FILES.PYPROJECT_INTEGRATION.value}', 'r') as file:
filedata = file.read()
extract_common_sections(filedata, global_sections)
with open(f'./{name}/{TAGGED_FILES.PYPROJECT_INTEGRATION.value}', 'r') as file:
filedata = file.read()
extract_common_sections(filedata, plugin_sections)
combine_dependenices(plugin_sections['DEPS'], global_sections['DEPS'])
combine_dependenices(
plugin_sections['DEV_DEPS'], global_sections['DEV_DEPS'])
return global_sections, plugin_sections
def process_integration_config_sections(name: str, plugin_sections: dict, global_sections: dict) -> None:
"""Process the integration test config sections and write them to the plugins intergqtion/pyproject.toml file."""
with open(f'./{GLOBAL_PLUGIN_DIR}/{TAGGED_FILES.PYPROJECT_INTEGRATION.value}', 'r') as in_file:
content = in_file.readlines()
sections = [section.value for section in MangagedPoetrySections]
output = []
with open(f'./{name}/{TAGGED_FILES.PYPROJECT_INTEGRATION.value}', 'w') as out_file:
i = 0
while i < len(content):
if content[i].startswith(MangagedPoetrySections.META.value):
output.append(MangagedPoetrySections.META.value + '\n')
[output.append(line + '\n')
for line in plugin_sections['META']]
i += 1
output.append('\n')
for section in sections:
if (content[i].startswith(section)):
i += get_section_output(i, content,
output, global_sections[MangagedPoetrySections(content[i].strip()).name], content[i])
else:
i += 1
out_file.writelines(output)
def replace_global_sections(name: str) -> None:
"""
Combine the global sections with the plugin specific sections and write them to the plugins pyproject.toml file
with the global dependencies overriding the plugin dependencies.
"""
global_sections, plugin_sections = get_and_combine_main_poetry_sections(
name)
process_main_config_sections(name, plugin_sections, global_sections)
global_sections, plugin_sections = get_and_combine_integration_poetry_sections(
name)
process_integration_config_sections(name, plugin_sections, global_sections)
def is_plugin_directory(plugin_name: str) -> bool:
# If there is a drirectory which is not a plugin it should be ignored here
return os.path.isdir(plugin_name) and plugin_name != GLOBAL_PLUGIN_DIR and not plugin_name.startswith('.')
def main():
print("Checking poetry is available...")
response = os.system('which poetry')
if response == "":
print("Poetry is not available. Please install poetry.")
exit(1)
options = """
What would you like to do?
(1) Create a new plugin
(2) Update all plugin common poetry sections
(3) Exit \n\nInput: """
selection = input(options)
# Create a new plugin
if selection == "1":
msg = """Creating a new plugin: This will create a blank plugin with all the common files and folders needed to get started developing and testing."""
print(msg)
name = input(
"Enter the plugin name (recommended to use snake_case): ")
if name == "":
print("You must enter a plugin name")
exit(1)
version = str(
input("Enter the plugin version (default is 0.1.0): ") or "0.1.0")
description = input(
"Enter the plugin description (default is ''): ") or ""
plugin_info = PluginInfo(name, version, description)
os.makedirs(f'./{name}/{name}/v1_0')
copy_all_common_files_for_new_plugin(plugin_info)
os.system(f'cd {name} && poetry install --no-root')
# Update common poetry sections
elif selection == "2":
msg = """Updating all plugin common poetry sections: This will take the global sections from the plugin_globals and combine them with the plugin specific sections, and install and update the lock file \n"""
print(msg)
for plugin_name in os.listdir('./'):
if is_plugin_directory(plugin_name):
print(f'Updating common poetry sections in {plugin_name}\n')
replace_global_sections(plugin_name)
os.system(
f'cd {plugin_name} && rm poetry.lock && poetry install')
os.system(
f'cd {plugin_name}/integration && rm poetry.lock && poetry install')
if __name__ == "__main__":
main()