shapes_converter/shex_to_uml/
shex2uml_config.rs

1use std::{
2    env::{self, VarError},
3    fs, io,
4    path::{Path, PathBuf},
5};
6
7use iri_s::IriS;
8use serde::{Deserialize, Serialize};
9use shex_validation::ShExConfig;
10use srdf::RDFS_LABEL_STR;
11use thiserror::Error;
12
13/// Name of Environment variable where we search for plantuml JAR
14pub const PLANTUML: &str = "PLANTUML";
15
16pub const DEFAULT_REPLACE_IRI_BY_LABEL: bool = true;
17
18#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
19pub struct ShEx2UmlConfig {
20    pub plantuml_path: Option<PathBuf>,
21    pub annotation_label: Vec<IriS>,
22    pub replace_iri_by_label: Option<bool>,
23    pub shex: Option<ShExConfig>,
24}
25
26impl ShEx2UmlConfig {
27    pub fn new() -> ShEx2UmlConfig {
28        let plantuml_path = match env::var(PLANTUML) {
29            Ok(value) => Some(Path::new(value.as_str()).to_path_buf()),
30            Err(_) => None,
31        };
32        Self {
33            plantuml_path,
34            annotation_label: vec![IriS::new_unchecked(RDFS_LABEL_STR)],
35            replace_iri_by_label: None,
36            shex: Some(ShExConfig::default()),
37        }
38    }
39
40    pub fn shex_config(&self) -> ShExConfig {
41        match &self.shex {
42            None => ShExConfig::default(),
43            Some(sc) => sc.clone(),
44        }
45    }
46
47    pub fn replace_iri_by_label(&self) -> bool {
48        self.replace_iri_by_label
49            .unwrap_or(DEFAULT_REPLACE_IRI_BY_LABEL)
50    }
51
52    pub fn from_file(file_name: &str) -> Result<ShEx2UmlConfig, ShEx2UmlConfigError> {
53        let config_str =
54            fs::read_to_string(file_name).map_err(|e| ShEx2UmlConfigError::ReadingConfigError {
55                path_name: file_name.to_string(),
56                error: e,
57            })?;
58        toml::from_str::<ShEx2UmlConfig>(&config_str).map_err(|e| ShEx2UmlConfigError::TomlError {
59            path_name: file_name.to_string(),
60            error: e,
61        })
62    }
63
64    pub fn with_plantuml_path<P: AsRef<Path>>(mut self, path: P) -> Self {
65        self.plantuml_path = Some(path.as_ref().to_owned());
66        self
67    }
68}
69
70#[derive(Error, Debug)]
71pub enum ShEx2UmlConfigError {
72    #[error("Reading path {path_name:?} error: {error:?}")]
73    ReadingConfigError { path_name: String, error: io::Error },
74
75    #[error("Reading TOML from {path_name:?}. Error: {error:?}")]
76    TomlError {
77        path_name: String,
78        error: toml::de::Error,
79    },
80
81    #[error("Accessing environment variable {var_name}: {error}")]
82    EnvVarError { var_name: String, error: VarError },
83}
84
85impl Default for ShEx2UmlConfig {
86    fn default() -> Self {
87        Self::new()
88    }
89}