use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PaneRecord {
pub cwd: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SessionRecord {
pub panes: Vec<PaneRecord>,
#[serde(default)]
pub active: usize,
}
impl SessionRecord {
pub fn is_trivial(&self, root: &str) -> bool {
match self.panes.as_slice() {
[] => true,
[only] => only.name.is_none() && same_dir(&only.cwd, root),
_ => false,
}
}
}
fn same_dir(a: &str, b: &str) -> bool {
if a == b {
return true;
}
match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
(Ok(x), Ok(y)) => x == y,
_ => false,
}
}
pub fn path() -> PathBuf {
crate::prefs::config_dir().join("terminal_sessions.json")
}
pub fn load(path: &Path) -> HashMap<String, SessionRecord> {
load_checked(path).unwrap_or_default()
}
fn load_checked(path: &Path) -> Result<HashMap<String, SessionRecord>, String> {
let raw = match std::fs::read_to_string(path) {
Ok(raw) => raw,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()),
Err(e) => return Err(format!("read {}: {e}", path.display())),
};
serde_json::from_str(&raw).map_err(|e| format!("parse {}: {e}", path.display()))
}
pub fn save_for_root(path: &Path, root: &str, record: SessionRecord) -> Result<(), String> {
crate::workspace::update_json_store::<SessionRecord, _>(path, |map| {
if record.is_trivial(root) {
map.remove(root);
} else {
map.insert(root.to_string(), record.clone());
}
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_corrupt_store_is_refused_not_replaced() {
let tmp = tempfile::tempdir().unwrap();
let store = tmp.path().join("sessions.json");
std::fs::write(&store, "{ not valid json").unwrap();
let record = SessionRecord {
panes: vec![PaneRecord {
cwd: String::from("/w/a/sub"),
name: Some(String::from("srv")),
}],
active: 0,
};
assert!(
save_for_root(&store, "/w/a", record.clone()).is_err(),
"a corrupt store must refuse the update"
);
assert_eq!(
std::fs::read_to_string(&store).unwrap(),
"{ not valid json",
"the corrupt bytes stay untouched"
);
assert!(load(&store).is_empty(), "read-only loads degrade to empty");
let fresh = tmp.path().join("fresh.json");
save_for_root(&fresh, "/w/a", record).unwrap();
assert_eq!(load(&fresh).get("/w/a").map(|r| r.panes.len()), Some(1));
}
#[test]
fn save_round_trips_and_trivial_records_prune() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("s.json");
let rec = SessionRecord {
panes: vec![
PaneRecord {
cwd: String::from("/repo"),
name: None,
},
PaneRecord {
cwd: String::from("/repo/sub"),
name: Some(String::from("srv")),
},
],
active: 1,
};
save_for_root(&p, "/repo", rec.clone()).unwrap();
let map = load(&p);
assert_eq!(map.get("/repo"), Some(&rec));
save_for_root(
&p,
"/repo",
SessionRecord {
panes: vec![PaneRecord {
cwd: String::from("/repo"),
name: None,
}],
active: 0,
},
)
.unwrap();
assert!(!load(&p).contains_key("/repo"));
std::fs::write(&p, "not json").unwrap();
assert!(load(&p).is_empty());
}
}