1use carch_core::error::{CarchError, Result};
4use std::path::PathBuf;
5use std::{env, fs};
6
7const STATE_FILE_NAME: &str = "state.toml";
8
9fn state_path() -> Result<PathBuf> {
10 let home = env::var("HOME").map_err(|_| CarchError::HomeDirNotFound)?;
11 Ok(PathBuf::from(home).join(".config/carch").join(STATE_FILE_NAME))
12}
13
14fn ensure_parent_dir(path: &std::path::Path) -> Result<()> {
15 if let Some(parent) = path.parent() {
16 fs::create_dir_all(parent)
17 .map_err(|e| CarchError::CreateDir(parent.display().to_string(), e))?;
18 }
19 Ok(())
20}
21
22pub fn save_favorite_theme(theme: &str) -> Result<()> {
23 if theme.is_empty() {
24 return Err(CarchError::Command("Theme name must not be empty".to_string()));
25 }
26 let path = state_path()?;
27 ensure_parent_dir(&path)?;
28 let contents = format!("theme = \"{}\"\n", escape_toml_string(theme));
29 let tmp = path.with_extension("toml.tmp");
30 fs::write(&tmp, contents).map_err(|e| CarchError::WriteFile(tmp.display().to_string(), e))?;
31 fs::rename(&tmp, &path).map_err(|e| CarchError::WriteFile(path.display().to_string(), e))?;
32 Ok(())
33}
34
35pub fn load_favorite_theme() -> Option<String> {
37 let path = state_path().ok()?;
38 let content = fs::read_to_string(&path).ok()?;
39 let table: toml::Table = content.parse().ok()?;
40 table.get("theme")?.as_str().map(str::to_string)
41}
42
43pub fn clear_favorite_theme() -> Result<bool> {
44 let path = state_path()?;
45 match fs::remove_file(&path) {
46 Ok(()) => Ok(true),
47 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
48 Err(e) => Err(CarchError::WriteFile(path.display().to_string(), e)),
49 }
50}
51
52fn escape_toml_string(s: &str) -> String {
53 s.replace('\\', "\\\\")
54 .replace('"', "\\\"")
55 .replace('\n', "\\n")
56 .replace('\r', "\\r")
57 .replace('\t', "\\t")
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63 use std::sync::{Mutex, PoisonError};
64
65 static HOME_LOCK: Mutex<()> = Mutex::new(());
66
67 struct ScopedHome {
68 _guard: std::sync::MutexGuard<'static, ()>,
69 prev: Option<String>,
70 tmp: PathBuf,
71 }
72
73 impl ScopedHome {
74 fn new() -> Self {
75 let guard = HOME_LOCK.lock().unwrap_or_else(PoisonError::into_inner);
76 let tmp = std::env::temp_dir().join(format!(
77 "carch_state_test_{}_{}",
78 std::process::id(),
79 std::time::SystemTime::now()
80 .duration_since(std::time::UNIX_EPOCH)
81 .unwrap()
82 .as_nanos()
83 ));
84 std::fs::create_dir_all(&tmp).unwrap();
85 let prev = std::env::var("HOME").ok();
86 unsafe {
88 std::env::set_var("HOME", &tmp);
89 }
90 ScopedHome { _guard: guard, prev, tmp }
91 }
92 }
93
94 impl Drop for ScopedHome {
95 fn drop(&mut self) {
96 match &self.prev {
97 Some(p) => unsafe {
98 std::env::set_var("HOME", p);
99 },
100 None => unsafe {
101 std::env::remove_var("HOME");
102 },
103 }
104 let _ = std::fs::remove_dir_all(&self.tmp);
105 }
106 }
107
108 #[test]
109 fn save_then_load_roundtrip() {
110 let _h = ScopedHome::new();
111 save_favorite_theme("dracula").unwrap();
112 assert_eq!(load_favorite_theme().as_deref(), Some("dracula"));
113 }
114
115 #[test]
116 fn load_returns_none_when_no_state_file() {
117 let _h = ScopedHome::new();
118 assert_eq!(load_favorite_theme(), None);
119 }
120
121 #[test]
122 fn save_rejects_empty_theme() {
123 let _h = ScopedHome::new();
124 let err = save_favorite_theme("").unwrap_err();
125 assert!(matches!(err, CarchError::Command(_)));
126 }
127
128 #[test]
129 fn save_escapes_special_chars_in_theme_name() {
130 let _h = ScopedHome::new();
131 save_favorite_theme(r#"a"b"#).unwrap();
132 assert_eq!(load_favorite_theme().as_deref(), Some(r#"a"b"#));
133 }
134
135 #[test]
136 fn clear_removes_state_file() {
137 let _h = ScopedHome::new();
138 save_favorite_theme("nord").unwrap();
139 assert!(clear_favorite_theme().unwrap());
140 assert_eq!(load_favorite_theme(), None);
141 }
142
143 #[test]
144 fn clear_returns_false_when_no_file() {
145 let _h = ScopedHome::new();
146 assert!(!clear_favorite_theme().unwrap());
147 }
148
149 #[test]
150 fn save_overwrites_previous_value() {
151 let _h = ScopedHome::new();
152 save_favorite_theme("dracula").unwrap();
153 save_favorite_theme("gruvbox").unwrap();
154 assert_eq!(load_favorite_theme().as_deref(), Some("gruvbox"));
155 }
156
157 #[test]
158 fn state_file_path_is_under_config_carch() {
159 let _h = ScopedHome::new();
160 save_favorite_theme("nord").unwrap();
161 let path = state_path().unwrap();
162 assert!(path.ends_with(".config/carch/state.toml"));
163 assert!(path.exists());
164 }
165
166 #[test]
167 fn escape_handles_special_chars() {
168 assert_eq!(escape_toml_string("plain"), "plain");
169 assert_eq!(escape_toml_string(r#"a"b"#), r#"a\"b"#);
170 assert_eq!(escape_toml_string("a\\b"), "a\\\\b");
171 assert_eq!(escape_toml_string("a\nb"), "a\\nb");
172 }
173}