Skip to main content

dsc/
utils.rs

1use anyhow::{Context, Result};
2use std::fs;
3use std::io::IsTerminal;
4use std::path::{Path, PathBuf};
5
6/// Trim trailing slashes from a base URL.
7pub fn normalize_baseurl(baseurl: &str) -> String {
8    baseurl.trim_end_matches('/').to_string()
9}
10
11/// Create a URL-safe slug from arbitrary input.
12pub fn slugify(input: &str) -> String {
13    let mut out = String::new();
14    let mut last_dash = false;
15    for ch in input.chars() {
16        if ch.is_ascii_alphanumeric() {
17            out.push(ch.to_ascii_lowercase());
18            last_dash = false;
19        } else if !last_dash {
20            out.push('-');
21            last_dash = true;
22        }
23    }
24    while out.starts_with('-') {
25        out.remove(0);
26    }
27    while out.ends_with('-') {
28        out.pop();
29    }
30    if out.is_empty() {
31        "untitled".to_string()
32    } else {
33        out
34    }
35}
36
37/// Ensure a directory exists.
38pub fn ensure_dir(path: &Path) -> Result<()> {
39    fs::create_dir_all(path).with_context(|| format!("creating {}", path.display()))?;
40    Ok(())
41}
42
43/// Resolve a topic path from a user-provided path and a topic title.
44pub fn resolve_topic_path(
45    provided: Option<&Path>,
46    title: &str,
47    default_dir: &Path,
48) -> Result<PathBuf> {
49    let filename = format!("{}.md", slugify(title));
50    match provided {
51        Some(path) if path.exists() && path.is_dir() => Ok(path.join(filename)),
52        Some(path) if path.extension().is_some() => Ok(path.to_path_buf()),
53        Some(path) => Ok(path.join(filename)),
54        None => Ok(default_dir.join(filename)),
55    }
56}
57
58/// Read a Markdown file.
59pub fn read_markdown(path: &Path) -> Result<String> {
60    let raw = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
61    Ok(raw)
62}
63
64/// Write a Markdown file, creating parent directories if needed.
65pub fn write_markdown(path: &Path, content: &str) -> Result<()> {
66    if let Some(parent) = path.parent() {
67        ensure_dir(parent)?;
68    }
69    fs::write(path, content).with_context(|| format!("writing {}", path.display()))?;
70    Ok(())
71}
72
73fn color_mode() -> &'static str {
74    match std::env::var("DSC_COLOR") {
75        Ok(value) => match value.trim().to_ascii_lowercase().as_str() {
76            "always" => "always",
77            "never" => "never",
78            _ => "auto",
79        },
80        Err(_) => "auto",
81    }
82}
83
84fn color_allowed_for_stdout() -> bool {
85    if std::env::var_os("NO_COLOR").is_some() {
86        return false;
87    }
88    match color_mode() {
89        "always" => true,
90        "never" => false,
91        _ => std::io::stdout().is_terminal(),
92    }
93}
94
95fn discourse_color_code(key: &str) -> u8 {
96    const COLORS: [u8; 12] = [31, 32, 33, 34, 35, 36, 91, 92, 93, 94, 95, 96];
97    let hash = key.bytes().fold(0usize, |acc, b| {
98        acc.wrapping_mul(31).wrapping_add(b as usize)
99    });
100    COLORS[hash % COLORS.len()]
101}
102
103pub fn color_discourse_label(label: &str, key: &str) -> String {
104    if !color_allowed_for_stdout() {
105        return label.to_string();
106    }
107    let code = discourse_color_code(key);
108    format!("\x1b[1;{}m{}\x1b[0m", code, label)
109}
110
111/// Parse a `--since`-style value. Accepts either a relative duration
112/// (`7d`, `24h`, `30m`, `1w`, `90s`) or an ISO-8601 absolute timestamp
113/// (`2026-04-01`, `2026-04-01T12:00:00Z`). Returns the resulting cutoff
114/// instant (now - duration, or the ISO value itself).
115pub fn parse_since_cutoff(input: &str) -> anyhow::Result<chrono::DateTime<chrono::Utc>> {
116    use anyhow::anyhow;
117    let trimmed = input.trim();
118    if trimmed.is_empty() {
119        return Err(anyhow!("empty --since value"));
120    }
121
122    if let Some(duration) = parse_relative_duration(trimmed) {
123        return Ok(chrono::Utc::now() - duration);
124    }
125
126    // Try RFC3339 (full timestamp).
127    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(trimmed) {
128        return Ok(dt.with_timezone(&chrono::Utc));
129    }
130    // Try date-only — treat as midnight UTC.
131    if let Ok(d) = chrono::NaiveDate::parse_from_str(trimmed, "%Y-%m-%d") {
132        return Ok(
133            chrono::NaiveDateTime::new(d, chrono::NaiveTime::from_hms_opt(0, 0, 0).unwrap())
134                .and_utc(),
135        );
136    }
137
138    Err(anyhow!(
139        "unrecognised --since value: {:?} (expected e.g. `7d`, `24h`, `30m`, `1w`, or an ISO-8601 timestamp)",
140        input
141    ))
142}
143
144/// Parse a relative duration like `7d`, `24h`, `30m`, `1w`, `90s`, `1y`.
145/// `y` is treated as 365 days (good enough for analytics windows; for
146/// precise calendar arithmetic pass an ISO-8601 timestamp instead).
147/// Months are deliberately not supported because their length depends
148/// on the calendar.
149pub fn parse_relative_duration(input: &str) -> Option<chrono::Duration> {
150    let s = input.trim();
151    if s.len() < 2 {
152        return None;
153    }
154    let (digits, unit) = s.split_at(s.len() - 1);
155    let n: i64 = digits.parse().ok()?;
156    match unit {
157        "s" => Some(chrono::Duration::seconds(n)),
158        "m" => Some(chrono::Duration::minutes(n)),
159        "h" => Some(chrono::Duration::hours(n)),
160        "d" => Some(chrono::Duration::days(n)),
161        "w" => Some(chrono::Duration::weeks(n)),
162        "y" => Some(chrono::Duration::days(n * 365)),
163        _ => None,
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn slugify_simple_ascii() {
173        assert_eq!(slugify("Hello World"), "hello-world");
174    }
175
176    #[test]
177    fn slugify_collapses_runs_of_non_alnum() {
178        assert_eq!(slugify("a   b___c!!!d"), "a-b-c-d");
179    }
180
181    #[test]
182    fn slugify_trims_leading_and_trailing_dashes() {
183        assert_eq!(slugify("   hello   "), "hello");
184        assert_eq!(slugify("!!!foo!!!"), "foo");
185    }
186
187    #[test]
188    fn slugify_empty_input_returns_untitled() {
189        assert_eq!(slugify(""), "untitled");
190        assert_eq!(slugify("   "), "untitled");
191        assert_eq!(slugify("!!!"), "untitled");
192    }
193
194    #[test]
195    fn slugify_preserves_numbers() {
196        assert_eq!(slugify("Topic 42 - intro"), "topic-42-intro");
197    }
198
199    #[test]
200    fn slugify_lowercases() {
201        assert_eq!(slugify("ABCxyz"), "abcxyz");
202    }
203
204    #[test]
205    fn normalize_baseurl_strips_trailing_slashes() {
206        assert_eq!(normalize_baseurl("https://example.com/"), "https://example.com");
207        assert_eq!(normalize_baseurl("https://example.com///"), "https://example.com");
208        assert_eq!(normalize_baseurl("https://example.com"), "https://example.com");
209    }
210
211    #[test]
212    fn normalize_baseurl_preserves_no_trailing() {
213        assert_eq!(normalize_baseurl(""), "");
214    }
215
216    #[test]
217    fn resolve_topic_path_uses_title_when_no_path_given() {
218        let default_dir = Path::new("/tmp/dsc-test");
219        let out = resolve_topic_path(None, "Hello World", default_dir).unwrap();
220        assert_eq!(out, default_dir.join("hello-world.md"));
221    }
222
223    #[test]
224    fn resolve_topic_path_uses_given_path_with_extension() {
225        let default_dir = Path::new("/tmp/dsc-test");
226        let explicit = Path::new("/tmp/custom.md");
227        let out = resolve_topic_path(Some(explicit), "Ignored", default_dir).unwrap();
228        assert_eq!(out, explicit);
229    }
230
231    #[test]
232    fn parse_relative_duration_common_units() {
233        assert_eq!(
234            parse_relative_duration("7d"),
235            Some(chrono::Duration::days(7))
236        );
237        assert_eq!(
238            parse_relative_duration("24h"),
239            Some(chrono::Duration::hours(24))
240        );
241        assert_eq!(
242            parse_relative_duration("30m"),
243            Some(chrono::Duration::minutes(30))
244        );
245        assert_eq!(
246            parse_relative_duration("1w"),
247            Some(chrono::Duration::weeks(1))
248        );
249        assert_eq!(
250            parse_relative_duration("90s"),
251            Some(chrono::Duration::seconds(90))
252        );
253    }
254
255    #[test]
256    fn parse_relative_duration_rejects_nonsense() {
257        assert!(parse_relative_duration("").is_none());
258        assert!(parse_relative_duration("d").is_none());
259        assert!(parse_relative_duration("7x").is_none());
260        assert!(parse_relative_duration("abc").is_none());
261        assert!(parse_relative_duration("3M").is_none()); // months deliberately unsupported
262    }
263
264    #[test]
265    fn parse_relative_duration_accepts_years_as_365d() {
266        assert_eq!(
267            parse_relative_duration("1y"),
268            Some(chrono::Duration::days(365))
269        );
270        assert_eq!(
271            parse_relative_duration("2y"),
272            Some(chrono::Duration::days(730))
273        );
274    }
275
276    #[test]
277    fn parse_since_cutoff_iso_date() {
278        let cutoff = parse_since_cutoff("2026-01-01").unwrap();
279        assert_eq!(cutoff.to_rfc3339(), "2026-01-01T00:00:00+00:00");
280    }
281
282    #[test]
283    fn parse_since_cutoff_iso_timestamp() {
284        let cutoff = parse_since_cutoff("2026-04-15T12:30:00Z").unwrap();
285        assert_eq!(cutoff.to_rfc3339(), "2026-04-15T12:30:00+00:00");
286    }
287
288    #[test]
289    fn parse_since_cutoff_relative_is_in_the_past() {
290        let now = chrono::Utc::now();
291        let cutoff = parse_since_cutoff("7d").unwrap();
292        let diff = now - cutoff;
293        // Should be very close to 7 days (within a second).
294        assert!(
295            (diff - chrono::Duration::days(7)).num_seconds().abs() < 2,
296            "expected ~7 day delta, got {}",
297            diff
298        );
299    }
300
301    #[test]
302    fn parse_since_cutoff_rejects_garbage() {
303        assert!(parse_since_cutoff("not a date").is_err());
304        assert!(parse_since_cutoff("").is_err());
305    }
306}
307