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