Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor env_var arg #1443

Merged
merged 1 commit into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 13 additions & 28 deletions src/cli/args/env_var.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,26 @@
use std::ffi::OsStr;

use clap::{Arg, Command, Error};
use std::str::FromStr;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct EnvVarArg {
pub key: String,
pub value: Option<String>,
}

impl EnvVarArg {
pub fn parse(input: &str) -> Self {
input
.split_once('=')
.map(|(k, v)| Self {
impl FromStr for EnvVarArg {
type Err = miette::Error;

fn from_str(input: &str) -> miette::Result<Self> {
let ev = match input.split_once('=') {
Some((k, v)) => Self {
key: k.to_string(),
value: Some(v.to_string()),
})
.unwrap_or_else(|| Self {
},
None => Self {
key: input.to_string(),
value: None,
})
}
}

#[derive(Debug, Clone)]
pub struct EnvVarArgParser;

impl clap::builder::TypedValueParser for EnvVarArgParser {
type Value = EnvVarArg;

fn parse_ref(
&self,
_cmd: &Command,
_arg: Option<&Arg>,
value: &OsStr,
) -> Result<Self::Value, Error> {
Ok(EnvVarArg::parse(&value.to_string_lossy()))
},
};
Ok(ev)
}
}

Expand All @@ -52,7 +37,7 @@ mod tests {
];

for (input, want) in values {
let got = EnvVarArg::parse(input);
let got: EnvVarArg = input.parse().unwrap();
assert_eq!(got, want);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/cli/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::env;
use crate::file::display_path;
use crate::ui::table;

use super::args::env_var::{EnvVarArg, EnvVarArgParser};
use super::args::env_var::EnvVarArg;

/// Manage environment variables
///
Expand All @@ -36,7 +36,7 @@ pub struct Set {

/// Environment variable(s) to set
/// e.g.: NODE_ENV=production
#[clap(value_parser = EnvVarArgParser, verbatim_doc_comment)]
#[clap(verbatim_doc_comment)]
env_vars: Option<Vec<EnvVarArg>>,
}

Expand Down