Skip to content

Instantly share code, notes, and snippets.

@GregGGregGreG
Forked from bvandenbon/README.md
Created April 22, 2020 14:08
Show Gist options
  • Save GregGGregGreG/d9d21e949204a254265d3b7502c63018 to your computer and use it in GitHub Desktop.
Save GregGGregGreG/d9d21e949204a254265d3b7502c63018 to your computer and use it in GitHub Desktop.

To install dependencies of the above script:

npm install yaml

Usage:

parameters:   <inputdir> <outputfile> [--help]
  --help         generates this message.
  <inputdir>     a directory containing individual yml files in a swagger structure.
  <outputfile>   a directory containing the merged swagger yml files.

Requirements for the input directory:

  • should contain a ./root.yml file
  • schema's should be stored in ./components/schemas
  • paths should be stored in ./paths

You can create as many subfolders within those schemas and paths folders as you like. The files will all be merged together regardless of their level (as if they would all be directly in ./components/schemas or ./paths

Enjoy.

console.log(`...opening root file ${rootYmlPath}`);
if (!fs.existsSync(rootYmlPath)) {
return console.error("input directory should contain a root.yml file");
}
const rootFileContent = fs.readFileSync(rootYmlPath, 'utf8')
const json = YAML.parse(rootFileContent);
const schemasFolder = `${inputDir}/components/schemas`;
if (! json.components) json.components = {};
if (! json.components.schemas) json.components.schemas = {};
const schemas = processFolder(json.components.schemas, schemasFolder);
const pathsFolder = `${inputDir}/paths`;
if (! json.paths) json.paths = {};
const paths = processFolder(json.paths, pathsFolder);
let data = "";
if (outputFile.toLowerCase().endsWith(".yml")) {
data = YAML.stringify(json);
} else {
data = JSON.stringify(json);
}
fs.writeFileSync(outputFile, data, { encoding: 'utf8'});
function printHelp() {
console.log("parameters: <inputdir> <outputfile> [--help]")
console.log(" --help generates this message.");
console.log(" <inputdir> a directory containing individual yml files in a swagger structure.");
console.log(" <outputfile> a directory containing the merged swagger yml files.");
}
function processFolder(target, folder) {
console.log(`processing folder ${folder}`);
const parts = folder.split("/");
const folderName = parts[parts.length - 1];
const files = fs.readdirSync(folder);
for (const file of files) {
const fullPath = `${folder}/${file}`;
const stats = fs.statSync(fullPath);
if (stats.isDirectory()) {
processFolder(target, fullPath);
} else {
processFile(target, fullPath);
}
}
}
function processFile(target, file) {
const content = fs.readFileSync(file, 'utf8')
const json = YAML.parse(content);
for (const key in json) {
if (!json.hasOwnProperty(key)) continue;
target[key] = json[key];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment