sigil-cli 1.2.0__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 (37) hide show
  1. {sigil_cli-1.2.0/src/sigil_cli.egg-info → sigil_cli-1.3.0}/PKG-INFO +39 -13
  2. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/README.md +38 -12
  3. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/pyproject.toml +1 -1
  4. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/__main__.py +10 -0
  5. sigil_cli-1.3.0/src/sigil/cli_tools/tree.py +40 -0
  6. sigil_cli-1.3.0/src/sigil/cli_tools/validate.py +116 -0
  7. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/entrypoint.py +0 -1
  8. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/models/command.py +17 -0
  9. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/stages/builder.py +19 -6
  10. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/stages/resolver.py +20 -4
  11. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/stages/yaml_reader.py +7 -3
  12. {sigil_cli-1.2.0 → sigil_cli-1.3.0/src/sigil_cli.egg-info}/PKG-INFO +39 -13
  13. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil_cli.egg-info/SOURCES.txt +5 -3
  14. sigil_cli-1.3.0/tests/test_cli_tree.py +80 -0
  15. sigil_cli-1.2.0/tests/test_validate.py → sigil_cli-1.3.0/tests/test_cli_validate.py +12 -7
  16. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/tests/test_reader.py +22 -16
  17. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/tests/test_resolver.py +18 -1
  18. sigil_cli-1.2.0/src/sigil/cli_tools/validate.py +0 -45
  19. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/LICENSE +0 -0
  20. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/setup.cfg +0 -0
  21. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/__init__.py +0 -0
  22. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/cli_tools/__init__.py +0 -0
  23. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/cli_tools/init.py +0 -0
  24. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/models/__init__.py +0 -0
  25. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/models/argparser.py +0 -0
  26. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/models/argument.py +0 -0
  27. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/models/script.py +0 -0
  28. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/stages/__init__.py +0 -0
  29. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil/stages/script_loader.py +0 -0
  30. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil_cli.egg-info/dependency_links.txt +0 -0
  31. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil_cli.egg-info/entry_points.txt +0 -0
  32. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil_cli.egg-info/requires.txt +0 -0
  33. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/src/sigil_cli.egg-info/top_level.txt +0 -0
  34. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/tests/test_builder.py +0 -0
  35. /sigil_cli-1.2.0/tests/test_cli_tools.py → /sigil_cli-1.3.0/tests/test_cli_init.py +0 -0
  36. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/tests/test_integration.py +0 -0
  37. {sigil_cli-1.2.0 → sigil_cli-1.3.0}/tests/test_scriptloader.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sigil-cli
3
- Version: 1.2.0
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,8 +32,8 @@ Dynamic: license-file
32
32
 
33
33
  > Declarative argparse, without the CLI boilerplate.
34
34
 
35
-
36
- 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.
37
37
  It plays nicely with `argcomplete` out of the box.
38
38
 
39
39
  [![PyPI Version](https://img.shields.io/pypi/v/sigil-cli)](https://pypi.python.org/pypi/sigil-cli)
@@ -75,12 +75,19 @@ your command structure modular and flexible.
75
75
  pip install sigil-cli
76
76
  ```
77
77
 
78
- 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:
79
81
 
80
82
  ```bash
81
- 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
82
87
  ```
83
88
 
89
+ For a full walkthrough with custom commands and arguments, jump to the Quick Start below.
90
+
84
91
  ### 0. Recommended file structure
85
92
 
86
93
  ```text
@@ -190,11 +197,12 @@ chmod +x mycli.py
190
197
  | `help` | Help text for this subcommand |
191
198
  | `script` | Python module name (without `.py`) inside `script_dir`, absolute paths supported |
192
199
  | `args` | List of argument definitions (see below) |
193
- | `default` | If `true`, this subcommand is used when no subcommand is given |
194
- | `load_ignore`| If `true` skips this command (or top level object) from being loaded into the command tree|
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`) |
195
202
  | any other parser kwarg | except for `dest`, `parents` and `formatter_class` they are all supported |
196
203
 
197
- Note that `parent` does not refer to argparse's `parents` parameter but is only used to resolve the parser tree. Parser (multi-)inheritance isn't supported but can be emulated by adding arguments to `parent` commands 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.
198
206
 
199
207
  ### Argument
200
208
 
@@ -224,24 +232,42 @@ Groups and mutex groups are also suppored via the "kind" parameter (defaults to
224
232
  The `name` field can be `--flag` for flags or a string for positional arguments.
225
233
  Both literal string and list of strings are supported.
226
234
 
227
- Types (`type:`) only supports python builtins
235
+ Types (`type:`) only supports python builtins
228
236
 
229
237
  ### Script files
230
238
 
231
- Each script files have as only requirement that they need to define a `def run(args: argparse.Namespace, ctx: dict[str, Any]) -> None` method.
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.
232
241
 
233
242
  args is the by argparse supplied namespace (parsed with parse_known_args), any additional args can be found in `ctx['other_args']`
234
243
 
235
- scripts run in sequence from command -> subcommand -> sub sub command -> ... and each may add to, remove or otherwise modify args.namespace and ctx to enrich or modify the behaviour of supsequent scripts.
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.)*
236
259
 
237
260
  ### Misc
238
261
 
239
- `load_ignore` may be used to detaching commands from the command tree for any purpose (deprecation, development, etc) or for non schema-compliant objects at the top level of a file, this may be useful to define anchors or references that should not directly be read as a command.
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.
240
265
 
241
266
  ## Tab‑Completion (argcomplete)
242
267
 
243
268
  Sigil registers itself with `argcomplete` automatically if available on your system.
244
- To enable completion, install [argcomplete](https://github.com/kislyuk/argcomplete) and activate it for your entry script (or use the builtin argcomplete comment):
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):
245
271
 
246
272
  ```bash
247
273
  pip install argcomplete
@@ -2,8 +2,8 @@
2
2
 
3
3
  > Declarative argparse, without the CLI boilerplate.
4
4
 
5
-
6
- 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.
7
7
  It plays nicely with `argcomplete` out of the box.
8
8
 
9
9
  [![PyPI Version](https://img.shields.io/pypi/v/sigil-cli)](https://pypi.python.org/pypi/sigil-cli)
@@ -45,12 +45,19 @@ your command structure modular and flexible.
45
45
  pip install sigil-cli
46
46
  ```
47
47
 
48
- 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:
49
51
 
50
52
  ```bash
51
- 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
52
57
  ```
53
58
 
59
+ For a full walkthrough with custom commands and arguments, jump to the Quick Start below.
60
+
54
61
  ### 0. Recommended file structure
55
62
 
56
63
  ```text
@@ -160,11 +167,12 @@ chmod +x mycli.py
160
167
  | `help` | Help text for this subcommand |
161
168
  | `script` | Python module name (without `.py`) inside `script_dir`, absolute paths supported |
162
169
  | `args` | List of argument definitions (see below) |
163
- | `default` | If `true`, this subcommand is used when no subcommand is given |
164
- | `load_ignore`| If `true` skips this command (or top level object) from being loaded into the command tree|
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`) |
165
172
  | any other parser kwarg | except for `dest`, `parents` and `formatter_class` they are all supported |
166
173
 
167
- Note that `parent` does not refer to argparse's `parents` parameter but is only used to resolve the parser tree. Parser (multi-)inheritance isn't supported but can be emulated by adding arguments to `parent` commands 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.
168
176
 
169
177
  ### Argument
170
178
 
@@ -194,24 +202,42 @@ Groups and mutex groups are also suppored via the "kind" parameter (defaults to
194
202
  The `name` field can be `--flag` for flags or a string for positional arguments.
195
203
  Both literal string and list of strings are supported.
196
204
 
197
- Types (`type:`) only supports python builtins
205
+ Types (`type:`) only supports python builtins
198
206
 
199
207
  ### Script files
200
208
 
201
- Each script files have as only requirement that they need to define a `def run(args: argparse.Namespace, ctx: dict[str, Any]) -> None` method.
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.
202
211
 
203
212
  args is the by argparse supplied namespace (parsed with parse_known_args), any additional args can be found in `ctx['other_args']`
204
213
 
205
- scripts run in sequence from command -> subcommand -> sub sub command -> ... and each may add to, remove or otherwise modify args.namespace and ctx to enrich or modify the behaviour of supsequent scripts.
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.)*
206
229
 
207
230
  ### Misc
208
231
 
209
- `load_ignore` may be used to detaching commands from the command tree for any purpose (deprecation, development, etc) or for non schema-compliant objects at the top level of a file, this may be useful to define anchors or references that should not directly be read as a command.
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.
210
235
 
211
236
  ## Tab‑Completion (argcomplete)
212
237
 
213
238
  Sigil registers itself with `argcomplete` automatically if available on your system.
214
- To enable completion, install [argcomplete](https://github.com/kislyuk/argcomplete) and activate it for your entry script (or use the builtin argcomplete comment):
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):
215
241
 
216
242
  ```bash
217
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.2.0"
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"
@@ -2,6 +2,7 @@ import argparse
2
2
 
3
3
  from sigil import __version__
4
4
  from sigil.cli_tools.init import create_project
5
+ from sigil.cli_tools.tree import display_project
5
6
  from sigil.cli_tools.validate import validate_project
6
7
 
7
8
 
@@ -17,6 +18,12 @@ def main():
17
18
  validate = sub.add_parser(name="validate", help="validate structure of a sigil")
18
19
  validate.add_argument('path', help="project to validate")
19
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
+
20
27
  args = parser.parse_args()
21
28
 
22
29
  if args.command == 'init':
@@ -25,6 +32,9 @@ def main():
25
32
  if args.command == 'validate':
26
33
  validate_project(args.path)
27
34
  return
35
+ if args.command == 'tree':
36
+ display_project(args.path)
37
+ return
28
38
 
29
39
  if __name__ == "__main__":
30
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)
@@ -7,7 +7,6 @@ from .stages import Builder, Resolver, ScriptLoader, YamlReader
7
7
  _logger = logging.getLogger(__name__)
8
8
 
9
9
  # default to yamlloader, use whatever datastore you feel like
10
- tmp = 0
11
10
  def run_from_config(config_root: str, loader_class = YamlReader):
12
11
  raw_data = loader_class.load(config_root)
13
12
  resolved = Resolver.resolve_inheritance(raw_data)
@@ -29,9 +29,12 @@ class ParserConfig:
29
29
  subparsers: 'dict[str, ParserConfig]' = field(default_factory=dict)
30
30
  # anything not already in here
31
31
  parser_kwargs: dict[str, Any] = field(default_factory=dict)
32
+ load: bool = True
32
33
 
33
34
  @classmethod
34
35
  def factory(cls, **kwargs):
36
+ if 'name' not in kwargs:
37
+ raise ValueError("required argument 'name' not defined.")
35
38
  uncaught_kwargs = {k: kwargs[k] for k in kwargs if k not in cls.__match_args__}
36
39
  caught_kwargs = {k: kwargs[k] for k in kwargs if k in cls.__match_args__}
37
40
  parser_kwargs = {}
@@ -46,3 +49,17 @@ class ParserConfig:
46
49
  else:
47
50
  parser_kwargs[kwarg] = value
48
51
  return cls(**caught_kwargs, parser_kwargs=parser_kwargs)
52
+
53
+ @classmethod
54
+ def construct_unloaded_data(cls, key: str, source: dict):
55
+ # this dataclass requires several attributes for either validation checks
56
+ # or instantiation requirements
57
+ # all get defined here, regardless of source data
58
+ # since this object is later required to validate and build tree
59
+ # structure minimal data is required
60
+ return {
61
+ 'name': key,
62
+ 'help': source.get('help', 'missing'),
63
+ 'load': source.get('load'),
64
+ 'parent': source.get('parent')
65
+ }
@@ -25,13 +25,26 @@ class Builder:
25
25
  )
26
26
  last_default = None # find the last default
27
27
  for _, subcommand in parser_data.subparsers.items():
28
- argparser = argparse_group.add_parser(
29
- subcommand.name,
30
- help=subcommand.help,
31
- **subcommand.parser_kwargs,
32
- )
28
+ try:
29
+ argparser = argparse_group.add_parser(
30
+ subcommand.name,
31
+ help=subcommand.help,
32
+ **subcommand.parser_kwargs,
33
+ )
34
+ except Exception as e:
35
+ _logger.error(
36
+ f"unable to instantiate subcommand '{subcommand.name}'\n {e}"
37
+ )
38
+ continue # parser cannot be resqued
33
39
  for arg in subcommand.args:
34
- cls.attach_argument(argparser, arg)
40
+ try:
41
+ cls.attach_argument(argparser, arg)
42
+ except Exception as e:
43
+ _logger.error(
44
+ f"unable to attach argument {arg.name}"
45
+ f"to command '{subcommand.name}'\n {e}"
46
+ )
47
+ # parser valid, just some args missing
35
48
  if subcommand.default:
36
49
  if last_default:
37
50
  _logger.warning(
@@ -1,4 +1,5 @@
1
1
  import logging
2
+ import sys
2
3
 
3
4
  from sigil.models import ParserConfig
4
5
 
@@ -19,6 +20,10 @@ class Resolver:
19
20
  resolved: dict[str, ParserConfig] = {}
20
21
  changed = True
21
22
 
23
+ if 'root' not in raw_config:
24
+ _logger.critical('missing root definition, aborting.')
25
+ sys.exit(1)
26
+
22
27
  while changed:
23
28
  changed = False # stays false unless something is attached
24
29
  for internal_id, config_item in raw_config.items():
@@ -32,15 +37,26 @@ class Resolver:
32
37
 
33
38
  parent = config_item.parent
34
39
 
35
- if parent and parent in resolved:
36
- changed = True # only run a new pass if something was attached
40
+ if not parent or parent not in resolved:
41
+ continue
42
+
43
+ # only attach if we can
44
+ changed = True
45
+ if config_item.load:
46
+ # only actually attach if loaded
47
+ # so we can still warn on actual orphans
48
+ # while ignoring intentionally disabled objects
37
49
  subparsers = resolved[parent].subparsers
38
50
  subparsers[config_item.name]= config_item
39
51
  resolved[parent].subparsers = subparsers
40
- resolved[internal_id] = config_item
52
+ else:
53
+ _logger.info(f"{internal_id} marked as unloaded, ignoring tree")
54
+ # no continue as we still need to register the key
55
+ # such that it's children don't cause warnings
56
+ resolved[internal_id] = config_item
41
57
 
42
58
  # log unattached items:
43
59
  for item in (raw_config.keys() - resolved.keys()):
44
- _logger.warning(f'failed to resolve command path for {item}')
60
+ _logger.warning(f'Command {item} may be orphaned')
45
61
 
46
62
  return resolved['root'] # one "root" is required
@@ -43,8 +43,12 @@ class YamlReader:
43
43
  continue
44
44
  tmp = {}
45
45
  for k, v in loaded_entry.items():
46
- if v.get('load_ignore'):
47
- _logger.warning(f'{k} marked as load_ignore, skipping')
46
+ if not v.get('load', True):
47
+ _logger.info(f'{k} marked as unloaded')
48
+ # truncate extra data
49
+ # the key will later be used for differentiating
50
+ # orphaned children vs intentionally unloaded subtrees
51
+ tmp[k] = ParserConfig.construct_unloaded_data(k, v)
48
52
  continue
49
53
  tmp[k] = v # pesky can't del in for loop :/
50
54
  loaded_entry = tmp
@@ -57,7 +61,7 @@ class YamlReader:
57
61
  try:
58
62
  loaded_config[k] = ParserConfig.factory(**v)
59
63
  except Exception as e:
60
- _logger.error(f'failed to parse config {k}, ignoring\n{e}')
64
+ _logger.error(f"failed to parse config '{k}', ignoring\n {e}")
61
65
  # pesky "dictionary changed size during iteration"
62
66
  loaded_config = {
63
67
  k: v
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sigil-cli
3
- Version: 1.2.0
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,8 +32,8 @@ Dynamic: license-file
32
32
 
33
33
  > Declarative argparse, without the CLI boilerplate.
34
34
 
35
-
36
- 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.
37
37
  It plays nicely with `argcomplete` out of the box.
38
38
 
39
39
  [![PyPI Version](https://img.shields.io/pypi/v/sigil-cli)](https://pypi.python.org/pypi/sigil-cli)
@@ -75,12 +75,19 @@ your command structure modular and flexible.
75
75
  pip install sigil-cli
76
76
  ```
77
77
 
78
- 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:
79
81
 
80
82
  ```bash
81
- 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
82
87
  ```
83
88
 
89
+ For a full walkthrough with custom commands and arguments, jump to the Quick Start below.
90
+
84
91
  ### 0. Recommended file structure
85
92
 
86
93
  ```text
@@ -190,11 +197,12 @@ chmod +x mycli.py
190
197
  | `help` | Help text for this subcommand |
191
198
  | `script` | Python module name (without `.py`) inside `script_dir`, absolute paths supported |
192
199
  | `args` | List of argument definitions (see below) |
193
- | `default` | If `true`, this subcommand is used when no subcommand is given |
194
- | `load_ignore`| If `true` skips this command (or top level object) from being loaded into the command tree|
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`) |
195
202
  | any other parser kwarg | except for `dest`, `parents` and `formatter_class` they are all supported |
196
203
 
197
- Note that `parent` does not refer to argparse's `parents` parameter but is only used to resolve the parser tree. Parser (multi-)inheritance isn't supported but can be emulated by adding arguments to `parent` commands 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.
198
206
 
199
207
  ### Argument
200
208
 
@@ -224,24 +232,42 @@ Groups and mutex groups are also suppored via the "kind" parameter (defaults to
224
232
  The `name` field can be `--flag` for flags or a string for positional arguments.
225
233
  Both literal string and list of strings are supported.
226
234
 
227
- Types (`type:`) only supports python builtins
235
+ Types (`type:`) only supports python builtins
228
236
 
229
237
  ### Script files
230
238
 
231
- Each script files have as only requirement that they need to define a `def run(args: argparse.Namespace, ctx: dict[str, Any]) -> None` method.
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.
232
241
 
233
242
  args is the by argparse supplied namespace (parsed with parse_known_args), any additional args can be found in `ctx['other_args']`
234
243
 
235
- scripts run in sequence from command -> subcommand -> sub sub command -> ... and each may add to, remove or otherwise modify args.namespace and ctx to enrich or modify the behaviour of supsequent scripts.
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.)*
236
259
 
237
260
  ### Misc
238
261
 
239
- `load_ignore` may be used to detaching commands from the command tree for any purpose (deprecation, development, etc) or for non schema-compliant objects at the top level of a file, this may be useful to define anchors or references that should not directly be read as a command.
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.
240
265
 
241
266
  ## Tab‑Completion (argcomplete)
242
267
 
243
268
  Sigil registers itself with `argcomplete` automatically if available on your system.
244
- To enable completion, install [argcomplete](https://github.com/kislyuk/argcomplete) and activate it for your entry script (or use the builtin argcomplete comment):
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):
245
271
 
246
272
  ```bash
247
273
  pip install argcomplete
@@ -6,6 +6,7 @@ src/sigil/__main__.py
6
6
  src/sigil/entrypoint.py
7
7
  src/sigil/cli_tools/__init__.py
8
8
  src/sigil/cli_tools/init.py
9
+ src/sigil/cli_tools/tree.py
9
10
  src/sigil/cli_tools/validate.py
10
11
  src/sigil/models/__init__.py
11
12
  src/sigil/models/argparser.py
@@ -24,9 +25,10 @@ src/sigil_cli.egg-info/entry_points.txt
24
25
  src/sigil_cli.egg-info/requires.txt
25
26
  src/sigil_cli.egg-info/top_level.txt
26
27
  tests/test_builder.py
27
- tests/test_cli_tools.py
28
+ tests/test_cli_init.py
29
+ tests/test_cli_tree.py
30
+ tests/test_cli_validate.py
28
31
  tests/test_integration.py
29
32
  tests/test_reader.py
30
33
  tests/test_resolver.py
31
- tests/test_scriptloader.py
32
- tests/test_validate.py
34
+ tests/test_scriptloader.py
@@ -0,0 +1,80 @@
1
+ import argparse
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+
6
+ from sigil.cli_tools.tree import display_project, parser_tree
7
+
8
+
9
+ def test_parser_tree_with_subcommands(
10
+ tmp_path: Path,
11
+ capsys: pytest.CaptureFixture
12
+ ) -> None:
13
+ """Test that validate_project exits when multiple subcommands have default: true."""
14
+ project_root = tmp_path / "mycli"
15
+ project_root.mkdir()
16
+
17
+ manifest = project_root / "manifest.yml"
18
+ manifest.write_text("""
19
+ - root.yml
20
+ - foo.yml
21
+ - bar.yml
22
+ """)
23
+
24
+ root_yml = project_root / "root.yml"
25
+ root_yml.write_text("""
26
+ root:
27
+ name: mycli
28
+ script_dir: scripts
29
+ """)
30
+
31
+ foo_yml = project_root / "foo.yml"
32
+ foo_yml.write_text("""
33
+ foo:
34
+ name: foo
35
+ parent: root
36
+
37
+ foo_sub1:
38
+ name: leaf1
39
+ parent: foo
40
+
41
+ foo_sub2:
42
+ name: leaf2
43
+ parent: foo
44
+ """)
45
+
46
+ bar_yml = project_root / "bar.yml"
47
+ bar_yml.write_text("""
48
+ bar:
49
+ name: bar
50
+ parent: root
51
+
52
+ bar_sub1:
53
+ name: leaf3
54
+ parent: bar
55
+
56
+ bar_sub2:
57
+ name: leaf4
58
+ parent: bar
59
+ """)
60
+ display_project(project_root)
61
+
62
+ excpected_tree = """
63
+ mycli
64
+ ├── bar
65
+ │ ├── leaf3
66
+ │ └── leaf4
67
+ └── foo
68
+ ├── leaf1
69
+ └── leaf2
70
+ """.strip()
71
+ captured = capsys.readouterr().out.strip()
72
+ assert captured == excpected_tree
73
+
74
+
75
+ def test_parser_tree_empty_parser():
76
+ """Test that parser_tree handles a parser with no subcommands gracefully."""
77
+ parser = argparse.ArgumentParser(prog="empty")
78
+ tree = parser_tree(parser)
79
+ # Only the root line should be present (no subcommands)
80
+ assert tree == "empty\n"
@@ -37,14 +37,14 @@ root:
37
37
  assert not caplog.records
38
38
 
39
39
  def test_validate_project_missing_manifest( tmp_path: Path) -> None:
40
- """Test that validate_project exits with code 1 when manifest.yml is missing."""
40
+ """Test that validate_project exits with code 2 when manifest.yml is missing."""
41
41
  project_root = tmp_path / "mycli"
42
42
  project_root.mkdir()
43
43
 
44
44
  with pytest.raises(SystemExit) as exc_info:
45
45
  validate_project(project_root)
46
46
 
47
- assert exc_info.value.code == 1
47
+ assert exc_info.value.code == 2
48
48
 
49
49
  def test_validate_project_missing_root_key(
50
50
  tmp_path: Path,
@@ -91,7 +91,8 @@ root:
91
91
  # Do NOT create scripts/ directory
92
92
 
93
93
  with caplog.at_level(logging.WARNING):
94
- validate_project(project_root)
94
+ with pytest.raises(SystemExit):
95
+ validate_project(project_root)
95
96
 
96
97
  assert "script_dir may be missing or unreachable" in caplog.text
97
98
 
@@ -130,7 +131,8 @@ greet:
130
131
  (scripts_dir / "greet.py").touch()
131
132
 
132
133
  with caplog.at_level(logging.WARNING):
133
- validate_project(project_root)
134
+ with pytest.raises(SystemExit):
135
+ validate_project(project_root)
134
136
 
135
137
  assert "command greet may be missing help text" in caplog.text
136
138
 
@@ -170,7 +172,8 @@ greet:
170
172
  # Do NOT create greet.py
171
173
 
172
174
  with caplog.at_level(logging.WARNING):
173
- validate_project(project_root)
175
+ with pytest.raises(SystemExit):
176
+ validate_project(project_root)
174
177
 
175
178
  assert 'script "greet" defined on command "greet" not found' in caplog.text
176
179
 
@@ -207,7 +210,8 @@ greet:
207
210
  # Do NOT create scripts/ directory
208
211
 
209
212
  with caplog.at_level(logging.WARNING):
210
- validate_project(project_root)
213
+ with pytest.raises(SystemExit):
214
+ validate_project(project_root)
211
215
 
212
216
  assert 'script defined on "greet" but no script dir defined' in caplog.text
213
217
 
@@ -258,6 +262,7 @@ bar:
258
262
  for cmd in ("root", "foo", "bar"):
259
263
  (scripts_dir / f"{cmd}.py").touch()
260
264
 
261
- validate_project(project_root)
265
+ with pytest.raises(SystemExit):
266
+ validate_project(project_root)
262
267
 
263
268
  assert 'last default bar overridden with foo' in caplog.text
@@ -1,6 +1,7 @@
1
1
  import yaml
2
2
 
3
3
  from sigil import ParserConfig, YamlReader
4
+ from sigil.models.command import UNSUPPORTED_KWARGS
4
5
 
5
6
 
6
7
  def test_yaml_reader_load(tmp_path, sample_manifest):
@@ -45,22 +46,6 @@ def test_yaml_reader_duplicate_warning(caplog, tmp_path):
45
46
  assert loaded["cmd"].help == "from a" # first wins
46
47
 
47
48
 
48
- def test_yaml_reader_load_ignore(tmp_path):
49
- """Test that entries with load_ignore: True are skipped."""
50
- manifest = tmp_path / "manifest.yml"
51
- manifest.write_text("- ignored.yml\n- kept.yml\n")
52
-
53
- ignored = {"ignored": {"name": "ignored", "load_ignore": True}}
54
- kept = {"kept": {"name": "kept"}}
55
-
56
- (tmp_path / "ignored.yml").write_text(yaml.dump(ignored))
57
- (tmp_path / "kept.yml").write_text(yaml.dump(kept))
58
-
59
- loaded = YamlReader.load(tmp_path)
60
- assert "ignored" not in loaded
61
- assert "kept" in loaded
62
-
63
-
64
49
  def test_yaml_reader_invalid_arg(caplog, tmp_path):
65
50
  """Test that invalid argument definitions are skipped."""
66
51
  manifest = tmp_path / "manifest.yml"
@@ -83,3 +68,24 @@ def test_yaml_reader_invalid_arg(caplog, tmp_path):
83
68
  assert "invalid argument definition" in caplog.text
84
69
  assert len(loaded["cmd"].args) == 1
85
70
  assert loaded["cmd"].args[0].name == ["valid"]
71
+
72
+ def test_invalid_parser(caplog, tmp_path):
73
+ manifest = tmp_path / "manifest.yml"
74
+ manifest.write_text("- cmd.yml\n")
75
+
76
+ cmd_data = {
77
+ "cmd": {
78
+ "name": "cmd",
79
+ "dest":"not_supported",
80
+ "formatter_class": "not_supported",
81
+ "parents": "not_supported",
82
+
83
+ }
84
+ }
85
+ (tmp_path / "cmd.yml").write_text(yaml.dump(cmd_data))
86
+
87
+ with caplog.at_level("WARNING"):
88
+ YamlReader.load(tmp_path)
89
+
90
+ for kw in UNSUPPORTED_KWARGS:
91
+ assert f"'{kw}' unsupported" in caplog.text
@@ -23,5 +23,22 @@ def test_resolver_unattached_warning(caplog):
23
23
  with caplog.at_level("WARNING"):
24
24
  root = resolver.resolve_inheritance(config)
25
25
 
26
- assert "failed to resolve command path for orphan" in caplog.text
26
+ assert "may be orphaned" in caplog.text
27
27
  assert "orphan" not in root.subparsers
28
+
29
+ def test_yaml_reader_load_ignore(tmp_path):
30
+ """Test that entries with load: False are skipped."""
31
+ manifest = tmp_path / "manifest.yml"
32
+ manifest.write_text("- ignored.yml\n- kept.yml\n")
33
+
34
+ config = {
35
+ "root": ParserConfig.factory(name="root"),
36
+ "ignored": ParserConfig.factory(name="ignored", load=False, parent="root"),
37
+ "kept": ParserConfig.factory(name="kept", parent="root"),
38
+ }
39
+ resolver = Resolver()
40
+ resolved = resolver.resolve_inheritance(config)
41
+ print(resolved)
42
+
43
+ assert "kept" in resolved.subparsers
44
+ assert "ignored" not in resolved.subparsers
@@ -1,45 +0,0 @@
1
- import logging
2
- import sys
3
- from pathlib import Path
4
-
5
- from sigil import Builder, Resolver, YamlReader
6
-
7
- _logger = logging.getLogger(__name__)
8
-
9
- def validate_project(projectroot):
10
- projectpath = Path(projectroot)
11
-
12
- if not (projectpath/'manifest.yml').exists():
13
- _logger.error('missing manifest.yml, aborting.')
14
- sys.exit(1)
15
-
16
- raw = YamlReader.load(projectroot)
17
-
18
- # these are easier for us to check
19
- if 'root' not in raw:
20
- _logger.error('missing required root command')
21
- sys.exit(2)
22
-
23
- resolved = Resolver.resolve_inheritance(raw) #alerts basic structural errors for us
24
- Builder.build(resolved) # catches the case for "only one default subcommand"
25
-
26
- script_root = None
27
- if not raw['root'].script_dir or not (projectpath/raw['root'].script_dir).exists():
28
- _logger.warning('script_dir may be missing or unreachable')
29
- else:
30
- script_root = projectpath/raw['root'].script_dir
31
-
32
- for c_id, command_def in raw.items():
33
- if not command_def.help and c_id != 'root':
34
- _logger.warning(f'command {c_id} may be missing help text')
35
- if command_def.script:
36
- if script_root:
37
- if not (
38
- script_root/f'{command_def.script}.py'
39
- ).exists():
40
- _logger.warning(
41
- f'script "{command_def.script}" defined on '
42
- f'command "{c_id}" not found'
43
- )
44
- else:
45
- _logger.warning(f'script defined on "{c_id}" but no script dir defined')
File without changes
File without changes