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;
mod structure;
pub mod structure;
pub fn args() -> Args {
return Args::parse();

View File

@@ -3,11 +3,11 @@ use clap::{Parser, Subcommand};
#[derive(Parser)]
pub struct Args {
#[command(subcommand)]
command: CommandArg
pub command: CommandArg
}
#[derive(Subcommand)]
enum CommandArg {
pub enum CommandArg {
Build,
Health,
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 struct Build;
impl Command for Build {
fn execute(&self, _args: &HashMap<String, String>) -> Result<(), String> {
pub fn build() -> () {
let mut build_execution = BuildExecution::new();
return build_execution.execute();
}
fn new() -> Self
where
Self: Sized,
{
return Build {}
}
build_execution.execute().expect("build failed")
}

View File

@@ -1,11 +1,6 @@
use std::{collections::HashMap, process, io::ErrorKind};
use std::{process::Command, io::ErrorKind};
use colored::Colorize;
use super::traits::Command;
pub struct Health;
const INFO_ASCIIDOC: &str = "
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
";
impl Command for Health {
fn execute(&self, _args: &HashMap<String, String>) -> Result<(), String> {
Self::health();
return Ok(())
}
pub fn health() {
check_asciidoc();
check_reveal();
}
fn new() -> Self where Self: Sized {
return Self {}
fn check_reveal() -> () {
if reveal_is_installed() {
print_health_ok("asciidoctor-revealjs")
} else {
print_health_not_ok("asciidoctor-revealjs", INFO_REVEAL)
}
}
fn reveal_is_installed() -> bool {
return check_command("asciidoctor-revealjs")
}
impl Health {
fn health() {
Self::check_asciidoc();
Self::check_reveal();
}
fn check_reveal() -> () {
if Self::reveal_is_installed() {
Self::print_health_ok("asciidoctor-revealjs")
fn check_asciidoc() -> () {
if asciidoc_is_installed() {
print_health_ok("asciidoctor")
} else {
Self::print_health_not_ok("asciidoctor-revealjs", INFO_REVEAL)
}
print_health_not_ok("asciidoctor", INFO_ASCIIDOC)
}
}
fn reveal_is_installed() -> bool {
return Self::check_command("asciidoctor-revealjs")
}
fn asciidoc_is_installed() -> bool {
return check_command("asciidoctor")
}
fn check_asciidoc() -> () {
if Self::asciidoc_is_installed() {
Self::print_health_ok("asciidoctor")
} else {
Self::print_health_not_ok("asciidoctor", INFO_ASCIIDOC)
}
}
fn asciidoc_is_installed() -> bool {
return Self::check_command("asciidoctor")
}
fn check_command(command: &str) -> bool {
return match process::Command::new(command)
fn check_command(command: &str) -> bool {
return match Command::new(command)
.output() {
Ok(_) => true,
Err(e) => ErrorKind::NotFound != e.kind()
}
}
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())
}
}
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 executions;
mod build;
mod health;
mod reveal;
pub mod build;
pub mod health;
pub mod install_reveal;
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;
mod args;
use std::collections::HashMap;
use std::env;
use commands::traits::Command;
use commands::CommandRegistry;
use self::args::{args, structure::CommandArg};
use self::commands::build::build;
use self::commands::health::health;
use self::commands::install_reveal::install_reveal;
use self::args::args;
pub struct App {
command_regisrty: CommandRegistry,
}
pub struct 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();
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());
}
fn execute_path(self, path: &String, args: &HashMap<String, String>) {
let command = self.command_regisrty.command_by(path);
if let Some(c) = command {
self.execute_command(c, args)
} else {
println!("command not found")
match args.command {
CommandArg::Build => build(),
CommandArg::Health => health(),
CommandArg::InstallReveal => install_reveal()
}
}
fn execute_command(&self, c: &Box<dyn Command>, args: &HashMap<String, String>) {
let result = c.execute(args);
pub fn new() -> Self {
Self {}
}
match result {
Ok(_) => println!("successfully executed"),
Err(message) => println!("{message}")
}
}
}

View File

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

View File

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