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: implement run command #10

Merged
merged 7 commits into from
Jul 20, 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
3 changes: 3 additions & 0 deletions .changeset/.markdownlint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"MD041": false
}
5 changes: 5 additions & 0 deletions .changeset/healthy-carpets-learn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'clap-js': patch
---

Implement utils functions to create clap command instance
5 changes: 5 additions & 0 deletions .changeset/nasty-bugs-jog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'clap-js': patch
---

Call callback functions with context object after merged parsed args
5 changes: 5 additions & 0 deletions .changeset/orange-bugs-rest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'clap-js': patch
---

Merge parsed args by `clap-rs` to context args object
5 changes: 5 additions & 0 deletions .changeset/poor-cats-grow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'clap-js': patch
---

Remove features for clap-rs
5 changes: 5 additions & 0 deletions .changeset/two-keys-thank.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'clap-js': patch
---

Implement command definition types
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
authors = ["苏向夜 <fu050409@163.com>"]
edition = "2021"
name = "clap-rs"
name = "clap-js"
version = "0.1.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand All @@ -10,8 +10,8 @@ version = "0.1.0"
crate-type = ["cdylib"]

[dependencies]
clap = "4.5.9"
napi = { version = "2", features = ["full"] }
clap = "4"
napi = "2"
napi-derive = "2"

[build-dependencies]
Expand Down
16 changes: 12 additions & 4 deletions __test__/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import test from 'ava'

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

test('define command', (t) => {
const cmd = {
meta: {},
options: {},
const cmd: Command = {
meta: {
name: 'test',
version: '1.0.0',
about: 'test command',
},
options: {
foo: {
type: 'positional',
},
},
callback: (ctx: any) => {
console.log(ctx)
},
Expand Down
2 changes: 1 addition & 1 deletion cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
"words": [
"aarch",
"androideabi",
"bindgen",
"cdylib",
"gnueabihf",
"msvc",
"napi",
"ntscl",
"oxlint",
"prebuild",
"taplo",
Expand Down
51 changes: 45 additions & 6 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,60 @@

/* auto-generated by NAPI-RS */

export declare function defineCommand(options: Command): Command
export declare function run(cmd: Command, args?: Array<string> | undefined | null): void
export const VERSION: string
export interface Context {

args: object
rawArgs: Array<string>
}
/** Command metadata */
export interface CommandMeta {
/**
* Command name
*
* This is the name of the command that will be used to call it from the CLI.
* If the command is the main command, the name will be the name of the binary.
* If the command is a subcommand, the name will be the name of the subcommand.
*/
name?: string
/**
* CLI version
*
* This is optional and can be used to display the version of the CLI
* when the command is called with the `--version` flag or `-V` option.
*
* This option will be ignored if the command is subcommand.
*/
version?: string
description?: string
hidden?: boolean
/**
* Command description
*
* Command description will be displayed in the help output.
*/
about?: string
}
export interface CommandOption {

type?: 'positional' | 'flag' | 'option'
parser?:
| 'string'
| 'str'
| 'string[]'
| 'str[]'
| 'number'
| 'boolean'
| 'bool'
short?: string
long?: string
alias?: Array<string>
hiddenAlias?: Array<string>
required?: boolean
default?: string
hidden?: boolean
}
export interface Command {
meta: CommandMeta
options: Record<string, CommandOption>
callback: (ctx: Context) => void
callback?: (ctx: Context) => void
subcommands?: Record<string, Command>
}
export declare function defineCommand(options: Command): Command
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,8 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`)
}

const { defineCommand, run } = nativeBinding
const { defineCommand, run, VERSION } = nativeBinding

module.exports.defineCommand = defineCommand
module.exports.run = run
module.exports.VERSION = VERSION
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "clap-js",
"version": "1.0.0",
"version": "0.1.0",
"description": "Fast and elegant CLI build tool based on clap-rs",
"main": "index.js",
"repository": "https://github.com/noctisynth/clap-js",
Expand Down
38 changes: 38 additions & 0 deletions simple.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const { defineCommand, run } = require('./index.js')

const dev = defineCommand({
meta: {
name: 'dev',
about: 'Run development server',
},
options: {
port: {
type: 'option',
parser: 'number',
default: '3000',
},
},
callback: (ctx) => {
console.log(ctx);
}
})

const main = defineCommand({
meta: {
name: 'simple',
version: '0.0.1',
about: 'A simple command line tool',
alias: ['dev']
},
options: {
verbose: {
type: 'flag',
parser: 'boolean',
},
},
subcommands: {
dev,
},
})

run(main)
44 changes: 44 additions & 0 deletions src/command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use napi::{bindgen_prelude::*, JsNull};
use napi_derive::napi;

use crate::types::{Command, Context};
use crate::utils::{merge_args_matches, resolve_command, resolve_option_args};

#[napi]
pub fn define_command(options: Command) -> Command {
options
}

#[napi]
pub fn run(env: Env, cmd: Command, args: Option<Vec<String>>) -> Result<()> {
let args = resolve_option_args(args);
let clap = resolve_command(clap::Command::default(), Default::default(), &cmd);
let matches = clap.clone().get_matches_from(&args);

let mut parsed_args = env.create_object()?;

merge_args_matches(&mut parsed_args, &cmd, &matches)?;

if let Some((sub_command, sub_matches)) = matches.subcommand() {
let sub_commands = &cmd.subcommands.unwrap_or_default();
let sub_command = sub_commands.get(sub_command).unwrap();
let cb = sub_command.callback.as_ref().unwrap();
merge_args_matches(&mut parsed_args, &sub_command, &sub_matches)?;
let context = Context {
args: parsed_args,
raw_args: args,
};
cb.call1::<Context, JsNull>(context)?;
} else {
let context = Context {
args: parsed_args,
raw_args: args,
};
if let Some(cb) = cmd.callback.as_ref() {
cb.call1::<Context, JsNull>(context)?;
} else {
env.throw_error("No callback function found for command", None)?;
};
}
Ok(())
}
34 changes: 3 additions & 31 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,5 @@
#![deny(clippy::all)]

use std::collections::HashMap;

use napi::JsFunction;
use napi_derive::napi;

#[napi(object)]
pub struct Context {}

#[napi(object)]
pub struct CommandMeta {
pub name: Option<String>,
pub version: Option<String>,
pub description: Option<String>,
pub hidden: Option<bool>,
}

#[napi(object)]
pub struct CommandOption {}

#[napi(object)]
pub struct Command {
pub meta: CommandMeta,
pub options: HashMap<String, CommandOption>,
#[napi(ts_type = "(ctx: Context) => void")]
pub callback: JsFunction,
}

#[napi]
pub fn define_command(options: Command) -> Command {
options
}
pub mod command;
pub mod types;
pub mod utils;
68 changes: 68 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use std::collections::HashMap;

use napi::{JsFunction, JsObject};
use napi_derive::napi;

#[napi]
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

#[napi(object)]
pub struct Context {
pub args: JsObject,
pub raw_args: Vec<String>,
}

/// Command metadata
#[napi(object)]
#[derive(Clone)]
pub struct CommandMeta {
/// Command name
///
/// This is the name of the command that will be used to call it from the CLI.
/// If the command is the main command, the name will be the name of the binary.
/// If the command is a subcommand, the name will be the name of the subcommand.
pub name: Option<String>,
/// CLI version
///
/// This is optional and can be used to display the version of the CLI
/// when the command is called with the `--version` flag or `-V` option.
///
/// This option will be ignored if the command is subcommand.
pub version: Option<String>,
/// Command description
///
/// Command description will be displayed in the help output.
pub about: Option<String>,
}

#[napi(object)]
#[derive(Clone)]
pub struct CommandOption {
#[napi(js_name = "type", ts_type = "'positional' | 'flag' | 'option'")]
pub _type: Option<String>,
#[napi(ts_type = r#"
| 'string'
| 'str'
| 'string[]'
| 'str[]'
| 'number'
| 'boolean'
| 'bool'"#)]
pub parser: Option<String>,
pub short: Option<String>,
pub long: Option<String>,
pub alias: Option<Vec<String>>,
pub hidden_alias: Option<Vec<String>>,
pub required: Option<bool>,
pub default: Option<String>,
pub hidden: Option<bool>,
}

#[napi(object)]
pub struct Command {
pub meta: CommandMeta,
pub options: HashMap<String, CommandOption>,
#[napi(ts_type = "(ctx: Context) => void")]
pub callback: Option<JsFunction>,
pub subcommands: Option<HashMap<String, Command>>,
}
Loading
Loading