Skip to main content

logicaffeine_cli/project/
manifest.rs

1//! Phase 37: Largo.toml Manifest Parser
2//!
3//! Parses project manifests for LOGOS build configuration.
4//!
5//! The manifest file (`Largo.toml`) defines project metadata, dependencies,
6//! and build settings. This module provides types for parsing and serializing
7//! these manifests.
8//!
9//! # Example Manifest
10//!
11//! ```toml
12//! [package]
13//! name = "my_project"
14//! version = "1.0.0"
15//! description = "A LOGOS project"
16//! entry = "src/main.lg"
17//!
18//! [dependencies]
19//! std = "logos:std"
20//! math = { path = "./math" }
21//! ```
22
23use serde::{Deserialize, Serialize};
24use std::collections::HashMap;
25use std::fs;
26use std::path::Path;
27
28/// Project manifest (`Largo.toml`).
29///
30/// The root structure of a LOGOS project manifest, containing package
31/// metadata and dependency specifications.
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct Manifest {
34    /// Package metadata section.
35    pub package: Package,
36    /// Map of dependency names to their specifications.
37    #[serde(default)]
38    pub dependencies: HashMap<String, DependencySpec>,
39    /// Test-framework configuration (`[test]`) — the discipline ledger's
40    /// budgets. Budgets should
41    /// only ever shrink.
42    #[serde(default)]
43    pub test: Option<TestSection>,
44    /// Web-site configuration (`[web]`) — whether a page ships the built-in theme.
45    #[serde(default)]
46    pub web: Option<WebSection>,
47}
48
49/// The `[web]` section: a site's opt-out of the framework's built-in theme.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct WebSection {
52    /// Whether a built page carries the built-in design-token `<style>` — `true` unless a
53    /// project brings its whole design and writes `theme = false`.
54    #[serde(default = "yes")]
55    pub theme: bool,
56}
57
58fn yes() -> bool {
59    true
60}
61
62/// The `[test]` section: conscious debt budgets for the test runner.
63#[derive(Debug, Clone, Default, Serialize, Deserialize)]
64pub struct TestSection {
65    /// How many loud skips the suite may carry (default 0 — an unbudgeted
66    /// skip fails the run).
67    #[serde(default)]
68    pub skip_budget: usize,
69}
70
71/// Package metadata from the `[package]` section.
72///
73/// Contains identifying information about the package used for
74/// building and publishing.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct Package {
77    /// Package name (used for registry publishing).
78    pub name: String,
79    /// Semantic version string. Defaults to "0.1.0".
80    #[serde(default = "default_version")]
81    pub version: String,
82    /// Short description of the package.
83    #[serde(default)]
84    pub description: Option<String>,
85    /// List of package authors.
86    #[serde(default)]
87    pub authors: Vec<String>,
88    /// Entry point file path. Defaults to "src/main.lg".
89    #[serde(default = "default_entry")]
90    pub entry: String,
91    /// The address this site is served at, e.g. `https://acme.example` — the one
92    /// thing a project knows about itself that its own files cannot.
93    ///
94    /// A `sitemap.xml`'s `<loc>` is ABSOLUTE by specification, so without this there
95    /// is no honest sitemap to write and none is written. Optional on purpose: a
96    /// project that is not a public website has no address to declare, and demanding
97    /// one would make every non-web project carry a field it must invent.
98    #[serde(default)]
99    pub site: Option<String>,
100}
101
102/// Dependency specification.
103///
104/// Dependencies can be specified in two forms:
105/// - Simple: Just a version string or URI (`"1.0.0"` or `"logos:std"`)
106/// - Detailed: A table with version, path, or git fields
107#[derive(Debug, Clone, Serialize, Deserialize)]
108#[serde(untagged)]
109pub enum DependencySpec {
110    /// Simple version string or URI (e.g., `"1.0.0"`, `"logos:std"`).
111    Simple(String),
112    /// Detailed specification with explicit fields.
113    Detailed(DependencyDetail),
114}
115
116impl std::fmt::Display for DependencySpec {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        match self {
119            DependencySpec::Simple(s) => write!(f, "{}", s),
120            DependencySpec::Detailed(d) => {
121                if let Some(v) = &d.version {
122                    write!(f, "{}", v)
123                } else if let Some(p) = &d.path {
124                    write!(f, "path:{}", p)
125                } else if let Some(g) = &d.git {
126                    write!(f, "git:{}", g)
127                } else {
128                    write!(f, "*")
129                }
130            }
131        }
132    }
133}
134
135/// Detailed dependency specification.
136///
137/// Allows specifying dependencies from multiple sources:
138/// version requirements, local paths, or git repositories.
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct DependencyDetail {
141    /// Version requirement (e.g., `"^1.0"`, `">=2.0.0"`).
142    #[serde(default)]
143    pub version: Option<String>,
144    /// Local filesystem path to the dependency.
145    #[serde(default)]
146    pub path: Option<String>,
147    /// Git repository URL.
148    #[serde(default)]
149    pub git: Option<String>,
150    /// Exact commit for a `git` dependency — a full 40-character hex SHA-1. A
151    /// git dependency MUST pin an exact commit: a floating `branch`/`tag` alone
152    /// is an irreproducible (false) build and is rejected during resolution.
153    #[serde(default)]
154    pub rev: Option<String>,
155    /// A git branch. Recorded for diagnostics/vendoring, but NEVER sufficient on
156    /// its own — an exact `rev` is still required.
157    #[serde(default)]
158    pub branch: Option<String>,
159    /// A git tag. Like `branch`, informational only — an exact `rev` is required.
160    #[serde(default)]
161    pub tag: Option<String>,
162}
163
164/// Where a declared dependency's source is rooted on disk, resolved from the
165/// manifest against a canonical project root.
166///
167/// PATH dependencies resolve their `path` relative to the project root and
168/// canonicalize it. GIT dependencies require an exact commit `rev` and resolve
169/// against a preserved local checkout (the vendored source) — see the module's
170/// [fetch/vendor documentation](ResolvedDep#vendoring). Both forms yield an
171/// existing, canonicalized directory that the module loader may traverse.
172///
173/// # Vendoring
174///
175/// A git dependency's source is expected to already be present on disk: `largo`
176/// vendors an exactly-pinned checkout under `<project>/.logos-deps/<name>-<rev>/`
177/// (a `git clone` + `git checkout <rev>`, done once and cached — the checkout is
178/// content-addressed by its commit, so it is reproducible and never re-fetched).
179/// The manifest's `path` field on a git dependency names that resolved checkout
180/// explicitly, which is what makes the exact-rev + closure-linking contract
181/// provable offline: resolution reads the pinned source directory, never the
182/// network. When only `git`/`rev` are given (no explicit `path`), resolution
183/// looks in the conventional vendor directory.
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub struct ResolvedDep {
186    /// The dependency's declared name (its `[dependencies]` key), also the alias
187    /// an `Import <Name>.` binds to.
188    pub name: String,
189    /// The canonicalized root directory the dependency's modules live under.
190    pub root: std::path::PathBuf,
191    /// The origin the source was resolved from, for the build manifest.
192    pub source: DepSource,
193}
194
195/// The origin a [`ResolvedDep`] was resolved from.
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub enum DepSource {
198    /// A local `path = "…"` dependency.
199    Path,
200    /// A `git = "…"` dependency pinned to an exact commit `rev`.
201    Git {
202        /// The repository URL.
203        url: String,
204        /// The exact 40-hex commit the source is pinned to.
205        rev: String,
206    },
207}
208
209/// An error resolving a `[dependencies]` declaration into a [`ResolvedDep`].
210#[derive(Debug)]
211pub enum DependencyError {
212    /// A `path`/`git` dependency's resolved root does not exist on disk.
213    Missing {
214        name: String,
215        root: std::path::PathBuf,
216    },
217    /// A `git` dependency did not pin an exact commit `rev`.
218    FloatingGit { name: String },
219    /// A `git` dependency's `rev` is not a full 40-character hex commit.
220    MalformedRev { name: String, rev: String },
221    /// A dependency form we cannot LINK locally (a registry version, or an empty
222    /// detail table). Registry linking is intentionally unsupported for the local
223    /// closure — path/git-local only.
224    NotLinkable { name: String, detail: String },
225}
226
227impl std::fmt::Display for DependencyError {
228    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229        match self {
230            DependencyError::Missing { name, root } => write!(
231                f,
232                "dependency `{name}` points at `{}`, which does not exist",
233                root.display()
234            ),
235            DependencyError::FloatingGit { name } => write!(
236                f,
237                "git dependency `{name}` must pin an exact commit — add `rev = \"<40-hex commit>\"`; \
238                 a branch or tag alone is an irreproducible build"
239            ),
240            DependencyError::MalformedRev { name, rev } => write!(
241                f,
242                "git dependency `{name}` has rev `{rev}`, which is not a full 40-character hex commit"
243            ),
244            DependencyError::NotLinkable { name, detail } => write!(
245                f,
246                "dependency `{name}` ({detail}) cannot be linked from the local closure — \
247                 use a `path` or an exactly-pinned `git` dependency (registry linking is not supported here)"
248            ),
249        }
250    }
251}
252
253impl std::error::Error for DependencyError {}
254
255/// True for a full 40-character lowercase-or-uppercase hex commit SHA-1.
256fn is_exact_commit(rev: &str) -> bool {
257    rev.len() == 40 && rev.chars().all(|c| c.is_ascii_hexdigit())
258}
259
260fn default_version() -> String {
261    "0.1.0".to_string()
262}
263
264fn default_entry() -> String {
265    "src/main.lg".to_string()
266}
267
268/// Errors that can occur when loading a manifest
269#[derive(Debug)]
270pub enum ManifestError {
271    Io(std::path::PathBuf, String),
272    Parse(std::path::PathBuf, String),
273    Serialize(String),
274}
275
276impl std::fmt::Display for ManifestError {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        match self {
279            ManifestError::Io(path, e) => write!(f, "Failed to read {}: {}", path.display(), e),
280            ManifestError::Parse(path, e) => write!(f, "Failed to parse {}: {}", path.display(), e),
281            ManifestError::Serialize(e) => write!(f, "Failed to serialize manifest: {}", e),
282        }
283    }
284}
285
286impl std::error::Error for ManifestError {}
287
288impl Manifest {
289    /// Load manifest from a directory (looks for Largo.toml)
290    pub fn load(dir: &Path) -> Result<Self, ManifestError> {
291        let path = dir.join("Largo.toml");
292        let content = fs::read_to_string(&path)
293            .map_err(|e| ManifestError::Io(path.clone(), e.to_string()))?;
294        toml::from_str(&content).map_err(|e| ManifestError::Parse(path, e.to_string()))
295    }
296
297    /// Whether a built page carries the framework's theme — the ONE rule every page
298    /// composition site reads, so a project's `[web]` `theme = false` reaches all of them alike.
299    pub fn shell_theme(&self) -> logicaffeine_compile::web_host::ShellTheme {
300        match &self.web {
301            Some(web) if !web.theme => logicaffeine_compile::web_host::ShellTheme::None,
302            _ => logicaffeine_compile::web_host::ShellTheme::Default,
303        }
304    }
305
306    /// Create a new manifest with default values
307    pub fn new(name: &str) -> Self {
308        Manifest {
309            package: Package {
310                name: name.to_string(),
311                version: default_version(),
312                description: None,
313                authors: Vec::new(),
314                entry: default_entry(),
315                site: None,
316            },
317            dependencies: HashMap::new(),
318            test: None,
319            web: None,
320        }
321    }
322
323    /// Serialize to TOML string
324    pub fn to_toml(&self) -> Result<String, ManifestError> {
325        toml::to_string_pretty(self).map_err(|e| ManifestError::Serialize(e.to_string()))
326    }
327
328    /// Resolve every LINKABLE `[dependencies]` declaration against `project_root`
329    /// into a canonicalized [`ResolvedDep`].
330    ///
331    /// Only PATH and exactly-pinned GIT dependencies are linkable from the local
332    /// closure — a plain version string (`foo = "1.2"`) or a `logos:` intrinsic is
333    /// resolved elsewhere (the AOT `## Requires` path / the built-in prelude) and
334    /// is skipped here, never treated as an error. This is what keeps the local
335    /// closure registry-free: `resolve_dependencies` reaches only the filesystem.
336    ///
337    /// Enforced invariants:
338    /// - A `git` dependency MUST carry an exact 40-hex commit `rev`
339    ///   ([`DependencyError::FloatingGit`] / [`DependencyError::MalformedRev`]).
340    /// - A `path`/`git` dependency's resolved root MUST exist
341    ///   ([`DependencyError::Missing`]).
342    ///
343    /// Determinism: names are resolved in sorted order, so the returned vec is
344    /// stable regardless of the manifest's `HashMap` iteration order.
345    pub fn resolve_dependencies(
346        &self,
347        project_root: &Path,
348    ) -> Result<Vec<ResolvedDep>, DependencyError> {
349        let mut names: Vec<&String> = self.dependencies.keys().collect();
350        names.sort();
351        let mut resolved = Vec::new();
352        for name in names {
353            if let Some(dep) = self.resolve_one(name, &self.dependencies[name], project_root)? {
354                resolved.push(dep);
355            }
356        }
357        Ok(resolved)
358    }
359
360    /// Resolve one declaration; `Ok(None)` for a non-linkable-but-legal form
361    /// (a version string / `logos:` intrinsic — resolved outside the local closure).
362    fn resolve_one(
363        &self,
364        name: &str,
365        spec: &DependencySpec,
366        project_root: &Path,
367    ) -> Result<Option<ResolvedDep>, DependencyError> {
368        let detail = match spec {
369            // A bare version / `logos:` URI is not a local-closure dependency.
370            DependencySpec::Simple(_) => return Ok(None),
371            DependencySpec::Detailed(d) => d,
372        };
373        // GIT takes precedence: an entry carrying `git` is a git dependency even
374        // if a `path` is also present (the path names the resolved checkout).
375        if let Some(url) = &detail.git {
376            let rev = detail
377                .rev
378                .as_deref()
379                .ok_or_else(|| DependencyError::FloatingGit {
380                    name: name.to_string(),
381                })?;
382            if !is_exact_commit(rev) {
383                return Err(DependencyError::MalformedRev {
384                    name: name.to_string(),
385                    rev: rev.to_string(),
386                });
387            }
388            // The preserved local checkout: an explicit `path`, else the
389            // conventional vendor directory keyed by name + commit.
390            let checkout = match &detail.path {
391                Some(p) => project_root.join(p),
392                None => project_root
393                    .join(".logos-deps")
394                    .join(format!("{name}-{rev}")),
395            };
396            let root = checkout
397                .canonicalize()
398                .map_err(|_| DependencyError::Missing {
399                    name: name.to_string(),
400                    root: checkout,
401                })?;
402            return Ok(Some(ResolvedDep {
403                name: name.to_string(),
404                root,
405                source: DepSource::Git {
406                    url: url.clone(),
407                    rev: rev.to_string(),
408                },
409            }));
410        }
411        if let Some(p) = &detail.path {
412            let joined = project_root.join(p);
413            let root = joined
414                .canonicalize()
415                .map_err(|_| DependencyError::Missing {
416                    name: name.to_string(),
417                    root: joined,
418                })?;
419            return Ok(Some(ResolvedDep {
420                name: name.to_string(),
421                root,
422                source: DepSource::Path,
423            }));
424        }
425        if detail.version.is_some() {
426            // A detailed version-only dependency is a registry dependency —
427            // not linkable from the local closure.
428            return Ok(None);
429        }
430        Err(DependencyError::NotLinkable {
431            name: name.to_string(),
432            detail: "no path or git source".to_string(),
433        })
434    }
435}
436
437#[cfg(test)]
438#[path = "../../../../crates/logicaffeine_tests/unit/logicaffeine_cli/project/manifest/tests.rs"]
439mod tests;