plut-core 2.4.0

Project model, run context and diagnostics for Plut
Documentation
use std::path::Path;

use serde::{Deserialize, Serialize};

/// Where a script runs. This is the single most important fact about a file: a rule that
/// fires in the wrong context is noise, and noise is how a security tool dies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RunContext {
    Server,
    Client,
    Shared,
    Unknown,
}

impl RunContext {
    /// The lowercase name used in output and JSON.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Server => "server",
            Self::Client => "client",
            Self::Shared => "shared",
            Self::Unknown => "unknown",
        }
    }

    /// Resolve from the Roblox service a file lands in.
    #[must_use]
    pub fn from_service(name: &str) -> Option<Self> {
        match name {
            "ServerScriptService" | "ServerStorage" | "Workspace" => Some(Self::Server),
            "StarterPlayer"
            | "StarterCharacterScripts"
            | "StarterPlayerScripts"
            | "StarterGui"
            | "StarterPack" => Some(Self::Client),
            "ReplicatedStorage" | "ReplicatedFirst" => Some(Self::Shared),
            _ => None,
        }
    }

    /// Resolve from a Rojo filename suffix: `Foo.server.luau`, `Bar.client.luau`.
    #[must_use]
    pub fn from_file_name(name: &str) -> Option<Self> {
        let stem = name
            .strip_suffix(".luau")
            .or_else(|| name.strip_suffix(".lua"))?;
        if stem.ends_with(".server") {
            Some(Self::Server)
        } else if stem.ends_with(".client") {
            Some(Self::Client)
        } else {
            None
        }
    }

    /// Resolve a file. The filename suffix wins over the service because
    /// `ReplicatedStorage/Foo.client.luau` is a client script in a shared container.
    ///
    /// `allow_path_guessing` is false in the plain model: an explicit `.server.luau` or
    /// `.client.luau` suffix still sets the context, but `src/server` and `src/client`
    /// directory names do not. A Lune project is not a Roblox project just because a
    /// folder is called `server`.
    #[must_use]
    pub fn resolve(relative: &Path, instance_path: &str) -> Self {
        Self::resolve_in(relative, instance_path, true)
    }

    /// Resolve a file, optionally allowing directory-name guessing. See [`resolve`](Self::resolve).
    #[must_use]
    pub fn resolve_in(relative: &Path, instance_path: &str, allow_path_guessing: bool) -> Self {
        let file_name = relative
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or_default();

        if let Some(context) = Self::from_file_name(file_name) {
            return context;
        }

        if let Some(service) = instance_path.split('/').next()
            && let Some(context) = Self::from_service(service)
        {
            return context;
        }

        if allow_path_guessing && let Some(context) = Self::from_path(relative) {
            return context;
        }

        Self::Unknown
    }

    fn from_path(path: &Path) -> Option<Self> {
        let mut components: Vec<&str> = path
            .components()
            .filter_map(|component| component.as_os_str().to_str())
            .collect();

        for component in components.iter().rev() {
            if let Some(context) = Self::from_service(component) {
                return Some(context);
            }
        }

        for component in components.drain(..).rev() {
            match component.to_ascii_lowercase().as_str() {
                "server" | "serverscript" | "serverscripts" | "serverside" => {
                    return Some(Self::Server);
                }
                "client" | "clientscript" | "clientscripts" | "clientside" => {
                    return Some(Self::Client);
                }
                "shared" | "common" => return Some(Self::Shared),
                _ => {}
            }
        }

        None
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::RunContext;

    #[test]
    fn suffix_wins_over_service() {
        let context = RunContext::resolve(
            Path::new("src/ReplicatedStorage/Foo.client.luau"),
            "ReplicatedStorage/Foo",
        );
        assert_eq!(context, RunContext::Client);
    }

    #[test]
    fn service_decides_when_there_is_no_suffix() {
        let context = RunContext::resolve(
            Path::new("src/server/Admin.luau"),
            "ServerScriptService/Admin",
        );
        assert_eq!(context, RunContext::Server);
    }

    #[test]
    fn shared_container_is_not_a_guess() {
        let context = RunContext::resolve(
            Path::new("src/shared/Config.luau"),
            "ReplicatedStorage/Config",
        );
        assert_eq!(context, RunContext::Shared);
    }

    #[test]
    fn unknown_stays_unknown() {
        let context = RunContext::resolve(Path::new("scratch.luau"), "");
        assert_eq!(context, RunContext::Unknown);
    }

    #[test]
    fn a_service_directory_resolves_without_a_sourcemap() {
        assert_eq!(
            RunContext::resolve(Path::new("ServerScriptService/Foo.lua"), ""),
            RunContext::Server
        );
        assert_eq!(
            RunContext::resolve(Path::new("ReplicatedStorage/Foo.lua"), ""),
            RunContext::Shared
        );
    }

    #[test]
    fn plain_mode_does_not_guess_from_directories() {
        assert_eq!(
            RunContext::resolve_in(Path::new("src/server/Foo.luau"), "", false),
            RunContext::Unknown
        );
        assert_eq!(
            RunContext::resolve_in(Path::new("src/Foo.server.luau"), "", false),
            RunContext::Server
        );
    }

    #[test]
    fn a_server_or_client_directory_resolves() {
        assert_eq!(
            RunContext::resolve(Path::new("src/server/Foo.luau"), ""),
            RunContext::Server
        );
        assert_eq!(
            RunContext::resolve(Path::new("src/client/Foo.luau"), ""),
            RunContext::Client
        );
        assert_eq!(
            RunContext::resolve(Path::new("src/shared/Foo.luau"), ""),
            RunContext::Shared
        );
    }
}