tooaio-scripts 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ .build/
5
+ build/
6
+ dist/
7
+ wheels/
8
+ *.egg-info
9
+
10
+ *.key
11
+ *.csr
12
+ *.crt
13
+ *.pfx
14
+ *.pem
15
+
16
+ .env
17
+
18
+ # Virtual environments
19
+ .venv
20
+
21
+ # Releases
22
+ .release*
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org>
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.5
2
+ Name: tooaio-scripts
3
+ Version: 1.0.0
4
+ Summary: Скрипты общего назначения: сборка документации, сборка приложений
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.12
7
+ Requires-Dist: gitpython>=3.1.62
8
+ Requires-Dist: pydantic-settings>=2.12.1
9
+ Requires-Dist: pydantic>=2.12.5
10
+ Requires-Dist: reportlab>=5.0.0
11
+ Description-Content-Type: text/markdown
12
+
13
+ # Скрипты общего назначения
14
+ * сборка документации;
15
+ * сборка приложений;
@@ -0,0 +1,3 @@
1
+ # Скрипты общего назначения
2
+ * сборка документации;
3
+ * сборка приложений;
@@ -0,0 +1,85 @@
1
+ [project]
2
+ name = "tooaio-scripts"
3
+ version = "1.0.0"
4
+
5
+ description = """
6
+ Скрипты общего назначения: сборка документации, сборка приложений
7
+ """
8
+
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ dependencies = [
12
+ "pydantic>=2.12.5",
13
+ "pydantic-settings>=2.12.1",
14
+ "reportlab>=5.0.0",
15
+ "gitpython>=3.1.62",
16
+ ]
17
+
18
+ [dependency-groups]
19
+ dev = [
20
+ "mypy>=2.3.0",
21
+ "ruff>=0.16.1",
22
+ "types-reportlab>=4.5.1.20260807",
23
+ ]
24
+
25
+ [build-system]
26
+ requires = ["hatchling"]
27
+ build-backend = "hatchling.build"
28
+
29
+ [tool.hatch.build]
30
+ packages = [
31
+ "src",
32
+ ]
33
+
34
+ [[tool.uv.index]]
35
+ url = "https://pypi.org/simple/"
36
+ default = true
37
+
38
+
39
+ [tool.mypy]
40
+ plugins = [
41
+ "pydantic.mypy"
42
+ ]
43
+ follow_imports = "normal"
44
+ warn_redundant_casts = true
45
+ warn_unused_ignores = true
46
+ disallow_any_generics = true
47
+ check_untyped_defs = true
48
+ no_implicit_reexport = true
49
+ disallow_untyped_defs = true
50
+
51
+ [tool.ruff]
52
+ target-version = "py312"
53
+ indent-width = 4
54
+ line-length = 120
55
+ include = [
56
+ "./src/**/*.py",
57
+ ]
58
+
59
+ [tool.ruff.format]
60
+ indent-style = "space"
61
+ quote-style = "double"
62
+ skip-magic-trailing-comma = false
63
+
64
+ [tool.ruff.lint]
65
+ select = [
66
+ "E", # pycodestyle errors
67
+ "W", # pycodestyle warnings
68
+ "F", # pyflakes (unused imports, undefined variables)
69
+ "B", # flake8-bugbear (common design issues)
70
+ "A", # flake8-builtins
71
+ "S", # flagk8-bandit (security testing)
72
+ "BLE", # flake8-blind-except
73
+ "FBT", # flake8-boolean-trap
74
+ "UP", # pyupgrade (modernizes syntax)
75
+ "SIM", # flake8-simplify (cleans up redundant code)
76
+ "ANN", # flake8-annotations
77
+ "EM", # flake8-errmsg
78
+ "DTZ", # flake8-datetimez
79
+ "LOG", # flake8-logging
80
+ "G", # flake8-logging-format
81
+ "ASYNC", # flake8-simplify (cleans up redundant code)
82
+ ]
83
+ ignore = [
84
+ "I", # isort (import sorting)
85
+ ]
File without changes
@@ -0,0 +1,200 @@
1
+ from pathlib import Path
2
+ import subprocess
3
+ import shutil
4
+ from collections.abc import Callable
5
+ from git import Repo, rmtree
6
+
7
+
8
+ class ReleaseSafeUtils:
9
+ def __init__(self, release_path: Path) -> None:
10
+ self.release_path = release_path
11
+
12
+ def __check_path_in_release(self, path: Path) -> None:
13
+ if not path.resolve().is_relative_to(self.release_path.resolve()):
14
+ err_msg = f"Путь {path.resolve()} должен быть внутри папки релиза {self.release_path.resolve()}"
15
+ raise Exception(err_msg)
16
+
17
+ def __check_path_not_nested(self, *, not_nested: Path, in_path: Path) -> None:
18
+ if not_nested.resolve().is_relative_to(in_path.resolve()):
19
+ err_msg = f"Путь {not_nested.resolve()} не должен быть внутри папки {in_path.resolve()}"
20
+ raise Exception(err_msg)
21
+
22
+ def mkdir_safe(self, path: Path, *, exist_ok: bool = False) -> None:
23
+ self.__check_path_in_release(path)
24
+ path.mkdir(exist_ok=exist_ok)
25
+
26
+ def rmtree_safe(self, path: Path) -> None:
27
+ self.__check_path_in_release(path)
28
+ rmtree(path.resolve())
29
+
30
+ def copytree_safe(
31
+ self, src: Path, dst: Path, *, ignore: Callable[[str, list[str]], list[str]] | None = None
32
+ ) -> None:
33
+ self.__check_path_in_release(dst)
34
+ self.__check_path_not_nested(not_nested=dst, in_path=src)
35
+ shutil.copytree(src.resolve(), dst.resolve(), ignore=ignore)
36
+
37
+ def copyfile_safe(self, src: Path, dst: Path) -> None:
38
+ self.__check_path_in_release(dst)
39
+ shutil.copyfile(src.resolve(), dst.resolve())
40
+
41
+ def copy_repo_files_safe(self, src_repo: Repo, dst_path: Path) -> None:
42
+ dst_path = dst_path.resolve()
43
+
44
+ if dst_path.exists():
45
+ self.rmtree_safe(dst_path)
46
+
47
+ dst_repo = src_repo.clone(dst_path)
48
+ self.rmtree_safe(Path(dst_repo.git_dir).resolve())
49
+
50
+ def zip_dir_safe(self, *, src_dir: Path, dst_zipfile: Path) -> None:
51
+ self.__check_path_not_nested(not_nested=dst_zipfile, in_path=src_dir)
52
+ res_file = shutil.make_archive(
53
+ base_name=str(dst_zipfile.with_suffix("")),
54
+ format="zip",
55
+ root_dir=str(src_dir),
56
+ )
57
+ print(res_file)
58
+
59
+
60
+ def build_release_git_remote(
61
+ *,
62
+ dev_repo_path: Path,
63
+ release_repo_url: str,
64
+ release_path: Path,
65
+ release_dev_repo_path: Path,
66
+ func_before_dev_repo_clone: Callable[[ReleaseSafeUtils], None] | None = None,
67
+ func_after_dev_repo_clone: Callable[[ReleaseSafeUtils], None] | None = None,
68
+ ) -> ReleaseSafeUtils:
69
+ """
70
+ Создание релиза в формате удаленного репозитория,
71
+ содержащего копию исходного кода из локального репозитория разработчика
72
+
73
+ Удаленный репозиторий - репозиторий на стороне заказчика (например, в среде разработки заказчика)
74
+
75
+ Удаленный репозиторий отличается от локального тем, что кроме исходного кода содержит файлы,\
76
+ специфичные для среды заказчика. Например: Dockerfile, предопределенные файлы конфигурации
77
+
78
+ Аргументы:
79
+ dev_repo_path - путь к локальному репозиторию разработчика, например "./"
80
+
81
+ release_repo_url - url удаленного репозитория
82
+
83
+ release_path - путь к локальной папке, в которой должен быть создан релиз, например "./.release"
84
+
85
+ release_dev_repo_path - путь к папке, в которой должна находится копия исходного кода
86
+ из локального репозитозитория резработчика, например "./release/src"
87
+ Путь, указанный в release_dev_repo_path, должен находится внути пути release_path
88
+
89
+ func_before_dev_repo_clone - функция, выполняющаяся перед копированием исходного кода
90
+ из локального репозитория разработчика в релиз.
91
+ Используется, например, для автообновления документации перед релизом
92
+
93
+ func_after_dev_repo_clone - функция, выполняющаяся после копирования исходного кода
94
+ из локального репозитория разработчика в релиз.
95
+ Используется, например, для добавления доп. артефактов в релиз
96
+ """
97
+
98
+ dev_repo_path = dev_repo_path.resolve()
99
+ release_path = release_path.resolve()
100
+ release_dev_repo_path = release_dev_repo_path.resolve()
101
+ release_safe_utils = ReleaseSafeUtils(release_path=release_path)
102
+ uv_path = shutil.which("uv")
103
+
104
+ ########################################
105
+ if release_path == dev_repo_path:
106
+ err_msg = f"Путь в аргументе release_path ({release_path}) не может совпадать с dev_repo_path ({dev_repo_path})"
107
+ raise Exception(err_msg)
108
+
109
+ if dev_repo_path.is_relative_to(release_path):
110
+ err_msg = f"Путь в аргументе dev_repo_path ({dev_repo_path}) не может быть внутри release_path ({release_path})"
111
+ raise Exception(err_msg)
112
+
113
+ if not release_path.is_relative_to(dev_repo_path):
114
+ err_msg = f"Путь в аргументе release_path ({release_path}) должен быть внутри dev_repo_path ({dev_repo_path})"
115
+ raise Exception(err_msg)
116
+
117
+ if not release_dev_repo_path.is_relative_to(release_path):
118
+ err_msg = (
119
+ f"Путь в аргументе release_dev_repo_path ({release_dev_repo_path})"
120
+ f" должен быть внутри release_path ({release_path})"
121
+ )
122
+ raise Exception(err_msg)
123
+
124
+ if not uv_path:
125
+ err_msg = "не найден uv"
126
+ raise Exception(err_msg)
127
+
128
+ ########################################
129
+ Path.mkdir(release_path, exist_ok=True)
130
+
131
+ if not (release_path / ".git").exists():
132
+ print(f"Клонирование удаленного репозитория {release_repo_url} (clone --depth=1 --no-single-branch)")
133
+ Repo.clone_from(release_repo_url, release_path, allow_unsafe_protocols=True, depth=1, no_single_branch=True)
134
+
135
+ ########################################
136
+ dev_repo = Repo(dev_repo_path)
137
+ release_repo = Repo(release_path)
138
+
139
+ print(f"Загрузка новых изменений и веток из удаленного репозитория {release_repo_url} (fetch --depth=1 )")
140
+ fetch_res = release_repo.remotes.origin.fetch(allow_unsafe_protocols=True, depth=1)
141
+ for fetch_info in fetch_res:
142
+ print(f"Загружена ветка {fetch_info.ref}")
143
+
144
+ if dev_repo.active_branch.name != release_repo.active_branch.name:
145
+ if dev_repo.active_branch.name in release_repo.remotes.origin.refs:
146
+ print(f"Переключение на удаленную ветку {dev_repo.active_branch}")
147
+ release_repo.git.switch(dev_repo.active_branch.name)
148
+ release_repo.active_branch.set_tracking_branch(
149
+ release_repo.remotes.origin.refs[dev_repo.active_branch.name]
150
+ )
151
+ elif dev_repo.active_branch.name in release_repo.heads:
152
+ print(f"Переключение на локальную ветку {dev_repo.active_branch}")
153
+ release_repo.git.switch(dev_repo.active_branch.name)
154
+ else:
155
+ print(f"Создание новой локальной ветки {dev_repo.active_branch}")
156
+ release_repo.git.switch("-c", dev_repo.active_branch.name)
157
+
158
+ if release_repo.active_branch.is_remote():
159
+ print(f"Вытягивание изменений из удаленного репозитория {release_repo_url} (pull --ff-only --depth 1)")
160
+ pull_res = release_repo.remotes.origin.pull(allow_unsafe_protocols=True, ff_only=True, depth=1)
161
+ for pull_info in pull_res:
162
+ print(f"Обновлена ветка {pull_info.ref}")
163
+
164
+ ########################################
165
+ print(f"Создание requirements.txt в {release_path}")
166
+ print(
167
+ subprocess.check_output( # noqa S603
168
+ [
169
+ uv_path,
170
+ "export",
171
+ "--format",
172
+ "requirements.txt",
173
+ "-o",
174
+ release_path / "requirements.txt",
175
+ "--no-dev",
176
+ "--quiet",
177
+ "--frozen",
178
+ "--no-hashes",
179
+ "--no-editable",
180
+ "--no-emit-local",
181
+ ],
182
+ text=True,
183
+ cwd=Path.cwd(),
184
+ )
185
+ )
186
+
187
+ ########################################
188
+ if func_before_dev_repo_clone:
189
+ func_before_dev_repo_clone(release_safe_utils)
190
+ ########################################
191
+
192
+ print(f"Копирование файлов локального репозитория в {release_dev_repo_path}")
193
+ release_safe_utils.copy_repo_files_safe(dev_repo, release_dev_repo_path)
194
+
195
+ ########################################
196
+ if func_after_dev_repo_clone:
197
+ func_after_dev_repo_clone(release_safe_utils)
198
+ ########################################
199
+
200
+ return release_safe_utils
@@ -0,0 +1,12 @@
1
+ from typing import Any
2
+ from .openapi_to_pdf import build_pdf
3
+ import json
4
+
5
+
6
+ def openapi_to_json(openapi_dict: dict[str, Any], output_path: str) -> None:
7
+ with open(output_path, "w", encoding="utf-8") as f:
8
+ json.dump(openapi_dict, f, ensure_ascii=False, indent=2)
9
+
10
+
11
+ def openapi_to_pdf(openapi_dict: dict[str, Any], output_path: str) -> None:
12
+ build_pdf(openapi_dict, output_path)