Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Annotation Builder #5071

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 65 additions & 1 deletion lib/config/src/package/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,33 @@ pub enum CommandAnnotations {
Raw(toml::Value),
}

/// Helper struct for building annotations
#[derive(Debug, Clone, Default)]
pub struct CommandAnnotationBuilder {
annotations: HashMap<String, toml::Value>,
}

impl CommandAnnotationBuilder {
/// Add an annotation, associating `key` to any serializable `value`.
pub fn add(
&mut self,
key: impl Into<String>,
value: impl serde::Serialize,
) -> Result<&mut Self, anyhow::Error> {
let key = key.into();
let value = toml::Value::try_from(value)?;

self.annotations.insert(key, value);

Ok(self)
}

/// Builds the added annotations into a [`toml::Value::Table`]
pub fn build(&self) -> toml::Value {
toml::Value::Table(toml::map::Map::from_iter(self.annotations.clone()))
}
}

/// Annotations on disk.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct FileCommandAnnotations {
Expand Down Expand Up @@ -965,7 +992,7 @@ pub enum ValidationError {

#[cfg(test)]
mod tests {
use std::fmt::Debug;
use std::{collections::HashSet, fmt::Debug};

use serde::{de::DeserializeOwned, Deserialize};
use toml::toml;
Expand Down Expand Up @@ -1488,4 +1515,41 @@ annotations = { file = "Runefile.yml", kind = "yaml" }

assert_eq!(round_tripped, original);
}

#[test]
fn create_command_annotations() -> Result<(), anyhow::Error> {
let command_annotations = CommandAnnotationBuilder::default()
.add(
"wasi",
CommandAnnotationBuilder::default()
.add("main-args", vec!["-w=/assets/config.toml", "-g=info"])?
.build(),
)?
.build();

let args = command_annotations
.as_table()
.unwrap()
.get("wasi")
.unwrap()
.as_table()
.unwrap()
.get("main-args")
.unwrap()
.as_array()
.unwrap()
.iter()
.map(|t| t.as_str().unwrap().to_string())
.collect::<HashSet<String>>();

assert_eq!(
args,
HashSet::from_iter(vec![
"-w=/assets/config.toml".to_string(),
"-g=info".to_string()
])
);

Ok(())
}
}
Loading