plut-core 2.0.0

Project model, run context and diagnostics for Plut
Documentation
//! Fallback project model: read `default.project.json` directly when Rojo is not
//! installed. This understands `$className` and `$path`, and expands a directory `$path`
//! into a folder of modules. It is deliberately smaller than Rojo; it exists so a machine
//! without Rojo still gets correct run context for the common layout.

use std::path::{Path, PathBuf};

use serde_json::Value;

use crate::Error;
use crate::index::is_luau;
use crate::sourcemap::Instance;

/// Build instances from a Rojo project file.
pub fn instances(path: &Path) -> Result<Vec<Instance>, Error> {
    let text = std::fs::read_to_string(path).map_err(|source| Error::Read {
        path: path.to_path_buf(),
        source,
    })?;
    let value: Value = serde_json::from_str(&text).map_err(|source| Error::ParseJson {
        path: path.to_path_buf(),
        source,
    })?;

    let base = path.parent().unwrap_or_else(|| Path::new("."));
    let mut out = Vec::new();

    if let Some(tree) = value.get("tree") {
        walk(tree, "", base, &mut out)?;
    }

    Ok(out)
}

fn walk(node: &Value, parent: &str, base: &Path, out: &mut Vec<Instance>) -> Result<(), Error> {
    let Some(map) = node.as_object() else {
        return Ok(());
    };

    for (name, child) in map {
        if name.starts_with('$') {
            continue;
        }

        let path = if parent.is_empty() {
            name.clone()
        } else {
            format!("{parent}/{name}")
        };

        let class_name = child
            .get("$className")
            .and_then(Value::as_str)
            .unwrap_or("Folder")
            .to_owned();

        if let Some(raw) = child.get("$path").and_then(Value::as_str) {
            let absolute = base.join(raw);
            if absolute.is_dir() {
                out.push(Instance {
                    path: path.clone(),
                    class_name,
                    file_paths: Vec::new(),
                });
                collect_dir(&absolute, &path, base, out)?;
            } else {
                out.push(Instance {
                    path: path.clone(),
                    class_name,
                    file_paths: vec![PathBuf::from(raw)],
                });
            }
        } else {
            out.push(Instance {
                path: path.clone(),
                class_name,
                file_paths: Vec::new(),
            });
        }

        walk(child, &path, base, out)?;
    }

    Ok(())
}

fn collect_dir(
    dir: &Path,
    instance: &str,
    base: &Path,
    out: &mut Vec<Instance>,
) -> Result<(), Error> {
    let entries = std::fs::read_dir(dir).map_err(|source| Error::Read {
        path: dir.to_path_buf(),
        source,
    })?;

    for entry in entries {
        let entry = entry.map_err(|source| Error::Read {
            path: dir.to_path_buf(),
            source,
        })?;

        let path = entry.path();
        let name = entry.file_name().to_string_lossy().into_owned();

        if name.starts_with('.') {
            continue;
        }

        if path.is_dir() {
            let child = format!("{instance}/{name}");
            out.push(Instance {
                path: child.clone(),
                class_name: "Folder".to_owned(),
                file_paths: Vec::new(),
            });
            collect_dir(&path, &child, base, out)?;
        } else if is_luau(&path) {
            let Ok(relative) = path.strip_prefix(base) else {
                continue;
            };

            let (stem, class_name) = classify(&path);
            let target = if stem == "init" {
                instance.to_owned()
            } else {
                format!("{instance}/{stem}")
            };

            out.push(Instance {
                path: target,
                class_name,
                file_paths: vec![relative.to_path_buf()],
            });
        }
    }

    Ok(())
}

fn classify(path: &Path) -> (String, String) {
    let file = path
        .file_stem()
        .and_then(|value| value.to_str())
        .unwrap_or_default();

    if let Some(stem) = file.strip_suffix(".server") {
        (stem.to_owned(), "Script".to_owned())
    } else if let Some(stem) = file.strip_suffix(".client") {
        (stem.to_owned(), "LocalScript".to_owned())
    } else {
        (file.to_owned(), "ModuleScript".to_owned())
    }
}