Merge branch 'dev' into 'main'
Release 1.0 See merge request implo/docki-cli!4
This commit is contained in:
2101
Cargo.lock
generated
2101
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "docki"
|
||||
version = "0.3.0"
|
||||
version = "1.0.0"
|
||||
edition = "2021"
|
||||
description = "cli for building and publishing documentation using asciidoctor"
|
||||
license-file = "LICENSE.txt"
|
||||
@@ -9,9 +9,14 @@ license-file = "LICENSE.txt"
|
||||
|
||||
[dependencies]
|
||||
bytes = "1.4.0"
|
||||
clap = { version = "4.1.8", features = ["derive"] }
|
||||
colored = "2.0.0"
|
||||
futures = "0.3.26"
|
||||
home = "0.5.4"
|
||||
live-server = "0.6.0"
|
||||
notify = { version = "5.1.0", features = ["serde"] }
|
||||
regex = "1.7.1"
|
||||
reqwest = { version = "0.11.14", features = ["blocking"] }
|
||||
text_io = "0.1.12"
|
||||
tokio = { version = "1.26.0", features = ["full"] }
|
||||
zip-extract = "0.1.1"
|
||||
|
||||
10
src/app/args/mod.rs
Normal file
10
src/app/args/mod.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
use clap::Parser;
|
||||
|
||||
use self::structure::Args;
|
||||
|
||||
pub mod structure;
|
||||
|
||||
pub fn args() -> Args {
|
||||
return Args::parse();
|
||||
|
||||
}
|
||||
23
src/app/args/structure.rs
Normal file
23
src/app/args/structure.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
#[derive(Parser)]
|
||||
pub struct Args {
|
||||
#[command(subcommand)]
|
||||
pub command: CommandArg
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum CommandArg {
|
||||
/// Builds the documentation into a dist folder
|
||||
Build,
|
||||
/// Checks if everything required for docki is installed
|
||||
Health,
|
||||
/// Helper command for installing asciidoctor-reveal-js
|
||||
InstallReveal,
|
||||
/// Starts a Webserver with the live preview of the Documentation
|
||||
Serve {
|
||||
/// Port for the Live Server
|
||||
#[arg(short, long)]
|
||||
port: Option<u16>
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,6 @@ use std::process;
|
||||
|
||||
use regex::Regex;
|
||||
|
||||
use super::Builder;
|
||||
|
||||
fn exec_command(command: &mut process::Command) -> Result<(), String> {
|
||||
let result = command.output();
|
||||
|
||||
@@ -11,11 +9,13 @@ fn exec_command(command: &mut process::Command) -> Result<(), String> {
|
||||
if success.stderr.len() == 0 {
|
||||
return Ok(());
|
||||
} else {
|
||||
return Err(AsciiDoctorDocsBuilder::from_utf8(success.stderr));
|
||||
return Err(from_utf8(success.stderr));
|
||||
}
|
||||
} else {
|
||||
println!("{}", result.unwrap_err());
|
||||
return Err("asciidoctor not installed. For more information run docki health!".to_string());
|
||||
return Err(
|
||||
"asciidoctor not installed. For more information run docki health!".to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,30 +50,34 @@ fn parent_path(child_path: &str) -> String {
|
||||
}
|
||||
|
||||
pub fn path_between(from: String, to: String) -> String {
|
||||
let from_segments = transform_input_to_clone_split(&from);
|
||||
let from_segments = transform_input_to_clone_split(&from);
|
||||
let to_segments = transform_input_to_clone_split(&to);
|
||||
let last_matching_index = matching_from_start(&from_segments, &to_segments);
|
||||
let number_of_backs = from_segments.len() - last_matching_index;
|
||||
let mut path_between = path_back(number_of_backs);
|
||||
let path_to_to_path = &to_segments[last_matching_index..];
|
||||
path_between.push_str(&path_to_to_path.join("/"));
|
||||
return path_between;
|
||||
return path_between;
|
||||
}
|
||||
|
||||
fn transform_input_to_clone_split(input: &String) -> Vec<String> {
|
||||
let regex = Regex::new(r"/$").unwrap();
|
||||
let first_transformation = input.clone().replace("./", "");
|
||||
return regex.replace_all(&first_transformation, "")
|
||||
.to_string().split("/")
|
||||
return regex
|
||||
.replace_all(&first_transformation, "")
|
||||
.to_string()
|
||||
.split("/")
|
||||
.collect::<Vec<&str>>()
|
||||
.iter().map(|s| s.to_string()).collect()
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
}
|
||||
|
||||
fn path_back(count: usize) -> String {
|
||||
let mut path = "".to_string();
|
||||
|
||||
for _ in 0..count {
|
||||
path.push_str("../");
|
||||
for _ in 0..count {
|
||||
path.push_str("../");
|
||||
}
|
||||
|
||||
return path;
|
||||
@@ -81,8 +85,8 @@ fn path_back(count: usize) -> String {
|
||||
|
||||
pub fn matching_from_start(from_segments: &Vec<String>, to_segments: &Vec<String>) -> usize {
|
||||
for (index, from_segment) in from_segments.iter().enumerate() {
|
||||
if let Some(to_segment) = to_segments.get(index){
|
||||
if from_segment != to_segment {
|
||||
if let Some(to_segment) = to_segments.get(index) {
|
||||
if from_segment != to_segment {
|
||||
return index;
|
||||
}
|
||||
} else {
|
||||
@@ -93,29 +97,19 @@ pub fn matching_from_start(from_segments: &Vec<String>, to_segments: &Vec<String
|
||||
return from_segments.len();
|
||||
}
|
||||
|
||||
pub struct AsciiDoctorDocsBuilder;
|
||||
|
||||
impl Builder for AsciiDoctorDocsBuilder {
|
||||
fn build(&self, in_path: &str, out_path: &str) -> Result<(), String> {
|
||||
let mut command = asciidoctor_docs(in_path, out_path);
|
||||
return exec_command(&mut command);
|
||||
}
|
||||
pub fn build_doc(in_path: &str, out_path: &str) -> Result<(), String> {
|
||||
let mut command = asciidoctor_docs(in_path, out_path);
|
||||
return exec_command(&mut command);
|
||||
}
|
||||
|
||||
impl AsciiDoctorDocsBuilder {
|
||||
fn from_utf8(input: Vec<u8>) -> String {
|
||||
return match String::from_utf8(input) {
|
||||
Ok(m) => m,
|
||||
Err(e) => panic!("could not print error message: {}", e),
|
||||
};
|
||||
}
|
||||
pub fn build_slide(in_path: &str, out_path: &str) -> Result<(), String> {
|
||||
let mut command = asciidoctor_slides(in_path, out_path);
|
||||
return exec_command(&mut command);
|
||||
}
|
||||
|
||||
pub struct AsciiDoctorSlideBuilder;
|
||||
|
||||
impl Builder for AsciiDoctorSlideBuilder {
|
||||
fn build(&self, in_path: &str, out_path: &str) -> Result<(), String> {
|
||||
let mut command = asciidoctor_slides(in_path, out_path);
|
||||
return exec_command(&mut command);
|
||||
}
|
||||
fn from_utf8(input: Vec<u8>) -> String {
|
||||
return match String::from_utf8(input) {
|
||||
Ok(m) => m,
|
||||
Err(e) => panic!("could not print error message: {}", e),
|
||||
};
|
||||
}
|
||||
53
src/app/build/mod.rs
Normal file
53
src/app/build/mod.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use std::fs;
|
||||
|
||||
use self::asciidoctor::{build_doc, build_slide};
|
||||
|
||||
use super::fs_util;
|
||||
|
||||
pub mod asciidoctor;
|
||||
|
||||
pub trait Builder {
|
||||
fn build(&self, in_path: &str, out_path: &str) -> Result<(), String>;
|
||||
}
|
||||
|
||||
pub fn docki_build(in_path: &str) -> DockiBuildResult {
|
||||
let out_path = in_path.replace("/docs/", "/dist/");
|
||||
let convert_out_path = out_path.replace(".adoc", ".html");
|
||||
|
||||
if in_path.starts_with("./docs/slides/") && in_path.ends_with(".adoc") {
|
||||
if let Err(err) = build_slide(&in_path, &convert_out_path) {
|
||||
return DockiBuildResult::Err(err);
|
||||
}
|
||||
|
||||
DockiBuildResult::Slide(convert_out_path)
|
||||
} else if in_path.ends_with(".adoc") {
|
||||
if let Err(err) = build_doc(&in_path, &convert_out_path) {
|
||||
return DockiBuildResult::Err(err);
|
||||
}
|
||||
|
||||
DockiBuildResult::Doc(convert_out_path)
|
||||
} else {
|
||||
if let Err(err) = copy(&in_path, &out_path) {
|
||||
return DockiBuildResult::Err(err);
|
||||
}
|
||||
|
||||
DockiBuildResult::Copy(out_path)
|
||||
}
|
||||
}
|
||||
|
||||
fn copy(in_path: &str, out_path: &str) -> Result<(), String> {
|
||||
fs_util::create_parent_dir_recursive(out_path);
|
||||
|
||||
if let Err(err) = fs::copy(in_path, out_path) {
|
||||
return Err(err.to_string())
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub enum DockiBuildResult {
|
||||
Slide(String),
|
||||
Doc(String),
|
||||
Copy(String),
|
||||
Err(String),
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
pub mod asciidoctor;
|
||||
|
||||
pub trait Builder {
|
||||
fn build(&self, in_path: &str, out_path: &str) -> Result<(), String>;
|
||||
}
|
||||
@@ -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> {
|
||||
let mut build_execution = BuildExecution::new();
|
||||
return build_execution.execute();
|
||||
}
|
||||
|
||||
fn new() -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
return Build {}
|
||||
}
|
||||
pub async fn build() -> () {
|
||||
let mut build_execution = BuildExecution::new();
|
||||
build_execution.execute().await.expect("build failed")
|
||||
}
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
use std::{fs, path::{Path, PathBuf}, io::Cursor};
|
||||
use std::{
|
||||
io::Cursor,
|
||||
path::PathBuf
|
||||
};
|
||||
|
||||
use crate::app::{
|
||||
builder::{
|
||||
asciidoctor::{AsciiDoctorDocsBuilder, AsciiDoctorSlideBuilder},
|
||||
Builder,
|
||||
},
|
||||
fs_util,
|
||||
build::{docki_build, DockiBuildResult},
|
||||
fs_util::{self, create_dir_recursive}, log::display_status,
|
||||
};
|
||||
|
||||
pub struct BuildExecution {
|
||||
progress: usize,
|
||||
goal: usize,
|
||||
doc_builder: Box<dyn Builder>,
|
||||
slide_builder: Box<dyn Builder>,
|
||||
}
|
||||
|
||||
impl BuildExecution {
|
||||
@@ -20,95 +18,37 @@ impl BuildExecution {
|
||||
return BuildExecution {
|
||||
progress: 0,
|
||||
goal: 0,
|
||||
slide_builder: Box::new(AsciiDoctorSlideBuilder {}),
|
||||
doc_builder: Box::new(AsciiDoctorDocsBuilder {}),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn execute(&mut self) -> Result<(), String> {
|
||||
pub async fn execute(&mut self) -> Result<(), String> {
|
||||
let path = "./docs/".to_string();
|
||||
|
||||
if !Self::directory_exists(&path) {
|
||||
return Err("docs directory does not exist it. Create it or use the template".to_string())
|
||||
if !fs_util::directory_exists(&path) {
|
||||
return Err(
|
||||
"docs directory does not exist it. Create it or use the template".to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
if let Err(error) = Self::prepare() {
|
||||
if let Err(error) = Self::prepare().await {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
|
||||
return self.build_dir(&path);
|
||||
}
|
||||
|
||||
fn build_file(
|
||||
&self,
|
||||
builder: &Box<dyn Builder>,
|
||||
in_path: &str,
|
||||
out_path: &str,
|
||||
) -> Result<(), String> {
|
||||
return builder.build(&in_path, &out_path);
|
||||
}
|
||||
|
||||
fn build_file_and_status(
|
||||
&self,
|
||||
builder: &Box<dyn Builder>,
|
||||
in_path: &str,
|
||||
out_path: &str,
|
||||
conversion_type: &str,
|
||||
) {
|
||||
let result = self.build_file(builder, in_path, out_path);
|
||||
if result.is_ok() {
|
||||
self.display_status(in_path, out_path, conversion_type)
|
||||
} else {
|
||||
self.display_status(in_path, out_path, "error");
|
||||
let error = result.unwrap_err();
|
||||
println!("{error}");
|
||||
}
|
||||
}
|
||||
|
||||
fn copy(&self, in_path: &str, out_path: &str) {
|
||||
let segments: &Vec<&str> = &out_path.split("/").collect();
|
||||
let parent_dir = &segments[0..segments.len() - 1].join("/");
|
||||
Self::create_dir_recursive(parent_dir);
|
||||
let result = fs::copy(in_path, out_path);
|
||||
if result.is_ok() {
|
||||
self.display_status(in_path, out_path, "copy");
|
||||
} else {
|
||||
self.display_status(in_path, out_path, "error");
|
||||
let error = result.unwrap_err();
|
||||
println!("{error}");
|
||||
}
|
||||
}
|
||||
|
||||
fn create_dir_recursive(path: &str) {
|
||||
let mut validated_path = "./".to_string();
|
||||
for segment in path.split("/") {
|
||||
validated_path.push_str(format!("{segment}/").as_str());
|
||||
if !Self::directory_exists(&validated_path) {
|
||||
fs::create_dir(&validated_path).unwrap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn display_status(&self, in_path: &str, out_path: &str, conversion_type: &str) -> () {
|
||||
println!(
|
||||
"({} / {}) [{}] {} -> {}",
|
||||
self.progress, self.goal, conversion_type, in_path, out_path
|
||||
);
|
||||
}
|
||||
|
||||
fn build_doc(&self, in_path: &str, out_path: &str) {
|
||||
self.build_file_and_status(&self.doc_builder, in_path, out_path, "doc");
|
||||
}
|
||||
|
||||
fn prepare() -> Result<(), String> {
|
||||
async fn prepare() -> Result<(), String> {
|
||||
let reveal_version = "3.9.2";
|
||||
let target = format!("https://github.com/hakimel/reveal.js/archive/{reveal_version}.zip");
|
||||
|
||||
let Ok(response) = reqwest::blocking::get(target) else {
|
||||
create_dir_recursive("./docs/slides");
|
||||
|
||||
let Ok(response) = reqwest::get(target).await else {
|
||||
return Err("could not downlaod revealjs".to_string())
|
||||
};
|
||||
|
||||
let Ok(bytes) = response.bytes() else {
|
||||
let Ok(bytes) = response.bytes().await else {
|
||||
return Err("could not extract bytes".to_string())
|
||||
};
|
||||
|
||||
@@ -118,15 +58,7 @@ impl BuildExecution {
|
||||
return Err("could not write extracted archive to disk".to_string());
|
||||
}
|
||||
|
||||
return Ok(())
|
||||
}
|
||||
|
||||
fn build_slide(&self, in_path: &str, out_path: &str) {
|
||||
self.build_file_and_status(&self.slide_builder, in_path, out_path, "slide");
|
||||
}
|
||||
|
||||
fn directory_exists(path: &String) -> bool {
|
||||
Path::new(path).is_dir()
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
fn build_dir(&mut self, path: &str) -> Result<(), String> {
|
||||
@@ -136,28 +68,28 @@ impl BuildExecution {
|
||||
return Err(result.unwrap_err())
|
||||
};
|
||||
|
||||
for (index, path) in paths.iter().enumerate() {
|
||||
for (index, in_path) in paths.iter().enumerate() {
|
||||
self.progress = index + 1;
|
||||
self.goal = paths.len();
|
||||
let result = docki_build(&in_path);
|
||||
|
||||
if path.ends_with(".adoc") && path.starts_with("./docs/slides") {
|
||||
let out_path = path
|
||||
.clone()
|
||||
.replace("adoc", "html")
|
||||
.replace("/docs/", "/dist/");
|
||||
self.build_slide(&path, &out_path)
|
||||
} else if path.ends_with(".adoc") {
|
||||
let out_path = path
|
||||
.clone()
|
||||
.replace("adoc", "html")
|
||||
.replace("/docs/", "/dist/");
|
||||
self.build_doc(&path, &out_path)
|
||||
} else {
|
||||
let out_path = path.clone().replace("/docs/", "/dist/");
|
||||
self.copy(&path, &out_path)
|
||||
match result {
|
||||
DockiBuildResult::Err(err) => {
|
||||
self.display_building_status("Error", in_path, "");
|
||||
println!("{}", err)
|
||||
},
|
||||
DockiBuildResult::Copy(out_path) => self.display_building_status("Copy", &in_path, &out_path),
|
||||
DockiBuildResult::Slide(out_path) => self.display_building_status("Slide", &in_path, &out_path),
|
||||
DockiBuildResult::Doc(out_path) => self.display_building_status("Doc", &in_path, &out_path)
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
fn display_building_status(&self, status_type: &str, in_path: &str, out_path: &str) -> () {
|
||||
let progress_str = format!("{} / {}", self.progress, self.goal);
|
||||
display_status(&progress_str, status_type, in_path, out_path);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
fn new() -> Self where Self: Sized {
|
||||
return Self {}
|
||||
}
|
||||
pub fn health() {
|
||||
check_asciidoc();
|
||||
check_reveal();
|
||||
}
|
||||
|
||||
|
||||
impl Health {
|
||||
fn health() {
|
||||
Self::check_asciidoc();
|
||||
Self::check_reveal();
|
||||
fn check_reveal() -> () {
|
||||
if reveal_is_installed() {
|
||||
print_health_ok("asciidoctor-revealjs")
|
||||
} else {
|
||||
print_health_not_ok("asciidoctor-revealjs", INFO_REVEAL)
|
||||
}
|
||||
|
||||
fn check_reveal() -> () {
|
||||
if Self::reveal_is_installed() {
|
||||
Self::print_health_ok("asciidoctor-revealjs")
|
||||
} else {
|
||||
Self::print_health_not_ok("asciidoctor-revealjs", INFO_REVEAL)
|
||||
}
|
||||
}
|
||||
|
||||
fn reveal_is_installed() -> bool {
|
||||
return Self::check_command("asciidoctor-revealjs")
|
||||
}
|
||||
|
||||
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)
|
||||
.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 reveal_is_installed() -> bool {
|
||||
return check_command("asciidoctor-revealjs")
|
||||
}
|
||||
|
||||
fn check_asciidoc() -> () {
|
||||
if asciidoc_is_installed() {
|
||||
print_health_ok("asciidoctor")
|
||||
} else {
|
||||
print_health_not_ok("asciidoctor", INFO_ASCIIDOC)
|
||||
}
|
||||
}
|
||||
|
||||
fn asciidoc_is_installed() -> bool {
|
||||
return check_command("asciidoctor")
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
|
||||
27
src/app/commands/install_reveal.rs
Normal file
27
src/app/commands/install_reveal.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
use std::{fs::{File, Permissions}, io::Write, os::unix::prelude::PermissionsExt};
|
||||
|
||||
use crate::app::fs_util;
|
||||
|
||||
const ASCIIDOC_REVEAL_VERSION: &str= "v4.1.0-rc.5";
|
||||
|
||||
pub async fn install_reveal() -> () {
|
||||
let result = reqwest::get(url()).await
|
||||
.expect("Could not download reveal. Make sure you are connected to the internet");
|
||||
|
||||
let binary = result.bytes().await.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.set_permissions(Permissions::from_mode(0o770)).expect("could not set permission");
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -1,46 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use traits::Command;
|
||||
|
||||
use self::{build::Build, health::Health, reveal::Reveal};
|
||||
|
||||
pub mod traits;
|
||||
pub mod executions;
|
||||
mod build;
|
||||
mod health;
|
||||
mod reveal;
|
||||
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
pub mod build;
|
||||
pub mod health;
|
||||
pub mod install_reveal;
|
||||
pub mod serve;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
}
|
||||
89
src/app/commands/serve.rs
Normal file
89
src/app/commands/serve.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
use colored::Colorize;
|
||||
use futures::StreamExt;
|
||||
use live_server::listen;
|
||||
use notify::{
|
||||
event::ModifyKind,
|
||||
Event, EventKind, RecursiveMode, Watcher,
|
||||
};
|
||||
use std::{env, path::Path};
|
||||
|
||||
use crate::app::{ watcher::watcher, build::{docki_build, DockiBuildResult}, commands::build::build, log::display_status};
|
||||
|
||||
|
||||
pub async fn serve(port: Option<u16>) {
|
||||
build().await;
|
||||
tokio::join!(watch_and_build(), start_server(port));
|
||||
}
|
||||
|
||||
async fn watch_and_build() {
|
||||
watch(Path::new("./docs"))
|
||||
.await
|
||||
.expect("something went wrong")
|
||||
}
|
||||
|
||||
async fn start_server(port: Option<u16>) {
|
||||
println!("\nServing at {} ", "http://localhost:8080".bold());
|
||||
|
||||
let Ok(()) = listen("localhost", port.unwrap_or(8080), "./dist").await else {
|
||||
panic!("could not start server")
|
||||
};
|
||||
}
|
||||
|
||||
async fn watch(path: &Path) -> notify::Result<()> {
|
||||
let (mut watcher, mut rx) = watcher()?;
|
||||
|
||||
watcher.watch(path.as_ref(), RecursiveMode::Recursive)?;
|
||||
|
||||
while let Some(res) = rx.next().await {
|
||||
let event = res.expect("watching failed");
|
||||
file_change(event)
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn file_change(event: Event) {
|
||||
match event.kind {
|
||||
EventKind::Modify(ModifyKind::Data(_)) => build_file(event.paths),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_file(paths: Vec<std::path::PathBuf>) {
|
||||
let invalid_path_message = "changed path is invalid";
|
||||
let in_path = paths
|
||||
.first()
|
||||
.expect(invalid_path_message)
|
||||
.to_str()
|
||||
.expect(invalid_path_message)
|
||||
.replace(¤t_dir(), "")
|
||||
.replace("/./", "./");
|
||||
|
||||
|
||||
let result = docki_build(&in_path);
|
||||
|
||||
match result {
|
||||
DockiBuildResult::Slide(out_path) => display_rebuilding_status("Slide", &in_path, &out_path),
|
||||
DockiBuildResult::Doc(out_path) => display_rebuilding_status("Doc", &in_path, &out_path),
|
||||
DockiBuildResult::Copy(out_path) => display_rebuilding_status("Copy", &in_path, &out_path),
|
||||
DockiBuildResult::Err(err) => {
|
||||
display_rebuilding_status("Error", &in_path, "");
|
||||
println!("{}", err);
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn display_rebuilding_status(context: &str, in_path: &str, out_path: &str) {
|
||||
display_status("Rebuildng", context, in_path, out_path)
|
||||
}
|
||||
|
||||
fn current_dir() -> String {
|
||||
let err_message = "something went wrong";
|
||||
return String::from(
|
||||
env::current_dir()
|
||||
.expect(err_message)
|
||||
.to_str()
|
||||
.expect(err_message),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -82,3 +82,10 @@ pub fn docki_path_env() -> String {
|
||||
let current = env::var("PATH").unwrap_or("".to_string());
|
||||
return expand_path(format!("{}:~/.docki/", current));
|
||||
}
|
||||
|
||||
pub fn create_parent_dir_recursive(out_path: &str) -> () {
|
||||
let segments: &Vec<&str> = &out_path.split("/").collect();
|
||||
let parent_dir = &segments[0..segments.len() - 1].join("/");
|
||||
create_dir_recursive(parent_dir);
|
||||
}
|
||||
|
||||
|
||||
20
src/app/log/mod.rs
Normal file
20
src/app/log/mod.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use colored::Colorize;
|
||||
|
||||
pub fn display_status(context1: &str, context2: &str, in_path: &str, out_path: &str) {
|
||||
let colored_context = color_context(context2);
|
||||
println!(
|
||||
"({}) [{}] {} -> {}",
|
||||
context1.bold(),
|
||||
colored_context,
|
||||
in_path,
|
||||
out_path
|
||||
);
|
||||
}
|
||||
|
||||
fn color_context(context: &str) -> colored::ColoredString {
|
||||
if context == "Error" {
|
||||
return context.bright_red()
|
||||
} else {
|
||||
return context.bright_green()
|
||||
}
|
||||
}
|
||||
@@ -1,74 +1,42 @@
|
||||
mod commands;
|
||||
pub mod builder;
|
||||
pub mod build;
|
||||
pub mod fs_util;
|
||||
pub mod watcher;
|
||||
pub mod log;
|
||||
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::commands::serve::serve;
|
||||
|
||||
pub struct App {
|
||||
command_regisrty: CommandRegistry,
|
||||
}
|
||||
pub struct App;
|
||||
|
||||
impl App {
|
||||
pub fn new() -> App {
|
||||
return App {
|
||||
command_regisrty: CommandRegistry::new()
|
||||
}
|
||||
|
||||
pub async fn start(&self) {
|
||||
let args = args();
|
||||
Self::setup_environment_variables();
|
||||
|
||||
match args.command {
|
||||
CommandArg::Build => build().await,
|
||||
CommandArg::Health => health(),
|
||||
CommandArg::InstallReveal => install_reveal().await,
|
||||
CommandArg::Serve { port } => serve(port).await
|
||||
};
|
||||
}
|
||||
|
||||
pub fn start(self, args: Vec<String>) {
|
||||
Self::preapare_env_path();
|
||||
let command_args = &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() {
|
||||
fn setup_environment_variables() {
|
||||
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")
|
||||
}
|
||||
pub fn new() -> Self {
|
||||
Self {}
|
||||
}
|
||||
|
||||
fn execute_command(&self, c: &Box<dyn Command>, args: &HashMap<String, String>) {
|
||||
let result = c.execute(args);
|
||||
|
||||
match result {
|
||||
Ok(_) => println!("successfully executed"),
|
||||
Err(message) => println!("{message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
17
src/app/watcher/mod.rs
Normal file
17
src/app/watcher/mod.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use futures::{channel::mpsc::{Receiver, channel}, SinkExt};
|
||||
use notify::{RecommendedWatcher, Event, Watcher, Config};
|
||||
|
||||
pub fn watcher() -> notify::Result<(RecommendedWatcher, Receiver<notify::Result<Event>>)> {
|
||||
let (mut tx, rx) = channel(1);
|
||||
|
||||
let watcher = RecommendedWatcher::new(
|
||||
move |res| {
|
||||
futures::executor::block_on(async {
|
||||
tx.send(res).await.unwrap();
|
||||
});
|
||||
},
|
||||
Config::default(),
|
||||
)?;
|
||||
|
||||
Ok((watcher, rx))
|
||||
}
|
||||
@@ -3,12 +3,10 @@ mod app;
|
||||
#[cfg(test)]
|
||||
mod test;
|
||||
|
||||
use std::env;
|
||||
|
||||
use app::App;
|
||||
|
||||
fn main() {
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let app = App::new();
|
||||
let args = env::args().collect();
|
||||
app.start(args);
|
||||
app.start().await;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::app::builder::asciidoctor;
|
||||
use crate::app::build::asciidoctor;
|
||||
|
||||
#[test]
|
||||
fn last_matching_index_0() {
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::{fs, path::Path};
|
||||
|
||||
use crate::app::fs_util;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
mod fs_util;
|
||||
mod builder;
|
||||
mod build;
|
||||
|
||||
Reference in New Issue
Block a user