Skip to content
This repository has been archived by the owner on Dec 11, 2024. It is now read-only.

Commit

Permalink
make logging configurable
Browse files Browse the repository at this point in the history
  • Loading branch information
noise64 committed Dec 4, 2024
1 parent 9b7995c commit b030a86
Show file tree
Hide file tree
Showing 3 changed files with 136 additions and 24 deletions.
88 changes: 69 additions & 19 deletions wasm-rpc-stubgen/src/commands/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use crate::cargo::regenerate_cargo_package_component;
use crate::fs;
use crate::fs::PathExtra;
use crate::log::{
log_action, log_skipping_up_to_date, log_validated_action_result, log_warn_action, LogColorize,
LogIndent,
log_action, log_skipping_up_to_date, log_validated_action_result, log_warn_action,
set_log_output, LogColorize, LogIndent, Output,
};
use crate::model::app::{
includes_from_yaml_file, Application, ComponentName, ComponentPropertiesExtensions,
Expand All @@ -27,6 +27,7 @@ use itertools::Itertools;
use std::cell::OnceCell;
use std::cmp::Ordering;
use std::collections::{BTreeSet, HashMap};
use std::fmt::Write;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::process::Command;
Expand All @@ -39,6 +40,7 @@ pub struct Config<CPE: ComponentPropertiesExtensions> {
pub profile: Option<ProfileName>,
pub offline: bool,
pub extensions: PhantomData<CPE>,
pub log_output: Output,
}

#[derive(Debug, Clone)]
Expand All @@ -57,7 +59,10 @@ pub struct ApplicationContext<CPE: ComponentPropertiesExtensions> {

impl<CPE: ComponentPropertiesExtensions> ApplicationContext<CPE> {
pub fn new(config: Config<CPE>) -> anyhow::Result<ApplicationContext<CPE>> {
set_log_output(config.log_output);

let ctx = to_anyhow(
config.log_output,
"Failed to create application context, see problems above",
load_app_validated(&config).and_then(|application| {
ResolvedWitApplication::new(&application, config.profile.as_ref()).map(|wit| {
Expand Down Expand Up @@ -252,6 +257,7 @@ impl<CPE: ComponentPropertiesExtensions> ApplicationContext<CPE> {

fn update_wit_context(&mut self) -> anyhow::Result<()> {
to_anyhow(
self.config.log_output,
"Failed to update application wit context, see problems above",
ResolvedWitApplication::new(&self.application, self.profile()).map(|wit| {
self.wit = wit;
Expand Down Expand Up @@ -486,6 +492,7 @@ pub async fn build<CPE: ComponentPropertiesExtensions>(config: Config<CPE>) -> a

pub fn clean<CPE: ComponentPropertiesExtensions>(config: Config<CPE>) -> anyhow::Result<()> {
let app = to_anyhow(
config.log_output,
"Failed to load application manifest(s), see problems above",
load_app_validated(&config),
)?;
Expand Down Expand Up @@ -579,6 +586,7 @@ pub fn available_custom_commands<CPE: ComponentPropertiesExtensions>(
config: Config<CPE>,
) -> anyhow::Result<BTreeSet<String>> {
let app = to_anyhow(
config.log_output,
"Failed to load application manifest(s), see problems above",
load_app_validated(&config),
)?;
Expand Down Expand Up @@ -781,36 +789,78 @@ fn find_main_source() -> Option<PathBuf> {
last_source
}

fn to_anyhow<T>(message: &str, result: ValidatedResult<T>) -> anyhow::Result<T> {
fn print_warns(warns: Vec<String>) {
fn to_anyhow<T>(
log_output: Output,
message: &str,
result: ValidatedResult<T>,
) -> anyhow::Result<T> {
fn format_warns(warns: Vec<String>) -> String {
let label = "Warning".yellow();
for warn in warns {
eprintln!("{}: {}", label, warn);
}
warns
.into_iter()
.map(|warn| format!("{}: {}", label, warn))
.join("\n")
}

fn print_errors(errors: Vec<String>) {
fn format_errors(errors: Vec<String>) -> String {
let label = "Error".red();
for error in errors {
eprintln!("{}: {}", label, error);
}
errors
.into_iter()
.map(|error| format!("{}: {}", label, error))
.join("\n")
}

match result {
ValidatedResult::Ok(value) => Ok(value),
ValidatedResult::OkWithWarns(components, warns) => {
println!();
print_warns(warns);
println!();
match log_output {
Output::Stdout => {
println!("\n{}\n", format_warns(warns));
}
Output::Stderr => {
eprintln!("\n{}\n", format_warns(warns));
}
Output::None => {
// NOP
}
}

Ok(components)
}
ValidatedResult::WarnsAndErrors(warns, errors) => {
println!();
print_warns(warns);
print_errors(errors);
println!();
let message = match log_output {
Output::Stdout => {
println!("\n");
println!("{}", format_warns(warns));
println!("{}", format_errors(errors));
println!("\n");

message.to_string()
}
Output::Stderr => {
eprintln!("\n");
eprintln!("{}", format_warns(warns));
eprintln!("{}", format_errors(errors));
eprintln!("\n");

message.to_string()
}
Output::None => {
fn with_new_line_if_not_empty(mut str: String) -> String {
if !str.is_empty() {
str.write_char('\n').unwrap()
}
str
}

let warns = with_new_line_if_not_empty(format_warns(warns));
let errors = with_new_line_if_not_empty(format_errors(errors));

format!("\n{}{}\n{}", warns, errors, message)
}
};

Err(anyhow!(message.to_string()))
Err(anyhow!(message))
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions wasm-rpc-stubgen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub mod wit_encode;
pub mod wit_generate;
pub mod wit_resolve;

use crate::log::Output;
use crate::model::app::{ComponentPropertiesExtensions, ComponentPropertiesExtensionsAny};
use crate::stub::{StubConfig, StubDefinition};
use crate::wit_generate::UpdateCargoToml;
Expand Down Expand Up @@ -309,6 +310,7 @@ pub async fn run_app_command<CPE: ComponentPropertiesExtensions>(
profile: args.profile.map(|profile| profile.into()),
offline: args.offline,
extensions: PhantomData::<CPE>,
log_output: Output::Stdout,
})
.await
}
Expand All @@ -318,6 +320,7 @@ pub async fn run_app_command<CPE: ComponentPropertiesExtensions>(
profile: None,
offline: false,
extensions: PhantomData::<ComponentPropertiesExtensionsAny>,
log_output: Output::Stdout,
}),
App::CustomCommand(_args) => {
// TODO: parse app manifest / profile args
Expand Down
69 changes: 64 additions & 5 deletions wasm-rpc-stubgen/src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,25 @@ use std::sync::{LazyLock, RwLock};

static LOG_STATE: LazyLock<RwLock<LogState>> = LazyLock::new(RwLock::default);

#[derive(Debug, Clone, Copy)]
pub enum Output {
Stdout,
Stderr,
None,
}

struct LogState {
indent_count: usize,
indent_prefix: String,
output: Output,
}

impl LogState {
pub fn new() -> Self {
Self {
indent_count: 0,
indent_prefix: "".to_string(),
output: Output::Stdout,
}
}

Expand All @@ -32,6 +41,10 @@ impl LogState {
fn regen_indent_prefix(&mut self) {
self.indent_prefix = " ".repeat(self.indent_count);
}

fn set_output(&mut self, output: Output) {
self.output = output;
}
}

impl Default for LogState {
Expand Down Expand Up @@ -61,22 +74,68 @@ impl Drop for LogIndent {
}
}

pub struct LogOutput {
prev_output: Output,
}

impl LogOutput {
pub fn new(output: Output) -> Self {
let prev_output = LOG_STATE.read().unwrap().output;
LOG_STATE.write().unwrap().set_output(output);
Self { prev_output }
}
}

impl Drop for LogOutput {
fn drop(&mut self) {
LOG_STATE.write().unwrap().set_output(self.prev_output);
}
}

pub fn set_log_output(output: Output) {
LOG_STATE.write().unwrap().set_output(output);
}

pub fn log_action<T: AsRef<str>>(action: &str, subject: T) {
println!(
let state = LOG_STATE.read().unwrap();
let message = format!(
"{}{} {}",
LOG_STATE.read().unwrap().indent_prefix,
state.indent_prefix,
action.log_color_action(),
subject.as_ref()
)
);

match state.output {
Output::Stdout => {
println!("{}", message);
}
Output::Stderr => {
eprintln!("{}", message);
}
Output::None => {
// NOP
}
}
}

pub fn log_warn_action<T: AsRef<str>>(action: &str, subject: T) {
println!(
let state = LOG_STATE.read().unwrap();
let message = format!(
"{}{} {}",
LOG_STATE.read().unwrap().indent_prefix,
action.log_color_warn(),
subject.as_ref(),
)
);

match state.output {
Output::Stdout => {
println!("{}", message)
}
Output::Stderr => {
eprintln!("{}", message)
}
Output::None => {}
}
}

pub fn log_skipping_up_to_date<T: AsRef<str>>(subject: T) {
Expand Down

0 comments on commit b030a86

Please sign in to comment.