use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::process::Command;
use crate::sourcemap::{self, Instance};
use crate::{Config, Error, RunContext, generated, index, project_file};
#[derive(Debug, Clone)]
pub struct Dependency {
pub name: String,
pub version: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
Luau,
Blink,
}
#[derive(Debug, Clone)]
pub struct Alias {
pub name: String,
pub path: PathBuf,
}
#[derive(Debug, Clone)]
pub struct SourceFile {
pub path: PathBuf,
pub relative: PathBuf,
pub kind: FileKind,
pub instance_path: String,
pub class_name: String,
pub run_context: RunContext,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModelSource {
Given(PathBuf),
Existing(PathBuf),
Generated(PathBuf),
ProjectFile(PathBuf),
Suffixes,
Studio,
Place,
}
impl ModelSource {
#[must_use]
pub fn describe(&self) -> String {
match self {
Self::Given(path) => format!("given ({})", path.display()),
Self::Existing(path) => format!("existing ({})", path.display()),
Self::Generated(path) => format!("generated with rojo ({})", path.display()),
Self::ProjectFile(path) => format!("project file ({})", path.display()),
Self::Suffixes => "filename suffixes only".to_owned(),
Self::Studio => "Roblox Studio (MCP)".to_owned(),
Self::Place => "Roblox place file".to_owned(),
}
}
}
#[derive(Debug)]
pub struct Project {
pub root: PathBuf,
pub files: Vec<SourceFile>,
pub generated: usize,
pub dependencies: Vec<Dependency>,
pub aliases: Vec<Alias>,
pub model: ModelSource,
pub notes: Vec<String>,
}
impl Project {
pub fn load(
root: &Path,
config: &Config,
explicit_sourcemap: Option<&Path>,
generate: bool,
) -> Result<Self, Error> {
let project_files = find_project_files(root);
let mut notes = Vec::new();
let (instances, model) = load_model(
root,
config,
explicit_sourcemap,
generate,
&project_files,
&mut notes,
)?;
let mut by_file: HashMap<PathBuf, (String, String)> = HashMap::new();
for instance in &instances {
for file in &instance.file_paths {
by_file
.entry(normalize(file))
.or_insert_with(|| (instance.path.clone(), instance.class_name.clone()));
}
}
let discovered = index::walk(root, config)?;
let mut files = Vec::with_capacity(discovered.len());
for file in discovered {
let key = normalize(&file.relative);
let (instance_path, class_name) = by_file.get(&key).cloned().unwrap_or_default();
let run_context = RunContext::resolve(&file.relative, &instance_path);
let kind =
if file.relative.extension().and_then(|value| value.to_str()) == Some("blink") {
FileKind::Blink
} else {
FileKind::Luau
};
files.push(SourceFile {
path: file.absolute,
relative: file.relative,
kind,
instance_path,
class_name,
run_context,
});
}
let luau = files
.iter()
.filter(|file| file.kind == FileKind::Luau)
.count();
let unknown = files
.iter()
.filter(|file| file.kind == FileKind::Luau && file.run_context == RunContext::Unknown)
.count();
if unknown * 2 > luau {
notes.push(format!(
"{unknown} of {luau} files have no run context; check the Rojo project file or pass --sourcemap"
));
}
let (generated, files): (Vec<_>, Vec<_>) = files
.into_iter()
.partition(|file| generated::is_generated(&file.path));
if !generated.is_empty() {
notes.push(format!(
"{} generated files were not analyzed",
generated.len()
));
}
Ok(Self {
root: root.to_path_buf(),
files,
generated: generated.len(),
dependencies: read_dependencies(root, &mut notes),
aliases: read_aliases(root, &mut notes),
model,
notes,
})
}
#[must_use]
pub fn context_counts(&self) -> [usize; 4] {
let mut counts = [0; 4];
for file in &self.files {
let index = match file.run_context {
RunContext::Server => 0,
RunContext::Client => 1,
RunContext::Shared => 2,
RunContext::Unknown => 3,
};
counts[index] += 1;
}
counts
}
}
fn load_model(
root: &Path,
config: &Config,
explicit_sourcemap: Option<&Path>,
generate: bool,
project_files: &[PathBuf],
notes: &mut Vec<String>,
) -> Result<(Vec<Instance>, ModelSource), Error> {
if let Some(path) = explicit_sourcemap {
return Ok((
sourcemap::load(path)?,
ModelSource::Given(path.to_path_buf()),
));
}
if config.project.sourcemap != "auto" {
let path = root.join(&config.project.sourcemap);
return Ok((sourcemap::load(&path)?, ModelSource::Given(path)));
}
if generate && !project_files.is_empty() {
match generate_sourcemaps(root, project_files) {
Ok((instances, path)) => {
return Ok((instances, ModelSource::Generated(path)));
}
Err(error) => {
notes.push(format!("rojo sourcemap failed, falling back: {error}"));
}
}
}
let existing = root.join("sourcemap.json");
if existing.is_file() {
return Ok((sourcemap::load(&existing)?, ModelSource::Existing(existing)));
}
if let Some(first) = project_files.first() {
let mut merged = Vec::new();
for project in project_files {
merged.extend(project_file::instances(project)?);
}
return Ok((merged, ModelSource::ProjectFile(first.clone())));
}
Ok((Vec::new(), ModelSource::Suffixes))
}
fn generate_sourcemaps(
root: &Path,
project_files: &[PathBuf],
) -> Result<(Vec<Instance>, PathBuf), Error> {
let mut merged = Vec::new();
let mut first = None;
for project in project_files {
let path = generate_sourcemap(root, project)?;
merged.extend(sourcemap::load(&path)?);
if first.is_none() {
first = Some(path);
}
}
first.map_or_else(
|| Err(Error::NoProject(root.to_path_buf())),
|path| Ok((merged, path)),
)
}
#[must_use]
pub fn find_project_files(root: &Path) -> Vec<PathBuf> {
let default = root.join("default.project.json");
let mut candidates = Vec::new();
if default.is_file() {
candidates.push(default.clone());
}
let Ok(entries) = std::fs::read_dir(root) else {
return candidates;
};
let mut others: Vec<PathBuf> = entries
.flatten()
.map(|entry| entry.path())
.filter(|path| {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.ends_with(".project.json"))
})
.filter(|path| *path != default)
.collect();
others.sort();
candidates.extend(others);
candidates
}
fn generate_sourcemap(root: &Path, project: &Path) -> Result<PathBuf, Error> {
let cache = root.join(".plut");
std::fs::create_dir_all(&cache).map_err(|source| Error::Write {
path: cache.clone(),
source,
})?;
let stem = project
.file_stem()
.and_then(|name| name.to_str())
.unwrap_or("project");
let output = cache.join(format!("{stem}.sourcemap.json"));
let result = Command::new("rojo")
.arg("sourcemap")
.arg(project)
.arg("--output")
.arg(&output)
.current_dir(root)
.output()
.map_err(Error::Rojo)?;
if !result.status.success() {
return Err(Error::RojoFailed {
code: result.status.code().unwrap_or(-1),
stderr: String::from_utf8_lossy(&result.stderr).trim().to_owned(),
});
}
Ok(output)
}
fn normalize(path: &Path) -> PathBuf {
path.components()
.filter(|component| !matches!(component, Component::CurDir))
.collect()
}
fn read_aliases(root: &Path, notes: &mut Vec<String>) -> Vec<Alias> {
let path = root.join(".luaurc");
if !path.is_file() {
return Vec::new();
}
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(error) => {
notes.push(format!(".luaurc could not be read: {error}"));
return Vec::new();
}
};
let value: serde_json::Value = match serde_json::from_str(&text) {
Ok(value) => value,
Err(error) => {
notes.push(format!(".luaurc could not be parsed: {error}"));
return Vec::new();
}
};
let Some(aliases) = value.get("aliases").and_then(serde_json::Value::as_object) else {
return Vec::new();
};
let mut out = Vec::new();
for (name, target) in aliases {
let Some(target) = target.as_str() else {
continue;
};
let target = target.strip_prefix('~').map_or_else(
|| PathBuf::from(target),
|rest| {
std::env::var_os("HOME").map_or_else(
|| PathBuf::from(target),
|home| PathBuf::from(home).join(rest.trim_start_matches('/')),
)
},
);
let target = if target.is_absolute() {
target
} else {
root.join(target)
};
out.push(Alias {
name: name.trim_start_matches('@').to_owned(),
path: normalize(&target),
});
}
out.sort_by(|left, right| left.name.cmp(&right.name));
out
}
fn read_dependencies(root: &Path, notes: &mut Vec<String>) -> Vec<Dependency> {
let mut out = Vec::new();
for manifest in ["pesde.toml", "wally.toml"] {
let path = root.join(manifest);
if !path.is_file() {
continue;
}
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(error) => {
notes.push(format!("{manifest} could not be read: {error}"));
continue;
}
};
let value: toml::Value = match toml::from_str(&text) {
Ok(value) => value,
Err(error) => {
notes.push(format!("{manifest} could not be parsed: {error}"));
continue;
}
};
let Some(dependencies) = value.get("dependencies").and_then(toml::Value::as_table) else {
continue;
};
for (name, entry) in dependencies {
let package = entry
.get("name")
.and_then(toml::Value::as_str)
.map_or_else(|| name.clone(), ToOwned::to_owned);
let version = entry.as_str().map(ToOwned::to_owned).or_else(|| {
entry
.get("version")
.and_then(toml::Value::as_str)
.map(ToOwned::to_owned)
});
out.push(Dependency {
name: package,
version,
});
}
}
out.sort_by(|left, right| left.name.cmp(&right.name));
out.dedup_by(|left, right| left.name == right.name);
out
}