Skip to main content

plut_core/
project.rs

1use std::collections::HashMap;
2use std::path::{Component, Path, PathBuf};
3use std::process::Command;
4
5use crate::sourcemap::{self, Instance};
6use crate::{Config, Error, Model, RunContext, generated, index, project_file};
7
8/// A package manager dependency, used by the ecosystem rules.
9#[derive(Debug, Clone)]
10pub struct Dependency {
11    pub name: String,
12    pub version: Option<String>,
13}
14
15/// What a source file is.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum FileKind {
18    Luau,
19    Blink,
20}
21
22/// A Luau path alias from `.luaurc`, such as `@game` pointing at `src`.
23#[derive(Debug, Clone)]
24pub struct Alias {
25    /// The alias without its leading `@`, for example `game`.
26    pub name: String,
27    /// Absolute directory the alias stands for.
28    pub path: PathBuf,
29}
30
31/// A source file, mapped onto the project model.
32#[derive(Debug, Clone)]
33pub struct SourceFile {
34    pub path: PathBuf,
35    pub relative: PathBuf,
36    pub kind: FileKind,
37    /// Instance path in the sourcemap, such as `ServerScriptService/Admin`.
38    pub instance_path: String,
39    pub class_name: String,
40    pub run_context: RunContext,
41}
42
43/// Where the project model came from. Printed under `--verbose` so a wrong context is
44/// diagnosable in one line.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum ModelSource {
47    Given(PathBuf),
48    Existing(PathBuf),
49    Generated(PathBuf),
50    ProjectFile(PathBuf),
51    Suffixes,
52    /// A plain Luau tree with no engine model. Context comes from filename suffixes only.
53    Plain,
54    /// The open place in Roblox Studio, read through its MCP server.
55    Studio,
56    /// A `.rbxl` or `.rbxlx` place read directly.
57    Place,
58}
59
60impl ModelSource {
61    /// A human-readable description for `--verbose`.
62    #[must_use]
63    pub fn describe(&self) -> String {
64        match self {
65            Self::Given(path) => format!("given ({})", path.display()),
66            Self::Existing(path) => format!("existing ({})", path.display()),
67            Self::Generated(path) => format!("generated with rojo ({})", path.display()),
68            Self::ProjectFile(path) => format!("project file ({})", path.display()),
69            Self::Suffixes => "filename suffixes only".to_owned(),
70            Self::Plain => "plain Luau tree".to_owned(),
71            Self::Studio => "Roblox Studio (MCP)".to_owned(),
72            Self::Place => "Roblox place file".to_owned(),
73        }
74    }
75}
76
77/// A Rojo project, indexed and ready for rules.
78#[derive(Debug)]
79pub struct Project {
80    pub root: PathBuf,
81    pub files: Vec<SourceFile>,
82    /// Files skipped because they declare themselves generated.
83    pub generated: usize,
84    pub dependencies: Vec<Dependency>,
85    /// Luau path aliases from `.luaurc`.
86    pub aliases: Vec<Alias>,
87    pub model: ModelSource,
88    /// Non-fatal problems worth telling the user about, such as a failed `rojo sourcemap`.
89    pub notes: Vec<String>,
90}
91
92impl Project {
93    /// Load a project: acquire the model, walk the tree, resolve run context.
94    pub fn load(
95        root: &Path,
96        config: &Config,
97        explicit_sourcemap: Option<&Path>,
98        generate: bool,
99    ) -> Result<Self, Error> {
100        let project_files = find_project_files(root);
101        let mut notes = Vec::new();
102        let (instances, model) = load_model(
103            root,
104            config,
105            explicit_sourcemap,
106            generate,
107            &project_files,
108            &mut notes,
109        )?;
110
111        let mut by_file: HashMap<PathBuf, (String, String)> = HashMap::new();
112        for instance in &instances {
113            for file in &instance.file_paths {
114                by_file
115                    .entry(normalize(file))
116                    .or_insert_with(|| (instance.path.clone(), instance.class_name.clone()));
117            }
118        }
119
120        let discovered = index::walk(root, config)?;
121        let mut files = Vec::with_capacity(discovered.len());
122
123        let allow_path_guessing = model != ModelSource::Plain
124            || config.project.contexts == crate::config::Contexts::Paths;
125        for file in discovered {
126            let key = normalize(&file.relative);
127            let (instance_path, class_name) = by_file.get(&key).cloned().unwrap_or_default();
128            let run_context =
129                RunContext::resolve_in(&file.relative, &instance_path, allow_path_guessing);
130
131            let kind =
132                if file.relative.extension().and_then(|value| value.to_str()) == Some("blink") {
133                    FileKind::Blink
134                } else {
135                    FileKind::Luau
136                };
137
138            files.push(SourceFile {
139                path: file.absolute,
140                relative: file.relative,
141                kind,
142                instance_path,
143                class_name,
144                run_context,
145            });
146        }
147
148        let luau = files
149            .iter()
150            .filter(|file| file.kind == FileKind::Luau)
151            .count();
152        let unknown = files
153            .iter()
154            .filter(|file| file.kind == FileKind::Luau && file.run_context == RunContext::Unknown)
155            .count();
156        if model != ModelSource::Plain && unknown * 2 > luau {
157            notes.push(format!(
158                "{unknown} of {luau} files have no run context; check the Rojo project file or pass --sourcemap"
159            ));
160        }
161        if model == ModelSource::Plain {
162            let source = if config.project.contexts == crate::config::Contexts::Paths {
163                "filename suffixes and path components"
164            } else {
165                "filename suffixes only (for example .server.luau)"
166            };
167            notes.push(format!("plain model: run context comes from {source}"));
168        }
169
170        let (generated, files): (Vec<_>, Vec<_>) = files
171            .into_iter()
172            .partition(|file| generated::is_generated(&file.path));
173        if !generated.is_empty() {
174            notes.push(format!(
175                "{} generated files were not analyzed",
176                generated.len()
177            ));
178        }
179
180        Ok(Self {
181            root: root.to_path_buf(),
182            files,
183            generated: generated.len(),
184            dependencies: read_dependencies(root, &mut notes),
185            aliases: read_aliases(root, &mut notes),
186            model,
187            notes,
188        })
189    }
190
191    /// Count files per run context, in the order server, client, shared, unknown.
192    #[must_use]
193    pub fn context_counts(&self) -> [usize; 4] {
194        let mut counts = [0; 4];
195        for file in &self.files {
196            let index = match file.run_context {
197                RunContext::Server => 0,
198                RunContext::Client => 1,
199                RunContext::Shared => 2,
200                RunContext::Unknown => 3,
201            };
202            counts[index] += 1;
203        }
204        counts
205    }
206}
207
208fn load_model(
209    root: &Path,
210    config: &Config,
211    explicit_sourcemap: Option<&Path>,
212    generate: bool,
213    project_files: &[PathBuf],
214    notes: &mut Vec<String>,
215) -> Result<(Vec<Instance>, ModelSource), Error> {
216    if config.project.model == Model::Plain {
217        if explicit_sourcemap.is_some() || config.project.sourcemap != "auto" {
218            notes.push("plain model: the configured sourcemap is ignored".to_owned());
219        }
220        return Ok((Vec::new(), ModelSource::Plain));
221    }
222
223    if let Some(path) = explicit_sourcemap {
224        return Ok((
225            sourcemap::load(path)?,
226            ModelSource::Given(path.to_path_buf()),
227        ));
228    }
229
230    if config.project.sourcemap != "auto" {
231        let path = root.join(&config.project.sourcemap);
232        return Ok((sourcemap::load(&path)?, ModelSource::Given(path)));
233    }
234
235    // Generation comes before a checked-in `sourcemap.json`: that file is frequently stale
236    // or built from a different project file in the same repository, and trusting it maps
237    // files to the wrong instances.
238    // A repository can hold several places: `default.project.json` for the game and
239    // `hub.project.json` for a second one. Every project contributes, and the first
240    // mapping of a file wins, so the default project has priority.
241    if generate && !project_files.is_empty() {
242        match generate_sourcemaps(root, project_files) {
243            Ok((instances, path)) => {
244                return Ok((instances, ModelSource::Generated(path)));
245            }
246            Err(error) => {
247                notes.push(format!("rojo sourcemap failed, falling back: {error}"));
248            }
249        }
250    }
251
252    let existing = root.join("sourcemap.json");
253    if existing.is_file() {
254        return Ok((sourcemap::load(&existing)?, ModelSource::Existing(existing)));
255    }
256
257    if let Some(first) = project_files.first() {
258        let mut merged = Vec::new();
259        for project in project_files {
260            merged.extend(project_file::instances(project)?);
261        }
262        return Ok((merged, ModelSource::ProjectFile(first.clone())));
263    }
264
265    if config.project.model == Model::Auto {
266        Ok((Vec::new(), ModelSource::Plain))
267    } else {
268        Ok((Vec::new(), ModelSource::Suffixes))
269    }
270}
271
272fn generate_sourcemaps(
273    root: &Path,
274    project_files: &[PathBuf],
275) -> Result<(Vec<Instance>, PathBuf), Error> {
276    let mut merged = Vec::new();
277    let mut first = None;
278
279    for project in project_files {
280        let path = generate_sourcemap(root, project)?;
281        merged.extend(sourcemap::load(&path)?);
282        if first.is_none() {
283            first = Some(path);
284        }
285    }
286
287    first.map_or_else(
288        || Err(Error::NoProject(root.to_path_buf())),
289        |path| Ok((merged, path)),
290    )
291}
292
293/// Find every Rojo project in the root: `default.project.json` first, then the rest.
294#[must_use]
295pub fn find_project_files(root: &Path) -> Vec<PathBuf> {
296    let default = root.join("default.project.json");
297    let mut candidates = Vec::new();
298
299    if default.is_file() {
300        candidates.push(default.clone());
301    }
302
303    let Ok(entries) = std::fs::read_dir(root) else {
304        return candidates;
305    };
306
307    let mut others: Vec<PathBuf> = entries
308        .flatten()
309        .map(|entry| entry.path())
310        .filter(|path| {
311            path.file_name()
312                .and_then(|name| name.to_str())
313                .is_some_and(|name| name.ends_with(".project.json"))
314        })
315        .filter(|path| *path != default)
316        .collect();
317
318    others.sort();
319    candidates.extend(others);
320    candidates
321}
322
323fn generate_sourcemap(root: &Path, project: &Path) -> Result<PathBuf, Error> {
324    let cache = root.join(".plut");
325    std::fs::create_dir_all(&cache).map_err(|source| Error::Write {
326        path: cache.clone(),
327        source,
328    })?;
329
330    let stem = project
331        .file_stem()
332        .and_then(|name| name.to_str())
333        .unwrap_or("project");
334    let output = cache.join(format!("{stem}.sourcemap.json"));
335    let result = Command::new("rojo")
336        .arg("sourcemap")
337        .arg(project)
338        .arg("--output")
339        .arg(&output)
340        .current_dir(root)
341        .output()
342        .map_err(Error::Rojo)?;
343
344    if !result.status.success() {
345        return Err(Error::RojoFailed {
346            code: result.status.code().unwrap_or(-1),
347            stderr: String::from_utf8_lossy(&result.stderr).trim().to_owned(),
348        });
349    }
350
351    Ok(output)
352}
353
354fn normalize(path: &Path) -> PathBuf {
355    path.components()
356        .filter(|component| !matches!(component, Component::CurDir))
357        .collect()
358}
359
360fn read_aliases(root: &Path, notes: &mut Vec<String>) -> Vec<Alias> {
361    let path = root.join(".luaurc");
362    if !path.is_file() {
363        return Vec::new();
364    }
365
366    let text = match std::fs::read_to_string(&path) {
367        Ok(text) => text,
368        Err(error) => {
369            notes.push(format!(".luaurc could not be read: {error}"));
370            return Vec::new();
371        }
372    };
373
374    // `.luaurc` is JSON with comments in some editors' versions. The Luau tooling writes
375    // plain JSON, so a strict parse is enough; a broken file only costs alias resolution.
376    let value: serde_json::Value = match serde_json::from_str(&text) {
377        Ok(value) => value,
378        Err(error) => {
379            notes.push(format!(".luaurc could not be parsed: {error}"));
380            return Vec::new();
381        }
382    };
383
384    let Some(aliases) = value.get("aliases").and_then(serde_json::Value::as_object) else {
385        return Vec::new();
386    };
387
388    let mut out = Vec::new();
389    for (name, target) in aliases {
390        let Some(target) = target.as_str() else {
391            continue;
392        };
393
394        let target = target.strip_prefix('~').map_or_else(
395            || PathBuf::from(target),
396            |rest| {
397                std::env::var_os("HOME").map_or_else(
398                    || PathBuf::from(target),
399                    |home| PathBuf::from(home).join(rest.trim_start_matches('/')),
400                )
401            },
402        );
403        let target = if target.is_absolute() {
404            target
405        } else {
406            root.join(target)
407        };
408
409        out.push(Alias {
410            name: name.trim_start_matches('@').to_owned(),
411            path: normalize(&target),
412        });
413    }
414
415    out.sort_by(|left, right| left.name.cmp(&right.name));
416    out
417}
418
419fn read_dependencies(root: &Path, notes: &mut Vec<String>) -> Vec<Dependency> {
420    let mut out = Vec::new();
421
422    for manifest in ["pesde.toml", "wally.toml"] {
423        let path = root.join(manifest);
424        if !path.is_file() {
425            continue;
426        }
427
428        let text = match std::fs::read_to_string(&path) {
429            Ok(text) => text,
430            Err(error) => {
431                notes.push(format!("{manifest} could not be read: {error}"));
432                continue;
433            }
434        };
435
436        let value: toml::Value = match toml::from_str(&text) {
437            Ok(value) => value,
438            Err(error) => {
439                notes.push(format!("{manifest} could not be parsed: {error}"));
440                continue;
441            }
442        };
443
444        let Some(dependencies) = value.get("dependencies").and_then(toml::Value::as_table) else {
445            continue;
446        };
447
448        for (name, entry) in dependencies {
449            // pesde maps an alias to a package: `KeepBlox = { name = "xopoiii/keepblox" }`.
450            let package = entry
451                .get("name")
452                .and_then(toml::Value::as_str)
453                .map_or_else(|| name.clone(), ToOwned::to_owned);
454
455            let version = entry.as_str().map(ToOwned::to_owned).or_else(|| {
456                entry
457                    .get("version")
458                    .and_then(toml::Value::as_str)
459                    .map(ToOwned::to_owned)
460            });
461
462            out.push(Dependency {
463                name: package,
464                version,
465            });
466        }
467    }
468
469    out.sort_by(|left, right| left.name.cmp(&right.name));
470    out.dedup_by(|left, right| left.name == right.name);
471    out
472}