use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OpenTabState {
pub path: Option<PathBuf>,
pub cursor_row: usize,
pub cursor_col: usize,
pub scroll: usize,
pub scroll_col: usize,
pub dirty: bool,
pub unsaved_text: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SessionState {
pub workspace_root: PathBuf,
pub tabs: Vec<OpenTabState>,
pub active_tab: usize,
pub sidebar_view: String,
pub sidebar_width: u16,
pub terminal_height: Option<u16>,
pub focus_editor: bool,
}
impl SessionState {
pub fn save(&self, path: &Path) -> Result<()> {
let json = serde_json::to_string(self).context("serializing session state")?;
write_private_atomically(path, json.as_bytes())
}
pub fn load(path: &Path) -> Result<Self> {
let json =
std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
serde_json::from_str(&json).context("parsing session state")
}
}
pub(crate) fn write_private_atomically(path: &Path, bytes: &[u8]) -> Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("creating {}", parent.display()))?;
}
use std::io::Write;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
let tmp = path.with_extension(format!(
"json.{}.{:?}.tmp",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_file(&tmp);
let write = || -> std::io::Result<()> {
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
opts.mode(0o600);
let mut f = opts.open(&tmp)?;
f.write_all(bytes)?;
f.sync_all()?;
std::fs::rename(&tmp, path)
};
write().map_err(|e| {
let _ = std::fs::remove_file(&tmp);
anyhow::Error::new(e).context(format!("writing {}", path.display()))
})
}
pub fn handoff_path() -> PathBuf {
let base = dirs_cache_croft();
base.join(format!("session-{}.json", std::process::id()))
}
#[cfg(test)]
thread_local! {
pub(crate) static CACHE_DIR_FOR_THIS_TEST_THREAD: std::cell::RefCell<Option<PathBuf>> =
const { std::cell::RefCell::new(None) };
}
pub(crate) fn dirs_cache_croft() -> PathBuf {
#[cfg(test)]
if let Some(dir) = CACHE_DIR_FOR_THIS_TEST_THREAD.with(|d| d.borrow().clone()) {
return dir;
}
let home = std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));
home.join(".cache").join("croft")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_through_disk() {
let dir = std::env::temp_dir().join(format!("croft-session-test-{}", std::process::id()));
let path = dir.join("state.json");
let state = SessionState {
workspace_root: PathBuf::from("/work/repo"),
tabs: vec![
OpenTabState {
path: Some(PathBuf::from("/work/repo/src/main.rs")),
cursor_row: 12,
cursor_col: 4,
scroll: 3,
scroll_col: 0,
dirty: false,
unsaved_text: None,
},
OpenTabState {
path: Some(PathBuf::from("/work/repo/README.md")),
cursor_row: 0,
cursor_col: 0,
scroll: 0,
scroll_col: 0,
dirty: true,
unsaved_text: Some(String::from("edited\nbody")),
},
],
active_tab: 1,
sidebar_view: String::from("Explorer"),
sidebar_width: 32,
terminal_height: Some(14),
focus_editor: true,
};
state.save(&path).expect("save");
let loaded = SessionState::load(&path).expect("load");
assert_eq!(state, loaded);
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn handoff_path_is_pid_scoped_under_cache_croft() {
let p = handoff_path();
assert!(p.to_string_lossy().contains(".cache/croft"));
assert!(
p.file_name()
.unwrap()
.to_string_lossy()
.starts_with("session-")
);
}
#[test]
fn the_handoff_does_not_carry_terminal_panes() {
let state = SessionState {
workspace_root: PathBuf::from("/work/repo"),
tabs: Vec::new(),
active_tab: 0,
sidebar_view: String::from("Explorer"),
sidebar_width: 32,
terminal_height: None,
focus_editor: true,
};
let json = serde_json::to_string(&state).expect("serialize");
assert!(
!json.contains("terminals"),
"panes belong to the per-workspace store, not the handoff: {json}"
);
}
}