1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
//! Parse environment variables by defining a struct. //! //! ## Example //! ```rust //! use envopt::EnvOpt; //! //! #[derive(EnvOpt)] //! pub enum EnvOpts { //! #[envopt(name = "FOO")] //! Foo, //! #[envopt(name = "BAR", default = "default-bar")] //! Bar, //! } //! //! pub fn main() { //! EnvOpts::validate_or_exit(); //! //! println!("FOO: {}", EnvOpts::Foo.value_or_exit()); //! println!("BAR: {}", EnvOpts::Bar.value_or_exit()); //! } //! ``` #[doc(hidden)] pub use envopt_derive::*; /// A struct that is converted from environment variables. pub trait EnvOpt { /// Validate all configured environment variables. /// /// Variants without a default cause an error. fn validate() -> Result<(), Vec<String>>; /// Validate all configured environment variables. /// /// If variants without a default are missing exit. fn validate_or_exit() { match Self::validate() { Ok(()) => {} Err(errors) => { for error in errors { eprintln!("{}", error); } std::process::exit(64); } } } /// Get the value for a variant. /// /// If it is missing the default value is returend. /// If no default is defined an error is returned. fn value(&self) -> Result<String, String>; /// Get the value for a variant. /// /// If it is missing the default value is returend. /// If no default is defined exit. fn value_or_exit(&self) -> String { match self.value() { Ok(val) => val, Err(error) => { eprintln!("{}", error); std::process::exit(64); } } } }