Skip to main content

outpost_core/
registry.rs

1use std::fs;
2use std::io::Write;
3use std::path::{Path, PathBuf};
4
5use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7
8use crate::{OutpostError, OutpostResult, RemoteName, SourceRepo};
9
10const REGISTRY_VERSION: u32 = 1;
11const OUTPOST_IGNORE_LINE: &str = ".outpost/";
12
13#[derive(Debug, Clone)]
14pub struct Registry {
15    path: PathBuf,
16    exclude_path: PathBuf,
17    version: u32,
18    entries: Vec<RegistryEntry>,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct RegistryEntry {
23    pub path: PathBuf,
24    pub created_at: DateTime<Utc>,
25    pub remote_name: RemoteName,
26    pub locked: bool,
27    pub lock_reason: Option<String>,
28    pub locked_at: Option<DateTime<Utc>>,
29}
30
31#[must_use = "RegistryMut changes are persisted only on save()"]
32pub struct RegistryMut<'src> {
33    _source: &'src SourceRepo,
34    inner: Registry,
35    dirty: bool,
36    saved: bool,
37}
38
39impl Registry {
40    pub fn load(source: &SourceRepo) -> OutpostResult<Self> {
41        let path = source.registry_path();
42        let exclude_path = source.local_exclude_path();
43        let contents = match fs::read_to_string(&path) {
44            Ok(contents) => contents,
45            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
46                return Ok(Self {
47                    path,
48                    exclude_path,
49                    version: REGISTRY_VERSION,
50                    entries: Vec::new(),
51                });
52            }
53            Err(source) => {
54                return Err(OutpostError::IoAt { path, source });
55            }
56        };
57
58        let file = serde_json::from_str::<RegistryFile>(&contents).map_err(|source| {
59            OutpostError::BadRegistry {
60                path: path.clone(),
61                reason: source.to_string(),
62            }
63        })?;
64        if file.version != REGISTRY_VERSION {
65            return Err(OutpostError::BadRegistry {
66                path,
67                reason: format!("unsupported registry version {}", file.version),
68            });
69        }
70
71        let entries = file
72            .outposts
73            .into_iter()
74            .map(|entry| entry.try_into_entry(&path))
75            .collect::<OutpostResult<Vec<_>>>()?;
76
77        Ok(Self {
78            path,
79            exclude_path,
80            version: REGISTRY_VERSION,
81            entries,
82        })
83    }
84
85    pub fn entries(&self) -> &[RegistryEntry] {
86        &self.entries
87    }
88
89    pub fn save(&self) -> OutpostResult<()> {
90        let parent = self.path.parent().ok_or_else(|| OutpostError::IoAt {
91            path: self.path.clone(),
92            source: std::io::Error::new(
93                std::io::ErrorKind::InvalidInput,
94                "registry path has no parent",
95            ),
96        })?;
97        fs::create_dir_all(parent).map_err(|source| OutpostError::IoAt {
98            path: parent.to_path_buf(),
99            source,
100        })?;
101        ensure_local_ignore(&self.exclude_path)?;
102
103        let file = RegistryFile::from_registry(self);
104        let mut temp =
105            tempfile::NamedTempFile::new_in(parent).map_err(|source| OutpostError::IoAt {
106                path: parent.to_path_buf(),
107                source,
108            })?;
109        serde_json::to_writer_pretty(temp.as_file_mut(), &file).map_err(|source| {
110            OutpostError::IoAt {
111                path: self.path.clone(),
112                source: std::io::Error::new(std::io::ErrorKind::Other, source),
113            }
114        })?;
115        writeln!(temp.as_file_mut()).map_err(|source| OutpostError::IoAt {
116            path: self.path.clone(),
117            source,
118        })?;
119        temp.persist(&self.path)
120            .map_err(|source| OutpostError::IoAt {
121                path: self.path.clone(),
122                source: source.error,
123            })?;
124
125        Ok(())
126    }
127
128    fn find(&self, path: &Path) -> Option<usize> {
129        self.entries.iter().position(|entry| entry.path == path)
130    }
131
132    fn find_existing_or_recorded(&self, path: &Path) -> OutpostResult<(PathBuf, Option<usize>)> {
133        match canonicalize_path(path) {
134            Ok(canonical) => {
135                let index = self.find(&canonical);
136                Ok((canonical, index))
137            }
138            Err(canonicalize_err) => {
139                if let Some(index) = self.entries.iter().position(|entry| entry.path == path) {
140                    Ok((path.to_path_buf(), Some(index)))
141                } else {
142                    Err(canonicalize_err)
143                }
144            }
145        }
146    }
147}
148
149impl RegistryEntry {
150    pub fn new(path: PathBuf, remote_name: RemoteName) -> OutpostResult<Self> {
151        Ok(Self {
152            path: canonicalize_path(&path)?,
153            created_at: Utc::now(),
154            remote_name,
155            locked: false,
156            lock_reason: None,
157            locked_at: None,
158        })
159    }
160}
161
162impl<'src> RegistryMut<'src> {
163    pub(crate) fn load(source: &'src SourceRepo) -> OutpostResult<Self> {
164        Ok(Self {
165            _source: source,
166            inner: Registry::load(source)?,
167            dirty: false,
168            saved: false,
169        })
170    }
171
172    pub fn add(&mut self, mut entry: RegistryEntry) -> OutpostResult<()> {
173        entry.path = canonicalize_path(&entry.path)?;
174        if let Some(index) = self.inner.find(&entry.path) {
175            let old = &self.inner.entries[index];
176            if old.locked && !entry.locked {
177                entry.locked = true;
178                entry.lock_reason = old.lock_reason.clone();
179                entry.locked_at = old.locked_at;
180            }
181            self.inner.entries[index] = entry;
182        } else {
183            self.inner.entries.push(entry);
184        }
185        self.dirty = true;
186        Ok(())
187    }
188
189    pub fn update_path(&mut self, old: &Path, new: PathBuf) -> OutpostResult<()> {
190        let (old, index) = self.inner.find_existing_or_recorded(old)?;
191        let new = canonicalize_path(&new)?;
192        let index = index.ok_or_else(|| OutpostError::RegistryEntryNotFound(old.clone()))?;
193        self.inner.entries[index].path = new;
194        self.dirty = true;
195        Ok(())
196    }
197
198    pub fn lock(&mut self, path: &Path, reason: Option<String>) -> OutpostResult<()> {
199        let path = canonicalize_path(path)?;
200        let index = self
201            .inner
202            .find(&path)
203            .ok_or_else(|| OutpostError::RegistryEntryNotFound(path.clone()))?;
204        let entry = &mut self.inner.entries[index];
205        entry.locked = true;
206        entry.lock_reason = reason;
207        entry.locked_at = Some(Utc::now());
208        self.dirty = true;
209        Ok(())
210    }
211
212    pub fn unlock(&mut self, path: &Path) -> OutpostResult<()> {
213        let path = canonicalize_path(path)?;
214        let index = self
215            .inner
216            .find(&path)
217            .ok_or_else(|| OutpostError::RegistryEntryNotFound(path.clone()))?;
218        let entry = &mut self.inner.entries[index];
219        entry.locked = false;
220        entry.lock_reason = None;
221        entry.locked_at = None;
222        self.dirty = true;
223        Ok(())
224    }
225
226    pub fn remove_by_path(&mut self, path: &Path) -> OutpostResult<bool> {
227        let (_path, index) = self.inner.find_existing_or_recorded(path)?;
228        if let Some(index) = index {
229            self.inner.entries.remove(index);
230            self.dirty = true;
231            Ok(true)
232        } else {
233            Ok(false)
234        }
235    }
236
237    pub fn entries(&self) -> &[RegistryEntry] {
238        self.inner.entries()
239    }
240
241    pub fn save(mut self) -> OutpostResult<()> {
242        self.saved = true;
243        let result = self.inner.save();
244        if result.is_ok() {
245            self.dirty = false;
246        }
247        result
248    }
249}
250
251impl<'src> Drop for RegistryMut<'src> {
252    fn drop(&mut self) {
253        if self.dirty && !self.saved {
254            debug_assert!(false, "RegistryMut dropped with unsaved changes");
255            eprintln!("warning: registry changes dropped without save");
256        }
257    }
258}
259
260#[derive(Debug, Serialize, Deserialize)]
261struct RegistryFile {
262    version: u32,
263    outposts: Vec<RegistryEntryFile>,
264}
265
266#[derive(Debug, Serialize, Deserialize)]
267struct RegistryEntryFile {
268    path: PathBuf,
269    created_at: DateTime<Utc>,
270    remote_name: String,
271    locked: bool,
272    lock_reason: Option<String>,
273    locked_at: Option<DateTime<Utc>>,
274}
275
276impl RegistryFile {
277    fn from_registry(registry: &Registry) -> Self {
278        Self {
279            version: registry.version,
280            outposts: registry
281                .entries
282                .iter()
283                .map(RegistryEntryFile::from_entry)
284                .collect(),
285        }
286    }
287}
288
289impl RegistryEntryFile {
290    fn from_entry(entry: &RegistryEntry) -> Self {
291        Self {
292            path: entry.path.clone(),
293            created_at: entry.created_at,
294            remote_name: entry.remote_name.as_str().to_owned(),
295            locked: entry.locked,
296            lock_reason: entry.lock_reason.clone(),
297            locked_at: entry.locked_at,
298        }
299    }
300
301    fn try_into_entry(self, registry_path: &Path) -> OutpostResult<RegistryEntry> {
302        let remote_name = RemoteName::parse(self.remote_name.clone()).map_err(|source| {
303            OutpostError::BadRegistry {
304                path: registry_path.to_path_buf(),
305                reason: source.to_string(),
306            }
307        })?;
308        Ok(RegistryEntry {
309            path: self.path,
310            created_at: self.created_at,
311            remote_name,
312            locked: self.locked,
313            lock_reason: self.lock_reason,
314            locked_at: self.locked_at,
315        })
316    }
317}
318
319fn ensure_local_ignore(exclude_path: &Path) -> OutpostResult<()> {
320    let parent = exclude_path.parent().ok_or_else(|| OutpostError::IoAt {
321        path: exclude_path.to_path_buf(),
322        source: std::io::Error::new(
323            std::io::ErrorKind::InvalidInput,
324            "exclude path has no parent",
325        ),
326    })?;
327    fs::create_dir_all(parent).map_err(|source| OutpostError::IoAt {
328        path: parent.to_path_buf(),
329        source,
330    })?;
331
332    let mut contents = match fs::read_to_string(exclude_path) {
333        Ok(contents) => contents,
334        Err(source) if source.kind() == std::io::ErrorKind::NotFound => String::new(),
335        Err(source) => {
336            return Err(OutpostError::IoAt {
337                path: exclude_path.to_path_buf(),
338                source,
339            });
340        }
341    };
342
343    if contents
344        .lines()
345        .any(|line| line.trim() == OUTPOST_IGNORE_LINE)
346    {
347        return Ok(());
348    }
349    if !contents.is_empty() && !contents.ends_with('\n') {
350        contents.push('\n');
351    }
352    contents.push_str(OUTPOST_IGNORE_LINE);
353    contents.push('\n');
354    fs::write(exclude_path, contents).map_err(|source| OutpostError::IoAt {
355        path: exclude_path.to_path_buf(),
356        source,
357    })
358}
359
360fn canonicalize_path(path: &Path) -> OutpostResult<PathBuf> {
361    fs::canonicalize(path).map_err(|source| OutpostError::IoAt {
362        path: path.to_path_buf(),
363        source,
364    })
365}
366
367#[cfg(test)]
368mod tests {
369    use std::panic::{catch_unwind, AssertUnwindSafe};
370
371    use chrono::TimeZone;
372    use serde_json::json;
373
374    use super::*;
375    use crate::GitInvoker;
376
377    #[test]
378    fn empty_registry_serializes_to_expected_json_and_round_trips() {
379        let (_temp, source) = init_source_repo();
380        let registry = Registry::load(&source).expect("missing registry loads");
381
382        registry.save().expect("save empty registry");
383
384        let value: serde_json::Value = serde_json::from_str(
385            &fs::read_to_string(source.registry_path()).expect("registry file"),
386        )
387        .expect("registry json parses");
388        assert_eq!(value, json!({ "version": 1, "outposts": [] }));
389        assert!(fs::read_to_string(source.local_exclude_path())
390            .expect("local exclude")
391            .lines()
392            .any(|line| line == OUTPOST_IGNORE_LINE));
393
394        let loaded = Registry::load(&source).expect("registry reloads");
395        assert!(loaded.entries().is_empty());
396    }
397
398    #[test]
399    fn add_readd_remove_and_add_round_trips_by_canonical_path() {
400        let (temp, source) = init_source_repo();
401        let outpost = temp.path().join("C");
402        let other = temp.path().join("D");
403        fs::create_dir_all(&outpost).expect("outpost dir");
404        fs::create_dir_all(&other).expect("other dir");
405
406        let mut registry = source.registry_mut().expect("registry mut");
407        registry
408            .add(entry_at(&outpost, "local", 1))
409            .expect("add local");
410        registry
411            .lock(&outpost, Some("keep".to_owned()))
412            .expect("lock");
413        registry
414            .add(entry_at(&outpost, "custom", 2))
415            .expect("re-add same path");
416        assert_eq!(registry.entries().len(), 1);
417        assert_eq!(registry.entries()[0].remote_name.as_str(), "custom");
418        assert!(registry.entries()[0].locked);
419        assert_eq!(registry.entries()[0].lock_reason.as_deref(), Some("keep"));
420
421        assert!(registry.remove_by_path(&outpost).expect("remove existing"));
422        assert!(!registry.remove_by_path(&outpost).expect("remove absent"));
423        registry
424            .add(entry_at(&other, "local", 3))
425            .expect("add other");
426        registry.save().expect("save");
427
428        let loaded = Registry::load(&source).expect("reload");
429        assert_eq!(loaded.entries().len(), 1);
430        assert_eq!(loaded.entries()[0].path, fs::canonicalize(&other).unwrap());
431        assert_eq!(loaded.entries()[0].remote_name.as_str(), "local");
432    }
433
434    #[test]
435    fn load_missing_registry_returns_empty_registry() {
436        let (_temp, source) = init_source_repo();
437        let registry = Registry::load(&source).expect("missing registry loads");
438
439        assert!(registry.entries().is_empty());
440        assert!(!source.registry_path().exists());
441    }
442
443    #[test]
444    fn update_path_handles_registered_old_path_after_rename() {
445        let (temp, source) = init_source_repo();
446        let old = temp.path().join("C");
447        let new = temp.path().join("D");
448        fs::create_dir_all(&old).expect("old outpost dir");
449        let canonical_old = fs::canonicalize(&old).expect("canonical old path");
450
451        let mut registry = source.registry_mut().expect("registry mut");
452        registry
453            .add(entry_at(&old, "local", 1))
454            .expect("add old path");
455        fs::rename(&old, &new).expect("rename outpost");
456
457        registry
458            .update_path(&canonical_old, new.clone())
459            .expect("update renamed path");
460        registry.save().expect("save");
461
462        let loaded = Registry::load(&source).expect("reload");
463        assert_eq!(loaded.entries().len(), 1);
464        assert_eq!(loaded.entries()[0].path, fs::canonicalize(&new).unwrap());
465    }
466
467    #[test]
468    fn remove_by_path_handles_registered_missing_path() {
469        let (temp, source) = init_source_repo();
470        let outpost = temp.path().join("C");
471        fs::create_dir_all(&outpost).expect("outpost dir");
472        let canonical_outpost = fs::canonicalize(&outpost).expect("canonical outpost");
473
474        let mut registry = source.registry_mut().expect("registry mut");
475        registry
476            .add(entry_at(&outpost, "local", 1))
477            .expect("add path");
478        fs::remove_dir(&outpost).expect("remove outpost dir");
479
480        assert!(registry
481            .remove_by_path(&canonical_outpost)
482            .expect("remove missing registered path"));
483        registry.save().expect("save");
484
485        assert!(Registry::load(&source)
486            .expect("reload")
487            .entries()
488            .is_empty());
489    }
490
491    #[test]
492    fn load_malformed_json_returns_bad_registry() {
493        let (_temp, source) = init_source_repo();
494        fs::create_dir_all(source.registry_path().parent().unwrap()).expect("registry dir");
495        fs::write(source.registry_path(), "{not json").expect("write bad json");
496
497        let err = Registry::load(&source).expect_err("bad json should fail");
498        assert!(matches!(
499            err,
500            OutpostError::BadRegistry { path, .. } if path == source.registry_path()
501        ));
502    }
503
504    #[test]
505    #[cfg(debug_assertions)]
506    fn dropping_dirty_registry_mut_trips_debug_drop_guard() {
507        let (temp, source) = init_source_repo();
508        let outpost = temp.path().join("C");
509        fs::create_dir_all(&outpost).expect("outpost dir");
510
511        let result = catch_unwind(AssertUnwindSafe(|| {
512            let mut registry = source.registry_mut().expect("registry mut");
513            registry
514                .add(entry_at(&outpost, "local", 1))
515                .expect("add entry");
516        }));
517
518        assert!(result.is_err());
519    }
520
521    #[test]
522    #[cfg(debug_assertions)]
523    fn failed_save_returns_error_without_drop_guard_panic() {
524        let temp = tempfile::tempdir().expect("tempdir");
525        let work_tree = temp.path().join("source");
526        let git_dir = temp.path().join("git-file");
527        let outpost = temp.path().join("C");
528        fs::create_dir_all(&work_tree).expect("source dir");
529        fs::write(&git_dir, "not a dir").expect("git file");
530        fs::create_dir_all(&outpost).expect("outpost dir");
531        let source =
532            SourceRepo::from_storage_paths(&work_tree, &git_dir).expect("source repo storage");
533
534        let result = catch_unwind(AssertUnwindSafe(|| {
535            let mut registry = source.registry_mut().expect("registry mut");
536            registry
537                .add(entry_at(&outpost, "local", 1))
538                .expect("add entry");
539            registry.save()
540        }));
541
542        let save_result = result.expect("save error should not panic");
543        assert!(matches!(save_result, Err(OutpostError::IoAt { .. })));
544    }
545
546    #[test]
547    #[cfg(not(debug_assertions))]
548    fn dropping_dirty_registry_mut_does_not_panic_in_release_builds() {
549        let (temp, source) = init_source_repo();
550        let outpost = temp.path().join("C");
551        fs::create_dir_all(&outpost).expect("outpost dir");
552
553        let mut registry = source.registry_mut().expect("registry mut");
554        registry
555            .add(entry_at(&outpost, "local", 1))
556            .expect("add entry");
557    }
558
559    fn init_source_repo() -> (tempfile::TempDir, SourceRepo) {
560        let temp = tempfile::tempdir().expect("tempdir");
561        GitInvoker::at(temp.path())
562            .run_check(["init", "--initial-branch=main"])
563            .expect("init source");
564        let source = SourceRepo::from_storage_paths(temp.path(), &temp.path().join(".git"))
565            .expect("source repo");
566        (temp, source)
567    }
568
569    fn entry_at(path: &Path, remote: &str, seconds: i64) -> RegistryEntry {
570        RegistryEntry {
571            path: path.to_path_buf(),
572            created_at: Utc.timestamp_opt(seconds, 0).single().unwrap(),
573            remote_name: RemoteName::parse(remote).expect("remote parses"),
574            locked: false,
575            lock_reason: None,
576            locked_at: None,
577        }
578    }
579}