From 2438616996e92095b42a96ed3a923d5dc20e05ef Mon Sep 17 00:00:00 2001
From: Roman <491247+moltar@users.noreply.github.com>
Date: Mon, 11 Dec 2023 14:18:49 +0000
Subject: [PATCH] feat(templating): adds encodeBase64 handlebars helper
 (#26197)

Co-authored-by: Rhys Arkins <rhys@arkins.net>
Co-authored-by: Michael Kriese <michael.kriese@visualon.de>
---
 docs/usage/templates.md         |  8 ++++++++
 lib/util/template/index.spec.ts | 24 ++++++++++++++++++++++++
 lib/util/template/index.ts      |  4 ++++
 3 files changed, 36 insertions(+)

diff --git a/docs/usage/templates.md b/docs/usage/templates.md
index e72e718257..f355135754 100644
--- a/docs/usage/templates.md
+++ b/docs/usage/templates.md
@@ -59,6 +59,14 @@ In the example above `depName` is the string you want to decode.
 
 Read the [MDN Web Docs, decodeURIComponent()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) to learn more.
 
+### encodeBase64
+
+If you want to convert a string to Base64, use the built-in function `encodeBase64` like this:
+
+`{{{encodeBase64 body}}}`
+
+In the example above `body` is the string you want to transform into a Base64-encoded value.
+
 ### replace
 
 The `replace` helper replaces _all_ found strings matching the given regex with the replacement string.
diff --git a/lib/util/template/index.spec.ts b/lib/util/template/index.spec.ts
index 308de56193..0b86af0915 100644
--- a/lib/util/template/index.spec.ts
+++ b/lib/util/template/index.spec.ts
@@ -219,6 +219,30 @@ describe('util/template/index', () => {
     });
   });
 
+  describe('base64 encoding', () => {
+    it('encodes values', () => {
+      const output = template.compile(
+        '{{{encodeBase64 "@fsouza/prettierd"}}}',
+        undefined as never,
+      );
+      expect(output).toBe('QGZzb3V6YS9wcmV0dGllcmQ=');
+    });
+
+    it('handles null values gracefully', () => {
+      const output = template.compile('{{{encodeBase64 packageName}}}', {
+        packageName: null,
+      });
+      expect(output).toBe('');
+    });
+
+    it('handles undefined values gracefully', () => {
+      const output = template.compile('{{{encodeBase64 packageName}}}', {
+        packageName: undefined,
+      });
+      expect(output).toBe('');
+    });
+  });
+
   describe('equals', () => {
     it('equals', () => {
       const output = template.compile(
diff --git a/lib/util/template/index.ts b/lib/util/template/index.ts
index 228dbea040..f9a7c21521 100644
--- a/lib/util/template/index.ts
+++ b/lib/util/template/index.ts
@@ -8,6 +8,10 @@ import { regEx } from '../regex';
 handlebars.registerHelper('encodeURIComponent', encodeURIComponent);
 handlebars.registerHelper('decodeURIComponent', decodeURIComponent);
 
+handlebars.registerHelper('encodeBase64', (str: string) =>
+  Buffer.from(str ?? '').toString('base64'),
+);
+
 handlebars.registerHelper('stringToPrettyJSON', (input: string): string =>
   JSON.stringify(JSON.parse(input), null, 2),
 );
-- 
GitLab