Skip to main content

surjection_core/layering/
mod.rs

1//! Project scope (SPEC 6): the project layer of a folder over the system
2//! layer of the store.
3//!
4//! - [`manifest`]: discovery of `<P>`, loading and validation of
5//!   `.surjection/project.toml` and `.surjection/project.local.toml`, the content
6//!   hash.
7//! - [`merge`]: local over shared, `from`, `unset`, suppressions, client
8//!   sets and the layer each entry comes from.
9//! - [`trust`]: `state/trust.json` (SPEC 17).
10//! - [`git`]: the project's repository, for the private-file rules of 6.5.
11//! - [`effective`]: what a client loads in a folder, and from where (6.4).
12//! - [`projects`]: init, add, remove, the trust review and trust, shared by
13//!   `surject project` and the app.
14//! - [`project_servers`]: the app's edits of a manifest's `[servers.*]`.
15//! - [`discover`]: folders the clients know, offered as new projects.
16//!
17//! The planner ([`crate::apply::plan`]) turns known projects into project
18//! and project-local targets.
19
20pub mod discover;
21pub mod effective;
22pub mod git;
23pub mod manifest;
24pub mod merge;
25pub mod project_servers;
26pub mod projects;
27pub mod trust;
28
29pub use effective::{
30    EffectiveEntry, EffectiveView, Layer, ProjectRef, Shadowed, Winner, effective,
31};
32
33use std::path::{Path, PathBuf};
34
35pub use git::ProjectRepo;
36pub use manifest::{
37    LOCAL_FILE, ManifestFile, Project, SHARED_FILE, content_hash, discover, path_key, resolved,
38    same_folder, same_path,
39};
40pub use merge::{
41    EntryBody, EntryLayer, ProjectEntry, deep_merge, default_clients, project_entries, remove_path,
42    suppression_mechanism,
43};
44pub use trust::{TRUST_FILE, TrustRecord, TrustState, TrustStore};
45
46use crate::env::Env;
47use crate::error::{CoreError, ErrorCode};
48use crate::fs::Fs;
49use crate::model::machine::MachineOverlay;
50
51/// A project this machine knows (overlay `[projects.<id>] path`).
52#[derive(Debug, Clone)]
53pub struct KnownProject {
54    /// The overlay key.
55    pub id: String,
56    pub root: PathBuf,
57    pub status: ProjectStatus,
58}
59
60/// What a known project's folder holds now.
61#[derive(Debug, Clone)]
62pub enum ProjectStatus {
63    /// The folder does not exist on this machine.
64    Missing,
65    /// The manifests cannot be used (absent, unreadable, invalid); the
66    /// project's entries are left alone.
67    Failed(CoreError),
68    Loaded {
69        project: Box<Project>,
70        trust: TrustState,
71    },
72}
73
74impl KnownProject {
75    /// The loaded project, if any.
76    pub fn project(&self) -> Option<&Project> {
77        match &self.status {
78            ProjectStatus::Loaded { project, .. } => Some(project),
79            _ => None,
80        }
81    }
82
83    /// `trust_required` for a project that is not trusted as it is now.
84    pub fn trust_error(&self) -> Option<CoreError> {
85        let ProjectStatus::Loaded { project, trust } = &self.status else {
86            return None;
87        };
88        trust_required(project, &self.root, *trust)
89    }
90}
91
92/// `trust_required` for `project` in `root` when `trust` is not
93/// [`TrustState::Trusted`].
94pub fn trust_required(project: &Project, root: &Path, trust: TrustState) -> Option<CoreError> {
95    let why = match trust {
96        TrustState::Trusted => return None,
97        TrustState::Untrusted => "is not trusted on this machine",
98        TrustState::Changed => "changed since it was trusted",
99    };
100    Some(
101        CoreError::new(
102            ErrorCode::TrustRequired,
103            format!(
104                "project {:?} {why}; review its manifests, then run `{} project trust {}`",
105                project.name(),
106                crate::brand::BIN_NAME,
107                root.display()
108            ),
109        )
110        .with_path(project.dir()),
111    )
112}
113
114/// The projects of this machine's overlay, in id order, with their
115/// manifests and trust state.
116pub fn known_projects(
117    fs: &dyn Fs,
118    env: &Env,
119    overlay: Option<&MachineOverlay>,
120    trust: &TrustStore,
121) -> Vec<KnownProject> {
122    let Some(projects) = overlay.and_then(|overlay| overlay.projects.as_ref()) else {
123        return Vec::new();
124    };
125    projects
126        .iter()
127        .map(|(id, known)| {
128            let root = PathBuf::from(&known.path);
129            let status = load_status(fs, env, id, &root, trust);
130            KnownProject {
131                id: id.clone(),
132                root,
133                status,
134            }
135        })
136        .collect()
137}
138
139fn load_status(fs: &dyn Fs, env: &Env, id: &str, root: &Path, trust: &TrustStore) -> ProjectStatus {
140    if !fs.is_dir(root) {
141        return ProjectStatus::Missing;
142    }
143    // A manifest directly in the home directory is ignored (SPEC 6.1):
144    // there, project files are the user files of several clients.
145    if same_folder(fs, root, env.home()) {
146        return ProjectStatus::Failed(
147            CoreError::new(
148                ErrorCode::InvalidPath,
149                format!(
150                    "project {id:?} is the home directory, which cannot be a project; its \
151                     entries are left alone"
152                ),
153            )
154            .with_path(root),
155        );
156    }
157    match Project::load(fs, root) {
158        Ok(Some(project)) if project.id != id => ProjectStatus::Failed(
159            CoreError::new(
160                ErrorCode::IdMismatch,
161                format!(
162                    "the manifests in this folder are project {:?}, but this machine knows the \
163                     folder as project {id:?}",
164                    project.id
165                ),
166            )
167            .with_path(project.dir()),
168        ),
169        Ok(Some(project)) => {
170            let state = trust.state(&project);
171            ProjectStatus::Loaded {
172                project: Box::new(project),
173                trust: state,
174            }
175        }
176        Ok(None) => ProjectStatus::Failed(
177            CoreError::new(
178                ErrorCode::NotFound,
179                format!("project {id:?} has no manifest in its folder; its entries are left alone"),
180            )
181            .with_path(manifest::manifest_dir(fs, root)),
182        ),
183        Err(err) => ProjectStatus::Failed(err),
184    }
185}