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::{AssertUnwindSafe, catch_unwind};
370
371    use super::*;
372    use crate::GitInvoker;
373    use chrono::TimeZone;
374
375    #[test]
376    fn empty_registry_serializes_to_expected_json_and_round_trips() {
377        let (_temp, source) = init_source_repo();
378        let registry = Registry::load(&source).expect("missing registry loads");
379
380        registry.save().expect("save empty registry");
381
382        let value: serde_json::Value = serde_json::from_str(
383            &fs::read_to_string(source.registry_path()).expect("registry file"),
384        )
385        .expect("registry json parses");
386        let expected: serde_json::Value =
387            serde_json::from_str(r#"{ "version": 1, "outposts": [] }"#).expect("expected json");
388        assert_eq!(value, expected);
389        assert!(
390            fs::read_to_string(source.local_exclude_path())
391                .expect("local exclude")
392                .lines()
393                .any(|line| line == OUTPOST_IGNORE_LINE)
394        );
395
396        let loaded = Registry::load(&source).expect("registry reloads");
397        assert!(loaded.entries().is_empty());
398    }
399
400    #[test]
401    fn add_readd_remove_and_add_round_trips_by_canonical_path() {
402        let (temp, source) = init_source_repo();
403        let outpost = temp.path().join("C");
404        let other = temp.path().join("D");
405        fs::create_dir_all(&outpost).expect("outpost dir");
406        fs::create_dir_all(&other).expect("other dir");
407
408        let mut registry = source.registry_mut().expect("registry mut");
409        registry
410            .add(entry_at(&outpost, "local", 1))
411            .expect("add local");
412        registry
413            .lock(&outpost, Some("keep".to_owned()))
414            .expect("lock");
415        registry
416            .add(entry_at(&outpost, "custom", 2))
417            .expect("re-add same path");
418        assert_eq!(registry.entries().len(), 1);
419        assert_eq!(registry.entries()[0].remote_name.as_str(), "custom");
420        assert!(registry.entries()[0].locked);
421        assert_eq!(registry.entries()[0].lock_reason.as_deref(), Some("keep"));
422
423        assert!(registry.remove_by_path(&outpost).expect("remove existing"));
424        assert!(!registry.remove_by_path(&outpost).expect("remove absent"));
425        registry
426            .add(entry_at(&other, "local", 3))
427            .expect("add other");
428        registry.save().expect("save");
429
430        let loaded = Registry::load(&source).expect("reload");
431        assert_eq!(loaded.entries().len(), 1);
432        assert_eq!(loaded.entries()[0].path, fs::canonicalize(&other).unwrap());
433        assert_eq!(loaded.entries()[0].remote_name.as_str(), "local");
434    }
435
436    #[test]
437    fn load_missing_registry_returns_empty_registry() {
438        let (_temp, source) = init_source_repo();
439        let registry = Registry::load(&source).expect("missing registry loads");
440
441        assert!(registry.entries().is_empty());
442        assert!(!source.registry_path().exists());
443    }
444
445    #[test]
446    fn update_path_handles_registered_old_path_after_rename() {
447        let (temp, source) = init_source_repo();
448        let old = temp.path().join("C");
449        let new = temp.path().join("D");
450        fs::create_dir_all(&old).expect("old outpost dir");
451        let canonical_old = fs::canonicalize(&old).expect("canonical old path");
452
453        let mut registry = source.registry_mut().expect("registry mut");
454        registry
455            .add(entry_at(&old, "local", 1))
456            .expect("add old path");
457        fs::rename(&old, &new).expect("rename outpost");
458
459        registry
460            .update_path(&canonical_old, new.clone())
461            .expect("update renamed path");
462        registry.save().expect("save");
463
464        let loaded = Registry::load(&source).expect("reload");
465        assert_eq!(loaded.entries().len(), 1);
466        assert_eq!(loaded.entries()[0].path, fs::canonicalize(&new).unwrap());
467    }
468
469    #[test]
470    fn remove_by_path_handles_registered_missing_path() {
471        let (temp, source) = init_source_repo();
472        let outpost = temp.path().join("C");
473        fs::create_dir_all(&outpost).expect("outpost dir");
474        let canonical_outpost = fs::canonicalize(&outpost).expect("canonical outpost");
475
476        let mut registry = source.registry_mut().expect("registry mut");
477        registry
478            .add(entry_at(&outpost, "local", 1))
479            .expect("add path");
480        fs::remove_dir(&outpost).expect("remove outpost dir");
481
482        assert!(
483            registry
484                .remove_by_path(&canonical_outpost)
485                .expect("remove missing registered path")
486        );
487        registry.save().expect("save");
488
489        assert!(
490            Registry::load(&source)
491                .expect("reload")
492                .entries()
493                .is_empty()
494        );
495    }
496
497    #[test]
498    fn load_malformed_json_returns_bad_registry() {
499        let (_temp, source) = init_source_repo();
500        fs::create_dir_all(source.registry_path().parent().unwrap()).expect("registry dir");
501        fs::write(source.registry_path(), "{not json").expect("write bad json");
502
503        let err = Registry::load(&source).expect_err("bad json should fail");
504        assert!(matches!(
505            err,
506            OutpostError::BadRegistry { path, .. } if path == source.registry_path()
507        ));
508    }
509
510    #[test]
511    #[cfg(debug_assertions)]
512    fn dropping_dirty_registry_mut_trips_debug_drop_guard() {
513        let (temp, source) = init_source_repo();
514        let outpost = temp.path().join("C");
515        fs::create_dir_all(&outpost).expect("outpost dir");
516
517        let result = catch_unwind(AssertUnwindSafe(|| {
518            let mut registry = source.registry_mut().expect("registry mut");
519            registry
520                .add(entry_at(&outpost, "local", 1))
521                .expect("add entry");
522        }));
523
524        assert!(result.is_err());
525    }
526
527    #[test]
528    #[cfg(debug_assertions)]
529    fn failed_save_returns_error_without_drop_guard_panic() {
530        let temp = tempfile::tempdir().expect("tempdir");
531        let work_tree = temp.path().join("source");
532        let git_dir = temp.path().join("git-file");
533        let outpost = temp.path().join("C");
534        fs::create_dir_all(&work_tree).expect("source dir");
535        fs::write(&git_dir, "not a dir").expect("git file");
536        fs::create_dir_all(&outpost).expect("outpost dir");
537        let source =
538            SourceRepo::from_storage_paths(&work_tree, &git_dir).expect("source repo storage");
539
540        let result = catch_unwind(AssertUnwindSafe(|| {
541            let mut registry = source.registry_mut().expect("registry mut");
542            registry
543                .add(entry_at(&outpost, "local", 1))
544                .expect("add entry");
545            registry.save()
546        }));
547
548        let save_result = result.expect("save error should not panic");
549        assert!(matches!(save_result, Err(OutpostError::IoAt { .. })));
550    }
551
552    #[test]
553    #[cfg(not(debug_assertions))]
554    fn dropping_dirty_registry_mut_does_not_panic_in_release_builds() {
555        let (temp, source) = init_source_repo();
556        let outpost = temp.path().join("C");
557        fs::create_dir_all(&outpost).expect("outpost dir");
558
559        let mut registry = source.registry_mut().expect("registry mut");
560        registry
561            .add(entry_at(&outpost, "local", 1))
562            .expect("add entry");
563    }
564
565    fn init_source_repo() -> (tempfile::TempDir, SourceRepo) {
566        let temp = tempfile::tempdir().expect("tempdir");
567        GitInvoker::at(temp.path())
568            .run_check(["init", "--initial-branch=main"])
569            .expect("init source");
570        let source = SourceRepo::from_storage_paths(temp.path(), &temp.path().join(".git"))
571            .expect("source repo");
572        (temp, source)
573    }
574
575    fn entry_at(path: &Path, remote: &str, seconds: i64) -> RegistryEntry {
576        RegistryEntry {
577            path: path.to_path_buf(),
578            created_at: Utc.timestamp_opt(seconds, 0).single().unwrap(),
579            remote_name: RemoteName::parse(remote).expect("remote parses"),
580            locked: false,
581            lock_reason: None,
582            locked_at: None,
583        }
584    }
585}