Skip to content

Commit

Permalink
feat(gcli): override paths on feature embed
Browse files Browse the repository at this point in the history
  • Loading branch information
clearloop committed Dec 14, 2023
1 parent c9ab66c commit 7aec959
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 68 deletions.
52 changes: 0 additions & 52 deletions gcli/src/cmd/meta.rs

This file was deleted.

15 changes: 15 additions & 0 deletions gcli/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,21 @@ impl Command {

Ok(())
}

#[cfg(feature = "embed")]
pub async fn exec_embedded(
self,
app: &impl App,
artifact: crate::embed::Artifact,
) -> anyhow::Result<()> {
let this = match self {
Command::Upload(upload) => Command::Upload(upload.override_code(artifact.opt)),
Command::Program(program) => Command::Program(program.try_override_meta(artifact.meta)),
_ => self,
};

Self::exec(&this, app).await
}
}

/// Gear command-line interface.
Expand Down
20 changes: 17 additions & 3 deletions gcli/src/cmd/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Command `program`.
use crate::{meta::Meta, result::Result, App};
use crate::{meta::Meta, result::Result, utils, App};
use clap::Parser;
use gsdk::{ext::sp_core::H256, Api};
use std::{fs, path::PathBuf};
Expand All @@ -33,7 +33,8 @@ pub enum Program {
///
/// - "*.meta.txt" describes the metadata of the program
/// - "*.meta.wasm" describes the wasm exports of the program
meta: PathBuf,
#[arg(short, long)]
meta: Option<PathBuf>,
/// Derive the description of the specified type from registry.
#[arg(short, long)]
derive: Option<String>,
Expand All @@ -60,6 +61,17 @@ pub enum Program {
}

impl Program {
/// Try override meta path.
pub fn try_override_meta(mut self, meta: Option<PathBuf>) -> Self {
if let Program::Meta { meta: m, .. } = &mut self {
if m.is_none() {
*m = meta;
}
}

self
}

/// Run command program.
pub async fn exec(&self, app: &impl App) -> Result<()> {
match self {
Expand All @@ -79,7 +91,9 @@ impl Program {
Self::full_state(api, *pid, *at).await?;
}
}
Program::Meta { meta, derive } => Self::meta(meta, derive)?,
Program::Meta { meta, derive } => {
Self::meta(&utils::meta_path(meta.clone(), "meta")?, derive)?
}
}

Ok(())
Expand Down
9 changes: 8 additions & 1 deletion gcli/src/cmd/upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ use std::{fs, path::PathBuf};
/// Deploy program to gear node or save program `code` in storage.
#[derive(Parser, Debug)]
pub struct Upload {
/// gear program code <*.wasm>
/// Gear program code <*.wasm>.
#[cfg_attr(feature = "embed", clap(skip))]
code: PathBuf,
/// Save program `code` in storage only.
#[arg(short, long)]
Expand All @@ -50,6 +51,12 @@ pub struct Upload {
}

impl Upload {
/// Override code path.
pub fn override_code(mut self, code: PathBuf) -> Self {
self.code = code;
self
}

/// Exec command submit
pub async fn exec(&self, signer: Signer) -> Result<()> {
let code =
Expand Down
41 changes: 30 additions & 11 deletions gcli/src/embed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@

use std::path::PathBuf;

/// This macro is used to lookup the artifact from the `OUT_DIR`.
/// This macro is used to lookup the artifact from the `OUT_DIR`,
/// it's just a wrapper around [`Artifact::from_out_dir`] for
/// avoiding importing [`Artifact`] in users' code.
///
/// NOTE: This macro should only be used in external crates.
#[macro_export]
macro_rules! lookup {
() => {{
Expand All @@ -38,7 +42,13 @@ const OUT_SUFFIX_LENGTH: usize = 17;
#[derive(Debug)]
pub struct Artifact {
/// Path of the optitmized WASM binary.
///
/// TODO: load the binary into memory instead of file path in
/// case of users renaming the binary after the build. (#3592)
pub opt: PathBuf,

/// Path of the metadata WASM binary.
pub meta: Option<PathBuf>,
}

impl Artifact {
Expand All @@ -53,19 +63,28 @@ impl Artifact {
.nth(1)?
.file_name()?
.to_str()
.map(|name| name.get(..name.len().checked_sub(OUT_SUFFIX_LENGTH)?))
.flatten()?,
(ancestors.nth(1)?.file_name()?.to_str()? == "debug")
.then(|| "debug")
.unwrap_or("release"),
.and_then(|name| name.get(..name.len().checked_sub(OUT_SUFFIX_LENGTH)?))?,
if ancestors.nth(1)?.file_name()?.to_str()? == "debug" {
"debug"
} else {
"release"
},
ancestors.next()?.to_str()?,
];

let opt = PathBuf::from(format!(
"{target}/wasm32-unknown-unknown/{profile}/{}.opt.wasm",
name.replace('-', "_")
));
let [bin, stem] = [
PathBuf::from(format!("{target}/wasm32-unknown-unknown/{profile}")),
PathBuf::from(name.replace('-', "_")),
];

let [opt, meta] = [
bin.join(stem.with_extension("wasm")),
bin.join(stem.with_extension("meta.wasm")),
];

opt.exists().then(|| Self { opt })
opt.exists().then(|| Self {
opt,
meta: meta.exists().then_some(meta),
})
}
}
22 changes: 21 additions & 1 deletion gcli/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
use crate::result::Result;
use anyhow::anyhow;
use std::{fs, path::PathBuf};
use std::{env, fs, path::PathBuf};

/// home directory of cli `gear`
pub fn home() -> PathBuf {
Expand All @@ -33,6 +33,26 @@ pub fn home() -> PathBuf {
home
}

/// Parse the metadata path with result.
pub fn meta_path(meta: Option<PathBuf>, opt: &str) -> Result<PathBuf> {
if let Some(meta) = meta {
return Ok(meta);
}

let cwd = env::current_dir()?;
for entry in fs::read_dir(&cwd)? {
let file = entry?.path();
if file.ends_with(".meta.wasm") {
return Ok(file);
}
}

Err(anyhow!(
"Could not find any *.meta.wasm in {cwd:?}, please specify the metadata path with --{opt}",
)
.into())
}

pub trait Hex {
fn to_vec(&self) -> Result<Vec<u8>>;
fn to_hash(&self) -> Result<[u8; 32]>;
Expand Down

0 comments on commit 7aec959

Please sign in to comment.