Skip to main content

artifactize_core/config/
authored_target.rs

1//! The validated spelling used for a definition's PATH and for editor operations.
2
3use super::{ArtifactKind, Target, Uri, validation};
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use std::{path::PathBuf, str::FromStr};
6
7/// The spelling in the definition, including a folder's trailing slash or a Live URI.
8/// Whether a folder is narrowed to an aspect depends on the separate `select` field.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct AuthoredTarget {
11    text: String,
12    target: Target,
13}
14
15impl AuthoredTarget {
16    pub fn as_str(&self) -> &str {
17        &self.text
18    }
19
20    pub(super) fn into_parts(self) -> (String, Target) {
21        (self.text, self.target)
22    }
23}
24
25impl FromStr for AuthoredTarget {
26    type Err = String;
27
28    fn from_str(text: &str) -> Result<Self, Self::Err> {
29        let target = if Uri::has_scheme(text) {
30            Target::Live(text.parse::<Uri>().map_err(|error| error.to_string())?)
31        } else if text == "./" {
32            Target::try_from(PathBuf::new()).expect("workspace root is relative")
33        } else {
34            let logical = text.strip_suffix('/').unwrap_or(text);
35            if logical.contains(':') {
36                return Err("Local paths must not contain ':'.".into());
37            }
38            if logical.is_empty() {
39                return Err("path must name a file or folder".into());
40            }
41            validation::path(logical)?;
42            let kind = if text.ends_with('/') {
43                ArtifactKind::Folder
44            } else {
45                ArtifactKind::File
46            };
47            Target::try_from(logical)
48                .and_then(|local| local.with_kind(kind, Vec::new()))
49                .map_err(|error| error.to_string())?
50        };
51        Ok(Self {
52            text: text.into(),
53            target,
54        })
55    }
56}
57
58impl Serialize for AuthoredTarget {
59    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
60        serializer.serialize_str(self.as_str())
61    }
62}
63
64impl<'de> Deserialize<'de> for AuthoredTarget {
65    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
66        String::deserialize(deserializer)?
67            .parse()
68            .map_err(serde::de::Error::custom)
69    }
70}