Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add cargo component add command #18

Merged
merged 7 commits into from
Apr 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/bin/cargo-component.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use anyhow::Result;
use cargo::{CliError, Config};
use cargo_component::commands::{BuildCommand, CheckCommand, MetadataCommand, NewCommand};
use cargo_component::commands::{
AddCommand, BuildCommand, CheckCommand, MetadataCommand, NewCommand,
};
use clap::Parser;

/// Cargo integration for WebAssembly components.
Expand All @@ -25,6 +27,7 @@ pub enum Command {
Build(BuildCommand),
Metadata(MetadataCommand),
Check(CheckCommand),
Add(AddCommand),
}

fn main() -> Result<()> {
Expand All @@ -39,6 +42,7 @@ fn main() -> Result<()> {
Command::Build(cmd) => cmd.exec(&mut config),
Command::Metadata(cmd) => cmd.exec(&mut config),
Command::Check(cmd) => cmd.exec(&mut config),
Command::Add(cmd) => cmd.exec(&mut config),
},
} {
cargo::exit_with_error(
Expand Down
2 changes: 2 additions & 0 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ use cargo::{core::Workspace, util::important_paths::find_root_manifest_for_wd, C
use cargo_util::paths::normalize_path;
use std::path::{Path, PathBuf};

mod add;
mod build;
mod check;
mod metadata;
mod new;

pub use self::add::*;
pub use self::build::*;
pub use self::check::*;
pub use self::metadata::*;
Expand Down
192 changes: 192 additions & 0 deletions src/commands/add.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
use super::workspace;
use crate::ComponentMetadata;
use anyhow::{bail, Context, Result};
use cargo::{core::package::Package, ops::Packages, Config};
use clap::Args;
use std::{fs, path::PathBuf};
use toml_edit::{table, value, Document, InlineTable, Value};

/// Add a depency for a WebAssembly component
#[derive(Args)]
pub struct AddCommand {
/// Do not print cargo log messages
#[clap(long = "quiet", short = 'q')]
pub quiet: bool,
///
/// Use verbose output (-vv very verbose/build.rs output)
#[clap(
long = "verbose",
short = 'v',
takes_value = false,
parse(from_occurrences)
)]
pub verbose: u32,

/// Coloring: auto, always, never
#[clap(long = "color", value_name = "WHEN")]
pub color: Option<String>,

/// Path to the interface definition of the dependency
#[clap(long = "path", value_name = "PATH")]
pub path: String,

/// Set the version of the dependency
#[clap(long = "version", value_name = "VERSION")]
pub version: Option<String>,

/// Name of the dependency
#[clap(value_name = "name")]
pub name: String,

/// Set the dependency as an exported interface
#[clap(long = "export")]
pub export: bool,

/// Path to the manifest to add a dependency to
#[clap(long = "manifest-path", value_name = "PATH")]
pub manifest_path: Option<PathBuf>,

/// Don't actually write the manifest
#[clap(long = "dry-run")]
pub dry_run: bool,

/// Package to add the dependency to (see `cargo help pkgid`)
#[clap(long = "package", short = 'p', value_name = "SPEC")]
pub package: Option<String>,
}

impl AddCommand {
/// Executes the command
pub fn exec(self, config: &mut Config) -> Result<()> {
config.configure(
self.verbose,
self.quiet,
self.color.as_deref(),
false,
false,
false,
&None,
&[],
&[],
)?;

let ws = workspace(self.manifest_path.as_deref(), config)?;
let package = if let Some(ref inner) = self.package {
let pkg = Packages::from_flags(false, vec![], vec![inner.clone()])?;
let packages = pkg.get_packages(&ws)?;

packages[0]
} else {
ws.current()?
};

let component_metadata = ComponentMetadata::from_package(config, &package)?;

self.validate(&component_metadata)
.and_then(|_| self.add(&package))?;

let status = if let Some(v) = self.version {
format!("interface {} v{} to dependencies", self.name, v)
} else {
format!("interface {} to dependencies", self.name)
};

config.shell().status("Adding", status)?;

Ok(())
}

fn add(&self, pkg: &Package) -> Result<()> {
let manifest_path = pkg.manifest_path();
let manifest = fs::read_to_string(&manifest_path).with_context(|| {
format!("failed to read manifest file `{}`", manifest_path.display())
})?;

let mut document: Document = manifest.parse().with_context(|| {
format!(
"failed to parse manifest file `{}`",
manifest_path.display()
)
})?;

let component = &mut document["package"]["metadata"]["component"]
.as_table_mut()
.with_context(|| {
format!(
"failed to find component metadata in manifest file `{}`",
manifest_path.display()
)
})?;

let deps = component.entry("dependencies").or_insert(table());
let mut inline_table = vec![("path", Value::from(self.path.clone()))];

if let Some(v) = &self.version {
inline_table.push(("version", Value::from(v.clone())));
}

if self.export {
inline_table.push(("export", Value::from(true)));
}

deps[&self.name] = value(InlineTable::from_iter(inline_table));

if self.dry_run {
println!("{}", document.to_string());
} else {
fs::write(&manifest_path, document.to_string()).with_context(|| {
format!(
"failed to write manifest file `{}`",
manifest_path.display()
)
})?;
}

Ok(())
}

fn validate(&self, metadata: &ComponentMetadata) -> Result<()> {
let path = PathBuf::from(&self.path);
if !path.exists() {
bail!("interface file `{}` doesn't exists", path.display());
}

if self.export {
// Validate default export
if let Some(default) = &metadata.interface {
if self.version.is_none() || self.name == default.interface.name {
bail!(
"{} is already declared as the default interface",
default.interface.name
);
}
}
} else {
if self.version.is_none() {
bail!("version not specified for import `{}`", self.name);
}
}

// Validate exports
let export = metadata
.exports
.iter()
.find(|e| self.name == e.interface.name);

if export.is_some() {
bail!("{} is already declared as an export", self.name);
}

// Validate imports
let import = metadata
.imports
.iter()
.find(|i| i.interface.name == self.name);

if import.is_some() {
bail!("{} is already declared as an import", self.name);
}

Ok(())
}
}