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 14 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
14 changes: 13 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,11 @@ Example:
render = true
character = "╎"
```

### `[editor.security]` Section

Opt in to features that may put you at risk.

| Key | Description | Default |
| --- | --- | --- |
| `load-local-config` | Load `config.yaml` from `$PWD/.helix` that will merge with your global configuration. | `false` |
AlexanderBrevig marked this conversation as resolved.
Show resolved Hide resolved
66 changes: 66 additions & 0 deletions helix-term/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,72 @@ 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.reduce(|a, b| helix_loader::merge_toml_values(b, a, 3)) {
Some(conf) => conf.try_into().unwrap_or_default(),
None => 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()
|| (config_path != helix_loader::config_file()
&& !root_config.editor.security.load_local_config)
{
return None;
}
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
}
};
cfg
}

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
11 changes: 11 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,13 @@ pub struct Config {
pub color_modes: bool,
}

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

#[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 +560,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