plut-core 2.3.0

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

use serde::Deserialize;

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, 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,
}

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

/// 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 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);
    }
}