Commit 97d8e9dd
97d8e9ddaa9dMerged
Scott Nixon <[email protected]> ยท 9 months ago ยท 1 file ยท ~1 modified
Description
[attractor-baz] Create projects.rs with Leptos server functions for project management
Implements 5 server functions:
- list_open_projects: List all open projects sorted by last_used
- open_project: Validate folder path and upsert into DB with canonicalization
- close_project: Mark project as closed without deleting data
- get_cached_documents: Fetch PRD/Spec docs from DB, return as CachedDocs struct
- list_directory: Browse server filesystem safely for folder picker
All functions extract SqlitePool from Leptos context, validate inputs, and handle errors. list_directory filters hidden dirs and only returns directories for safe browsing.
Defines CachedDocs and DirEntry structs for serialization to frontend. Re-exports Project and CachedDoc types from db module.
Details
- Commit
- 97d8e9ddaa9d
- Parent
- 2fb753185e8f
crates/attractor-web/src/server/projects.rsmodifiedView file
@@ -1,2 +1,206 @@
1-
// Project management server functions2-
// This module is a stub - full implementation in task attractor-baz1+
use crate::server::db;2+
use serde::{Deserialize, Serialize};3+
use sqlx::SqlitePool;4+
use std::path::{Path, PathBuf};5+
6+
// Re-export database types for use in server functions7+
pub use crate::server::db::{CachedDoc, Project};8+
9+
#[derive(Debug, Clone, Serialize, Deserialize)]10+
pub struct CachedDocs {11+
pub prd: Option<String>,12+
pub spec: Option<String>,13+
}14+
15+
#[derive(Debug, Clone, Serialize, Deserialize)]16+
pub struct DirEntry {17+
pub name: String,18+
pub path: String,19+
pub is_dir: bool,20+
}21+
22+
#[cfg(feature = "ssr")]23+
mod ssr_impl {24+
use super::*;25+
use leptos::prelude::*;26+
use std::fs;27+
28+
/// List all open projects sorted by most recently used.29+
#[server]30+
pub async fn list_open_projects() -> Result<Vec<Project>, ServerFnError> {31+
let pool = use_context::<SqlitePool>()32+
.ok_or_else(|| ServerFnError::new("No database pool"))?;33+
34+
db::list_open_projects(&pool)35+
.await36+
.map_err(|e| ServerFnError::new(format!("Failed to list projects: {}", e)))37+
}38+
39+
/// Open a project at the given folder path.40+
/// Validates that the path exists and is a directory, then upserts into DB.41+
#[server]42+
pub async fn open_project(folder_path: String) -> Result<Project, ServerFnError> {43+
let pool = use_context::<SqlitePool>()44+
.ok_or_else(|| ServerFnError::new("No database pool"))?;45+
46+
// Validate that the path exists and is a directory47+
let path = PathBuf::from(&folder_path);48+
if !path.exists() {49+
return Err(ServerFnError::new(format!(50+
"Path does not exist: {}",51+
folder_path52+
)));53+
}54+
55+
if !path.is_dir() {56+
return Err(ServerFnError::new(format!(57+
"Path is not a directory: {}",58+
folder_path59+
)));60+
}61+
62+
// Canonicalize the path to resolve symlinks and normalize63+
let canonical_path = path64+
.canonicalize()65+
.map_err(|e| ServerFnError::new(format!("Failed to canonicalize path: {}", e)))?;66+
67+
let canonical_str = canonical_path68+
.to_str()69+
.ok_or_else(|| ServerFnError::new("Path contains invalid UTF-8"))?70+
.to_string();71+
72+
// Upsert into database73+
db::upsert_project(&pool, &canonical_str)74+
.await75+
.map_err(|e| ServerFnError::new(format!("Failed to open project: {}", e)))76+
}77+
78+
/// Close a project (mark as not open) without deleting its data.79+
#[server]80+
pub async fn close_project(project_id: i64) -> Result<(), ServerFnError> {81+
let pool = use_context::<SqlitePool>()82+
.ok_or_else(|| ServerFnError::new("No database pool"))?;83+
84+
db::close_project(&pool, project_id)85+
.await86+
.map_err(|e| ServerFnError::new(format!("Failed to close project: {}", e)))87+
}88+
89+
/// Get cached PRD and Spec documents for a project.90+
#[server]91+
pub async fn get_cached_documents(project_id: i64) -> Result<CachedDocs, ServerFnError> {92+
let pool = use_context::<SqlitePool>()93+
.ok_or_else(|| ServerFnError::new("No database pool"))?;94+
95+
let docs = db::get_documents(&pool, project_id)96+
.await97+
.map_err(|e| ServerFnError::new(format!("Failed to fetch documents: {}", e)))?;98+
99+
let mut prd = None;100+
let mut spec = None;101+
102+
for doc in docs {103+
match doc.doc_type.as_str() {104+
"prd" => prd = Some(doc.content),105+
"spec" => spec = Some(doc.content),106+
_ => {}107+
}108+
}109+
110+
Ok(CachedDocs { prd, spec })111+
}112+
113+
/// List directory entries (only directories) for the folder picker browser.114+
/// If path is empty, defaults to home directory.115+
/// Returns parent (..) entry for navigation (except at filesystem root).116+
/// Filters out hidden directories starting with `.` unless in a special list.117+
#[server]118+
pub async fn list_directory(path: String) -> Result<Vec<DirEntry>, ServerFnError> {119+
let dir_path = if path.is_empty() {120+
// Default to home directory121+
std::env::var("HOME")122+
.map(PathBuf::from)123+
.map_err(|_| ServerFnError::new("HOME environment variable not set"))?124+
} else {125+
PathBuf::from(&path)126+
};127+
128+
// Verify the path is a directory129+
if !dir_path.is_dir() {130+
return Err(ServerFnError::new(format!(131+
"Path is not a directory: {}",132+
path133+
)));134+
}135+
136+
let mut entries = Vec::new();137+
138+
// Add parent (..) entry unless we're at filesystem root139+
if dir_path.parent().is_some() && dir_path.parent() != Some(Path::new("")) {140+
if let Some(parent) = dir_path.parent() {141+
if let Some(parent_str) = parent.to_str() {142+
entries.push(DirEntry {143+
name: "..".to_string(),144+
path: parent_str.to_string(),145+
is_dir: true,146+
});147+
}148+
}149+
}150+
151+
// Read directory and collect only subdirectories152+
match fs::read_dir(&dir_path) {153+
Ok(read_dir) => {154+
let mut sub_entries: Vec<DirEntry> = read_dir155+
.filter_map(|entry| {156+
let entry = entry.ok()?;157+
let path = entry.path();158+
159+
// Skip hidden directories (starting with .)160+
if let Some(name) = path.file_name() {161+
if let Some(name_str) = name.to_str() {162+
if name_str.starts_with('.') {163+
return None;164+
}165+
}166+
}167+
168+
// Only include directories169+
if path.is_dir() {170+
let name = path171+
.file_name()172+
.and_then(|n| n.to_str())173+
.unwrap_or("unknown")174+
.to_string();175+
let path_str = path.to_str().unwrap_or("").to_string();176+
177+
Some(DirEntry {178+
name,179+
path: path_str,180+
is_dir: true,181+
})182+
} else {183+
None184+
}185+
})186+
.collect();187+
188+
// Sort by name189+
sub_entries.sort_by(|a, b| a.name.cmp(&b.name));190+
entries.extend(sub_entries);191+
}192+
Err(e) => {193+
return Err(ServerFnError::new(format!(194+
"Failed to read directory: {}",195+
e196+
)))197+
}198+
}199+
200+
Ok(entries)201+
}202+
}203+
204+
// Re-export server functions for the frontend205+
#[cfg(feature = "ssr")]206+
pub use ssr_impl::*;