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    /// Workspace id → token, for accounts whose tokens each reach a single
39    /// workspace. `token` is the fallback for workspaces not listed here.
40    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
41    pub tokens: BTreeMap<String, String>,
42}
43
44impl Profile {
45    /// Store `token` for `workspace_id` and make it the default. A legacy
46    /// single token is kept under its own workspace so it keeps working.
47    pub fn add_token(&mut self, workspace_id: &str, token: String) {
48        if let (Some(old), Some(ws)) = (&self.token, &self.workspace_id) {
49            self.tokens.entry(ws.clone()).or_insert_with(|| old.clone());
50        }
51        self.tokens.insert(workspace_id.to_string(), token.clone());
52        self.token = Some(token);
53        self.workspace_id = Some(workspace_id.to_string());
54    }
55}
56
57fn env(key: &str) -> Option<String> {
58    std::env::var(key)
59        .ok()
60        .map(|v| v.trim().to_string())
61        .filter(|v| !v.is_empty())
62}
63
64fn env_parse<T: std::str::FromStr>(key: &str) -> Result<Option<T>> {
65    match env(key) {
66        None => Ok(None),
67        Some(v) => v
68            .parse()
69            .map(Some)
70            .map_err(|_| ClickUpError::Config(format!("{key} has an invalid value '{v}'"))),
71    }
72}
73
74impl ConfigFile {
75    /// `$CLICKUP_CONFIG_DIR/config.toml`, else `<config dir>/clickupc/config.toml`.
76    pub fn path() -> Result<PathBuf> {
77        let dir = match env("CLICKUP_CONFIG_DIR") {
78            Some(dir) => PathBuf::from(dir),
79            None => dirs::config_dir()
80                .ok_or_else(|| ClickUpError::Config("cannot locate a config directory".into()))?
81                .join("clickupc"),
82        };
83        Ok(dir.join("config.toml"))
84    }
85
86    pub fn load() -> Result<Self> {
87        let path = Self::path()?;
88        if !path.exists() {
89            return Ok(Self::default());
90        }
91        warn_if_world_readable(&path);
92        let text = std::fs::read_to_string(&path)?;
93        toml::from_str(&text).map_err(|e| ClickUpError::Config(format!("{}: {e}", path.display())))
94    }
95
96    pub fn save(&self) -> Result<PathBuf> {
97        let path = Self::path()?;
98        if let Some(dir) = path.parent() {
99            std::fs::create_dir_all(dir)?;
100        }
101        let text = toml::to_string_pretty(self).map_err(|e| ClickUpError::Config(e.to_string()))?;
102        std::fs::write(&path, text)?;
103        restrict_permissions(&path)?;
104        Ok(path)
105    }
106
107    /// `CLICKUP_PROFILE` > `current_profile` > `default`.
108    pub fn selected_profile_name(&self) -> String {
109        env("CLICKUP_PROFILE")
110            .or_else(|| self.current_profile.clone())
111            .unwrap_or_else(|| DEFAULT_PROFILE.to_string())
112    }
113
114    pub fn profile_mut(&mut self, name: &str) -> &mut Profile {
115        self.profiles.entry(name.to_string()).or_default()
116    }
117}
118
119/// `"Acme Corp (EU)"` → `"acme-corp-eu"`, for suggesting profile names.
120pub fn profile_slug(name: &str) -> String {
121    let mut out = String::new();
122    for c in name.trim().chars() {
123        if c.is_ascii_alphanumeric() {
124            out.push(c.to_ascii_lowercase());
125        } else if !out.ends_with('-') && !out.is_empty() {
126            out.push('-');
127        }
128    }
129    let out = out.trim_end_matches('-').to_string();
130    if out.is_empty() {
131        DEFAULT_PROFILE.to_string()
132    } else {
133        out
134    }
135}
136
137#[cfg(unix)]
138fn restrict_permissions(path: &std::path::Path) -> Result<()> {
139    use std::os::unix::fs::PermissionsExt;
140    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
141    Ok(())
142}
143
144#[cfg(not(unix))]
145fn restrict_permissions(_path: &std::path::Path) -> Result<()> {
146    Ok(())
147}
148
149#[cfg(unix)]
150fn warn_if_world_readable(path: &std::path::Path) {
151    use std::os::unix::fs::PermissionsExt;
152    if let Ok(meta) = std::fs::metadata(path) {
153        if meta.permissions().mode() & 0o077 != 0 {
154            tracing::warn!(
155                "{} is readable by other users; run `chmod 600` on it",
156                path.display()
157            );
158        }
159    }
160}
161
162#[cfg(not(unix))]
163fn warn_if_world_readable(_path: &std::path::Path) {}
164
165/// Effective settings after merging the selected profile with env overrides.
166#[derive(Debug, Clone)]
167pub struct ClickUpConfig {
168    pub profile: String,
169    pub token: Option<String>,
170    pub workspace_id: Option<String>,
171    pub default_list: Option<String>,
172    pub timezone: Option<String>,
173    pub timeout_secs: u64,
174    pub default_task_limit: Option<usize>,
175    pub aliases: BTreeMap<String, String>,
176    /// Per-workspace tokens of the profile; empty when `CLICKUP_TOKEN` is set.
177    pub tokens: BTreeMap<String, String>,
178    pub base_url: String,
179    pub cache_dir: PathBuf,
180    pub config_path: PathBuf,
181}
182
183impl ClickUpConfig {
184    /// Load using the profile chosen by env / `current_profile`.
185    pub fn load() -> Result<Self> {
186        Self::load_profile(None)
187    }
188
189    /// Load an explicit profile (e.g. `--profile work`), falling back to the
190    /// usual selection when `None`.
191    pub fn load_profile(profile: Option<&str>) -> Result<Self> {
192        let file = ConfigFile::load()?;
193        Self::from_file(&file, profile)
194    }
195
196    pub fn from_file(file: &ConfigFile, profile: Option<&str>) -> Result<Self> {
197        let name = profile
198            .map(str::to_string)
199            .unwrap_or_else(|| file.selected_profile_name());
200        let p = file.profiles.get(&name).cloned().unwrap_or_default();
201        let cache_dir = match env("CLICKUP_CACHE_DIR") {
202            Some(dir) => PathBuf::from(dir),
203            None => dirs::cache_dir()
204                .unwrap_or_else(std::env::temp_dir)
205                .join("clickupc"),
206        };
207        let env_token = env("CLICKUP_TOKEN");
208        let tokens = if env_token.is_some() {
209            BTreeMap::new()
210        } else {
211            p.tokens
212        };
213        let workspace_id = env("CLICKUP_WORKSPACE_ID").or(p.workspace_id);
214        let token = env_token
215            .or_else(|| workspace_id.as_ref().and_then(|w| tokens.get(w).cloned()))
216            .or(p.token);
217        Ok(Self {
218            profile: name,
219            token,
220            workspace_id,
221            tokens,
222            default_list: env("CLICKUP_DEFAULT_LIST").or(p.default_list),
223            timezone: env("CLICKUP_TIMEZONE").or(p.timezone),
224            timeout_secs: env_parse("CLICKUP_TIMEOUT_SECS")?
225                .or(p.timeout_secs)
226                .unwrap_or(DEFAULT_TIMEOUT_SECS),
227            default_task_limit: env_parse("CLICKUP_TASK_LIMIT")?.or(p.default_task_limit),
228            aliases: p.aliases,
229            base_url: env("CLICKUP_BASE_URL").unwrap_or_else(|| DEFAULT_BASE_URL.to_string()),
230            cache_dir,
231            config_path: ConfigFile::path()?,
232        })
233    }
234
235    /// Minimal config for tests and embedding: token + base URL, no file.
236    pub fn with_token(token: impl Into<String>, base_url: impl Into<String>) -> Self {
237        Self {
238            profile: DEFAULT_PROFILE.to_string(),
239            token: Some(token.into()),
240            workspace_id: None,
241            default_list: None,
242            timezone: None,
243            timeout_secs: DEFAULT_TIMEOUT_SECS,
244            default_task_limit: None,
245            aliases: BTreeMap::new(),
246            tokens: BTreeMap::new(),
247            base_url: base_url.into(),
248            cache_dir: std::env::temp_dir().join("clickupc"),
249            config_path: PathBuf::new(),
250        }
251    }
252
253    pub fn token(&self) -> Result<&str> {
254        self.token.as_deref().ok_or_else(|| {
255            ClickUpError::Auth(
256                "no API token configured; run `clickupc auth login` or set CLICKUP_TOKEN".into(),
257            )
258        })
259    }
260
261    pub fn workspace_id(&self) -> Result<&str> {
262        self.workspace_id.as_deref().ok_or_else(|| {
263            ClickUpError::Config(
264                "no workspace selected; run `clickupc workspace use <name>` or set CLICKUP_WORKSPACE_ID"
265                    .into(),
266            )
267        })
268    }
269
270    /// Switch to `workspace_id`, and to its own token when the profile has one.
271    pub fn set_workspace(&mut self, workspace_id: impl Into<String>) {
272        let id = workspace_id.into();
273        if let Some(t) = self.tokens.get(&id) {
274            self.token = Some(t.clone());
275        }
276        self.workspace_id = Some(id);
277    }
278
279    /// Every distinct token of the profile, the active one first.
280    pub fn all_tokens(&self) -> Vec<String> {
281        let mut out: Vec<String> = self.token.iter().cloned().collect();
282        for t in self.tokens.values() {
283            if !out.contains(t) {
284                out.push(t.clone());
285            }
286        }
287        out
288    }
289
290    /// `pk_12…AB` style preview that is safe to print.
291    pub fn masked_token(&self) -> Option<String> {
292        self.token.as_deref().map(mask_token)
293    }
294}
295
296pub fn mask_token(token: &str) -> String {
297    let chars: Vec<char> = token.chars().collect();
298    if chars.len() <= 8 {
299        return "***".into();
300    }
301    let head: String = chars[..5].iter().collect();
302    let tail: String = chars[chars.len() - 2..].iter().collect();
303    format!("{head}…{tail}")
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use serial_test::serial;
310
311    const VARS: &[&str] = &[
312        "CLICKUP_CONFIG_DIR",
313        "CLICKUP_TOKEN",
314        "CLICKUP_WORKSPACE_ID",
315        "CLICKUP_PROFILE",
316        "CLICKUP_DEFAULT_LIST",
317        "CLICKUP_TIMEOUT_SECS",
318        "CLICKUP_TASK_LIMIT",
319        "CLICKUP_BASE_URL",
320        "CLICKUP_TIMEZONE",
321    ];
322
323    fn isolated() -> tempfile::TempDir {
324        for v in VARS {
325            std::env::remove_var(v);
326        }
327        let dir = tempfile::tempdir().unwrap();
328        std::env::set_var("CLICKUP_CONFIG_DIR", dir.path());
329        dir
330    }
331
332    #[test]
333    #[serial]
334    fn save_load_round_trip() {
335        let _dir = isolated();
336        let mut file = ConfigFile {
337            current_profile: Some("work".into()),
338            ..Default::default()
339        };
340        let p = file.profile_mut("work");
341        p.token = Some("pk_abc".into());
342        p.workspace_id = Some("901".into());
343        p.aliases.insert("sprint".into(), "123".into());
344        let _path = file.save().unwrap();
345        assert_eq!(ConfigFile::load().unwrap(), file);
346
347        #[cfg(unix)]
348        {
349            let path = _path;
350            use std::os::unix::fs::PermissionsExt;
351            let mode = std::fs::metadata(path).unwrap().permissions().mode();
352            assert_eq!(mode & 0o777, 0o600);
353        }
354    }
355
356    #[test]
357    #[serial]
358    fn env_overrides_profile() {
359        let _dir = isolated();
360        let mut file = ConfigFile::default();
361        file.profile_mut("default").token = Some("pk_file".into());
362        file.profile_mut("default").workspace_id = Some("1".into());
363        file.save().unwrap();
364
365        std::env::set_var("CLICKUP_TOKEN", "pk_env");
366        std::env::set_var("CLICKUP_TIMEOUT_SECS", "5");
367        let cfg = ClickUpConfig::load().unwrap();
368        assert_eq!(cfg.token.as_deref(), Some("pk_env"));
369        assert_eq!(cfg.workspace_id.as_deref(), Some("1"));
370        assert_eq!(cfg.timeout_secs, 5);
371        assert_eq!(cfg.base_url, DEFAULT_BASE_URL);
372        isolated();
373    }
374
375    #[test]
376    #[serial]
377    fn profile_selection_priority() {
378        let _dir = isolated();
379        let mut file = ConfigFile {
380            current_profile: Some("a".into()),
381            ..Default::default()
382        };
383        file.profile_mut("a").workspace_id = Some("A".into());
384        file.profile_mut("b").workspace_id = Some("B".into());
385
386        assert_eq!(
387            ClickUpConfig::from_file(&file, None).unwrap().workspace_id,
388            Some("A".into())
389        );
390        std::env::set_var("CLICKUP_PROFILE", "b");
391        assert_eq!(
392            ClickUpConfig::from_file(&file, None).unwrap().workspace_id,
393            Some("B".into())
394        );
395        assert_eq!(
396            ClickUpConfig::from_file(&file, Some("a"))
397                .unwrap()
398                .workspace_id,
399            Some("A".into())
400        );
401        isolated();
402    }
403
404    #[test]
405    #[serial]
406    fn missing_token_is_auth_error() {
407        let _dir = isolated();
408        let cfg = ClickUpConfig::load().unwrap();
409        assert!(matches!(cfg.token(), Err(ClickUpError::Auth(_))));
410        assert!(matches!(cfg.workspace_id(), Err(ClickUpError::Config(_))));
411    }
412
413    #[test]
414    #[serial]
415    fn per_workspace_tokens() {
416        let _dir = isolated();
417        let mut file = ConfigFile::default();
418        let p = file.profile_mut("default");
419        p.token = Some("pk_one".into());
420        p.workspace_id = Some("1".into());
421        p.add_token("2", "pk_two".into());
422        assert_eq!(p.tokens.get("1").map(String::as_str), Some("pk_one"));
423        assert_eq!(p.token.as_deref(), Some("pk_two"));
424
425        let mut cfg = ClickUpConfig::from_file(&file, None).unwrap();
426        assert_eq!(cfg.token.as_deref(), Some("pk_two"));
427        assert_eq!(cfg.all_tokens(), vec!["pk_two", "pk_one"]);
428        cfg.set_workspace("1");
429        assert_eq!(cfg.token.as_deref(), Some("pk_one"));
430        cfg.set_workspace("3");
431        assert_eq!(cfg.token.as_deref(), Some("pk_one"));
432
433        std::env::set_var("CLICKUP_TOKEN", "pk_env");
434        let mut cfg = ClickUpConfig::from_file(&file, None).unwrap();
435        cfg.set_workspace("1");
436        assert_eq!(cfg.token.as_deref(), Some("pk_env"));
437        isolated();
438    }
439
440    #[test]
441    fn slugs() {
442        assert_eq!(profile_slug("Acme Corp (EU)"), "acme-corp-eu");
443        assert_eq!(profile_slug("  Side Project  "), "side-project");
444        assert_eq!(profile_slug("!!!"), "default");
445    }
446
447    #[test]
448    fn masks_token() {
449        assert_eq!(mask_token("pk_1234567890AB"), "pk_12…AB");
450        assert_eq!(mask_token("short"), "***");
451    }
452}