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

fix(global): fix global option can't be downcast #58

Merged
merged 1 commit into from
Jul 23, 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
5 changes: 5 additions & 0 deletions .changeset/curly-crews-pull.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'archons': patch
---

Wrap `parse_arguments` to inner function
5 changes: 5 additions & 0 deletions .changeset/perfect-fishes-trade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'archons': patch
---

Fix global option can't be downcast
32 changes: 32 additions & 0 deletions __test__/global.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import test from 'ava'

import { Context, defineCommand, run } from '../index'

test('global option', (t) => {
const dev = defineCommand({
meta: {
name: 'dev',
},
options: {},
callback: (ctx: Context) => {
t.is(ctx.args.config, 'config.json')
},
})
const main = defineCommand({
meta: {
name: 'test',
},
options: {
config: {
type: 'option',
global: true,
},
},
subcommands: {
dev,
},
})
t.notThrows(() => {
run(main, ['node', 'test.js', 'dev', '--config', 'config.json'])
})
})
30 changes: 30 additions & 0 deletions examples/global.cts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Context, defineCommand, run } from '..'

const dev = defineCommand({
meta: {
name: 'dev',
},
options: {},
callback: (ctx: Context) => {
console.log(ctx.args.config)
},
})
const main = defineCommand({
meta: {
name: 'test',
},
options: {
config: {
type: 'option',
global: true,
},
},
subcommands: {
dev,
},
callback: (ctx: Context) => {
console.log(ctx.args.config)
},
})

run(main)
14 changes: 1 addition & 13 deletions src/command.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::collections::HashMap;

use napi::{Env, Result};
use napi_derive::napi;

Expand All @@ -18,15 +16,5 @@ pub fn run(env: Env, cmd: Command, args: Option<Vec<String>>) -> Result<()> {
let clap = resolve_command(clap::Command::default(), Default::default(), &cmd);
let matches = clap.clone().get_matches_from(&raw_args);

parse_arguments(
env,
env.create_object()?,
&clap,
cmd,
&matches,
raw_args,
HashMap::new(),
)?;

Ok(())
parse_arguments(env, &clap, cmd, &matches, raw_args)
}
3 changes: 1 addition & 2 deletions src/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ pub(crate) fn resolve_action(action: &Option<String>, type_: &Option<String>) ->
Some("store") => clap::ArgAction::SetTrue,
Some("store_false") => clap::ArgAction::SetFalse,
None => match type_ {
"option" => clap::ArgAction::SetTrue,
"positional" => clap::ArgAction::Set,
"option" | "positional" => clap::ArgAction::Set,
_ => panic!("Unsupported type: {:?}", type_),
},
_ => panic!("Unsupported action: {:?}", action),
Expand Down
45 changes: 38 additions & 7 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ pub(crate) fn leak_borrowed_str(s: &String) -> &'static str {

pub(crate) fn merge_args_matches(
parsed_args: &mut JsObject,
clap: &clap::Command,
args: &[&clap::Arg],
options: &HashMap<String, &'static str>,
matches: &clap::ArgMatches,
) -> Result<()> {
for id in matches.ids() {
let action = clap
.get_arguments()
let action = args
.iter()
.find(|&arg| arg.get_id() == id)
.expect(&format!(
"{}\n{}",
Expand Down Expand Up @@ -83,14 +83,15 @@ pub(crate) fn merge_args_matches(
Ok(())
}

pub(crate) fn parse_arguments(
pub(crate) fn parse_arguments_inner<'arg>(
env: Env,
mut parsed_args: JsObject,
clap: &clap::Command,
clap: &'arg clap::Command,
cmd: Command,
matches: &clap::ArgMatches,
raw_args: Vec<String>,
mut global_options: HashMap<String, &'static str>,
mut global_args: Vec<&'arg clap::Arg>,
) -> napi::Result<()> {
let mut options: HashMap<String, &'static str> = HashMap::new();
options.extend(global_options.clone());
Expand All @@ -102,7 +103,15 @@ pub(crate) fn parse_arguments(
}
}

merge_args_matches(&mut parsed_args, clap, &options, &matches)?;
let mut args = clap.get_arguments().collect::<Vec<&clap::Arg>>();
args.extend(global_args.clone());
let global_args_this = clap
.get_arguments()
.filter(|arg| arg.is_global_set())
.collect::<Vec<&clap::Arg>>();
global_args.extend(global_args_this);

merge_args_matches(&mut parsed_args, &args, &options, &matches)?;

if let Some((sub_command_name, sub_matches)) = matches.subcommand() {
let mut sub_commands = cmd.subcommands.unwrap_or_default();
Expand All @@ -113,14 +122,15 @@ pub(crate) fn parse_arguments(
.find(|&sub_command| sub_command.get_name() == sub_command_name)
.unwrap();

parse_arguments(
parse_arguments_inner(
env,
parsed_args,
sub_command,
sub_command_def,
sub_matches,
raw_args,
global_options,
global_args,
)?;
} else {
let context = Context {
Expand All @@ -138,3 +148,24 @@ pub(crate) fn parse_arguments(
};
Ok(())
}

pub(crate) fn parse_arguments<'arg>(
env: Env,
clap: &'arg clap::Command,
cmd: Command,
matches: &clap::ArgMatches,
raw_args: Vec<String>,
) -> napi::Result<()> {
let parsed_args = env.create_object()?;

parse_arguments_inner(
env,
parsed_args,
clap,
cmd,
matches,
raw_args,
HashMap::new(),
Vec::new(),
)
}