plut-core 2.4.0

Project model, run context and diagnostics for Plut
Documentation
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Deserializer, Serialize};

use crate::Error;

/// Project-level configuration, read from `plut.toml` at the project root.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Config {
    pub project: ProjectConfig,
    pub run: RunConfig,
    /// Custom Luau rules and the runtime that executes them.
    pub custom: CustomConfig,
    /// Per-rule switches: `[rules] GB204 = "off"`. A rule not listed uses its default.
    pub rules: BTreeMap<String, String>,
    /// Per-rule options that are more than an on/off switch.
    pub rule: RuleOptions,
}

/// Options for the rules that need a list rather than a switch.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct RuleOptions {
    #[serde(rename = "GB117", alias = "gb117")]
    pub gb117: Gb117Options,
}

/// `[rule.GB117]`: the vehicle remotes and the checks that guard them.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct Gb117Options {
    /// Remote names that belong to a vehicle chassis.
    pub remotes: Vec<String>,
    /// Substrings that prove an ownership check in the handler body.
    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(),
        }
    }
}

/// Custom rules written in Luau, executed by a `LuneBlox` runtime.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct CustomConfig {
    /// Directory of `*.luau` rule files, relative to the project root.
    pub dir: String,
    /// The Luau runtime binary used to execute the rules.
    pub runtime: String,
    /// Seconds a custom-rule run may take before it is stopped.
    pub timeout: u64,
}

impl Default for CustomConfig {
    fn default() -> Self {
        Self {
            dir: ".plut/rules".to_owned(),
            runtime: "luneblox".to_owned(),
            timeout: 60,
        }
    }
}

/// How the project model is obtained.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Model {
    #[default]
    Auto,
    Rojo,
    Plain,
}

impl Model {
    /// The lowercase name used in configuration and output.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Rojo => "rojo",
            Self::Plain => "plain",
        }
    }
}

/// A runtime whose semantics the analyzed code uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Target {
    Roblox,
    Lute,
    Lune,
    Bare,
}

impl Target {
    /// The lowercase name used in configuration, manifests and reports.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Roblox => "roblox",
            Self::Lute => "lute",
            Self::Lune => "lune",
            Self::Bare => "bare",
        }
    }
}

/// `auto` or an explicit list of targets.
#[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>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Raw {
            Auto(String),
            List(Vec<Target>),
        }

        match Raw::deserialize(deserializer)? {
            Raw::Auto(value) if value.eq_ignore_ascii_case("auto") => Ok(Self::Auto),
            Raw::Auto(value) => Err(serde::de::Error::custom(format!(
                "targets must be \"auto\" or a list, got \"{value}\""
            ))),
            Raw::List(targets) => Ok(Self::List(targets)),
        }
    }
}

impl TargetsConfig {
    /// Resolve the automatic mode against the project model. Plain projects get `bare`
    /// (generic rules only); Rojo and place models get `roblox`.
    #[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(),
        }
    }
}

/// How the project model is obtained.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct ProjectConfig {
    /// `auto` generates a sourcemap with Rojo when one is missing (ADR-004).
    /// Any other value is treated as a path relative to the project root.
    pub sourcemap: String,
    /// `auto`, `rojo` or `plain`.
    pub model: Model,
    /// `auto` or a list of `roblox`, `lute`, `lune`, `bare`.
    pub targets: TargetsConfig,
}

impl Default for ProjectConfig {
    fn default() -> Self {
        Self {
            sourcemap: "auto".to_owned(),
            model: Model::Auto,
            targets: TargetsConfig::Auto,
        }
    }
}

/// What to analyze.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct RunConfig {
    /// Glob patterns, relative to the project root, that are never analyzed.
    pub exclude: Vec<String>,
}

impl Default for RunConfig {
    fn default() -> Self {
        Self {
            exclude: vec![
                // Third-party code installed by a package manager. A finding in a
                // dependency is not the project's to fix.
                "**/roblox_packages/**".to_owned(),
                "**/roblox_server_packages/**".to_owned(),
                "**/Packages/**".to_owned(),
                "**/node_modules/**".to_owned(),
                "**/vendor/**".to_owned(),
                // Test code is not shipped with the game. Environment tricks and test
                // vectors live here by design, and flagging them is noise on real
                // projects.
                "**/test/**".to_owned(),
                "**/tests/**".to_owned(),
                "**/spec/**".to_owned(),
                "**/*.spec.luau".to_owned(),
                "**/*.test.luau".to_owned(),
                // Benchmarks and examples are not shipped either.
                "**/benchmark/**".to_owned(),
                "**/benchmarks/**".to_owned(),
                "**/example/**".to_owned(),
                "**/examples/**".to_owned(),
                // Typedefs for the editor, not code that runs.
                "**/*.d.luau".to_owned(),
            ],
        }
    }
}

impl Config {
    /// Load configuration, falling back to defaults when no file exists.
    ///
    /// `explicit` is the `--config` path; otherwise `plut.toml` under `root` is used.
    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 = [\"lune\", \"bare\"]\n")
                .expect("config");
        assert_eq!(config.project.model, super::Model::Plain);
        assert_eq!(
            config.project.targets,
            super::TargetsConfig::List(vec![super::Target::Lune, 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 = \"lune\"\ntimeout = 5\n")
                .expect("config");
        assert_eq!(config.custom.dir, "rules");
        assert_eq!(config.custom.runtime, "lune");
        assert_eq!(config.custom.timeout, 5);
    }
}