sigil-cli 1.1.1__tar.gz → 1.3.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 (38) hide show
  1. {sigil_cli-1.1.1/src/sigil_cli.egg-info → sigil_cli-1.3.0}/PKG-INFO +61 -12
  2. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/README.md +60 -11
  3. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/pyproject.toml +4 -2
  4. sigil_cli-1.3.0/src/sigil/__init__.py +31 -0
  5. sigil_cli-1.3.0/src/sigil/__main__.py +40 -0
  6. sigil_cli-1.3.0/src/sigil/cli_tools/tree.py +40 -0
  7. sigil_cli-1.3.0/src/sigil/cli_tools/validate.py +116 -0
  8. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/entrypoint.py +18 -5
  9. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/models/argument.py +12 -10
  10. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/models/command.py +18 -1
  11. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/stages/builder.py +21 -9
  12. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/stages/resolver.py +20 -6
  13. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/stages/script_loader.py +22 -6
  14. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/stages/yaml_reader.py +26 -14
  15. {sigil_cli-1.1.1 → sigil_cli-1.3.0/src/sigil_cli.egg-info}/PKG-INFO +61 -12
  16. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil_cli.egg-info/SOURCES.txt +5 -1
  17. sigil_cli-1.3.0/tests/test_cli_tree.py +80 -0
  18. sigil_cli-1.3.0/tests/test_cli_validate.py +268 -0
  19. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/tests/test_integration.py +46 -1
  20. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/tests/test_reader.py +23 -17
  21. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/tests/test_resolver.py +18 -1
  22. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/tests/test_scriptloader.py +1 -1
  23. sigil_cli-1.1.1/src/sigil/__init__.py +0 -27
  24. sigil_cli-1.1.1/src/sigil/__main__.py +0 -20
  25. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/LICENSE +0 -0
  26. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/setup.cfg +0 -0
  27. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/cli_tools/__init__.py +0 -0
  28. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/cli_tools/init.py +0 -0
  29. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/models/__init__.py +0 -0
  30. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/models/argparser.py +0 -0
  31. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/models/script.py +0 -0
  32. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil/stages/__init__.py +0 -0
  33. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil_cli.egg-info/dependency_links.txt +0 -0
  34. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil_cli.egg-info/entry_points.txt +0 -0
  35. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil_cli.egg-info/requires.txt +0 -0
  36. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/src/sigil_cli.egg-info/top_level.txt +0 -0
  37. {sigil_cli-1.1.1 → sigil_cli-1.3.0}/tests/test_builder.py +0 -0
  38. /sigil_cli-1.1.1/tests/test_cli_tools.py → /sigil_cli-1.3.0/tests/test_cli_init.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sigil-cli
3
- Version: 1.1.1
3
+ Version: 1.3.0
4
4
  Summary: Configuration driven CLI builder with subcommands and script loading
5
5
  Author-email: Kenzo Staelens <kenzostael@gmail.com>
6
6
  License: MIT
@@ -32,10 +32,11 @@ Dynamic: license-file
32
32
 
33
33
  > Declarative argparse, without the CLI boilerplate.
34
34
 
35
- Sigil is a lightweight, declarative CLI framework for Python. Define your command tree in YAML (or any other format), and sigil builds the `argparse` parser on the fly. Complete with subcommands and dynamic script loading.
35
+ Sigil is a lightweight, declarative CLI framework for Python. Define your command tree in YAML (or any other format),
36
+ and sigil builds the `argparse` parser on the fly. Complete with subcommands and dynamic script loading.
36
37
  It plays nicely with `argcomplete` out of the box.
37
38
 
38
- [![pypi](https://badge.fury.io/py/sigil-cli.svg)](https://pypi.python.org/pypi/sigil-cli)
39
+ [![PyPI Version](https://img.shields.io/pypi/v/sigil-cli)](https://pypi.python.org/pypi/sigil-cli)
39
40
  [![PyPI Wheel](https://img.shields.io/pypi/wheel/sigil-cli.svg)](https://pypi.org/project/sigil-cli/)
40
41
  [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/release/python-3100/)
41
42
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
@@ -43,6 +44,10 @@ It plays nicely with `argcomplete` out of the box.
43
44
  [![Tests](https://github.com/kenzo-staelens/sigil/actions/workflows/tests.yml/badge.svg)](https://github.com/kenzo-staelens/sigil/actions/workflows/tests.yml)
44
45
  [![Coverage Status](https://coveralls.io/repos/github/kenzo-staelens/sigil/badge.svg?branch=main)](https://coveralls.io/github/kenzo-staelens/sigil?branch=main)
45
46
 
47
+ <div align="center">
48
+ <sub>in production since April 2026</sub>
49
+ </div>
50
+
46
51
  ---
47
52
 
48
53
  ## Features
@@ -70,17 +75,24 @@ your command structure modular and flexible.
70
75
  pip install sigil-cli
71
76
  ```
72
77
 
73
- or include argcomplete
78
+ *optionally include argcomplete with `sigil-cli[completion]`*
79
+
80
+ The `init` command generates a project directory with a sample configuration and entrypoint:
74
81
 
75
82
  ```bash
76
- pip install sigil-cli[completion]
83
+ sigil init demo
84
+ sigil validate demo/ # optional, should not output anything for correct configurations
85
+ cd demo
86
+ python main.py --help
77
87
  ```
78
88
 
89
+ For a full walkthrough with custom commands and arguments, jump to the Quick Start below.
90
+
79
91
  ### 0. Recommended file structure
80
92
 
81
93
  ```text
82
94
  project_root/
83
- ├── mycli.py # drop‑in entry script (alias this)
95
+ ├── mycli.py # drop‑in bootstrap script (alias this)
84
96
  ├── manifest.yml # lists all YAML config files to load
85
97
  ├── yml/
86
98
  │ ├── root.yml # root command definition
@@ -91,12 +103,15 @@ project_root/
91
103
  └── ... # other scripts
92
104
  ```
93
105
 
106
+ ps: don't shoot yourself in the foot, don't symlink the bootstrap script.
107
+
94
108
  ### 1. Entry script
95
109
 
96
110
  Create `mycli.py`:
97
111
 
98
112
  ```python
99
113
  #!/usr/bin/env python3
114
+ # PYTHON_ARGCOMPLETE_OK
100
115
  from pathlib import Path
101
116
  from sigil import run_from_config
102
117
 
@@ -166,7 +181,7 @@ chmod +x mycli.py
166
181
 
167
182
  ## Configuration Reference
168
183
 
169
- ### Root
184
+ ### Root Command
170
185
 
171
186
  | Field | Description |
172
187
  | --- | --- |
@@ -180,12 +195,14 @@ chmod +x mycli.py
180
195
  | `name` | Subcommand name |
181
196
  | `parent` | Parent command (must exist elsewhere in a config) |
182
197
  | `help` | Help text for this subcommand |
183
- | `script` | Python module name (without `.py`) inside `script_dir` or as absolute path |
198
+ | `script` | Python module name (without `.py`) inside `script_dir`, absolute paths supported |
184
199
  | `args` | List of argument definitions (see below) |
185
- | `default` | If `true`, this subcommand is used when no subcommand is given |
186
- | any other parser kwarg | except for `dest` and `formatter_class` they are all supported |
200
+ | `default` | If `True`, this subcommand is used when no subcommand is given |
201
+ | `load` | If `False` skips this command (or top level object) from being loaded into the command tree (default `True`) |
202
+ | any other parser kwarg | except for `dest`, `parents` and `formatter_class` they are all supported |
187
203
 
188
- Note that `parent` does not refer to argparse's parent parameter but is only used to resolve the parser tree. Parser (multi-)inheritance isn't supported but can be emulated by adding arguments to `this` command's parents in the tree.
204
+ Note that `parent` does not refer to argparse's `parents` parameter but is only used to resolve the parser tree.
205
+ Parser (multi-)inheritance isn't supported but can be emulated by adding arguments to `parent` commands in the tree.
189
206
 
190
207
  ### Argument
191
208
 
@@ -215,10 +232,42 @@ Groups and mutex groups are also suppored via the "kind" parameter (defaults to
215
232
  The `name` field can be `--flag` for flags or a string for positional arguments.
216
233
  Both literal string and list of strings are supported.
217
234
 
235
+ Types (`type:`) only supports python builtins
236
+
237
+ ### Script files
238
+
239
+ Each script files have as only requirement that they need to define a
240
+ `def run(args: argparse.Namespace, ctx: dict[str, Any]) -> None` method.
241
+
242
+ args is the by argparse supplied namespace (parsed with parse_known_args), any additional args can be found in `ctx['other_args']`
243
+
244
+ scripts run in sequence from command -> subcommand -> sub sub command -> ... and each may add to,
245
+ remove or otherwise modify args.namespace and ctx to enrich or modify the behaviour of supsequent scripts.
246
+
247
+ ## Sigil CLI Commands
248
+
249
+ `sigil` ships with its own lightweight toolbelt to manage your projects:
250
+
251
+ | Command | Purpose |
252
+ | --- | --- |
253
+ | `sigil init [project_name]` | Creates a new project folder with a sample ready-to-run Python entrypoint. |
254
+ | `sigil validate [project_path]` | Checks your sigil definition for schema errors and missing references. Run this after heavy edits to catch mistakes early. |
255
+ | `sigil tree [project_path]` | Print the command structure of a sigil. |
256
+
257
+ *(Note: Your generated CLI (the one you build with Sigil) is completely separate from the `sigil` management
258
+ commands above. You alias and run `main.py`. the `sigil` prefix is a different namespace.)*
259
+
260
+ ### Misc
261
+
262
+ `load_ignore` may be used to detaching commands from the command tree for any purpose
263
+ (deprecation, development, etc) or for non schema-compliant objects at the top level of a file, this may be useful to
264
+ define anchors or references that should not directly be read as a command.
265
+
218
266
  ## Tab‑Completion (argcomplete)
219
267
 
220
268
  Sigil registers itself with `argcomplete` automatically if available on your system.
221
- To enable completion, install [argcomplete](https://github.com/kislyuk/argcomplete) and activate it for your entry script:
269
+ To enable completion, install [argcomplete](https://github.com/kislyuk/argcomplete) and activate it for your entry
270
+ script (or use the builtin argcomplete comment):
222
271
 
223
272
  ```bash
224
273
  pip install argcomplete
@@ -2,10 +2,11 @@
2
2
 
3
3
  > Declarative argparse, without the CLI boilerplate.
4
4
 
5
- Sigil is a lightweight, declarative CLI framework for Python. Define your command tree in YAML (or any other format), and sigil builds the `argparse` parser on the fly. Complete with subcommands and dynamic script loading.
5
+ Sigil is a lightweight, declarative CLI framework for Python. Define your command tree in YAML (or any other format),
6
+ and sigil builds the `argparse` parser on the fly. Complete with subcommands and dynamic script loading.
6
7
  It plays nicely with `argcomplete` out of the box.
7
8
 
8
- [![pypi](https://badge.fury.io/py/sigil-cli.svg)](https://pypi.python.org/pypi/sigil-cli)
9
+ [![PyPI Version](https://img.shields.io/pypi/v/sigil-cli)](https://pypi.python.org/pypi/sigil-cli)
9
10
  [![PyPI Wheel](https://img.shields.io/pypi/wheel/sigil-cli.svg)](https://pypi.org/project/sigil-cli/)
10
11
  [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/release/python-3100/)
11
12
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
@@ -13,6 +14,10 @@ It plays nicely with `argcomplete` out of the box.
13
14
  [![Tests](https://github.com/kenzo-staelens/sigil/actions/workflows/tests.yml/badge.svg)](https://github.com/kenzo-staelens/sigil/actions/workflows/tests.yml)
14
15
  [![Coverage Status](https://coveralls.io/repos/github/kenzo-staelens/sigil/badge.svg?branch=main)](https://coveralls.io/github/kenzo-staelens/sigil?branch=main)
15
16
 
17
+ <div align="center">
18
+ <sub>in production since April 2026</sub>
19
+ </div>
20
+
16
21
  ---
17
22
 
18
23
  ## Features
@@ -40,17 +45,24 @@ your command structure modular and flexible.
40
45
  pip install sigil-cli
41
46
  ```
42
47
 
43
- or include argcomplete
48
+ *optionally include argcomplete with `sigil-cli[completion]`*
49
+
50
+ The `init` command generates a project directory with a sample configuration and entrypoint:
44
51
 
45
52
  ```bash
46
- pip install sigil-cli[completion]
53
+ sigil init demo
54
+ sigil validate demo/ # optional, should not output anything for correct configurations
55
+ cd demo
56
+ python main.py --help
47
57
  ```
48
58
 
59
+ For a full walkthrough with custom commands and arguments, jump to the Quick Start below.
60
+
49
61
  ### 0. Recommended file structure
50
62
 
51
63
  ```text
52
64
  project_root/
53
- ├── mycli.py # drop‑in entry script (alias this)
65
+ ├── mycli.py # drop‑in bootstrap script (alias this)
54
66
  ├── manifest.yml # lists all YAML config files to load
55
67
  ├── yml/
56
68
  │ ├── root.yml # root command definition
@@ -61,12 +73,15 @@ project_root/
61
73
  └── ... # other scripts
62
74
  ```
63
75
 
76
+ ps: don't shoot yourself in the foot, don't symlink the bootstrap script.
77
+
64
78
  ### 1. Entry script
65
79
 
66
80
  Create `mycli.py`:
67
81
 
68
82
  ```python
69
83
  #!/usr/bin/env python3
84
+ # PYTHON_ARGCOMPLETE_OK
70
85
  from pathlib import Path
71
86
  from sigil import run_from_config
72
87
 
@@ -136,7 +151,7 @@ chmod +x mycli.py
136
151
 
137
152
  ## Configuration Reference
138
153
 
139
- ### Root
154
+ ### Root Command
140
155
 
141
156
  | Field | Description |
142
157
  | --- | --- |
@@ -150,12 +165,14 @@ chmod +x mycli.py
150
165
  | `name` | Subcommand name |
151
166
  | `parent` | Parent command (must exist elsewhere in a config) |
152
167
  | `help` | Help text for this subcommand |
153
- | `script` | Python module name (without `.py`) inside `script_dir` or as absolute path |
168
+ | `script` | Python module name (without `.py`) inside `script_dir`, absolute paths supported |
154
169
  | `args` | List of argument definitions (see below) |
155
- | `default` | If `true`, this subcommand is used when no subcommand is given |
156
- | any other parser kwarg | except for `dest` and `formatter_class` they are all supported |
170
+ | `default` | If `True`, this subcommand is used when no subcommand is given |
171
+ | `load` | If `False` skips this command (or top level object) from being loaded into the command tree (default `True`) |
172
+ | any other parser kwarg | except for `dest`, `parents` and `formatter_class` they are all supported |
157
173
 
158
- Note that `parent` does not refer to argparse's parent parameter but is only used to resolve the parser tree. Parser (multi-)inheritance isn't supported but can be emulated by adding arguments to `this` command's parents in the tree.
174
+ Note that `parent` does not refer to argparse's `parents` parameter but is only used to resolve the parser tree.
175
+ Parser (multi-)inheritance isn't supported but can be emulated by adding arguments to `parent` commands in the tree.
159
176
 
160
177
  ### Argument
161
178
 
@@ -185,10 +202,42 @@ Groups and mutex groups are also suppored via the "kind" parameter (defaults to
185
202
  The `name` field can be `--flag` for flags or a string for positional arguments.
186
203
  Both literal string and list of strings are supported.
187
204
 
205
+ Types (`type:`) only supports python builtins
206
+
207
+ ### Script files
208
+
209
+ Each script files have as only requirement that they need to define a
210
+ `def run(args: argparse.Namespace, ctx: dict[str, Any]) -> None` method.
211
+
212
+ args is the by argparse supplied namespace (parsed with parse_known_args), any additional args can be found in `ctx['other_args']`
213
+
214
+ scripts run in sequence from command -> subcommand -> sub sub command -> ... and each may add to,
215
+ remove or otherwise modify args.namespace and ctx to enrich or modify the behaviour of supsequent scripts.
216
+
217
+ ## Sigil CLI Commands
218
+
219
+ `sigil` ships with its own lightweight toolbelt to manage your projects:
220
+
221
+ | Command | Purpose |
222
+ | --- | --- |
223
+ | `sigil init [project_name]` | Creates a new project folder with a sample ready-to-run Python entrypoint. |
224
+ | `sigil validate [project_path]` | Checks your sigil definition for schema errors and missing references. Run this after heavy edits to catch mistakes early. |
225
+ | `sigil tree [project_path]` | Print the command structure of a sigil. |
226
+
227
+ *(Note: Your generated CLI (the one you build with Sigil) is completely separate from the `sigil` management
228
+ commands above. You alias and run `main.py`. the `sigil` prefix is a different namespace.)*
229
+
230
+ ### Misc
231
+
232
+ `load_ignore` may be used to detaching commands from the command tree for any purpose
233
+ (deprecation, development, etc) or for non schema-compliant objects at the top level of a file, this may be useful to
234
+ define anchors or references that should not directly be read as a command.
235
+
188
236
  ## Tab‑Completion (argcomplete)
189
237
 
190
238
  Sigil registers itself with `argcomplete` automatically if available on your system.
191
- To enable completion, install [argcomplete](https://github.com/kislyuk/argcomplete) and activate it for your entry script:
239
+ To enable completion, install [argcomplete](https://github.com/kislyuk/argcomplete) and activate it for your entry
240
+ script (or use the builtin argcomplete comment):
192
241
 
193
242
  ```bash
194
243
  pip install argcomplete
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sigil-cli"
7
- version = "1.1.1"
7
+ version = "1.3.0"
8
8
  description = "Configuration driven CLI builder with subcommands and script loading"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -42,5 +42,7 @@ where = ["src"]
42
42
 
43
43
  [tool.coverage.run]
44
44
  omit = [
45
- "src/sigil/__main__.py"
45
+ "src/sigil/__main__.py",
46
+ "tests/*",
47
+ "*/scripts/*"
46
48
  ]
@@ -0,0 +1,31 @@
1
+ from importlib.metadata import version
2
+
3
+ __version__ = version('sigil-cli')
4
+
5
+ from .entrypoint import run_from_config
6
+ from .models import (
7
+ Argument,
8
+ ArgumentGroup,
9
+ LibArgParser,
10
+ ParserConfig,
11
+ SubcommandModule,
12
+ )
13
+ from .stages import (
14
+ Builder,
15
+ Resolver,
16
+ ScriptLoader,
17
+ YamlReader,
18
+ )
19
+
20
+ __all__ = (
21
+ 'run_from_config',
22
+ 'Argument',
23
+ 'ArgumentGroup',
24
+ 'LibArgParser',
25
+ 'ParserConfig',
26
+ 'SubcommandModule',
27
+ 'YamlReader',
28
+ 'Resolver',
29
+ 'Builder',
30
+ 'ScriptLoader',
31
+ )
@@ -0,0 +1,40 @@
1
+ import argparse
2
+
3
+ from sigil import __version__
4
+ from sigil.cli_tools.init import create_project
5
+ from sigil.cli_tools.tree import display_project
6
+ from sigil.cli_tools.validate import validate_project
7
+
8
+
9
+ def main():
10
+ # let's not start self hosting here
11
+ parser = argparse.ArgumentParser(prog='sigil')
12
+ parser.add_argument('--version', action='version', version=f'Sigil {__version__}')
13
+ sub = parser.add_subparsers(title="subcommands", dest='command')
14
+
15
+ init = sub.add_parser(name="init", help="generate a minimal sigil")
16
+ init.add_argument('name', help="project name to create")
17
+
18
+ validate = sub.add_parser(name="validate", help="validate structure of a sigil")
19
+ validate.add_argument('path', help="project to validate")
20
+
21
+ validate = sub.add_parser(
22
+ name="tree",
23
+ help="display the command structure of a sigil."
24
+ )
25
+ validate.add_argument('path', help="project to validate")
26
+
27
+ args = parser.parse_args()
28
+
29
+ if args.command == 'init':
30
+ create_project(args.name)
31
+ return
32
+ if args.command == 'validate':
33
+ validate_project(args.path)
34
+ return
35
+ if args.command == 'tree':
36
+ display_project(args.path)
37
+ return
38
+
39
+ if __name__ == "__main__":
40
+ main()
@@ -0,0 +1,40 @@
1
+ import argparse
2
+
3
+ from sigil import Builder, Resolver, YamlReader
4
+
5
+
6
+ # adapted from https://stackoverflow.com/questions/78166654/how-can-i-print-the-tree-structure-of-subparsers-of-an-argparse-parser-in-python/78246362#78246362
7
+ def parser_tree(
8
+ parser: argparse.ArgumentParser,
9
+ start: str = "",
10
+ down: str = "│ ",
11
+ leaf: tuple = ("├── ", "└── ")
12
+ ) -> str:
13
+ out = f"{parser.prog or 'root'}\n" if not start else ""
14
+ subparsers_actions = [
15
+ action for action in parser._actions
16
+ if isinstance(action, argparse._SubParsersAction)
17
+ ]
18
+
19
+ for subparsers_action in subparsers_actions:
20
+ choices = list(subparsers_action.choices.items())
21
+ for idx, (choice, subparser) in enumerate(choices):
22
+ is_last = (idx == len(choices) - 1)
23
+ # Prefix for this line: current indentation + branch symbol
24
+ prefix = start + leaf[is_last]
25
+ # Next indentation: if this is the last child, we stop vertical bars;
26
+ # otherwise continue
27
+ next_start = start + (down if not is_last else " " * len(down))
28
+ # Recurse and append
29
+ child_tree = parser_tree(subparser, next_start, down, leaf)
30
+ out += prefix + choice + "\n"
31
+ out += child_tree
32
+ return out
33
+
34
+
35
+ def display_project(projectroot):
36
+ raw = YamlReader.load(projectroot)
37
+ resolved = Resolver.resolve_inheritance(raw)
38
+ parser = Builder.build(resolved)
39
+ print(parser_tree(parser))
40
+
@@ -0,0 +1,116 @@
1
+ import contextlib
2
+ import logging
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ from sigil import Builder, Resolver, YamlReader
7
+
8
+
9
+ # small helper to capture logs from in the guts of sigil
10
+ class WarningCollector(logging.Handler):
11
+ """A handler that stores all records at WARNING level or above."""
12
+ def __init__(self):
13
+ super().__init__()
14
+ self.messages = []
15
+
16
+ def emit(self, record):
17
+ # Only store messages (you could also filter by level here)
18
+ if record.levelno >= logging.INFO:
19
+ self.messages.append(record)
20
+
21
+ @contextlib.contextmanager
22
+ def capture_package_warnings(package_name):
23
+ """
24
+ Captures INFO-level (and higher) logs from the given package tree.
25
+ Example: capture_package_warnings('myproject')
26
+ Info doesn't cause nonzero exit
27
+
28
+ Note that default loglevel is Info and is therefore not displayed by default
29
+ """
30
+ collector = WarningCollector()
31
+ # Get the package root logger – children will propagate to it
32
+ package_logger = logging.getLogger(package_name)
33
+ package_logger.addHandler(collector)
34
+ try:
35
+ yield collector
36
+ finally:
37
+ package_logger.removeHandler(collector)
38
+
39
+ # might as well use a logger and have cleaner counting logic
40
+ _logger = logging.getLogger(__name__)
41
+
42
+
43
+ # actual validation logging
44
+ def _validate_project(projectroot):
45
+ projectpath = Path(projectroot)
46
+
47
+ if not (projectpath/'manifest.yml').exists():
48
+ _logger.error('missing manifest.yml, aborting.')
49
+ sys.exit(1)
50
+
51
+ raw = YamlReader.load(projectroot)
52
+
53
+ # these are easier for us to check
54
+ if 'root' not in raw:
55
+ _logger.error('missing required root command')
56
+ sys.exit(2)
57
+
58
+ resolved = Resolver.resolve_inheritance(raw) #alerts basic structural errors for us
59
+ Builder.build(resolved) # catches the case for "only one default subcommand"
60
+
61
+ script_root = None
62
+ if not raw['root'].script_dir or not (projectpath/raw['root'].script_dir).exists():
63
+ _logger.warning('script_dir may be missing or unreachable')
64
+ else:
65
+ script_root = projectpath/raw['root'].script_dir
66
+
67
+ for c_id, command_def in raw.items():
68
+ if not command_def.help and c_id != 'root':
69
+ _logger.warning(f'command {c_id} may be missing help text')
70
+ if command_def.script:
71
+ if script_root:
72
+ if not (
73
+ script_root/f'{command_def.script}.py'
74
+ ).exists():
75
+ _logger.warning(
76
+ f'script "{command_def.script}" defined on '
77
+ f'command "{c_id}" not found'
78
+ )
79
+ else:
80
+ _logger.warning(f'script defined on "{c_id}" but no script dir defined')
81
+
82
+ # exit code wrapper
83
+ # validation partially happens deep in the guts of sigil,
84
+ # this caputures all validation logs, counts and converts to exit code
85
+ def validate_project(projectroot):
86
+ package_name = __name__.split('.', 1)[0]
87
+ with capture_package_warnings(package_name) as collector:
88
+ try:
89
+ _validate_project(projectroot)
90
+ except SystemExit: # special case to not hard exit
91
+ pass
92
+
93
+ errors = [r for r in collector.messages if r.levelno >= logging.ERROR]
94
+ warnings = [r for r in collector.messages if r.levelno == logging.WARNING]
95
+
96
+ for rec in collector.messages:
97
+ print(f"{rec.levelname}: {rec.getMessage()}", file=sys.stderr)
98
+
99
+ error_count = len(errors)
100
+ warning_count = len(warnings)
101
+
102
+ if error_count > 0:
103
+ print(
104
+ f'Validation failed with {error_count} error(s) '
105
+ f'and {warning_count} warning(s).',
106
+ file=sys.stderr
107
+ )
108
+ sys.exit(2)
109
+ elif warning_count > 0:
110
+ print(
111
+ f"Validation had {warning_count} warning(s) (no errors).",
112
+ file=sys.stderr
113
+ )
114
+ sys.exit(1)
115
+ else:
116
+ print("Validation passed successfully.", file=sys.stderr)
@@ -1,17 +1,26 @@
1
+ import logging
2
+ import sys
1
3
  from typing import Any
2
4
 
3
5
  from .stages import Builder, Resolver, ScriptLoader, YamlReader
4
6
 
7
+ _logger = logging.getLogger(__name__)
5
8
 
6
9
  # default to yamlloader, use whatever datastore you feel like
7
10
  def run_from_config(config_root: str, loader_class = YamlReader):
8
11
  raw_data = loader_class.load(config_root)
9
12
  resolved = Resolver.resolve_inheritance(raw_data)
10
13
  parser = Builder.build(resolved)
11
- args, other_args = parser.parse_known_args()
12
- scripts = ScriptLoader.get_scripts(args, 'root', parser, {'root': resolved})
13
14
 
14
- execution_context: dict[str, Any] = {'other_args': other_args}
15
+ execution_context = {}
16
+
17
+ if resolved.known_args:
18
+ args, other_args = parser.parse_known_args()
19
+ execution_context: dict[str, Any] = {'other_args': other_args}
20
+ else:
21
+ args = parser.parse_args()
22
+
23
+ scripts = ScriptLoader.get_scripts(args, 'root', parser, {'root': resolved})
15
24
  for script in scripts:
16
25
  try:
17
26
  module = ScriptLoader.import_module(
@@ -19,7 +28,11 @@ def run_from_config(config_root: str, loader_class = YamlReader):
19
28
  resolved.script_dir,
20
29
  script
21
30
  )
31
+ if not module:
32
+ continue
22
33
  except FileNotFoundError as e:
23
- print(f'failed to load script "{script}"\n {e}')
24
- return
34
+ # prevent your subcommand from turning your environment
35
+ # into undefined soup by not continuing execution
36
+ _logger.critical(f'failed to load script "{script}"\n {e}')
37
+ sys.exit(2)
25
38
  module.run(args, execution_context)
@@ -1,7 +1,7 @@
1
1
  import builtins
2
2
  import logging
3
3
  from dataclasses import dataclass, field
4
- from typing import Any
4
+ from typing import Any, cast
5
5
 
6
6
  AGGREGATE_TYPES = [
7
7
  'group',
@@ -18,21 +18,24 @@ _logger = logging.getLogger(__name__)
18
18
 
19
19
  @dataclass
20
20
  class ArgumentGroup:
21
- args: 'list[Argument]'
21
+ args: 'list[Argument | ArgumentGroup]'
22
22
  mutex: bool
23
23
  # anything else not specifically in here
24
24
  kw: dict[str, Any] = field(default_factory=dict)
25
25
 
26
26
  @classmethod
27
- def factory(cls, **kwargs: dict) -> 'ArgumentGroup':
28
- kind = kwargs.pop('kind')
27
+ def factory(cls, **kwargs: dict[str, Any]) -> 'ArgumentGroup':
28
+ kind: str = cast(str, kwargs.pop('kind', 'argument'))
29
29
  # yes argparse only supports these 2 groupings for now
30
30
  # but it can't hurt to not write an if/else ladder in the future
31
31
  is_mutex = {
32
32
  'group': False,
33
33
  'mutex': True
34
- }.get(kind)
35
- incoming_args = kwargs.pop('args', [])
34
+ }.get(kind, False)
35
+ incoming_args: list[dict[str, Any]] = cast(
36
+ list[dict[str, Any]],
37
+ kwargs.pop('args', [])
38
+ )
36
39
  group_content = [
37
40
  Argument.factory(**arg)
38
41
  for arg in incoming_args
@@ -48,14 +51,13 @@ class Argument:
48
51
  # help is so uber-common that while yes it could go into
49
52
  # kw i still explicitly defined it
50
53
  help: str | None = None
51
- action: str | None = None
52
54
  # anything we haven't explicitly defined.. yet
53
55
  kw: dict[str, Any] = field(default_factory=dict)
54
56
 
55
57
  # Source - https://stackoverflow.com/a/74459763
56
58
 
57
59
  @classmethod
58
- def factory(cls, **kwargs: dict) -> 'Argument | ArgumentGroup':
60
+ def factory(cls, **kwargs: dict[str, Any]) -> 'Argument | ArgumentGroup':
59
61
  kind = kwargs.get('kind', 'argument') # default to argument
60
62
  if kind not in ALLOWED_KINDS:
61
63
  raise ValueError(f'invalid kind {kind}')
@@ -63,10 +65,10 @@ class Argument:
63
65
  return ArgumentGroup.factory(**kwargs)
64
66
  name = kwargs.get('name')
65
67
  if isinstance(name, str):
66
- kwargs['name'] = [name]
68
+ kwargs['name'] = [name] # type: ignore
67
69
  uncaught_kwargs = {k: kwargs[k] for k in kwargs if k not in cls.__match_args__}
68
70
  caught_kwargs = {k: kwargs[k] for k in kwargs if k in cls.__match_args__}
69
- return cls(**caught_kwargs, kw=uncaught_kwargs)
71
+ return cls(**caught_kwargs, kw=uncaught_kwargs) # type: ignore
70
72
 
71
73
  def __post_init__(self):
72
74
  if argtype := self.kw.get('type'):