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: Added interactive-clap for cargo-near #103

Merged
merged 15 commits into from
Oct 1, 2023
2,638 changes: 2,364 additions & 274 deletions Cargo.lock

Large diffs are not rendered by default.

14 changes: 12 additions & 2 deletions cargo-near/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name = "cargo-near"
version = "0.3.1"
authors = ["Near Inc <[email protected]>"]
edition = "2021"
rust-version = "1.60.0"
rust-version = "1.70.0"
description = "Cargo extension for building Rust smart contracts on NEAR"
readme = "README.md"
repository = "https://github.com/near/cargo-near"
Expand All @@ -16,7 +16,7 @@ anyhow = "1.0"
bs58 = "0.4"
camino = "1.1.1"
cargo_metadata = "0.14"
clap = { version = "3.2", features = ["derive", "env"] }
clap = { version = "4.0.18", features = ["derive", "env"] }
colored = "2.0"
env_logger = "0.9"
log = "0.4"
Expand All @@ -29,3 +29,13 @@ near-abi = { version = "0.3.0", features = ["__chunked-entries"] }
libloading = "0.7.3"
zstd = "0.11"
atty = "0.2.14"

color-eyre = "0.6"
inquire = "0.6"
strum = { version = "0.24", features = ["derive"] }
strum_macros = "0.24"
interactive-clap = {git = "https://github.com/near-cli-rs/interactive-clap"}
interactive-clap-derive = {git = "https://github.com/near-cli-rs/interactive-clap"}
near-cli-rs = { version = "0.5.2" }
derive_more = "0.99.9"
shell-words = "1.0.0"
28 changes: 18 additions & 10 deletions cargo-near/src/abi.rs → cargo-near/src/abi_command/abi.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use crate::cargo::{manifest::CargoManifestPath, metadata::CrateMetadata};
use crate::{util, AbiCommand, ColorPreference};
use std::collections::HashMap;
use std::fs;

use camino::Utf8PathBuf;
use colored::Colorize;
use near_abi::AbiRoot;
use std::collections::HashMap;
use std::fs;

use crate::common::ColorPreference;
use crate::types::{manifest::CargoManifestPath, metadata::CrateMetadata};
use crate::util;

/// ABI generation result.
pub(crate) struct AbiResult {
Expand Down Expand Up @@ -174,18 +177,23 @@ fn strip_docs(abi_root: &mut near_abi::AbiRoot) {
}
}

pub(crate) fn run(args: AbiCommand) -> anyhow::Result<()> {
args.color.apply();
pub(crate) fn run(args: super::AbiCommand) -> anyhow::Result<()> {
let color = args.color.unwrap_or(ColorPreference::Auto);
color.apply();

let crate_metadata = util::handle_step("Collecting cargo project metadata...", || {
CrateMetadata::collect(CargoManifestPath::try_from(
args.manifest_path.unwrap_or_else(|| "Cargo.toml".into()),
)?)
let manifest_path: Utf8PathBuf = if let Some(manifest_path) = args.manifest_path {
manifest_path.into()
} else {
"Cargo.toml".into()
};
CrateMetadata::collect(CargoManifestPath::try_from(manifest_path)?)
})?;

let out_dir = args
.out_dir
.map_or(Ok(crate_metadata.target_directory.clone()), |out_dir| {
let out_dir = Utf8PathBuf::from(out_dir);
util::force_canonicalize_dir(&out_dir)
})?;

Expand All @@ -194,7 +202,7 @@ pub(crate) fn run(args: AbiCommand) -> anyhow::Result<()> {
} else {
AbiFormat::Json
};
let contract_abi = generate_abi(&crate_metadata, args.doc, false, args.color)?;
let contract_abi = generate_abi(&crate_metadata, args.doc, false, color)?;
let AbiResult { path } =
write_to_file(&contract_abi, &crate_metadata, format, AbiCompression::NoOp)?;

Expand Down
99 changes: 99 additions & 0 deletions cargo-near/src/abi_command/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
pub mod abi;

#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = near_cli_rs::GlobalContext)]
#[interactive_clap(skip_default_from_cli)]
pub struct AbiCommand {
/// Include rustdocs in the ABI file
#[interactive_clap(long)]
pub doc: bool,
/// Generate compact (minified) JSON
#[interactive_clap(long)]
pub compact_abi: bool,
/// Copy final artifacts to this directory
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
pub out_dir: Option<crate::types::utf8_path_buf::Utf8PathBuf>,
frol marked this conversation as resolved.
Show resolved Hide resolved
/// Path to the `Cargo.toml` of the contract to build
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
pub manifest_path: Option<crate::types::utf8_path_buf::Utf8PathBuf>,
/// Coloring: auto, always, never
#[interactive_clap(long)]
#[interactive_clap(value_enum)]
#[interactive_clap(skip_default_input_arg)]
pub color: Option<crate::common::ColorPreference>,
}

impl interactive_clap::FromCli for AbiCommand {
type FromCliContext = near_cli_rs::GlobalContext;
type FromCliError = color_eyre::eyre::Error;
fn from_cli(
optional_clap_variant: Option<<Self as interactive_clap::ToCli>::CliVariant>,
context: Self::FromCliContext,
) -> interactive_clap::ResultFromCli<
<Self as interactive_clap::ToCli>::CliVariant,
Self::FromCliError,
>
where
Self: Sized + interactive_clap::ToCli,
{
let mut clap_variant = optional_clap_variant.unwrap_or_default();
let doc = clap_variant.doc;
let compact_abi = clap_variant.compact_abi;
if clap_variant.out_dir.is_none() {
clap_variant.out_dir = match Self::input_out_dir(&context) {
Ok(optional_out_dir) => optional_out_dir,
Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err),
};
};
let out_dir = clap_variant.out_dir.clone();
if clap_variant.manifest_path.is_none() {
clap_variant.manifest_path = match Self::input_manifest_path(&context) {
Ok(optional_manifest_path) => optional_manifest_path,
Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err),
};
};
let manifest_path = clap_variant.manifest_path.clone();
if clap_variant.color.is_none() {
clap_variant.color = match Self::input_color(&context) {
Ok(optional_color) => optional_color,
Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err),
};
};
let color = clap_variant.color.clone();

let args = Self {
doc,
compact_abi,
out_dir,
manifest_path,
color,
};
if let Err(err) = self::abi::run(args) {
interactive_clap::ResultFromCli::Err(Some(clap_variant), color_eyre::Report::msg(err))
} else {
interactive_clap::ResultFromCli::Ok(clap_variant)
}
}
}

impl AbiCommand {
fn input_color(
_context: &near_cli_rs::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::common::ColorPreference>> {
Ok(None)
}

fn input_out_dir(
_context: &near_cli_rs::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::utf8_path_buf::Utf8PathBuf>> {
Ok(None)
}

fn input_manifest_path(
_context: &near_cli_rs::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::utf8_path_buf::Utf8PathBuf>> {
Ok(None)
}
}
30 changes: 19 additions & 11 deletions cargo-near/src/build.rs → cargo-near/src/build_command/build.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
use crate::abi::{AbiCompression, AbiFormat, AbiResult};
use crate::cargo::{manifest::CargoManifestPath, metadata::CrateMetadata};
use crate::util::CompilationArtifact;
use crate::{abi, util, BuildCommand};
use camino::Utf8PathBuf;
use colored::Colorize;
use near_abi::BuildInfo;
use sha2::{Digest, Sha256};
use std::io::BufRead;

use crate::abi_command::abi;
use crate::abi_command::abi::{AbiCompression, AbiFormat, AbiResult};
use crate::common::ColorPreference;
use crate::types::{manifest::CargoManifestPath, metadata::CrateMetadata};
use crate::util;

const COMPILATION_TARGET: &str = "wasm32-unknown-unknown";

pub fn run(args: BuildCommand) -> anyhow::Result<CompilationArtifact> {
args.color.apply();
pub fn run(args: super::BuildCommand) -> anyhow::Result<util::CompilationArtifact> {
let color = args.color.unwrap_or(ColorPreference::Auto);
color.apply();

util::handle_step("Checking the host environment...", || {
if !util::invoke_rustup(["target", "list", "--installed"])?
Expand All @@ -23,14 +27,18 @@ pub fn run(args: BuildCommand) -> anyhow::Result<CompilationArtifact> {
})?;

let crate_metadata = util::handle_step("Collecting cargo project metadata...", || {
CrateMetadata::collect(CargoManifestPath::try_from(
args.manifest_path.unwrap_or_else(|| "Cargo.toml".into()),
)?)
let manifest_path: Utf8PathBuf = if let Some(manifest_path) = args.manifest_path {
manifest_path.into()
} else {
"Cargo.toml".into()
};
CrateMetadata::collect(CargoManifestPath::try_from(manifest_path)?)
})?;

let out_dir = args
.out_dir
.map_or(Ok(crate_metadata.target_directory.clone()), |out_dir| {
let out_dir = Utf8PathBuf::from(out_dir);
util::force_canonicalize_dir(&out_dir)
})?;

Expand All @@ -43,7 +51,7 @@ pub fn run(args: BuildCommand) -> anyhow::Result<CompilationArtifact> {
let mut abi = None;
let mut min_abi_path = None;
if !args.no_abi {
let mut contract_abi = abi::generate_abi(&crate_metadata, args.doc, true, args.color)?;
let mut contract_abi = abi::generate_abi(&crate_metadata, args.doc, true, color.clone())?;
contract_abi.metadata.build = Some(BuildInfo {
compiler: format!("rustc {}", rustc_version::version()?),
builder: format!("cargo-near {}", env!("CARGO_PKG_VERSION")),
Expand Down Expand Up @@ -75,7 +83,7 @@ pub fn run(args: BuildCommand) -> anyhow::Result<CompilationArtifact> {
build_env,
"wasm",
false,
args.color,
color,
)?;

wasm_artifact.path = util::copy(&wasm_artifact.path, &out_dir)?;
Expand Down
110 changes: 110 additions & 0 deletions cargo-near/src/build_command/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
mod build;

#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(context = near_cli_rs::GlobalContext)]
#[interactive_clap(skip_default_from_cli)]
pub struct BuildCommand {
/// Build contract in release mode, with optimizations
#[interactive_clap(long)]
pub release: bool,
/// Embed the ABI in the contract binary
#[interactive_clap(long)]
pub embed_abi: bool,
/// Include rustdocs in the embedded ABI
#[interactive_clap(long)]
pub doc: bool,
/// Do not generate ABI for the contract
#[interactive_clap(long)]
// #[clap(long, conflicts_with_all = &["doc", "embed-abi"])]
pub no_abi: bool,
/// Copy final artifacts to this directory
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
pub out_dir: Option<crate::types::utf8_path_buf::Utf8PathBuf>,
/// Path to the `Cargo.toml` of the contract to build
#[interactive_clap(long)]
#[interactive_clap(skip_default_input_arg)]
pub manifest_path: Option<crate::types::utf8_path_buf::Utf8PathBuf>,
/// Coloring: auto, always, never
#[interactive_clap(long)]
#[interactive_clap(value_enum)]
#[interactive_clap(skip_default_input_arg)]
pub color: Option<crate::common::ColorPreference>,
}

impl interactive_clap::FromCli for BuildCommand {
type FromCliContext = near_cli_rs::GlobalContext;
type FromCliError = color_eyre::eyre::Error;
fn from_cli(
optional_clap_variant: Option<<Self as interactive_clap::ToCli>::CliVariant>,
context: Self::FromCliContext,
) -> interactive_clap::ResultFromCli<
<Self as interactive_clap::ToCli>::CliVariant,
Self::FromCliError,
>
where
Self: Sized + interactive_clap::ToCli,
{
let mut clap_variant = optional_clap_variant.unwrap_or_default();
let release = clap_variant.release;
let embed_abi = clap_variant.embed_abi;
let doc = clap_variant.doc;
let no_abi = clap_variant.no_abi;
if clap_variant.out_dir.is_none() {
clap_variant.out_dir = match Self::input_out_dir(&context) {
Ok(optional_out_dir) => optional_out_dir,
Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err),
};
};
let out_dir = clap_variant.out_dir.clone();
if clap_variant.manifest_path.is_none() {
clap_variant.manifest_path = match Self::input_manifest_path(&context) {
Ok(optional_manifest_path) => optional_manifest_path,
Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err),
};
};
let manifest_path = clap_variant.manifest_path.clone();
if clap_variant.color.is_none() {
clap_variant.color = match Self::input_color(&context) {
Ok(optional_color) => optional_color,
Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err),
};
};
let color = clap_variant.color.clone();

let args = Self {
release,
embed_abi,
doc,
no_abi,
out_dir,
manifest_path,
color,
};
if let Err(err) = self::build::run(args).map(|_| ()) {
interactive_clap::ResultFromCli::Err(Some(clap_variant), color_eyre::Report::msg(err))
} else {
interactive_clap::ResultFromCli::Ok(clap_variant)
}
}
}

impl BuildCommand {
fn input_color(
_context: &near_cli_rs::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::common::ColorPreference>> {
Ok(None)
}

fn input_out_dir(
_context: &near_cli_rs::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::utf8_path_buf::Utf8PathBuf>> {
Ok(None)
}

fn input_manifest_path(
_context: &near_cli_rs::GlobalContext,
) -> color_eyre::eyre::Result<Option<crate::types::utf8_path_buf::Utf8PathBuf>> {
Ok(None)
}
}
Loading
Loading