vrc-get 0.1.6

Open Source command line client of VRChat Package Manager.
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
use crate::version::Version;
use crate::vpm::structs::package::PackageJson;
use crate::vpm::structs::remote_repo::PackageVersions;
use crate::vpm::{download_remote_repository, AddPackageErr, VersionSelector};
use clap::{Parser, Subcommand};
use reqwest::Url;
use serde::Serialize;
use serde_json::{from_value, Map, Value};
use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
use std::num::NonZeroU32;
use std::path::{Path, PathBuf};
use std::process::exit;
use tokio::fs::{read_dir, remove_file};

macro_rules! multi_command {
    ($class: ident is $($variant: ident),*) => {
        impl $class {
            pub async fn run(self) {
                match self {
                    $($class::$variant(cmd) => cmd.run().await,)*
                }
            }
        }
    };
}

/// Open Source command line interface of VRChat Package Manager.
#[derive(Parser)]
#[command(author, version, about)]
pub enum Command {
    #[command(alias = "i", alias = "resolve")]
    Install(Install),
    #[command(alias = "rm")]
    Remove(Remove),
    Outdated(Outdated),
    Upgrade(Upgrade),
    Search(Search),
    #[command(subcommand)]
    Repo(Repo),
}

multi_command!(Command is Install, Remove, Outdated, Upgrade, Search, Repo);

/// Adds package to unity project
///
/// With install command, you'll add to dependencies. With upgrade command,
/// you'll upgrade dependencies or locked dependencies but not add to dependencies.
#[derive(Parser)]
#[command(author, version)]
pub struct Install {
    /// Name of Package
    #[arg()]
    name: Option<String>,
    /// Version of package. if not specified, latest version will be used
    #[arg(id = "VERSION")]
    version: Option<Version>,
    /// Include prerelease
    #[arg(long = "prerelease")]
    prerelease: bool,

    /// Path to project dir. by default CWD or parents of CWD will be used
    #[arg(short = 'p', long = "project")]
    project: Option<PathBuf>,
}

impl Install {
    pub async fn run(self) {
        let client = crate::create_client();
        let env = crate::vpm::Environment::load_default(client)
            .await
            .expect("loading global config");
        let mut unity = crate::vpm::UnityProject::find_unity_project(self.project)
            .await
            .expect("unity project not found");

        if let Some(name) = self.name {
            let version_selector = match self.version {
                None if self.prerelease => VersionSelector::LatestIncluidingPrerelease,
                None => VersionSelector::Latest,
                Some(ref version) => VersionSelector::Specific(version),
            };
            let package = env
                .find_package_by_name(&name, version_selector)
                .await
                .expect("finding package")
                .expect("no matching package not found");
            unity
                .add_package(&env, &package)
                .await
                .expect("adding package");

            for x in unity
                .mark_and_sweep()
                .await
                .expect("sweeping unused packages")
            {
                println!("removed {x} which is unused");
            }
        } else {
            unity.resolve(&env).await.expect("resolving");
        }

        unity.save().await.expect("saving manifest file");
    }
}

/// Remove package from Unity project.
#[derive(Parser)]
#[command(author, version)]
pub struct Remove {
    /// Name of Packages to remove
    #[arg()]
    names: Vec<String>,

    /// Path to project dir. by default CWD or parents of CWD will be used
    #[arg(short = 'p', long = "project")]
    project: Option<PathBuf>,
}

impl Remove {
    pub async fn run(self) {
        let mut unity = crate::vpm::UnityProject::find_unity_project(self.project)
            .await
            .expect("unity project not found");

        unity
            .remove(&self.names.iter().map(String::as_ref).collect::<Vec<_>>())
            .await
            .expect("removing package");

        for x in unity
            .mark_and_sweep()
            .await
            .expect("sweeping unused packages")
        {
            println!("removed {x} which is unused");
        }

        unity.save().await.expect("saving manifest file");
    }
}

/// Show list of outdated packages
#[derive(Parser)]
#[command(author, version)]
pub struct Outdated {
    /// Path to project dir. by default CWD or parents of CWD will be used
    #[arg(short = 'p', long = "project")]
    project: Option<PathBuf>,

    /// With this option, output is printed in json format
    #[arg(long = "json-format")]
    json_format: Option<NonZeroU32>,
}

impl Outdated {
    pub async fn run(self) {
        let client = crate::create_client();
        let env = crate::vpm::Environment::load_default(client)
            .await
            .expect("loading global config");
        let unity = crate::vpm::UnityProject::find_unity_project(self.project)
            .await
            .expect("unity project not found");

        let mut outdated_packages = HashMap::new();

        for (name, dep) in unity.locked_packages() {
            match env
                .find_package_by_name(name, VersionSelector::Latest)
                .await
            {
                Err(e) => log::error!("error loading package {}: {}", name, e),
                Ok(None) => log::error!("package {} not found.", name),
                // if found version is newer: add to outdated
                Ok(Some(pkg)) if dep.version < pkg.version => {
                    outdated_packages.insert(pkg.name.clone(), (pkg, &dep.version));
                }
                Ok(Some(_)) => (),
            }
        }

        for dep in unity.locked_packages().values() {
            for (name, range) in &dep.dependencies {
                if let Some((outdated, _)) = outdated_packages.get(name) {
                    if !range.matches(&outdated.version) {
                        outdated_packages.remove(name);
                    }
                }
            }
        }

        match self.json_format.map(|x| x.get()).unwrap_or(0) {
            0 => {
                for (name, (found, installed)) in &outdated_packages {
                    println!(
                        "{}: installed: {}, found: {}",
                        name, installed, &found.version
                    );
                }
            }
            1 => {
                #[derive(Serialize)]
                struct OutdatedInfo {
                    package_name: String,
                    installed_version: Version,
                    newer_version: Version,
                }
                let info = outdated_packages
                    .into_iter()
                    .map(|(package_name, (found, installed))| OutdatedInfo {
                        package_name,
                        installed_version: installed.clone(),
                        newer_version: found.version,
                    })
                    .collect::<Vec<_>>();
                println!("{}", serde_json::to_string(&info).unwrap());
            }
            v => {
                log::error!("unsupported version: {v}");
                exit(1);
            }
        }
    }
}

/// Upgrade specified package or all packages to latest or specified version.
///
/// With install command, you'll add to dependencies. With upgrade command,
/// you'll upgrade dependencies or locked dependencies but not add to dependencies.
#[derive(Parser)]
#[command(author, version)]
pub struct Upgrade {
    /// Name of Package
    #[arg()]
    name: Option<String>,
    /// Version of package. if not specified, latest version will be used
    #[arg(id = "VERSION")]
    version: Option<Version>,
    /// Include prerelease
    #[arg(long = "prerelease")]
    prerelease: bool,

    /// Path to project dir. by default CWD or parents of CWD will be used
    #[arg(short = 'p', long = "project")]
    project: Option<PathBuf>,
}

impl Upgrade {
    pub async fn run(self) {
        let client = crate::create_client();
        let env = crate::vpm::Environment::load_default(client)
            .await
            .expect("loading global config");
        let mut unity = crate::vpm::UnityProject::find_unity_project(self.project)
            .await
            .expect("unity project not found");

        if let Some(name) = self.name {
            let version_selector = match self.version {
                None if self.prerelease => VersionSelector::LatestIncluidingPrerelease,
                None => VersionSelector::Latest,
                Some(ref version) => VersionSelector::Specific(version),
            };
            let package = env
                .find_package_by_name(&name, version_selector)
                .await
                .expect("finding package")
                .expect("no matching package not found");

            unity
                .upgrade_package(&env, &package)
                .await
                .expect("upgrading package");

            println!("upgraded {} to {}", name, package.version);
        } else {
            let version_selector = match self.prerelease {
                true => VersionSelector::LatestIncluidingPrerelease,
                false => VersionSelector::Latest,
            };
            let package_names = unity.locked_packages().keys().cloned().collect::<Vec<_>>();
            for name in package_names {
                let package = env
                    .find_package_by_name(&name, version_selector)
                    .await
                    .expect("finding package")
                    .expect("no matching package not found");

                match unity.upgrade_package(&env, &package).await {
                    Ok(_) => {
                        println!("upgraded {} to {}", name, package.version);
                    }
                    Err(AddPackageErr::Io(e)) => log::error!("upgrading package: {}", e),
                    Err(AddPackageErr::AlreadyNewerPackageInstalled) => {}
                    Err(AddPackageErr::ConflictWithDependencies {
                        dependency_name, ..
                    }) => {
                        log::warn!(
                            "upgrading {} to {}: conflicts with {}",
                            name,
                            package.version,
                            dependency_name
                        );
                    }
                    Err(AddPackageErr::DependencyNotFound {
                        dependency_name, ..
                    }) => {
                        log::error!(
                            "upgrading {} to {}: dependencies of it {} not found",
                            name,
                            package.version,
                            dependency_name
                        );
                    }
                }
            }
        }

        for x in unity
            .mark_and_sweep()
            .await
            .expect("sweeping unused packages")
        {
            println!("removed {x} which is unused");
        }

        unity.save().await.expect("saving manifest file");
    }
}

/// Search package by the query
///
/// Search for packages that includes query in either name, displayName, or description.
#[derive(Parser)]
#[command(author, version)]
pub struct Search {
    /// Name of Package
    #[arg(required = true, name = "QUERY")]
    queries: Vec<String>,
}

impl Search {
    pub async fn run(self) {
        let client = crate::create_client();
        let env = crate::vpm::Environment::load_default(client)
            .await
            .expect("loading global config");

        let mut queries = self.queries;
        for query in &mut queries {
            query.make_ascii_lowercase();
        }

        fn search_targets(pkg: &PackageJson) -> Vec<String> {
            let mut sources = Vec::with_capacity(3);

            sources.push(pkg.name.as_str().to_ascii_lowercase());
            sources.extend(pkg.display_name.as_deref().map(|x| x.to_ascii_lowercase()));
            sources.extend(pkg.description.as_deref().map(|x| x.to_ascii_lowercase()));

            sources
        }

        let found_packages = env
            .find_whole_all_packages(|pkg| {
                // filtering
                let search_targets = search_targets(pkg);

                queries
                    .iter()
                    .all(|query| search_targets.iter().any(|x| x.contains(query)))
            })
            .await
            .expect("finding package");

        if found_packages.is_empty() {
            println!("No matching package found!")
        } else {
            for x in found_packages {
                if let Some(name) = x.display_name {
                    println!("{} version {}", name, x.version);
                    println!("({})", x.name);
                } else {
                    println!("{} version {}", x.name, x.version);
                }
                if let Some(description) = x.description {
                    println!("{}", description);
                }
                println!();
            }
        }
    }
}

/// Commands around repositories
#[derive(Subcommand)]
#[command(author, version)]
pub enum Repo {
    List(RepoList),
    Add(RepoAdd),
    Remove(RepoRemove),
    Cleanup(RepoCleanup),
    Packages(RepoPackages),
}

multi_command!(Repo is List, Add, Remove, Cleanup, Packages);

/// List all repositories
#[derive(Parser)]
#[command(author, version)]
pub struct RepoList {}

impl RepoList {
    pub async fn run(self) {
        let client = crate::create_client();
        let env = crate::vpm::Environment::load_default(client)
            .await
            .expect("loading global config");

        for repo in env.get_repos().await.expect("getting repo list") {
            let mut name = None;
            let mut r#type = None;
            let mut local_path = None;
            if let Some(description) = &repo.description {
                name = name.or(description.name.as_deref());
                r#type = r#type.or(description.r#type.as_deref());
            }
            if let Some(creation_info) = &repo.creation_info {
                name = name.or(creation_info.name.as_deref());
                local_path = local_path.or(creation_info.local_path.as_deref());
            }
            println!(
                "{} | {} (at {})",
                name.unwrap_or("(unnamed)"),
                r#type.unwrap_or("(unknown type)"),
                local_path.unwrap_or(Path::new("(unknown)")).display(),
            );
        }
    }
}

/// Add remote or local repository
#[derive(Parser)]
#[command(author, version)]
pub struct RepoAdd {
    /// URL of Package
    #[arg()]
    path_or_url: String,
    /// Name of Package
    #[arg()]
    name: Option<String>,
}

impl RepoAdd {
    pub async fn run(self) {
        let client = crate::create_client();
        let mut env = crate::vpm::Environment::load_default(client)
            .await
            .expect("loading global config");

        if let Ok(url) = Url::parse(&self.path_or_url) {
            env.add_remote_repo(url, self.name.as_deref())
                .await
                .expect("adding repository")
        } else {
            env.add_local_repo(Path::new(&self.path_or_url), self.name.as_deref())
                .await
                .expect("adding repository")
        }

        env.save().await.expect("saving settings file");
    }
}

/// Remove repository with specified url, path or name
#[derive(Parser)]
#[command(author, version)]
pub struct RepoRemove {
    /// URL of Package
    #[arg()]
    name_or_url: String,
}

impl RepoRemove {
    pub async fn run(self) {
        let client = crate::create_client();
        let mut env = crate::vpm::Environment::load_default(client)
            .await
            .expect("loading global config");

        let removed = if let Ok(url) = Url::parse(&self.name_or_url) {
            env.remove_repo(|x| x.url.as_deref() == Some(url.as_str()))
                .await
                .expect("removing based on url")
        } else {
            let path = Path::new(&self.name_or_url);
            env.remove_repo(|x| x.local_path.as_path() == path)
                .await
                .expect("removing based on path")
        };

        if !removed {
            env.remove_repo(|x| x.name.as_deref() == Some(self.name_or_url.as_str()))
                .await
                .expect("removing based on name");
        }

        env.save().await.expect("saving settings file");
    }
}

/// Cleanup repositories in Repos directory
///
/// The official VPM CLI will add <uuid>.json in the Repos directory even if error occurs.
/// So this command will cleanup Repos directory.
#[derive(Parser)]
#[command(author, version)]
pub struct RepoCleanup {}

impl RepoCleanup {
    pub async fn run(self) {
        let client = crate::create_client();
        let env = crate::vpm::Environment::load_default(client)
            .await
            .expect("loading global config");

        let mut uesr_repo_file_names = vec![
            OsString::from("vrc-official.json"),
            OsString::from("vrc-curated.json"),
        ];
        let repos_base = env.get_repos_dir();

        for x in env.get_user_repos().expect("userRepos") {
            if let Ok(relative) = x.local_path.strip_prefix(&repos_base) {
                if let Some(file_name) = relative.file_name() {
                    if relative
                        .parent()
                        .map(|x| x.as_os_str().is_empty())
                        .unwrap_or(true)
                    {
                        // the file must be in direct child of
                        uesr_repo_file_names.push(file_name.to_owned());
                    }
                }
            }
        }

        let mut entry = read_dir(repos_base).await.expect("reading dir");
        while let Some(entry) = entry.next_entry().await.expect("reading dir") {
            let path = entry.path();
            if tokio::fs::metadata(&path)
                .await
                .expect("metadata")
                .is_file()
                && path.extension() == Some(OsStr::new("json"))
                && !uesr_repo_file_names.contains(&entry.file_name())
            {
                remove_file(path).await.expect("reading dir");
            }
        }
    }
}

/// Remove repository from user repositories.
#[derive(Parser)]
#[command(author, version)]
pub struct RepoPackages {
    name_or_url: String,
}

impl RepoPackages {
    pub async fn run(self) {
        fn print_repo(cache: Map<String, Value>) {
            for (package, value) in cache {
                let versions = from_value::<PackageVersions>(value).expect("loading package data");
                if let Some((_, pkg)) = versions.versions.first() {
                    if let Some(display_name) = &pkg.display_name {
                        println!("{} | {}", display_name, package);
                    } else {
                        println!("{}", package);
                    }
                    if let Some(description) = &pkg.description {
                        println!("{}", description);
                    }
                    for (version, pkg) in &versions.versions {
                        println!("{}: {}", version, pkg.url);
                    }
                    println!();
                }
            }
        }

        let client = crate::create_client();

        if let Some(url) = Url::parse(&self.name_or_url).ok() {
            let repo = download_remote_repository(&client, url, None)
                .await
                .expect("downloading repository")
                .expect("logic failure: no etag")
                .0;

            let cache = repo
                .get("packages")
                .and_then(Value::as_object)
                .cloned()
                .unwrap_or(Map::<String, Value>::new());

            print_repo(cache);
        } else {
            let env = crate::vpm::Environment::load_default(client)
                .await
                .expect("loading global config");
            let some_name = Some(self.name_or_url.as_str());
            let mut found = false;

            for repo in env.get_repos().await.expect("listing packages") {
                if repo.creation_info.as_ref().and_then(|x| x.name.as_deref()) == some_name
                    || repo.description.as_ref().and_then(|x| x.name.as_deref()) == some_name
                {
                    print_repo(repo.cache.clone());
                    found = true;
                }
            }

            if !found {
                eprintln!("no repository named {} found!", self.name_or_url);
                exit(1);
            }
        }
    }
}