UNPKG

declapract

Version:

A tool to declaratively define best practices, maintainable evolve them, and scalably enforce them.

34 lines 2.42 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.replaceProjectVariablesInDeclaredFileContents = void 0; const flat_1 = __importDefault(require("flat")); const replaceAll_1 = require("../../../../utils/stringPolyfill/replaceAll"); const UnexpectedCodePathError_1 = require("../../../UnexpectedCodePathError"); const UserInputError_1 = require("../../../UserInputError"); const replaceProjectVariablesInDeclaredFileContents = ({ projectVariables, fileContents, }) => { // find the variables declared in the file contents const uniqueDeclaredVariableExpressions = [ ...new Set(Array.from(fileContents.matchAll(new RegExp(/\@declapract\{variable.[\w\.]+\}/g)), (m) => m[0])), ]; // flatten the project variables so we can dereference by nested keys (e.g., `variable.databaseUserName.serviceUser`) const flattenedProjectVariables = (0, flat_1.default)(projectVariables); // lookup each one and replace it (or throw an error if the variable was not defined) const replacedFileContents = uniqueDeclaredVariableExpressions.reduce((contents, thisVariableExpression) => { const variableKey = (new RegExp(/@declapract\{variable\.([\w\.]+)\}/).exec(thisVariableExpression) ?? [])[1]; if (!variableKey) throw new UnexpectedCodePathError_1.UnexpectedCodePathError(`could not extract variableKey from variableExpression '${thisVariableExpression}'`); const variableValue = flattenedProjectVariables[variableKey]; if (!variableValue) throw new UserInputError_1.UserInputError(`variable was declared in file contents but its value was not defined: '${variableKey}' (declared by '${thisVariableExpression}')`, { potentialSolution: 'Please either remove the reference to this variable or define its value in your projects variables (e.g., in `declapract.use.yml`)', }); return (0, replaceAll_1.replaceAll)(contents, thisVariableExpression, variableValue); }, fileContents); // and return the replaced contents return replacedFileContents; }; exports.replaceProjectVariablesInDeclaredFileContents = replaceProjectVariablesInDeclaredFileContents; //# sourceMappingURL=replaceProjectVariablesInDeclaredFileContents.js.map