diff --git a/__tests__/util.test.ts b/__tests__/util.test.ts index 745ec98..aa3d941 100644 --- a/__tests__/util.test.ts +++ b/__tests__/util.test.ts @@ -335,6 +335,22 @@ describe('formatFileSize', () => { }); }); +describe('generateRandomString', () => { + it('should generate a random string of default length 10', async () => { + const res = Util.generateRandomString(); + expect(typeof res).toBe('string'); + expect(res.length).toBe(10); + expect(/^[0-9a-f]+$/i.test(res)).toBe(true); + }); + it('should generate a random string of specified length', async () => { + const length = 15; + const res = Util.generateRandomString(length); + expect(typeof res).toBe('string'); + expect(res.length).toBe(15); + expect(/^[0-9a-f]+$/i.test(res)).toBe(true); + }); +}); + // See: https://github.com/actions/toolkit/blob/a1b068ec31a042ff1e10a522d8fdf0b8869d53ca/packages/core/src/core.ts#L89 function getInputName(name: string): string { return `INPUT_${name.replace(/ /g, '_').toUpperCase()}`; diff --git a/src/util.ts b/src/util.ts index 14a7da4..4fe0bd2 100644 --- a/src/util.ts +++ b/src/util.ts @@ -174,4 +174,9 @@ export class Util { const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } + + public static generateRandomString(length = 10) { + const bytes = crypto.randomBytes(Math.ceil(length / 2)); + return bytes.toString('hex').slice(0, length); + } }