1#![allow(deprecated)]
6
7mod error;
8mod named_package_ident;
9mod package_hash;
10mod package_id;
11mod package_ident;
12mod package_source;
13
14pub use self::{
15 error::PackageParseError,
16 named_package_ident::{NamedPackageIdent, Tag},
17 package_hash::PackageHash,
18 package_id::{NamedPackageId, PackageId},
19 package_ident::PackageIdent,
20 package_source::PackageSource,
21};
22
23use std::{
24 borrow::Cow,
25 collections::{BTreeMap, BTreeSet},
26 fmt::{self, Display},
27 path::{Path, PathBuf},
28 str::FromStr,
29};
30
31use indexmap::IndexMap;
32use semver::{Version, VersionReq};
33use serde::{Deserialize, Serialize, de::Error as _};
34use thiserror::Error;
35
36#[derive(Clone, Copy, Default, Debug, Deserialize, Serialize, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum Abi {
43 #[default]
44 #[serde(rename = "none")]
45 None,
46 #[serde(rename = "wasi")]
47 Wasi,
48 #[serde(rename = "wasm4")]
49 WASM4,
50}
51
52impl Abi {
53 pub fn to_str(&self) -> &str {
55 match self {
56 Abi::Wasi => "wasi",
57 Abi::WASM4 => "wasm4",
58 Abi::None => "generic",
59 }
60 }
61
62 pub fn is_none(&self) -> bool {
64 matches!(self, Abi::None)
65 }
66
67 pub fn from_name(name: &str) -> Self {
69 name.parse().unwrap_or(Abi::None)
70 }
71}
72
73impl fmt::Display for Abi {
74 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
75 write!(f, "{}", self.to_str())
76 }
77}
78
79impl FromStr for Abi {
80 type Err = Box<dyn std::error::Error + Send + Sync>;
81
82 fn from_str(s: &str) -> Result<Self, Self::Err> {
83 match s.to_lowercase().as_str() {
84 "wasi" => Ok(Abi::Wasi),
85 "wasm4" => Ok(Abi::WASM4),
86 "generic" => Ok(Abi::None),
87 _ => Err(format!("Unknown ABI, \"{s}\"").into()),
88 }
89 }
90}
91
92pub static MANIFEST_FILE_NAME: &str = "wasmer.toml";
94
95const README_PATHS: &[&str; 5] = &[
96 "README",
97 "README.md",
98 "README.markdown",
99 "README.mdown",
100 "README.mkdn",
101];
102
103const LICENSE_PATHS: &[&str; 3] = &["LICENSE", "LICENSE.md", "COPYING"];
104
105#[derive(Clone, Debug, Deserialize, Serialize, derive_builder::Builder)]
109#[non_exhaustive]
110pub struct Package {
111 #[builder(setter(into, strip_option), default)]
113 pub name: Option<String>,
114 #[builder(setter(into, strip_option), default)]
116 pub version: Option<Version>,
117 #[builder(setter(into, strip_option), default)]
119 pub description: Option<String>,
120 #[builder(setter(into, strip_option), default)]
122 pub license: Option<String>,
123 #[serde(rename = "license-file")]
125 #[builder(setter(into, strip_option), default)]
126 pub license_file: Option<PathBuf>,
127 #[serde(skip_serializing_if = "Option::is_none")]
129 #[builder(setter(into, strip_option), default)]
130 pub readme: Option<PathBuf>,
131 #[serde(skip_serializing_if = "Option::is_none")]
133 #[builder(setter(into, strip_option), default)]
134 pub repository: Option<String>,
135 #[serde(skip_serializing_if = "Option::is_none")]
137 #[builder(setter(into, strip_option), default)]
138 pub homepage: Option<String>,
139 #[serde(rename = "wasmer-extra-flags")]
140 #[builder(setter(into, strip_option), default)]
141 #[deprecated(
142 since = "0.9.2",
143 note = "Use runner-specific command attributes instead"
144 )]
145 pub wasmer_extra_flags: Option<String>,
146 #[serde(
147 rename = "disable-command-rename",
148 default,
149 skip_serializing_if = "std::ops::Not::not"
150 )]
151 #[builder(default)]
152 #[deprecated(
153 since = "0.9.2",
154 note = "Does nothing. Prefer a runner-specific command attribute instead"
155 )]
156 pub disable_command_rename: bool,
157 #[serde(
163 rename = "rename-commands-to-raw-command-name",
164 default,
165 skip_serializing_if = "std::ops::Not::not"
166 )]
167 #[builder(default)]
168 #[deprecated(
169 since = "0.9.2",
170 note = "Does nothing. Prefer a runner-specific command attribute instead"
171 )]
172 pub rename_commands_to_raw_command_name: bool,
173 #[serde(skip_serializing_if = "Option::is_none")]
175 #[builder(setter(into, strip_option), default)]
176 pub entrypoint: Option<String>,
177 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
179 #[builder(default)]
180 pub private: bool,
181}
182
183impl Package {
184 pub fn new_empty() -> Self {
185 PackageBuilder::default().build().unwrap()
186 }
187
188 pub fn builder(
190 name: impl Into<String>,
191 version: Version,
192 description: impl Into<String>,
193 ) -> PackageBuilder {
194 PackageBuilder::new(name, version, description)
195 }
196}
197
198impl PackageBuilder {
199 pub fn new(name: impl Into<String>, version: Version, description: impl Into<String>) -> Self {
200 let mut builder = PackageBuilder::default();
201 builder.name(name).version(version).description(description);
202 builder
203 }
204}
205
206#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
207#[serde(untagged)]
208pub enum Command {
209 V1(CommandV1),
210 V2(CommandV2),
211}
212
213impl Command {
214 pub fn get_name(&self) -> &str {
216 match self {
217 Self::V1(c) => &c.name,
218 Self::V2(c) => &c.name,
219 }
220 }
221
222 pub fn get_module(&self) -> &ModuleReference {
224 match self {
225 Self::V1(c) => &c.module,
226 Self::V2(c) => &c.module,
227 }
228 }
229}
230
231#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
238#[serde(deny_unknown_fields)] #[deprecated(since = "0.9.2", note = "Prefer the CommandV2 syntax")]
241pub struct CommandV1 {
242 pub name: String,
243 pub module: ModuleReference,
244 pub main_args: Option<String>,
245 pub package: Option<String>,
246}
247
248#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
250pub struct CommandV2 {
251 pub name: String,
253 pub module: ModuleReference,
255 pub runner: String,
259 pub annotations: Option<CommandAnnotations>,
261}
262
263impl CommandV2 {
264 pub fn get_annotations(&self, basepath: &Path) -> Result<Option<ciborium::Value>, String> {
267 match self.annotations.as_ref() {
268 Some(CommandAnnotations::Raw(v)) => Ok(Some(toml_to_cbor_value(v))),
269 Some(CommandAnnotations::File(FileCommandAnnotations { file, kind })) => {
270 let path = basepath.join(file.clone());
271 let file = std::fs::read_to_string(&path).map_err(|e| {
272 format!(
273 "Error reading {:?}.annotation ({:?}): {e}",
274 self.name,
275 path.display()
276 )
277 })?;
278 match kind {
279 FileKind::Json => {
280 let value: serde_json::Value =
281 serde_json::from_str(&file).map_err(|e| {
282 format!(
283 "Error reading {:?}.annotation ({:?}): {e}",
284 self.name,
285 path.display()
286 )
287 })?;
288 Ok(Some(json_to_cbor_value(&value)))
289 }
290 FileKind::Yaml => {
291 let value: serde_yaml::Value =
292 serde_yaml::from_str(&file).map_err(|e| {
293 format!(
294 "Error reading {:?}.annotation ({:?}): {e}",
295 self.name,
296 path.display()
297 )
298 })?;
299 Ok(Some(yaml_to_cbor_value(&value)))
300 }
301 }
302 }
303 None => Ok(None),
304 }
305 }
306}
307
308#[derive(Clone, Debug, PartialEq)]
314pub enum ModuleReference {
315 CurrentPackage {
317 module: String,
319 },
320 Dependency {
323 dependency: String,
325 module: String,
327 },
328}
329
330impl Serialize for ModuleReference {
331 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
332 where
333 S: serde::Serializer,
334 {
335 self.to_string().serialize(serializer)
336 }
337}
338
339impl<'de> Deserialize<'de> for ModuleReference {
340 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
341 where
342 D: serde::Deserializer<'de>,
343 {
344 let repr: Cow<'de, str> = Cow::deserialize(deserializer)?;
345 repr.parse().map_err(D::Error::custom)
346 }
347}
348
349impl FromStr for ModuleReference {
350 type Err = Box<dyn std::error::Error + Send + Sync>;
351
352 fn from_str(s: &str) -> Result<Self, Self::Err> {
353 match s.split_once(':') {
354 Some((dependency, module)) => {
355 if module.contains(':') {
356 return Err("Invalid format".into());
357 }
358
359 Ok(ModuleReference::Dependency {
360 dependency: dependency.to_string(),
361 module: module.to_string(),
362 })
363 }
364 None => Ok(ModuleReference::CurrentPackage {
365 module: s.to_string(),
366 }),
367 }
368 }
369}
370
371impl Display for ModuleReference {
372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373 match self {
374 ModuleReference::CurrentPackage { module } => Display::fmt(module, f),
375 ModuleReference::Dependency { dependency, module } => {
376 write!(f, "{dependency}:{module}")
377 }
378 }
379 }
380}
381
382fn toml_to_cbor_value(val: &toml::Value) -> ciborium::Value {
383 match val {
384 toml::Value::String(s) => ciborium::Value::Text(s.clone()),
385 toml::Value::Integer(i) => ciborium::Value::Integer(ciborium::value::Integer::from(*i)),
386 toml::Value::Float(f) => ciborium::Value::Float(*f),
387 toml::Value::Boolean(b) => ciborium::Value::Bool(*b),
388 toml::Value::Datetime(d) => ciborium::Value::Text(format!("{d}")),
389 toml::Value::Array(sq) => {
390 ciborium::Value::Array(sq.iter().map(toml_to_cbor_value).collect())
391 }
392 toml::Value::Table(m) => ciborium::Value::Map(
393 m.iter()
394 .map(|(k, v)| (ciborium::Value::Text(k.clone()), toml_to_cbor_value(v)))
395 .collect(),
396 ),
397 }
398}
399
400fn json_to_cbor_value(val: &serde_json::Value) -> ciborium::Value {
401 match val {
402 serde_json::Value::Null => ciborium::Value::Null,
403 serde_json::Value::Bool(b) => ciborium::Value::Bool(*b),
404 serde_json::Value::Number(n) => {
405 if let Some(i) = n.as_i64() {
406 ciborium::Value::Integer(ciborium::value::Integer::from(i))
407 } else if let Some(u) = n.as_u64() {
408 ciborium::Value::Integer(ciborium::value::Integer::from(u))
409 } else if let Some(f) = n.as_f64() {
410 ciborium::Value::Float(f)
411 } else {
412 ciborium::Value::Null
413 }
414 }
415 serde_json::Value::String(s) => ciborium::Value::Text(s.clone()),
416 serde_json::Value::Array(sq) => {
417 ciborium::Value::Array(sq.iter().map(json_to_cbor_value).collect())
418 }
419 serde_json::Value::Object(m) => ciborium::Value::Map(
420 m.iter()
421 .map(|(k, v)| (ciborium::Value::Text(k.clone()), json_to_cbor_value(v)))
422 .collect(),
423 ),
424 }
425}
426
427fn yaml_to_cbor_value(val: &serde_yaml::Value) -> ciborium::Value {
428 match val {
429 serde_yaml::Value::Null => ciborium::Value::Null,
430 serde_yaml::Value::Bool(b) => ciborium::Value::Bool(*b),
431 serde_yaml::Value::Number(n) => {
432 if let Some(i) = n.as_i64() {
433 ciborium::Value::Integer(ciborium::value::Integer::from(i))
434 } else if let Some(u) = n.as_u64() {
435 ciborium::Value::Integer(ciborium::value::Integer::from(u))
436 } else if let Some(f) = n.as_f64() {
437 ciborium::Value::Float(f)
438 } else {
439 ciborium::Value::Null
440 }
441 }
442 serde_yaml::Value::String(s) => ciborium::Value::Text(s.clone()),
443 serde_yaml::Value::Sequence(sq) => {
444 ciborium::Value::Array(sq.iter().map(yaml_to_cbor_value).collect())
445 }
446 serde_yaml::Value::Mapping(m) => ciborium::Value::Map(
447 m.iter()
448 .map(|(k, v)| (yaml_to_cbor_value(k), yaml_to_cbor_value(v)))
449 .collect(),
450 ),
451 serde_yaml::Value::Tagged(tag) => yaml_to_cbor_value(&tag.value),
452 }
453}
454
455#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
457#[serde(untagged)]
458#[repr(C)]
459pub enum CommandAnnotations {
460 File(FileCommandAnnotations),
462 Raw(toml::Value),
464}
465
466#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
468pub struct FileCommandAnnotations {
469 pub file: PathBuf,
471 pub kind: FileKind,
473}
474
475#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Deserialize, Serialize)]
477pub enum FileKind {
478 #[serde(rename = "yaml")]
480 Yaml,
481 #[serde(rename = "json")]
483 Json,
484}
485
486#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
489pub struct Module {
490 pub name: String,
492 pub source: PathBuf,
495 #[serde(default = "Abi::default", skip_serializing_if = "Abi::is_none")]
497 pub abi: Abi,
498 #[serde(default)]
499 pub kind: Option<String>,
500 #[serde(skip_serializing_if = "Option::is_none")]
502 pub interfaces: Option<IndexMap<String, String>>,
503 pub bindings: Option<Bindings>,
506 #[serde(skip_serializing_if = "Option::is_none")]
508 pub annotations: Option<UserAnnotations>,
509}
510
511#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)]
513pub struct UserAnnotations {
514 pub suggested_compiler_optimizations: SuggestedCompilerOptimizations,
515}
516
517#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize, Default)]
519pub struct SuggestedCompilerOptimizations {
520 pub pass_params: Option<bool>,
521}
522
523#[derive(Clone, Debug, PartialEq, Eq)]
525pub enum Bindings {
526 Wit(WitBindings),
527 Wai(WaiBindings),
528}
529
530impl Bindings {
531 pub fn referenced_files(&self, base_directory: &Path) -> Result<Vec<PathBuf>, ImportsError> {
538 match self {
539 Bindings::Wit(WitBindings { wit_exports, .. }) => {
540 let path = base_directory.join(wit_exports);
544
545 if path.exists() {
546 Ok(vec![path])
547 } else {
548 Err(ImportsError::FileNotFound(path))
549 }
550 }
551 Bindings::Wai(wai) => wai.referenced_files(base_directory),
552 }
553 }
554}
555
556impl Serialize for Bindings {
557 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
558 where
559 S: serde::Serializer,
560 {
561 match self {
562 Bindings::Wit(w) => w.serialize(serializer),
563 Bindings::Wai(w) => w.serialize(serializer),
564 }
565 }
566}
567
568impl<'de> Deserialize<'de> for Bindings {
569 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
570 where
571 D: serde::Deserializer<'de>,
572 {
573 let value = toml::Value::deserialize(deserializer)?;
574
575 let keys = ["wit-bindgen", "wai-version"];
576 let [wit_bindgen, wai_version] = keys.map(|key| value.get(key).is_some());
577
578 match (wit_bindgen, wai_version) {
579 (true, false) => WitBindings::deserialize(value)
580 .map(Bindings::Wit)
581 .map_err(D::Error::custom),
582 (false, true) => WaiBindings::deserialize(value)
583 .map(Bindings::Wai)
584 .map_err(D::Error::custom),
585 (true, true) | (false, false) => {
586 let msg = format!(
587 "expected one of \"{}\" to be provided, but not both",
588 keys.join("\" or \""),
589 );
590 Err(D::Error::custom(msg))
591 }
592 }
593 }
594}
595
596#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
597#[serde(rename_all = "kebab-case")]
598pub struct WitBindings {
599 pub wit_bindgen: Version,
601 pub wit_exports: PathBuf,
603}
604
605#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
606#[serde(rename_all = "kebab-case")]
607pub struct WaiBindings {
608 pub wai_version: Version,
610 pub exports: Option<PathBuf>,
612 #[serde(default, skip_serializing_if = "Vec::is_empty")]
615 pub imports: Vec<PathBuf>,
616}
617
618impl WaiBindings {
619 fn referenced_files(&self, base_directory: &Path) -> Result<Vec<PathBuf>, ImportsError> {
620 let WaiBindings {
621 exports, imports, ..
622 } = self;
623
624 let initial_paths = exports
629 .iter()
630 .chain(imports)
631 .map(|relative_path| base_directory.join(relative_path));
632
633 let mut to_check: Vec<PathBuf> = Vec::new();
634
635 for path in initial_paths {
636 if !path.exists() {
637 return Err(ImportsError::FileNotFound(path));
638 }
639 to_check.push(path);
640 }
641
642 let mut files = BTreeSet::new();
643
644 while let Some(path) = to_check.pop() {
645 if files.contains(&path) {
646 continue;
647 }
648
649 to_check.extend(get_imported_wai_files(&path)?);
650 files.insert(path);
651 }
652
653 Ok(files.into_iter().collect())
654 }
655}
656
657fn get_imported_wai_files(path: &Path) -> Result<Vec<PathBuf>, ImportsError> {
662 let _wai_src = std::fs::read_to_string(path).map_err(|error| ImportsError::Read {
663 path: path.to_path_buf(),
664 error,
665 })?;
666
667 let parent_dir = path.parent()
668 .expect("All paths should have a parent directory because we joined them relative to the base directory");
669
670 let raw_imports: Vec<String> = Vec::new();
674
675 let mut resolved_paths = Vec::new();
678
679 for imported in raw_imports {
680 let absolute_path = parent_dir.join(imported);
681
682 if !absolute_path.exists() {
683 return Err(ImportsError::ImportedFileNotFound {
684 path: absolute_path,
685 referenced_by: path.to_path_buf(),
686 });
687 }
688
689 resolved_paths.push(absolute_path);
690 }
691
692 Ok(resolved_paths)
693}
694
695#[derive(Debug, thiserror::Error)]
697#[non_exhaustive]
698pub enum ImportsError {
699 #[error(
700 "The \"{}\" mentioned in the manifest doesn't exist",
701 _0.display(),
702 )]
703 FileNotFound(PathBuf),
704 #[error(
705 "The \"{}\" imported by \"{}\" doesn't exist",
706 path.display(),
707 referenced_by.display(),
708 )]
709 ImportedFileNotFound {
710 path: PathBuf,
711 referenced_by: PathBuf,
712 },
713 #[error("Unable to parse \"{}\" as a WAI file", path.display())]
714 WaiParse { path: PathBuf },
715 #[error("Unable to read \"{}\"", path.display())]
716 Read {
717 path: PathBuf,
718 #[source]
719 error: std::io::Error,
720 },
721}
722
723#[derive(Clone, Debug, Deserialize, Serialize, derive_builder::Builder)]
725#[non_exhaustive]
726pub struct Manifest {
727 pub package: Option<Package>,
729 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
731 #[builder(default)]
732 pub dependencies: IndexMap<String, VersionReq>,
733 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
736 #[builder(default)]
737 pub fs: IndexMap<String, PathBuf>,
738 #[serde(default, rename = "module", skip_serializing_if = "Vec::is_empty")]
740 #[builder(default)]
741 pub modules: Vec<Module>,
742 #[serde(default, rename = "command", skip_serializing_if = "Vec::is_empty")]
744 #[builder(default)]
745 pub commands: Vec<Command>,
746}
747
748impl Manifest {
749 pub fn new_empty() -> Self {
750 Self {
751 package: None,
752 dependencies: IndexMap::new(),
753 fs: IndexMap::new(),
754 modules: Vec::new(),
755 commands: Vec::new(),
756 }
757 }
758
759 pub fn builder(package: Package) -> ManifestBuilder {
761 ManifestBuilder::new(package)
762 }
763
764 pub fn parse(s: &str) -> Result<Self, toml::de::Error> {
766 toml::from_str(s)
767 }
768
769 pub fn find_in_directory<T: AsRef<Path>>(path: T) -> Result<Self, ManifestError> {
772 let path = path.as_ref();
773
774 if !path.is_dir() {
775 return Err(ManifestError::MissingManifest(path.to_path_buf()));
776 }
777 let manifest_path_buf = path.join(MANIFEST_FILE_NAME);
778 let contents = std::fs::read_to_string(&manifest_path_buf)
779 .map_err(|_e| ManifestError::MissingManifest(manifest_path_buf))?;
780 let mut manifest: Self = toml::from_str(contents.as_str())?;
781
782 if let Some(package) = manifest.package.as_mut() {
783 if package.readme.is_none() {
784 package.readme = locate_file(path, README_PATHS);
785 }
786
787 if package.license_file.is_none() {
788 package.license_file = locate_file(path, LICENSE_PATHS);
789 }
790 }
791 manifest.validate()?;
792
793 Ok(manifest)
794 }
795
796 pub fn validate(&self) -> Result<(), ValidationError> {
806 let mut modules = BTreeMap::new();
807
808 for module in &self.modules {
809 let is_duplicate = modules.insert(&module.name, module).is_some();
810
811 if is_duplicate {
812 return Err(ValidationError::DuplicateModule {
813 name: module.name.clone(),
814 });
815 }
816 }
817
818 let mut commands = BTreeMap::new();
819
820 for command in &self.commands {
821 let is_duplicate = commands.insert(command.get_name(), command).is_some();
822
823 if is_duplicate {
824 return Err(ValidationError::DuplicateCommand {
825 name: command.get_name().to_string(),
826 });
827 }
828
829 let module_reference = command.get_module();
830 match &module_reference {
831 ModuleReference::CurrentPackage { module } => {
832 if let Some(module) = modules.get(&module) {
833 if module.abi == Abi::None && module.interfaces.is_none() {
834 return Err(ValidationError::MissingABI {
835 command: command.get_name().to_string(),
836 module: module.name.clone(),
837 });
838 }
839 } else {
840 return Err(ValidationError::MissingModuleForCommand {
841 command: command.get_name().to_string(),
842 module: command.get_module().clone(),
843 });
844 }
845 }
846 ModuleReference::Dependency { dependency, .. } => {
847 if !self.dependencies.contains_key(dependency) {
850 return Err(ValidationError::MissingDependency {
851 command: command.get_name().to_string(),
852 dependency: dependency.clone(),
853 module_ref: module_reference.clone(),
854 });
855 }
856 }
857 }
858 }
859
860 if let Some(package) = &self.package
861 && let Some(entrypoint) = package.entrypoint.as_deref()
862 && !commands.contains_key(entrypoint)
863 {
864 return Err(ValidationError::InvalidEntrypoint {
865 entrypoint: entrypoint.to_string(),
866 available_commands: commands.keys().map(ToString::to_string).collect(),
867 });
868 }
869
870 Ok(())
871 }
872
873 pub fn add_dependency(&mut self, dependency_name: String, dependency_version: VersionReq) {
875 self.dependencies
876 .insert(dependency_name, dependency_version);
877 }
878
879 pub fn remove_dependency(&mut self, dependency_name: &str) -> Option<VersionReq> {
881 self.dependencies.remove(dependency_name)
882 }
883
884 pub fn to_string(&self) -> anyhow::Result<String> {
886 let repr = toml::to_string_pretty(&self)?;
887 Ok(repr)
888 }
889
890 pub fn save(&self, path: impl AsRef<Path>) -> anyhow::Result<()> {
892 let manifest = toml::to_string_pretty(self)?;
893 std::fs::write(path, manifest).map_err(ManifestError::CannotSaveManifest)?;
894 Ok(())
895 }
896}
897
898fn locate_file(path: &Path, candidates: &[&str]) -> Option<PathBuf> {
899 for filename in candidates {
900 let path_buf = path.join(filename);
901 if path_buf.exists() {
902 return Some(filename.into());
903 }
904 }
905 None
906}
907
908impl ManifestBuilder {
909 pub fn new(package: Package) -> Self {
910 let mut builder = ManifestBuilder::default();
911 builder.package(Some(package));
912 builder
913 }
914
915 pub fn map_fs(&mut self, guest: impl Into<String>, host: impl Into<PathBuf>) -> &mut Self {
918 self.fs
919 .get_or_insert_with(IndexMap::new)
920 .insert(guest.into(), host.into());
921 self
922 }
923
924 pub fn with_dependency(&mut self, name: impl Into<String>, version: VersionReq) -> &mut Self {
926 self.dependencies
927 .get_or_insert_with(IndexMap::new)
928 .insert(name.into(), version);
929 self
930 }
931
932 pub fn with_module(&mut self, module: Module) -> &mut Self {
934 self.modules.get_or_insert_with(Vec::new).push(module);
935 self
936 }
937
938 pub fn with_command(&mut self, command: Command) -> &mut Self {
940 self.commands.get_or_insert_with(Vec::new).push(command);
941 self
942 }
943}
944
945#[derive(Debug, Error)]
947#[non_exhaustive]
948pub enum ManifestError {
949 #[error("Manifest file not found at \"{}\"", _0.display())]
950 MissingManifest(PathBuf),
951 #[error("Could not save manifest file: {0}.")]
952 CannotSaveManifest(#[source] std::io::Error),
953 #[error("Could not parse manifest because {0}.")]
954 TomlParseError(#[from] toml::de::Error),
955 #[error("There was an error validating the manifest")]
956 ValidationError(#[from] ValidationError),
957}
958
959#[derive(Debug, PartialEq, Error)]
961#[non_exhaustive]
962pub enum ValidationError {
963 #[error(
964 "missing ABI field on module, \"{module}\", used by command, \"{command}\"; an ABI of `wasi` is required"
965 )]
966 MissingABI { command: String, module: String },
967 #[error("missing module, \"{module}\", in manifest used by command, \"{command}\"")]
968 MissingModuleForCommand {
969 command: String,
970 module: ModuleReference,
971 },
972 #[error(
973 "The \"{command}\" command refers to a nonexistent dependency, \"{dependency}\" in \"{module_ref}\""
974 )]
975 MissingDependency {
976 command: String,
977 dependency: String,
978 module_ref: ModuleReference,
979 },
980 #[error("The entrypoint, \"{entrypoint}\", isn't a valid command (commands: {})", available_commands.join(", "))]
981 InvalidEntrypoint {
982 entrypoint: String,
983 available_commands: Vec<String>,
984 },
985 #[error("Duplicate module, \"{name}\"")]
986 DuplicateModule { name: String },
987 #[error("Duplicate command, \"{name}\"")]
988 DuplicateCommand { name: String },
989}
990
991#[cfg(test)]
992mod tests {
993 use std::fmt::Debug;
994
995 use serde::{Deserialize, de::DeserializeOwned};
996 use toml::toml;
997
998 use super::*;
999
1000 #[test]
1001 fn test_to_string() {
1002 Manifest {
1003 package: Some(Package {
1004 name: Some("package/name".to_string()),
1005 version: Some(Version::parse("1.0.0").unwrap()),
1006 description: Some("test".to_string()),
1007 license: None,
1008 license_file: None,
1009 readme: None,
1010 repository: None,
1011 homepage: None,
1012 wasmer_extra_flags: None,
1013 disable_command_rename: false,
1014 rename_commands_to_raw_command_name: false,
1015 entrypoint: None,
1016 private: false,
1017 }),
1018 dependencies: IndexMap::new(),
1019 modules: vec![Module {
1020 name: "test".to_string(),
1021 abi: Abi::Wasi,
1022 bindings: None,
1023 interfaces: None,
1024 kind: Some("https://webc.org/kind/wasi".to_string()),
1025 source: Path::new("test.wasm").to_path_buf(),
1026 annotations: None,
1027 }],
1028 commands: Vec::new(),
1029 fs: vec![
1030 ("a".to_string(), Path::new("/a").to_path_buf()),
1031 ("b".to_string(), Path::new("/b").to_path_buf()),
1032 ]
1033 .into_iter()
1034 .collect(),
1035 }
1036 .to_string()
1037 .unwrap();
1038 }
1039
1040 #[test]
1041 fn interface_test() {
1042 let manifest_str = r#"
1043[package]
1044name = "test"
1045version = "0.0.0"
1046description = "This is a test package"
1047license = "MIT"
1048
1049[[module]]
1050name = "mod"
1051source = "target/wasm32-wasip1/release/mod.wasm"
1052interfaces = {"wasi" = "0.0.0-unstable"}
1053
1054[[module]]
1055name = "mod-with-exports"
1056source = "target/wasm32-wasip1/release/mod-with-exports.wasm"
1057bindings = { wit-exports = "exports.wit", wit-bindgen = "0.0.0" }
1058
1059[[command]]
1060name = "command"
1061module = "mod"
1062"#;
1063 let manifest: Manifest = Manifest::parse(manifest_str).unwrap();
1064 let modules = &manifest.modules;
1065 assert_eq!(
1066 modules[0].interfaces.as_ref().unwrap().get("wasi"),
1067 Some(&"0.0.0-unstable".to_string())
1068 );
1069
1070 assert_eq!(
1071 modules[1],
1072 Module {
1073 name: "mod-with-exports".to_string(),
1074 source: PathBuf::from("target/wasm32-wasip1/release/mod-with-exports.wasm"),
1075 abi: Abi::None,
1076 kind: None,
1077 interfaces: None,
1078 bindings: Some(Bindings::Wit(WitBindings {
1079 wit_exports: PathBuf::from("exports.wit"),
1080 wit_bindgen: "0.0.0".parse().unwrap()
1081 })),
1082 annotations: None
1083 },
1084 );
1085 }
1086
1087 #[test]
1088 fn parse_wit_bindings() {
1089 let table = toml! {
1090 name = "..."
1091 source = "..."
1092 bindings = { wit-bindgen = "0.1.0", wit-exports = "./file.wit" }
1093 };
1094
1095 let module = Module::deserialize(table).unwrap();
1096
1097 assert_eq!(
1098 module.bindings.as_ref().unwrap(),
1099 &Bindings::Wit(WitBindings {
1100 wit_bindgen: "0.1.0".parse().unwrap(),
1101 wit_exports: PathBuf::from("./file.wit"),
1102 }),
1103 );
1104 assert_round_trippable(&module);
1105 }
1106
1107 #[test]
1108 fn parse_wai_bindings() {
1109 let table = toml! {
1110 name = "..."
1111 source = "..."
1112 bindings = { wai-version = "0.1.0", exports = "./file.wai", imports = ["a.wai", "../b.wai"] }
1113 };
1114
1115 let module = Module::deserialize(table).unwrap();
1116
1117 assert_eq!(
1118 module.bindings.as_ref().unwrap(),
1119 &Bindings::Wai(WaiBindings {
1120 wai_version: "0.1.0".parse().unwrap(),
1121 exports: Some(PathBuf::from("./file.wai")),
1122 imports: vec![PathBuf::from("a.wai"), PathBuf::from("../b.wai")],
1123 }),
1124 );
1125 assert_round_trippable(&module);
1126 }
1127
1128 #[track_caller]
1129 fn assert_round_trippable<T>(value: &T)
1130 where
1131 T: Serialize + DeserializeOwned + PartialEq + Debug,
1132 {
1133 let repr = toml::to_string(value).unwrap();
1134 let round_tripped: T = toml::from_str(&repr).unwrap();
1135 assert_eq!(
1136 round_tripped, *value,
1137 "The value should convert to/from TOML losslessly"
1138 );
1139 }
1140
1141 #[test]
1142 fn imports_and_exports_are_optional_with_wai() {
1143 let table = toml! {
1144 name = "..."
1145 source = "..."
1146 bindings = { wai-version = "0.1.0" }
1147 };
1148
1149 let module = Module::deserialize(table).unwrap();
1150
1151 assert_eq!(
1152 module.bindings.as_ref().unwrap(),
1153 &Bindings::Wai(WaiBindings {
1154 wai_version: "0.1.0".parse().unwrap(),
1155 exports: None,
1156 imports: Vec::new(),
1157 }),
1158 );
1159 assert_round_trippable(&module);
1160 }
1161
1162 #[test]
1163 fn ambiguous_bindings_table() {
1164 let table = toml! {
1165 wai-version = "0.2.0"
1166 wit-bindgen = "0.1.0"
1167 };
1168
1169 let err = Bindings::deserialize(table).unwrap_err();
1170
1171 assert_eq!(
1172 err.to_string(),
1173 "expected one of \"wit-bindgen\" or \"wai-version\" to be provided, but not both\n"
1174 );
1175 }
1176
1177 #[test]
1178 fn bindings_table_that_is_neither_wit_nor_wai() {
1179 let table = toml! {
1180 wai-bindgen = "lol, this should have been wai-version"
1181 exports = "./file.wai"
1182 };
1183
1184 let err = Bindings::deserialize(table).unwrap_err();
1185
1186 assert_eq!(
1187 err.to_string(),
1188 "expected one of \"wit-bindgen\" or \"wai-version\" to be provided, but not both\n"
1189 );
1190 }
1191
1192 #[test]
1193 fn command_v2_isnt_ambiguous_with_command_v1() {
1194 let src = r#"
1195[package]
1196name = "hotg-ai/sine"
1197version = "0.12.0"
1198description = "sine"
1199
1200[dependencies]
1201"hotg-ai/train_test_split" = "0.12.1"
1202"hotg-ai/elastic_net" = "0.12.1"
1203
1204[[module]] # This is the same as atoms
1205name = "sine"
1206kind = "tensorflow-SavedModel" # It can also be "wasm" (default)
1207source = "models/sine"
1208
1209[[command]]
1210name = "run"
1211runner = "rune"
1212module = "sine"
1213annotations = { file = "Runefile.yml", kind = "yaml" }
1214"#;
1215
1216 let manifest: Manifest = toml::from_str(src).unwrap();
1217
1218 let commands = &manifest.commands;
1219 assert_eq!(commands.len(), 1);
1220 assert_eq!(
1221 commands[0],
1222 Command::V2(CommandV2 {
1223 name: "run".into(),
1224 module: "sine".parse().unwrap(),
1225 runner: "rune".into(),
1226 annotations: Some(CommandAnnotations::File(FileCommandAnnotations {
1227 file: "Runefile.yml".into(),
1228 kind: FileKind::Yaml,
1229 }))
1230 })
1231 );
1232 }
1233
1234 #[test]
1235 fn get_manifest() {
1236 let wasmer_toml = toml! {
1237 [package]
1238 name = "test"
1239 version = "1.0.0"
1240 repository = "test.git"
1241 homepage = "test.com"
1242 description = "The best package."
1243 };
1244 let manifest: Manifest = wasmer_toml.try_into().unwrap();
1245 if let Some(package) = manifest.package {
1246 assert!(!package.disable_command_rename);
1247 }
1248 }
1249
1250 #[test]
1251 fn parse_manifest_without_package_section() {
1252 let wasmer_toml = toml! {
1253 [[module]]
1254 name = "test-module"
1255 source = "data.wasm"
1256 abi = "wasi"
1257 };
1258 let manifest: Manifest = wasmer_toml.try_into().unwrap();
1259 assert!(manifest.package.is_none());
1260 }
1261
1262 #[test]
1263 fn get_commands() {
1264 let wasmer_toml = toml! {
1265 [package]
1266 name = "test"
1267 version = "1.0.0"
1268 repository = "test.git"
1269 homepage = "test.com"
1270 description = "The best package."
1271 [[module]]
1272 name = "test-pkg"
1273 module = "target.wasm"
1274 source = "source.wasm"
1275 description = "description"
1276 interfaces = {"wasi" = "0.0.0-unstable"}
1277 [[command]]
1278 name = "foo"
1279 module = "test"
1280 [[command]]
1281 name = "baz"
1282 module = "test"
1283 main_args = "$@"
1284 };
1285 let manifest: Manifest = wasmer_toml.try_into().unwrap();
1286 let commands = &manifest.commands;
1287 assert_eq!(2, commands.len());
1288 }
1289
1290 #[test]
1291 fn add_new_dependency() {
1292 let tmp_dir = tempfile::tempdir().unwrap();
1293 let tmp_dir_path: &std::path::Path = tmp_dir.as_ref();
1294 let manifest_path = tmp_dir_path.join(MANIFEST_FILE_NAME);
1295 let wasmer_toml = toml! {
1296 [package]
1297 name = "_/test"
1298 version = "1.0.0"
1299 description = "description"
1300 [[module]]
1301 name = "test"
1302 source = "test.wasm"
1303 interfaces = {}
1304 };
1305 let toml_string = toml::to_string(&wasmer_toml).unwrap();
1306 std::fs::write(manifest_path, toml_string).unwrap();
1307 let mut manifest = Manifest::find_in_directory(tmp_dir).unwrap();
1308
1309 let dependency_name = "dep_pkg";
1310 let dependency_version: VersionReq = "0.1.0".parse().unwrap();
1311
1312 manifest.add_dependency(dependency_name.to_string(), dependency_version.clone());
1313 assert_eq!(1, manifest.dependencies.len());
1314
1315 manifest.add_dependency(dependency_name.to_string(), dependency_version);
1317 assert_eq!(1, manifest.dependencies.len());
1318
1319 let dependency_name_2 = "dep_pkg_2";
1321 let dependency_version_2: VersionReq = "0.2.0".parse().unwrap();
1322 manifest.add_dependency(dependency_name_2.to_string(), dependency_version_2);
1323 assert_eq!(2, manifest.dependencies.len());
1324 }
1325
1326 #[test]
1327 fn duplicate_modules_are_invalid() {
1328 let wasmer_toml = toml! {
1329 [package]
1330 name = "some/package"
1331 version = "0.0.0"
1332 description = ""
1333 [[module]]
1334 name = "test"
1335 source = "test.wasm"
1336 [[module]]
1337 name = "test"
1338 source = "test.wasm"
1339 };
1340 let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1341
1342 let error = manifest.validate().unwrap_err();
1343
1344 assert_eq!(
1345 error,
1346 ValidationError::DuplicateModule {
1347 name: "test".to_string()
1348 }
1349 );
1350 }
1351
1352 #[test]
1353 fn duplicate_commands_are_invalid() {
1354 let wasmer_toml = toml! {
1355 [package]
1356 name = "some/package"
1357 version = "0.0.0"
1358 description = ""
1359 [[module]]
1360 name = "test"
1361 source = "test.wasm"
1362 abi = "wasi"
1363 [[command]]
1364 name = "cmd"
1365 module = "test"
1366 [[command]]
1367 name = "cmd"
1368 module = "test"
1369 };
1370 let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1371
1372 let error = manifest.validate().unwrap_err();
1373
1374 assert_eq!(
1375 error,
1376 ValidationError::DuplicateCommand {
1377 name: "cmd".to_string()
1378 }
1379 );
1380 }
1381
1382 #[test]
1383 fn nonexistent_entrypoint() {
1384 let wasmer_toml = toml! {
1385 [package]
1386 name = "some/package"
1387 version = "0.0.0"
1388 description = ""
1389 entrypoint = "this-doesnt-exist"
1390 [[module]]
1391 name = "test"
1392 source = "test.wasm"
1393 abi = "wasi"
1394 [[command]]
1395 name = "cmd"
1396 module = "test"
1397 };
1398 let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1399
1400 let error = manifest.validate().unwrap_err();
1401
1402 assert_eq!(
1403 error,
1404 ValidationError::InvalidEntrypoint {
1405 entrypoint: "this-doesnt-exist".to_string(),
1406 available_commands: vec!["cmd".to_string()]
1407 }
1408 );
1409 }
1410
1411 #[test]
1412 fn command_with_nonexistent_module() {
1413 let wasmer_toml = toml! {
1414 [package]
1415 name = "some/package"
1416 version = "0.0.0"
1417 description = ""
1418 [[command]]
1419 name = "cmd"
1420 module = "this-doesnt-exist"
1421 };
1422 let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1423
1424 let error = manifest.validate().unwrap_err();
1425
1426 assert_eq!(
1427 error,
1428 ValidationError::MissingModuleForCommand {
1429 command: "cmd".to_string(),
1430 module: "this-doesnt-exist".parse().unwrap()
1431 }
1432 );
1433 }
1434
1435 #[test]
1436 fn use_builder_api_to_create_simplest_manifest() {
1437 let package =
1438 Package::builder("my/package", "1.0.0".parse().unwrap(), "My awesome package")
1439 .build()
1440 .unwrap();
1441 let manifest = Manifest::builder(package).build().unwrap();
1442
1443 manifest.validate().unwrap();
1444 }
1445
1446 #[test]
1447 fn deserialize_command_referring_to_module_from_dependency() {
1448 let wasmer_toml = toml! {
1449 [package]
1450 name = "some/package"
1451 version = "0.0.0"
1452 description = ""
1453
1454 [dependencies]
1455 dep = "1.2.3"
1456
1457 [[command]]
1458 name = "cmd"
1459 module = "dep:module"
1460 };
1461 let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1462
1463 let command = manifest
1464 .commands
1465 .iter()
1466 .find(|cmd| cmd.get_name() == "cmd")
1467 .unwrap();
1468
1469 assert_eq!(
1470 command.get_module(),
1471 &ModuleReference::Dependency {
1472 dependency: "dep".to_string(),
1473 module: "module".to_string()
1474 }
1475 );
1476 }
1477
1478 #[test]
1479 fn command_with_module_from_nonexistent_dependency() {
1480 let wasmer_toml = toml! {
1481 [package]
1482 name = "some/package"
1483 version = "0.0.0"
1484 description = ""
1485 [[command]]
1486 name = "cmd"
1487 module = "dep:module"
1488 };
1489 let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1490
1491 let error = manifest.validate().unwrap_err();
1492
1493 assert_eq!(
1494 error,
1495 ValidationError::MissingDependency {
1496 command: "cmd".to_string(),
1497 dependency: "dep".to_string(),
1498 module_ref: ModuleReference::Dependency {
1499 dependency: "dep".to_string(),
1500 module: "module".to_string()
1501 }
1502 }
1503 );
1504 }
1505
1506 #[test]
1507 fn round_trip_dependency_module_ref() {
1508 let original = ModuleReference::Dependency {
1509 dependency: "my/dep".to_string(),
1510 module: "module".to_string(),
1511 };
1512
1513 let repr = original.to_string();
1514 let round_tripped: ModuleReference = repr.parse().unwrap();
1515
1516 assert_eq!(round_tripped, original);
1517 }
1518}