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

[cli] optional override of existing environment variables #11348

Merged
merged 7 commits into from
Apr 10, 2024
Merged
13 changes: 9 additions & 4 deletions packages/cli/src/commands/env/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { isAPIError } from '../../util/errors-ts';
type Options = {
'--debug': boolean;
'--sensitive': boolean;
'--yes': boolean;
mountainash marked this conversation as resolved.
Show resolved Hide resolved
};

export default async function add(
Expand Down Expand Up @@ -91,7 +92,7 @@ export default async function add(
);
const choices = envTargetChoices.filter(c => !existing.has(c.value));

if (choices.length === 0) {
if (choices.length === 0 && !opts['--yes']) {
output.error(
`The variable ${param(
envName
Expand Down Expand Up @@ -146,6 +147,7 @@ export default async function add(
}

const type = opts['--sensitive'] ? 'sensitive' : 'encrypted';
const upsert = opts['--yes'] ? 'true' : '';

const addStamp = stamp();
try {
Expand All @@ -154,6 +156,7 @@ export default async function add(
output,
client,
project.id,
upsert,
type,
envName,
envValue,
Expand All @@ -170,9 +173,11 @@ export default async function add(

output.print(
`${prependEmoji(
`Added Environment Variable ${chalk.bold(
envName
)} to Project ${chalk.bold(project.name)} ${chalk.gray(addStamp())}`,
`${
opts['--yes'] ? 'Overrode' : 'Added'
} Environment Variable ${chalk.bold(envName)} to Project ${chalk.bold(
project.name
)} ${chalk.gray(addStamp())}`,
emoji('success')
)}\n`
);
Expand Down
4 changes: 4 additions & 0 deletions packages/cli/src/commands/env/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ export const envCommand: Command = {
`${packageName} env add DB_PASS production`,
],
},
{
name: 'Override an existing Environment Variable',
value: `${packageName} env add API_TOKEN --yes`,
},
{
name: 'Add a sensitive Environment Variable',
value: `${packageName} env add API_TOKEN --sensitive`,
Expand Down
8 changes: 6 additions & 2 deletions packages/cli/src/util/env/add-env-record.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ export default async function addEnvRecord(
output: Output,
client: Client,
projectId: string,
upsert: string,
type: ProjectEnvType,
key: string,
value: string,
targets: ProjectEnvTarget[],
gitBranch: string
): Promise<void> {
const actionWord = upsert ? 'Overriding' : 'Adding';
output.debug(
`Adding ${type} Environment Variable ${key} to ${targets.length} targets`
`${actionWord} ${type} Environment Variable ${key} to ${targets.length} targets`
);
const body: Omit<ProjectEnvVariable, 'id'> = {
type,
Expand All @@ -26,7 +28,9 @@ export default async function addEnvRecord(
target: targets,
gitBranch: gitBranch || undefined,
};
const url = `/v8/projects/${projectId}/env`;
const args = upsert ? `?upsert=${upsert}` : '';
const version = upsert ? 'v10' : 'v8';
mountainash marked this conversation as resolved.
Show resolved Hide resolved
const url = `/${version}/projects/${projectId}/env${args}`;
await client.fetch(url, {
method: 'POST',
body,
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/test/helpers/prepare.js
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,9 @@ module.exports = async function prepare(session, binaryPath, tmpFixturesDir) {
'project-sensitive-env-vars': {
'package.json': '{}',
},
'project-override-env-vars': {
'package.json': '{}',
},
'dev-proxy-headers-and-env': {
'package.json': JSON.stringify({}),
'server.js': `require('http').createServer((req, res) => {
Expand Down
66 changes: 66 additions & 0 deletions packages/cli/test/integration-2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,72 @@ test('add a sensitive env var', async () => {
);
});

test('override an existing env var', async () => {
const dir = await setupE2EFixture('project-override-env-vars');
const projectName = `project-override-env-vars-${
Math.random().toString(36).split('.')[1]
}`;

// remove previously linked project if it exists
await remove(path.join(dir, '.vercel'));

const vc = execCli(binaryPath, ['link'], {
cwd: dir,
env: {
FORCE_TTY: '1',
},
});

await setupProject(vc, projectName, {
buildCommand: `mkdir -p o && echo '<h1>custom hello</h1>' > o/index.html`,
outputDirectory: 'o',
});

await vc;

const link = require(path.join(dir, '.vercel/project.json'));
const options = {
env: {
VERCEL_ORG_ID: link.orgId,
VERCEL_PROJECT_ID: link.projectId,
},
};

// 1. Initial add
const addEnvCommand = execCli(
binaryPath,
['env', 'add', 'envVarName', 'production'],
options
);

await waitForPrompt(addEnvCommand, /What’s the value of [^?]+\?/);
addEnvCommand.stdin?.write('test\n');

const output = await addEnvCommand;

expect(output.exitCode, formatOutput(output)).toBe(0);
expect(output.stderr).toContain(
'Added Environment Variable envVarName to Project'
);

// 2. Override
const overrideEnvCommand = execCli(
binaryPath,
['env', 'add', 'envVarName', 'production', '--yes'],
options
);

await waitForPrompt(overrideEnvCommand, /What’s the value of [^?]+\?/);
overrideEnvCommand.stdin?.write('test\n');

const outputOverride = await overrideEnvCommand;

expect(outputOverride.exitCode, formatOutput(outputOverride)).toBe(0);
expect(outputOverride.stderr).toContain(
'Overrode Environment Variable envVarName to Project'
);
});

test('whoami with `VERCEL_ORG_ID` should favor `--scope` and should error', async () => {
if (!token) {
throw new Error('Shared state "token" not set.');
Expand Down