Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
georglauterbach committed Oct 23, 2023
1 parent 0bf9c74 commit 4cc262e
Show file tree
Hide file tree
Showing 16 changed files with 592 additions and 341 deletions.
3 changes: 1 addition & 2 deletions code/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,12 @@ lto = false
# -----------------------------------------------

[dependencies]
ansi_rgb = "0.2.0"
anyhow = "1.0.75"
chrono = "0.4.31"
clap = { version = "4.4.6", features = ["derive"] }
clap-verbosity-flag = "2.0.1"
colored = "2.0.4"
log = "0.4.20"
rgb = "0.8.36"
which = "5.0.0"

# -----------------------------------------------
Expand Down
182 changes: 0 additions & 182 deletions code/src/arguments.rs

This file was deleted.

43 changes: 22 additions & 21 deletions code/src/logger.rs → code/src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ static LOGGER: Logger = Logger;
///
/// This structure holds associated function that provide logging. The
/// [`log::Log`] trait is implemented for this structure.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub struct Logger;

Expand All @@ -22,40 +21,41 @@ impl Logger {
/// This function takes care of setting the correct log level. If [`None`]
/// is provided, the "fallback" implementation [`Logger::from_str`] is
/// used.
fn set_log_level(log_level: Option<log::Level>) {
fn set_log_level<'a>(log_level: Option<log::Level>) -> &'a str {
let level_filter = log_level.map_or(log::LevelFilter::Info, |log_level| log_level.to_level_filter());
log::set_max_level(level_filter);
level_filter.as_str()
}
}

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

fn log(&self, record: &log::Record) {
use ansi_rgb::Foreground;
use log::Level;
use rgb::RGB8;

if !self.enabled(record.metadata()) {
return;
}

/// Shortens the log sequence (writing via `println!`).
macro_rules! log_with_color {
($r:expr, $g:expr, $b:expr) => {{
use colored::*;
println!(
"{:<5} {}",
record.level().as_str().truecolor($r, $g, $b),
record.args().to_string().truecolor($r, $g, $b)
)
}};
}

// https://coolors.co/fb4934-fabd2f-458588-83a598-8f8f8f
let (log_level, color) = match record.level() {
Level::Error => ("ERROR", RGB8::new(251, 73, 52)),
Level::Warn => ("WARN ", RGB8::new(250, 189, 47)),
Level::Info => ("INFO ", RGB8::new(69, 133, 136)),
Level::Debug => ("DEBUG", RGB8::new(131, 165, 152)),
Level::Trace => ("TRACE", RGB8::new(143, 143, 143)),
match record.level() {
log::Level::Error => log_with_color!(251, 73, 52),
log::Level::Warn => log_with_color!(250, 189, 47),
log::Level::Info => log_with_color!(69, 133, 136),
log::Level::Debug => log_with_color!(131, 165, 152),
log::Level::Trace => log_with_color!(143, 143, 143),
};

println!(
"{} {:<15.*} | {}",
log_level.fg(color),
25,
record.module_path().unwrap_or("unknown"),
record.args().fg(color)
);
}

fn flush(&self) {}
Expand All @@ -67,6 +67,7 @@ impl log::Log for Logger {
/// bootloader information. The default log level chosen if [`None`] is provided
/// is "Info".
pub fn initialize(log_level: Option<log::Level>) {
Logger::set_log_level(log_level);
let level = Logger::set_log_level(log_level);
log::set_logger(&LOGGER).expect("Log should not have already been set");
log::debug!("Initialized log with log level '{}'", level.to_lowercase());
}
20 changes: 11 additions & 9 deletions code/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,18 @@
//! workspace, which enabled a seamless integration of `cargo run --` into the workflow of
//! `unCORE`.

mod arguments;
mod logger;
mod runtime;
mod log;

/// A simple main function.
fn main() -> anyhow::Result<()> {
let arguments = <arguments::Arguments as clap::Parser>::parse();
fn main() {
let arguments = <runtime::arguments::Arguments as clap::Parser>::parse();

logger::initialize(arguments.get_log_level());
// log::info!("{}", chrono::offset::Local::now().format("%+").to_string());
arguments.dispatch_command()?;

Ok(())
log::initialize(arguments.get_log_level());
if arguments.dispatch_command().is_err() {
::log::error!("Execution terminated unsuccessfully");
std::process::exit(1);
} else {
::log::trace!("Execution terminated successfully");
}
}
53 changes: 53 additions & 0 deletions code/src/runtime/arguments.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: GPL-3.0-or-later

//! This module provides all types required for parsing and working with command line
//! arguments.

/// Defines which architectures can be targeted by `unCORE`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, clap::ValueEnum)]
pub enum Architecture {
/// RISC-V 64 GC
// (see <https://www.cnx-software.com/2019/08/27/risc-v-bases-and-extensions-explained/>)
Riscv64,
}

/// Helper program to ease building and running `unCORE`.
#[derive(Debug, clap::Parser)]
#[command(author, version, about, long_about, propagate_version = true)]
#[command(bin_name = "cargo run -q --")]
pub struct Arguments {
/// Specify the verbosity
#[clap(flatten)]
verbosity: clap_verbosity_flag::Verbosity<clap_verbosity_flag::InfoLevel>,
/// Specify the architecture unCORE is built for.
#[clap(value_enum, default_value_t=Architecture::Riscv64)]
architecture: Architecture,
/// Specify what to do: build the kernel, run the kernel, etc.
#[command(subcommand)]
command: super::command::Command,
}

impl Arguments {
/// Get the log level specified by the arguments.
pub fn get_log_level(&self) -> Option<log::Level> { self.verbosity.log_level() }

/// Dispatches individual sub-commands to the correct sub-routines that execute the
/// sub-commands.
pub fn dispatch_command(self) -> Result<(), ()> {
log::debug!("Dispatching command '{}'", self.command);
match self.command.execute(self.architecture) {
Ok(()) => Ok(()),
Err(error) => {
log::error!(
"{}",
error
.chain()
.map(std::string::ToString::to_string)
.collect::<Vec<String>>()
.join(" - ")
);
Err(())
},
}
}
}
Loading

0 comments on commit 4cc262e

Please sign in to comment.