vilicvane / clime Goto Github PK
View Code? Open in Web Editor NEW⌨ The command-line interface framework for TypeScript.
⌨ The command-line interface framework for TypeScript.
First, absolutely awesome library. It is everything I've ever wanted from a CLI framework after working with commander.js
and oclif
extensively.
I'm using your module with webpack, and the statements such as:
require(path);
require(possiblePath);
cause this package to break with webpack. I've successfully made it work locally by providing the following export from your internal-util directory:
// @ts-ignore
export const requireFoolWebpack = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require;
This allows the require statements to work correctly in webpack and non-webpack environments/bundles.
Would you be open to using something like this in place of require
?
Cheers.
主要想要的是在创建命令行工具实例的时候能支持多个 commands目录的设置
比如现在的接口使用是这样
let cli = new CLI('greet', Path.join(__dirname, 'commands'));
希望能支持的方式
let cli = new CLI('greet', [Path.join(__dirname, 'commands'), Path.join('path/to/extend-commands-dir')]);
Hi @vilic,
Is it possible to cast a ContextExtension
parameter?
Example:
cast()
function that takes Slack user_id and resolves a user email:export class SlackUserResolved implements StringCastable<SlackUserResolved> {
constructor(public email: string){}
async cast(id: string, context: CastingContext<SlackUserResolved>): Promise<SlackUserResolved> {
const { email } = await getSlackUserProfile(id) as any;
return new SlackUserResolved(email);
}
}
SlackResolvedUserCommandContext
(defined below)@command({
description: 'This command is listing stuff',
})
export default class extends Command {
@metadata
execute(context: SlackResolvedUserCommandContext) {
return listStuffForUser(context.profile);
}
}
Now, here's where I'm having trouble:
How do I get the user to be resolved before command invocation?
I can't await
inside the constructor. What do I do?
SlackResolvedUserCommandContext
class extending SlackCommandContext
that I would like to have the user email resolved:export class SlackResolvedUserCommandContext extends SlackCommandContext {
public profile: SlackUserResolved;
constructor(options: ContextOptions, contextExt: SlackCommandContext) {
super(options, contextExt);
}
}
Appreciate the assistance,
Sapien
help
or option flag named h
foo/default.js
and foo.js
SubcommandDefinition
export class File implements StringCastable<File> {
constructor(public path: string) {}
// This is required by the StringCastable interface, but it's never called.
cast(source: string, context: CastingContext<File>): Promise<File> {
console.log('This is never called');
return new Promise(() => {});
}
// But this is actually called.
static cast(source: string, context: CastingContext<File>): Promise<File> {
console.log('This is actually called');
return new Promise((resolve, reject) => {
resolve(new File(Path.resolve(context.cwd, source)));
});
}
}
I'm wondering if I'm doing something wrong here: The StringCastable
forces me to implement cast(source: string, context: CastingContext<File>): Promise<File>
, which is then never even called. The static one is actually being called. And unless I implement the static one, I get a runtime error:
Error: Type
Filecannot be casted from a string, see
StringCastable interface for more information
When I try to run the example in the usage section of the README, I get this error:
TypeError: Class constructor Command cannot be invoked without 'new'
at new default_1 (/Users/michaelparis/Scaphold/code/fetch-schema/build/commands/default.js:8:42)
at CLI.<anonymous> (/Users/michaelparis/Scaphold/code/fetch-schema/node_modules/clime/bld/core/cli.js:50:35)
at next (native)
at fulfilled (/Users/michaelparis/Scaphold/code/fetch-schema/node_modules/clime/bld/core/cli.js:4:58)
No issue here-- in fact, I'm loving using clime! I just wanted to say thank you @vilic for making this and for maintaining it.
I wish more people used it! :) I'll try to get the word out my smallish network. But again, I just wanted to send gratitude your way.
When I have 2 not-required params in my command, parsed only first one.
@command()
export default class extends Command {
execute(@param({required: false}) first: boolean, @param({required: false}) second: boolean) {
console.log('first =', first)
console.log('second =', second)
}
}
second
ts-node ./src/index.ts second
first = undefined
second = true
first = true
second = undefined
Sample:
https://github.com/lamantin-group/publish/blob/bug/clime/src/commands/default.ts#L20
The demo doesn't work
I carefully made sure I'm following the guide and wiring the app correctly. It doesn't work:
ERR Unknown subcommand "demo".
USAGE
/ <subcommand>
I'm using the barebones example code in the documentation for the 'greet' command. Does clime work with ts-node? Either it clime doesn' work with ts-node or I'm missing something super silly.
I have:
src/cli.ts
src/commands/default.ts
cli.ts:
import * as Path from 'path';
import { CLI, Shim } from 'clime';
// The second parameter is the path to folder that contains command modules.
let cli = new CLI('greet', Path.join(__dirname, 'commands'));
// Clime in its core provides an object-based command-line infrastructure.
// To have it work as a common CLI, a shim needs to be applied:
let shim = new Shim(cli);
shim.execute(process.argv);
default.ts:
import {
Command,
command,
param,
} from 'clime';
@command({
description: 'This is a command for printing a greeting message',
})
export default class extends Command {
execute(
@param({
description: 'Your loud name',
required: true,
})
name: string,
) {
return `Hello, ${name}!`;
}
}
Here is my tsconfig.json file:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": ["es6", "es2016", "ES2016.Array.Include", "dom", "ES2017.object"],
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"strictNullChecks": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"outDir": "build",
"sourceMap": true,
"allowJs": true
},
"exclude": [
"node_modules"
]
}
But when I run it with ts-node -P . src/cli.ts
, the only output I ever see is (note: tsconfig.json lives in .
):
USAGE
greet <subcommand>
It doesn't complain about the required name
parameter missing. I get no description, etc...
What am I missing here?
Just checking, but are parameter arrays supposed to work?
import {Command, command, param, option, Options} from 'clime';
export class DefaultOptions extends Options {
@option({
})
cacheTtl: number;
@option({
type: String,
required: true,
})
output: string;
}
@command({
description: 'This is a command for printing a greeting message',
})
export default class extends Command {
async execute(
@param({
type: String,
description: 'extra parameters',
})
args: string[],
options: DefaultOptions,
) {
}
}
Gives me the output (at runtime) of:
$ tsc && node ./dist/src/cli.js a b
ERR Expecting 1 parameter(s) at most but got 2 instead.
When defining subcommand properties like alias
or brief
in the parent commands subcommands
export, there is no error shown, when a subcommand does not exist:
src/
+-- app.ts
+-- commands/
| +-- default.ts
| +-- my-command.ts
// src/commands/default.ts
import { SubcommandDefinition } from 'clime'
export const subcommands: SubcommandDefinition[] = [
{
name: 'my-cool-command',
brief: "Isn't it cool?",
}
]
$ node bin/app
USAGE
app <subcommand>
SUBCOMMANDS
my-cool-command - Isn't it cool?
my-command - It's definitely cool!.
$ node bin/app my-cool-command
ERR Unknown subcommand "my-cool-command".
USAGE
app <subcommand>
SUBCOMMANDS
my-cool-command - Isn't it cool?
my-command - It's definitely cool!.
As you can see, there is no such command like my-cool-command
but it is displayed because it is defined in default.ts
.
My suggestion is to test if the command exists (or at least if one of the files my-cool-command.js
or my-cool-command/default.js
exist) and to present the user with an error or at least a warning when it does not.
Example:
$ node bin/app
USAGE
app <subcommand>
SUBCOMMANDS
my-command - It's definitely cool!.
WARN Subcommand 'my-cool-command' is defined but does not exist!
Note that the missing subcommand would not be listed as subcommand and a warning would be displayed below the output.
Thank you for awesome package. Some of my command can take more than 3 minutes. Do we have best practice for shutdown the command execution?
I have the following use case:
-v
should print the version:
my-cli -v
Empty should print the default help text:
my-cli
I was able to print the version, but could not access the help text which is usually generated by clime.
The file src/clI/commands/default.ts
:
import { Command, command, metadata, option, Options } from 'clime';
import * as Fs from 'fs';
import * as Path from 'path';
export class DefaultOptions extends Options {
@option({
flag: 'v',
description: 'The version of my-cli',
toggle: true,
required: false
})
version: boolean = false;
}
@command({
description: 'my description'
})
export default class extends Command {
@metadata
async execute(
options: DefaultOptions
) {
const isVersion = !!options.version;
if (isVersion) {
const packageJsonPath = Path.join(__dirname, '../../package.json');
const packageJsonContent = Fs.readFileSync(packageJsonPath, 'utf8');
const packageJson = JSON.parse(packageJsonContent);
return packageJson.version;
}
// DOES NOT WORK:
return await Command.getHelp();
}
}
Did I miss something?
i use default command here
export const description = `
==============================
cli: v${version}
maintainer: ${author.name}
==============================
`;
export const subcommands: SubcommandDefinition[] = [
{ name: 'worker' }
];
command run but error code 1 and print helpinfo
i want helpInfo return and not throw how can?
I am learning the source code and the design of clime. When I was studying the shim
part, I was confused by the comment A Clime command line interface shim for pure Node.js.
. What's the aim of the shim.
Is it possible to have commands which work as usual, but are NOT listed when a user uses -h
or similar listings?
While trying to port hand-written argument parser, I noticed that there's currently no way to configure an option that may occur multiple times and accumulates the arguments:
grep -e 'foo' -e 'bar'
This is how I'd like this to work:
export class GrepOptions extends Options {
@param({multi: true}) public e: string[];
}
@command()
export default class extends Command {
@metadata
public execute(options: GrepOptions) {
console.log(options.e); // ['foo', 'bar']
}
}
I think it would be nice to be able to set the alias inside the subcommand file using the @command()
decorator.
It is currently only possible to defined aliases in the parent command by exporting a SubcommandDefinition
array:
import { SubcommandDefinition } from 'clime'
export const subcommands: SubcommandDefinition[] = [
{
name: 'my-really-annoying-long-but-descriptive-command',
alias: 'do-it',
}
]
This way, I will have to maintain the alias in a separate file from the actual subcommand definition file. And it is very easy to forget changing the command definition in the parent command when for example renaming the subcommand.
In this case one would end up with the new command name (without an alias) and the old one (with alias but not working as it is not defined anymore).
SUBCOMMANDS
my-really-annoying-long-but-descriptive-command [do-it]
my-long-but-descriptive-command - Isn't that a long command?
When setting the alias in the @command()
decorator, this would not happen.
Using this method, every subcommand has to be loaded when executing a subcommand using its alias because clime does not know which command has the given alias. This might produce some unwanted IO, especially in larger applications with many subcommands. But I don't know if this would really be a problem
This behavior could be configurable while bootstrapping clime:
let cli = new CLI(
Path.basename(process.argv[1]), // App name
Path.join(__dirname, 'commands') // Path to commands
{
aliasInSubcommand: false // I would prefer it to be `true` by default
}
);
Don't allow this at all if there are too may concerns but at least let the developer know that something is wrong. (See #33)
If there is an default value the required shoud not throw an error.
While trying to port my CLI, I noticed there is no way to declare options that may not consume the next argument if not necessary.
A popular example are TypeScript's compilerOptions:
tsc --project tsconfig.json
# parses as {strict: undefined, project: 'tsconfig.json'}
tsc --strict --project tsconfig.json
# parses as {strict: true, project: 'tsconfig.json'}
tsc --strict true --project tsconfig.json
# parses as {strict: true, project: 'tsconfig.json'}
tsc --strict false --project tsconfig.json
# parses as {strict: false, project: 'tsconfig.json'}
In my use case this is not limited to a switch option (boolean value). It's actually an optional boolean or number:
wotan foo.ts
# parses as {fix: false, files: ['foo.ts']}
wotan --fix foo.ts
# parses as {fix: true, files: ['foo.ts']}
wotan --fix foo.ts
# parses as {fix: true, files: ['foo.ts']}
wotan --fix false foo.ts
# parses as {fix: false, files: ['foo.ts']}
wotan --fix 5 foo.ts
# parses as {fix: 5, files: ['foo.ts']}
I can think of 2 possible solutions:
Add optional
flag
class MyOptions extends Options {
@option({optional: true, default: false, validator: /^(true|false|\d+)$/})
public fix: boolean | number;
}
If optional
is true and validating the argument using the validator
fails, do not consume the argument and use the default value instead.
Add parse
function
class MyOptions extends Options {
@option({
parse(consume: () => string | undefined, unconsume: (arg: string) => void) {
const option = consume();
if (option === undefined)
return false; // no more arguments available
if (option === 'true')
return true;
if (option === 'false')
return false;
const numeric = +option;
if (!Number.isNaN(numeric))
return numeric;
// argument is not in the expected format, push it back so that it may be parsed as another option or parameter
unconsume(option);
return false; // use a default value
},
validator(value: boolean | number) {
if (typeof value === 'number' && value < 0)
throw new ExpectedError('--fix must be a positive number');
}
})
public fix: boolean | number;
}
If a parse
function is provided, this function is responsible for consuming the arguments, parsing and converting the value. By calling consume()
more than once the parser may consume 0..n of the remaining arguments.
validators
are still executed after parsing. That means errors about invalid option values can be reported. That's not possible with the optional
proposal.
I'm going to save the state of user so that I can get it in different commands. But every command is a child_process
, I have no idea to do it. Do you have any good idea?
Hey ho,
I like your library, but something I'd like over the file-structured based hierarchy is if I could define the architecture myself when creating an instance of CLI
. This would also be a workaround for #41 as there's no need for a pre-compiled file.
I'd propose an overload for CLI
or a new type like InMemoryCLI
that accepts the following data structure as the second argument:
interface CommandMap { readonly [commandName: string]: CommandClass | CommandMap; }
To give an example, here's your structure from the "subcommands" section in the README:
command
command foo
command foo biu
command foo yo
command bar
command bar bia
command bar pia
//
- commands
- default.ts
- foo.ts
- foo
- biu.ts
- yo.ts
- bar
- default.ts
- bia.ts
- pia.ts
And with my proposed functionality:
import { DefaultCommand } from './commands/default';
import { FooDefaultCommand } from './commands/foo/default';
import { FooBiuCommand } from './commands/foo/biu';
import { FooYoCommand } from './commands/foo/yo';
import { BarDefaultCommand } from './commands/bar/default';
import { BarBiaCommand } from './commands/bar/bia';
import { BarPiaCommand } from './commands/bar/pia';
const cli = new CLI(
'name',
{
default: DefaultCommand,
foo: {
default: FooDefaultCommand,
biu: FooBiuCommand,
yo: FooYoCommand
},
bar: {
default: BarDefaultCommand,
bia: BarBiaCommand,
pia: BarPiaCommand
}
});
Or alternatively, you could create an index.ts
in ever sub-commands folder, e.g. for commands/foo/index.ts
:
import { DefaultCommand } from './default';
import { BiuCommand } from './biu';
import { YoCommand } from './yo';
export default {
default: DefaultCommand,
biu: BiuCommand,
yo: YoCommand
};
And when importing:
import FooCommands from './commands/foo';
new CLI('name', { foo: FooCommands });
Hi,
The way I understand it (and so it appears from testing), clime currently only looks at the first parameter that extends Options and adds its definitions to the command.
I think it would be useful to not limit to the first one and simply gather all of the Option derived parameters. You could then package shared command parameters into Option classes and compose them on a per-command basis.
Is there a better way to achieve this or am I misunderstanding something?
Cheers,
Asaf
The rc
package provides a standard way to lookup configuration files. It would be great if clime
had built in support for the same lookup. I am keen to implement this if you think it would be a good addition to the project. We can avoid statSync
that rc
does because clime
is async
by default so we can do the file lookups asynchronously.
If 👍 on this idea, I can do some investigation and figure out a spec before actually implementing it. I imagine it would be in preprocessArguments
but that's based on 1 minute or research.
The value passed to a validator should be a casted, and the value passed to regular expression validator should be the original string
With file structure like this (no foo.ts
or foo/default.ts
):
- commands
- foo
- biu.ts
- pia.ts
It complains unknown command foo
while it should not.
Update multi-level/case-2
baseman tests after fix.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.