Skip to main content

plut_core/
config.rs

1use std::collections::BTreeMap;
2use std::path::{Path, PathBuf};
3
4use serde::Deserialize;
5
6use crate::Error;
7
8/// Project-level configuration, read from `plut.toml` at the project root.
9#[derive(Debug, Clone, Default, Deserialize)]
10#[serde(default)]
11pub struct Config {
12    pub project: ProjectConfig,
13    pub run: RunConfig,
14    /// Custom Luau rules and the runtime that executes them.
15    pub custom: CustomConfig,
16    /// Per-rule switches: `[rules] GB204 = "off"`. A rule not listed uses its default.
17    pub rules: BTreeMap<String, String>,
18    /// Per-rule options that are more than an on/off switch.
19    pub rule: RuleOptions,
20}
21
22/// Options for the rules that need a list rather than a switch.
23#[derive(Debug, Clone, Default, Deserialize)]
24#[serde(default)]
25pub struct RuleOptions {
26    #[serde(rename = "GB117", alias = "gb117")]
27    pub gb117: Gb117Options,
28}
29
30/// `[rule.GB117]`: the vehicle remotes and the checks that guard them.
31#[derive(Debug, Clone, Deserialize)]
32#[serde(default)]
33pub struct Gb117Options {
34    /// Remote names that belong to a vehicle chassis.
35    pub remotes: Vec<String>,
36    /// Substrings that prove an ownership check in the handler body.
37    pub sanitizers: Vec<String>,
38}
39
40impl Default for Gb117Options {
41    fn default() -> Self {
42        Self {
43            remotes: ["SmeersLightsHandler", "Horn", "Smoke_FE"]
44                .into_iter()
45                .map(str::to_owned)
46                .collect(),
47            sanitizers: ["owner", "vehicletokens", "isdescendantof"]
48                .into_iter()
49                .map(str::to_owned)
50                .collect(),
51        }
52    }
53}
54
55/// Custom rules written in Luau, executed by a `LuneBlox` runtime.
56#[derive(Debug, Clone, Deserialize)]
57#[serde(default)]
58pub struct CustomConfig {
59    /// Directory of `*.luau` rule files, relative to the project root.
60    pub dir: String,
61    /// The Luau runtime binary used to execute the rules.
62    pub runtime: String,
63    /// Seconds a custom-rule run may take before it is stopped.
64    pub timeout: u64,
65}
66
67impl Default for CustomConfig {
68    fn default() -> Self {
69        Self {
70            dir: ".plut/rules".to_owned(),
71            runtime: "luneblox".to_owned(),
72            timeout: 60,
73        }
74    }
75}
76
77/// How the project model is obtained.
78#[derive(Debug, Clone, Deserialize)]
79#[serde(default)]
80pub struct ProjectConfig {
81    /// `auto` generates a sourcemap with Rojo when one is missing (ADR-004).
82    /// Any other value is treated as a path relative to the project root.
83    pub sourcemap: String,
84}
85
86impl Default for ProjectConfig {
87    fn default() -> Self {
88        Self {
89            sourcemap: "auto".to_owned(),
90        }
91    }
92}
93
94/// What to analyze.
95#[derive(Debug, Clone, Deserialize)]
96#[serde(default)]
97pub struct RunConfig {
98    /// Glob patterns, relative to the project root, that are never analyzed.
99    pub exclude: Vec<String>,
100}
101
102impl Default for RunConfig {
103    fn default() -> Self {
104        Self {
105            exclude: vec![
106                // Third-party code installed by a package manager. A finding in a
107                // dependency is not the project's to fix.
108                "**/roblox_packages/**".to_owned(),
109                "**/roblox_server_packages/**".to_owned(),
110                "**/Packages/**".to_owned(),
111                "**/node_modules/**".to_owned(),
112                "**/vendor/**".to_owned(),
113                // Test code is not shipped with the game. Environment tricks and test
114                // vectors live here by design, and flagging them is noise on real
115                // projects.
116                "**/test/**".to_owned(),
117                "**/tests/**".to_owned(),
118                "**/spec/**".to_owned(),
119                "**/*.spec.luau".to_owned(),
120                "**/*.test.luau".to_owned(),
121                // Benchmarks and examples are not shipped either.
122                "**/benchmark/**".to_owned(),
123                "**/benchmarks/**".to_owned(),
124                "**/example/**".to_owned(),
125                "**/examples/**".to_owned(),
126                // Typedefs for the editor, not code that runs.
127                "**/*.d.luau".to_owned(),
128            ],
129        }
130    }
131}
132
133impl Config {
134    /// Load configuration, falling back to defaults when no file exists.
135    ///
136    /// `explicit` is the `--config` path; otherwise `plut.toml` under `root` is used.
137    pub fn load(explicit: Option<&Path>, root: &Path) -> Result<Self, Error> {
138        let path: PathBuf = explicit.map_or_else(|| root.join("plut.toml"), Path::to_path_buf);
139
140        if !path.is_file() {
141            return Ok(Self::default());
142        }
143
144        let text = std::fs::read_to_string(&path).map_err(|source| Error::Read {
145            path: path.clone(),
146            source,
147        })?;
148
149        toml::from_str(&text).map_err(|source| Error::ParseToml { path, source })
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::Config;
156
157    #[test]
158    fn custom_rules_have_defaults() {
159        let config: Config = toml::from_str("").expect("empty config");
160        assert_eq!(config.custom.dir, ".plut/rules");
161        assert_eq!(config.custom.runtime, "luneblox");
162        assert_eq!(config.custom.timeout, 60);
163    }
164
165    #[test]
166    fn gb117_has_default_remotes_and_sanitizers() {
167        let config: Config = toml::from_str("").expect("empty config");
168        assert_eq!(
169            config.rule.gb117.remotes,
170            ["SmeersLightsHandler", "Horn", "Smoke_FE"]
171        );
172        assert!(config.rule.gb117.sanitizers.contains(&"owner".to_owned()));
173    }
174
175    #[test]
176    fn gb117_reads_its_section() {
177        let config: Config = toml::from_str(
178            "[rule.GB117]\n\
179             remotes = [\"MyChassisRemote\"]\n\
180             sanitizers = [\"driver\"]\n",
181        )
182        .expect("config");
183        assert_eq!(config.rule.gb117.remotes, ["MyChassisRemote"]);
184        assert_eq!(config.rule.gb117.sanitizers, ["driver"]);
185    }
186
187    #[test]
188    fn custom_rules_read_their_section() {
189        let config: Config =
190            toml::from_str("[custom]\ndir = \"rules\"\nruntime = \"lune\"\ntimeout = 5\n")
191                .expect("config");
192        assert_eq!(config.custom.dir, "rules");
193        assert_eq!(config.custom.runtime, "lune");
194        assert_eq!(config.custom.timeout, 5);
195    }
196}