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