From 8222dfa1e10a162a31cec20e0c2b2db564bba672 Mon Sep 17 00:00:00 2001 From: Dextheking1 Date: Fri, 23 Oct 2026 07:24:15 +0200 Subject: [PATCH] Fix silent overwrite of existing main.py and README.md in current directory mode --- src/fastapi_new/new.py | 18 ++++++++++++++++++ tests/test_new.py | 12 ++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/fastapi_new/new.py b/src/fastapi_new/new.py index f333ca2..8dda0a4 100644 --- a/src/fastapi_new/new.py +++ b/src/fastapi_new/new.py @@ -190,6 +190,24 @@ def new( if not current_dir and config.path.exists(): _exit_with_error(toolkit, f"Directory '{config.name}' already exists.") + # In current directory mode there is no new directory to protect + # existing work, so check the files the template writes. Without + # this, running the command in the wrong directory silently + # destroys an existing main.py and README.md. + if current_dir: + existing = [ + name + for name in ("main.py", "README.md") + if (config.path / name).exists() + ] + if existing: + _exit_with_error( + toolkit, + "Refusing to overwrite existing file(s): " + + ", ".join(existing) + + ". Move them aside or run in an empty directory.", + ) + if shutil.which("uv") is None: _exit_with_error( toolkit, diff --git a/tests/test_new.py b/tests/test_new.py index d3d13da..334c449 100644 --- a/tests/test_new.py +++ b/tests/test_new.py @@ -98,6 +98,18 @@ def test_rejects_existing_directory(temp_project_dir: Path) -> None: assert "Directory 'existing_project' already exists." in result.output +def test_refuses_to_overwrite_existing_files_in_current_dir( + temp_project_dir: Path, +) -> None: + (temp_project_dir / "main.py").write_text("precious code") + (temp_project_dir / "README.md").write_text("precious readme") + result = runner.invoke(app, []) + assert result.exit_code == 1 + assert "Refusing to overwrite" in result.output + assert (temp_project_dir / "main.py").read_text() == "precious code" + assert (temp_project_dir / "README.md").read_text() == "precious readme" + + def test_rejects_python_below_3_10(temp_project_dir: Path) -> None: result = runner.invoke(app, ["test_project", "--python", "3.9"]) assert result.exit_code == 1