Skip to content

Commit

Permalink
code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
jsoverson committed Jun 17, 2021
1 parent 80ac179 commit 168adf2
Show file tree
Hide file tree
Showing 63 changed files with 4,154 additions and 4,175 deletions.
172 changes: 86 additions & 86 deletions crates/logger/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,106 +13,106 @@ pub use options::LoggingOptions;
const FILTER_ENV: &str = "VINO_LOG";
use std::time::SystemTime;
pub struct Logger {
inner: Filter,
verbose: bool,
json: bool,
inner: Filter,
verbose: bool,
json: bool,
}

fn set_level<T: AsRef<str>>(builder: &mut Builder, priority_modules: &[T], level: LevelFilter) {
for module in priority_modules.iter() {
builder.filter_module(module.as_ref(), level);
}
for module in priority_modules.iter() {
builder.filter_module(module.as_ref(), level);
}
}

impl Logger {
fn new<T: AsRef<str>>(
opts: &LoggingOptions,
priority_modules: &[T],
chatty_modules: &[T],
) -> Logger {
let mut builder = Builder::new();

if let Ok(ref filter) = std::env::var(FILTER_ENV) {
builder.parse(filter);
} else {
builder.filter_level(log::LevelFilter::Off);
if opts.quiet {
set_level(&mut builder, priority_modules, log::LevelFilter::Error);
} else if opts.trace {
set_level(&mut builder, priority_modules, log::LevelFilter::Trace);
} else if opts.debug {
set_level(&mut builder, priority_modules, log::LevelFilter::Debug);
} else {
set_level(&mut builder, priority_modules, log::LevelFilter::Info);
}

for module in chatty_modules.iter() {
builder.filter_module(module.as_ref(), log::LevelFilter::Off);
}
}

Logger {
inner: builder.build(),
verbose: opts.verbose,
json: opts.json,
}
fn new<T: AsRef<str>>(
opts: &LoggingOptions,
priority_modules: &[T],
chatty_modules: &[T],
) -> Logger {
let mut builder = Builder::new();

if let Ok(ref filter) = std::env::var(FILTER_ENV) {
builder.parse(filter);
} else {
builder.filter_level(log::LevelFilter::Off);
if opts.quiet {
set_level(&mut builder, priority_modules, log::LevelFilter::Error);
} else if opts.trace {
set_level(&mut builder, priority_modules, log::LevelFilter::Trace);
} else if opts.debug {
set_level(&mut builder, priority_modules, log::LevelFilter::Debug);
} else {
set_level(&mut builder, priority_modules, log::LevelFilter::Info);
}

for module in chatty_modules.iter() {
builder.filter_module(module.as_ref(), log::LevelFilter::Off);
}
}

pub fn init<T: AsRef<str>>(
opts: &LoggingOptions,
priority_modules: &[T],
chatty_modules: &[T],
) -> Result<(), SetLoggerError> {
let logger = Self::new(opts, priority_modules, chatty_modules);

log::set_max_level(logger.inner.filter());
log::set_boxed_logger(Box::new(logger))?;
log::trace!("logger initialized");
Ok(())
Logger {
inner: builder.build(),
verbose: opts.verbose,
json: opts.json,
}

fn format(&self, record: &Record) -> String {
let datetime: DateTime<Utc> = SystemTime::now().into();
let datestring = datetime.format("%Y-%m-%d %T");
if self.json {
json!({ "timestamp": datetime.to_rfc3339(), "level": record.level().to_string(), "msg": format!("{}", record.args()) }).to_string()
} else {
let msg = if self.verbose {
format!(
"[{}|{}] {}",
datestring,
record.module_path().unwrap_or_default(),
record.args()
)
} else {
format!("[{}] {}", datestring, record.args())
};
Logger::colorize(record.level(), msg)
}
}

pub fn init<T: AsRef<str>>(
opts: &LoggingOptions,
priority_modules: &[T],
chatty_modules: &[T],
) -> Result<(), SetLoggerError> {
let logger = Self::new(opts, priority_modules, chatty_modules);

log::set_max_level(logger.inner.filter());
log::set_boxed_logger(Box::new(logger))?;
log::trace!("logger initialized");
Ok(())
}

fn format(&self, record: &Record) -> String {
let datetime: DateTime<Utc> = SystemTime::now().into();
let datestring = datetime.format("%Y-%m-%d %T");
if self.json {
json!({ "timestamp": datetime.to_rfc3339(), "level": record.level().to_string(), "msg": format!("{}", record.args()) }).to_string()
} else {
let msg = if self.verbose {
format!(
"[{}|{}] {}",
datestring,
record.module_path().unwrap_or_default(),
record.args()
)
} else {
format!("[{}] {}", datestring, record.args())
};
Logger::colorize(record.level(), msg)
}

fn colorize(level: Level, msg: String) -> String {
match level {
Level::Info => msg,
Level::Debug => msg.blue().dimmed().to_string(),
Level::Trace => msg.dimmed().to_string(),
Level::Warn => msg.yellow().to_string(),
Level::Error => msg.red().to_string(),
}
}

fn colorize(level: Level, msg: String) -> String {
match level {
Level::Info => msg,
Level::Debug => msg.blue().dimmed().to_string(),
Level::Trace => msg.dimmed().to_string(),
Level::Warn => msg.yellow().to_string(),
Level::Error => msg.red().to_string(),
}
}
}

impl Log for Logger {
fn enabled(&self, metadata: &Metadata) -> bool {
self.inner.enabled(metadata)
}

fn log(&self, record: &Record) {
// Check if the record is matched by the logger before logging
if self.inner.matches(record) {
eprintln!("{}", self.format(record));
}
fn enabled(&self, metadata: &Metadata) -> bool {
self.inner.enabled(metadata)
}

fn log(&self, record: &Record) {
// Check if the record is matched by the logger before logging
if self.inner.matches(record) {
eprintln!("{}", self.format(record));
}
}

fn flush(&self) {}
fn flush(&self) {}
}
54 changes: 27 additions & 27 deletions crates/logger/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,46 +3,46 @@ use env_logger::WriteStyle;
use structopt::StructOpt;

fn parse_write_style(spec: &str) -> anyhow::Result<WriteStyle> {
match spec {
"auto" => Ok(WriteStyle::Auto),
"always" => Ok(WriteStyle::Always),
"never" => Ok(WriteStyle::Never),
_ => Err(anyhow!("Configuration error")),
}
match spec {
"auto" => Ok(WriteStyle::Auto),
"always" => Ok(WriteStyle::Always),
"never" => Ok(WriteStyle::Never),
_ => Err(anyhow!("Configuration error")),
}
}

#[derive(StructOpt, Debug, Clone)]
pub struct LoggingOptions {
/// Disables logging
#[structopt(long = "quiet", short = "q")]
pub quiet: bool,
/// Disables logging
#[structopt(long = "quiet", short = "q")]
pub quiet: bool,

/// Outputs the version
#[structopt(long = "version", short = "v")]
pub version: bool,
/// Outputs the version
#[structopt(long = "version", short = "v")]
pub version: bool,

/// Turns on verbose logging
#[structopt(long = "verbose", short = "V")]
pub verbose: bool,
/// Turns on verbose logging
#[structopt(long = "verbose", short = "V")]
pub verbose: bool,

/// Turns on debug logging
#[structopt(long = "debug")]
pub debug: bool,
/// Turns on debug logging
#[structopt(long = "debug")]
pub debug: bool,

/// Turns on trace logging
#[structopt(long = "trace")]
pub trace: bool,
/// Turns on trace logging
#[structopt(long = "trace")]
pub trace: bool,

/// Log as JSON
#[structopt(long = "json")]
pub json: bool,
/// Log as JSON
#[structopt(long = "json")]
pub json: bool,

/// Log style
#[structopt(
/// Log style
#[structopt(
long = "log-style",
env = "VINO_LOG_STYLE",
parse(try_from_str = parse_write_style),
default_value="auto"
)]
pub log_style: WriteStyle,
pub log_style: WriteStyle,
}
46 changes: 23 additions & 23 deletions crates/vino-configfile/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,37 @@ use directories_next::BaseDirs;
use serde::Deserialize;
#[derive(Debug, Deserialize, Default)]
pub struct VinoConfig {
pub cache_dir: Option<String>,
pub cache_dir: Option<String>,
}

#[allow(dead_code)]
fn load_configfile<T: AsRef<str>>(file: T) -> VinoConfig {
let mut dir = match BaseDirs::new() {
Some(base_dirs) => base_dirs.home_dir().to_path_buf(),
None => PathBuf::new(),
};
let mut dir = match BaseDirs::new() {
Some(base_dirs) => base_dirs.home_dir().to_path_buf(),
None => PathBuf::new(),
};

dir.push(file.as_ref());
if let Ok(result) = std::fs::read_to_string(dir) {
let config: VinoConfig = toml::from_str(&result).unwrap_or_default();
dir.push(file.as_ref());
if let Ok(result) = std::fs::read_to_string(dir) {
let config: VinoConfig = toml::from_str(&result).unwrap_or_default();

println!("{:?}", config);
config
} else {
VinoConfig::default()
}
println!("{:?}", config);
config
} else {
VinoConfig::default()
}
}

#[cfg(test)]
mod tests {
use crate::load_configfile;
fn init() {
env_logger::init();
}
#[test]
fn runs_crud_api_config() {
init();
let config = load_configfile(".vinocfg");
println!("{:?}", config);
}
use crate::load_configfile;
fn init() {
env_logger::init();
}
#[test]
fn runs_crud_api_config() {
init();
let config = load_configfile(".vinocfg");
println!("{:?}", config);
}
}
50 changes: 25 additions & 25 deletions crates/vino-guest/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,43 +4,43 @@ use std::fmt::Display;

#[derive(Deserialize, Serialize, Debug)]
pub enum Signal {
Done,
Waiting,
HostError,
Done,
Waiting,
HostError,
}

impl Default for Signal {
fn default() -> Self {
Signal::Done
}
fn default() -> Self {
Signal::Done
}
}

impl Display for Signal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Signal::Done => "done".to_string(),
Signal::Waiting => "waiting".to_string(),
Signal::HostError => "host error".to_string(),
},
)
}
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Signal::Done => "done".to_string(),
Signal::Waiting => "waiting".to_string(),
Signal::HostError => "host error".to_string(),
},
)
}
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum OutputPayload {
MessagePack(Vec<u8>),
Exception(String),
Error(String),
MessagePack(Vec<u8>),
Exception(String),
Error(String),
}

#[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)]
pub struct ConnectionDownstream {
pub namespace: String,
pub host_id: String,
pub tx_id: String,
pub actor: String,
pub reference: String,
pub namespace: String,
pub host_id: String,
pub tx_id: String,
pub actor: String,
pub reference: String,
}
Loading

0 comments on commit 168adf2

Please sign in to comment.