Skip to content

Commit

Permalink
Removes Cli.getInstance()
Browse files Browse the repository at this point in the history
  • Loading branch information
waldekmastykarz committed Dec 8, 2023
1 parent 01256d2 commit 6be3ddf
Show file tree
Hide file tree
Showing 828 changed files with 4,464 additions and 4,891 deletions.
4 changes: 2 additions & 2 deletions docs/docs/contribute/new-command/unit-tests.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Before we start with the test suite, we want to make sure that the basic functio
// ...
import sinon from 'sinon';
import auth from '../../../../Auth.js';
import { Cli } from '../../../../cli/Cli.js';
import { cli } from '../../../../cli/cli.js';
import { CommandInfo } from '../../../../cli/CommandInfo.js';
import { telemetry } from '../../../../telemetry.js';
import { pid } from '../../../../utils/pid.js';
Expand All @@ -68,7 +68,7 @@ describe(commands.GROUP_GET, () => {
sinon.stub(pid, 'getProcessName').returns('');
sinon.stub(session, 'getId').returns('');
auth.service.connected = true;
commandInfo = Cli.getCommandInfo(command);
commandInfo = cli.getCommandInfo(command);
});
});
```
Expand Down
5 changes: 2 additions & 3 deletions scripts/write-all-commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'fs';
import path from 'path';
import url, { pathToFileURL } from 'url';
import Command from '../dist/Command.js';
import { Cli } from '../dist/cli/Cli.js';
import { cli } from '../dist/cli/cli.js';
import { fsUtil } from '../dist/utils/fsUtil.js';

const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
Expand All @@ -11,7 +11,6 @@ const commandHelpFolder = path.join(commandsFolder, '..', '..', 'docs', 'docs',

async function loadAllCommands() {
const files = fsUtil.readdirR(commandsFolder);
const cli = Cli.getInstance();

await Promise.all(files.map(async (filePath) => {
const file = pathToFileURL(filePath).toString();
Expand All @@ -23,7 +22,7 @@ async function loadAllCommands() {
const command = await import(file);
if (command.default instanceof Command) {
const helpFilePath = path.relative(commandHelpFolder, getCommandHelpFilePath(command.default.name));
cli.commands.push(Cli.getCommandInfo(command.default, path.relative(commandsFolder, filePath), helpFilePath));
cli.commands.push(cli.getCommandInfo(command.default, path.relative(commandsFolder, filePath), helpFilePath));
}
}
}));
Expand Down
12 changes: 5 additions & 7 deletions src/Auth.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import authServer from './AuthServer.js';
import { CommandError } from './Command.js';
import { FileTokenStorage } from './auth/FileTokenStorage.js';
import { TokenStorage } from './auth/TokenStorage.js';
import { Cli } from './cli/Cli.js';
import { cli } from './cli/cli.js';
import { Logger } from './cli/Logger.js';
import request from './request.js';
import { accessToken } from "./utils/accessToken.js";
Expand Down Expand Up @@ -44,7 +44,6 @@ const mockTokenCachePlugin: msal.ICachePlugin = {
describe('Auth', () => {
let log: any[];
let auth: Auth;
let cli: Cli;
let response: DeviceCodeResponse;
let openStub: sinon.SinonStub;
let clipboardStub: sinon.SinonStub;
Expand Down Expand Up @@ -85,7 +84,6 @@ describe('Auth', () => {

beforeEach(() => {
log = [];
cli = Cli.getInstance();
auth = new Auth();
response = {
deviceCode: "",
Expand Down Expand Up @@ -114,7 +112,7 @@ describe('Auth', () => {
readFileSyncStub.restore();
initializeServerStub.restore();
sinonUtil.restore([
cli.config.get,
cli.getConfig().get,
request.get,
(auth as any).getClientApplication,
(auth as any).getDeviceCodeResponse,
Expand Down Expand Up @@ -384,7 +382,7 @@ describe('Auth', () => {
});

it('retrieves new access token using existing refresh token when refresh forced', (done) => {
const config = cli.config;
const config = cli.getConfig();
sinon.stub(config, 'get').callsFake((() => { }) as any);
const now = new Date();
now.setSeconds(now.getSeconds() + 1);
Expand Down Expand Up @@ -413,7 +411,7 @@ describe('Auth', () => {
});

it('retrieves access token using device code authentication flow when no refresh token available and no authType specified', (done) => {
const config = cli.config;
const config = cli.getConfig();
sinon.stub(config, 'get').callsFake((() => 'value'));
sinon.stub(auth as any, 'getClientApplication').callsFake(_ => publicApplication);
sinon.stub(tokenCache, 'getAllAccounts').callsFake(() => []);
Expand Down Expand Up @@ -463,7 +461,7 @@ describe('Auth', () => {
});

it('retrieves token using device code authentication flow when authType deviceCode specified', (done) => {
const config = cli.config;
const config = cli.getConfig();
sinon.stub(config, 'get').callsFake((() => 'value'));
sinon.stub(auth as any, 'getClientApplication').callsFake(_ => publicApplication);
sinon.stub(tokenCache, 'getAllAccounts').callsFake(() => []);
Expand Down
7 changes: 3 additions & 4 deletions src/Auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { CommandError } from './Command.js';
import { FileTokenStorage } from './auth/FileTokenStorage.js';
import { TokenStorage } from './auth/TokenStorage.js';
import { msalCachePlugin } from './auth/msalCachePlugin.js';
import { Cli } from './cli/Cli.js';
import { cli } from './cli/cli.js';
import { Logger } from './cli/Logger.js';
import config from './config.js';
import request from './request.js';
Expand Down Expand Up @@ -420,7 +420,6 @@ export class Auth {
await logger.logToStderr('');
}

const cli = Cli.getInstance();
cli.spinner.text = response.message;
cli.spinner.spinner = {
frames: ['🌶️ ']
Expand All @@ -432,11 +431,11 @@ export class Auth {
cli.spinner.start();
}

if (Cli.getInstance().getSettingWithDefaultValue<boolean>(settingsNames.autoOpenLinksInBrowser, false)) {
if (cli.getSettingWithDefaultValue<boolean>(settingsNames.autoOpenLinksInBrowser, false)) {
browserUtil.open(response.verificationUri);
}

if (Cli.getInstance().getSettingWithDefaultValue<boolean>(settingsNames.copyDeviceCodeToClipboard, false)) {
if (cli.getSettingWithDefaultValue<boolean>(settingsNames.copyDeviceCodeToClipboard, false)) {
// _clipboardy is never set before hitting this line, but this check
// is implemented so that we can support lazy loading
// but also stub it for testing
Expand Down
16 changes: 7 additions & 9 deletions src/Command.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import assert from 'assert';
import chalk from 'chalk';
import sinon from 'sinon';
import auth from './Auth.js';
import { Cli } from './cli/Cli.js';
import { cli } from './cli/cli.js';
import { Logger } from './cli/Logger.js';
import Command, {
CommandError
Expand Down Expand Up @@ -130,7 +130,6 @@ describe('Command', () => {
let telemetryCommandName: any;
let logger: Logger;
let loggerLogToStderrSpy: sinon.SinonSpy;
let cli: Cli;

before(() => {
sinon.stub(auth, 'restoreAuth').callsFake(() => Promise.resolve());
Expand All @@ -145,7 +144,6 @@ describe('Command', () => {
logToStderr: async () => { }
};
loggerLogToStderrSpy = sinon.spy(logger, 'logToStderr');
cli = Cli.getInstance();
});

beforeEach(() => {
Expand All @@ -170,7 +168,7 @@ describe('Command', () => {

it('returns true by default', async () => {
const cmd = new MockCommand2();
assert.strictEqual(await cmd.validate({ options: {} }, Cli.getCommandInfo(cmd)), true);
assert.strictEqual(await cmd.validate({ options: {} }, cli.getCommandInfo(cmd)), true);
});

it('removes optional arguments from command name', () => {
Expand Down Expand Up @@ -534,27 +532,27 @@ describe('Command', () => {

it('passes validation when csv output specified', async () => {
const cmd = new MockCommand2();
assert.strictEqual(await cmd.validate({ options: { output: 'csv' } }, Cli.getCommandInfo(cmd)), true);
assert.strictEqual(await cmd.validate({ options: { output: 'csv' } }, cli.getCommandInfo(cmd)), true);
});

it('passes validation when json output specified', async () => {
const cmd = new MockCommand2();
assert.strictEqual(await cmd.validate({ options: { output: 'json' } }, Cli.getCommandInfo(cmd)), true);
assert.strictEqual(await cmd.validate({ options: { output: 'json' } }, cli.getCommandInfo(cmd)), true);
});

it('passes validation when text output specified', async () => {
const cmd = new MockCommand2();
assert.strictEqual(await cmd.validate({ options: { output: 'text' } }, Cli.getCommandInfo(cmd)), true);
assert.strictEqual(await cmd.validate({ options: { output: 'text' } }, cli.getCommandInfo(cmd)), true);
});

it('passes validation when no output specified', async () => {
const cmd = new MockCommand2();
assert.strictEqual(await cmd.validate({ options: {} }, Cli.getCommandInfo(cmd)), true);
assert.strictEqual(await cmd.validate({ options: {} }, cli.getCommandInfo(cmd)), true);
});

it('fails validation when invalid output specified', async () => {
const cmd = new MockCommand2();
assert.notStrictEqual(await cmd.validate({ options: { output: 'invalid' } }, Cli.getCommandInfo(cmd)), true);
assert.notStrictEqual(await cmd.validate({ options: { output: 'invalid' } }, cli.getCommandInfo(cmd)), true);
});

it('handles option with @meid token and spaces', async () => {
Expand Down
23 changes: 10 additions & 13 deletions src/Command.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import os from 'os';
import auth from './Auth.js';
import GlobalOptions from './GlobalOptions.js';
import { Cli } from './cli/Cli.js';
import { CommandInfo } from './cli/CommandInfo.js';
import { CommandOptionInfo } from './cli/CommandOptionInfo.js';
import { Logger } from './cli/Logger.js';
import { cli } from './cli/cli.js';
import request from './request.js';
import { settingsNames } from './settingsNames.js';
import { telemetry } from './telemetry.js';
Expand Down Expand Up @@ -148,7 +148,7 @@ export default abstract class Command {
}

private async validateRequiredOptions(args: CommandArgs, command: CommandInfo): Promise<string | boolean> {
const shouldPrompt = Cli.getInstance().getSettingWithDefaultValue<boolean>(settingsNames.prompt, true);
const shouldPrompt = cli.getSettingWithDefaultValue<boolean>(settingsNames.prompt, true);

let prompted: boolean = false;
for (let i = 0; i < command.options.length; i++) {
Expand All @@ -165,7 +165,7 @@ export default abstract class Command {

if (!prompted) {
prompted = true;
Cli.error('🌶️ Provide values for the following parameters:');
cli.error('🌶️ Provide values for the following parameters:');
}

const answer = optionInfo.autocomplete !== undefined
Expand All @@ -176,7 +176,7 @@ export default abstract class Command {
}

if (prompted) {
Cli.error('');
cli.error('');
}

this.processOptions(args.options);
Expand All @@ -190,7 +190,7 @@ export default abstract class Command {
return true;
}

const shouldPrompt = Cli.getInstance().getSettingWithDefaultValue<boolean>(settingsNames.prompt, true);
const shouldPrompt = cli.getSettingWithDefaultValue<boolean>(settingsNames.prompt, true);
const argsOptions: string[] = Object.keys(args.options);

for (const optionSet of optionsSets.sort(opt => opt.runsWhen ? 0 : 1)) {
Expand Down Expand Up @@ -220,22 +220,22 @@ export default abstract class Command {
}

private async promptForOptionSetNameAndValue(args: CommandArgs, optionSet: OptionSet): Promise<void> {
Cli.error(`🌶️ Please specify one of the following options:`);
cli.error(`🌶️ Please specify one of the following options:`);

const selectedOptionName = await prompt.forSelection<string>({ message: `Option to use:`, choices: optionSet.options.map((choice: any) => { return { name: choice, value: choice }; }) });
const optionValue = await prompt.forInput({ message: `${selectedOptionName}:` });

args.options[selectedOptionName] = optionValue;
Cli.error('');
cli.error('');
}

private async promptForSpecificOption(args: CommandArgs, commonOptions: string[]): Promise<void> {
Cli.error(`🌶️ Multiple options for an option set specified. Please specify the correct option that you wish to use.`);
cli.error(`🌶️ Multiple options for an option set specified. Please specify the correct option that you wish to use.`);

const selectedOptionName = await prompt.forSelection({ message: `Option to use:`, choices: commonOptions.map((choice: any) => { return { name: choice, value: choice }; }) });

commonOptions.filter(y => y !== selectedOptionName).map(optionName => args.options[optionName] = undefined);
Cli.error('');
cli.error('');
}

private async validateOutput(args: CommandArgs): Promise<string | boolean> {
Expand Down Expand Up @@ -512,7 +512,6 @@ export default abstract class Command {
}

protected async showDeprecationWarning(logger: Logger, deprecated: string, recommended: string): Promise<void> {
const cli: Cli = Cli.getInstance();
if (cli.currentCommandName &&
cli.currentCommandName.indexOf(deprecated) === 0) {
const chalk = (await import('chalk')).default;
Expand All @@ -526,7 +525,6 @@ export default abstract class Command {
}

protected getUsedCommandName(): string {
const cli: Cli = Cli.getInstance();
const commandName: string = this.getCommandName();
if (!cli.currentCommandName) {
return commandName;
Expand Down Expand Up @@ -607,7 +605,6 @@ export default abstract class Command {

public async getCsvOutput(logStatement: any[], options: GlobalOptions): Promise<string> {
const { stringify } = await import('csv-stringify/sync');
const cli = Cli.getInstance();

if (logStatement && logStatement.length > 0 && !options.query) {
logStatement.map(l => {
Expand All @@ -627,7 +624,7 @@ export default abstract class Command {
return stringify(logStatement, {
header: cli.getSettingWithDefaultValue<boolean>(settingsNames.csvHeader, true),
escape: cli.getSettingWithDefaultValue(settingsNames.csvEscape, '"'),
quote: cli.config.get(settingsNames.csvQuote),
quote: cli.getConfig().get(settingsNames.csvQuote),
quoted: cli.getSettingWithDefaultValue<boolean>(settingsNames.csvQuoted, false),
// eslint-disable-next-line camelcase
quoted_empty: cli.getSettingWithDefaultValue<boolean>(settingsNames.csvQuotedEmpty, false)
Expand Down
5 changes: 2 additions & 3 deletions src/api.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { Cli, CommandOutput } from "./cli/Cli.js";
import { CommandOutput, cli } from "./cli/cli.js";

export async function executeCommand(commandName: string, options: any, listener?: {
stdout: (message: any) => void,
stderr: (message: any) => void,
}): Promise<CommandOutput> {
const cli = Cli.getInstance();
cli.loadAllCommandsInfo();
await cli.loadCommandFromArgs(commandName.split(' '));
if (!cli.commandToExecute) {
return Promise.reject(`Command not found: ${commandName}`);
}

return Cli.executeCommandWithOutput(cli.commandToExecute.command, { options: options ?? {} }, listener);
return cli.executeCommandWithOutput(cli.commandToExecute.command, { options: options ?? {} }, listener);
}
Loading

0 comments on commit 6be3ddf

Please sign in to comment.