all files / require-dir-all/lib/ index.js

17.54% Statements 10/57
0% Branches 0/46
0% Functions 0/4
17.54% Lines 10/57
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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218                                                                                                                                                                                                                                                                                                                                                                                                                               
// See README.md for details.
 
// Inspired by require-all and require-dir packages:
// https://github.com/felixge/node-require-all
// https://github.com/aseemk/requireDir
 
'use strict';
 
var fs = require('fs'),
    path = require('path');
 
// Replacement for Object.assign() for node 0.10-0.12
var object_assign = require('./assign');
 
// Trick taken from https://github.com/aseemk/requireDir/blob/master/index.js
//
// make a note of the calling file's path, so that we can resolve relative
// paths. this only works if a fresh version of this module is run on every
// require(), so important: we clear the require() cache each time!
delete require.cache[__filename];
//
 
var parentModule = module.parent;
var parentFile   = parentModule.filename;
var parentDir    = path.dirname(parentFile);
 
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
/**
 * Require Module definition (passed to map function)
 *
 * @typedef {object} RequireModule
 * @property {string} filename     - filename with extension, without path
 * @property {string} ext          - file extension
 * @property {string} base         - filename without extension
 * @property {string} filepath     - full file path
 * @property {string} name         - module name
 * @property {{}} exports          - module's exports
 */
 
/**
 * Map function
 *
 * @callback RequireMap
 * @param {RequireModule} requireModule
 */
 
/**
 * Options for require-dir-all
 *
 * @typedef {object} RequireOptions
 * @property {boolean} [recursive=false]     - go recursively into subdirectories
 * @property {boolean} [indexAsParent=false] - exports of 'index' files will be added
 *                                     directly to object corresponding to the
 *                                     directory with this 'index' file, not to
 *                                     its child object named 'index'
 *                                     (as by default)
 * @property {RegExp} [excludeDirs]    - RegExp to exclude directories
 * @property {RegExp} [includeFiles]   - RegExp to include files
 * @property {RequireMap} [map]        - map function to be called for each require'd module
 */
 
/**
 * Check if the module to be excluded
 *
 * @param {RequireModule} reqModule
 * @param {RegExp} reIncludeFiles
 * @returns {boolean}
 */
function isExcludedFile(reqModule, reIncludeFiles) {
  return !! ( (reqModule.filepath === parentFile) ||   // Exclude require'ing file
  (reIncludeFiles && !reqModule.filename.match(reIncludeFiles)) ); // Exclude files non-matched to pattern includeFiles
}
 
 
/**
 * Check if the directory to be excluded
 *
 * @param {RequireModule} reqModule
 * @param {RegExp} reExcludeDirs
 * @returns {boolean}
 */
function isExcludedDir(reqModule, reExcludeDirs) {
  return  !! ( reExcludeDirs && reqModule.filename.match(reExcludeDirs) );
}
 
 
/**
 * Main function. Recursively go through directories and require modules according to options
 *
 * @param   {string}  absDir
 * @param   {RequireOptions} options
 * @returns {object}
 * @private
 */
function _requireDirAll(absDir, options) {
  var modules = {};
 
  var files = fs.readdirSync(absDir);
 
  for (var length=files.length, i=0; i<length; ++i) {
 
    var reqModule = {};
    reqModule.filename = files[i];                                         // full filename without path
    reqModule.ext      = path.extname(reqModule.filename);                 // file extension
    reqModule.base     = path.basename(reqModule.filename, reqModule.ext); // filename without extension
    reqModule.filepath = path.join(absDir, reqModule.filename);            // full filename with absolute path
 
    //console.log('reqModule:', reqModule);
 
    // If this is subdirectory, then descend recursively into it (excluding matching patter excludeDirs)
    if (fs.statSync(reqModule.filepath).isDirectory() &&
      options.recursive &&
      ! isExcludedDir(reqModule, options.excludeDirs) ) {
 
      // use filename (with extension) instead of base name (without extension)
      // to keep complete directory name for directories with '.', like 'dir.1.2.3'
      reqModule.name = reqModule.filename;
 
      // go recursively into subdirectory
      //if (typeof modules === 'undefined') {
      //  modules = {};
      //}
      modules[reqModule.name] = _requireDirAll(reqModule.filepath, options);
 
    } else if ( ! isExcludedFile(reqModule, options.includeFiles)) {
      reqModule.name    = reqModule.base;
      reqModule.exports = require(reqModule.filepath);
      if (options.map) {
        options.map(reqModule);
      }
 
      var source = reqModule.exports;
      var target = (reqModule.name === 'index' && options.indexAsParent) ? modules : modules &&  modules[ reqModule.name ];
 
      var sourceIsObject = (typeof source === 'object');
      var targetIsObject = (typeof target === 'object');
      //var targetUnassigned = (typeof target === 'undefined');
 
      if (sourceIsObject && targetIsObject) {
        if (Object.assign) {
          Object.assign(target, source);
        } else {
          object_assign(target, source);
        }
      } else //if (
      //(!sourceIsObject && !targetIsObject) || // if source and target both are not objects  or...
      //(targetUnassigned)   // if target is not yet assigned, we may assign any type to it
      //)
      {
        target = source;
        //} else {
        //  console.log('!!!! ' +
        //    '  source:', source,
        //    '  target:', target,
        //    '; sourceIsObject:', sourceIsObject,
        //    '; targetIsObject:', targetIsObject,
        //    '; targetUnassigned:', targetUnassigned,
        //    '');
        //  throw 'Not possible to mix objects with scalar or array values: ' +
        //  'filepath: '+ reqModule.filepath + '; ' +
        //  'modules: '+ JSON.stringify(modules) + '; ' +
        //  'exports: '+ JSON.stringify(reqModule.exports)
        //    ;
      }
 
      if (reqModule.name === 'index' && options.indexAsParent) {
        modules = target;
      } else {
        //if (typeof modules === 'undefined') {
        //  modules = {};
        //}
        modules[ reqModule.name ] = target;
      }
    }
 
  }
 
  return modules;
}
 
 
/**
 * Main entry point. Analyse input parameters and invoke main function _requireDirAll()
 *
 * @param { string||string[] } [relOrAbsDir]  - Directory or array of directories to 'require'
 * @param {RequireOptions} [options]          - Set of options
 * @returns {object || object[]}              - Returns object with require'd modules or array of such objects
 * @public
 */
module.exports = function requireDirAll(relOrAbsDir, options) {
 
  relOrAbsDir = relOrAbsDir || '.';
  options = options || {};
  options.recursive     = options.recursive     || false;
  options.indexAsParent = options.indexAsParent || false;
  options.includeFiles  = options.includeFiles  || /^.*\.(js|json|coffee)$/;
  options.excludeDirs   = options.excludeDirs   || /^(\.git|\.svn|node_modules)$/;
  options.map           = options.map           || null;
 
  var absDir;
 
  if (typeof relOrAbsDir === 'string') {
    absDir = path.resolve(parentDir, relOrAbsDir);
    //console.log('relOrAbsDir:', relOrAbsDir, '; options:', options);
    return _requireDirAll(absDir, options);
 
  } else { // Assume it is array
    var modulesArray = [];
    for (var length=relOrAbsDir.length, i=0; i<length; ++i) {
      //console.log('relOrAbsDir:', relOrAbsDir, '; options:', options);
      absDir = path.resolve(parentDir, relOrAbsDir[i]);
      modulesArray.push(_requireDirAll(absDir, options));
    }
    return modulesArray;
  }
};