From e12c042e86968b9495c481d8f8b4bb63a9188fdc Mon Sep 17 00:00:00 2001 From: CrazyMax <1951866+crazy-max@users.noreply.github.com> Date: Thu, 10 Apr 2025 22:27:07 +0200 Subject: [PATCH] util: formatDuration func Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com> --- __tests__/util.test.ts | 30 ++++++++++++++++++++++++++++++ src/util.ts | 16 ++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/__tests__/util.test.ts b/__tests__/util.test.ts index 76d6bed..b582f63 100644 --- a/__tests__/util.test.ts +++ b/__tests__/util.test.ts @@ -469,6 +469,36 @@ describe('isPathRelativeTo', () => { }); }); +describe('formatDuration', () => { + it('formats 0 nanoseconds as "0s"', () => { + expect(Util.formatDuration(0)).toBe('0s'); + }); + it('formats only seconds', () => { + expect(Util.formatDuration(5e9)).toBe('5s'); + expect(Util.formatDuration(59e9)).toBe('59s'); + }); + it('formats minutes and seconds', () => { + expect(Util.formatDuration(65e9)).toBe('1m5s'); + expect(Util.formatDuration(600e9)).toBe('10m'); + }); + it('formats hours, minutes, and seconds', () => { + expect(Util.formatDuration(3661e9)).toBe('1h1m1s'); + expect(Util.formatDuration(7322e9)).toBe('2h2m2s'); + }); + it('formats hours only', () => { + expect(Util.formatDuration(3 * 3600e9)).toBe('3h'); + }); + it('formats hours and minutes', () => { + expect(Util.formatDuration(3900e9)).toBe('1h5m'); + }); + it('formats minutes only', () => { + expect(Util.formatDuration(120e9)).toBe('2m'); + }); + it('rounds down partial seconds', () => { + expect(Util.formatDuration(1799999999)).toBe('1s'); + }); +}); + // 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 0b78575..e082da7 100644 --- a/src/util.ts +++ b/src/util.ts @@ -204,4 +204,20 @@ export class Util { const rcp = path.resolve(childPath); return rcp.startsWith(rpp.endsWith(path.sep) ? rpp : `${rpp}${path.sep}`); } + + public static formatDuration(ns: number): string { + if (ns === 0) return '0s'; + + const totalSeconds = Math.floor(ns / 1e9); + const hours = Math.floor(totalSeconds / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const seconds = totalSeconds % 60; + + const parts: string[] = []; + if (hours) parts.push(`${hours}h`); + if (minutes) parts.push(`${minutes}m`); + if (seconds || parts.length === 0) parts.push(`${seconds}s`); + + return parts.join(''); + } }