Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 09:04:14 +08:00
commit 70c36b5eff
248 changed files with 47482 additions and 0 deletions

View File

@@ -0,0 +1,310 @@
#!/usr/bin/env python3
"""
Advanced Click CLI Template
Demonstrates advanced patterns including:
- Custom parameter types
- Command chaining
- Plugin architecture
- Configuration management
- Logging integration
"""
import click
import logging
from rich.console import Console
from pathlib import Path
import json
from typing import Optional
console = Console()
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Custom parameter types
class JsonType(click.ParamType):
"""Custom type for JSON parsing"""
name = 'json'
def convert(self, value, param, ctx):
try:
return json.loads(value)
except json.JSONDecodeError as e:
self.fail(f'Invalid JSON: {e}', param, ctx)
class PathListType(click.ParamType):
"""Custom type for comma-separated paths"""
name = 'pathlist'
def convert(self, value, param, ctx):
paths = [Path(p.strip()) for p in value.split(',')]
for path in paths:
if not path.exists():
self.fail(f'Path does not exist: {path}', param, ctx)
return paths
# Configuration class
class Config:
"""Application configuration"""
def __init__(self):
self.debug = False
self.log_level = 'INFO'
self.config_file = 'config.json'
self._data = {}
def load(self, config_file: Optional[str] = None):
"""Load configuration from file"""
file_path = Path(config_file or self.config_file)
if file_path.exists():
with open(file_path) as f:
self._data = json.load(f)
logger.info(f"Loaded config from {file_path}")
def get(self, key: str, default=None):
"""Get configuration value"""
return self._data.get(key, default)
def set(self, key: str, value):
"""Set configuration value"""
self._data[key] = value
def save(self):
"""Save configuration to file"""
file_path = Path(self.config_file)
with open(file_path, 'w') as f:
json.dump(self._data, f, indent=2)
logger.info(f"Saved config to {file_path}")
# Pass config between commands
pass_config = click.make_pass_decorator(Config, ensure=True)
# Main CLI group
@click.group(chain=True)
@click.option('--debug', is_flag=True, help='Enable debug mode')
@click.option('--config', type=click.Path(), default='config.json',
help='Configuration file')
@click.option('--log-level',
type=click.Choice(['DEBUG', 'INFO', 'WARNING', 'ERROR']),
default='INFO',
help='Logging level')
@click.version_option(version='2.0.0')
@pass_config
def cli(config: Config, debug: bool, config: str, log_level: str):
"""
Advanced CLI with chaining and plugin support.
Commands can be chained together:
cli init process deploy
cli config set key=value process --validate
"""
config.debug = debug
config.log_level = log_level
config.config_file = config
config.load()
# Set logging level
logger.setLevel(getattr(logging, log_level))
if debug:
console.print("[dim]Debug mode enabled[/dim]")
# Pipeline commands (chainable)
@cli.command()
@click.option('--template', type=click.Choice(['basic', 'advanced', 'api']),
default='basic')
@pass_config
def init(config: Config, template: str):
"""Initialize project (chainable)"""
console.print(f"[cyan]Initializing with {template} template...[/cyan]")
config.set('template', template)
return config
@cli.command()
@click.option('--validate', is_flag=True, help='Validate before processing')
@click.option('--parallel', is_flag=True, help='Process in parallel')
@pass_config
def process(config: Config, validate: bool, parallel: bool):
"""Process data (chainable)"""
console.print("[cyan]Processing data...[/cyan]")
if validate:
console.print("[dim]Validating input...[/dim]")
mode = "parallel" if parallel else "sequential"
console.print(f"[dim]Processing mode: {mode}[/dim]")
return config
@cli.command()
@click.argument('environment', type=click.Choice(['dev', 'staging', 'prod']))
@click.option('--dry-run', is_flag=True, help='Simulate deployment')
@pass_config
def deploy(config: Config, environment: str, dry_run: bool):
"""Deploy to environment (chainable)"""
prefix = "[yellow][DRY RUN][/yellow] " if dry_run else ""
console.print(f"{prefix}[cyan]Deploying to {environment}...[/cyan]")
template = config.get('template', 'unknown')
console.print(f"[dim]Template: {template}[/dim]")
return config
# Advanced configuration commands
@cli.group()
def config():
"""Advanced configuration management"""
pass
@config.command()
@click.argument('key')
@pass_config
def get(config: Config, key: str):
"""Get configuration value"""
value = config.get(key)
if value is not None:
console.print(f"{key}: [green]{value}[/green]")
else:
console.print(f"[yellow]Key not found: {key}[/yellow]")
@config.command()
@click.argument('pair')
@pass_config
def set(config: Config, pair: str):
"""Set configuration (format: key=value)"""
if '=' not in pair:
raise click.BadParameter('Format must be key=value')
key, value = pair.split('=', 1)
config.set(key, value)
config.save()
console.print(f"[green]✓[/green] Set {key} = {value}")
@config.command()
@click.option('--format', type=click.Choice(['json', 'yaml', 'env']),
default='json')
@pass_config
def export(config: Config, format: str):
"""Export configuration in different formats"""
console.print(f"[cyan]Exporting config as {format}...[/cyan]")
if format == 'json':
output = json.dumps(config._data, indent=2)
elif format == 'yaml':
# Simplified YAML output
output = '\n'.join(f"{k}: {v}" for k, v in config._data.items())
else: # env
output = '\n'.join(f"{k.upper()}={v}" for k, v in config._data.items())
console.print(output)
# Advanced data operations
@cli.group()
def data():
"""Data operations with advanced types"""
pass
@data.command()
@click.option('--json-data', type=JsonType(), help='JSON data to import')
@click.option('--paths', type=PathListType(), help='Comma-separated paths')
@pass_config
def import_data(config: Config, json_data: Optional[dict], paths: Optional[list]):
"""Import data from various sources"""
console.print("[cyan]Importing data...[/cyan]")
if json_data:
console.print(f"[dim]JSON data: {json_data}[/dim]")
if paths:
console.print(f"[dim]Processing {len(paths)} path(s)[/dim]")
for path in paths:
console.print(f" - {path}")
@data.command()
@click.option('--input', type=click.File('r'), help='Input file')
@click.option('--output', type=click.File('w'), help='Output file')
@click.option('--format',
type=click.Choice(['json', 'csv', 'xml']),
default='json')
def transform(input, output, format):
"""Transform data between formats"""
console.print(f"[cyan]Transforming data to {format}...[/cyan]")
if input:
data = input.read()
console.print(f"[dim]Read {len(data)} bytes[/dim]")
if output:
# Would write transformed data here
output.write('{}') # Placeholder
console.print("[green]✓[/green] Transformation complete")
# Plugin system
@cli.group()
def plugin():
"""Plugin management"""
pass
@plugin.command()
@click.argument('plugin_name')
@click.option('--version', help='Plugin version')
def install(plugin_name: str, version: Optional[str]):
"""Install a plugin"""
version_str = f"@{version}" if version else "@latest"
console.print(f"[cyan]Installing plugin: {plugin_name}{version_str}...[/cyan]")
console.print("[green]✓[/green] Plugin installed successfully")
@plugin.command()
def list():
"""List installed plugins"""
console.print("[cyan]Installed Plugins:[/cyan]")
# Placeholder plugin list
plugins = [
{"name": "auth-plugin", "version": "1.0.0", "status": "active"},
{"name": "database-plugin", "version": "2.1.0", "status": "active"},
]
for p in plugins:
status_color = "green" if p["status"] == "active" else "yellow"
console.print(f" - {p['name']} ({p['version']}) [{status_color}]{p['status']}[/{status_color}]")
# Batch operations
@cli.command()
@click.argument('commands', nargs=-1, required=True)
@pass_config
def batch(config: Config, commands: tuple):
"""Execute multiple commands in batch"""
console.print(f"[cyan]Executing {len(commands)} command(s)...[/cyan]")
for i, cmd in enumerate(commands, 1):
console.print(f"[dim]{i}. {cmd}[/dim]")
# Would execute actual commands here
console.print("[green]✓[/green] Batch execution completed")
if __name__ == '__main__':
cli()

View File

@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""
Basic Click CLI Template
A simple single-command CLI using Click framework.
"""
import click
from rich.console import Console
console = Console()
@click.command()
@click.version_option(version='1.0.0')
@click.option('--name', '-n', default='World', help='Name to greet')
@click.option('--count', '-c', default=1, type=int, help='Number of greetings')
@click.option('--verbose', '-v', is_flag=True, help='Verbose output')
def cli(name, count, verbose):
"""
A simple greeting CLI tool.
Example:
python cli.py --name Alice --count 3
"""
if verbose:
console.print(f"[dim]Running with name={name}, count={count}[/dim]")
for i in range(count):
console.print(f"[green]Hello, {name}![/green]")
if verbose:
console.print(f"[dim]Completed {count} greeting(s)[/dim]")
if __name__ == '__main__':
cli()

View File

@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""
Nested Commands Click Template
Demonstrates command groups, nested subcommands, and context sharing.
"""
import click
from rich.console import Console
console = Console()
@click.group()
@click.version_option(version='1.0.0')
@click.pass_context
def cli(ctx):
"""
A powerful CLI tool with nested commands.
Example:
python cli.py init --template basic
python cli.py deploy production --mode safe
python cli.py config get api-key
"""
ctx.ensure_object(dict)
ctx.obj['console'] = console
@cli.command()
@click.option('--template', '-t', default='basic',
type=click.Choice(['basic', 'advanced', 'minimal']),
help='Project template')
@click.pass_context
def init(ctx, template):
"""Initialize a new project"""
console = ctx.obj['console']
console.print(f"[green]✓[/green] Initializing project with {template} template...")
@cli.command()
@click.argument('environment', type=click.Choice(['dev', 'staging', 'production']))
@click.option('--force', '-f', is_flag=True, help='Force deployment')
@click.option('--mode', '-m',
type=click.Choice(['fast', 'safe', 'rollback']),
default='safe',
help='Deployment mode')
@click.pass_context
def deploy(ctx, environment, force, mode):
"""Deploy to specified environment"""
console = ctx.obj['console']
console.print(f"[cyan]Deploying to {environment} in {mode} mode[/cyan]")
if force:
console.print("[yellow]⚠ Force mode enabled[/yellow]")
@cli.group()
def config():
"""Manage configuration settings"""
pass
@config.command()
@click.argument('key')
@click.pass_context
def get(ctx, key):
"""Get configuration value"""
console = ctx.obj['console']
# Placeholder for actual config retrieval
value = "example_value"
console.print(f"[dim]Config[/dim] {key}: [green]{value}[/green]")
@config.command()
@click.argument('key')
@click.argument('value')
@click.pass_context
def set(ctx, key, value):
"""Set configuration value"""
console = ctx.obj['console']
# Placeholder for actual config storage
console.print(f"[green]✓[/green] Set {key} = {value}")
@config.command()
@click.pass_context
def list(ctx):
"""List all configuration settings"""
console = ctx.obj['console']
console.print("[cyan]Configuration Settings:[/cyan]")
# Placeholder for actual config listing
console.print(" api-key: [dim]***hidden***[/dim]")
console.print(" debug: [green]true[/green]")
@cli.group()
def database():
"""Database management commands"""
pass
@database.command()
@click.option('--create-tables', is_flag=True, help='Create tables')
@click.pass_context
def migrate(ctx, create_tables):
"""Run database migrations"""
console = ctx.obj['console']
console.print("[cyan]Running migrations...[/cyan]")
if create_tables:
console.print("[green]✓[/green] Tables created")
@database.command()
@click.option('--confirm', is_flag=True, help='Confirm reset')
@click.pass_context
def reset(ctx, confirm):
"""Reset database (destructive)"""
console = ctx.obj['console']
if not confirm:
console.print("[yellow]⚠ Use --confirm to proceed[/yellow]")
return
console.print("[red]Resetting database...[/red]")
if __name__ == '__main__':
cli(obj={})

View File

@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""
Click Custom Validators Template
Demonstrates custom parameter validation, callbacks, and type conversion.
"""
import click
import re
from pathlib import Path
from rich.console import Console
console = Console()
# Custom validator callbacks
def validate_email(ctx, param, value):
"""Validate email format"""
if value and not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', value):
raise click.BadParameter('Invalid email format')
return value
def validate_port(ctx, param, value):
"""Validate port number"""
if value < 1 or value > 65535:
raise click.BadParameter('Port must be between 1 and 65535')
return value
def validate_path_exists(ctx, param, value):
"""Validate that path exists"""
if value and not Path(value).exists():
raise click.BadParameter(f'Path does not exist: {value}')
return value
def validate_url(ctx, param, value):
"""Validate URL format"""
if value and not re.match(r'^https?://[^\s]+$', value):
raise click.BadParameter('Invalid URL format (must start with http:// or https://)')
return value
# Custom Click types
class CommaSeparatedList(click.ParamType):
"""Custom type for comma-separated lists"""
name = 'comma-list'
def convert(self, value, param, ctx):
if isinstance(value, list):
return value
try:
return [item.strip() for item in value.split(',') if item.strip()]
except Exception:
self.fail(f'{value} is not a valid comma-separated list', param, ctx)
class EnvironmentVariable(click.ParamType):
"""Custom type for environment variables"""
name = 'env-var'
def convert(self, value, param, ctx):
if not re.match(r'^[A-Z_][A-Z0-9_]*$', value):
self.fail(f'{value} is not a valid environment variable name', param, ctx)
return value
@click.group()
def cli():
"""CLI with custom validators"""
pass
@cli.command()
@click.option('--email', callback=validate_email, required=True, help='User email address')
@click.option('--age', type=click.IntRange(0, 150), required=True, help='User age')
@click.option('--username', type=click.STRING, required=True,
help='Username (3-20 characters)',
callback=lambda ctx, param, value: value if 3 <= len(value) <= 20
else ctx.fail('Username must be 3-20 characters'))
def create_user(email, age, username):
"""Create a new user with validation"""
console.print(f"[green]✓[/green] User created: {username} ({email}), age {age}")
@cli.command()
@click.option('--port', type=int, callback=validate_port, default=8080, help='Server port')
@click.option('--host', default='localhost', help='Server host')
@click.option('--workers', type=click.IntRange(1, 32), default=4, help='Number of workers')
@click.option('--ssl', is_flag=True, help='Enable SSL')
def start_server(port, host, workers, ssl):
"""Start server with validated parameters"""
protocol = 'https' if ssl else 'http'
console.print(f"[cyan]Starting server at {protocol}://{host}:{port}[/cyan]")
console.print(f"[dim]Workers: {workers}[/dim]")
@cli.command()
@click.option('--config', type=click.Path(exists=True, dir_okay=False),
callback=validate_path_exists, required=True, help='Config file path')
@click.option('--output', type=click.Path(dir_okay=False), required=True, help='Output file path')
@click.option('--format', type=click.Choice(['json', 'yaml', 'toml']), default='json',
help='Output format')
def convert_config(config, output, format):
"""Convert configuration file"""
console.print(f"[cyan]Converting {config} to {format} format[/cyan]")
console.print(f"[green]✓[/green] Output: {output}")
@cli.command()
@click.option('--url', callback=validate_url, required=True, help='API URL')
@click.option('--method', type=click.Choice(['GET', 'POST', 'PUT', 'DELETE']),
default='GET', help='HTTP method')
@click.option('--headers', type=CommaSeparatedList(), help='Headers (comma-separated key:value)')
@click.option('--timeout', type=click.FloatRange(0.1, 300.0), default=30.0,
help='Request timeout in seconds')
def api_call(url, method, headers, timeout):
"""Make API call with validation"""
console.print(f"[cyan]{method} {url}[/cyan]")
console.print(f"[dim]Timeout: {timeout}s[/dim]")
if headers:
console.print(f"[dim]Headers: {headers}[/dim]")
@cli.command()
@click.option('--env-var', type=EnvironmentVariable(), required=True,
help='Environment variable name')
@click.option('--value', required=True, help='Environment variable value')
@click.option('--scope', type=click.Choice(['user', 'system', 'project']),
default='user', help='Variable scope')
def set_env(env_var, value, scope):
"""Set environment variable with validation"""
console.print(f"[green]✓[/green] Set {env_var}={value} (scope: {scope})")
@cli.command()
@click.option('--min', type=float, required=True, help='Minimum value')
@click.option('--max', type=float, required=True, help='Maximum value')
@click.option('--step', type=click.FloatRange(0.01, None), default=1.0, help='Step size')
def generate_range(min, max, step):
"""Generate numeric range with validation"""
if min >= max:
raise click.BadParameter('min must be less than max')
count = int((max - min) / step) + 1
console.print(f"[cyan]Generating range from {min} to {max} (step: {step})[/cyan]")
console.print(f"[dim]Total values: {count}[/dim]")
# Example combining multiple validators
@cli.command()
@click.option('--name', required=True, help='Project name',
callback=lambda ctx, param, value: value.lower().replace(' ', '-'))
@click.option('--tags', type=CommaSeparatedList(), help='Project tags (comma-separated)')
@click.option('--priority', type=click.IntRange(1, 10), default=5, help='Priority (1-10)')
@click.option('--template', type=click.Path(exists=True), help='Template directory')
def create_project(name, tags, priority, template):
"""Create project with multiple validators"""
console.print(f"[green]✓[/green] Project created: {name}")
console.print(f"[dim]Priority: {priority}[/dim]")
if tags:
console.print(f"[dim]Tags: {', '.join(tags)}[/dim]")
if template:
console.print(f"[dim]Template: {template}[/dim]")
if __name__ == '__main__':
cli()