Skip to content

Expanding envs in language config #13524

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions helix-loader/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ log = "0.4"
cc = { version = "1" }
threadpool = { version = "1.0" }
tempfile.workspace = true
regex = "1.11.1"

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
libloading = "0.8"
3 changes: 2 additions & 1 deletion helix-loader/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::str::from_utf8;
use crate::env_expander::get_env_expanded_toml;

/// Default built-in languages.toml.
pub fn default_lang_config() -> toml::Value {
Expand All @@ -17,7 +18,7 @@ pub fn user_lang_config() -> Result<toml::Value, toml::de::Error> {
.map(|path| path.join("languages.toml"))
.filter_map(|file| {
std::fs::read_to_string(file)
.map(|config| toml::from_str(&config))
.map(|config| get_env_expanded_toml(&config))
.ok()
})
.collect::<Result<Vec<_>, _>>()?
Expand Down
91 changes: 91 additions & 0 deletions helix-loader/src/env_expander.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use regex::Regex;
use std::env;
use std::str::FromStr;

#[derive(Debug)]
enum AllowedEnv {
Home,
User,
ConfigDir,
}

impl FromStr for AllowedEnv {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"HOME" => Ok(AllowedEnv::Home),
"USER" => Ok(AllowedEnv::User),
"CONFIG_DIR" => Ok(AllowedEnv::ConfigDir),
_ => Err(()),
}
}
}

/// Expands AllowedEnv variables in the input string.
/// Allowed patterns are in the format `${VAR_NAME}`.
pub fn expand_env_vars(input: &str) -> String {
let re = Regex::new(r"\$\{(\w+)\}").expect("Invalid regex");

re.replace_all(input, |caps: &regex::Captures| {
let var_name = &caps[1];
if let Ok(_allowed) = var_name.parse::<AllowedEnv>() {
env::var(var_name).unwrap_or_else(|_| "".to_string())
} else {
caps.get(0)
.map_or("".to_string(), |m| m.as_str().to_string())
}
})
.into_owned()
}

pub fn get_env_expanded_toml<T>(toml_str: &str) -> Result<T, toml::de::Error>
where
T: serde::de::DeserializeOwned
{
match std::env::consts::OS {
"linux" => toml::from_str(&expand_env_vars(toml_str)),
_ => toml::from_str(toml_str),
}

}

#[cfg(test)]
mod env_expander_tests {
use toml::Value;
use std::env;
use super::get_env_expanded_toml;

#[test]
fn expand_envs_and_parse_toml() {
let toml_text = r#"
title = "My App"
dir = "${HOME}/project/source"
user = "${USER}"
config = "${CONFIG_DIR}"
unknown = "${NOT_ALLOWED}"
"#;

env::set_var("HOME", "/home/example");
env::set_var("USER", "example_user");
env::set_var("CONFIG_DIR", "/etc/myapp");

let parsed: Value = get_env_expanded_toml(toml_text).unwrap();
assert_eq!(
parsed["dir"],
"/home/example/project/source".into()
);
assert_eq!(
parsed["user"],
"example_user".into()
);
assert_eq!(
parsed["config"],
"/etc/myapp".into()
);
assert_eq!(
parsed["unknown"],
"${NOT_ALLOWED}".into()
);
}
}

1 change: 1 addition & 0 deletions helix-loader/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod config;
pub mod grammar;
pub mod env_expander;

use helix_stdx::{env::current_working_dir, path};

Expand Down