From 476bdc31e72c3e6f90ac57cb987eceac0df6a0a4 Mon Sep 17 00:00:00 2001 From: Moshe Zadka Date: Fri, 19 Jan 2024 18:52:11 +0000 Subject: [PATCH] checkpoint --- doc/index.rst | 5 +++ src/gather/entry.py | 82 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 86 insertions(+), 1 deletion(-) diff --git a/doc/index.rst b/doc/index.rst index 781dcc1..896fd1b 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -157,3 +157,8 @@ Command dispatch .. autofunction:: run(*, parser, argv=sys.argv, env=os.environ, sp_run=subprocess.run) +Script entry points +~~~~~~~~~~~~~~~~~~~ + +.. automodule:: gather.entry + :members: diff --git a/src/gather/entry.py b/src/gather/entry.py index 1f47e51..bac3445 100644 --- a/src/gather/entry.py +++ b/src/gather/entry.py @@ -1,5 +1,85 @@ """ -Abstractions for writing entrypoints +Abstractions for writing entrypoints. + +This is meant to reduce the overhead when writing a command with +subcommands. + +In the example below, +the assumption is that your code is in the package +``awesomeawesome``. + +In +``awesomeawesome/__init__.py``: + +.. code:: + + from gather import entry + ENTRY_DATA = entry.EntryData.create(__name__) + +In +``__main__.py``: + +.. code:: + + from gather import entry + from . import ENTRY_DATA + + entry.dunder_main( + globals_dct=globals(), + command_data=ENTRY_DATA, + ) + +Registering a new subcommand is done by adding the following to, +say, +``awesomeawesome/commands.py``: + +.. code:: + + from gather.commands import add_argument + from . import ENTRY_DATA + from commander_data import COMMAND + + + @ENTRY_DATA.register() + def hello(args): + LOGGER.info("Hello world") + + + @ENTRY_DATA.register( + add_argument("--no-dry-run"), + add_argument("--a-thing", default="the-thing"), + ) + def frobnicate(args): + args.run( + COMMAND.rm(recursive=None, force=None) + ) # Will only run with --no-dry-run + hello = args.safe_run( + COMMAND.echo("hello") + ).stdout.strip() # Will run regardless + +Note that commands can be added in any file, +as long as they are registered properly. + +Optionally, +you can add script entry points +in +`pyproject.toml`: + +.. code:: + + [project.scripts] + awesomeawesomectl = "awesomeawesome:ENTRY_DATA.main_command" + frobnicate = "awesome:ENTRY_DATA.sub_command" + +In that case, +the following will work: + +* ``python -m awesomeawesome hello`` +* ``awesomeawesome hello`` +* ``python -m awesomeawesome frobnicate`` +* ``awesomeawesome frobnicate`` +* ``frobincate`` + """ from __future__ import annotations