1use std::{fs, path::PathBuf, sync::Arc};
23use clap::builder::TypedValueParser;
45#[derive(Debug, Clone)]
6struct Parser<C>(std::marker::PhantomData<C>);
78impl<C: ChainSpecParser> TypedValueParser for Parser<C> {
9type Value = Arc<C::ChainSpec>;
1011fn parse_ref(
12&self,
13 _cmd: &clap::Command,
14 arg: Option<&clap::Arg>,
15 value: &std::ffi::OsStr,
16 ) -> Result<Self::Value, clap::Error> {
17let val =
18value.to_str().ok_or_else(|| clap::Error::new(clap::error::ErrorKind::InvalidUtf8))?;
19C::parse(val).map_err(|err| {
20let arg = arg.map(|a| a.to_string()).unwrap_or_else(|| "...".to_owned());
21let possible_values = C::SUPPORTED_CHAINS.join(",");
22let msg = format!(
23"Invalid value '{val}' for {arg}: {err}.\n [possible values: {possible_values}]"
24);
25 clap::Error::raw(clap::error::ErrorKind::InvalidValue, msg)
26 })
27 }
28}
2930/// Trait for parsing chain specifications.
31///
32/// This trait extends [`clap::builder::TypedValueParser`] to provide a parser for chain
33/// specifications. Implementers of this trait must provide a list of supported chains and a
34/// function to parse a given string into a chain spec.
35pub trait ChainSpecParser: Clone + Send + Sync + 'static {
36/// The chain specification type.
37type ChainSpec: std::fmt::Debug + Send + Sync;
3839/// List of supported chains.
40const SUPPORTED_CHAINS: &'static [&'static str];
4142/// Parses the given string into a chain spec.
43 ///
44 /// # Arguments
45 ///
46 /// * `s` - A string slice that holds the chain spec to be parsed.
47 ///
48 /// # Errors
49 ///
50 /// This function will return an error if the input string cannot be parsed into a valid
51 /// chain spec.
52fn parse(s: &str) -> eyre::Result<Arc<Self::ChainSpec>>;
5354/// Produces a [`TypedValueParser`] for this chain spec parser.
55fn parser() -> impl TypedValueParser<Value = Arc<Self::ChainSpec>> {
56Parser(std::marker::PhantomData::<Self>)
57 }
5859/// Produces a help message for the chain spec argument.
60fn help_message() -> String {
61format!(
62"The chain this node is running.\nPossible values are either a built-in chain or the path to a chain specification file.\n\nBuilt-in chains:\n {}",
63Self::SUPPORTED_CHAINS.join(", ")
64 )
65 }
66}
6768/// A helper to parse a [`Genesis`](alloy_genesis::Genesis) as argument or from disk.
69pub fn parse_genesis(s: &str) -> eyre::Result<alloy_genesis::Genesis> {
70// try to read json from path first
71let raw = match fs::read_to_string(PathBuf::from(shellexpand::full(s)?.into_owned())) {
72Ok(raw) => raw,
73Err(io_err) => {
74// valid json may start with "\n", but must contain "{"
75if s.contains('{') {
76s.to_string()
77 } else {
78return Err(io_err.into()) // assume invalid path
79}
80 }
81 };
8283Ok(serde_json::from_str(&raw)?)
84}