Skip to content

Instantly share code, notes, and snippets.

@bvandenbon
Created November 27, 2019 16:17
Show Gist options
  • Save bvandenbon/b91c0e39387019daaa813fdcaeac2a51 to your computer and use it in GitHub Desktop.
Save bvandenbon/b91c0e39387019daaa813fdcaeac2a51 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