Skip to content
This repository was archived by the owner on Mar 1, 2023. It is now read-only.

Commit 0624215

Browse files
committed
feat: add env key to error struct
1 parent c9d8aa0 commit 0624215

File tree

10 files changed

+145
-30
lines changed

10 files changed

+145
-30
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,6 @@
22

33
/target
44

5+
# direnv
6+
.direnv/
7+
.envrc

.vim/coc-settings.json

Lines changed: 0 additions & 3 deletions
This file was deleted.

Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
[package]
22
name = "enve"
3-
version = "0.3.0"
4-
authors = ["Dmitriy Pleshevskiy <dmitriy@ideascup.me>"]
3+
version = "0.4.0"
4+
authors = ["Dmitriy Pleshevskiy <dmitriy@pleshevski.ru>"]
55
description = "it helps you work with environment variables and convert it to any type using only type annotations"
66
categories = ["config"]
77
keywords = ["env", "environment"]

Makefile

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
all: test build
2+
3+
test:
4+
cargo test --all-features
5+
6+
watch-test:
7+
cargo watch -x 'test --all-features'
8+
9+
build: fmt clippy
10+
cargo build
11+
12+
fmt:
13+
cargo fmt -- --check
14+
15+
clippy:
16+
cargo clippy
17+
18+
help:
19+
cat Makefile

examples/calc.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@ USAGE:
1111
E=10+10*2-4 cargo run --example calc --all-features
1212
";
1313

14-
fn main() -> Result<(), enve::Error> {
14+
fn main() {
1515
let res: f32 = enve::get::<Sum<PlusVec<MinusVec<Product<MulVec<f32>>>>>>("E")
1616
.map_err(|err| {
17-
match err {
18-
enve::Error::NotPresent => eprintln!("The expression was not found"),
17+
match err.reason() {
18+
enve::Reason::NotPresent => eprintln!("The expression was not found"),
1919
rest => eprintln!("ERROR: {}", rest),
2020
}
2121

@@ -26,8 +26,6 @@ fn main() -> Result<(), enve::Error> {
2626
.agg();
2727

2828
println!("result: {}", res);
29-
30-
Ok(())
3129
}
3230

3331
struct MinusVec<T>(Vec<T>);

flake.lock

Lines changed: 43 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

flake.nix

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
inputs = {
3+
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
4+
flake-utils.url = "github:numtide/flake-utils";
5+
};
6+
7+
outputs = { self, nixpkgs, flake-utils }:
8+
flake-utils.lib.eachDefaultSystem (system:
9+
let
10+
pkgs = import nixpkgs { inherit system; };
11+
in
12+
{
13+
devShell = pkgs.mkShell {
14+
packages = with pkgs; [
15+
cargo
16+
cargo-watch
17+
rustc
18+
rustfmt
19+
clippy
20+
rust-analyzer
21+
];
22+
RUST_SRC_PATH = pkgs.rustPlatform.rustLibSrc;
23+
};
24+
});
25+
}

src/core.rs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::error::Error;
1+
use crate::error::{Error, Reason};
22
use estring::{EString, ParseFragment, ToEString};
33

44
/// Fetches the environment variable `key` from the current process. It set value `default`
@@ -25,12 +25,14 @@ use estring::{EString, ParseFragment, ToEString};
2525
/// }
2626
/// ```
2727
#[allow(clippy::needless_pass_by_value)]
28-
pub fn get_or_set_default<R>(env_name: &str, default: R) -> Result<R, Error>
28+
pub fn get_or_set_default<R>(key: &str, default: R) -> Result<R, Error>
2929
where
3030
R: ParseFragment + ToEString,
3131
{
32-
get::<R>(env_name).or_else(|err| match err {
33-
Error::NotPresent => sset(env_name, default).parse().map_err(Error::from),
32+
get::<R>(key).or_else(|err| match err.reason() {
33+
Reason::NotPresent => sset(key, default)
34+
.parse()
35+
.map_err(|e| Error(key.to_string(), e.into())),
3436
_ => Err(err),
3537
})
3638
}
@@ -64,7 +66,7 @@ pub fn get<R>(key: &str) -> Result<R, Error>
6466
where
6567
R: ParseFragment,
6668
{
67-
sget(key).and_then(|v| v.parse().map_err(Error::from))
69+
sget(key).and_then(|v| v.parse().map_err(|e| Error(key.to_string(), e.into())))
6870
}
6971

7072
/// Fetches the environment variable `key` from the current process and returns value as
@@ -90,7 +92,9 @@ where
9092
/// }
9193
/// ```
9294
pub fn sget(key: &str) -> Result<EString, Error> {
93-
std::env::var(key).map_err(Error::from).map(EString::from)
95+
std::env::var(key)
96+
.map_err(|e| Error(key.to_string(), e.into()))
97+
.map(EString::from)
9498
}
9599

96100
/// Sets the environment variable `key` to the value `value` for the currently running
@@ -154,7 +158,7 @@ mod tests {
154158
fn should_throw_no_present_error() {
155159
let en = TestCase::<2>.to_string();
156160
match get::<&str>(&en) {
157-
Err(Error::NotPresent) => {}
161+
Err(Error(_, Reason::NotPresent)) => {}
158162
_ => unreachable!(),
159163
};
160164
}
@@ -187,7 +191,7 @@ mod tests {
187191
let en = TestCase::<5>.to_string();
188192
std::env::set_var(&en, "-10");
189193
match get::<u32>(&en) {
190-
Err(Error::Parse(orig)) => {
194+
Err(Error(_, Reason::Parse(orig))) => {
191195
assert_eq!(orig, EString::from("-10"));
192196
}
193197
_ => unreachable!(),
@@ -283,7 +287,7 @@ mod tests {
283287
let en = TestCase::<11>.to_string();
284288
std::env::set_var(&en, "1,2,3,4,5");
285289
match get::<SepVec<i32, '+'>>(&en) {
286-
Err(Error::Parse(orig)) => {
290+
Err(Error(_, Reason::Parse(orig))) => {
287291
assert_eq!(orig, EString::from("1,2,3,4,5"));
288292
}
289293
_ => unreachable!(),

src/error.rs

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,33 @@ use estring::EString;
77

88
/// The error type for operations interacting with environment variables
99
#[derive(Debug)]
10-
pub enum Error {
10+
pub struct Error(pub(crate) String, pub(crate) Reason);
11+
12+
impl Error {
13+
/// Returns the environment variable name for the failure
14+
pub fn var_name(&self) -> &str {
15+
&self.0
16+
}
17+
18+
/// Returns the reason for the failure
19+
pub fn reason(&self) -> &Reason {
20+
&self.1
21+
}
22+
}
23+
24+
impl fmt::Display for Error {
25+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26+
write!(
27+
f,
28+
"The environment variable '{}' failed: {}",
29+
self.0, self.1
30+
)
31+
}
32+
}
33+
34+
/// The reason for the failure to get environment variable
35+
#[derive(Debug, Clone)]
36+
pub enum Reason {
1137
/// The specified environment variable was not present in the current process's environment.
1238
NotPresent,
1339

@@ -20,16 +46,16 @@ pub enum Error {
2046
Invalid(OsString),
2147
}
2248

23-
impl fmt::Display for Error {
49+
impl fmt::Display for Reason {
2450
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2551
match &self {
26-
Error::NotPresent => f.write_str("The specified env variable was not present"),
27-
Error::Invalid(inner) => write!(
52+
Reason::NotPresent => f.write_str("The specified env variable was not present"),
53+
Reason::Invalid(inner) => write!(
2854
f,
2955
"The specified env variable was found, but it did not valid: '{:?}'",
3056
inner,
3157
),
32-
Error::Parse(env_name) => {
58+
Reason::Parse(env_name) => {
3359
write!(f, r#"Failed to parse environment variable "{}""#, env_name)
3460
}
3561
}
@@ -38,17 +64,17 @@ impl fmt::Display for Error {
3864

3965
impl error::Error for Error {}
4066

41-
impl From<VarError> for Error {
67+
impl From<VarError> for Reason {
4268
fn from(err: VarError) -> Self {
4369
match err {
44-
VarError::NotPresent => Error::NotPresent,
45-
VarError::NotUnicode(inner) => Error::Invalid(inner),
70+
VarError::NotPresent => Reason::NotPresent,
71+
VarError::NotUnicode(inner) => Reason::Invalid(inner),
4672
}
4773
}
4874
}
4975

50-
impl From<estring::Error> for Error {
76+
impl From<estring::Error> for Reason {
5177
fn from(err: estring::Error) -> Self {
52-
Error::Parse(err.0)
78+
Reason::Parse(err.0)
5379
}
5480
}

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ mod error;
9494
mod estr;
9595

9696
pub use crate::core::{get, get_or_set_default, sget, sset};
97-
pub use error::Error;
97+
pub use error::*;
9898
pub use estr::*;
9999

100100
pub use estring;

0 commit comments

Comments
 (0)