clove/code4dyslexia
src/config.rs
// src/config.rs
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt::Write as _;
use std::fs;
use std::io::{ErrorKind, Write as _};
use std::path::{Path, PathBuf};
use jpcl::{Object, ParseOptions, Value};
use tempfile::NamedTempFile;
use crate::terminal::Theme;
const THEME: &str = "terminal.color";
const DEFAULT_SOURCE: &str = include_str!("../data/default.jp");
const INDENT: &str = "formatting.indentSize";
pub const FILE_HEADER: &str = "formatting.filePathHeader";
const NEWLINE: &str = "formatting.newLineSize";
pub const FUNCTIONS: &str = "cases.functions";
pub const VARIABLES: &str = "cases.variables";
pub const CLASSES: &str = "cases.classes";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Case {
Flat,
Camel,
Pascal,
Snake,
ScreamingSnake,
Disabled,
}
impl Case {
fn parse(label: &str) -> Option<Self> {
match label {
"flatcase" => Some(Self::Flat),
"camelCase" => Some(Self::Camel),
"PascalCase" => Some(Self::Pascal),
"snake_case" => Some(Self::Snake),
"SCREAMING_SNAKE_CASE" => Some(Self::ScreamingSnake),
"disabled" => Some(Self::Disabled),
_ => None,
}
}
pub fn label(self) -> &'static str {
match self {
Self::Flat => "flatcase",
Self::Camel => "camelCase",
Self::Pascal => "PascalCase",
Self::Snake => "snake_case",
Self::ScreamingSnake => "SCREAMING_SNAKE_CASE",
Self::Disabled => "disabled",
}
}
pub fn matches(self, name: &str) -> bool {
let mut remaining = name.bytes();
let first = remaining.next().unwrap_or_default();
match self {
Self::Disabled => true,
Self::Flat => {
first.is_ascii_lowercase()
&& remaining.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
}
Self::Camel => {
first.is_ascii_lowercase() && remaining.all(|byte| byte.is_ascii_alphanumeric())
}
Self::Pascal => {
first.is_ascii_uppercase() && remaining.all(|byte| byte.is_ascii_alphanumeric())
}
Self::Snake | Self::ScreamingSnake => {
let letter = |byte: u8| {
if self == Self::Snake {
byte.is_ascii_lowercase()
} else {
byte.is_ascii_uppercase()
}
};
letter(first)
&& name.split('_').all(|word| {
!word.is_empty()
&& word
.bytes()
.all(|byte| letter(byte) || byte.is_ascii_digit())
})
}
}
}
}
#[derive(Debug, Clone, Copy)]
enum Setting {
Size(usize),
Toggle(bool),
Case(Case),
Theme(Theme),
}
type Layer = BTreeMap<&'static str, Setting>;
#[derive(Debug)]
struct Config {
base: Layer,
overrides: BTreeMap<String, Layer>,
origin: String,
}
fn object<'a>(value: &'a Value, path: &str) -> Result<&'a Object, String> {
value
.as_object()
.ok_or_else(|| format!("{path} must be an object"))
}
fn parse_section(
layer: &mut Layer,
section: &str,
value: &Value,
origin: &str,
) -> Result<(), String> {
let path = format!("{origin}.{section}");
if !matches!(section, "formatting" | "cases" | "terminal") {
return Err(format!("{path} is unknown"));
}
for (key, value) in object(value, &path)?.iter() {
let field = format!("{path}.{key}");
let full_key = match (section, key) {
("formatting", "indentSize") => INDENT,
("formatting", "filePathHeader") => FILE_HEADER,
("formatting", "newLineSize") => NEWLINE,
("terminal", "color") => THEME,
("cases", "functions") => FUNCTIONS,
("cases", "variables") => VARIABLES,
("cases", "classes") => CLASSES,
_ => return Err(format!("{field} is unknown")),
};
let setting = if full_key == THEME {
let theme = value.as_str().and_then(Theme::parse).ok_or_else(|| {
let names = Theme::names().collect::<Vec<_>>().join(", ");
format!("{field} must be one of {names}")
})?;
Setting::Theme(theme)
} else if full_key == FILE_HEADER {
let Value::Bool(enabled) = value else {
return Err(format!("{field} must be true or false"));
};
Setting::Toggle(*enabled)
} else if section == "formatting" {
let Value::Integer(value @ 0..=100) = value else {
return Err(format!("{field} must be an integer from 0 to 100"));
};
Setting::Size(*value as usize)
} else {
let convention = value.as_str().and_then(Case::parse).ok_or_else(|| {
format!("{field} must be flatcase, camelCase, PascalCase, snake_case, SCREAMING_SNAKE_CASE, or disabled")
})?;
Setting::Case(convention)
};
layer.insert(full_key, setting);
}
Ok(())
}
pub fn language_id(language: &str) -> bool {
language.starts_with(|character: char| character.is_ascii_lowercase())
&& language
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
}
fn parse_config(source: &[u8], origin: String) -> Result<Config, String> {
let parsed = jpcl::parse_bytes(source, &ParseOptions::default())
.map_err(|error| error.with_filename(origin.clone()).to_string())?;
let mut config = Config {
base: Layer::new(),
overrides: BTreeMap::new(),
origin,
};
for (section, value) in parsed.iter() {
if section != "overrides" {
parse_section(&mut config.base, section, value, &config.origin)?;
continue;
}
let path = format!("{}.overrides", config.origin);
for (language, values) in object(value, &path)?.iter() {
let label = format!("{path}.{language}");
if !language_id(language) {
return Err(format!("{label} must use a lowercase language identifier"));
}
let mut layer = Layer::new();
for (section, value) in object(values, &label)?.iter() {
parse_section(&mut layer, section, value, &label)?;
}
config.overrides.insert(language.to_owned(), layer);
}
}
Ok(config)
}
fn load(path: &Path) -> Result<Option<Config>, String> {
match fs::read(path) {
Ok(source) => parse_config(&source, path.display().to_string()).map(Some),
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
Err(error) => Err(format!("{}: {error}", path.display())),
}
}
#[derive(Default)]
pub struct Effective {
values: Layer,
origins: BTreeMap<&'static str, String>,
}
impl Effective {
fn apply(&mut self, layer: &Layer, origin: &str) {
for (&key, &setting) in layer {
self.values.insert(key, setting);
self.origins.insert(key, origin.to_owned());
}
}
pub fn indent_size(&self) -> usize {
self.size(INDENT)
}
pub fn newline_size(&self) -> usize {
self.size(NEWLINE)
}
pub fn file_path_header(&self) -> bool {
matches!(self.values[FILE_HEADER], Setting::Toggle(true))
}
fn size(&self, key: &str) -> usize {
match self.values[key] {
Setting::Size(value) => value,
_ => unreachable!("validated numeric setting"),
}
}
pub fn convention(&self, key: &str) -> Case {
match self.values[key] {
Setting::Case(value) => value,
_ => unreachable!("validated naming setting"),
}
}
pub fn theme(&self) -> Theme {
match self.values[THEME] {
Setting::Theme(theme) => theme,
_ => unreachable!("validated terminal theme"),
}
}
pub fn document(&self) -> Object {
let sections = [
(
"terminal",
Object::from_iter([("color".into(), Value::String(self.theme().name.into()))]),
),
(
"formatting",
Object::from_iter([
(
"indentSize".into(),
Value::Integer(self.indent_size() as i128),
),
(
"newLineSize".into(),
Value::Integer(self.newline_size() as i128),
),
(
"filePathHeader".into(),
Value::Bool(self.file_path_header()),
),
]),
),
(
"cases",
Object::from_iter([
(
"functions".into(),
Value::String(self.convention(FUNCTIONS).label().into()),
),
(
"variables".into(),
Value::String(self.convention(VARIABLES).label().into()),
),
(
"classes".into(),
Value::String(self.convention(CLASSES).label().into()),
),
]),
),
];
sections
.into_iter()
.map(|(key, section)| (key.into(), Value::Object(section)))
.collect()
}
pub fn write_origins(&self, output: &mut String, prefix: &str) {
for (key, origin) in &self.origins {
writeln!(output, "~~ {prefix}{key} from {}", origin.escape_debug()).unwrap();
}
}
}
pub fn initialize_global(home: &Path) -> Result<(), String> {
let directory = home.join(".c4d");
let path = directory.join("config.jp");
let initialize = || -> std::io::Result<()> {
match path.symlink_metadata() {
Ok(_) => return Ok(()),
Err(error) if error.kind() == ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
fs::create_dir_all(&directory)?;
let mut temporary = NamedTempFile::new_in(&directory)?;
temporary.write_all(DEFAULT_SOURCE.as_bytes())?;
match temporary.persist_noclobber(&path) {
Ok(_) => Ok(()),
Err(error) if error.error.kind() == ErrorKind::AlreadyExists => Ok(()),
Err(error) => Err(error.error),
}
};
initialize().map_err(|error| format!("{}: {error}", path.display()))
}
pub struct ConfigStore {
defaults: Config,
global: Option<Config>,
locations: HashMap<PathBuf, Option<PathBuf>>,
projects: HashMap<PathBuf, Option<Config>>,
effective: HashMap<(Option<PathBuf>, Option<String>), Effective>,
}
impl ConfigStore {
pub fn load(home: Option<&Path>) -> Result<Self, String> {
Ok(Self {
defaults: parse_config(DEFAULT_SOURCE.as_bytes(), "built-in defaults".into())?,
global: match home {
Some(home) => load(&home.join(".c4d/config.jp"))?,
None => None,
},
locations: HashMap::new(),
projects: HashMap::new(),
effective: HashMap::new(),
})
}
pub fn project(&mut self, directory: &Path) -> Result<Option<PathBuf>, String> {
let mut visited = Vec::new();
let mut root = None;
for candidate in directory.ancestors() {
if let Some(cached) = self.locations.get(candidate) {
root.clone_from(cached);
break;
}
visited.push(candidate.to_owned());
let config = load(&candidate.join(".c4d/config.jp"))?;
if config.is_some() || candidate.join(".git").symlink_metadata().is_ok() {
root = Some(candidate.to_owned());
self.projects.insert(candidate.to_owned(), config);
break;
}
}
for candidate in visited {
self.locations.insert(candidate, root.clone());
}
Ok(root)
}
pub fn settings(&mut self, root: Option<&Path>, language: Option<&str>) -> &Effective {
self.effective
.entry((root.map(Path::to_owned), language.map(str::to_owned)))
.or_insert_with(|| {
let mut effective = Effective::default();
let project = root
.and_then(|root| self.projects.get(root))
.and_then(Option::as_ref);
for config in [Some(&self.defaults), self.global.as_ref(), project]
.into_iter()
.flatten()
{
effective.apply(&config.base, &config.origin);
if let Some(layer) = language.and_then(|id| config.overrides.get(id)) {
effective.apply(
layer,
&format!("{} [overrides.{}]", config.origin, language.unwrap()),
);
}
}
effective
})
}
pub fn override_languages(&self, root: Option<&Path>) -> BTreeSet<String> {
let project = root
.and_then(|root| self.projects.get(root))
.and_then(Option::as_ref);
[self.global.as_ref(), project]
.into_iter()
.flatten()
.flat_map(|config| config.overrides.keys().cloned())
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn official_jpcl_parses_default_and_uncommented_example() {
let store = ConfigStore::load(None).unwrap();
assert!(store.defaults.overrides.is_empty());
let example = DEFAULT_SOURCE.replace("~*\n[overrides]", "[overrides]");
let example = example.trim_end().strip_suffix("*~").unwrap();
let config = parse_config(example.as_bytes(), "example.jp".into()).unwrap();
assert!(config.overrides.contains_key("typescript"));
}
#[test]
fn naming_cases_distinguish_valid_and_invalid_identifiers() {
for (case, valid, invalid) in [
(Case::Flat, "acoolfunction", "aCoolFunction"),
(Case::Camel, "aCoolFunction", "ACoolFunction"),
(Case::Pascal, "ACoolFunction", "aCoolFunction"),
(Case::Snake, "a_cool_function", "a__cool_function"),
(Case::ScreamingSnake, "A_COOL_FUNCTION", "a_COOL_FUNCTION"),
(Case::Disabled, "_any_Name", ""),
] {
assert!(case.matches(valid));
if case != Case::Disabled {
assert!(!case.matches(invalid));
}
}
}
}