use core::fmt;
#[cfg(feature = "schema")]
mod dog_wide;
mod error;
mod identity;
mod link;
mod long_action;
mod pane;
mod probes;
mod runtime;
mod section;
#[cfg(feature = "schema")]
mod sheep_settings;
mod startup;
mod stop;
mod validate;
#[cfg(feature = "clap")]
mod verb_clap;
pub use error::ShepherdError;
pub use identity::DogIdentity;
pub use long_action::{ActionDone, ActionId, DONE_KIND, LongActionError};
pub use pane::pane_answer;
pub use probes::{Probe, probe, probe_with_sheep};
pub use runtime::DogRuntime;
pub use section::{SectionError, parse_section};
use serde::de::DeserializeOwned;
#[cfg(feature = "schema")]
pub use sheep_settings::{ServedSheepError, SheepSettingsReadError};
use shep_core::config::DogTable;
pub use shep_core::dogs::manifest::{
DogDependency, Manifest, Permission, Serves, Subcommand, Verb,
};
pub use shep_core::dogs::pane::{
Destructive, Field, Fields, PANE_ACTION, Pane, PaneAction, Row, Section, Table,
};
pub use shep_core::dogs::validate::{Proposed, VALIDATE_ACTION, Verdict};
pub use shep_core::dogs::{DOG_WIDE_KEY, SECRET_KEY, SHEEP_SCHEMA_KEY};
pub use shep_macros::dog_config;
pub use startup::{DogAction, HomeError, PRINT_CONFIG_FLAG, UsageError, parse_args, resolve_paths};
pub use stop::{Interrupted, Stop, StopRequest};
pub use validate::validate_answer;
#[cfg(feature = "clap")]
pub use verb_clap::{FromClap, VerbClapError, render_examples};
pub trait DogConfig {}
#[cfg(feature = "schema")]
pub fn config_schema<T: DogConfig + schemars::JsonSchema>() -> schemars::Schema {
schemars::SchemaGenerator::default().into_root_schema_for::<T>()
}
#[cfg(feature = "schema")]
pub fn config_schema_with_sheep<T, S>() -> schemars::Schema
where
T: DogConfig + schemars::JsonSchema,
S: DogConfig + schemars::JsonSchema,
{
let mut generator = schemars::SchemaGenerator::default();
let sheep = generator.subschema_for::<S>();
let mut schema = generator.into_root_schema_for::<T>();
schema.insert(SHEEP_SCHEMA_KEY.to_owned(), sheep.to_value());
schema
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SheepSettingsError {
dog: String,
sheep: String,
}
impl fmt::Display for SheepSettingsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"the [app.dogs.{}] table on {} does not fit this dog's settings",
self.dog, self.sheep
)
}
}
impl core::error::Error for SheepSettingsError {}
pub fn parse_sheep_settings<S: DeserializeOwned>(
dog: &str,
sheep: &str,
table: &DogTable,
) -> Result<S, SheepSettingsError> {
serde_json::from_value(serde_json::Value::Object(table.as_map().clone())).map_err(|_| {
SheepSettingsError {
dog: dog.to_string(),
sheep: sheep.to_string(),
}
})
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, Default, PartialEq, serde::Deserialize)]
#[serde(deny_unknown_fields, default)]
struct JobsSettings {
concurrency: u32,
}
fn table(pairs: impl IntoIterator<Item = (&'static str, serde_json::Value)>) -> DogTable {
DogTable::from(
pairs
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect::<serde_json::Map<String, serde_json::Value>>(),
)
}
#[test]
fn a_table_that_fits_parses() {
let table = table([("concurrency", serde_json::json!(2))]);
let settings: JobsSettings = parse_sheep_settings("jobs", "web", &table).unwrap();
assert_eq!(settings, JobsSettings { concurrency: 2 });
}
#[test]
fn a_wrongly_typed_field_is_refused_and_never_quotes_the_value() {
let table = table([("concurrency", serde_json::json!("hunter2"))]);
let err = parse_sheep_settings::<JobsSettings>("jobs", "web", &table).unwrap_err();
assert_eq!(
err.to_string(),
"the [app.dogs.jobs] table on web does not fit this dog's settings"
);
assert!(!err.to_string().contains("hunter2"));
assert!(!format!("{err:?}").contains("hunter2"));
}
#[test]
fn an_unknown_key_is_refused_and_never_quotes_the_value() {
let table = table([
("concurrency", serde_json::json!(2)),
("token", serde_json::json!("hunter2")),
]);
let err = parse_sheep_settings::<JobsSettings>("jobs", "web", &table).unwrap_err();
assert_eq!(
err.to_string(),
"the [app.dogs.jobs] table on web does not fit this dog's settings"
);
assert!(!err.to_string().contains("hunter2"));
assert!(!format!("{err:?}").contains("hunter2"));
}
#[test]
fn every_pane_type_is_named_through_the_client() {
let pane = Pane::new()
.fields("host", [("VRAM", "20 GiB")])
.table("models", ["MODEL"], [Row::new("qwen3-32b", ["qwen3-32b"])])
.row_action("revoke", "Revoke lease", Destructive::Yes)
.action("pause", "Pause the board", Destructive::No);
let Section::Fields(fields) = &pane.sections[0] else {
panic!("the first section is a fields section");
};
let Section::Table(table) = &pane.sections[1] else {
panic!("the second section is a table section");
};
assert_eq!(PANE_ACTION, "shep.pane");
assert_eq!(fields.fields[0].label, "VRAM");
assert_eq!(table.rows[0].key, "qwen3-32b");
assert_eq!(table.row_actions[0].action, "revoke");
assert_eq!(pane.actions[0].label, "Pause the board");
assert!(pane.body().is_ok());
}
#[cfg(feature = "schema")]
mod schema {
use super::*;
#[dog_config]
#[derive(schemars::JsonSchema)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct Webhook {
#[shep(secret)]
url: String,
channel: String,
}
#[dog_config]
#[derive(schemars::JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
enum Sink {
Discord {
#[shep(secret)]
url: String,
quiet: bool,
},
Slack {
#[shep(secret)]
url: String,
},
}
#[dog_config]
#[derive(schemars::JsonSchema)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct Renamed {
#[shep(secret)]
#[serde(rename = "webhook_url")]
url: String,
}
#[dog_config]
#[derive(schemars::JsonSchema)]
#[serde(tag = "kind", rename_all_fields = "SCREAMING-KEBAB-CASE")]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
enum RenamedFields {
One {
#[shep(secret)]
api_token: String,
},
}
#[derive(schemars::JsonSchema)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct Inner {
token: String,
}
#[dog_config]
#[derive(schemars::JsonSchema)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct Outer {
#[shep(secret)]
token: String,
inner: Inner,
}
#[dog_config]
#[derive(schemars::JsonSchema)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct NestedSink {
#[shep(secret)]
url: String,
quiet: bool,
}
#[dog_config]
#[derive(schemars::JsonSchema)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct Host {
sinks: std::collections::BTreeMap<String, NestedSink>,
}
#[test]
fn a_secret_field_carries_the_marker_and_a_plain_one_does_not() {
let schema = config_schema::<Webhook>();
let props = schema
.as_value()
.get("properties")
.expect("a derived struct schema has properties");
assert_eq!(
props.get("url").and_then(|url| url.get(SECRET_KEY)),
Some(&serde_json::Value::Bool(true)),
"the marked field carries the marker"
);
assert_eq!(
props.get("channel").and_then(|it| it.get(SECRET_KEY)),
None,
"the unmarked field carries nothing"
);
}
#[test]
fn the_extension_key_is_the_one_shep_core_publishes() {
let schema = config_schema::<Webhook>();
assert_eq!(
schema
.as_value()
.pointer(&format!("/properties/url/{SECRET_KEY}")),
Some(&serde_json::Value::Bool(true)),
"`shep-macros` writes `{SECRET_KEY}` verbatim and has no way to \
name this constant"
);
}
#[test]
fn a_marker_reaches_every_variant_of_a_tagged_enum_and_no_plain_field() {
let schema = config_schema::<Sink>();
let variants = schema
.as_value()
.get("oneOf")
.and_then(|it| it.as_array())
.expect("a tagged enum is a oneOf");
assert_eq!(variants.len(), 2);
for variant in variants {
let props = variant
.get("properties")
.expect("each variant carries its own properties");
assert_eq!(
props.get("url").and_then(|url| url.get(SECRET_KEY)),
Some(&serde_json::Value::Bool(true)),
"every marked occurrence is marked"
);
assert_eq!(
props.get("quiet").and_then(|it| it.get(SECRET_KEY)),
None,
"a plain field in the same variant carries nothing"
);
}
}
#[test]
fn a_rename_moves_the_marker_onto_the_renamed_property() {
let renamed = config_schema::<Renamed>();
let renamed = renamed.as_value();
assert_eq!(
renamed.pointer("/properties/webhook_url/x-shep-secret"),
Some(&serde_json::Value::Bool(true)),
"`#[serde(rename)]` renames the property the mark is on"
);
assert_eq!(
renamed.pointer("/properties/url"),
None,
"nothing is left under the Rust identifier"
);
let fields = config_schema::<RenamedFields>();
assert_eq!(
fields
.as_value()
.pointer("/oneOf/0/properties/API-TOKEN/x-shep-secret"),
Some(&serde_json::Value::Bool(true)),
"`rename_all_fields` does the same to a variant's field"
);
}
#[test]
fn a_nested_types_marked_field_is_marked_in_the_hosts_schema() {
let schema = config_schema::<Host>();
let schema = schema.as_value();
assert_eq!(
schema.pointer("/$defs/NestedSink/properties/url/x-shep-secret"),
Some(&serde_json::Value::Bool(true)),
"the nested credential carries the marker through the map"
);
assert_eq!(
schema.pointer("/$defs/NestedSink/properties/quiet/x-shep-secret"),
None,
"its plain neighbour carries nothing"
);
}
#[test]
fn a_like_named_property_of_a_nested_type_is_left_plain() {
let schema = config_schema::<Outer>();
let schema = schema.as_value();
assert_eq!(
schema.pointer("/properties/token/x-shep-secret"),
Some(&serde_json::Value::Bool(true)),
"the root's own marked field carries the marker"
);
assert_eq!(
schema.pointer("/$defs/Inner/properties/token/x-shep-secret"),
None,
"a stranger that shares the name is not the marked field"
);
}
#[dog_config]
#[derive(schemars::JsonSchema)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct JobsConfig {
channel: String,
}
#[dog_config]
#[derive(schemars::JsonSchema)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct JobsSheepSettings {
concurrency: u32,
#[shep(secret)]
api_key: String,
hours: WorkingHours,
}
#[dog_config]
#[derive(schemars::JsonSchema)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct WorkingHours {
start: String,
}
fn sheep_def_name(schema: &serde_json::Value) -> &str {
schema
.pointer(&format!("/{SHEEP_SCHEMA_KEY}/$ref"))
.and_then(serde_json::Value::as_str)
.and_then(|r| r.strip_prefix("#/$defs/"))
.expect("the sheep key holds a $ref into $defs")
}
#[test]
fn the_combined_schema_carries_a_sheep_ref_that_resolves_in_root_defs() {
let schema = config_schema_with_sheep::<JobsConfig, JobsSheepSettings>();
let schema = schema.as_value();
let def_name = sheep_def_name(schema);
assert!(
schema.pointer(&format!("/$defs/{def_name}")).is_some(),
"the sheep key's $ref names a definition in the root's own $defs"
);
}
#[test]
fn a_secret_field_of_the_sheep_type_is_marked_in_the_resolved_schema() {
let schema = config_schema_with_sheep::<JobsConfig, JobsSheepSettings>();
let schema = schema.as_value();
let def_name = sheep_def_name(schema);
assert_eq!(
schema.pointer(&format!(
"/$defs/{def_name}/properties/api_key/{SECRET_KEY}"
)),
Some(&serde_json::Value::Bool(true)),
"the sheep type's marked field carries the marker, exactly as a root field does"
);
assert_eq!(
schema.pointer(&format!(
"/$defs/{def_name}/properties/concurrency/{SECRET_KEY}"
)),
None,
"its plain neighbour carries nothing"
);
}
#[test]
fn a_struct_nested_inside_the_sheep_type_resolves_in_root_defs_too() {
let schema = config_schema_with_sheep::<JobsConfig, JobsSheepSettings>();
let schema = schema.as_value();
let def_name = sheep_def_name(schema);
let hours = schema
.pointer(&format!("/$defs/{def_name}/properties/hours/$ref"))
.and_then(serde_json::Value::as_str)
.and_then(|r| r.strip_prefix("#/$defs/"))
.expect("the nested field holds a $ref into $defs");
assert!(
schema
.pointer(&format!("/$defs/{hours}/properties/start"))
.is_some(),
"a type nested inside the sheep type is hoisted into the same $defs, \
so lookout can flatten it"
);
}
#[test]
fn the_plain_schema_carries_no_sheep_key() {
let with_sheep = config_schema_with_sheep::<JobsConfig, JobsSheepSettings>();
let plain = config_schema::<JobsConfig>();
assert!(with_sheep.as_value().get(SHEEP_SCHEMA_KEY).is_some());
assert_eq!(
plain.as_value().get(SHEEP_SCHEMA_KEY),
None,
"config_schema stays exactly what it was: no sheep key"
);
}
}
}