Skip to content

Commit 1b3b887

Browse files
committed
Fix CLI argument parsing
1 parent bc86da6 commit 1b3b887

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

bin/json-schema-to-openapi-schema.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
#!/usr/bin/env node
22
'use strict';
33

4-
const yargs = require('yargs');
4+
const yargs = require('yargs/yargs');
5+
const { hideBin } = require('yargs/helpers');
56
const converter = require('../dist/index.js').default;
67
const helpText = require('./help-text.json');
78
const fs = require('fs');
@@ -35,7 +36,7 @@ const readFileAsync = require('util').promisify(fs.readFile);
3536
*/
3637
function parseArgs() {
3738
// Configure the argument parser
38-
yargs
39+
const parser = yargs(hideBin(process.argv))
3940
.option('d', {
4041
alias: 'dereference',
4142
type: 'boolean',
@@ -47,13 +48,13 @@ function parseArgs() {
4748
});
4849

4950
// Show the version number on "--version" or "-v"
50-
yargs.version().alias('v', 'version');
51+
parser.version().alias('v', 'version');
5152

5253
// Disable the default "--help" behavior
53-
yargs.help(false);
54+
parser.help(false);
5455

5556
// Parse the command-line arguments
56-
let args = yargs.argv;
57+
let args = parser.parseSync();
5758

5859
// Normalize the parsed arguments
5960
let parsed = {

test/cli.test.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { execFile } from 'node:child_process';
2+
import { join } from 'node:path';
3+
import { promisify } from 'node:util';
4+
import { getSchema } from './helpers';
5+
6+
const execFileAsync = promisify(execFile);
7+
const repoRoot = join(__dirname, '..');
8+
const cliPath = join(repoRoot, 'bin', 'json-schema-to-openapi-schema.js');
9+
const schemaPath = join(repoRoot, 'test', 'schemas', 'basic', 'json-schema.json');
10+
const expectedOpenApiPath = 'basic/openapi.json';
11+
12+
it('prints help without crashing', async ({ expect }) => {
13+
const { stdout, stderr } = await execFileAsync(process.execPath, [cliPath, '-h'], {
14+
cwd: repoRoot,
15+
});
16+
17+
expect(stderr).toBe('');
18+
expect(stdout).toContain('json-schema-to-openapi-schema <command> [options] <file>');
19+
});
20+
21+
it('converts a schema through the CLI', async ({ expect }) => {
22+
const { stdout, stderr } = await execFileAsync(
23+
process.execPath,
24+
[cliPath, 'convert', schemaPath],
25+
{
26+
cwd: repoRoot,
27+
},
28+
);
29+
30+
expect(stderr).toBe('');
31+
expect(JSON.parse(stdout)).toEqual(getSchema(expectedOpenApiPath));
32+
});

0 commit comments

Comments
 (0)