Created
October 3, 2017 14:42
-
-
Save darosh/866d905b6e0919301831393a96841e1a to your computer and use it in GitHub Desktop.
Patching script for openapi-directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const path = require('path') | |
const yaml = require('js-yaml') | |
// loads and parses tab delimited file 'categories.tab' | |
readFileAsync(path.join(__dirname, 'categories.tab')).then(data => { | |
const records = data.trim() | |
.split('\n').map(line => | |
line.split('\t').map((cell, index) => | |
index > 1 | |
? cell.trim().replace(/\s/g, '').split(',') | |
: cell.trim().replace(/\s/g, '') | |
) | |
) | |
records.forEach(record => { | |
const dirPath = record[1] ? path.join('./APIs', record[0], record[1]) : path.join('./APIs', record[0]) | |
existsAsync(dirPath).then(({exists, queryPath}) => { | |
if (exists) { | |
const patchPath = path.join(queryPath, 'patch.yaml') | |
readFileAsync(patchPath) | |
.then(data => { | |
const patch = yaml.load(data) | |
updatePatch(record, patch, patchPath) | |
}) | |
.catch(() => { | |
console.warn(`Missing patch file ${patchPath}`) | |
updatePatch(record, {}, patchPath) | |
}) | |
} else { | |
console.error(`Missing folder ${queryPath}`) | |
} | |
}) | |
}) | |
}) | |
function updatePatch(record, patch, patchPath) { | |
let updateNeeded = false | |
patch.info = patch.info || {} | |
const categories = patch.info['x-apisguru-categories'] = patch.info['x-apisguru-categories'] || [] | |
// removing old categories | |
record[2].forEach(category => { | |
const index = categories.indexOf(category) | |
if (index > -1) { | |
console.info(`Removing "${category}" from ${patchPath}`) | |
categories.splice(index, 1) | |
updateNeeded = true | |
} | |
}) | |
// adding new categories | |
record[3].forEach(category => { | |
const index = categories.indexOf(category) | |
if (index === -1) { | |
console.info(`Adding "${category}" to ${patchPath}`) | |
categories.push(category) | |
updateNeeded = true | |
} | |
}) | |
if(updateNeeded) { | |
fs.writeFile(patchPath, yaml.dump(patch), () => { | |
console.info(`Update saved to ${patchPath}`) | |
}) | |
} else { | |
console.warn(`No update needed in ${patchPath}`) | |
} | |
} | |
function existsAsync(queryPath) { | |
return new Promise(function (resolve) { | |
fs.exists(queryPath, (exists) => resolve({exists, queryPath})) | |
}) | |
} | |
function readFileAsync(filename) { | |
return new Promise(function (resolve, reject) { | |
fs.readFile(filename, 'utf8', function (err, data) { | |
if (err) | |
reject(err) | |
else | |
resolve(data) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment