Skip to main content

oci_core/core/
reference.rs

1use std::fmt;
2use std::str::FromStr;
3
4use crate::errors::OciError;
5
6#[derive(Debug, Clone, PartialEq, Eq, Hash)]
7pub struct Reference {
8    pub registry: String,
9    pub repository: String,
10    pub tag: Option<String>,
11    pub digest: Option<String>,
12}
13
14impl Reference {
15    pub fn parse(input: &str) -> Result<Self, OciError> {
16        let remainder = input.trim();
17        if remainder.is_empty() {
18            return Err(OciError::Reference("Empty image reference".to_string()));
19        }
20
21        let (registry, rest) = if remainder.contains('/')
22            && remainder
23                .split('/')
24                .next()
25                .map(|seg| seg.contains('.') || seg.contains(':') || seg == "localhost")
26                .unwrap_or(false)
27        {
28            let mut parts = remainder.splitn(2, '/');
29            (
30                parts.next().unwrap().to_string(),
31                parts.next().unwrap_or_default().to_string(),
32            )
33        } else {
34            ("registry-1.docker.io".to_string(), remainder.to_string())
35        };
36
37        let mut repository = rest;
38        let mut tag = None;
39        let mut digest = None;
40
41        if let Some(idx) = repository.rfind('@') {
42            digest = Some(repository[idx + 1..].to_string());
43            repository = repository[..idx].to_string();
44        }
45
46        if let Some(idx) = repository.rfind(':') {
47            if repository[idx + 1..]
48                .chars()
49                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
50            {
51                tag = Some(repository[idx + 1..].to_string());
52                repository = repository[..idx].to_string();
53            }
54        }
55
56        if repository.is_empty() {
57            return Err(OciError::Reference(
58                "Repository missing from reference".to_string(),
59            ));
60        }
61
62        if registry == "registry-1.docker.io" && !repository.contains('/') {
63            repository = format!("library/{}", repository);
64        }
65
66        Ok(Self {
67            registry,
68            repository,
69            tag,
70            digest,
71        })
72    }
73
74    pub fn registry_host(&self) -> &str {
75        &self.registry
76    }
77}
78
79impl FromStr for Reference {
80    type Err = OciError;
81
82    fn from_str(s: &str) -> Result<Self, Self::Err> {
83        Self::parse(s)
84    }
85}
86
87impl fmt::Display for Reference {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        let mut out = format!("{}/{}", self.registry, self.repository);
90        if let Some(tag) = &self.tag {
91            out.push(':');
92            out.push_str(tag);
93        }
94        if let Some(digest) = &self.digest {
95            out.push('@');
96            out.push_str(digest);
97        }
98        write!(f, "{}", out)
99    }
100}