Created
February 14, 2020 10:29
-
-
Save magicmark/066279c783c815048132c7e933c1176d to your computer and use it in GitHub Desktop.
Tool to import CloudFormation yaml sections
This file contains 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
#!/usr/bin/env node | |
const { existsSync, readFileSync } = require("fs"); | |
const path = require('path'); | |
const APP = "cf-merge"; | |
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html | |
const TOP_LEVEL_TOKENS = [ | |
"AWSTemplateFormatVersion", | |
"Description", | |
"Metadata", | |
"Parameters", | |
"Mappings", | |
"Conditions", | |
"Transform", | |
"Resources", | |
"Outputs" | |
]; | |
const SECTION_REGEX = new RegExp(`^(${TOP_LEVEL_TOKENS.join('|')}):`, 'gm'); | |
function main(filePath) { | |
if (String(filePath).trim().length === 0) { | |
throw new TypeError(`[${APP}] Expected a file path as the first argument`); | |
} | |
filePath = path.resolve(filePath) | |
if (!existsSync(filePath)) { | |
throw new Error(`[${APP}] Could not find '${filePath}' on disk`); | |
} | |
let file = readFileSync(filePath, "utf8"); | |
const includeMatches = [...file.matchAll(/# @include (.+?)$/gm)]; | |
includeMatches.forEach(match => { | |
// e.g. ['# @include ./main.yml#Resources', './main.yml#Resources'] | |
const [includeStatement, resource] = match; | |
// e.g. ['./main.yml', 'Resources'] | |
const [relativeImportFilePath, section] = resource.split("#"); | |
const resolvedImportFilePath = path.normalize(path.join(path.dirname(filePath), relativeImportFilePath)); | |
const importedFile = readFileSync(resolvedImportFilePath, "utf8"); | |
const sections = importedFile.match(SECTION_REGEX); | |
const nextSection = sections[sections.indexOf(`${section}:`) + 1] || null; | |
const partial = importedFile.split(`${section}:`)[1].split(nextSection)[0]; | |
file = file.replace(includeStatement, `# imported from ${resolvedImportFilePath}\n${partial}`); | |
}); | |
console.log(file); | |
} | |
main(...process.argv.slice(2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment