From c80c7f3d0cfd4118ee30648eebfe75d9fcc3a593 Mon Sep 17 00:00:00 2001
From: markussiebert <mail@markussiebert.com>
Date: Sun, 14 Nov 2021 20:49:05 +0100
Subject: [PATCH] feat: add stringToPrettyJSON handlebars function (#12643)

---
 docs/usage/templates.md                            | 10 ++++++++++
 lib/util/template/__snapshots__/index.spec.ts.snap |  8 ++++++++
 lib/util/template/index.spec.ts                    |  6 ++++++
 lib/util/template/index.ts                         |  4 ++++
 4 files changed, 28 insertions(+)

diff --git a/docs/usage/templates.md b/docs/usage/templates.md
index 6bdf0688c2..470c1d0efd 100644
--- a/docs/usage/templates.md
+++ b/docs/usage/templates.md
@@ -20,3 +20,13 @@ Some are configuration options passed through, while others are generated as par
 ## Other available fields
 
 <!-- Insert runtime fields here -->
+
+## Additional Handlebars helpers
+
+### stringToPrettyJSON
+
+If you want to print pretty JSON with Handlebars you can use the built-in function `stringToPrettyJSON` like this:
+
+`{{{stringToPrettyJSON myvar}}}`
+
+In the example above `myvar` is a variable/field, that contains valid JSON.
diff --git a/lib/util/template/__snapshots__/index.spec.ts.snap b/lib/util/template/__snapshots__/index.spec.ts.snap
index e9fc704894..d900a0a751 100644
--- a/lib/util/template/__snapshots__/index.spec.ts.snap
+++ b/lib/util/template/__snapshots__/index.spec.ts.snap
@@ -1,3 +1,11 @@
 // Jest Snapshot v1, https://goo.gl/fbAQLP
 
 exports[`util/template/index filters out disallowed fields 1`] = `"github token = \\"\\""`;
+
+exports[`util/template/index string to pretty JSON  1`] = `
+"{
+  \\"some\\": {
+    \\"fancy\\": \\"json\\"
+  }
+}"
+`;
diff --git a/lib/util/template/index.spec.ts b/lib/util/template/index.spec.ts
index 652d0f5e35..55ab3c7b27 100644
--- a/lib/util/template/index.spec.ts
+++ b/lib/util/template/index.spec.ts
@@ -18,4 +18,10 @@ describe('util/template/index', () => {
     expect(output).toContain('github');
     expect(output).not.toContain('123test');
   });
+  it('string to pretty JSON ', () => {
+    const userTemplate =
+      '{{{ stringToPrettyJSON \'{"some":{"fancy":"json"}}\'}}}';
+    const output = template.compile(userTemplate, undefined);
+    expect(output).toMatchSnapshot();
+  });
 });
diff --git a/lib/util/template/index.ts b/lib/util/template/index.ts
index d5415734a1..4a4ad1ee33 100644
--- a/lib/util/template/index.ts
+++ b/lib/util/template/index.ts
@@ -6,6 +6,10 @@ import { clone } from '../clone';
 
 handlebars.registerHelper('encodeURIComponent', encodeURIComponent);
 
+handlebars.registerHelper('stringToPrettyJSON', (input: string): string =>
+  JSON.stringify(JSON.parse(input), null, 2)
+);
+
 // istanbul ignore next
 handlebars.registerHelper(
   'replace',
-- 
GitLab