Skip to content

Commit

Permalink
fix(Config): Renaming of config options to correctly generate schema;…
Browse files Browse the repository at this point in the history
… add docs
  • Loading branch information
nokome committed Apr 23, 2021
1 parent 7869a92 commit 2466e20
Show file tree
Hide file tree
Showing 9 changed files with 137 additions and 110 deletions.
10 changes: 5 additions & 5 deletions cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,15 +153,15 @@ pub async fn main() -> Result<()> {

// Determine the log level to use on stderr
let level = if debug {
logging::Level::Debug
logging::LoggingLevel::Debug
} else if info {
logging::Level::Info
logging::LoggingLevel::Info
} else if warn {
logging::Level::Warn
logging::LoggingLevel::Warn
} else if error {
logging::Level::Error
logging::LoggingLevel::Error
} else {
logging::Level::Info
logging::LoggingLevel::Info
};

// Create a preliminary logging subscriber to be able to log any issues
Expand Down
7 changes: 6 additions & 1 deletion node/src/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ describe('config', () => {
$schema: 'http://json-schema.org/draft-07/schema#',
title: 'Config',
type: 'object',
definitions: expect.objectContaining({}),
definitions: expect.objectContaining({
LoggingConfig: expect.objectContaining({}),
PluginsConfig: expect.objectContaining({}),
ServeConfig: expect.objectContaining({}),
UpgradeConfig: expect.objectContaining({}),
}),
properties: expect.objectContaining({
logging: expect.objectContaining({}),
plugins: expect.objectContaining({}),
Expand Down
6 changes: 3 additions & 3 deletions node/src/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::sync::{Mutex, MutexGuard};
use stencila::{
config::Config,
once_cell::sync::Lazy,
plugins::{self, Installation, Plugin, Plugins},
plugins::{self, Plugin, PluginInstallation, Plugins},
};

/// A global plugins store
Expand Down Expand Up @@ -112,15 +112,15 @@ pub fn installations(
cx: &mut FunctionContext,
position: i32,
config: &Config,
) -> Result<Vec<Installation>, Throw> {
) -> Result<Vec<PluginInstallation>, Throw> {
let arg = cx.argument::<JsArray>(position)?.to_vec(cx)?;
if arg.is_empty() {
Ok(config.plugins.installations.clone())
} else {
let mut installations = Vec::new();
for value in arg {
let str = value.to_string(cx)?.value(cx);
let installation = match plugins::Installation::from_str(&str) {
let installation = match plugins::PluginInstallation::from_str(&str) {
Ok(value) => value,
Err(error) => return cx.throw_error(error.to_string()),
};
Expand Down
8 changes: 4 additions & 4 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ request-ws = ["tokio-tungstenite", "jsonwebtoken"]
plugins = ["jsonschema", "semver"]
plugins-docker = ["plugins", "bollard"]
plugins-binary = ["plugins", "self_update"]
plugins-js = ["plugins"]
plugins-py = ["plugins"]
plugins-javascript = ["plugins"]
plugins-python = ["plugins"]
plugins-r = ["plugins"]
plugins-link = ["plugins"]

Expand Down Expand Up @@ -69,8 +69,8 @@ default = [
"plugins-binary",
"plugins-docker",
"plugins-link",
"plugins-js",
"plugins-py",
"plugins-javascript",
"plugins-python",
"plugins-r",
"upgrade",
"config",
Expand Down
26 changes: 15 additions & 11 deletions rust/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{logging, plugins, serve, upgrade, util};
use anyhow::{bail, Result};
use schemars::{schema_for, JsonSchema};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::Write;
Expand All @@ -11,23 +11,27 @@ use validator::Validate;
#[serde(default)]
pub struct Config {
#[validate]
pub logging: logging::config::Config,
pub logging: logging::config::LoggingConfig,

#[validate]
pub serve: serve::config::Config,
pub serve: serve::config::ServeConfig,

#[validate]
pub plugins: plugins::config::Config,
pub plugins: plugins::config::PluginsConfig,

#[validate]
pub upgrade: upgrade::config::Config,
pub upgrade: upgrade::config::UpgradeConfig,
}

const CONFIG_FILE: &str = "config.toml";

/// Get the JSON Schema for the configuration
pub fn schema() -> String {
let schema = schema_for!(Config);
use schemars::gen::SchemaSettings;

let settings = SchemaSettings::default();
let generator = settings.into_generator();
let schema = generator.into_root_schema_for::<Config>();
serde_json::to_string_pretty(&schema).unwrap()
}

Expand Down Expand Up @@ -408,15 +412,15 @@ mod tests {
fn test_cli() -> Result<()> {
use super::cli::*;

let config = Config {
let mut config = Config {
..Default::default()
};

run(
Args {
action: Action::Get(Get { pointer: None }),
},
&config,
&mut config,
)?;

run(
Expand All @@ -426,7 +430,7 @@ mod tests {
value: "true".to_string(),
}),
},
&config,
&mut config,
)?;

run(
Expand All @@ -435,14 +439,14 @@ mod tests {
property: "upgrade".to_string(),
}),
},
&config,
&mut config,
)?;

run(
Args {
action: Action::Dirs,
},
&config,
&mut config,
)?;

Ok(())
Expand Down
50 changes: 32 additions & 18 deletions rust/src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use validator::Validate;

#[derive(Debug, PartialEq, Clone, Copy, JsonSchema, Deserialize, Serialize, ToString)]
#[serde(rename_all = "lowercase")]
pub enum Level {
pub enum LoggingLevel {
Debug,
Info,
Warn,
Expand All @@ -18,7 +18,7 @@ pub enum Level {

#[derive(Debug, PartialEq, Clone, Copy, JsonSchema, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Format {
pub enum LoggingFormat {
Plain,
Pretty,
Json,
Expand All @@ -29,28 +29,40 @@ pub mod config {
use super::*;
use crate::util::dirs;

/// Configuration settings for log entries printed to stderr when using the CLI
#[derive(
Debug, Defaults, PartialEq, Clone, Copy, JsonSchema, Deserialize, Serialize, Validate,
)]
pub struct StdErr {
pub struct LoggingStdErrConfig {
/// The maximum log level to emit
#[def = "Level::Info"]
pub level: Level,
#[def = "LoggingLevel::Info"]
pub level: LoggingLevel,

/// The format for the logs entries
#[def = "Format::Pretty"]
pub format: Format,
#[def = "LoggingFormat::Pretty"]
pub format: LoggingFormat,
}

/// Configuration settings for log entries shown to the user in the desktop
#[derive(
Debug, Defaults, PartialEq, Clone, Copy, JsonSchema, Deserialize, Serialize, Validate,
)]
pub struct LoggingDesktopConfig {
/// The maximum log level to emit
#[def = "LoggingLevel::Info"]
pub level: LoggingLevel,
}

/// Configuration settings for logs entries written to file
#[derive(Debug, Defaults, PartialEq, Clone, JsonSchema, Deserialize, Serialize, Validate)]
pub struct File {
pub struct LoggingFileConfig {
/// The path of the log file
#[def = "default_file_path()"]
pub path: String,

/// The maximum log level to emit
#[def = "Level::Debug"]
pub level: Level,
#[def = "LoggingLevel::Debug"]
pub level: LoggingLevel,
}

/// Get the default value for `logging.file.path`
Expand All @@ -63,10 +75,12 @@ pub mod config {
.expect("Unable to convert path to string")
}

/// Configuration settings for logging
#[derive(Debug, Default, PartialEq, Clone, JsonSchema, Deserialize, Serialize, Validate)]
pub struct Config {
pub stderr: StdErr,
pub file: File,
pub struct LoggingConfig {
pub stderr: LoggingStdErrConfig,
pub desktop: LoggingDesktopConfig,
pub file: LoggingFileConfig,
}
}

Expand All @@ -85,16 +99,16 @@ pub fn prelim() -> tracing::subscriber::DefaultGuard {

/// Initialize a logging subscriber based on passed args and read config.
pub fn init(
level: Option<Level>,
config: &config::Config,
level: Option<LoggingLevel>,
config: &config::LoggingConfig,
) -> Result<[tracing_appender::non_blocking::WorkerGuard; 2]> {
use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter};

let config::Config { stderr, file } = config;
let config::LoggingConfig { stderr, file, .. } = config;

let level = level.unwrap_or(stderr.level);

let (stderr_writer, stderr_guard) = if level != Level::Never {
let (stderr_writer, stderr_guard) = if level != LoggingLevel::Never {
tracing_appender::non_blocking(std::io::stderr())
} else {
tracing_appender::non_blocking(std::io::sink())
Expand All @@ -104,7 +118,7 @@ pub fn init(
.without_time()
.with_writer(stderr_writer);

let (file_writer, file_guard) = if file.level != Level::Never {
let (file_writer, file_guard) = if file.level != LoggingLevel::Never {
let path = Path::new(&file.path);
let file_appender =
tracing_appender::rolling::daily(&path.parent().unwrap(), &path.file_name().unwrap());
Expand Down

0 comments on commit 2466e20

Please sign in to comment.