All files index.js

83.33% Statements 20/24
50% Branches 6/12
100% Functions 4/4
95% Lines 19/20
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    1x 1x 1x                                     1x 1x 1x 1x 1x                 2x 2x                     1x 1x 1x 1x 1x 1x                   1x 1x       1x  
'use strict'
 
const Rule = require('counsel-rule')
const path = require('path')
const fs = require('fs-extra')
 
/**
 * Copies files into a project.
 * @class CopyRule
 * @extends {Rule}
 */
class CopyRule extends Rule {
 
  /**
   * Creates an instance of CopyRule.
   *
   * @param {object} opts
   * @param {string} opts.src absolute path to asset needing to be copied. yo can create
   * an absolute path at runtime by using `path.resolve(__dirname, '/rel/path/to/asset')`
   * @param {object} opts.dest see counsel.project#copy
   * @memberOf CopyRule
   */
  constructor (opts) {
    super(opts)
    const { src, dest } = opts
    Iif (!src) throw new Error('must provide a copy `src`')
    Iif (!dest) throw new Error('must provide a copy `dest`')
    Iif (!path.isAbsolute(src)) {
      throw new Error([
        'CopyRule `src` must be absolute.  see the nodejs docs for `path.resolve`',
        'on how to construct a full path from your CopyRule definition'
      ].join(' '))
    }
  }
 
  getAbsoluteDest (dest, counsel) {
    Eif (!path.isAbsolute(dest)) dest = path.join(counsel.targetProjectRoot, dest)
    return dest
  }
 
  /**
   * Does copying.
   * @override
   * @memberOf CopyRule
   * @param {Module} counsel
   * @returns {undefined}
   */
  async apply (counsel) {
    Rule.prototype.apply.apply(this, arguments)
    let { src, dest } = this.declaration
    dest = this.getAbsoluteDest(dest, counsel)
    const exists = await fs.exists(dest)
    Iif (exists && !counsel.forceApply) return null
    return fs.copy(src, dest, { overwrite: true })
  }
 
  /**
   * Checks that copy rule content is in place
   * @TODO for directories, test for file content present, vs just target dir
   * @param {Counsel} counsel
   * @memberOf CopyRule
   */
  check (counsel) {
    const dest = this.getAbsoluteDest(this.declaration.dest, counsel)
    return fs.exists(dest)
  }
}
 
module.exports = CopyRule