All files / src/commands/env env.import-vars.command.js

62.22% Statements 28/45
100% Branches 1/1
0% Functions 0/1
62.22% Lines 28/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x                                   193x 193x  
import { updateEnvVar } from '@clevercloud/client/esm/api/v2/application.js';
import { validateName } from '@clevercloud/client/esm/utils/env-vars.js';
import { z } from 'zod';
import { defineArgument } from '../../lib/define-argument.js';
import { defineCommand } from '../../lib/define-command.js';
import { Logger } from '../../logger.js';
import * as Application from '../../models/application.js';
import { sendToApi } from '../../models/send-to-api.js';
import { aliasOption, appIdOrNameOption } from '../global.options.js';
 
export const envImportVarsCommand = defineCommand({
  description:
    'Add or update environment variables named <variable-names> (comma-separated), taking their values from the current environment',
  since: '2.0.0',
  options: {
    alias: aliasOption,
    app: appIdOrNameOption,
  },
  args: [
    defineArgument({
      schema: z.string(),
      description: 'Comma separated list of names of the environment variables',
      placeholder: 'variable-names',
    }),
  ],
  async handler(options, envNames) {
    const { alias, app: appIdOrName } = options;

    for (const envName of envNames) {
      const nameIsValid = validateName(envName);
      if (!nameIsValid) {
        throw new Error(`Environment variable name ${envName} is invalid`);
      }
    }

    const { ownerId, appId } = await Application.resolveId(appIdOrName, alias);

    for (const envName of envNames) {
      const value = process.env[envName] || '';
      await updateEnvVar({ id: ownerId, appId, envName }, { value }).then(sendToApi);
    }

    Logger.println('Your environment variables have been successfully saved');
  },
});