1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
//! Provides a metadata view on an ontology file (that has previously been validated).

use anyhow::{anyhow, bail, Context};
use field33_rdftk_core_temporary_fork::model::graph::GraphRef;
use field33_rdftk_iri_temporary_fork::IRI as RDFTK_IRI;
use harriet::{Directive, Statement, TurtleDocument};
use plow_graphify::document_to_graph;
use plow_ontology::constants::{
    REGISTRY_CANONICAL_PREFIX, REGISTRY_DEPENDENCY, REGISTRY_ONTOLOGY_FORMAT_VERSION,
    REGISTRY_PACKAGE_NAME, REGISTRY_PACKAGE_VERSION,
};
use serde::Serialize;
use std::borrow::Cow;
use std::collections::HashSet;
use std::str::FromStr;

use crate::package::PackageVersion;
use crate::resolve::Dependency;
use crate::version::SemanticVersion;

#[derive(Debug, Clone)]
pub enum OntologyFormatVersion {
    V1,
}

impl FromStr for OntologyFormatVersion {
    type Err = anyhow::Error;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "v1" => Ok(Self::V1),
            _ => Err(anyhow!(
                "Unrecognized ontology format version: {input}",
                input = input
            )),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct OntologyMetadata {
    #[serde(skip)]
    pub ontology_format_version: OntologyFormatVersion,
    pub root_prefix: String,
    pub canonical_prefix: String,
    pub dependencies: Vec<Dependency<SemanticVersion>>,
    pub package_name: String,
    pub package_version: SemanticVersion,
}

impl OntologyMetadata {
    fn get_stringy_ontology_annotation(
        rdf_graph: &GraphRef,
        root_prefix: &str,
        annotation_property_iri: &str,
    ) -> Result<String, anyhow::Error> {
        let rdf_factory = field33_rdftk_core_temporary_fork::simple::statement::statement_factory();
        let rdf_graph_borrow = rdf_graph.borrow();

        // We explicitly pass valid data, unwrap is safe here.
        #[allow(clippy::unwrap_used)]
        let annotations = rdf_graph_borrow
            .statements()
            .filter(|statement| {
                statement.subject()
                    == &rdf_factory.named_subject(RDFTK_IRI::from_str(root_prefix).unwrap().into())
                    && statement.predicate()
                        == &RDFTK_IRI::from_str(annotation_property_iri).unwrap().into()
            })
            .collect::<HashSet<_>>();

        let annotation = annotations.iter().next().ok_or_else(|| {
            anyhow!(
                "No annotation found for annotation property: `{}`",
                annotation_property_iri
            )
        })?;
        let literal = annotation
            .object()
            .as_literal()
            .ok_or_else(|| anyhow!("annotation value is not a literal"))?;

        Ok(literal.lexical_form().as_str().to_owned())
    }

    fn get_dependency_strings(
        rdf_graph: &GraphRef,
        root_prefix: &str,
    ) -> Result<Vec<String>, anyhow::Error> {
        let rdf_factory = field33_rdftk_core_temporary_fork::simple::statement::statement_factory();
        let rdf_graph_borrow = rdf_graph.borrow();

        // We explicitly pass valid data, unwrap is safe here.
        #[allow(clippy::unwrap_used)]
        let annotations = rdf_graph_borrow
            .statements()
            .filter(|statement| {
                statement.subject()
                    == &rdf_factory.named_subject(RDFTK_IRI::from_str(root_prefix).unwrap().into())
                    && statement.predicate()
                        == &RDFTK_IRI::from_str(REGISTRY_DEPENDENCY).unwrap().into()
            })
            .collect::<HashSet<_>>();

        let dependency_literals = annotations
            .into_iter()
            .map(|annotation| {
                let literal = annotation
                    .object()
                    .as_literal()
                    .ok_or_else(|| anyhow!("annotation value is not a literal"))?;

                Ok(literal.lexical_form().as_str().to_owned())
            })
            .collect::<Result<Vec<_>, anyhow::Error>>()?;

        Ok(dependency_literals)
    }

    fn get_ontology_format_version(
        rdf_graph: &GraphRef,
        root_prefix: &str,
    ) -> Result<OntologyFormatVersion, anyhow::Error> {
        let literal_value = Self::get_stringy_ontology_annotation(
            rdf_graph,
            root_prefix,
            REGISTRY_ONTOLOGY_FORMAT_VERSION,
        )?;
        OntologyFormatVersion::from_str(&literal_value)
    }

    fn get_canonical_prefix(
        rdf_graph: &GraphRef,
        root_prefix: &str,
    ) -> Result<String, anyhow::Error> {
        let literal_value = Self::get_stringy_ontology_annotation(
            rdf_graph,
            root_prefix,
            REGISTRY_CANONICAL_PREFIX,
        )?;
        Ok(literal_value)
    }

    fn get_package_name(rdf_graph: &GraphRef, root_prefix: &str) -> Result<String, anyhow::Error> {
        let literal_value =
            Self::get_stringy_ontology_annotation(rdf_graph, root_prefix, REGISTRY_PACKAGE_NAME)?;
        Ok(literal_value)
    }

    fn get_package_version(
        rdf_graph: &GraphRef,
        root_prefix: &str,
    ) -> Result<SemanticVersion, anyhow::Error> {
        let literal_value = Self::get_stringy_ontology_annotation(
            rdf_graph,
            root_prefix,
            REGISTRY_PACKAGE_VERSION,
        )?;

        // We require that the version predicates which are fed to the resolver are either bare or exact but always complete.
        // This function ensures that this is the case.
        if let Ok(semver) = SemanticVersion::try_from(&literal_value) {
            let bare_and_complete = literal_value.replace('.', "").chars().all(char::is_numeric)
                && (literal_value.matches('.').count() == 2
                    && literal_value.split('.').count() == 3);

            if bare_and_complete {
                return Ok(semver);
            }
            bail!("Expected bare and complete version, got {literal_value}",);
        }
        bail!("Invalid version predicate {literal_value}",);
    }
}

pub fn get_root_prefix<'document>(
    document: &'document TurtleDocument,
) -> Option<&'document Cow<'document, str>> {
    let mut root_prefix_directive = None;
    for statement in &document.statements {
        if let Statement::Directive(Directive::Prefix(directive)) = statement {
            if directive.prefix.is_none() {
                root_prefix_directive = Some(directive);
            }
        }
    }

    root_prefix_directive.map(|n| &n.iri.iri)
}

impl TryFrom<&TurtleDocument<'_>> for OntologyMetadata {
    type Error = anyhow::Error;

    fn try_from<'document>(document: &TurtleDocument) -> Result<Self, Self::Error> {
        let rdf_graph = document_to_graph(document).context("Failed to parse turtle document")?;

        let root_prefix =
            get_root_prefix(document).ok_or_else(|| anyhow!("Unable to get root prefix"))?;

        let ontology_format_version = Self::get_ontology_format_version(&rdf_graph, root_prefix)?;

        let dependencies = Self::get_dependency_strings(&rdf_graph.clone(), root_prefix)?
            .iter()
            .map(|dep_string| Dependency::<SemanticVersion>::try_from(dep_string.as_str()))
            .collect::<Result<Vec<_>, anyhow::Error>>()?;

        Ok(Self {
            root_prefix: root_prefix.to_string(),
            ontology_format_version,
            canonical_prefix: Self::get_canonical_prefix(&rdf_graph, root_prefix)?,
            dependencies,
            package_name: Self::get_package_name(&rdf_graph, root_prefix)?,
            package_version: Self::get_package_version(&rdf_graph, root_prefix)?,
        })
    }
}

// Only one way conversion is allowed.
#[allow(clippy::from_over_into)]
impl Into<PackageVersion> for OntologyMetadata {
    fn into(self) -> PackageVersion {
        PackageVersion {
            package_name: self.package_name,
            version: self.package_version.to_string(),
        }
    }
}