refactored the project using the clap crate

This commit is contained in:
2023-03-08 21:35:15 +01:00
parent e469576d2c
commit 4b789e60c9
10 changed files with 92 additions and 233 deletions

View File

@@ -2,7 +2,7 @@ use clap::Parser;
use self::structure::Args; use self::structure::Args;
mod structure; pub mod structure;
pub fn args() -> Args { pub fn args() -> Args {
return Args::parse(); return Args::parse();

View File

@@ -3,11 +3,11 @@ use clap::{Parser, Subcommand};
#[derive(Parser)] #[derive(Parser)]
pub struct Args { pub struct Args {
#[command(subcommand)] #[command(subcommand)]
command: CommandArg pub command: CommandArg
} }
#[derive(Subcommand)] #[derive(Subcommand)]
enum CommandArg { pub enum CommandArg {
Build, Build,
Health, Health,
InstallReveal InstallReveal

View File

@@ -1,19 +1,6 @@
use std::collections::HashMap; use super::executions::build_execution::BuildExecution;
use super::{executions::build_execution::BuildExecution, traits::Command}; pub fn build() -> () {
let mut build_execution = BuildExecution::new();
pub struct Build; build_execution.execute().expect("build failed")
impl Command for Build {
fn execute(&self, _args: &HashMap<String, String>) -> Result<(), String> {
let mut build_execution = BuildExecution::new();
return build_execution.execute();
}
fn new() -> Self
where
Self: Sized,
{
return Build {}
}
} }

View File

@@ -1,11 +1,6 @@
use std::{collections::HashMap, process, io::ErrorKind}; use std::{process::Command, io::ErrorKind};
use colored::Colorize; use colored::Colorize;
use super::traits::Command;
pub struct Health;
const INFO_ASCIIDOC: &str = " const INFO_ASCIIDOC: &str = "
Install the binary with your package manager! Install the binary with your package manager!
@@ -28,64 +23,49 @@ Option 2:
- Make sure the binary is called asciidoctor-revealjs and not asciidoctor-revealjs-linux or similar - Make sure the binary is called asciidoctor-revealjs and not asciidoctor-revealjs-linux or similar
"; ";
impl Command for Health { pub fn health() {
fn execute(&self, _args: &HashMap<String, String>) -> Result<(), String> { check_asciidoc();
Self::health(); check_reveal();
return Ok(())
}
fn new() -> Self where Self: Sized {
return Self {}
}
} }
fn check_reveal() -> () {
impl Health { if reveal_is_installed() {
fn health() { print_health_ok("asciidoctor-revealjs")
Self::check_asciidoc(); } else {
Self::check_reveal(); print_health_not_ok("asciidoctor-revealjs", INFO_REVEAL)
} }
}
fn check_reveal() -> () {
if Self::reveal_is_installed() { fn reveal_is_installed() -> bool {
Self::print_health_ok("asciidoctor-revealjs") return check_command("asciidoctor-revealjs")
} else { }
Self::print_health_not_ok("asciidoctor-revealjs", INFO_REVEAL)
} fn check_asciidoc() -> () {
} if asciidoc_is_installed() {
print_health_ok("asciidoctor")
fn reveal_is_installed() -> bool { } else {
return Self::check_command("asciidoctor-revealjs") print_health_not_ok("asciidoctor", INFO_ASCIIDOC)
} }
}
fn check_asciidoc() -> () {
if Self::asciidoc_is_installed() { fn asciidoc_is_installed() -> bool {
Self::print_health_ok("asciidoctor") return check_command("asciidoctor")
} else { }
Self::print_health_not_ok("asciidoctor", INFO_ASCIIDOC)
} fn check_command(command: &str) -> bool {
} return match Command::new(command)
.output() {
fn asciidoc_is_installed() -> bool { Ok(_) => true,
return Self::check_command("asciidoctor") Err(e) => ErrorKind::NotFound != e.kind()
} }
}
fn check_command(command: &str) -> bool {
return match process::Command::new(command) fn print_health_ok(name: &str) {
.output() { println!("- ✔️ {}", name.bright_green());
Ok(_) => true, }
Err(e) => ErrorKind::NotFound != e.kind()
} fn print_health_not_ok(name: &str, info: &str) {
} println!("- ❗{}", name.bright_red());
println!("{}", info.bright_black())
fn print_health_ok(name: &str) {
println!("- ✔️ {}", name.bright_green());
}
fn print_health_not_ok(name: &str, info: &str) {
println!("- ❗{}", name.bright_red());
println!("{}", info.bright_black())
}
} }

View File

@@ -0,0 +1,26 @@
use std::{fs::File, io::Write};
use crate::app::fs_util;
const ASCIIDOC_REVEAL_VERSION: &str= "v4.1.0-rc.5";
pub fn install_reveal() -> () {
let result = reqwest::blocking::get(url())
.expect("Could not download reveal. Make sure you are connected to the internet");
let binary = result.bytes().expect("could not get binary");
let home_path = home::home_dir().expect("could not find home dir");
let save_path = format!("{}/.docki/asciidoctor-revealjs", home_path.display());
let save_dir = format!("{}/.docki", home_path.display());
fs_util::create_dir_recursive(save_dir.as_str());
let mut file = File::create(save_path).expect("could not save binary");
file.write_all(&binary).expect("could not save binary");
}
fn url() -> String {
return format!("https://github.com/asciidoctor/asciidoctor-reveal.js/releases/download/{}/asciidoctor-revealjs-linux", ASCIIDOC_REVEAL_VERSION);
}

View File

@@ -1,48 +1,6 @@
use std::collections::HashMap;
use traits::Command;
use self::{build::Build, health::Health, reveal::Reveal, serve::Serve};
pub mod traits; pub mod traits;
pub mod executions; pub mod executions;
mod build; pub mod build;
mod health; pub mod health;
mod reveal; pub mod install_reveal;
mod serve; mod serve;
pub struct CommandRegistry {
commands: HashMap<String, Box<dyn Command>>
}
impl CommandRegistry {
pub fn register_all(&mut self) {
let registry = self;
registry.register("/build".to_string(), Box::new(Build::new()), true);
registry.register("/health".to_string(), Box::new(Health::new()), true);
registry.register("/install-reveal".to_string(), Box::new(Reveal::new()), true);
registry.register("/serve".to_string(), Box::new(Serve::new()), true)
}
pub fn register(&mut self, path: String, command: Box<dyn Command>, enabled: bool) {
if enabled {
self.commands.insert(path, command);
}
}
pub fn new() -> CommandRegistry {
let mut registry = CommandRegistry { commands: HashMap::new() };
registry.register_all();
registry
}
pub fn command_by(&self, path: &String) -> Option<&Box<dyn Command>> {
let command = self.commands.get(path);
return command;
}
}

View File

@@ -1,43 +0,0 @@
use std::{fs::File, io::Write};
use crate::app::fs_util;
use super::traits::Command;
pub struct Reveal;
const ASCIIDOC_REVEAL_VERSION: &str= "v4.1.0-rc.5";
fn url() -> String {
return format!("https://github.com/asciidoctor/asciidoctor-reveal.js/releases/download/{}/asciidoctor-revealjs-linux", ASCIIDOC_REVEAL_VERSION);
}
impl Command for Reveal {
fn execute(&self, _args: &std::collections::HashMap<String, String>) -> Result<(), String> {
Self::install_asciidocto_revealjs();
return Ok(())
}
fn new() -> Self where Self: Sized {
return Self {}
}
}
impl Reveal {
fn install_asciidocto_revealjs() -> () {
let result = reqwest::blocking::get(url())
.expect("Could not download reveal. Make sure you are connected to the internet");
let binary = result.bytes().expect("could not get binary");
let home_path = home::home_dir().expect("could not find home dir");
let save_path = format!("{}/.docki/asciidoctor-revealjs", home_path.display());
let save_dir = format!("{}/.docki", home_path.display());
fs_util::create_dir_recursive(save_dir.as_str());
let mut file = File::create(save_path).expect("could not save binary");
file.write_all(&binary).expect("could not save binary");
}
}

View File

@@ -3,76 +3,32 @@ pub mod builder;
pub mod fs_util; pub mod fs_util;
mod args; mod args;
use std::collections::HashMap;
use std::env; use std::env;
use commands::traits::Command; use self::args::{args, structure::CommandArg};
use commands::CommandRegistry; use self::commands::build::build;
use self::commands::health::health;
use self::commands::install_reveal::install_reveal;
use self::args::args; pub struct App;
pub struct App {
command_regisrty: CommandRegistry,
}
impl App { impl App {
pub fn new() -> App {
return App {
command_regisrty: CommandRegistry::new()
}
}
pub fn start(self, old_args: Vec<String>) { pub fn start(&self) {
let args = args(); let args = args();
Self::preapare_env_path();
let command_args = &old_args[1..];
let mut path = String::from("");
let mut argument_map = HashMap::new();
let mut only_options_left = false;
for (index, argument) in command_args.iter().enumerate() {
if argument.starts_with("--") {
only_options_left = true;
let value = command_args.get(index + 1);
if let Some(v) = value {
if v.starts_with("--") {
argument_map.insert(argument.replace("--", ""), String::from(""));
} else {
argument_map.insert(argument.replace("--", ""), String::from(v));
}
} else {
argument_map.insert(argument.replace("--", ""), String::from(""));
}
} else if !only_options_left {
path.push_str(&format!("/{argument}"))
}
}
self.execute_path(&path, &argument_map);
}
fn preapare_env_path() {
env::set_var("PATH", fs_util::docki_path_env()); env::set_var("PATH", fs_util::docki_path_env());
}
fn execute_path(self, path: &String, args: &HashMap<String, String>) { match args.command {
let command = self.command_regisrty.command_by(path); CommandArg::Build => build(),
CommandArg::Health => health(),
if let Some(c) = command { CommandArg::InstallReveal => install_reveal()
self.execute_command(c, args)
} else {
println!("command not found")
} }
} }
fn execute_command(&self, c: &Box<dyn Command>, args: &HashMap<String, String>) { pub fn new() -> Self {
let result = c.execute(args); Self {}
match result {
Ok(_) => println!("successfully executed"),
Err(message) => println!("{message}")
}
} }
} }

View File

@@ -3,12 +3,9 @@ mod app;
#[cfg(test)] #[cfg(test)]
mod test; mod test;
use std::env;
use app::App; use app::App;
fn main() { fn main() {
let app = App::new(); let app = App::new();
let args = env::args().collect(); app.start();
app.start(args);
} }

View File

@@ -1,5 +1,3 @@
use std::{fs, path::Path};
use crate::app::fs_util; use crate::app::fs_util;
#[test] #[test]