Home Reference Source Repository

es6/utils/Ensure.js

import * as Errors from '../Errors'
import which       from 'which'

/**
 * || Ensure.throws
 * this makes sure that process.exit(1) happens because something is wrong with our environment
 * 
 * @class Ensure
 */
export default class Ensure {
  /**
   * generates an error with `msg` and throws it
   *
   * @method     error
   * @param      {<type>}  msg     The msg
   */
  static error (msg) {
    throw new Error(msg)
    process.exit(1)
  }

  /**
   * throws
   *
   * @method     throws
   * @param      {<type>}  err     The err
   * 
   * @example
   * const required_value = config.thing || Ensure.throws(`missing config.thing`)
   */
  static throws (err) {
    throw err
    process.exit(1)
  }

  /**
   * checks to ensure an environment variable is set
   *
   * @method     env
   * @param      {<type>}  key     The environment variable to check for
   */
  static env (key) {
    return process.env[key] || Ensure.throws( new Errors.Environment_Error(key) )
  }

  /**
   * makes sure a given executable/bin can be found in our environment
   *
   * @param      {String}  exe     The executable we need
   * @return     {String}          the path where the executable lives  
   */
  static executable (exe) {
    try {
      return which.sync(exe)
    } catch (err) {
      Ensure.throws( new Errors.Executable_Error(exe) )
    }
  }
}