kubegen
kubegen copied to clipboard
canonical sorting of keys in an object
It'd be beneficial to have a canonical sorting order for certain keys, i.e. apiVersion, kind metadata, spec and status.
I in another project we have done this:
exports.dumpSortedYAML = (body) => {
const orderedKeys = [ 'apiVersion', 'kind', 'name', 'metadata' ];
const opts = {
sortKeys: (a, b) => {
const hasA = orderedKeys.includes(a);
const hasB = orderedKeys.includes(b);
// a in reference array and b not in reference array
if (hasA && !hasB) return -1;
// a not in reference array and b in reference array
if (!hasA && hasB) return +1;
// both a and b in reference array: return comparison of position in array
if (hasA && hasB) return orderedKeys.indexOf(a) > orderedKeys.indexOf(b) ? +1 : -1;
// neither a nor b are in the reference array: return the normal alphabetic comparison
if (!hasA && !hasB) return a < b ? -1 : +1;
}
};
return yaml.safeDump(body, opts);
};
https://github.com/go-yaml/yaml/issues/30#issuecomment-56448360