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(help): possible values #133

Merged
merged 3 commits into from
May 3, 2024
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
74 changes: 60 additions & 14 deletions crates/pop-cli/src/commands/new/parachain.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,35 @@
// SPDX-License-Identifier: GPL-3.0
use crate::style::{style, Theme};
use anyhow::Result;
use clap::Args;
use clap::{
builder::{PossibleValue, PossibleValuesParser, TypedValueParser},
Args,
};
use std::{
fs,
path::{Path, PathBuf},
str::FromStr,
};

use cliclack::{clear_screen, confirm, input, intro, log, outro, outro_cancel, set_theme};
use pop_parachains::{instantiate_template_dir, Config, Git, GitHub, Provider, Release, Template};
use strum::VariantArray;

#[derive(Args)]
pub struct NewParachainCommand {
#[arg(help = "Name of the project. If empty assistance in the process will be provided.")]
pub(crate) name: Option<String>,
#[arg(
help = "Template provider. Options are pop or parity (deprecated).",
default_value = "pop"
help = "Template provider.",
default_value = Provider::Pop.as_ref(),
value_parser = crate::enum_variants!(Provider)
)]
pub(crate) provider: Option<Provider>,
#[arg(
short = 't',
long,
help = "Template to use: 'base' for Pop and 'cpt' and 'fpt' for Parity templates"
help = "Template to use.",
value_parser = crate::enum_variants!(Template)
)]
pub(crate) template: Option<Template>,
#[arg(long, short, help = "Token Symbol", default_value = "UNIT")]
Expand All @@ -44,6 +51,21 @@ pub struct NewParachainCommand {
pub(crate) path: Option<PathBuf>,
}

#[macro_export]
macro_rules! enum_variants {
($e: ty) => {{
PossibleValuesParser::new(
<$e>::VARIANTS
.iter()
.map(|p| PossibleValue::new(p.as_ref()))
.collect::<Vec<_>>(),
)
.try_map(|s| {
<$e>::from_str(&s).map_err(|e| format!("could not convert from {s} to provider"))
})
}};
}

impl NewParachainCommand {
pub(crate) async fn execute(&self) -> Result<()> {
clear_screen()?;
Expand Down Expand Up @@ -268,34 +290,58 @@ fn prompt_customizable_options() -> Result<Config> {
#[cfg(test)]
mod tests {

use super::*;
use crate::{
commands::new::{NewArgs, NewCommands::Parachain},
Cli,
Commands::New,
};
use clap::Parser;
use git2::Repository;
use tempfile::tempdir;

use super::*;
use std::{fs, path::Path};
#[tokio::test]
async fn test_new_parachain_command_with_defaults_executes() -> Result<()> {
let dir = tempdir()?;
let cli = Cli::parse_from([
"pop",
"new",
"parachain",
dir.path().join("test_parachain").to_str().unwrap(),
]);

let New(NewArgs { command: Parachain(command) }) = cli.command else {
panic!("unable to parse command")
};
// Execute
let name = command.name.as_ref().unwrap();
command.execute().await?;
// check for git_init
let repo = Repository::open(Path::new(name))?;
let reflog = repo.reflog("HEAD")?;
assert_eq!(reflog.len(), 1);
Ok(())
}

#[tokio::test]
async fn test_new_parachain_command_execute() -> anyhow::Result<()> {
async fn test_new_parachain_command_execute() -> Result<()> {
let dir = tempdir()?;
let command = NewParachainCommand {
name: Some("test_parachain".to_string()),
name: Some(dir.path().join("test_parachain").to_str().unwrap().to_string()),
provider: Some(Provider::Pop),
template: Some(Template::Base),
symbol: Some("UNIT".to_string()),
decimals: Some(12),
initial_endowment: Some("1u64 << 60".to_string()),
path: None,
};
let result = command.execute().await;
assert!(result.is_ok());
command.execute().await?;

// check for git_init
let repo = Repository::open(Path::new(&command.name.unwrap()))?;
let reflog = repo.reflog("HEAD")?;
assert_eq!(reflog.len(), 1);

// Clean up
if let Err(err) = fs::remove_dir_all("test_parachain") {
eprintln!("Failed to delete directory: {}", err);
}
Ok(())
}

Expand Down
7 changes: 7 additions & 0 deletions crates/pop-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,10 @@ fn cache() -> Result<PathBuf> {
create_dir_all(cache_path.as_path())?;
Ok(cache_path)
}

#[test]
fn verify_cli() {
// https://docs.rs/clap/latest/clap/_derive/_tutorial/chapter_4/index.html
use clap::CommandFactory;
Cli::command().debug_assert()
}
12 changes: 9 additions & 3 deletions crates/pop-parachains/src/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,24 @@
use strum::{
EnumMessage as EnumMessageT, EnumProperty as EnumPropertyT, VariantArray as VariantArrayT,
};
use strum_macros::{Display, EnumMessage, EnumProperty, EnumString, VariantArray};
use strum_macros::{AsRefStr, Display, EnumMessage, EnumProperty, EnumString, VariantArray};
use thiserror::Error;

#[derive(Clone, Default, Debug, Display, EnumMessage, EnumString, Eq, PartialEq, VariantArray)]
#[derive(
AsRefStr, Clone, Default, Debug, Display, EnumMessage, EnumString, Eq, PartialEq, VariantArray,
)]
pub enum Provider {
#[default]
#[strum(
ascii_case_insensitive,
serialize = "pop",
message = "Pop",
detailed_message = "An all-in-one tool for Polkadot development."
)]
Pop,
#[strum(
ascii_case_insensitive,
serialize = "parity",
message = "Parity",
detailed_message = "Solutions for a trust-free world."
)]
Expand Down Expand Up @@ -58,6 +62,7 @@ pub struct Config {
}

#[derive(
AsRefStr,
Clone,
Debug,
Default,
Expand Down Expand Up @@ -111,7 +116,8 @@ impl Template {
}

pub fn matches(&self, provider: &Provider) -> bool {
self.get_str("Provider") == Some(provider.to_string().as_str())
// Match explicitly on provider name (message)
self.get_str("Provider") == Some(provider.name())
}

pub fn repository_url(&self) -> Result<&str, Error> {
Expand Down
Loading