All files / gitlab/src source.ts

100% Statements 8/8
100% Branches 0/0
100% Functions 5/5
100% Lines 8/8

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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                4x   4x             2x       1x                 1x                           1x   1x                 1x                  
import { KeyInfo, PartiallyRequired, SourceModule, getEnv } from '@refreshly/core';
import { rotatePersonalAccessToken } from './gitlab/personal-access-token';
 
export class GitLabSourceModule extends SourceModule {
  private options: PartiallyRequired<Omit<GitLabSourceModule.Options, keyof SourceModule.Options>, 'token'>;
  private token?: string;
 
  constructor({ token, prefix, targets, ...options }: GitLabSourceModule.Options) {
    super({ targets, prefix });
 
    this.options = {
      ...options,
      token: getEnv('token', token, 'GITLAB_TOKEN', 'GL_TOKEN'),
    };
  }
 
  get name(): string {
    return 'gitlab';
  }
 
  get originalKeyInfos(): KeyInfo[] {
    return [
      {
        name: 'GITLAB_TOKEN',
        value: this.options.token,
      },
    ];
  }
 
  async source(): Promise<KeyInfo[]> {
    this.token = await rotatePersonalAccessToken({
      token: this.options.token,
    });
 
    /*
     * GitLab doesn't *really* support deferring the deletion of the old token.
     * This results in a few issues...
     *
     * 1. We can't revert to the old token if a failure occurs
     * 2. We have to update the environment variable so that 'Gitlab.Target' can pick it up.
     *
     * As an aside, GitLab DOES have a create token endpoint, however its only usable by server admins making it effectively useless
     * https://docs.gitlab.com/ee/api/personal_access_tokens.html#create-a-personal-access-token-administrator-only
     */
    process.env.GITLAB_TOKEN = this.token;
 
    return [
      {
        name: 'GITLAB_TOKEN',
        value: this.token,
      },
    ];
  }
 
  async revert(): Promise<void> {
    throw new Error(`(${this.name}) Recovery isn't possible, please manually create a new token...`);
  }
}
 
export namespace GitLabSourceModule {
  export type Options = {
    token?: string;
  } & SourceModule.Options;
}