argo-tugboat 0.1.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.
Files changed (30) hide show
  1. argo_tugboat-0.1.0/PKG-INFO +31 -0
  2. argo_tugboat-0.1.0/README.md +10 -0
  3. argo_tugboat-0.1.0/pyproject.toml +70 -0
  4. argo_tugboat-0.1.0/tugboat/__init__.py +3 -0
  5. argo_tugboat-0.1.0/tugboat/analyze.py +310 -0
  6. argo_tugboat-0.1.0/tugboat/analyzers/__init__.py +0 -0
  7. argo_tugboat-0.1.0/tugboat/analyzers/constraints.py +104 -0
  8. argo_tugboat-0.1.0/tugboat/analyzers/kubernetes.py +59 -0
  9. argo_tugboat-0.1.0/tugboat/analyzers/pydantic.py +199 -0
  10. argo_tugboat-0.1.0/tugboat/analyzers/utils.py +60 -0
  11. argo_tugboat-0.1.0/tugboat/analyzers/workflow.py +275 -0
  12. argo_tugboat-0.1.0/tugboat/analyzers/workflow_template.py +77 -0
  13. argo_tugboat-0.1.0/tugboat/console/__init__.py +1 -0
  14. argo_tugboat-0.1.0/tugboat/console/main.py +223 -0
  15. argo_tugboat-0.1.0/tugboat/console/outputs/__init__.py +0 -0
  16. argo_tugboat-0.1.0/tugboat/console/outputs/console.py +126 -0
  17. argo_tugboat-0.1.0/tugboat/console/outputs/junit.py +110 -0
  18. argo_tugboat-0.1.0/tugboat/console/utils.py +10 -0
  19. argo_tugboat-0.1.0/tugboat/core.py +79 -0
  20. argo_tugboat-0.1.0/tugboat/hookspecs/__init__.py +0 -0
  21. argo_tugboat-0.1.0/tugboat/hookspecs/core.py +49 -0
  22. argo_tugboat-0.1.0/tugboat/hookspecs/workflow.py +69 -0
  23. argo_tugboat-0.1.0/tugboat/schemas/__init__.py +19 -0
  24. argo_tugboat-0.1.0/tugboat/schemas/arguments/__init__.py +14 -0
  25. argo_tugboat-0.1.0/tugboat/schemas/arguments/artifact.py +219 -0
  26. argo_tugboat-0.1.0/tugboat/schemas/arguments/parameter.py +35 -0
  27. argo_tugboat-0.1.0/tugboat/schemas/basic.py +37 -0
  28. argo_tugboat-0.1.0/tugboat/schemas/manifest.py +27 -0
  29. argo_tugboat-0.1.0/tugboat/schemas/template.py +85 -0
  30. argo_tugboat-0.1.0/tugboat/schemas/workflow.py +36 -0
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.1
2
+ Name: argo-tugboat
3
+ Version: 0.1.0
4
+ Summary: Streamline your Argo Workflows with precision and confidence
5
+ License: Apache-2.0
6
+ Author: Tzu-Ting
7
+ Author-email: tzingshih@gmail.com
8
+ Requires-Python: >=3.12,<4.0
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Requires-Dist: cloup (>=3.0.5,<4.0.0)
14
+ Requires-Dist: colorlog (>=6.9.0,<7.0.0)
15
+ Requires-Dist: pluggy (>=1.5.0,<2.0.0)
16
+ Requires-Dist: pydantic (>=2.9.2,<3.0.0)
17
+ Requires-Dist: rapidfuzz (>=3.10.1,<4.0.0)
18
+ Requires-Dist: ruamel-yaml (>=0.18.6,<0.19.0)
19
+ Description-Content-Type: text/markdown
20
+
21
+ > [!CAUTION]
22
+ > This project is still in early development stage. Anything can change at any time.
23
+
24
+ # Tugboat
25
+
26
+ > The tugboat guides the ship to flight, from harbor's hold to ocean's light.
27
+
28
+ Streamline your [Argo Workflows] with precision and confidence.
29
+
30
+ [Argo Workflows]: https://argoproj.github.io/workflows/
31
+
@@ -0,0 +1,10 @@
1
+ > [!CAUTION]
2
+ > This project is still in early development stage. Anything can change at any time.
3
+
4
+ # Tugboat
5
+
6
+ > The tugboat guides the ship to flight, from harbor's hold to ocean's light.
7
+
8
+ Streamline your [Argo Workflows] with precision and confidence.
9
+
10
+ [Argo Workflows]: https://argoproj.github.io/workflows/
@@ -0,0 +1,70 @@
1
+ [tool.poetry]
2
+ name = "argo-tugboat"
3
+ version = "0.1.0"
4
+ description = "Streamline your Argo Workflows with precision and confidence"
5
+ authors = ["Tzu-Ting <tzingshih@gmail.com>"]
6
+ license = "Apache-2.0"
7
+ readme = "README.md"
8
+ packages = [{ include = "tugboat" }]
9
+
10
+ [tool.poetry.dependencies]
11
+ python = "^3.12"
12
+ cloup = "^3.0.5"
13
+ colorlog = "^6.9.0"
14
+ pluggy = "^1.5.0"
15
+ pydantic = "^2.9.2"
16
+ rapidfuzz = "^3.10.1"
17
+ ruamel-yaml = "^0.18.6"
18
+
19
+ [tool.poetry.group.dev.dependencies]
20
+ dirty-equals = "^0.8.0"
21
+ pyright = "^1.1.386"
22
+ pytest = "^8.3.3"
23
+ pytest-cov = "^5.0.0"
24
+ ruff = "^0.7.1"
25
+ shibuya = ">=2024.10.15"
26
+ sphinx = "^8.1.3"
27
+
28
+ [tool.poetry.scripts]
29
+ tugboat = "tugboat.console:main"
30
+
31
+ [build-system]
32
+ requires = ["poetry-core"]
33
+ build-backend = "poetry.core.masonry.api"
34
+
35
+ [tool.coverage.report]
36
+ exclude_lines = ["pragma: no cover", "if typing.TYPE_CHECKING"]
37
+
38
+ [tool.isort]
39
+ profile = "black"
40
+
41
+ [tool.pytest.ini_options]
42
+ addopts = "--cov=tugboat --cov-report xml --cov-report term-missing"
43
+
44
+ [tool.ruff]
45
+ target-version = "py312"
46
+
47
+ [tool.ruff.lint.extend-per-file-ignores]
48
+ "tugboat/schemas/**" = ["TCH001"]
49
+
50
+ [tool.ruff.lint]
51
+ extend-select = [
52
+ "B", # flake8-bugbear
53
+ "C4", # flake8-comprehensions
54
+ "C90", # mccabe
55
+ "ERA", # flake8-eradicate/eradicate
56
+ "I", # isort
57
+ "PGH", # pygrep
58
+ "PIE", # flake8-pie
59
+ "PT", # flake8-pytest-style
60
+ "RUF", # ruff checks
61
+ "TCH", # flake8-type-checking
62
+ "TID", # flake8-tidy-imports
63
+ "UP", # pyupgrade
64
+ ]
65
+
66
+ [tool.ruff.lint.mccabe]
67
+ max-complexity = 12
68
+
69
+ [tool.pyright]
70
+ include = ["tugboat"]
@@ -0,0 +1,3 @@
1
+ __all__ = ["hookimpl"]
2
+
3
+ from tugboat.core import hookimpl
@@ -0,0 +1,310 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import textwrap
5
+ import typing
6
+ from typing import Any, Literal, TypedDict
7
+
8
+ import ruamel.yaml
9
+ from pydantic import ValidationError
10
+ from ruamel.yaml.comments import CommentedMap
11
+ from ruamel.yaml.error import MarkedYAMLError
12
+
13
+ from tugboat.analyzers.pydantic import translate_pydantic_error
14
+ from tugboat.core import get_plugin_manager
15
+ from tugboat.schemas import Manifest
16
+
17
+ if typing.TYPE_CHECKING:
18
+ from collections.abc import Iterable, Sequence
19
+
20
+ from ruamel.yaml.comments import CommentedBase
21
+
22
+ from tugboat.core import Diagnostic
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ _yaml_parser = None
27
+
28
+
29
+ class ExtendedDiagnostic(TypedDict):
30
+ """
31
+ A diagnostic reported by the checker.
32
+
33
+ This extends the :py:class:`Diagnostic` type by adding extra fields, with
34
+ all members normalized.
35
+ """
36
+
37
+ line: int
38
+ """
39
+ Line number of the diagnostic in the source file.
40
+ Note that the line number is cumulative across all documents in the YAML file.
41
+ """
42
+
43
+ column: int
44
+ """
45
+ Column number of the diagnostic in the source file.
46
+ """
47
+
48
+ type: Literal["error", "failure", "skipped"]
49
+ """The type of diagnostic."""
50
+
51
+ code: str
52
+ """The code of the diagnostic."""
53
+
54
+ manifest: str | None
55
+ """The manifest name that caused the diagnostic."""
56
+
57
+ loc: tuple[str | int, ...]
58
+ """The location of the diagnostic in the manifest."""
59
+
60
+ summary: str
61
+ """The summary of the diagnostic."""
62
+
63
+ msg: str
64
+ """The detailed message of the diagnostic."""
65
+
66
+ input: Any | None
67
+ """The input that caused the diagnostic."""
68
+
69
+ fix: str | None
70
+ """The fix to the diagnostic."""
71
+
72
+
73
+ def analyze_yaml(manifest: str) -> list[ExtendedDiagnostic]:
74
+ """
75
+ Analyze a YAML manifest and report diagnostics.
76
+
77
+ This function internally uses :py:func:`analyze_raw` to analyze the manifest.
78
+ The manifest is first parsed into a Python dictionary before being analyzed.
79
+
80
+ Parameters
81
+ ----------
82
+ manifest : str
83
+ The YAML manifest to analyze.
84
+
85
+ Returns
86
+ -------
87
+ list[Diagnostic]
88
+ The diagnostics reported by the analyzers.
89
+ """
90
+ global _yaml_parser
91
+
92
+ if not _yaml_parser:
93
+ _yaml_parser = ruamel.yaml.YAML()
94
+
95
+ try:
96
+ documents = _yaml_parser.load_all(manifest)
97
+ documents = list(documents) # force evaluation
98
+ except MarkedYAMLError as e:
99
+ line = column = 1
100
+ if e.problem_mark:
101
+ line = e.problem_mark.line + 1
102
+ column = e.problem_mark.column + 1
103
+ return [
104
+ {
105
+ "line": line,
106
+ "column": column,
107
+ "type": "error",
108
+ "code": "F002",
109
+ "manifest": None,
110
+ "loc": (),
111
+ "summary": "Malformed YAML document",
112
+ "msg": e.problem,
113
+ "input": None,
114
+ "fix": None,
115
+ }
116
+ ]
117
+
118
+ diagnostics = []
119
+ for document in documents:
120
+ if document is None:
121
+ continue
122
+
123
+ if not isinstance(document, CommentedMap):
124
+ return [
125
+ {
126
+ "line": document.lc.line + 1,
127
+ "column": document.lc.col + 1,
128
+ "type": "error",
129
+ "code": "F003",
130
+ "manifest": None,
131
+ "loc": (),
132
+ "summary": "Malformed document structure",
133
+ "msg": "The YAML document should be a mapping",
134
+ "input": None,
135
+ "fix": None,
136
+ }
137
+ ]
138
+
139
+ for diag in analyze_raw(document):
140
+ line, column = _get_line_column(document, diag.get("loc", ()))
141
+ diagnostics.append(
142
+ {
143
+ "line": line + 1,
144
+ "column": column + 1,
145
+ "type": diag.get("type", "failure"),
146
+ "code": diag["code"],
147
+ "manifest": _get_manifest_name(document),
148
+ "loc": diag.get("loc", ()),
149
+ "summary": diag.get("summary") or _get_summary(diag["msg"]),
150
+ "msg": diag["msg"],
151
+ "input": diag.get("input"),
152
+ "fix": diag.get("fix"),
153
+ }
154
+ )
155
+
156
+ return diagnostics
157
+
158
+
159
+ def _get_line_column(node: CommentedBase, loc: Sequence[int | str]) -> tuple[int, int]:
160
+ last_known_pos = node.lc.line, node.lc.col
161
+ for part in loc:
162
+ try:
163
+ pos = node.lc.key(part)
164
+ except KeyError:
165
+ break
166
+
167
+ if pos:
168
+ last_known_pos = pos
169
+
170
+ try:
171
+ node = node[part] # type: ignore[reportIndexIssue]
172
+ except (KeyError, IndexError):
173
+ break
174
+
175
+ if not hasattr(node, "lc"):
176
+ break
177
+
178
+ return last_known_pos
179
+
180
+
181
+ def _get_summary(msg: str) -> str:
182
+ return msg.strip().splitlines()[0].split(". ")[0]
183
+
184
+
185
+ def analyze_raw(manifest: dict) -> list[Diagnostic]:
186
+ """
187
+ Analyze a raw manifest and report diagnostics.
188
+
189
+ This function underlyingly uses the plugin manager to run the analyzers
190
+ registered with the system. The diagnostics are collected and returned
191
+ as a list of Diagnostic objects.
192
+
193
+ Parameters
194
+ ----------
195
+ manifest : dict
196
+ The manifest to analyze.
197
+
198
+ Returns
199
+ -------
200
+ list[Diagnostic]
201
+ The diagnostics reported by the analyzers.
202
+ """
203
+ pm = get_plugin_manager()
204
+
205
+ # early exit if the manifest is not a Kubernetes manifest
206
+ if not is_kubernetes_manifest(manifest):
207
+ return [
208
+ {
209
+ "type": "skipped",
210
+ "code": "M001",
211
+ "loc": (),
212
+ "summary": "Not a Kubernetes manifest",
213
+ "msg": "The input does not look like a Kubernetes manifest",
214
+ }
215
+ ]
216
+
217
+ # get the manifest name
218
+ name = _get_manifest_name(manifest)
219
+ logger.debug("Analyzing manifest '%s' of kind '%s'", name, manifest.get("kind"))
220
+
221
+ # parse the manifest
222
+ try:
223
+ manifest_obj = pm.hook.parse_manifest(manifest=manifest)
224
+ except ValidationError as e:
225
+ return list(map(translate_pydantic_error, e.errors()))
226
+ except Exception as e:
227
+ logger.exception("Error during execution of parse_manifest hook")
228
+ return [
229
+ {
230
+ "type": "error",
231
+ "code": "F001",
232
+ "loc": (),
233
+ "summary": "Internal error while analyzing manifest",
234
+ "msg": f"An error occurred while parsing the manifest: {e}",
235
+ }
236
+ ]
237
+
238
+ logger.debug("Parsed manifest '%s' as %s object", name, type(manifest_obj))
239
+
240
+ if not manifest_obj:
241
+ kind = manifest.get("kind")
242
+ return [
243
+ {
244
+ "type": "skipped",
245
+ "code": "M002",
246
+ "loc": ("kind",),
247
+ "msg": f"Manifest of kind '{kind}' is not supported",
248
+ "input": kind,
249
+ }
250
+ ]
251
+
252
+ if not isinstance(manifest_obj, Manifest):
253
+ return [
254
+ {
255
+ "type": "error",
256
+ "code": "F001",
257
+ "loc": (),
258
+ "summary": "Internal error while analyzing manifest",
259
+ "msg": f"Expected a Manifest object, got {type(manifest_obj)}",
260
+ }
261
+ ]
262
+
263
+ # examine the manifest
264
+ try:
265
+ diagnostics: Iterable[Diagnostic] = pm.hook.analyze(manifest=manifest_obj)
266
+ diagnostics = list(diagnostics) # force evaluation
267
+ except Exception as e:
268
+ logger.exception("Error during execution of analyze hook")
269
+ return [
270
+ {
271
+ "type": "error",
272
+ "code": "F001",
273
+ "loc": (),
274
+ "summary": "Internal error while analyzing manifest",
275
+ "msg": f"An error occurred while analyzing the manifest: {e}",
276
+ }
277
+ ]
278
+
279
+ logger.debug("Got %d diagnostics for manifest '%s'", len(diagnostics), name)
280
+
281
+ # normalize the diagnostics
282
+ for diagnostic in diagnostics:
283
+ diagnostic.setdefault("code", "UNKNOWN")
284
+ diagnostic["msg"] = textwrap.dedent(diagnostic["msg"]).strip()
285
+
286
+ # sort the diagnostics
287
+ def _sort_key(diagnostic: Diagnostic) -> tuple:
288
+ return (
289
+ # 1. position of the occurrence
290
+ tuple(diagnostic.get("loc", [])),
291
+ # 2. diagnostic code
292
+ diagnostic.get("code") or "",
293
+ )
294
+
295
+ diagnostics = sorted(diagnostics, key=_sort_key)
296
+
297
+ return diagnostics
298
+
299
+
300
+ def _get_manifest_name(manifest: dict) -> str | None:
301
+ metadata = manifest.get("metadata", {})
302
+ if name := metadata.get("name"):
303
+ return name
304
+ if name := metadata.get("generateName"):
305
+ return name
306
+
307
+
308
+ def is_kubernetes_manifest(d: dict) -> bool:
309
+ """Returns True if the dictionary *looks like* a Kubernetes manifest."""
310
+ return "apiVersion" in d and "kind" in d
File without changes
@@ -0,0 +1,104 @@
1
+ """
2
+ This module provides some generic constraints that can be used on models.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+
9
+ from tugboat.analyzers.utils import get_context_name, join_with_and, join_with_or
10
+
11
+ if typing.TYPE_CHECKING:
12
+ from collections.abc import Iterator, Sequence
13
+ from typing import Any
14
+
15
+ from tugboat.core import Diagnostic
16
+
17
+
18
+ def accept_none(
19
+ *, model: Any, loc: Sequence[str | int], fields: Sequence[str]
20
+ ) -> Iterator[Diagnostic]:
21
+ """
22
+ This constraint checks if all the specified fields are set to None. For each
23
+ field that is not None, error M005 is yielded.
24
+ """
25
+ for field in fields:
26
+ if getattr(model, field, None) is not None:
27
+ yield {
28
+ "type": "failure",
29
+ "code": "M005",
30
+ "loc": (*loc, field),
31
+ "summary": f"Found redundant field '{field}'",
32
+ "msg": f"Field '{field}' is not valid within {get_context_name(loc)}.",
33
+ "input": field,
34
+ }
35
+
36
+
37
+ def require_all(
38
+ *, model: Any, loc: Sequence[str | int], fields: Sequence[str]
39
+ ) -> Iterator[Diagnostic]:
40
+ """
41
+ This constraint requires that all of the specified fields in the model are set.
42
+ If any of the fields are missing, error M004 is yielded.
43
+ """
44
+ for field in fields:
45
+ value = getattr(model, field, None)
46
+ if value is None:
47
+ yield {
48
+ "type": "failure",
49
+ "code": "M004",
50
+ "loc": (*loc, field),
51
+ "summary": f"Missing required field '{field}'",
52
+ "msg": f"Field '{field}' is required in {get_context_name(loc)} but missing",
53
+ }
54
+ elif value == "":
55
+ yield {
56
+ "type": "failure",
57
+ "code": "M004",
58
+ "loc": (*loc, field),
59
+ "summary": f"Missing required field '{field}'",
60
+ "msg": f"Field '{field}' is required in {get_context_name(loc)} but empty",
61
+ }
62
+
63
+
64
+ def require_exactly_one(
65
+ *, model: Any, loc: Sequence[str | int], fields: Sequence[str]
66
+ ) -> Iterator[Diagnostic]:
67
+ """
68
+ This constraint requires that exactly one of the specified fields in the
69
+ model is set. If the constraint is not met, following errors are yielded:
70
+
71
+ M004:
72
+ When none of the fields are set.
73
+ M006:
74
+ When more than one were set.
75
+ """
76
+ set_fields = [field for field in fields if getattr(model, field, None) is not None]
77
+
78
+ match len(set_fields):
79
+ case 0:
80
+ yield {
81
+ "type": "failure",
82
+ "code": "M004",
83
+ "loc": tuple(loc),
84
+ "summary": "Missing required field",
85
+ "msg": f"""
86
+ Missing required field for {get_context_name(loc)}.
87
+ One of the following fields is required: {join_with_or(fields)}.
88
+ """,
89
+ }
90
+
91
+ case 1:
92
+ ... # no error!
93
+
94
+ case _:
95
+ set_fields_str = join_with_and(set_fields)
96
+ for field in set_fields:
97
+ yield {
98
+ "type": "failure",
99
+ "code": "M006",
100
+ "loc": (*loc, field),
101
+ "summary": "Mutually exclusive field set",
102
+ "msg": f"Field {set_fields_str} are mutually exclusive.",
103
+ "input": field,
104
+ }
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import typing
5
+
6
+ if typing.TYPE_CHECKING:
7
+ from tugboat.core import Diagnostic
8
+
9
+
10
+ def check_resource_name(
11
+ name: str, *, length: int = 253, is_generate_name: bool = False
12
+ ) -> Diagnostic | None:
13
+ """
14
+ Check if the name is valid to be used as a Kubernetes resource name.
15
+ """
16
+ if is_generate_name:
17
+ # although kubernetes automatically truncates the name when it exceeds
18
+ # the length, we want to keep the name as close as possible to the
19
+ # original name to help users identify the resource.
20
+ length -= 5
21
+
22
+ if len(name) > length:
23
+ return {
24
+ "type": "failure",
25
+ "code": "M009",
26
+ "loc": (),
27
+ "summary": "Resource name is too long",
28
+ "msg": f"Resource name '{name}' is too long, maximum length is {length}.",
29
+ "input": name,
30
+ }
31
+
32
+ if is_generate_name:
33
+ internal_name = name.removesuffix("-")
34
+ else:
35
+ internal_name = name
36
+
37
+ pattern = re.compile(r"[a-z0-9]([a-z0-9.-]*[a-z0-9])?")
38
+ if pattern.fullmatch(internal_name):
39
+ return
40
+
41
+ diagnostic: Diagnostic = {
42
+ "type": "failure",
43
+ "code": "M010",
44
+ "loc": (),
45
+ "summary": "Invalid resource name",
46
+ "msg": f"""
47
+ Resource name '{name}' is invalid.
48
+ It must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character.
49
+ """,
50
+ "input": name,
51
+ }
52
+
53
+ alternative_name = internal_name.replace("_", "-").lower()
54
+ if pattern.fullmatch(alternative_name):
55
+ if is_generate_name and name.endswith("-"):
56
+ alternative_name += "-"
57
+ diagnostic["fix"] = alternative_name
58
+
59
+ return diagnostic