const fs = require('fs');
// Replace 'input.json' and 'input.yaml' with the paths to your JSON and YAML files
const jsonFilePath = 'input.json';
const yamlFilePath = 'application-cloud.yml';
const envParameterPrefix = 'vcap.services.authentication.credentials'
// Function to read the JSON file and transform it into a JavaScript object
function readAndTransformJson(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
reject(err);
return;
}
try {
const jsonData = JSON.parse(data);
const transformedObject = {};
// Transforming the JSON data into the desired format
Object.keys(jsonData).forEach(key => {
transformedObject[key] = jsonData[key];
});
resolve(transformedObject);
} catch (error) {
reject(error);
}
});
});
}
function getValueFromCustomPath(dataObject, customPath) {
const pathParts = customPath.split('.');
let value = dataObject;
for (const part of pathParts) {
if (value.hasOwnProperty(part)) {
value = value[part];
} else {
// Return an empty string if any part of the custom path is not found in the object
return '';
}
}
return value;
}
// Function to replace values in the YAML file based on the specified format
function replaceYamlValues(yamlFilePath, dataObject) {
fs.readFile(yamlFilePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading the YAML file:', err);
return;
}
try {
let lines = data.split('\n');
// Replace values in each line of the YAML data using the specified format
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const matches = line.match(new RegExp(`\\$\\{${envParameterPrefix}\\.(.+?)\\}`, 'g'));
if (matches) {
for (const match of matches) {
const customPath = match.slice(2, -1).replace(`${envParameterPrefix}.`, '');
const value = getValueFromCustomPath(dataObject, customPath);
if (value) {
lines[i] = lines[i].replace(match, value);
}
}
}
}
// Save the updated YAML data back to the file
const updatedYamlData = lines.join('\n');
fs.writeFile(yamlFilePath, updatedYamlData, 'utf8', err => {
if (err) {
console.error('Error writing the updated YAML file:', err);
return;
}
console.log('YAML file updated successfully!');
});
} catch (error) {
console.error('Error parsing YAML:', error);
}
});
}
async function main() {
try {
const dataObject = await readAndTransformJson(jsonFilePath);
replaceYamlValues(yamlFilePath, dataObject);
} catch (error) {
console.error('An error occurred:', error);
}
}
main();