Skip to main content

artifactize_core/monitor/model/
node_id.rs

1//! Validated tree identities and their typed navigation target.
2use super::Target;
3use std::{fmt, ops::Deref, str::FromStr};
4
5#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
6pub struct NodeId {
7    text: String,
8    target: Target,
9}
10impl NodeId {
11    pub fn artifact(id: crate::types::ArtifactName) -> Self {
12        Self {
13            text: format!("a:{id}"),
14            target: Target::Artifact(id),
15        }
16    }
17    pub fn eval(id: crate::types::EvalId) -> Self {
18        Self {
19            text: format!("e:{id}"),
20            target: Target::Eval(id),
21        }
22    }
23    pub fn run(id: &crate::types::RunId) -> Self {
24        Self {
25            text: format!("run:{id}"),
26            target: Target::Run,
27        }
28    }
29    pub fn as_str(&self) -> &str {
30        &self.text
31    }
32}
33impl FromStr for NodeId {
34    type Err = String;
35    fn from_str(text: &str) -> Result<Self, Self::Err> {
36        let (kind, id) = text.split_once(':').ok_or("Invalid tree node ID.")?;
37        match kind {
38            "a" => id.parse().map(Self::artifact),
39            "e" => id.parse().map(Self::eval),
40            "run" => id.parse::<crate::types::RunId>().map(|id| Self::run(&id)),
41            _ => Err("Invalid tree node ID.".into()),
42        }
43    }
44}
45impl Deref for NodeId {
46    type Target = str;
47    fn deref(&self) -> &str {
48        self.as_str()
49    }
50}
51impl fmt::Display for NodeId {
52    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
53        formatter.write_str(self.as_str())
54    }
55}
56impl PartialEq<str> for NodeId {
57    fn eq(&self, other: &str) -> bool {
58        self.as_str() == other
59    }
60}
61impl PartialEq<&str> for NodeId {
62    fn eq(&self, other: &&str) -> bool {
63        self.as_str() == *other
64    }
65}
66impl From<NodeId> for String {
67    fn from(id: NodeId) -> Self {
68        id.text
69    }
70}
71impl From<&NodeId> for Target {
72    fn from(id: &NodeId) -> Self {
73        id.target.clone()
74    }
75}