robloxstudio-worktree 0.1.0

Own an isolated Rojo, Roblox Studio, and MCP runtime for each Git worktree
Documentation
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::Deserialize;
use serde_json::Value;

pub const CONFIG_NAME: &str = "robloxstudio-worktree.json";

#[derive(Clone, Debug)]
pub struct ContractNames {
    pub endpoint_attribute: String,
    pub project_attribute: String,
    pub session_attribute: String,
    pub identity_attribute: String,
    pub connection_marker: String,
}

impl Default for ContractNames {
    fn default() -> Self {
        Self {
            endpoint_attribute: "__StudioWorktree_RojoEndpoint".into(),
            project_attribute: "__StudioWorktree_RojoProject".into(),
            session_attribute: "__StudioWorktree_Session".into(),
            identity_attribute: "__StudioWorktree_Identity".into(),
            connection_marker: "__StudioWorktree_RojoConnection".into(),
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct HookConfig {
    pub validate: Option<Vec<String>>,
    pub test: Option<Vec<String>>,
}

#[derive(Clone, Debug)]
pub struct BootstrapConfig {
    pub commands: Vec<Vec<String>>,
    pub required_globs: Vec<String>,
    pub plugin: Option<String>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum ServeMode {
    #[default]
    Full,
    SourceOverlay,
}

#[derive(Clone, Debug, Default)]
pub struct ServeConfig {
    pub mode: ServeMode,
    pub preserve: BTreeMap<String, Vec<String>>,
}

#[derive(Clone, Debug)]
pub struct ProjectConfig {
    pub root: PathBuf,
    pub path: PathBuf,
    pub project_path: PathBuf,
    pub project_name: String,
    pub state_dir: PathBuf,
    pub serve: ServeConfig,
    pub contract: ContractNames,
    pub hooks: HookConfig,
    pub bootstrap: BootstrapConfig,
}

impl ProjectConfig {
    pub fn bundled_plugin_bytes(&self) -> &'static [u8] {
        include_bytes!("../resources/RojoWorktree.rbxm")
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawConfig {
    version: u32,
    project: String,
    name: Option<String>,
    #[serde(rename = "stateDir", default = "default_state_dir")]
    state_dir: String,
    #[serde(default)]
    serve: RawServe,
    #[serde(default)]
    contract: RawContract,
    #[serde(default)]
    hooks: RawHooks,
    #[serde(default)]
    bootstrap: RawBootstrap,
}

fn default_state_dir() -> String {
    ".worktree-studio".into()
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawServe {
    #[serde(default)]
    mode: String,
    #[serde(default)]
    preserve: BTreeMap<String, Vec<String>>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawContract {
    #[serde(rename = "endpointAttribute")]
    endpoint_attribute: Option<String>,
    #[serde(rename = "projectAttribute")]
    project_attribute: Option<String>,
    #[serde(rename = "sessionAttribute")]
    session_attribute: Option<String>,
    #[serde(rename = "identityAttribute")]
    identity_attribute: Option<String>,
    #[serde(rename = "connectionMarker")]
    connection_marker: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawHooks {
    validate: Option<Vec<String>>,
    test: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawBootstrap {
    #[serde(default)]
    commands: Vec<Vec<String>>,
    #[serde(rename = "requiredGlobs", default)]
    required_globs: Vec<String>,
    #[serde(default = "default_plugin")]
    plugin: Option<String>,
}

impl Default for RawBootstrap {
    fn default() -> Self {
        Self {
            commands: Vec::new(),
            required_globs: Vec::new(),
            plugin: default_plugin(),
        }
    }
}

fn default_plugin() -> Option<String> {
    Some("bundled".into())
}

fn nonempty(value: String, label: &str) -> Result<String> {
    if value.is_empty() {
        bail!("{label} must be a non-empty string");
    }
    Ok(value)
}

fn validate_command(command: &[String], label: &str) -> Result<()> {
    if command.is_empty() {
        bail!("{label} must not be empty");
    }
    if command.iter().any(String::is_empty) {
        bail!("{label} must contain only non-empty strings");
    }
    Ok(())
}

fn canonicalish(path: PathBuf) -> Result<PathBuf> {
    if path.exists() {
        return path
            .canonicalize()
            .with_context(|| format!("Could not resolve {}", path.display()));
    }
    let parent = path
        .parent()
        .context("Path has no parent")?
        .canonicalize()
        .with_context(|| format!("Could not resolve parent of {}", path.display()))?;
    Ok(parent.join(path.file_name().context("Path has no file name")?))
}

pub fn find_config(start: &Path) -> Result<PathBuf> {
    let start = if start.is_file() {
        start.parent().context("Start path has no parent")?
    } else {
        start
    };
    for directory in start.ancestors() {
        let candidate = directory.join(CONFIG_NAME);
        if candidate.is_file() {
            return candidate
                .canonicalize()
                .with_context(|| format!("Could not resolve {}", candidate.display()));
        }
    }
    bail!("Could not find {CONFIG_NAME} from {}", start.display())
}

pub fn load_project_config(
    project_root: Option<&Path>,
    config_path: Option<&Path>,
) -> Result<ProjectConfig> {
    let path = match config_path {
        Some(path) => canonicalish(path.to_path_buf())?,
        None => match project_root {
            Some(root) => canonicalish(root.join(CONFIG_NAME))?,
            None => {
                find_config(&std::env::current_dir().context("Could not read current directory")?)?
            }
        },
    };
    let bytes = fs::read(&path).with_context(|| format!("Could not read {}", path.display()))?;
    let raw: RawConfig = serde_json::from_slice(&bytes)
        .with_context(|| format!("Invalid project contract {}", path.display()))?;
    if raw.version != 1 {
        bail!("{} must declare version 1", path.display());
    }

    let root = match project_root {
        Some(root) => canonicalish(root.to_path_buf())?,
        None => path
            .parent()
            .context("Config path has no parent")?
            .to_path_buf(),
    };
    let project_path = canonicalish(root.join(nonempty(raw.project, "project")?))?;
    let rojo_bytes = fs::read(&project_path)
        .with_context(|| format!("Could not read Rojo project {}", project_path.display()))?;
    let rojo: Value = serde_json::from_slice(&rojo_bytes)
        .with_context(|| format!("Invalid Rojo project {}", project_path.display()))?;
    let project_name = match raw.name {
        Some(name) => nonempty(name, "name")?,
        None => rojo
            .get("name")
            .and_then(Value::as_str)
            .filter(|value| !value.is_empty())
            .context("name or the Rojo project's name must be a non-empty string")?
            .to_owned(),
    };

    let state_dir = canonicalish(root.join(nonempty(raw.state_dir, "stateDir")?))?;
    let state_relative = state_dir
        .strip_prefix(&root)
        .context("stateDir must stay inside the project root")?;
    if state_relative.as_os_str().is_empty() {
        bail!("stateDir must not be the project root");
    }

    let mode = match raw.serve.mode.as_str() {
        "" | "full" => ServeMode::Full,
        "source-overlay" => ServeMode::SourceOverlay,
        _ => bail!("serve.mode must be 'full' or 'source-overlay'"),
    };
    if mode == ServeMode::Full && !raw.serve.preserve.is_empty() {
        bail!("serve.preserve is only valid when serve.mode is 'source-overlay'");
    }
    for (service, children) in &raw.serve.preserve {
        if service.is_empty() || children.iter().any(String::is_empty) {
            bail!("serve.preserve must contain only non-empty service and child names");
        }
    }

    if let Some(command) = &raw.hooks.validate {
        validate_command(command, "hooks.validate")?;
    }
    if let Some(command) = &raw.hooks.test {
        validate_command(command, "hooks.test")?;
    }
    for (index, command) in raw.bootstrap.commands.iter().enumerate() {
        validate_command(command, &format!("bootstrap.commands[{index}]"))?;
    }

    let defaults = ContractNames::default();
    Ok(ProjectConfig {
        root,
        path,
        project_path,
        project_name,
        state_dir,
        serve: ServeConfig {
            mode,
            preserve: raw.serve.preserve,
        },
        contract: ContractNames {
            endpoint_attribute: raw
                .contract
                .endpoint_attribute
                .unwrap_or(defaults.endpoint_attribute),
            project_attribute: raw
                .contract
                .project_attribute
                .unwrap_or(defaults.project_attribute),
            session_attribute: raw
                .contract
                .session_attribute
                .unwrap_or(defaults.session_attribute),
            identity_attribute: raw
                .contract
                .identity_attribute
                .unwrap_or(defaults.identity_attribute),
            connection_marker: raw
                .contract
                .connection_marker
                .unwrap_or(defaults.connection_marker),
        },
        hooks: HookConfig {
            validate: raw.hooks.validate,
            test: raw.hooks.test,
        },
        bootstrap: BootstrapConfig {
            commands: raw.bootstrap.commands,
            required_globs: raw.bootstrap.required_globs,
            plugin: raw.bootstrap.plugin,
        },
    })
}