Skip to content

Commit

Permalink
lint: fix warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
justinmk3 committed May 24, 2024
1 parent 5d8fc71 commit b2433de
Show file tree
Hide file tree
Showing 25 changed files with 56 additions and 43 deletions.
3 changes: 3 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ module.exports = {
// This is off because prettier takes care of it
'no-extra-semi': 'off',
'@typescript-eslint/no-empty-function': 'off',
// Disallows returning e.g. Promise<…|never> which signals that an exception may be thrown.
// https://stackoverflow.com/q/64230626/152142
'@typescript-eslint/no-redundant-type-constituents': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-floating-promises': 'error', // Promises must catch errors or be awaited.
'@typescript-eslint/no-var-requires': 'off', // Should be able to remove with the full migration of SDK v3
Expand Down
4 changes: 3 additions & 1 deletion packages/amazonq/src/extensionShared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ export async function activateShared(context: vscode.ExtensionContext, isWeb: bo
() =>
vscode.window
.showInformationMessage(
`The Amazon Q extension is incompatible with AWS Toolkit ${toolkitVersion} and older. Your AWS Toolkit was updated to version 3.0 or later.`,
`The Amazon Q extension is incompatible with AWS Toolkit ${
toolkitVersion as any
} and older. Your AWS Toolkit was updated to version 3.0 or later.`,
'Reload Now'
)
.then(async resp => {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/auth/credentials/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export async function throwOnInvalidCredentials(profileName: SectionName, data:

const credentialsDataErrors = getCredentialsErrors(data)
if (credentialsDataErrors !== undefined) {
throw new ToolkitError(`Errors in credentials data: ${credentialsDataErrors}`, {
throw new ToolkitError(`Errors in credentials data: ${String(credentialsDataErrors)}`, {
code: 'InvalidCredentialsData',
details: credentialsDataErrors,
})
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/awsexplorer/awsExplorer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export class AwsExplorer implements vscode.TreeDataProvider<AWSTreeNodeBase>, Re
}
} catch (err) {
const error = err as Error
this.logger.error(`Error getting children for node ${element?.label ?? 'Root Node'}: %s`, error)
this.logger.error(`Error getting children for node %O: %s`, element?.label ?? 'Root Node', error)

childNodes.splice(
0,
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/codewhisperer/client/codewhisperer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ export type ListCodeScanFindingsRequest = Readonly<
export type SupplementalContext = Readonly<
CodeWhispererClient.SupplementalContext | CodeWhispererUserClient.SupplementalContext
>
// eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents
export type ArtifactType = Readonly<CodeWhispererClient.ArtifactType | CodeWhispererUserClient.ArtifactType>
export type ArtifactMap = Readonly<CodeWhispererClient.ArtifactMap | CodeWhispererUserClient.ArtifactMap>
export type ListCodeScanFindingsResponse =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
FolderInfo,
TransformationCandidateProject,
ZipManifest,
TransformByQStatus,
} from '../models/model'
import { convertDateToTimestamp, getStringHash } from '../../shared/utilities/textUtilities'
import {
Expand Down Expand Up @@ -650,7 +651,7 @@ export async function postTransformationJob() {
codeTransformRunTimeLatency: durationInMs,
codeTransformLocalMavenVersion: mavenVersionInfoMessage,
codeTransformLocalJavaVersion: javaVersionInfoMessage,
result: resultStatusMessage === 'Succeeded' ? MetadataResult.Pass : MetadataResult.Fail,
result: resultStatusMessage === TransformByQStatus.Succeeded ? MetadataResult.Pass : MetadataResult.Fail,
reason: resultStatusMessage,
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,12 @@ export class CWInlineCompletionItemProvider implements vscode.InlineCompletionIt
if (matchedCount >= 2 || this.nextToken !== '') {
const result = [item]
for (let j = 0; j < matchedCount - 1; j++) {
result.push({ insertText: `${item.insertText}${j}`, range: item.range })
result.push({
insertText: `${
typeof item.insertText === 'string' ? item.insertText : item.insertText.value
}${j}`,
range: item.range,
})
}
return result
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -633,12 +633,14 @@ export class RecommendationHandler {
}

async onCursorChange(e: vscode.TextEditorSelectionChangeEvent) {
// e.kind will be 1 for keyboard cursor change events
// we do not want to reset the states for keyboard events because they can be typeahead
if (e.kind !== 1 && vscode.window.activeTextEditor === e.textEditor) {
if (
e.kind !== vscode.TextEditorSelectionChangeKind.Keyboard &&
vscode.window.activeTextEditor === e.textEditor
) {
application()._clearCodeWhispererUIListener.fire()
// when cursor change due to mouse movement we need to reset the active item index for inline
if (e.kind === 2) {
if (e.kind === vscode.TextEditorSelectionChangeKind.Mouse) {
this.inlineCompletionProvider?.clearActiveItemIndex()
}
}
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/dev/activation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ export type DevFunction =
| 'openTerminal'
| 'deleteDevEnv'
| 'editStorage'
| 'editStorage'
| 'showEnvVars'
| 'deleteSsoConnections'
| 'expireSsoConnections'
Expand Down
8 changes: 1 addition & 7 deletions packages/core/src/dev/codecatalyst.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,7 @@ async function promptVsix(
): Promise<vscode.Uri | undefined> {
const folders = (vscode.workspace.workspaceFolders ?? []).map(f => f.uri).concat(vscode.Uri.file(ctx.extensionPath))

enum ExtensionMode {
Production = 1,
Development = 2,
Test = 3,
}

const isDevelopmentWindow = ctx.extensionMode === ExtensionMode.Development
const isDevelopmentWindow = ctx.extensionMode === vscode.ExtensionMode.Development
const extPath = isDevelopmentWindow ? ctx.extensionPath : folders[0].fsPath

const packageNew = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ export default defineComponent({
}
this.containerBuild = config.sam?.containerBuild ?? false
this.skipNewImageCheck = config.sam?.skipNewImageCheck ?? false
this.msg = `Loaded config ${config}`
this.msg = `Loaded config: ${config.name}`
this.company = company
},
loadPayload() {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/lambda/vue/remoteInvoke/invokeLambda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export class RemoteInvokeWebview extends VueWebview {
this.channel.appendLine(logs)
this.channel.appendLine('')
this.channel.appendLine('Payload:')
this.channel.appendLine(payload.toString())
this.channel.appendLine(String(payload))
this.channel.appendLine('')
} catch (e) {
const error = e as Error
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/shared/cloudformation/cloudformation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,9 @@ export async function tryLoad(
// https://github.com/aws-cloudformation/aws-cfn-lint-visual-studio-code/blob/629de0bac4f36cfc6534e409a6f6766a2240992f/client/src/yaml-support/yaml-schema.ts#L39-L51
if (rv.template?.AWSTemplateFormatVersion || rv.template?.Resources) {
rv.kind =
rv.template.Transform && rv.template.Transform.toString().startsWith('AWS::Serverless') ? 'sam' : 'cfn'
typeof rv.template.Transform === 'string' && rv.template.Transform.startsWith('AWS::Serverless')
? 'sam'
: 'cfn'

return rv
}
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/shared/extensions/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,8 +341,8 @@ export class GitExtension {

if (version === undefined || version.compare(minGitFilterVersion) === -1) {
throw new Error(
`Git version is too low or could not be determined (min=${minGitFilterVersion}): ${
version ?? 'unknown'
`Git version is too low or could not be determined (min=${minGitFilterVersion.version}): ${
version?.version ?? 'unknown'
}`
)
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/shared/fs/watchedFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ export abstract class WatchedFiles<T> implements vscode.Disposable {
}

private outputPatterns(): string {
const watch = this.globs.map(cur => cur.toString())
const watch = this.globs.map(cur => (typeof cur === 'string' ? cur.toString() : cur.pattern))
if (this.watchingUntitledFiles) {
watch.push('Untitled Files')
}
Expand Down
9 changes: 6 additions & 3 deletions packages/core/src/shared/icons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { getLogger } from './logger/logger'
// https://code.visualstudio.com/api/references/icons-in-labels#animation

type ContributedIcon = keyof typeof packageJson.contributes.icons
type IconPath = { light: Uri; dark: Uri } | Icon
type IconPath = { light: Uri; dark: Uri; toString: () => string } | Icon
type IconId = `vscode-${string}` | ContributedIcon

/**
Expand Down Expand Up @@ -117,13 +117,16 @@ function resolveIconId(
return new Icon(namespace === 'vscode' ? name : id, source)
}

function resolvePathsSync(rootDir: string, target: string): { light: Uri; dark: Uri } | undefined {
function resolvePathsSync(
rootDir: string,
target: string
): { light: Uri; dark: Uri; toString: () => string } | undefined {
const darkPath = path.join(rootDir, 'dark', `${target}.svg`)
const lightPath = path.join(rootDir, 'light', `${target}.svg`)

try {
if (!isWeb() && fs.existsSync(darkPath) && fs.existsSync(lightPath)) {
return { dark: Uri.file(darkPath), light: Uri.file(lightPath) }
return { dark: Uri.file(darkPath), light: Uri.file(lightPath), toString: () => '[IconPath]' }
}
} catch (error) {
getLogger().warn(`icons: path resolution failed for "${target}": %s`, error)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,7 @@ export class HttpResourceFetcher implements ResourceFetcher {
promise.cancel(new CancellationError(event.agent).message)
})

promise.finally(() => cancelListener?.dispose())

return promise
return promise.finally(() => cancelListener?.dispose())
}

private buildRequestHeaders(requestHeaders?: RequestHeaders): Headers {
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/shared/sam/cli/samCliLocalInvoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/

import * as child_process from 'child_process'
import * as proc from 'child_process'
import { pushIf } from '../../utilities/collectionUtils'
import * as nls from 'vscode-nls'
import { fileExists } from '../../filesystemUtilities'
Expand All @@ -30,7 +30,7 @@ export const waitForDebuggerMessages = {
export interface SamLocalInvokeCommandArgs {
command: string
args: string[]
options?: child_process.SpawnOptions
options?: proc.SpawnOptions
/** Wait until strings specified in `debuggerAttachCues` appear in the process output. */
waitForCues: boolean
timeout?: Timeout
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/shared/sam/debugger/csharpSamDebug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ export async function makeDotnetDebugConfiguration(
codeUri: string
): Promise<DotNetDebugConfiguration> {
if (config.noDebug) {
throw Error(`SAM debug: invalid config ${config}`)
throw Error(`SAM debug: invalid config: ${config.name}`)
}
const pipeArgs = ['-c', `docker exec -i $(docker ps -q -f publish=${config.debugPort}) \${debuggerCommand}`]
config.debuggerPath = pathutil.normalize(getDebuggerPath(codeUri))
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/shared/typescriptLambdaHandlerSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,7 @@ export class TypescriptLambdaHandlerSearch implements LambdaHandlerSearch {
private static isNodeExported(node: ts.Node): boolean {
const flags: ts.ModifierFlags = ts.getCombinedModifierFlags(node as ts.Declaration)

// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
return (flags & ts.ModifierFlags.Export) === ts.ModifierFlags.Export
}

Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/shared/utilities/childProcess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/

import * as child_process from 'child_process'
import * as proc from 'child_process'
import * as crossSpawn from 'cross-spawn'
import * as logger from '../logger'
import { Timeout, CancellationError, waitUntil } from './timeoutUtils'
Expand Down Expand Up @@ -35,7 +35,7 @@ export interface ChildProcessOptions {
/** A `Timeout` token. The running process will be terminated on expiration or cancellation. */
timeout?: Timeout
/** Options sent to the `spawn` command. This is merged in with the base options if they exist. */
spawnOptions?: child_process.SpawnOptions
spawnOptions?: proc.SpawnOptions
/** Callback for intercepting text from the stdout stream. */
onStdout?: (text: string, context: RunParameterContext) => void
/** Callback for intercepting text from the stderr stream. */
Expand Down Expand Up @@ -67,7 +67,7 @@ export const eof = Symbol('EOF')
*/
export class ChildProcess {
static #runningProcesses: Map<number, ChildProcess> = new Map()
#childProcess: child_process.ChildProcess | undefined
#childProcess: proc.ChildProcess | undefined
#processErrors: Error[] = []
#processResult: ChildProcessResult | undefined
#log: logger.Logger
Expand Down Expand Up @@ -291,7 +291,7 @@ export class ChildProcess {
}

#registerLifecycleListeners(
process: child_process.ChildProcess,
process: proc.ChildProcess,
errorHandler: (error: Error, forceStop?: boolean) => void,
options?: ChildProcessOptions
): void {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/shared/utilities/vsCodeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export function buildMissingExtensionMessage(
feat = `${getIdeProperties().company} Toolkit`
): string {
const minV = semver.coerce(minVersion)
const expectedVersionMsg = isNonNullable(minV) ? ` of version >=${minV}` : ''
const expectedVersionMsg = isNonNullable(minV) ? ` of version >=${minV.version}` : ''

return localize(
'AWS.missingExtension',
Expand Down
10 changes: 7 additions & 3 deletions packages/core/src/ssmDocument/commands/publishDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ import { ssmJson, ssmYaml } from '../../shared/constants'

import * as localizedText from '../../shared/localizedText'
import { getLogger, Logger } from '../../shared/logger'
import { PublishSSMDocumentWizard, PublishSSMDocumentWizardResponse } from '../wizards/publishDocumentWizard'
import {
PublishSSMDocumentAction,
PublishSSMDocumentWizard,
PublishSSMDocumentWizardResponse,
} from '../wizards/publishDocumentWizard'
import { showConfirmationMessage } from '../util/util'
import { telemetry } from '../../shared/telemetry/telemetry'
import { Result, SsmOperation } from '../../shared/telemetry/telemetry'
Expand Down Expand Up @@ -49,9 +53,9 @@ export async function publishSSMDocument(): Promise<void> {

try {
const response = await new PublishSSMDocumentWizard().run()
if (response?.action === 'Create') {
if (response?.action === PublishSSMDocumentAction.QuickCreate) {
await createDocument(response, textDocument)
} else if (response?.action === 'Update') {
} else if (response?.action === PublishSSMDocumentAction.QuickUpdate) {
await updateDocument(response, textDocument)
}
} catch (err) {
Expand Down
4 changes: 1 addition & 3 deletions packages/core/src/test/shared/vscode/runCommand.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ import { Commands, defaultTelemetryThrottleMs, unsetSource } from '../../../shar
import { assertTelemetry, installFakeClock } from '../../testUtil'
import { getTestWindow } from '../../shared/vscode/window'

async function throwMe(
error?: unknown
): Promise<void | never /* eslint-disable @typescript-eslint/no-redundant-type-constituents */> {
async function throwMe(error?: unknown): Promise<void | never> {
if (error) {
throw error
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/test/testUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ export function partialDeepCompare<T>(actual: unknown, expected: T, message?: st
export function assertTelemetry<K extends MetricName>(
name: K,
expected: MetricShapes[K] | MetricShapes[K][]
): void | never // eslint-disable no-redundant-type-constituents
): void | never
export function assertTelemetry<K extends MetricName>(
name: K,
expected: MetricShapes[MetricName] | MetricShapes[MetricName][]
Expand Down

0 comments on commit b2433de

Please sign in to comment.