[ts][lint] Improve typecheck and linting #5 Include the `stylistic.configs.recommended` preset configuration and refactor code to fix the new lint warnings. Bug: 497015838 Change-Id: Idc09e642e51ad345e09ec91733fa8a9e58bd384e Reviewed-on: https://fuchsia-review.googlesource.com/c/vscode-plugins/+/1559521 Kokoro: Kokoro <noreply+kokoro@google.com> Reviewed-by: Jacob Rutherford <jruthe@google.com>
diff --git a/.ci/ci-tsc.mjs b/.ci/ci-tsc.mjs index 2a4805f..1d8aad9 100644 --- a/.ci/ci-tsc.mjs +++ b/.ci/ci-tsc.mjs
@@ -25,7 +25,7 @@ let stdout; let stderr; try { - ( { stdout, stderr } = await execFile('npx', ['tsc', '--pretty', 'false']) ); // pretty=false should be the default but better safe than sorry + ({ stdout, stderr } = await execFile('npx', ['tsc', '--pretty', 'false'])); // pretty=false should be the default but better safe than sorry } catch (ex) { if (ex.errno !== undefined) { // this was something like a failure to run the command at all, just bail @@ -34,7 +34,7 @@ process.exit(1); } console.error(`tsc returned code ${ex.code} with error\n${ex}`); - ( { code, stdout, stderr } = ex ); + ({ code, stdout, stderr } = ex); } // results are on stdout, so stderr is purely info, so just print it so it gets @@ -52,8 +52,8 @@ } // process the results -let infos = lines. - map((raw) => { +let infos = lines + .map((raw) => { // some/file.ts(line,col): kind code: message let match = raw.match(/^([^(]+)\((\d+),(\d+)\): (\w+) (\w+): (.+)$/); if (!match) { @@ -62,16 +62,16 @@ } let [, path, line, column, kind, code, message] = match; return { path, line, column, kind, code, message }; - }). - filter((info) => !!info); // filter out the invalid outputs + }) + .filter(info => !!info); // filter out the invalid outputs // write the results -const numErrs = infos.filter((info) => info.kind === 'error').length; +const numErrs = infos.filter(info => info.kind === 'error').length; const numOther = infos.length - numErrs; await fs.writeFile(outXML, `<testsuites> <testsuite name="tsc" tests="1" errors="${numErrs}" failures="${numOther}"> <testcase name="tsc" tests="1" errors="${numErrs}" failures="${numOther}"> -${infos.map((info) => formatMessage(info)).join('\n')} +${infos.map(info => formatMessage(info)).join('\n')} </testcase> </testsuite> </testsuites>`);
diff --git a/.ci/eslint-formatter.js b/.ci/eslint-formatter.js index dc26dc2..860d231 100644 --- a/.ci/eslint-formatter.js +++ b/.ci/eslint-formatter.js
@@ -21,7 +21,7 @@ * @param {string} file - The file name. * @returns {string} The XML representation of the message. */ -function formatMessage({ruleId, severity, message, line, column}, file) { +function formatMessage({ ruleId, severity, message, line, column }, file) { const tag = severity >= 2 ? 'error' : 'failure'; const type = severity >= 2 ? 'Error' : 'Warning'; return ` <${tag} message="${message.replace(/"/g, '"')}" type="lint"> @@ -36,22 +36,22 @@ // (x.y.ClassName), and therefore would only ever display `ts`, which is not // helpful. otoh, testcase names are displayed in full -module.exports = function(results) { +module.exports = function (results) { const suites = results.map((file) => { const fileName = path.relative(rootDir, file.filePath); - let cases = file.messages.map((inst) => formatMessage(inst, fileName)); + let cases = file.messages.map(inst => formatMessage(inst, fileName)); return ` <testcase name="${fileName}" classname="eslint"> ${cases.join('\n')} </testcase>`; }); const numErrs = results.reduce( - (total, file) => total + file.messages.filter((msg) => msg.severity >= 2).length, - 0 + (total, file) => total + file.messages.filter(msg => msg.severity >= 2).length, + 0, ); const numOther = results.reduce( - (total, file) => total + file.messages.filter((msg) => msg.severity === 1).length, - 0 + (total, file) => total + file.messages.filter(msg => msg.severity === 1).length, + 0, ); return ` <testsuites>
diff --git a/build-helpers.mjs b/build-helpers.mjs index 8f81b9f..e47684c 100644 --- a/build-helpers.mjs +++ b/build-helpers.mjs
@@ -56,7 +56,7 @@ watchFiles: [srcFile], }; }); - } + }, }; /// locates and bundles all test files @@ -92,10 +92,10 @@ * (e.g., 'syntax/cpp'). */ export async function allSyntax() { - return (await fs.readdir('syntax')). - filter((file) => path.extname(file) === '.ts'). - map((file) => path.basename(file).slice(0, -3)). - map((name) => `syntax/${name}`); + return (await fs.readdir('syntax')) + .filter(file => path.extname(file) === '.ts') + .map(file => path.basename(file).slice(0, -3)) + .map(name => `syntax/${name}`); } /** @@ -109,8 +109,8 @@ */ export function formatMachineOutput({ errors, warnings }, name) { return [ - ...(errors ?? []).map((err) => formatMessageForMachine(err, 'error', name)), - ...(warnings ?? []).map((warning) => formatMessageForMachine(warning, 'warning', name)), + ...(errors ?? []).map(err => formatMessageForMachine(err, 'error', name)), + ...(warnings ?? []).map(warning => formatMessageForMachine(warning, 'warning', name)), ].join('\n'); } @@ -149,11 +149,14 @@ // on the incremental API. if (error) { const out = formatMachineOutput(error, name); - if (out) { console.error(out); } - } - else { + if (out) { + console.error(out); + } + } else { const out = formatMachineOutput(result, name); - if (out) { console.log(out); } + if (out) { + console.log(out); + } } }, }; @@ -180,11 +183,11 @@ </${tag}> `; }; - let cases = results. - map(([name, { errors, warnings }]) => { + let cases = results + .map(([name, { errors, warnings }]) => { return ` <testcase name="${name}" status="run" result="completed"> - ${errors.map((msg) => formatMessage('error', msg))} - ${warnings.map((msg) => formatMessage('warning', msg))} + ${errors.map(msg => formatMessage('error', msg))} + ${warnings.map(msg => formatMessage('warning', msg))} </testcase>`; });
diff --git a/build.mjs b/build.mjs index 28163cb..2e242b4 100644 --- a/build.mjs +++ b/build.mjs
@@ -7,7 +7,7 @@ import { syntaxPlugin, testsPlugin, - allSyntax, formatMachineOutput, resultsToXML + allSyntax, formatMachineOutput, resultsToXML, } from './build-helpers.mjs'; /// determines if we generate sourcemaps & such @@ -36,7 +36,7 @@ sourcemap: IS_DEV ? 'linked' : '', minify: !IS_DEV, logLevel, -}).catch((res) => res); +}).catch(res => res); const resCfg = esbuild.build({ entryPoints: syntaxFiles, @@ -45,7 +45,7 @@ outbase: '.', outdir: 'dist', logLevel, -}).catch((res) => res); +}).catch(res => res); const testCfg = esbuild.build({ bundle: true, @@ -61,7 +61,7 @@ sourcemap: true, plugins: [testsPlugin('./src/**/*.test.ts')], logLevel, -}).catch((res) => res); +}).catch(res => res); // awaiting will print the results, but we want the results as objects (mapped // to their names) in case we need to write test xml for CI @@ -82,10 +82,15 @@ if (IS_MACHINE) { for (const [name, res] of results) { const out = formatMachineOutput(res, name); - if (!out) {continue;} + if (!out) { + continue; + } - if (res instanceof Error) { console.error(out); } - else { console.log(out); } + if (res instanceof Error) { + console.error(out); + } else { + console.log(out); + } } }
diff --git a/eslint.config.mjs b/eslint.config.mjs index 8dec09e..f656c35 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs
@@ -29,10 +29,15 @@ }, // Shared JS and TS rules + stylistic.configs.customize({ + indent: 2, + quotes: 'single', + semi: true, + braceStyle: '1tbs', + }), { plugins: { '@jsdoc': jsdoc, - '@stylistic': stylistic, }, rules: { // Best Practices @@ -45,14 +50,12 @@ '@jsdoc/require-description': 'error', // Stylistic - '@stylistic/indent': ['error', 2], '@stylistic/max-len': ['error', { code: 100, ignoreComments: true, ignoreStrings: true, }], - '@stylistic/quotes': ['error', 'single'], - '@stylistic/semi': ['error', 'always'], + '@stylistic/operator-linebreak': ['error', 'after'], }, },
diff --git a/src/analytics/environment_status.ts b/src/analytics/environment_status.ts index 12396cd..3c341bb 100644 --- a/src/analytics/environment_status.ts +++ b/src/analytics/environment_status.ts
@@ -21,10 +21,9 @@ 'BUILD_ID', 'TEAMCITY_VERSION', 'TRAVIS', - 'TEST_ONLY_ENV_END' + 'TEST_ONLY_ENV_END', ]; - /** * See below: * @returns whether analytics is set to be disabled by envrionment variables @@ -46,5 +45,4 @@ return false; } - export const TEST_ONLY = { botEnvrionments: BOT_ENVIRONMENTS };
diff --git a/src/analytics/ga4.ts b/src/analytics/ga4.ts index 96ca267..a79cbab 100644 --- a/src/analytics/ga4.ts +++ b/src/analytics/ga4.ts
@@ -11,7 +11,6 @@ import * as https from 'https'; import * as logger from '../logger'; - const QUERY_STRING = '?measurement_id=G-HHSGJ8EXW0&api_secret=Am2AYuPcTnK1KtJJloeLRg'; export interface Measurement { @@ -36,10 +35,8 @@ export type UserProperties = Record<string, UserProperty<string | number | boolean> | undefined>; - export type Item = Record<string, string | number | boolean>; - /** * Send a measurement to GA4 endpoint * @param measurement the Measurement object to send @@ -127,7 +124,6 @@ return Date.now() * 1000; } - /** * Create an Event with name and params. * @param name Event name @@ -138,7 +134,7 @@ params?: Record<string, string | number | boolean | undefined>): Event { const event: Event = { name: name, - timestamp_micros: getTimestampMicros() + timestamp_micros: getTimestampMicros(), }; if (params !== undefined) { event.params = params; @@ -160,7 +156,7 @@ client_id: client_id, events: events, timestamp_micros: getTimestampMicros(), - non_personalized_ads: true + non_personalized_ads: true, }; if (user_properties !== undefined) { measurement.user_properties = user_properties;
diff --git a/src/analytics/ga4_events.ts b/src/analytics/ga4_events.ts index 67b6fd6..efc55df 100644 --- a/src/analytics/ga4_events.ts +++ b/src/analytics/ga4_events.ts
@@ -8,7 +8,6 @@ import { createEvent, type Event } from './ga4'; - /** * Create a `command_execution` event. * @param command - the command being executed
diff --git a/src/analytics/init.ts b/src/analytics/init.ts index c022607..35e5670 100644 --- a/src/analytics/init.ts +++ b/src/analytics/init.ts
@@ -66,7 +66,7 @@ category: 'fuchsia-authors.vscode-fuchsia#fuchsia.welcome', step: `fuchsia-authors.vscode-fuchsia#fuchsia.analytics.${messageId}`, }, - false // force: false + false, // force: false ); } @@ -121,8 +121,8 @@ * Analytics initialization process specific to internal users. */ async init(): Promise<void> { - if (await PersistentStatus.internal.isNewUser() - || await PersistentStatus.internal.isExistingUnmigratedOptedInUser()) { + if (await PersistentStatus.internal.isNewUser() || + await PersistentStatus.internal.isExistingUnmigratedOptedInUser()) { if (vscode.env.isTelemetryEnabled) { await showMessage('internal_on'); } else {
diff --git a/src/analytics/lib.ts b/src/analytics/lib.ts index 3753ae1..f004cfd 100644 --- a/src/analytics/lib.ts +++ b/src/analytics/lib.ts
@@ -11,7 +11,6 @@ import { AnalyticsInfo } from './info'; import { AnalyticsState } from './state'; - interface FuchsiaUserProperties { [key: string]: string | number | boolean | undefined; os?: string; @@ -38,7 +37,7 @@ * @param event the Event to send */ export async function addEvent(event: Event): Promise<void> { - if (AnalyticsState.optInLevel === 0) { + if (AnalyticsState.optInLevel === 0 || !AnalyticsInfo.uuid) { return; } @@ -48,12 +47,10 @@ arch: AnalyticsInfo.arch, version: AnalyticsInfo.extensionVersion, internal: AnalyticsInfo.isInternalUser, - metrics_level: AnalyticsState.optInLevel + metrics_level: AnalyticsState.optInLevel, }); - const measurement: Measurement = - createMeasurement(AnalyticsInfo.uuid!, [event], userProperties); - + const measurement: Measurement = createMeasurement(AnalyticsInfo.uuid, [event], userProperties); await send(measurement, AnalyticsState.debugLevel); }
diff --git a/src/analytics/metric_properties.ts b/src/analytics/metric_properties.ts index 427aa04..1516670 100644 --- a/src/analytics/metric_properties.ts +++ b/src/analytics/metric_properties.ts
@@ -7,7 +7,6 @@ import * as path from 'path'; import * as process from 'process'; - // Functions to read/write metric properties (e.g. UUID, opt-in/out status), which are stored in // ~/.fuchsia/metrics/<property-name> @@ -46,7 +45,7 @@ export async function set(name: string, value: string): Promise<void> { try { await fs.mkdir(getMetricDirectory(), { recursive: true, mode: 0o700 }); - await fs.writeFile(getMetricPropertyPath(name), value + '\n', { 'mode': 0o600 }); + await fs.writeFile(getMetricPropertyPath(name), value + '\n', { mode: 0o600 }); } catch (err) { if (err instanceof Error) { console.log(`Warning: unable to set analytics property ${name}`);
diff --git a/src/analytics/persistent_status.ts b/src/analytics/persistent_status.ts index f2f80b8..4636612 100644 --- a/src/analytics/persistent_status.ts +++ b/src/analytics/persistent_status.ts
@@ -86,22 +86,22 @@ * Returns true if the user is new */ async isNewUser(): Promise<boolean> { - return (! await MetricProperties.exists(ENABLED_PROPERTY)) && - (! await MetricProperties.exists(INTERNAL_PROPERTY)); + return (!await MetricProperties.exists(ENABLED_PROPERTY)) && + (!await MetricProperties.exists(INTERNAL_PROPERTY)); }, /** * Returns true if the user has enabled external analytics but haven't opt-in/out for internal analytics */ async isExistingUnmigratedOptedInUser(): Promise<boolean> { - return (! await MetricProperties.exists(INTERNAL_PROPERTY)) && await external.isEnabled(); + return (!await MetricProperties.exists(INTERNAL_PROPERTY)) && await external.isEnabled(); }, /** * Returns true if the user has disabled external analytics but haven't opt-in/out for internal analytics */ async isExistingUnmigratedOptedOutUser(): Promise<boolean> { - return (! await MetricProperties.exists(INTERNAL_PROPERTY)) && (! await external.isEnabled()); + return (!await MetricProperties.exists(INTERNAL_PROPERTY)) && (!await external.isEnabled()); }, /**
diff --git a/src/analytics/setup.ts b/src/analytics/setup.ts index 51165d6..20dbc4a 100644 --- a/src/analytics/setup.ts +++ b/src/analytics/setup.ts
@@ -23,14 +23,13 @@ await init(context); } - /** * Hook up event triggers for sending analytics. */ export function setUpAnalyticsEvents(context: vscode.ExtensionContext) { - context.subscriptions.push(vscodeEvents.onWillExecuteCommand(event => { + context.subscriptions.push(vscodeEvents.onWillExecuteCommand((event) => { void /* in bg */ addEvent( - ga4Events.createCommandExecutionEvent(event.command) + ga4Events.createCommandExecutionEvent(event.command), ); })); }
diff --git a/src/analytics/state.ts b/src/analytics/state.ts index bd14cac..8ffe794 100644 --- a/src/analytics/state.ts +++ b/src/analytics/state.ts
@@ -9,23 +9,21 @@ import * as PersistentStatus from './persistent_status'; import { AnalyticsInfo } from './info'; - /* eslint-disable @typescript-eslint/naming-convention */ /** * Specifies whether/how to send analytics when the extension is running * in development mode or test mode. */ enum AnalyticsModeInDevOrTest { - NO_SEND, // this should be the default behavior + NO_SEND, // this should be the default behavior // The following two modes are for development/debugging of the analytics library itself - DEBUG, // send analytics to debug endpoint (non-logging) for validation - SEND // send analytics directly (recommended to be used with a test GA account/property) + DEBUG, // send analytics to debug endpoint (non-logging) for validation + SEND, // send analytics directly (recommended to be used with a test GA account/property) } /* eslint-enable @typescript-eslint/naming-convention */ const ANALYTICS_MODE_IN_DEV_OR_TEST: AnalyticsModeInDevOrTest = AnalyticsModeInDevOrTest.NO_SEND; - export class AnalyticsState { private static instanceInternal: AnalyticsState;
diff --git a/src/analytics/vscode_events.ts b/src/analytics/vscode_events.ts index 60a0fac..c84c9d7 100644 --- a/src/analytics/vscode_events.ts +++ b/src/analytics/vscode_events.ts
@@ -33,7 +33,7 @@ export function registerCommandWithAnalyticsEvent<T extends unknown[], S>( command: string, callback: (...args: T) => S, - thisArg?: unknown + thisArg?: unknown, ): vscode.Disposable { return vscode.commands.registerCommand( command, @@ -41,6 +41,6 @@ onWillExecuteCommandEmitter.fire({ command }); return callback(...args); }, - thisArg + thisArg, ); }
diff --git a/src/common-config.ts b/src/common-config.ts index 2992ef0..84b462b 100644 --- a/src/common-config.ts +++ b/src/common-config.ts
@@ -2,13 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. - /** * Constants to consistently refer to configuration parameters configured in * package.json. */ - /** * This is the root key for all configuration items for this extension. */
diff --git a/src/components.ts b/src/components.ts index 51342e9..ed5879e 100644 --- a/src/components.ts +++ b/src/components.ts
@@ -9,9 +9,9 @@ import { registerCommandWithAnalyticsEvent } from './analytics/vscode_events'; interface CommandOptions { - args: string[], - requiresURL?: boolean, - refresh?: boolean + args: string[]; + requiresURL?: boolean; + refresh?: boolean; } interface ComponentJson { @@ -81,7 +81,7 @@ const componentExplorer = new ComponentExplorerDataProvider(setup.ffx); vscode.window.registerTreeDataProvider('vscode-fuchsia.componentExplorer', componentExplorer); vscode.commands.registerCommand('fuchsia.refreshComponentExplorer', () => - componentExplorer.refresh() + componentExplorer.refresh(), ); registerCommandWithAnalyticsEvent('fuchsia.component.show', async (moniker?: string) => { @@ -89,7 +89,7 @@ moniker = await vscode.window.showInputBox({ placeHolder: '(e.g. core/ui/scenic)', value: '', - prompt: 'Enter a component moniker' + prompt: 'Enter a component moniker', }); } if (!moniker) { @@ -110,7 +110,7 @@ moniker = await vscode.window.showInputBox({ placeHolder: '(e.g. core/ui/scenic)', value: '', - prompt: 'Enter a component moniker' + prompt: 'Enter a component moniker', }); } if (!moniker) { @@ -123,7 +123,7 @@ url = await vscode.window.showInputBox({ placeHolder: '(e.g. fuchsia-pkg://fuchsia.com/hello-world-cpp#meta/hello-world-cpp.cm)', value: '', - prompt: 'Enter a component URL' + prompt: 'Enter a component URL', }); } if (!url) { @@ -143,7 +143,7 @@ const taskExplorer = new TaskExplorerDataProvider(setup.ffx); vscode.window.registerTreeDataProvider('vscode-fuchsia.taskExplorer', taskExplorer); vscode.commands.registerCommand('fuchsia.refreshTaskExplorer', () => - taskExplorer.refresh() + taskExplorer.refresh(), ); } @@ -232,7 +232,7 @@ private tree: ComponentTree | null = null; constructor( - private readonly ffx: Ffx + private readonly ffx: Ffx, ) { this.ffx.onSetTarget((device: FuchsiaDevice | null) => { if (this.currentDevice?.nodeName !== device?.nodeName) { @@ -244,6 +244,7 @@ private _onDidChangeTreeData: vscode.EventEmitter<ComponentInfo | undefined | null | void> = new vscode.EventEmitter<ComponentInfo | undefined | null | void>(); + readonly onDidChangeTreeData: vscode.Event<ComponentInfo | undefined | null | void> = this._onDidChangeTreeData.event; @@ -283,7 +284,7 @@ constructor( public readonly info: ComponentInfo, - public readonly collapsibleState: vscode.TreeItemCollapsibleState + public readonly collapsibleState: vscode.TreeItemCollapsibleState, ) { super(info.moniker.basename, collapsibleState); this.description = info.url; @@ -306,7 +307,7 @@ const contents = await ffx.runFfx(['component', 'show', moniker]); const document = await vscode.workspace.openTextDocument({ language: 'plaintext', - content: contents + content: contents, }); await vscode.window.showTextDocument(document); } @@ -370,7 +371,7 @@ private tree: TaskTree | null = null; constructor( - private readonly ffx: Ffx + private readonly ffx: Ffx, ) { this.ffx.onSetTarget((device: FuchsiaDevice | null) => { if (this.currentDevice?.nodeName !== device?.nodeName) { @@ -382,6 +383,7 @@ private _onDidChangeTreeData: vscode.EventEmitter<TaskInfo | undefined | null | void> = new vscode.EventEmitter<TaskInfo | undefined | null | void>(); + readonly onDidChangeTreeData: vscode.Event<TaskInfo | undefined | null | void> = this._onDidChangeTreeData.event; @@ -426,7 +428,7 @@ constructor( public readonly info: TaskInfo, - public readonly collapsibleState: vscode.TreeItemCollapsibleState + public readonly collapsibleState: vscode.TreeItemCollapsibleState, ) { super(info.name, collapsibleState); this.description = info.koid.toString();
diff --git a/src/doc_provider.ts b/src/doc_provider.ts index 8a4679f..28f1de3 100644 --- a/src/doc_provider.ts +++ b/src/doc_provider.ts
@@ -21,9 +21,8 @@ */ export class FuchsiaDocumentLinkProvider implements vscode.DocumentLinkProvider { provideDocumentLinks( - document: vscode.TextDocument + document: vscode.TextDocument, ): vscode.ProviderResult<vscode.DocumentLink[]> { - const links: vscode.DocumentLink[] = []; const workspaceFolder = vscode.workspace.workspaceFolders; @@ -41,7 +40,7 @@ for (const fileMatch of matches) { // Remove null items in matcher groups - const match = fileMatch.filter((item) => !!item); + const match = fileMatch.filter(item => !!item); const linkText = match[0]; const filePath = match[1]; @@ -59,7 +58,7 @@ // Link format is file:///path/to/file.ts#Lline,column const link = new vscode.DocumentLink( linkRange, - fileUri.with({ fragment: `L${line},${column}` }) + fileUri.with({ fragment: `L${line},${column}` }), ); link.tooltip = `Go to line ${line}${isNaN(column) ? '' : `:${column}`} in ${path.basename(filePath)}`;
diff --git a/src/extension.ts b/src/extension.ts index ed16bb1..0028774 100644 --- a/src/extension.ts +++ b/src/extension.ts
@@ -28,7 +28,6 @@ * contains common bits needed by the various setup functions below */ export class Setup { - /** * a ToolFinder instance */ @@ -97,7 +96,7 @@ logger.show(); }), - vscode.languages.registerDocumentLinkProvider(fuchsiaOutput, new FuchsiaDocumentLinkProvider() + vscode.languages.registerDocumentLinkProvider(fuchsiaOutput, new FuchsiaDocumentLinkProvider(), ), ); @@ -131,7 +130,7 @@ ctx.subscriptions.push( registerCommandWithAnalyticsEvent('fuchsia.viewLogs', () => { logView.output?.show(); - }) + }), ); } @@ -159,7 +158,7 @@ `error with ${commandName}, see output for details`); } }); - }) + }), ); }; @@ -196,7 +195,7 @@ `error with ${commandName}, see output for details`); } }); - }) + }), ); // set up commands... @@ -231,7 +230,7 @@ if (await vscode.window.showInformationMessage(msg, 'Open folder')) { spawn('xdg-open', [path]); } - }) + }), ); ctx.subscriptions.push( @@ -243,7 +242,7 @@ } setup.ffx.targetDevice = device; - }) + }), ); // ...and the status bar item
diff --git a/src/ffx.ts b/src/ffx.ts index 06e871f..56bd39f 100644 --- a/src/ffx.ts +++ b/src/ffx.ts
@@ -39,17 +39,17 @@ public static fromNodename(nodename: string, connected = false): FuchsiaDevice { // eslint-disable-next-line @typescript-eslint/naming-convention - return new FuchsiaDevice({nodename, 'rcs_state': connected ? 'Y' : 'N'}); + return new FuchsiaDevice({ nodename, rcs_state: connected ? 'Y' : 'N' }); } disconnected(): FuchsiaDevice { // eslint-disable-next-line @typescript-eslint/naming-convention - return new FuchsiaDevice({...this._data, 'rcs_state': 'N'}); + return new FuchsiaDevice({ ...this._data, rcs_state: 'N' }); } } interface SpawnOptions { - cwd?: string + cwd?: string; } export enum FfxEventType { @@ -58,7 +58,7 @@ }; export interface FfxInvocationEvent { - args: string[] + args: string[]; } // TODO: Should we make this value configuable? We already have the configuration key @@ -112,7 +112,7 @@ // initialization time, which may take longer to run ffx commands. This // setter side-effect isn't blocking anyways, so there's no real harm in // letting it run longer. - this.refreshTargets(5000).catch(err => { + this.refreshTargets(5000).catch((err) => { logger.warn(`Unable to refresh target list: ${err}`); }); } @@ -280,7 +280,7 @@ } throw new Error( `Target "${(device ?? this.targetDevice)?.nodeName}" ` + - `failed to come online within ${timeout} seconds.` + `failed to come online within ${timeout} seconds.`, ); } @@ -354,7 +354,7 @@ // Determine the default target in the following precedence: // 1. Preserve the last selected device if ffx is still tracking it. const sameDefaultDevice = () => discoveredDevices.find( - device => device.nodeName === this.defaultTarget?.nodeName + device => device.nodeName === this.defaultTarget?.nodeName, ); // 2. Preserve the last selected device and mark as disconnected. @@ -369,23 +369,23 @@ // 3. Use the ffx default device. const ffxDefaultDevice = () => discoveredDevices.find( - device => device.isFfxDefault + device => device.isFfxDefault, ); // 4. Fallback to the first connected device. const firstConnectedDevice = () => discoveredDevices.find( - device => device.connected + device => device.connected, ); // 5. Fallback to a remaining disconnected device. const anyDiscoveredDevice = () => discoveredDevices[0]; - return sameDefaultDevice() - ?? lostDefaultDevice() - ?? ffxDefaultDevice() - ?? firstConnectedDevice() - ?? anyDiscoveredDevice() - ?? null; + return sameDefaultDevice() ?? + lostDefaultDevice() ?? + ffxDefaultDevice() ?? + firstConnectedDevice() ?? + anyDiscoveredDevice() ?? + null; } /** @@ -410,8 +410,8 @@ */ private buildCommandLine( args: string[], - device?: string | null - ): { cmd: string, args: string[] } | undefined { + device?: string | null, + ): { cmd: string; args: string[] } | undefined { if (!this.path) { return; } @@ -440,7 +440,7 @@ */ public runFfxStreaming( args: string[], - device?: string | null + device?: string | null, ): ChildProcessWithoutNullStreams | undefined { const fullargs = this.buildCommandLine(args, device); if (!fullargs) { @@ -534,15 +534,19 @@ } let output = ''; - cmd?.stdout.on('data', (data) => { output += data; }); + cmd?.stdout.on('data', (data) => { + output += data; + }); let errorOutput = ''; - cmd?.stderr.on('data', (data) => { errorOutput += data; }); + cmd?.stderr.on('data', (data) => { + errorOutput += data; + }); // Keep track of the error state so that the 'close' event handler below won't handle the // error again. let hasError = false; - cmd?.on('error', err => { + cmd?.on('error', (err) => { logger.warn(`exit: ${err}`, 'ffx'); hasError = true; return reject(err);
diff --git a/src/fx.ts b/src/fx.ts index 25d92e1..16d2030 100644 --- a/src/fx.ts +++ b/src/fx.ts
@@ -51,15 +51,19 @@ return new Promise<string>((resolve, reject) => { let output = ''; const cmd = this.runStreaming(args); - cmd?.stdout.on('data', (data) => { output += data; }); + cmd?.stdout.on('data', (data) => { + output += data; + }); let errorOutput = ''; - cmd?.stderr.on('data', (data) => { errorOutput += data; }); + cmd?.stderr.on('data', (data) => { + errorOutput += data; + }); // Keep track of the error state so that the 'close' event handler below won't handle the // error again. let hasError = false; - cmd?.on('error', err => { + cmd?.on('error', (err) => { logger.warn(`exit: ${err}`, 'ffx'); hasError = true; return reject(err); @@ -92,7 +96,7 @@ */ public runJsonStreaming( args: string[], - onData: (data: object) => void + onData: (data: object) => void, ): JsonStreamProcess { return new JsonStreamProcess( this.runStreaming(args), @@ -101,5 +105,4 @@ logger.warn(`Error [fx ${args.join(' ')}]: ${data.toString()}`); }); } - }
diff --git a/src/git_helper.ts b/src/git_helper.ts index e63c5b1..ef5d5ad 100644 --- a/src/git_helper.ts +++ b/src/git_helper.ts
@@ -10,7 +10,7 @@ // The object received when the extension is called from context-menu / right click interface ContextMenuCommandArg { - path: string, + path: string; } /** @@ -44,8 +44,7 @@ function getPathSegment(arg?: ContextMenuCommandArg) { const root = getRoot()?.fsPath; - const fullPath = - arg?.path ?? // Try to use the passed in path, if available + const fullPath = arg?.path ?? // Try to use the passed in path, if available vscode.window.activeTextEditor?.document.fileName ?? // Fallback to the active editor's path root ?? // Fallback to the root of the workspace '';
diff --git a/src/log_view.ts b/src/log_view.ts index bcf056d..974c3a4 100644 --- a/src/log_view.ts +++ b/src/log_view.ts
@@ -14,7 +14,9 @@ public output?: vscode.OutputChannel; constructor(readonly ffx: Ffx) { - ffx.onSetTarget(target => { this.watch(target); }); + ffx.onSetTarget((target) => { + this.watch(target); + }); } watch(device: FuchsiaDevice | null) {
diff --git a/src/logger.ts b/src/logger.ts index 9efbd07..8570c4d 100644 --- a/src/logger.ts +++ b/src/logger.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. - - /** * The logger module encapsulates capturing information for logging activity done in the * extension and proving uniform methods for presenting information and notifications to @@ -19,10 +17,8 @@ * containing more information that is reasonable to show to the user. */ - import * as vscode from 'vscode'; - /** * Internal method for formatting logging category */ @@ -47,7 +43,6 @@ this.output = output; } - /** * Log a message at the vscode.LogLevel.Trace level. * @param message data. @@ -75,7 +70,6 @@ this.output.info(formatCategory(category), message, ...args); } - /** * Log warning message. * @param message data. @@ -85,7 +79,6 @@ this.output.warn(formatCategory(category), message, ...args); } - /** * Log error message. * @param message data. @@ -119,7 +112,6 @@ logger = new Logger(channel); } - /** * Log a message at the vscode.LogLevel.Trace level. * @param message data.
diff --git a/src/process.ts b/src/process.ts index 2adad98..3772360 100644 --- a/src/process.ts +++ b/src/process.ts
@@ -16,14 +16,14 @@ this.process.stdout.on('data', (chunk: unknown) => { const buffer = Buffer.isBuffer(chunk) ? chunk : - Buffer.from(typeof chunk === 'string' ? chunk : String(chunk)); + Buffer.from(typeof chunk === 'string' ? chunk : String(chunk)); this.outputChunks.push(buffer); onData(buffer); }); this.process.stderr.on('data', (chunk: unknown) => { const buffer = Buffer.isBuffer(chunk) ? chunk : - Buffer.from(typeof chunk === 'string' ? chunk : String(chunk)); + Buffer.from(typeof chunk === 'string' ? chunk : String(chunk)); this.outputChunks.push(buffer); onError(buffer); }); @@ -40,7 +40,7 @@ * A future that resolves when the process exits. */ public get exitCode(): Promise<number | null> { - return new Promise(resolve => { + return new Promise((resolve) => { this.process.on('exit', resolve); }); } @@ -79,7 +79,6 @@ this.process = new DataStreamProcess(process, (chunk) => { this.parser.write(chunk); }, onError); - } this.parser.onValue = (value: unknown) => { if (this.parser.stack.length === 0) {
diff --git a/src/target_status_bar_item.ts b/src/target_status_bar_item.ts index 564a2dd..140ba6f 100644 --- a/src/target_status_bar_item.ts +++ b/src/target_status_bar_item.ts
@@ -129,7 +129,7 @@ await this.toolFinder?.updateFfxPath(false); } - this.ffxTools.refreshTargets().then(async targetList => { + this.ffxTools.refreshTargets().then(async (targetList) => { const items = this.buildTargetQuickPickItems(targetList); if (items.length > 0) { const action = await vscode.window.showQuickPick(items); @@ -139,18 +139,19 @@ await vscode.commands.executeCommand(action.command, action.device); } else { const msg = Object.keys(targetList).length > 0 ? - 'No available devices found.' : 'No devices found.'; + 'No available devices found.' : + 'No devices found.'; logger.warn(msg); void vscode.window.showWarningMessage(msg); } }) // If there is a problem getting the list, just log it. The quickpick // will be empty. - .catch(err => { + .catch((err) => { logger.warn(`Could not build target list: ${err}`); void vscode.window.showWarningMessage('Failed to retrieve devices.'); }); - }) + }), ); // Target status-bar item @@ -159,20 +160,20 @@ this.fuchsiaStatusBarItem.command = 'fuchsia.target.attach'; this.fuchsiaStatusBarItem.tooltip = 'Fuchsia target device.'; contextSubscriptions.push(this.fuchsiaStatusBarItem); - this.setBarItemText(/*targetName*/ undefined, /*connected*/ false); + this.setBarItemText(/* targetName */ undefined, /* connected */ false); this.fuchsiaStatusBarItem.show(); // Clear the default target if there is no ffx found. - this.ffxTools.onDidChangeConfiguration(eventType => { + this.ffxTools.onDidChangeConfiguration((eventType) => { switch (eventType) { case FfxEventType.ffxPathReset: - this.setBarItemText(/*targetName*/ undefined, /*connected*/ false); + this.setBarItemText(/* targetName */ undefined, /* connected */ false); break; } }); // When the default target is set, update the item text. - this.ffxTools.onSetTarget(target => { + this.ffxTools.onSetTarget((target) => { this.setBarItemText(target?.nodeName, target?.connected ?? false); }); }
diff --git a/src/test/suite/analytics/metric_properties.test.ts b/src/test/suite/analytics/metric_properties.test.ts index 5e5bd67..8449e7c 100644 --- a/src/test/suite/analytics/metric_properties.test.ts +++ b/src/test/suite/analytics/metric_properties.test.ts
@@ -60,7 +60,6 @@ }); }); - describe('getBoolean() and setBoolean()', function () { it('work as intended', async function () { await MetricProperties.setBoolean('true', true); @@ -124,7 +123,6 @@ await fs.rm(tmpPath, { force: true, recursive: true }); }); - it('do nothing when there are neither old or new directories', async function () { await MetricProperties.migrateMetricDirectory(); assert.strictEqual(await fsExists(oldMetricDirectory), false);
diff --git a/src/test/suite/analytics/persistent_status.test.ts b/src/test/suite/analytics/persistent_status.test.ts index ab817fa..475f46b 100644 --- a/src/test/suite/analytics/persistent_status.test.ts +++ b/src/test/suite/analytics/persistent_status.test.ts
@@ -35,7 +35,6 @@ }); it('works as intended', async function () { - assert.strictEqual(await PersistentStatus.external.isFirstLaunchOfFirstTool(), true); await PersistentStatus.external.enable();
diff --git a/src/test/suite/commands.test.ts b/src/test/suite/commands.test.ts index 667390c..337bcec 100644 --- a/src/test/suite/commands.test.ts +++ b/src/test/suite/commands.test.ts
@@ -9,10 +9,10 @@ import { describe, it, before } from 'mocha'; -describe('commands', function() { +describe('commands', function () { let userCommands: string[]; let registeredCommands: string[]; - before(async function() { + before(async function () { const packageDir = path.join(__dirname, '..'); const packageJSON = JSON.parse(await fs.readFile(path.join(packageDir, 'package.json'), 'utf8')) as { contributes: { @@ -21,12 +21,12 @@ }; // sort to make comparison easier - userCommands = packageJSON.contributes.commands. - map((cmd: {command: string}) => cmd.command). - sort(); - registeredCommands = (await vscode.commands.getCommands(true /* filterInternal */)). - filter((cmd) => cmd.startsWith('fuchsia.')). - sort(); + userCommands = packageJSON.contributes.commands + .map((cmd: { command: string }) => cmd.command) + .sort(); + registeredCommands = (await vscode.commands.getCommands(true /* filterInternal */)) + .filter(cmd => cmd.startsWith('fuchsia.')) + .sort(); }); // two separate equalities to make the errors a bit clearer @@ -38,7 +38,7 @@ } // package.json commands (actual) should contain registered non-internal commands (expected) - const nonInternalRegistered = registeredCommands.filter((cmd) => !cmd.startsWith('fuchsia.internal.')); + const nonInternalRegistered = registeredCommands.filter(cmd => !cmd.startsWith('fuchsia.internal.')); for (const cmd of nonInternalRegistered) { assert.ok(userCommands.includes(cmd), `Unexpected registered command: ${cmd}`); }
diff --git a/src/test/suite/ffx.test.ts b/src/test/suite/ffx.test.ts index e298915..b54c513 100644 --- a/src/test/suite/ffx.test.ts +++ b/src/test/suite/ffx.test.ts
@@ -14,17 +14,17 @@ import { type MockedCommandInvocation, StubbedSpawn, noTimeout, setupMockFfx } from './utils'; -describe('FuchsiaDevice', function() { - describe('#constructor()', function() { +describe('FuchsiaDevice', function () { + describe('#constructor()', function () { it('creates an instance of FuchsiaDevice from the json returned from ffx target list', - function() { + function () { const data = { - 'nodename': 'test-device', - 'rcs_state': 'Y', - 'serial': '<unknown>', - 'target_type': 'workstation.qemu-x64', - 'target_state': 'Product', - 'addresses': ['fe80::3bee:1d4:e205:777e%brqemu', '172.1.1.1'] + nodename: 'test-device', + rcs_state: 'Y', + serial: '<unknown>', + target_type: 'workstation.qemu-x64', + target_state: 'Product', + addresses: ['fe80::3bee:1d4:e205:777e%brqemu', '172.1.1.1'], }; const device = new FuchsiaDevice(data); @@ -42,30 +42,30 @@ }); }); -describe('Ffx', function() { +describe('Ffx', function () { const sandbox = createSandbox(); const TEST_FFX = '/path/to/ffx'; const TEST_CWD = '/path/to/workspace'; let stubbedSpawn: StubbedSpawn; - this.beforeEach(function() { + this.beforeEach(function () { stubbedSpawn = new StubbedSpawn(sandbox); const log = vscode.window.createOutputChannel('tool_finder.test', { log: true }); logger.initLogger(log); }); - this.afterEach(function() { + this.afterEach(function () { sandbox.restore(); }); const SAMPLE_DEVICE = new FuchsiaDevice({ - 'nodename': 'sample-device', - 'rcs_state': 'Y', - 'serial': 'serial-54321', - 'target_type': 'sample-product', - 'target_state': 'Product', - 'addresses': ['fe80::f76b:3c1e:a01c:0851%en12'], - 'is_default': false + nodename: 'sample-device', + rcs_state: 'Y', + serial: 'serial-54321', + target_type: 'sample-product', + target_state: 'Product', + addresses: ['fe80::f76b:3c1e:a01c:0851%en12'], + is_default: false, }); const mockFfx = (...ffxInvocations: MockedCommandInvocation[]) => setupMockFfx( @@ -75,33 +75,33 @@ ffxInvocations, ); - describe('#constructor', function() { - it('creates an instance of ffx', function() { + describe('#constructor', function () { + it('creates an instance of ffx', function () { new Ffx(TEST_CWD, TEST_FFX); }); }); - describe('#rebootTarget', function() { - it('calls ffx target reboot for the default device successfully', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + describe('#rebootTarget', function () { + it('calls ffx target reboot for the default device successfully', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'sample-device', 'target', 'reboot'], - 'output': 'restarted sample-device', + args: ['--target', 'sample-device', 'target', 'reboot'], + output: 'restarted sample-device', }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [], + args: ['--machine', 'json', 'target', 'list'], + output: [], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'sample-device', 'rcs_state': 'N'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'sample-device', rcs_state: 'N' }, ], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'sample-device', 'rcs_state': 'Y'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'sample-device', rcs_state: 'Y' }, ], }, ); @@ -118,8 +118,8 @@ assert.strictEqual(ffx.targetDevice?.connected, true); }); - it('does not call ffx target reboot without a target', async function() { - const {actualInvocations, expectedInvocations} = mockFfx(); + it('does not call ffx target reboot without a target', async function () { + const { actualInvocations, expectedInvocations } = mockFfx(); const ffx = new Ffx(TEST_CWD, TEST_FFX); @@ -128,30 +128,30 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('calls ffx target reboot the specified device', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('calls ffx target reboot the specified device', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'test-device', 'target', 'reboot'], - 'output': 'restarted test-device', + args: ['--target', 'test-device', 'target', 'reboot'], + output: 'restarted test-device', }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'sample-device', 'rcs_state': 'Y'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'sample-device', rcs_state: 'Y' }, ], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'sample-device', 'rcs_state': 'Y'}, - {'nodename': 'test-device', 'rcs_state': 'N'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'sample-device', rcs_state: 'Y' }, + { nodename: 'test-device', rcs_state: 'N' }, ], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'sample-device', 'rcs_state': 'Y'}, - {'nodename': 'test-device', 'rcs_state': 'Y'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'sample-device', rcs_state: 'Y' }, + { nodename: 'test-device', rcs_state: 'Y' }, ], }, ); @@ -159,7 +159,7 @@ const ffx = new Ffx(TEST_CWD, TEST_FFX); ffx.targetDevice = SAMPLE_DEVICE; - const device = new FuchsiaDevice({ 'nodename': 'test-device' }); + const device = new FuchsiaDevice({ nodename: 'test-device' }); const stdout = await ffx.rebootTarget(device); assert.strictEqual(stdout, 'restarted test-device'); assert.deepStrictEqual(actualInvocations, expectedInvocations); @@ -169,12 +169,12 @@ assert.strictEqual(ffx.targetDevice?.connected, true); }); - it('fails when the reboot command fails to issue', async function() { + it('fails when the reboot command fails to issue', async function () { const errorMessage = 'Cannot reboot device'; - const {actualInvocations, expectedInvocations} = mockFfx( + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'sample-device', 'target', 'reboot'], - 'output': new Error(errorMessage), + args: ['--target', 'sample-device', 'target', 'reboot'], + output: new Error(errorMessage), }, ); @@ -188,20 +188,20 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('handles target list errors', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('handles target list errors', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'sample-device', 'target', 'reboot'], - 'output': 'restarted sample-device', + args: ['--target', 'sample-device', 'target', 'reboot'], + output: 'restarted sample-device', }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': new Error('sample error'), + args: ['--machine', 'json', 'target', 'list'], + output: new Error('sample error'), }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'sample-device', 'rcs_state': 'Y'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'sample-device', rcs_state: 'Y' }, ], }, ); @@ -218,20 +218,20 @@ assert.strictEqual(ffx.targetDevice?.connected, true); }); - it('fails when device does not reconnect', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('fails when device does not reconnect', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'sample-device', 'target', 'reboot'], - 'output': 'restarted sample-device', + args: ['--target', 'sample-device', 'target', 'reboot'], + output: 'restarted sample-device', }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [], + args: ['--machine', 'json', 'target', 'list'], + output: [], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'sample-device', 'rcs_state': 'N'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'sample-device', rcs_state: 'N' }, ], }, ); @@ -240,7 +240,7 @@ ffx.targetDevice = SAMPLE_DEVICE; await assert.rejects( - () => ffx.rebootTarget(SAMPLE_DEVICE, .19), + () => ffx.rebootTarget(SAMPLE_DEVICE, 0.19), new Error('Target "sample-device" failed to come online within 0.19 seconds.'), ); assert.deepStrictEqual(actualInvocations, expectedInvocations); @@ -251,18 +251,18 @@ }); }); - describe('#startEmulator', function() { - it('calls ffx emu start with the default emulator name and updates default target', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + describe('#startEmulator', function () { + it('calls ffx emu start with the default emulator name and updates default target', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['emu', 'start', '--name', 'fuchsia-emulator'], - 'output': 'started fuchsia-emulator', + args: ['emu', 'start', '--name', 'fuchsia-emulator'], + output: 'started fuchsia-emulator', }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'sample-device', 'rcs_state': 'Y', 'is_default': true}, - {'nodename': 'fuchsia-emulator', 'rcs_state': 'Y'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'sample-device', rcs_state: 'Y', is_default: true }, + { nodename: 'fuchsia-emulator', rcs_state: 'Y' }, ], }, ); @@ -279,17 +279,17 @@ assert.strictEqual(ffx.targetDevice?.connected, true); }); - it('calls ffx emu start headless with a specified emulator name and updates default target', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('calls ffx emu start headless with a specified emulator name and updates default target', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['emu', 'start', '--name', 'fuchsia-emulator2', '--headless'], - 'output': 'started fuchsia-emulator2', + args: ['emu', 'start', '--name', 'fuchsia-emulator2', '--headless'], + output: 'started fuchsia-emulator2', }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'sample-device', 'rcs_state': 'Y', 'is_default': true}, - {'nodename': 'fuchsia-emulator2', 'rcs_state': 'Y'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'sample-device', rcs_state: 'Y', is_default: true }, + { nodename: 'fuchsia-emulator2', rcs_state: 'Y' }, ], }, ); @@ -306,12 +306,12 @@ assert.strictEqual(ffx.targetDevice?.connected, true); }); - it('handles emu start failures', async function() { + it('handles emu start failures', async function () { const errorMessage = 'Cannot start the emulator'; - const {actualInvocations, expectedInvocations} = mockFfx( + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['emu', 'start', '--name', 'fuchsia-emulator'], - 'output': new Error(errorMessage), + args: ['emu', 'start', '--name', 'fuchsia-emulator'], + output: new Error(errorMessage), }, ); @@ -330,17 +330,17 @@ }); }); - describe('#stopEmulator', function() { - it('calls ffx emu stop for the default emulator name', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + describe('#stopEmulator', function () { + it('calls ffx emu stop for the default emulator name', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['emu', 'stop', 'fuchsia-emulator'], - 'output': 'stopped fuchsia-emulator', + args: ['emu', 'stop', 'fuchsia-emulator'], + output: 'stopped fuchsia-emulator', }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'test-device', 'rcs_state': 'Y'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'test-device', rcs_state: 'Y' }, ], }, ); @@ -357,16 +357,16 @@ assert.strictEqual(ffx.targetDevice?.connected, false); }); - it('calls ffx emu stop with a specified emulator name', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('calls ffx emu stop with a specified emulator name', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['emu', 'stop', 'fuchsia-emulator2'], - 'output': 'stopped fuchsia-emulator2', + args: ['emu', 'stop', 'fuchsia-emulator2'], + output: 'stopped fuchsia-emulator2', }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'default-device', 'rcs_state': 'Y', 'is_default': true}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'default-device', rcs_state: 'Y', is_default: true }, ], }, ); @@ -383,16 +383,16 @@ assert.strictEqual(ffx.targetDevice?.connected, false); }); - it('switches to a new default target if the emulator default is stopped', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('switches to a new default target if the emulator default is stopped', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['emu', 'stop', 'sample-device'], - 'output': 'stopped sample-device', + args: ['emu', 'stop', 'sample-device'], + output: 'stopped sample-device', }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'new-default-device', 'rcs_state': 'Y'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'new-default-device', rcs_state: 'Y' }, ], }, ); @@ -409,17 +409,17 @@ assert.strictEqual(ffx.targetDevice?.connected, true); }); - it('fails and refreshes target status but does not switch default target', async function() { + it('fails and refreshes target status but does not switch default target', async function () { const errorMessage = 'Cannot stop the emulator'; - const {actualInvocations, expectedInvocations} = mockFfx( + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['emu', 'stop', 'fuchsia-emulator'], - 'output': new Error(errorMessage), + args: ['emu', 'stop', 'fuchsia-emulator'], + output: new Error(errorMessage), }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'default-device', 'rcs_state': 'Y', 'is_default': true}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'default-device', rcs_state: 'Y', is_default: true }, ], }, ); @@ -439,17 +439,17 @@ }); }); - describe('#poweroffTarget', function() { - it('calls ffx target off for the default device successfully', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + describe('#poweroffTarget', function () { + it('calls ffx target off for the default device successfully', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'sample-device', 'target', 'off'], - 'output': 'powered off sample-device', + args: ['--target', 'sample-device', 'target', 'off'], + output: 'powered off sample-device', }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'test-device', 'rcs_state': 'Y'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'test-device', rcs_state: 'Y' }, ], }, ); @@ -466,26 +466,26 @@ assert.strictEqual(ffx.targetDevice?.connected, true); }); - it('does not call ffx target off without a target', async function() { + it('does not call ffx target off without a target', async function () { const ffx = new Ffx(TEST_CWD, TEST_FFX); const errorMessage = 'Unable to resolve the default target for ffx command: target off'; - const {actualInvocations, expectedInvocations} = mockFfx(); + const { actualInvocations, expectedInvocations } = mockFfx(); await assert.rejects(() => ffx.poweroffTarget(), new Error(errorMessage)); assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('calls ffx target off the specified device', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('calls ffx target off the specified device', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'test-device', 'target', 'off'], - 'output': 'powered off test-device', + args: ['--target', 'test-device', 'target', 'off'], + output: 'powered off test-device', }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'sample-device', 'rcs_state': 'Y'}, - {'nodename': 'default-device', 'rcs_state': 'Y', 'is_default': true}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'sample-device', rcs_state: 'Y' }, + { nodename: 'default-device', rcs_state: 'Y', is_default: true }, ], }, ); @@ -493,7 +493,7 @@ const ffx = new Ffx(TEST_CWD, TEST_FFX); ffx.targetDevice = SAMPLE_DEVICE; - const device = new FuchsiaDevice({ 'nodename': 'test-device' }); + const device = new FuchsiaDevice({ nodename: 'test-device' }); const stdout = await ffx.poweroffTarget(device); assert.strictEqual(stdout, 'powered off test-device'); assert.deepStrictEqual(actualInvocations, expectedInvocations); @@ -503,12 +503,12 @@ assert.strictEqual(ffx.targetDevice?.connected, true); }); - it('fails when target off command fails to issue', async function() { + it('fails when target off command fails to issue', async function () { const errorMessage = 'Cannot power off the device'; - const {actualInvocations, expectedInvocations} = mockFfx( + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'sample-device', 'target', 'off'], - 'output': new Error(errorMessage), + args: ['--target', 'sample-device', 'target', 'off'], + output: new Error(errorMessage), }, ); @@ -523,35 +523,35 @@ }); }); - describe('#waitForTarget', function() { - it('calls ffx target list repeatedly on the specified device', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + describe('#waitForTarget', function () { + it('calls ffx target list repeatedly on the specified device', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'default-device', 'rcs_state': 'Y'}, - {'nodename': 'test-device', 'rcs_state': 'N'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'default-device', rcs_state: 'Y' }, + { nodename: 'test-device', rcs_state: 'N' }, ], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'default-device', 'rcs_state': 'Y'}, - {'nodename': 'test-device', 'rcs_state': 'N'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'default-device', rcs_state: 'Y' }, + { nodename: 'test-device', rcs_state: 'N' }, ], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'default-device', 'rcs_state': 'Y'}, - {'nodename': 'test-device', 'rcs_state': 'N'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'default-device', rcs_state: 'Y' }, + { nodename: 'test-device', rcs_state: 'N' }, ], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'default-device', 'rcs_state': 'Y'}, - {'nodename': 'test-device', 'rcs_state': 'Y'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'default-device', rcs_state: 'Y' }, + { nodename: 'test-device', rcs_state: 'Y' }, ], }, ); @@ -571,27 +571,27 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('throws when ffx target wait times out', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('throws when ffx target wait times out', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'default-device', 'rcs_state': 'Y'}, - {'nodename': 'test-device', 'rcs_state': 'N'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'default-device', rcs_state: 'Y' }, + { nodename: 'test-device', rcs_state: 'N' }, ], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'default-device', 'rcs_state': 'Y'}, - {'nodename': 'test-device', 'rcs_state': 'N'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'default-device', rcs_state: 'Y' }, + { nodename: 'test-device', rcs_state: 'N' }, ], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'default-device', 'rcs_state': 'Y'}, - {'nodename': 'test-device', 'rcs_state': 'N'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'default-device', rcs_state: 'Y' }, + { nodename: 'test-device', rcs_state: 'N' }, ], }, ); @@ -606,20 +606,19 @@ // Wait for `test-device` to be available. await assert.rejects( - () => ffx.waitForTarget(testDevice, .19), + () => ffx.waitForTarget(testDevice, 0.19), new Error('Target "test-device" failed to come online within 0.19 seconds.'), ); assert.deepStrictEqual(actualInvocations, expectedInvocations); }); }); - - describe('#showTarget', function() { - it('calls ffx target show for the default device successfully', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + describe('#showTarget', function () { + it('calls ffx target show for the default device successfully', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'sample-device', 'target', 'show'], - 'output': 'TARGET_SHOW_SENTINAL', + args: ['--target', 'sample-device', 'target', 'show'], + output: 'TARGET_SHOW_SENTINAL', }, ); @@ -631,12 +630,12 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('calls ffx target show for the default device and fails', async function() { + it('calls ffx target show for the default device and fails', async function () { const errorMessage = 'Cannot show device'; - const {actualInvocations, expectedInvocations} = mockFfx( + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'sample-device', 'target', 'show'], - 'output': new Error(errorMessage), + args: ['--target', 'sample-device', 'target', 'show'], + output: new Error(errorMessage), }, ); @@ -650,8 +649,8 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('does not call ffx target show without a target', async function() { - const {actualInvocations, expectedInvocations} = mockFfx(); + it('does not call ffx target show without a target', async function () { + const { actualInvocations, expectedInvocations } = mockFfx(); const ffx = new Ffx(TEST_CWD, TEST_FFX); const errorMessage = 'Unable to resolve the default target for ffx command: target show'; @@ -659,30 +658,30 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('calls ffx target show for the specified device', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('calls ffx target show for the specified device', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'test-device', 'target', 'show'], - 'output': 'TARGET_SHOW_SENTINAL', + args: ['--target', 'test-device', 'target', 'show'], + output: 'TARGET_SHOW_SENTINAL', }, ); const ffx = new Ffx(TEST_CWD, TEST_FFX); ffx.targetDevice = SAMPLE_DEVICE; - const device = new FuchsiaDevice({ 'nodename': 'test-device' }); + const device = new FuchsiaDevice({ nodename: 'test-device' }); const stdout = await ffx.showTarget(device); assert.strictEqual(stdout, 'TARGET_SHOW_SENTINAL'); assert.deepStrictEqual(actualInvocations, expectedInvocations); }); }); - describe('#ExportSnapshot', function() { - it('calls ffx target snapshot for the default device successfully', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + describe('#ExportSnapshot', function () { + it('calls ffx target snapshot for the default device successfully', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'sample-device', 'target', 'snapshot', '-d', TEST_CWD], - 'output': 'TARGET_SNAPSHOT_SENTINAL', + args: ['--target', 'sample-device', 'target', 'snapshot', '-d', TEST_CWD], + output: 'TARGET_SNAPSHOT_SENTINAL', }, ); @@ -694,12 +693,12 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('calls ffx target snapshot for the default device and fails', async function() { + it('calls ffx target snapshot for the default device and fails', async function () { const errorMessage = 'Cannot snapshot device'; - const {actualInvocations, expectedInvocations} = mockFfx( + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'sample-device', 'target', 'snapshot', '-d', TEST_CWD], - 'output': new Error(errorMessage), + args: ['--target', 'sample-device', 'target', 'snapshot', '-d', TEST_CWD], + output: new Error(errorMessage), }, ); const ffx = new Ffx(TEST_CWD, TEST_FFX); @@ -712,8 +711,8 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('does not call ffx target snapshot without a target', async function() { - const {actualInvocations, expectedInvocations} = mockFfx(); + it('does not call ffx target snapshot without a target', async function () { + const { actualInvocations, expectedInvocations } = mockFfx(); const ffx = new Ffx(TEST_CWD, TEST_FFX); const errorMessage = 'Unable to resolve the default target for ffx command: target snapshot -d /path/to/workspace'; @@ -721,40 +720,40 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('calls ffx target snapshot for the specified device', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('calls ffx target snapshot for the specified device', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { - 'args': ['--target', 'test-device', 'target', 'snapshot', '-d', TEST_CWD], - 'output': 'TARGET_SNAPSHOT_SENTINAL', + args: ['--target', 'test-device', 'target', 'snapshot', '-d', TEST_CWD], + output: 'TARGET_SNAPSHOT_SENTINAL', }, ); const ffx = new Ffx(TEST_CWD, TEST_FFX); ffx.targetDevice = SAMPLE_DEVICE; - const device = new FuchsiaDevice({ 'nodename': 'test-device' }); + const device = new FuchsiaDevice({ nodename: 'test-device' }); const output = await ffx.exportSnapshotToCWD(device); assert.strictEqual(output, TEST_CWD); assert.deepStrictEqual(actualInvocations, expectedInvocations); }); }); - describe('#events', function() { - it('Verify set path events', async function() { - const {actualInvocations, expectedInvocations, singleCommandDuration} = mockFfx( + describe('#events', function () { + it('Verify set path events', async function () { + const { actualInvocations, expectedInvocations, singleCommandDuration } = mockFfx( { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': new Error('should be caught'), + args: ['--machine', 'json', 'target', 'list'], + output: new Error('should be caught'), }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'test-device', 'rcs_state': 'Y'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'test-device', rcs_state: 'Y' }, ], }, ); const ffx = new Ffx(TEST_CWD, TEST_FFX); let lastEvent: FfxEventType | undefined; - ffx.onDidChangeConfiguration(event => { + ffx.onDidChangeConfiguration((event) => { lastEvent = event; }); await singleCommandDuration(); // constructor shouldn't have any command execution side-effects. @@ -780,50 +779,54 @@ }); }); - describe('#onSetTarget', function() { - it('fired events are consistent with ffx targetDevice', async function() { - const {actualInvocations, expectedInvocations, singleCommandDuration} = mockFfx( + describe('#onSetTarget', function () { + it('fired events are consistent with ffx targetDevice', async function () { + const { actualInvocations, expectedInvocations, singleCommandDuration } = mockFfx( { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [], + args: ['--machine', 'json', 'target', 'list'], + output: [], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [{'nodename': 'device1'}], + args: ['--machine', 'json', 'target', 'list'], + output: [{ nodename: 'device1' }], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [ - {'nodename': 'sample-device', 'rcs_state': 'N'}, + args: ['--machine', 'json', 'target', 'list'], + output: [ + { nodename: 'sample-device', rcs_state: 'N' }, ], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [{'nodename': 'device2', 'rcs_state': 'Y'}], + args: ['--machine', 'json', 'target', 'list'], + output: [{ nodename: 'device2', rcs_state: 'Y' }], }, { - 'args': ['--machine', 'json', 'target', 'list'], - 'output': [{'nodename': 'device2', 'rcs_state': 'Y'}], + args: ['--machine', 'json', 'target', 'list'], + output: [{ nodename: 'device2', rcs_state: 'Y' }], }, ); const ffx = new Ffx(TEST_CWD, TEST_FFX); const seenDevices: ([Error | string | undefined, Error | boolean | undefined])[] = []; - ffx.onSetTarget(dev => { + ffx.onSetTarget((dev) => { seenDevices.push([ - ffx.targetDevice?.nodeName === dev?.nodeName ? dev?.nodeName : ( - new Error( - `onSetTarget device ${dev?.nodeName} !== ` + - `ffx.targetDevice?.nodeName ${ffx.targetDevice?.nodeName}` - ) - ), - ffx.targetDevice?.connected === dev?.connected ? dev?.connected : ( - new Error( - `onSetTarget connected ${dev?.connected} !== ` + - `ffx.targetDevice?.connected ${ffx.targetDevice?.connected}` - ) - ), + ffx.targetDevice?.nodeName === dev?.nodeName ? + dev?.nodeName : + ( + new Error( + `onSetTarget device ${dev?.nodeName} !== ` + + `ffx.targetDevice?.nodeName ${ffx.targetDevice?.nodeName}`, + ) + ), + ffx.targetDevice?.connected === dev?.connected ? + dev?.connected : + ( + new Error( + `onSetTarget connected ${dev?.connected} !== ` + + `ffx.targetDevice?.connected ${ffx.targetDevice?.connected}`, + ) + ), ]); }); @@ -875,71 +878,71 @@ }); }); - describe('#refreshTargets', function() { + describe('#refreshTargets', function () { // targetListData: Targets = 2, DefaultTargetCount = 1, ConnectedTargetCount = 2 const targetListData = [ { - 'nodename': 'test-device', - 'rcs_state': 'Y', - 'serial': 'serial-11111', - 'target_type': 'test-product', - 'target_state': 'Product', - 'addresses': ['fe80::41e7:ace8:59b7:3cb7%en11'], - 'is_default': false + nodename: 'test-device', + rcs_state: 'Y', + serial: 'serial-11111', + target_type: 'test-product', + target_state: 'Product', + addresses: ['fe80::41e7:ace8:59b7:3cb7%en11'], + is_default: false, }, { - 'nodename': 'another-device', - 'rcs_state': 'Y', - 'serial': 'serial-222222', - 'target_type': 'test-product', - 'target_state': 'Product', - 'addresses': ['fe80::1010:1010:1010:1010%en11'], - 'is_default': true - } + nodename: 'another-device', + rcs_state: 'Y', + serial: 'serial-222222', + target_type: 'test-product', + target_state: 'Product', + addresses: ['fe80::1010:1010:1010:1010%en11'], + is_default: true, + }, ]; // newTargetList: Targets = 3, DefaultTargetCount = 1, ConnectedTargetCount = 2 const newTargetList = [ { - 'nodename': 'dev1', - 'rcs_state': 'Y', - 'serial': 'na', 'target_type': 'na', 'target_state': 'na', 'addresses': ['127.0.0.1'], - 'is_default': true + nodename: 'dev1', + rcs_state: 'Y', + serial: 'na', target_type: 'na', target_state: 'na', addresses: ['127.0.0.1'], + is_default: true, }, { - 'nodename': 'dev2', - 'rcs_state': 'Y', - 'serial': 'na', 'target_type': 'na', 'target_state': 'na', 'addresses': ['127.0.0.1'], - 'is_default': false + nodename: 'dev2', + rcs_state: 'Y', + serial: 'na', target_type: 'na', target_state: 'na', addresses: ['127.0.0.1'], + is_default: false, }, { - 'nodename': 'dev3', - 'rcs_state': 'N', - 'serial': 'na', 'target_type': 'na', 'target_state': 'na', 'addresses': ['127.0.0.1'], - 'is_default': false - } + nodename: 'dev3', + rcs_state: 'N', + serial: 'na', target_type: 'na', target_state: 'na', addresses: ['127.0.0.1'], + is_default: false, + }, ]; // newTargetListError: Targets = 2, DefaultTargetCount = 0, ConnectedTargetCount = 0 const newTargetListError = [ { - 'nodename': '<unknown1>', - 'rcs_state': 'N', - 'serial': 'na', 'target_type': 'na', 'target_state': 'na', 'addresses': ['127.0.0.1'], - 'is_default': false + nodename: '<unknown1>', + rcs_state: 'N', + serial: 'na', target_type: 'na', target_state: 'na', addresses: ['127.0.0.1'], + is_default: false, }, { - 'nodename': '<unknown2>', - 'rcs_state': 'N', - 'serial': 'na', 'target_type': 'na', 'target_state': 'na', 'addresses': ['127.0.0.1'], - 'is_default': false - } + nodename: '<unknown2>', + rcs_state: 'N', + serial: 'na', target_type: 'na', target_state: 'na', addresses: ['127.0.0.1'], + is_default: false, + }, ]; const TARGET_LIST_ARGS = ['--machine', 'json', 'target', 'list']; - it('gets a map of device name to FuchsiaDevice and sets default to ffx default target', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('gets a map of device name to FuchsiaDevice and sets default to ffx default target', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { args: TARGET_LIST_ARGS, output: targetListData, @@ -958,8 +961,8 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('Verify device list and same default target after targetListData and then empty', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('Verify device list and same default target after targetListData and then empty', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { args: TARGET_LIST_ARGS, output: targetListData, @@ -983,8 +986,8 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('Verify device list and same default target after targetListData and then newTargetList', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('Verify device list and same default target after targetListData and then newTargetList', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { args: TARGET_LIST_ARGS, output: targetListData, @@ -1014,8 +1017,8 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('Verify device list and same default target after targetListData and then newTargetListError', async function() { - const {actualInvocations, expectedInvocations} = mockFfx( + it('Verify device list and same default target after targetListData and then newTargetListError', async function () { + const { actualInvocations, expectedInvocations } = mockFfx( { args: TARGET_LIST_ARGS, output: targetListData, @@ -1044,10 +1047,10 @@ }); }); - it('Timeout while calling FFX Target List', async function() { + it('Timeout while calling FFX Target List', async function () { const ffx = new Ffx(TEST_CWD, TEST_FFX); - stubbedSpawn.spawnStubInfo.callsFake(function() { + stubbedSpawn.spawnStubInfo.callsFake(function () { return stubbedSpawn.spawnEvent; }); @@ -1064,10 +1067,10 @@ } }); - it('calling FFX Target List with custom timeout', async function() { + it('calling FFX Target List with custom timeout', async function () { const ffx = new Ffx(TEST_CWD, TEST_FFX); - stubbedSpawn.spawnStubInfo.callsFake(function() { + stubbedSpawn.spawnStubInfo.callsFake(function () { setTimeout(() => { stubbedSpawn.spawnEvent.stdout?.emit('data', '[]'); stubbedSpawn.spawnEvent.kill(0);
diff --git a/src/test/suite/index.ts b/src/test/suite/index.ts index 37348f4..52faffa 100644 --- a/src/test/suite/index.ts +++ b/src/test/suite/index.ts
@@ -31,7 +31,7 @@ return new Promise((c, e) => { try { // Run the mocha test - mocha.run(failures => { + mocha.run((failures) => { if (failures > 0) { e(Error(`${failures} tests failed.`)); } else {
diff --git a/src/test/suite/problem_matcher.test.ts b/src/test/suite/problem_matcher.test.ts index 90ca7ee..631536d 100644 --- a/src/test/suite/problem_matcher.test.ts +++ b/src/test/suite/problem_matcher.test.ts
@@ -11,7 +11,7 @@ const case1 = [ '../../examples/file.cc:10:1: error: expected expression', '../../examples/file.cc:15:3: note: this should be logged :)', - 'The fog in SF is nicknamed Karl' + 'The fog in SF is nicknamed Karl', ]; const case2 = [
diff --git a/src/test/suite/reporter.ts b/src/test/suite/reporter.ts index dcd01cc..490d52b 100644 --- a/src/test/suite/reporter.ts +++ b/src/test/suite/reporter.ts
@@ -6,12 +6,11 @@ import * as fs from 'fs'; import * as stream from 'stream'; - type SuiteChild = Suite | Test; interface Suite { name: string; - children: SuiteChild[], + children: SuiteChild[]; tests: number; failures: number; skipped: number; @@ -59,7 +58,9 @@ }; runner.on('suite', (suite) => { - if (suite.root) { return; } + if (suite.root) { + return; + } suiteStack.push(currentSuite); currentSuite = { name: suite.title, @@ -160,4 +161,3 @@ this.out.write('</testcase>\n'); } } -
diff --git a/src/test/suite/snap.test.ts b/src/test/suite/snap.test.ts index fc78fd1..046fc35 100644 --- a/src/test/suite/snap.test.ts +++ b/src/test/suite/snap.test.ts
@@ -17,13 +17,15 @@ const onigWasmPath = require.resolve('vscode-oniguruma').replace(/main\.js$/, 'onig.wasm'); const onigWasmRaw = await fs.readFile(onigWasmPath); const onigLib = onig.loadWASM( - onigWasmRaw.byteOffset === 0 ? onigWasmRaw.buffer : onigWasmRaw.buffer.slice( - onigWasmRaw.byteOffset, - onigWasmRaw.byteOffset + onigWasmRaw.byteLength - ) + onigWasmRaw.byteOffset === 0 ? + onigWasmRaw.buffer : + onigWasmRaw.buffer.slice( + onigWasmRaw.byteOffset, + onigWasmRaw.byteOffset + onigWasmRaw.byteLength, + ), ).then(() => ({ createOnigScanner(patterns: string[]) { return new onig.OnigScanner(patterns); }, - createOnigString(s: string) { return new onig.OnigString(s); } + createOnigString(s: string) { return new onig.OnigString(s); }, })); return new tm.Registry({ @@ -50,7 +52,7 @@ // need the filename to indicate that this is JSON, no a plist return tm.parseRawGrammar(contents, `${ext}.json`); - } + }, }); } @@ -86,7 +88,9 @@ } const parsedLines = []; const splitLine = (line: string): ['#' | '>', string] => { - if (line.length < 1) { throw new Error('empty line in snapshot'); } + if (line.length < 1) { + throw new Error('empty line in snapshot'); + } const [indicator, contents] = [line[0], line.slice(1)]; if (indicator !== '#' && indicator !== '>') { throw new Error(`unknown snapshot line start character '${indicator}'`); @@ -188,9 +192,9 @@ for (const kind of kinds) { const snapDir = path.join(rootSnapDir, kind); // filter out the `.snap` files, so we're only left with the base input files - const files: [string, string][] = (await fs.readdir(snapDir)). - filter((file) => path.extname(file) === `.${kind}`). - map((file) => [file, path.join(snapDir, file)]); + const files: [string, string][] = (await fs.readdir(snapDir)) + .filter(file => path.extname(file) === `.${kind}`) + .map(file => [file, path.join(snapDir, file)]); snapFiles.set(kind, files); }
diff --git a/src/test/suite/target_status_bar_item.test.ts b/src/test/suite/target_status_bar_item.test.ts index c55c4da..3cd66a4 100644 --- a/src/test/suite/target_status_bar_item.test.ts +++ b/src/test/suite/target_status_bar_item.test.ts
@@ -9,7 +9,7 @@ import { TargetStatusBarItem, TargetPickAction, STATUS_PREFIX_CONNECTED, - STATUS_PREFIX_NOT_CONNECTED, STATUS_PREFIX_EMPTY + STATUS_PREFIX_NOT_CONNECTED, STATUS_PREFIX_EMPTY, } from '../../target_status_bar_item'; import { Ffx, FfxEventType, FuchsiaDevice } from '../../ffx'; @@ -24,7 +24,7 @@ let device1: FuchsiaDevice; let device2: FuchsiaDevice; -describe('TargetStatusBarItemTest', function() { +describe('TargetStatusBarItemTest', function () { const sandbox = createSandbox(); let onDidChangeConfiguration: vscode.EventEmitter<FfxEventType>; let onDefaultTargetChange: vscode.EventEmitter<FuchsiaDevice | null>; @@ -35,7 +35,7 @@ let targetList: Record<string, FuchsiaDevice>; let commands: Record<string, (...args: unknown[]) => unknown>; - this.beforeEach(function() { + this.beforeEach(function () { // Reset device settings for each test. // eslint-disable-next-line @typescript-eslint/naming-convention device0 = new FuchsiaDevice({ nodename: DEVICE_NAME_0, rcs_state: 'Y' }); @@ -47,7 +47,7 @@ targetList = { [DEVICE_NAME_0]: device0, [DEVICE_NAME_1]: device1, - [DEVICE_NAME_2]: device2 + [DEVICE_NAME_2]: device2, }; this.log = sandbox.spy(vscode.window.createOutputChannel)('test_ffx', { log: true }); ffxTools = createStubInstance(Ffx); @@ -74,7 +74,7 @@ sandbox.stub(toolFinder, 'ffx').get(() => ffxTools); }); - this.afterEach(function() { + this.afterEach(function () { onDidChangeConfiguration.dispose(); for (const subscription of subscriptions) { subscription.dispose(); @@ -84,13 +84,13 @@ sandbox.restore(); }); - describe('#constructor', function() { - it('creates an instance of TargetStatusBarItem', function() { + describe('#constructor', function () { + it('creates an instance of TargetStatusBarItem', function () { new TargetStatusBarItem(subscriptions, toolFinder); }); }); - describe('#behavior', function() { + describe('#behavior', function () { it('Test Status bar', async () => { const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 0); sandbox.stub(vscode.window, 'createStatusBarItem').callsFake(() => { @@ -164,7 +164,7 @@ // Check that the item selected exists. if (!itemSelection) { quickPickErrors.push(new Error( - `Selection = "${selection ?? 'undefined'}" is not in items = [${items.map(e => e.label).join(', ')}]` + `Selection = "${selection ?? 'undefined'}" is not in items = [${items.map(e => e.label).join(', ')}]`, )); }
diff --git a/src/test/suite/test_controller/discovery.test.ts b/src/test/suite/test_controller/discovery.test.ts index 0f03180..25c49ac 100644 --- a/src/test/suite/test_controller/discovery.test.ts +++ b/src/test/suite/test_controller/discovery.test.ts
@@ -5,9 +5,9 @@ import * as assert from 'assert'; import * as vscode from 'vscode'; import { describe, it } from 'mocha'; -import {createSandbox, type SinonStub} from 'sinon'; +import { createSandbox, type SinonStub } from 'sinon'; -import {Fx} from '../../../fx'; +import { Fx } from '../../../fx'; import { cacheTestCases, discoverTestCasesLogic, @@ -16,17 +16,17 @@ TestcaseDiscoveryQueue, } from '../../../test_controller/discovery'; -import {macrotask, type MockedCommandInvocation, setupMockedCommand, StubbedSpawn} from '../utils'; -import {Logger, initLogger} from '../../../logger'; -import {Ffx} from '../../../ffx'; +import { macrotask, type MockedCommandInvocation, setupMockedCommand, StubbedSpawn } from '../utils'; +import { Logger, initLogger } from '../../../logger'; +import { Ffx } from '../../../ffx'; -describe('Test Controller Discovery', function() { +describe('Test Controller Discovery', function () { const sandbox = createSandbox(); const TEST_CWD = '/path/to/workspace'; let controller: vscode.TestController; let fx: Fx; - this.beforeEach(function() { + this.beforeEach(function () { controller = vscode.tests.createTestController('TestControllerDiscovery', 'TestControllerDiscovery'); const log = vscode.window.createOutputChannel('test_controller.test', { log: true }); initLogger(log); @@ -34,15 +34,15 @@ fx = new Fx(TEST_CWD, ffx); }); - this.afterEach(function() { + this.afterEach(function () { controller.dispose(); sandbox.restore(); }); - describe('#fxListTestCases', function() { + describe('#fxListTestCases', function () { let stubbedSpawn: StubbedSpawn; - this.beforeEach(function() { + this.beforeEach(function () { stubbedSpawn = new StubbedSpawn(sandbox); }); @@ -52,9 +52,9 @@ commandInvocations, ); - it('resolves if no tests are discovered', async function() { + it('resolves if no tests are discovered', async function () { const TEST_URL = 'fuchsia-pkg://a_repo/test_pkg#meta/foo_test_component.cm'; - const {actualInvocations, expectedInvocations} = mockCommands( + const { actualInvocations, expectedInvocations } = mockCommands( { args: ['fx', `--invoker=Extension: ${vscode.env.appName}`, 'test', '--logpath=-', '--list', TEST_URL], output: {}, @@ -69,9 +69,9 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('populates a TestItem', async function() { + it('populates a TestItem', async function () { const TEST_URL = 'fuchsia-pkg://a_repo/test_pkg#meta/bar_test_component.cm'; - const {actualInvocations, expectedInvocations} = mockCommands( + const { actualInvocations, expectedInvocations } = mockCommands( { args: ['fx', `--invoker=Extension: ${vscode.env.appName}`, 'test', '--logpath=-', '--list', TEST_URL], output: { @@ -83,9 +83,9 @@ 'BarTest.testA', 'BarTest.testB', 'BarTest.testC', - ] - } - } + ], + }, + }, }, }, ); @@ -101,9 +101,9 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('specifies --no-build', async function() { + it('specifies --no-build', async function () { const TEST_URL = 'fuchsia-pkg://a_repo/test_pkg#meta/bar_test_component.cm'; - const {actualInvocations, expectedInvocations} = mockCommands( + const { actualInvocations, expectedInvocations } = mockCommands( { args: ['fx', `--invoker=Extension: ${vscode.env.appName}`, 'test', '--logpath=-', '--list', TEST_URL, '--no-build'], output: { @@ -113,9 +113,9 @@ // eslint-disable-next-line @typescript-eslint/naming-convention test_case_names: [ 'BarTest.testA', - ] - } - } + ], + }, + }, }, }, ); @@ -129,9 +129,9 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('attaches the FuchsiaTest tag', async function() { + it('attaches the FuchsiaTest tag', async function () { const TEST_URL = 'fuchsia-pkg://a_repo/test_pkg#meta/bar_test_component.cm'; - const {actualInvocations, expectedInvocations} = mockCommands( + const { actualInvocations, expectedInvocations } = mockCommands( { args: ['fx', `--invoker=Extension: ${vscode.env.appName}`, 'test', '--logpath=-', '--list', TEST_URL], output: { @@ -141,9 +141,9 @@ // eslint-disable-next-line @typescript-eslint/naming-convention test_case_names: [ 'BarTest.testA', - ] - } - } + ], + }, + }, }, }, ); @@ -160,9 +160,9 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('does not attach the FuchsiaTest tag', async function() { + it('does not attach the FuchsiaTest tag', async function () { const TEST_URL = 'fuchsia-pkg://a_repo/test_pkg#meta/bar_test_component.cm'; - const {actualInvocations, expectedInvocations} = mockCommands( + const { actualInvocations, expectedInvocations } = mockCommands( { args: ['fx', `--invoker=Extension: ${vscode.env.appName}`, 'test', '--logpath=-', '--list', TEST_URL], output: { @@ -172,9 +172,9 @@ // eslint-disable-next-line @typescript-eslint/naming-convention test_case_names: [ 'BarTest.testA', - ] - } - } + ], + }, + }, }, }, ); @@ -190,9 +190,9 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('throws if fx test errors', async function() { + it('throws if fx test errors', async function () { const TEST_URL = 'fuchsia-pkg://a_repo/test_pkg#meta/foo_test_component.cm'; - const {actualInvocations, expectedInvocations} = mockCommands( + const { actualInvocations, expectedInvocations } = mockCommands( { args: ['fx', `--invoker=Extension: ${vscode.env.appName}`, 'test', '--logpath=-', '--list', TEST_URL], output: new Error('{}'), @@ -205,7 +205,7 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('ignores irrelevant JSON objects', async function() { + it('ignores irrelevant JSON objects', async function () { const TEST_URL = 'fuchsia-pkg://a_repo/test_pkg#meta/foo_test_component.cm'; const MOCK_FX_JSON_OUTPUTS = [ undefined, @@ -248,7 +248,7 @@ }, }, ]; - const {actualInvocations, expectedInvocations} = mockCommands( + const { actualInvocations, expectedInvocations } = mockCommands( { args: ['fx', `--invoker=Extension: ${vscode.env.appName}`, 'test', '--logpath=-', '--list', TEST_URL], output: MOCK_FX_JSON_OUTPUTS.map(obj => JSON.stringify(obj)).join('\n'), @@ -264,9 +264,9 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('deduplicates test cases', async function() { + it('deduplicates test cases', async function () { const TEST_URL = 'fuchsia-pkg://a_repo/test_pkg#meta/foo_test_component.cm'; - const {actualInvocations, expectedInvocations} = mockCommands( + const { actualInvocations, expectedInvocations } = mockCommands( { args: ['fx', `--invoker=Extension: ${vscode.env.appName}`, 'test', '--logpath=-', '--list', TEST_URL], output: JSON.stringify({ @@ -300,9 +300,9 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('throws if test_case_names is the wrong type', async function() { + it('throws if test_case_names is the wrong type', async function () { const TEST_URL = 'fuchsia-pkg://a_repo/test_pkg#meta/foo_test_component.cm'; - const {actualInvocations, expectedInvocations} = mockCommands( + const { actualInvocations, expectedInvocations } = mockCommands( { args: ['fx', `--invoker=Extension: ${vscode.env.appName}`, 'test', '--logpath=-', '--list', TEST_URL], output: { @@ -311,10 +311,10 @@ enumerate_test_cases: { // eslint-disable-next-line @typescript-eslint/naming-convention test_case_names: { - fooTest: TEST_URL - } - } - } + fooTest: TEST_URL, + }, + }, + }, }, }, ); @@ -325,9 +325,9 @@ assert.deepStrictEqual(actualInvocations, expectedInvocations); }); - it('throws if test_case_names entries are the wrong type', async function() { + it('throws if test_case_names entries are the wrong type', async function () { const TEST_URL = 'fuchsia-pkg://a_repo/test_pkg#meta/foo_test_component.cm'; - const {actualInvocations, expectedInvocations} = mockCommands( + const { actualInvocations, expectedInvocations } = mockCommands( { args: ['fx', `--invoker=Extension: ${vscode.env.appName}`, 'test', '--logpath=-', '--list', TEST_URL], output: { @@ -337,9 +337,9 @@ // eslint-disable-next-line @typescript-eslint/naming-convention test_case_names: [ 123, - ] - } - } + ], + }, + }, }, }, ); @@ -351,17 +351,16 @@ }); }); - describe('TestcaseDiscoveryQueue', function() { - describe('#discover', function() { - it('populates independent TestItem discovery requests', async function() { + describe('TestcaseDiscoveryQueue', function () { + describe('#discover', function () { + it('populates independent TestItem discovery requests', async function () { const fooTestItem = controller.createTestItem('foo', 'foo'); const barTestItem = controller.createTestItem('bar', 'bar'); - const discoverFn = sandbox.stub().callsFake( (_controller, _fx, testItem: vscode.TestItem) => { testItem.children.add( - controller.createTestItem(`${testItem.id}.testCase`, `${testItem.id}.testCase`) + controller.createTestItem(`${testItem.id}.testCase`, `${testItem.id}.testCase`), ); return Promise.resolve(); }); @@ -380,7 +379,7 @@ assert.ok(discoverFn.secondCall.calledWith(controller, fx, barTestItem)); }); - it('performs TestItem discovery requests in parallel', async function() { + it('performs TestItem discovery requests in parallel', async function () { const fooTestItem = controller.createTestItem('foo', 'foo'); const barTestItem = controller.createTestItem('bar', 'bar'); @@ -388,7 +387,7 @@ async (_controller, _fx, testItem: vscode.TestItem) => { await new Promise(resolve => setTimeout(resolve, 50)); testItem.children.add( - controller.createTestItem(`${testItem.id}.testCase`, `${testItem.id}.testCase`) + controller.createTestItem(`${testItem.id}.testCase`, `${testItem.id}.testCase`), ); }); @@ -415,10 +414,10 @@ assert.ok(discoverFn.secondCall.calledWith(controller, fx, barTestItem)); }); - it('populates varied concurrent TestItem discovery requests', async function() { + it('populates varied concurrent TestItem discovery requests', async function () { const MOCK_DISCOVERY_DURATION = 10; const discoverFn = sandbox.stub().callsFake( - (_controller, _fx, testItem: vscode.TestItem) => new Promise<void>(resolve => { + (_controller, _fx, testItem: vscode.TestItem) => new Promise<void>((resolve) => { setTimeout(() => { const child = controller.createTestItem( `${testItem.id}.testCase`, @@ -427,7 +426,7 @@ testItem.children.add(child); resolve(); }, MOCK_DISCOVERY_DURATION); - }) + }), ); const queue = TestcaseDiscoveryQueue.createForTesting(controller, fx, discoverFn); @@ -455,7 +454,7 @@ await initialPromise; assert.deepStrictEqual( discovered, - {initial: true, synchronous: false, microtask: false, macrotask: false, timed: false}, + { initial: true, synchronous: false, microtask: false, macrotask: false, timed: false }, ); assert.strictEqual(initialTestItem.children.size, 1); assert.ok(initialTestItem.children.get('initial.testCase')); @@ -469,7 +468,7 @@ await synchronousPromise; assert.deepStrictEqual( discovered, - {initial: true, synchronous: true, microtask: false, macrotask: false, timed: false}, + { initial: true, synchronous: true, microtask: false, macrotask: false, timed: false }, ); assert.strictEqual(synchronousTestItem.children.size, 1); assert.ok(synchronousTestItem.children.get('synchronous.testCase')); @@ -483,7 +482,7 @@ await microtaskPromise; assert.deepStrictEqual( discovered, - {initial: true, synchronous: true, microtask: true, macrotask: false, timed: false}, + { initial: true, synchronous: true, microtask: true, macrotask: false, timed: false }, ); assert.strictEqual(microtaskTestItem.children.size, 1); assert.ok(microtaskTestItem.children.get('microtask.testCase')); @@ -496,7 +495,7 @@ await macrotaskPromise; assert.deepStrictEqual( discovered, - {initial: true, synchronous: true, microtask: true, macrotask: true, timed: false}, + { initial: true, synchronous: true, microtask: true, macrotask: true, timed: false }, ); assert.strictEqual(macrotaskTestItem.children.size, 1); assert.ok(macrotaskTestItem.children.get('macrotask.testCase')); @@ -505,7 +504,7 @@ await timedPromise; assert.deepStrictEqual( discovered, - {initial: true, synchronous: true, microtask: true, macrotask: true, timed: true}, + { initial: true, synchronous: true, microtask: true, macrotask: true, timed: true }, ); assert.strictEqual(timedTestItem.children.size, 1); assert.ok(timedTestItem.children.get('timed.testCase')); @@ -515,7 +514,7 @@ assert.strictEqual(discoverFn.callCount, 5); }); - it('issues a notification without resolving if discovery fails', async function() { + it('issues a notification without resolving if discovery fails', async function () { const discoverFn = sandbox.stub().rejects(new Error('Discovery failed')); const stubShowErrorMessage = sandbox.stub(vscode.window, 'showErrorMessage') as unknown as sinon.SinonStub; stubShowErrorMessage.resolves('Dismiss'); @@ -537,7 +536,7 @@ assert.strictEqual(testItem.children.size, 0); }); - it('shows error logs if the user clicks show logs', async function() { + it('shows error logs if the user clicks show logs', async function () { const CHOICES = ['Show Logs']; const stubShowErrorMessage = sandbox.stub(vscode.window, 'showErrorMessage') as unknown as sinon.SinonStub; stubShowErrorMessage.callsFake(() => { @@ -559,7 +558,7 @@ assert.strictEqual(testItem.children.size, 0); }); - it('reattempts a discovery and fails again', async function() { + it('reattempts a discovery and fails again', async function () { const CHOICES = ['Retry']; const stubShowErrorMessage = sandbox.stub(vscode.window, 'showErrorMessage') as unknown as sinon.SinonStub; stubShowErrorMessage.callsFake(() => { @@ -584,7 +583,7 @@ assert.strictEqual(discoverFn.callCount, 2); }); - it('issues one notification when multiple TestItems fail in a batch', async function() { + it('issues one notification when multiple TestItems fail in a batch', async function () { const spyShowErrorMessage = sandbox.spy(vscode.window, 'showErrorMessage'); const discoverFn = sandbox.stub().rejects(new Error('Discovery failed')); @@ -611,7 +610,7 @@ assert.strictEqual(discoverFn.callCount, 2); }); - it('batches previous failures onto future discoveries', async function() { + it('batches previous failures onto future discoveries', async function () { const CHOICES = [ undefined, // User clicks the (x) button on the notification. 'Retry', @@ -655,7 +654,7 @@ assert.strictEqual(barTestItem.children.size, 0); }); - it('reattempts a discovery and succeeds', async function() { + it('reattempts a discovery and succeeds', async function () { const CHOICES = ['Retry']; const stubShowErrorMessage = sandbox.stub(vscode.window, 'showErrorMessage') as unknown as sinon.SinonStub; stubShowErrorMessage.callsFake(() => { @@ -681,7 +680,7 @@ assert.ok(testItem.children.get('TestCase.testA')); }); - it('only retries failing discoveries when mixed with successful discoveries', async function() { + it('only retries failing discoveries when mixed with successful discoveries', async function () { const CHOICES = ['Retry']; const stubShowErrorMessage = sandbox.stub(vscode.window, 'showErrorMessage') as unknown as sinon.SinonStub; stubShowErrorMessage.callsFake(() => { @@ -721,7 +720,7 @@ assert.ok(barTestItem.children.get('bar')); }); - it('batches failing discoveries onto future discoveries when mixed with successful discoveries', async function() { + it('batches failing discoveries onto future discoveries when mixed with successful discoveries', async function () { const spyShowErrorMessage = sandbox.spy(vscode.window, 'showErrorMessage'); const fooTestItem = controller.createTestItem('foo', 'foo'); @@ -768,11 +767,11 @@ assert.ok(discoverFn.getCall(3).calledWith(controller, fx, bazTestItem)); }); - it('deduplicates 2 retry buttons rapidly clicked', async function() { + it('deduplicates 2 retry buttons rapidly clicked', async function () { const pendingErrorMessageToasts: ((choice: string | undefined) => void)[] = []; const stubShowErrorMessage = sandbox.stub(vscode.window, 'showErrorMessage') as unknown as sinon.SinonStub; stubShowErrorMessage.callsFake(() => { - return new Promise<string | undefined>(resolve => { + return new Promise<string | undefined>((resolve) => { pendingErrorMessageToasts.push(resolve); }); }); @@ -808,17 +807,17 @@ assert.strictEqual(stubShowErrorMessage.callCount, 3); // Final state check - assert.deepStrictEqual(resolved, {foo: false, bar: false}); + assert.deepStrictEqual(resolved, { foo: false, bar: false }); assert.strictEqual(fooTestItem.children.size, 0); assert.strictEqual(barTestItem.children.size, 0); }); }); }); - describe('Test Case Caching', function() { + describe('Test Case Caching', function () { let memento: vscode.Memento; - this.beforeEach(function() { + this.beforeEach(function () { const storage = new Map<string, unknown>(); memento = { keys: () => [...storage.keys()], @@ -832,7 +831,7 @@ }; }); - it('saves and restores TestItems from the cache', async function() { + it('saves and restores TestItems from the cache', async function () { const TEST_ID = 'fuchsia-pkg://a_repo/test_pkg#meta/foo_test_component.cm'; const TEST_URI = vscode.Uri.parse('file:///path/to/workspace/foo_test.cc'); const testCases: vscode.TestItem[] = [ @@ -860,12 +859,12 @@ assert.strictEqual(restoredTestB.tags.length, 0); }); - it('returns undefined for a cache miss', function() { + it('returns undefined for a cache miss', function () { const restoredTestCases = queryTestCaseCache(memento, controller, 'non-existent-id'); assert.deepStrictEqual(restoredTestCases, undefined); }); - it('handles test items without URIs or tags', async function() { + it('handles test items without URIs or tags', async function () { const TEST_ID = 'test-id-no-uri'; const testCases: vscode.TestItem[] = [ controller.createTestItem('NoUri.test', 'NoUri.test'), @@ -883,14 +882,14 @@ }); }); - describe('#discoverTestCasesLogic', function() { + describe('#discoverTestCasesLogic', function () { let queryCacheStub: SinonStub; let listTestCasesNoBuildStub: SinonStub; let listTestCasesWithBuildStub: SinonStub; let updateChildrenStub: SinonStub; let cacheResultStub: SinonStub; - this.beforeEach(function() { + this.beforeEach(function () { queryCacheStub = sandbox.stub(); listTestCasesNoBuildStub = sandbox.stub(); listTestCasesWithBuildStub = sandbox.stub(); @@ -898,7 +897,7 @@ cacheResultStub = sandbox.stub(); }); - it('should populate children from cache first, then no-build, then with-build', async function() { + it('should populate children from cache first, then no-build, then with-build', async function () { const cachedChildren = [controller.createTestItem('cached', 'Testcase (cached)')]; const noBuildChildren = [controller.createTestItem('no-build', 'Testcase (no-build)')]; const withBuildChildren = [controller.createTestItem('with-build', 'Testcase (with-build)')]; @@ -913,7 +912,7 @@ listTestCasesNoBuildStub, listTestCasesWithBuildStub, updateChildrenStub, - cacheResultStub + cacheResultStub, ); // Verify that the cache query, cached children update, no-build discovery, and with-build @@ -938,7 +937,7 @@ assert.ok(cacheResultStub.getCall(1).calledWith(withBuildChildren)); }); - it('should not block on no-build results', async function() { + it('should not block on no-build results', async function () { const cachedChildren = [controller.createTestItem('cached', 'Testcase (cached)')]; const withBuildChildren = [controller.createTestItem('with-build', 'Testcase (with-build)')]; @@ -952,7 +951,7 @@ listTestCasesNoBuildStub, listTestCasesWithBuildStub, updateChildrenStub, - cacheResultStub + cacheResultStub, ); // Verify that the cache query, cached children update, no-build discovery, and with-build @@ -975,7 +974,7 @@ assert.ok(cacheResultStub.calledWith(withBuildChildren)); }); - it('should reject and update with no-build results if with-build fails', async function() { + it('should reject and update with no-build results if with-build fails', async function () { const cachedChildren = [controller.createTestItem('cached', 'Testcase (cached)')]; const noBuildChildren = [controller.createTestItem('no-build', 'Testcase (no-build)')]; @@ -991,10 +990,9 @@ listTestCasesNoBuildStub, listTestCasesWithBuildStub, updateChildrenStub, - cacheResultStub + cacheResultStub, )); - // Verify that the cache query, cached children update, no-build discovery, and with-build // discovery are all stated synchronously. assert.ok(queryCacheStub.calledOnce); @@ -1015,14 +1013,14 @@ assert.ok(cacheResultStub.calledWith(noBuildChildren)); }); - it('should not update with no-build results if with-build has already updated', async function() { + it('should not update with no-build results if with-build has already updated', async function () { const cachedChildren = [controller.createTestItem('cached', 'Testcase (cached)')]; const noBuildChildren = [controller.createTestItem('no-build', 'Testcase (no-build)')]; const withBuildChildren = [controller.createTestItem('with-build', 'Testcase (with-build)')]; queryCacheStub.returns(cachedChildren); listTestCasesNoBuildStub.returns(new Promise( - resolve => setTimeout(() => resolve(noBuildChildren), 50) + resolve => setTimeout(() => resolve(noBuildChildren), 50), )); // Finishes slower. listTestCasesWithBuildStub.resolves(withBuildChildren); // Finishes quicker. cacheResultStub.resolves(); @@ -1032,7 +1030,7 @@ listTestCasesNoBuildStub, listTestCasesWithBuildStub, updateChildrenStub, - cacheResultStub + cacheResultStub, ); // Verify that the cache query, cached children update, no-build discovery, and with-build @@ -1056,7 +1054,7 @@ assert.ok(cacheResultStub.calledWith(withBuildChildren)); }); - it('should populate from no-build, then with-build when cache is unavailable', async function() { + it('should populate from no-build, then with-build when cache is unavailable', async function () { const noBuildChildren = [controller.createTestItem('no-build', 'Testcase (no-build)')]; const withBuildChildren = [controller.createTestItem('with-build', 'Testcase (with-build)')]; @@ -1070,10 +1068,9 @@ listTestCasesNoBuildStub, listTestCasesWithBuildStub, updateChildrenStub, - cacheResultStub + cacheResultStub, ); - // Verify that the cache query, and both discoveries are all stated synchronously. assert.ok(queryCacheStub.calledOnce); assert.ok(listTestCasesNoBuildStub.calledOnce); @@ -1093,7 +1090,7 @@ assert.ok(cacheResultStub.getCall(1).calledWith(withBuildChildren)); }); - it('should handle when no test cases are available from any source', async function() { + it('should handle when no test cases are available from any source', async function () { queryCacheStub.returns(undefined); listTestCasesNoBuildStub.rejects(new Error('failed to connect to target device')); listTestCasesWithBuildStub.rejects(new Error('failed to connect to target device')); @@ -1104,7 +1101,7 @@ listTestCasesNoBuildStub, listTestCasesWithBuildStub, updateChildrenStub, - cacheResultStub + cacheResultStub, )); // Verify that the cache query, no-build discovery, and with-build discovery are all called. @@ -1122,7 +1119,7 @@ assert.strictEqual(cacheResultStub.callCount, 0); }); - it('resolves when only built testcase results are available', async function() { + it('resolves when only built testcase results are available', async function () { const withBuildChildren = [controller.createTestItem('with-build', 'Testcase (with-build)')]; queryCacheStub.returns(undefined); listTestCasesNoBuildStub.rejects(new Error('test not built yet')); @@ -1134,7 +1131,7 @@ listTestCasesNoBuildStub, listTestCasesWithBuildStub, updateChildrenStub, - cacheResultStub + cacheResultStub, ); // Verify that the cache query, no-build discovery, and with-build discovery are all called.
diff --git a/src/test/suite/tool_finder.test.ts b/src/test/suite/tool_finder.test.ts index f90660d..7817b0b 100644 --- a/src/test/suite/tool_finder.test.ts +++ b/src/test/suite/tool_finder.test.ts
@@ -17,7 +17,6 @@ other: string; home: string; - constructor() { this.baseDir = path.join(vscode.workspace.workspaceFolders![0].uri.path, '..'); this.path = path.join(this.baseDir, 'workspace'); @@ -34,7 +33,7 @@ async setFfxPath(test: Mocha.Context, newPath: string, tools: ToolFinder) { // first, register to be notified when the config changes // (needa do this before changing it so we don't race)... - const didChange = anEventOf(tools.onDidUpdateFfx, (evt) => !evt.isInitial); + const didChange = anEventOf(tools.onDidUpdateFfx, evt => !evt.isInitial); // ...then, change the config... await noTimeout(test, vscode.workspace.getConfiguration('fuchsia').update('ffxPath', newPath)); @@ -102,7 +101,7 @@ // configuration. // gotta wait till we see that we went through the trouble of updating it first - await anEventOf(tools.onDidUpdateFfx, (evt) => evt.isInitial); + await anEventOf(tools.onDidUpdateFfx, evt => evt.isInitial); assert.strictEqual(tools.ffxPath, workspace.defaultFfx); });
diff --git a/src/test/suite/utils.ts b/src/test/suite/utils.ts index 9e93fdb..8c1b1cd 100644 --- a/src/test/suite/utils.ts +++ b/src/test/suite/utils.ts
@@ -48,16 +48,18 @@ export async function separateTimeoutBudget<T>( test: Mocha.Context, task: Thenable<T>, - timeout: number | null + timeout: number | null, ): Promise<T> { const testTimeout = test.timeout(); test.timeout(0); const initial = Date.now(); - const taskDeadline = timeout === null ? [] : [ - new Promise<T>((_, reject) => - setTimeout(() => reject(new Error(`Task timeout budget ${timeout} exceeded.`)), timeout) - ) - ]; + const taskDeadline = timeout === null ? + [] : + [ + new Promise<T>((_, reject) => + setTimeout(() => reject(new Error(`Task timeout budget ${timeout} exceeded.`)), timeout), + ), + ]; const result = await Promise.race([ task, ...taskDeadline, @@ -111,9 +113,9 @@ // imports. this is a teeensy bit janky, but we're on thin // ice with runtime stubs anyway. we should prob use something // like jest or esbuild's module-replacing functionality - this.spawnStubInfo = sandbox. - stub(childProcess, 'spawn'). - returns(this.spawnEvent) as + this.spawnStubInfo = sandbox + .stub(childProcess, 'spawn') + .returns(this.spawnEvent) as SinonStub<[ command: string, args: readonly string[], @@ -144,11 +146,11 @@ stubbedSpawn: StubbedSpawn, cwd: string, ffxPath: string, - ffxInvocations: MockedCommandInvocation[] + ffxInvocations: MockedCommandInvocation[], ): { - actualInvocations: string[][], - expectedInvocations: string[][], - singleCommandDuration: () => Promise<void> + actualInvocations: string[][]; + expectedInvocations: string[][]; + singleCommandDuration: () => Promise<void>; } { const ANALYTICS_FLAG = ['--config', `fuchsia.analytics.ffx_invoker=Extension: ${vscode.env.appName}`]; return setupMockedCommand( @@ -224,11 +226,11 @@ export function setupMockedCommand( stubbedSpawn: StubbedSpawn, cwd: string, - commandInvocations: MockedCommandInvocation[] + commandInvocations: MockedCommandInvocation[], ): { - actualInvocations: string[][], - expectedInvocations: string[][], - singleCommandDuration: () => Promise<void> + actualInvocations: string[][]; + expectedInvocations: string[][]; + singleCommandDuration: () => Promise<void>; } { const expectedInvocations = commandInvocations.map(inv => inv.args); const actualInvocations: string[][] = []; @@ -236,7 +238,7 @@ stubbedSpawn.spawnStubInfo.callsFake(( command: string, args: readonly string[], - options: SpawnOptions + options: SpawnOptions, ) => { const fakeSpawnedProcess = createFakeChildProcess(); @@ -257,7 +259,7 @@ if (command !== expectedInvocations[idx]?.at(0)) { console.warn( `[setupMockedCommand] Ignoring non-matching command ${command}, ` + - `${JSON.stringify(args)}, ${JSON.stringify(options)}` + `${JSON.stringify(args)}, ${JSON.stringify(options)}`, ); fakeSpawnedProcess.emit('exit', 0); fakeSpawnedProcess.emit('close', 0);
diff --git a/src/test/suite/workflow.test.ts b/src/test/suite/workflow.test.ts index 3107580..18fbaa6 100644 --- a/src/test/suite/workflow.test.ts +++ b/src/test/suite/workflow.test.ts
@@ -11,7 +11,6 @@ import { BUILD_MATCHER, logOutput } from '../../workflow/build'; describe('WorkflowTest', function () { - const sandbox = createSandbox(); let logger: Logger; let info: SinonSpy<[message: string, category?: string | undefined, ...args: unknown[]], void>; @@ -31,7 +30,7 @@ describe('for fx set', function () { const mockMemento = { get: sandbox.stub(), - update: sandbox.stub() + update: sandbox.stub(), } as unknown as vscode.Memento; const pkgHistory = new PkgHistory(mockMemento); const prevBuild = { @@ -41,45 +40,45 @@ boards: { notes: '//boards/Product1.gni', title: 'Board', - value: 'BoardB' + value: 'BoardB', }, // eslint-disable-next-line @typescript-eslint/naming-convention compilation_mode: { notes: null, title: 'Compilation mode', - value: 'debug' + value: 'debug', }, products: { notes: '//products/BoardB.gni', title: 'Product', - value: 'Product1' + value: 'Product1', }, // eslint-disable-next-line @typescript-eslint/naming-convention base_package_labels: { notes: '--with-base argument of `fx set`', title: 'Base packages', - value: ['//other:tests'] + value: ['//other:tests'], }, // eslint-disable-next-line @typescript-eslint/naming-convention cache_package_labels: { notes: '--with-cache argument of `fx set`', title: 'Cache packages', - value: ['//src/other:tests'] + value: ['//src/other:tests'], }, // eslint-disable-next-line @typescript-eslint/naming-convention developer_test_labels: { notes: '--with-test argument of `fx set`', title: 'Developer tests', - value: ['//other:tests'] + value: ['//other:tests'], }, // eslint-disable-next-line @typescript-eslint/naming-convention universe_package_labels: { notes: '--with argument of `fx set`', title: 'Universe packages', - value: ['//examples', '//examples:tests'] - } - } - } + value: ['//examples', '//examples:tests'], + }, + }, + }, }; const products = ['Product1', 'Product2']; const boards = ['BoardA', 'BoardB', 'BoardC']; @@ -122,11 +121,11 @@ it('Has one package selected in list', () => { const selection = pkgHistory.update([{ - 'title': 'Universe packages', - 'value': [ - '//examples' + title: 'Universe packages', + value: [ + '//examples', ], - 'notes': '--with argument of `fx set`' + notes: '--with argument of `fx set`', }] as Packages[]); const packageList = pkgHistory.toList(selection); assert.equal(selection.get('Universe packages')?.size, 1); @@ -159,7 +158,7 @@ const expectedOutput = [ '[1/45][ 4%/00:01](959)', '[4/45][ 8%/00:04](0)', - '[45/45][ 100%/00:10](0)' + '[45/45][ 100%/00:10](0)', ]; it('Test build matcher for notification msg', () => { @@ -181,12 +180,11 @@ message: msg, category: 'fx build', inMatcher: !!msg.match(BUILD_MATCHER), - logChannel: logger + logChannel: logger, }); }); sandbox.assert.callCount(info, 5); sandbox.assert.callCount(error, 2); }); }); - });
diff --git a/src/test/suite/zxdb/async_backtrace.test.ts b/src/test/suite/zxdb/async_backtrace.test.ts index 6e856cc..b0f94c4 100644 --- a/src/test/suite/zxdb/async_backtrace.test.ts +++ b/src/test/suite/zxdb/async_backtrace.test.ts
@@ -99,7 +99,7 @@ const child = result.children[0]; assert.strictEqual(child.viewId, 'root::task1::file1.ts::123::task2::file2.ts::0'); - } + }, ); it('should create a nested AsyncTasks without ids, files, or lines', function () { @@ -220,11 +220,11 @@ name: 'task-b1', file: '/path/to/b1.ts', line: 20, - children: [] - } - ] - } - ] + children: [], + }, + ], + }, + ], }, 'session-1'); threadFoo2 = new AsyncBacktrace({ @@ -242,11 +242,11 @@ name: 'task-b2', file: '/path/to/b2.ts', line: 21, - children: [] - } - ] - } - ] + children: [], + }, + ], + }, + ], }, 'session-2'); threadBar = new AsyncBacktrace({ @@ -258,15 +258,15 @@ name: longName, file: 'relative/path/to/long.ts', line: 12, - children: [] - } - ] + children: [], + }, + ], }, 'session-1'); threadBaz = new AsyncBacktrace({ id: 3, name: 'baz', - tasks: [] + tasks: [], }, 'session-1'); taskA1 = threadFoo1.children[0]; @@ -343,7 +343,7 @@ const expectedPath = vscode.Uri.file('/path/to/a1.ts').fsPath; assert.strictEqual((cmd.arguments[0] as vscode.Uri).fsPath, expectedPath); assert.deepStrictEqual(cmd.arguments[1], { - selection: new vscode.Range(9, 0, 9, 0) + selection: new vscode.Range(9, 0, 9, 0), }); }); @@ -357,7 +357,7 @@ const expectedPath = vscode.Uri.file('/some/workspace/relative/path/to/long.ts').fsPath; assert.strictEqual((cmd.arguments[0] as vscode.Uri).fsPath, expectedPath); assert.deepStrictEqual(cmd.arguments[1], { - selection: new vscode.Range(11, 0, 11, 0) + selection: new vscode.Range(11, 0, 11, 0), }); }); }); @@ -407,7 +407,7 @@ const updatedThread = new AsyncBacktrace({ id: 1, name: 'foo1-updated', - tasks: [] + tasks: [], }, 'session-1'); updatedThread.children.push(taskB1); provider.updateAsyncBacktrace(updatedThread); @@ -429,7 +429,7 @@ const newThread = new AsyncBacktrace({ id: 4, name: 'new-thread', - tasks: [] + tasks: [], }, 'session-1'); provider.updateAsyncBacktrace(newThread); @@ -448,7 +448,7 @@ const emptyThread = new AsyncBacktrace({ id: 1, name: 'foo1', - tasks: [] + tasks: [], }, 'session-1'); provider.updateAsyncBacktrace(emptyThread); @@ -466,7 +466,7 @@ const updatedThreadFoo1 = new AsyncBacktrace({ id: 1, name: 'foo1-updated', - tasks: [] + tasks: [], }, 'session-1'); provider.updateAsyncBacktrace(updatedThreadFoo1); @@ -547,7 +547,7 @@ provider.updateAsyncBacktrace(threadFoo1); const newThread = (provider.getChildren() as AsyncBacktrace[]).find( - t => t.sessionId === 'session-1' && t.koid === 1 + t => t.sessionId === 'session-1' && t.koid === 1, )!; const newTaskA = newThread.children[0]; @@ -564,7 +564,7 @@ provider.updateAsyncBacktrace(threadFoo1); const newThread = (provider.getChildren() as AsyncBacktrace[]).find( - t => t.sessionId === 'session-1' && t.koid === 1 + t => t.sessionId === 'session-1' && t.koid === 1, )!; const newTaskA = newThread.children[0]; @@ -607,7 +607,9 @@ it('should fire event', function () { let eventsFired = 0; - provider.onDidChangeTreeData(() => { eventsFired++; }); + provider.onDidChangeTreeData(() => { + eventsFired++; + }); provider.reset('session-1'); assert.strictEqual(eventsFired, 1); @@ -622,7 +624,7 @@ // Simulate reattach + thread state update. provider.updateAsyncBacktrace(threadFoo1); const newThread = (provider.getChildren() as AsyncBacktrace[]).find( - t => t.sessionId === 'session-1' && t.koid === 1 + t => t.sessionId === 'session-1' && t.koid === 1, )!; const newTaskA = newThread.children[0];
diff --git a/src/test/suite/zxdb/console.test.ts b/src/test/suite/zxdb/console.test.ts index 77e3ba6..4a2ee51 100644 --- a/src/test/suite/zxdb/console.test.ts +++ b/src/test/suite/zxdb/console.test.ts
@@ -35,8 +35,11 @@ this.waitResolve = resolve; }); }; + public trigger() { - if (!this.waitResolve) { return; } + if (!this.waitResolve) { + return; + } this.waitResolve(); this.waitResolve = undefined; } @@ -128,7 +131,7 @@ return { address: '', family: '', - port: portNumber++ + port: portNumber++, }; }); server.listen.callsFake((listeningListener: () => void) => { @@ -136,7 +139,9 @@ return server; }); server.close.callsFake((callback?: ((err?: Error) => void)) => { - if (callback) { callback(); } + if (callback) { + callback(); + } return server; }); sandbox.stub(mutableNet, 'createServer').returns(server); @@ -144,9 +149,9 @@ const session = {} as vscode.DebugSession; zxdbPortNumber = undefined; zxdbException = ''; - return console.lauchZxdb(session, /*timeout ms*/ 50).then((portNumber) => { + return console.lauchZxdb(session, /* timeout ms */ 50).then((portNumber) => { zxdbPortNumber = portNumber; - }).catch(err => { + }).catch((err) => { assert.strictEqual(err instanceof Error, true); zxdbException = (err as Error).message.toLowerCase(); }); @@ -315,6 +320,5 @@ assert.deepStrictEqual(socketDestroyCallCount, socketConnectCallCount); assert.deepStrictEqual(zxdbProcessesRunning, [false, false]); }); - }); });
diff --git a/src/test_controller/discovery.ts b/src/test_controller/discovery.ts index 8672dfd..842ac11 100644 --- a/src/test_controller/discovery.ts +++ b/src/test_controller/discovery.ts
@@ -24,13 +24,13 @@ const testcaseDiscoveryQueue = TestcaseDiscoveryQueue.create(controller, setup.fx, savedState); controller.refreshHandler = async () => { // TODO(https://fxbug.dev/441360934): Re-enable watching when file watchers are properly managed. - await discoverTests(controller, /*watch=*/ false); + await discoverTests(controller, /* watch= */ false); }; controller.resolveHandler = async (testItem?: TestItem) => { if (!testItem) { // TODO(https://fxbug.dev/441360934): Re-enable watching when file watchers are properly managed. - await discoverTests(controller, /*watch=*/ false); + await discoverTests(controller, /* watch= */ false); } else { await testcaseDiscoveryQueue.discover(testItem); } @@ -113,7 +113,7 @@ * `TestItem` are discovered successfully. */ discover(testItem: TestItem): Promise<void> { - return new Promise(resolve => { + return new Promise((resolve) => { this.queue.push([testItem, resolve]); this.discoverFromQueue(); }); @@ -219,7 +219,8 @@ } const relativePath = testData.relativePath; const uri = relativePath ? - vscode.Uri.joinPath(workspaceFolder.uri, relativePath) : undefined; + vscode.Uri.joinPath(workspaceFolder.uri, relativePath) : + undefined; const testItem = controller.createTestItem(testData.name, testData.prettyName, uri); if (testData.os === 'fuchsia') { testItem.tags = [new vscode.TestTag('FuchsiaTest')]; @@ -270,7 +271,7 @@ // The .fx-build-dir file doesn't exist yet. logger.debug(`Unable to scan .fx-build-dir: ${String(ex)}`); } - }) + }), ); } @@ -298,7 +299,7 @@ () => fxListTestCases(controller, fx, testItem, true), () => fxListTestCases(controller, fx, testItem, false), (children: TestItem[]) => testItem.children.replace(children), - (children: TestItem[]) => cacheTestCases(savedState, testItem.id, children) + (children: TestItem[]) => cacheTestCases(savedState, testItem.id, children), ); } @@ -313,7 +314,7 @@ listTestCasesNoBuild: () => Promise<TestItem[]>, listTestCasesWithBuild: () => Promise<TestItem[]>, updateChildren: (children: TestItem[]) => void, - cacheResult: (children: TestItem[]) => Promise<void> + cacheResult: (children: TestItem[]) => Promise<void>, ) { // 1. Restore test cases from cache, if available. let children = queryCache(); @@ -362,8 +363,8 @@ controller: TestController, testId: string, ): TestItem[] | undefined { - return savedState.get<{id: string, label: string, uri?: string, tags: string[]}[]>(testId) - ?.map(({id, label, uri, tags}) => { + return savedState.get<{ id: string; label: string; uri?: string; tags: string[] }[]>(testId) + ?.map(({ id, label, uri, tags }) => { const child = controller.createTestItem( id, label, @@ -444,8 +445,8 @@ if (error) { throw new Error( - 'Test case discovery failed due to a non-zero exit code or JSON parsing error.' - + `\nCommand output:\n${process.rawOutput}` + 'Test case discovery failed due to a non-zero exit code or JSON parsing error.' + + `\nCommand output:\n${process.rawOutput}`, ); } return testCases;
diff --git a/src/test_controller/test_controller.ts b/src/test_controller/test_controller.ts index 91e47bb..6ebe7fa 100644 --- a/src/test_controller/test_controller.ts +++ b/src/test_controller/test_controller.ts
@@ -25,7 +25,7 @@ vscode.TestRunProfileKind.Run, (request) => { void runTest(controller, setup.fx, false, request); - } + }, ); controller.createRunProfile( @@ -35,7 +35,7 @@ void runTest(controller, setup.fx, true, request); }, false, - new vscode.TestTag('FuchsiaTest') + new vscode.TestTag('FuchsiaTest'), ); } @@ -63,7 +63,7 @@ controller: TestController, fx: Fx, debug: boolean, - request: vscode.TestRunRequest + request: vscode.TestRunRequest, ) { const run = controller.createTestRun(request); try { @@ -100,7 +100,7 @@ const message = new vscode.TestMessage( `Unable to attach zxdb to ${testURL}\n` + 'See "Fuchsia Extension" in the `Output` tab for more details.\n' + - 'Alternatively, you can run the test without debugging.' + 'Alternatively, you can run the test without debugging.', ); run.errored(testItem, message); continue;
diff --git a/src/tool_finder.ts b/src/tool_finder.ts index 3d54ca1..97db81e 100644 --- a/src/tool_finder.ts +++ b/src/tool_finder.ts
@@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. - import * as vscode from 'vscode'; import * as fs from 'fs'; import * as logger from './logger'; @@ -34,10 +33,10 @@ this.ffxInternal = new Ffx(cwd, undefined); this.fxInternal = new Fx(cwd, this.ffxInternal); - this.updateFfxPath(true).catch((err) => logger.error('unable to configure initial ffx location', undefined, err)); - vscode.workspace.onDidChangeConfiguration(event => { + this.updateFfxPath(true).catch(err => logger.error('unable to configure initial ffx location', undefined, err)); + vscode.workspace.onDidChangeConfiguration((event) => { if (event.affectsConfiguration(`${CONFIG_ROOT_NAME}.ffxPath`)) { - this.updateFfxPath(false).catch((err) => logger.error('unable to reconfigure ffx location', undefined, err)); + this.updateFfxPath(false).catch(err => logger.error('unable to reconfigure ffx location', undefined, err)); } }); }
diff --git a/src/workflow/build.ts b/src/workflow/build.ts index a26d873..7661d89 100644 --- a/src/workflow/build.ts +++ b/src/workflow/build.ts
@@ -64,7 +64,7 @@ category: string, collection: FuchsiaDiagnostics, progress: vscode.Progress<{ message?: string; increment?: number }>, - percentage: { value: number } + percentage: { value: number }, ) { const msg = new TextDecoder().decode(buffer); const match = BUILD_MATCHER.exec(msg); @@ -108,8 +108,8 @@ const percentage = { value: 0 }; const cmd = setup.fx.runAsync( ['build'], - (buffer) => handleData(buffer, 'fx build', collection, progress, percentage), - (buffer) => handleData(buffer, 'fx build', collection, progress, percentage) + buffer => handleData(buffer, 'fx build', collection, progress, percentage), + buffer => handleData(buffer, 'fx build', collection, progress, percentage), ); token.onCancellationRequested(() => { @@ -125,11 +125,11 @@ if (exitCode === 1) { logger.error('fx build stopped: failed [code=1]', 'fx build'); void window.showErrorMessage( - 'Build stopped, [see output for details](command:fuchsia.showOutput)' + 'Build stopped, [see output for details](command:fuchsia.showOutput)', ); return Promise.reject(new Error(`fx build failed with exit code ${exitCode}`)); } - } + }, ); }); } @@ -149,8 +149,8 @@ const percentage = { value: 0 }; const cmd = setup.fx.runAsync( ['ota', '--build'], - (buffer) => handleData(buffer, 'fx ota', collection, progress, percentage), - (buffer) => handleData(buffer, 'fx ota', collection, progress, percentage) + buffer => handleData(buffer, 'fx ota', collection, progress, percentage), + buffer => handleData(buffer, 'fx ota', collection, progress, percentage), ); token.onCancellationRequested(() => { @@ -161,10 +161,10 @@ progress.report({ message: '[(details)](command:fuchsia.showOutput)' }); const exitCode = await cmd?.exitCode; - return exitCode === 0 - ? Promise.resolve() - : Promise.reject(new Error(`fx ota failed with exit code ${exitCode}`)); - } + return exitCode === 0 ? + Promise.resolve() : + Promise.reject(new Error(`fx ota failed with exit code ${exitCode}`)); + }, ); }); } @@ -184,8 +184,8 @@ const percentage = { value: 0 }; const cmd = setup.fx.runAsync( ['ota', '--no-build'], - (buffer) => handleData(buffer, 'fx ota', collection, progress, percentage), - (buffer) => handleData(buffer, 'fx ota', collection, progress, percentage) + buffer => handleData(buffer, 'fx ota', collection, progress, percentage), + buffer => handleData(buffer, 'fx ota', collection, progress, percentage), ); token.onCancellationRequested(() => { @@ -196,10 +196,10 @@ progress.report({ message: '[(details)](command:fuchsia.showOutput)' }); const exitCode = await cmd?.exitCode; - return exitCode === 0 - ? Promise.resolve() - : Promise.reject(new Error(`fx ota failed with exit code ${exitCode}`)); - } + return exitCode === 0 ? + Promise.resolve() : + Promise.reject(new Error(`fx ota failed with exit code ${exitCode}`)); + }, ); }); } @@ -213,7 +213,7 @@ export function registerBuildCommands( _ctx: vscode.ExtensionContext, setup: Setup, - collection: FuchsiaDiagnostics + collection: FuchsiaDiagnostics, ) { registerFxBuild(setup, collection); registerFxoOta(setup, collection);
diff --git a/src/workflow/index.ts b/src/workflow/index.ts index 3179497..3d7d04b 100644 --- a/src/workflow/index.ts +++ b/src/workflow/index.ts
@@ -28,7 +28,7 @@ void window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'fx serve', - cancellable: true + cancellable: true, }, async (progress, token) => { const cmd = setup.fx.runAsync(['serve', '--background'], handleData, handleData); @@ -38,9 +38,9 @@ }); const exitCode = await cmd?.exitCode; - return exitCode === 0 - ? Promise.resolve() - : Promise.reject(new Error(`fx serve failed with exit code ${exitCode}`)); + return exitCode === 0 ? + Promise.resolve() : + Promise.reject(new Error(`fx serve failed with exit code ${exitCode}`)); /** callback to handle buffer from process */ function handleData(buffer: Buffer) { @@ -79,7 +79,7 @@ const msg = new TextDecoder().decode(data); const list = toList(msg.split('\n')); const selected = await window.showQuickPick(list, { - title: 'Select build directory' + title: 'Select build directory', }); const dir = selected?.label; @@ -100,8 +100,7 @@ })(); }, () => { // Ignore since err returns 'INFO: listing build directories:' - } + }, ); }); - }
diff --git a/src/workflow/problem_matcher.ts b/src/workflow/problem_matcher.ts index c39510c..51e37f9 100644 --- a/src/workflow/problem_matcher.ts +++ b/src/workflow/problem_matcher.ts
@@ -6,9 +6,9 @@ import * as vscode from 'vscode'; const buildSeverity: Record<string, vscode.DiagnosticSeverity> = { - 'error': vscode.DiagnosticSeverity.Error, - 'warn': vscode.DiagnosticSeverity.Warning, - 'note': vscode.DiagnosticSeverity.Information + error: vscode.DiagnosticSeverity.Error, + warn: vscode.DiagnosticSeverity.Warning, + note: vscode.DiagnosticSeverity.Information, }; interface ProblemMatcher { @@ -53,7 +53,7 @@ */ match(msg: string) { const matcher = this.fuchsiaProblemMatcher.find( - (item: { name: string; }) => item.name === 'cpp-rust-build'); + (item: { name: string }) => item.name === 'cpp-rust-build'); const pattern = new RegExp(matcher!.pattern.regexp, 'g'); const matches = msg.matchAll(pattern); @@ -78,7 +78,7 @@ parseInt(match[matcher!.pattern.column]) - 1), new vscode.Position(parseInt(match[matcher!.pattern.line]) - 1, parseInt(match[matcher!.pattern.column]) - 1)), - severity: buildSeverity[match[matcher!.pattern.severity]] + severity: buildSeverity[match[matcher!.pattern.severity]], }]]); } this.collection.set(this.entries);
diff --git a/src/workflow/set.ts b/src/workflow/set.ts index 9ffa589..050cb7f 100644 --- a/src/workflow/set.ts +++ b/src/workflow/set.ts
@@ -43,16 +43,16 @@ export function toList( output: string[], currentPick?: string, - placeholders?: Map<string, string> + placeholders?: Map<string, string>, ): vscode.QuickPickItem[] { const list = output - .filter((item) => item) - .map<vscode.QuickPickItem>((item) => ({ + .filter(item => item) + .map<vscode.QuickPickItem>(item => ({ label: item, detail: placeholders?.get(item), })); - const currentPickIndex = list.findIndex((item) => item.label === currentPick); + const currentPickIndex = list.findIndex(item => item.label === currentPick); if (currentPickIndex > -1) { const [currentItem] = list.splice(currentPickIndex, 1); currentItem.description = '(Current)'; @@ -84,14 +84,14 @@ */ remove(items: { title: string; value: string }[]): void { const removePackageFromGroup = (title: string, value: string) => { - const group = this.pkgHistory.find((p) => p.title === title); + const group = this.pkgHistory.find(p => p.title === title); if (group) { - group.value = group.value.filter((v) => v !== value); + group.value = group.value.filter(v => v !== value); } }; - items.forEach((item) => removePackageFromGroup(item.title, item.value)); + items.forEach(item => removePackageFromGroup(item.title, item.value)); // Remove empty groups - this.pkgHistory = this.pkgHistory.filter((p) => p.value.length > 0); + this.pkgHistory = this.pkgHistory.filter(p => p.value.length > 0); void this.memento.update('pkgHistory', this.pkgHistory); } @@ -153,7 +153,7 @@ } // Merge status packages into history - const historyMap = new Map(this.pkgHistory.map((pkg) => [pkg.title, pkg])); + const historyMap = new Map(this.pkgHistory.map(pkg => [pkg.title, pkg])); statusPkgs.forEach((statusPkg) => { const existingPkg = historyMap.get(statusPkg.title); // If the package group is new, add it to the history. @@ -189,8 +189,8 @@ const statusData = data as { buildInfo: { items: Record<string, - | { value: string; title?: string; notes?: string } - | Packages + | { value: string; title?: string; notes?: string } | + Packages >; }; }; @@ -210,7 +210,7 @@ status.packages.push(buildInfo[item] as Packages); } } - } + }, ); await process.exitCode; return status; @@ -221,7 +221,7 @@ */ async function promptForProduct( products: string[], - currentProduct: string + currentProduct: string, ): Promise<string | undefined> { const list = toList(products, currentProduct, PRODUCT_PLACEHOLDERS); const selected = await window.showQuickPick(list, { title: 'Select Product' }); @@ -233,7 +233,7 @@ */ async function promptForBoard( boards: string[], - currentBoard: string + currentBoard: string, ): Promise<string | undefined> { const list = toList(boards, currentBoard); const selected = await window.showQuickPick(list, { title: 'Select Board' }); @@ -244,7 +244,7 @@ * Prompts the user to select a compilation mode. */ async function promptForCompilation( - currentCompilation: string + currentCompilation: string, ): Promise<string | undefined> { const list = toList(Object.keys(CompilationModes), currentCompilation); const selected = await window.showQuickPick(list, { @@ -258,7 +258,7 @@ */ async function promptForPackages( pkgHistory: PkgHistory, - currentPackages: Packages[] + currentPackages: Packages[], ): Promise<vscode.QuickPickItem[] | undefined> { if (currentPackages.length === 0 && pkgHistory.get().length === 0) { return []; @@ -311,7 +311,7 @@ board?: string; compilation?: string; packages?: vscode.QuickPickItem[]; - } + }, ): boolean { const lastMode = CompilationModes[last.compilation as keyof typeof CompilationModes]; @@ -343,7 +343,7 @@ product: string, board: string, compilation: string, - packages: vscode.QuickPickItem[] + packages: vscode.QuickPickItem[], ): string[] { const args = [ 'set', @@ -374,8 +374,8 @@ async (_progress, token) => { const cmd = setup.fx.runAsync( args, - (buffer) => logger.info(new TextDecoder().decode(buffer), 'fx set'), - (buffer) => logger.error(new TextDecoder().decode(buffer), 'fx set') + buffer => logger.info(new TextDecoder().decode(buffer), 'fx set'), + buffer => logger.error(new TextDecoder().decode(buffer), 'fx set'), ); token.onCancellationRequested(() => { @@ -388,12 +388,12 @@ void window.showInformationMessage('fx set completed'); logger.info( 'fx set process executed successfully [exit code = 0]', - 'fx set' + 'fx set', ); } else { logger.warn(`fx set stopped with exit code: ${exitCode}`, 'fx set'); } - } + }, ); } @@ -401,7 +401,7 @@ export function registerSetCommand( _ctx: vscode.ExtensionContext, setup: Setup, - pkgHistory: PkgHistory + pkgHistory: PkgHistory, ) { registerCommandWithAnalyticsEvent( 'fuchsia.fx.set', @@ -409,7 +409,7 @@ product?: string, board?: string, compilation?: string, - packages?: vscode.QuickPickItem[] + packages?: vscode.QuickPickItem[], ) => { const status = await getStatus(setup); @@ -456,32 +456,32 @@ selectedProduct, selectedBoard, selectedCompilation, - selectedPackages + selectedPackages, ); runFuchsiaSet(setup, args); - } + }, ); } /** Registers the `fuchsia.clearPackageHistory` command. */ export function registerClearPackageHistoryCommand( _ctx: vscode.ExtensionContext, - pkgHistory: PkgHistory + pkgHistory: PkgHistory, ) { registerCommandWithAnalyticsEvent( 'fuchsia.clearPackageHistory', () => { pkgHistory.clear(); void window.showInformationMessage('Fuchsia package history cleared.'); - } + }, ); } /** Registers the `fuchsia.removePackageFromHistory` command. */ export function registerRemovePackageCommand( _ctx: vscode.ExtensionContext, - pkgHistory: PkgHistory + pkgHistory: PkgHistory, ) { registerCommandWithAnalyticsEvent( 'fuchsia.removePackageFromHistory', @@ -524,14 +524,14 @@ if (selected && selected.length > 0) { const itemsToRemove = selected - .map((item) => itemMap.get(item)) + .map(item => itemMap.get(item)) .filter((i): i is { title: string; value: string } => !!i); pkgHistory.remove(itemsToRemove); void window.showInformationMessage( - `Removed ${itemsToRemove.length} item(s) from package history.` + `Removed ${itemsToRemove.length} item(s) from package history.`, ); } - } + }, ); }
diff --git a/src/workflow/task_provider.ts b/src/workflow/task_provider.ts index e7b6064..89e8a96 100644 --- a/src/workflow/task_provider.ts +++ b/src/workflow/task_provider.ts
@@ -12,21 +12,21 @@ provideTasks(): vscode.Task[] { const buildTask = new vscode.Task( { - type: 'fuchsia', 'presentation': { - 'showReuseMessage': false, - } + type: 'fuchsia', presentation: { + showReuseMessage: false, + }, }, vscode.TaskScope.Workspace, 'fx build', 'Fuchsia Extension', new vscode.ShellExecution('fx build'), - '$cpp-rust-build' + '$cpp-rust-build', ); buildTask.group = vscode.TaskGroup.Build; return [buildTask]; }, resolveTask(task: vscode.Task): vscode.ProviderResult<vscode.Task> { return task; - } + }, }); }
diff --git a/src/zxdb/async_backtrace.ts b/src/zxdb/async_backtrace.ts index 7a04b40..27b4426 100644 --- a/src/zxdb/async_backtrace.ts +++ b/src/zxdb/async_backtrace.ts
@@ -42,10 +42,10 @@ constructor( { viewId, name, children }: { - viewId: string, - name: string, - children: AsyncTask[] - } + viewId: string; + name: string; + children: AsyncTask[]; + }, ) { this.viewId = viewId; this.name = name; @@ -110,6 +110,7 @@ private _onDidChangeTreeData: vscode.EventEmitter<AsyncObject | void> = new vscode.EventEmitter<AsyncObject | void>(); + readonly onDidChangeTreeData: vscode.Event<AsyncObject | void> = this._onDidChangeTreeData.event; /** @@ -130,16 +131,16 @@ public getTreeItem(element: AsyncObject): vscode.TreeItem { // Task names often come with verbose, less useful namespace prefixes, so truncate them to // better fit the relevant part of that name. - const label = element instanceof AsyncTask && element.name.length > kMaxLabelLength - ? '…' + element.name.slice(-(kMaxLabelLength - 1)) - : element.name; + const label = element instanceof AsyncTask && element.name.length > kMaxLabelLength ? + '…' + element.name.slice(-(kMaxLabelLength - 1)) : + element.name; const item = new vscode.TreeItem(label); item.id = element.viewId; if (element.children.length) { - item.collapsibleState = this.expandedViewIds.has(element.viewId) - ? vscode.TreeItemCollapsibleState.Expanded - : vscode.TreeItemCollapsibleState.Collapsed; + item.collapsibleState = this.expandedViewIds.has(element.viewId) ? + vscode.TreeItemCollapsibleState.Expanded : + vscode.TreeItemCollapsibleState.Collapsed; } else { item.collapsibleState = vscode.TreeItemCollapsibleState.None; } @@ -151,13 +152,13 @@ } else if (element instanceof AsyncTask && element.file) { item.description = `${path.basename(element.file)}${element.line ? `:${element.line}` : ''}`; - const filePath = path.isAbsolute(element.file) - ? element.file - : path.resolve(this.workspaceRoot, element.file); + const filePath = path.isAbsolute(element.file) ? + element.file : + path.resolve(this.workspaceRoot, element.file); const args: unknown[] = [vscode.Uri.file(filePath)]; if (element.line) { args.push({ - selection: new vscode.Range(element.line - 1, 0, element.line - 1, 0) + selection: new vscode.Range(element.line - 1, 0, element.line - 1, 0), }); } @@ -185,7 +186,7 @@ throw new Error('AsyncBacktrace.threadExists must be true.'); } const existingIndex = this.asyncBacktraces.findIndex( - t => t.sessionId === backtrace.sessionId && t.koid === backtrace.koid + t => t.sessionId === backtrace.sessionId && t.koid === backtrace.koid, ); // This `backtrace`'s thread is either new or has been updated. // Either add it to the async-backtrace pane, or update the existing entry if it's already @@ -210,7 +211,7 @@ throw new Error('AsyncBacktrace.threadExists must be false.'); } const existingIndex = this.asyncBacktraces.findIndex( - t => t.sessionId === thread.sessionId && t.koid === thread.koid + t => t.sessionId === thread.sessionId && t.koid === thread.koid, ); if (existingIndex === -1) { logger.error( @@ -223,7 +224,7 @@ // Prune `expandedViewIds`. this.expandedViewIds.delete(thread.viewId); - this.expandedViewIds.forEach(id => { + this.expandedViewIds.forEach((id) => { if (id.startsWith(`${thread.viewId}::`)) { this.expandedViewIds.delete(id); } @@ -253,7 +254,7 @@ */ public reset(sessionId: string) { this.asyncBacktraces = this.asyncBacktraces.filter(t => t.sessionId !== sessionId); - this.expandedViewIds.forEach(id => { + this.expandedViewIds.forEach((id) => { if (id.startsWith(`${sessionId}::`)) { this.expandedViewIds.delete(id); } @@ -271,11 +272,11 @@ */ export function setUpAsyncBacktrace(ctx: vscode.ExtensionContext, setup: Setup) { const provider = new AsyncBacktraceProvider( - setup.fx.fuchsiaDir - ?? vscode.workspace.workspaceFolders?.[0]?.uri.fsPath - ?? process.cwd() + setup.fx.fuchsiaDir ?? + vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? + process.cwd(), ); - const asyncBacktraceUpdateListener = vscode.debug.onDidReceiveDebugSessionCustomEvent(e => { + const asyncBacktraceUpdateListener = vscode.debug.onDidReceiveDebugSessionCustomEvent((e) => { if (e.session.type !== kSessionType || e.event !== kEventName) { return; } @@ -304,12 +305,12 @@ const expandListener = treeView.onDidExpandElement( (e: vscode.TreeViewExpansionEvent<AsyncObject>) => { provider.updateTreeItemExpanded(e.element, true); - } + }, ); const collapseListener = treeView.onDidCollapseElement( (e: vscode.TreeViewExpansionEvent<AsyncObject>) => { provider.updateTreeItemExpanded(e.element, false); - } + }, ); const debugSessionTerminateListener = vscode.debug.onDidTerminateDebugSession( @@ -317,7 +318,7 @@ if (session.type === kSessionType) { provider.reset(session.id); } - } + }, ); ctx.subscriptions.push(
diff --git a/src/zxdb/console.ts b/src/zxdb/console.ts index 8f50717..85d3493 100644 --- a/src/zxdb/console.ts +++ b/src/zxdb/console.ts
@@ -12,7 +12,6 @@ import { type ChildProcessWithoutNullStreams } from 'child_process'; import { Fx } from '../fx'; - const ZXDB_COMMAND_OPT = ['debug', '--new-agent', '--', '--enable-debug-adapter']; // Although `ffx debug connect` typically services requests within a second of launch, // `fx debug` might start a temporary package server, so use a 30 second timeout. @@ -57,13 +56,15 @@ public async lauchZxdb(session: vscode.DebugSession, timeoutOverride?: number) { let inputPort = await this.findFreePort(); // TODO(fxbug.dev/112695): Capture analytics for how frequently we relaunch. - return this.connectToZxdb(session, inputPort, /*errorOnBindFailure*/false, timeoutOverride) + return this.connectToZxdb(session, inputPort, /* errorOnBindFailure */false, timeoutOverride) .then(async (portNumber) => { - if (portNumber !== INVALID_SERVER_PORT) { return portNumber; } + if (portNumber !== INVALID_SERVER_PORT) { + return portNumber; + } // Find a free port, and try connecting again. inputPort = await this.findFreePort(); - return await this.connectToZxdb(session, inputPort, /*errorOnBindFailure*/true, + return await this.connectToZxdb(session, inputPort, /* errorOnBindFailure */true, timeoutOverride); }); } @@ -94,11 +95,15 @@ const exitAndCleanUp = () => { done = true; - if (socket) { socket.destroy(); } + if (socket) { + socket.destroy(); + } }; const onCloseCallback = (errorMsg: string) => { - if (done) { return; } + if (done) { + return; + } exitAndCleanUp(); if (!exceptionOnFailure) { @@ -118,14 +123,18 @@ logger.debug(`attempting to connect to localhost:${portNumber}`); socket.on('connect', () => { - if (done) { return; } + if (done) { + return; + } exitAndCleanUp(); logger.info('zxdb console has started.'); resolve(portNumber); }); const retryConnect = async () => { - if (done) { return; } + if (done) { + return; + } socket.destroy(); await this.sleep(this.retryWaitTimeMs ?? 1000); connect(); @@ -142,7 +151,9 @@ connect(); const timeoutTimer = setTimeout(() => { - if (done) { return; } + if (done) { + return; + } exitAndCleanUp(); // End the process that was started from this request zxdbProcess?.kill();
diff --git a/src/zxdb/index.ts b/src/zxdb/index.ts index 1a392a9..dde387a 100644 --- a/src/zxdb/index.ts +++ b/src/zxdb/index.ts
@@ -59,8 +59,7 @@ const cfg = config as vscode.DebugConfiguration | undefined; let promptText: string; if (cfg?.request === 'launch') { - promptText = - 'Launch(zxdb): Enter name of the process that will be launched.' + + promptText = 'Launch(zxdb): Enter name of the process that will be launched.' + ' Hint: For components, it\'s usually the component name.'; } else { promptText = 'Attach(zxdb): Enter name of the process to debug.' + @@ -71,7 +70,7 @@ return vscode.window.showInputBox({ placeHolder: '(e.g. hello-world-test)', value: '', - prompt: promptText + prompt: promptText, }); })); @@ -81,7 +80,7 @@ placeHolder: '(e.g. fx test hello-world-test)', value: '', prompt: - 'Launch(zxdb): Enter launch command. This will be run in the vscode terminal.' + 'Launch(zxdb): Enter launch command. This will be run in the vscode terminal.', }); })); @@ -90,7 +89,7 @@ return vscode.window.showInputBox({ placeHolder: '(e.g. scenic)', value: '', - prompt: 'Attach(zxdb): Enter a process or component identifier (name, koid, or URL).' + prompt: 'Attach(zxdb): Enter a process or component identifier (name, koid, or URL).', }); })); } @@ -125,7 +124,7 @@ type: 'zxdb', request: 'attach', process: process, - recursive: true + recursive: true, }); })); @@ -154,7 +153,7 @@ // Final updates to debug configuration can be done here. resolveDebugConfigurationWithSubstitutedVariables( _folder: WorkspaceFolder | undefined, - config: DebugConfiguration + config: DebugConfiguration, ): ProviderResult<DebugConfiguration> { // Return null if launch.json is empty or missing. if (!config.type && !config.request && !config.name) { @@ -233,6 +232,7 @@ } } } + dispose() { this.send.dispose(); } } @@ -266,12 +266,11 @@ this.ignoreError = true; const disconnectRequest = request as { arguments?: { restart?: boolean } }; this.restart = !!disconnectRequest?.arguments?.restart; - } if (request.command === 'terminate') { + } else if (request.command === 'terminate') { // Ignore errors reported after this. The connection is closed by the // backend and hence debug adapter reports connection loss errors. this.ignoreError = true; - } - else if (request.command === 'runInTerminal') { + } else if (request.command === 'runInTerminal') { const response = message as DebugProtocol.RunInTerminalResponse; if (response.body.shellProcessId) { this.launchPID = getChildPID(response.body.shellProcessId); @@ -344,7 +343,7 @@ function destroyZxdbLaunch(pid: number | undefined) { if (pid) { logger.info(`zxdb launch (PID:${pid}) is destroyed.`); - process.kill(-pid, 2); // SIGINT + process.kill(-pid, 2); // SIGINT } } @@ -354,7 +353,7 @@ function _runCommand(cmd: string, ...args: string[]): Promise<void> { return new Promise((resolve, reject) => { const process = spawn(cmd, args); - process.on('close', code => { + process.on('close', (code) => { if (code) { reject(new Error(`Command "${JSON.stringify([cmd, ...args])}" exited with code ${code}.`)); } else { @@ -362,7 +361,7 @@ } }); - process.on('error', err => { + process.on('error', (err) => { reject(new Error(`Failed to start command ${JSON.stringify([cmd, ...args])}: ${err}`)); }); });
diff --git a/syntax/cml.ts b/syntax/cml.ts index 4f34dae..753a216 100644 --- a/syntax/cml.ts +++ b/syntax/cml.ts
@@ -175,7 +175,7 @@ return keyValue( args.name, [ - arrayBlock([dictionaryBlock(args.inner)]) + arrayBlock([dictionaryBlock(args.inner)]), ], ); } @@ -268,7 +268,7 @@ pattern ??= [patterns.anyString()]; const keyPattern = key ?? patterns.oneFrom( patterns.named(name, 'keyword.control'), - patterns.oneString(name, 'keyword.control') + patterns.oneString(name, 'keyword.control'), ); return block({ name: `meta.meta-${name}-block`, @@ -318,9 +318,9 @@ pats: Pattern[], prefix: string, separator: string, - suffix: string + suffix: string, ): NamedPattern { - const re = pats.map((p) => p.toString()).join(separator); + const re = pats.map(p => p.toString()).join(separator); return new NamedPattern(prefix + re + suffix, getPatternNames(pats)); } @@ -379,7 +379,7 @@ boolValue: function (type?: string) { return patterns.oneFrom( patterns.named('\\btrue\\b', type ?? 'constant.language.true'), - patterns.named('\\bfalse\\b', type ?? 'constant.language.false') + patterns.named('\\bfalse\\b', type ?? 'constant.language.false'), ); }, @@ -465,7 +465,7 @@ * @returns An array of patterns. */ function valueOrArray( - pattern: (Pattern | TmPattern)[] = [patterns.anyString()] + pattern: (Pattern | TmPattern)[] = [patterns.anyString()], ): (Pattern | TmPattern)[] { return [...pattern, arrayBlock(pattern)]; } @@ -643,8 +643,8 @@ keyValue('subdir'), keyValue('as'), keyValue('scope', [arrayBlock(), patterns.anyString()]), - //TODO(fxbug.dev/109399): Narrow down the types of valid objects once documentation is - //provided in fxbug.dev/96705. + // TODO(fxbug.dev/109399): Narrow down the types of valid objects once documentation is + // provided in fxbug.dev/96705. keyValue('filter', [ include('meta-valid-array-block'), include('meta-valid-dictionary-block'), @@ -710,8 +710,8 @@ keyValue('dependency', [patterns.oneStringFrom('strong', 'weak_for_migration', 'weak')]), keyValue('rights', [arrayBlock(), patterns.anyString()]), keyValue('subdir'), - //TODO(fxbug.dev/109399): Narrow down the types of valid objects once documentation is - //provided in fxbug.dev/96705. + // TODO(fxbug.dev/109399): Narrow down the types of valid objects once documentation is + // provided in fxbug.dev/96705. keyValue('filter', [ include('meta-valid-array-block'), include('meta-valid-dictionary-block'), @@ -736,7 +736,7 @@ patterns.boolValue(), include('meta-valid-array-block'), include('meta-valid-dictionary-block'), - ], false) + ], false), ], }, @@ -748,7 +748,7 @@ patterns.boolValue(), include('meta-valid-array-block'), include('meta-valid-dictionary-block'), - ], true) + ], true), ], }, @@ -766,8 +766,8 @@ patterns.oneFrom( patterns.identifier('invalid.illegal'), patterns.anyString('invalid.illegal'), - ) - ) + ), + ), ], }, @@ -785,8 +785,8 @@ patterns.oneFrom( patterns.identifier('keyword.control'), patterns.anyString('keyword.control'), - ) - ) + ), + ), ], }, @@ -794,7 +794,7 @@ patterns: [ dictionaryBlock([ include('meta-valid-key-value-block'), - ], false) + ], false), ], }, @@ -802,14 +802,14 @@ patterns: [ dictionaryBlock([ include('meta-valid-key-value-block'), - ], true) + ], true), ], }, /////////////////////////////////////////////////////////////////////////////////////////////// // Comments /////////////////////////////////////////////////////////////////////////////////////////////// - comments: { + 'comments': { patterns: [ match('invalid.illegal.stray-comment-end', '\\*/.*\\n'), match('comment.line.documentation', '///.*\\n'),
diff --git a/syntax/fidl.ts b/syntax/fidl.ts index 20307a5..d4af8d1 100644 --- a/syntax/fidl.ts +++ b/syntax/fidl.ts
@@ -189,9 +189,9 @@ pats: Pattern[], prefix: string, separator: string, - suffix: string + suffix: string, ): NamedPattern { - const re = pats.map((p) => p.toString()).join(separator); + const re = pats.map(p => p.toString()).join(separator); return new NamedPattern(prefix + re + suffix, getPatternNames(pats)); } @@ -293,11 +293,11 @@ const NUMERIC_LITERAL = patterns.named( '-?\\b(?:(?:0(?:x|X)[0-9a-fA-F]*)|(?:0(?:b|B)[01]*)|(?:(?:[0-9]+\\.?[0-9]*)|(?:\\.[0-9]+))(?:(?:e|E)(?:\\+|-)?[0-9]+)?)\\b', - 'constant.numeric' + 'constant.numeric', ); const BOOLEAN_LITERAL = patterns.named( patterns.oneWordFrom('true', 'false'), - 'constant.language' + 'constant.language', ); const STRING_LITERAL = patterns.named('"(?:[^\\"]|\\.)*"', 'string.quoted.double'); @@ -305,7 +305,7 @@ const IDENTIFIER = '\\b[a-zA-Z_][0-9a-zA-Z_]*\\b'; const COMPOUND_IDENTIFIER = new NamedPattern( - `${IDENTIFIER}(?:\\.${IDENTIFIER})*` + `${IDENTIFIER}(?:\\.${IDENTIFIER})*`, ); const CONSTANT = patterns.oneFrom(LITERAL, COMPOUND_IDENTIFIER); @@ -327,7 +327,7 @@ const PRIMITIVE_TYPE = patterns.named( patterns.oneWordFrom(...primitiveTypes), - 'storage.type.basic' + 'storage.type.basic', ); const EOL = new NamedPattern('(;)', ['punctuation.terminator']); const LIBRARY_NAME = patterns.named(COMPOUND_IDENTIFIER, 'entity.name.type'); @@ -337,7 +337,7 @@ const ATTRIBUTE_TAG = patterns.named(patterns.seq( '@', - IDENTIFIER + IDENTIFIER, ), 'entity.other.attribute-name'); const MODIFIERS = patterns.named(patterns.zeroOrMore( @@ -345,7 +345,7 @@ patterns.word('strict'), patterns.word('flexible'), patterns.word('resource'), - ) + ), ), 'storage.type.modifier'); const ORDINAL = patterns.seq(NUMERIC_LITERAL, patterns.separator(':')); @@ -355,7 +355,7 @@ patterns.keyword('struct'), patterns.keyword('table'), patterns.keyword('enum'), - patterns.keyword('bits') + patterns.keyword('bits'), ); const SUBTYPE = patterns.seq(patterns.separator(':'), LAYOUT_REFERENCE); @@ -366,7 +366,7 @@ patterns.seq( patterns.separator(','), NUMERIC_CONSTANT, - ) + ), ))); // Checks @@ -375,7 +375,7 @@ MODIFIERS, LAYOUT_KIND, patterns.optional(SUBTYPE), - '{' + '{', ); COMPOUND_IDENTIFIER.assert('foo'); @@ -424,7 +424,7 @@ match('meta.library', patterns.seq(patterns.keyword('using'), LIBRARY_NAME, EOL)), match( 'meta.library', - patterns.seq(patterns.keyword('using'), LIBRARY_NAME, patterns.keyword('as'), LOCAL_TYPE, EOL) + patterns.seq(patterns.keyword('using'), LIBRARY_NAME, patterns.keyword('as'), LOCAL_TYPE, EOL), ), // Aliases: an aliased type can only be a layout reference, and cannot be re-parameterized @@ -481,7 +481,7 @@ ], /* eslint-disable @typescript-eslint/naming-convention */ repository: { - comments: { + 'comments': { patterns: [ match('invalid.illegal.stray-comment-end', '\\*/.*\\n'), match('comment.line.documentation', '///.*\\n'), @@ -509,13 +509,13 @@ match('meta.attribute.no-args', ATTRIBUTE_TAG), ], }, - attributes: { + 'attributes': { patterns: [ include('attribute-with-args'), include('attribute-no-args'), ], }, - method: { + 'method': { patterns: [ block({ name: 'meta.method', @@ -593,7 +593,7 @@ begin: patterns.seq( LAYOUT_REFERENCE, '<', - INLINE_LAYOUT_PREFIX + INLINE_LAYOUT_PREFIX, ), end: patterns.seq( // the rest of the layout parameters (i.e. array size) @@ -612,7 +612,7 @@ patterns.seq( LAYOUT_REFERENCE, patterns.optional(TYPE_PARAMETERS), - ) + ), ), ], }, @@ -639,7 +639,7 @@ patterns.seq( ':', patterns.named(CONSTANT, 'storage.type.constraint'), - ) + ), ), ], }, @@ -658,7 +658,7 @@ patterns: [ match( 'meta.layout.reserved-member', - patterns.seq(ORDINAL, patterns.keyword('reserved'), EOL) + patterns.seq(ORDINAL, patterns.keyword('reserved'), EOL), ), ], },
diff --git a/syntax/fuchsia-log.ts b/syntax/fuchsia-log.ts index 148a5c7..0228b0a 100644 --- a/syntax/fuchsia-log.ts +++ b/syntax/fuchsia-log.ts
@@ -141,9 +141,9 @@ pats: Pattern[], prefix: string, separator: string, - suffix: string + suffix: string, ): NamedPattern { - const re = pats.map((p) => p.toString()).join(separator); + const re = pats.map(p => p.toString()).join(separator); return new NamedPattern(prefix + re + suffix, getPatternNames(pats)); } @@ -187,7 +187,7 @@ const TAGS = new NamedPattern( `^${TIMESTAMP_TAG.toString()}${USER_TAGS.toString()}`, - getPatternNames([TIMESTAMP_TAG, USER_TAGS]) + getPatternNames([TIMESTAMP_TAG, USER_TAGS]), ); const logLevels = [