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

feat: load local config #3207

Closed
Show file tree
Hide file tree
Changes from 6 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
16 changes: 15 additions & 1 deletion book/src/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ hidden = false
```

You may also specify a file to use for configuration with the `-c` or
`--config` CLI argument: `hx -c path/to/custom-config.toml`.
`--config` CLI argument: `hx -c path/to/custom-config.toml`.

Finally, you can have a `config.toml` local to a project by it under a `.helix` directory in your repository.
AlexanderBrevig marked this conversation as resolved.
Show resolved Hide resolved
Its settings will be merged with the configuration directory `config.toml` and the built-in configuration,
if you have enabled the feature under `[editor.security]` in your global configuration.

## Editor

Expand Down Expand Up @@ -229,3 +233,13 @@ Example:
render = true
character = "╎"
```

### `[editor.security]` Section

Opt in to features that may put you at risk.
It is possible to write malicious TOML files, so we suggest you keep the `confirm_*` options to their default value of `true`.
AlexanderBrevig marked this conversation as resolved.
Show resolved Hide resolved

| Key | Description | Default |
| --- | --- | --- |
| `load_local_config` | Load a `config.yaml` from `$PWD/.helix` that will merge with your global configuration. | `false` |
| `confirm_local_config` | Prompt the user at launch in order to accept the loading of a found local `$PWD/.helix` | `true` |
AlexanderBrevig marked this conversation as resolved.
Show resolved Hide resolved
89 changes: 89 additions & 0 deletions helix-term/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,95 @@ impl Config {
pub fn load_default() -> Result<Config, ConfigLoadError> {
Config::load(helix_loader::config_file())
}

// Load a merged config from configuration and $PWD/.helix/config.toml
pub fn load_merged_config() -> Config {
let root_config: Config = std::fs::read_to_string(helix_loader::config_file())
.ok()
.and_then(|config| toml::from_str(&config).ok())
.unwrap_or_else(|| {
eprintln!("Bad config: {:?}", helix_loader::config_file());
Config::halt_and_confirm("default");
Config::default()
});

// Load each config file
let local_config_values = helix_loader::local_config_dirs()
.into_iter()
.map(|path| path.join("config.toml"))
.chain([helix_loader::config_file()])
.filter_map(|file| Config::load_config_toml_values(&root_config, file));

// Merge configs and return, or alert user of error and load default
match local_config_values
.fold(toml::Value::Table(toml::value::Table::default()), |a, b| {
helix_loader::merge_toml_values(b, a, 3)
})
AlexanderBrevig marked this conversation as resolved.
Show resolved Hide resolved
.try_into()
{
Ok(conf) => conf,
Err(_) => root_config,
}
}

// Load a specific config file if allowed by config
// Stay with toml::Values as they can be merged
pub fn load_config_toml_values(
root_config: &Config,
config_path: std::path::PathBuf,
) -> Option<toml::Value> {
if config_path.exists() {
AlexanderBrevig marked this conversation as resolved.
Show resolved Hide resolved
let mut confirmed = true;
if config_path != helix_loader::config_file() {
if root_config.editor.security.load_local_config {
if root_config.editor.security.confirm_local_config {
eprintln!(
"Type yes<ENTER> to continue with loading config: {:#?}",
config_path
);
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap_or_default();
AlexanderBrevig marked this conversation as resolved.
Show resolved Hide resolved
confirmed = input.contains("yes");
} //else we still presume confirmed = true
} else {
// User denies local configs, do not load
confirmed = false;
}
}
if confirmed {
log::debug!("Load config: {:?}", config_path);
let bytes = std::fs::read(&config_path);
let cfg: Option<toml::Value> = match bytes {
Ok(bytes) => {
let cfg = toml::from_slice(&bytes);
match cfg {
Ok(cfg) => Some(cfg),
Err(e) => {
eprintln!("Toml parse error for {:?}: {}", &config_path, e);
Config::halt_and_confirm("loaded");
None
}
}
}
Err(e) => {
eprintln!("Could not read {:?}: {}", &config_path, e);
Config::halt_and_confirm("loaded");
None
}
};
return cfg;
} else {
return None;
}
}
None
}

fn halt_and_confirm(config_type: &'static str) {
eprintln!("Press <ENTER> to continue with {} config", config_type);
let mut tmp = String::new();
let _ = std::io::stdin().read_line(&mut tmp);
}
}

#[cfg(test)]
Expand Down
16 changes: 2 additions & 14 deletions helix-term/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::{Context, Error, Result};
use anyhow::{Context, Result};
use crossterm::event::EventStream;
use helix_term::application::Application;
use helix_term::args::Args;
Expand Down Expand Up @@ -122,19 +122,7 @@ FLAGS:

helix_loader::initialize_config_file(args.config_file.clone());

let config = match std::fs::read_to_string(helix_loader::config_file()) {
Ok(config) => toml::from_str(&config)
.map(helix_term::keymap::merge_keys)
.unwrap_or_else(|err| {
eprintln!("Bad config: {}", err);
eprintln!("Press <ENTER> to continue with default config");
use std::io::Read;
let _ = std::io::stdin().read(&mut []);
Config::default()
}),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Config::default(),
Err(err) => return Err(Error::new(err)),
};
let config = Config::load_merged_config();

// TODO: use the thread local executor to spawn the application task separately from the work pool
let mut app = Application::new(args, config).context("unable to create new application")?;
Expand Down
24 changes: 24 additions & 0 deletions helix-view/src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@ pub struct Config {
/// Search configuration.
#[serde(default)]
pub search: SearchConfig,
/// Security settings (i.e. loading TOML files from $PWD/.helix)
#[serde(default)]
pub security: SecurityConfig,
pub lsp: LspConfig,
pub terminal: Option<TerminalConfig>,
/// Column numbers at which to draw the rulers. Default to `[]`, meaning no rulers.
Expand All @@ -168,6 +171,26 @@ pub struct Config {
pub color_modes: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", default, deny_unknown_fields)]
pub struct SecurityConfig {
pub load_local_config: bool,
pub confirm_local_config: bool,
//pub load_local_languages: bool, //TODO: implement
//pub confirm_local_languages: bool, //TODO: implement
}

impl Default for SecurityConfig {
fn default() -> Self {
Self {
load_local_config: false,
confirm_local_config: true,
//load_local_languages: false,
//confirm_local_languages: true,
}
}
}

#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct TerminalConfig {
Expand Down Expand Up @@ -550,6 +573,7 @@ impl Default for Config {
cursor_shape: CursorShapeConfig::default(),
true_color: false,
search: SearchConfig::default(),
security: SecurityConfig::default(),
lsp: LspConfig::default(),
terminal: get_terminal_provider(),
rulers: Vec::new(),
Expand Down