1#[cfg(test)]
30#[macro_use]
31mod chart_rows;
32mod chart_path;
33mod classify;
34mod dependency;
35mod env;
36mod fetch;
37mod invocation;
38mod plugin;
39mod registry;
40mod release;
41mod render;
42mod repo;
43mod search;
44mod show;
45mod verification;
46mod version;
47
48#[cfg(test)]
49mod testing;
50
51#[cfg(test)]
52mod tests;
53
54use std::ffi::OsStr;
55use std::io;
56use std::path::PathBuf;
57use std::process::Stdio;
58
59use tokio::io::AsyncWriteExt;
60use tokio::process::{Child, Command as Process};
61use tracing::debug;
62
63use crate::backend::{Backend, Command, Execute};
64use crate::command::Version;
65use crate::error::{Error, Result};
66use crate::options::GlobalOptions;
67
68pub(crate) use chart_path::{chart_path, oci_host, oci_hosts, registry_auth};
69pub(crate) use invocation::{Invocation, flags, parse_json};
70
71pub(crate) trait CliCommand: Command {
73 const MUTATES: bool = false;
78
79 fn build(&self, inv: &mut Invocation) -> Result<()>;
81
82 fn parse(&self, stdout: String) -> Result<Self::Output>;
84
85 fn parse_failure(&self, _stdout: &str, _stderr: &str) -> Option<Result<Self::Output>> {
88 None
89 }
90}
91
92#[derive(Debug, Clone)]
95pub struct Cli {
96 pub binary: PathBuf,
98 pub version: semver::Version,
100}
101
102impl Cli {
103 pub async fn detect() -> Result<Self> {
105 Self::new("helm").await
106 }
107
108 pub async fn new(binary: impl Into<PathBuf>) -> Result<Self> {
110 let binary = binary.into();
111 let found = run(&binary, &GlobalOptions::default(), &Version)
112 .await?
113 .version;
114
115 if found.major < 4 {
116 return Err(Error::UnsupportedVersion { found });
117 }
118
119 Ok(Self {
120 binary,
121 version: found,
122 })
123 }
124}
125
126impl Backend for Cli {}
127
128impl<C: CliCommand> Execute<C> for Cli {
129 async fn execute(&self, options: &GlobalOptions, command: &C) -> Result<C::Output> {
130 run(&self.binary, options, command).await
131 }
132}
133
134fn is_helm_var(key: &OsStr) -> bool {
136 key.to_string_lossy().starts_with("HELM_")
137}
138
139async fn run<C: CliCommand>(
141 binary: &PathBuf,
142 options: &GlobalOptions,
143 command: &C,
144) -> Result<C::Output> {
145 let mut inv = Invocation::default();
146 let mut process = Process::new(binary);
147
148 inv.globals(options)?;
149 command.build(&mut inv)?;
150
151 for (key, _) in std::env::vars_os().filter(|(key, _)| is_helm_var(key)) {
152 process.env_remove(key);
153 }
154
155 process
156 .args(&inv.args)
157 .envs(inv.env.iter().map(|(k, v)| (k, v)))
158 .stdin(if inv.stdin.is_some() {
159 Stdio::piped()
160 } else {
161 Stdio::null()
162 })
163 .stdout(Stdio::piped())
164 .stderr(Stdio::piped())
165 .kill_on_drop(!C::MUTATES);
166
167 debug!(binary = %binary.display(), args = ?inv.args, "running helm");
168
169 let child = process.spawn().map_err(|e| match e.kind() {
170 io::ErrorKind::NotFound => Error::BinaryNotFound(binary.clone()),
171 _ => Error::Io(e),
172 })?;
173 let finished = if C::MUTATES {
174 tokio::spawn(finish(child, inv))
175 .await
176 .map_err(|e| Error::Io(io::Error::other(e)))??
177 } else {
178 finish(child, inv).await?
179 };
180
181 if !finished.success {
182 if let Some(parsed) = command.parse_failure(&finished.stdout, &finished.stderr) {
183 return parsed;
184 }
185
186 return Err(classify::classify(finished.exit_code, finished.stderr));
187 }
188
189 command.parse(finished.stdout)
190}
191
192struct Finished {
194 success: bool,
195 exit_code: Option<i32>,
196 stdout: String,
197 stderr: String,
198}
199
200async fn finish(mut child: Child, inv: Invocation) -> Result<Finished> {
204 let mut stdin = child.stdin.take();
205 let input = inv.stdin.as_deref().unwrap_or_default();
206 let feed = async {
207 if let Some(stdin) = stdin.as_mut() {
208 let _ = stdin.write_all(input).await;
210 }
211
212 drop(stdin.take());
213 };
214 let ((), output) = tokio::join!(feed, child.wait_with_output());
215 let output = output?;
216
217 debug!(status = %output.status, "helm finished");
218
219 if !output.status.success() {
220 return Ok(Finished {
221 success: false,
222 exit_code: output.status.code(),
223 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
224 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
225 });
226 }
227
228 let stdout = String::from_utf8(output.stdout)
229 .map_err(|e| Error::Io(io::Error::new(io::ErrorKind::InvalidData, e)))?;
230
231 Ok(Finished {
232 success: true,
233 exit_code: output.status.code(),
234 stdout,
235 stderr: String::new(),
236 })
237}