Skip to content

adds support for glob-style input spec paths and directory output paths #616

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

Merged
merged 3 commits into from
May 28, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
101 changes: 72 additions & 29 deletions bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const fs = require("fs");
const { bold, green, red } = require("kleur");
const path = require("path");
const meow = require("meow");
const glob = require("tiny-glob");
const { default: openapiTS } = require("../dist/cjs/index.js");
const { loadSpec } = require("./loaders");

Expand Down Expand Up @@ -52,36 +53,31 @@ Options
}
);

const OUTPUT_FILE = "FILE";
const OUTPUT_STDOUT = "STDOUT";

const timeStart = process.hrtime();

async function main() {
let output = "FILE"; // FILE or STDOUT
const pathToSpec = cli.input[0];
function errorAndExit(errorMessage) {
process.exitCode = 1; // needed for async functions
throw new Error(red(errorMessage));
}

// 0. setup
if (!cli.flags.output) {
output = "STDOUT"; // if --output not specified, fall back to stdout
}
if (output === "FILE") {
console.info(bold(`✨ openapi-typescript ${require("../package.json").version}`)); // only log if we’re NOT writing to stdout
}
if (cli.flags.rawSchema && !cli.flags.version) {
throw new Error(`--raw-schema requires --version flag`);
}
async function generateSchema(pathToSpec) {
const output = cli.flags.output ? OUTPUT_FILE : OUTPUT_STDOUT; // FILE or STDOUT

// 1. input
// load spec
let spec = undefined;
try {
spec = await loadSpec(pathToSpec, {
auth: cli.flags.auth,
log: output !== "STDOUT",
log: output !== OUTPUT_STDOUT,
});
} catch (err) {
process.exitCode = 1; // needed for async functions
throw new Error(red(`❌ ${err}`));
errorAndExit(`❌ ${err}`);
}

// 2. generate schema (the main part!)
// generate schema
const result = openapiTS(spec, {
auth: cli.flags.auth,
additionalProperties: cli.flags.additionalProperties,
Expand All @@ -91,11 +87,54 @@ async function main() {
version: cli.flags.version,
});

// 3. output
if (output === "FILE") {
// output option 1: file
const outputFile = path.resolve(process.cwd(), cli.flags.output);
// output
if (output === OUTPUT_FILE) {
let outputFile = path.resolve(process.cwd(), cli.flags.output);

// decide filename if outputFile is a directory
if (fs.existsSync(outputFile) && fs.lstatSync(outputFile).isDirectory()) {
const basename = path.basename(pathToSpec).split(".").slice(0, -1).join(".") + ".ts";
outputFile = path.resolve(outputFile, basename);
}

fs.writeFileSync(outputFile, result, "utf8");

const timeEnd = process.hrtime(timeStart);
const time = timeEnd[0] + Math.round(timeEnd[1] / 1e6);
console.log(green(`🚀 ${pathToSpec} -> ${bold(outputFile)} [${time}ms]`));
} else {
process.stdout.write(result);
}

return result;
}

async function main() {
const output = cli.flags.output ? OUTPUT_FILE : OUTPUT_STDOUT; // FILE or STDOUT
const pathToSpec = cli.input[0];
const inputSpecPaths = await glob(pathToSpec, { filesOnly: true });

if (output === OUTPUT_FILE) {
console.info(bold(`✨ openapi-typescript ${require("../package.json").version}`)); // only log if we’re NOT writing to stdout
}

if (cli.flags.rawSchema && !cli.flags.version) {
throw new Error(`--raw-schema requires --version flag`);
}

if (/^https?:\/\//.test(pathToSpec)) {
// handle remote resource input and exit
return await generateSchema(pathToSpec);
}

// no matches for glob
if (inputSpecPaths.length === 0) {
errorAndExit(
`❌ Could not find any spec files matching the provided input path glob. Please check that the path is correct.`
);
}

if (output === OUTPUT_FILE) {
// recursively create parent directories if they don’t exist
const parentDirs = cli.flags.output.split(path.sep);
for (var i = 1; i < parentDirs.length; i++) {
Expand All @@ -104,15 +143,19 @@ async function main() {
fs.mkdirSync(dir);
}
}
}

fs.writeFileSync(outputFile, result, "utf8");
// if there are multiple specs, ensure that output is a directory
if (inputSpecPaths.length > 1 && output === OUTPUT_FILE && !fs.lstatSync(cli.flags.output).isDirectory()) {
errorAndExit(
`❌ When specifying a glob matching multiple input specs, you must specify a directory for generated type definitions.`
);
}

const timeEnd = process.hrtime(timeStart);
const time = timeEnd[0] + Math.round(timeEnd[1] / 1e6);
console.log(green(`🚀 ${pathToSpec} -> ${bold(cli.flags.output)} [${time}ms]`));
} else {
// output option 2: stdout
process.stdout.write(result);
let result = "";
for (const specPath of inputSpecPaths) {
// append result returned for each spec
result += await generateSchema(specPath);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is clever. I hadn’t thought about the stdout case but this seems pretty handy.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh wait—we’re logging to stdout elsewhere. Truth be told, I don’t know why we’re returning the result here; it doesn’t seem to be helpful (and possibly wasting memory?). Either way, this is fine to leave in this PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey, I was initially confused as well about what the reason to return the result was. In user usage, the returned result doesn't matter, but I think it gets used in certain tests so it should be kept in.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK. Yeah leave it in for now, and I can revisit that post-merge.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright!
Rebasing and updating expected schemas fixed the broken test, so I think this PR should be ready now

}

return result;
Expand Down
41 changes: 40 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@
"kleur": "^4.1.4",
"meow": "^9.0.0",
"mime": "^2.5.2",
"prettier": "^2.3.0"
"prettier": "^2.3.0",
"tiny-glob": "^0.2.9"
},
"devDependencies": {
"@types/jest": "^26.0.14",
Expand Down
10 changes: 10 additions & 0 deletions tests/bin/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,14 @@ describe("cli", () => {
const result = execSync(`../../bin/cli.js specs/petstore.yaml`, { cwd: __dirname });
expect(result.toString("utf8")).toBe(expected);
});

it("supports glob paths", () => {
const expectedPetstore = fs.readFileSync(path.join(__dirname, "expected", "petstore.ts"), "utf8");
const expectedManifold = fs.readFileSync(path.join(__dirname, "expected", "manifold.ts"), "utf8");
execSync(`../../bin/cli.js \"specs/*.yaml\" -o generated/`, { cwd: __dirname }); // Quotes are necessary because shells like zsh treats glob weirdly
const outputPetstore = fs.readFileSync(path.join(__dirname, "generated", "petstore.ts"), "utf8");
const outputManifold = fs.readFileSync(path.join(__dirname, "generated", "manifold.ts"), "utf8");
expect(outputPetstore).toBe(expectedPetstore);
expect(outputManifold).toBe(expectedManifold);
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice test!

});
Loading