use std::path::{Path, PathBuf};
pub struct PluginDevWorkspace {
dir: PathBuf,
pub plugin_file: PathBuf,
}
const TSCONFIG_CONTENT: &str = r#"{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"moduleResolution": "node",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"lib": ["ES2020"],
"types": []
},
"files": ["fresh.d.ts", "plugin.ts"]
}
"#;
impl PluginDevWorkspace {
pub fn create(
buffer_id: usize,
content: &str,
fresh_dts_source: &Path,
) -> Result<Self, String> {
let cache_dir =
dirs::cache_dir().ok_or_else(|| "Could not determine cache directory".to_string())?;
let dir = cache_dir
.join("fresh")
.join("plugin-dev")
.join(buffer_id.to_string());
std::fs::create_dir_all(&dir)
.map_err(|e| format!("Failed to create plugin dev workspace: {}", e))?;
let dest_dts = dir.join("fresh.d.ts");
std::fs::copy(fresh_dts_source, &dest_dts)
.map_err(|e| format!("Failed to copy fresh.d.ts: {}", e))?;
let tsconfig_path = dir.join("tsconfig.json");
std::fs::write(&tsconfig_path, TSCONFIG_CONTENT)
.map_err(|e| format!("Failed to write tsconfig.json: {}", e))?;
let plugin_file = dir.join("plugin.ts");
std::fs::write(&plugin_file, content)
.map_err(|e| format!("Failed to write plugin.ts: {}", e))?;
tracing::info!(
"Created plugin dev workspace at {:?} for buffer {}",
dir,
buffer_id
);
Ok(Self { dir, plugin_file })
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn cleanup(&self) {
if self.dir.exists() {
if let Err(e) = std::fs::remove_dir_all(&self.dir) {
tracing::warn!(
"Failed to clean up plugin dev workspace {:?}: {}",
self.dir,
e
);
} else {
tracing::debug!("Cleaned up plugin dev workspace {:?}", self.dir);
}
}
}
}
impl Drop for PluginDevWorkspace {
fn drop(&mut self) {
self.cleanup();
}
}