Bash tool

This commit is contained in:
2025-05-03 11:24:34 -07:00
parent 20bf33fa05
commit 00c88ccf51
12 changed files with 1286 additions and 152 deletions

170
src/logging.rs Normal file
View File

@ -0,0 +1,170 @@
use clap::{Parser, ValueEnum};
use serde::Deserialize;
use std::{fmt::Display, str::FromStr};
use tracing_subscriber::EnvFilter;
#[derive(Debug)]
pub enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
}
impl Default for LogLevel {
fn default() -> Self {
Self::Info
}
}
impl Display for LogLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Trace => write!(f, "trace"),
Self::Debug => write!(f, "debug"),
Self::Info => write!(f, "info"),
Self::Warn => write!(f, "warn"),
Self::Error => write!(f, "error"),
}
}
}
#[derive(Debug, Deserialize, Clone, Copy, ValueEnum, PartialEq, Eq)]
pub enum LoggingPreset {
Error,
Warn,
Info,
Debug,
TraceMain,
TraceTools,
}
pub struct LoggingConfig {
other: LogLevel,
pick: LogLevel,
tool: LogLevel,
}
impl From<LoggingConfig> for EnvFilter {
fn from(conf: LoggingConfig) -> Self {
// Should never fail
#[expect(clippy::unwrap_used)]
EnvFilter::from_str(
&[
format!("pick={}", conf.pick),
format!("pick::tool={}", conf.tool),
conf.other.to_string(),
]
.join(","),
)
.unwrap()
}
}
impl Default for LoggingPreset {
fn default() -> Self {
return Self::Info;
}
}
impl LoggingPreset {
/// Returns a logging preset with the given level.
/// Negative numbers are more quiet, positive are more verbose.
/// Zero is the default.
pub fn from_number(level: i16) -> Self {
if level <= -2 {
return Self::Error;
} else if level == -1 {
return Self::Warn;
} else if level == 0 {
return Self::Info;
} else if level == 1 {
return Self::Debug;
} else if level == 2 {
return Self::TraceMain;
} else if level >= 3 {
return Self::TraceTools;
} else {
unreachable!()
}
}
pub fn get_config(&self) -> LoggingConfig {
match self {
Self::Error => LoggingConfig {
other: LogLevel::Error,
pick: LogLevel::Error,
tool: LogLevel::Error,
},
Self::Warn => LoggingConfig {
other: LogLevel::Error,
pick: LogLevel::Warn,
tool: LogLevel::Warn,
},
Self::Info => LoggingConfig {
other: LogLevel::Warn,
pick: LogLevel::Info,
tool: LogLevel::Info,
},
Self::Debug => LoggingConfig {
other: LogLevel::Warn,
pick: LogLevel::Debug,
tool: LogLevel::Debug,
},
Self::TraceMain => LoggingConfig {
other: LogLevel::Trace,
pick: LogLevel::Trace,
tool: LogLevel::Debug,
},
Self::TraceTools => LoggingConfig {
other: LogLevel::Trace,
pick: LogLevel::Trace,
tool: LogLevel::Trace,
},
}
}
}
/// A pre-baked set of loglevel cli arguments.
///
/// # Usage
/// ```ignore
/// #[derive(Parser, Debug)]
/// struct Cli {
/// #[command(flatten)]
/// log: LogCli,
/// }
/// ```
#[derive(Parser, Debug)]
pub struct LogCli {
/// Increase verbosity (can be repeated)
#[arg(short, action = clap::ArgAction::Count,global = true)]
pub v: u8,
/// Decrease verbosity (can be repeated)
#[arg(short, action = clap::ArgAction::Count, global = true)]
pub q: u8,
}
impl LogCli {
pub fn to_preset(&self) -> LoggingPreset {
LoggingPreset::from_number(self.v as i16 - self.q as i16)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn loglevel_0_is_default() {
assert_eq!(LoggingPreset::default(), LoggingPreset::from_number(0));
}
}

View File

@ -1,33 +1,215 @@
use anyhow::{Context, Result};
use clap::Parser;
use logging::LogCli;
use manifest::Manifest;
use std::{path::PathBuf, process::ExitCode};
use tool::{PickTool, TaskContext};
use tracing::{debug, error, trace};
use walkdir::WalkDir;
pub mod logging;
pub mod manifest;
pub mod tool;
pub mod util;
fn main() {
let file = std::fs::read_to_string("./test.toml").unwrap();
let x: manifest::Manifest = toml::from_str(&file).unwrap();
// enumerate files with a spinner (count size)
// warn if links and follow
// trim everything
// parallelism
// input from stdin?
// * ** greed
// fix and document "**.flac", "**/*.flac"
// tests
// show progress
// bash before and after
// capture/print stdout/stderr
// workdir vs root?
//
// Tools:
// - *** bash
// - * list
// - *** rename
// - ** typst
// - *** retag
// - gitea pkg (POST)
// - s3
// - rsync
//
// chain tools
// print output?
let rules = x
#[derive(Parser, Debug)]
#[command(version, about, long_about = None, styles=util::get_styles())]
struct Cli {
#[command(flatten)]
log: LogCli,
manifest: PathBuf,
}
fn main() -> ExitCode {
if let Err(e) = main_inner() {
for e in e.chain() {
error!(e);
}
return ExitCode::FAILURE;
}
return ExitCode::SUCCESS;
}
fn main_inner() -> Result<ExitCode> {
//
// MARK: setup
//
let cli = Cli::parse();
tracing_subscriber::fmt()
.with_env_filter(cli.log.to_preset().get_config())
.without_time()
.with_ansi(true)
.with_writer(std::io::stderr)
.init();
let manifest_path_str = cli
.manifest
.to_str()
.context("while converting path to string")?;
if !cli.manifest.is_file() {
error!("Manifest {manifest_path_str} isn't a file");
return Ok(ExitCode::FAILURE);
}
let manifest_string = match std::fs::read_to_string(&cli.manifest) {
Ok(x) => x,
Err(error) => {
error!("Error while reading {manifest_path_str}: {error}");
return Ok(ExitCode::FAILURE);
}
};
let manifest = match toml::from_str::<Manifest>(&manifest_string) {
Ok(manifest) => {
// Validate manifest
if manifest.config.follow_links && manifest.config.links {
error!("Error: `follow_links` and `links` are mutually exclusive");
return Ok(ExitCode::FAILURE);
}
manifest
}
Err(error) => {
error!("Error while parsing {manifest_path_str}");
error!("{}", error.to_string());
return Ok(ExitCode::FAILURE);
}
};
let manifest_path = std::path::absolute(cli.manifest)?;
let work_dir = manifest.config.work_dir(&manifest_path)?;
debug!("Working directory is {work_dir:?}");
//
// MARK: rules
//
let rules = manifest
.rules
.iter()
.map(|rule| (rule.regex(), rule.action))
.map(|rule| (rule.regex(), rule.tasks))
.collect::<Vec<_>>();
let walker = WalkDir::new("./target").into_iter();
let source_path = std::path::absolute(&work_dir)?;
let walker = WalkDir::new(&source_path).follow_links(manifest.config.follow_links);
let bash = manifest.tool.bash.as_ref().unwrap();
bash.before(&manifest_path, &manifest.config)?;
for entry in walker {
let e = entry.unwrap();
let p = e.path();
let s = p.to_str().unwrap();
let entry = entry?;
let path_abs = std::path::absolute(entry.path())?;
if !p.is_file() {
// This path is a child of source_path, so this cannot fail
#[expect(clippy::unwrap_used)]
let path_rel = entry.path().strip_prefix(&source_path).unwrap();
let path_rel = if path_rel.parent().is_none() {
// Make sure we never have empty string paths
// (makes logs clearer)
PathBuf::from(".").join(path_rel)
} else {
path_rel.to_path_buf()
};
let path_abs_str = path_abs
.to_str()
.context("could not convert path to string")?
.to_owned();
let path_rel_str = path_rel
.to_str()
.context("could not convert path to string")?
.to_owned();
if path_abs.is_symlink() && !manifest.config.links {
trace!("Skipping {}, is a symlink", path_rel_str);
continue;
}
let m = rules
.iter()
.find(|(r, _)| r.is_match(s))
.map(|x| x.1.clone());
if path_abs.is_dir() && !manifest.config.dirs {
trace!("Skipping {}, is a directory", path_rel_str);
continue;
}
println!(" {m:?} {s}")
if path_abs.is_file() && !manifest.config.files {
trace!("Skipping {}, is a file", path_rel_str);
continue;
}
let task = rules.iter().find(|(r, _)| r.is_match(&path_rel_str));
let tasks = match task {
None => {
trace!("Skipping {}, no match", path_rel_str);
continue;
}
Some(x) => {
let tasks: Vec<String> =
x.1.iter()
.map(|x| x.trim())
.filter(|x| !x.is_empty())
.map(|x| x.to_owned())
.collect();
if tasks.is_empty() {
trace!("Skipping {}", path_rel_str);
continue;
}
tasks
}
};
let base_ctx = TaskContext {
task: "".into(),
path_abs,
path_abs_str,
path_rel,
path_rel_str,
};
for task in tasks {
trace!("Running `{task}` on {}", base_ctx.path_rel_str);
let mut ctx = base_ctx.clone();
ctx.task = task;
bash.run(&manifest_path, &manifest.config, ctx)?;
}
}
bash.after(&manifest_path, &manifest.config)?;
return Ok(ExitCode::SUCCESS);
}

View File

@ -1,18 +1,63 @@
use anyhow::Result;
use indexmap::IndexMap;
use regex::Regex;
use serde::Deserialize;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Deserialize)]
use crate::tool::ToolConfig;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
pub config: PickConfig,
pub tool: ToolConfig,
pub rules: PickRules,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PickConfig {
pub source: PathBuf,
pub target: PathBuf,
#[serde(default)]
pub work_dir: Option<PathBuf>,
#[serde(default = "default_false")]
pub follow_links: bool,
#[serde(default = "default_true")]
pub files: bool,
#[serde(default = "default_false")]
pub dirs: bool,
#[serde(default = "default_false")]
pub links: bool,
}
impl PickConfig {
pub fn work_dir(&self, manifest_path: &Path) -> Result<PathBuf> {
// Parent directory should always exist since manifest is a file.
#[expect(clippy::unwrap_used)]
let p = manifest_path.parent().unwrap().to_path_buf();
match &self.work_dir {
None => Ok(p),
Some(path) => {
if path.is_absolute() {
Ok(path.to_owned())
} else {
Ok(std::path::absolute(p.join(path))?)
}
}
}
}
}
fn default_true() -> bool {
true
}
fn default_false() -> bool {
false
}
//
@ -21,12 +66,12 @@ pub struct PickConfig {
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum OptVec<T> {
pub enum OptVec<T: Clone> {
Single(T),
Vec(Vec<T>),
}
impl<T> OptVec<T> {
impl<T: Clone> OptVec<T> {
pub fn len(&self) -> usize {
match self {
Self::Single(_) => 1,
@ -34,6 +79,13 @@ impl<T> OptVec<T> {
}
}
pub fn is_empty(&self) -> bool {
match self {
Self::Single(_) => false,
Self::Vec(v) => v.is_empty(),
}
}
pub fn get(&self, idx: usize) -> Option<&T> {
match self {
Self::Single(t) => (idx == 0).then_some(t),
@ -41,11 +93,20 @@ impl<T> OptVec<T> {
}
}
}
impl<T: Clone> From<OptVec<T>> for Vec<T> {
fn from(val: OptVec<T>) -> Self {
match val {
OptVec::Single(t) => vec![t],
OptVec::Vec(v) => v,
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
#[serde(deny_unknown_fields)]
pub enum PickRule {
Plain(String),
Plain(OptVec<String>),
Nested(PickRules),
}
@ -54,7 +115,7 @@ pub enum PickRule {
pub struct PickRules(OptVec<IndexMap<String, PickRule>>);
impl PickRules {
pub fn iter<'a>(&'a self) -> PickRuleIterator<'a> {
pub fn iter(&self) -> PickRuleIterator<'_> {
PickRuleIterator {
stack: vec![PickRuleIterState {
rules: self,
@ -82,11 +143,13 @@ impl<'a> IntoIterator for &'a PickRules {
#[derive(Debug, Clone)]
pub struct FlatPickRule {
pub patterns: Vec<String>,
pub action: String,
pub tasks: Vec<String>,
}
impl FlatPickRule {
pub fn regex(&self) -> Regex {
// This regex should always be valid
#[expect(clippy::unwrap_used)]
Regex::new(
&self
.patterns
@ -122,6 +185,7 @@ impl Iterator for PickRuleIterator<'_> {
return None;
}
#[expect(clippy::unwrap_used)]
let current = self.stack.last_mut().unwrap();
if current.map_index >= current.rules.0.len() {
@ -129,6 +193,7 @@ impl Iterator for PickRuleIterator<'_> {
return self.next();
}
#[expect(clippy::unwrap_used)]
let current_map = &current.rules.0.get(current.map_index).unwrap();
if current.entry_index >= current_map.len() {
@ -137,18 +202,19 @@ impl Iterator for PickRuleIterator<'_> {
return self.next();
}
#[expect(clippy::unwrap_used)]
let (key, value) = current_map.get_index(current.entry_index).unwrap();
current.entry_index += 1;
match value {
PickRule::Plain(action) => {
PickRule::Plain(task) => {
let mut patterns = current.prefix.clone();
patterns.push(key.to_string());
Some(FlatPickRule {
patterns,
action: action.clone(),
tasks: task.clone().into(),
})
}
PickRule::Nested(nested_rules) => {
@ -175,121 +241,82 @@ impl Iterator for PickRuleIterator<'_> {
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
#[test]
fn parse_simple_manifest() {
let toml_str = r#"
[config]
source = "./src"
target = "./tgt"
[[rules]]
"*.rs" = "copy"
"*.md" = "ignore"
"#;
let manifest: Manifest = toml::from_str(toml_str).unwrap();
assert_eq!(manifest.config.source, Path::new("./src"));
assert_eq!(manifest.config.target, Path::new("./tgt"));
let rules: Vec<FlatPickRule> = manifest.rules.iter().collect();
assert_eq!(rules.len(), 2);
assert_eq!(rules[0].patterns, vec!["*.rs"]);
assert_eq!(rules[0].action, "copy");
assert_eq!(rules[1].patterns, vec!["*.md"]);
assert_eq!(rules[1].action, "ignore");
#[derive(Debug, Clone, Deserialize)]
struct TestManifest {
rules: PickRules,
}
#[test]
fn rule_ordering_preserved() {
let toml_str = r#"
[config]
source = "./src"
target = "./tgt"
[[rules]]
"third" = "c"
"first" = "a"
"second" = "b"
"#;
let manifest: Manifest = toml::from_str(toml_str).unwrap();
let rules: Vec<FlatPickRule> = manifest.rules.iter().collect();
let test_manifest: TestManifest = toml::from_str(toml_str).unwrap();
let rules: Vec<FlatPickRule> = test_manifest.rules.iter().collect();
assert_eq!(rules.len(), 3);
assert_eq!(rules[0].patterns, vec!["third"]);
assert_eq!(rules[0].action, "c");
assert_eq!(rules[0].tasks, vec!["c"]);
assert_eq!(rules[1].patterns, vec!["first"]);
assert_eq!(rules[1].action, "a");
assert_eq!(rules[1].tasks, vec!["a"]);
assert_eq!(rules[2].patterns, vec!["second"]);
assert_eq!(rules[2].action, "b");
assert_eq!(rules[2].tasks, vec!["b"]);
}
#[test]
fn nested_rules_order() {
let toml_str = r#"
[config]
source = "./src"
target = "./tgt"
[[rules]]
"a" = "action_a"
"b" = "action_b"
"a" = "task_a"
"b" = "task_b"
[[rules."nested"]]
"c" = "action_c"
"d" = "action_d"
"c" = "task_c"
"d" = "task_d"
[[rules]]
"e" = "action_e"
"e" = "task_e"
"#;
let manifest: Manifest = toml::from_str(toml_str).unwrap();
let rules: Vec<FlatPickRule> = manifest.rules.iter().collect();
let test_manifest: TestManifest = toml::from_str(toml_str).unwrap();
let rules: Vec<FlatPickRule> = test_manifest.rules.iter().collect();
assert_eq!(rules.len(), 5);
assert_eq!(rules[0].patterns, vec!["a"]);
assert_eq!(rules[0].action, "action_a");
assert_eq!(rules[0].tasks, vec!["task_a"]);
assert_eq!(rules[1].patterns, vec!["b"]);
assert_eq!(rules[1].action, "action_b");
assert_eq!(rules[1].tasks, vec!["task_b"]);
assert_eq!(rules[2].patterns, vec!["nested", "c"]);
assert_eq!(rules[2].action, "action_c");
assert_eq!(rules[2].tasks, vec!["task_c"]);
assert_eq!(rules[3].patterns, vec!["nested", "d"]);
assert_eq!(rules[3].action, "action_d");
assert_eq!(rules[3].tasks, vec!["task_d"]);
assert_eq!(rules[4].patterns, vec!["e"]);
assert_eq!(rules[4].action, "action_e");
assert_eq!(rules[4].tasks, vec!["task_e"]);
}
#[test]
fn deeply_nested_rules() {
let toml_str = r#"
[config]
source = "./src"
target = "./tgt"
[[rules."a"."b"."c"]]
"d" = "action_d"
"d" = "task_d"
"#;
let manifest: Manifest = toml::from_str(toml_str).unwrap();
let rules: Vec<FlatPickRule> = manifest.rules.iter().collect();
let test_manifest: TestManifest = toml::from_str(toml_str).unwrap();
let rules: Vec<FlatPickRule> = test_manifest.rules.iter().collect();
assert_eq!(rules.len(), 1);
assert_eq!(rules[0].patterns, vec!["a", "b", "c", "d"]);
assert_eq!(rules[0].action, "action_d");
assert_eq!(rules[0].tasks, vec!["task_d"]);
}
#[test]
fn multiple_maps_same_level() {
let toml_str = r#"
[config]
source = "./src"
target = "./tgt"
[[rules]]
"a1" = "copy"
"a2" = "ignore"
@ -299,91 +326,41 @@ mod tests {
"b2" = "ignore"
"#;
let manifest: Manifest = toml::from_str(toml_str).unwrap();
let rules: Vec<FlatPickRule> = manifest.rules.iter().collect();
let test_manifest: TestManifest = toml::from_str(toml_str).unwrap();
let rules: Vec<FlatPickRule> = test_manifest.rules.iter().collect();
// Test that all rules exist and are in the correct order
assert_eq!(rules.len(), 4);
assert_eq!(rules[0].patterns, vec!["a1"]);
assert_eq!(rules[0].action, "copy");
assert_eq!(rules[0].tasks, vec!["copy"]);
assert_eq!(rules[1].patterns, vec!["a2"]);
assert_eq!(rules[1].action, "ignore");
assert_eq!(rules[1].tasks, vec!["ignore"]);
assert_eq!(rules[2].patterns, vec!["b1"]);
assert_eq!(rules[2].action, "copy");
assert_eq!(rules[2].tasks, vec!["copy"]);
assert_eq!(rules[3].patterns, vec!["b2"]);
assert_eq!(rules[3].action, "ignore");
assert_eq!(rules[3].tasks, vec!["ignore"]);
}
#[test]
fn empty_rules_list() {
let toml_str = r#"
[config]
source = "./src"
target = "./tgt"
[[rules]]
"#;
let manifest: Manifest = toml::from_str(toml_str).unwrap();
let rules: Vec<FlatPickRule> = manifest.rules.iter().collect();
let test_manifest: TestManifest = toml::from_str(toml_str).unwrap();
let rules: Vec<FlatPickRule> = test_manifest.rules.iter().collect();
assert_eq!(rules.len(), 0);
}
#[test]
#[should_panic(expected = "missing field `config`")]
fn missing_config() {
let toml_str = r#"
[[rules]]
"a" = "copy"
"#;
let _: Manifest = toml::from_str(toml_str).unwrap();
}
#[test]
#[should_panic(expected = "missing field `source`")]
fn incomplete_config() {
let toml_str = r#"
[config]
target = "./tgt"
[[rules]]
"a" = "copy"
"#;
let _: Manifest = toml::from_str(toml_str).unwrap();
}
#[test]
#[should_panic]
fn invalid_toml_syntax() {
let toml_str = r#"
[config]
source = "./src"
target = "./tgt"
[[rules]]
"invalid" = { this is not valid TOML }
"#;
let _: Manifest = toml::from_str(toml_str).unwrap();
}
#[test]
fn mixed_rule_types() {
let toml_str = r#"
[config]
source = "./src"
target = "./tgt"
[[rules]]
"plain" = "copy"
"nested" = { invalid_as_string = true }
"#;
// This should fail because a table is not a valid PickRule
let result = toml::from_str::<Manifest>(toml_str);
let result = toml::from_str::<TestManifest>(toml_str);
assert!(result.is_err());
}
}

174
src/tool/bash.rs Normal file
View File

@ -0,0 +1,174 @@
use anyhow::{Context, Result};
use serde::Deserialize;
use std::io::Write;
use std::{collections::HashMap, path::Path};
use tracing::{error, trace, warn};
use crate::manifest::PickConfig;
use super::{PickTool, TaskContext};
#[derive(Debug, Deserialize)]
pub struct ToolBash {
#[serde(default)]
pub before: Option<String>,
#[serde(default)]
pub after: Option<String>,
#[serde(default)]
pub env: HashMap<String, String>,
#[serde(default)]
pub script: HashMap<String, String>,
}
impl PickTool for ToolBash {
fn before(&self, manifest_path: &Path, cfg: &PickConfig) -> Result<()> {
let script = match &self.before {
None => {
return Ok(());
}
Some(script) => {
trace!("Running `before` script");
let mut temp_file =
tempfile::NamedTempFile::new().context("while creating temporary script")?;
writeln!(temp_file, "{}", script).context("while creating temporary script")?;
temp_file
}
};
let mut cmd = std::process::Command::new("bash");
cmd.arg(script.path());
cmd.current_dir(&cfg.work_dir(manifest_path)?);
for (key, value) in &self.env {
cmd.env(key, value);
}
let output = match cmd.output() {
Ok(output) => output,
Err(error) => {
error!("Failed to execute `before` script: {error}");
return Ok(());
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
error!(
"`before` script failed with status {}: {stderr}",
output.status.code().unwrap_or(-1)
);
} else {
let stdout = String::from_utf8_lossy(&output.stdout);
#[expect(clippy::print_stdout)]
if !stdout.is_empty() {
println!("{}", stdout.trim());
}
}
return Ok(());
}
fn after(&self, manifest_path: &Path, cfg: &PickConfig) -> Result<()> {
let script = match &self.after {
None => {
return Ok(());
}
Some(script) => {
trace!("Running `after` script");
let mut temp_file =
tempfile::NamedTempFile::new().context("while creating temporary script")?;
writeln!(temp_file, "{}", script).context("while creating temporary script")?;
temp_file
}
};
let mut cmd = std::process::Command::new("bash");
cmd.arg(script.path());
cmd.current_dir(&cfg.work_dir(manifest_path)?);
for (key, value) in &self.env {
cmd.env(key, value);
}
let output = match cmd.output() {
Ok(output) => output,
Err(error) => {
error!("Failed to execute `after` script: {error}");
return Ok(());
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
error!(
"`after` script failed with status {}: {stderr}",
output.status.code().unwrap_or(-1)
);
} else {
let stdout = String::from_utf8_lossy(&output.stdout);
#[expect(clippy::print_stdout)]
if !stdout.is_empty() {
println!("{}", stdout.trim());
}
}
return Ok(());
}
fn run(&self, manifest_path: &Path, cfg: &PickConfig, ctx: TaskContext) -> Result<()> {
let script = match self.script.get(&ctx.task) {
None => {
warn!("No script named \"{}\"", ctx.task);
return Ok(());
}
Some(script) => {
trace!("Running script for {}: {}", ctx.path_rel_str, ctx.task);
let mut temp_file =
tempfile::NamedTempFile::new().context("while creating temporary script")?;
writeln!(temp_file, "{}", script).context("while creating temporary script")?;
temp_file
}
};
let mut cmd = std::process::Command::new("bash");
cmd.arg(script.path());
cmd.current_dir(&cfg.work_dir(manifest_path)?);
cmd.env("PICK_FILE", &ctx.path_abs_str);
cmd.env("PICK_RELATIVE", &ctx.path_rel_str);
for (key, value) in &self.env {
cmd.env(key, value);
}
let output = match cmd.output() {
Ok(output) => output,
Err(error) => {
error!("Failed to execute script for {}: {error}", ctx.path_rel_str);
return Ok(());
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
error!(
"Script for {} failed with status {}: {stderr}",
ctx.path_rel_str,
output.status.code().unwrap_or(-1)
);
} else {
let stdout = String::from_utf8_lossy(&output.stdout);
#[expect(clippy::print_stdout)]
if !stdout.is_empty() {
println!("{}", stdout.trim());
}
}
return Ok(());
}
}

48
src/tool/mod.rs Normal file
View File

@ -0,0 +1,48 @@
use anyhow::Result;
use serde::{Deserialize, de::DeserializeOwned};
use std::{
fmt::Debug,
path::{Path, PathBuf},
};
mod bash;
pub use bash::*;
use crate::manifest::PickConfig;
pub trait PickTool: Debug + DeserializeOwned {
/// Runs once, before all tasks
fn before(&self, manifest_path: &Path, cfg: &PickConfig) -> Result<()>;
/// Runs once, after all tasks
fn after(&self, manifest_path: &Path, cfg: &PickConfig) -> Result<()>;
/// Runs once per task
fn run(&self, manifest_path: &Path, cfg: &PickConfig, ctx: TaskContext) -> Result<()>;
}
#[derive(Debug, Clone)]
/// All the information available when running a task
pub struct TaskContext {
/// The task to run
pub task: String,
/// The absolute path of the file we're processing
pub path_abs: PathBuf,
/// `self.path_abs` as a string
pub path_abs_str: String,
/// The path of the file we're processing,
/// relative to our working directory.
pub path_rel: PathBuf,
/// `self.path_rel`` as a string
pub path_rel_str: String,
}
#[derive(Debug, Deserialize)]
pub struct ToolConfig {
#[serde(default)]
pub bash: Option<ToolBash>,
}

37
src/util.rs Normal file
View File

@ -0,0 +1,37 @@
use anstyle::{AnsiColor, Color, Style};
pub fn get_styles() -> clap::builder::Styles {
clap::builder::Styles::styled()
.usage(
Style::new()
.bold()
.fg_color(Some(Color::Ansi(AnsiColor::Blue))),
)
.header(
Style::new()
.bold()
.fg_color(Some(Color::Ansi(AnsiColor::Blue))),
)
.literal(
Style::new()
.bold()
.fg_color(Some(Color::Ansi(AnsiColor::BrightBlack))),
)
.invalid(
Style::new()
.bold()
.fg_color(Some(Color::Ansi(AnsiColor::Red))),
)
.error(
Style::new()
.bold()
.fg_color(Some(Color::Ansi(AnsiColor::Red))),
)
.valid(
Style::new()
.bold()
.underline()
.fg_color(Some(Color::Ansi(AnsiColor::Green))),
)
.placeholder(Style::new().fg_color(Some(Color::Ansi(AnsiColor::White))))
}