Mini task runner configurable via YAML file

A Rust mini task runner configurable via YAML, enabling execution of user-defined shell commands with error handling and CLI support.

Brief Introduction

Mini task runner configurable via YAML file (rust)
DESCRIPTION:
A simple task runner written in Rust that reads configuration from a YAML file and allows executing user-defined tasks with shell commands. The project includes YAML parsing, error handling, and execution of external commands.

ADDITIONAL NOTES:
The task runner is designed for Unix-like environments (Linux, macOS) but also works on Windows with compatible shells. The YAML file must follow the structure defined in the code (map of tasks with list of commands).

EXPLANATIONS:
- The main structure is a Config struct that maps the tasks defined in the YAML file.
- Each task is a list of shell commands to be executed sequentially.
- serde_yaml is used to deserialize the YAML file into Rust structs.
- Clap manages the command line interface to specify the task to run and the configuration file.
- The run_task function executes shell commands one after another, propagating any errors.
- Anyhow simplifies error handling with the Result type.
- The code is commented in Italian to facilitate understanding.

Example Code: rust

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(())
}
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

Complete Example

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 task

What do you need?

Rust 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

Similar Topics

Mini phonebook saved in CSV
Simple Rust phonebook program to add view and save contacts in CSV file using csv crate with a textual interface for beginners managing persistent contact lists
Mini multiple choice quiz from terminal
A simple Rust terminal multiple choice quiz presenting questions with four options and validating user input for beginners learning Rust IO handling.
Guess the Number Mini Game with Difficulty Levels
A Rust console game where players guess a random number with three difficulty levels controlling range and attempts. Ideal for beginners learning Rust basics.
Mini quick note system saved in Markdown
Simple Rust program for creating, saving, and reading quick Markdown notes locally in a timestamped folder without a database.
Minimal HTTP Server with Multiple Route Handling and JSON Responses in Rust
Complete Rust HTTP server example using warp crate with multiple routes and JSON responses, ideal for async web applications on port 33.
Mini template engine to generate static HTML pages
A simple Rust template engine for generating static HTML pages by replacing variables within templates using HashMap, ideal for basic static site generation.
Configurable logging system with levels and multiple outputs
Configurable Rust logging system with levels (Error, Warn, Info, Debug) and multiple outputs like console and file for modular, extendable use.
Library to implement a plugin system via traits and dynamic loading in Rust
Rust plugin system using traits and dynamic loading for extensible apps. Load shared libraries (.so/.dll) at runtime with safe ABI compatibility.