Skip to main content

clickupc_core/
config.rs

1//! Config file (`~/.config/clickupc/config.toml`) with named profiles and
2//! `CLICKUP_*` env overrides. Priority: env > selected profile > defaults.
3
4use std::{collections::BTreeMap, path::PathBuf};
5
6use serde::{Deserialize, Serialize};
7
8use crate::error::{ClickUpError, Result};
9
10pub const DEFAULT_BASE_URL: &str = "https://api.clickup.com/api";
11pub const DEFAULT_PROFILE: &str = "default";
12pub const DEFAULT_TIMEOUT_SECS: u64 = 30;
13
14#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
15pub struct ConfigFile {
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub current_profile: Option<String>,
18    #[serde(default)]
19    pub profiles: BTreeMap<String, Profile>,
20}
21
22#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
23pub struct Profile {
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub token: Option<String>,
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub workspace_id: Option<String>,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub default_list: Option<String>,
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub timezone: Option<String>,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub timeout_secs: Option<u64>,
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub default_task_limit: Option<usize>,
36    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
37    pub aliases: BTreeMap<String, String>,
38}
39
40fn env(key: &str) -> Option<String> {
41    std::env::var(key)
42        .ok()
43        .map(|v| v.trim().to_string())
44        .filter(|v| !v.is_empty())
45}
46
47fn env_parse<T: std::str::FromStr>(key: &str) -> Result<Option<T>> {
48    match env(key) {
49        None => Ok(None),
50        Some(v) => v
51            .parse()
52            .map(Some)
53            .map_err(|_| ClickUpError::Config(format!("{key} has an invalid value '{v}'"))),
54    }
55}
56
57impl ConfigFile {
58    /// `$CLICKUP_CONFIG_DIR/config.toml`, else `<config dir>/clickupc/config.toml`.
59    pub fn path() -> Result<PathBuf> {
60        let dir = match env("CLICKUP_CONFIG_DIR") {
61            Some(dir) => PathBuf::from(dir),
62            None => dirs::config_dir()
63                .ok_or_else(|| ClickUpError::Config("cannot locate a config directory".into()))?
64                .join("clickupc"),
65        };
66        Ok(dir.join("config.toml"))
67    }
68
69    pub fn load() -> Result<Self> {
70        let path = Self::path()?;
71        if !path.exists() {
72            return Ok(Self::default());
73        }
74        warn_if_world_readable(&path);
75        let text = std::fs::read_to_string(&path)?;
76        toml::from_str(&text).map_err(|e| ClickUpError::Config(format!("{}: {e}", path.display())))
77    }
78
79    pub fn save(&self) -> Result<PathBuf> {
80        let path = Self::path()?;
81        if let Some(dir) = path.parent() {
82            std::fs::create_dir_all(dir)?;
83        }
84        let text = toml::to_string_pretty(self).map_err(|e| ClickUpError::Config(e.to_string()))?;
85        std::fs::write(&path, text)?;
86        restrict_permissions(&path)?;
87        Ok(path)
88    }
89
90    /// `CLICKUP_PROFILE` > `current_profile` > `default`.
91    pub fn selected_profile_name(&self) -> String {
92        env("CLICKUP_PROFILE")
93            .or_else(|| self.current_profile.clone())
94            .unwrap_or_else(|| DEFAULT_PROFILE.to_string())
95    }
96
97    pub fn profile_mut(&mut self, name: &str) -> &mut Profile {
98        self.profiles.entry(name.to_string()).or_default()
99    }
100}
101
102#[cfg(unix)]
103fn restrict_permissions(path: &std::path::Path) -> Result<()> {
104    use std::os::unix::fs::PermissionsExt;
105    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
106    Ok(())
107}
108
109#[cfg(not(unix))]
110fn restrict_permissions(_path: &std::path::Path) -> Result<()> {
111    Ok(())
112}
113
114#[cfg(unix)]
115fn warn_if_world_readable(path: &std::path::Path) {
116    use std::os::unix::fs::PermissionsExt;
117    if let Ok(meta) = std::fs::metadata(path) {
118        if meta.permissions().mode() & 0o077 != 0 {
119            tracing::warn!(
120                "{} is readable by other users; run `chmod 600` on it",
121                path.display()
122            );
123        }
124    }
125}
126
127#[cfg(not(unix))]
128fn warn_if_world_readable(_path: &std::path::Path) {}
129
130/// Effective settings after merging the selected profile with env overrides.
131#[derive(Debug, Clone)]
132pub struct ClickUpConfig {
133    pub profile: String,
134    pub token: Option<String>,
135    pub workspace_id: Option<String>,
136    pub default_list: Option<String>,
137    pub timezone: Option<String>,
138    pub timeout_secs: u64,
139    pub default_task_limit: Option<usize>,
140    pub aliases: BTreeMap<String, String>,
141    pub base_url: String,
142    pub cache_dir: PathBuf,
143    pub config_path: PathBuf,
144}
145
146impl ClickUpConfig {
147    /// Load using the profile chosen by env / `current_profile`.
148    pub fn load() -> Result<Self> {
149        Self::load_profile(None)
150    }
151
152    /// Load an explicit profile (e.g. `--profile work`), falling back to the
153    /// usual selection when `None`.
154    pub fn load_profile(profile: Option<&str>) -> Result<Self> {
155        let file = ConfigFile::load()?;
156        Self::from_file(&file, profile)
157    }
158
159    pub fn from_file(file: &ConfigFile, profile: Option<&str>) -> Result<Self> {
160        let name = profile
161            .map(str::to_string)
162            .unwrap_or_else(|| file.selected_profile_name());
163        let p = file.profiles.get(&name).cloned().unwrap_or_default();
164        let cache_dir = match env("CLICKUP_CACHE_DIR") {
165            Some(dir) => PathBuf::from(dir),
166            None => dirs::cache_dir()
167                .unwrap_or_else(std::env::temp_dir)
168                .join("clickupc"),
169        };
170        Ok(Self {
171            profile: name,
172            token: env("CLICKUP_TOKEN").or(p.token),
173            workspace_id: env("CLICKUP_WORKSPACE_ID").or(p.workspace_id),
174            default_list: env("CLICKUP_DEFAULT_LIST").or(p.default_list),
175            timezone: env("CLICKUP_TIMEZONE").or(p.timezone),
176            timeout_secs: env_parse("CLICKUP_TIMEOUT_SECS")?
177                .or(p.timeout_secs)
178                .unwrap_or(DEFAULT_TIMEOUT_SECS),
179            default_task_limit: env_parse("CLICKUP_TASK_LIMIT")?.or(p.default_task_limit),
180            aliases: p.aliases,
181            base_url: env("CLICKUP_BASE_URL").unwrap_or_else(|| DEFAULT_BASE_URL.to_string()),
182            cache_dir,
183            config_path: ConfigFile::path()?,
184        })
185    }
186
187    /// Minimal config for tests and embedding: token + base URL, no file.
188    pub fn with_token(token: impl Into<String>, base_url: impl Into<String>) -> Self {
189        Self {
190            profile: DEFAULT_PROFILE.to_string(),
191            token: Some(token.into()),
192            workspace_id: None,
193            default_list: None,
194            timezone: None,
195            timeout_secs: DEFAULT_TIMEOUT_SECS,
196            default_task_limit: None,
197            aliases: BTreeMap::new(),
198            base_url: base_url.into(),
199            cache_dir: std::env::temp_dir().join("clickupc"),
200            config_path: PathBuf::new(),
201        }
202    }
203
204    pub fn token(&self) -> Result<&str> {
205        self.token.as_deref().ok_or_else(|| {
206            ClickUpError::Auth(
207                "no API token configured; run `clickupc auth login` or set CLICKUP_TOKEN".into(),
208            )
209        })
210    }
211
212    pub fn workspace_id(&self) -> Result<&str> {
213        self.workspace_id.as_deref().ok_or_else(|| {
214            ClickUpError::Config(
215                "no workspace selected; run `clickupc workspace use <name>` or set CLICKUP_WORKSPACE_ID"
216                    .into(),
217            )
218        })
219    }
220
221    /// `pk_12…AB` style preview that is safe to print.
222    pub fn masked_token(&self) -> Option<String> {
223        self.token.as_deref().map(mask_token)
224    }
225}
226
227pub fn mask_token(token: &str) -> String {
228    let chars: Vec<char> = token.chars().collect();
229    if chars.len() <= 8 {
230        return "***".into();
231    }
232    let head: String = chars[..5].iter().collect();
233    let tail: String = chars[chars.len() - 2..].iter().collect();
234    format!("{head}…{tail}")
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use serial_test::serial;
241
242    const VARS: &[&str] = &[
243        "CLICKUP_CONFIG_DIR",
244        "CLICKUP_TOKEN",
245        "CLICKUP_WORKSPACE_ID",
246        "CLICKUP_PROFILE",
247        "CLICKUP_DEFAULT_LIST",
248        "CLICKUP_TIMEOUT_SECS",
249        "CLICKUP_TASK_LIMIT",
250        "CLICKUP_BASE_URL",
251        "CLICKUP_TIMEZONE",
252    ];
253
254    fn isolated() -> tempfile::TempDir {
255        for v in VARS {
256            std::env::remove_var(v);
257        }
258        let dir = tempfile::tempdir().unwrap();
259        std::env::set_var("CLICKUP_CONFIG_DIR", dir.path());
260        dir
261    }
262
263    #[test]
264    #[serial]
265    fn save_load_round_trip() {
266        let _dir = isolated();
267        let mut file = ConfigFile {
268            current_profile: Some("work".into()),
269            ..Default::default()
270        };
271        let p = file.profile_mut("work");
272        p.token = Some("pk_abc".into());
273        p.workspace_id = Some("901".into());
274        p.aliases.insert("sprint".into(), "123".into());
275        let _path = file.save().unwrap();
276        assert_eq!(ConfigFile::load().unwrap(), file);
277
278        #[cfg(unix)]
279        {
280            let path = _path;
281            use std::os::unix::fs::PermissionsExt;
282            let mode = std::fs::metadata(path).unwrap().permissions().mode();
283            assert_eq!(mode & 0o777, 0o600);
284        }
285    }
286
287    #[test]
288    #[serial]
289    fn env_overrides_profile() {
290        let _dir = isolated();
291        let mut file = ConfigFile::default();
292        file.profile_mut("default").token = Some("pk_file".into());
293        file.profile_mut("default").workspace_id = Some("1".into());
294        file.save().unwrap();
295
296        std::env::set_var("CLICKUP_TOKEN", "pk_env");
297        std::env::set_var("CLICKUP_TIMEOUT_SECS", "5");
298        let cfg = ClickUpConfig::load().unwrap();
299        assert_eq!(cfg.token.as_deref(), Some("pk_env"));
300        assert_eq!(cfg.workspace_id.as_deref(), Some("1"));
301        assert_eq!(cfg.timeout_secs, 5);
302        assert_eq!(cfg.base_url, DEFAULT_BASE_URL);
303        isolated();
304    }
305
306    #[test]
307    #[serial]
308    fn profile_selection_priority() {
309        let _dir = isolated();
310        let mut file = ConfigFile {
311            current_profile: Some("a".into()),
312            ..Default::default()
313        };
314        file.profile_mut("a").workspace_id = Some("A".into());
315        file.profile_mut("b").workspace_id = Some("B".into());
316
317        assert_eq!(
318            ClickUpConfig::from_file(&file, None).unwrap().workspace_id,
319            Some("A".into())
320        );
321        std::env::set_var("CLICKUP_PROFILE", "b");
322        assert_eq!(
323            ClickUpConfig::from_file(&file, None).unwrap().workspace_id,
324            Some("B".into())
325        );
326        assert_eq!(
327            ClickUpConfig::from_file(&file, Some("a"))
328                .unwrap()
329                .workspace_id,
330            Some("A".into())
331        );
332        isolated();
333    }
334
335    #[test]
336    #[serial]
337    fn missing_token_is_auth_error() {
338        let _dir = isolated();
339        let cfg = ClickUpConfig::load().unwrap();
340        assert!(matches!(cfg.token(), Err(ClickUpError::Auth(_))));
341        assert!(matches!(cfg.workspace_id(), Err(ClickUpError::Config(_))));
342    }
343
344    #[test]
345    fn masks_token() {
346        assert_eq!(mask_token("pk_1234567890AB"), "pk_12…AB");
347        assert_eq!(mask_token("short"), "***");
348    }
349}