Skip to content

Instantly share code, notes, and snippets.

@darosh
Created October 6, 2017 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darosh/d376c3a60f3b49b6c1d1319505c85472 to your computer and use it in GitHub Desktop.
Save darosh/d376c3a60f3b49b6c1d1319505c85472 to your computer and use it in GitHub Desktop.
const fs = require('fs')
const path = require('path')
const yaml = require('js-yaml')
const knownCategories = yaml.load(fs.readFileSync('./resources/categories.yaml', 'utf8'))
const TITLE = 0
const DOMAIN = 1
const PRODUCT = 2
const OLD = 3
const NEW = 4
// 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 >= OLD
? cell.trim().replace(/\s/g, '').split(',')
: cell.trim().replace(/\s/g, '')
)
)
records.forEach(record => {
const dirPath = record[PRODUCT] ? path.join('./APIs', record[DOMAIN], record[PRODUCT]) : path.join('./APIs', record[DOMAIN])
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[OLD].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[NEW].forEach(category => {
const index = categories.indexOf(category)
if (index === -1) {
if(knownCategories[category]) {
console.info(`Adding "${category}" to ${patchPath}`)
categories.push(category)
updateNeeded = true
} else {
console.info(`Skipping unknown category "${category}" for ${patchPath}`)
}
}
})
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