Skip to content

Commit

Permalink
Support for single and double quotes
Browse files Browse the repository at this point in the history
Added support for single and double quotes.
Tests for simple case, and the case where JSON is used.
Updated README.md

Signed-off-by: Matthew B. White <whitemat@uk.ibm.com>
  • Loading branch information
mbwhite committed Feb 14, 2020
1 parent 9f0c21b commit f36c791
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
16 changes: 16 additions & 0 deletions README.md
Expand Up @@ -26,6 +26,22 @@ with one running node process. Cliffy is NOT an argv parser.
This is what allows Cliffy to parse negatives.
- Requires node v6+

### Quoted parameters

Parameters may be quoted using either ' (single) or " (double) quotes. For example the command could be

```
say "Hello World" 'Lovely Weather'
```

This would give two parameters of `Hello World` and `Lovely Weather`. When inside the quoted parameter, the other type of quotes can be used. This lets JSON be entered for example.

```
say '{"text": "This is the weather"}'
```

Will give a parameter of the string, `{"text": "This is the weather"}` that can then be parsed as JSON.

## Quickstart

**Installation**:
Expand Down
5 changes: 3 additions & 2 deletions src/index.ts
Expand Up @@ -57,8 +57,9 @@ export class CLI {
}

private async executeCommand(input: string): Promise<void> {
const parts = input.match(/(\w|@|-|\.)+|"[^"]+"/g) || [];
const pieces = parts.map(word => word.replace(/^"(.+(?="$))"$/, '$1'));
const parts = input.match(/(\w|@|-|\.)+|"[^"]+"|'[^']+'/g) || [];
const pieces = parts.map(word => word.replace(/^"(.+(?="$))"$/, '$1')).
map(word => word.replace(/^'(.+(?='$))'$/, '$1'));

if (pieces[0] === "help") return this.help(pieces.slice(1));

Expand Down
29 changes: 29 additions & 0 deletions src/test/index.ts
Expand Up @@ -79,6 +79,35 @@ describe("CLI", function() {
});
});

it("Should accept single and double quoted parameters", function() {
return new Promise((res, rej) => {
cli.addCommand("test", {
parameters: [
{ label: "p1", type: "string" },
{ label: "p2", type: "string" }],
action(params) {
const correct = params.p1 === "hello \"quoted\" world" && params.p2 === "lovely 'quoted' weather";
if (correct) { res(); } else { rej(new Error("Bad params")); }
}
});
send("test 'hello \"quoted\" world' \"lovely 'quoted' weather\"");
});
});
it("Should accept json-style parameters", function() {
return new Promise((res, rej) => {
cli.addCommand("test", {
parameters: [
{ label: "p1", type: "string" }],
action(params) {
const correct = params.p1 === "{\"text\":\"This is the weather\"}";
if (correct) { res(); } else { rej(new Error("Bad params")); }
}
});
const testJson = JSON.stringify({text:"This is the weather"});
send(`test '${testJson}'`);
});
});

it("Should throw an error on invalid optional parameter order", function() {
try {
cli.addCommand("test", {
Expand Down

0 comments on commit f36c791

Please sign in to comment.