diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0f4ecc5..af1db05 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -185,5 +185,10 @@ jobs: select(.name | ascii_downcase | test(\"linux.*x86_64|x86_64.*linux\")).browser_download_url" | \ wget -qi - tar -xvf cargo-msrv*.tar* -C ~/.cargo/bin/ cargo-msrv - printf "%s" "Checking MSRV..." - cargo msrv --output-format json verify | tail -n 1 | jq --exit-status '.success' + # Workaround for https://github.com/foresterre/cargo-msrv/issues/590 + for package in $(cargo metadata --format-version 1 --no-deps | jq -r ".workspace_members[]" | awk '{print $1}'); do + version=$(cargo metadata --format-version 1 --no-deps | jq -r '.packages[] | select(.name | test("^daktilo$")) | .rust_version') + printf "Checking MSRV $version for $package..." + echo -e "[package.metadata]\nmsrv = \"${version}\"" >> "crates/${package}/Cargo.toml" + cargo msrv --output-format json --path "crates/${package}" verify | tail -n 1 | jq --exit-status '.success' + done diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 166c84e..28de66a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -58,7 +58,7 @@ jobs: with: submodules: recursive - name: Install cargo-dist - run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.4.0/cargo-dist-installer.sh | sh" + run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.4.2/cargo-dist-installer.sh | sh" - id: plan run: | cargo dist plan ${{ !github.event.pull_request && format('--tag={0}', github.ref_name) || '' }} --output-format=json > dist-manifest.json @@ -140,7 +140,7 @@ jobs: with: submodules: recursive - name: Install cargo-dist - run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.4.0/cargo-dist-installer.sh | sh" + run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.4.2/cargo-dist-installer.sh | sh" # Get all the local artifacts for the global tasks to use (for e.g. checksums) - name: Fetch local artifacts uses: actions/download-artifact@v3 diff --git a/Cargo.lock b/Cargo.lock index 2a47d95..5d87b67 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -441,9 +441,9 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.2.9" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" +checksum = "ce420fe07aecd3e67c5f910618fe65e94158f6dcc0adf44e00d69ce2bdfe0fd0" dependencies = [ "libc", ] @@ -475,6 +475,20 @@ dependencies = [ "clap_complete", "clap_mangen", "colored", + "daktilo_lib", + "dirs", + "pretty_assertions", + "regex", + "serde", + "serde_regex", + "tokio", + "tracing", +] + +[[package]] +name = "daktilo_lib" +version = "0.5.0" +dependencies = [ "dirs", "fastrand", "pretty_assertions", @@ -615,9 +629,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "hashbrown" -version = "0.14.1" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dfda62a12f55daeae5015f81b0baea145391cb4520f86c248fc615d72640d12" +checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156" [[package]] name = "heck" @@ -856,17 +870,6 @@ dependencies = [ "adler", ] -[[package]] -name = "mio" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" -dependencies = [ - "libc", - "wasi", - "windows-sys", -] - [[package]] name = "ndk" version = "0.7.0" @@ -1289,9 +1292,9 @@ checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" [[package]] name = "rustix" -version = "0.38.19" +version = "0.38.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "745ecfa778e66b2b63c88a61cb36e0eea109e803b0b86bf9879fbc77c70e86ed" +checksum = "2b426b0506e5d50a7d8dafcf2e81471400deb602392c7dd110815afb4eaf02a3" dependencies = [ "bitflags 2.4.1", "errno", @@ -1380,31 +1383,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7cee0529a6d40f580e7a5e6c495c8fbfe21b7b52795ed4bb5e62cdf92bc6380" -[[package]] -name = "signal-hook-registry" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" -dependencies = [ - "libc", -] - [[package]] name = "smallvec" version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" -[[package]] -name = "socket2" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4031e820eb552adee9295814c0ced9e5cf38ddf1e8b7d566d6de8e2538ea989e" -dependencies = [ - "libc", - "windows-sys", -] - [[package]] name = "strsim" version = "0.10.0" @@ -1530,16 +1514,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f38200e3ef7995e5ef13baec2f432a6da0aa9ac495b2c0e8f3b7eec2c92d653" dependencies = [ "backtrace", - "bytes", - "libc", - "mio", "num_cpus", - "parking_lot", "pin-project-lite", - "signal-hook-registry", - "socket2", "tokio-macros", - "windows-sys", ] [[package]] @@ -1632,12 +1609,12 @@ dependencies = [ [[package]] name = "tracing-log" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" +checksum = "f751112709b4e791d8ce53e32c4ed2d353565a795ce84da2285393f41557bdf2" dependencies = [ - "lazy_static", "log", + "once_cell", "tracing-core", ] diff --git a/Cargo.toml b/Cargo.toml index 72c47ea..3c45eba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,8 @@ -[package] -name = "daktilo" +[workspace] +members = ["crates/*"] +resolver = "2" + +[workspace.package] version = "0.5.0" description = "Turn your keyboard into a typewriter! 📇" authors = ["Orhun Parmaksız "] @@ -9,43 +12,16 @@ homepage = "https://github.com/orhun/daktilo" repository = "https://github.com/orhun/daktilo" keywords = ["typewriter", "keyboard", "nostalgic", "type"] categories = ["command-line-utilities", "multimedia"] -default-run = "daktilo" rust-version = "1.70.0" edition = "2021" -[features] -audio-tests = [] - -[[bin]] -name = "daktilo-completions" -path = "src/bin/completions.rs" - -[[bin]] -name = "daktilo-mangen" -path = "src/bin/mangen.rs" - -[dependencies] -rdev = { version = "0.5.3", features = ["serialize"] } -rodio = { version = "0.17.3", default-features = false, features = [ - "symphonia-mp3", -] } -rust-embed = { version = "8.0.0", features = ["debug-embed", "compression"] } +[workspace.dependencies] thiserror = "1.0.50" -tokio = { version = "1.33.0", features = ["full"] } +serde = { version = "1.0.190", features = ["derive"] } tracing = "0.1.40" tracing-subscriber = { version = "0.3.17", features = ["env-filter"] } -clap = { version = "4.4.7", features = ["derive", "env", "wrap_help", "cargo"] } -serde = { version = "1.0.190", features = ["derive"] } -dirs = "5.0.1" -toml = "0.8.6" -regex = "1.10.2" -serde_regex = "1.1.0" +tokio = { version = "1.33.0", features = ["macros", "rt-multi-thread", "sync"] } colored = "2.0.4" -clap_complete = "4.4.4" -clap_mangen = "0.2.15" -fastrand = "2.0.1" - -[dev-dependencies] pretty_assertions = "1.4.0" [profile.dev] @@ -93,13 +69,3 @@ targets = [ pr-run-mode = "upload" # Skip checking whether the specified configuration files are up to date allow-dirty = ["ci", "msi"] - -[workspace.metadata.dist.dependencies.apt] -libasound2-dev = '*' -libxi-dev = '*' -libxtst-dev = '*' -pkg-config = '*' - -[package.metadata.wix] -upgrade-guid = "51610A8E-55C9-4F49-8C9F-3529499D5C60" -path-guid = "2198A7FB-5F3C-4FAB-B253-2314115AD2DD" diff --git a/crates/daktilo/Cargo.toml b/crates/daktilo/Cargo.toml new file mode 100644 index 0000000..127664f --- /dev/null +++ b/crates/daktilo/Cargo.toml @@ -0,0 +1,51 @@ +[package] +name = "daktilo" +version.workspace = true +description.workspace = true +authors.workspace = true +license.workspace = true +readme.workspace = true +homepage.workspace = true +repository.workspace = true +keywords.workspace = true +categories.workspace = true +rust-version.workspace = true +edition.workspace = true +default-run = "daktilo" + +[features] +audio-tests = [] + +[[bin]] +name = "daktilo-completions" +path = "src/bin/completions.rs" + +[[bin]] +name = "daktilo-mangen" +path = "src/bin/mangen.rs" + +[dependencies] +clap = { version = "4.4.7", features = ["derive", "env", "wrap_help", "cargo"] } +dirs = "5.0.1" +regex = "1.10.2" +serde_regex = "1.1.0" +clap_complete = "4.4.4" +clap_mangen = "0.2.15" +colored = "2.0.4" +tokio.workspace = true +serde.workspace = true +tracing.workspace = true +daktilo_lib = { path = "../daktilo_lib" } + +[dev-dependencies] +pretty_assertions.workspace = true + +[package.metadata.dist.dependencies.apt] +libasound2-dev = '*' +libxi-dev = '*' +libxtst-dev = '*' +pkg-config = '*' + +[package.metadata.wix] +upgrade-guid = "51610A8E-55C9-4F49-8C9F-3529499D5C60" +path-guid = "2198A7FB-5F3C-4FAB-B253-2314115AD2DD" diff --git a/src/args.rs b/crates/daktilo/src/args.rs similarity index 96% rename from src/args.rs rename to crates/daktilo/src/args.rs index 8ab022f..e94855d 100644 --- a/src/args.rs +++ b/crates/daktilo/src/args.rs @@ -2,7 +2,7 @@ use std::path::PathBuf; use clap::Parser; -use crate::config::SoundVariation; +use daktilo_lib::config::SoundVariation; /// Typewriter ASCII banner. pub const BANNER: &str = r#" @@ -34,8 +34,8 @@ pub const BANNER: &str = r#" )] pub struct Args { /// Enables verbose logging. - #[arg(short, long, env)] - pub verbose: bool, + #[arg(short, long, action = clap::ArgAction::Count)] + pub verbose: u8, /// Sets the name of the sound preset to use. /// /// Can be specified multiple times to play multiple presets at once. diff --git a/src/bin/completions.rs b/crates/daktilo/src/bin/completions.rs similarity index 75% rename from src/bin/completions.rs rename to crates/daktilo/src/bin/completions.rs index 9290197..0c25d72 100644 --- a/src/bin/completions.rs +++ b/crates/daktilo/src/bin/completions.rs @@ -27,12 +27,20 @@ fn main() -> Result<()> { #[cfg(test)] mod tests { + use std::path::PathBuf; + use super::*; #[test] fn generate_completions() -> Result<()> { - if env::var(OUT_DIR_ENV).is_ok() { - main()?; + let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../"); + if let Ok(out_dir) = env::var(OUT_DIR_ENV) { + path = path.join(out_dir); + } else { + path = path.join("target"); } + + env::set_var(OUT_DIR_ENV, path); + main()?; Ok(()) } } diff --git a/src/bin/mangen.rs b/crates/daktilo/src/bin/mangen.rs similarity index 78% rename from src/bin/mangen.rs rename to crates/daktilo/src/bin/mangen.rs index af46f42..53260f1 100644 --- a/src/bin/mangen.rs +++ b/crates/daktilo/src/bin/mangen.rs @@ -32,11 +32,18 @@ fn main() -> Result<()> { #[cfg(test)] mod tests { use super::*; + #[test] fn generate_manpage() -> Result<()> { - if env::var(OUT_DIR_ENV).is_ok() { - main()?; + let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../"); + if let Ok(out_dir) = env::var(OUT_DIR_ENV) { + path = path.join(out_dir); + } else { + path = path.join("target"); } + + env::set_var(OUT_DIR_ENV, path); + main()?; Ok(()) } } diff --git a/crates/daktilo/src/lib.rs b/crates/daktilo/src/lib.rs new file mode 100644 index 0000000..892dcf5 --- /dev/null +++ b/crates/daktilo/src/lib.rs @@ -0,0 +1,8 @@ +//! Turn your keyboard into a typewriter! 📇 + +#![warn(missing_docs)] + +/// CLI argument parser. +/// +/// Needs to be in a lib for completions and mangen. +pub mod args; diff --git a/src/main.rs b/crates/daktilo/src/main.rs similarity index 51% rename from src/main.rs rename to crates/daktilo/src/main.rs index d807ec8..7cab2f3 100644 --- a/src/main.rs +++ b/crates/daktilo/src/main.rs @@ -1,23 +1,66 @@ use clap::Parser; -use colored::*; -use rodio::cpal::traits::HostTrait; -use rodio::DeviceTrait; +use colored::Colorize; +use daktilo::args::Args; +use daktilo_lib::config::{Config, KeyEvent, SoundPreset, DEFAULT_CONFIG}; +use daktilo_lib::embed::EmbeddedConfig; +use daktilo_lib::error::Result; +use daktilo_lib::logger; use std::{fs, process}; use tracing::Level; -use daktilo::args::Args; -use daktilo::config::{Config, DEFAULT_CONFIG}; -use daktilo::embed::EmbeddedConfig; -use daktilo::error::Result; -use daktilo::logger; +/// Prints the available presets to stdout as a table. +fn list_presets(presets: Vec) { + tracing::info!("Available presets:"); + presets.iter().for_each(|preset| { + println!("[{}]", preset.name.white().bold()); + let mut table = format!( + " {:<20} {:<20} {:<20}\n", + "Event".bold(), + "Keys".bold(), + "File".bold() + ); + table.push_str(&format!( + " {:<20} {:<20} {:<20}\n", + "-----", "----", "----" + )); + for key_config in &preset.key_config { + let event_str = match key_config.event { + KeyEvent::KeyPress => "Key Press", + KeyEvent::KeyRelease => "Key Release", + }; + let keys_str = key_config.keys.as_str(); + let file_str = &key_config + .files + .iter() + .map(|v| v.path.clone()) + .collect::>() + .join(","); + table.push_str(&format!( + " {:<20} {:<20} {:<20}\n", + event_str, + keys_str, + file_str.italic() + )); + } + println!("{}", table) + }); +} +/// Entry-point of the application. #[tokio::main] async fn main() -> Result<()> { // Parse command-line arguments. let args = Args::parse(); // Initialize the logger. - logger::init(args.verbose.then_some(Level::DEBUG))?; + logger::init( + Some(match args.verbose { + 0 => Level::INFO, + 1 => Level::DEBUG, + _ => Level::TRACE, + }), + vec![env!("CARGO_PKG_NAME").to_string()], + )?; tracing::info!("Starting..."); // Parse the config file. @@ -45,17 +88,14 @@ async fn main() -> Result<()> { // Start the typewriter. if args.list_presets { tracing::info!("Available presets:"); - config - .sound_presets - .iter() - .for_each(|preset| println!("{}", preset)); + list_presets(config.sound_presets); return Ok(()); } else if args.list_devices { tracing::info!("Available devices:"); - rodio::cpal::default_host() - .output_devices()? + daktilo_lib::audio::get_devices()? + .iter() .try_for_each::<_, Result<()>>(|v| { - println!("• {}", v.name()?.white().bold()); + println!("• {}", v.0.white().bold()); Ok(()) })?; return Ok(()); @@ -71,7 +111,7 @@ async fn main() -> Result<()> { .map(|name| config.select_preset(name)) .collect::>>()?; - match daktilo::run( + match daktilo_lib::run( presets, args.sound_variation_args.map(|v| v.into()), args.device, diff --git a/wix/main.wxs b/crates/daktilo/wix/main.wxs similarity index 100% rename from wix/main.wxs rename to crates/daktilo/wix/main.wxs diff --git a/crates/daktilo_lib/Cargo.toml b/crates/daktilo_lib/Cargo.toml new file mode 100644 index 0000000..c43542c --- /dev/null +++ b/crates/daktilo_lib/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "daktilo_lib" +version.workspace = true +description.workspace = true +authors.workspace = true +license.workspace = true +readme.workspace = true +homepage.workspace = true +repository.workspace = true +keywords.workspace = true +categories.workspace = true +rust-version.workspace = true +edition.workspace = true + +[dependencies] +rdev = { version = "0.5.3", features = ["serialize"] } +rodio = { version = "0.17.3", default-features = false, features = [ + "symphonia-mp3", +] } +rust-embed = { version = "8.0.0", features = ["debug-embed", "compression"] } +toml = "0.8.6" +fastrand = "2.0.1" +dirs = "5.0.1" +regex = "1.10.2" +serde_regex = "1.1.0" +tokio.workspace = true +serde.workspace = true +thiserror.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true + +[dev-dependencies] +pretty_assertions.workspace = true diff --git a/src/app.rs b/crates/daktilo_lib/src/app.rs similarity index 100% rename from src/app.rs rename to crates/daktilo_lib/src/app.rs diff --git a/crates/daktilo_lib/src/audio.rs b/crates/daktilo_lib/src/audio.rs new file mode 100644 index 0000000..4bc2692 --- /dev/null +++ b/crates/daktilo_lib/src/audio.rs @@ -0,0 +1,11 @@ +use crate::error::Result; +use rodio::cpal::traits::HostTrait; +use rodio::DeviceTrait; + +/// Get a list of all available audio devices. +pub fn get_devices() -> Result> { + Ok(rodio::cpal::default_host() + .output_devices()? + .map(|d| (d.name().unwrap_or("Unknown".to_string()), d)) + .collect()) +} diff --git a/src/config.rs b/crates/daktilo_lib/src/config.rs similarity index 81% rename from src/config.rs rename to crates/daktilo_lib/src/config.rs index 03d28ad..f26a558 100644 --- a/src/config.rs +++ b/crates/daktilo_lib/src/config.rs @@ -1,16 +1,14 @@ use crate::error::{Error, Result}; -use colored::*; use rdev::Key; use regex::Regex; use serde::{Deserialize, Serialize}; use std::env; -use std::fmt; use std::fs; use std::path::{Path, PathBuf}; use std::str; /// Default configuration file. -pub const DEFAULT_CONFIG: &str = concat!(env!("CARGO_PKG_NAME"), ".toml"); +pub const DEFAULT_CONFIG: &str = "daktilo.toml"; /// Configuration. #[derive(Debug, Serialize, Deserialize)] @@ -116,42 +114,6 @@ pub struct SoundPreset { pub variation: Option, } -impl fmt::Display for SoundPreset { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - writeln!(f, "[{}]", self.name.white().bold())?; - let mut table = format!( - " {:<20} {:<20} {:<20}\n", - "Event".bold(), - "Keys".bold(), - "File".bold() - ); - table.push_str(&format!( - " {:<20} {:<20} {:<20}\n", - "-----", "----", "----" - )); - for key_config in &self.key_config { - let event_str = match key_config.event { - KeyEvent::KeyPress => "Key Press", - KeyEvent::KeyRelease => "Key Release", - }; - let keys_str = key_config.keys.as_str(); - let file_str = &key_config - .files - .iter() - .map(|v| v.path.clone()) - .collect::>() - .join(","); - table.push_str(&format!( - " {:<20} {:<20} {:<20}\n", - event_str, - keys_str, - file_str.italic() - )); - } - write!(f, "{}", table) - } -} - /// Key configuration. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct KeyConfig { @@ -217,8 +179,9 @@ mod tests { #[test] fn test_parse_config() -> Result<()> { let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../") .join("config") - .join(format!("{}.toml", env!("CARGO_PKG_NAME"))); + .join(DEFAULT_CONFIG); if let Some(global_path) = Config::get_default_location() { path = global_path; } diff --git a/src/embed.rs b/crates/daktilo_lib/src/embed.rs similarity index 84% rename from src/embed.rs rename to crates/daktilo_lib/src/embed.rs index 6be59c6..df09a96 100644 --- a/src/embed.rs +++ b/crates/daktilo_lib/src/embed.rs @@ -8,7 +8,7 @@ use std::str; /// Embedded sound assets. #[derive(RustEmbed)] -#[folder = "sounds"] +#[folder = "../../sounds"] pub struct EmbeddedSound; impl EmbeddedSound { @@ -22,7 +22,7 @@ impl EmbeddedSound { /// /// Embeds `config/`[`DEFAULT_CONFIG`] into the binary. #[derive(Debug, RustEmbed)] -#[folder = "config/"] +#[folder = "../../config/"] pub struct EmbeddedConfig; impl EmbeddedConfig { @@ -30,7 +30,10 @@ impl EmbeddedConfig { pub fn get_config() -> Result { match Self::get(DEFAULT_CONFIG) { Some(v) => Ok(str::from_utf8(&v.data)?.to_string()), - None => Err(Error::Embedded(String::from("embedded config not found"))), + None => Err(Error::Embedded(format!( + "embedded config {} not found", + DEFAULT_CONFIG, + ))), } } diff --git a/src/error.rs b/crates/daktilo_lib/src/error.rs similarity index 100% rename from src/error.rs rename to crates/daktilo_lib/src/error.rs diff --git a/src/lib.rs b/crates/daktilo_lib/src/lib.rs similarity index 89% rename from src/lib.rs rename to crates/daktilo_lib/src/lib.rs index 9ed510d..5549484 100644 --- a/src/lib.rs +++ b/crates/daktilo_lib/src/lib.rs @@ -1,4 +1,6 @@ -//! Turn your keyboard into a typewriter! 📇 +//! A library for turning your keyboard into a typewriter! 📇 +//! +//! See [`daktilo`](https://github.com/orhun/daktilo). #![warn(missing_docs)] @@ -11,15 +13,15 @@ pub mod logger; /// File embedder. pub mod embed; -/// Command-line arguments. -pub mod args; - /// Application state. pub mod app; /// Configuration file. pub mod config; +/// Rodio helpers. +pub mod audio; + use app::App; use config::{SoundPreset, SoundVariation}; use error::Result; diff --git a/crates/daktilo_lib/src/logger.rs b/crates/daktilo_lib/src/logger.rs new file mode 100644 index 0000000..7b9d2cf --- /dev/null +++ b/crates/daktilo_lib/src/logger.rs @@ -0,0 +1,20 @@ +use crate::error::Result; +use tracing::Level; +use tracing_subscriber::EnvFilter; + +/// Initializes the logger with the given default log level. +/// +/// Provide your crate names to enable logging for them. +pub fn init(default_level: Option, mut crates: Vec) -> Result<()> { + crates.push(env!("CARGO_PKG_NAME").to_string()); + let mut env_filter = EnvFilter::builder() + .from_env_lossy() + .add_directive("none".parse()?); + for crate_name in crates { + env_filter = env_filter.add_directive( + format!("{}={}", crate_name, default_level.unwrap_or(Level::INFO)).parse()?, + ); + } + tracing_subscriber::fmt().with_env_filter(env_filter).init(); + Ok(()) +} diff --git a/src/logger.rs b/src/logger.rs deleted file mode 100644 index be43cd7..0000000 --- a/src/logger.rs +++ /dev/null @@ -1,23 +0,0 @@ -use crate::error::Result; -use tracing::Level; -use tracing_subscriber::EnvFilter; - -/// Initializes the logger with the given default log level. -pub fn init(default_level: Option) -> Result<()> { - tracing_subscriber::fmt() - .with_env_filter( - EnvFilter::builder() - .from_env_lossy() - .add_directive("none".parse()?) - .add_directive( - format!( - "{}={}", - env!("CARGO_PKG_NAME"), - default_level.unwrap_or(Level::INFO) - ) - .parse()?, - ), - ) - .init(); - Ok(()) -}