audb_core/features/config/
state.rs1use anyhow::{anyhow, Result};
2use directories::BaseDirs;
3use std::fs;
4use std::path::PathBuf;
5
6pub struct DeviceState;
7
8impl DeviceState {
9 pub fn state_path() -> Result<PathBuf> {
10 let base_dirs = BaseDirs::new().ok_or_else(|| anyhow!("Could not determine home directory"))?;
11 let config_dir = base_dirs.config_dir().join("audb");
12 fs::create_dir_all(&config_dir)?;
13 Ok(config_dir.join("current_device"))
14 }
15
16 pub fn get_current() -> Result<String> {
17 let path = Self::state_path()?;
18 if !path.exists() {
19 return Err(anyhow!("No device selected. Use 'audb select <identifier>' to select a device"));
20 }
21
22 let host = fs::read_to_string(&path)?.trim().to_string();
23 if host.is_empty() {
24 return Err(anyhow!("No device selected"));
25 }
26
27 Ok(host)
28 }
29
30 pub fn set_current(host: &str) -> Result<()> {
31 let path = Self::state_path()?;
32 fs::write(&path, host)?;
33 Ok(())
34 }
35
36 pub fn clear_current() -> Result<()> {
37 let path = Self::state_path()?;
38 if path.exists() {
39 fs::remove_file(&path)?;
40 }
41 Ok(())
42 }
43}