Skip to main content

clickupc_core/
task_ref.rs

1//! Parse a task reference: id, custom id (`DEV-123`), or task URL.
2
3use std::{fmt, str::FromStr};
4
5use crate::{client::Query, error::ClickUpError};
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum TaskRef {
9    Id(String),
10    Custom(String),
11}
12
13fn is_custom_id(s: &str) -> bool {
14    let Some((prefix, num)) = s.rsplit_once('-') else {
15        return false;
16    };
17    let mut chars = prefix.chars();
18    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
19        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
20        && !num.is_empty()
21        && num.chars().all(|c| c.is_ascii_digit())
22}
23
24fn is_task_id(s: &str) -> bool {
25    !s.is_empty() && s.len() <= 64 && s.chars().all(|c| c.is_ascii_alphanumeric())
26}
27
28fn classify(s: &str) -> Option<TaskRef> {
29    if is_custom_id(s) {
30        Some(TaskRef::Custom(s.to_string()))
31    } else if is_task_id(s) {
32        Some(TaskRef::Id(s.to_string()))
33    } else {
34        None
35    }
36}
37
38impl FromStr for TaskRef {
39    type Err = ClickUpError;
40
41    fn from_str(input: &str) -> Result<Self, Self::Err> {
42        let s = input.trim();
43        let s = s.strip_prefix('#').unwrap_or(s);
44        let err = || {
45            ClickUpError::Invalid(format!(
46                "'{input}' is not a task id, custom id (DEV-123) or ClickUp task URL"
47            ))
48        };
49
50        if s.starts_with("http://") || s.starts_with("https://") {
51            let url = url::Url::parse(s).map_err(|_| err())?;
52            if !url.host_str().is_some_and(|h| h.ends_with("clickup.com")) {
53                return Err(err());
54            }
55            let segs: Vec<&str> = url
56                .path_segments()
57                .map(|p| p.filter(|x| !x.is_empty()).collect())
58                .unwrap_or_default();
59            return match segs.as_slice() {
60                ["t", id] => classify(id).ok_or_else(err),
61                ["t", _team, id] => classify(id).ok_or_else(err),
62                _ => Err(err()),
63            };
64        }
65
66        classify(s).ok_or_else(err)
67    }
68}
69
70impl fmt::Display for TaskRef {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.write_str(self.path_id())
73    }
74}
75
76impl TaskRef {
77    pub fn path_id(&self) -> &str {
78        match self {
79            TaskRef::Id(s) | TaskRef::Custom(s) => s,
80        }
81    }
82
83    pub fn is_custom(&self) -> bool {
84        matches!(self, TaskRef::Custom(_))
85    }
86
87    /// `custom_task_ids=true&team_id=…` for custom ids, empty otherwise.
88    pub fn query(&self, workspace_id: &str) -> Query {
89        match self {
90            TaskRef::Custom(_) => Query::new()
91                .push("custom_task_ids", "true")
92                .push("team_id", workspace_id),
93            TaskRef::Id(_) => Query::new(),
94        }
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    fn p(s: &str) -> Result<TaskRef, ClickUpError> {
103        s.parse()
104    }
105
106    #[test]
107    fn plain_ids() {
108        assert_eq!(p("86b1abcde").unwrap(), TaskRef::Id("86b1abcde".into()));
109        assert_eq!(p("  9hz ").unwrap(), TaskRef::Id("9hz".into()));
110        assert_eq!(p("#86b1abcde").unwrap(), TaskRef::Id("86b1abcde".into()));
111    }
112
113    #[test]
114    fn custom_ids() {
115        assert_eq!(p("DEV-123").unwrap(), TaskRef::Custom("DEV-123".into()));
116        assert_eq!(p("eng2-42").unwrap(), TaskRef::Custom("eng2-42".into()));
117        assert_eq!(p("#DEV-1").unwrap(), TaskRef::Custom("DEV-1".into()));
118        assert_eq!(p("MY_TEAM-7").unwrap(), TaskRef::Custom("MY_TEAM-7".into()));
119    }
120
121    #[test]
122    fn urls() {
123        assert_eq!(
124            p("https://app.clickup.com/t/86b1abcde").unwrap(),
125            TaskRef::Id("86b1abcde".into())
126        );
127        assert_eq!(
128            p("https://app.clickup.com/t/9012345678/DEV-123").unwrap(),
129            TaskRef::Custom("DEV-123".into())
130        );
131        assert_eq!(
132            p("https://app.clickup.com/t/86b1abcde/").unwrap(),
133            TaskRef::Id("86b1abcde".into())
134        );
135        assert_eq!(
136            p("https://app.clickup.com/t/86b1abcde?comment=1").unwrap(),
137            TaskRef::Id("86b1abcde".into())
138        );
139    }
140
141    #[test]
142    fn garbage() {
143        for bad in [
144            "",
145            "#",
146            "-123",
147            "DEV-",
148            "1-2-3 x",
149            "has space",
150            "https://example.com/t/abc",
151            "https://app.clickup.com/v/l/abc",
152            "https://app.clickup.com/t/",
153            "abc/def",
154            "DEV-12a",
155        ] {
156            assert!(p(bad).is_err(), "{bad:?} should fail");
157        }
158    }
159
160    #[test]
161    fn query_only_for_custom() {
162        assert!(p("abc").unwrap().query("9").pairs().is_empty());
163        let q = p("DEV-1").unwrap().query("9");
164        assert_eq!(q.get("custom_task_ids"), Some("true"));
165        assert_eq!(q.get("team_id"), Some("9"));
166    }
167}