use std::io::Write as _;
use shep_core::dogs::manifest::{DogDependency, Manifest, Permission, Verb};
use shep_core::dogs::{
MANIFEST_FLAG, SCHEMA_FLAG, SHEP_CHANNEL_KEY, SHEP_PROTOCOL_KEY, VERSION_FLAG,
};
use super::DogConfig;
#[cfg(feature = "schema")]
use super::{config_schema, config_schema_with_sheep};
#[cfg(feature = "schema")]
pub fn probe<T: DogConfig + schemars::JsonSchema>(name: &str, version: &str) {
Probe::new(name, version).answer::<T>();
}
#[cfg(feature = "schema")]
pub fn probe_with_sheep<T, S>(name: &str, version: &str)
where
T: DogConfig + schemars::JsonSchema,
S: DogConfig + schemars::JsonSchema,
{
Probe::new(name, version).answer_with_sheep::<T, S>();
}
#[cfg(not(feature = "schema"))]
pub fn probe<T: DogConfig>(name: &str, version: &str) {
Probe::new(name, version).answer::<T>();
}
#[cfg(not(feature = "schema"))]
pub fn probe_with_sheep<T: DogConfig, S: DogConfig>(name: &str, version: &str) {
Probe::new(name, version).answer_with_sheep::<T, S>();
}
#[derive(Debug, Clone)]
#[must_use = "a Probe answers nothing until `answer` is called"]
pub struct Probe<'a> {
name: &'a str,
version: &'a str,
channel: bool,
permissions: Vec<Permission>,
verb: Option<Verb>,
dogs: Vec<DogDependency>,
shep: Option<String>,
defaults: Option<String>,
validate: bool,
launch: bool,
}
impl<'a> Probe<'a> {
pub const fn new(name: &'a str, version: &'a str) -> Self {
Self {
name,
version,
channel: false,
permissions: Vec::new(),
verb: None,
dogs: Vec::new(),
shep: None,
defaults: None,
validate: false,
launch: false,
}
}
pub const fn ask_for_channel(mut self) -> Self {
self.channel = true;
self
}
pub fn permission(mut self, permission: Permission) -> Self {
self.permissions.push(permission);
self
}
pub fn verb(mut self, verb: Verb) -> Self {
self.verb = Some(verb);
self
}
pub fn depends_on_dog(mut self, dependency: DogDependency) -> Self {
self.dogs.push(dependency);
self
}
pub fn depends_on_shep(mut self, minimum: impl Into<String>) -> Self {
self.shep = Some(minimum.into());
self
}
pub fn defaults(mut self, toml: impl Into<String>) -> Self {
self.defaults = Some(toml.into());
self
}
pub const fn validate(mut self) -> Self {
self.validate = true;
self
}
pub const fn launch(mut self) -> Self {
self.launch = true;
self
}
#[cfg(feature = "schema")]
pub fn answer<T: DogConfig + schemars::JsonSchema>(self) {
self.answering(|| Some(config_schema::<T>().into()));
}
#[cfg(feature = "schema")]
pub fn answer_with_sheep<T, S>(self)
where
T: DogConfig + schemars::JsonSchema,
S: DogConfig + schemars::JsonSchema,
{
self.answering(|| Some(config_schema_with_sheep::<T, S>().into()));
}
#[cfg(not(feature = "schema"))]
pub fn answer<T: DogConfig>(self) {
self.answering(|| None);
}
#[cfg(not(feature = "schema"))]
pub fn answer_with_sheep<T: DogConfig, S: DogConfig>(self) {
self.answer::<T>();
}
fn answering(self, schema: impl FnOnce() -> Option<serde_json::Value>) {
if let Some(text) = self.reply(first_argument().as_deref(), schema) {
answer(&text);
}
}
fn reply(
&self,
flag: Option<&str>,
schema: impl FnOnce() -> Option<serde_json::Value>,
) -> Option<String> {
match flag? {
VERSION_FLAG => Some(self.version_answer()),
SCHEMA_FLAG => Some(schema().map(|schema| rendered(&schema)).unwrap_or_default()),
MANIFEST_FLAG => Some(rendered(&self.manifest(schema()))),
_ => None,
}
}
fn manifest(&self, settings: Option<serde_json::Value>) -> Manifest {
let mut manifest = Manifest::new(self.name, self.version, crate::PROTOCOL_VERSION);
manifest.channel = self.channel;
manifest.settings = settings;
manifest.defaults.clone_from(&self.defaults);
manifest.permissions.clone_from(&self.permissions);
manifest.verb.clone_from(&self.verb);
manifest.depends.dogs.clone_from(&self.dogs);
manifest.depends.shep.clone_from(&self.shep);
manifest.validate = self.validate;
manifest.launch = self.launch;
manifest
}
fn version_answer(&self) -> String {
let mut text = format!(
"{} {}\n{SHEP_PROTOCOL_KEY}: {}\n",
self.name,
self.version,
crate::PROTOCOL_VERSION
);
if self.channel {
text.push_str(&format!("{SHEP_CHANNEL_KEY}: true\n"));
}
text
}
}
fn first_argument() -> Option<String> {
std::env::args().nth(1)
}
fn answer(text: &str) -> ! {
let mut stdout = std::io::stdout();
let _ = write!(stdout, "{text}");
let _ = stdout.flush();
std::process::exit(0);
}
fn rendered(value: &impl serde::Serialize) -> String {
let json = serde_json::to_string_pretty(value).expect("these always serialize to JSON");
format!("{json}\n")
}
#[cfg(all(test, feature = "schema"))]
mod manifest_tests;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_version_answer_parses_with_the_shepherds_own_parser() {
let answer = Probe::new("shep-otel", "0.1.3").version_answer();
let parsed = shep_core::dogs::parse_version_answer(&answer)
.expect("the answer shep's own parser cannot read is the bug this pins");
assert_eq!(parsed.version, "0.1.3");
assert_eq!(parsed.protocol, Some(crate::PROTOCOL_VERSION));
assert!(
!parsed.channel,
"a dog that asks for nothing asks for nothing"
);
}
#[test]
fn a_channel_ask_reaches_the_shepherds_own_parser() {
let answer = Probe::new("shep-otel", "0.1.3")
.ask_for_channel()
.version_answer();
let parsed = shep_core::dogs::parse_version_answer(&answer).unwrap();
assert!(parsed.channel, "{answer}");
assert_eq!(parsed.protocol, Some(crate::PROTOCOL_VERSION));
}
}