wasmer-cli 7.2.0-alpha.2

Wasmer CLI
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
use crate::{
    commands::{
        AsyncCliCommand,
        package::common::{macros::*, wait::wait_package, *},
    },
    config::WasmerEnv,
};
use anyhow::Context;
use colored::Colorize;
use dialoguer::{Confirm, theme::ColorfulTheme};
use std::io::IsTerminal as _;
use std::{
    path::{Path, PathBuf},
    str::FromStr,
};
use wasmer_backend_api::WasmerClient;
use wasmer_config::package::{
    Manifest, NamedPackageId, NamedPackageIdent, PackageBuilder, PackageHash, PackageIdent,
};

use super::PublishWait;

/// Tag an existing package.
#[derive(Debug, clap::Parser)]
pub struct PackageTag {
    #[clap(flatten)]
    pub env: WasmerEnv,

    /// Run the publish logic without sending anything to the registry server
    #[clap(long, name = "dry-run")]
    pub dry_run: bool,

    /// Run the publish command without any output
    #[clap(long)]
    pub quiet: bool,

    /// Override the namespace of the package to upload
    #[clap(long = "namespace")]
    pub package_namespace: Option<String>,

    /// Override the name of the package to upload
    #[clap(long = "name")]
    pub package_name: Option<String>,

    /// Override the package version of the uploaded package in the wasmer.toml
    #[clap(long = "version")]
    pub package_version: Option<semver::Version>,

    /// Timeout (in seconds) for the publish query to the registry.
    ///
    /// Note that this is not the timeout for the entire publish process, but
    /// for each individual query to the registry during the publish flow.
    #[clap(long, default_value = "5m")]
    pub timeout: humantime::Duration,

    /// Whether or not the patch field of the version of the package - if any - should be bumped.
    #[clap(long, conflicts_with = "package_version")]
    pub bump: bool,

    /// Do not prompt for user input.
    #[clap(long, default_value_t = !std::io::stdin().is_terminal())]
    pub non_interactive: bool,

    /// The hash of the package to tag
    #[clap(name = "hash")]
    pub package_hash: PackageHash,

    /// The package to tag.
    #[clap(name = "package_ident")]
    pub package_id: Option<NamedPackageIdent>,

    /// Directory containing the `wasmer.toml`, or a custom *.toml manifest file.
    ///
    /// Defaults to current working directory.
    #[clap(long = "path", default_value = ".")]
    pub package_path: PathBuf,

    /// Wait for package to be available on the registry before exiting.
    #[clap(
            long,
            require_equals = true,
            num_args = 0..=1,
            default_value_t = PublishWait::None,
            default_missing_value = "container",
            value_enum
        )]
    pub wait: PublishWait,
}

impl PackageTag {
    async fn update_manifest_name(
        &self,
        manifest_path: Option<&Path>,
        manifest: Option<&Manifest>,
        full_name: &str,
    ) -> anyhow::Result<Option<Manifest>> {
        if manifest_path.is_none() && manifest.is_none() {
            return Ok(None);
        }

        let mut new_manifest = manifest.cloned().unwrap();
        let manifest_path = manifest_path.unwrap();

        if let Some(pkg) = &mut new_manifest.package {
            pkg.name = Some(full_name.to_string());
        } else {
            let package = PackageBuilder::default().name(full_name).build()?;
            new_manifest.package = Some(package);
        }

        let manifest_raw = toml::to_string(&new_manifest)?;

        tokio::fs::write(manifest_path, manifest_raw)
            .await
            .context("while trying to serialize the manifest")?;

        Ok(Some(new_manifest))
    }

    async fn update_manifest_version(
        &self,
        manifest_path: Option<&Path>,
        manifest: Option<&Manifest>,
        user_version: &semver::Version,
    ) -> anyhow::Result<Option<Manifest>> {
        if manifest_path.is_none() && manifest.is_none() {
            return Ok(None);
        }

        let mut new_manifest = manifest.cloned().unwrap();
        let manifest_path = manifest_path.unwrap();

        if let Some(pkg) = &mut new_manifest.package {
            pkg.version = Some(user_version.clone());
        } else {
            let package = PackageBuilder::default()
                .version(user_version.clone())
                .build()?;
            new_manifest.package = Some(package);
        }

        let manifest_raw = toml::to_string(&new_manifest)?;

        tokio::fs::write(manifest_path, manifest_raw)
            .await
            .context("while trying to serialize the manifest")?;

        Ok(Some(new_manifest))
    }

    #[tracing::instrument]
    async fn do_tag(
        &self,
        client: &WasmerClient,
        id: &NamedPackageId,
        manifest: Option<&Manifest>,
        package_release_id: &wasmer_backend_api::types::Id,
    ) -> anyhow::Result<()> {
        tracing::info!(
            "Tagging package with registry id {:?} and specifier {:?}",
            package_release_id,
            id
        );

        let pb = make_spinner!(self.quiet, "Tagging package...");

        let NamedPackageId { full_name, version } = id;
        let maybe_description = manifest
            .and_then(|m| m.package.as_ref())
            .and_then(|p| p.description.clone());
        let maybe_homepage = manifest
            .and_then(|m| m.package.as_ref())
            .and_then(|p| p.homepage.clone());
        let maybe_license = manifest
            .and_then(|m| m.package.as_ref())
            .and_then(|p| p.license.clone());
        let maybe_license_file = manifest
            .and_then(|m| m.package.as_ref())
            .and_then(|p| p.license_file.clone())
            .map(|f| f.to_string_lossy().to_string());
        let maybe_readme = manifest
            .and_then(|m| m.package.as_ref())
            .and_then(|p| p.readme.clone())
            .map(|f| f.to_string_lossy().to_string());
        let maybe_repository = manifest
            .and_then(|m| m.package.as_ref())
            .and_then(|p| p.repository.clone());

        let private = if let Some(pkg) = &manifest.and_then(|m| m.package.as_ref()) {
            Some(pkg.private)
        } else {
            Some(false)
        };

        let version = version.to_string();

        let manifest_raw = if let Some(manifest) = manifest {
            Some(toml::to_string(&manifest)?)
        } else {
            None
        };

        let maybe_readme_content = match maybe_readme {
            Some(readme) => {
                let readme_path = self.package_path.join(&readme);
                if readme_path.exists() {
                    Some(tokio::fs::read_to_string(readme_path).await?)
                } else {
                    None
                }
            }
            None => None,
        };

        let r = wasmer_backend_api::query::tag_package_release(
            client,
            maybe_description.as_deref(),
            maybe_homepage.as_deref(),
            maybe_license.as_deref(),
            maybe_license_file.as_deref(),
            manifest_raw.as_deref(),
            full_name,
            None,
            package_release_id,
            private,
            maybe_readme_content.as_deref(),
            maybe_repository.as_deref(),
            &version,
        );

        match r.await? {
            Some(r) => {
                if r.success {
                    spinner_ok!(pb, format!("Successfully tagged package {id}"));
                    if let Some(package_version) = r.package_version {
                        wait_package(client, self.wait, package_version.id, self.timeout).await?;
                    }
                    Ok(())
                } else {
                    spinner_err!(pb, "Could not tag package!");
                    anyhow::bail!("An unknown error occurred and the tagging failed.")
                }
            }
            None => {
                spinner_err!(pb, "Could not tag package!");
                anyhow::bail!("The registry returned an empty response.")
            }
        }
    }

    async fn get_package_id(
        &self,
        client: &WasmerClient,
        hash: &PackageHash,
        check_package_exists: bool,
    ) -> anyhow::Result<wasmer_backend_api::types::Id> {
        let pb = make_spinner!(
            self.quiet || check_package_exists,
            "Checking if the package exists.."
        );

        tracing::debug!("Searching for package with hash: {hash}");

        let pkg = match wasmer_backend_api::query::get_package_release(client, &hash.to_string())
            .await?
        {
            Some(p) => p,
            None => {
                spinner_err!(pb, "The package is not in the registry!");
                if !self.quiet {
                    eprintln!(
                        "\n\nThe package with the required hash does not exist in the selected registry."
                    );
                    let bin_name = bin_name!();
                    let cli = std::env::args()
                        .filter(|s| !s.starts_with('-'))
                        .collect::<Vec<String>>()
                        .join(" ");

                    if cli.contains("publish") && self.dry_run {
                        eprintln!(
                            "{}: you are running `{cli}` with `--dry-run` set.\n",
                            "HINT".bold()
                        );
                    } else {
                        eprintln!(
                            "To first push the package to the registry, run `{}`.",
                            format!("{bin_name} package push").bold()
                        );
                        eprintln!(
                            "{}: you can also use `{}` to push {} tag your package.\n",
                            "NOTE".bold(),
                            format!("{bin_name} package publish").bold(),
                            "and".italic()
                        );
                    }
                }
                anyhow::bail!("Can't tag, no matching package found in the registry.")
            }
        };

        spinner_ok!(
            pb,
            format!(
                "Found package in the registry ({})",
                hash.to_string()
                    .trim_start_matches("sha256:")
                    .chars()
                    .take(7)
                    .collect::<String>()
            )
        );

        Ok(pkg.id)
    }

    fn get_name(
        &self,
        manifest: Option<&Manifest>,
        allow_unnamed: bool,
    ) -> anyhow::Result<Option<String>> {
        if let Some(name) = &self.package_id.as_ref().map(|id| id.name.clone()) {
            return Ok(Some(name.clone()));
        }

        // REMOVE ME: This is here for backwards compatibility, but we should remove the flag.
        if let Some(name) = &self.package_name {
            return Ok(Some(name.clone()));
        }

        if let Some(pkg) = &manifest.and_then(|m| m.package.as_ref())
            && let Some(ns) = &pkg.name
            && let Some(name) = ns.split('/').nth(1)
        {
            return Ok(Some(name.to_string()));
        }

        if allow_unnamed {
            return Ok(None);
        }

        if self.non_interactive {
            // if not interactive we can't prompt the user to choose the owner of the app.
            anyhow::bail!("No package name specified: use --name <package_name>");
        }

        let default_name = std::env::current_dir().ok().and_then(|dir| {
            dir.file_name()
                .and_then(|f| f.to_str())
                .map(|s| s.to_owned())
        });

        crate::utils::prompts::prompt_for_ident("Choose a package name", default_name.as_deref())
            .map(Some)
    }

    async fn get_namespace(
        &self,
        client: &WasmerClient,
        manifest: Option<&Manifest>,
    ) -> anyhow::Result<String> {
        if let Some(namespace) = self.package_id.as_ref().and_then(|id| id.namespace.clone()) {
            return Ok(namespace);
        }

        // REMOVE ME: This is here for backwards compatibility, but we should remove the flag.
        if let Some(namespace) = &self.package_namespace {
            return Ok(namespace.clone());
        }

        if let Some(pkg) = manifest.and_then(|m| m.package.clone())
            && let Some(name) = &pkg.name
            && let Some(ns) = name.split('/').next()
        {
            return Ok(ns.to_string());
        }

        if self.non_interactive {
            // if not interactive we can't prompt the user to choose the owner of the app.
            anyhow::bail!("No package namespace specified: use --namespace <package_namespace>");
        }

        let user = wasmer_backend_api::query::current_user_with_namespaces(client, None).await?;
        crate::utils::prompts::prompt_for_namespace("Choose a namespace", None, Some(&user))
    }

    async fn get_version(
        &mut self,
        client: &WasmerClient,
        manifest: Option<&Manifest>,
        manifest_path: Option<&Path>,
        full_pkg_name: &str,
    ) -> anyhow::Result<semver::Version> {
        if let Some(wasmer_config::package::Tag::VersionReq(r)) =
            self.package_id.as_ref().and_then(|id| id.tag.clone())
        {
            let mut version = r.to_string();
            version.remove(0);
            let version = semver::Version::parse(&version)?;
            return Ok(version);
        }

        // REMOVE ME: This is here for backwards compatibility, but we should remove the flag.
        if let Some(version) = &self.package_version {
            // If a user specified a version, then they meant it.
            return Ok(version.clone());
        }

        let user_version = if let Some(pkg) = manifest.and_then(|m| m.package.as_ref()) {
            pkg.version.clone()
        } else {
            None
        };

        let pb = make_spinner!(
            self.quiet,
            format!("Checking if a version of {full_pkg_name} already exists..")
        );

        if let Some(registry_version) = wasmer_backend_api::query::get_package_version(
            client,
            full_pkg_name.to_string(),
            String::from("latest"),
        )
        .await?
        .map(|p| p.version)
        .and_then(|v| semver::Version::from_str(&v).ok())
        {
            spinner_ok!(
                pb,
                format!("Found version {registry_version} of {full_pkg_name}")
            );

            let mut user_version = if let Some(v) = user_version {
                v
            } else {
                registry_version.clone()
            };

            // Must necessarily bump if there's a package with the chosen version with a different hash.
            let must_bump = {
                let maybe_pkg = wasmer_backend_api::query::get_package_version(
                    client,
                    full_pkg_name.to_string(),
                    user_version.to_string(),
                )
                .await?;
                let maybe_hash = maybe_pkg
                    .as_ref()
                    .and_then(|p| p.distribution_v3.pirita_sha256_hash.clone());

                if let Some(hash) = maybe_hash {
                    let registry_package_hash = PackageHash::from_str(&format!("sha256:{hash}"))?;
                    registry_package_hash != self.package_hash
                } else {
                    false
                }
            };

            if user_version <= registry_version {
                if self.bump {
                    user_version = registry_version.clone();
                    user_version.patch = registry_version.patch + 1;
                } else if !self.non_interactive {
                    let theme = ColorfulTheme::default();
                    let mut new_version = registry_version.clone();
                    new_version.patch += 1;
                    if must_bump {
                        eprintln!(
                            "{}: Registry already has version {user_version} of {full_pkg_name}, but with different contents.",
                            "Warn".bold().yellow()
                        );
                        eprintln!(
                            "{}: Not bumping the version will make this action fail.",
                            "Warn".bold().yellow()
                        );
                        let res = Confirm::with_theme(&theme)
                            .with_prompt(format!("Continue ({user_version} -> {new_version})?"))
                            .interact()?;
                        if res {
                            user_version = new_version.clone();
                            self.update_manifest_version(manifest_path, manifest, &user_version)
                                .await?;
                        } else {
                            anyhow::bail!(
                                "Refusing to map two different releases of {full_pkg_name} to the same version."
                            )
                        }
                    } else {
                        let res = Confirm::with_theme(&theme)
                        .with_prompt(format!("Do you want to bump the package's version ({user_version} -> {new_version})?"))
                            .interact()?;
                        if res {
                            user_version = new_version.clone();
                            self.update_manifest_version(manifest_path, manifest, &user_version)
                                .await?;
                        }
                    }
                }
            }

            Ok(user_version)
        } else {
            pb.finish_and_clear();

            match user_version {
                Some(v) => Ok(v),
                None => {
                    if self.non_interactive {
                        anyhow::bail!(
                            "No package version specified: use --version <package_version>"
                        )
                    } else {
                        let version = crate::utils::prompts::prompt_for_package_version(
                            "Enter the package version",
                            Some("0.1.0"),
                        )?;

                        self.update_manifest_version(manifest_path, manifest, &version)
                            .await?;

                        Ok(version)
                    }
                }
            }
        }
    }

    async fn synthesize_id(
        &mut self,
        client: &WasmerClient,
        manifest: Option<&Manifest>,
        manifest_path: Option<&Path>,
        allow_unnamed: bool,
    ) -> anyhow::Result<Option<NamedPackageId>> {
        let name = match self.get_name(manifest, allow_unnamed)? {
            Some(name) => name,
            None => return Ok(None),
        };

        let namespace = self.get_namespace(client, manifest).await?;
        let full_name = format!("{namespace}/{name}");
        let should_update_name = match &manifest.and_then(|m| m.package.as_ref()) {
            Some(pkg) => match &pkg.name {
                Some(n) => n.as_str() != full_name.as_str(),
                None => true,
            },
            None => true,
        };

        let manifest = if should_update_name {
            self.update_manifest_name(manifest_path, manifest, &full_name)
                .await?
        } else {
            manifest.cloned()
        };

        let version = self
            .get_version(client, manifest.as_ref(), manifest_path, &full_name)
            .await?;

        Ok(Some(NamedPackageId { full_name, version }))
    }

    pub async fn tag(
        &mut self,
        client: &WasmerClient,
        manifest: Option<&Manifest>,
        manifest_path: Option<&Path>,
        after_push: bool,
        allow_unnamed: bool,
    ) -> anyhow::Result<PackageIdent> {
        tracing::debug!("{:?}", self);
        let package_id = self
            .get_package_id(client, &self.package_hash, after_push)
            .await?;
        tracing::info!(
            "The package identifier returned from the registry is {:?}",
            package_id
        );

        let id = match self
            .synthesize_id(client, manifest, manifest_path, allow_unnamed)
            .await?
        {
            Some(id) => id,
            None => return Ok(PackageIdent::Hash(self.package_hash.clone())),
        };

        if self.should_tag(client, &id).await? {
            self.do_tag(client, &id, manifest, &package_id)
                .await
                .map_err(on_error)?;
        }

        Ok(PackageIdent::Named(id.into()))
    }

    // Check if a package with the same hash, namespace, name and version already exists. In such a
    // case, don't tag the package again.
    #[tracing::instrument]
    async fn should_tag(&self, client: &WasmerClient, id: &NamedPackageId) -> anyhow::Result<bool> {
        if self.dry_run {
            if !self.quiet {
                eprintln!("Skipping tagging {id} as `--dry-run` was set");
            }
            return Ok(false);
        }

        let pkg = wasmer_backend_api::query::get_package_version(
            client,
            id.full_name.clone(),
            id.version.to_string(),
        )
        .await?;

        if let Some(hash) = pkg
            .as_ref()
            .and_then(|p| p.distribution_v3.pirita_sha256_hash.as_ref())
        {
            let registry_package_hash = PackageHash::from_str(&format!("sha256:{hash}"))?;
            if registry_package_hash == self.package_hash {
                tracing::info!("decided not to tag as package {pkg:?} already exists");
                return Ok(false);
            }
        }

        Ok(true)
    }
}

#[async_trait::async_trait]
impl AsyncCliCommand for PackageTag {
    type Output = ();

    async fn run_async(mut self) -> Result<Self::Output, anyhow::Error> {
        tracing::info!("Checking if user is logged in");
        let client = login_user(&self.env, !self.non_interactive, "tag a package").await?;

        let (manifest_path, manifest) = match get_manifest(&self.package_path) {
            Ok((manifest_path, manifest)) => {
                tracing::info!("Got manifest at path {}", manifest_path.display());
                (Some(manifest_path), Some(manifest))
            }
            Err(_) => (None, None),
        };

        let id = self
            .tag(
                &client,
                manifest.as_ref(),
                manifest_path.as_deref(),
                false,
                false,
            )
            .await?;

        match id {
            PackageIdent::Named(ref n) => {
                let url = make_package_url(&client, n);
                eprintln!("{} Package URL: {url}", "ð–¥”".yellow().bold());
            }
            PackageIdent::Hash(ref h) => {
                eprintln!("{} Succesfully tagged package ({h})", "✔".green().bold());
            }
        }

        Ok(())
    }
}