Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release of v1.0 #156

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
apply term crates
  • Loading branch information
MindPatch committed Nov 18, 2024
commit 4d6abce62b813c76e09225da2cc3bbe6fdb1ae73
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ serde = { version = "1.0.144", features = ["derive"] }

slinger = { version = "0.1.2", features = ["serde", "cookie", "charset", "tls", "gzip"] }
url = "2.2.2"
regex = "1.11.1"
console = "0.15.8"
chrono = "0.4.38"
colored = "2.1.0"

[profile.release]
opt-level = "z" # Optimize for size.
Expand Down
38 changes: 38 additions & 0 deletions src/cli/args.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use regex::Regex;
use std::path::PathBuf;
use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[structopt(name = "lotus", about = "A powerful CLI tool with advanced options.")]
pub struct Cli {
#[structopt(short, long, default_value = "30", parse(try_from_str = parse_timeout))]
pub timeout: u64,

#[structopt(short, long, parse(try_from_str = parse_proxy))]
pub proxy: Option<String>,

#[structopt(short, long, parse(from_os_str))]
pub output: PathBuf,
}

pub fn parse_timeout(s: &str) -> Result<u64, String> {
s.parse::<u64>().map_err(|_| "Invalid timeout value. Must be a positive integer.".to_string())
}

pub fn parse_proxy(s: &str) -> Result<String, String> {
let url_regex = Regex::new(r"^(http|https)://").map_err(|_| "Regex compilation failed.".to_string())?;
if url_regex.is_match(s) {
Ok(s.to_string())
} else {
Err("Invalid proxy URL. Must start with http:// or https://".to_string())
}
}

impl Cli {
pub fn validate(&self) -> Result<(), String> {
if self.timeout == 0 {
return Err("Timeout must be greater than zero.".to_string());
}
Ok(())
}
}
Empty file added src/cli/errors.rs
Empty file.
2 changes: 2 additions & 0 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod args;
pub mod term;
28 changes: 28 additions & 0 deletions src/cli/term/bar.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use indicatif::{ProgressBar, ProgressStyle};

pub struct ProgressManager {
progress_bar: ProgressBar,
}

impl ProgressManager {
pub fn new(size: u64, message: impl Into<String>) -> Self {
let pb = ProgressBar::new(size);
pb.set_style(
ProgressStyle::default_bar()
.template("{spinner:.green} [{elapsed_precise}] {bar:40.cyan/blue} {pos:>3}/{len:3} {msg}")
.unwrap()
.progress_chars("#>-"),
);
pb.set_message(message.into());
ProgressManager { progress_bar: pb }
}

pub fn increment(&self, value: u64, message: impl Into<String>) {
self.progress_bar.inc(value);
self.progress_bar.set_message(message.into());
}

pub fn finish(&self, message: impl Into<String>) {
self.progress_bar.finish_with_message(message.into());
}
}
10 changes: 10 additions & 0 deletions src/cli/term/emojis.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use console::Emoji;

static SPARKLE: Emoji<'_, '_> = Emoji("✨", "");
static FIRE: Emoji<'_, '_> = Emoji("🔥", "");
static CHECK: Emoji<'_, '_> = Emoji("✅", "");
static CROSS: Emoji<'_, '_> = Emoji("❌", "");
static WARNING: Emoji<'_, '_> = Emoji("⚠️", "");
static INFO: Emoji<'_, '_> = Emoji("ℹ️", "");
static STAR: Emoji<'_, '_> = Emoji("⭐", "");
static HEART: Emoji<'_, '_> = Emoji("❤️", "");
61 changes: 61 additions & 0 deletions src/cli/term/logger.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use chrono::Local;
use colored::*;
use log::{info, warn, error, Record, Level, Metadata};
use std::sync::Once;
use indicatif::ProgressBar;

static INIT: Once = Once::new();

pub struct RichLogger;

impl log::Log for RichLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= Level::Info
}

fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
let time = Local::now().format("%Y-%m-%d %H:%M:%S");
let message = match record.level() {
Level::Info => format!("{} {}", time.to_string(), record.args().to_string()),
Level::Warn => format!("{} {}", time.to_string(), record.args().to_string()),
Level::Error => format!("{} {}", time.to_string(), record.args().to_string()),
_ => format!("{} {}", time.to_string(), record.args().to_string())
};

let progress_bar = ProgressBar::new_spinner();
progress_bar.println(message);
}
}

fn flush(&self) {}
}

pub fn init_logger() {
INIT.call_once(|| {
log::set_logger(&RichLogger).unwrap();
log::set_max_level(log::LevelFilter::Info);
});
}

#[macro_export]
macro_rules! log_info {
($($arg:tt)*) => ({
log::info!($($arg)*);
})
}

#[macro_export]
macro_rules! log_warn {
($($arg:tt)*) => ({
log::warn!($($arg)*);
})
}

#[macro_export]
macro_rules! log_error {
($($arg:tt)*) => ({
log::error!($($arg)*);
})
}

3 changes: 3 additions & 0 deletions src/cli/term/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod bar;
pub mod emojis;
pub mod logger;
7 changes: 4 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
impl Lotus {
fn init(){}
}
//
pub mod cli;

pub fn lib(){}
Empty file added src/lua/mod.rs
Empty file.
5 changes: 4 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
mod cli;

#[tokio::main]
async fn main(){

fn main(){}
}
68 changes: 68 additions & 0 deletions tests/args_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@

#[cfg(test)]
mod tests {
pub use lotus::cli::args::{parse_timeout, parse_proxy, Cli};
use structopt::StructOpt;
use std::path::PathBuf;

#[test]
fn test_parse_timeout_valid() {
assert_eq!(parse_timeout("10").unwrap(), 10);
assert_eq!(parse_timeout("0").unwrap(), 0);
assert!(parse_timeout("999999").is_ok());
}

#[test]
fn test_parse_timeout_invalid() {
assert!(parse_timeout("-10").is_err());
assert!(parse_timeout("abc").is_err());
assert!(parse_timeout("").is_err());
}

#[test]
fn test_parse_proxy_valid() {
assert_eq!(
parse_proxy("http://example.com").unwrap(),
"http://example.com"
);
assert_eq!(
parse_proxy("https://example.com").unwrap(),
"https://example.com"
);
}

#[test]
fn test_parse_proxy_invalid() {
assert!(parse_proxy("ftp://example.com").is_err());
assert!(parse_proxy("example.com").is_err());
assert!(parse_proxy("").is_err());
}

#[test]
fn test_cli_struct() {
let args = vec![
"lotus", // program name
"--timeout", "15", // timeout
"--proxy", "http://proxy.test", // proxy
"--output", "output.log", // output file
];
let cli = Cli::from_iter_safe(&args).unwrap();

assert_eq!(cli.timeout, 15);
assert_eq!(cli.proxy.unwrap(), "http://proxy.test");
assert_eq!(cli.output, PathBuf::from("output.log"));
}

#[test]
fn test_cli_struct_defaults() {
let args = vec![
"lotus", // program name
"--output", "output.log", // output file
];
let cli = Cli::from_iter_safe(&args).unwrap();

assert_eq!(cli.timeout, 30); // default timeout
assert!(cli.proxy.is_none());
assert_eq!(cli.output, PathBuf::from("output.log"));
}
}
13 changes: 0 additions & 13 deletions tests/files.rs

This file was deleted.

69 changes: 0 additions & 69 deletions tests/http.rs

This file was deleted.

45 changes: 0 additions & 45 deletions tests/url.rs

This file was deleted.