Code coverage report for father/lib/package.js

Statements: 100% (149 / 149)      Branches: 100% (71 / 71)      Functions: 96.15% (25 / 26)      Lines: 100% (143 / 143)      Ignored: none     

All files » father/lib/ » package.js
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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296    1 1 1 1 1 1 1 1 1 1 1 1   1                       1                   1         56 55 55 55 55 55 55 55       46 14   32 31         116 28   88 88       3 1   2 2       55 55 385   121 121 16 16 21 21   16   105           385           56 56 56 52     52 52     49 49 49 49       52 52   40 40 30 30   40   52       52 52 52   52   1 98 98 97     97 2 1     1   95         95 95     95 95     95 95 95 78     78 3       75 39 39 1   38       36 36   17 3 3 3   32       90 131     90   90     90                       1     1 95   72   8   15     1 75         1 52 52 52     52 51       52   22 1       22 10       52   63       1 52   8       1 98 98 74   24 23   1 1     1 85 85 170 421     85    
'use strict';
 
var fs = require('fs');
var path = require('path');
var join = path.join;
var dirname = path.dirname;
var extname = path.extname;
var relative = path.relative;
var requires = require('requires');
var imports = require('css-imports');
var Class = require('arale').Class;
var Events = require('arale').Events;
var debug = require('debug')('father:package');
var util = require('./util');
 
var defaults = {
  // config an extension as key, when that extension is found,
  // value will be added to deps
  extraDeps: {},
 
  // another entry point for parse
  entry: [],
 
  // ignore file or package when parseFiles
  ignore: []
};
 
var properties = [
  'name',
  'version',
  'main',
  'origin',
  'dependencies',
  'files',
  'output'
];
 
var Package = Class.create({
 
  Implements: [Events],
 
  initialize: function(dir, options) {
    if (!dir) throw new Error('miss the first argument');
    options = extend({}, defaults, options);
    this.father = options.father;
    this.options = options;
    this.dest = dir;
    this._packages = {};
    this._dependencies = [];
    this._exportProperty(properties);
  },
 
  set: function(pkg) {
    if (this.father) {
      return this.father.set(pkg);
    }
    if (!this._packages[pkg.id]) {
      this._packages[pkg.id] = pkg;
    }
  },
 
  get: function(id) {
    if (this.father) {
      return this.father.get(id);
    }
    if (!this._parsed && !this._parsing) this._parse();
    return id === this.id ? this : this._packages[id];
  },
 
  getPackages: function() {
    if (this.father) {
      return this.father.getPackages();
    }
    if (!this._parsed && !this._parsing) this._parse();
    return this._packages;
  },
 
  _exportProperty: function(keys) {
    var that = this;
    keys.forEach(function(key) {
      var prop = {
        get: function() {
          if (!that._parsed && !that._parsing) that._parse();
          if (key === 'dependencies') {
            var deps = {};
            that._dependencies.forEach(function(id) {
              var pkg = that.get(id);
              deps[pkg.name] = pkg;
            });
            return deps;
          } else {
            return that._pkg[key];
          }
        },
        configurable: true
      };
 
      Object.defineProperty(that, key, prop);
    });
  },
 
  _parse: function() {
    // start
    debug('*start parse %s', this.dest);
    this._parsing = true;
    this._pkg = this.readPackage();
    this.id = this._pkg.id;
 
    // parsing
    this._parsePkgDeps();
    this._parseFiles();
 
    // end
    this._parsed = true;
    this._parsing = false;
    debug('* end  parse %s', this.dest);
    return this;
  },
 
  _parsePkgDeps: function() {
    var Self = this.constructor, deps = this._pkg.dependencies;
    Object.keys(deps)
      .forEach(function(name) {
        var sub = deps[name];
        if (!this.get(sub.id)) {
          var opt = extend({}, this.options, {father: this});
          this.set(new Self(sub.dest, opt)._parse());
        }
        this._dependencies.push(sub.id);
      }.bind(this));
    debug('_parsePkgDeps of pkg(%s) [%s]', this.id, Object.keys(deps));
  },
 
  _parseFiles: function() {
    var dest = this.dest, options = this.options;
    var pkg = this._pkg, files = pkg.files = {};
    var extraVal = getExtraVal(options.extraDeps);
 
    getEntry(this, options).forEach(lookupFiles);
 
    function lookupFiles(src, entry) {
      var deps = [];
      src = testFile(src, dest);
      var ext = extname(src).substring(1);
 
      // parsing or parsed
      if (files[src]) {
        if (!files[src].dependencies) {
          throw new Error('found ' + src + ' has recursive dependency');
        }
        // dependencies exist if file has been parsed,
        return files[src].dependencies;
      } else {
        files[src] = {};
      }
 
      // extension in extraDeps will be added to deps
      // E.g. a.handlebars should require `handlebars`
      var extraDeps = options.extraDeps;
      if (extraDeps[ext]) deps.push(extraDeps[ext]);
 
      // file dependencies
      var data = fs.readFileSync(join(dest, src)).toString();
      deps = deps.concat(getFileDeps(data, ext, options));
 
      // conbime with the dependencies of the dependent file
      var fileDeps = deps;
      deps = [];
      fileDeps.forEach(function(name) {
        deps.push(name);
 
        // ignore extraDeps, E.g. hanldebars
        if (~extraVal.indexOf(name)) {
          return deps.push(name);
        }
 
        // dependent packages
        if (!util.isRelative(name)) {
          var pkg_ = pkg.dependencies[name];
          if (!~options.ignore.indexOf(name) && !pkg_) {
            throw new Error(name + ' not found but required');
          }
          return deps.push(name);
        }
 
        // relative files
        name = util.resolvePath(name, src);
        var deps_ = lookupFiles(name, src)
          .map(function(it) {
            if (!util.isRelative(it)) return it;
            it = util.resolvePath(it, name);
            it = relative(dirname(src), it);
            return util.isRelative(it) ? it : './' + it;
          });
        deps = deps.concat(deps_);
      });
 
      // unique
      deps = deps.filter(function(item, index, arr) {
        return index === arr.indexOf(item);
      });
 
      files[src].dependencies = deps;
 
      debug('_parseFiles of pkg(%s): file %s, deps [%s]', pkg.id, src, deps);
 
      // css which is required by js don't return deps
      return extname(entry) === '.js' && ext === 'css' ? [] : deps;
    }
  },
 
  /*
    Method below can be overridden
  */
 
  readPackage: function() {}
 
});
 
module.exports = Package;
 
 
function getFileDeps(code, ext) {
  switch(ext) {
    case 'js':
      return requires(code).map(transform);
    case 'css':
      return imports(code).map(transform);
    default:
      return [];
  }
 
  function transform(item) {
    return item.path.replace(/\.js$/, '');
  }
}
 
// entry point of package
function getEntry(pkg, options) {
  var isFather = !pkg.father;
  var entry = [];
  pkg = pkg._pkg;
 
  // base on pkg.main
  if (fs.existsSync(join(pkg.dest, pkg.main))) {
    entry.push(pkg.main);
  }
 
  // only father package will concat option.entry and pkg.output
  if (isFather) {
    // base on options.entry
    if (Array.isArray(options.entry) && options.entry.length) {
      entry = entry.concat(options.entry);
    }
 
    // base on pkg.output
    if (Array.isArray(pkg.output) && pkg.output.length) {
      entry = entry.concat(pkg.output);
    }
  }
 
  return entry
    .filter(function(item, index, arr) {
      return index === arr.indexOf(item);
    });
}
 
function getExtraVal(extraDeps) {
  return Object.keys(extraDeps)
    .map(function(key) {
      return extraDeps[key];
    });
}
 
function testFile(src, cwd) {
  src = /\.js$/.test(src) ? src : src + '.js';
  if (fs.existsSync(join(cwd, src))) {
    return src;
  }
  if (fs.existsSync(join(cwd, src.replace(/\.js$/, '')))) {
    return src.replace(/\.js$/, '');
  }
  debug('%s not found', src);
  throw new Error(src + ' not found');
}
 
function extend(target) {
  var args = [].slice.call(arguments, 1);
  args.forEach(function(obj) {
    for (var i in obj) {
      target[i] = obj[i];
    }
  });
  return target;
}