Last active
December 13, 2022 21:39
-
-
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
This file contains hidden or 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
{ | |
"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" | |
} | |
} |
This file contains hidden or 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 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); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use this script, save it to a file (e.g. split-yaml.js) and run it using
node split-yaml.js input.yaml
, whereinput.yaml
is the name of the input YAML file.