mps-rs 1.1.0

MPS — plain-text personal productivity CLI (Rust)
Documentation
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
427
428
429
430
431
432
433
434
435
436
437
438
//! File-system layer — discovers, reads, and writes `.mps` files.
//!
//! The CLI delegates all I/O to [`Store`]; no direct file operations happen
//! in command handlers.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use chrono::NaiveDate;
use indexmap::IndexMap;
use crate::constants::{mps_file_name_regexp, new_file_name, MPS_EXT};
use crate::elements::Element;
use crate::error::MpsError;
use crate::parser;
use crate::ref_resolver::RefResolver;

#[allow(dead_code)]
pub struct SearchResult {
    pub element:  Element,
    pub file:     PathBuf,
    pub date_str: String,  // "YYYYMMDD"
}

pub struct Store {
    storage_dir: PathBuf,
}

impl Store {
    pub fn new(storage_dir: impl Into<PathBuf>) -> Self {
        Store { storage_dir: storage_dir.into() }
    }

    /// First .mps file matching date, or None.
    pub fn find_file(&self, date: NaiveDate) -> Option<PathBuf> {
        self.find_files(date).into_iter().next()
    }

    /// All .mps files matching date (handles multiple files per day).
    pub fn find_files(&self, date: NaiveDate) -> Vec<PathBuf> {
        let prefix = date.format("%Y%m%d").to_string();
        let re = mps_file_name_regexp();
        let mut files: Vec<PathBuf> = std::fs::read_dir(&self.storage_dir)
            .map(|rd| {
                rd.filter_map(|e| e.ok())
                    .map(|e| e.path())
                    .filter(|p| {
                        p.extension().and_then(|e| e.to_str()) == Some(MPS_EXT)
                            && p.file_name()
                                .and_then(|n| n.to_str())
                                .map(|n| re.is_match(n) && n.starts_with(&prefix))
                                .unwrap_or(false)
                    })
                    .collect()
            })
            .unwrap_or_default();
        files.sort();
        files
    }

    /// Existing file for date, or a generated new path (file not yet created).
    pub fn find_or_create_path(&self, date: NaiveDate) -> PathBuf {
        self.find_file(date)
            .unwrap_or_else(|| self.storage_dir.join(new_file_name(date)))
    }

    /// Parsed elements for date. Returns empty map if no file exists.
    pub fn parse_date(&self, date: NaiveDate) -> Result<IndexMap<String, Element>, MpsError> {
        match self.find_file(date) {
            None    => Ok(IndexMap::new()),
            Some(p) => parser::parse_file(&p),
        }
    }

    /// Append a new element to date's file (creates file if absent).
    pub fn append(
        &self,
        kind:  &str,
        body:  &str,
        tags:  &[String],
        attrs: &[(&str, &str)],
        date:  NaiveDate,
    ) -> Result<PathBuf, MpsError> {
        let mut parts: Vec<String> = attrs.iter().map(|(k, v)| format!("{}: {}", k, v)).collect();
        parts.extend(tags.iter().cloned());
        let args_str = parts.join(", ");

        let path = self.find_or_create_path(date);
        let chunk = format!("\n@{}[{}]{{\n  {}\n}}\n", kind, args_str, body);
        use std::io::Write;
        let mut f = std::fs::OpenOptions::new().create(true).append(true).open(&path)?;
        f.write_all(chunk.as_bytes())?;
        Ok(path)
    }

    /// All .mps files in storage_dir, sorted by filename (chronological).
    pub fn all_files(&self) -> Result<Vec<PathBuf>, MpsError> {
        let re = mps_file_name_regexp();
        let mut files: Vec<PathBuf> = std::fs::read_dir(&self.storage_dir)?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| {
                p.extension().and_then(|e| e.to_str()) == Some(MPS_EXT)
                    && p.file_name()
                        .and_then(|n| n.to_str())
                        .map(|n| re.is_match(n))
                        .unwrap_or(false)
            })
            .collect();
        files.sort();
        Ok(files)
    }

    /// Files whose date-stamp >= since_date.
    pub fn files_since(&self, since_date: NaiveDate) -> Result<Vec<PathBuf>, MpsError> {
        let since_str = since_date.format("%Y%m%d").to_string();
        let files = self.all_files()?
            .into_iter()
            .filter(|p| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .map(|n| &n[..8] >= since_str.as_str())
                    .unwrap_or(false)
            })
            .collect();
        Ok(files)
    }

    /// Unique sorted dates for which .mps files exist.
    pub fn all_file_dates(&self) -> Result<Vec<NaiveDate>, MpsError> {
        let mut seen = std::collections::HashSet::new();
        let mut dates: Vec<NaiveDate> = self.all_files()?
            .iter()
            .filter_map(|p| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .and_then(|n| NaiveDate::parse_from_str(&n[..8], "%Y%m%d").ok())
            })
            .filter(|d| seen.insert(*d))
            .collect();
        dates.sort();
        Ok(dates)
    }

    /// Rewrite an element's typed attributes in-place, atomically.
    ///
    /// `ref_str` may be an epoch ref (e.g. "20260428.1") or a human ref (e.g. "task-1").
    /// Human refs are resolved against `date` (defaults to today in the caller).
    /// `new_attrs` maps attribute name → new value (e.g. {"status" → "done"}).
    ///
    /// Returns `true` on success, `false` if ref not found or file unchanged.
    pub fn rewrite_element(
        &self,
        ref_str:   &str,
        new_attrs: &HashMap<String, String>,
        date:      NaiveDate,
    ) -> Result<bool, MpsError> {
        let (epoch_ref, path) = self.resolve_ref_to_path(ref_str, date)?;
        let (epoch_ref, path) = match (epoch_ref, path) {
            (Some(e), Some(p)) => (e, p),
            _ => return Ok(false),
        };

        let elements = parser::parse_file(&path)?;
        let el = match elements.get(&epoch_ref) {
            Some(e) => e.clone(),
            None    => return Ok(false),
        };
        if el.is_unknown() { return Ok(false); }

        self.rewrite_element_in_file(&path, &el, &epoch_ref, &elements, new_attrs)
    }

    // ── private helpers ──────────────────────────────────────────────────────

    /// Resolve a ref string to (epoch_ref, file_path).
    /// Epoch refs (YYYYMMDD.n...) encode their own date; human refs need the given date.
    fn resolve_ref_to_path(
        &self,
        ref_str: &str,
        date:    NaiveDate,
    ) -> Result<(Option<String>, Option<PathBuf>), MpsError> {
        // Epoch ref: 8 ASCII digits followed by '.' then a digit
        let is_epoch = ref_str.len() >= 10
            && ref_str[..8].chars().all(|c| c.is_ascii_digit())
            && ref_str.chars().nth(8) == Some('.')
            && ref_str.chars().nth(9).map(|c| c.is_ascii_digit()).unwrap_or(false);

        if is_epoch {
            let d = NaiveDate::parse_from_str(&ref_str[..8], "%Y%m%d")
                .map_err(|_| MpsError::DateParseError(ref_str[..8].to_string()))?;
            let path = self.find_file(d);
            Ok((Some(ref_str.to_string()), path))
        } else {
            let path = match self.find_file(date) {
                Some(p) => p,
                None    => return Ok((None, None)),
            };
            let elements   = parser::parse_file(&path)?;
            let resolver   = RefResolver::new(&elements);
            let epoch_ref  = resolver.to_epoch(ref_str).map(|s| s.to_string());
            Ok((epoch_ref, Some(path)))
        }
    }

    /// Rewrite the `@type[args]{` opening line in-place and save atomically.
    ///
    /// `epoch_ref` and `all_elements` are used to determine WHICH occurrence of the
    /// opening pattern to replace when multiple elements share identical raw_args.
    /// Elements are sorted by their numeric ref-path parts (same order as RefResolver),
    /// which mirrors the order openers appear in the file. This makes the N-th
    /// occurrence of the pattern map to the correct element even with duplicate args.
    fn rewrite_element_in_file(
        &self,
        path:         &Path,
        el:           &Element,
        epoch_ref:    &str,
        all_elements: &IndexMap<String, Element>,
        new_attrs:    &HashMap<String, String>,
    ) -> Result<bool, MpsError> {
        let content   = std::fs::read_to_string(path)?;
        let type_name = el.sign();
        let raw       = el.raw_args();

        // Merge new attrs over existing typed attrs (preserve order; append new keys at end).
        let mut merged: Vec<(String, String)> = el.typed_attrs();
        for (k, v) in new_attrs {
            if let Some(pos) = merged.iter().position(|(ek, _)| ek == k) {
                merged[pos].1 = v.clone();
            } else {
                merged.push((k.clone(), v.clone()));
            }
        }

        // Build new args string: named attrs first, then tags.
        let attr_parts: Vec<String> = merged.iter()
            .filter(|(_, v)| !v.is_empty())
            .map(|(k, v)| format!("{}: {}", k, v))
            .collect();
        let new_args_str: String = attr_parts.into_iter()
            .chain(el.tags().iter().cloned())
            .collect::<Vec<_>>()
            .join(", ");

        // Build a regex matching the current element opening line.
        let esc_type = regex::escape(type_name);
        let old_pat = if raw.is_empty() {
            format!(r"@{}(?:\[\])?\s*\{{", esc_type)
        } else {
            format!(r"@{}\[{}\]\s*\{{", esc_type, regex::escape(raw))
        };

        let re = regex::Regex::new(&old_pat)
            .map_err(|e| MpsError::ParseError { file: path.display().to_string(), msg: e.to_string() })?;

        // Determine which occurrence to replace.
        // Sort all elements by their numeric ref-path parts — this order mirrors the
        // order in which openers appear in the file (depth-first, opening order).
        // Count how many elements with the same (sign, raw_args) appear before our
        // target in that sorted order; skip synthetic root (keys without any dot).
        let mut sorted_keys: Vec<&String> = all_elements.keys().collect();
        sorted_keys.sort_by(|a, b| {
            let ap: Vec<u64> = a.split('.').filter_map(|s| s.parse().ok()).collect();
            let bp: Vec<u64> = b.split('.').filter_map(|s| s.parse().ok()).collect();
            ap.cmp(&bp)
        });

        let mut occurrence: usize = 0;
        for key in &sorted_keys {
            if *key == epoch_ref { break; }
            // Skip synthetic root (no dot → single-segment key like "20260302")
            if !key.contains('.') { continue; }
            if let Some(other) = all_elements.get(*key) {
                if other.sign() == type_name && other.raw_args() == raw {
                    occurrence += 1;
                }
            }
        }

        // Replace specifically the (occurrence)-th match (0-indexed).
        let new_open = format!("@{}[{}]{{", type_name, new_args_str);
        let mut match_n = 0usize;
        let mut new_content: Option<String> = None;
        for m in re.find_iter(&content) {
            if match_n == occurrence {
                new_content = Some(format!("{}{}{}", &content[..m.start()], new_open, &content[m.end()..]));
                break;
            }
            match_n += 1;
        }

        let new_content = match new_content {
            Some(c) => c,
            None    => return Ok(false),
        };
        if new_content == content { return Ok(false); }

        // Atomic write: tmp file → rename
        let tmp_path = PathBuf::from(format!("{}.tmp.{}", path.display(), std::process::id()));
        std::fs::write(&tmp_path, &new_content)?;
        std::fs::rename(&tmp_path, path)?;
        Ok(true)
    }

    /// Full-text search across files. Returns matched elements with file and date_str.
    pub fn search(
        &self,
        query:       &str,
        type_filter: Option<&str>,
        tag_filter:  Option<&str>,
        since_date:  Option<NaiveDate>,
    ) -> Result<Vec<SearchResult>, MpsError> {
        let files = match since_date {
            Some(d) => self.files_since(d)?,
            None    => self.all_files()?,
        };

        let query_lower = query.to_lowercase();
        let mut results = Vec::new();

        for file in files {
            let date_str = file.file_name()
                .and_then(|n| n.to_str())
                .map(|n| n[..8].to_string())
                .unwrap_or_default();

            let elements = parser::parse_file(&file)?;

            for (_, el) in elements {
                if el.is_mps_group() || el.is_unknown() { continue; }

                if let Some(tf) = type_filter {
                    if el.sign() != tf { continue; }
                }
                if let Some(tag) = tag_filter {
                    if !el.tags().iter().any(|t| t == tag) { continue; }
                }
                if !el.body_str().to_lowercase().contains(&query_lower) { continue; }

                results.push(SearchResult {
                    element: el,
                    file: file.clone(),
                    date_str: date_str.clone(),
                });
            }
        }

        Ok(results)
    }
}

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

    fn make_store(dir: &Path) -> Store {
        Store::new(dir)
    }

    fn write_file(dir: &Path, name: &str, content: &str) -> PathBuf {
        let path = dir.join(name);
        std::fs::write(&path, content).unwrap();
        path
    }

    #[test]
    fn test_find_file_absent() {
        let dir = tempfile::tempdir().unwrap();
        let store = make_store(dir.path());
        let date = NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();
        assert!(store.find_file(date).is_none());
    }

    #[test]
    fn test_find_file_present() {
        let dir = tempfile::tempdir().unwrap();
        write_file(dir.path(), "20260101.1700000000.mps", "@task{ Hi }");
        let store = make_store(dir.path());
        let date = NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();
        assert!(store.find_file(date).is_some());
    }

    #[test]
    fn test_parse_date_empty() {
        let dir = tempfile::tempdir().unwrap();
        let store = make_store(dir.path());
        let date = NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();
        let els = store.parse_date(date).unwrap();
        assert!(els.is_empty());
    }

    #[test]
    fn test_append_creates_file() {
        let dir = tempfile::tempdir().unwrap();
        let store = make_store(dir.path());
        let date = NaiveDate::from_ymd_opt(2026, 4, 28).unwrap();
        let path = store.append("task", "Do a thing", &["work".into()], &[], date).unwrap();
        assert!(path.exists());

        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("@task"));
        assert!(content.contains("Do a thing"));
    }

    #[test]
    fn test_append_then_parse() {
        let dir = tempfile::tempdir().unwrap();
        let store = make_store(dir.path());
        let date = NaiveDate::from_ymd_opt(2026, 4, 28).unwrap();
        store.append("task", "Test task", &["work".into()], &[], date).unwrap();
        let els = store.parse_date(date).unwrap();
        // root mps + task
        assert!(els.len() >= 2);
        let has_task = els.values().any(|e| e.kind() == ElementKind::Task);
        assert!(has_task);
    }

    #[test]
    fn test_search_by_query() {
        let dir = tempfile::tempdir().unwrap();
        write_file(dir.path(), "20260101.1700000000.mps", "@task{ auth token fix }");
        let store = make_store(dir.path());
        let results = store.search("auth", None, None, None).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].date_str, "20260101");
    }

    #[test]
    fn test_files_since() {
        let dir = tempfile::tempdir().unwrap();
        write_file(dir.path(), "20260101.1700000000.mps", "@note{ old }");
        write_file(dir.path(), "20260601.1800000000.mps", "@note{ new }");
        let store = make_store(dir.path());
        let since = NaiveDate::from_ymd_opt(2026, 3, 1).unwrap();
        let files = store.files_since(since).unwrap();
        assert_eq!(files.len(), 1);
        assert!(files[0].to_str().unwrap().contains("20260601"));
    }
}