use std::ffi::{OsStr, OsString};
use std::fmt::Display;
use std::io::{self, Write};
use std::path::PathBuf;
use std::time::Duration;
use serde::de::DeserializeOwned;
use tempfile::NamedTempFile;
use crate::error::{Error, Result};
use crate::options::{Color, GlobalOptions, Secret};
use crate::values::{Values, ValuesFile};
#[derive(Debug, Default)]
pub(crate) struct Invocation {
pub(super) args: Vec<OsString>,
pub(super) env: Vec<(OsString, OsString)>,
pub(super) stdin: Option<Vec<u8>>,
#[allow(dead_code, reason = "held so the files outlive the process")]
temp_files: Vec<NamedTempFile>,
}
macro_rules! flags {
($inv:ident, $o:ident; $($kind:ident($flag:literal, $field:ident);)*) => {
$(flags!(@row $inv, $o, $kind, $flag, $field);)*
};
(@row $inv:ident, $o:ident, option, $flag:literal, $field:ident) => {
$inv.option($flag, $o.$field.as_ref())
};
(@row $inv:ident, $o:ident, number, $flag:literal, $field:ident) => {
$inv.number($flag, $o.$field.as_ref())
};
(@row $inv:ident, $o:ident, switch, $flag:literal, $field:ident) => {
$inv.switch($flag, $o.$field)
};
(@row $inv:ident, $o:ident, each, $flag:literal, $field:ident) => {
$inv.each($flag, &$o.$field)
};
}
pub(crate) use flags;
pub(crate) fn go_duration(duration: Duration) -> String {
if duration.subsec_nanos() == 0 {
format!("{}s", duration.as_secs())
} else if duration.subsec_nanos().is_multiple_of(1_000_000) {
format!("{}ms", duration.as_millis())
} else {
format!("{}ns", duration.as_nanos())
}
}
pub(crate) fn parse_json<T: DeserializeOwned>(command: &'static str, stdout: &str) -> Result<T> {
serde_json::from_str(without_registry_lines(stdout)).map_err(|e| Error::Parse {
command,
message: e.to_string(),
})
}
pub(crate) fn without_registry_lines(stdout: &str) -> &str {
let mut rest = stdout.trim_start();
while rest.starts_with("Pulled: ") || rest.starts_with("Digest: ") {
rest = rest
.split_once('\n')
.map_or("", |(_, after)| after)
.trim_start();
}
rest
}
impl Invocation {
pub(crate) fn arg(&mut self, arg: impl Into<OsString>) {
self.args.push(arg.into());
}
pub(crate) fn switch(&mut self, flag: &str, on: bool) {
if on {
self.arg(flag);
}
}
pub(crate) fn option<T: AsRef<OsStr> + ?Sized>(&mut self, flag: &str, value: Option<&T>) {
if let Some(value) = value {
self.arg(flag);
self.arg(value.as_ref());
}
}
pub(crate) fn number<T: Display>(&mut self, flag: &str, value: Option<&T>) {
if let Some(value) = value {
self.arg(flag);
self.arg(value.to_string());
}
}
pub(crate) fn each<T: AsRef<OsStr>>(&mut self, flag: &str, values: &[T]) {
for value in values {
self.arg(flag);
self.arg(value.as_ref());
}
}
pub(crate) fn equals(&mut self, flag: &str, value: Option<&str>) {
if let Some(value) = value {
self.arg(format!("{flag}={value}"));
}
}
pub(crate) fn timeout(&mut self, timeout: Option<Duration>) {
self.option("--timeout", timeout.map(go_duration).as_ref());
}
pub(crate) fn json_output(&mut self) {
self.arg("-o");
self.arg("json");
}
pub(crate) fn env(&mut self, key: &str, value: impl Into<OsString>) {
self.env.push((key.into(), value.into()));
}
fn env_option<T: Into<OsString>>(&mut self, key: &str, value: Option<T>) {
if let Some(value) = value {
self.env(key, value);
}
}
pub(crate) fn temp_file(&mut self, contents: &[u8]) -> Result<PathBuf> {
let mut temp = NamedTempFile::new()?;
temp.write_all(contents)?;
temp.flush()?;
let path = temp.path().to_path_buf();
self.temp_files.push(temp);
Ok(path)
}
pub(crate) fn globals(&mut self, o: &GlobalOptions) -> Result<()> {
flags! { self, o;
option("--kubeconfig", kubeconfig);
option("--kube-context", kube_context);
option("--namespace", namespace);
option("--kube-apiserver", kube_apiserver);
option("--kube-as-user", kube_as_user);
each("--kube-as-group", kube_as_group);
option("--kube-ca-file", kube_ca_file);
switch("--kube-insecure-skip-tls-verify", kube_insecure_skip_tls_verify);
option("--kube-tls-server-name", kube_tls_server_name);
number("--qps", qps);
number("--burst-limit", burst_limit);
switch("--debug", debug);
option("--registry-config", registry_config);
option("--repository-config", repository_config);
option("--repository-cache", repository_cache);
option("--content-cache", content_cache);
}
self.option("--color", o.color.map(Color::as_str).as_ref());
self.env_option("HELM_KUBETOKEN", o.kube_token.as_ref().map(Secret::expose));
self.env_option("HELM_CACHE_HOME", o.cache_home.as_deref());
self.env_option("HELM_CONFIG_HOME", o.config_home.as_deref());
self.env_option("HELM_DATA_HOME", o.data_home.as_deref());
self.env_option("HELM_DRIVER", o.driver.map(crate::options::Driver::as_str));
self.env_option(
"HELM_DRIVER_SQL_CONNECTION_STRING",
o.driver_sql_connection_string.as_ref().map(Secret::expose),
);
self.env_option("HELM_MAX_HISTORY", o.max_history.map(|n| n.to_string()));
self.env_option("HELM_PLUGINS", o.plugins.as_deref());
self.env_option("HELM_NO_PLUGINS", o.no_plugins.then_some("1"));
if !o.memory_driver_data.is_empty() {
let joined = std::env::join_paths(&o.memory_driver_data)
.map_err(|e| Error::Io(io::Error::new(io::ErrorKind::InvalidInput, e)))?;
self.env("HELM_MEMORY_DRIVER_DATA", joined);
}
Ok(())
}
pub(crate) fn values(&mut self, values: &Values) -> Result<()> {
for file in &values.files {
match file {
ValuesFile::Path(path) => self.option("-f", Some(path)),
ValuesFile::Url(url) => self.option("-f", Some(url)),
ValuesFile::Json(value) => {
let path = self.temp_file(&serde_json::to_vec(value)?)?;
self.option("-f", Some(&path));
}
}
}
self.each("--set-json", &values.set_json);
self.each("--set", &values.set);
self.each("--set-string", &values.set_string);
self.each("--set-file", &values.set_file);
self.each("--set-literal", &values.set_literal);
Ok(())
}
}
#[cfg(test)]
mod tests;