Python API reference#

These modules are the Python API that template hooks use. Cookieplone runs a template's hooks with the Python interpreter that runs Cookieplone itself, so a hook can import them.

Validators and filters have their own pages: Validators reference and Filters reference.

Sub-templates#

Helpers for post-generation hooks that orchestrate sub-template rendering.

cookieplone.utils.subtemplates.SubtemplateHandler#

Signature for custom subtemplate handler functions. Receives (context, output_dir) and returns the generated directory path.

alias of Callable[[OrderedDict, Path], Path]

cookieplone.utils.subtemplates.run_subtemplates(context: OrderedDict, output_dir: Path, handlers: dict[str, Callable[[OrderedDict, Path], Path]] | None = None, global_versions: dict[str, str] | None = None) dict[str, Path][source]#

Process and generate all subtemplates defined in the context.

This is the main entry point for post-generation hooks to trigger subtemplate generation. It replaces the boilerplate loop that was previously duplicated across every post_gen_project.py.

For each enabled subtemplate:

  • If a matching handler is provided, it is called with a deep copy of the context and the output directory.

  • Otherwise, generate_subtemplate() is called with default arguments.

Disabled subtemplates are logged and skipped.

Parameters:
  • context -- The cookiecutter context OrderedDict from the post-generation hook.

  • output_dir -- The generated project directory (typically Path.cwd()).

  • handlers -- Optional mapping of template_idSubtemplateHandler for subtemplates that need custom context manipulation.

  • global_versions -- Version pins from the parent template's cookieplone-config.json. Forwarded to each generate_subtemplate() call so that {{ versions.X }} works in child template files.

Returns:

Dict mapping template_id → generated Path for each subtemplate that was processed.

Post-generation actions#

Helpers for post-generation action hooks.

Provides run_post_gen_actions() — a single dispatcher that replaces the boilerplate run_actions() loop duplicated across every template's post_gen_project.py — together with a set of ready-made handlers for common post-generation tasks (git init, file removal, file moves, namespace packages, make format).

class cookieplone.utils.post_gen.PostGenAction[source]#

A single post-generation action entry.

cookieplone.utils.post_gen.PostGenHandler#

Signature for post-generation action handlers. Receives (context, output_dir) and returns nothing.

alias of Callable[[OrderedDict, Path], None]

cookieplone.utils.post_gen.create_namespace_packages(context: OrderedDict, output_dir: Path) None[source]#

Create Python namespace package structure.

Reads python_package_name from context and delegates to create_namespace_packages(). The namespace_style key defaults to "native" (PEP 420).

cookieplone.utils.post_gen.initialize_git_repository(context: OrderedDict, output_dir: Path) None[source]#

Initialize a git repository in output_dir and stage all files.

Wraps initialize_repository(). After the initial git add performed by that function, a second git add is run to capture any files created by earlier post-gen actions.

cookieplone.utils.post_gen.move_files(pairs: list[tuple[str, str]]) Callable[[OrderedDict, Path], None][source]#

Return a handler that renames files within output_dir.

Parameters:

pairs -- List of (source, destination) relative paths.

Returns:

A PostGenHandler suitable for PostGenAction.

Example:

action = {
    "handler": move_files([("docs/.readthedocs.yaml", ".readthedocs.yml")]),
    "title": "Move docs config",
    "enabled": True,
}
cookieplone.utils.post_gen.remove_files_by_key(to_remove: dict[str, list[str]], key: str) Callable[[OrderedDict, Path], None][source]#

Return a handler that removes files listed under key in to_remove.

Parameters:
  • to_remove -- Mapping of group keys to lists of relative paths.

  • key -- The group to remove.

Returns:

A PostGenHandler suitable for PostGenAction.

Example:

POST_GEN_TO_REMOVE = {
    "devops-ansible": ["devops/ansible"],
    "devops-gha": [".github/workflows/deploy.yml"],
}
action = {
    "handler": remove_files_by_key(POST_GEN_TO_REMOVE, "devops-ansible"),
    "title": "Remove Ansible files",
    "enabled": True,
}
cookieplone.utils.post_gen.run_make_format(make_target: str = 'format', folder: str = '') Callable[[OrderedDict, Path], None][source]#

Return a handler that runs make <target> in a subfolder.

Parameters:
  • make_target -- The make target to invoke (default "format").

  • folder -- Subfolder relative to output_dir. When empty, runs in output_dir itself.

Returns:

A PostGenHandler suitable for PostGenAction.

Example:

action = {
    "handler": run_make_format("format", "backend"),
    "title": "Format backend code",
    "enabled": True,
}
cookieplone.utils.post_gen.run_post_gen_actions(context: OrderedDict, output_dir: Path, actions: list[PostGenAction]) None[source]#

Run a list of post-generation actions against a generated project.

Each action is a PostGenAction dict with handler, title, and enabled keys. Disabled actions are logged and skipped; enabled actions receive a deep copy of context and the output_dir.

Parameters:
  • context -- The cookiecutter context OrderedDict from the post-generation hook.

  • output_dir -- The generated project directory.

  • actions -- Ordered list of actions to execute.

Generator#

cookieplone.generator.generate_subtemplate(template_path: str, output_dir: Path, folder_name: str, context: OrderedDict, remove_files: list[str] | None = None, global_versions: dict[str, str] | None = None) Path[source]#

Generate a sub-template as part of a larger cookieplone run.

Intended to be called from within a cookiecutter hook to render a nested template. Quiet mode is enabled for the duration so that the sub-template's output does not clutter the parent run's UI.

Deprecated since version 2.0.0: Use run_subtemplates() instead, which handles the full subtemplates loop with automatic fallback for subtemplates that don't need custom handlers.

Parameters:
  • template_path -- Relative path (within the repository) to the sub-template directory.

  • output_dir -- Directory where the sub-template output should be written.

  • folder_name -- Name of the folder to create inside output_dir.

  • context -- The current cookiecutter context, used to locate the repository root and to pass answers through to the sub-template.

  • remove_files -- Optional list of paths relative to the generated folder that should be deleted after generation.

  • global_versions -- Version pins from the parent template's cookieplone-config.json. Passed through to the child generate() call so that {{ versions.X }} works in child template files.

Returns:

Path to the generated sub-template directory.

Raises:

GeneratorException -- If generation of the sub-template fails.

Git#

class cookieplone.utils.git.GitUserInfo[source]#

GitUserInfo(name: str = '', email: str = '')

__init__(name: str = '', email: str = '') None#
cookieplone.utils.git.check_path_is_repository(path: Path) bool[source]#

Check if given path is a Git Repository.

cookieplone.utils.git.get_last_commit(path: Path) Commit | None[source]#

Return the last commit for a repo.

cookieplone.utils.git.get_user_info() GitUserInfo[source]#

Return git user info by reading available config levels.

Checks the repository config (via config_reader()) when the current directory is inside a git repo, then falls through to the user, global, and system levels using GitConfigParser as a context manager.

Note

GitConfigParser(config_level="repository") cannot be used standalone — it requires a Repo object internally and will raise ValueError before _read_only is initialised, leaving a partially-constructed object that triggers an AttributeError in __del__ when the GC collects it. We therefore read the repository level through Repo.config_reader().

cookieplone.utils.git.initialize_repository(path: Path) Repo[source]#

Initialize a git repository and add all files.

cookieplone.utils.git.repo_from_path(path: Path) Repo | None[source]#

Return the repo for the given path.

Plone#

cookieplone.utils.plone.add_dependency_profile_to_metadata(profile: str, raw_xml: str) str[source]#

Inject a dependency into the metadata.xml file.

cookieplone.utils.plone.add_dependency_to_zcml(package: str, raw_xml: str) str[source]#

Inject a dependency into the dependencies.zcml file.

cookieplone.utils.plone.create_namespace_packages(path: Path, package_name: str, style: str = 'native')[source]#

Create namespace packages to hold an existing package.

cookieplone.utils.plone.format_python_codebase(path: Path)[source]#

Format a Python codebase after code generation.

npm#

cookieplone.utils.npm.parse_package_name(name: str) tuple[str, str][source]#

Parses an npm name, and returns organization and package_name.

cookieplone.utils.npm.unscoped_package_name(name: str) str[source]#

Return the unscoped package name for an npm package.