Skip to content

Instantly share code, notes, and snippets.

@tyriis
Last active December 13, 2022 21:39
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 tyriis/56934f1360047512f2a2238c833a748c to your computer and use it in GitHub Desktop.
Save tyriis/56934f1360047512f2a2238c833a748c to your computer and use it in GitHub Desktop.
split a yaml file into multiple ones based on the first level key
{
"name": "split-yaml",
"version": "1.0.0",
"main": "split-yaml.js",
"scripts": {
"split": "node split-yaml.js"
},
"dependencies": {
"js-yaml": "^3.14.0",
"readline": "^1.3.0"
}
}
const fs = require('fs');
const yaml = require('js-yaml');
const readline = require('readline');
// Get the name of the input YAML file from the command-line arguments
const [, , inputYamlFile] = process.argv;
// Load the YAML file into a JavaScript object
const yamlObj = yaml.safeLoad(fs.readFileSync(inputYamlFile));
// Create a readline interface for prompting the user
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// Loop over each top-level key in the object
Object.keys(yamlObj).forEach(key => {
// Create a copy of the value object
const value = Object.assign({}, yamlObj[key]);
// Change the key name from "groups" to "members"
value.members = value.groups;
delete value.groups;
// Create a new object containing only the key and its modified value
const obj = { [key]: value };
// Convert the object to a YAML string
const yamlStr = yaml.safeDump(obj);
// Check if a file with the same name already exists
if (fs.existsSync(`${key}.yaml`)) {
// Prompt the user for confirmation before overwriting the file
rl.question(`File "${key}.yaml" already exists. Overwrite? (Y/n) `, answer => {
if (answer.toLowerCase() === 'y' || answer === '') {
// Write the YAML string to the file if the user confirms
fs.writeFileSync(`${key}.yaml`, yamlStr);
}
rl.close();
});
} else {
// Write the YAML string to the file if it does not already exist
// Write the YAML string to a file named after the key
fs.writeFileSync(`${key}.yaml`, yamlStr);
}
});
@tyriis
Copy link
Author

tyriis commented Dec 13, 2022

To use this script, save it to a file (e.g. split-yaml.js) and run it using node split-yaml.js input.yaml, where input.yaml is the name of the input YAML file.

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