use crate::command::{CommandExecutor, CommandOutput, DockerCommand};
use crate::error::Result;
use async_trait::async_trait;
#[derive(Debug, Clone)]
pub struct SwarmUnlockKeyResult {
pub key: Option<String>,
pub output: String,
}
impl SwarmUnlockKeyResult {
fn parse(output: &CommandOutput, quiet: bool) -> Self {
let stdout = output.stdout.trim();
let key = if quiet {
Some(stdout.to_string())
} else {
let mut found_key = None;
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.starts_with("SWMKEY-") {
found_key = Some(trimmed.to_string());
break;
}
}
found_key
};
Self {
key,
output: stdout.to_string(),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct SwarmUnlockKeyCommand {
quiet: bool,
rotate: bool,
pub executor: CommandExecutor,
}
impl SwarmUnlockKeyCommand {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn quiet(mut self) -> Self {
self.quiet = true;
self
}
#[must_use]
pub fn rotate(mut self) -> Self {
self.rotate = true;
self
}
fn build_args(&self) -> Vec<String> {
let mut args = vec!["swarm".to_string(), "unlock-key".to_string()];
if self.quiet {
args.push("--quiet".to_string());
}
if self.rotate {
args.push("--rotate".to_string());
}
args
}
}
#[async_trait]
impl DockerCommand for SwarmUnlockKeyCommand {
type Output = SwarmUnlockKeyResult;
fn get_executor(&self) -> &CommandExecutor {
&self.executor
}
fn get_executor_mut(&mut self) -> &mut CommandExecutor {
&mut self.executor
}
fn build_command_args(&self) -> Vec<String> {
self.build_args()
}
async fn execute(&self) -> Result<Self::Output> {
let args = self.build_args();
let output = self.execute_command(args).await?;
Ok(SwarmUnlockKeyResult::parse(&output, self.quiet))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_swarm_unlock_key_basic() {
let cmd = SwarmUnlockKeyCommand::new();
let args = cmd.build_args();
assert_eq!(args, vec!["swarm", "unlock-key"]);
}
#[test]
fn test_swarm_unlock_key_quiet() {
let cmd = SwarmUnlockKeyCommand::new().quiet();
let args = cmd.build_args();
assert!(args.contains(&"--quiet".to_string()));
}
#[test]
fn test_swarm_unlock_key_rotate() {
let cmd = SwarmUnlockKeyCommand::new().rotate();
let args = cmd.build_args();
assert!(args.contains(&"--rotate".to_string()));
}
#[test]
fn test_swarm_unlock_key_all_options() {
let cmd = SwarmUnlockKeyCommand::new().quiet().rotate();
let args = cmd.build_args();
assert_eq!(args, vec!["swarm", "unlock-key", "--quiet", "--rotate"]);
}
}