Skip to content

Commit

Permalink
chore: use nunjucks to generate name from template
Browse files Browse the repository at this point in the history
  • Loading branch information
azech-hqs committed May 15, 2023
1 parent 5b67e62 commit b3242a2
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 15 deletions.
2 changes: 1 addition & 1 deletion assets/test.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
ldaConfigs: !combine
name:
template: DFT($parameters.functional)
template: DFT-{{ parameters.functional }}
substitutions:
pz: PZ
forEach:
Expand Down
29 changes: 18 additions & 11 deletions build_models.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import yaml from "js-yaml";
import lodash from "lodash";
import { allYAMLSchemas } from "@exabyte-io/code.js/dist/utils";
import Ajv from "ajv";
import nunjucks from "nunjucks"

/**
* Render name template based on config.
Expand All @@ -13,24 +14,30 @@ import Ajv from "ajv";
* @return {string}
* @example
* generateName(
* "Hello $user!",
* "Hello {{user}}!",
* {user: "user001"},
* {user001: "John Doe"}
* ); // "Hello John Doe!"
*/
function generateName(template, data, substitutionMap = {}) {
// Regular expression to match the template variables, e.g `$job.workflow`
const regex = /\$(\w+(\.\w+)*)/g;
// Create a copy of data to avoid modifying the original
const renderData = lodash.cloneDeep(data);

return template.replace(regex, (match, objPath) => {
const value = lodash.get(data, objPath)
// Helper function for recursive substitution
function substituteNested(obj) {
lodash.forIn(obj, (value, key) => {
if (lodash.isPlainObject(value)) {
// If value is an object, recurse
substituteNested(value);
} else if (substitutionMap[value]) {
// If value is in substitution map, replace it
obj[key] = substitutionMap[value];
}
});
}

if (substitutionMap[value]) {
return substitutionMap[value];
}

return value || "";
});
substituteNested(renderData);
return nunjucks.renderString(template, renderData);
}


Expand Down
31 changes: 29 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,13 @@
"js-yaml": "^4.1.0",
"lodash": "^4.17.21",
"mixwith": "^0.1.1",
"nunjucks": "^3.2.4",
"underscore": "^1.13.3",
"underscore.string": "^3.3.4"
},
"devDependencies": {
"@exabyte-io/ade.js": "2022.8.31-0",
"@exabyte-io/code.js": "git+https://github.com/Exabyte-io/code.js.git#083c471cbeee3196c37ea304ae8bc5d44e984e2b",
"@exabyte-io/code.js": "git+https://github.com/Exabyte-io/code.js.git#ba9ad6131c39e9940bd8dff66f6b2876fe89a0fc",
"@exabyte-io/eslint-config": "^2022.11.17-0",
"@exabyte-io/made.js": "2022.6.15-0",
"chai": "^4.3.4",
Expand Down

0 comments on commit b3242a2

Please sign in to comment.