Created
September 21, 2018 18:51
-
-
Save commenthol/2fc09b54ee95ab0d14e1375afccf1bc1 to your computer and use it in GitHub Desktop.
convert loopback yaml models to json
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
/** | |
* convert models-yaml/*.yaml file to models/*.json | |
*/ | |
/* eslint no-console: off */ | |
const yaml = require('js-yaml') | |
const {resolve, basename} = require('path') | |
const fs = require('fs') | |
const HELP = ` | |
scripts/models.js [OPTIONS] dirname | |
dirname basedir should contain \`models-yaml\` and | |
\`models\` directory | |
OPTIONS: | |
-f|--file filename process filename | |
-h|--help This help | |
` | |
/** | |
* parse arguments | |
*/ | |
function cmd () { | |
const args = process.argv.slice(2) | |
const o = {} | |
while (args.length) { | |
const arg = args.shift() | |
if (/^-h|--help$/.test(arg)) { | |
o.help = true | |
} else if (/^-f|--file$/.test(arg)) { | |
o.file = arg.shift() | |
} else { | |
o.dir = arg | |
} | |
} | |
return o | |
} | |
/** | |
* get yaml files from `dirname` | |
*/ | |
function dirFiles (dirname) { | |
const files = fs.readdirSync(dirname) | |
.filter(file => /\.yaml$/.test(file)) | |
.map(file => resolve(dirname, file)) | |
return files | |
} | |
/** | |
* get target filename from `filename` and `basedir` | |
*/ | |
function targetFile (filename, basedir) { | |
const targetDir = resolve(basedir, 'models') | |
const name = basename(filename) | |
let out = resolve(targetDir, name) | |
if (name === 'model-config.yaml') { | |
out = resolve(basedir, name) | |
} | |
return out.replace(/\.yaml$/, '.json') | |
} | |
/** | |
* convert yaml file to json | |
*/ | |
function toJson (filename, basedir) { | |
const target = targetFile(filename, basedir) | |
const data = fs.readFileSync(filename, 'utf8') | |
const doc = yaml.safeLoad(data) | |
fs.writeFileSync(target, JSON.stringify(doc, null, 2) + '\n', 'utf8') | |
} | |
function main (obj) { | |
const o = cmd() | |
if (o.help) { | |
console.log(HELP) | |
return process.exit(0) | |
} | |
const basedir = o.dir || resolve(__dirname, '../server') | |
const source = resolve(basedir, 'models-yaml') | |
let files | |
if (o.file) { | |
files = [o.file] | |
} else { | |
files = dirFiles(source) | |
} | |
files.forEach(file => toJson(file, basedir)) | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment