logicaffeine_cli/project/
credentials.rs1use std::collections::HashMap;
21use std::fs;
22use std::path::PathBuf;
23
24#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
36pub struct Credentials {
37 #[serde(default)]
39 pub registries: HashMap<String, String>,
40}
41
42impl Credentials {
43 pub fn load() -> Result<Self, CredentialsError> {
45 let path = credentials_path().ok_or(CredentialsError::NoConfigDir)?;
46
47 if !path.exists() {
48 return Ok(Self::default());
49 }
50
51 let content = fs::read_to_string(&path).map_err(|e| CredentialsError::Io(e.to_string()))?;
52
53 toml::from_str(&content).map_err(|e| CredentialsError::Parse(e.to_string()))
54 }
55
56 pub fn save(&self) -> Result<(), CredentialsError> {
58 let path = credentials_path().ok_or(CredentialsError::NoConfigDir)?;
59
60 if let Some(parent) = path.parent() {
62 fs::create_dir_all(parent).map_err(|e| CredentialsError::Io(e.to_string()))?;
63 }
64
65 let content =
66 toml::to_string_pretty(self).map_err(|e| CredentialsError::Serialize(e.to_string()))?;
67
68 fs::write(&path, content).map_err(|e| CredentialsError::Io(e.to_string()))?;
69
70 #[cfg(unix)]
72 {
73 use std::os::unix::fs::PermissionsExt;
74 let perms = std::fs::Permissions::from_mode(0o600);
75 fs::set_permissions(&path, perms).map_err(|e| CredentialsError::Io(e.to_string()))?;
76 }
77
78 Ok(())
79 }
80
81 pub fn get_token(&self, registry_url: &str) -> Option<&str> {
83 self.registries.get(registry_url).map(|s| s.as_str())
84 }
85
86 pub fn set_token(&mut self, registry_url: &str, token: &str) {
88 self.registries
89 .insert(registry_url.to_string(), token.to_string());
90 }
91
92 pub fn remove_token(&mut self, registry_url: &str) {
94 self.registries.remove(registry_url);
95 }
96}
97
98pub fn get_token(registry_url: &str) -> Option<String> {
100 if let Ok(token) = std::env::var("LOGOS_TOKEN") {
102 if !token.is_empty() {
103 return Some(token);
104 }
105 }
106
107 Credentials::load()
109 .ok()
110 .and_then(|c| c.get_token(registry_url).map(String::from))
111}
112
113pub fn credentials_path() -> Option<PathBuf> {
115 if let Ok(path) = std::env::var("LOGOS_CREDENTIALS_PATH") {
117 return Some(PathBuf::from(path));
118 }
119
120 dirs::config_dir().map(|p| p.join("logos").join("credentials.toml"))
122}
123
124#[derive(Debug)]
126pub enum CredentialsError {
127 NoConfigDir,
129 Io(String),
131 Parse(String),
133 Serialize(String),
135}
136
137impl std::fmt::Display for CredentialsError {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 match self {
140 Self::NoConfigDir => write!(f, "Could not determine config directory"),
141 Self::Io(e) => write!(f, "I/O error: {}", e),
142 Self::Parse(e) => write!(f, "Failed to parse credentials: {}", e),
143 Self::Serialize(e) => write!(f, "Failed to serialize credentials: {}", e),
144 }
145 }
146}
147
148impl std::error::Error for CredentialsError {}