luaupm 0.2.0

The Luau package manager: dependencies, tools and scripts for Luau and Roblox projects
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
pub mod edit;

use crate::error::Error;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
use std::path::Path;

pub const MANIFEST_FILE: &str = "lpm.toml";

/// [indices] key used for dependencies that name no index.
pub const DEFAULT_INDEX_NAME: &str = "default";

/** lpm's own package index, the fallback for dependencies naming no index when
the project defines no `default` one. pesde-format entries whose `download` URLs
point at the registry CDN; written only by the lpm API at publish time, read by
the CLI like any other git index. */
pub const DEFAULT_INDEX_URL: &str = "https://github.com/luaupm/index";

#[derive(Serialize, Deserialize, Debug)]
pub struct Manifest {
    pub package: Package,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<Target>,
    #[serde(default, skip_serializing_if = "Config::is_default")]
    pub config: Config,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub indices: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub dependencies: BTreeMap<String, Dependency>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub tools: BTreeMap<String, Tool>,
    /// shell commands runnable with `lpm run <name>`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub scripts: BTreeMap<String, String>,
    /// what `lpm studio open` opens in Roblox Studio.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub studio: Option<Studio>,
}

/// per-environment install locations; each defaults to "packages/<env>".
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Config {
    #[serde(
        rename = "shared-packages-out",
        skip_serializing_if = "Option::is_none"
    )]
    pub shared_packages_out: Option<String>,
    #[serde(
        rename = "server-packages-out",
        skip_serializing_if = "Option::is_none"
    )]
    pub server_packages_out: Option<String>,
    #[serde(rename = "lune-packages-out", skip_serializing_if = "Option::is_none")]
    pub lune_packages_out: Option<String>,
    #[serde(rename = "luau-packages-out", skip_serializing_if = "Option::is_none")]
    pub luau_packages_out: Option<String>,
    #[serde(rename = "lute-packages-out", skip_serializing_if = "Option::is_none")]
    pub lute_packages_out: Option<String>,
}

impl Config {
    fn is_default(&self) -> bool {
        self.shared_packages_out.is_none()
            && self.server_packages_out.is_none()
            && self.lune_packages_out.is_none()
            && self.luau_packages_out.is_none()
            && self.lute_packages_out.is_none()
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Package {
    pub name: String,
    pub version: String,
    /** never published. workspace roots that only exist to hold members set this
    so publish skips them (chief's root manifest is the archetype). */
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub private: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub authors: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repository: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub license: Option<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Target {
    pub environment: Environment,
    /** entry point, e.g. "src/init.luau". not needed when `workspace` is set,
    a workspace root has no code of its own to require. */
    #[serde(skip_serializing_if = "Option::is_none")]
    pub main: Option<String>,
    /// member globs (relative to this manifest): `workspace = ["packages/*"]`
    /// (`!` negates, literal "." includes the root). having members makes this
    /// a workspace root; publish/install there run for every member. pesde's
    /// spelling `workspace_members` is accepted as an alias. read through
    /// [`Manifest::workspace_members`].
    #[serde(
        rename = "workspace",
        alias = "workspace_members",
        default,
        skip_serializing_if = "Vec::is_empty"
    )]
    pub workspace: Vec<String>,
    /// what goes into the published archive: plain file/dir paths (a dir
    /// covers everything under it) or globs like `src/*`. empty = "everything
    /// sensible", the default walk minus VCS/output dirs.
    #[serde(default, alias = "include", skip_serializing_if = "Vec::is_empty")]
    pub includes: Vec<String>,
    /** subtracted from whatever `includes` (or the default walk) selected; same
    path-or-glob entries. lpm.toml always ships. */
    #[serde(default, alias = "exclude", skip_serializing_if = "Vec::is_empty")]
    pub excludes: Vec<String>,
}

/// where a package's Luau code runs. output folders under packages/ use the serialized (lowercase) form.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[serde(rename_all = "lowercase")]
pub enum Environment {
    /// Luau code that must run in Roblox
    Shared,
    /// Roblox server-side only
    Server,
    /// needs the Lune runtime
    Lune,
    /// standalone Luau, runnable with the luau CLI
    Luau,
    /// needs the Lute runtime
    Lute,
}

impl Environment {
    pub const ALL: [Environment; 5] = [
        Environment::Shared,
        Environment::Server,
        Environment::Lune,
        Environment::Luau,
        Environment::Lute,
    ];

    pub fn dir_name(self) -> &'static str {
        match self {
            Environment::Shared => "shared",
            Environment::Server => "server",
            Environment::Lune => "lune",
            Environment::Luau => "luau",
            Environment::Lute => "lute",
        }
    }

    /// translates a pesde `target.environment` value.
    pub fn from_pesde(environment: &str) -> Result<Self, Error> {
        match environment {
            "roblox" => Ok(Environment::Shared),
            "roblox_server" => Ok(Environment::Server),
            "lune" => Ok(Environment::Lune),
            "luau" => Ok(Environment::Luau),
            "lute" => Ok(Environment::Lute),
            other => Err(Error::UnsupportedEnvironment(other.to_string())),
        }
    }

    /// translates a wally `realm` value.
    pub fn from_wally_realm(realm: &str) -> Result<Self, Error> {
        match realm {
            "shared" => Ok(Environment::Shared),
            "server" => Ok(Environment::Server),
            other => Err(Error::UnsupportedEnvironment(other.to_string())),
        }
    }

    /// parses lpm's own environment names ("shared", "lune", ...).
    pub fn from_lpm(environment: &str) -> Result<Self, Error> {
        match environment {
            "shared" => Ok(Environment::Shared),
            "server" => Ok(Environment::Server),
            "lune" => Ok(Environment::Lune),
            "luau" => Ok(Environment::Luau),
            "lute" => Ok(Environment::Lute),
            other => Err(Error::UnsupportedEnvironment(other.to_string())),
        }
    }
}

impl fmt::Display for Environment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.dir_name())
    }
}

/// the [studio] table: either a published place (both IDs) or a local place file.
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Studio {
    /// universe (experience) ID the place belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub universe: Option<u64>,
    /// place ID inside the universe.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub place: Option<u64>,
    /// path to a .rbxl/.rbxlx place file, relative to lpm.toml.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<String>,
    /** anything else written under [studio]. the table gets hand-edited a lot and
    a typo'd key would otherwise read as "unconfigured", so `target()` reports
    these. only there, though: `deny_unknown_fields` would let a [studio] typo
    fail unrelated commands. */
    #[serde(flatten)]
    pub unknown: BTreeMap<String, toml::Value>,
}

/// a validated [studio] table: the one thing `lpm studio open` should open.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StudioTarget {
    /// published place, opened through the roblox-studio: protocol.
    Place { universe: u64, place: u64 },
    /// local place file, opened through the OS file association.
    File(String),
}

impl Studio {
    /// reduces the table to what to open. everything that can be wrong with a hand-written [studio] gets caught here, before any launch attempt.
    pub fn target(&self) -> Result<StudioTarget, Error> {
        if let Some((key, _)) = self.unknown.first_key_value() {
            return Err(Error::StudioUnknownKey(key.clone()));
        }
        if self.file.is_some() && (self.universe.is_some() || self.place.is_some()) {
            return Err(Error::StudioConflict);
        }

        match (self.file.as_deref(), self.universe, self.place) {
            (Some(file), ..) => {
                let file = file.trim();
                if file.is_empty() {
                    return Err(Error::StudioEmptyFile);
                }
                Ok(StudioTarget::File(file.to_string()))
            }
            (None, Some(universe), Some(place)) => {
                for (key, id) in [("universe", universe), ("place", place)] {
                    if id == 0 {
                        return Err(Error::StudioInvalidId(key));
                    }
                }
                Ok(StudioTarget::Place { universe, place })
            }
            (None, Some(_), None) => Err(Error::StudioIncomplete {
                has: "universe",
                needs: "place",
            }),
            (None, None, Some(_)) => Err(Error::StudioIncomplete {
                has: "place",
                needs: "universe",
            }),
            (None, None, None) => Err(Error::StudioUnconfigured),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum Dependency {
    /// package from an index: `{ name = "scope/pkg", version = "^", index = "wally" }`.
    Registry {
        /// "scope/name" identifier.
        name: String,
        /// semver requirement; "^" alone means "latest".
        version: String,
        /// key into [indices]; None means the default luaupm index.
        #[serde(skip_serializing_if = "Option::is_none")]
        index: Option<String>,
    },
    /** another member of this workspace, pesde-style:
    `{ workspace = "scope/pkg", version = "^" }`. linked in place during
    development; `version` is a version TYPE (`^`, `~`, `=`, `*`) or a full
    requirement, applied to the member's current version only at publish time
    (see [`workspace_version_req`]). */
    Workspace {
        workspace: String,
        #[serde(default = "default_workspace_version")]
        version: String,
    },
}

fn default_workspace_version() -> String {
    "^".to_string()
}

/** the registry requirement a workspace dependency publishes as, pesde's rules
exactly: `^`/`~`/`=` prefix the member's current version (`^` + `1.2.3` ->
`^1.2.3`), `*` stays "any", anything else must already be a full semver
requirement and passes through unchanged. */
pub fn workspace_version_req(
    version: &str,
    member_version: &semver::Version,
) -> Result<String, Error> {
    let version = version.trim();
    Ok(match version {
        "*" => "*".to_string(),
        "" | "^" => format!("^{member_version}"),
        "~" => format!("~{member_version}"),
        "=" => format!("={member_version}"),
        other => {
            semver::VersionReq::parse(other)?;
            other.to_string()
        }
    })
}

/// a GitHub-released binary tool, written in lpm.toml as the single string "owner/repo@version" under [tools] (key = alias).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tool {
    /// "owner/repo" GitHub repository.
    pub repository: String,
    /// exact release version, no leading 'v'.
    pub version: String,
}

impl Tool {
    /// parses an "owner/repo@version" tool spec.
    pub fn parse(spec: &str) -> Result<Self, Error> {
        let invalid = || Error::InvalidToolSpec(spec.to_string());

        let (repository, version) = spec.trim().split_once('@').ok_or_else(invalid)?;
        if version.is_empty() || version.contains('@') {
            return Err(invalid());
        }
        Self::split_repository(repository).map_err(|_| invalid())?;

        Ok(Tool {
            repository: repository.to_string(),
            version: version.to_string(),
        })
    }

    /** splits an "owner/repo" GitHub repository name. unlike index package names
    (see `split_package_name`), GitHub owners/repos may contain uppercase and dots
    ("JohnnyMorganz/StyLua"), so only the shape is validated: exactly one '/',
    both halves non-empty. */
    pub fn split_repository(repository: &str) -> Result<(&str, &str), Error> {
        match repository.split_once('/') {
            Some((owner, repo)) if !owner.is_empty() && !repo.is_empty() && !repo.contains('/') => {
                Ok((owner, repo))
            }
            _ => Err(Error::InvalidToolSpec(repository.to_string())),
        }
    }
}

impl fmt::Display for Tool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}@{}", self.repository, self.version)
    }
}

impl Serialize for Tool {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for Tool {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let spec = String::deserialize(deserializer)?;
        Tool::parse(&spec).map_err(serde::de::Error::custom)
    }
}

impl Manifest {
    /// loads the manifest from the current directory.
    pub fn load() -> Result<Self, Error> {
        Self::load_from(Path::new(MANIFEST_FILE))
    }

    /// member globs from [target] workspace. empty = not a workspace root.
    pub fn workspace_members(&self) -> &[String] {
        self.target
            .as_ref()
            .map(|target| target.workspace.as_slice())
            .unwrap_or(&[])
    }

    pub fn load_from(path: &Path) -> Result<Self, Error> {
        if !path.exists() {
            return Err(Error::ManifestMissing);
        }
        Ok(toml::from_str(&std::fs::read_to_string(path)?)?)
    }

    /// folder an environment's packages (and their link files) install to.
    pub fn packages_out(&self, environment: Environment) -> std::path::PathBuf {
        let configured = match environment {
            Environment::Shared => &self.config.shared_packages_out,
            Environment::Server => &self.config.server_packages_out,
            Environment::Lune => &self.config.lune_packages_out,
            Environment::Luau => &self.config.luau_packages_out,
            Environment::Lute => &self.config.lute_packages_out,
        };
        match configured {
            Some(dir) => std::path::PathBuf::from(dir),
            None => std::path::Path::new("packages").join(environment.dir_name()),
        }
    }

    /** resolves a dependency's `index` key to an index URL. no key = the `default`
    entry under [indices] when the project defines one, lpm's own index otherwise. */
    pub fn index_url(&self, index: Option<&str>) -> Result<&str, Error> {
        match index {
            None => Ok(self
                .indices
                .get(DEFAULT_INDEX_NAME)
                .map(String::as_str)
                .unwrap_or(DEFAULT_INDEX_URL)),
            Some(key) => self
                .indices
                .get(key)
                .map(String::as_str)
                .ok_or_else(|| Error::UnknownIndex(key.to_string())),
        }
    }

    /// the command a `[scripts]` entry runs. read side only, used by `lpm run`; edits go through `edit::ManifestDoc`.
    pub fn script(&self, name: &str) -> Result<&str, Error> {
        self.scripts
            .get(name)
            .map(String::as_str)
            .ok_or_else(|| Error::ScriptMissing(name.to_string()))
    }
}

/** shape of a GitHub username: 1-39 chars, alphanumeric or dashes, no leading/
trailing/consecutive dash. `[package] authors` must pass this: the registry
appends authors to the scope's owner list on publish (co-ownership) and 400s
anything that isn't a username. shape only; account existence is never checked,
so typos still bite. */
pub fn is_github_username(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 39
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
        && !name.starts_with('-')
        && !name.ends_with('-')
        && !name.contains("--")
}

/// splits a "scope/name" package identifier. wally allows dashes, so parts accept lowercase letters, digits, dashes, underscores.
pub fn split_package_name(name: &str) -> Result<(&str, &str), Error> {
    let is_valid_part = |part: &str| {
        !part.is_empty()
            && part
                .chars()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
    };

    match name.split('/').collect::<Vec<_>>().as_slice() {
        [scope, package] if is_valid_part(scope) && is_valid_part(package) => Ok((scope, package)),
        _ => Err(Error::InvalidPackageName(name.to_string())),
    }
}

/// parses a manifest version requirement. bare "^" (or "*") means "latest".
pub fn parse_version_req(req: &str) -> Result<semver::VersionReq, Error> {
    let trimmed = req.trim();
    if trimmed == "^" || trimmed == "*" || trimmed.is_empty() {
        Ok(semver::VersionReq::STAR)
    } else {
        Ok(semver::VersionReq::parse(trimmed)?)
    }
}

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

    #[test]
    fn parses_full_manifest() {
        let manifest: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"
            authors = ["Someone"]
            license = "MIT"

            [target]
            environment = "lune"
            main = "src/init.luau"

            [indices]
            wally = "https://github.com/UpliftGames/wally-index"

            [dependencies]
            Chief = { name = "chief/core", version = "^" }
            Other = { name = "user/other_package", version = "^", index = "wally" }

            [tools]
            stylua = "johnnymorganz/stylua@2.0.0"
            StyLua = "JohnnyMorganz/StyLua@2.1.0"

            [scripts]
            build = "rojo build -o game.rbxl"
            "#,
        )
        .unwrap();

        assert_eq!(manifest.package.name, "scope/name");
        assert_eq!(
            manifest.target.as_ref().unwrap().environment,
            Environment::Lune
        );
        assert!(matches!(
            &manifest.dependencies["Chief"],
            Dependency::Registry { index: None, .. }
        ));
        assert!(matches!(
            &manifest.dependencies["Other"],
            Dependency::Registry { index: Some(index), .. } if index == "wally"
        ));
        assert_eq!(manifest.tools["stylua"].repository, "johnnymorganz/stylua");
        assert_eq!(manifest.tools["stylua"].version, "2.0.0");
        assert_eq!(manifest.tools["StyLua"].repository, "JohnnyMorganz/StyLua");
        assert_eq!(manifest.tools["StyLua"].version, "2.1.0");
        assert_eq!(manifest.script("build").unwrap(), "rojo build -o game.rbxl");
        assert!(matches!(
            manifest.script("test"),
            Err(Error::ScriptMissing(_))
        ));
    }

    #[test]
    fn resolves_index_urls() {
        let manifest: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"

            [indices]
            wally = "https://example.com/wally-index"
            "#,
        )
        .unwrap();

        // no `default` key: bare deps fall back to lpm's own index.
        assert_eq!(manifest.index_url(None).unwrap(), DEFAULT_INDEX_URL);
        assert_eq!(
            manifest.index_url(Some("wally")).unwrap(),
            "https://example.com/wally-index"
        );
        assert!(matches!(
            manifest.index_url(Some("missing")),
            Err(Error::UnknownIndex(_))
        ));
    }

    #[test]
    fn default_index_key_resolves_bare_dependencies() {
        let manifest: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"

            [indices]
            default = "https://example.com/my-index"
            "#,
        )
        .unwrap();

        assert_eq!(
            manifest.index_url(None).unwrap(),
            "https://example.com/my-index"
        );
    }

    #[test]
    fn packages_out_defaults_and_overrides() {
        let manifest: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"

            [config]
            shared-packages-out = "src/ReplicatedStorage/Packages"
            "#,
        )
        .unwrap();

        assert_eq!(
            manifest.packages_out(Environment::Shared),
            std::path::PathBuf::from("src/ReplicatedStorage/Packages")
        );
        assert_eq!(
            manifest.packages_out(Environment::Luau),
            std::path::PathBuf::from("packages").join("luau")
        );
        assert_eq!(
            manifest.packages_out(Environment::Lute),
            std::path::PathBuf::from("packages").join("lute")
        );
    }

    #[test]
    fn translates_environments() {
        assert_eq!(
            Environment::from_pesde("roblox").unwrap(),
            Environment::Shared
        );
        assert_eq!(
            Environment::from_pesde("roblox_server").unwrap(),
            Environment::Server
        );
        assert_eq!(Environment::from_pesde("lune").unwrap(), Environment::Lune);
        assert!(Environment::from_pesde("nonsense").is_err());
        assert_eq!(
            Environment::from_wally_realm("shared").unwrap(),
            Environment::Shared
        );
        assert_eq!(
            Environment::from_wally_realm("server").unwrap(),
            Environment::Server
        );
        assert!(Environment::from_wally_realm("lune").is_err());
    }

    #[test]
    fn parses_workspace_manifests_and_dependencies() {
        /* the chief repo's shape: private root listing member globs, members
        depending on each other with workspace specifiers. */
        let root: Manifest = toml::from_str(
            r#"
            [package]
            name = "chief/root"
            version = "0.0.0"
            private = true

            [target]
            environment = "shared"
            workspace = ["packages/*", "!packages/legacy"]
            "#,
        )
        .unwrap();
        assert!(root.package.private);
        // a root needs a [target] but no `main`; members carry the code.
        assert!(root.target.as_ref().unwrap().main.is_none());
        assert_eq!(root.workspace_members(), ["packages/*", "!packages/legacy"]);

        // pesde's spelling still parses so converted repos keep working.
        let aliased: Manifest = toml::from_str(
            r#"
            [package]
            name = "chief/root"
            version = "0.0.0"

            [target]
            environment = "shared"
            workspace_members = ["packages/*"]
            "#,
        )
        .unwrap();
        assert_eq!(aliased.workspace_members(), ["packages/*"]);

        let member: Manifest = toml::from_str(
            r#"
            [package]
            name = "chief/dependencies"
            version = "0.1.0"

            [dependencies]
            core = { workspace = "chief/core", version = "^" }
            pinned = { workspace = "chief/bin" }
            "#,
        )
        .unwrap();
        assert!(matches!(
            &member.dependencies["core"],
            Dependency::Workspace { workspace, version }
                if workspace == "chief/core" && version == "^"
        ));
        // version defaults to "^", pesde's default version type.
        assert!(matches!(
            &member.dependencies["pinned"],
            Dependency::Workspace { version, .. } if version == "^"
        ));

        // not-a-workspace manifests don't accidentally gain the fields.
        let plain: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"
            "#,
        )
        .unwrap();
        assert!(!plain.package.private);
        assert!(plain.workspace_members().is_empty());
        let serialized = toml::to_string(&plain).unwrap();
        assert!(!serialized.contains("private"));
        assert!(!serialized.contains("workspace"));
    }

    #[test]
    fn workspace_version_reqs_follow_pesde_rules() {
        let version = semver::Version::new(2, 1, 5);
        assert_eq!(workspace_version_req("^", &version).unwrap(), "^2.1.5");
        assert_eq!(workspace_version_req("~", &version).unwrap(), "~2.1.5");
        assert_eq!(workspace_version_req("=", &version).unwrap(), "=2.1.5");
        assert_eq!(workspace_version_req("*", &version).unwrap(), "*");
        assert_eq!(workspace_version_req("", &version).unwrap(), "^2.1.5");
        // a full requirement passes through unchanged.
        assert_eq!(workspace_version_req("^2.1.0", &version).unwrap(), "^2.1.0");
        assert!(workspace_version_req("not a req", &version).is_err());
    }

    #[test]
    fn recognizes_github_username_shapes() {
        for name in ["octocat", "Luau-PM", "a", "user123", "x-1-y"] {
            assert!(is_github_username(name), "{name:?} should be accepted");
        }
        for name in [
            "",
            "-octocat",
            "octocat-",
            "double--dash",
            "with space",
            "name@example.com",
            "Jane Doe <jane@example.com>",
            "under_score",
            &"a".repeat(40),
        ] {
            assert!(!is_github_username(name), "{name:?} should be rejected");
        }
    }

    #[test]
    fn splits_package_names() {
        assert_eq!(
            split_package_name("evaera/promise").unwrap(),
            ("evaera", "promise")
        );
        assert_eq!(
            split_package_name("scope/pkg-name_2").unwrap(),
            ("scope", "pkg-name_2")
        );
        assert!(split_package_name("noslash").is_err());
        assert!(split_package_name("Upper/case").is_err());
        assert!(split_package_name("a/b/c").is_err());
    }

    #[test]
    fn parses_tool_specs() {
        let tool = Tool::parse("  JohnnyMorganz/StyLua@2.0.0  ").unwrap();
        assert_eq!(tool.repository, "JohnnyMorganz/StyLua");
        assert_eq!(tool.version, "2.0.0");
        assert_eq!(tool.to_string(), "JohnnyMorganz/StyLua@2.0.0");
    }

    #[test]
    fn rejects_invalid_tool_specs() {
        for spec in [
            "norepo@1.0",
            "owner/repo",
            "owner/repo@",
            "a/b/c@1.0",
            "@1.0",
            "owner/@1.0",
            "/repo@1.0",
            "owner/repo@1.0@2.0",
            "",
        ] {
            assert!(
                matches!(Tool::parse(spec), Err(Error::InvalidToolSpec(_))),
                "spec {spec:?} should be rejected"
            );
        }
    }

    #[test]
    fn tool_round_trips_through_toml() {
        #[derive(Serialize, Deserialize)]
        struct Tools {
            stylua: Tool,
        }

        let tools = Tools {
            stylua: Tool {
                repository: "JohnnyMorganz/StyLua".to_string(),
                version: "2.0.0".to_string(),
            },
        };
        let serialized = toml::to_string(&tools).unwrap();
        assert_eq!(
            serialized.trim(),
            r#"stylua = "JohnnyMorganz/StyLua@2.0.0""#
        );
        let parsed: Tools = toml::from_str(&serialized).unwrap();
        assert_eq!(parsed.stylua, tools.stylua);
    }

    #[test]
    fn includes_and_excludes_round_trip() {
        let manifest: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"

            [target]
            environment = "luau"
            includes = ["src", "lpm.toml", "README.md"]
            excludes = ["src/tests"]
            "#,
        )
        .unwrap();

        let target = manifest.target.as_ref().unwrap();
        assert_eq!(target.includes, ["src", "lpm.toml", "README.md"]);
        assert_eq!(target.excludes, ["src/tests"]);

        let serialized = toml::to_string(&manifest).unwrap();
        let parsed: Manifest = toml::from_str(&serialized).unwrap();
        let reparsed = parsed.target.as_ref().unwrap();
        assert_eq!(reparsed.includes, target.includes);
        assert_eq!(reparsed.excludes, target.excludes);

        // the singular spellings parse too.
        let aliased: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"

            [target]
            environment = "luau"
            include = ["src"]
            exclude = ["tests"]
            "#,
        )
        .unwrap();
        assert_eq!(aliased.target.as_ref().unwrap().includes, ["src"]);
        assert_eq!(aliased.target.as_ref().unwrap().excludes, ["tests"]);

        // absent lists stay absent on write.
        let bare: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"

            [target]
            environment = "luau"
            "#,
        )
        .unwrap();
        assert!(bare.target.as_ref().unwrap().includes.is_empty());
        let serialized = toml::to_string(&bare).unwrap();
        assert!(!serialized.contains("includes"));
        assert!(!serialized.contains("excludes"));
    }

    #[test]
    fn parses_studio_place_ids() {
        let manifest: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"

            [studio]
            universe = 13058
            place = 1818
            "#,
        )
        .unwrap();

        assert_eq!(
            manifest.studio.unwrap().target().unwrap(),
            StudioTarget::Place {
                universe: 13058,
                place: 1818
            }
        );
    }

    #[test]
    fn parses_studio_file() {
        let manifest: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"

            [studio]
            file = "place.rbxl"
            "#,
        )
        .unwrap();

        assert_eq!(
            manifest.studio.unwrap().target().unwrap(),
            StudioTarget::File("place.rbxl".to_string())
        );
    }

    #[test]
    fn studio_target_catches_hand_edit_mistakes() {
        let studio = |universe, place, file: Option<&str>| Studio {
            universe,
            place,
            file: file.map(str::to_string),
            ..Default::default()
        };

        // both forms at once is ambiguous, even with only half the IDs.
        assert!(matches!(
            studio(Some(1), Some(2), Some("a.rbxl")).target(),
            Err(Error::StudioConflict)
        ));
        assert!(matches!(
            studio(Some(1), None, Some("a.rbxl")).target(),
            Err(Error::StudioConflict)
        ));

        // one ID without the other.
        assert!(matches!(
            studio(Some(1), None, None).target(),
            Err(Error::StudioIncomplete {
                has: "universe",
                needs: "place"
            })
        ));
        assert!(matches!(
            studio(None, Some(2), None).target(),
            Err(Error::StudioIncomplete {
                has: "place",
                needs: "universe"
            })
        ));

        // nothing at all, zero IDs, blank file path.
        assert!(matches!(
            studio(None, None, None).target(),
            Err(Error::StudioUnconfigured)
        ));
        assert!(matches!(
            studio(Some(0), Some(2), None).target(),
            Err(Error::StudioInvalidId("universe"))
        ));
        assert!(matches!(
            studio(Some(1), Some(0), None).target(),
            Err(Error::StudioInvalidId("place"))
        ));
        assert!(matches!(
            studio(None, None, Some("   ")).target(),
            Err(Error::StudioEmptyFile)
        ));

        // surrounding whitespace in the path is tolerated.
        assert_eq!(
            studio(None, None, Some(" place.rbxl ")).target().unwrap(),
            StudioTarget::File("place.rbxl".to_string())
        );
    }

    #[test]
    fn studio_flags_unknown_keys_without_failing_the_manifest() {
        /* a typo'd key must not break `Manifest::load` (that would take
        install/add/run down with it), but `target()` names it. */
        let manifest: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"

            [studio]
            universeId = 13058
            place = 1818
            "#,
        )
        .unwrap();

        assert!(matches!(
            manifest.studio.unwrap().target(),
            Err(Error::StudioUnknownKey(key)) if key == "universeId"
        ));
    }

    #[test]
    fn studio_stays_absent_when_unset() {
        let manifest: Manifest = toml::from_str(
            r#"
            [package]
            name = "scope/name"
            version = "0.1.0"
            "#,
        )
        .unwrap();
        assert!(manifest.studio.is_none());
        assert!(!toml::to_string(&manifest).unwrap().contains("studio"));
    }

    #[test]
    fn parses_version_requirements() {
        let latest = parse_version_req("^").unwrap();
        assert!(latest.matches(&semver::Version::new(99, 0, 0)));
        let caret = parse_version_req("^1.2").unwrap();
        assert!(caret.matches(&semver::Version::new(1, 9, 0)));
        assert!(!caret.matches(&semver::Version::new(2, 0, 0)));
        assert!(parse_version_req("not a version").is_err());
    }
}