Skip to content

Commit

Permalink
impl FromStr, Serialize and Deserialize traits for ImageName (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
termoshtt authored Jul 26, 2024
1 parent 1fabf35 commit 4c95748
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
2 changes: 1 addition & 1 deletion ocipkg/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ log = "0.4.22"
maplit = "1.0.2"
oci-spec = "0.6.7"
regex = "1.10.5"
serde = "1.0.204"
serde = { version = "1.0.204", features = ["derive"] }
serde_json = "1.0.120"
sha2 = "0.10.8"
tar = "0.4.41"
Expand Down
49 changes: 47 additions & 2 deletions ocipkg/src/image_name.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use crate::distribution::{Name, Reference};
use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::{
fmt,
path::{Path, PathBuf},
str::FromStr,
};
use url::Url;

Expand Down Expand Up @@ -163,8 +165,9 @@ impl Default for ImageName {
}
}

impl ImageName {
pub fn parse(name: &str) -> Result<Self> {
impl FromStr for ImageName {
type Err = anyhow::Error;
fn from_str(name: &str) -> Result<Self> {
let (hostname, name) = name
.split_once('/')
.unwrap_or(("registry-1.docker.io", name));
Expand All @@ -181,6 +184,31 @@ impl ImageName {
reference: Reference::new(reference)?,
})
}
}

impl Serialize for ImageName {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_string())
}
}

impl<'de> Deserialize<'de> for ImageName {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
ImageName::parse(&s).map_err(serde::de::Error::custom)
}
}

impl ImageName {
pub fn parse(name: &str) -> Result<Self> {
Self::from_str(name)
}

/// URL for OCI distribution API endpoint
pub fn registry_url(&self) -> Result<Url> {
Expand Down Expand Up @@ -333,4 +361,21 @@ mod test {
)?;
Ok(())
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct SerializeTest {
name: ImageName,
}

#[test]
fn serialize() {
let input = SerializeTest {
name: ImageName::parse("localhost:5000/test_repo:latest").unwrap(),
};
let json = serde_json::to_string(&input).unwrap();
assert_eq!(json, r#"{"name":"localhost:5000/test_repo:latest"}"#);

let output: SerializeTest = serde_json::from_str(&json).unwrap();
assert_eq!(input, output)
}
}

0 comments on commit 4c95748

Please sign in to comment.