diff --git a/crates/ide-host/src/ops/scaffold.rs b/crates/ide-host/src/ops/scaffold.rs index 46cb3246e..1f0a380f5 100644 --- a/crates/ide-host/src/ops/scaffold.rs +++ b/crates/ide-host/src/ops/scaffold.rs @@ -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 { + 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 { + 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, ); diff --git a/crates/ide-scaffold/src/engine.rs b/crates/ide-scaffold/src/engine.rs index de78e6adf..5272f7a64 100644 --- a/crates/ide-scaffold/src/engine.rs +++ b/crates/ide-scaffold/src/engine.rs @@ -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); diff --git a/crates/ide-scaffold/src/engine/tests.rs b/crates/ide-scaffold/src/engine/tests.rs index a1d1d7587..72c53bb55 100644 --- a/crates/ide-scaffold/src/engine/tests.rs +++ b/crates/ide-scaffold/src/engine/tests.rs @@ -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"); +} diff --git a/crates/ide-scaffold/src/lib.rs b/crates/ide-scaffold/src/lib.rs index e4192121e..3884a9e34 100644 --- a/crates/ide-scaffold/src/lib.rs +++ b/crates/ide-scaffold/src/lib.rs @@ -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, diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 477fcfc03..6431b344c 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -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 diff --git a/src/bindings.ts b/src/bindings.ts index 7ae5f283f..3a115bcf1 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -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) => typedError(__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(__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(__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(__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(__TAURI_INVOKE("scaffold_target_taken", { location, name })), scopeFiles: (pattern: string, limit: number) => typedError(__TAURI_INVOKE("scope_files", { pattern, limit })), /** The project interpreter when it is a Docker or Compose run target's, with its snapshot. */ sdkContainerPython: () => typedError<{ diff --git a/src/features/app/NewProject.tsx b/src/features/app/NewProject.tsx index 2f264981e..c6a7e924b 100644 --- a/src/features/app/NewProject.tsx +++ b/src/features/app/NewProject.tsx @@ -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(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(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); + }} />