use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};
use serde::de::{self, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use crate::Error;
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Config {
pub project: ProjectConfig,
pub run: RunConfig,
pub custom: CustomConfig,
pub rules: BTreeMap<String, String>,
pub rule: RuleOptions,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct RuleOptions {
#[serde(rename = "GB117", alias = "gb117")]
pub gb117: Gb117Options,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct Gb117Options {
pub remotes: Vec<String>,
pub sanitizers: Vec<String>,
}
impl Default for Gb117Options {
fn default() -> Self {
Self {
remotes: ["SmeersLightsHandler", "Horn", "Smoke_FE"]
.into_iter()
.map(str::to_owned)
.collect(),
sanitizers: ["owner", "vehicletokens", "isdescendantof"]
.into_iter()
.map(str::to_owned)
.collect(),
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct CustomConfig {
pub dir: String,
pub runtime: String,
pub timeout: u64,
}
impl Default for CustomConfig {
fn default() -> Self {
Self {
dir: ".plut/rules".to_owned(),
runtime: "luneblox".to_owned(),
timeout: 60,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Model {
#[default]
Auto,
Rojo,
Plain,
}
impl Model {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Auto => "auto",
Self::Rojo => "rojo",
Self::Plain => "plain",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Target {
Roblox,
Lute,
Luneblox,
Bare,
}
impl Target {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Roblox => "roblox",
Self::Lute => "lute",
Self::Luneblox => "luneblox",
Self::Bare => "bare",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum TargetsConfig {
#[default]
Auto,
List(Vec<Target>),
}
impl<'de> Deserialize<'de> for TargetsConfig {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct TargetsVisitor;
impl<'de> Visitor<'de> for TargetsVisitor {
type Value = TargetsConfig;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("targets = \"auto\" or a list of roblox, lute, luneblox, bare")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
if value.eq_ignore_ascii_case("auto") {
Ok(TargetsConfig::Auto)
} else {
Err(E::custom(format!(
"targets must be \"auto\" or a list, got \"{value}\""
)))
}
}
fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut targets = Vec::new();
while let Some(target) = sequence.next_element::<Target>()? {
targets.push(target);
}
Ok(TargetsConfig::List(targets))
}
}
deserializer.deserialize_any(TargetsVisitor)
}
}
impl TargetsConfig {
#[must_use]
pub fn resolve(&self, model_plain: bool) -> Vec<Target> {
match self {
Self::Auto if model_plain => vec![Target::Bare],
Self::Auto => vec![Target::Roblox],
Self::List(targets) => targets.clone(),
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct ProjectConfig {
pub sourcemap: String,
pub model: Model,
pub targets: TargetsConfig,
}
impl Default for ProjectConfig {
fn default() -> Self {
Self {
sourcemap: "auto".to_owned(),
model: Model::Auto,
targets: TargetsConfig::Auto,
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct RunConfig {
pub exclude: Vec<String>,
}
impl Default for RunConfig {
fn default() -> Self {
Self {
exclude: vec![
"**/roblox_packages/**".to_owned(),
"**/roblox_server_packages/**".to_owned(),
"**/Packages/**".to_owned(),
"**/node_modules/**".to_owned(),
"**/vendor/**".to_owned(),
"**/test/**".to_owned(),
"**/tests/**".to_owned(),
"**/spec/**".to_owned(),
"**/*.spec.luau".to_owned(),
"**/*.test.luau".to_owned(),
"**/benchmark/**".to_owned(),
"**/benchmarks/**".to_owned(),
"**/example/**".to_owned(),
"**/examples/**".to_owned(),
"**/*.d.luau".to_owned(),
],
}
}
}
impl Config {
pub fn load(explicit: Option<&Path>, root: &Path) -> Result<Self, Error> {
let path: PathBuf = explicit.map_or_else(|| root.join("plut.toml"), Path::to_path_buf);
if !path.is_file() {
return Ok(Self::default());
}
let text = std::fs::read_to_string(&path).map_err(|source| Error::Read {
path: path.clone(),
source,
})?;
toml::from_str(&text).map_err(|source| Error::ParseToml { path, source })
}
}
#[cfg(test)]
mod tests {
use super::Config;
#[test]
fn model_and_targets_default_to_auto() {
let config: Config = toml::from_str("").expect("empty config");
assert_eq!(config.project.model, super::Model::Auto);
assert_eq!(config.project.targets, super::TargetsConfig::Auto);
assert_eq!(
config.project.targets.resolve(false),
vec![super::Target::Roblox]
);
assert_eq!(
config.project.targets.resolve(true),
vec![super::Target::Bare]
);
}
#[test]
fn followers_read_model_and_targets() {
let config: Config =
toml::from_str("[project]\nmodel = \"plain\"\ntargets = [\"luneblox\", \"bare\"]\n")
.expect("config");
assert_eq!(config.project.model, super::Model::Plain);
assert_eq!(
config.project.targets,
super::TargetsConfig::List(vec![super::Target::Luneblox, super::Target::Bare])
);
}
#[test]
fn custom_rules_have_defaults() {
let config: Config = toml::from_str("").expect("empty config");
assert_eq!(config.custom.dir, ".plut/rules");
assert_eq!(config.custom.runtime, "luneblox");
assert_eq!(config.custom.timeout, 60);
}
#[test]
fn gb117_has_default_remotes_and_sanitizers() {
let config: Config = toml::from_str("").expect("empty config");
assert_eq!(
config.rule.gb117.remotes,
["SmeersLightsHandler", "Horn", "Smoke_FE"]
);
assert!(config.rule.gb117.sanitizers.contains(&"owner".to_owned()));
}
#[test]
fn gb117_reads_its_section() {
let config: Config = toml::from_str(
"[rule.GB117]\n\
remotes = [\"MyChassisRemote\"]\n\
sanitizers = [\"driver\"]\n",
)
.expect("config");
assert_eq!(config.rule.gb117.remotes, ["MyChassisRemote"]);
assert_eq!(config.rule.gb117.sanitizers, ["driver"]);
}
#[test]
fn custom_rules_read_their_section() {
let config: Config =
toml::from_str("[custom]\ndir = \"rules\"\nruntime = \"luneblox\"\ntimeout = 5\n")
.expect("config");
assert_eq!(config.custom.dir, "rules");
assert_eq!(config.custom.runtime, "luneblox");
assert_eq!(config.custom.timeout, 5);
}
}