#![doc(
html_root_url = "https://docs.rs/spirit-cfg-helpers/0.4.0/spirit_cfg_helpers/",
test(attr(deny(warnings)))
)]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![allow(
unknown_lints,
clippy::unknown_clippy_lints,
clippy::needless_doctest_main
)]
use std::borrow::Borrow;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::process;
use std::str::FromStr;
use std::sync::Arc;
use arc_swap::ArcSwap;
use log::{log, Level};
use serde::de::DeserializeOwned;
use serde::Serialize;
use spirit::extension::{Extensible, Extension};
use spirit::validation::Action;
use spirit::Builder;
use structopt::StructOpt;
pub fn config_logging<E>(level: Level, opts_too: bool) -> impl Extension<E>
where
E: Extensible,
E::Opts: Debug,
E::Config: Debug,
{
move |ext: E| {
ext.on_config(move |opts, cfg| {
if opts_too {
log!(
level,
"Using cmd-line options {:?} and configuration {:?}",
opts,
cfg
);
} else {
log!(level, "Using configuration {:?}", cfg);
}
})
}
}
#[derive(Debug)]
struct DumpFormatParseError(String);
impl Display for DumpFormatParseError {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
write!(fmt, "Invalid config format {}", self.0)
}
}
impl Error for DumpFormatParseError {}
#[derive(Copy, Clone, Debug)]
enum DumpFormat {
Toml,
#[cfg(feature = "json")]
Json,
#[cfg(feature = "yaml")]
Yaml,
}
impl DumpFormat {
fn dump<C: Serialize>(self, cfg: &C) {
let dump = match self {
DumpFormat::Toml => {
let value =
toml::Value::try_from(cfg).expect("Dirty stuff in config, can't manipulate");
toml::to_string_pretty(&value).expect("Dirty stuff in config, can't dump")
}
#[cfg(feature = "json")]
DumpFormat::Json => {
serde_json::to_string_pretty(cfg).expect("Dirty stuff in config, can't dump")
}
#[cfg(feature = "yaml")]
DumpFormat::Yaml => {
serde_yaml::to_string(cfg).expect("Dirty stuff in config, can't dump")
}
};
println!("{}", dump);
}
}
impl FromStr for DumpFormat {
type Err = DumpFormatParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"toml" => Ok(DumpFormat::Toml),
#[cfg(feature = "json")]
"json" => Ok(DumpFormat::Json),
#[cfg(feature = "yaml")]
"yaml" => Ok(DumpFormat::Yaml),
s => Err(DumpFormatParseError(s.to_owned())),
}
}
}
#[cfg_attr(not(doc), allow(missing_docs))]
#[cfg_attr(
doc,
doc = r#"
A command line fragment to add `--dump-config` to allow showing loaded configuration.
When this is added into the command line options structure, the `--dump-config` and
`--dump-config-as` options are added.
These dump the current configuration and exit.
In case the configuration is collected over multiple configuration files, directories and
possibly environment variables and command line overrides, it is not always clear what exact
configuration is actually used. This allows the user to query the actual configuration the
application would use.
The fragment can be either used manually with the [`dump`][CfgDump::dump] method or
automatically by registering its [`extension`][CfgDump::extension].
# Requirements
For this to work, the configuration structure must implement [`Serialize`]. This is not
mandated by [`Spirit`][spirit::Spirit] itself. However, all the fragments provided by spirit
crates implement it. For custom structures it is often sufficient to stick
`#[derive(Serialize)]` onto them.
# Examples
```rust
use serde_derive::{Deserialize, Serialize};
use spirit::Spirit;
use spirit::prelude::*;
use spirit_cfg_helpers::CfgDump;
use structopt::StructOpt;
#[derive(Default, Deserialize, Serialize)]
struct Cfg {
option: Option<String>,
}
#[derive(Debug, StructOpt)]
struct Opts {
#[structopt(flatten)]
dump: CfgDump,
}
impl Opts {
fn dump(&self) -> &CfgDump {
&self.dump
}
}
fn main() {
Spirit::<Opts, Cfg>::new()
.with(CfgDump::extension(Opts::dump))
.run(|_| Ok(()));
}
```
"#
)]
#[derive(Clone, Debug, Default, StructOpt)]
pub struct CfgDump {
#[structopt(long = "--dump-config")]
dump_config: bool,
#[cfg_attr(feature = "json", doc = "json")]
#[cfg_attr(feature = "yaml", doc = "yaml")]
#[structopt(long = "--dump-config-as")]
dump_config_as: Option<DumpFormat>,
}
impl CfgDump {
pub fn dump<C: Serialize>(&self, cfg: &C) {
if let Some(format) = self.dump_config_as {
format.dump(cfg);
} else if self.dump_config {
DumpFormat::Toml.dump(cfg);
} else {
return;
}
process::exit(0);
}
pub fn extension<E, F>(extract: F) -> impl Extension<E>
where
E: Extensible<Ok = E>,
F: FnOnce(&E::Opts) -> &Self + Send + 'static,
E::Config: Serialize,
{
let mut extract = Some(extract);
let validator = move |_: &_, cfg: &_, opts: &_| {
if let Some(extract) = extract.take() {
let me = extract(opts);
me.dump(&cfg as &E::Config);
}
Ok(Action::new())
};
|ext: E| ext.config_validator(validator)
}
}
#[cfg(feature = "cfg-help")]
mod cfg_help {
use super::*;
use structdoc::StructDoc;
#[cfg_attr(not(doc), allow(missing_docs))]
#[cfg_attr(
doc,
doc = r#"
A command line options fragment to add the `--help-config` option.
For the user to be able to configure an application, the user needs to know what options
can be configured. Usually, this is explained using an example configuration file or through
a manually written documentation. However, maintaining either is a lot of work, not
mentioning that various [spirit] crates provide configuration fragments composed from
several type parameters so hunting down all the available options might be hard.
This helper uses the [`StructDoc`] trait to extract the structure and documentation of the
configuration automatically. Usually, its derive will extract description from fields' doc
comments. See the [structdoc] crate's documentation to know how to let the documentation be
created semi-automatically. All the configuration fragments provided by the spirit crates
implement [`StructDoc`], unless their [`cfg-help`] feature is disabled.
When the `--help-config` is specified, this auto-generated documentation is printed and the
application exits.
The fragment can be used either manually with the [`help`][CfgHelp::help] method or by
registering the [`extension`][CfgHelp::extension] within an
[`Extensible`][Extensible::with].
# Examples
```rust
use serde_derive::Deserialize;
use spirit::Spirit;
use spirit::prelude::*;
use spirit_cfg_helpers::CfgHelp;
use structdoc::StructDoc;
use structopt::StructOpt;
#[derive(Default, Deserialize, StructDoc)]
struct Cfg {
/// A very much useless but properly documented option.
# #[allow(dead_code)]
option: Option<String>,
}
#[derive(Debug, StructOpt)]
struct Opts {
#[structopt(flatten)]
help: CfgHelp,
}
impl Opts {
fn help(&self) -> &CfgHelp {
&self.help
}
}
fn main() {
Spirit::<Opts, Cfg>::new()
.with(CfgHelp::extension(Opts::help))
.run(|_| Ok(()));
}
"#
)]
#[derive(Clone, Debug, Default, StructOpt)]
pub struct CfgHelp {
#[structopt(long = "--help-config")]
config_help: bool,
}
impl CfgHelp {
pub fn help<C: StructDoc>(&self) {
if self.config_help {
println!("{}", C::document());
process::exit(0);
}
}
pub fn extension<O, C, F>(extract: F) -> impl Extension<Builder<O, C>>
where
F: FnOnce(&O) -> &Self + Send + 'static,
O: Debug + StructOpt + Send + Sync + 'static,
C: DeserializeOwned + StructDoc + Send + Sync + 'static,
{
|builder: Builder<O, C>| {
builder.before_config(|_: &C, opts: &O| {
extract(opts).help::<C>();
Ok(())
})
}
}
}
#[cfg_attr(not(doc), allow(missing_docs))]
#[cfg_attr(
doc,
doc = r#"
A combination of the [`CfgDump`] and [`CfgHelp`] fragments.
This is simply a combination of both fragments, providing the same options and
functionality. Usually one wants to use both. This saves a bit of code, as only one field
and one extension needs to be registered.
# Requirements
For this to work, the configuration structure needs to implement both [`Serialize`] and
[`StructDoc`].
"#
)]
#[derive(Clone, Debug, Default, StructOpt)]
pub struct Opts {
#[structopt(flatten)]
config_dump: CfgDump,
#[structopt(flatten)]
config_help: CfgHelp,
}
impl Opts {
pub fn extension<O, C, F>(extract: F) -> impl Extension<Builder<O, C>>
where
F: Fn(&O) -> &Self + Send + Sync + 'static,
O: Debug + StructOpt + Send + Sync + 'static,
C: DeserializeOwned + Serialize + StructDoc + Send + Sync + 'static,
{
let extract_dump = Arc::new(extract);
let extract_help = Arc::clone(&extract_dump);
|builder: Builder<O, C>| {
builder
.with(CfgDump::extension(move |opts| {
&extract_dump(opts).config_dump
}))
.with(CfgHelp::extension(move |opts| {
&extract_help(opts).config_help
}))
}
}
}
}
#[cfg(feature = "cfg-help")]
pub use crate::cfg_help::{CfgHelp, Opts};
pub fn cfg_store<S, E>(storage: S) -> impl Extension<E>
where
E: Extensible,
S: Borrow<ArcSwap<E::Config>> + Send + Sync + 'static,
{
|ext: E| ext.on_config(move |_o: &_, c: &Arc<E::Config>| storage.borrow().store(Arc::clone(c)))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_derive::Serialize;
#[test]
fn toml_out_of_order() {
#[derive(Default, Serialize)]
struct A {
x: i32,
y: i32,
}
#[derive(Default, Serialize)]
struct B {
a: A,
z: i32,
}
let b = B::default();
DumpFormat::Toml.dump(&b);
}
}