specfold_core/config/private_root.rs
1//! F1: documents for a public repository kept in a private directory outside it. A user-level
2//! file maps the repository to that directory; nothing is written inside the public tree.
3//!
4//! It also names other repositories by id prefix (F2), read like `[remotes]`.
5//!
6//! ```toml
7//! # ~/.config/specfold/roots.toml (or $SPECFOLD_ROOTS)
8//! [[root]]
9//! repo = "~/src/public-lib"
10//! spec = "~/notes/public-lib-spec"
11//! public = "libs/public-lib" # optional: its [public] path in the spec root
12//! [prefix]
13//! lib = "~/src/other-lib" # spec show lib:<id>
14//! ```
15
16use super::paths;
17use serde::Deserialize;
18use std::path::{Path, PathBuf};
19
20#[derive(Deserialize)]
21struct Roots {
22 #[serde(default)]
23 root: Vec<Entry>,
24 /// F2: id prefix → repository root, read-only (`[prefix] lib = "~/src/lib"`).
25 #[serde(default)]
26 prefix: std::collections::BTreeMap<String, String>,
27}
28
29#[derive(Deserialize)]
30struct Entry {
31 repo: String,
32 spec: String,
33 /// The `[public]` path of the spec root this repository is a copy of, when the spec root
34 /// publishes more than one and none is named like the repository's directory.
35 #[serde(default)]
36 public: Option<String>,
37}
38
39/// A repository mapped to a private spec root.
40pub struct Mapping {
41 /// The private directory holding the documents and its spec.toml.
42 pub spec: PathBuf,
43 /// The `public` key of the entry, as written.
44 pub public: Option<String>,
45}
46
47/// The user-level mapping file: `$SPECFOLD_ROOTS`, else `$XDG_CONFIG_HOME/specfold/roots.toml`,
48/// else `~/.config/specfold/roots.toml`.
49pub fn file() -> Option<PathBuf> {
50 if let Some(p) = std::env::var_os("SPECFOLD_ROOTS") {
51 return Some(PathBuf::from(p));
52 }
53 let base = std::env::var_os("XDG_CONFIG_HOME")
54 .map(PathBuf::from)
55 .or_else(|| paths::home_dir().map(|h| h.join(".config")))?;
56 Some(base.join("specfold/roots.toml"))
57}
58
59fn read() -> Option<Roots> {
60 toml::from_str(&std::fs::read_to_string(file()?).ok()?).ok()
61}
62
63/// F2: the id prefixes of the user-level file, as (prefix, absolute root).
64pub fn prefixes() -> Vec<(String, PathBuf)> {
65 read()
66 .map(|r| r.prefix.into_iter().map(|(k, v)| (k, paths::expand(Path::new("/"), &v))).collect())
67 .unwrap_or_default()
68}
69
70/// The private root mapped to the repository at `repo`, when the mapping file names it.
71pub fn mapped(repo: &Path) -> Option<PathBuf> {
72 mapping(repo).map(|m| m.spec)
73}
74
75/// The mapping entry for the repository at `repo`, when the mapping file names it.
76pub fn mapping(repo: &Path) -> Option<Mapping> {
77 let roots = read()?;
78 let canon = |p: &Path| p.canonicalize().ok();
79 let me = canon(repo)?;
80 roots.root.into_iter().find_map(|e| {
81 let r = paths::expand(Path::new("/"), &e.repo);
82 (canon(&r)? == me).then(|| Mapping { spec: paths::expand(Path::new("/"), &e.spec), public: e.public })
83 })
84}