diff --git a/docs/usage/templates.md b/docs/usage/templates.md index fb1fc89c5f0146abf8c807f5a9afbb1373581e2f..5d09d741019c312a09413370fe9e3bc3faa1e750 100644 --- a/docs/usage/templates.md +++ b/docs/usage/templates.md @@ -102,6 +102,14 @@ In the example above all matches of the regex `[a-z]+\.github\.com` will be repl Read the [MDN Web Docs, String.prototype.replace()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) to learn more. +### split + +Splits a string into an array of substrings. + +This example splits a package name by `-` and gets the second part: +`{{ lookup (split packageName '-') 1 }}` +An input of `foo-bar-test` therefor would return `bar`. + ### stringToPrettyJSON If you want to print pretty JSON with Handlebars you can use the built-in function `stringToPrettyJSON` like this: diff --git a/lib/util/template/index.spec.ts b/lib/util/template/index.spec.ts index 123040edabed9e781685179c29c708b5486b0586..d587fbf452a3ca4a19dc4ca4e254e3c37f62d9cb 100644 --- a/lib/util/template/index.spec.ts +++ b/lib/util/template/index.spec.ts @@ -390,4 +390,37 @@ describe('util/template/index', () => { expect(output).toBe('notProduction'); }); }); + + describe('split', () => { + it('should return empty array on non string input', () => { + const output = template.compile("test {{ split labels '-' }}", { + labels: 123, + }); + expect(output).toBe('test '); + }); + + it('should return empty array on missing parameter', () => { + const output = template.compile('test {{ split labels }}', { + labels: 'foo-bar', + }); + expect(output).toBe('test '); + }); + + it('should return array on success', () => { + const output = template.compile("{{ split labels '-' }}", { + labels: 'foo-bar', + }); + expect(output).toBe('foo,bar'); + }); + + it('should return array element', () => { + const output = template.compile( + "{{ lookup (split packageName '-') 1 }}", + { + packageName: 'foo-bar-test', + }, + ); + expect(output).toBe('bar'); + }); + }); }); diff --git a/lib/util/template/index.ts b/lib/util/template/index.ts index 6164b1b15acd76f9c5549d92cb2a2aa38a9d7571..6711406a1dd2b2427be7b7b84bd8ab58f873bb59 100644 --- a/lib/util/template/index.ts +++ b/lib/util/template/index.ts @@ -62,6 +62,16 @@ handlebars.registerHelper('includes', (arg1: string[], arg2: string) => { return false; }); +handlebars.registerHelper( + 'split', + (str: unknown, separator: unknown): string[] => { + if (is.string(str) && is.string(separator)) { + return str.split(separator); + } + return []; + }, +); + handlebars.registerHelper({ and(...args) { // Need to remove the 'options', as last parameter