A Rust mini task runner configurable via YAML, enabling execution of user-defined shell commands with error handling and CLI support.
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::process::Command;
use anyhow::{Context, Result};
use clap::Parser;
use serde::Deserialize;
// Definition of the configuration structure mapping the tasks
#[derive(Debug, Deserialize)]
struct Config {
tasks: HashMap<String, Vec<String>>,
}
// Definition of the CLI with clap
#[derive(Parser, Debug)]
#[command(author = "Senior Software Engineer", version = "1.0", about = "Mini task runner configurable via YAML")]
struct Cli {
/// Name of the task to execute
task: String,
/// Path to the YAML configuration file
#[arg(short, long, default_value = "tasks.yaml")]
config: String,
}
fn main() -> Result<()> {
// Parse CLI arguments
let cli = Cli::parse();
// Load and parse the YAML file
let config = load_config(&cli.config)?;
// Retrieve the requested task
let commands = config.tasks.get(&cli.task)
.with_context(|| format!("Task '{}' not found in configuration", cli.task))?;
println!("Executing task '{}':", cli.task);
// Sequential execution of commands
run_task(commands)?;
println!("Task '{}' completed successfully.", cli.task);
Ok(())
}
/// Loads and deserializes the YAML file into Config
fn load_config(path: &str) -> Result<Config> {
let mut file = File::open(path)
.with_context(|| format!("Unable to open configuration file '{}'", path))?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let config: Config = serde_yaml::from_str(&contents)
.with_context(|| "Error parsing the YAML file")?;
Ok(config)
}
/// Executes shell commands sequentially
fn run_task(commands: &[String]) -> Result<()> {
for cmd in commands {
println!("Running: {}", cmd);
// Execute the command via shell
// On Windows it might be necessary to adapt the command
let status = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(["/C", cmd])
.status()
} else {
Command::new("sh")
.arg("-c")
.arg(cmd)
.status()
}?;
if !status.success() {
return Err(anyhow::anyhow!("Command '{}' failed with code {:?}", cmd, status.code()));
}
}
Ok(())
}use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::process::Command;
use anyhow::{Context, Result};
use clap::Parser;
use serde::Deserialize;
// Definition of the configuration structure mapping the tasks
#[derive(Debug, Deserialize)]
struct Config {
tasks: HashMap<String, Vec<String>>,
}
// Definition of the CLI with clap
#[derive(Parser, Debug)]
#[command(author = "Senior Software Engineer", version = "1.0", about = "Mini task runner configurable via YAML")]
struct Cli {
/// Name of the task to execute
task: String,
/// Path to the YAML configuration file
#[arg(short, long, default_value = "tasks.yaml")]
config: String,
}
fn main() -> Result<()> {
// Parse CLI arguments
let cli = Cli::parse();
// Load and parse the YAML file
let config = load_config(&cli.config)?;
// Retrieve the requested task
let commands = config.tasks.get(&cli.task)
.with_context(|| format!("Task '{}' not found in configuration", cli.task))?;
println!("Executing task '{}':", cli.task);
// Sequential execution of commands
run_task(commands)?;
println!("Task '{}' completed successfully.", cli.task);
Ok(())
}
/// Loads and deserializes the YAML file into Config
fn load_config(path: &str) -> Result<Config> {
let mut file = File::open(path)
.with_context(|| format!("Unable to open configuration file '{}'", path))?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let config: Config = serde_yaml::from_str(&contents)
.with_context(|| "Error parsing the YAML file")?;
Ok(config)
}
/// Executes shell commands sequentially
fn run_task(commands: &[String]) -> Result<()> {
for cmd in commands {
println!("Running: {}", cmd);
// Execute the command via shell
// On Windows it might be necessary to adapt the command
let status = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(["/C", cmd])
.status()
} else {
Command::new("sh")
.arg("-c")
.arg(cmd)
.status()
}?;
if !status.success() {
return Err(anyhow::anyhow!("Command '{}' failed with code {:?}", cmd, status.code()));
}
}
Ok(())
}
// Example YAML configuration file content (save as tasks.yaml in the same directory):
//
// build:
// - "echo Building project..."
// - "cargo build"
// test:
// - "echo Running tests..."
// - "cargo test"
// clean:
// - "echo Cleaning project..."
// - "cargo clean"
// To run this example:
// 1. Save this Rust code in a file, e.g., main.rs
// 2. Create a tasks.yaml file with the above content
// 3. Build the Rust project with `cargo build` or run directly with `cargo run -- <task_name>`
// For example: `cargo run -- build` to execute the build taskRust 1.65+
Cargo dependency: serde = { version = "1.0", features = ["derive"] }
Cargo dependency: serde_yaml = "0.9" for YAML parsing
Cargo dependency: anyhow = "1.0" for error handling
Cargo dependency: clap = { version = "4.0", features = ["derive"] } for CLI
YAML configuration file (e.g. tasks.yaml) defining tasks and commands
No specific hardware required (standalone software)
Configuration: the YAML file must be placed in the same folder as the executable or specified via CLI argument