1#![allow(clippy::print_stderr)]
2#![allow(clippy::print_stdout)]
3
4use std::ffi::{OsStr, OsString};
5use std::io::IsTerminal;
6use std::process::{Command, Output};
7use std::{
8 collections::BTreeMap, fmt::Debug, fs, io::ErrorKind, path::Path, process, sync::LazyLock,
9};
10
11use anyhow::{Context as _, Result};
12use serde::Deserialize;
13use serde_json::Value;
14
15pub static IS_A_TTY: LazyLock<bool> = LazyLock::new(|| std::io::stdout().is_terminal());
16
17#[derive(Deserialize)]
18pub struct CargoTomlPackage {
19 pub version: String,
20}
21
22#[derive(Deserialize)]
24pub struct CargoToml {
25 pub package: CargoTomlPackage,
26 pub features: BTreeMap<String, Value>,
27}
28
29impl CargoToml {
30 pub fn load() -> Result<CargoToml> {
31 let text = fs::read_to_string("Cargo.toml").context("Could not read `Cargo.toml`")?;
32 toml::from_str::<CargoToml>(&text).context("Invalid contents in `Cargo.toml`")
33 }
34}
35
36pub fn read_version() -> Result<String> {
38 CargoToml::load().map(|cargo| cargo.package.version)
39}
40
41pub fn get_version() -> Result<String> {
43 std::env::var("VERSION")
44 .or_else(|_| std::env::var("VECTOR_VERSION"))
45 .or_else(|_| read_version())
46}
47
48pub fn git_head() -> Result<Output> {
49 Command::new("git")
50 .args(["describe", "--exact-match", "--tags", "HEAD"])
51 .output()
52 .context("Could not execute `git`")
53}
54
55pub fn get_channel() -> String {
56 std::env::var("CHANNEL").unwrap_or_else(|_| "custom".to_string())
57}
58
59pub fn exists(path: impl AsRef<Path> + Debug) -> Result<bool> {
60 match fs::metadata(path.as_ref()) {
61 Ok(_) => Ok(true),
62 Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
63 Err(error) => Err(error).context(format!("Could not stat {path:?}")),
64 }
65}
66
67pub trait ChainArgs {
68 fn chain_args<I: Into<OsString>>(&self, args: impl IntoIterator<Item = I>) -> Vec<OsString>;
69}
70
71impl<T: AsRef<OsStr>> ChainArgs for Vec<T> {
72 fn chain_args<I: Into<OsString>>(&self, args: impl IntoIterator<Item = I>) -> Vec<OsString> {
73 self.iter()
74 .map(Into::into)
75 .chain(args.into_iter().map(Into::into))
76 .collect()
77 }
78}
79
80impl<T: AsRef<OsStr>> ChainArgs for [T] {
81 fn chain_args<I: Into<OsString>>(&self, args: impl IntoIterator<Item = I>) -> Vec<OsString> {
82 self.iter()
83 .map(Into::into)
84 .chain(args.into_iter().map(Into::into))
85 .collect()
86 }
87}
88
89pub fn run_command(cmd: &str) -> String {
90 let output = Command::new("sh")
91 .arg("-c")
92 .arg(cmd)
93 .output()
94 .expect("Failed to execute command");
95
96 if !output.status.success() {
97 eprintln!(
98 "Command failed: {cmd} - Error: {}",
99 String::from_utf8_lossy(&output.stderr)
100 );
101 process::exit(1);
102 }
103
104 String::from_utf8_lossy(&output.stdout).to_string()
105}