wac_cli/commands/
targets.rs1use anyhow::{bail, Context, Result};
2use clap::Args;
3use std::{
4 fs,
5 path::{Path, PathBuf},
6};
7use wac_types::{validate_target, ItemKind, Package, Types, WorldId};
8
9#[derive(Args)]
11#[clap(disable_version_flag = true)]
12pub struct TargetsCommand {
13 #[clap(value_name = "COMPONENT_PATH")]
15 pub component: PathBuf,
16 #[clap(long, value_name = "WIT_PATH")]
18 pub wit: PathBuf,
19 #[clap(long)]
23 pub world: Option<String>,
24}
25
26impl TargetsCommand {
27 pub async fn exec(self) -> Result<()> {
29 log::debug!("executing targets command");
30 let mut types = Types::default();
31
32 let wit_bytes = encode_wit_as_component(&self.wit)?;
33 let wit = Package::from_bytes("wit", None, wit_bytes, &mut types)?;
34
35 let component_bytes = fs::read(&self.component).with_context(|| {
36 format!(
37 "failed to read file `{path}`",
38 path = self.component.display()
39 )
40 })?;
41 let component = Package::from_bytes("component", None, component_bytes, &mut types)?;
42
43 let wit = get_wit_world(&types, wit.ty(), self.world.as_deref())?;
44
45 validate_target(&types, wit, component.ty())?;
46
47 Ok(())
48 }
49}
50
51fn get_wit_world(
53 types: &Types,
54 top_level_world: WorldId,
55 world_name: Option<&str>,
56) -> anyhow::Result<WorldId> {
57 let top_level_world = &types[top_level_world];
58 let world = match world_name {
59 Some(world_name) => top_level_world
60 .exports
61 .get(world_name)
62 .with_context(|| format!("wit package did not contain a world named '{world_name}'"))?,
63 None if top_level_world.exports.len() == 1 => {
64 top_level_world.exports.values().next().unwrap()
65 }
66 None if top_level_world.exports.len() > 1 => {
67 bail!("wit package has multiple worlds, please specify one with the --world flag")
68 }
69 None => {
70 bail!("wit package did not contain a world")
71 }
72 };
73 let ItemKind::Type(wac_types::Type::World(world_id)) = world else {
74 bail!("wit package was not encoded properly")
76 };
77 let wit_world = &types[*world_id];
78 let world = wit_world.exports.values().next();
79 let Some(ItemKind::Component(w)) = world else {
80 bail!("wit package was not encoded properly")
82 };
83 Ok(*w)
84}
85
86fn encode_wit_as_component(path: &Path) -> anyhow::Result<Vec<u8>> {
88 let mut resolve = wit_parser::Resolve::new();
89 let pkg = if path.is_dir() {
90 log::debug!(
91 "loading WIT package from directory `{path}`",
92 path = path.display()
93 );
94
95 let (pkg, _) = resolve.push_dir(path)?;
96 pkg
97 } else {
98 resolve.push_path(path)?.0
99 };
100 let encoded = wit_component::encode(&resolve, pkg).with_context(|| {
101 format!(
102 "failed to encode WIT package from `{path}`",
103 path = path.display()
104 )
105 })?;
106 Ok(encoded)
107}