the first commit
This commit is contained in:
@@ -0,0 +1,4 @@
|
|||||||
|
/.venv
|
||||||
|
/dist
|
||||||
|
*.egg-info
|
||||||
|
__pycache__
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
Dux Technica Source Code License Agreement
|
DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL)
|
||||||
|
|
||||||
1. Introduction
|
1. Introduction
|
||||||
|
|
||||||
@@ -11,8 +11,8 @@ terms and conditions of this Agreement.
|
|||||||
|
|
||||||
Subject to the terms and conditions of this Agreement, the Licensor hereby grants to the Licensee a
|
Subject to the terms and conditions of this Agreement, the Licensor hereby grants to the Licensee a
|
||||||
non-exclusive, non-transferable, limited license to use the Source Code solely for internal
|
non-exclusive, non-transferable, limited license to use the Source Code solely for internal
|
||||||
purposes. The Licensee may use the Source Code for evaluation, development, and testing purposes
|
purposes only. The Licensee may use the Source Code for evaluation, development, and testing
|
||||||
within their organisation.
|
purposes within their organisation.
|
||||||
|
|
||||||
3. Restrictions
|
3. Restrictions
|
||||||
|
|
||||||
@@ -31,6 +31,7 @@ reasonable steps to prevent unauthorised access or disclosure.
|
|||||||
Source Code.
|
Source Code.
|
||||||
|
|
||||||
4. Payment
|
4. Payment
|
||||||
|
|
||||||
Access to the Source Code may be subject to payment. The terms of payment will be specified
|
Access to the Source Code may be subject to payment. The terms of payment will be specified
|
||||||
separately by the Licensor. The Licensee agrees to pay any applicable fees as stipulated by the
|
separately by the Licensor. The Licensee agrees to pay any applicable fees as stipulated by the
|
||||||
Licensor before accessing the Source Code.
|
Licensor before accessing the Source Code.
|
||||||
|
|||||||
@@ -1,3 +1,15 @@
|
|||||||
# scott
|
# scott
|
||||||
|
|
||||||
A framework to create scoped task-oriented terminal tools
|
A framework to create scoped task-oriented terminal tools.
|
||||||
|
|
||||||
|
## Run these
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pip install --upgrade build
|
||||||
|
```
|
||||||
|
|
||||||
|
You can then run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -m build
|
||||||
|
```
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["setuptools"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "scott"
|
||||||
|
version = "1.0"
|
||||||
|
|
||||||
|
[tools.setuptools.packages.find]
|
||||||
|
where = ["src"]
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
from .scott import Scott
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import argparse
|
||||||
|
import importlib
|
||||||
|
import inspect
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
|
||||||
|
"""
|
||||||
|
Command-line application support for dynamically loaded subcommands.
|
||||||
|
|
||||||
|
The :class:`Scott` class provides the common command-line infrastructure for the package. It owns
|
||||||
|
the ``ArgumentParser``, loads command implementations on demand, and dispatches parsed arguments to
|
||||||
|
the selected command module.
|
||||||
|
|
||||||
|
Each command is expected to be available as ``modules.<name>.command`` and to provide a callable
|
||||||
|
``scott_run(args)`` function. A command module may also provide ``scott_description()`` for its help
|
||||||
|
text and ``scott_arguments(parser)`` for command-specific options. Modules that cannot be imported
|
||||||
|
or do not provide a callable ``scott_run`` function are skipped during registration.
|
||||||
|
|
||||||
|
Typical usage from an application entry point is::
|
||||||
|
|
||||||
|
scott = Scott(__file__, app_desc="A toolset to manage something")
|
||||||
|
for command in commands:
|
||||||
|
scott.register_command(command)
|
||||||
|
scott.run()
|
||||||
|
|
||||||
|
The application entry point is responsible for defining the command names. Once ``run()`` is called,
|
||||||
|
``Scott`` parses the process arguments, validates the selected command, displays parser help for
|
||||||
|
invalid input, and invokes the selected module's ``scott_run(args)`` function.
|
||||||
|
"""
|
||||||
|
|
||||||
|
sys.dont_write_bytecode = True
|
||||||
|
|
||||||
|
class Scott:
|
||||||
|
|
||||||
|
"""
|
||||||
|
Initialize Scott and its argument parser.
|
||||||
|
Parameters:
|
||||||
|
app_dir (str): The directory where the application script is located. This is used to set up
|
||||||
|
the Python path and to resolve relative paths for subcommand modules.
|
||||||
|
app_desc (str): Optional description for the application, used in the argument parser help.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, app_dir: str, app_desc: str = ""):
|
||||||
|
self.script_dir = Path(app_dir).resolve().parent
|
||||||
|
|
||||||
|
# Ensure the script directory is on Python's import path so local subcommand modules can be
|
||||||
|
# imported by name even when this script is executed from another working directory.
|
||||||
|
script_dir_str = str(self.script_dir)
|
||||||
|
if script_dir_str not in sys.path:
|
||||||
|
sys.path.insert(0, script_dir_str)
|
||||||
|
|
||||||
|
self.modules = {}
|
||||||
|
self.subparsers_by_command = {}
|
||||||
|
|
||||||
|
# prepare the argument parser and subparser collection for command registration
|
||||||
|
self.parser = argparse.ArgumentParser()
|
||||||
|
self.parser.description = app_desc
|
||||||
|
self.subparsers = self.parser.add_subparsers(dest="command", required=True)
|
||||||
|
|
||||||
|
"""
|
||||||
|
Register one subcommand by dynamically importing its module.
|
||||||
|
Parameters:
|
||||||
|
command (str): The name of the subcommand to register. This is used to construct the module
|
||||||
|
path as ``modules.<command-name>.command``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def register_command(self, cmd_name: str):
|
||||||
|
try:
|
||||||
|
module_path = f"modules.{cmd_name}.command"
|
||||||
|
module = importlib.import_module(module_path)
|
||||||
|
scott_run = getattr(module, "scott_run", None)
|
||||||
|
if not callable(scott_run):
|
||||||
|
print(
|
||||||
|
f"Warning: Script {cmd_name}.py is missing a scott_run() function, skipping registration.",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
parameter_count = len(inspect.signature(scott_run).parameters)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
parameter_count = 0
|
||||||
|
if parameter_count != 1:
|
||||||
|
print(
|
||||||
|
f"Warning: Script {cmd_name}.py scott_run() must take exactly one argument, skipping registration.",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# store the module for later dispatch when the command is invoked
|
||||||
|
self.modules[cmd_name] = module
|
||||||
|
|
||||||
|
# create a subparser for the command and allow the module to add its own arguments
|
||||||
|
subparser = self.subparsers.add_parser(
|
||||||
|
cmd_name,
|
||||||
|
help = module.scott_description() if hasattr(module, "scott_description") else None,
|
||||||
|
)
|
||||||
|
self.subparsers_by_command[cmd_name] = subparser
|
||||||
|
if hasattr(module, "scott_arguments"):
|
||||||
|
module.scott_arguments(subparser)
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
print(
|
||||||
|
f"Warning: Script {cmd_name}.py not found, skipping registration.",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
|
||||||
|
"""
|
||||||
|
Parse arguments and execute the selected subcommand.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def run(self):
|
||||||
|
try:
|
||||||
|
args = self.parser.parse_args()
|
||||||
|
except SystemExit as error:
|
||||||
|
if error.code != 0:
|
||||||
|
self.parser.print_help()
|
||||||
|
raise
|
||||||
|
|
||||||
|
if args.command not in self.modules:
|
||||||
|
print(f"Error: command '{args.command}' does not exist.", file=sys.stderr)
|
||||||
|
self.parser.print_help()
|
||||||
|
return
|
||||||
|
|
||||||
|
selected_module = self.modules[args.command]
|
||||||
|
try:
|
||||||
|
selected_module.scott_run(args)
|
||||||
|
except Exception as error:
|
||||||
|
print("\n!! Error Encountered !!", file=sys.stderr)
|
||||||
|
print(f"({args.command}): {error}", file=sys.stderr)
|
||||||
|
self.subparsers_by_command[args.command].print_help(sys.stderr)
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
# Scott — Usage Guide
|
||||||
|
|
||||||
|
**scott** is a framework for creating scoped, task-oriented terminal tools. It wraps
|
||||||
|
Python's `argparse` and adds a dynamic subcommand system: each subcommand lives in its
|
||||||
|
own module, is loaded on demand, declares its own CLI options, and is dispatched by the
|
||||||
|
framework. You write small, self-contained command modules; Scott handles argument
|
||||||
|
parsing, help text, validation, and error reporting.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Installation
|
||||||
|
|
||||||
|
Scott is a standard setuptools package. From the package root:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# create and activate a virtual environment (recommended)
|
||||||
|
python -m venv .venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
|
||||||
|
# build a distributable wheel/sdist
|
||||||
|
pip install --upgrade build
|
||||||
|
python -m build
|
||||||
|
|
||||||
|
# install the built wheel
|
||||||
|
pip install dist/scott-1.0-*.whl
|
||||||
|
|
||||||
|
# ...or install in editable mode for development
|
||||||
|
pip install -e .
|
||||||
|
```
|
||||||
|
|
||||||
|
Once installed, import the framework with:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from scott import Scott
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Anatomy of a Scott tool
|
||||||
|
|
||||||
|
A Scott application is a plain Python script (the *entry point*) plus a `modules/`
|
||||||
|
directory of subcommand packages, laid out like this:
|
||||||
|
|
||||||
|
```
|
||||||
|
my-tool/
|
||||||
|
├── my-tool.py # entry point script
|
||||||
|
└── modules/
|
||||||
|
├── cleanup/
|
||||||
|
│ └── command.py # implements the `cleanup` subcommand
|
||||||
|
├── pack/
|
||||||
|
│ └── command.py # implements the `pack` subcommand
|
||||||
|
└── unpack/
|
||||||
|
└── command.py # implements the `unpack` subcommand
|
||||||
|
```
|
||||||
|
|
||||||
|
Each subcommand name maps to `modules/<name>/command.py`. The entry point registers the
|
||||||
|
commands it wants to expose, and Scott imports and dispatches them dynamically.
|
||||||
|
|
||||||
|
### 2.1 The entry point
|
||||||
|
|
||||||
|
```python
|
||||||
|
from scott import Scott
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
# app_dir: path of this script — Scott resolves it to locate the modules/ directory
|
||||||
|
# app_desc: description shown in the tool's help output
|
||||||
|
scott = Scott(__file__, "A toolset to manage EPUB files")
|
||||||
|
|
||||||
|
commands = [
|
||||||
|
"cleanup",
|
||||||
|
"pack",
|
||||||
|
"unpack",
|
||||||
|
]
|
||||||
|
for command in commands:
|
||||||
|
scott.register_command(command)
|
||||||
|
|
||||||
|
scott.run()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
```
|
||||||
|
|
||||||
|
Running the tool:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
$ python my-tool.py --help
|
||||||
|
usage: my-tool.py [-h] {cleanup,pack,unpack} ...
|
||||||
|
|
||||||
|
A toolset to manage EPUB files
|
||||||
|
|
||||||
|
positional arguments:
|
||||||
|
{cleanup,pack,unpack}
|
||||||
|
cleanup This will cleanup
|
||||||
|
pack This will pack
|
||||||
|
unpack This will unpack
|
||||||
|
|
||||||
|
options:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. The command module contract
|
||||||
|
|
||||||
|
Every command module (`modules/<name>/command.py`) is a plain Python module. Scott
|
||||||
|
recognizes the following functions:
|
||||||
|
|
||||||
|
| Function | Required | Purpose |
|
||||||
|
| ------------------------- | -------- | ------------------------------------------------------------------------ |
|
||||||
|
| `scott_run(args)` | **Yes** | The command's entry point. Called with the parsed `argparse` namespace. |
|
||||||
|
| `scott_description()` | Optional | Returns a short help string shown in the command list. |
|
||||||
|
| `scott_arguments(parser)` | Optional | Registers command-specific options on the command's subparser. |
|
||||||
|
|
||||||
|
### 3.1 `scott_run(args)` — required
|
||||||
|
|
||||||
|
The command's main function. It **must accept exactly one argument** (the parsed
|
||||||
|
`argparse` namespace); registration is skipped with a warning otherwise.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def scott_run(args):
|
||||||
|
# args contains any options registered via scott_arguments(),
|
||||||
|
# plus args.command (the subcommand name)
|
||||||
|
print("command: pack")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 `scott_description()` — optional
|
||||||
|
|
||||||
|
Returns a one-line description used as the command's help text in the parent help
|
||||||
|
listing.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def scott_description():
|
||||||
|
return "This will pack"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 `scott_arguments(parser)` — optional
|
||||||
|
|
||||||
|
Receives the command's `argparse` subparser so the command can define its own positional
|
||||||
|
arguments and options. They arrive in `args` at dispatch time.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def scott_arguments(parser):
|
||||||
|
parser.add_argument(
|
||||||
|
"file_path",
|
||||||
|
help="The path where the file to be unpacked."
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
A complete command module:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# modules/unpack/command.py
|
||||||
|
|
||||||
|
def scott_description():
|
||||||
|
return "This will unpack"
|
||||||
|
|
||||||
|
def scott_arguments(parser):
|
||||||
|
parser.add_argument(
|
||||||
|
"file_path",
|
||||||
|
help="The path where the file to be unpacked."
|
||||||
|
)
|
||||||
|
|
||||||
|
def scott_run(args):
|
||||||
|
print(f"command: unpack, file: {args.file_path}")
|
||||||
|
```
|
||||||
|
|
||||||
|
Which produces:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
$ python my-tool.py unpack --help
|
||||||
|
usage: my-tool.py unpack [-h] file_path
|
||||||
|
|
||||||
|
positional arguments:
|
||||||
|
file_path The path where the file to be unpacked.
|
||||||
|
|
||||||
|
options:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. API reference
|
||||||
|
|
||||||
|
### `Scott(app_dir: str, app_desc: str = "")`
|
||||||
|
|
||||||
|
Creates the framework and its argument parser.
|
||||||
|
|
||||||
|
- `app_dir` — typically `__file__` from the entry script. Scott resolves it to the
|
||||||
|
containing directory, which is used to (a) locate the `modules/` packages and (b) is
|
||||||
|
prepended to `sys.path` so the tool works no matter which directory you invoke it from.
|
||||||
|
- `app_desc` — description shown at the top of the tool's help output.
|
||||||
|
|
||||||
|
### `Scott.register_command(cmd_name: str)`
|
||||||
|
|
||||||
|
Registers a subcommand by dynamically importing `modules.<cmd_name>.command`. During
|
||||||
|
registration Scott:
|
||||||
|
|
||||||
|
1. Imports the module; if it cannot be imported, prints a warning to *stderr* and skips
|
||||||
|
the command.
|
||||||
|
2. Verifies `scott_run` exists, is callable, and takes **exactly one** parameter;
|
||||||
|
otherwise warns to *stderr* and skips the command.
|
||||||
|
3. Creates an `argparse` subparser named `cmd_name`, using `scott_description()` (if
|
||||||
|
present) as its help text.
|
||||||
|
4. Calls `module.scott_arguments(subparser)` (if present) so the command can add options.
|
||||||
|
|
||||||
|
Skipped commands never appear in help output and cannot be invoked.
|
||||||
|
|
||||||
|
### `Scott.run()`
|
||||||
|
|
||||||
|
Parses the process arguments and dispatches to the selected command's
|
||||||
|
`scott_run(args)`. Behavior on failure is covered in the next section.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Error handling and exit codes
|
||||||
|
|
||||||
|
| Situation | Behavior | Exit code |
|
||||||
|
| --------------------------------------- | -------------------------------------------------------------------------------------------- | --------- |
|
||||||
|
| Command runs successfully | Normal output. | `0` |
|
||||||
|
| Exception raised inside `scott_run` | Prints `!! Error Encountered !!`, `(command): <error>`, and the command's help to *stderr*. | `0` |
|
||||||
|
| Unknown command / missing required args | argparse error message, then the tool's full help is printed. | `2` |
|
||||||
|
| No command given | Help is printed (a command is **required**). | `2` |
|
||||||
|
|
||||||
|
Example of a command that raised an exception:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
$ python my-tool.py unpack /tmp/book.epub
|
||||||
|
command: unpack
|
||||||
|
|
||||||
|
!! Error Encountered !!
|
||||||
|
(unpack): The unpack command is not yet implemented.
|
||||||
|
usage: my-tool.py unpack [-h] file_path
|
||||||
|
|
||||||
|
positional arguments:
|
||||||
|
file_path The path where the file to be unpacked.
|
||||||
|
|
||||||
|
options:
|
||||||
|
-h, --help show this help message and exit
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that errors inside a command are caught and reported but do not propagate — the
|
||||||
|
process still exits `0`. Commands that need to signal failure should handle it
|
||||||
|
themselves (e.g. via `sys.exit(1)` inside `scott_run`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. A complete, minimal example
|
||||||
|
|
||||||
|
```
|
||||||
|
hello-tool/
|
||||||
|
├── hello-tool.py
|
||||||
|
└── modules/
|
||||||
|
└── greet/
|
||||||
|
└── command.py
|
||||||
|
```
|
||||||
|
|
||||||
|
`hello-tool.py`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from scott import Scott
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
scott = Scott(__file__, "A tiny Scott-powered tool")
|
||||||
|
scott.register_command("greet")
|
||||||
|
scott.run()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
```
|
||||||
|
|
||||||
|
`modules/greet/command.py`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def scott_description():
|
||||||
|
return "Greet someone"
|
||||||
|
|
||||||
|
def scott_arguments(parser):
|
||||||
|
parser.add_argument("name", help="Who to greet")
|
||||||
|
|
||||||
|
def scott_run(args):
|
||||||
|
print(f"Hello, {args.name}!")
|
||||||
|
```
|
||||||
|
|
||||||
|
Run it:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
$ python hello-tool.py greet World
|
||||||
|
Hello, World!
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Notes
|
||||||
|
|
||||||
|
- **Work from any directory.** The entry script's directory is added to `sys.path`
|
||||||
|
automatically, so `python /path/to/my-tool.py pack` works from anywhere.
|
||||||
|
- **Commands are loaded at registration.** Modules are imported once, when
|
||||||
|
`register_command()` is called, and reused for dispatch; only registered commands are
|
||||||
|
loaded.
|
||||||
|
- **Bytecode is disabled.** Scott sets `sys.dont_write_bytecode = True` on import, so no
|
||||||
|
`__pycache__` directories are created for the framework or your modules.
|
||||||
|
- **Layout matters.** The `modules/` directory must be a sibling of the entry script, and
|
||||||
|
each command must be a package directory named exactly like the command
|
||||||
|
(`modules/<name>/command.py`).
|
||||||
|
- **License.** Scott is distributed under the DuxTechnica Limited Use Source Code License
|
||||||
|
Agreement (DT-LUSCL) — see `LICENSE` for details.
|
||||||
|
|
||||||
Reference in New Issue
Block a user