ohsh 0.1.0__py3-none-any.whl

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.
ohsh/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """ohsh (Ola's HDL Source Handler).
3
+
4
+ Finds the ``manifest.json`` files under a project directory, resolves the
5
+ dependencies of a top-level module, and writes each library's source files in
6
+ compile order, plus the order to compile the libraries in.
7
+
8
+ Example manifest file (``manifest.json``)::
9
+
10
+ {
11
+ "module": "module_name",
12
+ "sources": [
13
+ "source1.v",
14
+ "source2.v",
15
+ "source3.v"
16
+ ],
17
+ "dependencies": {
18
+ "work": ["module1", "module2"],
19
+ "lib_name": ["module3"]
20
+ }
21
+ }
22
+ """
23
+
24
+ __version__ = "0.1.0"
ohsh/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ from .cli import main
3
+
4
+ main()
ohsh/cli.py ADDED
@@ -0,0 +1,78 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+
3
+ import argparse
4
+ import pathlib
5
+
6
+ from . import __version__
7
+ from .core import run
8
+ from .utils import EXIT_CODE_DESCRIPTIONS, configure_logging
9
+
10
+
11
+ def log_file_path(value):
12
+ path = pathlib.Path(value)
13
+ if not path.parent.is_dir():
14
+ raise argparse.ArgumentTypeError(f"directory does not exist: {path.parent}")
15
+ return path
16
+
17
+
18
+ def format_exit_codes():
19
+ lines = [f" {code:>3} {description}" for code, description in EXIT_CODE_DESCRIPTIONS.items()]
20
+ return "exit codes:\n" + "\n".join(lines)
21
+
22
+
23
+ def build_parser(cwd):
24
+ parser = argparse.ArgumentParser(
25
+ prog="ohsh",
26
+ formatter_class=argparse.RawDescriptionHelpFormatter,
27
+ epilog=format_exit_codes(),
28
+ description="Resolve HDL module manifests into ordered, per-library source lists.",
29
+ )
30
+ parser.add_argument("module", help="name of the top-level module")
31
+ parser.add_argument(
32
+ "-t",
33
+ "--top-dir",
34
+ default=cwd,
35
+ help="directory to search for manifest files (default: current directory)",
36
+ )
37
+ parser.add_argument(
38
+ "-w",
39
+ "--work",
40
+ default="work",
41
+ help="library for the top module, which 'work' in its manifest refers to (default: work)",
42
+ )
43
+ parser.add_argument(
44
+ "-o",
45
+ "--output",
46
+ default=cwd,
47
+ help="directory for the .src lists and libraries.src, created if missing (default: current directory)",
48
+ )
49
+ parser.add_argument(
50
+ "-v",
51
+ "--verbose",
52
+ action="count",
53
+ default=0,
54
+ help="show progress (-v) or debug details (-vv), otherwise only warnings and errors",
55
+ )
56
+ parser.add_argument(
57
+ "--log-file",
58
+ type=log_file_path,
59
+ default=None,
60
+ metavar="PATH",
61
+ help="also write debug logs to this file",
62
+ )
63
+ parser.add_argument(
64
+ "--version",
65
+ action="version",
66
+ version=f"%(prog)s {__version__}",
67
+ )
68
+ return parser
69
+
70
+
71
+ def main():
72
+ cwd = pathlib.Path.cwd()
73
+ parser = build_parser(cwd)
74
+ args = parser.parse_args()
75
+ # Only the command line configures logging, so programs that call run()
76
+ # directly keep control of where ohsh log messages go.
77
+ configure_logging(verbosity=args.verbose, log_file=args.log_file)
78
+ run(args, cwd)
ohsh/core.py ADDED
@@ -0,0 +1,201 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ import json
3
+ import logging
4
+ import pathlib
5
+ import sys
6
+
7
+ from .utils import (
8
+ EXIT_CANNOT_CREATE_OUTPUT,
9
+ EXIT_CIRCULAR_DEPENDENCY,
10
+ EXIT_DATA_ERROR,
11
+ EXIT_DUPLICATE_MODULE,
12
+ EXIT_MANIFEST_NOT_FOUND,
13
+ EXIT_MODULE_NOT_FOUND,
14
+ EXIT_NO_INPUT,
15
+ CircularDependencyError,
16
+ InvalidManifestError,
17
+ MissingManifestError,
18
+ discover_manifests,
19
+ extract_dependencies,
20
+ find_duplicate_modules,
21
+ find_manifest,
22
+ order_libraries,
23
+ to_absolute_path,
24
+ validate_manifest,
25
+ validate_top_dir,
26
+ )
27
+
28
+ VERILOG_EXTENSIONS = {".v", ".sv", ".svp", ".vh", ".svh"}
29
+ VHDL_EXTENSIONS = {".vhd", ".vhdl", ".vo"}
30
+
31
+ LIBRARY_ORDER_FILE_NAME = "libraries.src"
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ def _exit_with_error(message, code):
37
+ logger.error(message)
38
+ sys.exit(code)
39
+
40
+
41
+ def run(args, cwd):
42
+ module = args.module
43
+ top_dir = args.top_dir
44
+ work = args.work
45
+
46
+ # If the top-level directory is a relative path, make it absolute.
47
+ top_dir = to_absolute_path(cwd, top_dir)
48
+
49
+ # Check if top-level is a directory and exists
50
+ if not validate_top_dir(top_dir):
51
+ _exit_with_error(
52
+ f"The specified top-level directory {top_dir} does not exist or is not a directory.",
53
+ EXIT_NO_INPUT,
54
+ )
55
+
56
+ # Find all files named "manifest.json" in the current working directory
57
+ all_manifest_files = discover_manifests(top_dir)
58
+
59
+ # parse all manifest files
60
+ manifest_data = []
61
+ for manifest_file in all_manifest_files:
62
+ try:
63
+ with open(manifest_file, encoding="utf-8") as file:
64
+ data = json.load(file)
65
+ validate_manifest(data)
66
+ except (json.JSONDecodeError, UnicodeDecodeError) as e:
67
+ _exit_with_error(f"Error parsing JSON from {manifest_file}: {e}", EXIT_DATA_ERROR)
68
+ except InvalidManifestError as e:
69
+ _exit_with_error(f"Invalid manifest {manifest_file}: {e}", EXIT_DATA_ERROR)
70
+ except OSError as e:
71
+ _exit_with_error(f"File error reading {manifest_file}: {e}", EXIT_NO_INPUT)
72
+ data["manifest_path"] = str(manifest_file.resolve())
73
+ manifest_data.append(data)
74
+ logger.debug(f"Parsed manifest file: {manifest_file}")
75
+
76
+ # Every lookup by module name below relies on the names being unique.
77
+ duplicates = find_duplicate_modules(manifest_data)
78
+ if duplicates:
79
+ listing = "\n".join(
80
+ f" {name}: {', '.join(sorted(paths))}" for name, paths in sorted(duplicates.items())
81
+ )
82
+ _exit_with_error(
83
+ f"Each module must be declared in exactly one manifest, but these are not:\n{listing}",
84
+ EXIT_DUPLICATE_MODULE,
85
+ )
86
+
87
+ top_manifest = find_manifest(manifest_data, module)
88
+ if top_manifest is None:
89
+ _exit_with_error(
90
+ f"The specified module {module} was not found in any manifest.", EXIT_MODULE_NOT_FOUND
91
+ )
92
+ logger.debug(f"Found module {module} in manifest.")
93
+
94
+ # Extract dependencies recursively
95
+ try:
96
+ dependencies = extract_dependencies(manifest_data, top_manifest, work)
97
+ except CircularDependencyError as e:
98
+ _exit_with_error(f"Circular dependency detected: {e}", EXIT_CIRCULAR_DEPENDENCY)
99
+ except MissingManifestError as e:
100
+ _exit_with_error(f"Missing dependency: {e}", EXIT_MANIFEST_NOT_FOUND)
101
+
102
+ # Remove duplicate entries
103
+ dependencies = list(dict.fromkeys(dependencies))
104
+ logger.debug(f"Dependencies for module {module}: {dependencies}")
105
+
106
+ # Append the top manifest module with the work library to the dependencies list
107
+ dependencies.append((work, module))
108
+
109
+ logger.debug(f"Complete module list: {dependencies}")
110
+
111
+ library_order = order_libraries(manifest_data, dependencies)
112
+ logger.info(f"Library compile order: {', '.join(library_order)}")
113
+
114
+ # Extract source file list from all modules in the final dependencies list
115
+ source_files_by_lib = {}
116
+ for lib_name, module in dependencies:
117
+ # Separate Verilog and VHDL files
118
+ verilog_sources = []
119
+ vhdl_sources = []
120
+
121
+ manifest = find_manifest(manifest_data, module)
122
+ manifest_path = pathlib.Path(manifest["manifest_path"]).parent
123
+ sources = [str(manifest_path / source) for source in manifest.get("sources", [])]
124
+ for source in sources:
125
+ extension = pathlib.Path(source).suffix.lower()
126
+ if extension in VERILOG_EXTENSIONS:
127
+ verilog_sources.append(source)
128
+ elif extension in VHDL_EXTENSIONS:
129
+ vhdl_sources.append(source)
130
+ else:
131
+ logger.warning(f"Skipping {source} in module {module}: unknown file extension")
132
+
133
+ # If the library already exists in the source_files_by_lib dictionary, append the source files
134
+ if lib_name in source_files_by_lib:
135
+ source_files_by_lib[lib_name]["verilog"].extend(verilog_sources)
136
+ source_files_by_lib[lib_name]["vhdl"].extend(vhdl_sources)
137
+ else: # Otherwise, create a new entry in the dictionary and add the source files
138
+ source_files_by_lib[lib_name] = {
139
+ "verilog": verilog_sources,
140
+ "vhdl": vhdl_sources,
141
+ }
142
+
143
+ # Remove duplicate source files while preserving order within each library
144
+ for lib_name, sources in source_files_by_lib.items():
145
+ sources["verilog"] = list(dict.fromkeys(sources["verilog"]))
146
+ sources["vhdl"] = list(dict.fromkeys(sources["vhdl"]))
147
+ logger.debug(
148
+ f"Source files for library {lib_name}: Verilog: {sources['verilog']}, VHDL: {sources['vhdl']}"
149
+ )
150
+
151
+ # Check that all source files exist
152
+ missing_files = []
153
+ for source_files in source_files_by_lib.values():
154
+ for source_file in source_files["verilog"] + source_files["vhdl"]:
155
+ if not pathlib.Path(source_file).exists():
156
+ missing_files.append(source_file)
157
+
158
+ if missing_files:
159
+ _exit_with_error(f"The following source files do not exist: {missing_files}", EXIT_NO_INPUT)
160
+
161
+ source_files_by_lib = {lib_name: source_files_by_lib[lib_name] for lib_name in library_order}
162
+
163
+ # Write the source files to output files, one file per library
164
+ output_dir = pathlib.Path(args.output)
165
+ try:
166
+ output_dir.mkdir(parents=True, exist_ok=True)
167
+ except OSError as e:
168
+ _exit_with_error(
169
+ f"Cannot create output directory {output_dir}: {e}", EXIT_CANNOT_CREATE_OUTPUT
170
+ )
171
+ for lib_name, source_files in source_files_by_lib.items():
172
+ verilog_output_file = output_dir / f"{lib_name}_verilog.src"
173
+ vhdl_output_file = output_dir / f"{lib_name}_vhdl.src"
174
+
175
+ if source_files["verilog"]:
176
+ with open(verilog_output_file, "w", encoding="utf-8") as f:
177
+ for source_file in source_files["verilog"]:
178
+ f.write(f"{source_file}\n")
179
+ logger.info(
180
+ f"Wrote {len(source_files['verilog'])} Verilog files for library {lib_name} "
181
+ f"to {verilog_output_file}"
182
+ )
183
+ else:
184
+ logger.debug(f"No Verilog source files for library {lib_name}, skipping file creation.")
185
+
186
+ if source_files["vhdl"]:
187
+ with open(vhdl_output_file, "w", encoding="utf-8") as f:
188
+ for source_file in source_files["vhdl"]:
189
+ f.write(f"{source_file}\n")
190
+ logger.info(
191
+ f"Wrote {len(source_files['vhdl'])} VHDL files for library {lib_name} "
192
+ f"to {vhdl_output_file}"
193
+ )
194
+ else:
195
+ logger.debug(f"No VHDL source files for library {lib_name}, skipping file creation.")
196
+
197
+ library_order_file = output_dir / LIBRARY_ORDER_FILE_NAME
198
+ with open(library_order_file, "w", encoding="utf-8") as f:
199
+ for lib_name in library_order:
200
+ f.write(f"{lib_name}\n")
201
+ logger.info(f"Wrote library compile order to {library_order_file}")
ohsh/utils.py ADDED
@@ -0,0 +1,242 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+
3
+ import logging
4
+ import pathlib
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ CONSOLE_HANDLER_NAME = "ohsh-console"
9
+ CONSOLE_LEVEL_BY_VERBOSITY = {0: logging.WARNING, 1: logging.INFO}
10
+
11
+ # Exit codes follow the Unix conventions where one exists: 1 for a general
12
+ # error, 2 for usage errors (raised by argparse), and BSD sysexits.h (64-78) for
13
+ # bad input and output. Errors specific to ohsh start at 100, clear of those
14
+ # ranges and of the 126+ codes that shells reserve.
15
+ EXIT_SUCCESS = 0
16
+ EXIT_UNEXPECTED_ERROR = 1
17
+ EXIT_USAGE = 2
18
+ EXIT_DATA_ERROR = 65
19
+ EXIT_NO_INPUT = 66
20
+ EXIT_CANNOT_CREATE_OUTPUT = 73
21
+ EXIT_MODULE_NOT_FOUND = 100
22
+ EXIT_MANIFEST_NOT_FOUND = 101
23
+ EXIT_CIRCULAR_DEPENDENCY = 102
24
+ EXIT_DUPLICATE_MODULE = 103
25
+
26
+ EXIT_CODE_DESCRIPTIONS = {
27
+ EXIT_SUCCESS: "success",
28
+ EXIT_UNEXPECTED_ERROR: "unexpected error",
29
+ EXIT_USAGE: "invalid command-line arguments",
30
+ EXIT_DATA_ERROR: "a manifest is not valid JSON or has the wrong structure",
31
+ EXIT_NO_INPUT: "top directory, manifest or source file missing or unreadable",
32
+ EXIT_CANNOT_CREATE_OUTPUT: "output directory cannot be created",
33
+ EXIT_MODULE_NOT_FOUND: "top module not found in any manifest",
34
+ EXIT_MANIFEST_NOT_FOUND: "a dependency has no manifest",
35
+ EXIT_CIRCULAR_DEPENDENCY: "modules depend on each other in a loop",
36
+ EXIT_DUPLICATE_MODULE: "a module name is declared in more than one manifest",
37
+ }
38
+
39
+
40
+ class CircularDependencyError(Exception):
41
+ def __init__(self, cycle):
42
+ self.cycle = cycle
43
+ super().__init__(" -> ".join(cycle))
44
+
45
+
46
+ class MissingManifestError(Exception):
47
+ def __init__(self, module, required_by):
48
+ self.module = module
49
+ self.required_by = required_by
50
+ super().__init__(f"no manifest found for module {module} (required by {required_by})")
51
+
52
+
53
+ class InvalidManifestError(Exception):
54
+ pass
55
+
56
+
57
+ def _is_list_of_strings(value):
58
+ return isinstance(value, list) and all(isinstance(item, str) for item in value)
59
+
60
+
61
+ def validate_manifest(manifest):
62
+ """Raise ``InvalidManifestError`` naming the first structural problem in ``manifest``.
63
+
64
+ ``sources`` and ``dependencies`` are optional. Unknown keys are ignored.
65
+ """
66
+ if not isinstance(manifest, dict):
67
+ raise InvalidManifestError("the top level must be a JSON object")
68
+ if not isinstance(manifest.get("module"), str) or not manifest["module"]:
69
+ raise InvalidManifestError('"module" must be a non-empty string')
70
+ if not _is_list_of_strings(manifest.get("sources", [])):
71
+ raise InvalidManifestError('"sources" must be a list of file names')
72
+ dependencies = manifest.get("dependencies", {})
73
+ if not isinstance(dependencies, dict) or not all(
74
+ _is_list_of_strings(modules) for modules in dependencies.values()
75
+ ):
76
+ raise InvalidManifestError('"dependencies" must map library names to lists of module names')
77
+
78
+
79
+ def find_duplicate_modules(manifest_data):
80
+ """Return {module: [manifest paths]} for every module declared more than once."""
81
+ paths_by_module = {}
82
+ for manifest in manifest_data:
83
+ paths_by_module.setdefault(manifest["module"], []).append(manifest["manifest_path"])
84
+ return {module: paths for module, paths in paths_by_module.items() if len(paths) > 1}
85
+
86
+
87
+ def find_manifest(manifest_data, module):
88
+ return next((m for m in manifest_data if m.get("module") == module), None)
89
+
90
+
91
+ def resolve_library_name(declared_library, current_library):
92
+ # In a manifest, 'work' means the library the module itself is compiled into.
93
+ return current_library if declared_library == "work" else declared_library
94
+
95
+
96
+ def extract_dependencies(manifest_data, top_manifest, work):
97
+ """Return every module ``top_manifest`` depends on, directly or indirectly.
98
+
99
+ The result is a list of (library, module) pairs in compile order: each module
100
+ comes after all the modules it depends on, and each pair appears once. The
101
+ top module itself is not included. A circular dependency has no valid compile
102
+ order, so it raises ``CircularDependencyError`` naming the modules in the cycle.
103
+ A dependency without a manifest raises ``MissingManifestError``.
104
+ """
105
+ collected_deps = []
106
+ dependency_chain = []
107
+ resolved = set()
108
+
109
+ def _collect_dependencies_of(manifest, library):
110
+ module_name = manifest.get("module")
111
+ # The same module reached through another library resolves its 'work'
112
+ # dependencies differently, so only skip exact (library, module) repeats.
113
+ if (library, module_name) in resolved:
114
+ return
115
+ logger.debug(f"Extracting dependencies for {module_name}")
116
+ dependency_chain.append(module_name)
117
+
118
+ for lib_name, modules in manifest.get("dependencies", {}).items():
119
+ lib_name = resolve_library_name(lib_name, library)
120
+ for module in modules:
121
+ logger.debug(f"Processing dependency {module} in library {lib_name}")
122
+ if module in dependency_chain:
123
+ cycle_start = dependency_chain.index(module)
124
+ raise CircularDependencyError(dependency_chain[cycle_start:] + [module])
125
+
126
+ # Recurse first so deeper dependencies are collected before this one.
127
+ dep_manifest = find_manifest(manifest_data, module)
128
+ if dep_manifest is None:
129
+ raise MissingManifestError(module, required_by=module_name)
130
+ _collect_dependencies_of(dep_manifest, lib_name)
131
+
132
+ dep_tuple = (lib_name, module)
133
+ if dep_tuple not in collected_deps:
134
+ collected_deps.append(dep_tuple)
135
+
136
+ dependency_chain.pop()
137
+ resolved.add((library, module_name))
138
+
139
+ _collect_dependencies_of(top_manifest, work)
140
+ return collected_deps
141
+
142
+
143
+ def order_libraries(manifest_data, dependencies):
144
+ """Return the libraries used in ``dependencies`` in compile order.
145
+
146
+ Each library comes after the libraries its modules depend on. When libraries
147
+ depend on each other in a loop, no such order exists: a warning names the loop
148
+ and a best-effort order is returned, which tools that sort files themselves
149
+ can still use.
150
+ """
151
+ libraries = list(dict.fromkeys(library for library, _ in dependencies))
152
+ used_libraries = {library: set() for library in libraries}
153
+ for library, module in dependencies:
154
+ manifest = find_manifest(manifest_data, module)
155
+ for declared_library, modules in manifest.get("dependencies", {}).items():
156
+ used_library = resolve_library_name(declared_library, library)
157
+ if modules and used_library != library:
158
+ used_libraries[library].add(used_library)
159
+
160
+ ordered = []
161
+ while len(ordered) < len(libraries):
162
+ remaining = [library for library in libraries if library not in ordered]
163
+ ready = [library for library in remaining if used_libraries[library] <= set(ordered)]
164
+ if not ready:
165
+ loop = _find_library_loop(remaining[0], used_libraries, ordered)
166
+ logger.warning(
167
+ f"Libraries depend on each other in a loop ({' -> '.join(loop)}), so no "
168
+ "library order is valid. Writing a best-effort order: tools that compile "
169
+ "one library at a time may fail."
170
+ )
171
+ ready = remaining
172
+ ordered.append(ready[0])
173
+ return ordered
174
+
175
+
176
+ def _find_library_loop(start, used_libraries, ordered):
177
+ # Every library still unordered uses at least one other unordered library,
178
+ # so following those edges from any of them must eventually revisit one.
179
+ path = [start]
180
+ while True:
181
+ next_library = min(used_libraries[path[-1]] - set(ordered))
182
+ if next_library in path:
183
+ return path[path.index(next_library) :] + [next_library]
184
+ path.append(next_library)
185
+
186
+
187
+ def validate_top_dir(top_dir):
188
+ return pathlib.Path(top_dir).is_dir()
189
+
190
+
191
+ def to_absolute_path(cwd, path):
192
+ """Return ``path`` as an absolute path, resolving a relative one against ``cwd``."""
193
+ path = pathlib.Path(path)
194
+ if not path.is_absolute():
195
+ return (pathlib.Path(cwd) / path).resolve()
196
+ return path
197
+
198
+
199
+ def configure_logging(verbosity=0, log_file=None):
200
+ """Configure logging for the ``ohsh`` package.
201
+
202
+ Handlers are attached to the package logger (``ohsh``) so that messages from
203
+ every submodule are captured. Console output goes to stderr and shows
204
+ warnings and errors only, INFO messages with ``verbosity`` 1, and DEBUG
205
+ messages with 2 or more. A file handler, which always records DEBUG, is only
206
+ added when ``log_file`` is given.
207
+ """
208
+ pkg_logger = logging.getLogger("ohsh")
209
+ pkg_logger.setLevel(logging.DEBUG)
210
+ # Our handlers already emit everything, so a root handler set up by the
211
+ # host application (e.g. logging.basicConfig) would print each line twice.
212
+ pkg_logger.propagate = False
213
+
214
+ # Avoid attaching duplicate handlers if called more than once. Look for our
215
+ # own handler by name: other code (e.g. pytest capture) may attach its own.
216
+ if any(h.get_name() == CONSOLE_HANDLER_NAME for h in pkg_logger.handlers):
217
+ return pkg_logger
218
+
219
+ formatter = logging.Formatter("ohsh - %(levelname)s - %(message)s")
220
+
221
+ console_handler = logging.StreamHandler()
222
+ console_handler.set_name(CONSOLE_HANDLER_NAME)
223
+ console_handler.setLevel(CONSOLE_LEVEL_BY_VERBOSITY.get(verbosity, logging.DEBUG))
224
+ console_handler.setFormatter(formatter)
225
+ pkg_logger.addHandler(console_handler)
226
+
227
+ if log_file:
228
+ file_handler = logging.FileHandler(log_file)
229
+ file_handler.setLevel(logging.DEBUG)
230
+ file_handler.setFormatter(formatter)
231
+ pkg_logger.addHandler(file_handler)
232
+
233
+ return pkg_logger
234
+
235
+
236
+ def discover_manifests(top_dir):
237
+ logger.debug(f"Discovering manifest files in {top_dir}")
238
+ manifest_files = list(pathlib.Path(top_dir).rglob("manifest*.json"))
239
+ for manifest in manifest_files:
240
+ logger.debug(f"Found manifest file: {manifest}")
241
+ logger.info(f"Found {len(manifest_files)} manifest files in {top_dir}")
242
+ return manifest_files
@@ -0,0 +1,153 @@
1
+ Metadata-Version: 2.4
2
+ Name: ohsh
3
+ Version: 0.1.0
4
+ Summary: Resolve HDL module manifests into ordered, per-library source lists and a library compile order.
5
+ Author: Ola Groettvik
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/logvik-org/ohsh
8
+ Project-URL: Repository, https://github.com/logvik-org/ohsh
9
+ Project-URL: Issues, https://github.com/logvik-org/ohsh/issues
10
+ Project-URL: Changelog, https://github.com/logvik-org/ohsh/blob/main/CHANGELOG.md
11
+ Keywords: hdl,verilog,vhdl,systemverilog,fpga,eda,dependency,manifest,hog
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)
24
+ Classifier: Topic :: Software Development :: Build Tools
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ License-File: NOTICE
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.0; extra == "dev"
31
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
32
+ Requires-Dist: build>=1.0; extra == "dev"
33
+ Requires-Dist: twine>=5.0; extra == "dev"
34
+ Requires-Dist: pre-commit>=3.0; extra == "dev"
35
+ Provides-Extra: examples
36
+ Requires-Dist: cocotb==2.1.0; extra == "examples"
37
+ Requires-Dist: vunit-hdl==4.7.1; extra == "examples"
38
+ Dynamic: license-file
39
+
40
+ # ohsh - Ola's HDL Source Handler
41
+
42
+ [![CI](https://github.com/logvik-org/ohsh/actions/workflows/ci.yml/badge.svg)](https://github.com/logvik-org/ohsh/actions/workflows/ci.yml)
43
+ [![Integrations](https://github.com/logvik-org/ohsh/actions/workflows/integration.yml/badge.svg)](https://github.com/logvik-org/ohsh/actions/workflows/integration.yml)
44
+ [![PyPI](https://img.shields.io/pypi/v/ohsh.svg)](https://pypi.org/project/ohsh/)
45
+ [![Python](https://img.shields.io/pypi/pyversions/ohsh.svg)](https://pypi.org/project/ohsh/)
46
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/logvik-org/ohsh/blob/main/LICENSE)
47
+
48
+ **ohsh** is a small, deliberately humble command-line tool that figures out, in
49
+ the right order, which HDL (Verilog / SystemVerilog / VHDL) source files your
50
+ design needs - by reading simple per-module `manifest.json` files and resolving
51
+ their dependencies.
52
+
53
+ It is a *companion* to the big build flows (like [hog](https://hog.readthedocs.io),
54
+ Vivado, Quartus, Questa, cocotb, VUnit, …), not a replacement for them. ohsh
55
+ just answers one question well - *"what files, in what order, for which
56
+ libraries?"* - and hands you plain `.src` lists you can feed anywhere.
57
+
58
+ > So simple it's an *oh sh… that was easy* moment. 🙂
59
+
60
+ ---
61
+
62
+ ## Features
63
+
64
+ - 🔍 Auto-discovers HDL module manifests anywhere under a project tree.
65
+ - 📂 Resolves module dependencies recursively, across libraries.
66
+ - 🔁 Detects circular dependencies and exits with an error naming the cycle.
67
+ - 📝 Emits ordered, per-library source lists for Verilog and VHDL.
68
+ - 📚 Writes the order to compile the libraries in.
69
+ - ✅ Validates that every referenced source file actually exists.
70
+ - 🐍 Pure Python, zero runtime dependencies.
71
+
72
+ ## Installation
73
+
74
+ ```bash
75
+ pip install ohsh
76
+ ```
77
+
78
+ Or from a clone:
79
+
80
+ ```bash
81
+ git clone https://github.com/logvik-org/ohsh.git
82
+ cd ohsh
83
+ pip install .
84
+ ```
85
+
86
+ ## Usage
87
+
88
+ ```bash
89
+ ohsh [OPTIONS] MODULE
90
+ ```
91
+
92
+ ohsh will:
93
+ 1. Search for all `manifest*.json` files starting from `--top-dir`.
94
+ 2. Resolve dependencies for `MODULE` (the top-level).
95
+ 3. Generate ordered Verilog and VHDL source lists per library.
96
+ 4. Write them as `<lib>_verilog.src` / `<lib>_vhdl.src` in the output directory.
97
+ 5. Write the library compile order to `libraries.src`.
98
+
99
+ ### Options
100
+
101
+ | Option | Description | Default |
102
+ |---------------------|------------------------------------------------------------------------|--------------|
103
+ | `-t`, `--top-dir` | Project top-level directory, the base for manifest discovery. | cwd |
104
+ | `-w`, `--work` | Library for the top module, which `work` in its manifest refers to. | `work` |
105
+ | `-o`, `--output` | Directory for the `.src` lists and `libraries.src`, created if missing. | cwd |
106
+ | `-v`, `--verbose` | Show progress (`-v`) or debug details (`-vv`). | quiet |
107
+ | `--log-file PATH` | Also write logs to a file (no log file is written by default). | none |
108
+ | `--version` | Print version and exit. | |
109
+ | `-h`, `--help` | Show help and exit. | |
110
+
111
+ ### Example
112
+
113
+ ```bash
114
+ ohsh -t /path/to/hdl_project -w mylib -o ./src_lists top_module
115
+ ```
116
+
117
+ Produces:
118
+
119
+ ```
120
+ src_lists/
121
+ ├── libraries.src
122
+ ├── mylib_verilog.src
123
+ └── mylib_vhdl.src
124
+ ```
125
+
126
+ Each `<lib>_verilog.src` / `<lib>_vhdl.src` file contains absolute paths to the
127
+ source files, one per line, in compilation order.
128
+
129
+ `libraries.src` lists the library names, one per line, in the order to compile
130
+ them: each library comes after the libraries it uses. Compile the libraries in
131
+ this order rather than hard-coding it. If libraries depend on each other in a
132
+ loop (a module in `libA` uses `libB` and a module in `libB` uses `libA`), no
133
+ such order exists. ohsh then logs a warning and writes a best-effort order,
134
+ which works for tools that sort files themselves (such as Vivado or Quartus
135
+ projects) but may fail with tools that compile one library at a time.
136
+
137
+ ## Documentation
138
+
139
+ - [Manifest file format](https://github.com/logvik-org/ohsh/blob/main/docs/manifest-format.md)
140
+ - [Exit codes](https://github.com/logvik-org/ohsh/blob/main/docs/exit-codes.md)
141
+ - [Integrations with simulators and build tools](https://github.com/logvik-org/ohsh/blob/main/docs/integrations.md)
142
+ - [Contributing and development](https://github.com/logvik-org/ohsh/blob/main/CONTRIBUTING.md)
143
+
144
+ ## License
145
+
146
+ Licensed under the **Apache License 2.0**. See [LICENSE](https://github.com/logvik-org/ohsh/blob/main/LICENSE) and
147
+ [NOTICE](https://github.com/logvik-org/ohsh/blob/main/NOTICE).
148
+
149
+ ## Author
150
+
151
+ **Ola Groettvik** - [GitHub](https://github.com/olagrottvik)
152
+
153
+ Contributions, issues, and suggestions are welcome!
@@ -0,0 +1,12 @@
1
+ ohsh/__init__.py,sha256=SUwu4cC9AvJ5ygpbvCf_OdlXrcFqKsm8KcUW9PVELH8,626
2
+ ohsh/__main__.py,sha256=joODZGnsQelRyR4fxFIThmMeoZDCwcNUjHraEK0Rrcc,68
3
+ ohsh/cli.py,sha256=_Q11w30QSoDAwm5AgW0rmvG-UJmlVLbCkugsRPOR4Ak,2301
4
+ ohsh/core.py,sha256=w3HhaF8OHQi6TLutLJP-QS1nIi4Q_d8FFKVTa-CEIYk,7932
5
+ ohsh/utils.py,sha256=x4gCFF9-JvCBsA1WBTNzaxWOJh11L-ngn7Rm2eYtw9Y,10076
6
+ ohsh-0.1.0.dist-info/licenses/LICENSE,sha256=zWm71hiYF505c5M38iGCPUfT3ZiyIHtJpdU_3BSTMV4,11348
7
+ ohsh-0.1.0.dist-info/licenses/NOTICE,sha256=nWvVPkA-v_U_iOMLDgVhUuXVCAxJGzAt9fWUXSZuLuc,344
8
+ ohsh-0.1.0.dist-info/METADATA,sha256=SjQr0sUbiVAkmVnYyNpSyfnCOklpx1V8pJzAhWAUdfE,6593
9
+ ohsh-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
10
+ ohsh-0.1.0.dist-info/entry_points.txt,sha256=PsMSxOQ_FVtCksSjd33iMpgFAXwprS6sAcTuhuXl-30,39
11
+ ohsh-0.1.0.dist-info/top_level.txt,sha256=7j-bMBksgpWmaP9J1OH6R5a0rd23Cueg2fCVyFD9ZS0,5
12
+ ohsh-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ohsh = ohsh.cli:main
@@ -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 Derivative
95
+ 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 2024-2026 Ola Groettvik
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,10 @@
1
+ ohsh - Ola's HDL Source Handler
2
+ Copyright 2024-2026 Ola Groettvik
3
+
4
+ This product includes software developed by Ola Groettvik.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License");
7
+ you may not use this file except in compliance with the License.
8
+ You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
@@ -0,0 +1 @@
1
+ ohsh