rproj 0.15.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Project decision graph. It records intent, derives tools/files/packages,
//! and stays independent of prompting or filesystem work. See
//! `docs/architecture.md` ยง3b.

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use crate::catalog::artifacts::{self, Environment, Planned};
use crate::catalog::capabilities;
use crate::config::PackageWorkflow;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TestRunner {
    TestEz,
    JestRoblox,
}

/// One editable decision. Ordered as they are asked, which is also the
/// order they constrain each other in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Node {
    Strategy,
    Packages,
    Capabilities,
    Files,
}

impl Node {
    pub const ALL: [Node; 4] = [
        Node::Strategy,
        Node::Packages,
        Node::Capabilities,
        Node::Files,
    ];

    pub fn label(&self) -> &'static str {
        match self {
            Node::Strategy => "dependencies",
            Node::Packages => "packages",
            Node::Capabilities => "capabilities",
            Node::Files => "files",
        }
    }

    /// What re-answering this node makes stale.
    ///
    /// **The whole invalidation model, and it is four rows.** Changing the
    /// strategy can make a chosen package unvendorable, so the packages go;
    /// anything upstream of the file list makes the file list stale. What is
    /// *absent* matters as much: the strategy does not touch capabilities
    /// (linting does not care where packages come from), and packages do not
    /// touch the strategy, which is what stopped React silently switching a
    /// project to Wally.
    pub fn invalidates(&self) -> &'static [Node] {
        match self {
            Node::Strategy => &[Node::Packages, Node::Files],
            Node::Packages => &[Node::Files],
            Node::Capabilities => &[Node::Files],
            Node::Files => &[],
        }
    }
}

/// Everything `rproj new` decided, and everything `rproj upgrade` needs to
/// decide it again.
///
/// Field order is load-bearing for TOML: `capabilities` serialises as a
/// `[capabilities]` table, and TOML requires every bare key to precede the
/// first table header. A test round-trips this rather than trusting it.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProjectGraph {
    /// How the packages were chosen: `guided`, `expert`, `none`, or
    /// `like:<setup>`. A decision in its own right, so it lives here.
    #[serde(default)]
    pub mode: String,
    #[serde(default = "wally")]
    pub package_workflow: PackageWorkflow,
    #[serde(default)]
    pub packages: Vec<String>,
    /// Artifacts declined at the summary. Recorded so `rproj upgrade` does
    /// not helpfully restore a file the user deliberately removed.
    #[serde(default)]
    pub dropped: Vec<String>,
    /// Capability key -> the implementation actually used.
    ///
    /// Concrete rather than `Option`, deliberately: the file records what
    /// this project *has*, so a later change to which implementation is the
    /// default cannot silently re-point an existing project at a different
    /// test runner.
    #[serde(default)]
    pub capabilities: BTreeMap<String, String>,
}

fn wally() -> PackageWorkflow {
    PackageWorkflow::Wally
}

impl ProjectGraph {
    /// Records a capability choice, resolving `None` to whatever the default
    /// implementation is *now* so the file never carries an ambiguity.
    pub fn choose(&mut self, capability: &str, implementation: Option<&str>) {
        let Some(entry) = capabilities::find(capability) else {
            return;
        };
        let resolved = implementation
            .and_then(|key| entry.implementation(key))
            .unwrap_or_else(|| entry.default_implementation());
        self.capabilities
            .insert(entry.key.to_string(), resolved.key.to_string());
    }

    /// The `(capability, implementation)` pairs the catalog's `derive` takes.
    pub fn choices(&self) -> Vec<(String, Option<String>)> {
        let mut choices = Vec::new();
        for (key, implementation) in &self.capabilities {
            let key = key.to_string();
            if choices
                .iter()
                .any(|(existing, _): &(String, Option<String>)| existing == &key)
            {
                continue;
            }
            choices.push((key, Some(implementation.clone())));
        }
        choices
    }

    pub fn capability_keys(&self) -> Vec<String> {
        self.choices().into_iter().map(|(key, _)| key).collect()
    }

    pub fn package_set(&self) -> BTreeSet<String> {
        self.packages.iter().cloned().collect()
    }

    pub fn derived(&self) -> capabilities::Derived {
        capabilities::derive(&self.choices())
    }

    pub fn test_runner(&self) -> Option<TestRunner> {
        let key = match self.capabilities.get("test") {
            Some(key) => key,
            None if self.packages.iter().any(|package| package == "testez") => {
                return Some(TestRunner::TestEz);
            }
            None => return None,
        };
        Some(match key.as_str() {
            "jest-roblox" => TestRunner::JestRoblox,
            // TestEZ is deliberately the compatibility fallback for stale
            // implementation keys and manifests from before implementations.
            _ => TestRunner::TestEz,
        })
    }

    pub fn testing_is_compatible(&self) -> bool {
        self.test_runner() != Some(TestRunner::JestRoblox)
            || self.package_workflow == PackageWorkflow::Wally
    }

    pub fn remove_incompatible_testing(&mut self) -> bool {
        if self.testing_is_compatible() {
            return false;
        }
        self.capabilities.remove("test");
        true
    }

    /// Every tool this project pins: what the capabilities need, plus what
    /// the dependency strategy needs.
    ///
    /// Wally is not a capability - nobody wants "Wally", they want their
    /// packages installed - so it is derived from the strategy that actually
    /// needs it. Merged here rather than at the call sites so `rokit.toml`,
    /// the check script and the summary cannot disagree about the list.
    pub fn tools(&self) -> Vec<String> {
        let mut tools = self.derived().tools;
        for tool in strategy_tools(self.package_workflow, self.packages.is_empty()) {
            if !tools.iter().any(|t| t == tool) {
                tools.push((*tool).to_string());
            }
        }
        tools
    }

    pub fn strategy(&self) -> artifacts::Strategy {
        match self.package_workflow {
            PackageWorkflow::Wally => artifacts::Strategy::Wally,
            PackageWorkflow::GitSubmodules => artifacts::Strategy::GitSubmodules,
            PackageWorkflow::None => artifacts::Strategy::None,
        }
    }

    /// The files this project gets, each with the reason it gets them.
    pub fn plan(&self, apps: &[String], extensions: &[String]) -> Vec<Planned> {
        let environment = Environment {
            apps,
            extensions,
            strategy: self.strategy(),
        };
        artifacts::plan(
            &environment,
            &self.capability_keys(),
            &self.derived().artifacts,
            &self.tools(),
            &self.dropped,
        )
    }

    /// The plan for **maintaining** a project, as opposed to creating one.
    ///
    /// `rproj upgrade` must not consult the machine. A `.vscode/settings.json`
    /// that exists is a file this project asked for; whether *this* machine
    /// has VS Code installed today says nothing about that, and you might be
    /// upgrading on a different machine than you scaffolded on. So the app and
    /// extension conditions are treated as satisfied here, while the
    /// capability and strategy conditions - which are properties of the
    /// project rather than of the desk it is sitting on - still apply.
    pub fn maintenance_plan(&self) -> Vec<Planned> {
        let (apps, extensions) = artifacts::every_machine_requirement();
        self.plan(&apps, &extensions)
    }

    /// The plan with nothing dropped - what `customize` offers, so a file
    /// removed once can be restored without restarting the command.
    pub fn full_plan(&self, apps: &[String], extensions: &[String]) -> Vec<Planned> {
        let mut undropped = self.clone();
        undropped.dropped.clear();
        undropped.plan(apps, extensions)
    }

    /// Clears whatever re-answering `node` made stale.
    ///
    /// The packages are cleared rather than filtered on a strategy change:
    /// the user is about to be asked again, and silently keeping the subset
    /// that survives would be a third party editing their answer.
    pub fn invalidate(&mut self, node: Node) {
        for stale in node.invalidates() {
            match stale {
                Node::Strategy => self.package_workflow = PackageWorkflow::Wally,
                Node::Packages => self.packages.clear(),
                Node::Capabilities => self.capabilities.clear(),
                Node::Files => self.dropped.clear(),
            }
        }
    }
}

/// The tools the **dependency strategy** pins, as opposed to the ones
/// capabilities pin.
///
/// `wally-package-types` travels with `wally` because a plain `wally install`
/// writes link files with no `export type` lines, so without it every
/// package silently degrades to `any`.
///
/// Empty with no packages: a manifest with nothing in it needs no installer.
/// Empty under submodules: there is no `wally.toml` to install from and no
/// thunks to retype, so pinning either would be noise in `rokit.toml`.
pub fn strategy_tools(workflow: PackageWorkflow, no_packages: bool) -> &'static [&'static str] {
    match workflow {
        PackageWorkflow::Wally if !no_packages => &["wally", "wally-package-types"],
        _ => &[],
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn graph(workflow: PackageWorkflow, packages: &[&str], caps: &[&str]) -> ProjectGraph {
        let mut g = ProjectGraph {
            mode: "expert".into(),
            package_workflow: workflow,
            packages: packages.iter().map(|p| p.to_string()).collect(),
            ..Default::default()
        };
        for key in caps {
            g.choose(key, None);
        }
        g
    }

    // ---------------------------------------------------------------
    // Invalidation - the reason this is a graph and not a wizard.
    // ---------------------------------------------------------------

    /// Changing the strategy clears the packages, because some may no longer
    /// be vendorable - but leaves the capabilities alone, because linting
    /// does not care where packages come from.
    #[test]
    fn changing_the_strategy_invalidates_packages_but_not_capabilities() {
        let mut g = graph(PackageWorkflow::Wally, &["react"], &["lint", "format"]);
        g.dropped.push(".gitignore".into());

        g.invalidate(Node::Strategy);

        assert!(g.packages.is_empty(), "packages must be re-asked");
        assert!(
            g.dropped.is_empty(),
            "the file list is downstream of everything"
        );
        assert_eq!(
            g.capability_keys(),
            ["format", "lint"],
            "capabilities are orthogonal"
        );
    }

    /// Everything upstream of the file list makes the file list stale, and
    /// nothing else does.
    #[test]
    fn only_the_file_list_is_downstream_of_everything() {
        for node in [Node::Strategy, Node::Packages, Node::Capabilities] {
            assert!(
                node.invalidates().contains(&Node::Files),
                "{:?} must invalidate the file list",
                node
            );
        }
        assert!(
            Node::Files.invalidates().is_empty(),
            "nothing is downstream of files"
        );
    }

    /// Invalidation must only ever point *forward*, or re-answering one node
    /// could clear an answer the user gave before it - which is the "go back
    /// three screens and lose your work" behaviour this replaces.
    #[test]
    fn invalidation_only_points_forward() {
        for (i, node) in Node::ALL.iter().enumerate() {
            for stale in node.invalidates() {
                let at = Node::ALL.iter().position(|n| n == stale).expect("in ALL");
                assert!(
                    at > i,
                    "{node:?} invalidates {stale:?}, which comes before it"
                );
            }
        }
    }

    #[test]
    fn changing_capabilities_keeps_the_packages() {
        let mut g = graph(PackageWorkflow::Wally, &["reflex"], &["lint"]);
        g.invalidate(Node::Capabilities);
        assert_eq!(g.packages, ["reflex"], "packages are upstream");
    }

    // ---------------------------------------------------------------
    // Derivation.
    // ---------------------------------------------------------------

    #[test]
    fn a_capability_choice_is_recorded_concretely() {
        let g = graph(PackageWorkflow::None, &[], &["lint"]);
        assert_eq!(
            g.capabilities.get("lint").map(String::as_str),
            Some("selene")
        );
    }

    #[test]
    fn an_unknown_capability_is_not_recorded() {
        let mut g = ProjectGraph::default();
        g.choose("teleportation", None);
        assert!(g.capabilities.is_empty());
    }

    #[test]
    fn tools_merge_the_capability_and_strategy_halves() {
        let g = graph(PackageWorkflow::Wally, &["reflex"], &["lint", "gate"]);
        let tools = g.tools();
        assert!(tools.contains(&"selene".to_string()), "{tools:?}");
        assert!(tools.contains(&"lute".to_string()), "{tools:?}");
        assert!(tools.contains(&"wally".to_string()), "{tools:?}");
        assert!(
            tools.contains(&"wally-package-types".to_string()),
            "{tools:?}"
        );
    }

    #[test]
    fn a_wally_project_with_no_packages_pins_no_installer() {
        let g = graph(PackageWorkflow::Wally, &[], &[]);
        assert!(g.tools().is_empty(), "{:?}", g.tools());
    }

    #[test]
    fn submodule_projects_never_pin_wally() {
        let g = graph(PackageWorkflow::GitSubmodules, &["charm"], &["lint"]);
        assert!(
            !g.tools().iter().any(|t| t.starts_with("wally")),
            "{:?}",
            g.tools()
        );
    }

    /// The bare project, from the graph rather than from the command.
    #[test]
    fn an_empty_graph_plans_only_the_basics_and_housekeeping() {
        let g = graph(PackageWorkflow::None, &[], &[]);
        let keys: Vec<&str> = g.plan(&[], &[]).iter().map(|p| p.key).collect();
        assert_eq!(
            keys,
            ["src", "default.project.json", "rproj.toml", ".gitignore"]
        );
    }

    /// And `dropped` reaches the housekeeping entries, so the absolute
    /// minimum stays reachable.
    #[test]
    fn dropping_housekeeping_leaves_only_the_mandatory_two() {
        let mut g = graph(PackageWorkflow::None, &[], &[]);
        g.dropped = vec!["rproj.toml".into(), ".gitignore".into()];
        let keys: Vec<&str> = g.plan(&[], &[]).iter().map(|p| p.key).collect();
        assert_eq!(keys, ["src", "default.project.json"]);
    }

    /// `customize` has to offer what was dropped, or removing a file would
    /// make it unrecoverable without restarting the command.
    #[test]
    fn the_full_plan_ignores_what_was_dropped() {
        let mut g = graph(PackageWorkflow::None, &[], &[]);
        g.dropped = vec![".gitignore".into()];
        let full: Vec<&str> = g.full_plan(&[], &[]).iter().map(|p| p.key).collect();
        assert!(full.contains(&".gitignore"), "{full:?}");
    }

    // ---------------------------------------------------------------
    // Persistence.
    // ---------------------------------------------------------------

    /// TOML requires bare keys to precede the first `[table]` header, and
    /// `capabilities` is a table. Field order in the struct is what puts it
    /// last, so this asserts the file is valid rather than trusting it.
    #[test]
    fn the_graph_round_trips_through_toml() {
        let mut g = graph(
            PackageWorkflow::GitSubmodules,
            &["charm", "vide"],
            &["lint", "test"],
        );
        g.dropped = vec![".gitignore".into()];

        let text = toml::to_string_pretty(&g).expect("serialise");
        let back: ProjectGraph = toml::from_str(&text).expect("parse back");
        assert_eq!(back.package_workflow, PackageWorkflow::GitSubmodules);
        assert_eq!(back.packages, ["charm", "vide"]);
        assert_eq!(back.dropped, [".gitignore"]);
        assert_eq!(back.capability_keys(), ["lint", "test"]);
        assert_eq!(
            back.capabilities.get("test").map(String::as_str),
            Some("testez")
        );
    }

    #[test]
    fn changing_away_from_wally_removes_only_jest() {
        let mut graph = graph(PackageWorkflow::Wally, &[], &["lint"]);
        graph.choose("test", Some("jest-roblox"));
        graph.package_workflow = PackageWorkflow::None;
        assert!(graph.remove_incompatible_testing());
        assert!(graph.capabilities.contains_key("lint"));
        assert!(!graph.capabilities.contains_key("test"));

        graph.choose("test", Some("testez"));
        assert!(!graph.remove_incompatible_testing());
        assert_eq!(graph.test_runner(), Some(TestRunner::TestEz));
    }

    #[test]
    fn package_only_legacy_manifests_keep_testez() {
        let graph = graph(PackageWorkflow::Wally, &["testez"], &[]);
        assert_eq!(graph.test_runner(), Some(TestRunner::TestEz));
    }

    #[test]
    fn selected_test_runner_does_not_plan_its_peer_files() {
        let testez = graph(PackageWorkflow::Wally, &[], &["test"]);
        let testez_files: Vec<&str> = testez
            .plan(&[], &[])
            .into_iter()
            .map(|artifact| artifact.key)
            .collect();
        assert!(testez_files.contains(&"tests"));
        assert!(!testez_files.contains(&"jest.project.json"));

        let mut jest = ProjectGraph {
            package_workflow: PackageWorkflow::Wally,
            ..Default::default()
        };
        jest.choose("test", Some("jest-roblox"));
        let jest_files: Vec<&str> = jest
            .plan(&[], &[])
            .into_iter()
            .map(|artifact| artifact.key)
            .collect();
        assert!(jest_files.contains(&"jest.project.json"));
        assert!(!jest_files.contains(&"testez.yml"));
    }
}