|
| 1 | +import pathlib |
| 2 | +import shutil |
| 3 | +import subprocess |
| 4 | +from dataclasses import dataclass |
| 5 | +from typing import Annotated |
| 6 | + |
| 7 | +import typer |
| 8 | +from rich_toolkit import RichToolkit |
| 9 | + |
| 10 | +from .utils.cli import get_rich_toolkit |
| 11 | + |
| 12 | +TEMPLATE_CONTENT = """from fastapi import FastAPI |
| 13 | +app = FastAPI() |
| 14 | +
|
| 15 | +@app.get("/") |
| 16 | +def main(): |
| 17 | + return {"message": "Hello World"} |
| 18 | +""" |
| 19 | + |
| 20 | + |
| 21 | +@dataclass |
| 22 | +class ProjectConfig: |
| 23 | + name: str |
| 24 | + path: pathlib.Path |
| 25 | + python: str | None = None |
| 26 | + |
| 27 | + |
| 28 | +def _generate_readme(project_name: str) -> str: |
| 29 | + return f"""# {project_name} |
| 30 | +
|
| 31 | +A project created with FastAPI CLI. |
| 32 | +
|
| 33 | +## Quick Start |
| 34 | +
|
| 35 | +### Start the development server: |
| 36 | +
|
| 37 | +```bash |
| 38 | +uv run fastapi dev |
| 39 | +``` |
| 40 | +
|
| 41 | +Visit http://localhost:8000 |
| 42 | +
|
| 43 | +### Deploy to FastAPI Cloud: |
| 44 | +
|
| 45 | +> Reader's note: These commands are not quite ready for prime time yet, but will be soon! Join the waiting list at https://fastapicloud.com! |
| 46 | +
|
| 47 | +```bash |
| 48 | +uv run fastapi login |
| 49 | +uv run fastapi deploy |
| 50 | +``` |
| 51 | +
|
| 52 | +## Project Structure |
| 53 | +
|
| 54 | +- `main.py` - Your FastAPI application |
| 55 | +- `pyproject.toml` - Project dependencies |
| 56 | +
|
| 57 | +## Learn More |
| 58 | +
|
| 59 | +- [FastAPI Documentation](https://fastapi.tiangolo.com) |
| 60 | +- [FastAPI Cloud](https://fastapicloud.com) |
| 61 | +""" |
| 62 | + |
| 63 | + |
| 64 | +def _exit_with_error(toolkit: RichToolkit, error_msg: str) -> None: |
| 65 | + toolkit.print(f"[bold red]Error:[/bold red] {error_msg}", tag="error") |
| 66 | + raise typer.Exit(code=1) |
| 67 | + |
| 68 | + |
| 69 | +def _validate_python_version(python: str | None) -> str | None: |
| 70 | + """ |
| 71 | + Validate Python version is >= 3.10. |
| 72 | + Returns error message if < 3.10, None otherwise. |
| 73 | + Let uv handle malformed versions or versions it can't find. |
| 74 | + """ |
| 75 | + if not python: |
| 76 | + return None |
| 77 | + |
| 78 | + try: |
| 79 | + parts = python.split(".") |
| 80 | + if len(parts) < 2: |
| 81 | + return None # Let uv handle malformed version |
| 82 | + major, minor = int(parts[0]), int(parts[1]) |
| 83 | + |
| 84 | + if major < 3 or (major == 3 and minor < 10): |
| 85 | + return f"Python {python} is not supported. FastAPI requires Python 3.10 or higher." |
| 86 | + except (ValueError, IndexError): |
| 87 | + # Malformed version - let uv handle the error |
| 88 | + pass |
| 89 | + |
| 90 | + return None |
| 91 | + |
| 92 | + |
| 93 | +def _setup(toolkit: RichToolkit, config: ProjectConfig) -> None: |
| 94 | + error = _validate_python_version(config.python) |
| 95 | + if error: |
| 96 | + _exit_with_error(toolkit, error) |
| 97 | + |
| 98 | + msg = "Setting up environment with uv" |
| 99 | + |
| 100 | + if config.python: |
| 101 | + msg += f" (Python {config.python})" |
| 102 | + |
| 103 | + toolkit.print(msg, tag="env") |
| 104 | + |
| 105 | + # If config.name is provided, create in subdirectory; otherwise init in current dir |
| 106 | + # uv will infer the project name from the directory name |
| 107 | + if config.path == pathlib.Path.cwd(): |
| 108 | + init_cmd = ["uv", "init", "--bare"] |
| 109 | + else: |
| 110 | + init_cmd = ["uv", "init", "--bare", config.name] |
| 111 | + |
| 112 | + if config.python: |
| 113 | + init_cmd.extend(["--python", config.python]) |
| 114 | + |
| 115 | + try: |
| 116 | + subprocess.run(init_cmd, check=True, capture_output=True) |
| 117 | + except subprocess.CalledProcessError as e: |
| 118 | + stderr = e.stderr.decode() if e.stderr else "No details available" |
| 119 | + _exit_with_error(toolkit, f"Failed to initialize project with uv. {stderr}") |
| 120 | + |
| 121 | + |
| 122 | +def _install_dependencies(toolkit: RichToolkit, config: ProjectConfig) -> None: |
| 123 | + toolkit.print("Installing dependencies...", tag="deps") |
| 124 | + |
| 125 | + try: |
| 126 | + subprocess.run( |
| 127 | + ["uv", "add", "fastapi[standard]"], |
| 128 | + check=True, |
| 129 | + capture_output=True, |
| 130 | + cwd=config.path, |
| 131 | + ) |
| 132 | + except subprocess.CalledProcessError as e: |
| 133 | + stderr = e.stderr.decode() if e.stderr else "No details available" |
| 134 | + _exit_with_error(toolkit, f"Failed to install dependencies. {stderr}") |
| 135 | + |
| 136 | + |
| 137 | +def _write_template_files(toolkit: RichToolkit, config: ProjectConfig) -> None: |
| 138 | + toolkit.print("Writing template files...", tag="template") |
| 139 | + readme_content = _generate_readme(config.name) |
| 140 | + |
| 141 | + try: |
| 142 | + (config.path / "main.py").write_text(TEMPLATE_CONTENT) |
| 143 | + (config.path / "README.md").write_text(readme_content) |
| 144 | + except Exception as e: |
| 145 | + _exit_with_error(toolkit, f"Failed to write template files. {str(e)}") |
| 146 | + |
| 147 | + |
| 148 | +def new( |
| 149 | + ctx: typer.Context, |
| 150 | + project_name: Annotated[ |
| 151 | + str | None, |
| 152 | + typer.Argument( |
| 153 | + help="The name of the new FastAPI project. If not provided, initializes in the current directory.", |
| 154 | + ), |
| 155 | + ] = None, |
| 156 | + python: Annotated[ |
| 157 | + str | None, |
| 158 | + typer.Option( |
| 159 | + "--python", |
| 160 | + "-p", |
| 161 | + help="Specify the Python version for the new project (e.g., 3.14). Must be 3.10 or higher.", |
| 162 | + ), |
| 163 | + ] = None, |
| 164 | +) -> None: |
| 165 | + if project_name: |
| 166 | + name = project_name |
| 167 | + path = pathlib.Path.cwd() / project_name |
| 168 | + else: |
| 169 | + name = pathlib.Path.cwd().name |
| 170 | + path = pathlib.Path.cwd() |
| 171 | + |
| 172 | + config = ProjectConfig( |
| 173 | + name=name, |
| 174 | + path=path, |
| 175 | + python=python, |
| 176 | + ) |
| 177 | + |
| 178 | + with get_rich_toolkit() as toolkit: |
| 179 | + toolkit.print_title("Creating a new project 🚀", tag="FastAPI") |
| 180 | + |
| 181 | + toolkit.print_line() |
| 182 | + |
| 183 | + if not project_name: |
| 184 | + toolkit.print( |
| 185 | + f"[yellow]⚠️ No project name provided. Initializing in current directory: {path}[/yellow]", |
| 186 | + tag="warning", |
| 187 | + ) |
| 188 | + toolkit.print_line() |
| 189 | + |
| 190 | + # Check if project directory already exists (only for new subdirectory) |
| 191 | + if project_name and config.path.exists(): |
| 192 | + _exit_with_error(toolkit, f"Directory '{project_name}' already exists.") |
| 193 | + |
| 194 | + if shutil.which("uv") is None: |
| 195 | + _exit_with_error( |
| 196 | + toolkit, |
| 197 | + "uv is required to create new projects. Install it from https://docs.astral.sh/uv/getting-started/installation/", |
| 198 | + ) |
| 199 | + |
| 200 | + _setup(toolkit, config) |
| 201 | + |
| 202 | + toolkit.print_line() |
| 203 | + |
| 204 | + _install_dependencies(toolkit, config) |
| 205 | + |
| 206 | + toolkit.print_line() |
| 207 | + |
| 208 | + _write_template_files(toolkit, config) |
| 209 | + |
| 210 | + toolkit.print_line() |
| 211 | + |
| 212 | + # Print success message |
| 213 | + if project_name: |
| 214 | + toolkit.print( |
| 215 | + f"[bold green]✨ Success![/bold green] Created FastAPI project: [cyan]{project_name}[/cyan]", |
| 216 | + tag="success", |
| 217 | + ) |
| 218 | + |
| 219 | + toolkit.print_line() |
| 220 | + |
| 221 | + toolkit.print("[bold]Next steps:[/bold]") |
| 222 | + toolkit.print(f" [dim]$[/dim] cd {project_name}") |
| 223 | + toolkit.print(" [dim]$[/dim] uv run fastapi dev") |
| 224 | + else: |
| 225 | + toolkit.print( |
| 226 | + "[bold green]✨ Success![/bold green] Initialized FastAPI project in current directory", |
| 227 | + tag="success", |
| 228 | + ) |
| 229 | + |
| 230 | + toolkit.print_line() |
| 231 | + |
| 232 | + toolkit.print("[bold]Next steps:[/bold]") |
| 233 | + toolkit.print(" [dim]$[/dim] uv run fastapi dev") |
| 234 | + |
| 235 | + toolkit.print_line() |
| 236 | + |
| 237 | + toolkit.print("Visit [blue]http://localhost:8000[/blue]") |
| 238 | + |
| 239 | + toolkit.print_line() |
| 240 | + |
| 241 | + toolkit.print("[bold]Deploy to FastAPI Cloud:[/bold]") |
| 242 | + toolkit.print(" [dim]$[/dim] uv run fastapi login") |
| 243 | + toolkit.print(" [dim]$[/dim] uv run fastapi deploy") |
| 244 | + |
| 245 | + toolkit.print_line() |
| 246 | + |
| 247 | + toolkit.print( |
| 248 | + "[dim]💡 Tip: Use 'uv run' to automatically use the project's environment[/dim]" |
| 249 | + ) |
0 commit comments