Skip to content

Commit

Permalink
Move commands to constants and clean up circular imports (#116)
Browse files Browse the repository at this point in the history
* add interfaces to fix circular import

move commands to consts

* replace more string parts with consts

remove commented code

* remove OAuth strings

cleanup more unused code

* Update src/commands/configureLaunchDarklyEnvironment.ts

Co-authored-by: Henry Barrow <[email protected]>

* update string to const

---------

Co-authored-by: Henry Barrow <[email protected]>
  • Loading branch information
Dan O'Brien and ldhenry authored Feb 8, 2024
1 parent 92a7aef commit ff565d0
Show file tree
Hide file tree
Showing 42 changed files with 532 additions and 314 deletions.
48 changes: 26 additions & 22 deletions src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,24 @@ const axios = require('axios').default;
import axiosRetry from 'axios-retry';
import retry from 'axios-retry-after';

import { Configuration } from './configuration';
import { FlagLink, InstructionPatch, NewFlag, ProjectAPI, ReleasePhase, ReleasePipeline } from './models';
import {
FlagLink,
IConfiguration,
ILDExtensionConfiguration,
InstructionPatch,
ILaunchDarklyAuthenticationSession,
NewFlag,
ProjectAPI,
ReleasePhase,
ReleasePipeline,
} from './models';
import { Resource, Project, FeatureFlag, Environment, PatchOperation, PatchComment, Metric } from './models';
import { RepositoryRep } from 'launchdarkly-api-typescript';
import { LDExtensionConfiguration } from './ldExtensionConfiguration';
import { LaunchDarklyAuthenticationSession } from './providers/authProvider';
import { debuglog } from 'util';
import { legacyAuth } from './utils';
import { CMD_LD_CONFIG } from './utils/commands';
import { legacyAuth } from './utils/legacyAuth';
import { CONST_CONFIG_LD } from './utils/constants';

interface CreateOptionsParams {
method?: string;
Expand All @@ -39,7 +49,7 @@ axios.interceptors.response.use(
originalRequest._retry = true;
const session = (await authentication.getSession('launchdarkly', ['writer'], {
createIfNone: false,
})) as LaunchDarklyAuthenticationSession;
})) as ILaunchDarklyAuthenticationSession;
config.setSession(session);
originalRequest.headers['Authorization'] = `Bearer ${session.accessToken}`;
return axios(originalRequest);
Expand Down Expand Up @@ -83,10 +93,10 @@ axiosRetry(axios, { retries: 2, retryDelay: axiosRetry.exponentialDelay });

// LaunchDarklyAPI is a wrapper around request-promise-native for requesting data from LaunchDarkly's REST API. The caller is expected to catch all exceptions.
export class LaunchDarklyAPI {
private readonly config: Configuration;
private readonly ldConfig: LDExtensionConfiguration;
private readonly config: IConfiguration;
private readonly ldConfig: ILDExtensionConfiguration;

constructor(config: Configuration, ldConfig: LDExtensionConfiguration) {
constructor(config: IConfiguration, ldConfig: ILDExtensionConfiguration) {
this.config = config;
this.ldConfig = ldConfig;
}
Expand Down Expand Up @@ -146,13 +156,9 @@ export class LaunchDarklyAPI {
return project;
} catch (err) {
window
.showErrorMessage(
`[LaunchDarkly] Error getting Project: ${projectKey}\n${err}`,
'Configure LaunchDarkly Extension',
)
.showErrorMessage(`${CONST_CONFIG_LD} Error getting Project: ${projectKey}\n${err}`, CONST_CONFIG_LD)
.then((selection) => {
if (selection === 'Configure LaunchDarkly Extension')
commands.executeCommand('extension.configureLaunchDarkly');
if (selection === CONST_CONFIG_LD) commands.executeCommand(CMD_LD_CONFIG);
});
}
}
Expand Down Expand Up @@ -191,12 +197,11 @@ export class LaunchDarklyAPI {
console.log(err);
window
.showErrorMessage(
`[LaunchDarkly] Error getting Project: ${projectKey} Environment: ${envKey}\n${err}`,
'Configure LaunchDarkly Extension',
`${CONST_CONFIG_LD} Error getting Project: ${projectKey} Environment: ${envKey}\n${err}`,
CONST_CONFIG_LD,
)
.then((selection) => {
if (selection === 'Configure LaunchDarkly Extension')
commands.executeCommand('extension.configureLaunchDarkly');
if (selection === CONST_CONFIG_LD) commands.executeCommand(CMD_LD_CONFIG);
});
}
}
Expand All @@ -210,12 +215,11 @@ export class LaunchDarklyAPI {
} catch (err) {
window
.showErrorMessage(
`[LaunchDarkly] Error getting Metrics for Project: ${projectKey}\n${err}`,
'Configure LaunchDarkly Extension',
`${CONST_CONFIG_LD} Error getting Metrics for Project: ${projectKey}\n${err}`,
CONST_CONFIG_LD,
)
.then((selection) => {
if (selection === 'Configure LaunchDarkly Extension')
commands.executeCommand('extension.configureLaunchDarkly');
if (selection === CONST_CONFIG_LD) commands.executeCommand(CMD_LD_CONFIG);
});
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/commands/clearGlobalContext.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { commands, Disposable, window } from 'vscode';
import { extensionReload } from '../utils';
import { extensionReload } from '../generalUtils';
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';

export default async function globalClearCmd(config: LDExtensionConfiguration) {
Expand Down
5 changes: 3 additions & 2 deletions src/commands/configureLaunchDarkly.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { Disposable, ProgressLocation, window } from 'vscode';
import { ConfigurationMenu } from '../configurationMenu';
import { FlagStore } from '../flagStore';
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';
import { registerCommand } from '../utils';
import { CMD_LD_CONFIG } from '../utils/commands';
import { registerCommand } from '../utils/registerCommand';

export default function configureLaunchDarkly(config: LDExtensionConfiguration) {
const configureExtension: Disposable = registerCommand('extension.configureLaunchDarkly', async () => {
const configureExtension: Disposable = registerCommand(CMD_LD_CONFIG, async () => {
try {
const configurationMenu = new ConfigurationMenu(config);
await configurationMenu.configure();
Expand Down
56 changes: 26 additions & 30 deletions src/commands/configureLaunchDarklyEnvironment.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,32 @@
import { commands, Disposable, window } from 'vscode';
//import { sortNameCaseInsensitive } from '../api';
import { extensionReload } from '../utils';
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';
import { extensionReload } from '../generalUtils';
import { CMD_LD_CONFIG_ENV } from '../utils/commands';
import { ILDExtensionConfiguration } from '../models';
import { CONST_LD_PREFIX } from '../utils/constants';

export default async function configureEnvironmentCmd(config: LDExtensionConfiguration): Promise<Disposable> {
const configureEnvironmentCmd = commands.registerCommand(
'launchdarkly.configureLaunchDarklyEnvironment',
async () => {
try {
//const intConfig = config.getConfig();
const api = config.getApi();
if (!config.getConfig()) {
return;
}
const project = await api?.getProject(config.getConfig().project);
if (!project) {
window.showErrorMessage(`[LaunchDarkly] Please Configure LaunchDarkly Extension`);
return;
}
//const environments = project.environments.sort(sortNameCaseInsensitive);
const environments = project.environments.items;
const newEnvironment = await window.showQuickPick(environments.map((env) => env.key));
if (newEnvironment) {
await config.getConfig().update('env', newEnvironment, false);
await extensionReload(config, true);
}
} catch (err) {
console.log(err);
window.showErrorMessage(`[LaunchDarkly] ${err}`);
export default async function configureEnvironmentCmd(config: ILDExtensionConfiguration): Promise<Disposable> {
const configureEnvironmentCmd = commands.registerCommand(CMD_LD_CONFIG_ENV, async () => {
try {
const api = config.getApi();
if (!config.getConfig()) {
return;
}
},
);
const project = await api?.getProject(config.getConfig().project);
if (!project) {
window.showErrorMessage(`${CONST_LD_PREFIX} Please Configure LaunchDarkly Extension`);
return;
}
const environments = project.environments.items;
const newEnvironment = await window.showQuickPick(environments.map((env) => env.key));
if (newEnvironment) {
await config.getConfig().update('env', newEnvironment, false);
await extensionReload(config, true);
}
} catch (err) {
console.log(err);
window.showErrorMessage(`${CONST_LD_PREFIX} ${err}`);
}
});

config.getCtx().subscriptions.push(configureEnvironmentCmd);

Expand Down
9 changes: 5 additions & 4 deletions src/commands/createFlag.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Disposable } from 'vscode';
import { CreateFlagMenu } from '../createFlagMenu';
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';
import { registerCommand } from '../utils';
import { CMD_LD_CREATE_FLAG } from '../utils/commands';
import { registerCommand } from '../utils/registerCommand';
import { ILDExtensionConfiguration } from '../models';

export default function createFlagCmd(config: LDExtensionConfiguration): Disposable {
const createFlagCmd = registerCommand('launchdarkly.createFlag', async () => {
export default function createFlagCmd(config: ILDExtensionConfiguration): Disposable {
const createFlagCmd = registerCommand(CMD_LD_CREATE_FLAG, async () => {
const configurationMenu = new CreateFlagMenu(config);
await configurationMenu.collectInputs();
});
Expand Down
9 changes: 5 additions & 4 deletions src/commands/enableCodeLens.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Disposable, workspace } from 'vscode';
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';
import { registerCommand } from '../utils';
import { CMD_LD_ENABLE_LENS } from '../utils/commands';
import { registerCommand } from '../utils/registerCommand';
import { ILDExtensionConfiguration } from '../models';

export default function enableCodeLensConfig(config: LDExtensionConfiguration): Disposable {
const enableCodeLens: Disposable = registerCommand('launchdarkly.enableCodeLens', async () => {
export default function enableCodeLensConfig(config: ILDExtensionConfiguration): Disposable {
const enableCodeLens: Disposable = registerCommand(CMD_LD_ENABLE_LENS, async () => {
workspace.getConfiguration('launchdarkly').update('enableCodeLens', !config.getConfig().enableCodeLens);
config.getConfig().enableCodeLens = !config.getConfig().enableCodeLens;
});
Expand Down
2 changes: 1 addition & 1 deletion src/commands/evaluateFlag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import os from 'os';
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';
import { LDMultiKindContext, LDSingleKindContext } from '@launchdarkly/node-server-sdk';
import { YamlContextReader } from '../utils/contextYAML';
import { registerCommand } from '../utils';
import { registerCommand } from '../utils/registerCommand';

// Not officially implemented. Leaving for future decision.

Expand Down
15 changes: 9 additions & 6 deletions src/commands/flagActions.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { QuickPickItemKind, Disposable, commands, window } from 'vscode';
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';
import { FlagQuickPickItem, targetFlag } from './selectRule';
import { ToggleCache } from '../toggleCache';
import { flagCodeSearch, flagOffFallthroughPatch, registerCommand, toggleFlag } from '../utils';
import { flagOffFallthroughPatch, toggleFlag } from '../generalUtils';
import { CMD_LD_FLAG_ACTION, CMD_LD_OPEN_BROWSER } from '../utils/commands';
import { flagCodeSearch } from '../utils/flagCodeSearch';
import { registerCommand } from '../utils/registerCommand';
import { ILDExtensionConfiguration } from '../models';

const cache = new ToggleCache();

export default function flagCmd(config: LDExtensionConfiguration): Disposable {
const flagCmd = registerCommand('launchdarkly.quickFlag', async () => {
export default function flagCmd(config: ILDExtensionConfiguration): Disposable {
const flagCmd = registerCommand(CMD_LD_FLAG_ACTION, async () => {
const flags = await config.getFlagStore()?.allFlagsMetadata();
if (flags === undefined) {
// Errors would be handled in the flagStore
Expand Down Expand Up @@ -79,7 +82,7 @@ export default function flagCmd(config: LDExtensionConfiguration): Disposable {
const linkUrl = `${config.getSession().fullUri}/${config.getConfig().project}/${
config.getConfig().env
}/features/${flagWindow.value}`;
commands.executeCommand('launchdarkly.openBrowser', linkUrl);
commands.executeCommand(CMD_LD_OPEN_BROWSER, linkUrl);
break;
}
case 'Toggle Flag':
Expand All @@ -102,7 +105,7 @@ export default function flagCmd(config: LDExtensionConfiguration): Disposable {
return flagCmd;
}

function revealFlag(config: LDExtensionConfiguration, key: string) {
function revealFlag(config: ILDExtensionConfiguration, key: string) {
const node = config.getFlagView().flagNodes.filter((node) => node.flagKey === key)[0];
config.getFlagTreeProvider().reveal(node, { select: true, focus: true, expand: true });
}
4 changes: 2 additions & 2 deletions src/commands/generalCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import enableCodeLensConfig from './enableCodeLens';
import configureEnvironmentCmd from './configureLaunchDarklyEnvironment';
import selectRuleCmd from './selectRule';
import setMaintainerCmd from './setMaintainer';
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';
import { SetGlobalCmd } from './setGlobal';
import flagCmd from './flagActions';
import { ILDExtensionConfiguration } from '../models';

export default async function generalCommands(LDExtenConfig: LDExtensionConfiguration) {
export default async function generalCommands(LDExtenConfig: ILDExtensionConfiguration) {
const createFlag = createFlagCmd(LDExtenConfig);
const toggleFlagCmd = toggleFlagCtxCmd(LDExtenConfig);
const setMaintainerCmd1 = setMaintainerCmd(LDExtenConfig);
Expand Down
11 changes: 5 additions & 6 deletions src/commands/openLaunchDarkly.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { commands, Disposable, window } from 'vscode';
import { FLAG_KEY_REGEX } from '../providers';
import { kebabCase } from 'lodash';
import { FlagStore } from '../flagStore';
import { FeatureFlagConfig } from '../models';
import { FeatureFlagConfig, IFlagStore, ILDExtensionConfiguration } from '../models';
import * as url from 'url';
import opn = require('opn');
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';
import { CMD_LD_OPEN } from '../utils/commands';

export default function openInLdCmd(config: LDExtensionConfiguration): Disposable {
const openInLdCmd = commands.registerTextEditorCommand('launchdarkly.openInLaunchDarkly', async (editor) => {
export default function openInLdCmd(config: ILDExtensionConfiguration): Disposable {
const openInLdCmd = commands.registerTextEditorCommand(CMD_LD_OPEN, async (editor) => {
const flagKey = editor.document.getText(
editor.document.getWordRangeAtPosition(editor.selection.anchor, FLAG_KEY_REGEX),
);
Expand Down Expand Up @@ -52,7 +51,7 @@ export default function openInLdCmd(config: LDExtensionConfiguration): Disposabl
return openInLdCmd;
}

const openFlagInBrowser = async (config: LDExtensionConfiguration, flagKey: string, flagStore: FlagStore) => {
const openFlagInBrowser = async (config: ILDExtensionConfiguration, flagKey: string, flagStore: IFlagStore) => {
const { flag } = await flagStore.getFeatureFlag(flagKey);

// Default to first environment
Expand Down
14 changes: 7 additions & 7 deletions src/commands/selectRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { Disposable, ProgressLocation, QuickPickItem, QuickPickItemKind, window
import { YAMLIndividualTarget, YamlReader, YAMLRuleTarget } from '../utils/rulesYaml';
import { ToggleCache } from '../toggleCache';
import os from 'os';
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';
import { Dictionary, isArray } from 'lodash';
import crypto from 'crypto';
import { Clause, FeatureFlag, InstructionPatch } from '../models';
import { registerCommand } from '../utils';
import { Clause, FeatureFlag, ILDExtensionConfiguration, InstructionPatch } from '../models';
import { logDebugMessage } from '../utils/logDebugMessage';
import { CMD_LD_PICK_RULES } from '../utils/commands';
import { registerCommand } from '../utils/registerCommand';

const cache = new ToggleCache();
const revertLastCmd = {};
Expand All @@ -26,8 +26,8 @@ export interface FlagQuickPickItem extends QuickPickItem {
value: string;
}

export default function selectRuleCmd(config: LDExtensionConfiguration): Disposable {
const selectRuleCmd = registerCommand('launchdarkly.quickPickRules', async () => {
export default function selectRuleCmd(config: ILDExtensionConfiguration): Disposable {
const selectRuleCmd = registerCommand(CMD_LD_PICK_RULES, async () => {
const flags = await config.getFlagStore()?.allFlagsMetadata();
if (flags === undefined) {
// Errors would be handled in the flagStore
Expand Down Expand Up @@ -147,7 +147,7 @@ function removeRuleInstruction(
async function updateFlag(
flagWindow: FlagQuickPickItem,
cache: ToggleCache,
config: LDExtensionConfiguration,
config: ILDExtensionConfiguration,
instruction: InstructionPatch,
origFlag?: FeatureFlag,
): Promise<FeatureFlag | undefined> {
Expand Down Expand Up @@ -394,7 +394,7 @@ function generateRefFromClauses(clauses) {
export async function targetFlag(
flagWindow,
cache: ToggleCache,
config: LDExtensionConfiguration,
config: ILDExtensionConfiguration,
flags: Dictionary<FeatureFlag>,
) {
const addRemove: Array<FlagQuickPickItem> = [];
Expand Down
5 changes: 3 additions & 2 deletions src/commands/setGlobal.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { ExtensionContext, window } from 'vscode';
import { registerCommand } from '../utils';
import { CMD_LD_SET_GLOBAL_DEFAULT } from '../utils/commands';
import { registerCommand } from '../utils/registerCommand';

export function SetGlobalCmd(ctx: ExtensionContext) {
const proj = ctx.workspaceState.get('project');
const env = ctx.workspaceState.get('env');
const disposable = registerCommand('launchdarkly.setGlobalDefaults', () => {
const disposable = registerCommand(CMD_LD_SET_GLOBAL_DEFAULT, () => {
// The code you want to run when the command is executed
window
.showInformationMessage(
Expand Down
9 changes: 5 additions & 4 deletions src/commands/setMaintainer.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Disposable, window } from 'vscode';
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';
import { registerCommand } from '../utils';
import { CMD_LD_SET_MAINTAINER } from '../utils/commands';
import { registerCommand } from '../utils/registerCommand';
import { ILDExtensionConfiguration } from '../models';

// This function is only called from a location that already checks if a team is available.
// If that changes more logic needs to be moved here
export default function setMaintainerCmd(config: LDExtensionConfiguration): Disposable {
const setMaintainerCmd = registerCommand('launchdarkly.setMaintainer', async (args) => {
export default function setMaintainerCmd(config: ILDExtensionConfiguration): Disposable {
const setMaintainerCmd = registerCommand(CMD_LD_SET_MAINTAINER, async (args) => {
try {
const key = args;
if (key) {
Expand Down
6 changes: 4 additions & 2 deletions src/commands/setWorkspaceEnabled.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { LDExtensionConfiguration } from '../ldExtensionConfiguration';
import { extensionReload, registerCommand } from '../utils';
import { extensionReload } from '../generalUtils';
import { CMD_LD_ENABLE_WORKSPACE } from '../utils/commands';
import { registerCommand } from '../utils/registerCommand';

export function SetWorkspaceCmd(config: LDExtensionConfiguration) {
const disposable = registerCommand('launchdarkly.enableWorkspace', async () => {
const disposable = registerCommand(CMD_LD_ENABLE_WORKSPACE, async () => {
// The code you want to run when the command is executed
if (
config.getCtx().workspaceState.get('isDisabledForWorkspace') !== false ||
Expand Down
Loading

0 comments on commit ff565d0

Please sign in to comment.