my-arch 1.0.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.
- my_arch-1.0.0/PKG-INFO +100 -0
- my_arch-1.0.0/README.md +69 -0
- my_arch-1.0.0/arch/Architectonic.py +505 -0
- my_arch-1.0.0/arch/README.md +4 -0
- my_arch-1.0.0/arch/__init__.py +51 -0
- my_arch-1.0.0/arch/__main__.py +5 -0
- my_arch-1.0.0/arch/base/Cell.py +123 -0
- my_arch-1.0.0/arch/base/Idx.py +267 -0
- my_arch-1.0.0/arch/base/Lang.py +110 -0
- my_arch-1.0.0/arch/base/__init__.py +21 -0
- my_arch-1.0.0/arch/base/sqltypes.py +77 -0
- my_arch-1.0.0/arch/code/Block.py +517 -0
- my_arch-1.0.0/arch/code/Element.py +445 -0
- my_arch-1.0.0/arch/code/File.py +178 -0
- my_arch-1.0.0/arch/code/Imports.py +422 -0
- my_arch-1.0.0/arch/code/Module.py +149 -0
- my_arch-1.0.0/arch/code/__init__.py +23 -0
- my_arch-1.0.0/arch/idx/__init__.py +60 -0
- my_arch-1.0.0/arch/idx/cli.py +454 -0
- my_arch-1.0.0/arch/idx/config.py +287 -0
- my_arch-1.0.0/arch/idx/documents.py +196 -0
- my_arch-1.0.0/arch/idx/engine.py +490 -0
- my_arch-1.0.0/arch/idx/header_engine.py +294 -0
- my_arch-1.0.0/arch/idx/headers.py +736 -0
- my_arch-1.0.0/arch/idx/model.py +526 -0
- my_arch-1.0.0/arch/idx/spec_tui.py +375 -0
- my_arch-1.0.0/arch/idx/tui.py +328 -0
- my_arch-1.0.0/arch/irix/Color.py +123 -0
- my_arch-1.0.0/arch/irix/Color.ts +61 -0
- my_arch-1.0.0/arch/irix/__init__.py +10 -0
- my_arch-1.0.0/arch/irix/irix-dark.yaml +294 -0
- my_arch-1.0.0/arch/irix/irix-light.yaml +293 -0
- my_arch-1.0.0/arch/py.typed +0 -0
- my_arch-1.0.0/arch/tools/__init__.py +23 -0
- my_arch-1.0.0/arch/tools/assay/__init__.py +31 -0
- my_arch-1.0.0/arch/tools/assay/checks.py +2065 -0
- my_arch-1.0.0/arch/tools/assay/cli.py +246 -0
- my_arch-1.0.0/arch/tools/assay/context.py +264 -0
- my_arch-1.0.0/arch/tools/assay/diff.py +172 -0
- my_arch-1.0.0/arch/tools/assay/engine.py +448 -0
- my_arch-1.0.0/arch/tools/assay/gather.py +222 -0
- my_arch-1.0.0/arch/tools/assay/model.py +321 -0
- my_arch-1.0.0/arch/tools/assay/models.py +89 -0
- my_arch-1.0.0/arch/tools/assay/report.py +909 -0
- my_arch-1.0.0/arch/tools/assay/routing.py +147 -0
- my_arch-1.0.0/arch/tools/assay/sites.py +202 -0
- my_arch-1.0.0/arch/tools/common.py +33 -0
- my_arch-1.0.0/arch/tools/dev/__init__.py +5 -0
- my_arch-1.0.0/arch/tools/dev/set_dircolors.py +115 -0
- my_arch-1.0.0/arch/tools/mod/__init__.py +7 -0
- my_arch-1.0.0/arch/tools/mod/apply_edit.py +219 -0
- my_arch-1.0.0/arch/tools/mod/document.py +116 -0
- my_arch-1.0.0/arch/tools/mod/infer_exports.py +66 -0
- my_arch-1.0.0/arch/tools/mod/sync.py +977 -0
- my_arch-1.0.0/arch/tools/viz/__init__.py +6 -0
- my_arch-1.0.0/arch/tools/viz/tree.py +452 -0
- my_arch-1.0.0/pyproject.toml +246 -0
my_arch-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: my-arch
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: An architectonic framework for building cognitive software.
|
|
5
|
+
Author: Robb Doering
|
|
6
|
+
Author-email: Robb Doering <robb@doering.ai>
|
|
7
|
+
License-Expression: MPL-2.0
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
10
|
+
Requires-Dist: asyncpg>=0.30.0
|
|
11
|
+
Requires-Dist: coverage>=7.10.5
|
|
12
|
+
Requires-Dist: gitpython>=3.1.45
|
|
13
|
+
Requires-Dist: greenlet>=3.2.4
|
|
14
|
+
Requires-Dist: jinja2>=3.1.6
|
|
15
|
+
Requires-Dist: logfire>=4.0.0
|
|
16
|
+
Requires-Dist: more-itertools>=10.7.0
|
|
17
|
+
Requires-Dist: my-basis>=1.0.0
|
|
18
|
+
Requires-Dist: pandas>=2.3.1
|
|
19
|
+
Requires-Dist: mypy>=1.17.1
|
|
20
|
+
Requires-Dist: pydantic>=2.11.7
|
|
21
|
+
Requires-Dist: regex>=2025.7.34
|
|
22
|
+
Requires-Dist: sqlmodel>=0.0.39
|
|
23
|
+
Requires-Dist: pyyaml>=6.0.3
|
|
24
|
+
Requires-Dist: yapf>=0.43.0
|
|
25
|
+
Requires-Dist: dspy>=2.5.0 ; extra == 'assay'
|
|
26
|
+
Requires-Dist: pyratatui>=0.2.9 ; extra == 'terminal'
|
|
27
|
+
Requires-Python: >=3.14
|
|
28
|
+
Provides-Extra: assay
|
|
29
|
+
Provides-Extra: terminal
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+

|
|
33
|
+
|
|
34
|
+
# myArch: _A Systematic Development Framework_
|
|
35
|
+
|
|
36
|
+
  [](/LICENSE) [](https://github.com/pre-commit/pre-commit) [](https://github.com/facebook/pyrefly) [](https://github.com/astral-sh/ruff)
|
|
37
|
+
|
|
38
|
+
`myArch` has two deliberately distinct index domains:
|
|
39
|
+
|
|
40
|
+
- `arch.Quad` is the preferred name for the original fixed, four-place architectonic address.
|
|
41
|
+
`arch.Idx` remains its compatibility name.
|
|
42
|
+
- `arch.idx.Idx` is the definitive arbitrary-depth document index: numeric, alphabetic, Roman,
|
|
43
|
+
symbolic, dotted or compact, optionally marked and wrapped.
|
|
44
|
+
|
|
45
|
+
They are not subtypes of one another.
|
|
46
|
+
A Quad admits the empty root and abstract `a` / `b` halves and has a special four-branch ancestry; a document idx is a non-empty, arbitrary-depth sequence whose rendering policy is independent of its place.
|
|
47
|
+
Keeping them separate makes those invariants visible instead of weakening either model.
|
|
48
|
+
|
|
49
|
+
The `arch` executable is both an agent-oriented linter and a human-oriented terminal workspace.
|
|
50
|
+
Arguments select a deterministic CLI operation; bare `arch` on a real terminal opens the PyRatatui browser.
|
|
51
|
+
|
|
52
|
+
```console
|
|
53
|
+
$ arch check docs src
|
|
54
|
+
$ arch --json plan docs | jq '.plans[] | select(.changed)'
|
|
55
|
+
$ arch apply --dry-run --diff docs
|
|
56
|
+
$ arch apply docs
|
|
57
|
+
$ arch # TUI when stdin/stdout are terminals
|
|
58
|
+
|
|
59
|
+
$ arch format --check src docs # report non-canonical configured header blocks
|
|
60
|
+
$ arch format --diff src docs # print patches, never write
|
|
61
|
+
$ arch format src docs # atomically format them
|
|
62
|
+
$ arch spec --input headers.yaml --output headers.yaml
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The safety rule is structural: a file containing no recognized idx is never modified, even by `--operation reindex --insertion all`.
|
|
66
|
+
In a partially indexed file, the default `observed` insertion scope fills only hierarchy depths already represented in that file.
|
|
67
|
+
Every write is planned first, content-hash checked, and atomically replaced without normalizing newlines or the final newline.
|
|
68
|
+
|
|
69
|
+
Configuration is layered as command flags, an explicit `--config`, the nearest `.arch.yaml`, `~/.config/my/arch.yaml`, then built-ins.
|
|
70
|
+
Higher-precedence path rules are tried first:
|
|
71
|
+
|
|
72
|
+
```yaml
|
|
73
|
+
default_spec: decimal
|
|
74
|
+
insertion: observed
|
|
75
|
+
|
|
76
|
+
specs:
|
|
77
|
+
decimal:
|
|
78
|
+
styles: [number]
|
|
79
|
+
separator: '.'
|
|
80
|
+
doctrine:
|
|
81
|
+
styles: [number, alpha-lower, roman-lower]
|
|
82
|
+
separator: '.'
|
|
83
|
+
marker: '.'
|
|
84
|
+
max_depth: 6
|
|
85
|
+
|
|
86
|
+
paths:
|
|
87
|
+
- path: /absolute/path/to/canon.md
|
|
88
|
+
spec: doctrine
|
|
89
|
+
- regex: '^journal/[0-9]{4}/'
|
|
90
|
+
spec: doctrine
|
|
91
|
+
- glob: 'docs/**'
|
|
92
|
+
spec: decimal
|
|
93
|
+
|
|
94
|
+
ignore:
|
|
95
|
+
- 'vendor/**'
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
See the [idx guide](docs/idx.md), [design explanation](docs/idx-design.md), and [rendered API page](docs/idx-api.md) for document indexes; see the [Header formatting guide](docs/headers.md) for `HeaderSpec`, `arch format`, and the keyboard-first profile editor.
|
|
99
|
+
|
|
100
|
+
______________________________________________________________________
|
my_arch-1.0.0/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
# myArch: _A Systematic Development Framework_
|
|
4
|
+
|
|
5
|
+
  [](/LICENSE) [](https://github.com/pre-commit/pre-commit) [](https://github.com/facebook/pyrefly) [](https://github.com/astral-sh/ruff)
|
|
6
|
+
|
|
7
|
+
`myArch` has two deliberately distinct index domains:
|
|
8
|
+
|
|
9
|
+
- `arch.Quad` is the preferred name for the original fixed, four-place architectonic address.
|
|
10
|
+
`arch.Idx` remains its compatibility name.
|
|
11
|
+
- `arch.idx.Idx` is the definitive arbitrary-depth document index: numeric, alphabetic, Roman,
|
|
12
|
+
symbolic, dotted or compact, optionally marked and wrapped.
|
|
13
|
+
|
|
14
|
+
They are not subtypes of one another.
|
|
15
|
+
A Quad admits the empty root and abstract `a` / `b` halves and has a special four-branch ancestry; a document idx is a non-empty, arbitrary-depth sequence whose rendering policy is independent of its place.
|
|
16
|
+
Keeping them separate makes those invariants visible instead of weakening either model.
|
|
17
|
+
|
|
18
|
+
The `arch` executable is both an agent-oriented linter and a human-oriented terminal workspace.
|
|
19
|
+
Arguments select a deterministic CLI operation; bare `arch` on a real terminal opens the PyRatatui browser.
|
|
20
|
+
|
|
21
|
+
```console
|
|
22
|
+
$ arch check docs src
|
|
23
|
+
$ arch --json plan docs | jq '.plans[] | select(.changed)'
|
|
24
|
+
$ arch apply --dry-run --diff docs
|
|
25
|
+
$ arch apply docs
|
|
26
|
+
$ arch # TUI when stdin/stdout are terminals
|
|
27
|
+
|
|
28
|
+
$ arch format --check src docs # report non-canonical configured header blocks
|
|
29
|
+
$ arch format --diff src docs # print patches, never write
|
|
30
|
+
$ arch format src docs # atomically format them
|
|
31
|
+
$ arch spec --input headers.yaml --output headers.yaml
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The safety rule is structural: a file containing no recognized idx is never modified, even by `--operation reindex --insertion all`.
|
|
35
|
+
In a partially indexed file, the default `observed` insertion scope fills only hierarchy depths already represented in that file.
|
|
36
|
+
Every write is planned first, content-hash checked, and atomically replaced without normalizing newlines or the final newline.
|
|
37
|
+
|
|
38
|
+
Configuration is layered as command flags, an explicit `--config`, the nearest `.arch.yaml`, `~/.config/my/arch.yaml`, then built-ins.
|
|
39
|
+
Higher-precedence path rules are tried first:
|
|
40
|
+
|
|
41
|
+
```yaml
|
|
42
|
+
default_spec: decimal
|
|
43
|
+
insertion: observed
|
|
44
|
+
|
|
45
|
+
specs:
|
|
46
|
+
decimal:
|
|
47
|
+
styles: [number]
|
|
48
|
+
separator: '.'
|
|
49
|
+
doctrine:
|
|
50
|
+
styles: [number, alpha-lower, roman-lower]
|
|
51
|
+
separator: '.'
|
|
52
|
+
marker: '.'
|
|
53
|
+
max_depth: 6
|
|
54
|
+
|
|
55
|
+
paths:
|
|
56
|
+
- path: /absolute/path/to/canon.md
|
|
57
|
+
spec: doctrine
|
|
58
|
+
- regex: '^journal/[0-9]{4}/'
|
|
59
|
+
spec: doctrine
|
|
60
|
+
- glob: 'docs/**'
|
|
61
|
+
spec: decimal
|
|
62
|
+
|
|
63
|
+
ignore:
|
|
64
|
+
- 'vendor/**'
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
See the [idx guide](docs/idx.md), [design explanation](docs/idx-design.md), and [rendered API page](docs/idx-api.md) for document indexes; see the [Header formatting guide](docs/headers.md) for `HeaderSpec`, `arch format`, and the keyboard-first profile editor.
|
|
68
|
+
|
|
69
|
+
______________________________________________________________________
|
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
############
|
|
2
|
+
### HEAD ###
|
|
3
|
+
############
|
|
4
|
+
### STANDARD
|
|
5
|
+
from typing import ClassVar, Any, Self
|
|
6
|
+
from collections.abc import Iterator, Iterable, AsyncGenerator
|
|
7
|
+
import itertools as it
|
|
8
|
+
import more_itertools as mi
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import functools as ft
|
|
11
|
+
import contextlib as ctx
|
|
12
|
+
import subprocess
|
|
13
|
+
|
|
14
|
+
### EXTERNAL
|
|
15
|
+
import pydantic as pyd
|
|
16
|
+
import jinja2 as jn
|
|
17
|
+
import logfire as fire
|
|
18
|
+
|
|
19
|
+
# SQLAlchemy
|
|
20
|
+
from sqlalchemy import URL
|
|
21
|
+
from sqlalchemy.exc import SQLAlchemyError
|
|
22
|
+
import sqlalchemy.ext.asyncio as aiosql
|
|
23
|
+
|
|
24
|
+
# SQLModel
|
|
25
|
+
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
26
|
+
|
|
27
|
+
### INTERNAL
|
|
28
|
+
from my import ut, typist, RegexStore, env
|
|
29
|
+
from .base import Lang, Idx, Cell
|
|
30
|
+
|
|
31
|
+
############
|
|
32
|
+
### DATA ###
|
|
33
|
+
############
|
|
34
|
+
# Constants
|
|
35
|
+
DEFAULT_BASE = ('Element', 'Elements')
|
|
36
|
+
|
|
37
|
+
# Caches
|
|
38
|
+
JINJA_CACHE: dict[str, jn.Template] = {}
|
|
39
|
+
|
|
40
|
+
LOADED = False
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
############
|
|
44
|
+
### BODY ###
|
|
45
|
+
############
|
|
46
|
+
class Architectonic(pyd.BaseModel):
|
|
47
|
+
"""The in-memory architectonic: a mapping of Idx to Cell, plus the machinery around it.
|
|
48
|
+
|
|
49
|
+
Built from an `architectonic.yaml` file below a root directory, it layers on the
|
|
50
|
+
filesystem naming conventions, a static parameter cache, a jinja template environment,
|
|
51
|
+
the irix color palettes, and an optional async database connection. A default instance
|
|
52
|
+
is exported as `ARCH` at import time, located via `$MY_ARCH` or the current directory.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
model_config = pyd.ConfigDict(arbitrary_types_allowed=True)
|
|
56
|
+
|
|
57
|
+
root: pyd.DirectoryPath
|
|
58
|
+
file: pyd.FilePath
|
|
59
|
+
size: int = 511
|
|
60
|
+
data: dict[Idx, Cell] = {}
|
|
61
|
+
parameters: dict[Idx, dict[str, dict[str, Any]]] = {}
|
|
62
|
+
jinja: jn.Environment | None = None
|
|
63
|
+
|
|
64
|
+
DB: ClassVar[aiosql.AsyncEngine | None] = None
|
|
65
|
+
DARK_IRIX: ClassVar[list[list[list[str]]]] = []
|
|
66
|
+
LIGHT_IRIX: ClassVar[list[list[list[str]]]] = []
|
|
67
|
+
IRIX_MAP: ClassVar[list[list[str]]] = []
|
|
68
|
+
SETUP: ClassVar[bool] = False
|
|
69
|
+
INST: ClassVar[Self | None] = None
|
|
70
|
+
|
|
71
|
+
RGXS: ClassVar[RegexStore] = RegexStore.new(
|
|
72
|
+
options=dict(
|
|
73
|
+
force_named_groups=True,
|
|
74
|
+
),
|
|
75
|
+
title=r'([[:upper:]][[:lower:]]+)+',
|
|
76
|
+
suffix=r'\.[[:lower:]]{2,4}',
|
|
77
|
+
arch_file=r'^_([ab]_)?(?P=title)(?P=suffix)$',
|
|
78
|
+
arch_dir=r'^_[0-3]_[[:lower:]]+$',
|
|
79
|
+
inst_file=r'^(?P=title)(?P=suffix)$',
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# -------------------
|
|
83
|
+
# `0` Initial Methods
|
|
84
|
+
# -------------------
|
|
85
|
+
def __new__(cls, *args, **kwargs) -> Self:
|
|
86
|
+
"""Ensure the one-time class setup has run before any instance is created."""
|
|
87
|
+
if not cls.SETUP:
|
|
88
|
+
cls.setup()
|
|
89
|
+
return super().__new__(cls)
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def setup(cls) -> None:
|
|
93
|
+
"""Perform one-time class setup: load the irix palettes and connect the DB if configured."""
|
|
94
|
+
# I. Setup Irix color palette
|
|
95
|
+
cls.DARK_IRIX, cls.LIGHT_IRIX = cls.setup_irix()
|
|
96
|
+
|
|
97
|
+
# II. Setup SQLAlchemy database connection
|
|
98
|
+
if ut.has_all(env, 'MY_DB_USER', 'MY_DB_PASS', 'MY_DB_HOST', 'MY_DB_PORT', 'MY_DB_NAME'):
|
|
99
|
+
with fire.span('Connecting to database...'):
|
|
100
|
+
cls.connect_db()
|
|
101
|
+
|
|
102
|
+
cls.SETUP = True
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def connect_db(cls) -> None:
|
|
106
|
+
"""Create the async SQLAlchemy engine from the `MY_DB_*` environment variables."""
|
|
107
|
+
# assert '=' in env.MY_DB_ARGS, f'Invalid DB args "{env.MY_DB_ARGS}"'
|
|
108
|
+
# query = dict(arg.split('=', 1) for arg in env.MY_DB_ARGS.strip('? ').split('&'))
|
|
109
|
+
query = dict()
|
|
110
|
+
url = URL(
|
|
111
|
+
drivername=env.MY_DB_DRIVER,
|
|
112
|
+
username=env.MY_DB_USER,
|
|
113
|
+
password=env.MY_DB_PASS,
|
|
114
|
+
host=env.MY_DB_HOST,
|
|
115
|
+
port=env.flags.MY_DB_PORT,
|
|
116
|
+
database=env.MY_DB_NAME,
|
|
117
|
+
query=query, # type: ignore
|
|
118
|
+
)
|
|
119
|
+
cls.DB = aiosql.create_async_engine(url, echo=True)
|
|
120
|
+
|
|
121
|
+
@classmethod
|
|
122
|
+
async def disconnect_db(cls) -> None:
|
|
123
|
+
"""Dispose of the database engine, if one was created."""
|
|
124
|
+
if cls.SETUP and (db := getattr(cls, 'DB', None)):
|
|
125
|
+
await db.dispose()
|
|
126
|
+
|
|
127
|
+
@classmethod
|
|
128
|
+
def new(cls, root: pyd.DirectoryPath, **kwargs: Any) -> Self:
|
|
129
|
+
"""Build an architectonic from a root directory containing an `architectonic.yaml` file."""
|
|
130
|
+
# I. Read in primary data object
|
|
131
|
+
file = root / 'architectonic.yaml'
|
|
132
|
+
ut.validate_file(file)
|
|
133
|
+
if not (data := kwargs.pop('data', {})):
|
|
134
|
+
data = cls.load(file, kwargs)
|
|
135
|
+
|
|
136
|
+
return cls(root=root, file=file, data=data, **kwargs)
|
|
137
|
+
|
|
138
|
+
@pyd.model_validator(mode='after')
|
|
139
|
+
def create(self) -> Self:
|
|
140
|
+
"""Populate the parameter cache and jinja environment after validation."""
|
|
141
|
+
if not self.parameters:
|
|
142
|
+
self.parameters = self.read_parameter_cache()
|
|
143
|
+
|
|
144
|
+
# I. Setup jinja evironment
|
|
145
|
+
if self.jinja is None:
|
|
146
|
+
template_dir = self.get_dir('0001') / 'templates'
|
|
147
|
+
ut.validate_dir(template_dir)
|
|
148
|
+
self.jinja = jn.Environment(
|
|
149
|
+
loader=jn.FileSystemLoader(template_dir), trim_blocks=True, lstrip_blocks=True
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
return self
|
|
153
|
+
|
|
154
|
+
@pyd.model_serializer(mode='plain')
|
|
155
|
+
def serialize(self) -> dict[str, dict[str, str | list[str]]]:
|
|
156
|
+
"""Serialize the architectonic as a sorted mapping of index strings to dumped cells."""
|
|
157
|
+
return {str(idx): cell.model_dump() for idx, cell in sorted(self.data.items())}
|
|
158
|
+
|
|
159
|
+
# -------------------
|
|
160
|
+
# `-` Private Methods
|
|
161
|
+
# -------------------
|
|
162
|
+
@classmethod
|
|
163
|
+
def load(cls, file: pyd.FilePath, kwargs: dict[str, Any]) -> dict[Idx, Cell]:
|
|
164
|
+
"""Read an architectonic file into a dict of cells, prepending the base cell."""
|
|
165
|
+
# I. Read file contents into a nested dict
|
|
166
|
+
arch = typist.from_file(file)
|
|
167
|
+
assert arch is not None, f'Empty arch file {file}'
|
|
168
|
+
|
|
169
|
+
# II. Create base cell
|
|
170
|
+
base_names = kwargs.pop('base_names', DEFAULT_BASE)
|
|
171
|
+
cells = {
|
|
172
|
+
Idx(''): Cell(
|
|
173
|
+
idx=Idx(''),
|
|
174
|
+
singular=base_names[0],
|
|
175
|
+
plural=base_names[1],
|
|
176
|
+
division='',
|
|
177
|
+
moments='antithesis thesis synthesis',
|
|
178
|
+
)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
# III. Create all cells
|
|
182
|
+
cells |= {Idx(idx): Cell.read(idx, data) for idx, data in arch.items()}
|
|
183
|
+
return cells
|
|
184
|
+
|
|
185
|
+
def get_lang(self, idx: Idx) -> Lang:
|
|
186
|
+
"""Get the language for a given index."""
|
|
187
|
+
for anc in (idx, *idx.ancestors):
|
|
188
|
+
cell = self.data[anc]
|
|
189
|
+
if cell.lang is not None:
|
|
190
|
+
return cell.lang
|
|
191
|
+
return Lang.PY
|
|
192
|
+
|
|
193
|
+
@classmethod
|
|
194
|
+
def setup_irix(cls) -> tuple[list[list[list[str]]], list[list[list[str]]]]:
|
|
195
|
+
"""Read the irix YAML files into nested lists of dark and light colors."""
|
|
196
|
+
# I. Find the files
|
|
197
|
+
irix_dir = Path(__file__).parent / 'irix'
|
|
198
|
+
dark, light = (irix_dir / 'irix-dark.yaml', irix_dir / 'irix-light.yaml')
|
|
199
|
+
ut.validate_file(dark, light)
|
|
200
|
+
|
|
201
|
+
# II. Read them into dictionary obects
|
|
202
|
+
maps = typist.from_yaml(dark), typist.from_yaml(light)
|
|
203
|
+
|
|
204
|
+
# III.i. Split up the top-level keys into sets of four
|
|
205
|
+
chambers: list = list(map(list, mi.sliced(list(maps[0].keys()), 4)))
|
|
206
|
+
assert len(chambers) == 5, f'Malformed dark irix file returned {chambers=}'
|
|
207
|
+
if not cls.IRIX_MAP:
|
|
208
|
+
cls.IRIX_MAP = chambers
|
|
209
|
+
|
|
210
|
+
# III. Parse the contents into lists
|
|
211
|
+
ret = [
|
|
212
|
+
[[list(irix[shade].values()) for shade in chamber] for chamber in chambers]
|
|
213
|
+
for irix in maps
|
|
214
|
+
]
|
|
215
|
+
|
|
216
|
+
return ret[0], ret[1]
|
|
217
|
+
|
|
218
|
+
def infer_idx(self, path: Path) -> Idx | None:
|
|
219
|
+
"""Infer the index of a path from its architectonic directory parts, if possible."""
|
|
220
|
+
if path.is_absolute():
|
|
221
|
+
if str(path).startswith(str(self.root)):
|
|
222
|
+
path = path.relative_to(self.root)
|
|
223
|
+
else:
|
|
224
|
+
fire.error(f'Path {path} is not relative to the ARCH root: {self.root}')
|
|
225
|
+
return None
|
|
226
|
+
|
|
227
|
+
if arch_parts := list(it.takewhile(self.RGXS['arch_dir'].match, path.parts)):
|
|
228
|
+
return Idx.new(''.join(part[1] for part in mi.take(4, arch_parts)))
|
|
229
|
+
else:
|
|
230
|
+
fire.error(f'Path {path} does not match ARCH directory pattern.')
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
def dir_filter(self, paths: Iterable[Path]) -> list[pyd.DirectoryPath]:
|
|
234
|
+
"""Filter the given paths down to architectonic directories, sorted by name."""
|
|
235
|
+
dirs = [p for p in paths if p.is_dir() and self.RGXS['arch_dir'].match(p.name)]
|
|
236
|
+
return list(sorted(dirs, key=lambda d: d.name))
|
|
237
|
+
|
|
238
|
+
def file_filter(self, paths: Iterable[Path]) -> list[pyd.FilePath]:
|
|
239
|
+
"""Filter the given paths down to instance files, sorted by path."""
|
|
240
|
+
files = [p for p in paths if p.is_file() and self.RGXS['inst_file'].match(p.name)]
|
|
241
|
+
return list(sorted(files, key=Path.as_posix))
|
|
242
|
+
|
|
243
|
+
# -------------------
|
|
244
|
+
# `+` Primary Methods
|
|
245
|
+
# -------------------
|
|
246
|
+
def read_parameter_cache(self) -> dict[Idx, dict[str, dict[str, Any]]]:
|
|
247
|
+
"""Read the cached parameter files into a mapping of index to per-class parameters."""
|
|
248
|
+
directory = self.get_dir(Idx('0001')) / 'parameters'
|
|
249
|
+
ut.validate_dir(directory)
|
|
250
|
+
return {
|
|
251
|
+
Idx(file.stem.split('_')[1]): typist.from_yaml(file)
|
|
252
|
+
for file in directory.glob('_*.yaml')
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
# ------------------
|
|
256
|
+
# `x` Public Methods
|
|
257
|
+
# ------------------
|
|
258
|
+
### ---------------
|
|
259
|
+
### `x.i` Overrides
|
|
260
|
+
### ---------------
|
|
261
|
+
def __contains__(self, idx: Idx) -> bool:
|
|
262
|
+
return Idx.new(idx) in self.data
|
|
263
|
+
|
|
264
|
+
def __len__(self) -> int:
|
|
265
|
+
return self.size
|
|
266
|
+
|
|
267
|
+
def __getitem__(self, idx: Idx | str) -> Cell:
|
|
268
|
+
return self.data[Idx.new(idx)]
|
|
269
|
+
|
|
270
|
+
def keys(self) -> list[Idx]:
|
|
271
|
+
"""Return the indices of all cells."""
|
|
272
|
+
return list(self.data.keys())
|
|
273
|
+
|
|
274
|
+
def values(self) -> list[Cell]:
|
|
275
|
+
"""Return all cells."""
|
|
276
|
+
return list(self.data.values())
|
|
277
|
+
|
|
278
|
+
def items(self) -> list[tuple[Idx, Cell]]:
|
|
279
|
+
"""Return all (index, cell) pairs."""
|
|
280
|
+
return list(self.data.items())
|
|
281
|
+
|
|
282
|
+
def idx_iter(self) -> Iterator[Idx]:
|
|
283
|
+
"""Yield the indices of all cells."""
|
|
284
|
+
yield from self.data.keys()
|
|
285
|
+
|
|
286
|
+
@ft.cached_property
|
|
287
|
+
def langs(self) -> set[Lang]:
|
|
288
|
+
"""Return the set of languages explicitly assigned to any cell."""
|
|
289
|
+
return {cell.lang for cell in self.data.values() if cell.lang is not None}
|
|
290
|
+
|
|
291
|
+
### -----------------
|
|
292
|
+
### `x.ii` Filesystem
|
|
293
|
+
### -----------------
|
|
294
|
+
def get_filename(self, idx: Idx | str, lang: Lang | None = None) -> str:
|
|
295
|
+
"""Construct the architectonic filename for an index, e.g. `_Element.py` or `_a_Word.md`."""
|
|
296
|
+
idx = Idx.new(idx)
|
|
297
|
+
if lang is None:
|
|
298
|
+
lang = self.get_lang(idx)
|
|
299
|
+
|
|
300
|
+
prefix = '_' if idx.is_concrete else f'_{idx[-1]}_'
|
|
301
|
+
suffix = f'.{lang.suffix}' if lang else ''
|
|
302
|
+
return f'{prefix}{self[idx].singular}{suffix}'
|
|
303
|
+
|
|
304
|
+
def get_dirname(self, idx: Idx | str) -> str:
|
|
305
|
+
"""Construct the architectonic directory name for an index, e.g. `_0_elements`."""
|
|
306
|
+
idx = Idx.new(idx)
|
|
307
|
+
if len(idx) == 0:
|
|
308
|
+
return ''
|
|
309
|
+
elif not idx.is_concrete:
|
|
310
|
+
return self.get_dirname(idx - 1)
|
|
311
|
+
|
|
312
|
+
return f'_{idx[-1]}_{self[idx].plural.lower()}'
|
|
313
|
+
|
|
314
|
+
def get_dir(self, idx: Idx | str) -> pyd.DirectoryPath:
|
|
315
|
+
"""Construct the absolute directory path for an index below the root."""
|
|
316
|
+
idx = Idx.new(idx)
|
|
317
|
+
ancestors = list(map(self.get_dirname, idx.concrete_ancestors))
|
|
318
|
+
if idx.is_concrete:
|
|
319
|
+
ancestors.append(self.get_dirname(idx))
|
|
320
|
+
|
|
321
|
+
return self.root / '/'.join(ancestors)
|
|
322
|
+
|
|
323
|
+
def get_file(self, idx: Idx | str, lang: Lang | None = None) -> pyd.FilePath:
|
|
324
|
+
"""Construct the absolute path of the architectonic file for an index."""
|
|
325
|
+
idx = Idx.new(idx)
|
|
326
|
+
return self.get_dir(idx) / self.get_filename(idx, lang)
|
|
327
|
+
|
|
328
|
+
### ----------------
|
|
329
|
+
### `x.iii` Database
|
|
330
|
+
### ----------------
|
|
331
|
+
@ctx.asynccontextmanager
|
|
332
|
+
async def db_session(self) -> AsyncGenerator[AsyncSession]:
|
|
333
|
+
"""Yield an async database session, rolling back on SQLAlchemy errors."""
|
|
334
|
+
assert self.DB is not None, 'Database not setup.'
|
|
335
|
+
factory = aiosql.async_sessionmaker(
|
|
336
|
+
bind=self.DB,
|
|
337
|
+
class_=AsyncSession,
|
|
338
|
+
expire_on_commit=False,
|
|
339
|
+
)
|
|
340
|
+
async with factory() as session:
|
|
341
|
+
try:
|
|
342
|
+
yield session
|
|
343
|
+
except SQLAlchemyError as e:
|
|
344
|
+
await session.rollback()
|
|
345
|
+
fire.error(f'Database session error: {e}')
|
|
346
|
+
raise
|
|
347
|
+
|
|
348
|
+
### ------------------
|
|
349
|
+
### `x.iv` Incidentals
|
|
350
|
+
### ------------------
|
|
351
|
+
def get_template(self, filename: str) -> jn.Template:
|
|
352
|
+
"""Fetch a jinja template by filename, caching compiled templates globally."""
|
|
353
|
+
if filename in JINJA_CACHE:
|
|
354
|
+
return JINJA_CACHE[filename]
|
|
355
|
+
elif self.jinja is not None:
|
|
356
|
+
JINJA_CACHE[filename] = ret = self.jinja.get_template(filename)
|
|
357
|
+
return ret
|
|
358
|
+
else:
|
|
359
|
+
raise RuntimeError('Jinja environment not initialized.')
|
|
360
|
+
|
|
361
|
+
def render(self, filename: str, data: dict[str, Any], **kwargs: Any) -> str:
|
|
362
|
+
"""Render the named jinja template with the given data."""
|
|
363
|
+
template = self.get_template(filename)
|
|
364
|
+
return template.render(data, **kwargs)
|
|
365
|
+
|
|
366
|
+
def get_parameters(self, idx: Idx, name: str) -> dict[str, Any]:
|
|
367
|
+
"""Look up the static parameters for a named class, falling back to ancestors' files."""
|
|
368
|
+
if idx in self.parameters:
|
|
369
|
+
# I. Primary case: This element has paramters
|
|
370
|
+
return self.parameters[idx].get(name, {})
|
|
371
|
+
elif anc_idx := ut.next_in(self.parameters, reversed(list(idx.concrete_ancestors))):
|
|
372
|
+
# II. Fallback case: An ancestor's file contains this element's parameters
|
|
373
|
+
return self.parameters[anc_idx].get(name, {})
|
|
374
|
+
else:
|
|
375
|
+
# III. Null case: Most elements have no static parameters
|
|
376
|
+
return {}
|
|
377
|
+
|
|
378
|
+
def index_file(self, idx: Idx) -> pyd.FilePath:
|
|
379
|
+
"""Get an index file, preferring this instance's mirrored constitution data."""
|
|
380
|
+
program_root = self.get_dir(idx)
|
|
381
|
+
roots = [program_root]
|
|
382
|
+
nucleus_root = self.get_dir(Idx('0'))
|
|
383
|
+
if (instance_root := env.get('MY_SELF')) and program_root.is_relative_to(nucleus_root):
|
|
384
|
+
instance_dir = Path(instance_root) / program_root.relative_to(nucleus_root)
|
|
385
|
+
roots.insert(0, instance_dir)
|
|
386
|
+
|
|
387
|
+
name = f'{self[idx].singular.lower()}-index'
|
|
388
|
+
for root in roots:
|
|
389
|
+
candidates = list(root.glob(f'{name}.*'))
|
|
390
|
+
if not candidates:
|
|
391
|
+
continue
|
|
392
|
+
elif len(candidates) > 1:
|
|
393
|
+
fire.warning(f'Multiple index files found for {idx} in {root}: {candidates}')
|
|
394
|
+
return candidates[0]
|
|
395
|
+
|
|
396
|
+
return program_root / f'{name}.yaml'
|
|
397
|
+
|
|
398
|
+
@classmethod
|
|
399
|
+
def find_arch_file(cls, root: pyd.DirectoryPath) -> pyd.FilePath | None:
|
|
400
|
+
"""Find the architectonic file in a given directory."""
|
|
401
|
+
return next(
|
|
402
|
+
filter(lambda f: f.suffix in {'.yaml', '.yml', '.json'}, root.rglob('architectonic.*')),
|
|
403
|
+
None,
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
@staticmethod
|
|
407
|
+
def _git_common_dir(path: Path) -> Path | None:
|
|
408
|
+
"""Return the git common directory (`.git`) for a path inside a git repo, or None.
|
|
409
|
+
|
|
410
|
+
Uses `git rev-parse --git-common-dir` which returns the shared repository directory
|
|
411
|
+
that is identical for the primary tree and all linked worktrees of the same repo.
|
|
412
|
+
"""
|
|
413
|
+
try:
|
|
414
|
+
result = subprocess.run(
|
|
415
|
+
['git', 'rev-parse', '--git-common-dir'],
|
|
416
|
+
cwd=path,
|
|
417
|
+
capture_output=True,
|
|
418
|
+
text=True,
|
|
419
|
+
timeout=10,
|
|
420
|
+
check=False,
|
|
421
|
+
)
|
|
422
|
+
except OSError, subprocess.TimeoutExpired:
|
|
423
|
+
return None
|
|
424
|
+
if result.returncode != 0:
|
|
425
|
+
return None
|
|
426
|
+
common_dir = result.stdout.strip()
|
|
427
|
+
if not common_dir:
|
|
428
|
+
return None
|
|
429
|
+
common_path = Path(common_dir)
|
|
430
|
+
if not common_path.is_absolute():
|
|
431
|
+
common_path = (path / common_path).resolve()
|
|
432
|
+
return common_path.resolve()
|
|
433
|
+
|
|
434
|
+
@staticmethod
|
|
435
|
+
def _git_toplevel(path: Path) -> Path | None:
|
|
436
|
+
"""Return the git top-level directory for a path inside a git repo, or None.
|
|
437
|
+
|
|
438
|
+
For a primary tree this is the repo root; for a linked worktree it is the
|
|
439
|
+
worktree's own root directory.
|
|
440
|
+
"""
|
|
441
|
+
try:
|
|
442
|
+
result = subprocess.run(
|
|
443
|
+
['git', 'rev-parse', '--show-toplevel'],
|
|
444
|
+
cwd=path,
|
|
445
|
+
capture_output=True,
|
|
446
|
+
text=True,
|
|
447
|
+
timeout=10,
|
|
448
|
+
check=False,
|
|
449
|
+
)
|
|
450
|
+
except OSError, subprocess.TimeoutExpired:
|
|
451
|
+
return None
|
|
452
|
+
if result.returncode != 0:
|
|
453
|
+
return None
|
|
454
|
+
toplevel = result.stdout.strip()
|
|
455
|
+
if not toplevel:
|
|
456
|
+
return None
|
|
457
|
+
return Path(toplevel).resolve()
|
|
458
|
+
|
|
459
|
+
@classmethod
|
|
460
|
+
def resolve_arch_root(cls, arch_root: Path) -> Path:
|
|
461
|
+
"""Resolve the architectonic root, preferring a worktree root when inside one.
|
|
462
|
+
|
|
463
|
+
When ``arch_root`` (typically from ``$MY_ARCH``) points at the primary checkout but
|
|
464
|
+
the current working directory is inside a linked worktree of the *same* repository,
|
|
465
|
+
return the worktree's root instead. This ensures tests and tooling that spawn
|
|
466
|
+
subprocesses with ``cwd=ARCH.root`` exercise the worktree's code, not the primary
|
|
467
|
+
tree's. Primary-tree runs are unaffected: when cwd is not inside a worktree (or is
|
|
468
|
+
inside the primary tree itself), the original ``arch_root`` is returned unchanged.
|
|
469
|
+
"""
|
|
470
|
+
cwd = Path.cwd()
|
|
471
|
+
arch_root = arch_root.resolve()
|
|
472
|
+
|
|
473
|
+
wt_toplevel = cls._git_toplevel(cwd)
|
|
474
|
+
if wt_toplevel is None:
|
|
475
|
+
return arch_root
|
|
476
|
+
if wt_toplevel == arch_root:
|
|
477
|
+
return arch_root
|
|
478
|
+
|
|
479
|
+
wt_common = cls._git_common_dir(cwd)
|
|
480
|
+
arch_common = cls._git_common_dir(arch_root)
|
|
481
|
+
if wt_common is None or arch_common is None:
|
|
482
|
+
return arch_root
|
|
483
|
+
if wt_common != arch_common:
|
|
484
|
+
return arch_root
|
|
485
|
+
|
|
486
|
+
# Same repo, different tree: the worktree root is the correct arch root.
|
|
487
|
+
wt_arch_file = wt_toplevel / 'architectonic.yaml'
|
|
488
|
+
if wt_arch_file.exists():
|
|
489
|
+
return wt_toplevel
|
|
490
|
+
return arch_root
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
# Create a default instance for export
|
|
494
|
+
ARCH: Architectonic
|
|
495
|
+
if not LOADED:
|
|
496
|
+
if 'MY_ARCH' in env:
|
|
497
|
+
_arch_root = env.paths.MY_ARCH
|
|
498
|
+
elif _arch_file := Architectonic.find_arch_file(Path.cwd()):
|
|
499
|
+
_arch_root = _arch_file.parent
|
|
500
|
+
else:
|
|
501
|
+
raise RuntimeError(f'MY_ARCH unset, and no architectonic file below {Path.cwd()}.')
|
|
502
|
+
|
|
503
|
+
_arch_root = Architectonic.resolve_arch_root(_arch_root)
|
|
504
|
+
ut.validate_dir(_arch_root)
|
|
505
|
+
ARCH = Architectonic.INST = Architectonic.new(_arch_root)
|