|
1 | 1 | /*! |
2 | | -# Introduction |
| 2 | +# Multicall Binary for schnauzer |
3 | 3 |
|
4 | | -schnauzer is called by sundog as a setting generator. |
5 | | -Its sole parameter is the name of the setting to generate. |
6 | | -
|
7 | | -The setting we're generating is expected to have a metadata key already set: "template". |
8 | | -"template" is an arbitrary string with mustache template variables that reference other settings. |
| 4 | +This binary serves as both schnauzer (v1) and schnauzer-v2 based on how it's invoked. |
| 5 | +The dispatch mechanism checks argv[0] to determine which tool to run. |
9 | 6 |
|
10 | | -For example, if we're generating "settings.x" and we have template "foo-{{ settings.bar }}", we look up the value of "settings.bar" in the API. |
11 | | -If the returned value is "baz", our generated value will be "foo-baz". |
| 7 | +schnauzer is called by sundog as a setting generator. |
| 8 | +schnauzer-v2 is a more advanced settings generator for rendering handlebars templates. |
12 | 9 |
|
13 | | -(The name "schnauzer" comes from the fact that Schnauzers are search and rescue dogs (similar to this search and replace task) and because they have mustaches.) |
| 10 | +(The name "schnauzer" comes from the fact that Schnauzers are search and rescue dogs |
| 11 | +(similar to this search and replace task) and because they have mustaches.) |
14 | 12 | */ |
15 | 13 |
|
16 | | -use snafu::{ensure, OptionExt, ResultExt}; |
17 | | -use std::collections::HashMap; |
18 | | -use std::string::String; |
19 | | -use std::{env, process}; |
20 | | - |
21 | | -// Setting generators do not require dynamic socket paths at this moment. |
22 | | -const API_METADATA_URI_BASE: &str = "/metadata/"; |
23 | | - |
24 | | -mod error { |
25 | | - use http::StatusCode; |
26 | | - use snafu::Snafu; |
27 | | - |
28 | | - #[derive(Debug, Snafu)] |
29 | | - #[snafu(visibility(pub(super)))] |
30 | | - pub(super) enum Error { |
31 | | - #[snafu(display("Error {}ing to {}: {}", method, uri, source))] |
32 | | - APIRequest { |
33 | | - method: String, |
34 | | - uri: String, |
35 | | - #[snafu(source(from(apiclient::Error, Box::new)))] |
36 | | - source: Box<apiclient::Error>, |
37 | | - }, |
38 | | - |
39 | | - #[snafu(display("Error {} when {}ing to '{}': {}", code, method, uri, response_body))] |
40 | | - Response { |
41 | | - method: String, |
42 | | - uri: String, |
43 | | - code: StatusCode, |
44 | | - response_body: String, |
45 | | - }, |
46 | | - |
47 | | - #[snafu(display("Error deserializing to JSON: {}", source))] |
48 | | - DeserializeJson { source: serde_json::error::Error }, |
49 | | - |
50 | | - #[snafu(display("Error serializing to JSON '{}': {}", output, source))] |
51 | | - SerializeOutput { |
52 | | - output: String, |
53 | | - source: serde_json::error::Error, |
54 | | - }, |
55 | | - |
56 | | - #[snafu(display("Missing metadata {} for key: {}", meta, key))] |
57 | | - MissingMetadata { meta: String, key: String }, |
58 | | - |
59 | | - #[snafu(display("Metadata {} expected to be {}, got: {}", meta, expected, value))] |
60 | | - MetadataWrongType { |
61 | | - meta: String, |
62 | | - expected: String, |
63 | | - value: String, |
64 | | - }, |
65 | | - |
66 | | - #[snafu(display("Failed to build template registry: {}", source))] |
67 | | - BuildTemplateRegistry { source: schnauzer::v1::Error }, |
| 14 | +const SCHNAUZER_NAME: &str = "schnauzer"; |
| 15 | +const SCHNAUZER_V2_NAME: &str = "schnauzer-v2"; |
| 16 | +const DEFAULT_TOOL_NAME: &str = SCHNAUZER_V2_NAME; |
68 | 17 |
|
69 | | - #[snafu(display("Failed to get settings from API: {}", source))] |
70 | | - GetSettings { source: schnauzer::v1::Error }, |
| 18 | +use snafu::ResultExt; |
| 19 | +use std::env; |
71 | 20 |
|
72 | | - #[snafu(display( |
73 | | - "Failed to render setting '{}' from template '{}': {}", |
74 | | - setting_name, |
75 | | - template, |
76 | | - source |
77 | | - ))] |
78 | | - RenderTemplate { |
79 | | - setting_name: String, |
80 | | - template: String, |
81 | | - #[snafu(source(from(handlebars::RenderError, Box::new)))] |
82 | | - source: Box<handlebars::RenderError>, |
83 | | - }, |
84 | | - } |
| 21 | +/// Enumeration of available tools in this multicall binary |
| 22 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 23 | +enum ToolName { |
| 24 | + SchnauzerV1, |
| 25 | + SchnauzerV2, |
85 | 26 | } |
86 | | -type Result<T> = std::result::Result<T, error::Error>; |
87 | 27 |
|
88 | | -/// Returns the value of a metadata key for a given data key, erroring if the value is not a |
89 | | -/// string or is empty. |
90 | | -async fn get_metadata(key: &str, meta: &str) -> Result<String> { |
91 | | - let uri = &format!("{API_METADATA_URI_BASE}{meta}?keys={key}"); |
92 | | - let method = "GET"; |
93 | | - let (code, response_body) = apiclient::raw_request(constants::API_SOCKET, &uri, method, None) |
94 | | - .await |
95 | | - .context(error::APIRequestSnafu { method, uri })?; |
96 | | - ensure!( |
97 | | - code.is_success(), |
98 | | - error::ResponseSnafu { |
99 | | - method, |
100 | | - uri, |
101 | | - code, |
102 | | - response_body |
| 28 | +impl ToolName { |
| 29 | + /// Determine which tool to run based on the program name |
| 30 | + fn from_program_name(name: &str) -> Self { |
| 31 | + match name { |
| 32 | + SCHNAUZER_NAME => Self::SchnauzerV1, |
| 33 | + _ => Self::SchnauzerV2, |
103 | 34 | } |
104 | | - ); |
105 | | - |
106 | | - // Metadata responses are of the form `{"data_key": METADATA}` so we pull out the value. |
107 | | - let mut response_map: HashMap<String, serde_json::Value> = |
108 | | - serde_json::from_str(&response_body).context(error::DeserializeJsonSnafu)?; |
109 | | - let response_val = response_map |
110 | | - .remove(key) |
111 | | - .context(error::MissingMetadataSnafu { meta, key })?; |
112 | | - |
113 | | - // Ensure it's a non-empty string |
114 | | - let response_str = response_val |
115 | | - .as_str() |
116 | | - .with_context(|| error::MetadataWrongTypeSnafu { |
117 | | - meta, |
118 | | - expected: "string", |
119 | | - value: response_val.to_string(), |
120 | | - })?; |
121 | | - ensure!( |
122 | | - !response_str.is_empty(), |
123 | | - error::MissingMetadataSnafu { meta, key } |
124 | | - ); |
125 | | - Ok(response_str.to_string()) |
| 35 | + } |
126 | 36 | } |
127 | 37 |
|
128 | | -/// Print usage message. |
129 | | -fn usage() -> ! { |
130 | | - let program_name = env::args().next().unwrap_or_else(|| "program".to_string()); |
131 | | - eprintln!("Usage: {program_name} SETTING_KEY"); |
132 | | - process::exit(2); |
| 38 | +/// Extract program name from argv[0] for tool dispatch |
| 39 | +fn extract_program_name() -> String { |
| 40 | + env::args() |
| 41 | + .next() |
| 42 | + .and_then(|path| { |
| 43 | + std::path::Path::new(&path) |
| 44 | + .file_name() |
| 45 | + .and_then(|name| name.to_str()) |
| 46 | + .map(|s| s.to_string()) |
| 47 | + }) |
| 48 | + .unwrap_or_else(|| DEFAULT_TOOL_NAME.to_string()) |
133 | 49 | } |
134 | 50 |
|
135 | | -/// Parses args for the setting key name. |
136 | | -fn parse_args(mut args: env::Args) -> String { |
137 | | - let arg = args.nth(1).unwrap_or_else(|| "--help".to_string()); |
138 | | - if arg == "--help" || arg == "-h" { |
139 | | - usage() |
| 51 | +#[snafu::report] |
| 52 | +#[tokio::main] |
| 53 | +async fn main() -> Result<(), snafu::Whatever> { |
| 54 | + let program_name = extract_program_name(); |
| 55 | + let tool = ToolName::from_program_name(&program_name); |
| 56 | + |
| 57 | + // Dispatch to the appropriate CLI module |
| 58 | + match tool { |
| 59 | + ToolName::SchnauzerV1 => schnauzer::v1::cli::run() |
| 60 | + .await |
| 61 | + .whatever_context("schnauzer v1 execution failed"), |
| 62 | + ToolName::SchnauzerV2 => schnauzer::v2::cli::run() |
| 63 | + .await |
| 64 | + .whatever_context("schnauzer v2 execution failed"), |
140 | 65 | } |
141 | | - arg |
142 | | -} |
143 | | - |
144 | | -async fn run() -> Result<()> { |
145 | | - let setting_name = parse_args(env::args()); |
146 | | - |
147 | | - let registry = |
148 | | - schnauzer::v1::build_template_registry().context(error::BuildTemplateRegistrySnafu)?; |
149 | | - let template = get_metadata(&setting_name, "templates").await?; |
150 | | - let settings = schnauzer::v1::get_settings(constants::API_SOCKET) |
151 | | - .await |
152 | | - .context(error::GetSettingsSnafu)?; |
153 | | - |
154 | | - let setting = |
155 | | - registry |
156 | | - .render_template(&template, &settings) |
157 | | - .context(error::RenderTemplateSnafu { |
158 | | - setting_name, |
159 | | - template, |
160 | | - })?; |
161 | | - |
162 | | - // sundog expects JSON-serialized output so that many types can be represented, allowing the |
163 | | - // API model to use more accurate types. |
164 | | - let output = serde_json::to_string(&setting) |
165 | | - .context(error::SerializeOutputSnafu { output: &setting })?; |
166 | | - |
167 | | - println!("{output}"); |
168 | | - Ok(()) |
169 | 66 | } |
170 | 67 |
|
171 | | -// Returning a Result from main makes it print a Debug representation of the error, but with Snafu |
172 | | -// we have nice Display representations of the error, so we wrap "main" (run) and print any error. |
173 | | -// https://github.com/shepmaster/snafu/issues/110 |
174 | | -#[tokio::main] |
175 | | -async fn main() { |
176 | | - if let Err(e) = run().await { |
177 | | - eprintln!("{e}"); |
178 | | - process::exit(1); |
| 68 | +#[cfg(test)] |
| 69 | +mod tests { |
| 70 | + use super::*; |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn test_tool_name_from_program_name() { |
| 74 | + // Given Various program names |
| 75 | + // When Converting program names to ToolName enum |
| 76 | + // Then Should correctly identify schnauzer v1 vs v2 |
| 77 | + |
| 78 | + // Test schnauzer v1 detection |
| 79 | + assert_eq!( |
| 80 | + ToolName::from_program_name("schnauzer"), |
| 81 | + ToolName::SchnauzerV1 |
| 82 | + ); |
| 83 | + |
| 84 | + // Test schnauzer v2 detection |
| 85 | + assert_eq!( |
| 86 | + ToolName::from_program_name("schnauzer-v2"), |
| 87 | + ToolName::SchnauzerV2 |
| 88 | + ); |
| 89 | + |
| 90 | + // Test default behavior (unknown names default to v2) |
| 91 | + assert_eq!( |
| 92 | + ToolName::from_program_name("unknown"), |
| 93 | + ToolName::SchnauzerV2 |
| 94 | + ); |
| 95 | + assert_eq!(ToolName::from_program_name(""), ToolName::SchnauzerV2); |
179 | 96 | } |
180 | 97 | } |
0 commit comments