All files / src/commands/logout logout.command.js

48.93% Statements 23/47
100% Branches 1/1
0% Functions 0/1
48.93% Lines 23/47

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 46 47 48193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x                                                 193x 193x  
import { z } from 'zod';
import { config, removeProfile } from '../../config/config.js';
import { defineCommand } from '../../lib/define-command.js';
import { defineOption } from '../../lib/define-option.js';
import { formatProfile } from '../../lib/profile.js';
import { styleText } from '../../lib/style-text.js';
import { Logger } from '../../logger.js';
 
export const logoutCommand = defineCommand({
  description: 'Logout from Clever Cloud',
  since: '1.0.0',
  options: {
    alias: defineOption({
      name: 'alias',
      aliases: ['a'],
      schema: z.string().optional(),
      description: 'Alias of the profile to log out',
      placeholder: 'alias',
    }),
  },
  async handler(options) {
    if (config.profiles.length === 0) {
      throw new Error(`No profile found, use ${styleText('red', 'clever login')} command`);
    }

    const [activeProfile] = config.profiles;
    const aliasToRemove = options.alias ?? activeProfile.alias;

    if (aliasToRemove === '$env') {
      throw new Error(
        `Cannot logout from environment-based profile, unset ${styleText('red', 'CLEVER_TOKEN')} and ${styleText('red', 'CLEVER_SECRET')} instead`,
      );
    }

    const profileToRemove = config.profiles.find((p) => p.alias === aliasToRemove);
    if (profileToRemove == null) {
      throw new Error(`Profile "${aliasToRemove}" not found.`);
    }

    const newActiveProfile = await removeProfile(aliasToRemove);
    Logger.printSuccess(`Logged out of profile ${styleText('green', formatProfile(profileToRemove))}`);

    if (newActiveProfile != null && newActiveProfile.alias !== activeProfile.alias) {
      Logger.printSuccess(`Switched active profile to ${styleText('green', formatProfile(newActiveProfile))}`);
    }
  },
});