upgr/src/lib.rs

83 lines
1.8 KiB
Rust

use crate::config::CfgCommand;
use config::Config;
use miette::{Context, IntoDiagnostic};
use mlua::prelude::*;
use owo_colors::OwoColorize;
use std::path::{Path, PathBuf};
pub mod config;
pub mod luautil;
pub fn exec_steps(conf: Config, uninteractive: bool) -> miette::Result<()> {
for step in conf.steps {
if step.interactive && uninteractive {
if let Some(cmd) = step.unint_alt {
exec_cmd(cmd, &conf.shell, step.when, step.workdir)?;
}
} else {
exec_cmd(step.command, &conf.shell, step.when, step.workdir)?;
}
}
Ok(())
}
pub fn exec_cmd(
cmd: CfgCommand,
shell: &[String],
when: Option<LuaFunction>,
workdir: Option<PathBuf>,
) -> miette::Result<()> {
let cmd_str = cmd.to_string();
let len = cmd_str.len();
if let Some(func) = when {
let val: bool = func
.call(())
.into_diagnostic()
.wrap_err("Failed to call when function")?;
if !val {
println!("Skipping {}", cmd_str.blue());
return Ok(());
}
}
let mut cmd = cmd.into_command(shell)?;
if let Some(workdir) = workdir {
cmd.current_dir(workdir);
}
println!(
"{:=<len$}\nRunning {}\n{:=<len$}",
"",
cmd_str.green(),
"",
len = 8 + len
);
cmd.spawn().into_diagnostic()?.wait().into_diagnostic()?;
Ok(())
}
pub enum PathStatus {
NonExistant,
Directory,
File,
}
pub trait PathExt {
fn status(&self) -> PathStatus;
}
impl PathExt for Path {
fn status(&self) -> PathStatus {
match self.metadata() {
Ok(m) if m.is_file() => PathStatus::File,
Ok(m) if m.is_dir() => PathStatus::Directory,
_ => PathStatus::NonExistant,
}
}
}