fix(new-project): flag a taken folder and remember the location (#5024)

New Project accepted the name of a folder that already exists and has files, and only reported "already exists and is not empty" in the progress view after Create. It now checks as the name or location changes: the name field and its hint turn red and Create is disabled. Until the user types a name, it follows the first free `untitled`, `untitled1`, … in the location.

The location always started at the home folder (unless Default Project Directory was set). It now starts where the last project was created; the Default Project Directory setting still comes first.

The check is the one `scaffold_create` already did, moved into `ide_scaffold::target_taken` and exposed with `free_name` as `scaffold_target_taken` / `scaffold_free_name`.
This commit is contained in:
l0ng-ai
2026-11-22 00:51:52 +08:00
committed by GitHub
parent 0798582173
commit 8eb332aba7
11 changed files with 229 additions and 10 deletions
+16
View File
@@ -6,6 +6,7 @@ use ide_command::command;
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
use ide_scaffold::{CreateRequest, Field, GeneratorInfo, Requirement, ScaffoldEvent, Values};
use std::path::PathBuf;
fn join_err(e: impl std::fmt::Display) -> IdeError {
IdeError::internal(e.to_string())
@@ -41,6 +42,19 @@ pub async fn scaffold_requirements(generator: String, values: Values) -> IdeResu
tokio::task::spawn_blocking(move || ide_scaffold::requirements(&generator, &values)).await.map_err(join_err)?
}
/// Whether a project named `name` cannot be created in `location`: something other than an
/// empty folder is already there.
#[command(trust = always)]
pub async fn scaffold_target_taken(location: PathBuf, name: String) -> IdeResult<bool> {
tokio::task::spawn_blocking(move || ide_scaffold::target_taken(&location.join(name.trim()))).await.map_err(join_err)
}
/// The first of `base`, `base1`, `base2`, … that names nothing in `location` yet.
#[command(trust = always)]
pub async fn scaffold_free_name(location: PathBuf, base: String) -> IdeResult<String> {
tokio::task::spawn_blocking(move || ide_scaffold::free_name(&location, &base)).await.map_err(join_err)
}
/// Creates a project, streaming progress through `on_event`, and returns its directory,
/// trusted. Cancellable with `cancel_request(request)`; a failed or cancelled run leaves nothing.
#[command(trust = always)]
@@ -69,6 +83,8 @@ ide_command::domain!(
scaffold:
scaffold_catalog,
scaffold_create,
scaffold_free_name,
scaffold_options,
scaffold_requirements,
scaffold_target_taken,
);
+15 -1
View File
@@ -132,6 +132,20 @@ pub fn name_error(name: &str) -> Option<&'static str> {
}
}
/// Whether `dir` cannot take a new project: something other than an empty folder is there.
pub fn target_taken(dir: &Path) -> bool {
dir.exists() && std::fs::read_dir(dir).map(|mut d| d.next().is_some()).unwrap_or(true)
}
/// The first of `base`, `base1`, `base2`, … that names nothing in `location` yet.
pub fn free_name(location: &Path, base: &str) -> String {
let base = base.trim();
std::iter::once(base.to_owned())
.chain((1..10_000).map(|i| format!("{base}{i}")))
.find(|n| !location.join(n).exists())
.unwrap_or_else(|| base.to_owned())
}
/// The staging directory; removed on drop unless the project was moved out of it.
struct Staging(PathBuf);
@@ -388,7 +402,7 @@ pub(crate) fn create_with(
std::fs::create_dir_all(&location)?;
}
let target = location.join(name);
if target.exists() && std::fs::read_dir(&target).map(|mut d| d.next().is_some()).unwrap_or(true) {
if target_taken(&target) {
return Err(IdeError::invalid(format!("{} already exists and is not empty", target.display())));
}
let values = with_defaults(def, name, &req.values);
+16
View File
@@ -237,3 +237,19 @@ fn versions_and_ansi() {
assert_eq!(strip_ansi("\u{1b}[32m✔\u{1b}[0m done\r"), "✔ done");
assert_eq!(strip_ansi("\u{1b}]8;;http://x\u{7}link\u{1b}]8;;\u{7}"), "link");
}
#[test]
fn taken_targets_and_free_names() {
let tmp = tempfile::tempdir().unwrap();
let at = |n: &str| tmp.path().join(n);
assert!(!target_taken(&at("untitled")));
assert_eq!(free_name(tmp.path(), "untitled"), "untitled");
std::fs::create_dir(at("untitled")).unwrap();
assert!(!target_taken(&at("untitled")), "an empty folder takes the project");
std::fs::write(at("untitled/a.txt"), "").unwrap();
assert!(target_taken(&at("untitled")));
std::fs::write(at("untitled1"), "").unwrap();
assert!(target_taken(&at("untitled1")), "a file is in the way");
assert_eq!(free_name(tmp.path(), "untitled"), "untitled2");
}
+1 -1
View File
@@ -10,7 +10,7 @@ mod providers;
mod template;
pub use catalog::catalog;
pub use engine::{Emit, create, name_error, options, requirements};
pub use engine::{Emit, create, free_name, name_error, options, requirements, target_taken};
pub use model::{
ChoiceOption, CreateRequest, Dependency, DependencyGroup, Field, FieldKind, GeneratorInfo, Requirement,
ScaffoldEvent, Values,
+2
View File
@@ -572,8 +572,10 @@ run_tomcat_update trusted project_host bin
run_without_derived trusted project_host bindings async
scaffold_catalog always project_host bindings sync
scaffold_create always project_host bindings async
scaffold_free_name always project_host bindings async
scaffold_options always project_host bindings async
scaffold_requirements always project_host bindings async
scaffold_target_taken always project_host bindings async
scope_files always project_host bindings async
sdk_container_python trusted project_host bindings sync
sdk_container_python_refresh trusted project_host bindings async
+7
View File
@@ -1501,6 +1501,8 @@ export const commands = {
* trusted. Cancellable with `cancel_request(request)`; a failed or cancelled run leaves nothing.
*/
scaffoldCreate: (req: CreateRequest, request: RequestId, onEvent: Channel<ScaffoldEvent>) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("scaffold_create", { req, request, onEvent })),
/** The first of `base`, `base1`, `base2`, … that names nothing in `location` yet. */
scaffoldFreeName: (location: string, base: string) => typedError<string, IdeError>(__TAURI_INVOKE("scaffold_free_name", { location, base })),
/**
* The fields a generator's project service adds for `values`; cancellable with
* `cancel_request(request)`.
@@ -1508,6 +1510,11 @@ export const commands = {
scaffoldOptions: (generator: string, values: { [key in string]: string }, request: RequestId) => typedError<Field[], IdeError>(__TAURI_INVOKE("scaffold_options", { generator, values, request })),
/** The programs a generator needs for `values`, and whether they are installed. */
scaffoldRequirements: (generator: string, values: { [key in string]: string }) => typedError<Requirement[], IdeError>(__TAURI_INVOKE("scaffold_requirements", { generator, values })),
/**
* Whether a project named `name` cannot be created in `location`: something other than an
* empty folder is already there.
*/
scaffoldTargetTaken: (location: string, name: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("scaffold_target_taken", { location, name })),
scopeFiles: (pattern: string, limit: number) => typedError<ScopeFiles, IdeError>(__TAURI_INVOKE("scope_files", { pattern, limit })),
/** The project interpreter when it is a Docker or Compose run target's, with its snapshot. */
sdkContainerPython: () => typedError<{
+68 -7
View File
@@ -65,9 +65,28 @@ function errorText(e: unknown) {
return e instanceof Error ? e.message : String(e);
}
/** Default Project Directory, else the parent of the open project. */
const LOCATION_KEY = "openidea.newProject.location";
const DEFAULT_NAME = "untitled";
function lastLocation(): string {
try {
return localStorage.getItem(LOCATION_KEY) ?? "";
} catch {
return "";
}
}
function saveLocation(dir: string) {
try {
localStorage.setItem(LOCATION_KEY, dir);
} catch {
// Not kept: the next project starts from the default location.
}
}
/** Default Project Directory, else where the last project was created, else the parent of the open project. */
function initialLocation(): string {
const preset = defaultProjectDirectory();
const preset = defaultProjectDirectory() || lastLocation();
if (preset) return preset;
const root = useProject.getState().project?.root;
return root ? root.slice(0, Math.max(root.lastIndexOf("/"), 1)) : "";
@@ -119,7 +138,11 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
const [catalogError, setCatalogError] = useState<string | null>(null);
const [selected, setSelected] = useState("empty");
const [query, setQuery] = useState("");
const [name, setName] = useState("untitled");
const [name, setName] = useState(DEFAULT_NAME);
/** Until the user types a name, it follows the first free `untitled…` in the location. */
const [nameEdited, setNameEdited] = useState(false);
/** The project path last found taken (something other than an empty folder is there). */
const [takenPath, setTakenPath] = useState<string | null>(null);
const [location, setLocation] = useState(initialLocation);
const [git, setGit] = useState(true);
/** Values the user set, per generator; the rest are rendered defaults. */
@@ -212,8 +235,42 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
const setValue = (id: string, value: string) =>
setEdited((all) => ({ ...all, [selected]: { ...(all[selected] ?? {}), [id]: value } }));
const nameError = projectNameError(name);
const path = location.trim() && !nameError ? joinPath(location.trim(), name) : "";
const syntaxError = projectNameError(name);
const path = location.trim() && !syntaxError ? joinPath(location.trim(), name) : "";
const nameError =
syntaxError ?? (path && takenPath === path ? "A folder with this name already exists and is not empty" : null);
useEffect(() => {
const dir = location.trim();
if (nameEdited || !dir) return;
let live = true;
const timer = setTimeout(() => {
call(commands.scaffoldFreeName(dir, DEFAULT_NAME))
.then((free) => live && setName(free))
.catch(() => {});
}, 200);
return () => {
live = false;
clearTimeout(timer);
};
}, [location, nameEdited]);
useEffect(() => {
if (!path) return;
let live = true;
const dir = location.trim();
const timer = setTimeout(() => {
call(commands.scaffoldTargetTaken(dir, name.trim()))
.then((taken) => live && setTakenPath(taken ? path : null))
.catch(() => {});
}, 150);
return () => {
live = false;
clearTimeout(timer);
};
// `path` already reflects `location` and `name`.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [path]);
const visibleFields = fields.filter((f) => isVisible(f, values));
const invalidField = visibleFields.find((f) => fieldError(f, values[f.id] ?? ""));
const missing = requirements.filter((r) => !r.satisfied);
@@ -265,6 +322,7 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
channel,
),
);
saveLocation(location.trim());
onClose();
await openProjectInWindow(dir, useProject.getState().project !== null);
} catch (e) {
@@ -354,7 +412,10 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
data-autofocus
value={name}
invalid={!!nameError}
onChange={(e) => setName(e.target.value)}
onChange={(e) => {
setNameEdited(true);
setName(e.target.value);
}}
/>
<label className={styles.label} htmlFor="np-location">
<T>Location:</T>
@@ -376,7 +437,7 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
/>
</div>
<span />
<div className={styles.hint}>
<div className={nameError ? `${styles.hint} ${styles.hintError}` : styles.hint}>
{nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)}
</div>
{generator?.git && (
@@ -0,0 +1,98 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { GeneratorInfo } from "@/bindings";
import { NewProjectOverlay, showNewProject } from "../NewProject";
const mocks = vi.hoisted(() => ({
freeName: vi.fn(),
taken: vi.fn(),
create: vi.fn(),
open: vi.fn(),
}));
const empty: GeneratorInfo = {
id: "empty",
name: "Empty Project",
group: "New Project",
icon: "folder",
order: 0,
description: "An empty folder to add files to.",
git: true,
fields: [],
dynamic: false,
};
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = () => {};
},
}));
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
commands: {
...actual.commands,
scaffoldCatalog: () => Promise.resolve([empty]),
scaffoldRequirements: () => Promise.resolve({ status: "ok", data: [] }),
scaffoldFreeName: mocks.freeName,
scaffoldTargetTaken: mocks.taken,
scaffoldCreate: mocks.create,
},
};
});
vi.mock("../windows", async (original) => ({
...(await original<typeof import("../windows")>()),
openProjectInWindow: mocks.open,
}));
const ok = <T,>(data: T) => Promise.resolve({ status: "ok" as const, data });
const nameInput = () => screen.getByLabelText("Name:");
const createButton = () => screen.getByRole("button", { name: "Create" });
describe("File › New Project… name and location", () => {
beforeEach(() => {
localStorage.clear();
localStorage.setItem("openidea.newProject.location", "/work/projects");
mocks.freeName.mockImplementation(() => ok("untitled2"));
mocks.taken.mockImplementation((_dir: string, name: string) => ok(name === "existing"));
mocks.create.mockImplementation(() => ok("/work/projects/untitled2"));
mocks.open.mockResolvedValue(undefined);
});
afterEach(() => {
vi.clearAllMocks();
localStorage.clear();
});
it("starts where the last project was created, named after the first free untitled folder", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
expect(screen.getByLabelText("Location:")).toHaveValue("/work/projects");
await waitFor(() => expect(nameInput()).toHaveValue("untitled2"));
expect(mocks.freeName).toHaveBeenCalledWith("/work/projects", "untitled");
});
it("marks a name whose folder already exists with files and disables Create", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
await waitFor(() => expect(nameInput()).toHaveValue("untitled2"));
fireEvent.change(nameInput(), { target: { value: "existing" } });
expect(await screen.findByText("A folder with this name already exists and is not empty")).toBeInTheDocument();
expect(nameInput()).toHaveAttribute("aria-invalid", "true");
expect(createButton()).toBeDisabled();
fireEvent.change(nameInput(), { target: { value: "fresh" } });
await waitFor(() => expect(createButton()).toBeEnabled());
expect(screen.queryByText("A folder with this name already exists and is not empty")).toBeNull();
});
it("remembers the location of the project it created", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
await waitFor(() => expect(nameInput()).toHaveValue("untitled2"));
fireEvent.change(screen.getByLabelText("Location:"), { target: { value: "/elsewhere" } });
await waitFor(() => expect(createButton()).toBeEnabled());
fireEvent.click(createButton());
await waitFor(() => expect(mocks.open).toHaveBeenCalled());
expect(localStorage.getItem("openidea.newProject.location")).toBe("/elsewhere");
});
});
+3
View File
@@ -117,6 +117,9 @@
.hint {
min-height: 1.5em;
}
.hint.hintError {
color: var(--danger);
}
.fieldHint {
margin-top: 4px;
}
+2 -1
View File
@@ -3016,5 +3016,6 @@
"Location:": "Location:",
"ID:": "ID:",
"Homepage:": "Homepage:",
"Mail:": "Mail:"
"Mail:": "Mail:",
"A folder with this name already exists and is not empty": "A folder with this name already exists and is not empty"
}
+1
View File
@@ -3719,6 +3719,7 @@
"Choose a scope": "选择范围",
"Enter a project name": "请输入项目名称",
"The name contains characters a folder name cannot have": "名称包含文件夹名称中不能使用的字符",
"A folder with this name already exists and is not empty": "已存在同名文件夹且不为空",
"Project Location": "项目位置",
"New Project": "新建项目",
"New Project…": "新建项目…",