/**
 * Copyright (c) 2019 Paul Armstrong
 */ import { BudgetLevel , BudgetResult , BudgetType } from '@build-tracker/types' ; type { Number } const BYTES_IN_KIBIBYTE = 1024 ; const KIB_UNIT_STRING = 'KiB' ; const defaultByteFormatting = ( bytes , units ) : number => { return Math . round ( ( bytes / units ) * 100 ) / 100 ; } ; interface FormattingOptions { units ? : number ; formatter ? : ( bytes : number , units : number ) => number ; unitString ? : string ; } export function formatBytes ( bytes , options = { } ) { const { units = BYTES_IN_KIBIBYTE , unitString = KIB_UNIT_STRING , formatter = defaultByteFormatting } = options ; return `${ formatter ( bytes , units ) . toLocaleString ( ) } ${ unitString }` ; } export function formatSha ( sha ) { return sha . slice ( 0 , 7 ) ; } function formatPercent ( value ) { const val = Math . ceil ( value * 1000 ) / 10 ; return `${ val }%` ; } const levelToString = { [ BudgetLevel . WARN ] : 'Warning' , [ BudgetLevel . ERROR ] : 'Error' , hash : 'Hash' , } ; export const levelToEmoji = { [ BudgetLevel . WARN ] : '⚠️' , [ BudgetLevel . ERROR ] : '🚨' , hash : '#️⃣' , } ; function getPrefix ( artifactName , level , useEmoji = false ) { return `${ ( useEmoji ? levelToEmoji : levelToString ) [ level ] }: *${ artifactName . replace ( /~/g , '\\~' ) }*` ; } export function formatBudgetResult ( budgetResult , artifactName , useEmoji = false ) { const { actual , expected , level , sizeKey , type } = budgetResult ; const actualFormatted = type === BudgetType . PERCENT_DELTA ? formatPercent ( actual ) : formatBytes ( actual ) ; const expectedFormatted = type === BudgetType . PERCENT_DELTA ? formatPercent ( expected ) : formatBytes ( expected ) ; const diffFormatted = type === BudgetType . PERCENT_DELTA ? formatPercent ( actual - expected ) : formatBytes ( actual - expected ) ; const prefix = getPrefix ( artifactName , level , useEmoji ) ; switch ( type ) { case BudgetType . DELTA : return `${ prefix } failed the ${ sizeKey } budget delta limit. Expected to increase no more than ${ expectedFormatted }, but increased by ${ actualFormatted }` ; case BudgetType . PERCENT_DELTA : return `${ prefix } failed the ${ sizeKey } budget percent change limit. Expected to not increase by more than ${ expectedFormatted }, but increased by ${ actualFormatted }` ; case BudgetType . SIZE : return `${ prefix } failed the ${ sizeKey } budget size limit of ${ expectedFormatted } by ${ diffFormatted }` ; } } export function formatUnexpectedHashChange ( artifactName , useEmoji = false ) { const prefix = getPrefix ( artifactName , 'hash' , useEmoji ) ; return `${ prefix } hash changed without any file size change` ; } export function formatDatetime ( date ) { const dateString = date . toLocaleDateString ( 'ja' , { year : 'numeric' , month : '2-digit' , day : '2-digit' , } ) . replace ( /\//g , '-' ) ; const timeString = date . toLocaleTimeString ( ) ; return `${ dateString } ${ timeString }` ; }