vrc-get 0.2.2

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
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
use crate::version::Version;
use crate::vpm::structs::package::PackageJson;
use crate::vpm::structs::repository::Repository;
use crate::vpm::{AddPackageRequest, download_remote_repository, Environment, PackageInfo, UnityProject, VersionSelector};
use clap::{Parser, Subcommand, Args};
use reqwest::Url;
use serde::Serialize;
use std::collections::HashMap;
use std::error::Error as StdError;
use std::ffi::{OsStr, OsString};
use std::fmt::{Debug, Display};
use std::num::NonZeroU32;
use std::path::{Path, PathBuf};
use std::process::exit;
use std::str::FromStr;
use dialoguer::Confirm;
use indexmap::IndexMap;
use reqwest::header::{HeaderName, HeaderValue, InvalidHeaderName, InvalidHeaderValue};
use tokio::fs::{read_dir, remove_file};
use crate::vpm::structs::setting::UserRepoSetting;

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

// small wrapper utilities

macro_rules! exit_with {
    ($($tt:tt)*) => {{
        eprintln!($($tt)*);
        exit(1)
    }};
}

async fn load_env(client: Option<reqwest::Client>) -> Environment {
    let mut env = Environment::load_default(client)
        .await
        .exit_context("loading global config");

    env.load_package_infos().await.exit_context("loading repositories");
    env.save().await.exit_context("saving repositories updates");

    env
}

async fn load_unity(path: Option<PathBuf>) -> UnityProject {
    UnityProject::find_unity_project(path)
        .await
        .exit_context("loading unity project")
}

fn get_package<'env>(
    env: &'env Environment,
    name: &str,
    version_selector: VersionSelector,
) -> PackageInfo<'env> {
    env.find_package_by_name(&name, version_selector)
        .unwrap_or_else(|| exit_with!("no matching package not found"))
}

async fn mark_and_sweep(unity: &mut UnityProject) {
    for x in unity
        .mark_and_sweep()
        .await
        .exit_context("sweeping unused packages")
    {
        eprintln!("removed {x} which is unused");
    }
}

async fn save_unity(unity: &mut UnityProject) {
    unity.save().await.exit_context("saving manifest file");
}

async fn save_env(env: &mut Environment) {
    env.save().await.exit_context("saving global config");
}

fn confirm_prompt(msg: &str) -> bool {
    Confirm::new().with_prompt(msg).interact().unwrap_or(false)
}

fn print_prompt_install(request: &AddPackageRequest, yes: bool) {
    if request.locked().len() == 0 && request.dependencies().len() == 0 {
        exit_with!("nothing to do")
    }

    let mut prompt = false;

    if request.locked().len() != 0 {
        println!("You're installing the following packages:");
        for x in request.locked() {
            println!("- {} version {}", x.name(), x.version());
        }
        prompt = prompt || request.locked().len() > 1;
    }

    if request.legacy_folders().len() != 0 || request.legacy_files().len() != 0 {
        println!("You're removing the following legacy assets:");
        for x in request.legacy_folders().iter().chain(request.legacy_files()) {
            println!("- {}", x.display());
        }
        prompt = true;
    }

    if prompt {
        if yes {
            println!("--yes is set. skipping confirm");
        } else {
            if !confirm_prompt("Do you want to continue install?") {
                exit(1);
            }
        }
    }
}

trait ResultExt<T, E>: Sized {
    fn exit_context(self, context: &str) -> T
    where
        E: Display;
}

impl<T, E> ResultExt<T, E> for Result<T, E> {
    fn exit_context(self, context: &str) -> T
    where
        E: Display,
    {
        match self {
            Ok(value) => value,
            Err(err) => exit_with!("error {context}: {err}"),
        }
    }
}

/// 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>,
    /// do not connect to remote servers, use local caches only
    #[arg(long)]
    offline: bool,

    /// skip confirm
    #[arg(short, long)]
    yes: bool,
}

impl Install {
    pub async fn run(self) {
        let client = crate::create_client(self.offline);
        let env = load_env(client).await;
        let mut unity = load_unity(self.project).await;

        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 = get_package(&env, &name, version_selector);

            let request = unity.add_package_request(&env, vec![package], true)
                .await
                .exit_context("collecting packages to be installed");

            print_prompt_install(&request, self.yes);

            unity.do_add_package_request(&env, request).await.exit_context("adding package");

            mark_and_sweep(&mut unity).await;
        } else {
            unity.resolve(&env).await.exit_context("resolving packages");
        }

        unity.save().await.exit_context("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 = load_unity(self.project).await;

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

        mark_and_sweep(&mut unity).await;

        save_unity(&mut unity).await;
    }
}

/// 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>,

    /// do not connect to remote servers, use local caches only
    #[arg(long)]
    offline: bool,
}

impl Outdated {
    pub async fn run(self) {
        let client = crate::create_client(self.offline);
        let env = load_env(client).await;
        let unity = load_unity(self.project).await;

        let mut outdated_packages = HashMap::new();

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

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

        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<'a> {
                    package_name: &'a str,
                    installed_version: &'a Version,
                    newer_version: &'a Version,
                }
                let info = outdated_packages
                    .into_iter()
                    .map(|(package_name, (found, installed))| OutdatedInfo {
                        package_name,
                        installed_version: installed,
                        newer_version: found.version(),
                    })
                    .collect::<Vec<_>>();
                println!("{}", serde_json::to_string(&info).unwrap());
            }
            v => exit_with!("unsupported json version: {v}"),
        }
    }
}

/// 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>,
    /// do not connect to remote servers, use local caches only
    #[arg(long)]
    offline: bool,

    /// skip confirm
    #[arg(short, long)]
    yes: bool,
}

impl Upgrade {
    pub async fn run(self) {
        let client = crate::create_client(self.offline);
        let env = load_env(client).await;
        let mut unity = load_unity(self.project).await;

        let updates = 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 = get_package(&env, &name, version_selector);

            vec![package]
        } else {
            let version_selector = match self.prerelease {
                true => VersionSelector::LatestIncluidingPrerelease,
                false => VersionSelector::Latest,
            };

            unity.locked_packages()
                .keys()
                .map(|name| get_package(&env, &name, version_selector))
                .collect()
        };

        let request = unity.add_package_request(&env, updates, false)
            .await
            .exit_context("collecting packages to be upgraded");

        print_prompt_install(&request, self.yes);

        let updates = request.locked().iter().map(|x| (x.name().clone(), x.version().clone())).collect::<Vec<_>>();

        unity.do_add_package_request(&env, request).await.exit_context("upgrading packages");

        for (name, version) in updates {
            println!("upgraded {} to {}", name, version);
        }

        mark_and_sweep(&mut unity).await;
        save_unity(&mut unity).await;
    }
}

/// 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>,

    /// do not connect to remote servers, use local caches only
    #[arg(long)]
    offline: bool,
}

impl Search {
    pub async fn run(self) {
        let client = crate::create_client(self.offline);
        let env = load_env(client).await;

        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)))
            });

        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 {
    /// do not connect to remote servers, use local caches only
    #[arg(long)]
    offline: bool,
}

impl RepoList {
    pub async fn run(self) {
        let client = crate::create_client(self.offline);
        let env = load_env(client).await;

        for (local_path, repo) in env.get_repo_with_path() {
            println!(
                "{}: {} (from {} at {})",
                repo.id().or(repo.url()).unwrap_or("(no id)"),
                repo.name().unwrap_or("(unnamed)"),
                repo.url().unwrap_or("(no remote)"),
                local_path.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>,

    /// Headers
    #[arg(short='H', long, value_parser = HeaderPair::from_str)]
    header: Vec<HeaderPair>,

    /// do not connect to remote servers, use local caches only
    #[arg(long)]
    offline: bool,
}

#[derive(Clone)]
struct HeaderPair(HeaderName, HeaderValue);

impl FromStr for HeaderPair {
    type Err = HeaderPairErr;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (name, value) = s.split_once(":").ok_or(HeaderPairErr::NoComma)?;
        Ok(HeaderPair(name.parse()?, value.parse()?))
    }
}

#[derive(Debug)]
enum HeaderPairErr {
    NoComma,
    HeaderNameErr(InvalidHeaderName),
    HeaderValueErr(InvalidHeaderValue),
}

impl From<InvalidHeaderName> for HeaderPairErr {
    fn from(value: InvalidHeaderName) -> Self {
        Self::HeaderNameErr(value)
    }
}

impl From<InvalidHeaderValue> for HeaderPairErr {
    fn from(value: InvalidHeaderValue) -> Self {
        Self::HeaderValueErr(value)
    }
}

impl Display for HeaderPairErr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HeaderPairErr::NoComma => f.write_str("no ':' found"),
            HeaderPairErr::HeaderNameErr(e) => Display::fmt(e, f),
            HeaderPairErr::HeaderValueErr(e) => Display::fmt(e, f),
        }
    }
}

impl StdError for HeaderPairErr {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            HeaderPairErr::NoComma => None,
            HeaderPairErr::HeaderNameErr(e) => Some(e),
            HeaderPairErr::HeaderValueErr(e) => Some(e),
        }
    }
}

impl RepoAdd {
    pub async fn run(self) {
        let client = crate::create_client(self.offline);
        let mut env = load_env(client).await;

        if let Ok(url) = Url::parse(&self.path_or_url) {
            let mut headers = IndexMap::<String, String>::new();
            for HeaderPair(name, value) in self.header {
                headers.insert(name.to_string(), value.to_str().unwrap().to_string());
            }
            env.add_remote_repo(url, self.name.as_deref(), headers)
                .await
                .exit_context("adding repository")
        } else {
            env.add_local_repo(Path::new(&self.path_or_url), self.name.as_deref())
                .exit_context("adding repository")
        }

        save_env(&mut env).await;
    }
}
/// Remove repository with specified url, path or name
#[derive(Parser)]
#[command(author, version)]
pub struct RepoRemove {
    /// id, url, name, or path of repository
    #[arg()]
    finder: String,

    #[clap(flatten)]
    searcher: RepoSearcherArgs,

    /// do not connect to remote servers, use local caches only
    #[arg(long)]
    offline: bool,
}

#[derive(Args)]
#[group(multiple = false)]
struct RepoSearcherArgs {
    /// Find repository to remove by id
    #[arg(long)]
    id: bool,
    /// Find repository to remove by url
    #[arg(long)]
    url: bool,
    /// Find repository to remove by name
    #[arg(long)]
    name: bool,
    /// Find repository to remove by local path
    #[arg(long)]
    path: bool,
}

impl RepoSearcherArgs {
    fn as_searcher(&self) -> RepoSearcher {
        match () {
            () if self.id => RepoSearcher::Id,
            () if self.url => RepoSearcher::Url,
            () if self.name => RepoSearcher::Name,
            () if self.path => RepoSearcher::Path,
            () => RepoSearcher::Id,
        }
    }
}

#[derive(Copy, Clone)]
enum RepoSearcher {
    Id,
    Url,
    Name,
    Path,
}

impl Display for RepoSearcher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RepoSearcher::Id => f.write_str("id"),
            RepoSearcher::Url => f.write_str("url"),
            RepoSearcher::Name => f.write_str("name"),
            RepoSearcher::Path => f.write_str("path"),
        }
    }
}

impl RepoSearcher {
    fn get(self, repo: &UserRepoSetting) -> Option<&OsStr> {
        match self {
            RepoSearcher::Id => repo.id.as_deref().map(|x| OsStr::new(x)),
            RepoSearcher::Url => repo.url.as_deref().map(|x| OsStr::new(x)),
            RepoSearcher::Name => repo.name.as_deref().map(|x| OsStr::new(x)),
            RepoSearcher::Path => Some(repo.local_path.as_os_str())
        }
    }
}

impl RepoRemove {
    pub async fn run(self) {
        let client = crate::create_client(self.offline);
        let mut env = load_env(client).await;

        // we're using OsStr for paths.
        let finder = OsStr::new(self.finder.as_str());
        let searcher = self.searcher.as_searcher();

        let count = env.remove_repo(|x| searcher.get(x) == Some(finder))
            .await
            .exit_context("removing repository");

        println!("removed {} repositories with {}", count, searcher);

        save_env(&mut env).await;
    }
}

/// 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 {
    /// do not connect to remote servers, use local caches only
    #[arg(long)]
    offline: bool,
}

impl RepoCleanup {
    pub async fn run(self) {
        let client = crate::create_client(self.offline);
        let env = load_env(client).await;

        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().exit_context("reading user repos") {
            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.exit_context("reading dir");
        while let Some(entry) = entry.next_entry().await.exit_context("reading dir") {
            let path = entry.path();
            if tokio::fs::metadata(&path)
                .await
                .map(|x| x.is_file())
                .unwrap_or(false)
                && path.extension() == Some(OsStr::new("json"))
                && !uesr_repo_file_names.contains(&entry.file_name())
            {
                remove_file(path)
                    .await
                    .exit_context("removing unused files");
            }
        }
    }
}

/// List packages in specified repository
#[derive(Parser)]
#[command(author, version)]
pub struct RepoPackages {
    name_or_url: String,

    /// do not connect to remote servers, use local caches only
    #[arg(long)]
    offline: bool,
}

impl RepoPackages {
    pub async fn run(self) {
        fn print_repo<'a>(packages: &Repository) {
            for versions in packages.get_packages() {
                if let Some((_, pkg)) = versions.versions.iter().max_by_key(|(_, pkg)| &pkg.version) {
                    let package = &pkg.name;
                    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(self.offline);

        if let Some(url) = Url::parse(&self.name_or_url).ok() {
            let Some(client) = client else {
                exit_with!("remote repository specified but offline mode.");
            };
            let repo = download_remote_repository(&client, url, None, None)
                .await
                .exit_context("downloading repository")
                .unwrap()
                .0;

            print_repo(&repo);
        } else {
            let env = load_env(client).await;

            let some_name = Some(self.name_or_url.as_str());
            let mut found = false;

            for repo in env.get_repos() {
                if repo.name() == some_name {
                    print_repo(repo.repo());
                    found = true;
                }
            }

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