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
10mod contexts;
11
12pub use contexts::Contexts;
13
14#[derive(Debug, Clone, Default, Deserialize)]
16#[serde(default)]
17pub struct Config {
18 pub project: ProjectConfig,
19 pub run: RunConfig,
20 pub custom: CustomConfig,
22 pub rules: BTreeMap<String, String>,
24 pub rule: RuleOptions,
26 pub semantics: SemanticsConfig,
28}
29
30#[derive(Debug, Clone, Default, Deserialize)]
32#[serde(default)]
33pub struct SemanticsConfig {
34 pub luneblox: RuntimeSemantics,
35 pub lute: RuntimeSemantics,
36}
37
38#[derive(Debug, Clone, Default, Deserialize)]
41#[serde(default)]
42pub struct RuntimeSemantics {
43 pub sources: Vec<String>,
45 pub source_calls: Vec<String>,
47 pub command_sinks: Vec<String>,
49 pub path_sinks: Vec<String>,
51 pub url_sinks: Vec<String>,
53 pub log_sinks: Vec<String>,
55 pub sanitizers: Vec<String>,
57}
58
59#[derive(Debug, Clone, Default, Deserialize)]
61#[serde(default)]
62pub struct RuleOptions {
63 #[serde(rename = "GB117", alias = "gb117")]
64 pub gb117: Gb117Options,
65}
66
67#[derive(Debug, Clone, Deserialize)]
69#[serde(default)]
70pub struct Gb117Options {
71 pub remotes: Vec<String>,
73 pub sanitizers: Vec<String>,
75}
76
77impl Default for Gb117Options {
78 fn default() -> Self {
79 Self {
80 remotes: ["SmeersLightsHandler", "Horn", "Smoke_FE"]
81 .into_iter()
82 .map(str::to_owned)
83 .collect(),
84 sanitizers: ["owner", "vehicletokens", "isdescendantof"]
85 .into_iter()
86 .map(str::to_owned)
87 .collect(),
88 }
89 }
90}
91
92#[derive(Debug, Clone, Deserialize)]
94#[serde(default)]
95pub struct CustomConfig {
96 pub dir: String,
98 pub runtime: String,
100 pub timeout: u64,
102}
103
104impl Default for CustomConfig {
105 fn default() -> Self {
106 Self {
107 dir: ".plut/rules".to_owned(),
108 runtime: "luneblox".to_owned(),
109 timeout: 60,
110 }
111 }
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
116#[serde(rename_all = "lowercase")]
117pub enum Model {
118 #[default]
119 Auto,
120 Rojo,
121 Plain,
122}
123
124impl Model {
125 #[must_use]
127 pub const fn as_str(self) -> &'static str {
128 match self {
129 Self::Auto => "auto",
130 Self::Rojo => "rojo",
131 Self::Plain => "plain",
132 }
133 }
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
138#[serde(rename_all = "lowercase")]
139pub enum Target {
140 Roblox,
141 Lute,
142 Luneblox,
143 Bare,
144}
145
146impl Target {
147 #[must_use]
149 pub const fn as_str(self) -> &'static str {
150 match self {
151 Self::Roblox => "roblox",
152 Self::Lute => "lute",
153 Self::Luneblox => "luneblox",
154 Self::Bare => "bare",
155 }
156 }
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct TargetMask(u8);
162
163impl TargetMask {
164 pub const ROBLOX: Self = Self(0b0001);
165 pub const LUTE: Self = Self(0b0010);
166 pub const LUNEBLOX: Self = Self(0b0100);
167 pub const BARE: Self = Self(0b1000);
168 pub const ANY: Self = Self(0b1111);
169
170 #[must_use]
172 pub fn from_targets(targets: &[Target]) -> Self {
173 targets.iter().fold(Self(0), |mask, target| {
174 mask.union(match target {
175 Target::Roblox => Self::ROBLOX,
176 Target::Lute => Self::LUTE,
177 Target::Luneblox => Self::LUNEBLOX,
178 Target::Bare => Self::BARE,
179 })
180 })
181 }
182
183 #[must_use]
185 pub fn targets(self) -> Vec<Target> {
186 [
187 (Self::ROBLOX, Target::Roblox),
188 (Self::LUTE, Target::Lute),
189 (Self::LUNEBLOX, Target::Luneblox),
190 (Self::BARE, Target::Bare),
191 ]
192 .into_iter()
193 .filter_map(|(bit, target)| self.intersects(bit).then_some(target))
194 .collect()
195 }
196
197 #[must_use]
199 pub const fn union(self, other: Self) -> Self {
200 Self(self.0 | other.0)
201 }
202
203 #[must_use]
205 pub const fn intersects(self, other: Self) -> bool {
206 self.0 & other.0 != 0
207 }
208
209 #[must_use]
211 pub const fn is_empty(self) -> bool {
212 self.0 == 0
213 }
214
215 #[must_use]
217 pub const fn label(self) -> &'static str {
218 match self.0 {
219 0b1111 => "any",
220 0b0001 => "roblox",
221 0b0010 => "lute",
222 0b0100 => "luneblox",
223 0b1000 => "bare",
224 _ => "mixed",
225 }
226 }
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Default)]
231pub enum TargetsConfig {
232 #[default]
233 Auto,
234 List(Vec<Target>),
235}
236
237impl<'de> Deserialize<'de> for TargetsConfig {
238 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
239 where
240 D: Deserializer<'de>,
241 {
242 struct TargetsVisitor;
243
244 impl<'de> Visitor<'de> for TargetsVisitor {
245 type Value = TargetsConfig;
246
247 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
248 formatter.write_str("targets = \"auto\" or a list of roblox, lute, luneblox, bare")
249 }
250
251 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
252 where
253 E: de::Error,
254 {
255 if value.eq_ignore_ascii_case("auto") {
256 Ok(TargetsConfig::Auto)
257 } else {
258 Err(E::custom(format!(
259 "targets must be \"auto\" or a list, got \"{value}\""
260 )))
261 }
262 }
263
264 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
265 where
266 A: SeqAccess<'de>,
267 {
268 let mut targets = Vec::new();
269 while let Some(target) = sequence.next_element::<Target>()? {
270 targets.push(target);
271 }
272 Ok(TargetsConfig::List(targets))
273 }
274 }
275
276 deserializer.deserialize_any(TargetsVisitor)
277 }
278}
279
280impl TargetsConfig {
281 #[must_use]
284 pub fn resolve(&self, model_plain: bool) -> Vec<Target> {
285 match self {
286 Self::Auto if model_plain => vec![Target::Bare],
287 Self::Auto => vec![Target::Roblox],
288 Self::List(targets) => targets.clone(),
289 }
290 }
291}
292
293#[derive(Debug, Clone, Deserialize)]
295#[serde(default)]
296pub struct ProjectConfig {
297 pub sourcemap: String,
300 pub model: Model,
302 pub targets: TargetsConfig,
304 pub contexts: Contexts,
306}
307
308impl Default for ProjectConfig {
309 fn default() -> Self {
310 Self {
311 sourcemap: "auto".to_owned(),
312 model: Model::Auto,
313 targets: TargetsConfig::Auto,
314 contexts: Contexts::Suffixes,
315 }
316 }
317}
318
319#[derive(Debug, Clone, Deserialize)]
321#[serde(default)]
322pub struct RunConfig {
323 pub exclude: Vec<String>,
325}
326
327impl Default for RunConfig {
328 fn default() -> Self {
329 Self {
330 exclude: vec![
331 "**/roblox_packages/**".to_owned(),
334 "**/roblox_server_packages/**".to_owned(),
335 "**/Packages/**".to_owned(),
336 "**/node_modules/**".to_owned(),
337 "**/vendor/**".to_owned(),
338 "**/test/**".to_owned(),
342 "**/tests/**".to_owned(),
343 "**/spec/**".to_owned(),
344 "**/*.spec.luau".to_owned(),
345 "**/*.test.luau".to_owned(),
346 "**/benchmark/**".to_owned(),
348 "**/benchmarks/**".to_owned(),
349 "**/example/**".to_owned(),
350 "**/examples/**".to_owned(),
351 "**/*.d.luau".to_owned(),
353 ],
354 }
355 }
356}
357
358impl Config {
359 pub fn load(explicit: Option<&Path>, root: &Path) -> Result<Self, Error> {
363 let path: PathBuf = explicit.map_or_else(|| root.join("plut.toml"), Path::to_path_buf);
364
365 if !path.is_file() {
366 return Ok(Self::default());
367 }
368
369 let text = std::fs::read_to_string(&path).map_err(|source| Error::Read {
370 path: path.clone(),
371 source,
372 })?;
373
374 toml::from_str(&text).map_err(|source| Error::ParseToml { path, source })
375 }
376}
377
378#[cfg(test)]
379mod tests {
380 use super::Config;
381
382 #[test]
383 fn model_and_targets_default_to_auto() {
384 let config: Config = toml::from_str("").expect("empty config");
385 assert_eq!(config.project.model, super::Model::Auto);
386 assert_eq!(config.project.targets, super::TargetsConfig::Auto);
387 assert_eq!(
388 config.project.targets.resolve(false),
389 vec![super::Target::Roblox]
390 );
391 assert_eq!(
392 config.project.targets.resolve(true),
393 vec![super::Target::Bare]
394 );
395 }
396
397 #[test]
398 fn contexts_default_to_suffixes_and_accept_paths() {
399 let config: Config = toml::from_str("").expect("empty config");
400 assert_eq!(config.project.contexts, super::Contexts::Suffixes);
401
402 let config: Config =
403 toml::from_str("[project]\ncontexts = \"paths\"\n").expect("contexts config");
404 assert_eq!(config.project.contexts, super::Contexts::Paths);
405 }
406
407 #[test]
408 fn followers_read_model_and_targets() {
409 let config: Config =
410 toml::from_str("[project]\nmodel = \"plain\"\ntargets = [\"luneblox\", \"bare\"]\n")
411 .expect("config");
412 assert_eq!(config.project.model, super::Model::Plain);
413 assert_eq!(
414 config.project.targets,
415 super::TargetsConfig::List(vec![super::Target::Luneblox, super::Target::Bare])
416 );
417 }
418
419 #[test]
420 fn semantics_overrides_are_read() {
421 let config: Config = toml::from_str(
422 "[semantics.lute]\n\
423 sources = [\"request.query\"]\n\
424 path_sinks = [\"myfs.read\"]\n\
425 sanitizers = [\"safePath\"]\n",
426 )
427 .expect("config");
428 assert_eq!(
429 config.semantics.lute.sources,
430 vec!["request.query".to_owned()]
431 );
432 assert_eq!(
433 config.semantics.lute.path_sinks,
434 vec!["myfs.read".to_owned()]
435 );
436 assert_eq!(
437 config.semantics.lute.sanitizers,
438 vec!["safePath".to_owned()]
439 );
440 assert_eq!(config.semantics.luneblox.sources, Vec::<String>::new());
441 }
442
443 #[test]
444 fn custom_rules_have_defaults() {
445 let config: Config = toml::from_str("").expect("empty config");
446 assert_eq!(config.custom.dir, ".plut/rules");
447 assert_eq!(config.custom.runtime, "luneblox");
448 assert_eq!(config.custom.timeout, 60);
449 }
450
451 #[test]
452 fn gb117_has_default_remotes_and_sanitizers() {
453 let config: Config = toml::from_str("").expect("empty config");
454 assert_eq!(
455 config.rule.gb117.remotes,
456 ["SmeersLightsHandler", "Horn", "Smoke_FE"]
457 );
458 assert!(config.rule.gb117.sanitizers.contains(&"owner".to_owned()));
459 }
460
461 #[test]
462 fn gb117_reads_its_section() {
463 let config: Config = toml::from_str(
464 "[rule.GB117]\n\
465 remotes = [\"MyChassisRemote\"]\n\
466 sanitizers = [\"driver\"]\n",
467 )
468 .expect("config");
469 assert_eq!(config.rule.gb117.remotes, ["MyChassisRemote"]);
470 assert_eq!(config.rule.gb117.sanitizers, ["driver"]);
471 }
472
473 #[test]
474 fn custom_rules_read_their_section() {
475 let config: Config =
476 toml::from_str("[custom]\ndir = \"rules\"\nruntime = \"luneblox\"\ntimeout = 5\n")
477 .expect("config");
478 assert_eq!(config.custom.dir, "rules");
479 assert_eq!(config.custom.runtime, "luneblox");
480 assert_eq!(config.custom.timeout, 5);
481 }
482}