tracevault_cli/
credentials.rs1use serde::{Deserialize, Serialize};
2use std::fs;
3use std::path::PathBuf;
4
5#[derive(Debug, Serialize, Deserialize)]
6pub struct Credentials {
7 pub server_url: String,
8 pub token: String,
9 pub email: String,
10}
11
12impl Credentials {
13 pub fn path() -> PathBuf {
14 dirs::config_dir()
15 .unwrap_or_else(|| PathBuf::from("~/.config"))
16 .join("tracevault")
17 .join("credentials.json")
18 }
19
20 pub fn load() -> Option<Self> {
21 let path = Self::path();
22 let content = fs::read_to_string(&path).ok()?;
23 serde_json::from_str(&content).ok()
24 }
25
26 pub fn save(&self) -> Result<(), std::io::Error> {
27 let path = Self::path();
28 if let Some(parent) = path.parent() {
29 fs::create_dir_all(parent)?;
30 }
31 let json = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
32 fs::write(&path, json)
33 }
34
35 pub fn delete() -> Result<(), std::io::Error> {
36 let path = Self::path();
37 if path.exists() {
38 fs::remove_file(&path)?;
39 }
40 Ok(())
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47
48 #[test]
61 fn load_old_credentials_with_org_slug_still_parses() {
62 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
63 let dir = tempfile::tempdir().unwrap();
64 let mut _guard = crate::test_helpers::EnvVarGuard::new();
65 _guard.set("XDG_CONFIG_HOME", dir.path());
66
67 let creds_dir = dir.path().join("tracevault");
68 fs::create_dir_all(&creds_dir).unwrap();
69 fs::write(
70 creds_dir.join("credentials.json"),
71 r#"{"server_url":"https://example.com","token":"tok","email":"a@b.com","org_slug":"x"}"#,
72 )
73 .unwrap();
74
75 let creds =
76 Credentials::load().expect("old credentials.json with org_slug must still parse");
77 assert_eq!(creds.server_url, "https://example.com");
78 assert_eq!(creds.token, "tok");
79 assert_eq!(creds.email, "a@b.com");
80 }
81}