|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Generate LeetCode problem from JSON using cookiecutter.""" |
| 3 | + |
| 4 | +import json |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +import typer |
| 8 | +from cookiecutter.main import cookiecutter |
| 9 | + |
| 10 | + |
| 11 | +def check_and_prompt_tags(data: dict) -> dict: |
| 12 | + """Check if tags are empty and prompt user for common options.""" |
| 13 | + import sys |
| 14 | + |
| 15 | + common_tags = ["grind-75", "blind-75", "neetcode-150", "top-interview"] |
| 16 | + |
| 17 | + if "tags" in data and (not data["tags"] or data["tags"] == []): |
| 18 | + if sys.stdin.isatty(): # Interactive terminal |
| 19 | + typer.echo("\n📋 No tags specified. Would you like to add any common tags?") |
| 20 | + typer.echo("Available options:") |
| 21 | + for i, tag in enumerate(common_tags, 1): |
| 22 | + typer.echo(f" {i}. {tag}") |
| 23 | + typer.echo(" 0. Skip (no tags)") |
| 24 | + |
| 25 | + choices_input = typer.prompt("Select options (comma-separated, e.g. '1,2' or '0' to skip)") |
| 26 | + |
| 27 | + try: |
| 28 | + choices = [int(x.strip()) for x in choices_input.split(",")] |
| 29 | + selected_tags = [] |
| 30 | + |
| 31 | + for choice in choices: |
| 32 | + if choice == 0: |
| 33 | + selected_tags = [] |
| 34 | + break |
| 35 | + elif 1 <= choice <= len(common_tags): |
| 36 | + tag = common_tags[choice - 1] |
| 37 | + if tag not in selected_tags: |
| 38 | + selected_tags.append(tag) |
| 39 | + |
| 40 | + data["tags"] = selected_tags |
| 41 | + if selected_tags: |
| 42 | + typer.echo(f"✅ Added tags: {', '.join(selected_tags)}") |
| 43 | + else: |
| 44 | + typer.echo("✅ No tags added") |
| 45 | + |
| 46 | + except ValueError: |
| 47 | + typer.echo("⚠️ Invalid input, skipping tags") |
| 48 | + data["tags"] = [] |
| 49 | + |
| 50 | + return data |
| 51 | + |
| 52 | + |
| 53 | +def convert_arrays_to_nested(data: dict) -> dict: |
| 54 | + """Convert array fields to cookiecutter-friendly nested format.""" |
| 55 | + extra_context = data.copy() |
| 56 | + array_fields = ["examples", "test_cases", "tags"] |
| 57 | + for field in array_fields: |
| 58 | + if field in data and isinstance(data[field], list): |
| 59 | + extra_context[f"_{field}"] = {"list": data[field]} |
| 60 | + del extra_context[field] |
| 61 | + return extra_context |
| 62 | + |
| 63 | + |
| 64 | +def check_overwrite_permission(question_name: str, force: bool) -> None: |
| 65 | + """Check if user wants to overwrite existing problem.""" |
| 66 | + import sys |
| 67 | + |
| 68 | + if force: |
| 69 | + return |
| 70 | + |
| 71 | + output_dir = Path(__file__).parent.parent.parent / "leetcode" |
| 72 | + problem_dir = output_dir / question_name |
| 73 | + |
| 74 | + if not problem_dir.exists(): |
| 75 | + return |
| 76 | + |
| 77 | + typer.echo(f"⚠️ Warning: Question '{question_name}' already exists in leetcode/", err=True) |
| 78 | + typer.echo("This will overwrite existing files. Use --force to skip this check.", err=True) |
| 79 | + |
| 80 | + if sys.stdin.isatty(): # Interactive terminal |
| 81 | + confirm = typer.confirm("Continue?") |
| 82 | + if not confirm: |
| 83 | + typer.echo("Cancelled.") |
| 84 | + raise typer.Exit(1) |
| 85 | + else: # Non-interactive mode |
| 86 | + typer.echo("Non-interactive mode: use --force to overwrite.", err=True) |
| 87 | + raise typer.Exit(1) |
| 88 | + |
| 89 | + |
| 90 | +def generate_problem(json_file: str, force: bool = False) -> None: |
| 91 | + """Generate LeetCode problem from JSON file.""" |
| 92 | + json_path = Path(json_file) |
| 93 | + if not json_path.exists(): |
| 94 | + typer.echo(f"Error: {json_file} not found", err=True) |
| 95 | + raise typer.Exit(1) |
| 96 | + |
| 97 | + # Load JSON data |
| 98 | + with open(json_path) as f: |
| 99 | + data = json.load(f) |
| 100 | + |
| 101 | + # Check and prompt for tags if empty |
| 102 | + data = check_and_prompt_tags(data) |
| 103 | + |
| 104 | + # Save updated data back to JSON file |
| 105 | + with open(json_path, 'w') as f: |
| 106 | + json.dump(data, f, indent=4) |
| 107 | + |
| 108 | + # Convert arrays to cookiecutter-friendly nested format |
| 109 | + extra_context = convert_arrays_to_nested(data) |
| 110 | + |
| 111 | + # Check if problem already exists |
| 112 | + question_name = extra_context.get("question_name", "unknown") |
| 113 | + check_overwrite_permission(question_name, force) |
| 114 | + |
| 115 | + # Generate project using cookiecutter |
| 116 | + template_dir = Path(__file__).parent |
| 117 | + output_dir = template_dir.parent.parent / "leetcode" |
| 118 | + |
| 119 | + cookiecutter( |
| 120 | + str(template_dir), |
| 121 | + extra_context=extra_context, |
| 122 | + no_input=True, |
| 123 | + overwrite_if_exists=True, |
| 124 | + output_dir=str(output_dir), |
| 125 | + ) |
| 126 | + |
| 127 | + typer.echo(f"✅ Generated problem: {question_name}") |
| 128 | + |
| 129 | + |
| 130 | +if __name__ == "__main__": |
| 131 | + typer.run(generate_problem) |
0 commit comments