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

Load modes from <config dir>/modes/ #68

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
62 changes: 58 additions & 4 deletions zee/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
use include_dir::{include_dir, Dir};
use once_cell::sync::Lazy;
use serde_derive::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::{
fs::File,
path::{Path, PathBuf},
};

use zee_grammar::{config::ModeConfig, Mode};

use crate::error::{Context, Result};
use crate::{
error::{Context, Result},
utils,
};

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields, rename = "Zee")]
Expand All @@ -24,10 +30,26 @@ impl Default for EditorConfig {
/// Finds the editor configuration. If we cannot for any reason, we'll use the
/// default configuration to ensure the editor opens in any environment.
pub fn find_editor_config(config_dir: Option<PathBuf>) -> EditorConfig {
config_dir
let config_dir = config_dir
.or_else(|| zee_grammar::config::config_dir().ok())
.ok_or_else(|| anyhow::Error::msg("Unable to determine configuration directory"))
.ok();

// First construct the `EditorConfig` from the configuration file
let mut editor_config = config_dir
.as_ref()
.map(|config_dir| config_dir.join("config.ron"))
.map_or_else(Default::default, |path| read_config_file(&path))
.map_or_else(Default::default, |path| read_config_file(&path));

// Second, load modes from the modes directory (if available)
if let Some(config_dir) = config_dir {
let modes_dir = config_dir.join("modes");
if let Ok(mut additional_modes) = load_modes_from_dir(&modes_dir) {
editor_config.modes.append(&mut additional_modes);
}
}

editor_config
}

fn read_config_file(path: &Path) -> EditorConfig {
Expand All @@ -47,6 +69,38 @@ fn read_config_file(path: &Path) -> EditorConfig {
}
}

fn load_modes_from_dir(dir: &PathBuf) -> Result<Vec<ModeConfig>> {
if !dir.exists() {
if let Err(e) = std::fs::create_dir(dir) {
log::warn!(
"Unable to create modes configuration directory `{}`. {}",
dir.display(),
e
);
}
}

let mut modes = vec![];
for mode_file in utils::files_with_extension(dir, "ron")? {
match File::open(&mode_file) {
Ok(handle) => match ron::de::from_reader(handle) {
Ok(mode_cfg) => modes.push(mode_cfg),
Err(e) => log::warn!(
"Unable to parse configuration file `{}`: {}",
mode_file.display(),
e
),
},
Err(e) => log::warn!(
"Unable to open configuration file `{}`: {}",
&mode_file.display(),
e
),
};
}
Ok(modes)
}

pub fn create_default_config_file(path: &Path) -> Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
Expand Down
19 changes: 19 additions & 0 deletions zee/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use ropey::Rope;
use std::path::PathBuf;

#[derive(Copy)]
pub struct StaticRefEq<T: 'static>(&'static T);
Expand Down Expand Up @@ -34,3 +35,21 @@ pub fn ensure_trailing_newline_with_content(text: &mut Rope) {
text.insert_char(text.len_chars(), '\n');
}
}
/// Given a path and extension, find all child files with the provided extension if the path is
/// a directory. If the path is a file or non-existent, an vector will be returned.
pub fn files_with_extension(base_path: &PathBuf, extension: &str) -> anyhow::Result<Vec<PathBuf>> {
if base_path.is_dir() && base_path.exists() {
Ok(std::fs::read_dir(base_path)?
.into_iter()
.filter(|r| r.is_ok())
.map(|r| r.unwrap().path())
.filter(|r| {
r.extension()
.filter(|e| e.to_str() == Some(extension))
.is_some()
})
.collect())
} else {
Ok(vec![])
}
}