sushicore 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 (44) hide show
  1. sushicore-0.1.0/LICENSE +201 -0
  2. sushicore-0.1.0/PKG-INFO +44 -0
  3. sushicore-0.1.0/README.md +21 -0
  4. sushicore-0.1.0/pyproject.toml +39 -0
  5. sushicore-0.1.0/setup.cfg +4 -0
  6. sushicore-0.1.0/sushicore/__init__.py +74 -0
  7. sushicore-0.1.0/sushicore/build_env.py +229 -0
  8. sushicore-0.1.0/sushicore/cli_console.py +76 -0
  9. sushicore-0.1.0/sushicore/cmake_cache.py +61 -0
  10. sushicore-0.1.0/sushicore/cmake_driver.py +164 -0
  11. sushicore-0.1.0/sushicore/config.py +110 -0
  12. sushicore-0.1.0/sushicore/config_base.py +125 -0
  13. sushicore-0.1.0/sushicore/console.py +79 -0
  14. sushicore-0.1.0/sushicore/diag.py +176 -0
  15. sushicore-0.1.0/sushicore/discovery.py +165 -0
  16. sushicore-0.1.0/sushicore/events.py +27 -0
  17. sushicore-0.1.0/sushicore/icons.py +47 -0
  18. sushicore-0.1.0/sushicore/module_config.py +128 -0
  19. sushicore-0.1.0/sushicore/proc.py +117 -0
  20. sushicore-0.1.0/sushicore/profile.py +145 -0
  21. sushicore-0.1.0/sushicore/py.typed +0 -0
  22. sushicore-0.1.0/sushicore/renderer.py +283 -0
  23. sushicore-0.1.0/sushicore/stack_config.py +100 -0
  24. sushicore-0.1.0/sushicore/theme.py +110 -0
  25. sushicore-0.1.0/sushicore/toolchain_args.py +42 -0
  26. sushicore-0.1.0/sushicore/typer_theme.py +35 -0
  27. sushicore-0.1.0/sushicore/workspace.py +103 -0
  28. sushicore-0.1.0/sushicore.egg-info/PKG-INFO +44 -0
  29. sushicore-0.1.0/sushicore.egg-info/SOURCES.txt +42 -0
  30. sushicore-0.1.0/sushicore.egg-info/dependency_links.txt +1 -0
  31. sushicore-0.1.0/sushicore.egg-info/requires.txt +7 -0
  32. sushicore-0.1.0/sushicore.egg-info/top_level.txt +1 -0
  33. sushicore-0.1.0/tests/test_build_env.py +60 -0
  34. sushicore-0.1.0/tests/test_cmake_cache.py +56 -0
  35. sushicore-0.1.0/tests/test_cmake_driver.py +226 -0
  36. sushicore-0.1.0/tests/test_console_semantics.py +96 -0
  37. sushicore-0.1.0/tests/test_discovery.py +115 -0
  38. sushicore-0.1.0/tests/test_events.py +31 -0
  39. sushicore-0.1.0/tests/test_json_renderer.py +84 -0
  40. sushicore-0.1.0/tests/test_lazy_console.py +25 -0
  41. sushicore-0.1.0/tests/test_module_config.py +43 -0
  42. sushicore-0.1.0/tests/test_proc.py +84 -0
  43. sushicore-0.1.0/tests/test_profile.py +69 -0
  44. sushicore-0.1.0/tests/test_toolchain_args.py +43 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: sushicore
3
+ Version: 0.1.0
4
+ Summary: Shared core for the Sushi* developer CLIs (hub / sr / se / sa / sb / sd / st): workspace resolution, layered config, presentation, and the cmake/ctest driver.
5
+ Author-email: Mustafa Garip <mustafagarip@sushisystems.io>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/SushiSystems/SushiCore
8
+ Project-URL: Source, https://github.com/SushiSystems/SushiCore
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Topic :: Software Development :: Build Tools
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: rich>=13.0
19
+ Requires-Dist: tomli>=2.0; python_version < "3.11"
20
+ Provides-Extra: test
21
+ Requires-Dist: pytest>=7.0; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ # sushicore
25
+
26
+ The shared core of the Sushi developer CLIs. `hub`, `sr`, `se`, `sa`, `sb`, `sd` and `st` all
27
+ import it for the same four things: locating a workspace, loading layered TOML configuration,
28
+ printing to a terminal or to a JSON stream, and driving cmake and ctest.
29
+
30
+ ```bash
31
+ pip install sushicore
32
+ ```
33
+
34
+ It is a library for those CLIs rather than a tool of its own: it installs no console script and
35
+ it knows nothing about SYCL, a renderer, or any one module's schema.
36
+
37
+ | Module | What it does |
38
+ |---|---|
39
+ | `sushicore.workspace` | Walks up for a marker, merges a `[tool]` table with its platform override |
40
+ | `sushicore.config_base` | The layered load: defaults, file, local file, environment |
41
+ | `sushicore.console`, `renderer`, `events`, `theme`, `icons` | One seam for human output and for `--json` |
42
+ | `sushicore.cmake_driver`, `cmake_cache`, `proc`, `toolchain_args` | The configure, build and test driver the CLIs share |
43
+
44
+ The manual is in `docs/README.md`. Licensed under the terms in `LICENSE`.
@@ -0,0 +1,21 @@
1
+ # sushicore
2
+
3
+ The shared core of the Sushi developer CLIs. `hub`, `sr`, `se`, `sa`, `sb`, `sd` and `st` all
4
+ import it for the same four things: locating a workspace, loading layered TOML configuration,
5
+ printing to a terminal or to a JSON stream, and driving cmake and ctest.
6
+
7
+ ```bash
8
+ pip install sushicore
9
+ ```
10
+
11
+ It is a library for those CLIs rather than a tool of its own: it installs no console script and
12
+ it knows nothing about SYCL, a renderer, or any one module's schema.
13
+
14
+ | Module | What it does |
15
+ |---|---|
16
+ | `sushicore.workspace` | Walks up for a marker, merges a `[tool]` table with its platform override |
17
+ | `sushicore.config_base` | The layered load: defaults, file, local file, environment |
18
+ | `sushicore.console`, `renderer`, `events`, `theme`, `icons` | One seam for human output and for `--json` |
19
+ | `sushicore.cmake_driver`, `cmake_cache`, `proc`, `toolchain_args` | The configure, build and test driver the CLIs share |
20
+
21
+ The manual is in `docs/README.md`. Licensed under the terms in `LICENSE`.
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sushicore"
7
+ version = "0.1.0"
8
+ description = "Shared core for the Sushi* developer CLIs (hub / sr / se / sa / sb / sd / st): workspace resolution, layered config, presentation, and the cmake/ctest driver."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Developers",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Topic :: Software Development :: Build Tools",
19
+ ]
20
+ authors = [{ name = "Mustafa Garip", email = "mustafagarip@sushisystems.io" }]
21
+ requires-python = ">=3.10"
22
+ dependencies = [
23
+ "rich>=13.0",
24
+ "tomli>=2.0; python_version < '3.11'",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/SushiSystems/SushiCore"
29
+ Source = "https://github.com/SushiSystems/SushiCore"
30
+
31
+ [project.optional-dependencies]
32
+ test = ["pytest>=7.0"]
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["."]
36
+ include = ["sushicore*"]
37
+
38
+ [tool.setuptools.package-data]
39
+ sushicore = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,74 @@
1
+ """sushicore — shared foundation for the Sushi* developer CLIs: hub, sr, se, sa, sb, sd, st.
2
+
3
+ Two things live here. A config-driven CLI presentation layer: :func:`build_console`
4
+ assembles a :class:`Console` from layered TOML config + environment, using pluggable
5
+ :mod:`~sushicore.theme` and :mod:`~sushicore.icons` presets rendered through a pluggable
6
+ :mod:`~sushicore.renderer` backend. And the build machinery that decides what reaches a
7
+ compiler in five of those repositories: :class:`~sushicore.proc.Runner` (spawning),
8
+ :mod:`~sushicore.cmake_cache` (reading CMakeCache.txt), :class:`~sushicore.cmake_driver.CMakeDriver`
9
+ (the cmake and ctest invocations) and :mod:`~sushicore.toolchain_args` (compiler and vcpkg
10
+ prefix derivation). Each consumer's own ``services/project.py`` keeps its own build policy
11
+ and calls into these. Each piece can be registered, overridden, or swapped independently —
12
+ see the module docstrings for how.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import Sequence
20
+
21
+ from .config import load_appearance
22
+ from .console import Console
23
+ from .icons import IconSet, get_icon_set, known_icon_sets, register_icon_set
24
+ from .renderer import JsonRenderer, PlainRenderer, Renderer, RichRenderer
25
+ from .theme import Theme, get_theme, known_themes, register_theme
26
+ from .typer_theme import apply_typer_theme
27
+
28
+ __all__ = [
29
+ "Console",
30
+ "Theme",
31
+ "IconSet",
32
+ "Renderer",
33
+ "RichRenderer",
34
+ "PlainRenderer",
35
+ "JsonRenderer",
36
+ "build_console",
37
+ "register_theme",
38
+ "register_icon_set",
39
+ "known_themes",
40
+ "known_icon_sets",
41
+ "get_theme",
42
+ "get_icon_set",
43
+ "apply_typer_theme",
44
+ ]
45
+
46
+
47
+ def _use_color(mode: str) -> bool:
48
+ """Decide whether colour is on for ``always``, ``never`` or ``auto`` (a TTY stdout)."""
49
+ if mode == "always":
50
+ return True
51
+ if mode == "never":
52
+ return False
53
+ return sys.stdout.isatty() # auto
54
+
55
+
56
+ def build_console(config_paths: Sequence[Path] = (), *, machine: bool = False) -> Console:
57
+ """Build a themed :class:`Console` from a repo's own config files.
58
+
59
+ Args:
60
+ config_paths: The TOML files a repo already resolves for its build config,
61
+ low to high precedence; only the ``[cli]`` table is read.
62
+ machine: When true, render through :class:`JsonRenderer` so stdout carries
63
+ one JSON event per line. Theme and icons are still loaded.
64
+ """
65
+ spec = load_appearance(list(config_paths))
66
+ theme = get_theme(spec.theme).merged(spec.color_overrides)
67
+ icons = get_icon_set(spec.icons).merged(spec.icon_overrides)
68
+ apply_typer_theme(theme)
69
+ renderer: Renderer
70
+ if machine:
71
+ renderer = JsonRenderer()
72
+ else:
73
+ renderer = RichRenderer(theme, no_color=not _use_color(spec.color))
74
+ return Console(renderer, theme, icons)
@@ -0,0 +1,229 @@
1
+ """Snapshotting the environment a build runs under.
2
+
3
+ A parent process cannot ``call vcvars64.bat`` and inherit the result: the batch
4
+ file sets its variables in its own shell, which then exits. So the shell is run
5
+ as a child, its environment is dumped and parsed, and that dictionary is handed
6
+ to every cmake/ctest subprocess. The snapshot is cached on disk keyed by the
7
+ configuration that produced it, so an unchanged config skips the shell entirely.
8
+
9
+ The primitives below are the parts that are the same wherever this is done.
10
+ :class:`StackBuildEnv` composes them the way a module that *consumes* the shared
11
+ toolchain needs; SushiRuntime, which *selects* one, composes them itself.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import json
18
+ import os
19
+ import subprocess
20
+ from pathlib import Path
21
+ from typing import Mapping, Sequence
22
+
23
+
24
+ def merge_env(base: Mapping[str, str], overlay: Mapping[str, str]) -> dict[str, str]:
25
+ """Merge *overlay* into *base*, prepending PATH into the base's case variant.
26
+
27
+ PATH is collapsed into the *single* case variant the base already uses (for
28
+ instance Windows' "Path"). Writing the overlay's "PATH" as a new key while
29
+ base keeps "Path" leaves two conflicting entries; Windows then honours only
30
+ one of them for child processes, so toolchain directories added to the other
31
+ silently vanish from DLL and executable resolution.
32
+ """
33
+ merged = dict(base)
34
+ path_key = next((k for k in merged if k.upper() == "PATH"), None)
35
+ for k, v in overlay.items():
36
+ if k.upper() == "PATH":
37
+ target = path_key or k
38
+ existing = merged.get(target, "")
39
+ merged[target] = v + os.pathsep + existing if existing else v
40
+ path_key = target
41
+ else:
42
+ merged[k] = v
43
+ return merged
44
+
45
+
46
+ def prepend_path(env: dict[str, str], var: str, dirs: Sequence[str]) -> None:
47
+ """Prepend *dirs* to the (case-insensitive) *var* path entry of *env*."""
48
+ if not dirs:
49
+ return
50
+ key = next((k for k in env if k.upper() == var.upper()), var)
51
+ existing = env.get(key, "")
52
+ env[key] = os.pathsep.join(list(dirs) + ([existing] if existing else []))
53
+
54
+
55
+ #: Variables that pick which accelerator a program runs on. The snapshot dumps
56
+ #: the whole environment of the shell that produced it, so anything exported for
57
+ #: one debugging session would otherwise be frozen into the cache and replayed
58
+ #: into every later build and run -- including from a fresh terminal, since the
59
+ #: snapshot is merged over the current environment. These name a run-time choice,
60
+ #: never a toolchain fact, so they are dropped on the way in and on the way out.
61
+ RUNTIME_DEVICE_VARS = frozenset({
62
+ "ONEAPI_DEVICE_SELECTOR",
63
+ "SYCL_DEVICE_FILTER",
64
+ "SYCL_DEVICE_ALLOWLIST",
65
+ "CUDA_VISIBLE_DEVICES",
66
+ "HIP_VISIBLE_DEVICES",
67
+ "ZE_AFFINITY_MASK",
68
+ })
69
+
70
+
71
+ def without_device_selection(env: Mapping[str, str]) -> dict[str, str]:
72
+ """Copy *env* without the variables that choose an accelerator.
73
+
74
+ Applied to a snapshot before it is cached and to one read back, so a cache
75
+ written before this existed heals on its next read rather than having to be
76
+ deleted by hand.
77
+ """
78
+ return {k: v for k, v in env.items() if k.upper() not in RUNTIME_DEVICE_VARS}
79
+
80
+
81
+ def parse_windows_set(output: str) -> dict[str, str]:
82
+ """Parse the KEY=VALUE lines that cmd.exe's ``set`` prints."""
83
+ env: dict[str, str] = {}
84
+ for line in output.splitlines():
85
+ key, sep, value = line.partition("=")
86
+ if sep and key:
87
+ env[key] = value
88
+ return env
89
+
90
+
91
+ def snapshot_windows(cfg, console) -> dict[str, str] | None:
92
+ """Run vcvars64 in a child shell and return the environment it produced.
93
+
94
+ None when no vcvars is configured or it fails, which callers treat as "use
95
+ the current environment" rather than an error: a machine with MSVC already
96
+ on PATH needs no snapshot.
97
+ """
98
+ vcvars = cfg.expand(cfg.vs_vcvars)
99
+ if not (vcvars and Path(vcvars).is_file()):
100
+ return None
101
+ console.info("Loading Visual Studio environment (vcvars64)...")
102
+ # Pass the whole command as a single string, NOT as ["cmd", "/c", script]:
103
+ # with a list, subprocess re-quotes each element and mangles the inner quotes
104
+ # around the (space-containing) vcvars path, so cmd.exe sees the quoted path
105
+ # as one unknown token and returns non-zero -- silently dropping the VS
106
+ # environment.
107
+ script = 'cmd /c call "' + vcvars + '" && set'
108
+ result = subprocess.run(script, capture_output=True, text=True)
109
+ if result.returncode != 0:
110
+ console.warn("vcvars64 returned non-zero; using current env.")
111
+ return None
112
+ return without_device_selection(parse_windows_set(result.stdout))
113
+
114
+
115
+ def read_cache(cache_file: Path, key: str) -> dict[str, str] | None:
116
+ """The cached snapshot when it was produced by *key*, else None."""
117
+ if not cache_file.is_file():
118
+ return None
119
+ try:
120
+ cached = json.loads(cache_file.read_text())
121
+ except (json.JSONDecodeError, OSError):
122
+ return None
123
+ if not isinstance(cached, dict) or cached.get("key") != key:
124
+ return None
125
+ env = cached.get("env")
126
+ return without_device_selection(env) if isinstance(env, dict) else None
127
+
128
+
129
+ def write_cache(cache_file: Path, key: str, env: Mapping[str, str]) -> None:
130
+ """Store *env* under *key*. Failing to write is not failing to build."""
131
+ try:
132
+ cache_file.write_text(json.dumps({"key": key, "env": dict(env)}))
133
+ except OSError:
134
+ pass
135
+
136
+
137
+ class StackBuildEnv:
138
+ """The build environment for a module that consumes the shared toolchain.
139
+
140
+ SushiEngine, SushiAI and SushiBLAS each carried a copy of this. Stripped of
141
+ comments the three were the same code but for one expression -- the cache
142
+ key, which lists the sibling checkouts -- and those the profile already
143
+ names. So even the one difference was not one.
144
+
145
+ @param profile Supplies the siblings that belong in the cache key.
146
+ @param console The CLI's console module.
147
+ @param find_root The CLI's project-root resolver.
148
+ @param cache_name Filename of the on-disk snapshot, inside the build dir.
149
+ """
150
+
151
+ __slots__ = ("_profile", "_console", "_find_root", "_cache_name")
152
+
153
+ def __init__(self, *, profile, console, find_root,
154
+ cache_name: str = ".sushi_env.json") -> None:
155
+ self._profile = profile
156
+ self._console = console
157
+ self._find_root = find_root
158
+ self._cache_name = cache_name
159
+
160
+ def cache_key(self, cfg) -> str:
161
+ """Hash of everything that would change the snapshot.
162
+
163
+ The sibling directories are in here because moving one changes which
164
+ toolchain bundle gets injected. They come from the profile rather than
165
+ being listed again, which is exactly where the three copies differed.
166
+ """
167
+ material = {"platform": cfg.platform, "vs_vcvars": cfg.vs_vcvars}
168
+ for name in self._profile.siblings:
169
+ material[name + "_dir"] = getattr(cfg, name + "_dir", "")
170
+ return hashlib.sha256(
171
+ json.dumps(material, sort_keys=True).encode()
172
+ ).hexdigest()
173
+
174
+ def inject_toolchain(self, cfg, env: dict[str, str]) -> None:
175
+ """Add the shared bundled clang++ bin/lib to a build or run environment.
176
+
177
+ Neither platform ships a system SYCL compiler: these modules build with
178
+ the intel/llvm clang++ provisioned into the shared SushiStack dependency
179
+ tree, so that bin must be on PATH -- and on Linux its lib on
180
+ LD_LIBRARY_PATH -- for the compiler and its SYCL runtime libraries to
181
+ resolve at build and run time.
182
+ """
183
+ try:
184
+ root = self._find_root()
185
+ except SystemExit:
186
+ return
187
+ bundle = cfg.deps_dir(root) / "toolchains" / "llvm-sycl"
188
+ if (bundle / "bin").is_dir():
189
+ prepend_path(env, "PATH", [str(bundle / "bin")])
190
+ if not cfg.is_windows and (bundle / "lib").is_dir():
191
+ prepend_path(env, "LD_LIBRARY_PATH", [str(bundle / "lib")])
192
+
193
+ # On Windows the runtime DLL pulls in vcpkg-installed dependencies
194
+ # (hwloc), so the vcpkg installed bin must be on PATH for the runtime
195
+ # DLL to load.
196
+ if cfg.is_windows:
197
+ vcpkg = cfg.resolved_vcpkg(root)
198
+ if vcpkg:
199
+ vcpkg_bin = Path(vcpkg) / "installed" / cfg.vcpkg_triplet / "bin"
200
+ if vcpkg_bin.is_dir():
201
+ prepend_path(env, "PATH", [str(vcpkg_bin)])
202
+
203
+ def load(self, cfg, build_dir: Path) -> dict[str, str]:
204
+ """Return the environment for build, test and run subprocesses.
205
+
206
+ Falls back to the current ``os.environ`` when no toolchain script is
207
+ configured: a machine with clang++ and MSVC already on PATH needs no
208
+ snapshot, and that is not an error.
209
+ """
210
+ build_dir.mkdir(parents=True, exist_ok=True)
211
+ cache_file = build_dir / self._cache_name
212
+ key = self.cache_key(cfg)
213
+
214
+ cached = read_cache(cache_file, key)
215
+ if cached is not None:
216
+ env = merge_env(os.environ, cached)
217
+ self.inject_toolchain(cfg, env)
218
+ return env
219
+
220
+ snapshot = snapshot_windows(cfg, self._console) if cfg.is_windows else None
221
+ if not snapshot:
222
+ env = dict(os.environ)
223
+ self.inject_toolchain(cfg, env)
224
+ return env
225
+
226
+ write_cache(cache_file, key, snapshot)
227
+ env = merge_env(os.environ, snapshot)
228
+ self.inject_toolchain(cfg, env)
229
+ return env