Skip to main content

plut_core/
run_context.rs

1use std::path::Path;
2
3use serde::{Deserialize, Serialize};
4
5/// Where a script runs. This is the single most important fact about a file: a rule that
6/// fires in the wrong context is noise, and noise is how a security tool dies.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
8#[serde(rename_all = "lowercase")]
9pub enum RunContext {
10    Server,
11    Client,
12    Shared,
13    Unknown,
14}
15
16impl RunContext {
17    /// The lowercase name used in output and JSON.
18    #[must_use]
19    pub const fn as_str(self) -> &'static str {
20        match self {
21            Self::Server => "server",
22            Self::Client => "client",
23            Self::Shared => "shared",
24            Self::Unknown => "unknown",
25        }
26    }
27
28    /// Resolve from the Roblox service a file lands in.
29    #[must_use]
30    pub fn from_service(name: &str) -> Option<Self> {
31        match name {
32            "ServerScriptService" | "ServerStorage" | "Workspace" => Some(Self::Server),
33            "StarterPlayer"
34            | "StarterCharacterScripts"
35            | "StarterPlayerScripts"
36            | "StarterGui"
37            | "StarterPack" => Some(Self::Client),
38            "ReplicatedStorage" | "ReplicatedFirst" => Some(Self::Shared),
39            _ => None,
40        }
41    }
42
43    /// Resolve from a Rojo filename suffix: `Foo.server.luau`, `Bar.client.luau`.
44    #[must_use]
45    pub fn from_file_name(name: &str) -> Option<Self> {
46        let stem = name
47            .strip_suffix(".luau")
48            .or_else(|| name.strip_suffix(".lua"))?;
49        if stem.ends_with(".server") {
50            Some(Self::Server)
51        } else if stem.ends_with(".client") {
52            Some(Self::Client)
53        } else {
54            None
55        }
56    }
57
58    /// Resolve a file. The filename suffix wins over the service because
59    /// `ReplicatedStorage/Foo.client.luau` is a client script in a shared container.
60    #[must_use]
61    pub fn resolve(relative: &Path, instance_path: &str) -> Self {
62        let file_name = relative
63            .file_name()
64            .and_then(|name| name.to_str())
65            .unwrap_or_default();
66
67        if let Some(context) = Self::from_file_name(file_name) {
68            return context;
69        }
70
71        if let Some(service) = instance_path.split('/').next()
72            && let Some(context) = Self::from_service(service)
73        {
74            return context;
75        }
76
77        // A repository without a sourcemap still says where a file runs through its
78        // directories: `ServerScriptService/Foo.lua`, `src/server/Foo.luau`,
79        // `src/client/Foo.luau`. A service name wins over a generic folder.
80        if let Some(context) = Self::from_path(relative) {
81            return context;
82        }
83
84        Self::Unknown
85    }
86
87    fn from_path(path: &Path) -> Option<Self> {
88        let mut components: Vec<&str> = path
89            .components()
90            .filter_map(|component| component.as_os_str().to_str())
91            .collect();
92
93        for component in components.iter().rev() {
94            if let Some(context) = Self::from_service(component) {
95                return Some(context);
96            }
97        }
98
99        for component in components.drain(..).rev() {
100            match component.to_ascii_lowercase().as_str() {
101                "server" | "serverscript" | "serverscripts" | "serverside" => {
102                    return Some(Self::Server);
103                }
104                "client" | "clientscript" | "clientscripts" | "clientside" => {
105                    return Some(Self::Client);
106                }
107                "shared" | "common" => return Some(Self::Shared),
108                _ => {}
109            }
110        }
111
112        None
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use std::path::Path;
119
120    use super::RunContext;
121
122    #[test]
123    fn suffix_wins_over_service() {
124        let context = RunContext::resolve(
125            Path::new("src/ReplicatedStorage/Foo.client.luau"),
126            "ReplicatedStorage/Foo",
127        );
128        assert_eq!(context, RunContext::Client);
129    }
130
131    #[test]
132    fn service_decides_when_there_is_no_suffix() {
133        let context = RunContext::resolve(
134            Path::new("src/server/Admin.luau"),
135            "ServerScriptService/Admin",
136        );
137        assert_eq!(context, RunContext::Server);
138    }
139
140    #[test]
141    fn shared_container_is_not_a_guess() {
142        let context = RunContext::resolve(
143            Path::new("src/shared/Config.luau"),
144            "ReplicatedStorage/Config",
145        );
146        assert_eq!(context, RunContext::Shared);
147    }
148
149    #[test]
150    fn unknown_stays_unknown() {
151        let context = RunContext::resolve(Path::new("scratch.luau"), "");
152        assert_eq!(context, RunContext::Unknown);
153    }
154
155    #[test]
156    fn a_service_directory_resolves_without_a_sourcemap() {
157        assert_eq!(
158            RunContext::resolve(Path::new("ServerScriptService/Foo.lua"), ""),
159            RunContext::Server
160        );
161        assert_eq!(
162            RunContext::resolve(Path::new("ReplicatedStorage/Foo.lua"), ""),
163            RunContext::Shared
164        );
165    }
166
167    #[test]
168    fn a_server_or_client_directory_resolves() {
169        assert_eq!(
170            RunContext::resolve(Path::new("src/server/Foo.luau"), ""),
171            RunContext::Server
172        );
173        assert_eq!(
174            RunContext::resolve(Path::new("src/client/Foo.luau"), ""),
175            RunContext::Client
176        );
177        assert_eq!(
178            RunContext::resolve(Path::new("src/shared/Foo.luau"), ""),
179            RunContext::Shared
180        );
181    }
182}