Skip to content

Latest commit

 

History

History
857 lines (674 loc) · 33.6 KB

PLUGINS.md

File metadata and controls

857 lines (674 loc) · 33.6 KB

Plugin Development Guide

This guide is for extending osh with plugins. Plugins can add commands, execution runtimes, and backup sources, and extend core commands in place.

For general osh development, see DEVELOP.md. For using osh, see README.md.

Quick start

A plugin is a Python package whose pyproject.toml declares its surface under [tool.osh]; the code self-describes on import:

# my_plugin/pyproject.toml (or the project's own, co-located package)
[tool.osh]
description = "My hello plugin."

[tool.osh.commands]
hello = "Say hello."
# my_plugin/__init__.py
import click

from osh.handlers import CommandHandler


class Hello(CommandHandler):
    """Say hello."""

    _cli_name = "hello"

    name = "world"

    @click.option("--name", default="world", help="Who to greet.")
    def run(self):
        click.echo(f"Hello, {self.name}!")

Ship it as a Python distribution declaring an osh.plugins entry point, in the same pyproject.toml:

[project]
name = "my-osh-plugin"
version = "1.0.0"

[project.entry-points."osh.plugins"]
my-plugin = "my_plugin"

Install it into the osh environment — editable, so code edits apply on the next osh run:

pipx inject -e osh /path/to/my_plugin   # osh installed with pipx
pip install -e /path/to/my_plugin       # osh installed with pip
python -m osh hello --name developer

The package's __init__.py must expose the plugin's contributions — CommandHandler subclasses, Runtime/ BackupSource subclasses and handler extensions are discovered among its attributes, so re-export implementations living in submodules.

How plugins load

osh loads plugins in two stages, so osh --help stays fast no matter what plugins install:

  1. Metadata inspection — at startup, osh scans plugin sources and reads only plugin declarations ([tool.osh] in pyproject.toml, or osh-plugin.toml for built-in plugins) and entry-point metadata. Command, runtime and source names register as lightweight stubs; no plugin module is imported.
  2. Import on use — a plugin's module is imported only when needed: invoking osh hello imports the plugin declaring hello, resolving the docker runtime imports only the plugin declaring it, and composing backup.restore imports only plugins declaring extends = ["backup.restore"]. Other installed plugins are never evaluated.

A plugin that fails to import reports a clean error at invocation time (Could not load plugin 'x' command 'y': ...) — typically a missing dependency — without affecting other commands.

Plugins are discovered from two sources, in order:

  • built-in packages under osh/plugins/;
  • the osh.plugins entry-point group of installed distributions ([project.entry-points."osh.plugins"] in pyproject.toml — the value is a module path, optionally module:callable for a plain handler that receives the remaining argv).

Everything pip install can reach — PyPI, a git URL, a local directory — works, and pip uninstall removes a plugin.

Plugin declarations

The [tool.osh] table declares the plugin's command surface — the metadata needed to list and place commands without importing the plugin. For installed plugins it lives in the pyproject.toml co-located with the plugin package (or one of its parents in a source checkout); built-in plugins use osh-plugin.toml instead, since they have no pyproject.toml of their own. All keys are optional:

[tool.osh]
description = "What this plugin does."   # fallback help text
min_osh = "1.1"                          # minimum osh version required

# Handlers this plugin extends — the plugin is imported when one of
# them is composed.
extends = ["backup.restore"]

# Named non-CLI handlers this plugin provides — resolvable by name
# through resolve() without generating a command.
handlers = ["my_plugin.cmd"]

# Plugin source names imported before this plugin — for couplings
# extends/resolve() do not cover (direct package imports, side effects).
depends = ["osh-backup"]

[tool.osh.commands]            # top-level `osh <name>` commands
hello = "Say hello."
remote = { group = true, help = "Manage remotes." }   # a command group
_sidecar = { hidden = true, help = "Internal helper." }  # not listed in --help

[tool.osh.group_commands.db]   # subcommands of an existing group
restore = "Restore a backup."

[tool.osh.group_commands.backup]  # subcommands of a plugin-added group
prune = "Prune old backups."

[tool.osh.runtimes]            # Runtime subclasses provided
docker = "Run Odoo inside a Docker Compose stack."

[tool.osh.sources]             # `osh backup get` backup source schemes provided
s3 = "Download a backup from an S3 bucket."

[tool.osh.group_help]          # help text for a plugin-created command group
backup = "Download, cache and restore Odoo database backups."

group_help maps a group_commands group name to the description shown by osh <group> --help and the top-level osh --help listing. Groups auto-created for plugin commands get their help from a same-named runtime, then group_help, then — when a single plugin provides the whole group — that plugin's own description. Declare group_help when several plugins share a group, so the listing describes the group rather than one plugin's slice of it.

Command declaration values are the short help text shown in --help listings, or a table with help and optional group = true when the command is itself a group (e.g. osh backup remote — a handler class with @subcommand methods), or hidden = true for internal commands that never appear in listings (e.g. sidecar helpers spawned by the plugin itself).

The declared names must match what the code provides on import — a command listed in [commands] resolves to a CommandHandler subclass named after it in the plugin package.

depends names other plugin sources (the osh.plugins entry-point names other distributions declare) that must be imported before this plugin's module. Dependencies are imported recursively first; an unknown, disabled or failing dependency fails the plugin's load with a clear error, and circular dependencies are reported. Handler extension doesn't need it — extends plus resolve() already order the imports — depends covers the rest: importing another plugin's package directly, relying on its import side effects, or using its runtimes or handlers at module level. Unresolved extends and depends references also warn at startup, without importing anything.

Command naming convention

Commands follow a noun/verb rule: anything that operates on a persistent resource is osh <noun> <verb> (osh backup restore, osh apps update), while bare top-level verbs are reserved for the primary day-to-day workflow actions (osh init, osh odoo, osh exec, osh test). If your plugin manages a resource, attach its commands to the matching group via group_commands instead of claiming a bare top-level verb. Verbs may deliberately diverge between groups when the underlying concepts differ — osh apps uninstall removes an Odoo module while pip uninstall removes an osh plugin, and osh db set/unset moves a mutable pointer rather than acquiring or removing anything.

Installing and managing plugins

Plugins are ordinary Python distributions — pip is the installer. When osh itself is installed with pipx, pipx inject osh is the same thing into the osh environment:

pipx inject osh git+https://github.com/USER/REPO  # pipx-installed osh
pip install osh-contrib                           # from PyPI
pip install git+https://github.com/USER/REPO      # a git repository
pip install /absolute/path/to/repo                # a local checkout
pip install -e /absolute/path/to/repo             # editable install
pip uninstall osh-contrib                         # remove

The distribution declares its plugins as osh.plugins entry points in pyproject.toml — one plugin per entry point:

[project.entry-points."osh.plugins"]
osh-scan = "osh_scan"
osh-audit = "osh_audit"

Make sure the pyproject.toml carrying [tool.osh] is reachable from the installed package — co-located with it (contributed to the wheel via setuptools [tool.setuptools.package-data] or include-package-data) or inside it. A plugin without declarations installs fine but loads eagerly, losing the lazy-loading benefits.

A plugin's version is the installed distribution's version. Built-in plugins ship inside the osh distribution and inherit osh.__version__.

min_osh declares the minimum osh version the plugin needs — compared numerically (1.1 matches 1.1.0; a +commit local suffix is ignored). When the running osh is older the plugin still lists its commands, but any attempt to import it — invoking a command, composing an extends target, loading a dependent — fails with a requires osh >= X error, and startup warns once. An unparsable value warns but never blocks.

Multi-plugin distributions

One distribution can ship several plugins — like an Odoo addons repo — by declaring an osh.plugins entry point per plugin package:

osh-contrib/
├── pyproject.toml
├── osh_scan/
│   ├── pyproject.toml   # [tool.osh.commands] scan = "..."
│   └── __init__.py
├── osh_audit/
│   ├── pyproject.toml
│   └── __init__.py
└── osh_misc/
    ├── pyproject.toml
    └── __init__.py
[project.entry-points."osh.plugins"]
osh-scan = "osh_scan"
osh-audit = "osh_audit"
osh-misc = "osh_misc"

Each plugin is a real package (relative imports inside it work) and gets its own source name — the entry-point name — used in help listings, depends references and collision-fallback prefixes. Declarations are per plugin: each package's own pyproject.toml holds its [tool.osh] table, co-located with the package.

Command name collisions

A plugin command registers under its declared name (or the function name). If the name is taken — by a core command or an earlier plugin — osh registers it as <plugin>-<name> and warns on every load:

⚠️ plugin 'osh-scan' command 'init' conflicts with the existing 'init'
  command; registered as 'osh-scan-init'.

A fallback name that itself collides is an error, and the command is skipped — the fix is to rename the command in the plugin's [tool.osh] declarations.

Runtime and backup source names are functional identifiers (osh init <name> subcommands and <scheme>:// prefixes), so they cannot be renamed — a collision is an error and the contribution is skipped.

Built-in plugins

Built-in plugins live in osh/plugins/ and register automatically; osh/plugins/osh_test/ is the canonical example. To add one:

  1. Create a package under osh/plugins/<name>/.
  2. Declare the plugin's surface in osh-plugin.toml.
  3. Implement the commands as CommandHandler subclasses, re-exported from __init__.py.
  4. Run python -m osh --help to verify the command appears.

Plugin dependencies

osh does not manage plugin dependencies. Document the packages your plugin needs; users install them into the same environment as osh. Because plugins import lazily, a missing dependency surfaces as an error when the plugin's command runs — other commands keep working.

Public API surface

The stable public API for plugins is intentionally small. Import from these top-level modules only; everything else is internal and may change without notice.

  • osh.common — shared helpers: run_subprocess, run_shell_pipeline, find_project_root, ensure_tool, get_odoo_data_dir, get_odoo_config_path, resolve_config_file, discover_addons_paths, decode_stderr.
  • osh.runtimes — Runtime, EnvSpec, copy_odoo_rc_to_osh_conf.
  • osh.backup_sources — BackupSource, SourceError — the interface for new osh backup get schemes.
  • osh.echo — output helpers: info, warning, error, internal, friendly.
  • osh.handlers — CommandHandler, Env, resolve(), subcommand() — see Extending core commands.
  • osh.db — database and runtime-selection helpers: run_in_runtime, create_db, drop_db, db_exists, resolve_db_name, get_current_branch, resolve_runtime, get_active_runtime_name, deactivate_runtime.
  • osh.sources — source installation helpers (ensure_osh_sources, pull_odoo_sources, ...).

Internal implementation modules live in osh/utils/ and osh/commands/. Diagnostics in osh.commands.helpers is the one exception — it is part of the runtime contract.

API reference

Command plugins

A plugin command is a CommandHandler subclass declaring _cli_name — the name doubles as command placement: a dotted name attaches to the group named by its first segment (backup.restore → osh backup restore), a bare name registers top-level (scan → osh scan). Declare each command in [tool.osh] under commands or group_commands.<group> so it can be listed without importing:

from osh.handlers import CommandHandler


class DbAudit(CommandHandler):
    """Audit the database."""      # the command's --help body

    _cli_name = "db.audit"

    verbose = False

    @click.option("--verbose", is_flag=True)
    def run(self):
        ...

run()'s @click.option/@click.argument decorators are the command's parameters — get_options() reads them across the MRO, so an extension adds options just by stacking decorators on its run() override. For parameters computed at runtime, override the get_options() classmethod and append to super().get_options(). Parsed values become instance attributes. format_cli_help(formatter) writes extra sections after the --help body. Help text has two homes with distinct roles: the [tool.osh] declaration is the short description shown in command listings (it stays authoritative after import, so listings never drift), and the class docstring is the --help body. The _cli_* class attributes customize the wiring:

  • A _-prefixed name segment (_util.fmt, db._fmt) marks a programmatic-only handler — no command generated. Declare such handlers under the handlers key in [tool.osh].
  • _cli_group: target group override for bare names.
  • _cli_context_settings: dict passed to the click.Command.
  • _cli_hidden: truthy hides the command from --help listings — the command stays invocable. Pair it with hidden = true in [tool.osh] so the lazy stub is hidden before the plugin loads.

The handler class is the command's public API — DbAudit(ctx, verbose=True).run() runs it, resolving any registered extensions transparently (see below). To reach a handler by name without importing it directly, osh.handlers.resolve("db.audit") returns the class.

A plugin-provided command group — one handler class whose @subcommand-marked methods become the subcommands — declares its _cli_name as <group>.<name>, like osh backup remote:

from osh.handlers import CommandHandler, subcommand


class DbRemote(CommandHandler):
    """Manage named backup sources."""     # the group's --help body

    _cli_name = "backup.remote"

    @subcommand
    @click.argument("name")
    @click.argument("url")
    def add(self):
        """Add a named backup source."""   # `osh backup remote add --help`
        ...

Each marked method generates a command whose --help body is the method docstring and whose parameters are its own @click.option/@click.argument decorators; a <method>_options() classmethod hook adds dynamic parameters without overriding the method. Extensions subclass the group class and override methods — an anonymous subclass can also add a method, which registers as a new subcommand of the group.

Runtime plugins

A runtime plugin subclasses Runtime and declares the runtime under [runtimes]:

[runtimes]
myruntime = "Run Odoo on my custom target."
from osh.runtimes import Runtime


class MyRuntime(Runtime):
    runtime_type = "runtime"
    name = "myruntime"
    ...

Two core commands drive a runtime's lifecycle:

  • osh init <name> runs the common base setup, then the runtime's init() (its get_init_options() are exposed on the osh init <name> subcommand), and records run.runtime = <name> in .osh/config.toml — the active runtime osh odoo/osh exec/osh db run through. osh init host is the way back to host execution.
  • osh init on an initialized project reports status and calls the active runtime's status() hook.
  • osh stop calls the active runtime's stop() (its get_stop_options() are merged onto osh stop), osh stop <name> its stop_by_name() and osh stop --all its stop_all(). --list turns any of them into a report — the hooks get dry_run=True — and adds every runtime's port_holders() on the project's odoo_port().

The runtime class is imported only when the runtime is selected or one of these hooks runs — listing runtime subcommands in osh init --help and osh init's status report reads the declared descriptions instead.

Plugins should use get_active_runtime_name, set_active_runtime_name and resolve_runtime from osh.db rather than reading the keys directly. Built-in examples: osh/plugins/osh_runtime_docker/ (Docker Compose) and osh/plugins/osh_runtime_venv/ (managed virtualenv). The core host runtime (HostRuntime) is the "bring your own Odoo" default — it runs the machine's Odoo, optionally pinned by osh init host --odoo-command/--odoo-conf — and stops a host Odoo process listening on the project's HTTP port.

Runtime class attributes

class MyRuntime(Runtime):
    runtime_type = "runtime"
    name = "my-target"              # Selected via `osh init my-target`
    label = "My Target"             # Short label shown to users
    description = "Runs Odoo on my custom target."
    help_text = "Long help text for --help."

Runtime class methods

  • get_init_options(cls): return a list of click.Option instances for the osh init <name> subcommand, on top of the common init options (--edition, --dev, --save, --yes, --dry-run, ...). The parsed values are passed to init() as **options.

  • get_stop_options(cls): return a list of click.Option instances that osh stop should accept; the parsed values are passed to stop() as **options.

  • odoo_command(self, base): return the run command osh odoo should use as its argv prefix (it may carry arguments), or None to let the executable be resolved normally. HostRuntime answers the recorded init.odoo_command — its --odoo-command init option.

  • base_odoo_conf(self, base): return a base Odoo config file the generated per-database config (.osh/cache/env/*.conf) should seed from — the project's .osh/odoo.conf/.odoorc overrides it, and generated values (addons_path, db_name, dbfilter) layer on top. HostRuntime answers the recorded init.odoo_conf — its --odoo-conf init option.

  • detect_odoo_version(self, base): return the installed Odoo version for base, or None if it cannot be determined. The base implementation reads the version from the checked-out Odoo sources; runtimes override it to try target-specific detection first (e.g. the local executable, a compose image tag).

  • diagnose(self, base, ctx=None, **options): inspect the project and system. Return a Diagnostics object. osh init <name> and osh odoo both use this. options may include phase ("init" or "run") and any CLI options passed by the command.

  • init(self, target, *, version="", edition="ce", dry_run=False, **options): prepare target for use and return True when ready. This is called by osh init <name> after the common base setup.

  • status(self, ctx, base): report what the runtime has running for base — called by osh init's status report on an initialized project. The default prints nothing.

  • odoo_port(self, base): return the host port Odoo serves HTTP on for base, or None when it cannot be determined. osh stop --list uses it to report what holds the project's port. The default reads the Odoo config files.

  • port_holders(self, ctx, port, base): return report lines for this runtime's holders of host port — a container publishing it, a process listening on it. osh stop --list asks every runtime so holders the active runtime cannot stop are reported too (e.g. a Docker stack publishing the port of a host-runtime project). base is the project asking; lines should name the owning resource and which osh stop invocation frees it. The default reports no holders.

  • stop(self, ctx, base, *, dry_run=False, **options): stop anything the runtime leaves running. Called by osh stop in the project; the host runtimes kill a rogue Odoo process listening on the configured HTTP port. With dry_run=True — osh stop --list — report what would be stopped instead of stopping it.

  • stop_by_name(self, ctx, name, *, dry_run=False, **options): stop resources belonging to another Osh project identified by name — backs osh stop <name>; with dry_run (osh stop <name> --list) they are only reported. The default rejects with an error.

  • stop_all(self, ctx, *, dry_run=False, **options): stop every Osh-managed resource of this runtime — backs osh stop --all; with dry_run (osh stop --all --list) they are only reported. The default is a no-op.

  • env(self, ctx, base, env_spec, *, dry_run=False, **options): execute a command inside the target environment. env_spec is an EnvSpec instance (or an argv-style list for backwards compatibility). It carries the assembled argv list and environment variables such as ODOO_RC and PGDATABASE. When argv is empty, runtimes should launch an interactive shell.

  • db_env(self, ctx, base, env_spec, *, dry_run=False, **options): execute a command inside the database environment, used by osh db exec. The default delegates to env() — the right answer for host-like runtimes where PostgreSQL shares Odoo's environment. Runtimes with a separate database service (e.g. Docker's Compose db service) override it to target that service.

Extending core commands

Core commands delegate to handler classes — CommandHandler subclasses declared under a stable _cli_name. A plugin extends a command's behaviour in place (Odoo _inherit-style) by subclassing the handler it extends — a plain subclass with no _cli_name of its own is an extension of its nearest named ancestor. Declare the extended handlers in [tool.osh] so the plugin is imported when that handler is composed — the declaration is required: nothing else ever triggers the plugin's import, so without it the extension silently never applies:

[tool.osh]
extends = ["db.list"]
from osh.commands.db_cmd import Db


class DanglingFilestores(Db):
    def extra_sections(self):
        lines = list(super().extra_sections())
        ...  # append extra output lines
        return lines

The extends name keeps subcommand granularity: a class extending a group handler is imported when any extends entry names the group (db) or one of its subcommands (db.list).

When the extended handler lives in a plugin (not core), importing it just to subclass it couples the plugins — subclass resolve("name") instead, which returns the effective class by name:

from osh.handlers import CommandHandler, resolve


class FingerprintBaseline(resolve("backup.restore")):
    def post_restore(self):
        super().post_restore()
        ...

Extensions layer onto the handler class in plugin discovery order: a later plugin's subclass is outermost (its methods win) and reaches the earlier ones through super(). Always call super() in an overridden method — skipping it silently drops every earlier extension.

A subclass that does declare its own _cli_name is a new command reusing the parent's implementation — it does not affect the parent:

class SmartRestore(resolve("backup.restore")):
    _cli_name = "backup.smart_restore"

Command state lives on self: self.env is the per-invocation Env, self.ctx its Click context (self.ctx.params holds the parsed CLI values, including plugin-injected options), and the parsed parameters are attributes (self.show_all, self.dry_run, ...). Handlers decompose their work into methods so any step is an extension point.

Every built-in command is a named handler — the _cli_name is the extension target to declare under extends:

_cli_name Commands Handler
init osh init Init (init_cmd)
odoo osh odoo OdooRun (odoo_cmd)
exec osh exec ShellRun (shell_cmd)
db, db.<sub> osh db show/list/set/copy/exec/unset Db (db_cmd)
stop osh stop Stop (stop_cmd)
config, config.show osh config show Config (config_cmd)
config.user.<sub> osh config user verbosity ConfigUser (config_cmd)
config.odoo.<sub> osh config odoo dev ConfigOdoo (config_cmd)

All modules live in osh/commands/. A group handler like Db owns each db.<sub> name — subcommands are @subcommand methods on the class, so extending osh db list means subclassing Db and overriding list() (or a helper it calls, like extra_sections()). Nested groups work the same way: config.user is itself a handler class whose verbosity method backs osh config user verbosity. Plugin-generated groups are limited to one level — a plugin can name backup.remote, not backup.remote.foo.

resolve(name) is the lazy name→class bridge — it imports only the plugin declaring the handler, then returns the class. Subcommand names resolve to their group handler — resolve("db.list") and resolve("db") both return Db. Use it wherever a name is all you have:

def list_dbs(ctx, show_all):
    resolve("db.list")(ctx, show_all=show_all).list()

self.env (Env) offers the same resolution bound to the handler's context — self.env["db.list"](show_all=show_all).list() returns a bound instance of the effective class and invokes its list subcommand. For class-level access, resolve("db").effective() returns the composed class — resolve("odoo").effective().get_options().

Extension points on osh odoo:

  • run() decorators — stacking a @click.option on the extension's run() override adds a flag such as --open without modifying core (get_options() merges them across the MRO). For parameters computed at runtime, override get_options() and append to super().
  • pre_env() — runs after the EnvSpec is assembled, right before Runtime.env() executes. It runs for every osh odoo invocation — exec and --wait paths, --dry-run and subcommands included — so extensions must self-filter. Raising click.ClickException aborts the run. Since osh odoo execs Odoo, pre_env() is also the place to spawn detached sidecar processes that must outlive osh itself.
  • Finer steps such as resolve_db(), build_env_spec() and execute() can be overridden the same way. Useful state: self.extra_args, self.dry_run, self.env_spec and self.has_subcommand (whether extra_args invokes an Odoo subcommand such as shell).

osh db list (Db.list) exposes extra_sections() — extra output lines printed after the database listing (osh_db_drop uses it to report filestore directories with no matching database). Available state: self.base, self.db_names (the full, unfiltered name set parsed from psql -l), self.prefix and self.show_all.

Any named handler can be extended — including plugin-provided ones: other plugins subclass resolve("my_plugin.cmd") (or the class directly) and declare extends = ["my_plugin.cmd"] in their [tool.osh] the same way. Non-CLI handlers use a _-prefixed name (e.g. _util.fmt) and are listed under the handlers key so resolve() can find them without a command.

Backup source plugins

osh backup get <scheme>://... schemes come from BackupSource subclasses. Declare each scheme in [tool.osh.sources] so the plugin is imported only when the scheme is actually used, and so osh backup get --help can list it:

[sources]
myscheme = "Download a backup from my service."
from osh.backup_sources import BackupSource


class MySource(BackupSource):
    scheme = "myscheme"

A source class must:

  • Define a scheme class attribute (e.g. scheme = "s3").
  • Optionally set a short description attribute; it is shown in osh backup get --help next to the scheme.
  • Optionally set a longer help_text attribute; users can view it with osh backup get --help-scheme <scheme>.
  • Implement from_source(source, base, *, output_format="dump", **options) returning an instance. source is the full URL string and base is the project root (or None).
  • Implement default_output_name() returning the default filename.
  • Implement fetch(output, *, dry_run=False) to write the backup to output.
  • Optionally implement canonical_source(source) returning a normalized identity for a source string. osh backup restore <source> restores the newest cached backup whose stored source has the same identity, so implement it when one source can be spelled in different ways — e.g. the https source maps https://host/web?db=x and https://host?db=x to https://host?db=x. The default returns the source string unchanged, meaning only an exact match restores.

The built-in sources ship in the consolidated osh/plugins/osh_backup/ plugin — db://, https:///http://, odoosh:// and ssh:// — alongside the osh backup get/restore/list/remote commands.

osh backup restore is a regular handler (backup.restore), so post-restore behaviour is an ordinary extension subclass: override post_restore() and call super(). The handler state carries self.ctx, self.base, self.db_name and self.env_spec; post_restore is skipped under --dry-run, and a failing extension is reported as a warning without failing the restore (run osh --verbose for the traceback):

from osh.handlers import resolve


class FingerprintBaseline(resolve("backup.restore")):
    def post_restore(self):
        super().post_restore()
        # e.g. record module fingerprints in self.db_name

Example plugin source:

# my_backup/__init__.py
from osh.backup_sources import BackupSource


class S3BackupSource(BackupSource):
    scheme = "s3"
    description = "Download a backup from an S3 bucket."
    help_text = """\
Download a backup from an S3 bucket.

Example:
  osh backup get s3://my-bucket/backups/odoo.sql.gz
"""

    @classmethod
    def from_source(cls, source, base, *, output_format="dump", **options):
        return cls(source)

    def __init__(self, source):
        self.source = source

    def default_output_name(self):
        return "s3-backup.zip"

    def fetch(self, output, *, dry_run=False):
        if dry_run:
            return
        # download from S3 into output

EnvSpec

osh odoo, osh run and osh backup restore pass an EnvSpec dataclass (from osh/runtimes.py) to Runtime.env(). It describes a command to execute inside the prepared target environment:

  • argv: the command and arguments to execute. When empty, runtimes should launch an interactive shell.
  • env: a mapping of extra environment variables (ODOO_RC, PGDATABASE, PGHOST, etc.) to expose before running the command.
  • db_name: the resolved Odoo database name, if any.
  • config_path: the generated --osh-config file path, if any.

Diagnostics

Runtimes return diagnostics via the Diagnostics dataclass in osh/commands/helpers.py:

  • runtime: runtime name.
  • ready: True unless add_error() was called.
  • errors, warnings, info, plan: lists/dicts describing checks.
  • add_error(msg), add_warning(msg), add_info(key, value), add_plan(item): helper methods.

osh odoo aborts on errors; osh init <name> uses plan to show the user what will happen.

Minimal runtime plugin example

# my_runtime/pyproject.toml (or the project's own, co-located package)
[tool.osh]
description = "Echo runtime plugin."

[tool.osh.runtimes]
echo = "Print the Odoo command instead of running it."
# my_runtime/__init__.py
import click
from osh.runtimes import Runtime, EnvSpec
from osh.commands.helpers import Diagnostics


class EchoRuntime(Runtime):
    name = "echo"
    label = "Echo runtime"
    description = "Prints the Odoo command instead of running it."

    @classmethod
    def get_init_options(cls):
        return [
            click.Option(["--my-source"], help="Path to my source.")
        ]

    def diagnose(self, base, ctx=None, **options):
        d = Diagnostics(self.name, project=base)
        d.add_plan("Print the assembled Odoo command.")
        return d

    def init(self, target, *, version="", edition="ce", dry_run=False, **options):
        return True

    def env(self, ctx, base, env_spec, *, dry_run=False, **options):
        click.echo(" ".join(env_spec.argv))
        return 0

osh init echo then runs the base setup plus init(), osh stop and osh stop --all the teardown hooks — no command declarations needed.