rproj 0.18.0

Guided bootstrap-to-game-dev CLI for Roblox: takes a fresh Windows PC to a working Roblox/Luau setup, then scaffolds projects on it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use std::fs;
use std::path::Path;

use anyhow::{Context, Result, bail};
use serde_json::{Map, Value, json};

use crate::ui;

pub const PROJECT_FILE: &str = "jest.project.json";
pub const CONFIG_FILE: &str = "jest.config.json";

const STARTER_SPECS: &[(&str, &str)] = &[
    ("tests/shared/hello.spec.luau", "shared"),
    ("tests/server/hello.spec.luau", "server"),
    ("tests/client/hello.spec.luau", "client"),
];

/// Jest Roblox 0.3.x treats a string in `test.projects` as the path to a
/// project config file. Inline entries are therefore required for the three
/// Luau test trees that rproj scaffolds.
const PROJECTS: &[(&str, &str)] = &[
    ("shared", "tests/shared/**/*.spec.luau"),
    ("server", "tests/server/**/*.spec.luau"),
    ("client", "tests/client/**/*.spec.luau"),
];

fn starter_spec(area: &str) -> String {
    format!(
        "--!strict\n\nlocal ReplicatedStorage = game:GetService(\"ReplicatedStorage\")\nlocal JestGlobals = require(ReplicatedStorage.devPackages.JestGlobals)\nlocal describe = JestGlobals.describe\nlocal it = JestGlobals.it\nlocal expect = JestGlobals.expect\n\ndescribe(\"{area}\", function()\n\tit(\"runs\", function()\n\t\texpect(1 + 1).toBe(2)\n\tend)\nend)\n"
    )
}

pub fn ensure_test_tree(project_dir: &Path, examples: bool) -> Result<()> {
    for (relative, area) in STARTER_SPECS {
        let file = project_dir.join(relative);
        let parent = file.parent().expect("test path has a parent");
        fs::create_dir_all(parent)?;
        if examples && !file.exists() {
            fs::write(&file, starter_spec(area))
                .with_context(|| format!("failed to write {}", file.display()))?;
        } else if !examples {
            let keep = parent.join(".gitkeep");
            if !keep.exists() {
                fs::write(keep, "")?;
            }
        }
    }
    ui::ok("prepared Jest test tree");
    Ok(())
}

pub fn project_document(production: &Value) -> Result<Value> {
    let mut project = production.clone();
    ensure_dev_mount(&mut project)?;
    let tree = project
        .get_mut("tree")
        .and_then(Value::as_object_mut)
        .context("default.project.json `tree` must be an object")?;

    tree.remove("Lighting");
    let server = child_object_mut(tree, "ServerScriptService")?;
    let properties = server.entry("$properties").or_insert_with(|| json!({}));
    properties
        .as_object_mut()
        .context("ServerScriptService properties must be an object")?
        .insert("LoadStringEnabled".into(), json!(true));
    insert_path(
        child_object_mut(tree, "ReplicatedStorage")?,
        "test",
        "tests/shared",
        "tree.ReplicatedStorage.test",
    )?;
    insert_path(
        child_object_mut(tree, "ServerScriptService")?,
        "test",
        "tests/server",
        "tree.ServerScriptService.test",
    )?;
    let starter_player = child_object_mut(tree, "StarterPlayer")?;
    insert_path(
        child_object_mut(starter_player, "StarterPlayerScripts")?,
        "test",
        "tests/client",
        "tree.StarterPlayer.StarterPlayerScripts.test",
    )?;
    Ok(project)
}

pub fn ensure_dev_mount(project: &mut Value) -> Result<()> {
    let tree = project
        .get_mut("tree")
        .and_then(Value::as_object_mut)
        .context("default.project.json `tree` must be an object")?;
    let storage = child_object_mut(tree, "ReplicatedStorage")?;
    if let Some(existing) = storage.get("devPackages") {
        if existing != &json!({ "$path": "DevPackages" }) {
            bail!("cannot create Jest mount `devPackages` because node already exists");
        }
    } else {
        storage.insert("devPackages".into(), json!({ "$path": "DevPackages" }));
    }
    Ok(())
}

fn child_object_mut<'a>(
    parent: &'a mut Map<String, Value>,
    key: &str,
) -> Result<&'a mut Map<String, Value>> {
    parent
        .get_mut(key)
        .and_then(Value::as_object_mut)
        .with_context(|| format!("default.project.json `{key}` must be an object"))
}

fn insert_path(
    parent: &mut Map<String, Value>,
    key: &str,
    path: &str,
    location: &str,
) -> Result<()> {
    if parent.contains_key(key) {
        bail!("cannot create Jest mount `{location}` because that node already exists");
    }
    parent.insert(key.to_string(), json!({ "$path": path }));
    Ok(())
}

pub fn project_contents(production: &Value) -> Result<String> {
    Ok(format!(
        "{}\n",
        serde_json::to_string_pretty(&project_document(production)?)?
    ))
}

pub fn refresh_project(project_dir: &Path) -> Result<()> {
    let source = project_dir.join("default.project.json");
    let mut production: Value = serde_json::from_str(
        &fs::read_to_string(&source)
            .with_context(|| format!("failed to read {}", source.display()))?,
    )
    .with_context(|| format!("failed to parse {}", source.display()))?;
    let original = production.clone();
    ensure_dev_mount(&mut production)?;
    let contents = project_contents(&production)?;
    if production != original {
        atomic_write(
            &source,
            format!("{}\n", serde_json::to_string_pretty(&production)?).as_bytes(),
        )?;
    }
    atomic_write(&project_dir.join(PROJECT_FILE), contents.as_bytes())?;
    ui::ok("wrote jest.project.json");
    Ok(())
}

pub fn merged_config(project_dir: &Path, backend: crate::graph::JestBackend) -> Result<String> {
    let path = project_dir.join(CONFIG_FILE);
    let mut root = if path.exists() {
        let value: Value = serde_json::from_str(&fs::read_to_string(&path)?)
            .with_context(|| format!("failed to parse {}", path.display()))?;
        value
            .as_object()
            .cloned()
            .with_context(|| format!("{} must contain a JSON object", path.display()))?
    } else {
        Map::new()
    };
    root.insert("backend".into(), json!(backend.key()));
    root.insert("rojoProject".into(), json!(PROJECT_FILE));
    root.insert(
        "jestPath".into(),
        json!("ReplicatedStorage/devPackages/Jest"),
    );
    let test = root.entry("test").or_insert_with(|| json!({}));
    let test = test
        .as_object_mut()
        .context("jest.config.json `test` must be an object")?;
    let projects: Vec<Value> = PROJECTS
        .iter()
        .map(|(display_name, include)| {
            json!({
                "test": {
                    "displayName": display_name,
                    "include": [include],
                }
            })
        })
        .collect();
    test.insert("projects".into(), Value::Array(projects));
    Ok(format!(
        "{}\n",
        serde_json::to_string_pretty(&Value::Object(root))?
    ))
}

pub fn ensure_config(project_dir: &Path, backend: crate::graph::JestBackend) -> Result<()> {
    atomic_write(
        &project_dir.join(CONFIG_FILE),
        merged_config(project_dir, backend)?.as_bytes(),
    )?;
    ui::ok("wrote jest.config.json");
    Ok(())
}

fn atomic_write(path: &Path, contents: &[u8]) -> Result<()> {
    let parent = path.parent().context("output path has no parent")?;
    let mut pending = tempfile::NamedTempFile::new_in(parent)?;
    use std::io::Write;
    pending.write_all(contents)?;
    pending.flush()?;
    if !path.exists() {
        return pending
            .persist(path)
            .map(|_| ())
            .map_err(|error| error.error.into());
    }

    let backup = path.with_extension("rproj-old");
    let _ = fs::remove_file(&backup);
    fs::rename(path, &backup)
        .with_context(|| format!("failed to prepare replacement for {}", path.display()))?;
    match pending.persist(path) {
        Ok(_) => {
            let _ = fs::remove_file(backup);
            Ok(())
        }
        Err(error) => {
            let _ = fs::rename(&backup, path);
            Err(error.error.into())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::steps::{run_in, wally};
    use tempfile::TempDir;

    fn production() -> Value {
        crate::steps::rojo::project_document(
            "Demo",
            crate::config::PackageWorkflow::Wally,
            false,
            false,
            None,
        )
        .unwrap()
    }

    #[test]
    fn test_project_inherits_production_and_adds_only_test_mounts() {
        let mut source = production();
        source["tree"]["Workspace"] = json!({ "$properties": { "StreamingEnabled": true } });
        let test = project_document(&source).unwrap();
        assert_eq!(test["tree"]["Workspace"], source["tree"]["Workspace"]);
        assert!(test["tree"].get("Lighting").is_none());
        assert_eq!(
            test["tree"]["ServerScriptService"]["$properties"]["LoadStringEnabled"],
            true
        );
        assert_ne!(
            source["tree"]["ServerScriptService"]["$properties"]["LoadStringEnabled"],
            true
        );
        assert_eq!(
            test["tree"]["ReplicatedStorage"]["devPackages"]["$path"],
            "DevPackages"
        );
        assert!(
            source["tree"]["ReplicatedStorage"]
                .get("DevPackages")
                .is_none()
        );
    }

    #[test]
    fn collisions_are_rejected() {
        let mut source = production();
        source["tree"]["ReplicatedStorage"]["devPackages"] = json!({});
        assert!(
            project_document(&source)
                .unwrap_err()
                .to_string()
                .contains("already exists")
        );
    }

    #[test]
    fn refresh_adds_analysis_mount_and_is_repeatable() {
        let dir = TempDir::new().unwrap();
        let source = dir.path().join("default.project.json");
        fs::write(&source, serde_json::to_string(&production()).unwrap()).unwrap();
        refresh_project(dir.path()).unwrap();
        let first = fs::read(&source).unwrap();
        let production: Value = serde_json::from_slice(&first).unwrap();
        assert_eq!(
            production["tree"]["ReplicatedStorage"]["devPackages"]["$path"],
            "DevPackages"
        );
        refresh_project(dir.path()).unwrap();
        assert_eq!(fs::read(&source).unwrap(), first);
        assert!(starter_spec("shared").contains("ReplicatedStorage.devPackages.JestGlobals"));
    }

    #[test]
    fn config_merge_preserves_unknown_fields() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join(CONFIG_FILE),
            r#"{"timeout":123,"test":{"verbose":true}}"#,
        )
        .unwrap();
        let merged: Value = serde_json::from_str(
            &merged_config(dir.path(), crate::graph::JestBackend::Studio).unwrap(),
        )
        .unwrap();
        assert_eq!(merged["timeout"], 123);
        assert_eq!(merged["test"]["verbose"], true);
        assert_eq!(merged["backend"], "studio-cli");
    }

    #[test]
    fn starter_specs_use_explicit_jest_globals() {
        let spec = starter_spec("shared");
        assert!(spec.contains("JestGlobals.describe"));
        assert!(spec.contains("expect(1 + 1).toBe(2)"));
        assert!(!spec.contains("return function()"));
    }

    #[test]
    fn generated_config_uses_inline_projects_for_luau_test_trees() {
        let dir = TempDir::new().unwrap();
        let config: Value = serde_json::from_str(
            &merged_config(dir.path(), crate::graph::JestBackend::Studio).unwrap(),
        )
        .unwrap();
        let projects = config["test"]["projects"].as_array().unwrap();

        assert_eq!(projects.len(), PROJECTS.len());
        for (project, (display_name, include)) in projects.iter().zip(PROJECTS) {
            assert_eq!(project["test"]["displayName"], json!(display_name));
            assert_eq!(project["test"]["include"], json!([include]));
        }
    }

    #[test]
    #[ignore = "requires Wally, Rojo, wally-package-types, jest-roblox, Roblox Studio, and its runner plugin"]
    fn real_jest_stack_installs_validates_retypes_and_executes() {
        use crate::catalog::package_usage;
        let examples = [
            "charm", "reflex", "matter", "sift", "t", "greentea", "janitor", "ripple",
        ];
        let dir = TempDir::new().unwrap();
        for path in ["src/shared", "src/server", "src/client"] {
            fs::create_dir_all(dir.path().join(path)).unwrap();
        }
        let production = production();
        fs::write(
            dir.path().join("default.project.json"),
            format!("{}\n", serde_json::to_string_pretty(&production).unwrap()),
        )
        .unwrap();
        fs::write(
            dir.path().join("wally.toml"),
            wally::render_wally_toml(
                "rproj/jest-validation",
                &["jest", "jest-globals"]
                    .into_iter()
                    .chain(examples)
                    .map(str::to_owned)
                    .collect::<Vec<_>>(),
            )
            .unwrap(),
        )
        .unwrap();
        ensure_test_tree(dir.path(), false).unwrap();
        let mut spec = package_usage::import(
            crate::catalog::wally_packages::find("jest-globals").unwrap(),
            false,
        );
        for key in examples {
            let guide = package_usage::find(key).unwrap();
            spec.push_str(&format!(
                "\nJestGlobals.it(\"catalog {key}\", function()\n{}\nend)\n",
                package_usage::example(&guide)
            ));
        }
        fs::write(dir.path().join("tests/shared/catalog.spec.luau"), spec).unwrap();
        refresh_project(dir.path()).unwrap();
        ensure_config(dir.path(), crate::graph::JestBackend::Studio).unwrap();
        wally::sync_for_project(dir.path(), PROJECT_FILE).unwrap();
        // The ordinary quality gate replaces the Jest sourcemap with this one.
        wally::sync(dir.path()).unwrap();
        let sourcemap = fs::read_to_string(dir.path().join("sourcemap.json")).unwrap();
        assert!(sourcemap.contains("devPackages"));
        assert!(sourcemap.contains("JestGlobals"));
        run_in(
            "jest-roblox-cli",
            &[
                "--backend",
                "studio-cli",
                "--no-color",
                "--formatters",
                "json",
                "--outputFile",
                "report.json",
            ],
            Some(dir.path()),
        )
        .unwrap();
        let report: Value =
            serde_json::from_slice(&fs::read(dir.path().join("report.json")).unwrap()).unwrap();
        assert_eq!(report["numPassedTests"], examples.len(), "{report}");
        assert_eq!(report["numFailedTests"], 0, "{report}");
    }
}