Skip to main content

plut_core/
config.rs

1use std::collections::BTreeMap;
2use std::fmt;
3use std::path::{Path, PathBuf};
4
5use serde::de::{self, SeqAccess, Visitor};
6use serde::{Deserialize, Deserializer, Serialize};
7
8use crate::Error;
9
10/// Project-level configuration, read from `plut.toml` at the project root.
11#[derive(Debug, Clone, Default, Deserialize)]
12#[serde(default)]
13pub struct Config {
14    pub project: ProjectConfig,
15    pub run: RunConfig,
16    /// Custom Luau rules and the runtime that executes them.
17    pub custom: CustomConfig,
18    /// Per-rule switches: `[rules] GB204 = "off"`. A rule not listed uses its default.
19    pub rules: BTreeMap<String, String>,
20    /// Per-rule options that are more than an on/off switch.
21    pub rule: RuleOptions,
22}
23
24/// Options for the rules that need a list rather than a switch.
25#[derive(Debug, Clone, Default, Deserialize)]
26#[serde(default)]
27pub struct RuleOptions {
28    #[serde(rename = "GB117", alias = "gb117")]
29    pub gb117: Gb117Options,
30}
31
32/// `[rule.GB117]`: the vehicle remotes and the checks that guard them.
33#[derive(Debug, Clone, Deserialize)]
34#[serde(default)]
35pub struct Gb117Options {
36    /// Remote names that belong to a vehicle chassis.
37    pub remotes: Vec<String>,
38    /// Substrings that prove an ownership check in the handler body.
39    pub sanitizers: Vec<String>,
40}
41
42impl Default for Gb117Options {
43    fn default() -> Self {
44        Self {
45            remotes: ["SmeersLightsHandler", "Horn", "Smoke_FE"]
46                .into_iter()
47                .map(str::to_owned)
48                .collect(),
49            sanitizers: ["owner", "vehicletokens", "isdescendantof"]
50                .into_iter()
51                .map(str::to_owned)
52                .collect(),
53        }
54    }
55}
56
57/// Custom rules written in Luau, executed by a `LuneBlox` runtime.
58#[derive(Debug, Clone, Deserialize)]
59#[serde(default)]
60pub struct CustomConfig {
61    /// Directory of `*.luau` rule files, relative to the project root.
62    pub dir: String,
63    /// The Luau runtime binary used to execute the rules.
64    pub runtime: String,
65    /// Seconds a custom-rule run may take before it is stopped.
66    pub timeout: u64,
67}
68
69impl Default for CustomConfig {
70    fn default() -> Self {
71        Self {
72            dir: ".plut/rules".to_owned(),
73            runtime: "luneblox".to_owned(),
74            timeout: 60,
75        }
76    }
77}
78
79/// How the project model is obtained.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
81#[serde(rename_all = "lowercase")]
82pub enum Model {
83    #[default]
84    Auto,
85    Rojo,
86    Plain,
87}
88
89impl Model {
90    /// The lowercase name used in configuration and output.
91    #[must_use]
92    pub const fn as_str(self) -> &'static str {
93        match self {
94            Self::Auto => "auto",
95            Self::Rojo => "rojo",
96            Self::Plain => "plain",
97        }
98    }
99}
100
101/// A runtime whose semantics the analyzed code uses.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
103#[serde(rename_all = "lowercase")]
104pub enum Target {
105    Roblox,
106    Lute,
107    Luneblox,
108    Bare,
109}
110
111impl Target {
112    /// The lowercase name used in configuration, manifests and reports.
113    #[must_use]
114    pub const fn as_str(self) -> &'static str {
115        match self {
116            Self::Roblox => "roblox",
117            Self::Lute => "lute",
118            Self::Luneblox => "luneblox",
119            Self::Bare => "bare",
120        }
121    }
122}
123
124/// `auto` or an explicit list of targets.
125#[derive(Debug, Clone, PartialEq, Eq, Default)]
126pub enum TargetsConfig {
127    #[default]
128    Auto,
129    List(Vec<Target>),
130}
131
132impl<'de> Deserialize<'de> for TargetsConfig {
133    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
134    where
135        D: Deserializer<'de>,
136    {
137        struct TargetsVisitor;
138
139        impl<'de> Visitor<'de> for TargetsVisitor {
140            type Value = TargetsConfig;
141
142            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
143                formatter.write_str("targets = \"auto\" or a list of roblox, lute, luneblox, bare")
144            }
145
146            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
147            where
148                E: de::Error,
149            {
150                if value.eq_ignore_ascii_case("auto") {
151                    Ok(TargetsConfig::Auto)
152                } else {
153                    Err(E::custom(format!(
154                        "targets must be \"auto\" or a list, got \"{value}\""
155                    )))
156                }
157            }
158
159            fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
160            where
161                A: SeqAccess<'de>,
162            {
163                let mut targets = Vec::new();
164                while let Some(target) = sequence.next_element::<Target>()? {
165                    targets.push(target);
166                }
167                Ok(TargetsConfig::List(targets))
168            }
169        }
170
171        deserializer.deserialize_any(TargetsVisitor)
172    }
173}
174
175impl TargetsConfig {
176    /// Resolve the automatic mode against the project model. Plain projects get `bare`
177    /// (generic rules only); Rojo and place models get `roblox`.
178    #[must_use]
179    pub fn resolve(&self, model_plain: bool) -> Vec<Target> {
180        match self {
181            Self::Auto if model_plain => vec![Target::Bare],
182            Self::Auto => vec![Target::Roblox],
183            Self::List(targets) => targets.clone(),
184        }
185    }
186}
187
188/// How the project model is obtained.
189#[derive(Debug, Clone, Deserialize)]
190#[serde(default)]
191pub struct ProjectConfig {
192    /// `auto` generates a sourcemap with Rojo when one is missing (ADR-004).
193    /// Any other value is treated as a path relative to the project root.
194    pub sourcemap: String,
195    /// `auto`, `rojo` or `plain`.
196    pub model: Model,
197    /// `auto` or a list of `roblox`, `lute`, `luneblox`, `bare`.
198    pub targets: TargetsConfig,
199}
200
201impl Default for ProjectConfig {
202    fn default() -> Self {
203        Self {
204            sourcemap: "auto".to_owned(),
205            model: Model::Auto,
206            targets: TargetsConfig::Auto,
207        }
208    }
209}
210
211/// What to analyze.
212#[derive(Debug, Clone, Deserialize)]
213#[serde(default)]
214pub struct RunConfig {
215    /// Glob patterns, relative to the project root, that are never analyzed.
216    pub exclude: Vec<String>,
217}
218
219impl Default for RunConfig {
220    fn default() -> Self {
221        Self {
222            exclude: vec![
223                // Third-party code installed by a package manager. A finding in a
224                // dependency is not the project's to fix.
225                "**/roblox_packages/**".to_owned(),
226                "**/roblox_server_packages/**".to_owned(),
227                "**/Packages/**".to_owned(),
228                "**/node_modules/**".to_owned(),
229                "**/vendor/**".to_owned(),
230                // Test code is not shipped with the game. Environment tricks and test
231                // vectors live here by design, and flagging them is noise on real
232                // projects.
233                "**/test/**".to_owned(),
234                "**/tests/**".to_owned(),
235                "**/spec/**".to_owned(),
236                "**/*.spec.luau".to_owned(),
237                "**/*.test.luau".to_owned(),
238                // Benchmarks and examples are not shipped either.
239                "**/benchmark/**".to_owned(),
240                "**/benchmarks/**".to_owned(),
241                "**/example/**".to_owned(),
242                "**/examples/**".to_owned(),
243                // Typedefs for the editor, not code that runs.
244                "**/*.d.luau".to_owned(),
245            ],
246        }
247    }
248}
249
250impl Config {
251    /// Load configuration, falling back to defaults when no file exists.
252    ///
253    /// `explicit` is the `--config` path; otherwise `plut.toml` under `root` is used.
254    pub fn load(explicit: Option<&Path>, root: &Path) -> Result<Self, Error> {
255        let path: PathBuf = explicit.map_or_else(|| root.join("plut.toml"), Path::to_path_buf);
256
257        if !path.is_file() {
258            return Ok(Self::default());
259        }
260
261        let text = std::fs::read_to_string(&path).map_err(|source| Error::Read {
262            path: path.clone(),
263            source,
264        })?;
265
266        toml::from_str(&text).map_err(|source| Error::ParseToml { path, source })
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::Config;
273
274    #[test]
275    fn model_and_targets_default_to_auto() {
276        let config: Config = toml::from_str("").expect("empty config");
277        assert_eq!(config.project.model, super::Model::Auto);
278        assert_eq!(config.project.targets, super::TargetsConfig::Auto);
279        assert_eq!(
280            config.project.targets.resolve(false),
281            vec![super::Target::Roblox]
282        );
283        assert_eq!(
284            config.project.targets.resolve(true),
285            vec![super::Target::Bare]
286        );
287    }
288
289    #[test]
290    fn followers_read_model_and_targets() {
291        let config: Config =
292            toml::from_str("[project]\nmodel = \"plain\"\ntargets = [\"luneblox\", \"bare\"]\n")
293                .expect("config");
294        assert_eq!(config.project.model, super::Model::Plain);
295        assert_eq!(
296            config.project.targets,
297            super::TargetsConfig::List(vec![super::Target::Luneblox, super::Target::Bare])
298        );
299    }
300
301    #[test]
302    fn custom_rules_have_defaults() {
303        let config: Config = toml::from_str("").expect("empty config");
304        assert_eq!(config.custom.dir, ".plut/rules");
305        assert_eq!(config.custom.runtime, "luneblox");
306        assert_eq!(config.custom.timeout, 60);
307    }
308
309    #[test]
310    fn gb117_has_default_remotes_and_sanitizers() {
311        let config: Config = toml::from_str("").expect("empty config");
312        assert_eq!(
313            config.rule.gb117.remotes,
314            ["SmeersLightsHandler", "Horn", "Smoke_FE"]
315        );
316        assert!(config.rule.gb117.sanitizers.contains(&"owner".to_owned()));
317    }
318
319    #[test]
320    fn gb117_reads_its_section() {
321        let config: Config = toml::from_str(
322            "[rule.GB117]\n\
323             remotes = [\"MyChassisRemote\"]\n\
324             sanitizers = [\"driver\"]\n",
325        )
326        .expect("config");
327        assert_eq!(config.rule.gb117.remotes, ["MyChassisRemote"]);
328        assert_eq!(config.rule.gb117.sanitizers, ["driver"]);
329    }
330
331    #[test]
332    fn custom_rules_read_their_section() {
333        let config: Config =
334            toml::from_str("[custom]\ndir = \"rules\"\nruntime = \"luneblox\"\ntimeout = 5\n")
335                .expect("config");
336        assert_eq!(config.custom.dir, "rules");
337        assert_eq!(config.custom.runtime, "luneblox");
338        assert_eq!(config.custom.timeout, 5);
339    }
340}