1use std::{
2 borrow::Cow,
3 env,
4 ffi::{OsStr, OsString},
5 io::Read,
6 path::PathBuf,
7 process::{Command, ExitStatus, Stdio},
8 sync::{LazyLock, OnceLock},
9 time::Duration,
10};
11
12use anyhow::{Context as _, Result, bail};
13use indicatif::{ProgressBar, ProgressStyle};
14use log::LevelFilter;
15
16use crate::{config::Config, git, platform, util};
17
18#[cfg(windows)]
21const DEFAULT_SHELL: &str = "C:\\Program Files\\Git\\bin\\bash.EXE";
22
23#[cfg(not(windows))]
25const DEFAULT_SHELL: &str = "/bin/sh";
26
27pub static SHELL: LazyLock<OsString> =
30 LazyLock::new(|| (env::var_os("SHELL").unwrap_or_else(|| DEFAULT_SHELL.into())));
31
32static VERBOSITY: OnceLock<LevelFilter> = OnceLock::new();
33static CONFIG: OnceLock<Config> = OnceLock::new();
34static PATH: OnceLock<String> = OnceLock::new();
35
36pub fn verbosity() -> &'static LevelFilter {
37 VERBOSITY.get().expect("verbosity is not initialized")
38}
39
40pub fn config() -> &'static Config {
41 CONFIG.get().expect("config is not initialized")
42}
43
44pub fn path() -> &'static String {
45 PATH.get().expect("path is not initialized")
46}
47
48pub fn set_repo_dir() -> Result<()> {
49 env::set_current_dir(path()).context("Could not change directory")
50}
51
52pub fn version() -> Result<String> {
53 let mut version = util::get_version()?;
54
55 let channel = util::get_channel();
56
57 if channel == "release" {
58 let head = util::git_head()?;
59 if !head.status.success() {
60 let error = String::from_utf8_lossy(&head.stderr);
61 bail!("Error running `git describe`:\n{error}");
62 }
63 let tag = String::from_utf8_lossy(&head.stdout).trim().to_string();
64 if tag != format!("v{version}") {
65 bail!(
66 "On latest release channel and tag {tag:?} is different from Cargo.toml {version:?}. Aborting"
67 );
68 }
69
70 } else if channel == "custom" && !version.contains("custom") {
72 let sha = git::get_git_sha()?;
73
74 version = format!("{version}.custom.{sha}");
77 }
78
79 Ok(version)
80}
81
82pub trait CommandExt {
84 fn script(script: &str) -> Self;
85 fn in_repo(&mut self) -> &mut Self;
86 fn check_output(&mut self) -> Result<String>;
87 fn check_run(&mut self) -> Result<()>;
88 fn run(&mut self) -> Result<ExitStatus>;
89 fn wait(&mut self, message: impl Into<Cow<'static, str>>) -> Result<()>;
90 fn pre_exec(&self);
91 fn features(&mut self, features: &[String]) -> &mut Self;
92}
93
94impl CommandExt for Command {
95 fn script(script: &str) -> Self {
97 let path: PathBuf = [path(), "scripts", script].into_iter().collect();
98 if cfg!(windows) {
99 let mut command = Command::new(&*SHELL);
101 command.arg(path);
102 command
103 } else {
104 Command::new(path)
106 }
107 }
108
109 fn in_repo(&mut self) -> &mut Self {
111 self.current_dir(path())
112 }
113
114 fn check_output(&mut self) -> Result<String> {
116 self.pre_exec();
118 self.stdout(Stdio::piped());
119
120 let mut child = self.spawn()?;
122
123 let mut buffer = Vec::new();
125 child.stdout.take().unwrap().read_to_end(&mut buffer)?;
126
127 let status = child.wait()?;
129 if !status.success() {
133 let stdout = String::from_utf8_lossy(&buffer);
134 bail!(
135 "Command: {:?}\nfailed with exit code: {}\n\noutput:\n{}",
136 self,
137 status.code().unwrap(),
138 stdout
139 );
140 }
141
142 Ok(String::from_utf8(buffer)?)
144 }
145
146 fn run(&mut self) -> Result<ExitStatus> {
148 self.pre_exec();
149 self.status().map_err(Into::into)
150 }
151
152 fn check_run(&mut self) -> Result<()> {
153 let status = self.run()?;
154 if status.success() {
155 Ok(())
156 } else {
157 let exit = status.code().unwrap();
158 bail!("command: {self:?}\n failed with exit code: {exit}")
159 }
160 }
161
162 fn wait(&mut self, message: impl Into<Cow<'static, str>>) -> Result<()> {
165 self.pre_exec();
166
167 let progress_bar = get_progress_bar()?;
168 progress_bar.set_message(message);
169
170 let result = self.output();
171 progress_bar.finish_and_clear();
172
173 let Ok(output) = result else {
174 bail!("could not run command")
175 };
176
177 if output.status.success() {
178 Ok(())
179 } else {
180 bail!(
181 "{}\nfailed with exit code: {}",
182 String::from_utf8(output.stdout)?,
183 output.status.code().unwrap()
184 )
185 }
186 }
187
188 fn pre_exec(&self) {
190 debug!("Executing: {self:?}");
191 if let Some(cwd) = self.get_current_dir() {
192 debug!(" in working directory {cwd:?}");
193 }
194 for (key, value) in self.get_envs() {
195 let key = key.to_string_lossy();
196 if let Some(value) = value {
197 debug!(" ${key}={:?}", value.to_string_lossy());
198 } else {
199 debug!(" unset ${key}");
200 }
201 }
202 }
203
204 fn features(&mut self, features: &[String]) -> &mut Self {
205 self.arg("--no-default-features");
206 self.arg("--features");
207 if features.is_empty() {
208 self.arg(platform::default_features());
209 } else {
210 self.arg(features.join(","));
211 }
212 self
213 }
214}
215
216pub fn exec<T: AsRef<OsStr>>(
219 program: &str,
220 args: impl IntoIterator<Item = T>,
221 in_repo: bool,
222) -> Result<()> {
223 let mut command = match program.strip_prefix("scripts/") {
224 Some(script) => Command::script(script),
225 None => Command::new(program),
226 };
227 command.args(args);
228 if in_repo {
229 command.in_repo();
230 }
231 command.check_run()
232}
233
234fn get_progress_bar() -> Result<ProgressBar> {
235 let progress_bar = ProgressBar::new_spinner();
236 progress_bar.enable_steady_tick(Duration::from_millis(125));
237 progress_bar.set_style(
238 ProgressStyle::with_template("{spinner} {msg:.magenta.bold}")?
239 .tick_strings(&["∙∙∙", "●∙∙", "∙●∙", "∙∙●", "∙∙∙"]),
241 );
242
243 Ok(progress_bar)
244}
245
246pub fn set_global_verbosity(verbosity: LevelFilter) {
247 VERBOSITY.set(verbosity).expect("could not set verbosity");
248}
249
250pub fn set_global_config(config: Config) {
251 CONFIG.set(config).expect("could not set config");
252}
253
254pub fn set_global_path(path: String) {
255 PATH.set(path).expect("could not set path");
256}