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        for file in discovered {
125            let key = normalize(&file.relative);
126            let (instance_path, class_name) = by_file.get(&key).cloned().unwrap_or_default();
127            let run_context =
128                RunContext::resolve_in(&file.relative, &instance_path, allow_path_guessing);
129
130            let kind =
131                if file.relative.extension().and_then(|value| value.to_str()) == Some("blink") {
132                    FileKind::Blink
133                } else {
134                    FileKind::Luau
135                };
136
137            files.push(SourceFile {
138                path: file.absolute,
139                relative: file.relative,
140                kind,
141                instance_path,
142                class_name,
143                run_context,
144            });
145        }
146
147        let luau = files
148            .iter()
149            .filter(|file| file.kind == FileKind::Luau)
150            .count();
151        let unknown = files
152            .iter()
153            .filter(|file| file.kind == FileKind::Luau && file.run_context == RunContext::Unknown)
154            .count();
155        if model != ModelSource::Plain && unknown * 2 > luau {
156            notes.push(format!(
157                "{unknown} of {luau} files have no run context; check the Rojo project file or pass --sourcemap"
158            ));
159        }
160        if model == ModelSource::Plain {
161            notes.push(
162                "plain model: run context comes from filename suffixes only (for example .server.luau)"
163                    .to_owned(),
164            );
165        }
166
167        let (generated, files): (Vec<_>, Vec<_>) = files
168            .into_iter()
169            .partition(|file| generated::is_generated(&file.path));
170        if !generated.is_empty() {
171            notes.push(format!(
172                "{} generated files were not analyzed",
173                generated.len()
174            ));
175        }
176
177        Ok(Self {
178            root: root.to_path_buf(),
179            files,
180            generated: generated.len(),
181            dependencies: read_dependencies(root, &mut notes),
182            aliases: read_aliases(root, &mut notes),
183            model,
184            notes,
185        })
186    }
187
188    /// Count files per run context, in the order server, client, shared, unknown.
189    #[must_use]
190    pub fn context_counts(&self) -> [usize; 4] {
191        let mut counts = [0; 4];
192        for file in &self.files {
193            let index = match file.run_context {
194                RunContext::Server => 0,
195                RunContext::Client => 1,
196                RunContext::Shared => 2,
197                RunContext::Unknown => 3,
198            };
199            counts[index] += 1;
200        }
201        counts
202    }
203}
204
205fn load_model(
206    root: &Path,
207    config: &Config,
208    explicit_sourcemap: Option<&Path>,
209    generate: bool,
210    project_files: &[PathBuf],
211    notes: &mut Vec<String>,
212) -> Result<(Vec<Instance>, ModelSource), Error> {
213    if config.project.model == Model::Plain {
214        if explicit_sourcemap.is_some() || config.project.sourcemap != "auto" {
215            notes.push("plain model: the configured sourcemap is ignored".to_owned());
216        }
217        return Ok((Vec::new(), ModelSource::Plain));
218    }
219
220    if let Some(path) = explicit_sourcemap {
221        return Ok((
222            sourcemap::load(path)?,
223            ModelSource::Given(path.to_path_buf()),
224        ));
225    }
226
227    if config.project.sourcemap != "auto" {
228        let path = root.join(&config.project.sourcemap);
229        return Ok((sourcemap::load(&path)?, ModelSource::Given(path)));
230    }
231
232    // Generation comes before a checked-in `sourcemap.json`: that file is frequently stale
233    // or built from a different project file in the same repository, and trusting it maps
234    // files to the wrong instances.
235    // A repository can hold several places: `default.project.json` for the game and
236    // `hub.project.json` for a second one. Every project contributes, and the first
237    // mapping of a file wins, so the default project has priority.
238    if generate && !project_files.is_empty() {
239        match generate_sourcemaps(root, project_files) {
240            Ok((instances, path)) => {
241                return Ok((instances, ModelSource::Generated(path)));
242            }
243            Err(error) => {
244                notes.push(format!("rojo sourcemap failed, falling back: {error}"));
245            }
246        }
247    }
248
249    let existing = root.join("sourcemap.json");
250    if existing.is_file() {
251        return Ok((sourcemap::load(&existing)?, ModelSource::Existing(existing)));
252    }
253
254    if let Some(first) = project_files.first() {
255        let mut merged = Vec::new();
256        for project in project_files {
257            merged.extend(project_file::instances(project)?);
258        }
259        return Ok((merged, ModelSource::ProjectFile(first.clone())));
260    }
261
262    if config.project.model == Model::Auto {
263        Ok((Vec::new(), ModelSource::Plain))
264    } else {
265        Ok((Vec::new(), ModelSource::Suffixes))
266    }
267}
268
269fn generate_sourcemaps(
270    root: &Path,
271    project_files: &[PathBuf],
272) -> Result<(Vec<Instance>, PathBuf), Error> {
273    let mut merged = Vec::new();
274    let mut first = None;
275
276    for project in project_files {
277        let path = generate_sourcemap(root, project)?;
278        merged.extend(sourcemap::load(&path)?);
279        if first.is_none() {
280            first = Some(path);
281        }
282    }
283
284    first.map_or_else(
285        || Err(Error::NoProject(root.to_path_buf())),
286        |path| Ok((merged, path)),
287    )
288}
289
290/// Find every Rojo project in the root: `default.project.json` first, then the rest.
291#[must_use]
292pub fn find_project_files(root: &Path) -> Vec<PathBuf> {
293    let default = root.join("default.project.json");
294    let mut candidates = Vec::new();
295
296    if default.is_file() {
297        candidates.push(default.clone());
298    }
299
300    let Ok(entries) = std::fs::read_dir(root) else {
301        return candidates;
302    };
303
304    let mut others: Vec<PathBuf> = entries
305        .flatten()
306        .map(|entry| entry.path())
307        .filter(|path| {
308            path.file_name()
309                .and_then(|name| name.to_str())
310                .is_some_and(|name| name.ends_with(".project.json"))
311        })
312        .filter(|path| *path != default)
313        .collect();
314
315    others.sort();
316    candidates.extend(others);
317    candidates
318}
319
320fn generate_sourcemap(root: &Path, project: &Path) -> Result<PathBuf, Error> {
321    let cache = root.join(".plut");
322    std::fs::create_dir_all(&cache).map_err(|source| Error::Write {
323        path: cache.clone(),
324        source,
325    })?;
326
327    let stem = project
328        .file_stem()
329        .and_then(|name| name.to_str())
330        .unwrap_or("project");
331    let output = cache.join(format!("{stem}.sourcemap.json"));
332    let result = Command::new("rojo")
333        .arg("sourcemap")
334        .arg(project)
335        .arg("--output")
336        .arg(&output)
337        .current_dir(root)
338        .output()
339        .map_err(Error::Rojo)?;
340
341    if !result.status.success() {
342        return Err(Error::RojoFailed {
343            code: result.status.code().unwrap_or(-1),
344            stderr: String::from_utf8_lossy(&result.stderr).trim().to_owned(),
345        });
346    }
347
348    Ok(output)
349}
350
351fn normalize(path: &Path) -> PathBuf {
352    path.components()
353        .filter(|component| !matches!(component, Component::CurDir))
354        .collect()
355}
356
357fn read_aliases(root: &Path, notes: &mut Vec<String>) -> Vec<Alias> {
358    let path = root.join(".luaurc");
359    if !path.is_file() {
360        return Vec::new();
361    }
362
363    let text = match std::fs::read_to_string(&path) {
364        Ok(text) => text,
365        Err(error) => {
366            notes.push(format!(".luaurc could not be read: {error}"));
367            return Vec::new();
368        }
369    };
370
371    // `.luaurc` is JSON with comments in some editors' versions. The Luau tooling writes
372    // plain JSON, so a strict parse is enough; a broken file only costs alias resolution.
373    let value: serde_json::Value = match serde_json::from_str(&text) {
374        Ok(value) => value,
375        Err(error) => {
376            notes.push(format!(".luaurc could not be parsed: {error}"));
377            return Vec::new();
378        }
379    };
380
381    let Some(aliases) = value.get("aliases").and_then(serde_json::Value::as_object) else {
382        return Vec::new();
383    };
384
385    let mut out = Vec::new();
386    for (name, target) in aliases {
387        let Some(target) = target.as_str() else {
388            continue;
389        };
390
391        let target = target.strip_prefix('~').map_or_else(
392            || PathBuf::from(target),
393            |rest| {
394                std::env::var_os("HOME").map_or_else(
395                    || PathBuf::from(target),
396                    |home| PathBuf::from(home).join(rest.trim_start_matches('/')),
397                )
398            },
399        );
400        let target = if target.is_absolute() {
401            target
402        } else {
403            root.join(target)
404        };
405
406        out.push(Alias {
407            name: name.trim_start_matches('@').to_owned(),
408            path: normalize(&target),
409        });
410    }
411
412    out.sort_by(|left, right| left.name.cmp(&right.name));
413    out
414}
415
416fn read_dependencies(root: &Path, notes: &mut Vec<String>) -> Vec<Dependency> {
417    let mut out = Vec::new();
418
419    for manifest in ["pesde.toml", "wally.toml"] {
420        let path = root.join(manifest);
421        if !path.is_file() {
422            continue;
423        }
424
425        let text = match std::fs::read_to_string(&path) {
426            Ok(text) => text,
427            Err(error) => {
428                notes.push(format!("{manifest} could not be read: {error}"));
429                continue;
430            }
431        };
432
433        let value: toml::Value = match toml::from_str(&text) {
434            Ok(value) => value,
435            Err(error) => {
436                notes.push(format!("{manifest} could not be parsed: {error}"));
437                continue;
438            }
439        };
440
441        let Some(dependencies) = value.get("dependencies").and_then(toml::Value::as_table) else {
442            continue;
443        };
444
445        for (name, entry) in dependencies {
446            // pesde maps an alias to a package: `KeepBlox = { name = "xopoiii/keepblox" }`.
447            let package = entry
448                .get("name")
449                .and_then(toml::Value::as_str)
450                .map_or_else(|| name.clone(), ToOwned::to_owned);
451
452            let version = entry.as_str().map(ToOwned::to_owned).or_else(|| {
453                entry
454                    .get("version")
455                    .and_then(toml::Value::as_str)
456                    .map(ToOwned::to_owned)
457            });
458
459            out.push(Dependency {
460                name: package,
461                version,
462            });
463        }
464    }
465
466    out.sort_by(|left, right| left.name.cmp(&right.name));
467    out.dedup_by(|left, right| left.name == right.name);
468    out
469}