xtr_maker ¶
Console commands that write application code for the xtr libraries.
Every maker writes through the same pieces, usable on their own:
- :class:
~xtr_maker.class_name.ClassName— what a person typed, as the class, module and file under the folder for its kind. - :class:
~xtr_maker.name_converter.NameConverter— one name as a class, a module, a console name or a table. - :class:
~xtr_maker.import_collector.ImportCollector— the imports a module needs, grouped and sorted. - :class:
~xtr_maker.template_renderer.TemplateRenderer— a template rendered, and refused when its Python does not parse. - :class:
~xtr_maker.file_manager.FileManager— the application package on disk, and writes kept inside the project. - :class:
~xtr_maker.generator.Generator— the files of one run, queued, then written together.
ClassName
dataclass
¶
A class a maker writes: its name, the package it lives in, and its file.
Built with :meth:create from what a person typed; built directly, every
part is checked the same way. The package is the folder for the kind of
class (message_handler) under the application package, plus the
subpackages the person typed before the name (ordering.PlaceOrder)::
name = ClassName.create(
"ordering.place order", root_package="app", kind="message_handler", suffix="Handler"
)
name.short_name # "PlaceOrderHandler"
name.module # "app.message_handler.ordering.place_order_handler"
name.path # PurePosixPath("message_handler/ordering/place_order_handler.py")
Attributes:
-
root_package(str) –The application package, dotted.
-
package(tuple[str, ...]) –The package under it, one entry per folder.
-
short_name(str) –The class's own name.
-
suffix(str) –The ending every class of its kind carries,
""for none.
Raises:
-
InvalidClassNameError–When the class name is not an identifier, is a keyword, or shadows a builtin, or a package part is not an identifier or is a keyword.
name_without_suffix
property
¶
The class name without its kind's suffix: PlaceOrderHandler → PlaceOrder.
snake_name
property
¶
The module's own name: PlaceOrderHandler → place_order_handler.
path
property
¶
The module's file, relative to the application package's directory.
create
classmethod
¶
Resolve what a person typed into the class a maker writes.
Parameters:
-
name(str) –The class name as typed —
place order,PlaceOrder— optionally after subpackages, separated by.or/:ordering.PlaceOrderputs the class in<kind>/ordering/. -
root_package(str) –The application package, dotted.
-
kind(str) –The folder for the kind of class, dotted when nested (
security.voter). -
suffix(str, default:'') –The ending every class of its kind carries; added unless the name already ends with it.
Returns:
-
ClassName–The class, its package and its suffix.
Raises:
-
InvalidClassNameError–When
nameis empty, holds a character no name can, or resolves to a part :class:ClassNamerefuses.
AppPackageNotFoundError ¶
Bases: MakerError
The application package the makers write into, not found by the import system.
Raised the first time a maker needs the package, never while the container is built, so the console keeps running and the message can say which setting to change.
Attributes:
-
root_package(str) –The package that was looked for.
-
project_dir(str) –The project the makers write into.
Record the package that was looked for, and the project it was looked for from.
GeneratedSourceError ¶
Bases: MakerError
Python source rendered from a template that does not parse.
A template is checked every time it renders, so a broken one — or a value that broke it — is reported against the template, never written into the application for the next import to trip over.
Attributes:
-
template(str) –The template that rendered the source.
-
reason(str) –What the parser reported.
-
line(int | None) –The line of the rendered source it reported, when it named one.
Record the template, the parser's message and the line it pointed at.
InvalidArgumentError ¶
Bases: MakerError, ValueError
A configuration value the makers cannot work with.
Also a :class:ValueError, so code catching that keeps working.
InvalidClassNameError ¶
Bases: MakerError, ValueError
A name typed for a class that cannot become one.
Raised before anything is rendered, so a person is asked again rather than
handed a file that does not import. Also a :class:ValueError, which is
what a question's validator raises to have the question asked again.
Attributes:
Record the name and why it was refused.
MakerError ¶
Bases: Exception
Base class for every error raised by this library.
Catch this to handle anything that can stop a maker from writing its files; 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.
TargetExistsError ¶
Bases: MakerError, FileExistsError
A file a maker would write that already exists, or is already about to be written.
Makers never overwrite: code someone wrote, or edited after a maker wrote it, is theirs. The error is raised when the file is queued, before anything is written, so a maker writing several files writes none of them.
Also a :class:FileExistsError, so code catching that keeps working.
Attributes:
-
path(str) –The file, relative to the project directory.
Record the file that is in the way.
UnsafePathError ¶
Bases: MakerError, OSError
A path a maker was asked to write that lies outside the project, or is a symbolic link.
A name typed at a prompt ends up in a path, so every path is checked before a byte is written: one climbing out of the project, or a link pointing anywhere, is refused rather than followed.
Also an :class:OSError, so code catching filesystem failures keeps
working.
Attributes:
Record the path and why it was refused.
FileManager ¶
The project directory, the application package in it, and the files makers write there.
The application package is found where the import system finds it — the very folder the kernel scans — whatever the project's layout. It is looked for when a maker first needs it, never when the manager is built, so a console whose package cannot be found still starts.
Every path written is checked first: one outside the project directory or
a symbolic link is refused, so a name typed at a prompt cannot reach
anywhere else on disk. Each write says what it did — created,
updated or no change — with the path relative to the project.
Write inside project_dir, into the package root_package.
Parameters:
-
project_dir(Path) –The directory holding the application's
pyproject.toml. -
root_package(str) –The application package, dotted.
package_dir
property
¶
The application package's directory.
Raises:
-
AppPackageNotFoundError–When the import system finds no package of that name.
absolute ¶
Return path — relative to the project directory, or absolute — as an absolute path.
Raises:
-
UnsafePathError–When
pathlies outside the project directory.
relative ¶
Return path relative to the project directory, /-separated.
exists ¶
Report whether path exists, a broken symbolic link included.
read ¶
dump ¶
Write content to path, creating its directories, and say what changed.
Raises:
-
UnsafePathError–When
pathis a symbolic link or lies outside the project directory.
ensure_package ¶
Make directory and every folder above it, up to the application package, packages.
A folder with no __init__.py gets one declaring nothing, so the
module a maker writes there imports by its dotted name, and the
container scanning the application finds it.
Raises:
-
AppPackageNotFoundError–When the application package cannot be found.
-
UnsafePathError–When
directorylies outside the application package.
Generator ¶
Generator(file_manager: FileManager, template_renderer: TemplateRenderer, *, final_classes: bool = True)
Queues the files a maker run writes, and writes them once every one is known.
A maker renders all its files before any is written: a name already
taken, or a template that renders broken source, then stops the run with
nothing on disk. A file that exists, or one already queued, is refused —
makers add code, they never replace it — unless the maker read that file
and asks to write it back edited, with :meth:dump_file's replace.
Every template receives final_classes: whether a generated class is
marked @final. :meth:generate_class adds the class's class_name
and module.
Write through file_manager what template_renderer renders.
Parameters:
-
file_manager(FileManager) –Where the files go, and how they are written.
-
template_renderer(TemplateRenderer) –What turns a template into a file's content.
-
final_classes(bool, default:True) –Whether generated classes are marked
@final.
generated_files
property
¶
Every file queued by this generator, written or not, in the order queued.
final_classes
property
¶
Whether generated classes are marked @final.
A maker reads it to import final only for a template that uses it.
generate_class ¶
generate_class(class_name: ClassName, template: str, context: Mapping[str, object] | None = None) -> Path
Queue the module of class_name, rendered from template.
Returns:
-
Path–The module's absolute path.
Raises:
-
TargetExistsError–When the module exists or is already queued.
-
GeneratedSourceError–When the template renders source that does not parse.
generate_file ¶
Queue path (relative to the project directory, or absolute) from template.
Returns:
-
Path–The file's absolute path.
Raises:
-
TargetExistsError–When the file exists or is already queued.
-
GeneratedSourceError–When the template renders source that does not parse.
dump_file ¶
Queue path — relative to the project directory, or absolute — with contents.
Parameters:
-
path(Path | str) –The file to write.
-
contents(str) –What it holds once written.
-
replace(bool, default:False) –Whether a file already at
pathis written over: the maker read it and is writing it back edited.
Returns:
-
Path–The file's absolute path.
Raises:
-
TargetExistsError–When the file is already queued, or exists and
replaceis off.
has_pending_operations ¶
Report whether a file is queued and not yet written.
write_changes ¶
Write every queued file, in the order queued, and empty the queue.
A module inside the application package gets the __init__.py
files it needs to import by its dotted name.
ImportCollector ¶
Collects from module import Name imports and renders them sorted and grouped.
Makers never write an import by hand in a template: they add what the code
uses here and place :meth:render where the imports go, after the
template's own from __future__ import annotations. The output is what
the linter's import sorting writes with its defaults — standard library,
third-party, then the application's own package, a blank line between
them; one statement per module, names ordered constants, classes, then the
rest; a statement too long for one line wrapped with a trailing comma — so
a generated file needs no fixing.
A name added only for annotations goes in an if TYPE_CHECKING: block,
which is written after the rest with TYPE_CHECKING imported for it. Two
modules exporting the same name get the second one an alias; :meth:add
returns the name the code must use.
Collect imports for a module of the application package first_party.
Parameters:
-
first_party(str) –The application's root package; imports from it are grouped last.
-
line_length(int, default:_DEFAULT_LINE_LENGTH) –Longest line a statement is written on before it is wrapped.
add ¶
Import name from module, and return the name the code refers to it by.
Parameters:
-
module(str) –The dotted module to import from.
-
name(str) –The name to import.
-
type_checking(bool, default:False) –Whether the code uses the name in annotations only; a name added both ways is imported at runtime.
Returns:
render ¶
Return the import statements, without a trailing newline; "" when there are none.
NameConverter ¶
Turns one name into the forms the generated code spells it in.
A person types place order, PlaceOrder or place_order; the
class is PlaceOrder, its module place_order, a console command
place-order and a table place_orders. Every form is made from the
same words, so the forms of one name always agree.
The plural covers English as names in code use it: a few rules and a list
of irregular words, applied to the last word only — order_item becomes
order_items. It is not a dictionary, and a name it gets wrong is
changed where it is written.
words
staticmethod
¶
Split value into its words, at separators and at case changes.
as_class_name
staticmethod
¶
Return value as a class name: place order → PlaceOrder.
A name already written as one — an identifier starting with a capital,
with no underscore — is kept as typed, so HTTPClient stays
HTTPClient rather than becoming HttpClient.
as_snake_case
staticmethod
¶
Return value as a module or function name: PlaceOrder → place_order.
as_kebab_case
staticmethod
¶
Return value as a console name: PlaceOrder → place-order.
as_table_name
staticmethod
¶
Return value as a plural, snake-cased table name: OrderItem → order_items.
pluralize
staticmethod
¶
Return value with its last word in the plural, keeping its case.
singularize
staticmethod
¶
Return value with its last word in the singular, keeping its case.
TemplateRenderer ¶
Renders the makers' templates, and checks that Python source comes out.
Templates are read from the directories given, then from the
templates directory shipped in this package, so a directory listed
first can replace a shipped template of the same name. A value a template
names but the maker did not pass is an error, never an empty string, and
nothing is escaped: the output is code, not markup.
Every template ending in .py.jinja is parsed once rendered. A template
that renders source with a syntax error — through its own fault or a value
passed to it — raises :class:GeneratedSourceError rather than handing the
application a module that fails at import.
Read templates from template_dirs, then from this package's templates.
render ¶
Render template with context.
Parameters:
-
template(str) –The template's path under a template directory,
/-separated. -
context(Mapping[str, object]) –The values the template reads.
Returns:
-
str–The rendered text.
Raises:
-
GeneratedSourceError–When
templateends in.py.jinjaand what it rendered does not parse as Python. -
TemplateNotFound–When no template directory holds
template. -
UndefinedError–When the template reads a value
contextdoes not hold.