-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmain.rs
314 lines (275 loc) · 9.4 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Copyright 2024 Oxide Computer Company
#![forbid(unsafe_code)]
use std::net::IpAddr;
use std::sync::atomic::AtomicBool;
use anyhow::Result;
use async_trait::async_trait;
use cli_builder::NewCli;
use generated_cli::CliConfig;
use oxide::context::Context;
use oxide::types::{IdpMetadataSource, IpRange, Ipv4Range, Ipv6Range};
mod cli_builder;
mod cmd_api;
mod cmd_auth;
mod cmd_completion;
mod cmd_disk;
mod cmd_docs;
mod cmd_instance;
mod cmd_version;
#[allow(unused_mut)]
#[allow(unused)] // TODO
#[allow(unused_must_use)] // TODO
#[allow(clippy::clone_on_copy)]
mod generated_cli;
#[async_trait]
pub trait RunnableCmd: Send + Sync {
async fn run(&self, ctx: &Context) -> Result<()>;
fn is_subtree() -> bool {
true
}
}
pub fn make_cli() -> NewCli<'static> {
NewCli::default()
.add_custom::<cmd_auth::CmdAuth>("auth")
.add_custom::<cmd_api::CmdApi>("api")
.add_custom::<cmd_docs::CmdDocs>("docs")
.add_custom::<cmd_version::CmdVersion>("version")
.add_custom::<cmd_disk::CmdDiskImport>("disk import")
.add_custom::<cmd_instance::CmdInstanceSerial>("instance serial")
.add_custom::<cmd_instance::CmdInstanceVnc>("instance vnc")
.add_custom::<cmd_instance::CmdInstanceFromImage>("instance from-image")
.add_custom::<cmd_completion::CmdCompletion>("completion")
}
#[tokio::main]
async fn main() {
env_logger::init();
let new_cli = make_cli();
// Spawn a task so we get this potentially chunky Future off the
// main thread's stack.
let result = tokio::spawn(async move { new_cli.run().await })
.await
.unwrap();
if let Err(e) = result {
eprintln!("{e}");
std::process::exit(1)
}
}
#[derive(Default)]
struct OxideOverride {
needs_comma: AtomicBool,
}
impl OxideOverride {
fn ip_range(matches: &clap::ArgMatches) -> anyhow::Result<IpRange> {
let first = matches.get_one::<IpAddr>("first").unwrap();
let last = matches.get_one::<IpAddr>("last").unwrap();
match (first, last) {
(IpAddr::V4(first), IpAddr::V4(last)) => {
let range = Ipv4Range::try_from(Ipv4Range::builder().first(*first).last(*last))?;
Ok(range.into())
}
(IpAddr::V6(first), IpAddr::V6(last)) => {
let range = Ipv6Range::try_from(Ipv6Range::builder().first(*first).last(*last))?;
Ok(range.into())
}
_ => anyhow::bail!(
"first and last must either both be ipv4 or ipv6 addresses".to_string()
),
}
}
}
impl CliConfig for OxideOverride {
fn item_success<T>(&self, value: &oxide::ResponseValue<T>)
where
T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug,
{
let s = serde_json::to_string_pretty(std::ops::Deref::deref(value))
.expect("failed to serialize return to json");
println!("{}", s);
}
fn item_error<T>(&self, _value: &oxide::Error<T>)
where
T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug,
{
eprintln!("error");
}
fn list_start<T>(&self)
where
T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug,
{
self.needs_comma
.store(false, std::sync::atomic::Ordering::Relaxed);
print!("[");
}
fn list_item<T>(&self, value: &T)
where
T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug,
{
let s = serde_json::to_string_pretty(&[value]).expect("failed to serialize result to json");
if self.needs_comma.load(std::sync::atomic::Ordering::Relaxed) {
print!(", {}", &s[4..s.len() - 2]);
} else {
print!("\n{}", &s[2..s.len() - 2]);
};
self.needs_comma
.store(true, std::sync::atomic::Ordering::Relaxed);
}
fn list_end_success<T>(&self)
where
T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug,
{
if self.needs_comma.load(std::sync::atomic::Ordering::Relaxed) {
println!("\n]");
} else {
println!("]");
}
}
fn list_end_error<T>(&self, _value: &oxide::Error<T>)
where
T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug,
{
self.list_end_success::<T>()
}
// Deal with all the operations that require an `IpPool` as input
fn execute_ip_pool_range_add(
&self,
matches: &clap::ArgMatches,
request: &mut oxide::builder::IpPoolRangeAdd,
) -> anyhow::Result<()> {
*request = request.to_owned().body(Self::ip_range(matches)?);
Ok(())
}
fn execute_ip_pool_range_remove(
&self,
matches: &clap::ArgMatches,
request: &mut oxide::builder::IpPoolRangeRemove,
) -> anyhow::Result<()> {
*request = request.to_owned().body(Self::ip_range(matches)?);
Ok(())
}
fn execute_ip_pool_service_range_add(
&self,
matches: &clap::ArgMatches,
request: &mut oxide::builder::IpPoolServiceRangeAdd,
) -> anyhow::Result<()> {
*request = request.to_owned().body(Self::ip_range(matches)?);
Ok(())
}
fn execute_ip_pool_service_range_remove(
&self,
matches: &clap::ArgMatches,
request: &mut oxide::builder::IpPoolServiceRangeRemove,
) -> anyhow::Result<()> {
*request = request.to_owned().body(Self::ip_range(matches)?);
Ok(())
}
fn execute_saml_identity_provider_create(
&self,
matches: &clap::ArgMatches,
request: &mut oxide::builder::SamlIdentityProviderCreate,
) -> anyhow::Result<()> {
match matches
.get_one::<clap::Id>("idp_metadata_source")
.map(clap::Id::as_str)
{
Some("metadata-url") => {
let value = matches.get_one::<String>("metadata-url").unwrap();
*request = request.to_owned().body_map(|body| {
body.idp_metadata_source(IdpMetadataSource::Url { url: value.clone() })
});
}
Some("metadata-value") => {
let value = matches.get_one::<String>("metadata-value").unwrap();
*request = request.to_owned().body_map(|body| {
body.idp_metadata_source(IdpMetadataSource::Base64EncodedXml {
data: value.clone(),
})
});
}
_ => unreachable!("invalid value for idp_metadata_source group"),
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use clap::Command;
use expectorate::assert_contents;
use oxide::types::ByteCount;
use crate::make_cli;
// This is the real trait that we're going to tell people about
trait MyFromStr: Sized {
type Err;
fn my_from_str(value: &str) -> Result<Self, Self::Err>;
}
// This is the trait we implement by rote for a type that we are interested
// in.
// trait AutoRefFromStr: Sized {
// fn auto_ref_from_str(value: &str) -> Option<Self>;
// }
// Trait that **only** AutoRefFromStrTarget impls (twice).
trait AutoRefFromStrTargetTrait<T> {
fn auto_ref_from_str(self, value: &str) -> Option<T>;
}
// The struct that we'll either refer to directly or by "auto" reference.
struct AutoRefTarget<T> {
_phantom: std::marker::PhantomData<T>,
}
impl<T> AutoRefTarget<T> {
fn new() -> Self {
Self {
_phantom: std::marker::PhantomData,
}
}
}
impl<T: MyFromStr> AutoRefFromStrTargetTrait<T> for AutoRefTarget<T> {
fn auto_ref_from_str(self, value: &str) -> Option<T> {
T::my_from_str(value).ok()
}
}
impl<T: std::str::FromStr> AutoRefFromStrTargetTrait<T> for &AutoRefTarget<T> {
fn auto_ref_from_str(self, value: &str) -> Option<T> {
T::from_str(value).ok()
}
}
// this is the thing that may or may not exist
impl MyFromStr for oxide::types::ByteCount {
type Err = &'static str;
fn my_from_str(_value: &str) -> Result<Self, Self::Err> {
Ok(Self(42))
}
}
#[test]
fn test_autoref() {
let y = {
// this is what we're going to copy everywhere we use a type.
AutoRefTarget::<ByteCount>::new().auto_ref_from_str("900")
};
println!("{:?}", y)
}
#[test]
fn test_json_body_required() {
fn find_json_body_required(path: String, cmd: &Command) -> Vec<String> {
let mut ret = cmd
.get_subcommands()
.flat_map(|subcmd| {
find_json_body_required(format!("{} {}", path, subcmd.get_name()), subcmd)
})
.collect::<Vec<_>>();
if cmd
.get_arguments()
.any(|arg| arg.get_long() == Some("json-body") && arg.is_required_set())
{
ret.push(path);
}
ret
}
let cli = make_cli();
let cmd = cli.command();
let out = find_json_body_required("oxide".to_string(), cmd).join("\n");
// We want this list to shrink, not grow.
assert_contents("tests/data/json-body-required.txt", &out);
}
}