clin-rs 0.3.4-2

Encrypted terminal note-taking app
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Template management module
//!
//! This module handles user-defined note templates stored in <`storage_path>/templates`/
//! Templates are TOML files that define boilerplate content for new notes.

use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use chrono::Local;
use serde::{Deserialize, Serialize};

/// A note template
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Template {
    /// Display name for the template
    pub name: String,

    /// Title configuration
    #[serde(default)]
    pub title: TitleConfig,

    /// Content configuration
    pub content: ContentConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TitleConfig {
    /// Template string for the title (supports variables)
    #[serde(default)]
    pub template: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ContentConfig {
    /// Template string for the content (supports variables)
    #[serde(default)]
    pub template: String,
}

impl Template {
    /// Load a template from a TOML file
    pub fn load(path: &Path) -> Result<Self> {
        let content = fs::read_to_string(path).context("failed to read template file")?;
        let template: Template = toml::from_str(&content).context("failed to parse template")?;
        Ok(template)
    }

    /// Save the template to a TOML file
    pub fn save(&self, path: &Path) -> Result<()> {
        let content = toml::to_string_pretty(self).context("failed to serialize template")?;

        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).context("failed to create templates directory")?;
        }

        let mut file = fs::File::create(path).context("failed to create template file")?;
        file.write_all(content.as_bytes())
            .context("failed to write template file")?;

        Ok(())
    }

    /// Render the template with variable substitution
    pub fn render(&self) -> RenderedTemplate {
        let vars = TemplateVariables::now();

        let title = self.title.template.as_ref().map(|t| vars.substitute(t));

        let content = vars.substitute(&self.content.template);

        RenderedTemplate { title, content }
    }
}

/// Result of rendering a template
#[derive(Debug, Clone)]
pub struct RenderedTemplate {
    pub title: Option<String>,
    pub content: String,
}

/// Variables available for template substitution
#[derive(Debug, Clone)]
pub struct TemplateVariables {
    pub date: String,     // YYYY-MM-DD
    pub datetime: String, // YYYY-MM-DD HH:MM
    pub time: String,     // HH:MM
    pub weekday: String,  // Monday, Tuesday, etc.
    pub year: String,     // YYYY
    pub month: String,    // MM
    pub day: String,      // DD
}

impl TemplateVariables {
    /// Create variables for the current time
    pub fn now() -> Self {
        let now = Local::now();
        Self {
            date: now.format("%Y-%m-%d").to_string(),
            datetime: now.format("%Y-%m-%d %H:%M").to_string(),
            time: now.format("%H:%M").to_string(),
            weekday: now.format("%A").to_string(),
            year: now.format("%Y").to_string(),
            month: now.format("%m").to_string(),
            day: now.format("%d").to_string(),
        }
    }

    /// Substitute variables in a template string
    pub fn substitute(&self, template: &str) -> String {
        let mut result = String::with_capacity(template.len() + 50);
        let mut chars = template.chars().peekable();

        while let Some(c) = chars.next() {
            if c == '{' {
                let mut var_name = String::new();
                let mut closed = false;
                while let Some(&next) = chars.peek() {
                    if next == '}' {
                        chars.next();
                        closed = true;
                        break;
                    }
                    var_name.push(chars.next().unwrap());
                }

                if closed {
                    match var_name.as_str() {
                        "date" => result.push_str(&self.date),
                        "datetime" => result.push_str(&self.datetime),
                        "time" => result.push_str(&self.time),
                        "weekday" => result.push_str(&self.weekday),
                        "year" => result.push_str(&self.year),
                        "month" => result.push_str(&self.month),
                        "day" => result.push_str(&self.day),
                        _ => {
                            result.push('{');
                            result.push_str(&var_name);
                            result.push('}');
                        }
                    }
                } else {
                    result.push('{');
                    result.push_str(&var_name);
                }
            } else {
                result.push(c);
            }
        }
        result
    }
}

/// Template manager for CRUD operations
#[derive(Debug)]
pub struct TemplateManager {
    templates_dir: PathBuf,
}

impl TemplateManager {
    /// Create a new template manager for the given templates directory
    pub fn new(templates_dir: PathBuf) -> Self {
        Self { templates_dir }
    }

    /// Ensure the templates directory exists
    pub fn ensure_dir(&self) -> Result<()> {
        fs::create_dir_all(&self.templates_dir).context("failed to create templates directory")?;
        Ok(())
    }

    /// Get the path for a template by name
    pub fn template_path(&self, name: &str) -> PathBuf {
        let filename = sanitize_filename(name);
        self.templates_dir.join(format!("{filename}.toml"))
    }

    /// List all available templates
    pub fn list(&self) -> Result<Vec<TemplateSummary>> {
        let mut templates = Vec::new();

        if !self.templates_dir.exists() {
            return Ok(templates);
        }

        for entry in
            fs::read_dir(&self.templates_dir).context("failed to read templates directory")?
        {
            let entry = entry.context("failed to read template entry")?;
            let path = entry.path();

            if path.extension().and_then(|e| e.to_str()) != Some("toml") {
                continue;
            }

            let filename = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("unknown")
                .to_string();

            match Template::load(&path) {
                Ok(template) => {
                    templates.push(TemplateSummary {
                        filename,
                        name: template.name,
                    });
                }
                Err(_) => {
                    // Skip invalid templates
                    continue;
                }
            }
        }

        // Sort by name
        templates.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));

        Ok(templates)
    }

    /// Load a template by filename (without extension)
    pub fn load(&self, filename: &str) -> Result<Template> {
        let path = self.template_path(filename);
        Template::load(&path)
    }

    /// Save a template
    pub fn save(&self, filename: &str, template: &Template) -> Result<()> {
        self.ensure_dir()?;
        let path = self.template_path(filename);
        template.save(&path)
    }

    /// Load the default template if it exists
    pub fn load_default(&self) -> Option<Template> {
        self.load("default").ok()
    }

    /// Check if any templates exist
    pub fn has_templates(&self) -> bool {
        self.list().map(|t| !t.is_empty()).unwrap_or(false)
    }

    /// Create example templates if none exist
    pub fn create_examples(&self) -> Result<()> {
        if self.has_templates() {
            return Ok(());
        }

        self.ensure_dir()?;

        // Meeting notes template
        let meeting = Template {
            name: "Meeting Notes".to_string(),
            title: TitleConfig {
                template: Some("Meeting - {date}".to_string()),
            },
            content: ContentConfig {
                template: r"# Meeting Notes

**Date:** {date}
**Time:** {time}

## Attendees

- 

## Agenda

1. 

## Discussion

## Action Items

- [ ] 

## Next Meeting

"
                .to_string(),
            },
        };
        self.save("meeting", &meeting)?;

        // Todo list template
        let todo = Template {
            name: "Todo List".to_string(),
            title: TitleConfig {
                template: Some("Tasks - {date}".to_string()),
            },
            content: ContentConfig {
                template: r"# Tasks for {weekday}, {date}

## High Priority

- [ ] 

## Normal Priority

- [ ] 

## Low Priority

- [ ] 

## Notes

"
                .to_string(),
            },
        };
        self.save("todo", &todo)?;

        // Journal entry template
        let journal = Template {
            name: "Journal Entry".to_string(),
            title: TitleConfig {
                template: Some("Journal - {date}".to_string()),
            },
            content: ContentConfig {
                template: r"# {weekday}, {date}

## How I'm feeling



## What happened today



## Grateful for

1. 
2. 
3. 

## Tomorrow's focus

"
                .to_string(),
            },
        };
        self.save("journal", &journal)?;

        Ok(())
    }
}

/// Summary of a template for listing
#[derive(Debug, Clone)]
pub struct TemplateSummary {
    /// Filename without extension
    pub filename: String,
    /// Display name from the template
    pub name: String,
}

/// Sanitize a string for use as a filename
fn sanitize_filename(name: &str) -> String {
    let mut result = String::new();
    for c in name.chars() {
        if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
            result.push(c.to_ascii_lowercase());
        } else if c == ' ' {
            result.push('_');
        }
    }
    if result.is_empty() {
        result = "template".to_string();
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_template_variables_substitution() {
        let vars = TemplateVariables {
            date: "2026-03-28".to_string(),
            datetime: "2026-03-28 14:30".to_string(),
            time: "14:30".to_string(),
            weekday: "Saturday".to_string(),
            year: "2026".to_string(),
            month: "03".to_string(),
            day: "28".to_string(),
        };

        let template = "Meeting on {date} at {time}";
        let result = vars.substitute(template);
        assert_eq!(result, "Meeting on 2026-03-28 at 14:30");
    }

    #[test]
    fn test_sanitize_filename() {
        assert_eq!(sanitize_filename("Meeting Notes"), "meeting_notes");
        assert_eq!(sanitize_filename("todo-list"), "todo-list");
        assert_eq!(sanitize_filename("My Template!"), "my_template");
        assert_eq!(sanitize_filename(""), "template");
    }

    #[test]
    fn test_template_toml_roundtrip() {
        let template = Template {
            name: "Test".to_string(),
            title: TitleConfig {
                template: Some("Title - {date}".to_string()),
            },
            content: ContentConfig {
                template: "Content here".to_string(),
            },
        };

        let toml_str = toml::to_string_pretty(&template).unwrap();
        let parsed: Template = toml::from_str(&toml_str).unwrap();

        assert_eq!(template.name, parsed.name);
        assert_eq!(template.title.template, parsed.title.template);
        assert_eq!(template.content.template, parsed.content.template);
    }
}