use std::path::{Path, PathBuf};
use std::sync::RwLock;
pub const PROFILED_FILES: &[&str] = &["config.json", "keybindings.json", "snippets.json"];
static ACTIVE: RwLock<Option<String>> = RwLock::new(None);
pub fn profiles_dir() -> PathBuf {
crate::paths::config_dir().join("profiles")
}
fn global_choice_path() -> PathBuf {
crate::paths::config_dir().join("profile")
}
pub fn workspace_choice_path(root: &Path) -> PathBuf {
root.join(".croft").join("profile")
}
pub fn file(name: &str) -> PathBuf {
match active() {
Some(profile) => profiles_dir().join(profile).join(name),
None => crate::paths::config_dir().join(name),
}
}
pub fn active() -> Option<String> {
ACTIVE.read().ok().and_then(|a| a.clone())
}
fn set_active(name: Option<String>) {
if let Ok(mut a) = ACTIVE.write() {
*a = name;
}
}
pub fn valid_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& !name.starts_with('.')
&& name
.chars()
.all(|c| c.is_alphanumeric() || " -_".contains(c))
}
pub fn list() -> Vec<String> {
list_in(&profiles_dir())
}
fn list_in(dir: &Path) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.filter_map(|e| e.file_name().into_string().ok())
.filter(|n| valid_name(n))
.collect();
names.sort();
names
}
fn read_choice(path: &Path) -> Option<String> {
let text = std::fs::read_to_string(path).ok()?;
let name = text.lines().next()?.trim().to_string();
(valid_name(&name) && profiles_dir().join(&name).is_dir()).then_some(name)
}
pub fn activate_for_workspace(root: &Path) -> Option<String> {
let chosen =
read_choice(&workspace_choice_path(root)).or_else(|| read_choice(&global_choice_path()));
set_active(chosen.clone());
chosen
}
pub fn switch(name: Option<&str>) -> std::io::Result<()> {
let path = global_choice_path();
match name {
Some(n) => {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(&path, format!("{n}\n"))?;
}
None => {
let _ = std::fs::remove_file(&path);
}
}
set_active(name.map(str::to_string));
Ok(())
}
pub fn create_from_current(name: &str) -> std::io::Result<()> {
create_in(&profiles_dir(), name, file)
}
fn create_in(
profiles: &Path,
name: &str,
current: impl Fn(&str) -> PathBuf,
) -> std::io::Result<()> {
if !valid_name(name) {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"a profile name uses letters, digits, spaces, - and _",
));
}
let dir = profiles.join(name);
if dir.exists() {
return Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
format!("profile {name} already exists"),
));
}
std::fs::create_dir_all(&dir)?;
for f in PROFILED_FILES {
let from = current(f);
if from.is_file() {
std::fs::copy(&from, dir.join(f))?;
}
}
Ok(())
}
pub fn set_workspace_default(root: &Path, name: Option<&str>) -> std::io::Result<()> {
let path = workspace_choice_path(root);
match name {
Some(n) => {
let dir = path.parent().unwrap_or(root);
if std::fs::symlink_metadata(dir).is_ok_and(|m| m.file_type().is_symlink())
|| std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink())
{
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("{} is a symlink; not writing through it", path.display()),
));
}
std::fs::create_dir_all(dir)?;
std::fs::write(&path, format!("{n}\n"))
}
None => match std::fs::remove_file(&path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_that_could_escape_the_profiles_dir_are_refused() {
assert!(valid_name("Python"));
assert!(valid_name("writing mode_2"));
assert!(!valid_name(""));
assert!(!valid_name("../etc"));
assert!(!valid_name(".hidden"));
assert!(!valid_name("a/b"));
}
#[test]
fn a_new_profile_copies_the_files_in_effect_and_is_listed() {
let tmp = tempfile::tempdir().unwrap();
let current = tmp.path().join("current");
std::fs::create_dir(¤t).unwrap();
std::fs::write(current.join("keybindings.json"), "[]").unwrap();
let profiles = tmp.path().join("profiles");
create_in(&profiles, "Python", |f| current.join(f)).unwrap();
assert_eq!(
std::fs::read_to_string(profiles.join("Python").join("keybindings.json")).unwrap(),
"[]"
);
assert!(
!profiles.join("Python").join("config.json").exists(),
"only what exists is copied"
);
assert!(
create_in(&profiles, "Python", |f| current.join(f)).is_err(),
"no overwrite"
);
assert!(create_in(&profiles, "../x", |f| current.join(f)).is_err());
assert_eq!(list_in(&profiles), vec![String::from("Python")]);
}
#[test]
fn a_workspace_default_is_written_and_cleared() {
let tmp = tempfile::tempdir().unwrap();
set_workspace_default(tmp.path(), Some("Python")).unwrap();
assert_eq!(
std::fs::read_to_string(workspace_choice_path(tmp.path())).unwrap(),
"Python\n"
);
set_workspace_default(tmp.path(), None).unwrap();
assert!(!workspace_choice_path(tmp.path()).exists());
set_workspace_default(tmp.path(), None).unwrap();
}
#[test]
#[cfg(unix)]
fn a_symlinked_workspace_choice_is_never_written_through() {
let tmp = tempfile::tempdir().unwrap();
let victim = tmp.path().join("victim");
std::fs::write(&victim, "keep me").unwrap();
let ws = tmp.path().join("ws");
std::fs::create_dir_all(ws.join(".croft")).unwrap();
std::os::unix::fs::symlink(&victim, workspace_choice_path(&ws)).unwrap();
assert!(set_workspace_default(&ws, Some("Python")).is_err());
assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me");
let ws2 = tmp.path().join("ws2");
std::fs::create_dir(&ws2).unwrap();
std::os::unix::fs::symlink(tmp.path(), ws2.join(".croft")).unwrap();
assert!(set_workspace_default(&ws2, Some("Python")).is_err());
}
#[test]
fn with_no_profile_the_files_live_in_the_config_dir() {
if active().is_none() {
assert_eq!(
file("config.json"),
crate::paths::config_dir().join("config.json")
);
}
}
}