Skip to main content

meta_language/
project_data.rs

1//! Filesystem boundary for structured project data and explicit external JSON.
2//!
3//! Logical `.json` identities resolve to their converted `.lino` files. The
4//! decoder is the shared structured-data codec; these adapters neither parse
5//! programming languages nor change fixture identities or digest inputs.
6
7use std::fs;
8use std::path::{Path, PathBuf};
9
10use serde::de::DeserializeOwned;
11
12/// The requested storage format at a project or external data boundary.
13#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
14pub enum ProjectDataFormat {
15    /// Infer storage from the resolved extension, accepting legacy JSON.
16    #[default]
17    Auto,
18    /// Read exactly the requested path as external JSON, without alias lookup.
19    Json,
20    /// Read the corresponding Links Notation file.
21    Lino,
22}
23
24/// Resolve a logical JSON identity to its canonical stored data file.
25///
26/// Other extensions retain their exact path, including source and grammar
27/// files whose raw bytes form a checksum input.
28///
29/// # Errors
30/// Returns an error if both JSON and Links Notation storage exist.
31pub fn resolve_project_data_path(file: impl AsRef<Path>) -> Result<PathBuf, String> {
32    resolve_project_data_path_with_format(file, ProjectDataFormat::Auto)
33}
34
35/// Resolve storage with an explicit external JSON or Links Notation boundary.
36///
37/// # Errors
38/// Returns an error when automatic or Links Notation resolution finds both
39/// formats. Explicit JSON always preserves the requested path.
40pub fn resolve_project_data_path_with_format(
41    file: impl AsRef<Path>,
42    format: ProjectDataFormat,
43) -> Result<PathBuf, String> {
44    let logical = file.as_ref();
45    if format == ProjectDataFormat::Json {
46        return Ok(logical.to_path_buf());
47    }
48    let extension = logical.extension().and_then(|value| value.to_str());
49    let structured = matches!(extension, Some("json" | "lino"));
50    if format == ProjectDataFormat::Auto && !structured {
51        return Ok(logical.to_path_buf());
52    }
53    let (json, lino) = if structured {
54        (
55            logical.with_extension("json"),
56            logical.with_extension("lino"),
57        )
58    } else {
59        let mut json = logical.as_os_str().to_os_string();
60        json.push(".json");
61        let mut lino = logical.as_os_str().to_os_string();
62        lino.push(".lino");
63        (PathBuf::from(json), PathBuf::from(lino))
64    };
65    if json.exists() && lino.exists() {
66        return Err(format!(
67            "project data has duplicate JSON and LiNo storage: {}",
68            logical.display()
69        ));
70    }
71    if format == ProjectDataFormat::Lino
72        || extension == Some("lino")
73        || lino.exists()
74        || !json.exists()
75    {
76        Ok(lino)
77    } else {
78        Ok(json)
79    }
80}
81
82/// Read the exact resolved storage bytes for checksums or source processing.
83///
84/// # Errors
85/// Returns a storage conflict or filesystem read error with its physical path.
86pub fn read_project_file_bytes(file: impl AsRef<Path>) -> Result<Vec<u8>, String> {
87    let actual = resolve_project_data_path(file)?;
88    fs::read(&actual).map_err(|error| format!("{}: {error}", actual.display()))
89}
90
91/// Read project data through its logical identity into a host data structure.
92///
93/// The Links decoder preserves structure; conversion to `serde_json::Value`
94/// retains that type's existing map-order and Unicode interoperability limits.
95/// Use the codec's ordered API when those distinctions must stay lossless.
96///
97/// # Errors
98/// Returns a storage conflict, unsupported extension, read, decoding or host
99/// deserialization error. Malformed `LiNo` never falls back to JSON.
100pub fn read_project_data_file<T: DeserializeOwned>(file: impl AsRef<Path>) -> Result<T, String> {
101    read_project_data_file_with_format(file, ProjectDataFormat::Auto)
102}
103
104/// Read data with an explicitly chosen external JSON or `LiNo` representation.
105///
106/// # Errors
107/// Returns a storage conflict, unsupported format, read or decoding error.
108pub fn read_project_data_file_with_format<T: DeserializeOwned>(
109    file: impl AsRef<Path>,
110    format: ProjectDataFormat,
111) -> Result<T, String> {
112    let actual = resolve_project_data_path_with_format(file, format)?;
113    let encoding = match format {
114        ProjectDataFormat::Auto => match actual.extension().and_then(|value| value.to_str()) {
115            Some("json") => ProjectDataFormat::Json,
116            Some("lino") => ProjectDataFormat::Lino,
117            _ => {
118                return Err(format!(
119                    "project data has an unsupported storage extension: {}",
120                    actual.display()
121                ));
122            }
123        },
124        encoding => encoding,
125    };
126    let text =
127        fs::read_to_string(&actual).map_err(|error| format!("{}: {error}", actual.display()))?;
128    match encoding {
129        ProjectDataFormat::Lino => {
130            let value = crate::structured_data_links::read_structured_data_lino(&text)
131                .map_err(|error| format!("{}: {error}", actual.display()))?;
132            serde_json::from_value(value).map_err(|error| format!("{}: {error}", actual.display()))
133        }
134        ProjectDataFormat::Json => {
135            serde_json::from_str(&text).map_err(|error| format!("{}: {error}", actual.display()))
136        }
137        ProjectDataFormat::Auto => unreachable!("automatic storage is resolved above"),
138    }
139}