add possibility to configure nunjucks configs

Signed-off-by: Kiss Miklos <miklos@roadie.io>
This commit is contained in:
Kiss Miklos
2024-01-23 16:49:16 +01:00
parent 086294bda1
commit 00c90984e5
4 changed files with 17 additions and 1 deletions
@@ -19,6 +19,7 @@ import { resolvePackagePath } from '@backstage/backend-common';
import {
TemplateFilter as _TemplateFilter,
TemplateGlobal as _TemplateGlobal,
NunjucksConfigs,
} from '@backstage/plugin-scaffolder-node';
import fs from 'fs-extra';
import { JsonValue } from '@backstage/types';
@@ -34,6 +35,7 @@ const { render, renderCompat } = (() => {
const env = module.exports.configure({
autoescape: false,
...JSON.parse(nunjucksConfigs),
tags: {
variableStart: '\${{',
variableEnd: '}}',
@@ -42,6 +44,7 @@ const { render, renderCompat } = (() => {
const compatEnv = module.exports.configure({
autoescape: false,
...JSON.parse(nunjucksConfigs),
tags: {
variableStart: '{{',
variableEnd: '}}',
@@ -109,6 +112,7 @@ export interface SecureTemplaterOptions {
templateFilters?: Record<string, TemplateFilter>;
/* Extra user-provided nunjucks globals */
templateGlobals?: Record<string, TemplateGlobal>;
nunjucksConfigs?: NunjucksConfigs;
}
export type SecureTemplateRenderer = (
@@ -122,6 +126,7 @@ export class SecureTemplater {
cookiecutterCompat,
templateFilters = {},
templateGlobals = {},
nunjucksConfigs = {},
} = options;
const isolate = new Isolate({ memoryLimit: 128 });
@@ -140,6 +145,8 @@ export class SecureTemplater {
mkScript(nunjucksSource),
);
await contextGlobal.set('nunjucksConfigs', JSON.stringify(nunjucksConfigs));
const availableFilters = Object.keys(templateFilters);
await contextGlobal.set(
@@ -69,6 +69,8 @@ export function createFetchTemplateAction(options: {
copyWithoutTemplating?: string[];
cookiecutterCompat?: boolean;
replace?: boolean;
trimBlocks?: boolean;
lstripBlocks?: boolean;
}>({
id: 'fetch:template',
description:
@@ -237,6 +239,10 @@ export function createFetchTemplateAction(options: {
...additionalTemplateFilters,
},
templateGlobals: additionalTemplateGlobals,
nunjucksConfigs: {
trimBlocks: ctx.input.trimBlocks,
lstripBlocks: ctx.input.lstripBlocks,
},
});
for (const location of allEntriesInTemplate) {
+1 -1
View File
@@ -23,4 +23,4 @@
export * from './actions';
export * from './tasks';
export * from './files';
export type { TemplateFilter, TemplateGlobal } from './types';
export type { TemplateFilter, TemplateGlobal, NunjucksConfigs } from './types';
+3
View File
@@ -23,3 +23,6 @@ export type TemplateFilter = (...args: JsonValue[]) => JsonValue | undefined;
export type TemplateGlobal =
| ((...args: JsonValue[]) => JsonValue | undefined)
| JsonValue;
/** @public */
export type NunjucksConfigs = { trimBlocks?: boolean; lstripBlocks?: boolean };