use crate::{errors::GovmError, logging};
use std::{
env,
fs::{self, File},
io::Write,
path::{Path, PathBuf},
time::Instant,
};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
pub(crate) struct ShimManager {
shim_dir: PathBuf,
}
impl ShimManager {
pub(crate) fn new() -> Result<Self, GovmError> {
let home = dirs::home_dir().ok_or(GovmError::HomeNotFound)?;
let shim_dir = home.join(".govmr").join("shim");
fs::create_dir_all(&shim_dir).map_err(|e| {
logging::error(&format!(
"shim failed: action=create_dir dir=\"{}\" error={e}",
shim_dir.display()
));
GovmError::Io(e)
})?;
logging::debug(&format!(
"shim: ready dir=\"{}\"",
shim_dir.to_string_lossy()
));
Ok(Self { shim_dir })
}
#[must_use]
pub(crate) fn get_shim_dir(&self) -> &Path {
&self.shim_dir
}
#[must_use]
pub(crate) fn is_in_path(&self) -> bool {
let in_path = path_contains_dir(&self.shim_dir);
logging::debug(&format!(
"shim: path check dir=\"{}\" in_path={in_path}",
self.shim_dir.to_string_lossy()
));
in_path
}
pub(crate) fn setup_shims_for_version(&self, bin_dir: &Path) -> Result<(), GovmError> {
let started_at = Instant::now();
self.cleanup_shims()?;
let entries = fs::read_dir(bin_dir).map_err(|e| {
logging::error(&format!(
"shim failed: action=read_bin_dir dir=\"{}\" error={e}",
bin_dir.display()
));
GovmError::Io(e)
})?;
let mut created: Vec<String> = Vec::new();
for entry in entries {
let path = entry?.path();
if path.is_file() {
let bin_name = match path.file_stem() {
Some(name) => name.to_string_lossy().to_string(),
None => continue,
};
self.create_shim(&bin_name, &path)?;
created.push(bin_name);
}
}
logging::info(&format!(
"shim: created count={} names=[{}] for=\"{}\" elapsed_ms={}",
created.len(),
created.join(", "),
bin_dir.display(),
started_at.elapsed().as_millis()
));
if created.is_empty() {
logging::warn(&format!(
"shim: created nothing dir=\"{}\" note=no_executables_found",
bin_dir.display()
));
}
Ok(())
}
fn cleanup_shims(&self) -> Result<(), GovmError> {
if !self.shim_dir.exists() {
return Ok(());
}
let mut removed = 0usize;
let mut failed = 0usize;
for entry in fs::read_dir(&self.shim_dir)? {
let path = entry?.path();
if path.is_file() {
if fs::remove_file(&path).is_ok() {
removed += 1;
} else {
failed += 1;
}
}
}
if failed > 0 {
logging::warn(&format!(
"shim: cleanup dir=\"{}\" removed={removed} failed={failed}",
self.shim_dir.to_string_lossy()
));
} else if removed > 0 {
logging::debug(&format!(
"shim: cleanup dir=\"{}\" removed={removed}",
self.shim_dir.to_string_lossy()
));
}
Ok(())
}
#[cfg(unix)]
fn create_shim(&self, bin_name: &str, target_path: &Path) -> Result<(), GovmError> {
let shim_path = self.shim_dir.join(bin_name);
let content = format!(
"#!/usr/bin/env bash\n\"{}\" \"$@\"\n",
target_path.display()
);
let mut file = File::create(&shim_path)?;
file.write_all(content.as_bytes())?;
fs::set_permissions(&shim_path, fs::Permissions::from_mode(0o755))?;
logging::debug(&format!(
"shim: wrote name={bin_name} path=\"{}\" target=\"{}\" mode=755",
shim_path.display(),
target_path.display()
));
Ok(())
}
#[cfg(windows)]
fn create_shim(&self, bin_name: &str, target_path: &Path) -> Result<(), GovmError> {
let shim_path = self.shim_dir.join(format!("{bin_name}.bat"));
let content = format!("@echo off\r\n\"{}\" %*\r\n", target_path.display());
let mut file = File::create(&shim_path)?;
file.write_all(content.as_bytes())?;
logging::debug(&format!(
"shim: wrote name={bin_name} path=\"{}\" target=\"{}\"",
shim_path.display(),
target_path.display()
));
Ok(())
}
}
fn path_contains_dir(dir: &Path) -> bool {
env::var_os("PATH").is_some_and(|paths| env::split_paths(&paths).any(|p| p == dir))
}