Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add new env commands #290

Merged
merged 3 commits into from
Jul 2, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/plugin-serverless/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@
},
"serverless:deploy": {
"description": "deploys your local serverless project"
},
"serverless:env": {
"description": "retrieve and modify the environment variables for your deployment"
}
}
},
Expand Down
49 changes: 49 additions & 0 deletions packages/plugin-serverless/src/TwilioRunCommand.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const {
convertYargsOptionsToOclifFlags,
normalizeFlags,
createExternalCliOptions,
getRegionAndEdge,
} = require('./utils');

const { TwilioClientCommand } = require('@twilio/cli-core').baseCommands;

function createTwilioRunCommand(name, path, inheritedFlags = []) {
const { handler, cliInfo, describe } = require(path);
const { flags, aliasMap } = convertYargsOptionsToOclifFlags(cliInfo.options);

const commandClass = class extends TwilioClientCommand {
async run() {
await super.run();

const flags = normalizeFlags(this.flags, aliasMap, process.argv);

const externalOptions = createExternalCliOptions(
flags,
this.twilioClient
);

const { edge, region } = getRegionAndEdge(flags, this);
flags.region = region;
flags.edge = edge;

const opts = Object.assign({}, flags, this.args);

return handler(opts, externalOptions);
}
};

const inheritedFlagObject = inheritedFlags.reduce((current, flag) => {
return {
...current,
[flag]: TwilioClientCommand.flags[flag],
};
}, {});

Object.defineProperty(commandClass, 'name', { value: name });
commandClass.description = describe;
commandClass.flags = Object.assign(flags, inheritedFlagObject);

return commandClass;
}

module.exports = { createTwilioRunCommand };
7 changes: 7 additions & 0 deletions packages/plugin-serverless/src/commands/serverless/env/get.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const { createTwilioRunCommand } = require('../../../TwilioRunCommand');

module.exports = createTwilioRunCommand(
'EnvGet',
'twilio-run/dist/commands/env/env-get',
['profile']
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const { createTwilioRunCommand } = require('../../../TwilioRunCommand');

module.exports = createTwilioRunCommand(
'EnvImport',
'twilio-run/dist/commands/env/env-import',
['profile']
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const { createTwilioRunCommand } = require('../../../TwilioRunCommand');

module.exports = createTwilioRunCommand(
'EnvList',
'twilio-run/dist/commands/env/env-list',
['profile']
);
7 changes: 7 additions & 0 deletions packages/plugin-serverless/src/commands/serverless/env/set.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const { createTwilioRunCommand } = require('../../../TwilioRunCommand');

module.exports = createTwilioRunCommand(
'EnvSet',
'twilio-run/dist/commands/env/env-set',
['profile']
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const { createTwilioRunCommand } = require('../../../TwilioRunCommand');

module.exports = createTwilioRunCommand(
'EnvUnset',
'twilio-run/dist/commands/env/env-unset',
['profile']
);
85 changes: 85 additions & 0 deletions packages/plugin-serverless/tests/TwilioRunCommand.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
const { createTwilioRunCommand } = require('../src/TwilioRunCommand');

jest.mock(
'twilio-run/test-command',
() => {
return {
handler: jest.fn(),
describe: 'Some test description',
cliInfo: {
options: {
region: {
type: 'string',
hidden: true,
describe: 'Twilio API Region',
},
edge: {
type: 'string',
hidden: true,
describe: 'Twilio API Region',
},
username: {
type: 'string',
alias: 'u',
describe:
'A specific API key or account SID to be used for deployment. Uses fields in .env otherwise',
},
password: {
type: 'string',
describe:
'A specific API secret or auth token for deployment. Uses fields from .env otherwise',
},
'load-system-env': {
default: false,
type: 'boolean',
describe:
'Uses system environment variables as fallback for variables specified in your .env file. Needs to be used with --env explicitly specified.',
},
},
},
};
},
{ virtual: true }
);

const command = require('twilio-run/test-command');
const { convertYargsOptionsToOclifFlags } = require('../src/utils');
const TwilioClientCommand = require('@twilio/cli-core/src/base-commands/twilio-client-command');

describe('createTwilioRunCommand', () => {
test('should create a new class', () => {
const ResultCommand = createTwilioRunCommand(
'TestCommand',
'twilio-run/test-command'
);
expect(ResultCommand.name).toBe('TestCommand');
expect(ResultCommand.description).toBe(command.describe);
expect(ResultCommand.flags.toString()).toEqual(
convertYargsOptionsToOclifFlags(command.cliInfo.options).flags.toString()
);
});

test('should add base properties as defined', () => {
const ResultCommand = createTwilioRunCommand(
'TestCommand',
'twilio-run/test-command',
['profile']
);
expect(ResultCommand.name).toBe('TestCommand');
expect(ResultCommand.description).toBe(command.describe);
expect(ResultCommand.flags.profile.toString()).toEqual(
TwilioClientCommand.flags.profile.toString()
);
});

// takes too long in some runs. We should find a faster way.
// test('should call the handler', async () => {
// const ResultCommand = createTwilioRunCommand(
// 'TestCommand',
// 'twilio-run/test-command'
// );

// await ResultCommand.run(['--region', 'dev']);
// expect(command.handler).toHaveBeenCalled();
// });
});
15 changes: 15 additions & 0 deletions packages/serverless-api/src/api/utils/type-checks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Sid } from '../../types';

const SidRegEx = /^[A-Z]{2}[a-f0-9]{32}$/;

export function isSid(value: unknown): value is Sid {
if (typeof value !== 'string') {
return false;
}

if (value.length !== 34) {
return false;
}

return SidRegEx.test(value);
}
96 changes: 93 additions & 3 deletions packages/serverless-api/src/api/variables.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
/** @module @twilio-labs/serverless-api/dist/api */

import debug from 'debug';
import { TwilioServerlessApiClient } from '../client';
import {
EnvironmentVariables,
Sid,
Variable,
VariableList,
VariableResource,
} from '../types';
import { TwilioServerlessApiClient } from '../client';
import { getPaginatedResource } from './utils/pagination';
import { ClientApiError } from '../utils/error';
import { getPaginatedResource } from './utils/pagination';
import { isSid } from './utils/type-checks';

const log = debug('twilio-serverless-api:variables');

Expand Down Expand Up @@ -137,13 +139,15 @@ function convertToVariableArray(env: EnvironmentVariables): Variable[] {
* @param {string} environmentSid the environment the varibales should be set for
* @param {string} serviceSid the service the environment belongs to
* @param {TwilioServerlessApiClient} client API client
* @param {boolean} [removeRedundantOnes=false] whether to remove variables that are not passed but are currently set
* @returns {Promise<void>}
*/
export async function setEnvironmentVariables(
envVariables: EnvironmentVariables,
environmentSid: string,
serviceSid: string,
client: TwilioServerlessApiClient
client: TwilioServerlessApiClient,
removeRedundantOnes: boolean = false
): Promise<void> {
const existingVariables = await listVariablesForEnvironment(
environmentSid,
Expand Down Expand Up @@ -181,4 +185,90 @@ export async function setEnvironmentVariables(
});

await Promise.all(variableResources);

if (removeRedundantOnes) {
const removeVariablePromises = existingVariables.map(async (variable) => {
if (typeof envVariables[variable.key] === 'undefined') {
return deleteEnvironmentVariable(
variable.sid,
environmentSid,
serviceSid,
client
);
}
});
await Promise.all(removeVariablePromises);
}
}

/**
* Deletes a given variable from a given environment
*
* @export
* @param {string} variableSid the SID of the variable to delete
* @param {string} environmentSid the environment the variable belongs to
* @param {string} serviceSid the service the environment belongs to
* @param {TwilioServerlessApiClient} client API client instance
* @returns {Promise<boolean>}
*/
export async function deleteEnvironmentVariable(
variableSid: string,
environmentSid: string,
serviceSid: string,
client: TwilioServerlessApiClient
): Promise<boolean> {
try {
const resp = await client.request(
'delete',
`Services/${serviceSid}/Environments/${environmentSid}/Variables/${variableSid}`
);
return true;
} catch (err) {
log('%O', new ClientApiError(err));
throw err;
}
}

/**
* Deletes all variables matching the passed keys from an environment
*
* @export
* @param {string[]} keys the keys of the variables to delete
* @param {string} environmentSid the environment the variables belong to
* @param {string} serviceSid the service the environment belongs to
* @param {TwilioServerlessApiClient} client API client instance
* @returns {Promise<boolean>}
*/
export async function removeEnvironmentVariables(
keys: string[],
environmentSid: string,
serviceSid: string,
client: TwilioServerlessApiClient
): Promise<boolean> {
const existingVariables = await listVariablesForEnvironment(
environmentSid,
serviceSid,
client
);

const variableSidMap = new Map<string, Sid>();
existingVariables.forEach((variableResource) => {
variableSidMap.set(variableResource.key, variableResource.sid);
});

const requests: Promise<boolean>[] = keys.map((key) => {
const variableSid = variableSidMap.get(key);
if (isSid(variableSid)) {
return deleteEnvironmentVariable(
variableSid,
environmentSid,
serviceSid,
client
);
}
return Promise.resolve(true);
});

await Promise.all(requests);
return true;
}
Loading