Allow having only one env conversion (#548)

Allows setting only `from_string` or `to_string` in `env_conversions`
config. Previously, both were required.
This commit is contained in:
Jakub Žádník 2021-12-22 00:32:38 +02:00 committed by GitHub
parent 52dba91e1a
commit deeb1da359
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 75 additions and 70 deletions

View file

@ -12,7 +12,7 @@ impl Command for Env {
} }
fn usage(&self) -> &str { fn usage(&self) -> &str {
"Display current environment" "Display current environment variables"
} }
fn signature(&self) -> nu_protocol::Signature { fn signature(&self) -> nu_protocol::Signature {

View file

@ -16,7 +16,7 @@ const ENV_SEP: &str = ":";
/// It returns Option instead of Result since we do want to translate all the values we can and /// It returns Option instead of Result since we do want to translate all the values we can and
/// skip errors. This function is called in the main() so we want to keep running, we cannot just /// skip errors. This function is called in the main() so we want to keep running, we cannot just
/// exit. /// exit.
pub fn env_to_values( pub fn convert_env_values(
engine_state: &EngineState, engine_state: &EngineState,
stack: &mut Stack, stack: &mut Stack,
config: &Config, config: &Config,
@ -28,40 +28,48 @@ pub fn env_to_values(
let mut new_scope = HashMap::new(); let mut new_scope = HashMap::new();
for (name, val) in scope { for (name, val) in scope {
if let Some(conv) = config.env_conversions.get(name) { if let Some(env_conv) = config.env_conversions.get(name) {
let span = match val.span() { if let Some((block_id, from_span)) = env_conv.from_string {
Ok(sp) => sp, let val_span = match val.span() {
Err(e) => { Ok(sp) => sp,
error = error.or(Some(e)); Err(e) => {
continue; error = error.or(Some(e));
} continue;
};
let block = engine_state.get_block(conv.from_string.0);
if let Some(var) = block.signature.get_positional(0) {
let mut stack = stack.collect_captures(&block.captures);
if let Some(var_id) = &var.var_id {
stack.add_var(*var_id, val.clone());
}
let result =
eval_block(engine_state, &mut stack, block, PipelineData::new(span));
match result {
Ok(data) => {
let val = data.into_value(span);
new_scope.insert(name.to_string(), val);
} }
Err(e) => error = error.or(Some(e)), };
let block = engine_state.get_block(block_id);
if let Some(var) = block.signature.get_positional(0) {
let mut stack = stack.collect_captures(&block.captures);
if let Some(var_id) = &var.var_id {
stack.add_var(*var_id, val.clone());
}
let result = eval_block(
engine_state,
&mut stack,
block,
PipelineData::new(val_span),
);
match result {
Ok(data) => {
let val = data.into_value(val_span);
new_scope.insert(name.to_string(), val);
}
Err(e) => error = error.or(Some(e)),
}
} else {
error = error.or_else(|| {
Some(ShellError::MissingParameter(
"block input".into(),
from_span,
))
});
} }
} else { } else {
error = error.or_else(|| { new_scope.insert(name.to_string(), val.clone());
Some(ShellError::MissingParameter(
"block input".into(),
conv.from_string.1,
))
});
} }
} else { } else {
new_scope.insert(name.to_string(), val.clone()); new_scope.insert(name.to_string(), val.clone());
@ -84,28 +92,31 @@ pub fn env_to_string(
stack: &mut Stack, stack: &mut Stack,
config: &Config, config: &Config,
) -> Result<String, ShellError> { ) -> Result<String, ShellError> {
if let Some(conv) = config.env_conversions.get(env_name) { if let Some(env_conv) = config.env_conversions.get(env_name) {
let block = engine_state.get_block(conv.to_string.0); if let Some((block_id, to_span)) = env_conv.to_string {
let block = engine_state.get_block(block_id);
if let Some(var) = block.signature.get_positional(0) { if let Some(var) = block.signature.get_positional(0) {
let span = value.span()?; let val_span = value.span()?;
let mut stack = stack.collect_captures(&block.captures); let mut stack = stack.collect_captures(&block.captures);
if let Some(var_id) = &var.var_id { if let Some(var_id) = &var.var_id {
stack.add_var(*var_id, value); stack.add_var(*var_id, value);
}
Ok(
// This one is OK to fail: We want to know if custom conversion is working
eval_block(engine_state, &mut stack, block, PipelineData::new(val_span))?
.into_value(val_span)
.as_string()?,
)
} else {
Err(ShellError::MissingParameter("block input".into(), to_span))
} }
Ok(
// This one is OK to fail: We want to know if custom conversion is working
eval_block(engine_state, &mut stack, block, PipelineData::new(span))?
.into_value(span)
.as_string()?,
)
} else { } else {
Err(ShellError::MissingParameter( // Do not fail here. Must sicceed, otherwise setting a non-string env var would constantly
"block input".into(), // throw errors when running externals etc.
conv.to_string.1, Ok(value.into_string(ENV_SEP, config))
))
} }
} else { } else {
// Do not fail here. Must sicceed, otherwise setting a non-string env var would constantly // Do not fail here. Must sicceed, otherwise setting a non-string env var would constantly

View file

@ -6,8 +6,8 @@ const ANIMATE_PROMPT_DEFAULT: bool = false;
#[derive(Serialize, Deserialize, Clone, Debug)] #[derive(Serialize, Deserialize, Clone, Debug)]
pub struct EnvConversion { pub struct EnvConversion {
pub from_string: (BlockId, Span), pub from_string: Option<(BlockId, Span)>,
pub to_string: (BlockId, Span), pub to_string: Option<(BlockId, Span)>,
} }
impl EnvConversion { impl EnvConversion {
@ -28,20 +28,13 @@ impl EnvConversion {
} }
} }
match (conv_map.get("from_string"), conv_map.get("to_string")) { let from_string = conv_map.get("from_string").cloned();
(None, _) => Err(ShellError::MissingConfigValue( let to_string = conv_map.get("to_string").cloned();
"'from_string' field".into(),
value.span()?, Ok(EnvConversion {
)), from_string,
(_, None) => Err(ShellError::MissingConfigValue( to_string,
"'to_string' field".into(), })
value.span()?,
)),
(Some(from), Some(to)) => Ok(EnvConversion {
from_string: *from,
to_string: *to,
}),
}
} }
} }
@ -177,6 +170,7 @@ impl Value {
let mut env_conversions = HashMap::new(); let mut env_conversions = HashMap::new();
for (env_var, record) in env_vars.iter().zip(conversions) { for (env_var, record) in env_vars.iter().zip(conversions) {
// println!("{}: {:?}", env_var, record);
env_conversions.insert(env_var.into(), EnvConversion::from_record(record)?); env_conversions.insert(env_var.into(), EnvConversion::from_record(record)?);
} }

View file

@ -8,7 +8,7 @@ use dialoguer::{
use miette::{IntoDiagnostic, Result}; use miette::{IntoDiagnostic, Result};
use nu_cli::{CliError, NuCompleter, NuHighlighter, NuValidator, NushellPrompt}; use nu_cli::{CliError, NuCompleter, NuHighlighter, NuValidator, NushellPrompt};
use nu_command::create_default_context; use nu_command::create_default_context;
use nu_engine::{env_to_values, eval_block}; use nu_engine::{convert_env_values, eval_block};
use nu_parser::{lex, parse, trim_quotes, Token, TokenContents}; use nu_parser::{lex, parse, trim_quotes, Token, TokenContents};
use nu_protocol::{ use nu_protocol::{
ast::Call, ast::Call,
@ -153,7 +153,7 @@ fn main() -> Result<()> {
}; };
// Translate environment variables from Strings to Values // Translate environment variables from Strings to Values
if let Some(e) = env_to_values(&engine_state, &mut stack, &config) { if let Some(e) = convert_env_values(&engine_state, &mut stack, &config) {
let working_set = StateWorkingSet::new(&engine_state); let working_set = StateWorkingSet::new(&engine_state);
report_error(&working_set, &e); report_error(&working_set, &e);
std::process::exit(1); std::process::exit(1);
@ -289,7 +289,7 @@ fn main() -> Result<()> {
}; };
// Translate environment variables from Strings to Values // Translate environment variables from Strings to Values
if let Some(e) = env_to_values(&engine_state, &mut stack, &config) { if let Some(e) = convert_env_values(&engine_state, &mut stack, &config) {
let working_set = StateWorkingSet::new(&engine_state); let working_set = StateWorkingSet::new(&engine_state);
report_error(&working_set, &e); report_error(&working_set, &e);
} }