CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cookiecutter

A command-line utility that creates projects from project templates, e.g. creating a Python package project from a Python package project template.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

user-interaction.mddocs/

User Interaction

Interactive prompts for template variables with support for different input types including text, choices, boolean, and JSON inputs. This module handles all user interaction during the template generation process.

Capabilities

Main Prompt Functions

Core prompting functionality for gathering user input during template generation.

def prompt_for_config(context, no_input=False):
    """
    Main function to prompt user for project config.
    
    Parameters:
    - context: dict - Template context containing variables to prompt for
    - no_input: bool - Skip prompts and use defaults if True
    
    Returns:
    dict - Dictionary of user responses to prompts
    """

def prompt_choice_for_config(cookiecutter_dict, env, key, options, no_input, prompts=None, prefix=""):
    """
    Prompt for config choice from a list of options.
    
    Parameters:
    - cookiecutter_dict: dict - Current cookiecutter context
    - env: Environment - Jinja2 environment for rendering
    - key: str - Configuration key being prompted for
    - options: list - Available choices
    - no_input: bool - Skip prompt if True
    - prompts: dict, optional - Custom prompt text
    - prefix: str - Prefix for prompt display
    
    Returns:
    str - Selected choice
    """

Variable Input Functions

Functions for different types of user input.

def read_user_variable(var_name, default_value, prompts=None, prefix=""):
    """
    Prompt user for variable input.
    
    Parameters:
    - var_name: str - Name of variable to prompt for
    - default_value: Any - Default value to use
    - prompts: dict, optional - Custom prompt messages  
    - prefix: str - Prefix for prompt display
    
    Returns:
    str - User input or default value
    """

def read_user_yes_no(var_name, default_value, prompts=None, prefix=""):
    """
    Prompt for yes/no response.
    
    Parameters:
    - var_name: str - Name of variable to prompt for
    - default_value: bool - Default boolean value
    - prompts: dict, optional - Custom prompt messages
    - prefix: str - Prefix for prompt display
    
    Returns:
    bool - User's yes/no response
    """

def read_user_choice(var_name, options, prompts=None, prefix=""):
    """
    Prompt user to choose from options.
    
    Parameters:
    - var_name: str - Name of variable to prompt for
    - options: list - List of available choices
    - prompts: dict, optional - Custom prompt messages
    - prefix: str - Prefix for prompt display
    
    Returns:
    str - Selected option
    """

def read_user_dict(var_name, default_value, prompts=None, prefix=""):
    """
    Prompt for dictionary input.
    
    Parameters:
    - var_name: str - Name of variable to prompt for
    - default_value: dict - Default dictionary value
    - prompts: dict, optional - Custom prompt messages
    - prefix: str - Prefix for prompt display
    
    Returns:
    dict - User-provided dictionary
    """

Special Input Functions

Specialized prompting functions for specific use cases.

def read_repo_password(question):
    """
    Prompt for password input.
    
    Parameters:
    - question: str - Password prompt question
    
    Returns:
    str - Password entered by user (input hidden)
    """

def process_json(user_value, default_value=None):
    """
    Load user input as JSON dict.
    
    Parameters:
    - user_value: str - JSON string from user input
    - default_value: Any, optional - Default value if parsing fails
    
    Returns:
    dict - Parsed JSON dictionary
    """

Template and Context Functions

Functions for handling template selection and variable rendering.

def render_variable(env, raw, cookiecutter_dict):
    """
    Render variable for user prompt.
    
    Parameters:
    - env: Environment - Jinja2 environment
    - raw: str - Raw template variable string
    - cookiecutter_dict: dict - Current cookiecutter context
    
    Returns:
    Any - Rendered variable value
    """

def prompt_choice_for_template(key, options, no_input):
    """
    Prompt for template selection.
    
    Parameters:
    - key: str - Template key
    - options: list - Available template options
    - no_input: bool - Skip prompt if True
    
    Returns:
    str - Selected template
    """

def choose_nested_template(context, repo_dir, no_input=False):
    """
    Prompt for nested template selection.
    
    Parameters:
    - context: dict - Template context
    - repo_dir: str - Repository directory
    - no_input: bool - Skip prompts if True
    
    Returns:
    str - Path to selected nested template
    """

def prompt_and_delete(path, no_input=False):
    """
    Ask user about deleting existing files.
    
    Parameters:
    - path: str - Path to potentially delete
    - no_input: bool - Skip prompt if True
    
    Returns:
    bool - True if user wants to delete
    """

Prompt Classes

Custom prompt classes for specialized input types.

class YesNoPrompt(Confirm):
    """Boolean prompt for yes/no questions."""

class JsonPrompt(PromptBase[dict]):
    """Prompt that returns dict from JSON string."""

Constants

DEFAULT_DISPLAY: str  # Default display string ('default')

Usage Examples

Basic Variable Prompting

from cookiecutter.prompt import read_user_variable, read_user_yes_no, read_user_choice

# Simple text input
project_name = read_user_variable(
    var_name='project_name',
    default_value='my-project',
    prompts={'project_name': 'What is your project name?'}
)

# Yes/no prompt
use_docker = read_user_yes_no(
    var_name='use_docker',
    default_value=True,
    prompts={'use_docker': 'Do you want Docker support?'}
)

# Choice from options
license_type = read_user_choice(
    var_name='license',
    options=['MIT', 'Apache-2.0', 'GPL-3.0', 'BSD-3-Clause'],
    prompts={'license': 'Choose a license for your project'}
)

Complete Configuration Prompting

from cookiecutter.prompt import prompt_for_config
from cookiecutter.generate import generate_context

# Generate context from cookiecutter.json
context = generate_context('./template/cookiecutter.json')

# Prompt user for all configuration values
user_config = prompt_for_config(context, no_input=False)

print("User provided configuration:")
for key, value in user_config.items():
    print(f"  {key}: {value}")

Advanced Input Types

from cookiecutter.prompt import read_user_dict, process_json

# Dictionary input
database_config = read_user_dict(
    var_name='database_settings',
    default_value={'host': 'localhost', 'port': 5432},
    prompts={'database_settings': 'Enter database configuration as JSON'}
)

# JSON processing
json_input = '{"name": "test", "version": "1.0.0"}'
parsed_config = process_json(json_input, default_value={})

Custom Prompts with Context

from cookiecutter.prompt import render_variable, prompt_choice_for_config
from cookiecutter.environment import StrictEnvironment

# Set up Jinja2 environment
env = StrictEnvironment()

# Render dynamic variable
cookiecutter_dict = {'project_name': 'my-project', 'year': '2024'}
rendered_value = render_variable(
    env=env,
    raw='{{cookiecutter.project_name}}-{{cookiecutter.year}}',
    cookiecutter_dict=cookiecutter_dict
)
# Returns: 'my-project-2024'

# Dynamic choice prompting
framework_choice = prompt_choice_for_config(
    cookiecutter_dict=cookiecutter_dict,
    env=env,
    key='framework',
    options=['django', 'flask', 'fastapi'],
    no_input=False,
    prompts={'framework': 'Select a web framework'}
)

Password and Security

from cookiecutter.prompt import read_repo_password

# Secure password input
repo_password = read_repo_password(
    "Enter password for private repository: "
)
# Password input is hidden from terminal display

Template Selection

from cookiecutter.prompt import choose_nested_template, prompt_choice_for_template

# Choose from nested templates
context = {
    'cookiecutter': {
        'template': ['basic', 'advanced', 'minimal'],
        'templates': {
            'basic': './templates/basic',
            'advanced': './templates/advanced',
            'minimal': './templates/minimal'
        }
    }
}

selected_template = choose_nested_template(
    context=context,
    repo_dir='./template-repo',
    no_input=False
)

Handling Existing Files

from cookiecutter.prompt import prompt_and_delete
import os

output_path = './my-new-project'
if os.path.exists(output_path):
    should_delete = prompt_and_delete(output_path, no_input=False)
    if should_delete:
        import shutil
        shutil.rmtree(output_path)
        print(f"Deleted existing directory: {output_path}")
    else:
        print("Keeping existing directory")

No-Input Mode

from cookiecutter.prompt import prompt_for_config

# Skip all prompts and use defaults
context = generate_context('./template/cookiecutter.json')
default_config = prompt_for_config(context, no_input=True)

# All values will be defaults from cookiecutter.json
print("Using default configuration:")
for key, value in default_config.items():
    print(f"  {key}: {value}")

Custom Prompt Messages

from cookiecutter.prompt import read_user_variable

# Custom prompt with detailed help
custom_prompts = {
    'author_email': 'Enter your email address (will be used in setup.py and documentation)',
    'version': 'Initial version number (use semantic versioning like 0.1.0)',
    'description': 'Brief description of your project (one line)'
}

author_email = read_user_variable(
    var_name='author_email',
    default_value='user@example.com',
    prompts=custom_prompts
)

version = read_user_variable(
    var_name='version',
    default_value='0.1.0',
    prompts=custom_prompts
)

Install with Tessl CLI

npx tessl i tessl/pypi-cookiecutter

docs

configuration.md

hooks-extensions.md

index.md

main-api.md

repository-handling.md

template-processing.md

user-interaction.md

utilities-exceptions.md

tile.json