Skip to content

Instantly share code, notes, and snippets.

@jaimefps
Last active April 29, 2020 20:26
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 jaimefps/8db70ee2247788b54de50b25fb269bad to your computer and use it in GitHub Desktop.
Save jaimefps/8db70ee2247788b54de50b25fb269bad to your computer and use it in GitHub Desktop.
Sort root level keys on a Yaml string or Yaml file.
fs = require("fs");
yaml = require("yamljs");
// Sort root level keys on a JS object.
function sortKeys(obj, promote = [], demote = [], sorter) {
const sorted = {};
promote.forEach((k) => (sorted[k] = obj[k]));
Object.keys(obj)
.filter((k) => !demote.includes(k) && !promote.includes(k))
.sort(sorter)
.forEach((k) => (sorted[k] = obj[k]));
demote.forEach((k) => (sorted[k] = obj[k]));
return sorted;
}
// Sort root level keys on a Yaml file or string.
function sortYaml({
demote,
inputPath,
outputPath,
promote,
sorter,
verbose,
yamlString,
}) {
if (verbose) {
console.log("Attempting to sort keys in Yaml at: ", inputPath, "\n\n");
}
let yamlObj;
try {
if (yamlString) {
yamlObj = yaml.parse(yamlString);
} else if (inputPath) {
yamlObj = yaml.parse(fs.readFileSync(inputPath, "utf8"));
} else {
console.error("No Yaml data provided.");
return;
}
if (verbose) {
console.log(
"Parsed yaml to json:\n\n",
JSON.stringify(yamlObj, null, 2),
"\n\n"
);
}
} catch (e) {
console.error("Yaml parser failed.");
console.error(e);
return;
}
try {
const sortedObj = sortKeys(yamlObj, promote, demote, sorter);
const ymlResult = yaml.stringify(sortedObj);
if (verbose) {
console.log(
"Sorted object:\n\n",
JSON.stringify(sortedObj, null, 2),
"\n\n"
);
console.log("Sorted yaml:\n\n", ymlResult, "\n\n");
}
if (outputPath) {
fs.writeFileSync(outputPath, ymlResult);
} else {
return ymlResult;
}
if (verbose) {
console.log("Yaml sorter completed successfully");
}
} catch (e) {
console.error("Failed to write file.");
console.error(e);
}
}
// Sample invocation:
const finalResult = sortYaml({
demote: ["doe"],
inputPath: "./sample.yaml",
outputPath: "./sample-output.yaml",
promote: ["ray"],
verbose: true,
// sorter: undefined,
// yamlString: undefined,
});
// If "outputPath" is not provided:
// console.log(`final result:\n\n${finalResult}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment