Last active
June 16, 2017 16:18
-
-
Save ryanve/e1c251f40879855935ad615e26f72d8c to your computer and use it in GitHub Desktop.
Sort YAML keys using Node.js
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 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 | |
} | |
}) |
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 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', | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uses js-yaml, traverse, deep-equal and Node filesystem.