xtr_recipes ¶
A package's Use in an application steps, applied to a project by a command.
Every package that ships a bundle also ships a recipe beside it — the bundle to list, the configuration file to write, the environment variables to set and the ignore lines to add. A recipe is declarative, so the same description that configures an application also says, read backwards, how to unconfigure it.
The command xtr-recipes recipes:sync reads the recipes of the application's
runtime and development dependencies, diffs them against a committed lock file,
and applies the difference: nothing cares how a package arrived, and running it
twice changes nothing the second time.
This module exposes the pieces that read a project, parse a recipe, read or
write the lock, and compute the plan that applies the difference. The commands
that drive them live in :mod:xtr_recipes.command, behind the xtr-recipes
console script.
RECIPES_ENTRY_POINT_GROUP
module-attribute
¶
The entry point group a distribution advertises its recipe package under.
A distribution ships <bundle name> = "xtr_<name>.recipe" here; the value is
a package path. It is located on disk, never imported: importing it would run
the package's own __init__, and one package that fails to import must not
stop every other recipe from being read.
BundleState ¶
How a recipe's bundle came to be in BUNDLES.
listed when the sync added it, adopted when it was already there.
BundleEntry
dataclass
¶
One line of an application's BUNDLES: a bundle, and where it is active.
The bundle is held as the "module:Class" string a recipe and the lock
already use, so the same spelling travels from a manifest through the lock
into the generated file without being translated on the way.
Attributes:
BundlePlanner ¶
Decides which of a plan's candidate bundles the application must list.
Every recipe in a plan names its bundles; the list they go in is one file, so the decision is made once, for all of them together. Two answers come out of it, and each is what the lock records:
- adopted — already listed, so the environments beside it were chosen by the application owner and are left exactly as they are;
- listed — the plan adds it.
Every recipe bundle is listed, even one another listed bundle also
requires: the file shows exactly what the application's dependencies
configure, and a bundle that is both a recipe's own and a peer of another
belongs in it as much as its requirer does. A peer with no recipe of its
own — a transitive package's bundle — is activated by the kernel without
being listed, and debug:bundles shows it.
finalize ¶
finalize(existing: BundlesFile, removed: set[str], candidates: Mapping[str, Mapping[str, bool]]) -> tuple[BundlesFile, dict[str, BundleState]]
Return the bundle list to write and what became of every candidate.
Parameters:
-
existing(BundlesFile) –The list as the application has it now.
-
removed(set[str]) –Targets to take out of it — a package being unconfigured leaves nothing importable behind, whether it was listed by a sync or by hand.
-
candidates(Mapping[str, Mapping[str, bool]]) –Each candidate target mapped to the environments its recipe would list it in, in the order the recipes named them.
Returns:
-
tuple[BundlesFile, dict[str, BundleState]]–The new list, and each candidate's standing in it.
BundleRequirements ¶
Tells which bundle targets load, so a sync can skip the rest.
A recipe names its bundles as "module:Class" targets, and a sync may
only list one whose class the installation actually carries: a broken
installation, or a module a bundle needs missing, would otherwise leave
the application with a bundle list that cannot be imported. A target that
does not load is reported as not loadable, so the recipe is skipped and
retried on the next sync.
Resolve "module:Class" with loader, or by import when none is given.
loadable ¶
Whether target names a loadable bundle of distribution's own package.
Resolving a target imports its module, so a recipe may only name a
bundle under its own distribution's import package: a manifest naming
os:system or another package's module would otherwise make a sync
import whatever it points at. A target outside the package, or one the
installation cannot load, is reported as not loadable, so a sync skips
the recipe and retries next time.
BundlesFile
dataclass
¶
BundlesFile(entries: tuple[BundleEntry, ...] = (), docstring: str | None = None, path: Path | None = None)
An application's bundle list, read as data and written back whole.
The file is parsed with :mod:ast and never imported, so reading it costs
nothing and cannot run application code. What is kept is what the generated
form holds: the module docstring and the ordered entries. Per-entry
comments are not, which is why the file is regenerated rather than patched
— a shape this reader cannot account for raises
:class:~xtr_recipes.exception.BundlesNotEditableError instead of being
rewritten and losing something.
Every change returns a new value, so the one on disk is only touched by
:meth:write.
Attributes:
-
entries(tuple[BundleEntry, ...]) –The bundles in the order the file lists them.
-
docstring(str | None) –The module docstring as its source spells it, quotes and prefix included, so it is written back byte for byte;
Nonewhen the file has none and the default should be written. -
path(Path | None) –The file these entries were read from, when they were read from one; an error raised while rendering names it.
read
classmethod
¶
Read path, or report an empty list when it does not exist yet.
Parameters:
-
path(Path) –The
bundles.pyto read.
Returns:
-
BundlesFile–The file as data; an empty list with no docstring when absent.
Raises:
-
BundlesNotEditableError–The file does not parse, or builds its mapping in a way this reader cannot account for.
adding ¶
Return a copy with every target not already listed appended.
A target already listed is left as it is, flags included: the application owner chose those environments.
removing ¶
Return a copy without the entries whose target is in targets.
render ¶
Render the canonical file, ready for ruff check and ruff format.
Parameters:
-
first_party(Collection[str]) –The application's own top-level package names; an entry whose module starts with one of them is imported in the second import block, as an import sorter would place it.
Returns:
-
str–The whole file, ending in a newline.
Raises:
-
BundlesNotEditableError–Two entries would import the same class name from different modules, which one mapping cannot spell.
ComposeFileEditor ¶
Reads and rewrites the blocks one package owns in a compose.yaml.
A Compose file is one mapping, so a package cannot own a stretch of it the
way it owns a block of .env: what it brings goes under keys every
package shares. Each of its contributions is a block of its own, between
the markers naming its distribution, placed at the end of the top-level key
it belongs under::
services:
###> xtr-orm ###
database:
image: postgres:16-alpine
###< xtr-orm ###
volumes:
###> xtr-orm ###
database_data:
###< xtr-orm ###
The markers are comments, so the file stays valid YAML. A missing key is added at the end of the file. A block is rewritten where it stands, so a service the owner added after it is not moved. The blocks are indented the way the file already is, so they sit beside services written at four spaces as well as at two. Removal takes the blocks out, and a key left with nothing under it goes with them; a file left with nothing reads as empty.
Stateless: every method takes a file's whole text and returns the new one.
has_blocks ¶
Whether text holds any block of package's.
Raises:
-
MarkedBlockError–When one of the package's blocks is opened and never closed.
put_blocks ¶
Return text with package owning exactly sections.
Parameters:
-
text(str) –The Compose file's whole text.
-
package(str) –The distribution the blocks belong to.
-
sections(Mapping[str, Sequence[str]]) –Each top-level key mapped to the YAML lines that go under it; no sections clears every block the package has.
Returns:
-
str–The new text, ending in a newline, or empty when nothing is left.
Raises:
-
MarkedBlockError–When one of the package's blocks is opened and never closed.
EntryPointRecipeSource ¶
Reads each distribution's recipe from its xtr_recipes entry point.
load ¶
Return every advertised recipe, keyed by normalised distribution name.
BundlesNotEditableError ¶
Bases: RecipesError
A bundles.py is shaped in a way its reader cannot edit in place.
The bundle list is read and rewritten mechanically; a file that builds its
mapping some other way — a key that is not an imported name, non-literal
flags, or no single BUNDLES assignment — cannot be changed without
risking what it already holds. Rather than guess, the error reports the
entries to add by hand so the application owner stays in control.
Attributes:
-
path(Path) –The
bundles.pythat could not be rewritten. -
reason(str) –Why it could not be rewritten.
-
entries(tuple[str, ...]) –The bundle targets (
"module:Class") to add by hand.
Record the file, why it is not editable, and what to add by hand.
InvalidManifestError ¶
Bases: RecipesError, ValueError
A recipe manifest holds something its reader cannot make sense of.
Raised where the manifest is parsed rather than letting an unknown table, an unknown key or a mistyped value through: a recipe that would configure an application wrongly should fail at load time, not halfway through a sync. The same error reports a template that names a placeholder the renderer was never given.
Also a :class:ValueError, so code that already guards parsing with
except ValueError keeps working without learning a new exception.
Attributes:
-
package(str) –The distribution whose recipe could not be read.
-
key(str) –The table, key, value or template path at fault.
-
reason(str) –What about it could not be read.
Record which recipe, which key, and why it could not be read.
MarkedBlockError ¶
Bases: RecipesError, ValueError
A recipe's block is opened in a file and never closed.
The markers are the whole reason a recipe can be undone: everything between them belongs to the recipe, everything outside belongs to the application owner. An opening marker with no closing one leaves that line undrawn, and rewriting or removing the block would then swallow whatever follows it — so the file is reported rather than guessed at.
Also a :class:ValueError, so code that already guards parsing with
except ValueError keeps working without learning a new exception.
Attributes:
-
path_or_name(Path | str) –The file whose block is unclosed, or the package the block belongs to when the text was handed over without a path.
-
reason(str) –What about the block could not be read.
Record which file or package, and why its block could not be read.
ProjectNotFoundError ¶
Bases: RecipesError
The project, or the application package inside it, is not where expected.
Raised when no pyproject.toml lies at or above the directory
searched, and when not exactly one package under src/ or the project
root holds a kernel.py — the file that marks the application package.
Attributes:
-
directory(Path) –The directory that was searched.
-
reason(str) –What was looked for and not found.
Record where the search ran and what failed.
RecipeNotInstalledError ¶
Bases: RecipesError
One package was named to configure, and it is not one that can be.
A full sync works from what is installed, so it has nothing to report about a package that is not. Naming one explicitly is different: the answer must be an error rather than a silent plan of nothing, because the cause is usually a package the application does not depend on, or one installed without the recipe that configures it.
Attributes:
-
package(str) –The distribution that was named.
Record the distribution that has no recipe to apply.
RecipesError ¶
Bases: Exception
Base class for every error raised by this library.
Catch this to handle anything applying a recipe can go wrong with; catch a subclass to handle one cause. Every subclass carries the data a caller needs as typed attributes and composes its own message from them, so a handler reads the fields rather than parsing the text.
UnreadableFileError ¶
Bases: RecipesError
A file the tool must read holds bytes it cannot decode.
Raised where xtr.lock or a pyproject.toml is read: a truncated
JSON lock, a manifest that is not valid TOML, or either saved in an
encoding other than UTF-8 would otherwise surface as a bare decode error
with no hint which file was at fault. The file is named so the fix is
obvious.
Attributes:
-
path(Path) –The file that could not be read.
-
reason(str) –What about its bytes could not be decoded.
Record which file could not be read, and why.
UnsafePathError ¶
Bases: RecipesError
A recipe path escapes the project or points at a symbolic link.
A recipe records and resolves paths relative to the project directory, so
one that resolves outside it — through .. or an absolute spelling, in a
manifest or in a tampered xtr.lock — would let a recipe write or delete
anywhere on disk. A write target that is a symbolic link would follow the
link out of the project just the same. Both are refused before anything is
touched.
Attributes:
-
path(str) –The path that could not be made safe, as it reads in the plan or the lock.
-
reason(str) –Why it was refused.
Record the offending path and why it was refused.
KeyPairConfig
dataclass
¶
One [keys] entry: the private key to mint, and what encrypts it.
Attributes:
-
algorithm(str) –The signature algorithm the key is for, one of :data:
KEY_ALGORITHMS; it decides the key's type and size. -
passphrase(str | None) –The
[env]key whose generated secret the private key is encrypted with, orNoneto write it unencrypted. -
path_env(str | None) –The
[env]key the application reads the key's path from, whose default names this very key, orNonewhen nothing does. A project that set it to another file has a key of its own, so none is minted for it.
MarkedBlockEditor ¶
Reads and rewrites the block one package owns in a line-oriented file.
A recipe writes the environment variables and ignore lines it brings between two marker comments naming its distribution::
###> xtr-messenger ###
MESSENGER_DSN=
###< xtr-messenger ###
The markers are what makes undoing possible: removal deletes the block rather than guessing which lines were once written for the package. Everything outside the block belongs to the application owner — a key already set, an ignore line already there — and is adopted: left exactly where it is, never recorded, so it survives the package going away.
A block an earlier release wrote between # >>> <package> and
# <<< <package> is still read as the package's own, and is rewritten
with the current markers the next time the block is written.
Stateless: every method takes a file's whole text and returns the new one, with two helpers so a caller need not repeat the encoding.
env_lines ¶
Return the assignments to write for entries that text lacks.
A key already assigned outside package's own block is the
application owner's and is skipped — adopted, not recorded, so removing
the package leaves it alone. A key commented out is not in the
environment, so the recipe still has its line to contribute.
Parameters:
-
text(str) –The
.envfile's whole text. -
package(str) –The distribution whose block the keys would go in.
-
entries(Mapping[str, str]) –Each key mapped to its default;
""means the recipe has no default to offer.
Returns:
-
str–One
KEY=valueline per key still to write, inentries -
...–order, commented out as
# KEY=where there is no default — an -
tuple[str, ...]–empty
KEY=would set the variable to""and hide the error -
tuple[str, ...]–that says it was never configured. A key already assigned inside
-
tuple[str, ...]–the package's own block keeps the line it has there: the owner
-
tuple[str, ...]–filled the value in, and re-applying the recipe must not undo it.
Raises:
-
MarkedBlockError–When the package's block is opened and never closed.
env_keys ¶
Return the keys :meth:env_lines would write, without their values.
These are the keys the lock records, because they are the ones inside the package's own block: what is skipped as already set belongs to the application owner and must survive the package going away.
Parameters:
-
text(str) –The
.envfile's whole text. -
package(str) –The distribution whose block the keys would go in.
-
entries(Mapping[str, str]) –Each key mapped to its default, as in :meth:
env_lines.
Returns:
Raises:
-
MarkedBlockError–When the package's block is opened and never closed.
env_value ¶
Return the value key is assigned in text, or None when it is not.
The last assignment wins, as it does when the file is loaded; a value wrapped in matching quotes is read without them.
ignore_lines ¶
Return the entries of lines that text does not already carry.
Compared stripped and outside package's own block, so an ignore
rule the application owner wrote by hand is adopted rather than
repeated; a blank entry has nothing to ignore and is dropped.
Raises:
-
MarkedBlockError–When the package's block is opened and never closed.
block_lines ¶
Return what lies inside package's block, or () when it has none.
Raises:
-
MarkedBlockError–When the block is opened and never closed.
put_block ¶
Return text with package's block holding exactly lines.
An existing block is replaced where it stands, so applying the same recipe twice leaves the file byte for byte the same; a new one is appended after a single blank line. No lines means the package contributes nothing, which is the same as having no block at all.
Parameters:
-
text(str) –The file's whole text.
-
package(str) –The distribution the block belongs to.
-
lines(Sequence[str]) –What goes between the markers.
Returns:
-
str–The new text, ending in a newline.
Raises:
-
MarkedBlockError–When the block is opened and never closed.
remove_block ¶
Return text without package's block, or unchanged when it has none.
The blank line that separated the block from its neighbour goes with it, so a file a recipe once wrote into comes back as it was.
Raises:
-
MarkedBlockError–When the block is opened and never closed.
NotesConfig
dataclass
¶
What a recipe cannot do for an application, told to the person instead.
A recipe is declarative: it writes files, lists bundles, adds environment and ignore lines. Three things remain that it either must not do or cannot do, so it prints them for someone to act on — which is why they are kept apart rather than folded into one blob of text.
Attributes:
-
steps(tuple[str, ...]) –Manual changes an Activate or Configure step lists that a declarative recipe cannot make, such as editing application code.
-
check(tuple[str, ...]) –Commands that show the package working, for after the sync.
-
run(tuple[str, ...]) –Commands that put the package to work.
OperationInterface ¶
Bases: Protocol
One step of a plan: what it would say, and what it would do.
A plan is computed in full before anything is written, so a command can
print it and stop — that is the whole of --dry-run and --check.
Every step therefore answers twice: :meth:render for the person reading,
:meth:apply for the project on disk.
Attributes:
-
changes(bool) –Whether applying this step changes the project. A step that only reports — a section heading, a file left alone, a bundle another one already requires — says
False, which is what lets--checkpass on a plan made entirely of messages.
Plan
dataclass
¶
Plan(operations: tuple[OperationInterface, ...] = (), project_operations: tuple[OperationInterface, ...] = (), previous_lock: RecipeLock = RecipeLock())
The ordered steps of one sync, as data.
Computing the whole plan before applying any of it is what makes printing it without doing it, and refusing a project that would change, the same code path as doing it: the steps are the single description both read.
The steps come in two layers because a sync writes in two layers: each package's own, then the two files the whole run shares. Keeping them apart is what lets a run that stops part way say which packages it finished.
Attributes:
-
operations(tuple[OperationInterface, ...]) –Each package's steps, in the order they are reported and applied; every block opens with its heading.
-
project_operations(tuple[OperationInterface, ...]) –The steps of the run as a whole — the bundle list and the lock — carried out once every package has had its say.
-
previous_lock(RecipeLock) –The lock as the last sync left it, which a package this run does not finish keeps.
has_changes
property
¶
Whether any step would touch the project.
A plan can be made entirely of headings, kept files and bundle notes — there is something to say and nothing to do. That is the difference between a sync that reports and one that writes.
apply ¶
Carry out every step, in order.
A run that stops part way leaves files on disk the lock knows nothing about, and the lock is the record a later sync reconciles against. So the lock is written before the failure propagates — for the packages whose every step ran and no others. One that stopped half way keeps the entry the last sync left it, so the next sync plans it again.
PlannedRecipe
dataclass
¶
PlannedRecipe(operations: tuple[OperationInterface, ...] = (), notes: Notes | None = None, files: Mapping[str, LockedFile] = dict[str, LockedFile](), env: tuple[str, ...] = (), gitignore: tuple[str, ...] = ())
What one recipe contributes to a plan, and what it would then be locked as.
The two travel together because they are decided together: whether a file is written or kept is the same judgement as whether the lock records the new hash or the old one. Bundles are absent — they are settled once for the whole plan, after every recipe has named its candidates.
Attributes:
-
operations(tuple[OperationInterface, ...]) –The recipe's own steps, in order: files first, then the shared
.envand.gitignoreblocks. -
notes(Notes | None) –What to print after the steps, or
Nonewhen the recipe has nothing to say. -
files(Mapping[str, LockedFile]) –Each written path, as the lock spells it, mapped to what the lock should record for it.
-
env(tuple[str, ...]) –The environment keys the recipe wrote inside its own block.
-
gitignore(tuple[str, ...]) –The ignore lines it wrote inside its own block.
Project
dataclass
¶
Project(project_dir: Path, app: str, package_dir: Path, dependencies: tuple[str, ...], dev_dependencies: tuple[str, ...], script: str | None)
An application on disk, read once from its pyproject.toml.
Built by :meth:load or :meth:discover; both read the manifest and
find the application package, so a value of this type is known to point
at an application that exists.
The application package is the one package holding kernel.py (see
:class:~xtr_recipes.application_package.ApplicationPackage); nothing in
pyproject.toml names it.
Attributes:
-
project_dir(Path) –The directory that holds
pyproject.toml. -
app(str) –The application's dotted import name —
bookshopforsrc/bookshop/,acme.shopforsrc/acme/shop/. -
package_dir(Path) –The directory of the application package, the one holding
kernel.py; a recipe writes its files below it. -
dependencies(tuple[str, ...]) –The PEP 503-normalised names of the direct dependencies (
[project].dependencies), with extras, markers and versions removed. -
dev_dependencies(tuple[str, ...]) –The development dependencies, read the same way from the
devdependency group ([dependency-groups].dev) and from the list uv kept before dependency groups existed,[tool.uv].dev-dependencies; uv installs the two as one group. A name already in :attr:dependenciesis left out: the application runs with that package, so it is a runtime dependency. An{include-group = ...}entry is not followed — these are the namesuv add --devwrites anduv remove --devtakes out, and an included group is a table of its own. -
script(str | None) –The first
[project.scripts]name, orNonewhen none is declared.
discover
classmethod
¶
Load the project in the nearest ancestor of start holding a manifest.
Parameters:
-
start(Path | None, default:None) –Where to begin the upward search; the current working directory when
None.
Returns:
-
Project–The project found.
Raises:
-
ProjectNotFoundError–When no
pyproject.tomllies at or abovestart, or the application package cannot be found.
load
classmethod
¶
Load the project rooted at project_dir.
Parameters:
-
project_dir(Path) –The directory holding
pyproject.toml.
Returns:
-
Project–The project.
Raises:
-
ProjectNotFoundError–When
project_dirholds nopyproject.toml, or when not exactly one package holds akernel.py.
RecipeConfig
dataclass
¶
RecipeConfig(bundles: Mapping[str, Mapping[str, bool]] = dict(), files: Mapping[str, str] = dict(), env: Mapping[str, str] = dict(), secrets: Mapping[str, SecretConfig] = dict[str, SecretConfig](), keys: Mapping[str, KeyPairConfig] = dict[str, KeyPairConfig](), gitignore: tuple[str, ...] = (), compose: Mapping[str, Mapping[str, tuple[str, ...]]] = dict(), notes: NotesConfig = NotesConfig())
Everything a recipe declares, parsed from its manifest.toml.
Built by :meth:from_toml, which is the trust boundary: it is the only
place untrusted manifest data is turned into these typed fields, so the
rest of the library receives a value it never has to re-check. A hand-built
instance is trusted as given.
Attributes:
-
bundles(Mapping[str, Mapping[str, bool]]) –Each bundle target (
"module:Class") mapped to the environment flags it is listed with, as they appear inBUNDLES. -
files(Mapping[str, str]) –Each destination, relative to the application package, mapped to its template path relative to the recipe.
-
env(Mapping[str, str]) –Each environment variable mapped to its default,
""meaning no default (written commented out so the variable stays unset) and a%generate(secret, …)%placeholder a fresh secret made when the line is written. -
secrets(Mapping[str, SecretConfig]) –Each environment variable whose default is a generator, mapped to how its secret is made.
-
keys(Mapping[str, KeyPairConfig]) –Each private key to mint, relative to the project directory, mapped to its algorithm and the env key encrypting it.
-
gitignore(tuple[str, ...]) –The
.gitignorelines the recipe contributes. -
compose(Mapping[str, Mapping[str, tuple[str, ...]]]) –Each Compose file, one of :data:
COMPOSE_FILES, mapped to its top-level keys, each mapped to the YAML lines the recipe puts under it. -
notes(NotesConfig) –What the recipe prints rather than does.
from_toml
classmethod
¶
Parse one recipe's manifest, validating every table, key and value.
Parameters:
-
package(str) –The distribution whose manifest this is, named in errors.
-
data(Mapping[str, object]) –The manifest, already read from TOML into a mapping.
Returns:
-
RecipeConfig–The parsed, validated recipe content.
Raises:
-
InvalidManifestError–On an unknown table, an unknown key, a malformed
"module:Class"bundle target, an unknown generator or key algorithm, or a value of the wrong type — each naming the package and the key at fault.
RecipeContent
dataclass
¶
One recipe as a source hands it over: unparsed manifest and templates.
This is the boundary between discovering recipes and interpreting them. A
source — the installed entry points, or a fake in a test — produces these,
and the loader turns each into a :class:~xtr_recipes.recipe_loader.Recipe.
Keeping the raw bytes lets the loader hash exactly what shipped.
Attributes:
-
manifest(bytes) –The raw
manifest.tomlbytes. -
templates(Mapping[str, bytes]) –Each template path, relative to the recipe, mapped to its raw bytes.
Recipe
dataclass
¶
One parsed recipe, ready to apply.
Attributes:
-
distribution(str) –The PEP 503-normalised name of the distribution that ships the recipe.
-
config(RecipeConfig) –The declarative content, parsed and validated.
-
templates(Mapping[str, bytes]) –Each template path mapped to its raw bytes.
-
recipe_hash(str) –A sha256 over the manifest and every template, so a sync re-applies a recipe when its content changes rather than when the shared package version is bumped.
render ¶
Render a template, substituting ${app} with the application name.
Parameters:
-
template(str) –The template path, as it appears under
[files]in the manifest. -
app(str) –The application import name put in for
${app}.
Returns:
-
str–The rendered text.
Raises:
-
InvalidManifestError–When no such template exists, or the template names a placeholder the renderer was not given.
RecipeLoader ¶
Loads recipes from a source, parsing and hashing each.
The default source reads the installed distributions' xtr_recipes
entry points; a test passes its own so no installation is needed.
Use source for discovery, or the entry-point source by default.
load ¶
Return every recipe the source offers, parsed, sorted by distribution.
Raises:
-
InvalidManifestError–When a manifest cannot be parsed.
LockedFile
dataclass
¶
A file a recipe wrote, as the lock remembers it.
Attributes:
-
sha256(str) –The hash of the content the recipe wrote, telling an untouched file from one the application owner has since edited.
-
adopted(bool) –Whether the file was already present when the recipe first ran, and so must never be deleted on removal.
LockEntry
dataclass
¶
LockEntry(recipe: str = '', bundles: Mapping[str, BundleState] = dict(), files: Mapping[str, LockedFile] = dict(), env: tuple[str, ...] = (), gitignore: tuple[str, ...] = ())
What one recipe applied to the project.
Attributes:
-
recipe(str) –The recipe hash in force when it was applied.
-
bundles(Mapping[str, BundleState]) –Each bundle target mapped to how it entered
BUNDLES. -
files(Mapping[str, LockedFile]) –Each written file path mapped to what was written.
-
env(tuple[str, ...]) –The environment keys the sync wrote inside its own block; adopted keys are not recorded, so they are never removed.
-
gitignore(tuple[str, ...]) –The ignore lines the sync wrote inside its own block.
RecipeLock
dataclass
¶
The whole xtr.lock: every applied recipe, keyed by distribution.
The lock alone is enough to undo a recipe after its package is removed, so
it records paths relative to the project directory, /-separated.
load
classmethod
¶
Read xtr.lock from project_dir; a missing file is an empty lock.
write ¶
Write xtr.lock into project_dir: sorted keys, 2-space, newline-ended.
dumps ¶
Return the exact text :meth:write would write: sorted, 2-space, newline-ended.
A sync compares this against the file already on disk, so it writes the
lock only when the lock actually changed — the difference between a
--check that passes and one that fails.
RecipePlanner ¶
Plans one recipe at a time, reading the project but never writing to it.
Everything it decides, it decides from what is on disk now: whether a file is absent, untouched since the lock recorded it, edited or adopted, and whether a shared block would come out any different. Nothing is applied here, so a plan can be printed and thrown away.
One planner serves one plan run: it remembers which of the application's
config packages have already been accounted for, so two recipes writing
into one do not both claim to create its __init__.py. Build a fresh one
per run.
Plan for project, reading its shared blocks through editor.
configure ¶
Plan a recipe the lock has never recorded.
A file the project already has is adopted — kept as it is and locked
as adopted, so removing the package later leaves it alone. So is one
at the place an earlier layout put it, config/<name>.py for
config/packages/<name>.py: it already configures the package, and
a second copy beside it would configure it twice.
update ¶
Plan a recipe whose content has moved on from what the lock recorded.
Parameters:
-
recipe(Recipe) –The recipe as it ships now.
-
prior(LockEntry) –What the lock says was applied last time.
-
force(bool) –Whether to overwrite a file that is not the sync's to overwrite; without it the new content goes beside the file.
Returns:
-
PlannedRecipe–The recipe's steps and what the lock should then say.
A file the lock recorded at the place an earlier layout put it is carried to where the recipe writes it now when the recipe wrote it, and reconciled there as if it had always been; one the recipe adopted stays where it is, the owner's as before.
unconfigure ¶
Plan the undoing of a recipe whose package is gone.
The lock alone says what to undo, which is the point of keeping it: every file it recorded as written and untouched goes, and the package's own blocks in the shared files are removed. An edited or adopted file still configures the package that is gone, so left where it is the application would fail to load it; it is the owner's, so it is not deleted either, but renamed out of the way with its content intact.
config_packages ¶
Plan every config package a file the run writes sits in, once each.
The bundle list is written by the run as a whole rather than by a
recipe, and it lives in config/ too, so the run asks here for the
packages a recipe's file would have been given.
Parameters:
-
destination(str) –The file's path relative to the application package.
RecipeSourceInterface ¶
Bases: Protocol
A place recipes come from, keyed by the distribution that ships each.
Structural on purpose: the default source reads the installed
distributions' xtr_recipes entry points, while a test supplies its own
built from bytes in memory, so the loader is exercised without installing
anything — a fake, not a mock.
load ¶
Return every available recipe, keyed by normalised distribution name.
RecipeSurvey
dataclass
¶
RecipeSurvey(installed: Mapping[str, Recipe] = _no_recipes(), skipped: Mapping[str, tuple[str, ...]] = _no_targets(), selection: SyncSelection = SyncSelection(), lock: RecipeLock = RecipeLock())
What a project's recipes are and how each stands against the lock.
The same reading a sync starts from, stopped before anything is planned: enough to report a project, not enough to change it. A command that only tells the application owner what is configured reads this, so the rule for which recipes count — the runtime and development dependencies, minus the ones whose bundle class the installation does not carry — is stated once.
Attributes:
-
installed(Mapping[str, Recipe]) –Each recipe of a runtime or development dependency whose bundles all load, keyed by distribution.
-
skipped(Mapping[str, tuple[str, ...]]) –Each package left out because its bundle class does not load, mapped to the targets that could not be loaded.
-
selection(SyncSelection) –Where each of them stands — never configured, configured and current, configured and since changed, or locked and no longer installed.
-
lock(RecipeLock) –The lock as the last sync left it, so a package the lock still records but the project no longer installs can be read from it.
SecretConfig
dataclass
¶
How one generated secret is made: how many random bytes, spelled how.
Written in an [env] default as %generate(secret)%, optionally followed
by keyword arguments — %generate(secret, bytes=64, encoding=hex)%,
%generate(secret, encoding=base64, prefix=whsec_)% — and read by
:meth:parse, which is where a manifest's spelling is checked.
Attributes:
-
byte_count(int) –How many random bytes the secret carries, from :data:
MIN_BYTESto :data:MAX_BYTES. -
encoding(str) –How those bytes are spelled, one of :data:
ENCODINGS. -
prefix(str) –Text written before them, for a format that marks its secrets.
parse
classmethod
¶
Read the generator value spells, or None when it is a plain default.
Parameters:
-
package(str) –The distribution whose manifest this is, named in errors.
-
key(str) –The
[env]key the value is the default of, named in errors. -
value(str) –The default as the manifest writes it.
Returns:
-
SecretConfig | None–How the secret is made, or
Nonewhenvalueis no generator.
Raises:
-
InvalidManifestError–When
valueopens a generator and does not spell one: an unknown kind, an unknown or repeated argument, a size out of range, an unknown encoding or an unsafe prefix. A misspelt generator would otherwise reach.envas a literal, and the application would read the placeholder as its secret.
generate ¶
Return a fresh secret: the prefix, then :attr:byte_count random bytes encoded.
SyncDraft
dataclass
¶
SyncDraft(selection: SyncSelection = SyncSelection(), installed: Mapping[str, Recipe] = _no_recipes(), planned: Mapping[str, PlannedRecipe] = _no_planned(), undone: Mapping[str, tuple[OperationInterface, ...]] = _no_steps(), skipped: Mapping[str, tuple[str, ...]] = _no_targets(), states: Mapping[str, BundleState] = _no_states(), lock: RecipeLock = RecipeLock(), listed: frozenset[str] = frozenset())
A sync with every package decided, before any of it is put in order.
Two things are read off it, and they must agree: the steps it reports and the lock it would leave behind. Keeping both here is what makes them agree — the standing a bundle is reported with is the one recorded, and a file reported as kept is the one the lock keeps as it was.
Attributes:
-
selection(SyncSelection) –Which packages the sync configures, updates, undoes or leaves alone.
-
installed(Mapping[str, Recipe]) –Each installed recipe, keyed by distribution.
-
planned(Mapping[str, PlannedRecipe]) –What each configured or re-applied recipe would do.
-
undone(Mapping[str, tuple[OperationInterface, ...]]) –The steps that undo each package being unconfigured.
-
skipped(Mapping[str, tuple[str, ...]]) –Each package whose bundle class the installation does not carry, mapped to the targets that could not be loaded.
-
states(Mapping[str, BundleState]) –Each candidate bundle's standing in the final list.
-
lock(RecipeLock) –The lock as the last sync left it.
-
listed(frozenset[str]) –The bundle targets the application's list held before the run, so an unconfigured package's bundles are only reported as removed when they were there to remove.
sections ¶
Return one block of steps per package: undone first, then applied, then skipped.
next_lock ¶
Return the lock this sync would leave behind.
An untouched package keeps everything but its bundle standings, which are recomputed: another package arriving or leaving changes what requires what, and the lock is where that is read back from.
SyncOptions
dataclass
¶
How to run one sync.
The defaults are the whole sync: every installed recipe against the lock, and nothing overwritten that the sync does not own.
Attributes:
-
force(bool) –Overwrite a file the application owner has edited or that was adopted, instead of putting the new content beside it.
-
only(str | None) –Re-apply one package and leave the rest of the lock alone;
Nonesyncs everything. Re-applying is unconditional — a package whose recipe has not changed is applied again anyway, which is what makes it a way to restore a file that went missing.
SyncSelection
dataclass
¶
SyncSelection(unconfigure: tuple[str, ...] = (), configure: tuple[str, ...] = (), update: tuple[str, ...] = (), unchanged: tuple[str, ...] = ())
The four groups a sync sorts packages into, as names.
Built by diffing what is installed against what the lock records, which is why a sync does not care how a package arrived or left: the difference is the work, and running it twice finds none.
Attributes:
-
unconfigure(tuple[str, ...]) –Locked packages no longer installed, in lock order. Each is undone from the lock alone and touches only what it recorded, so the order they are undone in does not matter.
-
configure(tuple[str, ...]) –Installed packages the lock has never recorded.
-
update(tuple[str, ...]) –Locked packages whose recipe content has moved on.
-
unchanged(tuple[str, ...]) –Locked packages with nothing to re-apply; their bundle standings are still recomputed, because another package arriving or leaving changes what requires what.
diff
classmethod
¶
diff(installed: Mapping[str, Recipe], lock: RecipeLock, held: Collection[str] = ()) -> SyncSelection
Sort every installed and locked package into its group.
Parameters:
-
installed(Mapping[str, Recipe]) –Each installed recipe, keyed by distribution.
-
lock(RecipeLock) –What the last sync recorded.
-
held(Collection[str], default:()) –Packages still depended on whose bundle class does not load. A locked one is left exactly as the lock has it: a broken or partial installation is no reason to delete what was applied.
Returns:
-
SyncSelection–The selection a full sync works from.
only
classmethod
¶
Select one package, re-applied whether or not its recipe has changed.
Synchronizer ¶
Synchronizer(project: Project, source: RecipeSourceInterface | None = None, requirements: BundleRequirements | None = None)
Brings a project in line with the recipes of its runtime and development dependencies.
The work is a diff: what is installed against what the lock records. Nothing cares how a package arrived or left, so the same run configures what is new, re-applies what has changed, undoes what is gone, and finds nothing to do the second time.
Planning and applying are separate on purpose. :meth:plan only reads, so
a command can print the steps or refuse a project that would change;
:meth:apply carries out a plan already computed.
Sync project from source, resolving bundles with requirements.
plan ¶
Compute every step the sync would take, writing nothing.
Parameters:
-
options(SyncOptions | None, default:None) –How to run; the default syncs everything and overwrites nothing the sync does not own.
Returns:
-
Plan–The plan, in the order it reads and applies.
Raises:
-
BundlesNotEditableError–The application's bundle list is shaped in a way it cannot be rewritten from. Raised before any step is computed, so a project that cannot be finished is not half-done.
-
RecipeNotInstalledError–One package was named and it has no recipe to apply.
survey ¶
Report what is installed and where each recipe stands, planning nothing.
Reads exactly what :meth:plan reads and stops there, so a command
that only tells the application owner what is configured agrees with
the one that configures it.
Returns:
-
RecipeSurvey–Each installed recipe, each package skipped for want of its
-
RecipeSurvey–bundle class, and where the lock leaves them.
Raises:
-
BundlesNotEditableError–The application's bundle list is shaped in a way it cannot be rewritten from.