zamm 0.2.1

Quick and dirty script executor
use clap::{crate_description, App, SubCommand};
use duct::cmd;
use path_absolutize::Absolutize;
use serde::Deserialize;
use serde_json::{Result, Value};
use std::env;
use std::fs;
use std::io::prelude::*;
use std::io::BufReader;
use std::io::ErrorKind;
use std::path::Path;
use std::path::PathBuf;
use std::process;

const KB_FILE: &str = ".zamm/kb.json";

#[derive(Deserialize)]
struct Command {
    name: Option<String>,
    invocation: String,
    command: String,
}

fn parse_commands(path: &str, commands: &mut Vec<Command>) -> () {
    // read file
    let contents = match fs::read_to_string(path) {
        Ok(result) => result,
        Err(err) => match err.kind() {
            ErrorKind::NotFound => {
                return;
            }
            _ => {
                eprintln!("Error reading file: {}", err);
                process::exit(1);
            }
        },
    };

    // parse file contents into JSON values
    let values: Vec<Value> = match serde_json::from_str(&contents) {
        Ok(result) => result,
        Err(err) => {
            eprintln!("Error parsing JSON: {}", err);
            process::exit(1);
        }
    };

    // parse JSON values into Commands
    values.into_iter().for_each(|v| {
        if v.get("invocation").is_some() && v.get("command").is_some() {
            match serde_json::from_value::<Command>(v) {
                Ok(result) => commands.push(result),
                Err(err) => {
                    eprintln!("Error parsing command: {}", err);
                    std::process::exit(1);
                }
            }
        }
    });
}

fn force_pb_to_str(p: PathBuf) -> String {
    p.into_os_string()
        .into_string()
        .expect("Can't turn PathBuf into string")
}

fn main() -> Result<()> {
    // parse commands in home dir
    let home_dir = match dirs::home_dir() {
        Some(dir) => force_pb_to_str(dir),
        None => {
            eprintln!("Can't find home directory");
            std::process::exit(1);
        }
    };
    let home_dir_kb_path: String = format!("{}/{}", home_dir, KB_FILE);
    let mut commands = vec![];
    parse_commands(&home_dir_kb_path, &mut commands);

    // parse commands in current dir
    match Path::new(KB_FILE).absolutize() {
        Ok(full_path) => {
            let path_str = force_pb_to_str(full_path.to_path_buf());
            parse_commands(&path_str, &mut commands);
        }
        Err(_) => (),
    };

    // Build list of subcommands
    let mut app = App::new("zamm").about(crate_description!());
    for cmd in &commands {
        app = app.subcommand(SubCommand::with_name(&cmd.invocation).about(cmd.name.as_deref()));
    }

    // Execute command
    let matches = app.get_matches_mut();
    match matches.subcommand_name() {
        None => {
            app.print_help().unwrap();
            process::exit(0);
        }
        Some(invocation) => {
            for cmd in &commands {
                if cmd.invocation == invocation {
                    println!("Executing command: {}", cmd.command);
                    let cmd_execution = cmd!("sh", "-c", &cmd.command);
                    let reader = cmd_execution
                        .stderr_to_stdout()
                        .reader()
                        .expect("Can't get stdout");
                    let mut reader = BufReader::new(reader);

                    let mut line = String::new();
                    let mut should_continue = true;
                    while should_continue {
                        match reader.read_line(&mut line) {
                            Err(_) => {
                                eprintln!("Execution failed");
                                process::exit(1);
                            }
                            Ok(bytes_read) => {
                                should_continue = bytes_read > 0;
                                print!("{}", line);
                                line.clear();
                            }
                        }
                    }
                }
            }
        }
    }

    Ok(())
}