From fde78df4be8a71397fbcffe2ddf5e6725a6e0cd2 Mon Sep 17 00:00:00 2001 From: Yizhou Jiang Date: Sun, 22 Nov 2026 11:23:40 +0800 Subject: [PATCH] feat(project): scaffold a project into the directory you already opened --- src-tauri/src/lib.rs | 1 + src-tauri/src/new_project/init_project.rs | 130 +++++++++++++++ src-tauri/src/new_project/mod.rs | 6 + src-tauri/src/new_project/tests_init.rs | 192 ++++++++++++++++++++++ 4 files changed, 329 insertions(+) create mode 100644 src-tauri/src/new_project/init_project.rs create mode 100644 src-tauri/src/new_project/tests_init.rs diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index bc995353..5bb23268 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -153,6 +153,7 @@ pub fn run() { settings::read_project_settings, settings::write_project_settings, new_project::create_project, + new_project::init_project, git::git_status, git::git_file_diff, git::git_stage, diff --git a/src-tauri/src/new_project/init_project.rs b/src-tauri/src/new_project/init_project.rs new file mode 100644 index 00000000..1157c292 --- /dev/null +++ b/src-tauri/src/new_project/init_project.rs @@ -0,0 +1,130 @@ +//! Initialize a project inside a directory the user already opened. +//! +//! Unlike [`create_project`], which makes a fresh `/` directory, this command fills +//! the directory it is handed. It reuses the same templates and standard resolution so the two +//! paths can never drift, but refuses to touch a directory that already holds anything meaningful. + +#![allow(unused_imports)] + +pub(crate) use crate::project; +pub(crate) use crate::types::ProjectInfo; +pub use std::fs; +pub use std::path::{Path, PathBuf}; + +use super::*; + +/// Entries that never count as meaningful content: our own state and Finder hygiene files. +const IGNORED_ENTRIES: [&str; 2] = [".DS_Store", ".git"]; + +/// List directory entries that block initialization. +/// +/// A `.quarry/` directory is ours and may be left from the previous (project-less) open; a `.git` +/// entry and `.DS_Store` are harmless. Everything else is reported so the dialog can say why. +fn occupancy_offenders(root: &Path) -> Result, String> { + let entries = + fs::read_dir(root).map_err(|e| format!("cannot read directory {}: {e}", root.display()))?; + let mut offenders = Vec::new(); + for entry in entries { + let entry = + entry.map_err(|e| format!("cannot read an entry in {}: {e}", root.display()))?; + let name = entry.file_name().to_string_lossy().into_owned(); + if name == ".quarry" { + if entry.file_type().map(|kind| kind.is_dir()).unwrap_or(false) { + continue; + } + } else if IGNORED_ENTRIES.contains(&name.as_str()) { + continue; + } + offenders.push(name); + } + Ok(offenders) +} + +/// The shared refusal used both by the occupancy check and by a would-be overwrite. +fn occupancy_error(offenders: &[String]) -> String { + let shown: Vec<&str> = offenders.iter().take(3).map(String::as_str).collect(); + format!( + "directory already holds {}; initialize needs an empty directory (or only .quarry/, .git, .DS_Store)", + shown.join(", ") + ) +} + +/// Write a starter file, refusing if the path already exists rather than replacing it. +pub fn write_new_file(root: &Path, rel: &str, contents: &str) -> Result<(), String> { + let path = root.join(rel); + if path.exists() { + return Err(occupancy_error(&[rel.to_string()])); + } + write_file(root, rel, contents) +} + +/// The project name for a scaffold in `root`: the name of the directory being initialized. +fn project_name(root: &Path) -> String { + root.file_name() + .unwrap_or(root.as_os_str()) + .to_string_lossy() + .into_owned() +} + +/// Scaffold one of the four supported kinds into `root` itself and return the opened project. +#[tauri::command] +pub fn init_project(root: String, kind: String, standard: String) -> Result { + let root_path = Path::new(root.trim()); + if !root_path.is_absolute() { + return Err(format!("root must be an absolute path: {root}")); + } + if !root_path.is_dir() { + return Err(format!("root directory does not exist: {root}")); + } + + let offenders = occupancy_offenders(root_path)?; + if !offenders.is_empty() { + return Err(occupancy_error(&offenders)); + } + + match kind.as_str() { + "rust-bin" | "rust-lib" | "c-cmake" | "cpp-cmake" => {} + _ => { + return Err(format!( + "unknown project kind \"{kind}\"; accepted values: rust-bin, rust-lib, c-cmake, cpp-cmake." + )); + } + } + + let standard = resolve_standard(&kind, standard.trim())?; + let name = project_name(root_path); + + match kind.as_str() { + "rust-bin" => { + write_new_file(root_path, "Cargo.toml", &rust_cargo_toml(&name, &standard))?; + write_new_file(root_path, "src/main.rs", &with_name(RUST_MAIN, &name))?; + write_new_file(root_path, ".gitignore", GITIGNORE_TARGET)?; + } + "rust-lib" => { + write_new_file(root_path, "Cargo.toml", &rust_cargo_toml(&name, &standard))?; + write_new_file(root_path, "src/lib.rs", RUST_LIB)?; + write_new_file(root_path, ".gitignore", GITIGNORE_TARGET)?; + } + "c-cmake" => { + write_new_file( + root_path, + "CMakeLists.txt", + &c_cmake_lists(&name, &standard), + )?; + write_new_file(root_path, "src/main.c", &with_name(C_MAIN, &name))?; + write_new_file(root_path, ".gitignore", GITIGNORE_BUILD)?; + } + "cpp-cmake" => { + write_new_file( + root_path, + "CMakeLists.txt", + &cpp_cmake_lists(&name, &standard), + )?; + write_new_file(root_path, "src/main.cpp", &with_name(CPP_MAIN, &name))?; + write_new_file(root_path, ".gitignore", GITIGNORE_BUILD)?; + } + _ => unreachable!(), + } + + project::open_project(root_path.to_string_lossy().into_owned()) +} diff --git a/src-tauri/src/new_project/mod.rs b/src-tauri/src/new_project/mod.rs index 0337d62d..f5432918 100644 --- a/src-tauri/src/new_project/mod.rs +++ b/src-tauri/src/new_project/mod.rs @@ -15,6 +15,9 @@ pub use templates::*; mod create_project; pub use create_project::*; +mod init_project; +pub use init_project::*; + mod resolve_standard; pub use resolve_standard::*; @@ -23,3 +26,6 @@ pub use tests_1::*; mod tests_2; pub use tests_2::*; + +mod tests_init; +pub use tests_init::*; diff --git a/src-tauri/src/new_project/tests_init.rs b/src-tauri/src/new_project/tests_init.rs new file mode 100644 index 00000000..d5ee37ab --- /dev/null +++ b/src-tauri/src/new_project/tests_init.rs @@ -0,0 +1,192 @@ +#![allow(unused_imports)] + +pub(crate) use crate::project; +pub(crate) use crate::types::ProjectInfo; +pub use std::fs; +pub use std::path::{Path, PathBuf}; + +use super::*; + +#[cfg(test)] +#[allow(dead_code)] +pub mod tests_init_group { + use super::*; + + fn scratch(label: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("quarry-init-{}-{label}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("creates the scratch directory"); + dir + } + + fn init(root: &Path, kind: &str) -> Result { + init_with(root, kind, "") + } + + fn init_with(root: &Path, kind: &str, standard: &str) -> Result { + init_project( + root.display().to_string(), + kind.to_string(), + standard.to_string(), + ) + } + + #[test] + fn init_writes_each_kind_into_the_root() { + let cases = [ + ("rust-bin", "src/main.rs", crate::types::ProjectKind::Cargo), + ("rust-lib", "src/lib.rs", crate::types::ProjectKind::Cargo), + ("c-cmake", "src/main.c", crate::types::ProjectKind::Cmake), + ( + "cpp-cmake", + "src/main.cpp", + crate::types::ProjectKind::Cmake, + ), + ]; + for (kind, entry, expected) in cases { + let root = scratch(kind); + let name = root.file_name().unwrap().to_string_lossy().into_owned(); + let info = init(&root, kind).expect("initializes"); + assert!( + !root.join(&name).join(entry).exists(), + "{kind} nested inside a subdirectory" + ); + assert!( + root.join(entry).is_file(), + "{kind} did not write {entry} in root" + ); + assert_eq!(info.kind, expected, "{kind} detected wrong"); + if kind.ends_with("cmake") { + let manifest = fs::read_to_string(root.join("CMakeLists.txt")).expect("reads"); + let language = if kind == "c-cmake" { "C" } else { "CXX" }; + assert!( + manifest.contains(&format!("project({name} {language})")), + "{manifest}" + ); + } + let _ = fs::remove_dir_all(&root); + } + } + + #[test] + fn init_uses_the_directory_name_as_project_name() { + let parent = scratch("name"); + let root = parent.join("mylib"); + fs::create_dir(&root).expect("creates root"); + let info = init(&root, "rust-lib").expect("initializes"); + assert_eq!(info.name, "mylib", "name should come from the directory"); + let manifest = fs::read_to_string(root.join("Cargo.toml")).expect("reads"); + assert!(manifest.contains("name = \"mylib\""), "{manifest}"); + let _ = fs::remove_dir_all(&parent); + } + + #[test] + fn init_returns_what_open_project_returns() { + let root = scratch("reopen"); + let info = init(&root, "rust-bin").expect("initializes"); + let reopened = project::open_project(root.display().to_string()).expect("reopens"); + assert_eq!(info.root, reopened.root); + assert_eq!(info.opened_root, reopened.opened_root); + assert_eq!(info.name, reopened.name); + assert_eq!(info.kind, reopened.kind); + assert_eq!(info.build_root, reopened.build_root); + assert_eq!(info.launch_config, reopened.launch_config); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn init_refuses_a_relative_or_missing_root() { + let error = init_project( + "relative/dir".to_string(), + "rust-bin".to_string(), + String::new(), + ) + .unwrap_err(); + assert!(error.contains("absolute"), "{error}"); + + let root = scratch("missing-root"); + let missing = root.join("nope"); + let error = init_with(&missing, "rust-bin", "").unwrap_err(); + assert!(error.contains("directory"), "{error}"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn init_refuses_a_directory_with_meaningful_content() { + let root = scratch("occupied"); + fs::write(root.join("notes.txt"), "hi").expect("writes stray file"); + let error = init(&root, "rust-bin").unwrap_err(); + assert!(error.contains("already holds"), "{error}"); + assert!(error.contains("notes.txt"), "{error}"); + assert!( + !root.join("Cargo.toml").exists(), + "must write nothing on refusal" + ); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn init_names_at_most_three_offenders() { + let root = scratch("many"); + for i in 0..5 { + fs::write(root.join(format!("file{i}")), "x").expect("writes stray file"); + } + let error = init(&root, "rust-bin").unwrap_err(); + let named: Vec = (0..5) + .filter(|i| error.contains(&format!("file{i}"))) + .collect(); + assert!(!named.is_empty() && named.len() <= 3, "{error}"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn init_allows_quarry_git_and_ds_store_occupants() { + let root = scratch("allowed"); + fs::create_dir(root.join(".quarry")).expect("creates .quarry"); + fs::write(root.join(".quarry/launch.json"), "{}").expect("writes state"); + fs::create_dir(root.join(".git")).expect("creates .git"); + fs::write(root.join(".DS_Store"), "x").expect("writes finder file"); + init(&root, "rust-bin").expect("initializes around the allowed entries"); + assert!(root.join("Cargo.toml").is_file()); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn init_never_overwrites_an_existing_file() { + let root = scratch("no-overwrite"); + fs::write(root.join("Cargo.toml"), "keep me").expect("writes existing file"); + let error = write_new_file(&root, "Cargo.toml", "replacement").unwrap_err(); + assert!(error.contains("already holds"), "{error}"); + assert_eq!( + fs::read_to_string(root.join("Cargo.toml")).unwrap(), + "keep me" + ); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn init_refuses_unknown_kind_with_the_existing_refusal_text() { + let root = scratch("bad-kind"); + let error = init(&root, "kotlin").unwrap_err(); + assert!(error.contains("accepted values"), "{error}"); + assert!(error.contains("rust-bin"), "{error}"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn init_refuses_a_standard_from_the_wrong_language() { + let root = scratch("bad-standard"); + let error = init_with(&root, "c-cmake", "20").unwrap_err(); + assert!(error.contains("not available"), "{error}"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn init_standard_reaches_the_manifest() { + let root = scratch("standard"); + init_with(&root, "rust-bin", "2021").expect("initializes"); + let manifest = fs::read_to_string(root.join("Cargo.toml")).expect("reads"); + assert!(manifest.contains("edition = \"2021\""), "{manifest}"); + let _ = fs::remove_dir_all(&root); + } +}