Skip to content

Commit

Permalink
Less magic
Browse files Browse the repository at this point in the history
Call forc_util::cli::register() explicitly instead of doing some dark magic
behind through cli_examples macro
  • Loading branch information
crodas committed Feb 22, 2024
1 parent 13119c7 commit 9c2044f
Show file tree
Hide file tree
Showing 12 changed files with 44 additions and 75 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion forc-plugins/forc-client/src/bin/deploy.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use clap::Parser;
use clap::{IntoApp, Parser};
use forc_tracing::{init_tracing_subscriber, println_error};

#[tokio::main]
async fn main() {
forc_util::cli::register(forc_client::cmd::Deploy::into_app());
init_tracing_subscriber(Default::default());
let command = forc_client::cmd::Deploy::parse();
if let Err(err) = forc_client::op::deploy(command).await {
Expand Down
3 changes: 2 additions & 1 deletion forc-plugins/forc-client/src/bin/run.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use clap::Parser;
use clap::{IntoApp, Parser};
use forc_tracing::{init_tracing_subscriber, println_error};

#[tokio::main]
async fn main() {
forc_util::cli::register(forc_client::cmd::Run::into_app());
init_tracing_subscriber(Default::default());
let command = forc_client::cmd::Run::parse();
if let Err(err) = forc_client::op::run(command).await {
Expand Down
3 changes: 2 additions & 1 deletion forc-plugins/forc-client/src/bin/submit.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use clap::Parser;
use clap::{IntoApp, Parser};
use forc_tracing::{init_tracing_subscriber, println_error};

#[tokio::main]
async fn main() {
forc_util::cli::register(forc_client::cmd::Submit::into_app());
init_tracing_subscriber(Default::default());
let command = forc_client::cmd::Submit::parse();
if let Err(err) = forc_client::op::submit(command).await {
Expand Down
3 changes: 2 additions & 1 deletion forc-plugins/forc-crypto/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use anyhow::Result;
use atty::Stream;
use clap::Parser;
use clap::{IntoApp, Parser};
use forc_tracing::{init_tracing_subscriber, println_error};
use std::{
default::Default,
Expand Down Expand Up @@ -57,6 +57,7 @@ fn main() {
}

fn run() -> Result<()> {
forc_util::cli::register(Command::into_app());
let app = Command::parse();
let content = match app {
Command::Keccak256(arg) => keccak256::hash(arg)?,
Expand Down
1 change: 1 addition & 0 deletions forc-plugins/forc-debug/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ clap = { version = "3", features = ["env", "derive"] }
dap = "0.4.1-alpha1"
forc-pkg = { version = "0.50.0", path = "../../forc-pkg" }
forc-test = { version = "0.50.0", path = "../../forc-test" }
forc-util = { version = "0.50.0", path = "../../forc-util" }
fuel-core-client = { workspace = true }
fuel-types = { workspace = true, features = ["serde"] }
fuel-vm = { workspace = true, features = ["serde"] }
Expand Down
3 changes: 2 additions & 1 deletion forc-plugins/forc-debug/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use clap::Parser;
use clap::{IntoApp, Parser};
use forc_debug::{
names::{register_index, register_name},
server::DapServer,
Expand All @@ -20,6 +20,7 @@ pub struct Opt {

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
forc_util::cli::register(Opt::into_app());
let config = Opt::parse();

if config.serve {
Expand Down
3 changes: 2 additions & 1 deletion forc-plugins/forc-doc/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::{
search::write_search_index,
};
use anyhow::{bail, Result};
use clap::Parser;
use clap::{IntoApp, Parser};
use cli::Command;
use colored::*;
use forc_pkg as pkg;
Expand Down Expand Up @@ -51,6 +51,7 @@ struct ProgramInfo<'a> {
}

pub fn main() -> Result<()> {
forc_util::cli::register(Command::into_app());
let build_instructions = Command::parse();

let (doc_path, pkg_manifest) = compile_html(&build_instructions, &get_doc_dir)?;
Expand Down
6 changes: 4 additions & 2 deletions forc-plugins/forc-fmt/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! A `forc` plugin for running the Sway code formatter.

use anyhow::{bail, Result};
use clap::Parser;
use clap::{IntoApp, Parser};
use forc_pkg::{
manifest::{GenericManifestFile, ManifestFile},
WorkspaceManifestFile,
Expand Down Expand Up @@ -51,7 +51,8 @@ pub struct App {
pub path: Option<String>,
#[clap(short, long)]
/// Formats a single .sw file with the default settings.
/// If not specified, current working directory will be formatted using a Forc.toml configuration.
/// If not specified, current working directory will be formatted using a Forc.toml
/// configuration.
pub file: Option<String>,
}

Expand All @@ -65,6 +66,7 @@ fn main() {
}

fn run() -> Result<()> {
forc_util::cli::register(App::into_app());
let app = App::parse();

let dir = match app.path.as_ref() {
Expand Down
6 changes: 2 additions & 4 deletions forc-plugins/forc-tx/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@ use std::path::PathBuf;
use thiserror::Error;

forc_util::cli_examples! {
{
None
}
{
// This parser has a custom parser
super::Command::try_parse_from_args
Expand Down Expand Up @@ -728,7 +725,8 @@ impl TryFrom<Script> for fuel_tx::Script {
script_tx.set_script_gas_limit(script_gas_limit)
} else {
let consensus_params = ConsensusParameters::default();
// Get `max_gas` used by everything except the script execution. Add `1` because of rounding.
// Get `max_gas` used by everything except the script execution. Add `1` because of
// rounding.
let max_gas =
script_tx.max_gas(consensus_params.gas_costs(), consensus_params.fee_params()) + 1;
// Increase `script_gas_limit` to the maximum allowed value.
Expand Down
66 changes: 15 additions & 51 deletions forc-util/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,46 +165,28 @@ impl ArgInfo {
}
}

pub fn dump_cli_definition<X: clap::IntoApp>(app: X) {
let cmd = app.into_app();
serde_json::to_writer_pretty(std::io::stdout(), &CommandInfo::new(&cmd)).unwrap();
std::process::exit(0);
}

macro_rules! clap_completions {
($st:path) => {
use clap::IntoApp;
$st::into_app()

mod cli_definition {
/// Dump the CLI definition to the stdout
pub(crate) fn dump() {
std::env::set_var("CLI_DUMP_DEFINITION", "");

if let Some(mut cmd) = $into_app {
forc_util::serde_json::to_writer_pretty(
std::io::stdout(),
&forc_util::cli::CommandInfo::new(&cmd)
).unwrap();
std::process::exit(0);
}
}
/// Registers the current command to print the CLI definition, if the `--cli-definition` argument is
/// passed.
///
/// The existance of --cli-definition is arbitrary, a convention that is used by forc and is
/// probably not defined inside the clap struct. Because of this, the `--cli-definition` argument,
/// the function should be called *before* the `clap::App` is built to parse the arguments.
pub fn register(cmd: clap::App<'_>) {
std::env::args().skip(1).for_each(|arg| {
if arg == "--cli-definition" {
let cmd_info = CommandInfo::new(&cmd);
serde_json::to_writer_pretty(std::io::stdout(), &cmd_info).unwrap();
std::process::exit(0);
}

};
});
}

#[macro_export]
// Let the user format the help and parse it from that string into arguments to create the unit test
macro_rules! cli_examples {
($st:path { $( [ $($description:ident)* => $command:stmt ] )* }) => {
forc_util::cli_examples! {
{
$crate::paste::paste! {
use clap::IntoApp;
Some($st::into_app())
}
} {
{
$crate::paste::paste! {
use clap::Parser;
$st::try_parse_from
Expand All @@ -214,7 +196,7 @@ macro_rules! cli_examples {
}
}
};
( $into_app:block $parser:block { $( [ $($description:ident)* => $command:stmt ] )* }) => {
( $parser:block { $( [ $($description:ident)* => $command:stmt ] )* }) => {
$crate::paste::paste! {
#[cfg(test)]
mod cli_parsing {
Expand Down Expand Up @@ -301,30 +283,12 @@ macro_rules! cli_examples {
}
}

mod cli_definition {
/// Dump the CLI definition to the stdout
pub(crate) fn dump() {
std::env::set_var("CLI_DUMP_DEFINITION", "");

if let Some(mut cmd) = $into_app {
forc_util::serde_json::to_writer_pretty(
std::io::stdout(),
&forc_util::cli::CommandInfo::new(&cmd)
).unwrap();
std::process::exit(0);
}
}
}

/// Show the long help for the current app
///
/// This function is being called automatically, so if CLI_DUMP_DEFINITION is set to 1, it
/// will dump the definition of the CLI. Otherwise, it would have to be manually invoked by
/// the developer
fn help() -> &'static str {
if std::env::var("CLI_DUMP_DEFINITION") == Ok("1".to_string()) {
cli_definition::dump();
}
Box::leak(format!("{}\n{}", forc_util::ansi_term::Colour::Yellow.paint("EXAMPLES:"), examples()).into_boxed_str())
}

Expand Down
21 changes: 9 additions & 12 deletions forc/src/cli/commands/completions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,19 +54,16 @@ fn generate_autocomplete_script(target: Target, writer: &mut dyn Write) {
let mut cmd = CommandInfo::new(&super::super::Opt::command());
let mut plugins = HashMap::new();
find_all().for_each(|path| {
let mut proc = std::process::Command::new(path.clone());
proc.env("CLI_DUMP_DEFINITION", "1");
if let Ok(proc) = proc.output() {
if let Ok(proc) = std::process::Command::new(path.clone())
.arg("--cli-definition")
.output()
{
if let Ok(mut command_info) = serde_json::from_slice::<CommandInfo>(&proc.stdout) {
command_info.name = if let Some(name) = path
.file_name()
.map(|x| {
x.to_string_lossy()
.strip_prefix("forc-")
.map(|x| x.to_owned())
})
.flatten()
{
command_info.name = if let Some(name) = path.file_name().and_then(|x| {
x.to_string_lossy()
.strip_prefix("forc-")
.map(|x| x.to_owned())
}) {
name
} else {
command_info.name
Expand Down

0 comments on commit 9c2044f

Please sign in to comment.