All files / src env.js

77.5% Statements 62/80
54.54% Branches 6/11
100% Functions 2/2
77.5% Lines 62/80

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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 811x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x             2x 2x 2x 2x 2x 2x     2x 2x 2x               2x 2x 2x 2x       2x 2x 2x 2x 2x 22x 20x 20x 22x 22x 2x 1x 1x 1x  
//@ts-check
import { isEmpty, set } from 'lodash-es';
import fs from 'node:fs/promises';
import process from 'node:process';
import path from 'node:path';
import ora from './ora-ext.js';
import { Gitlab } from '@gitbeaker/rest';
import { loadFile } from './utils.js';
import { fileURLToPath } from 'node:url';
 
const dirname = path.dirname(fileURLToPath(import.meta.url));
 
class Env {
  constructor() {
    /** @type {GitConfig.Config} */ // @ts-ignore
    this.config = null;
    /** @type {GitConfig.EnvOpts} */ // @ts-ignore
    this.opts = null;
    /** @type {OraExt.$OraExt} */ // @ts-ignore
    this.spin = null;
    /** @type {InstanceType<Gitlab<false>>} */ // @ts-ignore
    this.gitlab = null;
    /** @type {{ [key:string]: GitConfig.Plugin }} */
    this.plugins = {};
  }
 
  /**
   * @param {GitConfig.Config|string} config
   * @param {GitConfig.EnvOpts} opts
   */
  // eslint-disable-next-line complexity
  async load(config, opts) {
    this.opts = opts;
 
    if (typeof config === 'string') {
      this.config = await loadFile(config)
      .catch((err) => {
        console.log(err);
        throw new Error(`Configuration file not found: ${config}`);
      });
    }
    else {
      this.config = config;
    }
 
    /* override path from env */
    if (this.opts.path && !isEmpty(this.opts.path)) {
      this.config.path = this.opts.path;
    }
 
    /* null token means no token */
    if (this.opts.token === undefined) {
      this.opts.token = process.env['ACCESS_TOKEN'] ?? await loadFile(
        path.join(process.cwd(), '.token'))
      .catch((err) => {
        console.log(err);
        throw new Error(`Access token is required`);
      });
    }
 
    // @ts-ignore
    this.gitlab = new Gitlab({ host: this.opts.url, token: this.opts.token });
    if (!this.spin) {
      this.spin = ora('Loading...').start();
      set(this.spin, 'options.debug', this.opts.debug);
    }
 
    const pluginDir = path.join(dirname, '..', 'plugins');
 
    this.plugins = {};
    for (const file of await fs.readdir(pluginDir)) {
      if (!file.endsWith('.js')) { continue; }
      this.spin.debug('Loading plugin %s', file);
      var info = path.parse(file);
      this.plugins[info.name] = (await import(path.join(pluginDir, file)))?.default;
    }
  }
}
 
export default Env;