Skip to content

Commit

Permalink
feat(main): add cmd group for build image
Browse files Browse the repository at this point in the history
  • Loading branch information
cuisongliu committed Jun 23, 2024
1 parent b817540 commit d3e149f
Show file tree
Hide file tree
Showing 8 changed files with 136 additions and 13 deletions.
7 changes: 5 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@ description = "rbuild-runtime, a rusty-hermit application"
repository = "https://github.com/rust-learn-days/rbuild-runtime"
license-file = "LICENSE"
[dependencies]
rust-embed="8.4.0"
rust-embed = "8.4.0"
tokio = { version = "1.0.0", features = ["rt", "rt-multi-thread", "macros"] }
clap = { version = "4.5.7", features = ["derive"] }
serde = { version = "1.0.203", features = ["derive"] }

colored = "2.1.0"
log = "0.4"
chrono = "0.4"
env_logger = "0.9"
[build-dependencies]
reqwest = "0.12.5"
tokio = { version = "1.0.0", features = ["rt", "rt-multi-thread", "macros"] }
Expand Down
56 changes: 53 additions & 3 deletions src/cli/cli.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use std::fmt;
use std::str::FromStr;

use clap::Parser;

use crate::BuildRuntime;
Expand All @@ -10,8 +13,55 @@ pub struct BuildRuntimeOpts {
#[arg(
short,
long,
default_value = "false",
long_help = "Print debug information"
default_value = "info",
long_help = "Set the log level for the application. Supported log levels are error, info, warn, debug, trace.",
value_parser = parse_log_level,
)]
pub debug: bool,
pub log_level: LogLevel,
}

#[derive(Debug, Copy, Clone)]
pub enum LogLevel {
ERROR,
INFO,
WARN,
DEBUG,
TRACE,
}

impl From<LogLevel> for &'static str {
fn from(f: LogLevel) -> Self {
match f {
LogLevel::ERROR => "error",
LogLevel::INFO => "info",
LogLevel::WARN => "warn",
LogLevel::DEBUG => "debug",
LogLevel::TRACE => "trace",
}
}
}

fn parse_log_level(s: &str) -> Result<LogLevel, &'static str> {
s.parse()
}

impl FromStr for LogLevel {
type Err = &'static str;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"error" => Ok(LogLevel::ERROR),
"info" => Ok(LogLevel::INFO),
"warn" => Ok(LogLevel::WARN),
"debug" => Ok(LogLevel::DEBUG),
"trace" => Ok(LogLevel::TRACE),
_ => Err("Invalid Log Level"),
}
}
}

impl fmt::Display for LogLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", Into::<&str>::into(*self))
}
}
8 changes: 5 additions & 3 deletions src/cli/cli_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,19 @@ pub enum BuildCommand {

#[derive(Parser, Debug)]
pub struct DockerOpts {
#[arg(default_value = "20.10.9")]
#[arg(long, long_help = "docker cli version", default_value = "20.10.9")]
pub version: String,
#[arg(default_value = "v0.3.14")]
#[arg(long, long_help = "crd dockerd version", default_value = "v0.3.14")]
pub cri_docker_version: String,
}

#[derive(Parser, Debug)]
pub struct ContainerdOpts {
#[arg(long, default_value = "v1.6.23")]
pub version: String,
#[arg(short, long, default_value = "runc", value_parser = parse_container_runtime)]
#[arg(
short, long, long_help = "using container runtime name", default_value = "runc", value_parser = parse_container_runtime
)]
pub runtime: ContainerRuntime,
}

Expand Down
6 changes: 3 additions & 3 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pub mod cli;
pub mod cli_build;

pub use cli::*;
pub use cli_build::*;
#[allow(clippy::module_inception)]
mod cli;
mod cli_build;
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pub use cli::*;
pub use logger::*;

mod cli;
mod logger;
47 changes: 47 additions & 0 deletions src/logger/logger.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use std::io::Write;

use colored::Colorize;
use env_logger::Builder;
use log::{Level, LevelFilter};

pub fn init_logger(filter: LevelFilter) {
Builder::new()
.format(|buf, record| {
let level_color = match record.level() {
Level::Error => "ERROR".red(),
Level::Warn => "WARN".yellow(),
Level::Info => "INFO".green(),
Level::Debug => "DEBUG".blue(),
Level::Trace => "TRACE".white(),
};
writeln!(
buf,
"{} [{}] - {}",
chrono::Local::now()
.format("%Y-%m-%d %H:%M:%S")
.to_string()
.cyan(),
level_color,
record.args()
)
})
.filter(None, filter)
.init();
}

#[cfg(test)]
mod tests {
use log::{debug, error, info, trace, warn};

use super::*;

#[test]
fn test_logging() {
init_logger(LevelFilter::Trace);
info!("{}", "This is another info message with color");
error!("{}", "This is error msg");
warn!("{}", "This is warn msg");
debug!("{}", "This is debug msg");
trace!("{}", "This is trace msg");
}
}
3 changes: 3 additions & 0 deletions src/logger/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub use logger::*;
#[allow(clippy::module_inception)]
mod logger;
17 changes: 15 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
use clap::Parser;
use log::{info, trace, LevelFilter};
use rust_embed::Embed;

use rbuild_runtime::{init_logger, BuildRuntimeOpts, LogLevel};

#[derive(Embed)]
#[folder = "files/"]
struct Asset;

fn main() {
println!("Hello, world!");
let asset = Asset::get("sealos").unwrap();
println!("asset: {:?}", asset.data.len());
let opts: BuildRuntimeOpts = BuildRuntimeOpts::parse();
let level = match opts.log_level {
LogLevel::ERROR => LevelFilter::Error,
LogLevel::INFO => LevelFilter::Info,
LogLevel::WARN => LevelFilter::Warn,
LogLevel::DEBUG => LevelFilter::Debug,
LogLevel::TRACE => LevelFilter::Trace,
};
init_logger(level);
info!("log level set to: {:?}", opts.log_level);
trace!("asset: {:?}", asset.data.len());
}

0 comments on commit d3e149f

Please sign in to comment.