Skip to content

Commit

Permalink
refactor: moving existing functions to datetime
Browse files Browse the repository at this point in the history
It now makes sense for some existing functions to be in this new module

Signed-off-by: nkomonen-amazon <[email protected]>
  • Loading branch information
nkomonen-amazon committed Nov 13, 2024
1 parent fbb7b2c commit 3df7502
Show file tree
Hide file tree
Showing 19 changed files with 216 additions and 204 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ import {
import { prepareDocument, searchLogGroup } from './searchLogGroup'
import { telemetry, Result } from '../../../shared/telemetry/telemetry'
import { CancellationError } from '../../../shared/utilities/timeoutUtils'
import { formatLocalized } from '../../../shared/utilities/textUtilities'
import { cwlUriSchema } from '../cloudWatchLogsUtils'
import { formatLocalized } from '../../../shared/datetime'

export async function viewLogStream(node: LogGroupNode, registry: LogDataRegistry): Promise<void> {
await telemetry.cloudwatchlogs_open.run(async (span) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
* SPDX-License-Identifier: Apache-2.0
*/

import { formatDateTimestamp } from '../../../shared/datetime'
import { CloudWatchLogsEvent, CloudWatchLogsGroupInfo } from '../registry/logDataRegistry'
import { formatDateTimestamp } from '../../../shared/utilities/textUtilities'

export const timestampSpaceEquivalent = ' '

Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/awsService/ecs/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import globals from '../../shared/extensionGlobals'
import { ToolkitPromptSettings } from '../../shared/settings'
import { ChildProcess } from '../../shared/utilities/processUtils'
import { showMessageWithCancel, showOutputMessage } from '../../shared/utilities/messages'
import { formatDateTimestamp, removeAnsi } from '../../shared/utilities/textUtilities'
import { removeAnsi } from '../../shared/utilities/textUtilities'
import { CancellationError, Timeout } from '../../shared/utilities/timeoutUtils'
import { Commands } from '../../shared/vscode/commands2'
import { EcsSettings } from './util'
Expand All @@ -22,6 +22,7 @@ import { Container, Service } from './model'
import { Instance } from '../../shared/utilities/typeConstructors'
import { telemetry } from '../../shared/telemetry/telemetry'
import { openRemoteTerminal } from '../../shared/remoteSession'
import { formatDateTimestamp } from '../../shared/datetime'

async function runCommandWizard(
param?: unknown,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ import { IotCertsFolderNode } from './iotCertFolderNode'
import { IotThingNode } from './iotThingNode'
import { IotPolicyCertNode } from './iotPolicyNode'
import { getIcon } from '../../../shared/icons'
import { formatLocalized, truncate } from '../../../shared/utilities/textUtilities'
import { truncate } from '../../../shared/utilities/textUtilities'
import { Settings } from '../../../shared/settings'
import { ClassToInterfaceType } from '../../../shared/utilities/tsUtils'
import { formatLocalized } from '../../../shared/datetime'

const contextBase = 'awsIotCertificateNode'
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { AWSTreeNodeBase } from '../../../shared/treeview/nodes/awsTreeNodeBase'
import { inspect } from 'util'
import { IotPolicyWithVersionsNode } from './iotPolicyNode'
import { localize } from '../../../shared/utilities/vsCodeUtils'
import { formatLocalized } from '../../../shared/utilities/textUtilities'
import { formatLocalized } from '../../../shared/datetime'

/**
* Represents an IoT Policy that may have either a Certificate Node or the
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/awsService/s3/explorer/s3FileNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ import { inspect } from 'util'
import { S3BucketNode } from './s3BucketNode'
import { S3FolderNode } from './s3FolderNode'
import globals from '../../../shared/extensionGlobals'
import { formatLocalized, getRelativeDate } from '../../../shared/utilities/textUtilities'
import { isCloud9 } from '../../../shared/extensionUtilities'
import { getIcon } from '../../../shared/icons'
import { formatLocalized, getRelativeDate } from '../../../shared/datetime'

/**
* Represents an object in an S3 bucket.
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/codecatalyst/wizards/selectResource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ import {
QuickPickPrompter,
} from '../../shared/ui/pickerPrompter'
import { AsyncCollection } from '../../shared/utilities/asyncCollection'
import { getRelativeDate } from '../../shared/utilities/textUtilities'
import { isValidResponse } from '../../shared/wizards/wizard'
import { associateDevEnv, docs } from '../model'
import { getHelpUrl, isDevenvVscode } from '../utils'
import { getLogger } from '../../shared/logger/logger'
import { getRelativeDate } from '../../shared/datetime'

export function createRepoLabel(r: codecatalyst.CodeCatalystRepo): string {
return `${r.org.name} / ${r.project.name} / ${r.name}`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import {
DB,
TransformationType,
} from '../models/model'
import { convertDateToTimestamp } from '../../shared/utilities/textUtilities'
import {
createZipManifest,
downloadAndExtractResultArchive,
Expand Down Expand Up @@ -80,6 +79,7 @@ import { HumanInTheLoopManager } from '../service/transformByQ/humanInTheLoopMan
import { setContext } from '../../shared/vscode/setContext'
import { makeTemporaryToolkitFolder } from '../../shared'
import globals from '../../shared/extensionGlobals'
import { convertDateToTimestamp } from '../../shared/datetime'

function getFeedbackCommentData() {
const jobId = transformByQState.getJobId()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ import { downloadExportResultArchive } from '../../../shared/utilities/download'
import { ExportIntent, TransformationDownloadArtifactType } from '@amzn/codewhisperer-streaming'
import fs from '../../../shared/fs/fs'
import { ChatSessionManager } from '../../../amazonqGumby/chat/storages/chatSession'
import { convertToTimeString, encodeHTML } from '../../../shared/utilities/textUtilities'
import { encodeHTML } from '../../../shared/utilities/textUtilities'
import { convertToTimeString } from '../../../shared/datetime'

export function getSha256(buffer: Buffer) {
const hasher = crypto.createHash('sha256')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
sessionJobHistory,
transformByQState,
} from '../../models/model'
import { convertToTimeString } from '../../../shared/utilities/textUtilities'
import { getLogger } from '../../../shared/logger'
import { getTransformationSteps } from './transformApiHandler'
import {
Expand All @@ -23,6 +22,7 @@ import {
} from '../../../codewhisperer/client/codewhispereruserclient'
import { startInterval } from '../../commands/startTransformByQ'
import { CodeTransformTelemetryState } from '../../../amazonqGumby/telemetry/codeTransformTelemetryState'
import { convertToTimeString } from '../../../shared/datetime'

export class TransformationHubViewProvider implements vscode.WebviewViewProvider {
public static readonly viewType = 'aws.amazonq.transformationHub'
Expand Down
148 changes: 148 additions & 0 deletions packages/core/src/shared/datetime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,156 @@
* SPDX-License-Identifier: Apache-2.0
*/

import { isCloud9 } from './extensionUtilities'

// constants for working with milliseconds
export const oneSecond = 1000
export const oneMinute = oneSecond * 60
export const oneHour = oneMinute * 60
export const oneDay = oneHour * 24

// Given number of milliseconds elapsed (ex. 4,500,000) return hr / min / sec it represents (ex. "1 hr 15 min")
export function convertToTimeString(durationInMs: number) {
const time = new Date(durationInMs)
const hours = time.getUTCHours()
const minutes = time.getUTCMinutes()
const seconds = time.getUTCSeconds()
let timeString = `${seconds} sec`
if (minutes > 0) {
timeString = `${minutes} min ${timeString}`
}
if (hours > 0) {
timeString = `${hours} hr ${timeString}`
}
return timeString
}

// Given Date object, return timestamp it represents (ex. "01/01/23, 12:00 AM")
export function convertDateToTimestamp(date: Date) {
return date.toLocaleDateString('en-US', {
month: '2-digit',
day: '2-digit',
year: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}

/**
* Gets a relative date between the from date and now date (default: current time)
* e.g. "in 1 minute", '1 minute ago'
* works on the scales of seconds, minutes, hours, days, weeks, months, years
* @param from start Date
* @param now end Date (default: current time)
* @returns string representation of relative date
*/
export function getRelativeDate(from: Date, now: Date = new Date()): string {
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto', style: 'long' })

const second = 1000
const minute = second * 60
const hour = minute * 60
const day = hour * 24
const week = day * 7

// Prevent clock skew showing future date - adjust 5 seconds
const fromAdj = new Date(from.valueOf() - 5 * second)

const diff = fromAdj.valueOf() - now.valueOf()
const absDiff = Math.abs(diff)
// seconds
if (absDiff < minute) {
// magnitude is less than a minute
return rtf.format(Math.floor(diff / second), 'second')
}
// minutes
if (absDiff < hour) {
// magnitude is less than an hour
return rtf.format(Math.floor(diff / minute), 'minute')
}
// hours
if (absDiff < day) {
// magnitude is less than a day
return rtf.format(Math.floor(diff / hour), 'hour')
}
// days
if (absDiff < week) {
// magnitude is less than a week
return rtf.format(Math.floor(diff / day), 'day')
}
// weeks
if (
(Math.abs(fromAdj.getUTCMonth() - now.getUTCMonth()) === 0 &&
Math.abs(fromAdj.getUTCFullYear() - now.getUTCFullYear()) === 0) || // same month of same year
(fromAdj.getUTCMonth() - now.getUTCMonth() === 1 && fromAdj.getUTCDate() < now.getUTCDate()) || // different months, but less than a month apart in terms of numeric days
(now.getUTCMonth() - fromAdj.getUTCMonth() === 1 && now.getUTCDate() < fromAdj.getUTCDate()) // same as above but in the opposite direction
) {
return rtf.format(Math.floor(diff / week), 'week')
}
// months
if (
Math.abs(fromAdj.getUTCFullYear() - now.getUTCFullYear()) === 0 || // same year, and all the other conditions above didn't pass
(fromAdj.getUTCFullYear() - now.getUTCFullYear() === 1 && fromAdj.getUTCMonth() < now.getUTCMonth()) || // different years, but less than a year apart in terms of months
(now.getUTCFullYear() - fromAdj.getUTCFullYear() === 1 && now.getUTCMonth() < fromAdj.getUTCMonth()) // same as the above, but in reverse
) {
// add/subtract months to make up for the difference between years
let adjMonths = 0
if (fromAdj.getUTCFullYear() > now.getUTCFullYear()) {
adjMonths = 12
} else if (fromAdj.getUTCFullYear() < now.getUTCFullYear()) {
adjMonths = -12
}
return rtf.format(Math.floor(fromAdj.getUTCMonth() - now.getUTCMonth() + adjMonths), 'month')
}
// years
// if all conditionals above have failed, we're looking in terms of a > 1 year gap
return rtf.format(Math.floor(fromAdj.getUTCFullYear() - now.getUTCFullYear()), 'year')
}

/**
* Format for rendering readable dates.
*
* Same format used in the S3 console, but it's also locale-aware.
* This specifically combines a separate date and time format
* in order to avoid a comma between the date and time.
*
* US: Jan 5, 2020 5:30:20 PM GMT-0700
* GB: 5 Jan 2020 17:30:20 GMT+0100
*/
export function formatLocalized(d: Date = new Date(), cloud9 = isCloud9()): string {
const dateFormat = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
})
const timeFormat = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: cloud9 ? 'short' : 'shortOffset',
})

return `${dateFormat.format(d)} ${timeFormat.format(d)}`
}
/**
* Matches Insights console timestamp, e.g.: 2019-03-04T11:40:08.781-08:00
* TODO: Do we want this this verbose? Log stream just shows HH:mm:ss
*/
export function formatDateTimestamp(forceUTC: boolean, d: Date = new Date()): string {
let offsetString: string
if (!forceUTC) {
// manually adjust offset seconds if looking for a GMT timestamp:
// the date is created in local time, but `getISOString` will always output unadjusted GMT
d = new Date(d.getTime() - d.getTimezoneOffset() * 1000 * 60)
offsetString = '+00:00'
} else {
// positive offset means GMT-n, negative offset means GMT+n
// offset is in minutes
offsetString = `${d.getTimezoneOffset() <= 0 ? '+' : '-'}${(d.getTimezoneOffset() / 60)
.toString()
.padStart(2, '0')}:00`
}
const iso = d.toISOString()
// trim 'Z' (last char of iso string) and add offset string
return `${iso.substring(0, iso.length - 1)}${offsetString}`
}
Loading

0 comments on commit 3df7502

Please sign in to comment.