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

Add --derives_for_type to cli #706

Closed
Closed
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
60 changes: 46 additions & 14 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ enum Command {
/// # Example (with code formatting)
///
/// `subxt codegen | rustfmt --edition=2018 --emit=stdout`
///
/// # Example with `derive_for_type` and `type_attr`.
///
/// `subxt codegen --derive_for_type my_module::my_type=serde::Serialize`
Codegen {
/// The url of the substrate node to query for metadata for codegen.
#[structopt(name = "url", long, parse(try_from_str))]
Expand All @@ -91,6 +95,11 @@ enum Command {
/// Additional derives
#[structopt(long = "derive")]
derives: Vec<String>,
/// Additional derives for a given type.
///
/// Example `--derive_for_type my_module::my_type=serde::Serialize`.
#[structopt(long = "derive_for_type", parse(try_from_str = derive_for_type_parser))]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit; can we go with derive-for-type please (ie dashes instead of underscores) :)

derives_for_type: Vec<(syn::TypePath, syn::Path)>,
},
/// Verify metadata compatibility between substrate nodes.
Compatibility {
Expand All @@ -106,6 +115,19 @@ enum Command {
},
}

fn derive_for_type_parser(src: &str) -> Result<(syn::TypePath, syn::Path), String> {
let (ty, derive) = src
.split_once('=')
.ok_or::<String>( "Invalid pattern for `derive_for_type`. It should be `type=derive`, like `my_type=serde::Serialize`".into())?;

let ty = syn::parse_str(ty)
.map_err(|e| format!("Target type `{:?}` cannot be parsed: {:?}", ty, e))?;
let derive = syn::parse_str(derive)
.map_err(|e| format!("Derive `{:?}` cannot be parsed: {:?}", derive, e))?;

Ok((ty, derive))
}

#[tokio::main]
async fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
Expand Down Expand Up @@ -136,27 +158,32 @@ async fn main() -> color_eyre::Result<()> {
}
}
}
Command::Codegen { url, file, derives } => {
if let Some(file) = file.as_ref() {
Command::Codegen {
url,
file,
derives,
derives_for_type,
} => {
let bytes = if let Some(file) = file.as_ref() {
if url.is_some() {
eyre::bail!("specify one of `--url` or `--file` but not both")
};

let mut file = fs::File::open(file)?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)?;
codegen(&mut &bytes[..], derives)?;
return Ok(())
}

let url = url.unwrap_or_else(|| {
"http://localhost:9933"
.parse::<Uri>()
.expect("default url is valid")
});
let (_, bytes) = fetch_metadata(&url).await?;
codegen(&mut &bytes[..], derives)?;
Ok(())
bytes
} else {
let url = url.unwrap_or_else(|| {
"http://localhost:9933"
.parse::<Uri>()
.expect("default url is valid")
});
let (_, bytes) = fetch_metadata(&url).await?;
bytes
};

codegen(&mut &bytes[..], derives, derives_for_type)
}
Command::Compatibility { nodes, pallet } => {
match pallet {
Expand Down Expand Up @@ -296,6 +323,7 @@ async fn fetch_metadata(url: &Uri) -> color_eyre::Result<(String, Vec<u8>)> {
fn codegen<I: Input>(
encoded: &mut I,
raw_derives: Vec<String>,
derives_for_type: Vec<(syn::TypePath, syn::Path)>,
) -> color_eyre::Result<()> {
let metadata = <RuntimeMetadataPrefixed as Decode>::decode(encoded)?;
let generator = subxt_codegen::RuntimeGenerator::new(metadata);
Expand All @@ -310,6 +338,10 @@ fn codegen<I: Input>(
let mut derives = DerivesRegistry::default();
derives.extend_for_all(p.into_iter());

for (ty, derive) in derives_for_type.into_iter() {
derives.extend_for_type(ty, std::iter::once(derive))
}

let runtime_api = generator.generate_runtime(item_mod, derives);
println!("{}", runtime_api);
Ok(())
Expand Down