cycl 0.2.2__tar.gz → 0.2.7__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 (49) hide show
  1. {cycl-0.2.2 → cycl-0.2.7}/PKG-INFO +28 -19
  2. {cycl-0.2.2 → cycl-0.2.7}/README.md +5 -9
  3. {cycl-0.2.2 → cycl-0.2.7}/pyproject.toml +43 -12
  4. cycl-0.2.7/src/cycl/__init__.py +8 -0
  5. cycl-0.2.7/src/cycl/cli.py +128 -0
  6. cycl-0.2.7/src/cycl/cycl.py +74 -0
  7. cycl-0.2.7/src/cycl/models/export_data.py +162 -0
  8. {cycl-0.2.2 → cycl-0.2.7}/src/cycl/utils/cdk.py +15 -11
  9. {cycl-0.2.2 → cycl-0.2.7}/src/cycl/utils/testing.py +1 -1
  10. {cycl-0.2.2 → cycl-0.2.7}/src/cycl.egg-info/PKG-INFO +28 -19
  11. cycl-0.2.7/src/cycl.egg-info/SOURCES.txt +20 -0
  12. cycl-0.2.7/src/cycl.egg-info/requires.txt +23 -0
  13. cycl-0.2.2/.github/dependabot.yml +0 -11
  14. cycl-0.2.2/.github/workflows/ci.yml +0 -72
  15. cycl-0.2.2/.github/workflows/release.yml +0 -37
  16. cycl-0.2.2/.gitignore +0 -186
  17. cycl-0.2.2/Makefile +0 -45
  18. cycl-0.2.2/TODO.md +0 -21
  19. cycl-0.2.2/compose.yml +0 -13
  20. cycl-0.2.2/docs/Dockerfile +0 -3
  21. cycl-0.2.2/docs/cmd.md +0 -8
  22. cycl-0.2.2/docs/conf.py +0 -28
  23. cycl-0.2.2/docs/index.md +0 -23
  24. cycl-0.2.2/requirements-build.txt +0 -2
  25. cycl-0.2.2/requirements-dev.txt +0 -8
  26. cycl-0.2.2/requirements.txt +0 -2
  27. cycl-0.2.2/src/cycl/__init__.py +0 -6
  28. cycl-0.2.2/src/cycl/cli.py +0 -77
  29. cycl-0.2.2/src/cycl/cycl.py +0 -66
  30. cycl-0.2.2/src/cycl/utils/cfn.py +0 -57
  31. cycl-0.2.2/src/cycl.egg-info/SOURCES.txt +0 -41
  32. cycl-0.2.2/src/cycl.egg-info/requires.txt +0 -9
  33. cycl-0.2.2/tests/cli_test.py +0 -176
  34. cycl-0.2.2/tests/cycl_test.py +0 -445
  35. cycl-0.2.2/tests/utils/__init__.py +0 -0
  36. cycl-0.2.2/tests/utils/cdk_test.py +0 -208
  37. cycl-0.2.2/tests/utils/cfn_test.py +0 -171
  38. cycl-0.2.2/tests/utils/log_config_test.py +0 -17
  39. cycl-0.2.2/tests/utils/testing_test.py +0 -20
  40. {cycl-0.2.2 → cycl-0.2.7}/LICENSE +0 -0
  41. {cycl-0.2.2 → cycl-0.2.7}/setup.cfg +0 -0
  42. {cycl-0.2.2 → cycl-0.2.7}/src/cycl/__main__.py +0 -0
  43. {cycl-0.2.2/src/cycl/utils → cycl-0.2.7/src/cycl/models}/__init__.py +0 -0
  44. {cycl-0.2.2 → cycl-0.2.7}/src/cycl/py.typed +0 -0
  45. {cycl-0.2.2/tests → cycl-0.2.7/src/cycl/utils}/__init__.py +0 -0
  46. {cycl-0.2.2 → cycl-0.2.7}/src/cycl/utils/log_config.py +0 -0
  47. {cycl-0.2.2 → cycl-0.2.7}/src/cycl.egg-info/dependency_links.txt +0 -0
  48. {cycl-0.2.2 → cycl-0.2.7}/src/cycl.egg-info/entry_points.txt +0 -0
  49. {cycl-0.2.2 → cycl-0.2.7}/src/cycl.egg-info/top_level.txt +0 -0
@@ -1,12 +1,12 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: cycl
3
- Version: 0.2.2
3
+ Version: 0.2.7
4
4
  Summary: CLI and Python SDK to help identify cross-stack import/export circular dependencies, for a given AWS account and region.
5
+ License: MIT
5
6
  Project-URL: Repository, http://github.com/tcm5343/cycl
6
7
  Project-URL: Documentation, https://tcm5343.github.io/cycl/index.html
7
8
  Keywords: aws,cdk,cycle,circular,dependency,infrastructure,boto3,cloud
8
9
  Classifier: Intended Audience :: Developers
9
- Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Natural Language :: English
11
11
  Classifier: Programming Language :: Python :: 3.10
12
12
  Classifier: Programming Language :: Python :: 3.11
@@ -16,17 +16,30 @@ Classifier: Programming Language :: Python :: 3.9
16
16
  Classifier: Programming Language :: Python :: 3
17
17
  Classifier: Programming Language :: Python
18
18
  Classifier: Topic :: Software Development
19
- Requires-Python: >=3.8
19
+ Requires-Python: >=3.9
20
20
  Description-Content-Type: text/markdown
21
21
  License-File: LICENSE
22
22
  Requires-Dist: boto3~=1.0
23
23
  Requires-Dist: networkx~=3.0
24
- Provides-Extra: docs
25
- Requires-Dist: myst-parser==4.0.1; extra == "docs"
26
- Requires-Dist: sphinx_rtd_theme==3.0.2; extra == "docs"
27
- Requires-Dist: sphinx-argparse==0.5.2; extra == "docs"
28
- Requires-Dist: sphinx-autobuild==2024.10.3; extra == "docs"
29
- Requires-Dist: sphinx==8.1.3; extra == "docs"
24
+ Provides-Extra: dev
25
+ Requires-Dist: boto3-stubs[essential]==1.37.13; extra == "dev"
26
+ Requires-Dist: mypy==1.15.0; extra == "dev"
27
+ Requires-Dist: pytest-cov==6.0.0; extra == "dev"
28
+ Requires-Dist: pytest-subtests==0.14.1; extra == "dev"
29
+ Requires-Dist: pytest-sugar==1.0.0; extra == "dev"
30
+ Requires-Dist: pytest==8.3.4; extra == "dev"
31
+ Requires-Dist: ruff==0.9.9; extra == "dev"
32
+ Requires-Dist: types-networkx==3.4.2.20250312; extra == "dev"
33
+ Provides-Extra: doc
34
+ Requires-Dist: myst-parser==4.0.1; extra == "doc"
35
+ Requires-Dist: sphinx_rtd_theme==3.0.2; extra == "doc"
36
+ Requires-Dist: sphinx-argparse==0.5.2; extra == "doc"
37
+ Requires-Dist: sphinx-autobuild==2024.10.3; extra == "doc"
38
+ Requires-Dist: sphinx==8.1.3; extra == "doc"
39
+ Provides-Extra: dist
40
+ Requires-Dist: build==1.2.2.post1; extra == "dist"
41
+ Requires-Dist: twine==6.1.0; extra == "dist"
42
+ Dynamic: license-file
30
43
 
31
44
  # cycl
32
45
 
@@ -38,21 +51,17 @@ Requires-Dist: sphinx==8.1.3; extra == "docs"
38
51
  [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v0.json)](https://github.com/charliermarsh/ruff)
39
52
  ![Checked with mypy](https://img.shields.io/badge/mypy-checked-blue)
40
53
 
41
- cycl is a CLI and Python SDK to help identify cross-stack import/export circular dependencies, for a given AWS account and region. The successor to [circular-dependency-detector](https://github.com/tcm5343/circular-dependency-detector), which was built at the University of Texas at Austin.
54
+ cycl is a CLI and Python SDK to help identify cross-stack import/export circular dependencies, for a given AWS account and region. The successor to [circular-dependency-detector](https://github.com/tcm5343/circular-dependency-detector), which was built at the University of Texas at Austin (ECE 382C: Software Testing).
42
55
 
43
56
  ## Documentation
44
57
 
45
- Documentation for using `cycl` is found [here](https://tcm5343.github.io/cycl/).
58
+ Documentation for using `cycl` may be found [here](https://tcm5343.github.io/cycl/).
46
59
 
47
60
  ## Contributing
48
61
 
49
- `cycl` is being actively developed, instructions will come as it becomes more stable.
50
-
51
- Run `make` to see the available targets and their descriptions.
52
-
53
- To serve the documentation pages locally, you can simply run `make docs-serve`. The address should be served on `http://0.0.0.0:8000`, if not, you can run `docker compose logs sphinx | grep "Serving"` to determine the correct address.
62
+ `cycl` is being actively developed, instructions will come as it becomes more stable. Run `make` to see the available targets and their descriptions. To run tests using `tox`, you must install `tox` and `pyenv`. A VScode dev container is coming soon.
54
63
 
55
64
  To run specific tests:
56
65
 
57
- * `tox -e py39 -- ./tests/utils/cdk_test.py`
58
- * `make test ARGS=./tests/utils/cdk_test.py`
66
+ * using tox: `tox -e py39 -- ./tests/utils/cdk_test.py`
67
+ * using pytest directly: `make test ARGS=./tests/utils/cdk_test.py`
@@ -8,21 +8,17 @@
8
8
  [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v0.json)](https://github.com/charliermarsh/ruff)
9
9
  ![Checked with mypy](https://img.shields.io/badge/mypy-checked-blue)
10
10
 
11
- cycl is a CLI and Python SDK to help identify cross-stack import/export circular dependencies, for a given AWS account and region. The successor to [circular-dependency-detector](https://github.com/tcm5343/circular-dependency-detector), which was built at the University of Texas at Austin.
11
+ cycl is a CLI and Python SDK to help identify cross-stack import/export circular dependencies, for a given AWS account and region. The successor to [circular-dependency-detector](https://github.com/tcm5343/circular-dependency-detector), which was built at the University of Texas at Austin (ECE 382C: Software Testing).
12
12
 
13
13
  ## Documentation
14
14
 
15
- Documentation for using `cycl` is found [here](https://tcm5343.github.io/cycl/).
15
+ Documentation for using `cycl` may be found [here](https://tcm5343.github.io/cycl/).
16
16
 
17
17
  ## Contributing
18
18
 
19
- `cycl` is being actively developed, instructions will come as it becomes more stable.
20
-
21
- Run `make` to see the available targets and their descriptions.
22
-
23
- To serve the documentation pages locally, you can simply run `make docs-serve`. The address should be served on `http://0.0.0.0:8000`, if not, you can run `docker compose logs sphinx | grep "Serving"` to determine the correct address.
19
+ `cycl` is being actively developed, instructions will come as it becomes more stable. Run `make` to see the available targets and their descriptions. To run tests using `tox`, you must install `tox` and `pyenv`. A VScode dev container is coming soon.
24
20
 
25
21
  To run specific tests:
26
22
 
27
- * `tox -e py39 -- ./tests/utils/cdk_test.py`
28
- * `make test ARGS=./tests/utils/cdk_test.py`
23
+ * using tox: `tox -e py39 -- ./tests/utils/cdk_test.py`
24
+ * using pytest directly: `make test ARGS=./tests/utils/cdk_test.py`
@@ -1,17 +1,20 @@
1
1
  [build-system]
2
- requires = ['setuptools>=64', 'setuptools-scm>=8']
2
+ requires = [
3
+ 'setuptools>=70',
4
+ 'wheel',
5
+ 'setuptools-git-versioning>=2.1',
6
+ ]
3
7
  build-backend = 'setuptools.build_meta'
4
8
 
5
9
  [project]
6
10
  name = 'cycl'
7
- version='0.2.2'
8
- requires-python = '>=3.8'
11
+ requires-python = '>=3.9'
9
12
  description = 'CLI and Python SDK to help identify cross-stack import/export circular dependencies, for a given AWS account and region.'
10
13
  readme = 'README.md'
14
+ license = {text = "MIT"}
11
15
  keywords = ['aws', 'cdk', 'cycle', 'circular', 'dependency', 'infrastructure', 'boto3', 'cloud']
12
16
  classifiers = [
13
17
  'Intended Audience :: Developers',
14
- 'License :: OSI Approved :: MIT License',
15
18
  'Natural Language :: English',
16
19
  'Programming Language :: Python :: 3.10',
17
20
  'Programming Language :: Python :: 3.11',
@@ -26,15 +29,33 @@ dependencies = [
26
29
  'boto3~=1.0',
27
30
  'networkx~=3.0',
28
31
  ]
32
+ dynamic = ['version']
33
+
34
+ [tool.setuptools-git-versioning]
35
+ enabled = true
29
36
 
30
37
  [project.optional-dependencies]
31
- docs = [
38
+ dev = [
39
+ 'boto3-stubs[essential]==1.37.13',
40
+ 'mypy==1.15.0',
41
+ 'pytest-cov==6.0.0',
42
+ 'pytest-subtests==0.14.1',
43
+ 'pytest-sugar==1.0.0',
44
+ 'pytest==8.3.4',
45
+ 'ruff==0.9.9',
46
+ 'types-networkx==3.4.2.20250312',
47
+ ]
48
+ doc = [
32
49
  'myst-parser==4.0.1',
33
50
  'sphinx_rtd_theme==3.0.2',
34
51
  'sphinx-argparse==0.5.2',
35
52
  'sphinx-autobuild==2024.10.3',
36
53
  'sphinx==8.1.3',
37
54
  ]
55
+ dist = [
56
+ 'build==1.2.2.post1',
57
+ 'twine==6.1.0', # not used in pipeline
58
+ ]
38
59
 
39
60
  [project.urls]
40
61
  Repository = 'http://github.com/tcm5343/cycl'
@@ -50,7 +71,14 @@ line-length = 125
50
71
  select = ['ALL']
51
72
  ignore = [
52
73
  'COM', # flake8-commas
53
- 'D', # pydocstyle
74
+ 'D100',
75
+ 'D101',
76
+ 'D102',
77
+ 'D103',
78
+ 'D104',
79
+ 'D105',
80
+ 'D106',
81
+ 'D107',
54
82
  'ERA001', # commented-out-code
55
83
  'FIX002', # line-contains-todo
56
84
  'Q000', # bad-quotes-inline-string
@@ -78,6 +106,9 @@ quote-style = 'single'
78
106
  indent-style = 'space'
79
107
  docstring-code-format = true
80
108
 
109
+ [tool.ruff.lint.pydocstyle]
110
+ convention = 'google'
111
+
81
112
  [tool.coverage.run]
82
113
  branch = true
83
114
  source = ['./src']
@@ -88,7 +119,7 @@ show_missing = true
88
119
  skip_covered = true
89
120
  skip_empty = true
90
121
  exclude_lines = [
91
- "if TYPE_CHECKING:",
122
+ 'if TYPE_CHECKING:',
92
123
  ]
93
124
  omit = [
94
125
  '__*__.py',
@@ -99,14 +130,14 @@ log_cli_level = 'INFO'
99
130
  addopts = ['--import-mode=importlib']
100
131
 
101
132
  [tool.tox]
102
- env_list = ["py39", "py310", "py311", "py312", "py313"]
133
+ env_list = ['py39', 'py310', 'py311', 'py312', 'py313']
103
134
  skip_missing_interpreters = false
104
135
 
105
136
  [tool.tox.env_run_base]
106
137
  allowlist_externals = ['make']
107
- package = "editable"
108
- deps = '-rrequirements-dev.txt'
138
+ package = 'editable'
139
+ deps = ['.[dev]']
109
140
  commands = [
110
- ["make", "validate"],
111
- ["make", "test", "ARGS={posargs}"]
141
+ ['make', 'validate'],
142
+ ['make', 'test', 'ARGS={posargs}']
112
143
  ]
@@ -0,0 +1,8 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ from .cycl import build_graph, get_graph_data
4
+
5
+ try:
6
+ __version__ = version('cycl')
7
+ except PackageNotFoundError:
8
+ __version__ = 'v?'
@@ -0,0 +1,128 @@
1
+ import argparse
2
+ import json
3
+ import logging
4
+ import pathlib
5
+ import sys
6
+ from logging import getLogger
7
+
8
+ import networkx as nx
9
+
10
+ from cycl import build_graph
11
+ from cycl.utils.log_config import configure_log
12
+
13
+ log = getLogger(__name__)
14
+
15
+
16
+ # def get_node_key_function(node_key: str, missing_tag: str = 'ignore') -> Callable[[ExportData], str]:
17
+ # if node_key.startswith("tag:"):
18
+ # tag_name = node_key.split(":", 1)[1]
19
+
20
+ # if missing_tag == 'error':
21
+ # return lambda x: x.tags[tag_name] # strict mode
22
+
23
+ # default_value = f"Unknown-{tag_name}" if missing_tag == 'default' else x.stack_name
24
+ # return lambda x: x.tags.get(tag_name, default_value)
25
+
26
+ # node_key_map = {
27
+ # 'stack_name': lambda x: x.stack_name,
28
+ # 'export_name': lambda x: x.export_name or 'NoExport',
29
+ # 'parent_id': lambda x: x.parent_id or 'NoParent',
30
+ # }
31
+
32
+ # return node_key_map.get(node_key, lambda x: x.stack_name)
33
+
34
+
35
+ def create_parser() -> argparse.ArgumentParser:
36
+ parser = argparse.ArgumentParser(prog='cycl', description='Check circular dependencies between imports and exports.')
37
+ sp = parser.add_subparsers(dest='cmd', required=True)
38
+
39
+ check_p = sp.add_parser('check', help='Check for cycles between AWS stack imports and exports.')
40
+ check_p.add_argument('--exit-zero', action='store_true', help='Exit zero regardless of cyclic chekc result.')
41
+
42
+ topo_p = sp.add_parser('topo', help='Find topological generations, if dependencies are acyclic')
43
+
44
+ # global options
45
+ for p in [check_p, topo_p]:
46
+ p.add_argument(
47
+ '--log-level',
48
+ choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
49
+ default='INFO',
50
+ help='Sets the logging level.',
51
+ )
52
+ p.add_argument(
53
+ '--cdk-out',
54
+ type=pathlib.Path,
55
+ help='EXPERIMENTAL : Path to cdk.out/, where the cdk synthesizes the cloud assembly output.',
56
+ )
57
+ p.add_argument(
58
+ '--ignore-nodes',
59
+ nargs='+',
60
+ default=[],
61
+ type=str,
62
+ help=(
63
+ "List of nodes to to ignore when building the graph. Don't repeat ``--ignore-nodes`` if you "
64
+ 'have multiple nodes (ex. ``--ignore-nodes v1 v2``).'
65
+ ),
66
+ )
67
+ p.add_argument(
68
+ '--ignore-edge',
69
+ nargs=2,
70
+ default=[],
71
+ action='append',
72
+ metavar=('u', 'v'),
73
+ help=(
74
+ 'Specify an edge to ignore by providing two nodes delimited by a space. ``--ignore-edge u v`` must be '
75
+ 'repeated for each edge provided.'
76
+ ),
77
+ )
78
+ # p.add_argument( # TODO
79
+ # '--node-key',
80
+ # type=str,
81
+ # choices=['stack_name', 'export_name', 'parent_id', 'tag:Environment'],
82
+ # default='stack_name',
83
+ # help='Specify which ExportData attribute to use as the graph node identifier.'
84
+ # )
85
+ # parser.add_argument(
86
+ # '--missing-tag',
87
+ # choices=['ignore', 'error', 'default'],
88
+ # default='ignore',
89
+ # help='How to handle missing tags: "ignore" (fallback to stack name), "error" (raise),
90
+ # or "default" (custom value).'
91
+ # )
92
+ return parser
93
+
94
+
95
+ def app() -> None:
96
+ parser = create_parser()
97
+
98
+ if len(sys.argv) == 1:
99
+ parser.print_help()
100
+ sys.exit(0)
101
+
102
+ args = parser.parse_args()
103
+ configure_log(getattr(logging, args.log_level))
104
+
105
+ dep_graph = build_graph(
106
+ cdk_out_path=args.cdk_out,
107
+ nodes_to_ignore=args.ignore_nodes,
108
+ edges_to_ignore=args.ignore_edge,
109
+ )
110
+
111
+ cycles = list(nx.simple_cycles(dep_graph))
112
+ for cycle in cycles:
113
+ print(f'cycle found between nodes: {cycle}')
114
+
115
+ if args.cmd == 'check':
116
+ if cycles and not args.exit_zero:
117
+ sys.exit(1)
118
+ elif args.cmd == 'topo':
119
+ if cycles:
120
+ log.error('graph is cyclic, topological generations can only be computed on an acyclic graph')
121
+ sys.exit(1)
122
+ generations = [sorted(generation) for generation in nx.topological_generations(dep_graph)]
123
+ print(json.dumps(generations, indent=2))
124
+ sys.exit(0)
125
+
126
+
127
+ if __name__ == '__main__':
128
+ app()
@@ -0,0 +1,74 @@
1
+ from __future__ import annotations
2
+
3
+ from logging import getLogger
4
+ from pathlib import Path
5
+
6
+ import boto3
7
+ import networkx as nx
8
+ from botocore.config import Config
9
+
10
+ from cycl.models.export_data import ExportData
11
+ from cycl.utils.cdk import get_exports_from_assembly
12
+
13
+ log = getLogger(__name__)
14
+
15
+
16
+ def get_graph_data(cdk_out_path: Path | None = None) -> dict[str, ExportData]:
17
+ cdk_out_imports: dict[str, list[ExportData]] = get_exports_from_assembly(Path(cdk_out_path)) if cdk_out_path else {}
18
+ log.info('cdk_out_imports: %s', cdk_out_imports)
19
+
20
+ boto_config = Config(retries={'max_attempts': 10, 'mode': 'adaptive'})
21
+ cfn_client = boto3.client('cloudformation', config=boto_config)
22
+
23
+ log.info('getting all exports')
24
+ exports = ExportData.get_all_exports(cfn_client=cfn_client)
25
+ for export_name, importing_stacks in cdk_out_imports.items():
26
+ if export_name not in exports:
27
+ log.warning(
28
+ 'found an export (%s) which has not been deployed yet about to be imported stack(s): (%s)',
29
+ export_name,
30
+ importing_stacks,
31
+ )
32
+
33
+ log.info('getting imports for %s exports', len(exports))
34
+ for export in exports.values():
35
+ if export.export_name: # TODO: i think this is a given, maybe enforce at object level, add unit test
36
+ export.get_all_imports(cfn_client=cfn_client)
37
+ export.importing_stacks += cdk_out_imports.get(export.export_name, []) # TODO: should we convert to method?
38
+ if len(export.importing_stacks) == 0:
39
+ log.warning('Export found with no import: %s from %s', export.export_name, export.stack_name)
40
+ return exports
41
+
42
+
43
+ def build_graph(
44
+ graph_data: dict[str, ExportData] | None = None,
45
+ cdk_out_path: Path | None = None,
46
+ # node_key: Callable[[ExportData], str] = lambda x: x.stack_name,
47
+ nodes_to_ignore: list[str] | None = None,
48
+ edges_to_ignore: list[list[str]] | None = None,
49
+ ) -> nx.MultiDiGraph:
50
+ nodes_to_ignore = nodes_to_ignore or []
51
+ edges_to_ignore = edges_to_ignore or []
52
+ graph_data = get_graph_data(cdk_out_path) if graph_data is None else graph_data
53
+
54
+ log.info('building dependency graph from graph data')
55
+ dep_graph: nx.MultiDiGraph = nx.MultiDiGraph()
56
+ for export in graph_data.values():
57
+ # export_key = node_key(export)
58
+ if export.stack_name in nodes_to_ignore:
59
+ continue
60
+
61
+ edges = []
62
+ for importing_stack in export.importing_stacks:
63
+ # importing_key = node_key(importing_stack)
64
+ if importing_stack.stack_name not in nodes_to_ignore:
65
+ edge = (export.stack_name, importing_stack.stack_name)
66
+ if list(edge) not in edges_to_ignore:
67
+ edges.append(edge)
68
+
69
+ if edges:
70
+ dep_graph.add_edges_from(ebunch_to_add=edges)
71
+ else:
72
+ # export key
73
+ dep_graph.add_node(export.stack_name)
74
+ return dep_graph
@@ -0,0 +1,162 @@
1
+ from __future__ import annotations
2
+
3
+ from logging import getLogger
4
+ from typing import TYPE_CHECKING
5
+
6
+ import boto3
7
+ from botocore.exceptions import ClientError
8
+
9
+ if TYPE_CHECKING:
10
+ from mypy_boto3_cloudformation import CloudFormationClient
11
+ from mypy_boto3_cloudformation.type_defs import ListExportsOutputTypeDef
12
+
13
+ log = getLogger(__name__)
14
+
15
+
16
+ class ExportData:
17
+ def __init__(
18
+ self,
19
+ stack_name: str,
20
+ stack_id: str | None = None,
21
+ export_name: str | None = None,
22
+ export_value: str | None = None,
23
+ # parent_id: str | None = None,
24
+ # root_id: str | None = None,
25
+ # tags: dict[str, str] | None = None,
26
+ # outputs: list[str] | None = None,
27
+ importing_stacks: list[ExportData] | None = None,
28
+ ) -> None:
29
+ self.stack_name = stack_name
30
+ self.stack_id = stack_id
31
+ self.export_name = export_name
32
+ self.export_value = export_value
33
+ # self.parent_id = parent_id
34
+ # self.root_id = root_id
35
+ # self.tags = tags
36
+ # self.outputs = outputs or []
37
+ self.importing_stacks = importing_stacks or []
38
+
39
+ @classmethod
40
+ def from_list_exports(cls, list_exports_resp: ListExportsOutputTypeDef) -> dict[str, ExportData]:
41
+ """Convert an AWS CloudFormation list exports response into a dictionary of export name to ExportData instances.
42
+
43
+ Args:
44
+ list_exports_resp: A dictionary representing the list exports response,
45
+ where each entry contains export details with keys:
46
+ - 'ExportingStackId': The ID of the stack exporting the value.
47
+ - 'Name': The name of the export.
48
+ - 'Value': The exported value.
49
+
50
+ Returns:
51
+ A dictionary mapping export names to ExportData instances,
52
+ where each ExportData object contains information about the corresponding export.
53
+ """
54
+ return {
55
+ export['Name']: cls(
56
+ stack_name=cls.parse_name_from_id(export['ExportingStackId']),
57
+ stack_id=export['ExportingStackId'],
58
+ export_name=export['Name'],
59
+ export_value=export['Value'],
60
+ )
61
+ for export in list_exports_resp['Exports']
62
+ }
63
+
64
+ @classmethod
65
+ def get_all_exports(cls, cfn_client: CloudFormationClient | None = None) -> dict[str, ExportData]:
66
+ """Retrieve all AWS CloudFormation exports and return them as a dictionary of export name to ExportData instances.
67
+
68
+ Args:
69
+ cfn_client: A Boto3 CloudFormation client instance.
70
+ If not provided, a new client will be created.
71
+
72
+ Returns:
73
+ A dictionary mapping export names to ExportData instances,
74
+ where each ExportData object contains details about the corresponding export.
75
+
76
+ Note:
77
+ This function paginates through the AWS CloudFormation `list_exports` API to retrieve all exports.
78
+ """
79
+ cfn_client = cfn_client or boto3.client('cloudformation')
80
+
81
+ exports: dict[str, ExportData] = {}
82
+ resp = cfn_client.list_exports()
83
+ log.debug(resp)
84
+ exports.update(ExportData.from_list_exports(resp))
85
+ while token := resp.get('NextToken'):
86
+ resp = cfn_client.list_exports(NextToken=token)
87
+ log.debug(resp)
88
+ exports.update(ExportData.from_list_exports(resp))
89
+ log.debug(exports)
90
+ return exports
91
+
92
+ def __eq__(self, other: object) -> bool:
93
+ if not isinstance(other, ExportData):
94
+ return False
95
+ return vars(self) == vars(other)
96
+
97
+ def __hash__(self) -> int:
98
+ return hash(tuple((key, tuple(value) if isinstance(value, list) else value) for key, value in vars(self).items()))
99
+
100
+ def __repr__(self) -> str:
101
+ return f'ExportData(stack_name={self.stack_name!r}, export_name={self.export_name!r})'
102
+
103
+ def get_all_imports(self, cfn_client: CloudFormationClient | None = None) -> ExportData:
104
+ """Retrieve all stacks that import the current export and update the importing_stacks attribute.
105
+
106
+ Args:
107
+ cfn_client: A Boto3 CloudFormation client instance. If not provided, a new client will be created.
108
+
109
+ Returns:
110
+ The updated instance with importing stacks added to the `importing_stacks` attribute.
111
+
112
+ Note:
113
+ This function paginates through the AWS CloudFormation `list_imports` API to retrieve all importing stacks.
114
+ If the export is not imported by any stack, it logs a debug message instead of raising an error.
115
+ """
116
+ if self.export_name:
117
+ cfn_client = cfn_client or boto3.client('cloudformation')
118
+
119
+ try:
120
+ resp = cfn_client.list_imports(ExportName=self.export_name)
121
+ log.debug(resp)
122
+ self.importing_stacks.extend(
123
+ [ExportData(stack_name=importing_stack_name) for importing_stack_name in resp['Imports']]
124
+ )
125
+ while token := resp.get('NextToken'):
126
+ resp = cfn_client.list_imports(ExportName=self.export_name, NextToken=token)
127
+ log.debug(resp)
128
+ self.importing_stacks.extend(
129
+ [ExportData(stack_name=importing_stack_name) for importing_stack_name in resp['Imports']]
130
+ )
131
+ except ClientError as err:
132
+ if 'is not imported by any stack' not in repr(err):
133
+ raise
134
+ log.debug('') # TODO: refine msg
135
+ log.debug(self.importing_stacks)
136
+ else:
137
+ warning_msg = (
138
+ f'export_name not defined for {type(self).__name__}, which probably means {self.stack_name} '
139
+ 'imports an export but does not export any'
140
+ )
141
+ log.warning(warning_msg)
142
+ return self
143
+
144
+ @staticmethod
145
+ def parse_name_from_id(stack_id: str) -> str:
146
+ """Extract the stack name from a given stack ID.
147
+
148
+ Args:
149
+ stack_id: The full stack ID, typically in the format
150
+ 'arn:aws:cloudformation:region:account-id:stack/stack-name/guid'.
151
+
152
+ Returns:
153
+ The extracted stack name, or an empty string if parsing fails.
154
+
155
+ Note:
156
+ Logs a warning if the stack ID format is unexpected.
157
+ """
158
+ try:
159
+ return stack_id.split('/')[1]
160
+ except IndexError:
161
+ log.warning('Unable to parse name from stack_id: %s', stack_id)
162
+ return ''
@@ -4,6 +4,8 @@ import json
4
4
  from logging import getLogger
5
5
  from pathlib import Path
6
6
 
7
+ from cycl.models.export_data import ExportData
8
+
7
9
  log = getLogger(__name__)
8
10
 
9
11
 
@@ -13,7 +15,7 @@ class InvalidCdkOutPathError(Exception):
13
15
 
14
16
 
15
17
  def __find_import_values(data: dict) -> list[str]:
16
- """recursively search for all 'Fn::ImportValue' keys and return their values"""
18
+ """Recursively search for all 'Fn::ImportValue' keys and return their values."""
17
19
  results = []
18
20
 
19
21
  if isinstance(data, dict):
@@ -31,16 +33,14 @@ def __find_import_values(data: dict) -> list[str]:
31
33
 
32
34
 
33
35
  def __get_import_values_from_template(file_path: Path) -> list[str]:
34
- """todo: handle yaml templates too"""
36
+ """todo: handle yaml templates too."""
35
37
  with Path.open(file_path) as f:
36
38
  json_data = json.load(f)
37
39
  return __find_import_values(json_data)
38
40
 
39
41
 
40
42
  def __get_stack_name_from_manifest(path_to_manifest: Path, template_file_name: str) -> str:
41
- """
42
- Grabs the stack name, if set, or parses stack name from the displayName (construct id) of the stack
43
- """
43
+ """Grabs the stack name, if set, or parses stack name from the displayName (construct id) of the stack."""
44
44
  with Path.open(path_to_manifest) as f:
45
45
  json_data = json.load(f)
46
46
 
@@ -72,18 +72,17 @@ def __validate_cdk_out_path(cdk_out_path: Path) -> Path:
72
72
  return cdk_out_path
73
73
 
74
74
 
75
- def get_cdk_out_imports(cdk_out_path: Path) -> dict[str, list[str]]:
76
- """
77
- map an export name to a list of stacks which import it
75
+ def get_exports_from_assembly(cdk_out_path: Path) -> dict[str, list[ExportData]]:
76
+ """Map an export name to a list of stacks which import it from the cloud assembly.
78
77
 
79
- function does not take into consideration exports
78
+ function does not take into consideration exports defined in the assembly
80
79
  - if we found an export, we may not be able to resolve the name of it
81
80
  - AWS has built in circular dependency detection inside of a stack
82
81
  - a circular dependency couldn't be introduced in a single deployment
83
82
  """
84
83
  cdk_out_path = __validate_cdk_out_path(cdk_out_path)
85
84
 
86
- stack_import_mapping: dict[str, list[str]] = {}
85
+ stack_import_mapping: dict[str, list[ExportData]] = {}
87
86
  for template_file in cdk_out_path.rglob('*.template.json'):
88
87
  log.info('Processing template: %s', template_file)
89
88
  imported_export_names = __get_import_values_from_template(template_file)
@@ -98,5 +97,10 @@ def get_cdk_out_imports(cdk_out_path: Path) -> dict[str, list[str]]:
98
97
  continue
99
98
  log.info('stack name found: %s', stack_name)
100
99
  for export_name in imported_export_names:
101
- stack_import_mapping.setdefault(export_name, []).append(stack_name)
100
+ stack_import_mapping.setdefault(export_name, []).append(
101
+ ExportData(
102
+ stack_name=stack_name,
103
+ export_name=export_name,
104
+ )
105
+ )
102
106
  return stack_import_mapping
@@ -1,5 +1,5 @@
1
1
  def is_circular_reversible_permutation(lst: list, candidate: list) -> bool:
2
- """the output cycle is non-deterministic, it could be reversed and any node could be the start"""
2
+ """The output cycle is non-deterministic, it could be reversed and any node could be the start."""
3
3
  extended_lst = lst + lst
4
4
  extended_lst_reverse = lst[::-1] + lst[::-1]
5
5
  return any(extended_lst[i : i + len(candidate)] == candidate for i in range(len(lst))) or any(