From f26cfdc680bea82592aac39ab51c15390c949927 Mon Sep 17 00:00:00 2001
From: theMackabu <theMackabu@gmail.com>
Date: Mon, 25 Nov 2024 19:56:19 -0800
Subject: [PATCH] improve list cli

---
 Maidfile.toml                      |   2 +-
 maid/client/{cli/mod.rs => cli.rs} |   4 +-
 maid/client/cli/tasks.rs           | 136 ++++++++++++-----------------
 maid/client/main.rs                |   4 +-
 maid/shared/log/verbose.rs         |  17 ++--
 maid/shared/models/client.rs       |   1 -
 6 files changed, 69 insertions(+), 95 deletions(-)
 rename maid/client/{cli/mod.rs => cli.rs} (99%)

diff --git a/Maidfile.toml b/Maidfile.toml
index 96c076d..5d9687d 100644
--- a/Maidfile.toml
+++ b/Maidfile.toml
@@ -12,7 +12,7 @@ version = "2.0.0"
 # Build on a remote server
 [project.server]
 token = "test_token1"
-address = { host = "localhost", port = 3500, ssl = false }
+address = { host = "localhost", port = 3500, tls = false }
 
 # Global environment (applied to shell)
 [env]
diff --git a/maid/client/cli/mod.rs b/maid/client/cli.rs
similarity index 99%
rename from maid/client/cli/mod.rs
rename to maid/client/cli.rs
index ed439b4..74bb83c 100644
--- a/maid/client/cli/mod.rs
+++ b/maid/client/cli.rs
@@ -2,9 +2,7 @@ pub(crate) mod dispatch;
 pub(crate) mod run;
 pub(crate) mod tasks;
 
-use crate::parse;
-use crate::server;
-use crate::task;
+use crate::{parse, server, task};
 
 use maid::{
     helpers,
diff --git a/maid/client/cli/tasks.rs b/maid/client/cli/tasks.rs
index 95e309e..12803d2 100644
--- a/maid/client/cli/tasks.rs
+++ b/maid/client/cli/tasks.rs
@@ -1,61 +1,65 @@
-use crate::cli;
-use crate::parse;
+use crate::{cli, parse};
+use maid::{log::prelude::*, models::client::DisplayTask, table};
 
 use inquire::Select;
-use macros_rs::{exp::ternary, fmt::string};
-use maid::log::prelude::*;
-use maid::{models::client::DisplayTask, table};
 use text_placeholder::Template;
+use tracing::Level;
 
-pub(crate) fn list_json(path: &String, args: &Vec<String>, hydrate: bool) {
+fn create_options(path: &String, remote: bool, log_level: Option<Level>) -> Vec<DisplayTask> {
     let values = parse::merge(path);
-    let project_root = parse::file::find_maidfile_root(path);
-    let json = values.clone().to_json();
-    let table = table::create(values.clone(), args, project_root);
-    let hydrated_json = Template::new_with_placeholder(&json, "%{", "}").fill_with_hashmap(&table);
+    let mut options: Vec<DisplayTask> = Vec::new();
+
+    for (key, task) in &values.tasks {
+        let mut verbose = String::default();
+        let mut desc = format!(" {}", "undescribed".on_black().red());
+
+        if let Some(info) = &task.info {
+            if !info.trim().is_empty() {
+                desc = format!("{} {info}", ":".white())
+            }
+        }
+
+        if log_level.unwrap_or(Level::INFO) != Level::INFO {
+            verbose = task.script.to_string()
+        };
+
+        let hidden = match remote {
+            true => match task.remote {
+                Some(_) => false,
+                None => true,
+            },
+            false => key.starts_with("_") || task.hide.map_or(task.remote.as_ref().map_or(false, |r| r.exclusive), |h| h),
+        };
+
+        if !hidden {
+            options.push(DisplayTask {
+                name: key.to_owned(),
+                formatted: format!("{}{desc} {}", format!("{key}").truecolor(255, 165, 0), verbose.bright_blue()),
+            });
+        }
+    }
 
-    println!("{}", ternary!(hydrate.clone(), hydrated_json, json))
+    options
 }
 
-pub(crate) fn list_all(path: &String, silent: bool, log_level: Option<tracing::Level>, force: bool) {
+pub(crate) fn list_json(path: &String, args: &Vec<String>, hydrate: bool) {
     let values = parse::merge(path);
-    let mut options: Vec<_> = values
-        .tasks
-        .iter()
-        .map(|(key, task)| {
-            let info = match &task.info {
-                Some(info) => match info.trim().len() < 1 {
-                    true => "(no description)".to_string().bright_red(),
-                    false => format!("({info})").white(),
-                },
-                None => "(no description)".to_string().bright_red(),
-            };
-
-            let verbose = match log_level.unwrap() {
-                tracing::Level::INFO => string!(),
-                _ => string!(task.script),
-            };
-
-            let hidden = match key.starts_with("_") {
-                true => true,
-                false => match task.hide {
-                    Some(val) => val,
-                    None => match task.remote.as_ref() {
-                        Some(val) => val.exclusive,
-                        None => false,
-                    },
-                },
-            };
-
-            return DisplayTask {
-                name: key.clone(),
-                formatted: format!("{} {} {}", format!("{key}").bright_yellow(), info, verbose.bright_blue()),
-                hidden: hidden.clone(),
-            };
-        })
-        .collect();
-
-    options.retain(|key| key.hidden == false);
+    let json = values.to_json();
+
+    if hydrate {
+        let project = parse::file::find_maidfile_root(path);
+        let table = table::create(values, args, project);
+        let hydrated = Template::new_with_placeholder(&json, "%{", "}").fill_with_hashmap(&table);
+
+        println!("{hydrated}")
+    } else {
+        println!("{json}")
+    }
+}
+
+pub(crate) fn list_all(path: &String, silent: bool, log_level: Option<Level>, force: bool) {
+    let options = create_options(path, false, log_level);
+
     match Select::new("Select a task to run:", options).prompt() {
         Ok(task) => {
             debug!("Starting {}", task.name);
@@ -66,39 +70,9 @@ pub(crate) fn list_all(path: &String, silent: bool, log_level: Option<tracing::L
     }
 }
 
-pub(crate) fn list_remote(path: &String, silent: bool, log_level: Option<tracing::Level>) {
-    let values = parse::merge(path);
-    let mut options: Vec<_> = values
-        .tasks
-        .iter()
-        .map(|(key, task)| {
-            let info = match &task.info {
-                Some(info) => match info.trim().len() < 1 {
-                    true => "(no description)".to_string().bright_red(),
-                    false => format!("({info})").white(),
-                },
-                None => "(no description)".to_string().bright_red(),
-            };
-
-            let verbose = match log_level.unwrap() {
-                tracing::Level::INFO => string!(),
-                _ => string!(task.script),
-            };
-
-            let hidden = match task.remote {
-                Some(_) => false,
-                None => true,
-            };
-
-            return DisplayTask {
-                name: key.clone(),
-                formatted: format!("{} {} {}", format!("{key}").bright_yellow(), info, verbose.bright_blue()),
-                hidden: hidden.clone(),
-            };
-        })
-        .collect();
+pub(crate) fn list_remote(path: &String, silent: bool, log_level: Option<Level>) {
+    let options = create_options(path, true, log_level);
 
-    options.retain(|key| key.hidden == false);
     match Select::new("Select a remote task to run:", options).prompt() {
         Ok(task) => {
             debug!("Starting {}", task.name);
diff --git a/maid/client/main.rs b/maid/client/main.rs
index a173227..f924c54 100644
--- a/maid/client/main.rs
+++ b/maid/client/main.rs
@@ -111,7 +111,7 @@ fn main() {
         health => server::cli::connect(&cli.path),
         health => match cli.remote {
             true => server::cli::connect(&cli.path),
-            false => server::cli::connect(&cli.path), // improve health command for later
+            false => {}, // improve health command for later
         },
         clean_cache => match cli.remote {
             true => server::cli::connect(&cli.path),
@@ -133,7 +133,7 @@ fn main() {
     if let Some(system) = cli.system {
         return match system {
             System::CheckUpdates => cli::dispatch::check_update(),
-            System::Upgrade => cli::dispatch::check_update(),
+            System::Upgrade => {} // add upgrader
             System::Json => cli::tasks::list_json(&cli.path, &cli.task, false),
             System::JsonHydrated => cli::tasks::list_json(&cli.path, &cli.task, true),
         };
diff --git a/maid/shared/log/verbose.rs b/maid/shared/log/verbose.rs
index 1b1eff8..224b355 100644
--- a/maid/shared/log/verbose.rs
+++ b/maid/shared/log/verbose.rs
@@ -16,13 +16,12 @@ pub struct Verbosity<L: LogLevel = ErrorLevel> {
     #[arg(
         long,
         short = 'q',
-        action = clap::ArgAction::Count,
         global = true,
         help = L::quiet_help(),
         long_help = L::quiet_long_help(),
         conflicts_with = "verbose",
     )]
-    quiet: u8,
+    quiet: bool,
 
     #[arg(skip)]
     phantom: std::marker::PhantomData<L>,
@@ -30,7 +29,7 @@ pub struct Verbosity<L: LogLevel = ErrorLevel> {
 
 #[allow(dead_code)]
 impl<L: LogLevel> Verbosity<L> {
-    pub fn new(verbose: u8, quiet: u8) -> Self {
+    pub fn new(verbose: u8, quiet: bool) -> Self {
         Verbosity {
             verbose,
             quiet,
@@ -38,15 +37,19 @@ impl<L: LogLevel> Verbosity<L> {
         }
     }
 
-    pub fn is_present(&self) -> bool { self.verbose != 0 || self.quiet != 0 }
+    pub fn is_silent(&self) -> bool { self.log_level().is_none() }
 
     pub fn log_level(&self) -> Option<Level> { level_enum(self.verbosity()) }
 
     pub fn log_level_filter(&self) -> LevelFilter { return level_enum(self.verbosity()).map(LevelFilter::from_level).unwrap_or(LevelFilter::OFF); }
 
-    pub fn is_silent(&self) -> bool { self.log_level().is_none() }
-
-    fn verbosity(&self) -> i8 { level_value(L::default()) - (self.quiet as i8) + (self.verbose as i8) }
+    fn verbosity(&self) -> i8 {
+        if !self.quiet {
+            level_value(L::default()) + (self.verbose as i8)
+        } else {
+            -1
+        }
+    }
 }
 
 fn level_value(level: Option<Level>) -> i8 {
diff --git a/maid/shared/models/client.rs b/maid/shared/models/client.rs
index a1d7b5e..50498bb 100644
--- a/maid/shared/models/client.rs
+++ b/maid/shared/models/client.rs
@@ -38,7 +38,6 @@ pub struct Runner<'a, T> {
 pub struct DisplayTask {
     pub name: String,
     pub formatted: String,
-    pub hidden: bool,
 }
 
 #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
-- 
GitLab