diff --git a/CHANGELOG.md b/CHANGELOG.md index 37856d25..d21001b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,7 @@ Released: TBD editors, from @Mingun - [#299](https://github.com/peggyjs/peggy/issues/299) Add example grammar for a [SemVer.org](https://semver.org) semantic version string, from @dselman +- [#308](https://github.com/peggyjs/peggy/pull/308) Add support for reading test data from stdin using `-T -`, from @hildjj. ### Bug Fixes diff --git a/bin/peggy-cli.js b/bin/peggy-cli.js index eedf3dbd..bbf8b7c7 100644 --- a/bin/peggy-cli.js +++ b/bin/peggy-cli.js @@ -191,7 +191,7 @@ class PeggyCLI extends Command { ) .addOption(new Option( "-T, --test-file ", - "Test the parser with the contents of the given file, outputting the result of running the parser instead of the parser itself. If the input to be tested is not parsed, the CLI will exit with code 2" + "Test the parser with the contents of the given file, outputting the result of running the parser instead of the parser itself. If the input to be tested is not parsed, the CLI will exit with code 2. A filename of '-' will read from stdin." ).conflicts("test")) .option("--trace", "Enable tracing in generated parser", false) .addOption( @@ -548,9 +548,13 @@ class PeggyCLI extends Command { }); } - test(source) { + async test(source) { if (this.testFile) { - this.testText = fs.readFileSync(this.testFile, "utf8"); + if (this.testFile === "-") { + this.testText = await readStream(this.std.in); + } else { + this.testText = fs.readFileSync(this.testFile, "utf8"); + } } if (typeof this.testText === "string") { this.verbose("TEST TEXT:", this.testText); @@ -654,7 +658,7 @@ class PeggyCLI extends Command { exitCode = 2; this.verbose("CLI", errorText = "running test"); - this.test(mappedSource); + await this.test(mappedSource); } } catch (error) { // Will either exit or throw. diff --git a/test/cli/run.spec.ts b/test/cli/run.spec.ts index ad2e57d7..856ec62a 100644 --- a/test/cli/run.spec.ts +++ b/test/cli/run.spec.ts @@ -370,7 +370,8 @@ Options: given file, outputting the result of running the parser instead of the parser itself. If the input to be tested is not parsed, the - CLI will exit with code 2 + CLI will exit with code 2. A filename of '-' + will read from stdin. --trace Enable tracing in generated parser (default: false) -h, --help display help for command @@ -1040,6 +1041,12 @@ bar = '2' expected: /name: 'peggy',$/m, // Output is JS, not JSON }); + await exec({ + args: [grammarFile, "-T", "-"], + stdin: '{"foo": null}', + expected: "{ foo: null }\n", // Still JS, not JSON + }); + await exec({ args: ["-T", "____ERROR____FILE_DOES_NOT_EXIST.js", grammarFile], errorCode: "peggy.cli",