Metadata-Version: 2.4
Name: rn-forge-commons
Version: 0.8.1
Summary: Shared, framework-agnostic utilities for Python programming
Author: Rohit Narayanan
Author-email: Rohit Narayanan <rohit.nn@gmail.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Dist: ruamel-yaml[oldlibyaml]>=0.19.1
Requires-Dist: tomlkit>=0.15.0
Requires-Dist: verboselogs>=1.7
Requires-Dist: rich>=15.0.0
Requires-Dist: dacite>=1.9.2
Requires-Dist: httpx>=0.28 ; extra == 'all'
Requires-Dist: jinja2>=3.1.6 ; extra == 'all'
Requires-Dist: markdown>=3.7 ; extra == 'all'
Requires-Dist: markdown-it-py>=3.0 ; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-logging>=0.64b0 ; extra == 'all'
Requires-Dist: purgatory>=3.0.1 ; extra == 'all'
Requires-Dist: pydantic>=2.12 ; extra == 'all'
Requires-Dist: python-json-logger>=4.0.0 ; extra == 'all'
Requires-Dist: stamina>=25.2.0 ; extra == 'all'
Requires-Dist: structlog>=25.1.0 ; extra == 'all'
Requires-Dist: python-json-logger>=4.0.0 ; extra == 'json'
Requires-Dist: markdown>=3.7 ; extra == 'markdown'
Requires-Dist: markdown-it-py>=3.0 ; extra == 'markdown'
Requires-Dist: opentelemetry-instrumentation-logging>=0.64b0 ; extra == 'otel'
Requires-Dist: pydantic>=2.12 ; extra == 'pydantic'
Requires-Dist: purgatory>=3.0.1 ; extra == 'resilience'
Requires-Dist: stamina>=25.2.0 ; extra == 'resilience'
Requires-Dist: httpx>=0.28 ; extra == 'resilience'
Requires-Dist: structlog>=25.1.0 ; extra == 'structlog'
Requires-Dist: jinja2>=3.1.6 ; extra == 'templates'
Requires-Dist: assertpy>=1.1 ; extra == 'testing'
Requires-Dist: pytest>=9.1.1 ; extra == 'testing'
Requires-Python: >=3.14
Project-URL: Documentation, https://rn-forge.github.io/pykit/packages/rn-forge-commons/latest/
Project-URL: Source, https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-commons
Project-URL: Changelog, https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-commons/CHANGELOG.md
Project-URL: Issues, https://github.com/rn-forge/pykit/issues
Provides-Extra: all
Provides-Extra: json
Provides-Extra: markdown
Provides-Extra: otel
Provides-Extra: pydantic
Provides-Extra: resilience
Provides-Extra: structlog
Provides-Extra: templates
Provides-Extra: testing
Description-Content-Type: text/markdown

# rn-forge-commons

[Documentation](https://rn-forge.github.io/pykit/packages/rn-forge-commons/latest/)
·
[Changelog](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-commons/CHANGELOG.md)
·
[Source](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-commons)
· [All pykit packages](https://rn-forge.github.io/pykit/)

Shared, framework-agnostic utilities for Python programming.

## Install

Require the package by version range:

```toml
[project]
dependencies = ["rn-forge-commons>=0.8,<0.9"]
```

Optional extras:

| Extra | Adds |
| -- | -- |
| `json` | JSON-formatted log output (`python-json-logger`) |
| `pydantic` | Strict pydantic models for configuration documents, with every failure named by dotted path |
| `otel` | OpenTelemetry logging instrumentation |
| `testing` | `assertpy` + `pytest` integration helpers |
| `resilience` | Async circuit breakers and HTTP retries (`purgatory`, `stamina`, `httpx`) |
| `structlog` | Structured logging over the existing stdlib handlers |
| `templates` | The Jinja template engine, `rn_forge.commons.text.templates` (`jinja2`) |
| `markdown` | Markdown structure, `rn_forge.commons.text.markdown` (`markdown`, `markdown-it-py`) |
| `all` | Everything above |

Console log output is Rich-formatted by default (a hard dependency) when stdout
is a TTY.

## What's inside

Modules are grouped by kind of mechanism. Public class names do not encode the
grouping and are all re-exported from the package facade, so
`from rn_forge.commons import PathUtils` works regardless of which submodule
holds it.

**Top level**

- **`config`** — `Config`: loads JSON/YAML config from a file or directory,
  deep-merges multiple sources, and resolves internal references.
- **`exceptions`** — `AppException`: structured exception base class for the
  `rn-forge-*` family.
- **`findings`** — `Finding`, `Severity`: the structured result shape every
  checker and doctor reports in, serialisable for `--json`.
- **`testing`** — `output_path` fixture and `assertpy` integration, for use from
  `conftest.py`.

**`lang/`** — Python objects themselves; no filesystem, no outside world.

- **`collections`** — `DictUtils`, `ListUtils`: dot-path get/set, typed dot-path
  reads that treat a wrong-shaped value as absent (`get_mapping`, `get_list`,
  `get_strings`, `get_str`, `get_bool`), layered merge with provenance,
  flatten, structural comparison, sorting, filtering, grouping.
- **`dataclasses`** — `DataclassMixin`: adds `as_dict()`, `to_json()`,
  `to_yaml()`, `from_dict()` to any `@dataclass`, reconstructing nested
  dataclasses and enum members on the way back. `from_dict()` is **strict**: a
  value whose type does not match its field is rejected as an `AppException`
  naming the offending field. `LenientDataclassMixin`: the same surface with
  type checking off — for a record whose input is known-ragged, and for the
  two annotations dacite cannot see through (a PEP 695 `type` alias, an
  unbound type variable), which the module docstring spells out.
  `StrictDataclassMixin`: type checking plus rejection of unknown keys at
  every nesting level, named by dotted path (`repository.archtype`) — for
  configuration documents.
- **`models`** (`pydantic` extra) — `StrictModel`, `parse_model`,
  `ModelValidationError`: pydantic models that are strict, frozen and reject
  unknown keys, raising one `AppException` that names every failing key by its
  dotted path. Not on the facade, so `import rn_forge.commons` never loads
  pydantic.
- **`reflection`** — `ReflectUtils`: fully-qualified name resolution,
  error-message formatting, and stack-frame variable inspection.
- **`types`** — the recursive `JsonValue` alias.
- **`utils`** — `AppUtils`, `Base64`: bool parsing, emptiness checks, dynamic
  imports, null-safe attribute access, string joining, unified diffs, and
  base64 encode/decode.

**`fs/`** — everything that reads or writes a real file.

- **`paths`** — `PathUtils`: atomic writes, backups, temp dirs, repository-root
  discovery and the `assert_within` path-escape guard.
- **`hashing`** — `ContentHash`: content and file digests, for detecting drift.
- **`locks`** — `DirectoryLock`, `atomic_symlink`: cross-process serialization
  and atomic publication.
- **`state`** — `StateStore`: a locked, atomically-written JSON key-to-entry
  store.
- **`blocks`** — `ManagedBlock`: render, extract and remove a generator-owned
  fenced block inside a file somebody else owns (`.gitignore`, `CLAUDE.md`,
  `mkdocs.yml`), preserving every byte outside the markers.
- **`documents`** — `JsonUtils`, `YamlUtils`, `DocumentUtils`, `ConfigFormat`:
  JSON/YAML/TOML (de)serialization and file I/O, plus comment-preserving
  round-trip editing of config documents.

**`generation/`** — plan, diff and atomic apply of owned files (`Artifact`,
`plan`, `apply`). Imported directly, never through the facade.

**`text/`** — text formats, each module behind its own extra and imported
directly (never through the facade).

- **`markdown`** (`markdown` extra) — `MarkdownUtils`, `MarkdownHeading`,
  `MarkdownTable`: headings and MkDocs-compatible anchors, link and image
  targets, pipe tables with line positions, and text without fenced code.
- **`templates`** (`templates` extra) — `TemplateEngine`, `RenderError`: strict
  Jinja rendering from a directory or a package, with `autoescape`, a
  process-wide `TemplateEngine.cached` constructor, and `to_toml`/`to_yaml`
  filters.

**`logging/`**

- **`logging`** — `AppLogger`, `LoggingConfig`: idempotent logging setup via
  `dictConfig`, built on `verboselogs` with a custom `TRACE` level. Console
  records go to **stderr**, so a command's stdout carries only its result.
- **`structlog`** (`structlog` extra) — `StructLogger`: structured logging over
  the same handlers.

**`runtime/`** — the process and its surroundings.

- **`environment`** — `Environment`: typed env-var access, plus the
  `require`/`forbid` fail-fast guards a process calls at startup.
- **`console`** — `AppConsole`, `OutputMode`, `console`: a Rich output facade
  with RICH/PLAIN/ QUIET/JSON modes, semantic helpers, a one-call table
  builder and confirm/prompt/status interaction. Imports no Typer or Click, so
  a script, a worker or a Django management command uses it directly;
  `rn-forge-cli` drives its mode from `--quiet`/`--json`.
- **`subprocess`** — `Process`: immutable dataclass that runs a subprocess and
  captures return code, stdout, and stderr.
- **`tasks`** — `Task`, `TaskPool`: parallel task execution via a managed thread
  pool.
- **`plugins`** — `EntryPointLoader`: failure-isolated entry-point plugin
  discovery.

**`integration/`** — protocols for the systems an application talks to.

- **`messaging`**, **`objects`**, **`secrets`** — `MessageBus`, `ObjectStore`,
  `SecretStore` and their in-memory implementations.
- **`resilience`** (`resilience` extra) — async circuit breakers and a retrying
  HTTP client.

Import from the top-level package for the curated public API:

```python
from rn_forge.commons import AppLogger, Config, DictUtils, JsonUtils

logger = AppLogger.initialize(root_logger_name="my-service")
cfg = Config("config")
logger.info("database.host={}", cfg.get("database.host"))
```

### The developer-tooling packages

The command-line layer lives in
[`rn-forge-cli`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-cli)
and the file-owning tooling in
[`rn-forge-tooling`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-tooling).
Both depend on this package; neither is depended on by it, and there are
deliberately no compatibility re-exports in either direction — that would
reverse the dependency. `uv run lint-imports` proves it.

| Concern | Package |
| -- | -- |
| `AppConsole`, Typer app factory, standard options, exit codes, the `[cli]` surface | `rn-forge-cli` |
| `extract_archive`, the install lifecycle, docs checkers | `rn-forge-tooling` |

## Docs

Full API reference and guides are built with mkdocs:

```bash
uv run --group docs mkdocs serve   # or `mkdocs build`
```

Source lives in
[`docs/`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-commons/docs),
configured via
[`mkdocs.yml`](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-commons/mkdocs.yml).

## Development

From the repo root or this directory:

```bash
uv run pytest packages/rn-forge-commons
uv run ruff check packages/rn-forge-commons
uv run pyright
```
