Skip to content

Commit

Permalink
refactor: move extract_template_files into common crate (#283)
Browse files Browse the repository at this point in the history
* refactor: move extract_template_files into common crate

* fix: unnnecesary API query

* refactor: directories instead of folders (#286)

* refactor: directories instead of folders

* style: fmt

* stable fmt

---------

Co-authored-by: Alejandro Martinez Andres <[email protected]>
  • Loading branch information
AlexD10S and al3mart authored Aug 27, 2024
1 parent 11ea129 commit e829471
Show file tree
Hide file tree
Showing 37 changed files with 266 additions and 239 deletions.
4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ All notable changes to this project will be documented in this file.

- Handle IO error if rename fails (#241)
- Readme commands (#243)
- Remove unused folders after download contracts node binary (#240)
- Remove unused directories after download contracts node binary (#240)
- Check if contracts needs to be build before deploy (#246)

### 🚜 Refactor
Expand Down Expand Up @@ -163,7 +163,7 @@ All notable changes to this project will be documented in this file.
- Structure for call command
- Call a smart contract
- Execute call flag
- *(pop-cli)* Pallets folder for new ones
- *(pop-cli)* Pallets directory for new ones
- *(up-parachain)* Improve ux
- Init git repo (#65)
- *(up-parachain)* Enable optional verbose output (#79)
Expand Down
4 changes: 2 additions & 2 deletions crates/pop-cli/src/commands/build/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ pub struct BuildContractCommand {
/// Path for the contract project [default: current directory]
#[arg(long)]
pub(crate) path: Option<PathBuf>,
/// The default compilation includes debug functionality, increasing contract size and gas usage.
/// For production, always build in release mode to exclude debug features.
/// The default compilation includes debug functionality, increasing contract size and gas
/// usage. For production, always build in release mode to exclude debug features.
#[clap(short, long)]
pub(crate) release: bool,
// Deprecation flag, used to specify whether the deprecation warning is shown.
Expand Down
3 changes: 2 additions & 1 deletion crates/pop-cli/src/commands/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ pub(crate) enum Command {
#[cfg(feature = "parachain")]
#[clap(alias = "p")]
Parachain(BuildParachainCommand),
/// [DEPRECATED] Build a contract, generate metadata, bundle together in a `<name>.contract` file
/// [DEPRECATED] Build a contract, generate metadata, bundle together in a `<name>.contract`
/// file
#[cfg(feature = "contract")]
#[clap(alias = "c")]
Contract(BuildContractCommand),
Expand Down
2 changes: 1 addition & 1 deletion crates/pop-cli/src/commands/build/parachain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ mod tests {
use duct::cmd;
use std::{fs, io::Write, path::Path};

// Function that generates a Cargo.toml inside node folder for testing.
// Function that generates a Cargo.toml inside node directory for testing.
fn generate_mock_node(temp_dir: &Path) -> anyhow::Result<()> {
// Create a node directory
let target_dir = temp_dir.join("node");
Expand Down
8 changes: 6 additions & 2 deletions crates/pop-cli/src/commands/build/spec.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
// SPDX-License-Identifier: GPL-3.0

use crate::{cli, cli::traits::Cli as _, cli::Cli, style::style};
use crate::{
cli,
cli::{traits::Cli as _, Cli},
style::style,
};
use clap::{Args, ValueEnum};
use cliclack::{confirm, input};
use pop_common::Profile;
Expand Down Expand Up @@ -221,7 +225,7 @@ impl BuildSpecCommand {
// Locate binary, if it doesn't exist trigger build.
let mode: Profile = self.release.into();
let cwd = current_dir().unwrap_or(PathBuf::from("./"));
let binary_path = match binary_path(&mode.target_folder(&cwd), &cwd.join("node")) {
let binary_path = match binary_path(&mode.target_directory(&cwd), &cwd.join("node")) {
Ok(binary_path) => binary_path,
_ => {
cli.info("Node was not found. The project will be built locally.".to_string())?;
Expand Down
2 changes: 1 addition & 1 deletion crates/pop-cli/src/commands/call/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use std::path::PathBuf;

#[derive(Args)]
pub struct CallContractCommand {
/// Path to the contract build folder.
/// Path to the contract build directory.
#[arg(short = 'p', long)]
path: Option<PathBuf>,
/// The address of the contract to call.
Expand Down
6 changes: 4 additions & 2 deletions crates/pop-cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,14 @@ impl Command {
},
#[cfg(feature = "parachain")]
new::Command::Pallet(cmd) => {
// When more contract selections are added the tel data will likely need to go deeper in the stack
// When more contract selections are added the tel data will likely need to go
// deeper in the stack
cmd.execute().await.map(|_| json!("template"))
},
#[cfg(feature = "contract")]
new::Command::Contract(cmd) => {
// When more contract selections are added, the tel data will likely need to go deeper in the stack
// When more contract selections are added, the tel data will likely need to go
// deeper in the stack
cmd.execute().await.map(|_| json!("default"))
},
},
Expand Down
2 changes: 1 addition & 1 deletion crates/pop-cli/src/commands/new/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl NewContractCommand {
let contract_type = &contract_config.contract_type.clone().unwrap_or_default();
let template = match &contract_config.template {
Some(template) => template.clone(),
None => contract_type.default_template().expect("contract types have defaults; qed."), // Default contract type
None => contract_type.default_template().expect("contract types have defaults; qed."), /* Default contract type */
};

is_template_supported(contract_type, &template)?;
Expand Down
9 changes: 5 additions & 4 deletions crates/pop-cli/src/commands/new/parachain.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// SPDX-License-Identifier: GPL-3.0

use crate::cli::{traits::Cli as _, Cli};
use crate::style::style;
use crate::{
cli::{traits::Cli as _, Cli},
style::style,
};
use anyhow::Result;
use clap::{
builder::{PossibleValue, PossibleValuesParser, TypedValueParser},
Expand Down Expand Up @@ -78,7 +80,7 @@ impl NewParachainCommand {
let provider = &parachain_config.provider.clone().unwrap_or_default();
let template = match &parachain_config.template {
Some(template) => template.clone(),
None => provider.default_template().expect("parachain templates have defaults; qed."), // Each provider has a template by default
None => provider.default_template().expect("parachain templates have defaults; qed."), /* Each provider has a template by default */
};

is_template_supported(provider, &template)?;
Expand Down Expand Up @@ -313,7 +315,6 @@ async fn choose_release(template: &Parachain) -> Result<Option<String>> {
async fn get_latest_3_releases(repo: &GitHub) -> Result<Vec<Release>> {
let mut latest_3_releases: Vec<Release> =
repo.releases().await?.into_iter().filter(|r| !r.prerelease).take(3).collect();
repo.get_repo_license().await?;
// Get the commit sha for the releases
for release in latest_3_releases.iter_mut() {
let commit = repo.get_commit_sha_from_release(&release.tag_name).await?;
Expand Down
16 changes: 9 additions & 7 deletions crates/pop-cli/src/commands/up/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@ use pop_contracts::{
};
use sp_core::Bytes;
use sp_weights::Weight;
use std::process::Child;
use std::{
path::{Path, PathBuf},
process::Command,
process::{Child, Command},
};
use tempfile::NamedTempFile;
use url::Url;
Expand All @@ -30,7 +29,7 @@ const FAILED: &str = "🚫 Deployment failed.";

#[derive(Args, Clone)]
pub struct UpContractCommand {
/// Path to the contract build folder.
/// Path to the contract build directory.
#[arg(short = 'p', long)]
path: Option<PathBuf>,
/// The name of the contract constructor to call.
Expand Down Expand Up @@ -71,7 +70,8 @@ pub struct UpContractCommand {
/// Uploads the contract only, without instantiation.
#[clap(short('u'), long)]
upload_only: bool,
/// Automatically source or update the needed binary required without prompting for confirmation.
/// Automatically source or update the needed binary required without prompting for
/// confirmation.
#[clap(short('y'), long)]
skip_confirm: bool,
}
Expand All @@ -81,7 +81,7 @@ impl UpContractCommand {
pub(crate) async fn execute(mut self) -> anyhow::Result<()> {
Cli.intro("Deploy a smart contract")?;

// Check if build exists in the specified "Contract build folder"
// Check if build exists in the specified "Contract build directory"
if !has_contract_been_built(self.path.as_deref()) {
// Build the contract in release mode
Cli.warning("NOTE: contract has not yet been built.")?;
Expand Down Expand Up @@ -313,10 +313,12 @@ impl From<UpContractCommand> for UpOpts {
}
}

/// Checks if a contract has been built by verifying the existence of the build directory and the <name>.contract file.
/// Checks if a contract has been built by verifying the existence of the build directory and the
/// <name>.contract file.
///
/// # Arguments
/// * `path` - An optional path to the project directory. If no path is provided, the current directory is used.
/// * `path` - An optional path to the project directory. If no path is provided, the current
/// directory is used.
pub fn has_contract_been_built(path: Option<&Path>) -> bool {
let project_path = path.unwrap_or_else(|| Path::new("./"));
let manifest = match from_path(Some(project_path)) {
Expand Down
16 changes: 8 additions & 8 deletions crates/pop-cli/src/commands/up/parachain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,21 @@ pub(crate) struct ZombienetCommand {
/// The Zombienet network configuration file to be used.
#[arg(short, long)]
file: String,
/// The version of the binary to be used for the relay chain, as per the release tag (e.g. "v1.13.0").
/// See https://github.com/paritytech/polkadot-sdk/releases for more details.
/// The version of the binary to be used for the relay chain, as per the release tag (e.g.
/// "v1.13.0"). See https://github.com/paritytech/polkadot-sdk/releases for more details.
#[arg(short, long)]
relay_chain: Option<String>,
/// The version of the runtime to be used for the relay chain, as per the release tag (e.g. "v1.2.7").
/// See https://github.com/polkadot-fellows/runtimes/releases for more details.
/// The version of the runtime to be used for the relay chain, as per the release tag (e.g.
/// "v1.2.7"). See https://github.com/polkadot-fellows/runtimes/releases for more details.
#[arg(short = 'R', long)]
relay_chain_runtime: Option<String>,
/// The version of the binary to be used for system parachains, as per the release tag (e.g. "v1.13.0").
/// Defaults to the relay chain version if not specified.
/// The version of the binary to be used for system parachains, as per the release tag (e.g.
/// "v1.13.0"). Defaults to the relay chain version if not specified.
/// See https://github.com/paritytech/polkadot-sdk/releases for more details.
#[arg(short, long)]
system_parachain: Option<String>,
/// The version of the runtime to be used for system parachains, as per the release tag (e.g. "v1.2.7").
/// See https://github.com/polkadot-fellows/runtimes/releases for more details.
/// The version of the runtime to be used for system parachains, as per the release tag (e.g.
/// "v1.2.7"). See https://github.com/polkadot-fellows/runtimes/releases for more details.
#[arg(short = 'S', long)]
system_parachain_runtime: Option<String>,
/// The url of the git repository of a parachain to be used, with branch/release tag/commit specified as #fragment (e.g. 'https://github.com/org/repository#ref').
Expand Down
3 changes: 2 additions & 1 deletion crates/pop-cli/src/common/contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ use cliclack::{confirm, log::warning, spinner};
use pop_contracts::contracts_node_generator;
use std::path::PathBuf;

/// Checks the status of the `substrate-contracts-node` binary, sources it if necessary, and prompts the user to update it if the existing binary is not the latest version.
/// Checks the status of the `substrate-contracts-node` binary, sources it if necessary, and
/// prompts the user to update it if the existing binary is not the latest version.
///
/// # Arguments
/// * `skip_confirm`: A boolean indicating whether to skip confirmation prompts.
Expand Down
3 changes: 2 additions & 1 deletion crates/pop-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ async fn main() -> Result<()> {

#[cfg(feature = "telemetry")]
if let Some(tel) = maybe_tel.clone() {
// `args` is guaranteed to have at least 3 elements as clap will display help message if not set.
// `args` is guaranteed to have at least 3 elements as clap will display help message if not
// set.
let (command, subcommand) = parse_args(args().collect());

if let Ok(sub_data) = &res {
Expand Down
5 changes: 3 additions & 2 deletions crates/pop-cli/tests/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async fn contract_lifecycle() -> Result<()> {
.args(&["build", "--path", "./test_contract", "--release"])
.assert()
.success();
// Verify that the folder target has been created
// Verify that the directory target has been created
assert!(temp_dir.join("test_contract/target").exists());
// Verify that all the artifacts has been generated
assert!(temp_dir.join("test_contract/target/ink/test_contract.contract").exists());
Expand Down Expand Up @@ -71,7 +71,8 @@ async fn contract_lifecycle() -> Result<()> {
])
.assert()
.success();
// Using methods from the pop_contracts crate to instantiate it to get the Contract Address for the call
// Using methods from the pop_contracts crate to instantiate it to get the Contract Address for
// the call
let instantiate_exec = set_up_deployment(UpOpts {
path: Some(temp_dir.join("test_contract")),
constructor: "new".to_string(),
Expand Down
3 changes: 2 additions & 1 deletion crates/pop-cli/tests/parachain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ async fn parachain_lifecycle() -> Result<()> {
assert!(temp_dir.join("test_parachain/target").exists());

let temp_parachain_dir = temp_dir.join("test_parachain");
// pop build spec --output ./target/pop/test-spec.json --id 2222 --type development --relay paseo-local --protocol-id pop-protocol"
// pop build spec --output ./target/pop/test-spec.json --id 2222 --type development --relay
// paseo-local --protocol-id pop-protocol"
Command::cargo_bin("pop")
.unwrap()
.current_dir(&temp_parachain_dir)
Expand Down
4 changes: 2 additions & 2 deletions crates/pop-common/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ pub enum Profile {
}

impl Profile {
/// Returns the corresponding path to the target folder.
pub fn target_folder(&self, path: &Path) -> PathBuf {
/// Returns the corresponding path to the target directory.
pub fn target_directory(&self, path: &Path) -> PathBuf {
match self {
Profile::Release => path.join("target/release"),
Profile::Debug => path.join("target/debug"),
Expand Down
8 changes: 4 additions & 4 deletions crates/pop-common/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ use std::{
/// # Arguments
///
/// * `file_path` - A `PathBuf` specifying the path to the file to be modified.
/// * `replacements` - A `HashMap` where each key-value pair represents
/// a target string and its corresponding replacement string.
///
/// * `replacements` - A `HashMap` where each key-value pair represents a target string and its
/// corresponding replacement string.
pub fn replace_in_file(file_path: PathBuf, replacements: HashMap<&str, &str>) -> Result<(), Error> {
// Read the file content
let mut file_content = String::new();
Expand All @@ -31,7 +30,8 @@ pub fn replace_in_file(file_path: PathBuf, replacements: HashMap<&str, &str>) ->
Ok(())
}

/// Gets the last component (name of a project) of a path or returns a default value if the path has no valid last component.
/// Gets the last component (name of a project) of a path or returns a default value if the path has
/// no valid last component.
///
/// # Arguments
/// * `path` - Location path of the project.
Expand Down
1 change: 1 addition & 0 deletions crates/pop-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub use build::Profile;
pub use errors::Error;
pub use git::{Git, GitHub, Release};
pub use helpers::{get_project_name_from_path, replace_in_file};
pub use templates::extractor::extract_template_files;

static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

Expand Down
6 changes: 4 additions & 2 deletions crates/pop-common/src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ use toml_edit::{value, DocumentMut, Item, Value};
/// Parses the contents of a `Cargo.toml` manifest.
///
/// # Arguments
/// * `path` - The optional path to the manifest, defaulting to the current directory if not specified.
/// * `path` - The optional path to the manifest, defaulting to the current directory if not
/// specified.
pub fn from_path(path: Option<&Path>) -> Result<Manifest, Error> {
// Resolve manifest path
let path = match path {
Expand All @@ -28,7 +29,8 @@ pub fn from_path(path: Option<&Path>) -> Result<Manifest, Error> {
Ok(Manifest::from_path(path.canonicalize()?)?)
}

/// This function is used to determine if a Path is contained inside a workspace, and returns a PathBuf to the workspace Cargo.toml if found
/// This function is used to determine if a Path is contained inside a workspace, and returns a
/// PathBuf to the workspace Cargo.toml if found
///
/// # Arguments
/// * `target_dir` - A directory that may be contained inside a workspace
Expand Down
16 changes: 10 additions & 6 deletions crates/pop-common/src/sourcing/binary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

use crate::{
sourcing::{
from_local_package, Error, GitHub::ReleaseArchive, GitHub::SourceCodeArchive, Source,
Source::Archive, Source::Git, Source::GitHub,
from_local_package, Error,
GitHub::{ReleaseArchive, SourceCodeArchive},
Source,
Source::{Archive, Git, GitHub},
},
Status,
};
Expand Down Expand Up @@ -85,13 +87,14 @@ impl Binary {
}
}

/// Attempts to resolve a version of a binary based on whether one is specified, an existing version
/// can be found cached locally, or uses the latest version.
/// Attempts to resolve a version of a binary based on whether one is specified, an existing
/// version can be found cached locally, or uses the latest version.
///
/// # Arguments
/// * `name` - The name of the binary.
/// * `specified` - If available, a version explicitly specified.
/// * `available` - The available versions, used to check for those cached locally or the latest otherwise.
/// * `available` - The available versions, used to check for those cached locally or the latest
/// otherwise.
/// * `cache` - The location used for caching binaries.
pub fn resolve_version(
name: &str,
Expand Down Expand Up @@ -120,7 +123,8 @@ impl Binary {
/// Sources the binary.
///
/// # Arguments
/// * `release` - Whether any binaries needing to be built should be done so using the release profile.
/// * `release` - Whether any binaries needing to be built should be done so using the release
/// profile.
/// * `status` - Used to observe status updates.
/// * `verbose` - Whether verbose output is required.
pub async fn source(
Expand Down
Loading

0 comments on commit e829471

Please sign in to comment.