API
This is the Cookiecutter modules API documentation.
cookiecutter.cli module
Main cookiecutter CLI.
- cookiecutter.cli.list_installed_templates(default_config, passed_config_file)[source]
List installed (locally cloned) templates. Use cookiecutter –list-installed.
- Return type:
cookiecutter.config module
Global configuration handling.
- cookiecutter.config.get_config(config_path)[source]
Retrieve the config from the specified path, returning a config dict.
- cookiecutter.config.get_user_config(config_file=None, default_config=False)[source]
Return the user config as a dict.
If
default_config
is True, ignoreconfig_file
and return default values for the config parameters.If
default_config
is a dict, merge values with default values and return them for the config parameters.If a path to a
config_file
is given, that is different from the default location, load the user config from that.Otherwise look up the config file path in the
COOKIECUTTER_CONFIG
environment variable. If set, load the config from this path. This will raise an error if the specified path is not valid.If the environment variable is not set, try the default config file path before falling back to the default config values.
cookiecutter.environment module
Jinja2 environment and extensions loading.
- class cookiecutter.environment.ExtensionLoaderMixin(*, context=None, **kwargs)[source]
Bases:
object
Mixin providing sane loading of extensions specified in a given context.
The context is being extracted from the keyword arguments before calling the next parent class in line of the child.
- class cookiecutter.environment.StrictEnvironment(**kwargs)[source]
Bases:
ExtensionLoaderMixin
,Environment
Create strict Jinja2 environment.
Jinja2 environment will raise error on undefined variable in template- rendering context.
cookiecutter.exceptions module
All exceptions used in the Cookiecutter code base are defined here.
- exception cookiecutter.exceptions.ConfigDoesNotExistException[source]
Bases:
CookiecutterException
Exception for missing config file.
Raised when get_config() is passed a path to a config file, but no file is found at that path.
- exception cookiecutter.exceptions.ContextDecodingException[source]
Bases:
CookiecutterException
Exception for failed JSON decoding.
Raised when a project’s JSON context file can not be decoded.
- exception cookiecutter.exceptions.CookiecutterException[source]
Bases:
Exception
Base exception class.
All Cookiecutter-specific exceptions should subclass this class.
- exception cookiecutter.exceptions.EmptyDirNameException[source]
Bases:
CookiecutterException
Exception for a empty directory name.
Raised when the directory name provided is empty.
- exception cookiecutter.exceptions.FailedHookException[source]
Bases:
CookiecutterException
Exception for hook failures.
Raised when a hook script fails.
- exception cookiecutter.exceptions.InvalidConfiguration[source]
Bases:
CookiecutterException
Exception for invalid configuration file.
Raised if the global configuration file is not valid YAML or is badly constructed.
- exception cookiecutter.exceptions.InvalidModeException[source]
Bases:
CookiecutterException
Exception for incompatible modes.
Raised when cookiecutter is called with both no_input==True and replay==True at the same time.
- exception cookiecutter.exceptions.InvalidZipRepository[source]
Bases:
CookiecutterException
Exception for bad zip repo.
Raised when the specified cookiecutter repository isn’t a valid Zip archive.
- exception cookiecutter.exceptions.MissingProjectDir[source]
Bases:
CookiecutterException
Exception for missing generated project directory.
Raised during cleanup when remove_repo() can’t find a generated project directory inside of a repo.
- exception cookiecutter.exceptions.NonTemplatedInputDirException[source]
Bases:
CookiecutterException
Exception for when a project’s input dir is not templated.
The name of the input directory should always contain a string that is rendered to something else, so that input_dir != output_dir.
- exception cookiecutter.exceptions.OutputDirExistsException[source]
Bases:
CookiecutterException
Exception for existing output directory.
Raised when the output directory of the project exists already.
- exception cookiecutter.exceptions.RepositoryCloneFailed[source]
Bases:
CookiecutterException
Exception for un-cloneable repo.
Raised when a cookiecutter template can’t be cloned.
- exception cookiecutter.exceptions.RepositoryNotFound[source]
Bases:
CookiecutterException
Exception for missing repo.
Raised when the specified cookiecutter repository doesn’t exist.
- exception cookiecutter.exceptions.UndefinedVariableInTemplate(message, error, context)[source]
Bases:
CookiecutterException
Exception for out-of-scope variables.
Raised when a template uses a variable which is not defined in the context.
- exception cookiecutter.exceptions.UnknownExtension[source]
Bases:
CookiecutterException
Exception for un-importable extension.
Raised when an environment is unable to import a required extension.
- exception cookiecutter.exceptions.UnknownRepoType[source]
Bases:
CookiecutterException
Exception for unknown repo types.
Raised if a repo’s type cannot be determined.
- exception cookiecutter.exceptions.UnknownTemplateDirException[source]
Bases:
CookiecutterException
Exception for ambiguous project template directory.
Raised when Cookiecutter cannot determine which directory is the project template, e.g. more than one dir appears to be a template dir.
- exception cookiecutter.exceptions.VCSNotInstalled[source]
Bases:
CookiecutterException
Exception when version control is unavailable.
Raised if the version control system (git or hg) is not installed.
cookiecutter.extensions module
Jinja2 extensions.
- class cookiecutter.extensions.JsonifyExtension(environment)[source]
Bases:
Extension
Jinja2 extension to convert a Python object to JSON.
- identifier = 'cookiecutter.extensions.JsonifyExtension'
- class cookiecutter.extensions.RandomStringExtension(environment)[source]
Bases:
Extension
Jinja2 extension to create a random string.
- identifier = 'cookiecutter.extensions.RandomStringExtension'
- class cookiecutter.extensions.SlugifyExtension(environment)[source]
Bases:
Extension
Jinja2 Extension to slugify string.
- identifier = 'cookiecutter.extensions.SlugifyExtension'
cookiecutter.find module
Functions for finding Cookiecutter templates and other components.
cookiecutter.generate module
Functions for generating a project from a project template.
- cookiecutter.generate.apply_overwrites_to_context(context, overwrite_context, *, in_dictionary_variable=False)[source]
Modify the given context in place based on the overwrite_context.
- Return type:
- cookiecutter.generate.generate_context(context_file='cookiecutter.json', default_context=None, extra_context=None)[source]
Generate the context for a Cookiecutter project template.
Loads the JSON file as a Python object, with key being the JSON filename.
- Parameters:
- Return type:
- cookiecutter.generate.generate_file(project_dir, infile, context, env, skip_if_file_exists=False)[source]
Render filename of infile as name of outfile, handle infile correctly.
Dealing with infile appropriately:
If infile is a binary file, copy it over without rendering.
If infile is a text file, render its contents and write the rendered infile to outfile.
Precondition:
When calling generate_file(), the root template dir must be the current working directory. Using utils.work_in() is the recommended way to perform this directory change.
- Parameters:
- Return type:
- cookiecutter.generate.generate_files(repo_dir, context=None, output_dir='.', overwrite_if_exists=False, skip_if_file_exists=False, accept_hooks=True, keep_project_on_failure=False)[source]
Render the templates and saves them to files.
- Parameters:
context (
Optional
[dict
[str
,Any
]]) – Dict for populating the template’s variables.output_dir (
Path
|str
) – Where to output the generated project dir into.overwrite_if_exists (
bool
) – Overwrite the contents of the output directory if it exists.skip_if_file_exists (
bool
) – Skip the files in the corresponding directories if they already existaccept_hooks (
bool
) – Accept pre and post hooks if set to True.keep_project_on_failure (
bool
) – If True keep generated project directory even when generation fails
- Return type:
cookiecutter.hooks module
Functions for discovering and executing various cookiecutter hooks.
- cookiecutter.hooks.find_hook(hook_name, hooks_dir='hooks')[source]
Return a dict of all hook scripts provided.
Must be called with the project template as the current working directory. Dict’s key will be the hook/script’s name, without extension, while values will be the absolute path to the script. Missing scripts will not be included in the returned dict.
- cookiecutter.hooks.run_hook(hook_name, project_dir, context)[source]
Try to find and execute a hook from the specified project directory.
- cookiecutter.hooks.run_hook_from_repo_dir(repo_dir, hook_name, project_dir, context, delete_project_on_failure)[source]
Run hook from repo directory, clean project directory if hook fails.
- cookiecutter.hooks.run_script(script_path, cwd='.')[source]
Execute a script from a working directory.
cookiecutter.log module
Module for setting up logging.
cookiecutter.main module
Main entry point for the cookiecutter command.
The code in this module is also a good example of how to use Cookiecutter as a library rather than a script.
- cookiecutter.main.cookiecutter(template, checkout=None, no_input=False, extra_context=None, replay=None, overwrite_if_exists=False, output_dir='.', config_file=None, default_config=False, password=None, directory=None, skip_if_file_exists=False, accept_hooks=True, keep_project_on_failure=False)[source]
Run Cookiecutter just as if using it from the command line.
- Parameters:
template (
str
) – A directory containing a project template directory, or a URL to a git repository.checkout (
Optional
[str
]) – The branch, tag or commit ID to checkout after clone.no_input (
bool
) – Do not prompt for user input. Use default values for template parameters taken from cookiecutter.json, user config and extra_dict. Force a refresh of cached resources.extra_context (
Optional
[dict
[str
,Any
]]) – A dictionary of context that overrides default and user configuration.replay (
Union
[bool
,str
,None
]) – Do not prompt for input, instead read from saved json. IfTrue
read from thereplay_dir
. if it existsoverwrite_if_exists (
bool
) – Overwrite the contents of the output directory if it exists.output_dir (
str
) – Where to output the generated project dir into.default_config (
bool
) – Use default values rather than a config file.password (
Optional
[str
]) – The password to use when extracting the repository.directory (
Optional
[str
]) – Relative path to a cookiecutter template in a repository.skip_if_file_exists (
bool
) – Skip the files in the corresponding directories if they already exist.accept_hooks (
bool
) – Accept pre and post hooks if set to True.keep_project_on_failure (
bool
) – If True keep generated project directory even when generation fails
- Return type:
cookiecutter.prompt module
Functions for prompting the user for project info.
- class cookiecutter.prompt.JsonPrompt(prompt='', *, console=None, password=False, choices=None, show_default=True, show_choices=True)[source]
Bases:
PromptBase
[dict
]A prompt that returns a dict from JSON string.
- default = None
- validate_error_message = '[prompt.invalid] Please enter a valid JSON string'
- class cookiecutter.prompt.YesNoPrompt(prompt='', *, console=None, password=False, choices=None, show_default=True, show_choices=True)[source]
Bases:
Confirm
A prompt that returns a boolean for yes/no questions.
- no_choices = ['0', 'false', 'f', 'no', 'n', 'off']
- yes_choices = ['1', 'true', 't', 'yes', 'y', 'on']
- cookiecutter.prompt.choose_nested_template(context, repo_dir, no_input=False)[source]
Prompt user to select the nested template to use.
- cookiecutter.prompt.process_json(user_value)[source]
Load user-supplied value as a JSON dict.
- Parameters:
user_value (
str
) – User-supplied value to load as a JSON dict
- cookiecutter.prompt.prompt_and_delete(path, no_input=False)[source]
Ask user if it’s okay to delete the previously-downloaded file/directory.
If yes, delete it. If no, checks to see if the old version should be reused. If yes, it’s reused; otherwise, Cookiecutter exits.
- cookiecutter.prompt.prompt_choice_for_config(cookiecutter_dict, env, key, options, no_input, prompts=None, prefix='')[source]
Prompt user with a set of options to choose from.
- Parameters:
no_input (
bool
) – Do not prompt for user input and return the first available option.- Return type:
OrderedDict
[str
,Any
] |str
- cookiecutter.prompt.prompt_choice_for_template(key, options, no_input)[source]
Prompt user with a set of options to choose from.
- Parameters:
no_input (
bool
) – Do not prompt for user input and return the first available option.- Return type:
- cookiecutter.prompt.prompt_for_config(context, no_input=False)[source]
Prompt user to enter a new config.
- Parameters:
- Return type:
- cookiecutter.prompt.read_user_choice(var_name, options, prompts=None, prefix='')[source]
Prompt the user to choose from several options for the given variable.
The first item will be returned if no input happens.
- cookiecutter.prompt.read_user_dict(var_name, default_value, prompts=None, prefix='')[source]
Prompt the user to provide a dictionary of data.
- Parameters:
var_name (
str
) – Variable as specified in the contextdefault_value – Value that will be returned if no input is provided
- Returns:
A Python dictionary to use in the context.
- cookiecutter.prompt.read_user_variable(var_name, default_value, prompts=None, prefix='')[source]
Prompt user for variable and return the entered value or given default.
- Parameters:
var_name (str) – Variable of the context to query the user
default_value – Value that will be returned if no input happens
- cookiecutter.prompt.read_user_yes_no(var_name, default_value, prompts=None, prefix='')[source]
Prompt the user to reply with ‘yes’ or ‘no’ (or equivalent values).
These input values will be converted to
True
: “1”, “true”, “t”, “yes”, “y”, “on”These input values will be converted to
False
: “0”, “false”, “f”, “no”, “n”, “off”
Actual parsing done by
prompt()
; Check this function codebase change in case of unexpected behaviour.- Parameters:
question (str) – Question to the user
default_value – Value that will be returned if no input happens
- cookiecutter.prompt.render_variable(env, raw, cookiecutter_dict)[source]
Render the next variable to be displayed in the user prompt.
Inside the prompting taken from the cookiecutter.json file, this renders the next variable. For example, if a project_name is “Peanut Butter Cookie”, the repo_name could be be rendered with:
{{ cookiecutter.project_name.replace(” “, “_”) }}.
This is then presented to the user as the default.
- Parameters:
- Return type:
- Returns:
The rendered value for the default variable.
cookiecutter.replay module
cookiecutter.replay.
- cookiecutter.replay.dump(replay_dir, template_name, context)[source]
Write json data to file.
- Return type:
cookiecutter.repository module
Cookiecutter repository functions.
- cookiecutter.repository.determine_repo_dir(template, abbreviations, clone_to_dir, checkout, no_input, password=None, directory=None)[source]
Locate the repository directory from a template reference.
Applies repository abbreviations to the template reference. If the template refers to a repository URL, clone it. If the template is a path to a local repository, use it.
- Parameters:
template (
str
) – A directory containing a project template directory, or a URL to a git repository.abbreviations (
dict
[str
,str
]) – A dictionary of repository abbreviation definitions.clone_to_dir (
Path
|str
) – The directory to clone the repository into.checkout (
str
|None
) – The branch, tag or commit ID to checkout after clone.no_input (
bool
) – Do not prompt for user input and eventually force a refresh of cached resources.password (
Optional
[str
]) – The password to use when extracting the repository.directory (
Optional
[str
]) – Directory within repo where cookiecutter.json lives.
- Return type:
- Returns:
A tuple containing the cookiecutter template directory, and a boolean describing whether that directory should be cleaned up after the template has been instantiated.
- Raises:
RepositoryNotFound if a repository directory could not be found.
- cookiecutter.repository.expand_abbreviations(template, abbreviations)[source]
Expand abbreviations in a template name.
- cookiecutter.repository.is_repo_url(value)[source]
Return True if value is a repository URL.
- Return type:
cookiecutter.utils module
Helper functions used throughout Cookiecutter.
- cookiecutter.utils.create_env_with_context(context)[source]
Create a jinja environment using the provided context.
- Return type:
- cookiecutter.utils.create_tmp_repo_dir(repo_dir)[source]
Create a temporary dir with a copy of the contents of repo_dir.
- Return type:
- cookiecutter.utils.force_delete(func, path, _exc_info)[source]
Error handler for shutil.rmtree() equivalent to rm -rf.
Usage: shutil.rmtree(path, onerror=force_delete) From https://docs.python.org/3/library/shutil.html#rmtree-example
- Return type:
- cookiecutter.utils.rmtree(path)[source]
Remove a directory and all its contents. Like rm -rf on Unix.
cookiecutter.vcs module
Helper functions for working with version control systems.
- cookiecutter.vcs.clone(repo_url, checkout=None, clone_to_dir='.', no_input=False)[source]
Clone a repo to the current directory.
- Parameters:
repo_url (
str
) – Repo URL of unknown type.checkout (
Optional
[str
]) – The branch, tag or commit ID to checkout after clone.clone_to_dir (
Path
|str
) – The directory to clone to. Defaults to the current directory.no_input (
bool
) – Do not prompt for user input and eventually force a refresh of cached resources.
- Return type:
- Returns:
str with path to the new directory of the repository.
cookiecutter.zipfile module
Utility functions for handling and fetching repo archives in zip format.
- cookiecutter.zipfile.unzip(zip_uri, is_url, clone_to_dir='.', no_input=False, password=None)[source]
Download and unpack a zipfile at a given URI.
This will download the zipfile to the cookiecutter repository, and unpack into a temporary directory.
- Parameters:
zip_uri (
str
) – The URI for the zipfile.is_url (
bool
) – Is the zip URI a URL or a file?clone_to_dir (
Path
|str
) – The cookiecutter repository directory to put the archive into.no_input (
bool
) – Do not prompt for user input and eventually force a refresh of cached resources.password (
Optional
[str
]) – The password to use when unpacking the repository.
- Return type:
Module contents
Main package for Cookiecutter.