Skip to content

Instantly share code, notes, and snippets.

@ryanve
Last active June 16, 2017 16:18
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 ryanve/e1c251f40879855935ad615e26f72d8c to your computer and use it in GitHub Desktop.
Save ryanve/e1c251f40879855935ad615e26f72d8c to your computer and use it in GitHub Desktop.
Sort YAML keys using Node.js
const fs = require('fs')
const yaml = require('js-yaml')
const transform = ({target, source, options}) => {
fs.readFile(source, 'utf8', function(err, data) {
if (err) throw err
data = yaml.safeLoad(data)
data = yaml.safeDump(data, options)
fs.writeFile(target, data, function(err) {
if (err) throw err
})
})
}
transform({
source: 'source.yml',
target: 'target.yml',
options: {
sortKeys: true,
lineWidth: 1000
}
})
const fs = require('fs')
const yaml = require('js-yaml')
const traverse = require('traverse')
const equal = require('deep-equal')
const verify = ({target, source}) => {
source = traverse(yaml.safeLoad(fs.readFileSync(source, 'utf8')))
target = traverse(yaml.safeLoad(fs.readFileSync(target, 'utf8')))
const measure = function(a, b) {
if (a.length !== b.length) console.error('Length mismatch:', a.length, b.length)
}
const is = function(p) {
const diff = !equal(source.get(p), target.get(p))
if (diff) console.error('Value mismatch for path', JSON.stringify(p))
return !diff
}
const report = function(array) {
if (array.every(is)) console.log(array.length, 'verified')
}
measure(source.paths(), target.paths())
report(source.paths().sort().reverse())
report(target.paths().sort().reverse())
}
verify({
source: 'source.yml',
target: 'target.yml',
})
@ryanve
Copy link
Author

ryanve commented Jun 16, 2017

Uses js-yaml, traverse, deep-equal and Node filesystem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment