<commit_before>/**
 * Module for global and app configs.
 * @module kbox.core.config
 */

'use strict';

var path = require('path');
var os = require('os');
var fs = require('fs');
var env = require('./env.js');
var deps = require('./deps.js');
var log = require('./log.js');
var _ = require('lodash');

// Constants
var CONFIG_FILENAME = 'kalabox.json';
exports.CONFIG_FILENAME = CONFIG_FILENAME;

var DEFAULT_GLOBAL_CONFIG = {
  domain: 'kbox',
  engine: 'kalabox-engine-docker@0.10.3',
  engineRepo: 'kalabox',
  codeDir: 'code',
  services: 'kalabox-services-kalabox@0.10.3',
  apps: [
    'kalabox-app-pantheon@0.10.2'
  ],
  profile: 'standard',
  sharing: true,
  stats: {
    report: true,
    url: 'http://stats.kalabox.biz'
  },
  kboxRoot: ':home:/kalabox',
  kalaboxRoot: ':kboxRoot:',
  logLevel: 'debug',
  logLevelConsole: 'info',
  logRoot: ':sysConfRoot:/logs',
  downloadsRoot: ':sysConfRoot:/downloads',
  appsRoot: ':kboxRoot:/apps',
  appRegistry: ':sysConfRoot:/appRegistry.json',
  globalPluginRoot: ':kboxRoot:/plugins',
  globalPlugins: [
    'kalabox-core',
    'kalabox-dev',
    'kalabox-syncthing',
    'kalabox-app-pantheon'
  ],
  configSources: [
    'DEFAULT_GLOBAL_CONFIG'
  ],
  shareIgnores: [
    '*.7z',
    '*.bz2',
    '*.dmg',
    '*.gz',
    '*.iso',
    '*.jar',
    '*.rar',
    '*.tar',
    '*.tgz',
    '*.un~',
    '*.zip',
    '.*.swp',
    '.*DS_Store',
    '.DS_Store*',
    '._*',
    '.sass-cache',
    'Icon',
    'Thumbs.db',
    'ehthumbs.db'
  ]
};

var logDebug = log.debug;
var logInfo = log.info;

/*
 * Pretty print an object.
 */
var pp = function(obj) {
  return JSON.stringify(obj, null, '  ');
};

/*
 * Looks up a key of the config object and returns it.
 */
var lookupKey = function(config, keyToFind) {

  // Recursive function.
  var rec = function(o, prefix) {

    // Loop through each of the objects properties to find value.
    return _.find(o, function(val, key) {

      // Build namespaced name.
      var name = _.filter([prefix, key]).join('.');

      if (typeof val === 'string') {

        // If name of string value matches, return it.
        return (':' + name + ':') === keyToFind;

      } else if (typeof val === 'object') {

        // Recursively check object.
        return rec(val, name);

      } else {

        // Not a string or an object so just return false.
        return false;

      }

    });

  };

  // Init recursive function and return.
  return rec(config);

};

/*
 * Translate a value.
 */
var normalizeValue = exports.normalizeValue = function(config, v) {

  // Search value for regex matches.
  //var params = v.match(/:[a-zA-Z0-9-_]*:/g);
  var params;
  try {
    params = v.match(/:[a-zA-Z0-9-_]*:/g);
  }
  catch (err) {
    throw new Error(typeof v);
  }

  if (!params) {

    // No params were found, so just return original value.
    return v;

  } else {

    // Reduce list of params to final value.
    return _.reduce(params, function(acc, param) {

      // Get replacement value from config object based on param name.
      var replacementValue = lookupKey(config, param);

      if (!replacementValue) {

        // Replacement value was not found so just return value.
        return acc;

      } else {

        // Replace and return.
        return acc.replace(param, replacementValue);

      }

    }, v);

  }

};

/*
 * Walk the properties of the top level object, replacing strings
 * with other properties values.
 */
var normalize = exports.normalize = function(config) {

  // Recursive funciton.
  var rec = function(o) {

    // Loop through each property of the object.
    _.each(o, function(val, key) {

      if (typeof val === 'string') {

        // For string values normalize.
        o[key] = normalizeValue(config, val);

      } else if (typeof val === 'object') {

        // For object values recursively normalize.
        rec(val);

      }

    });

  };

  // Init recursive function with config.
  rec(config);

  // Return config.
  return config;

};

function sort(config) {
  var keys = Object.keys(config).sort();
  var retVal = {};
  for (var i = 0; i < keys.length; ++i) {
    var key = keys[i];
    retVal[key] = config[key];
  }
  return retVal;
}

// @todo: implement
var KEYS_TO_CONCAT = [
  'configSources',
  'shareIgnores'
];

function mixIn(a, b) {
  for (var key in b) {
    var shouldConcat = _.contains(KEYS_TO_CONCAT, key);
    if (shouldConcat) {
      // Concat.
      if (_.isArray(a[key]) && _.isArray(b[key])) {
        a[key] = _.uniq(a[key].concat(b[key]));
        a[key].sort();
      } else {
        a[key] = b[key];
      }
    } else {
      // Override.
      a[key] = b[key];
    }
  }
  return sort(normalize(a));
}
exports.mixIn = mixIn;

var getPackageJson = function() {
  return require(path.join(env.getSourceRoot(), 'package.json'));
};

/**
 * Gets the kalabox environment config.
 * @returns {object} config - The kalabox enviroment config.
 * @example
 * var envConfig = kbox.core.config.getEnvConfig();
 * // Print home directory to stdout.
 * console.log(envConfig.home);
 */
exports.getEnvConfig = function() {

  // Grab the kbox version
  var packageJson = getPackageJson();
  var kboxVersion = packageJson.version;

  // Grab the provision file path
  var provisionedFile = path.join(env.getSysConfRoot(), 'provisioned');

  // Grab the installed file
  var iF = path.join(env.getSysConfRoot(), 'installed.json');
  var cI = (fs.existsSync(iF)) ? require(iF) : {KALABOX_VERSION:kboxVersion};

  // Check whether we are in a binary or not
  var isBinary = (process.isPackaged || process.IsEmbedded) ? true : false;

  return {
    isBinary: isBinary,
    needsUpdates: (cI.KALABOX_VERSION !== kboxVersion),
    devMode: env.getDevMode(),
    provisioned: fs.existsSync(provisionedFile),
    home: env.getHomeDir(),
    os: {
      type: os.type(),
      platform: os.platform(),
      release: os.release(),
      arch: os.arch()
    },
    sysConfRoot: env.getSysConfRoot(),
    sysProviderRoot: env.getSysProviderRoot(),
    srcRoot: env.getSourceRoot(),
    version: kboxVersion,
    configSources: [
      'ENV_CONFIG'
    ]
  };
};

/**
 * Gets the default config. The default config is a combination of the
 *   environment config and a set of default config values.
 * @returns {object} config - The kalabox default config.
 * @example
 * var defaultConfig = kbox.core.config.getDefaultConfig();
 * // Print global plugins
 * defaultConfig.globalPlugins.forEach(function(plugin) {
 *   console.log(plugin)  ;
 * });
 */
exports.getDefaultConfig = function() {
  return mixIn(this.getEnvConfig(), DEFAULT_GLOBAL_CONFIG);
};

var getReleaseConfigFilepath = exports.getReleaseConfigFilepath = function() {
  return path.join(env.getSourceRoot(), CONFIG_FILENAME);
};

var getGlobalConfigFilepath = function() {
  return path.join(env.getSysConfRoot(), CONFIG_FILENAME);
};

var loadConfigFile = function(configFilepath) {
  var loadedConfigFile = require(configFilepath);
  loadedConfigFile.configSources = [configFilepath];
  return loadedConfigFile;
};

/**
 * Gets the global config. The global config is a combination of the
 *   environment config, the default config, and any values overriden
 *   in the $HOME/.kalabox/kalabox.json config file.
 * @returns {object} config - The kalabox global config.
 * @example
 * var globalConfig = kbox.core.config.getGlobalConfig();
 * // Print the entire global config.
 * console.log(JSON.stringify(globalConfig, null, '\t'));
 */
exports.getGlobalConfig = function() {
  var defaultConfig = this.getDefaultConfig();
  var filesToLoad = [
    getReleaseConfigFilepath(),
    getGlobalConfigFilepath()
  ];
  var globalConfig = _.reduce(filesToLoad, function(config, fileToLoad) {
    if (fs.existsSync(fileToLoad)) {
      var loadedConfigFile = loadConfigFile(fileToLoad);
      config = mixIn(config, loadedConfigFile);
    }
    return config;
  }, defaultConfig);
  return globalConfig;
};

exports.getAppConfigFilepath = function(app, config) {
  return path.join(config.appsRoot, app.name, CONFIG_FILENAME);
};

/**
 * Gets the app config for an app. The app config is a combination of the
 *   environment config, the default config, any values overriden in the
 *   $HOME/.kalabox/kalabox.json config file, and the kalabox.json config
 *   file in the app's root directory.
 * @arg {string} app - The name of the app you'd like to get the config for.
 * @arg {string} appRoot [optional] - Directory to load the
 * app's config file from.
 * @returns {object} config - The app's kalabox app config.
 * @example
 * var appConfig = kbox.core.config.getAppConfig('myapp');
 * // Print the entire app config.
 * console.log(JSON.stringify(appConfig, null, '\t'));
 */
exports.getAppConfig = function(app, appRoot) {
  // @todo: this is jank
  if (typeof app === 'string') {
    var appName = app;
    app = {name: appName};
  }

  var globalConfig = this.getGlobalConfig();

  if (!appRoot) {
    appRoot = path.join(globalConfig.appsRoot, app.name);
  }

  var appConfigFilepath = path.join(appRoot, CONFIG_FILENAME);
  var appConfigFile = require(appConfigFilepath);
  var appConfigOverride = function(key, val) {
    if (!appConfigFile[key]) {
      appConfigFile[key] = val;
    }
  };

  appConfigOverride('appRoot', appRoot);
  appConfigOverride('appCidsRoot', ':sysConfRoot:' + path.sep + 'appcids');
  appConfigOverride('codeRoot', ':appRoot:' + path.sep + ':codeDir:');
  var retVal = mixIn(globalConfig, appConfigFile);
  logDebug('CONFIG => App config loaded.', retVal);
  return retVal;
};
<commit_msg>UPDATE BACKENDS AND APPS FOR IMMINENT v0.10.3-alpha3 RELEASE<commit_after>/**
 * Module for global and app configs.
 * @module kbox.core.config
 */

'use strict';

var path = require('path');
var os = require('os');
var fs = require('fs');
var env = require('./env.js');
var deps = require('./deps.js');
var log = require('./log.js');
var _ = require('lodash');

// Constants
var CONFIG_FILENAME = 'kalabox.json';
exports.CONFIG_FILENAME = CONFIG_FILENAME;

var DEFAULT_GLOBAL_CONFIG = {
  domain: 'kbox',
  engine: 'kalabox-engine-docker@0.10.4',
  engineRepo: 'kalabox',
  codeDir: 'code',
  services: 'kalabox-services-kalabox@0.10.4',
  apps: [
    'kalabox-app-pantheon@0.10.3'
  ],
  profile: 'standard',
  sharing: true,
  stats: {
    report: true,
    url: 'http://stats.kalabox.biz'
  },
  kboxRoot: ':home:/kalabox',
  kalaboxRoot: ':kboxRoot:',
  logLevel: 'debug',
  logLevelConsole: 'info',
  logRoot: ':sysConfRoot:/logs',
  downloadsRoot: ':sysConfRoot:/downloads',
  appsRoot: ':kboxRoot:/apps',
  appRegistry: ':sysConfRoot:/appRegistry.json',
  globalPluginRoot: ':kboxRoot:/plugins',
  globalPlugins: [
    'kalabox-core',
    'kalabox-dev',
    'kalabox-syncthing',
    'kalabox-app-pantheon'
  ],
  configSources: [
    'DEFAULT_GLOBAL_CONFIG'
  ],
  shareIgnores: [
    '*.7z',
    '*.bz2',
    '*.dmg',
    '*.gz',
    '*.iso',
    '*.jar',
    '*.rar',
    '*.tar',
    '*.tgz',
    '*.un~',
    '*.zip',
    '.*.swp',
    '.*DS_Store',
    '.DS_Store*',
    '._*',
    '.sass-cache',
    'Icon',
    'Thumbs.db',
    'ehthumbs.db'
  ]
};

var logDebug = log.debug;
var logInfo = log.info;

/*
 * Pretty print an object.
 */
var pp = function(obj) {
  return JSON.stringify(obj, null, '  ');
};

/*
 * Looks up a key of the config object and returns it.
 */
var lookupKey = function(config, keyToFind) {

  // Recursive function.
  var rec = function(o, prefix) {

    // Loop through each of the objects properties to find value.
    return _.find(o, function(val, key) {

      // Build namespaced name.
      var name = _.filter([prefix, key]).join('.');

      if (typeof val === 'string') {

        // If name of string value matches, return it.
        return (':' + name + ':') === keyToFind;

      } else if (typeof val === 'object') {

        // Recursively check object.
        return rec(val, name);

      } else {

        // Not a string or an object so just return false.
        return false;

      }

    });

  };

  // Init recursive function and return.
  return rec(config);

};

/*
 * Translate a value.
 */
var normalizeValue = exports.normalizeValue = function(config, v) {

  // Search value for regex matches.
  //var params = v.match(/:[a-zA-Z0-9-_]*:/g);
  var params;
  try {
    params = v.match(/:[a-zA-Z0-9-_]*:/g);
  }
  catch (err) {
    throw new Error(typeof v);
  }

  if (!params) {

    // No params were found, so just return original value.
    return v;

  } else {

    // Reduce list of params to final value.
    return _.reduce(params, function(acc, param) {

      // Get replacement value from config object based on param name.
      var replacementValue = lookupKey(config, param);

      if (!replacementValue) {

        // Replacement value was not found so just return value.
        return acc;

      } else {

        // Replace and return.
        return acc.replace(param, replacementValue);

      }

    }, v);

  }

};

/*
 * Walk the properties of the top level object, replacing strings
 * with other properties values.
 */
var normalize = exports.normalize = function(config) {

  // Recursive funciton.
  var rec = function(o) {

    // Loop through each property of the object.
    _.each(o, function(val, key) {

      if (typeof val === 'string') {

        // For string values normalize.
        o[key] = normalizeValue(config, val);

      } else if (typeof val === 'object') {

        // For object values recursively normalize.
        rec(val);

      }

    });

  };

  // Init recursive function with config.
  rec(config);

  // Return config.
  return config;

};

function sort(config) {
  var keys = Object.keys(config).sort();
  var retVal = {};
  for (var i = 0; i < keys.length; ++i) {
    var key = keys[i];
    retVal[key] = config[key];
  }
  return retVal;
}

// @todo: implement
var KEYS_TO_CONCAT = [
  'configSources',
  'shareIgnores'
];

function mixIn(a, b) {
  for (var key in b) {
    var shouldConcat = _.contains(KEYS_TO_CONCAT, key);
    if (shouldConcat) {
      // Concat.
      if (_.isArray(a[key]) && _.isArray(b[key])) {
        a[key] = _.uniq(a[key].concat(b[key]));
        a[key].sort();
      } else {
        a[key] = b[key];
      }
    } else {
      // Override.
      a[key] = b[key];
    }
  }
  return sort(normalize(a));
}
exports.mixIn = mixIn;

var getPackageJson = function() {
  return require(path.join(env.getSourceRoot(), 'package.json'));
};

/**
 * Gets the kalabox environment config.
 * @returns {object} config - The kalabox enviroment config.
 * @example
 * var envConfig = kbox.core.config.getEnvConfig();
 * // Print home directory to stdout.
 * console.log(envConfig.home);
 */
exports.getEnvConfig = function() {

  // Grab the kbox version
  var packageJson = getPackageJson();
  var kboxVersion = packageJson.version;

  // Grab the provision file path
  var provisionedFile = path.join(env.getSysConfRoot(), 'provisioned');

  // Grab the installed file
  var iF = path.join(env.getSysConfRoot(), 'installed.json');
  var cI = (fs.existsSync(iF)) ? require(iF) : {KALABOX_VERSION:kboxVersion};

  // Check whether we are in a binary or not
  var isBinary = (process.isPackaged || process.IsEmbedded) ? true : false;

  return {
    isBinary: isBinary,
    needsUpdates: (cI.KALABOX_VERSION !== kboxVersion),
    devMode: env.getDevMode(),
    provisioned: fs.existsSync(provisionedFile),
    home: env.getHomeDir(),
    os: {
      type: os.type(),
      platform: os.platform(),
      release: os.release(),
      arch: os.arch()
    },
    sysConfRoot: env.getSysConfRoot(),
    sysProviderRoot: env.getSysProviderRoot(),
    srcRoot: env.getSourceRoot(),
    version: kboxVersion,
    configSources: [
      'ENV_CONFIG'
    ]
  };
};

/**
 * Gets the default config. The default config is a combination of the
 *   environment config and a set of default config values.
 * @returns {object} config - The kalabox default config.
 * @example
 * var defaultConfig = kbox.core.config.getDefaultConfig();
 * // Print global plugins
 * defaultConfig.globalPlugins.forEach(function(plugin) {
 *   console.log(plugin)  ;
 * });
 */
exports.getDefaultConfig = function() {
  return mixIn(this.getEnvConfig(), DEFAULT_GLOBAL_CONFIG);
};

var getReleaseConfigFilepath = exports.getReleaseConfigFilepath = function() {
  return path.join(env.getSourceRoot(), CONFIG_FILENAME);
};

var getGlobalConfigFilepath = function() {
  return path.join(env.getSysConfRoot(), CONFIG_FILENAME);
};

var loadConfigFile = function(configFilepath) {
  var loadedConfigFile = require(configFilepath);
  loadedConfigFile.configSources = [configFilepath];
  return loadedConfigFile;
};

/**
 * Gets the global config. The global config is a combination of the
 *   environment config, the default config, and any values overriden
 *   in the $HOME/.kalabox/kalabox.json config file.
 * @returns {object} config - The kalabox global config.
 * @example
 * var globalConfig = kbox.core.config.getGlobalConfig();
 * // Print the entire global config.
 * console.log(JSON.stringify(globalConfig, null, '\t'));
 */
exports.getGlobalConfig = function() {
  var defaultConfig = this.getDefaultConfig();
  var filesToLoad = [
    getReleaseConfigFilepath(),
    getGlobalConfigFilepath()
  ];
  var globalConfig = _.reduce(filesToLoad, function(config, fileToLoad) {
    if (fs.existsSync(fileToLoad)) {
      var loadedConfigFile = loadConfigFile(fileToLoad);
      config = mixIn(config, loadedConfigFile);
    }
    return config;
  }, defaultConfig);
  return globalConfig;
};

exports.getAppConfigFilepath = function(app, config) {
  return path.join(config.appsRoot, app.name, CONFIG_FILENAME);
};

/**
 * Gets the app config for an app. The app config is a combination of the
 *   environment config, the default config, any values overriden in the
 *   $HOME/.kalabox/kalabox.json config file, and the kalabox.json config
 *   file in the app's root directory.
 * @arg {string} app - The name of the app you'd like to get the config for.
 * @arg {string} appRoot [optional] - Directory to load the
 * app's config file from.
 * @returns {object} config - The app's kalabox app config.
 * @example
 * var appConfig = kbox.core.config.getAppConfig('myapp');
 * // Print the entire app config.
 * console.log(JSON.stringify(appConfig, null, '\t'));
 */
exports.getAppConfig = function(app, appRoot) {
  // @todo: this is jank
  if (typeof app === 'string') {
    var appName = app;
    app = {name: appName};
  }

  var globalConfig = this.getGlobalConfig();

  if (!appRoot) {
    appRoot = path.join(globalConfig.appsRoot, app.name);
  }

  var appConfigFilepath = path.join(appRoot, CONFIG_FILENAME);
  var appConfigFile = require(appConfigFilepath);
  var appConfigOverride = function(key, val) {
    if (!appConfigFile[key]) {
      appConfigFile[key] = val;
    }
  };

  appConfigOverride('appRoot', appRoot);
  appConfigOverride('appCidsRoot', ':sysConfRoot:' + path.sep + 'appcids');
  appConfigOverride('codeRoot', ':appRoot:' + path.sep + ':codeDir:');
  var retVal = mixIn(globalConfig, appConfigFile);
  logDebug('CONFIG => App config loaded.', retVal);
  return retVal;
};
<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/* global  __DEBUG__ */

var os = require('os');

var _ = require('lodash');
var async = require('async');

var serialDevice = require('../serialDevice');
var hidDevice = require('../hidDevice');
var usbDevice = require('../usbDevice');
var driverManager = require('../driverManager');
var builder = require('../objectBuilder')();
var hid = require('node-hid');
var usb = require('usb');
var SerialPort = require('serialport');

var dexcomDriver = require('../drivers/dexcom/dexcomDriver');
var oneTouchMiniDriver = require('../drivers/onetouch/oneTouchMiniDriver');
var abbottPrecisionXtra = require('../drivers/abbott/abbottPrecisionXtra');
var tandemDriver = require('../drivers/tandem/tandemDriver');
var insuletOmniPod = require('../drivers/insulet/insuletDriver');
var oneTouchUltra2 = require('../drivers/onetouch/oneTouchUltra2');
var oneTouchVerio = require('../drivers/onetouch/oneTouchVerio');
var oneTouchVerioIQ = require('../drivers/onetouch/oneTouchVerioIQ');
var abbottFreeStyleLite = require('../drivers/abbott/abbottFreeStyleLite');
var abbottFreeStyleLibre = require('../drivers/abbott/abbottFreeStyleLibre');
var bayerContourNext = require('../drivers/bayer/bayerContourNext');
var animasDriver = require('../drivers/animas/animasDriver');
var medtronicDriver = require('../drivers/medtronic/medtronicDriver');

var device = {
  log: require('bows')('Device')
};

var hostMap = {
  'darwin': 'mac',
  'win32' : 'win',
  'linux': 'linux',
};

device._deviceDrivers = {
  'Dexcom': dexcomDriver,
  'OneTouchMini': oneTouchMiniDriver,
  'AbbottPrecisionXtra': abbottPrecisionXtra,
  'InsuletOmniPod': insuletOmniPod,
  'Tandem': tandemDriver,
  'OneTouchUltra2': oneTouchUltra2,
  'OneTouchVerio': oneTouchVerio,
  'OneTouchVerioIQ': oneTouchVerioIQ,
  'AbbottFreeStyleLite': abbottFreeStyleLite,
  'AbbottFreeStyleFreedomLite': abbottFreeStyleLite,
  'AbbottFreeStyleLibre': abbottFreeStyleLibre,
  'BayerContourNext': bayerContourNext,
  'BayerContourNextUsb': bayerContourNext,
  'BayerContourUsb': bayerContourNext,
  'BayerContourNextLink': bayerContourNext,
  'Animas': animasDriver,
  'Medtronic': medtronicDriver
};

device._deviceComms = {
  'Dexcom': serialDevice,
  'OneTouchMini': serialDevice,
  'AbbottPrecisionXtra': serialDevice,
  'OneTouchUltra2': serialDevice,
  'OneTouchVerio': usbDevice,
  'OneTouchVerioIQ': serialDevice,
  'AbbottFreeStyleLite': serialDevice,
  'AbbottFreeStyleFreedomLite': serialDevice,
  'AbbottFreeStyleLibre': hidDevice,
  'Tandem': serialDevice,
  'BayerContourNext': hidDevice,
  'BayerContourNextUsb': hidDevice,
  'BayerContourUsb': hidDevice,
  'BayerContourNextLink': hidDevice,
  'Animas': serialDevice,
  'Medtronic': hidDevice
};

device._silentComms = {};
_.forEach(_.keys(device._deviceComms), function(driverId) {

  var comm = device._deviceComms[driverId];
  device._silentComms[driverId] = comm({silent: true});
  device._deviceComms[driverId] = comm();
});

// this is a cache for device information
// we need it so that what we learn in detect()
// can be used by process().
device._deviceInfoCache = {};

device.init = function(options, cb) {
  var self=this;
  self._defaultTimezone = options.defaultTimezone;
  self._driverManifests = self._getAllDriverManifests();
  self._api = options.api;
  self._version = options.version;
  self._groupId = options.targetId;
  self._os = hostMap[os.platform()];
  cb();
};

device._getAllDriverManifests = function() {
  var manifest = require('../../manifest.json');

  var usbDevicesPermission = _.find(manifest.permissions, function(permission) {
    return permission.usbDevices;
  });
  return _.reduce(usbDevicesPermission.usbDevices, function(acc, usbDevice) {
    acc[usbDevice.driverId] = usbDevice;
    return acc;
  }, {});
};

device.getDriverManifests = function() {
  return _.cloneDeep(this._driverManifests);
};

device.getDriverIds = function() {
  return _.keys(this._driverManifests);
};

device.getDriverManifest = function(driverId) {
  var driverManifest = this._driverManifests[driverId];
  if (!driverManifest) {
    throw new Error('Could not find driver manifest for "' + driverId + '"');
  }
  return driverManifest;
};

device.detectHelper = function(driverId, options, cb) {
  // Detect can run on a loop, so don't pollute the console with logging
  options.silent = true;
  var dm = this._createDriverManager(driverId, options);
  dm.detect(driverId, cb);
};

device._createDriverManager = function(driverId, options) {
  var drivers = {};
  drivers[driverId] = this._deviceDrivers[driverId];
  var configs = {};
  configs[driverId] = this._createDriverConfig(driverId, options);
  configs.debug = __DEBUG__ || false;

  return driverManager(drivers, configs);
};

device._createDriverConfig = function(driverId, options) {
  options = options || {};
  var timezone = options.timezone || this._defaultTimezone;
  var comms = options.silent ? this._silentComms : this._deviceComms;
  var theVersion = options.version || this._version;
  var uploadGroup = options.targetId || this._groupId;

  // handle config for block-mode devices, which includes the file name and data
  if (options.filename != null) {
    return {
      filename: options.filename,
      filedata: options.filedata,
      deviceInfo: this._deviceInfoCache[driverId],
      timezone: timezone,
      groupId: uploadGroup,
      api: this._api,
      version: options.version,
      builder: builder,
      progress: options.progress,
      silent: Boolean(options.silent)
    };
  }

  var deviceInfo = this._deviceInfoCache[driverId];

  if(options.serialNumber) {
    _.assign(deviceInfo, {serialNumber: options.serialNumber});
  }

  return {
    deviceInfo: deviceInfo,
    deviceComms: comms[driverId],
    timezone: timezone,
    groupId: uploadGroup,
    api: this._api,
    version: options.version,
    builder: builder,
    progress: options.progress,
    silent: Boolean(options.silent)
  };
};

device.detectHid = function(driverId, cb) {
  var self = this;
  var driverManifest = this.getDriverManifest(driverId);
  var results = hid.devices();
  results = _.filter(results, function(p) {
    return (p.vendorId === driverManifest.vendorId);
  });

  var devices = _.map(results, function(result) {
    var retval = {
      driverId: driverId,
      deviceId: result.deviceId,
      vendorId: result.vendorId,
      productId: result.productId
    };

    return retval;
  });

  var devdata = _.first(devices);

  if (devices.length > 1) {
    self.log('WARNING: More than one device found for "' + driverId + '"');
    device.othersConnected = devices.length - 1;
  }

  return cb(null, devdata);
};

device.detectUsbSerial = function(driverId, cb) {
  var self = this;
  var driverManifest = this.getDriverManifest(driverId);
  var identification = {
    vendorId: driverManifest.vendorId,
    productId: driverManifest.productId
  };

  var getDevice = function(results) {
    var devices = _.map(results, function(result) {
      var retval = {
        driverId: driverId,
        vendorId: driverManifest.vendorId,
        productId: driverManifest.productId,
        usbDevice: result.device,
        path: result.comName
      };
      if (!!driverManifest.bitrate) {
        retval.bitrate = driverManifest.bitrate;
      }
      if(!!driverManifest.ctsFlowControl) {
        retval.ctsFlowControl = driverManifest.ctsFlowControl;
      }
      if(!!driverManifest.sendTimeout){
        retval.sendTimeout = driverManifest.sendTimeout;
      }
      if(!!driverManifest.receiveTimeout) {
        retval.receiveTimeout = driverManifest.receiveTimeout;
      }
      return retval;
    });

    var devdata = _.first(devices);

    if (devices.length > 1) {
      self.log('WARNING: More than one device found for "' + driverId + '"');
      device.othersConnected = devices.length - 1;
    }
    return cb(null, devdata);
  };

  SerialPort.list(function (err, results) {
    console.log('Connected device(s):', results);
    results = _.filter(results, function(p) {
      var vendorId = parseInt(p.vendorId,16);
      var productId = parseInt(p.productId,16);
      if (self._os === 'mac') {
        return (vendorId === driverManifest.vendorId) &&
          (productId === driverManifest.productId) &&
          p.comName.match('/dev/cu.+');
      } else {
        return (vendorId === driverManifest.vendorId) &&
          (productId === driverManifest.productId);
      }
    });
    console.log('Possible device(s):', results);
    getDevice(results);
  });
};

device.detect = function(driverId, options, cb) {
  var self = this;
  if (_.isFunction(options)) {
    cb = options;
    options = { version: self._version };
  }
  var driverManifest = this.getDriverManifest(driverId);

  if(driverManifest.mode === 'HID'){
      this.detectHid(driverId, function(err, devdata) {

        if (err) {
          return cb(err);
        }

        if (!devdata) {
          return cb();
        }

        self._deviceInfoCache[driverId] = _.cloneDeep(devdata);
        self.detectHelper(driverId, options, function(err, ftdiDevice) {

          if (err) {
            return cb(err);
          }
          device = _.assign(devdata, ftdiDevice);
          return cb(null, devdata);
        });
      });

  } else if (driverManifest.mode === 'usb') {

    var device = usb.findByIds(driverManifest.vendorId, driverManifest.productId);
    if (device) {
      return cb(null, {
        driverId: driverId,
        vendorId: driverManifest.vendorId,
        productId: driverManifest.productId,
        usbDevice: device
      });
    }
    return cb();

  } else {

    this.detectUsbSerial(driverId, function(err, devdata) {

      if (err) {
        return cb(err);
      }

      if (!devdata) {
        return cb();
      }

      self._deviceInfoCache[driverId] = _.cloneDeep(devdata);
      self.detectHelper(driverId, options, function(err, ftdiDevice) {
        if (err) {
          return cb(err);
        }
        device = _.assign(devdata, ftdiDevice);
        return cb(null, devdata);
      });
    });
  }
};

device.detectAll = function(cb) {
  async.map(this.getDriverIds(), this.detect.bind(this), function(err, results) {
    if (err) {
      return cb(err);
    }
    // Filter out any nulls
    results = _.filter(results);
    cb(null, results);
  });
};

device.upload = function(driverId, options, cb) {
  var dm = this._createDriverManager(driverId, options);
  dm.process(driverId, function(err, result) {
    return cb(err, result);
  });
};

module.exports = device;
<commit_msg>add detectUsb to work similarly to detectHid and detectUsbSerial<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/* global  __DEBUG__ */

var os = require('os');

var _ = require('lodash');
var async = require('async');

var serialDevice = require('../serialDevice');
var hidDevice = require('../hidDevice');
var usbDevice = require('../usbDevice');
var driverManager = require('../driverManager');
var builder = require('../objectBuilder')();
var hid = require('node-hid');
var usb = require('usb');
var SerialPort = require('serialport');

var dexcomDriver = require('../drivers/dexcom/dexcomDriver');
var oneTouchMiniDriver = require('../drivers/onetouch/oneTouchMiniDriver');
var abbottPrecisionXtra = require('../drivers/abbott/abbottPrecisionXtra');
var tandemDriver = require('../drivers/tandem/tandemDriver');
var insuletOmniPod = require('../drivers/insulet/insuletDriver');
var oneTouchUltra2 = require('../drivers/onetouch/oneTouchUltra2');
var oneTouchVerio = require('../drivers/onetouch/oneTouchVerio');
var oneTouchVerioIQ = require('../drivers/onetouch/oneTouchVerioIQ');
var abbottFreeStyleLite = require('../drivers/abbott/abbottFreeStyleLite');
var abbottFreeStyleLibre = require('../drivers/abbott/abbottFreeStyleLibre');
var bayerContourNext = require('../drivers/bayer/bayerContourNext');
var animasDriver = require('../drivers/animas/animasDriver');
var medtronicDriver = require('../drivers/medtronic/medtronicDriver');

var device = {
  log: require('bows')('Device')
};

var hostMap = {
  'darwin': 'mac',
  'win32' : 'win',
  'linux': 'linux',
};

device._deviceDrivers = {
  'Dexcom': dexcomDriver,
  'OneTouchMini': oneTouchMiniDriver,
  'AbbottPrecisionXtra': abbottPrecisionXtra,
  'InsuletOmniPod': insuletOmniPod,
  'Tandem': tandemDriver,
  'OneTouchUltra2': oneTouchUltra2,
  'OneTouchVerio': oneTouchVerio,
  'OneTouchVerioIQ': oneTouchVerioIQ,
  'AbbottFreeStyleLite': abbottFreeStyleLite,
  'AbbottFreeStyleFreedomLite': abbottFreeStyleLite,
  'AbbottFreeStyleLibre': abbottFreeStyleLibre,
  'BayerContourNext': bayerContourNext,
  'BayerContourNextUsb': bayerContourNext,
  'BayerContourUsb': bayerContourNext,
  'BayerContourNextLink': bayerContourNext,
  'Animas': animasDriver,
  'Medtronic': medtronicDriver
};

device._deviceComms = {
  'Dexcom': serialDevice,
  'OneTouchMini': serialDevice,
  'AbbottPrecisionXtra': serialDevice,
  'OneTouchUltra2': serialDevice,
  'OneTouchVerio': usbDevice,
  'OneTouchVerioIQ': serialDevice,
  'AbbottFreeStyleLite': serialDevice,
  'AbbottFreeStyleFreedomLite': serialDevice,
  'AbbottFreeStyleLibre': hidDevice,
  'Tandem': serialDevice,
  'BayerContourNext': hidDevice,
  'BayerContourNextUsb': hidDevice,
  'BayerContourUsb': hidDevice,
  'BayerContourNextLink': hidDevice,
  'Animas': serialDevice,
  'Medtronic': hidDevice
};

device._silentComms = {};
_.forEach(_.keys(device._deviceComms), function(driverId) {

  var comm = device._deviceComms[driverId];
  device._silentComms[driverId] = comm({silent: true});
  device._deviceComms[driverId] = comm();
});

// this is a cache for device information
// we need it so that what we learn in detect()
// can be used by process().
device._deviceInfoCache = {};

device.init = function(options, cb) {
  var self=this;
  self._defaultTimezone = options.defaultTimezone;
  self._driverManifests = self._getAllDriverManifests();
  self._api = options.api;
  self._version = options.version;
  self._groupId = options.targetId;
  self._os = hostMap[os.platform()];
  cb();
};

device._getAllDriverManifests = function() {
  var manifest = require('../../manifest.json');

  var usbDevicesPermission = _.find(manifest.permissions, function(permission) {
    return permission.usbDevices;
  });
  return _.reduce(usbDevicesPermission.usbDevices, function(acc, usbDevice) {
    acc[usbDevice.driverId] = usbDevice;
    return acc;
  }, {});
};

device.getDriverManifests = function() {
  return _.cloneDeep(this._driverManifests);
};

device.getDriverIds = function() {
  return _.keys(this._driverManifests);
};

device.getDriverManifest = function(driverId) {
  var driverManifest = this._driverManifests[driverId];
  if (!driverManifest) {
    throw new Error('Could not find driver manifest for "' + driverId + '"');
  }
  return driverManifest;
};

device.detectHelper = function(driverId, options, cb) {
  // Detect can run on a loop, so don't pollute the console with logging
  options.silent = true;
  var dm = this._createDriverManager(driverId, options);
  dm.detect(driverId, cb);
};

device._createDriverManager = function(driverId, options) {
  var drivers = {};
  drivers[driverId] = this._deviceDrivers[driverId];
  var configs = {};
  configs[driverId] = this._createDriverConfig(driverId, options);
  configs.debug = __DEBUG__ || false;

  return driverManager(drivers, configs);
};

device._createDriverConfig = function(driverId, options) {
  options = options || {};
  var timezone = options.timezone || this._defaultTimezone;
  var comms = options.silent ? this._silentComms : this._deviceComms;
  var theVersion = options.version || this._version;
  var uploadGroup = options.targetId || this._groupId;

  // handle config for block-mode devices, which includes the file name and data
  if (options.filename != null) {
    return {
      filename: options.filename,
      filedata: options.filedata,
      deviceInfo: this._deviceInfoCache[driverId],
      timezone: timezone,
      groupId: uploadGroup,
      api: this._api,
      version: options.version,
      builder: builder,
      progress: options.progress,
      silent: Boolean(options.silent)
    };
  }

  var deviceInfo = this._deviceInfoCache[driverId];

  if(options.serialNumber) {
    _.assign(deviceInfo, {serialNumber: options.serialNumber});
  }

  return {
    deviceInfo: deviceInfo,
    deviceComms: comms[driverId],
    timezone: timezone,
    groupId: uploadGroup,
    api: this._api,
    version: options.version,
    builder: builder,
    progress: options.progress,
    silent: Boolean(options.silent)
  };
};

device.detectUsb = function(driverId, cb) {
  var self = this;
  var driverManifest = this.getDriverManifest(driverId);
  var result = usb.findByIds(driverManifest.vendorId, driverManifest.productId);

  var device = {
    driverId: driverId,
    deviceId: result.deviceId,
    vendorId: result.deviceDescriptor.idVendor,
    productId: result.deviceDescriptor.idProduct
  };

  return cb(null, device);
};

device.detectHid = function(driverId, cb) {
  var self = this;
  var driverManifest = this.getDriverManifest(driverId);
  var results = hid.devices();
  results = _.filter(results, function(p) {
    return (p.vendorId === driverManifest.vendorId);
  });

  var devices = _.map(results, function(result) {
    var retval = {
      driverId: driverId,
      deviceId: result.deviceId,
      vendorId: result.vendorId,
      productId: result.productId
    };

    return retval;
  });

  var devdata = _.first(devices);

  if (devices.length > 1) {
    self.log('WARNING: More than one device found for "' + driverId + '"');
    device.othersConnected = devices.length - 1;
  }

  return cb(null, devdata);
};

device.detectUsbSerial = function(driverId, cb) {
  var self = this;
  var driverManifest = this.getDriverManifest(driverId);
  var identification = {
    vendorId: driverManifest.vendorId,
    productId: driverManifest.productId
  };

  var getDevice = function(results) {
    var devices = _.map(results, function(result) {
      var retval = {
        driverId: driverId,
        vendorId: driverManifest.vendorId,
        productId: driverManifest.productId,
        usbDevice: result.device,
        path: result.comName
      };
      if (!!driverManifest.bitrate) {
        retval.bitrate = driverManifest.bitrate;
      }
      if(!!driverManifest.ctsFlowControl) {
        retval.ctsFlowControl = driverManifest.ctsFlowControl;
      }
      if(!!driverManifest.sendTimeout){
        retval.sendTimeout = driverManifest.sendTimeout;
      }
      if(!!driverManifest.receiveTimeout) {
        retval.receiveTimeout = driverManifest.receiveTimeout;
      }
      return retval;
    });

    var devdata = _.first(devices);

    if (devices.length > 1) {
      self.log('WARNING: More than one device found for "' + driverId + '"');
      device.othersConnected = devices.length - 1;
    }
    return cb(null, devdata);
  };

  SerialPort.list(function (err, results) {
    console.log('Connected device(s):', results);
    results = _.filter(results, function(p) {
      var vendorId = parseInt(p.vendorId,16);
      var productId = parseInt(p.productId,16);
      if (self._os === 'mac') {
        return (vendorId === driverManifest.vendorId) &&
          (productId === driverManifest.productId) &&
          p.comName.match('/dev/cu.+');
      } else {
        return (vendorId === driverManifest.vendorId) &&
          (productId === driverManifest.productId);
      }
    });
    console.log('Possible device(s):', results);
    getDevice(results);
  });
};

device.detect = function(driverId, options, cb) {
  var self = this;
  if (_.isFunction(options)) {
    cb = options;
    options = { version: self._version };
  }
  var driverManifest = this.getDriverManifest(driverId);

  if(driverManifest.mode === 'HID'){
      this.detectHid(driverId, function(err, devdata) {

        if (err) {
          return cb(err);
        }

        if (!devdata) {
          return cb();
        }

        self._deviceInfoCache[driverId] = _.cloneDeep(devdata);
        self.detectHelper(driverId, options, function(err, ftdiDevice) {

          if (err) {
            return cb(err);
          }
          device = _.assign(devdata, ftdiDevice);
          return cb(null, devdata);
        });
      });

  } else if (driverManifest.mode === 'usb') {

    this.detectUsb(driverId, function(err, devdata) {

      if (err) {
        return cb(err);
      }

      if (!devdata) {
        return cb();
      }

      self._deviceInfoCache[driverId] = _.cloneDeep(devdata);

      self.detectHelper(driverId, options, function(err, usbDevice) {

        if (err) {
          return cb(err);
        }
        device = _.assign(devdata, usbDevice);
        return cb(null, devdata);
      });
    });

  } else {

    this.detectUsbSerial(driverId, function(err, devdata) {

      if (err) {
        return cb(err);
      }

      if (!devdata) {
        return cb();
      }

      self._deviceInfoCache[driverId] = _.cloneDeep(devdata);
      self.detectHelper(driverId, options, function(err, ftdiDevice) {
        if (err) {
          return cb(err);
        }
        device = _.assign(devdata, ftdiDevice);
        return cb(null, devdata);
      });
    });
  }
};

device.detectAll = function(cb) {
  async.map(this.getDriverIds(), this.detect.bind(this), function(err, results) {
    if (err) {
      return cb(err);
    }
    // Filter out any nulls
    results = _.filter(results);
    cb(null, results);
  });
};

device.upload = function(driverId, options, cb) {
  var dm = this._createDriverManager(driverId, options);
  dm.process(driverId, function(err, result) {
    return cb(err, result);
  });
};

module.exports = device;
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

"use strict";

module.metadata = {
  "stability": "unstable"
};

var self = require("sdk/self");

const { Trace, TraceError } = require("../core/trace.js");
// "_" will make it possible to work with existing tools
// that expect "_" to indicate localizable strings.
// More info: https://developer.mozilla.org/en-US/Add-ons/SDK/Tutorials/l10n
const _ = require("sdk/l10n").get;

// Module Implementation
// xxxHonza: The module implements only basic API, so the reset of
// the code base can start localizing strings. Still needs to be
// finished, see: https://github.com/firebug/firebug.next/issues/12
var Locale = {};

Locale.$STR = function(name) {
  return Locale.$STRF(name);
};

Locale.$STRF = function(name, args) {
  if(!name)
    return "";

  // Keep the value of name before manipulating to return back if there is
  // no identifier/key in the localization file corresponding to the name.
  let originalName = name;

  name = name.replace(/\s/g, '_');
  let localizedStr = _.apply(this, arguments);
  // _() returns a value same sa the identifier's if it can't find
  // a entry for the identifier/key passed to the func.
  if(localizedStr != name)
    return validate(localizedStr);

  var index = originalName.lastIndexOf(".");
  // xxxFarshid: As an escaped char like '\.' occupies only one position
  // in a cahr sequence, I think it wouldn't evaluate to true. Yet, Came
  // from the firebug code just to make sure I am not missing something!
  if (index > 0 && originalName.charAt(index-1) != "\\")
    originalName = originalName.substr(index + 1);

  return validate(originalName);

};

Locale.$STRP = function(name, index, args) {
  if(index === void(0))
    index = 0;
  // Move the plural form number to the first index of the array, if
  // it's no there.
  if(index != 0)
    [arguments[1], arguments[0]] = [arguments[0], arguments[1]];

  return Locale.$STRF.apply(this, arguments);
};

// Helpers
function validate(str) {
  return str.replace(/"/g, "'");
}

// Exports from this module
exports.Locale = Locale;
<commit_msg>Fix a mistake: Related to issue #12.<commit_after>/* See license.txt for terms of usage */

"use strict";

module.metadata = {
  "stability": "unstable"
};

var self = require("sdk/self");

const { Trace, TraceError } = require("../core/trace.js");
// "_" will make it possible to work with existing tools
// that expect "_" to indicate localizable strings.
// More info: https://developer.mozilla.org/en-US/Add-ons/SDK/Tutorials/l10n
const _ = require("sdk/l10n").get;

// Module Implementation
// xxxHonza: The module implements only basic API, so the reset of
// the code base can start localizing strings. Still needs to be
// finished, see: https://github.com/firebug/firebug.next/issues/12
var Locale = {};

Locale.$STR = function(name) {
  return Locale.$STRF(name);
};

Locale.$STRF = function(name, args) {
  if(!name)
    return "";

  // Keep the value of name before manipulating to return back if there is
  // no identifier/key in the localization file corresponding to the name.
  let originalName = name;

  name = name.replace(/\s/g, '_');
  let localizedStr = _.apply(this, arguments);
  // _() returns a value same sa the identifier's if it can't find
  // a entry for the identifier/key passed to the func.
  if(localizedStr != name)
    return validate(localizedStr);

  var index = originalName.lastIndexOf(".");
  // xxxFarshid: As an escaped char like '\.' occupies only one position
  // in a cahr sequence, I think it wouldn't evaluate to true. Yet, Came
  // from the firebug code just to make sure I am not missing something!
  if (index > 0 && originalName.charAt(index-1) != "\\")
    originalName = originalName.substr(index + 1);

  return validate(originalName);

};

Locale.$STRP = function(name, index, args) {
  if(index === void(0))
    index = 0;
  // Move the plural form number to the first index of the array, if
  // it's no there.
  if(index != 0)
    [arguments[index], arguments[0]] = [arguments[0], arguments[index]];

  return Locale.$STRF.apply(this, arguments);
};

// Helpers
function validate(str) {
  return str.replace(/"/g, "'");
}

// Exports from this module
exports.Locale = Locale;
<|endoftext|>


<commit_before>const fs = require('./fs.js');
const utils = require('../utils/utils.js');
const constants = require('../constants');

// TODO: pass other params like blockchainConfig, contract files, etc..
var Plugin = function(options) {
  this.name = options.name;
  this.isInternal = options.isInternal;
  this.pluginModule = options.pluginModule;
  this.pluginPath = options.pluginPath;
  this.pluginConfig = options.pluginConfig;
  this.shouldInterceptLogs = options.interceptLogs;
  this.clientWeb3Providers = [];
  this.beforeDeploy = [];
  this.contractsGenerators = [];
  this.pipeline = [];
  this.pipelineFiles = [];
  this.console = [];
  this.contractsConfigs = [];
  this.contractsFiles = [];
  this.compilers = [];
  this.serviceChecks = [];
  this.pluginTypes = [];
  this.uploadCmds = [];
  this.imports = [];
  this.embarkjs_code = [];
  this.embarkjs_init_code = {};
  this.embarkjs_init_console_code = {};
  this.afterContractsDeployActions = [];
  this.onDeployActions = [];
  this.eventActions = {};
  this._loggerObject = options.logger;
  this.logger = this._loggerObject; // Might get changed if we do intercept
  this.events = options.events;
  this.config = options.config;
  this.env = options.env;
  this.loaded = false;
  this.currentContext = options.context;
  this.acceptedContext = options.pluginConfig.context || [constants.contexts.any];

  if (!Array.isArray(this.currentContext)) {
    this.currentContext = [this.currentContext];
  }
  if (!Array.isArray(this.acceptedContext)) {
    this.acceptedContext = [this.acceptedContext];
  }
};

Plugin.prototype._log = function(type) {
  this._loggerObject[type](this.name + ':', ...[].slice.call(arguments, 1));
};

Plugin.prototype.setUpLogger = function () {
  this.logger = {
    log: this._log.bind(this, 'log'),
    warn: this._log.bind(this, 'warn'),
    error: this._log.bind(this, 'error'),
    info: this._log.bind(this, 'info'),
    debug: this._log.bind(this, 'debug'),
    trace: this._log.bind(this, 'trace'),
    dir: this._log.bind(this, 'dir')
  };
};

Plugin.prototype.isContextValid = function() {
  if (this.currentContext.includes(constants.contexts.any) || this.acceptedContext.includes(constants.contexts.any)) {
    return true;
  }
  return this.acceptedContext.some(context => {
    return this.currentContext.includes(context);
  });
};

Plugin.prototype.hasContext = function(context) {
  return this.currentContext.includes(context);
};

Plugin.prototype.loadPlugin = function() {
  if (!this.isContextValid())  {
    this.logger.warn(__('Plugin {{name}} can only be loaded in the context of "{{contextes}}"', {name: this.name, contextes: this.acceptedContext.join(', ')}));
    return false;
  }
  this.loaded = true;
  if (this.shouldInterceptLogs) {
    this.setUpLogger();
  }
  (this.pluginModule.call(this, this));
};

Plugin.prototype.loadInternalPlugin = function() {
  new this.pluginModule(this, this.pluginConfig); /*eslint no-new: "off"*/
};

Plugin.prototype.loadPluginFile = function(filename) {
  return fs.readFileSync(this.pathToFile(filename)).toString();
};

Plugin.prototype.pathToFile = function(filename) {
  if (!this.pluginPath) {
    throw new Error('pluginPath not defined for plugin: ' + this.name);
  }
  return utils.joinPath(this.pluginPath, filename);
};

// TODO: add deploy provider
Plugin.prototype.registerClientWeb3Provider = function(cb) {
  this.clientWeb3Providers.push(cb);
  this.addPluginType('clientWeb3Provider');
};

Plugin.prototype.registerContractsGeneration = function(cb) {
  this.contractsGenerators.push(cb);
  this.addPluginType('contractGeneration');
};

Plugin.prototype.registerPipeline = function(matcthingFiles, cb) {
  // TODO: generate error for more than one pipeline per plugin
  this.pipeline.push({matcthingFiles: matcthingFiles, cb: cb});
  this.addPluginType('pipeline');
};

Plugin.prototype.addFileToPipeline = function(file, intendedPath, options) {
  this.pipelineFiles.push({file: file, intendedPath: intendedPath, options: options});
  this.addPluginType('pipelineFiles');
};

Plugin.prototype.addContractFile = function(file) {
  if (this.isInternal) {
    throw new Error("this API cannot work for internal modules. please use an event command instead: config:contractsFiles:add");
  }
  this.contractsFiles.push(file);
  this.addPluginType('contractFiles');
};

Plugin.prototype.registerConsoleCommand = function(cb) {
  this.console.push(cb);
  this.addPluginType('console');
};

// TODO: this only works for services done on startup
Plugin.prototype.registerServiceCheck = function(checkName, checkFn, time) {
  this.serviceChecks.push({checkName: checkName, checkFn: checkFn, time: time});
  this.addPluginType('serviceChecks');
};

Plugin.prototype.has = function(pluginType) {
  return this.pluginTypes.indexOf(pluginType) >= 0;
};

Plugin.prototype.addPluginType = function(pluginType) {
  this.pluginTypes.push(pluginType);
  this.pluginTypes = Array.from(new Set(this.pluginTypes));
};

Plugin.prototype.generateProvider = function(args) {
  return this.clientWeb3Providers.map(function(cb) {
    return cb.call(this, args);
  }).join("\n");
};

Plugin.prototype.generateContracts = function(args) {
  return this.contractsGenerators.map(function(cb) {
    return cb.call(this, args);
  }).join("\n");
};

Plugin.prototype.registerContractConfiguration = function(config) {
  this.contractsConfigs.push(config);
  this.addPluginType('contractsConfig');
};

Plugin.prototype.registerCompiler = function(extension, cb) {
  this.compilers.push({extension: extension, cb: cb});
  this.addPluginType('compilers');
};

Plugin.prototype.registerUploadCommand = function(cmd, cb) {
  this.uploadCmds.push({cmd: cmd, cb: cb});
  this.addPluginType('uploadCmds');
};

Plugin.prototype.addCodeToEmbarkJS = function(code) {
  this.embarkjs_code.push(code);
  this.addPluginType('embarkjsCode');
};

Plugin.prototype.addProviderInit = function(providerType, code, initCondition) {
  this.embarkjs_init_code[providerType] = this.embarkjs_init_code[providerType] || [];
  this.embarkjs_init_code[providerType].push([code, initCondition]);
  this.addPluginType('initCode');
};

Plugin.prototype.addConsoleProviderInit = function(providerType, code, initCondition) {
  this.embarkjs_init_console_code[providerType] = this.embarkjs_init_console_code[providerType] || [];
  this.embarkjs_init_console_code[providerType].push([code, initCondition]);
  this.addPluginType('initConsoleCode');
};

Plugin.prototype.registerImportFile = function(importName, importLocation) {
  this.imports.push([importName, importLocation]);
  this.addPluginType('imports');
};

Plugin.prototype.registerActionForEvent = function(eventName, cb) {
  if (!this.eventActions[eventName]) {
    this.eventActions[eventName] = [];
  }
  this.eventActions[eventName].push(cb);
  this.addPluginType('eventActions');
};

Plugin.prototype.runFilePipeline = function() {
  var self = this;

  return this.pipelineFiles.map(function(file) {
      var obj = {};
      obj.filename = file.file.replace('./','');
      obj.content = self.loadPluginFile(file.file).toString();
      obj.intendedPath = file.intendedPath;
      obj.options = file.options;
      obj.path = self.pathToFile(obj.filename);

      return obj;
  });
};

Plugin.prototype.runPipeline = function(args) {
  // TODO: should iterate the pipelines
  var pipeline = this.pipeline[0];
  var shouldRunPipeline = utils.fileMatchesPattern(pipeline.matcthingFiles, args.targetFile);
  if (shouldRunPipeline) {
    return pipeline.cb.call(this, args);
  }
  return args.source;
};

module.exports = Plugin;
<commit_msg>Add support for ES6 plugins<commit_after>const fs = require('./fs.js');
const utils = require('../utils/utils.js');
const constants = require('../constants');

// TODO: pass other params like blockchainConfig, contract files, etc..
var Plugin = function(options) {
  this.name = options.name;
  this.isInternal = options.isInternal;
  this.pluginModule = options.pluginModule;
  this.pluginPath = options.pluginPath;
  this.pluginConfig = options.pluginConfig;
  this.shouldInterceptLogs = options.interceptLogs;
  this.clientWeb3Providers = [];
  this.beforeDeploy = [];
  this.contractsGenerators = [];
  this.pipeline = [];
  this.pipelineFiles = [];
  this.console = [];
  this.contractsConfigs = [];
  this.contractsFiles = [];
  this.compilers = [];
  this.serviceChecks = [];
  this.pluginTypes = [];
  this.uploadCmds = [];
  this.imports = [];
  this.embarkjs_code = [];
  this.embarkjs_init_code = {};
  this.embarkjs_init_console_code = {};
  this.afterContractsDeployActions = [];
  this.onDeployActions = [];
  this.eventActions = {};
  this._loggerObject = options.logger;
  this.logger = this._loggerObject; // Might get changed if we do intercept
  this.events = options.events;
  this.config = options.config;
  this.env = options.env;
  this.loaded = false;
  this.currentContext = options.context;
  this.acceptedContext = options.pluginConfig.context || [constants.contexts.any];

  if (!Array.isArray(this.currentContext)) {
    this.currentContext = [this.currentContext];
  }
  if (!Array.isArray(this.acceptedContext)) {
    this.acceptedContext = [this.acceptedContext];
  }
};

Plugin.prototype._log = function(type) {
  this._loggerObject[type](this.name + ':', ...[].slice.call(arguments, 1));
};

Plugin.prototype.setUpLogger = function () {
  this.logger = {
    log: this._log.bind(this, 'log'),
    warn: this._log.bind(this, 'warn'),
    error: this._log.bind(this, 'error'),
    info: this._log.bind(this, 'info'),
    debug: this._log.bind(this, 'debug'),
    trace: this._log.bind(this, 'trace'),
    dir: this._log.bind(this, 'dir')
  };
};

Plugin.prototype.isContextValid = function() {
  if (this.currentContext.includes(constants.contexts.any) || this.acceptedContext.includes(constants.contexts.any)) {
    return true;
  }
  return this.acceptedContext.some(context => {
    return this.currentContext.includes(context);
  });
};

Plugin.prototype.hasContext = function(context) {
  return this.currentContext.includes(context);
};

Plugin.prototype.loadPlugin = function() {
  if (!this.isContextValid())  {
    this.logger.warn(__('Plugin {{name}} can only be loaded in the context of "{{contexts}}"', {name: this.name, contexts: this.acceptedContext.join(', ')}));
    return false;
  }
  this.loaded = true;
  if (this.shouldInterceptLogs) {
    this.setUpLogger();
  }
  if (typeof this.pluginModule === 'object' && typeof this.pluginModule.default === 'function' && this.pluginModule.__esModule){
    this.pluginModule = this.pluginModule.default;
    return new this.pluginModule(this);
  }
  (this.pluginModule.call(this, this));
};

Plugin.prototype.loadInternalPlugin = function() {
  new this.pluginModule(this, this.pluginConfig); /*eslint no-new: "off"*/
};

Plugin.prototype.loadPluginFile = function(filename) {
  return fs.readFileSync(this.pathToFile(filename)).toString();
};

Plugin.prototype.pathToFile = function(filename) {
  if (!this.pluginPath) {
    throw new Error('pluginPath not defined for plugin: ' + this.name);
  }
  return utils.joinPath(this.pluginPath, filename);
};

// TODO: add deploy provider
Plugin.prototype.registerClientWeb3Provider = function(cb) {
  this.clientWeb3Providers.push(cb);
  this.addPluginType('clientWeb3Provider');
};

Plugin.prototype.registerContractsGeneration = function(cb) {
  this.contractsGenerators.push(cb);
  this.addPluginType('contractGeneration');
};

Plugin.prototype.registerPipeline = function(matcthingFiles, cb) {
  // TODO: generate error for more than one pipeline per plugin
  this.pipeline.push({matcthingFiles: matcthingFiles, cb: cb});
  this.addPluginType('pipeline');
};

Plugin.prototype.addFileToPipeline = function(file, intendedPath, options) {
  this.pipelineFiles.push({file: file, intendedPath: intendedPath, options: options});
  this.addPluginType('pipelineFiles');
};

Plugin.prototype.addContractFile = function(file) {
  if (this.isInternal) {
    throw new Error("this API cannot work for internal modules. please use an event command instead: config:contractsFiles:add");
  }
  this.contractsFiles.push(file);
  this.addPluginType('contractFiles');
};

Plugin.prototype.registerConsoleCommand = function(cb) {
  this.console.push(cb);
  this.addPluginType('console');
};

// TODO: this only works for services done on startup
Plugin.prototype.registerServiceCheck = function(checkName, checkFn, time) {
  this.serviceChecks.push({checkName: checkName, checkFn: checkFn, time: time});
  this.addPluginType('serviceChecks');
};

Plugin.prototype.has = function(pluginType) {
  return this.pluginTypes.indexOf(pluginType) >= 0;
};

Plugin.prototype.addPluginType = function(pluginType) {
  this.pluginTypes.push(pluginType);
  this.pluginTypes = Array.from(new Set(this.pluginTypes));
};

Plugin.prototype.generateProvider = function(args) {
  return this.clientWeb3Providers.map(function(cb) {
    return cb.call(this, args);
  }).join("\n");
};

Plugin.prototype.generateContracts = function(args) {
  return this.contractsGenerators.map(function(cb) {
    return cb.call(this, args);
  }).join("\n");
};

Plugin.prototype.registerContractConfiguration = function(config) {
  this.contractsConfigs.push(config);
  this.addPluginType('contractsConfig');
};

Plugin.prototype.registerCompiler = function(extension, cb) {
  this.compilers.push({extension: extension, cb: cb});
  this.addPluginType('compilers');
};

Plugin.prototype.registerUploadCommand = function(cmd, cb) {
  this.uploadCmds.push({cmd: cmd, cb: cb});
  this.addPluginType('uploadCmds');
};

Plugin.prototype.addCodeToEmbarkJS = function(code) {
  this.embarkjs_code.push(code);
  this.addPluginType('embarkjsCode');
};

Plugin.prototype.addProviderInit = function(providerType, code, initCondition) {
  this.embarkjs_init_code[providerType] = this.embarkjs_init_code[providerType] || [];
  this.embarkjs_init_code[providerType].push([code, initCondition]);
  this.addPluginType('initCode');
};

Plugin.prototype.addConsoleProviderInit = function(providerType, code, initCondition) {
  this.embarkjs_init_console_code[providerType] = this.embarkjs_init_console_code[providerType] || [];
  this.embarkjs_init_console_code[providerType].push([code, initCondition]);
  this.addPluginType('initConsoleCode');
};

Plugin.prototype.registerImportFile = function(importName, importLocation) {
  this.imports.push([importName, importLocation]);
  this.addPluginType('imports');
};

Plugin.prototype.registerActionForEvent = function(eventName, cb) {
  if (!this.eventActions[eventName]) {
    this.eventActions[eventName] = [];
  }
  this.eventActions[eventName].push(cb);
  this.addPluginType('eventActions');
};

Plugin.prototype.runFilePipeline = function() {
  var self = this;

  return this.pipelineFiles.map(function(file) {
      var obj = {};
      obj.filename = file.file.replace('./','');
      obj.content = self.loadPluginFile(file.file).toString();
      obj.intendedPath = file.intendedPath;
      obj.options = file.options;
      obj.path = self.pathToFile(obj.filename);

      return obj;
  });
};

Plugin.prototype.runPipeline = function(args) {
  // TODO: should iterate the pipelines
  var pipeline = this.pipeline[0];
  var shouldRunPipeline = utils.fileMatchesPattern(pipeline.matcthingFiles, args.targetFile);
  if (shouldRunPipeline) {
    return pipeline.cb.call(this, args);
  }
  return args.source;
};

module.exports = Plugin;
<|endoftext|>


<commit_before>const fs = require('./fs.js');
const utils = require('../utils/utils.js');
const constants = require('../constants');
const _ = require('underscore');

// TODO: pass other params like blockchainConfig, contract files, etc..
var Plugin = function(options) {
  this.name = options.name;
  this.isInternal = options.isInternal;
  this.pluginModule = options.pluginModule;
  this.pluginPath = options.pluginPath;
  this.pluginConfig = options.pluginConfig;
  this.shouldInterceptLogs = options.interceptLogs;
  this.clientWeb3Providers = [];
  this.beforeDeploy = [];
  this.contractsGenerators = [];
  this.pipeline = [];
  this.pipelineFiles = [];
  this.console = [];
  this.contractsConfigs = [];
  this.contractsFiles = [];
  this.compilers = [];
  this.serviceChecks = [];
  this.pluginTypes = [];
  this.uploadCmds = [];
  this.imports = [];
  this.embarkjs_code = [];
  this.embarkjs_init_code = {};
  this.afterContractsDeployActions = [];
  this.onDeployActions = [];
  this.eventActions = {};
  this.logger = options.logger;
  this.events = options.events;
  this.config = options.config;
  this.env = options.env;
  this.loaded = false;
  this.currentContext = options.context;
  this.acceptedContext = options.pluginConfig.context || [constants.contexts.any];

  if (!Array.isArray(this.currentContext)) {
    this.currentContext = [this.currentContext];
  }
  if (!Array.isArray(this.acceptedContext)) {
    this.acceptedContext = [this.acceptedContext];
  }
};

Plugin.prototype.isContextValid = function() {
  if (this.currentContext.includes(constants.contexts.any) || this.acceptedContext.includes(constants.contexts.any)) {
    return true;
  }
  return this.acceptedContext.some(context => {
    return this.currentContext.includes(context);
  });
};

Plugin.prototype.hasContext = function(context) {
  return this.currentContext.includes(context);
};

Plugin.prototype.loadPlugin = function() {
  if (!this.isContextValid())  {
    console.log(this.acceptedContext);
    this.logger.warn(__('Plugin {{name}} can only be loaded in the context of "{{contextes}}"', {name: this.name, contextes: this.acceptedContext.join(', ')}));
    return false;
  }
  this.loaded = true;
  if (this.shouldInterceptLogs) {
    this.interceptLogs(this.pluginModule);
  }
  (this.pluginModule.call(this, this));
};

Plugin.prototype.loadInternalPlugin = function() {
  new this.pluginModule(this, this.pluginConfig); /*eslint no-new: "off"*/
};

Plugin.prototype.loadPluginFile = function(filename) {
  return fs.readFileSync(this.pathToFile(filename)).toString();
};

Plugin.prototype.pathToFile = function(filename) {
  if (!this.pluginPath) {
    throw new Error('pluginPath not defined for plugin: ' + this.name);
  }
  return utils.joinPath(this.pluginPath, filename);
};

Plugin.prototype.interceptLogs = function(context) {
  var self = this;
  // TODO: this is a bit nasty, figure out a better way
  context.console = context.console || console;

  //context.console.error  = function(txt) {
  //  // TODO: logger should support an array instead of a single argument
  //  //self.logger.error.apply(self.logger, arguments);
  //  self.logger.error(self.name + " > " + txt);
  //};
  context.console.log  = function(txt) {
    self.logger.info(self.name + " > " + txt);
  };
  context.console.warn  = function(txt) {
    self.logger.warn(self.name + " > " + txt);
  };
  context.console.info  = function(txt) {
    self.logger.info(self.name + " > " + txt);
  };
  context.console.debug  = function(txt) {
    // TODO: ue JSON.stringify
    self.logger.debug(self.name + " > " + txt);
  };
  context.console.trace  = function(txt) {
    self.logger.trace(self.name + " > " + txt);
  };
  context.console.dir  = function(txt) {
    self.logger.dir(txt);
  };
};

// TODO: add deploy provider
Plugin.prototype.registerClientWeb3Provider = function(cb) {
  this.clientWeb3Providers.push(cb);
  this.pluginTypes.push('clientWeb3Provider');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.registerContractsGeneration = function(cb) {
  this.contractsGenerators.push(cb);
  this.pluginTypes.push('contractGeneration');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.registerPipeline = function(matcthingFiles, cb) {
  // TODO: generate error for more than one pipeline per plugin
  this.pipeline.push({matcthingFiles: matcthingFiles, cb: cb});
  this.pluginTypes.push('pipeline');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.addFileToPipeline = function(file, intendedPath, options) {
  this.pipelineFiles.push({file: file, intendedPath: intendedPath, options: options});
  this.pluginTypes.push('pipelineFiles');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.addContractFile = function(file) {
  this.contractsFiles.push(file);
  this.pluginTypes.push('contractFiles');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.registerConsoleCommand = function(cb) {
  this.console.push(cb);
  this.pluginTypes.push('console');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

// TODO: this only works for services done on startup
Plugin.prototype.registerServiceCheck = function(checkName, checkFn, time) {
  this.serviceChecks.push({checkName: checkName, checkFn: checkFn, time: time});
  this.pluginTypes.push('serviceChecks');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.has = function(pluginType) {
  return this.pluginTypes.indexOf(pluginType) >= 0;
};

Plugin.prototype.generateProvider = function(args) {
  return this.clientWeb3Providers.map(function(cb) {
    return cb.call(this, args);
  }).join("\n");
};

Plugin.prototype.generateContracts = function(args) {
  return this.contractsGenerators.map(function(cb) {
    return cb.call(this, args);
  }).join("\n");
};

Plugin.prototype.registerContractConfiguration = function(config) {
  this.contractsConfigs.push(config);
  this.pluginTypes.push('contractsConfig');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.registerCompiler = function(extension, cb) {
  this.compilers.push({extension: extension, cb: cb});
  this.pluginTypes.push('compilers');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.registerUploadCommand = function(cmd, cb) {
  this.uploadCmds.push({cmd: cmd, cb: cb});
  this.pluginTypes.push('uploadCmds');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.addCodeToEmbarkJS = function(code) {
  this.embarkjs_code.push(code);
  this.pluginTypes.push('embarkjsCode');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.addProviderInit = function(providerType, code, initCondition) {
  this.embarkjs_init_code[providerType] = this.embarkjs_init_code[providerType] || [];
  this.embarkjs_init_code[providerType].push([code, initCondition]);
  this.pluginTypes.push('initCode');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.registerImportFile = function(importName, importLocation) {
  this.imports.push([importName, importLocation]);
  this.pluginTypes.push('imports');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.registerActionForEvent = function(eventName, cb) {
  if (!this.eventActions[eventName]) {
    this.eventActions[eventName] = [];
  }
  this.eventActions[eventName].push(cb);
  this.pluginTypes.push('eventActions');
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.runFilePipeline = function() {
  var self = this;

  return this.pipelineFiles.map(function(file) {
      var obj = {};
      obj.filename = file.file.replace('./','');
      obj.content = self.loadPluginFile(file.file).toString();
      obj.intendedPath = file.intendedPath;
      obj.options = file.options;
      obj.path = self.pathToFile(obj.filename);

      return obj;
  });
};

Plugin.prototype.runPipeline = function(args) {
  // TODO: should iterate the pipelines
  var pipeline = this.pipeline[0];
  var shouldRunPipeline = utils.fileMatchesPattern(pipeline.matcthingFiles, args.targetFile);
  if (shouldRunPipeline) {
    return pipeline.cb.call(this, args);
  } else {
    return args.source;
  }
};

module.exports = Plugin;
<commit_msg>refactor to addPluginType<commit_after>const fs = require('./fs.js');
const utils = require('../utils/utils.js');
const constants = require('../constants');
const _ = require('underscore');

// TODO: pass other params like blockchainConfig, contract files, etc..
var Plugin = function(options) {
  this.name = options.name;
  this.isInternal = options.isInternal;
  this.pluginModule = options.pluginModule;
  this.pluginPath = options.pluginPath;
  this.pluginConfig = options.pluginConfig;
  this.shouldInterceptLogs = options.interceptLogs;
  this.clientWeb3Providers = [];
  this.beforeDeploy = [];
  this.contractsGenerators = [];
  this.pipeline = [];
  this.pipelineFiles = [];
  this.console = [];
  this.contractsConfigs = [];
  this.contractsFiles = [];
  this.compilers = [];
  this.serviceChecks = [];
  this.pluginTypes = [];
  this.uploadCmds = [];
  this.imports = [];
  this.embarkjs_code = [];
  this.embarkjs_init_code = {};
  this.afterContractsDeployActions = [];
  this.onDeployActions = [];
  this.eventActions = {};
  this.logger = options.logger;
  this.events = options.events;
  this.config = options.config;
  this.env = options.env;
  this.loaded = false;
  this.currentContext = options.context;
  this.acceptedContext = options.pluginConfig.context || [constants.contexts.any];

  if (!Array.isArray(this.currentContext)) {
    this.currentContext = [this.currentContext];
  }
  if (!Array.isArray(this.acceptedContext)) {
    this.acceptedContext = [this.acceptedContext];
  }
};

Plugin.prototype.isContextValid = function() {
  if (this.currentContext.includes(constants.contexts.any) || this.acceptedContext.includes(constants.contexts.any)) {
    return true;
  }
  return this.acceptedContext.some(context => {
    return this.currentContext.includes(context);
  });
};

Plugin.prototype.hasContext = function(context) {
  return this.currentContext.includes(context);
};

Plugin.prototype.loadPlugin = function() {
  if (!this.isContextValid())  {
    console.log(this.acceptedContext);
    this.logger.warn(__('Plugin {{name}} can only be loaded in the context of "{{contextes}}"', {name: this.name, contextes: this.acceptedContext.join(', ')}));
    return false;
  }
  this.loaded = true;
  if (this.shouldInterceptLogs) {
    this.interceptLogs(this.pluginModule);
  }
  (this.pluginModule.call(this, this));
};

Plugin.prototype.loadInternalPlugin = function() {
  new this.pluginModule(this, this.pluginConfig); /*eslint no-new: "off"*/
};

Plugin.prototype.loadPluginFile = function(filename) {
  return fs.readFileSync(this.pathToFile(filename)).toString();
};

Plugin.prototype.pathToFile = function(filename) {
  if (!this.pluginPath) {
    throw new Error('pluginPath not defined for plugin: ' + this.name);
  }
  return utils.joinPath(this.pluginPath, filename);
};

Plugin.prototype.interceptLogs = function(context) {
  var self = this;
  // TODO: this is a bit nasty, figure out a better way
  context.console = context.console || console;

  //context.console.error  = function(txt) {
  //  // TODO: logger should support an array instead of a single argument
  //  //self.logger.error.apply(self.logger, arguments);
  //  self.logger.error(self.name + " > " + txt);
  //};
  context.console.log  = function(txt) {
    self.logger.info(self.name + " > " + txt);
  };
  context.console.warn  = function(txt) {
    self.logger.warn(self.name + " > " + txt);
  };
  context.console.info  = function(txt) {
    self.logger.info(self.name + " > " + txt);
  };
  context.console.debug  = function(txt) {
    // TODO: ue JSON.stringify
    self.logger.debug(self.name + " > " + txt);
  };
  context.console.trace  = function(txt) {
    self.logger.trace(self.name + " > " + txt);
  };
  context.console.dir  = function(txt) {
    self.logger.dir(txt);
  };
};

// TODO: add deploy provider
Plugin.prototype.registerClientWeb3Provider = function(cb) {
  this.clientWeb3Providers.push(cb);
  this.addPluginType('clientWeb3Provider');
};

Plugin.prototype.registerContractsGeneration = function(cb) {
  this.contractsGenerators.push(cb);
  this.addPluginType('contractGeneration');
};

Plugin.prototype.registerPipeline = function(matcthingFiles, cb) {
  // TODO: generate error for more than one pipeline per plugin
  this.pipeline.push({matcthingFiles: matcthingFiles, cb: cb});
  this.addPluginType('pipeline');
};

Plugin.prototype.addFileToPipeline = function(file, intendedPath, options) {
  this.pipelineFiles.push({file: file, intendedPath: intendedPath, options: options});
  this.addPluginType('pipelineFiles');
};

Plugin.prototype.addContractFile = function(file) {
  this.contractsFiles.push(file);
  this.addPluginType('contractFiles');
};

Plugin.prototype.registerConsoleCommand = function(cb) {
  this.console.push(cb);
  this.addPluginType('console');
};

// TODO: this only works for services done on startup
Plugin.prototype.registerServiceCheck = function(checkName, checkFn, time) {
  this.serviceChecks.push({checkName: checkName, checkFn: checkFn, time: time});
  this.addPluginType('serviceChecks');
};

Plugin.prototype.has = function(pluginType) {
  return this.pluginTypes.indexOf(pluginType) >= 0;
};

Plugin.prototype.addPluginType = function(pluginType) {
  this.pluginTypes.push(pluginType);
  this.pluginTypes = _.uniq(this.pluginTypes);
};

Plugin.prototype.generateProvider = function(args) {
  return this.clientWeb3Providers.map(function(cb) {
    return cb.call(this, args);
  }).join("\n");
};

Plugin.prototype.generateContracts = function(args) {
  return this.contractsGenerators.map(function(cb) {
    return cb.call(this, args);
  }).join("\n");
};

Plugin.prototype.registerContractConfiguration = function(config) {
  this.contractsConfigs.push(config);
  this.addPluginType('contractsConfig');
};

Plugin.prototype.registerCompiler = function(extension, cb) {
  this.compilers.push({extension: extension, cb: cb});
  this.addPluginType('compilers');
};

Plugin.prototype.registerUploadCommand = function(cmd, cb) {
  this.uploadCmds.push({cmd: cmd, cb: cb});
  this.addPluginType('uploadCmds');
};

Plugin.prototype.addCodeToEmbarkJS = function(code) {
  this.embarkjs_code.push(code);
  this.addPluginType('embarkjsCode');
};

Plugin.prototype.addProviderInit = function(providerType, code, initCondition) {
  this.embarkjs_init_code[providerType] = this.embarkjs_init_code[providerType] || [];
  this.embarkjs_init_code[providerType].push([code, initCondition]);
  this.addPluginType('initCode');
};

Plugin.prototype.registerImportFile = function(importName, importLocation) {
  this.imports.push([importName, importLocation]);
  this.addPluginType('imports');
};

Plugin.prototype.registerActionForEvent = function(eventName, cb) {
  if (!this.eventActions[eventName]) {
    this.eventActions[eventName] = [];
  }
  this.eventActions[eventName].push(cb);
  this.addPluginType('eventActions');
};

Plugin.prototype.runFilePipeline = function() {
  var self = this;

  return this.pipelineFiles.map(function(file) {
      var obj = {};
      obj.filename = file.file.replace('./','');
      obj.content = self.loadPluginFile(file.file).toString();
      obj.intendedPath = file.intendedPath;
      obj.options = file.options;
      obj.path = self.pathToFile(obj.filename);

      return obj;
  });
};

Plugin.prototype.runPipeline = function(args) {
  // TODO: should iterate the pipelines
  var pipeline = this.pipeline[0];
  var shouldRunPipeline = utils.fileMatchesPattern(pipeline.matcthingFiles, args.targetFile);
  if (shouldRunPipeline) {
    return pipeline.cb.call(this, args);
  } else {
    return args.source;
  }
};

module.exports = Plugin;
<|endoftext|>


<commit_before>TBD<commit_msg>Fixed test for #612<commit_after>"use strict";

var marko_template = module.exports = require("marko/html").t(__filename),
    marko_component = {
        test: function(e) {
          return;
        }
      },
    marko_components = require("marko/components"),
    marko_registerComponent = marko_components.rc,
    marko_componentType = marko_registerComponent("/marko-test$1.0.0/autotests/components-compilation/class-method-empty-return/index.marko", function() {
      return module.exports;
    }),
    marko_helpers = require("marko/runtime/html/helpers"),
    marko_attr = marko_helpers.a;

function render(input, out, __component, component, state) {
  var data = input;

  out.w("

");
}

marko_template._ = marko_components.r(render, {
    type: marko_componentType
  }, marko_component);

marko_template.Component = marko_components.c(marko_component, marko_template._);

marko_template.meta = {
    deps: [
      {
          type: "require",
          path: "./"
        }
    ]
  };
<|endoftext|>


<commit_before>var exec = require( 'child_process' ).exec,
	path = require( 'path' );

exports.exists = require( 'fs' ).exists;
exports.parse = require( 'plist' ).parseFile;

exports.find = function( id, callback ) {
	var pathQuery = 'mdfind "kMDItemCFBundleIdentifier=="' + id + '"" | head -1';

	exec( pathQuery, function( err, stdout ) {
		var loc = stdout.trim();

		if ( loc === '' ) {
			loc = null;
			err = 'not installed';
		}

		callback( err, loc );
	} );
};

exports.getInfoPath = function( p ) {
	return path.join( p, 'Contents', 'Info.plist' );
};
<commit_msg>change parseFile to parse<commit_after>var exec = require( 'child_process' ).exec,
	path = require( 'path' );

exports.exists = require( 'fs' ).exists;
exports.parse = require( 'plist' ).parse;

exports.find = function( id, callback ) {
	var pathQuery = 'mdfind "kMDItemCFBundleIdentifier=="' + id + '"" | head -1';

	exec( pathQuery, function( err, stdout ) {
		var loc = stdout.trim();

		if ( loc === '' ) {
			loc = null;
			err = 'not installed';
		}

		callback( err, loc );
	} );
};

exports.getInfoPath = function( p ) {
	return path.join( p, 'Contents', 'Info.plist' );
};
<|endoftext|>


<commit_before>function nutTray(partlist, cols, rows, boxSize, canvas) {
	var self = this;

	var _cols = cols;
	var _rows= rows;
	var _trayBoxSize = boxSize;
	var _trayCanvas = canvas;
	var _parts = partlist;

	self.render = function() {
		_drawTray();
		for (var i in _parts()) {
			_drawPart(_parts()[i], "black");
		}
	}

	self.selectPart = function(x, y) {
		var canvasBoxSize = _getCanvasBoxSize();
		col = Math.floor(x/(canvasBoxSize+1)) + 1;
		row = Math.floor(((_rows*canvasBoxSize)-y)/(canvasBoxSize-1)) + 1;

		self.render();

		var part = _getPartId(col, row);
		if(part) {
			_drawPart(part, "red");
		}
		return part.id;
	}

	function _drawTray () {
		if (_trayCanvas && _trayCanvas.getContext) {
			var ctx = _trayCanvas.getContext("2d");
			if (ctx) {
				var size_x = ctx.canvas.width;
				var size_y = ctx.canvas.height;
				var canvasBoxSize = _getCanvasBoxSize();

				//initialize white tray
				ctx.strokeStyle = "black";
				ctx.fillStyle = "white";
				ctx.lineWidth = 1;
				ctx.fillRect(0,0,size_x,size_y);
				ctx.strokeRect (0,0,size_x,size_y);

				for(var x=0; x<_cols; x++) {
					for(var y=0; y<_rows; y++) {
						_drawTrayBox(x+1, y+1, canvasBoxSize);
					}
				}
			}
		}
	}

	//draw a part into a tray box
	function _drawPart(part, color) {
		//clear old box
		var canvasBoxSize = _getCanvasBoxSize();
		_drawTrayBox(part.col, part.row, canvasBoxSize);

		var scale = canvasBoxSize/_trayBoxSize;
		var col_offset = part.col*canvasBoxSize-canvasBoxSize+4;
		var row_offset = _rows*canvasBoxSize-part.row*canvasBoxSize+4;
		// use function fom trayUtil.js to actually draw the component
		drawPart(part, _trayCanvas, col_offset+canvasBoxSize/2, row_offset+canvasBoxSize/2, col_offset, row_offset, scale, color, 0);
	}

	// draw a single tray box
	function _drawTrayBox(col, row, size) {
		col -=1;
		row -=1;
		if (_trayCanvas && _trayCanvas.getContext) {
			var ctx = _trayCanvas.getContext("2d");
			if (ctx) {
				ctx.lineWidth = 4;
				ctx.strokeStyle = "green";
				ctx.fillStyle = "white";
				ctx.strokeRect (col*size+ctx.lineWidth/2,(_rows-1)*size-row*size+ctx.lineWidth/2,size-ctx.lineWidth/2,size-ctx.lineWidth/2);
				ctx.fillRect (col*size+ctx.lineWidth,(_rows-1)*size-row*size+ctx.lineWidth,size-ctx.lineWidth,size-ctx.lineWidth);
			}
		}
	}

	// returns the box size to use the available canvas-space in an optimal way
	function _getCanvasBoxSize() {
		var boxSize = 0;
		if (_trayCanvas && _trayCanvas.getContext) {
			var ctx = _trayCanvas.getContext("2d");
			if (ctx) {
				var size_x = ctx.canvas.width;
				var size_y = ctx.canvas.height;
				boxSize = Math.min((size_x-4)/_cols, (size_y-4)/_rows);
			}
		}
		return Math.floor(boxSize);
	}

	// select partId from col/row
	function _getPartId(col, row) {
		var result = false;
		for (var i in _parts()) {
			if((_parts()[i].col == col) && (_parts()[i].row == row)) {
				result = _parts()[i];
				break;
			}
		}
		return result;
	}
}
<commit_msg>nutTray.js: migrate octoMagnetPNP changes<commit_after>function nutTray(cols, rows, boxSize, config, canvas) {
	var self = this;

	var _cols = cols;
	var _rows= rows;
	var _trayBoxSize = boxSize;
	var _trayCanvas = canvas;
	var _config = JSON.parse(config);
	var _parts = {};

	self.erase = function() {
		_parts = {};
		_drawTray();
	}

	self.addPart = function(part) {
		// sanitiy checks!?
		// add part to dict
		_parts[part.id] = part;

		_parts[part.id].row = parseInt(((part.partPosition) / _cols)) + 1;
		_parts[part.id].col = (part.partPosition) % _cols + 1;

		// and draw to canvas
		_drawPart(part.id, part.threadSize, part.type, "#aaa");
	}

	self.selectPart = function(x, y) {
		var canvasBoxSize = _getCanvasBoxSize();
		col = Math.floor(x/(canvasBoxSize+1)) + 1;
		row = Math.floor(((_rows*canvasBoxSize)-y)/(canvasBoxSize-1)) + 1;

		for (var id in _parts) {
			_drawPart(id, _parts[id].threadSize, _parts[id].type, "#aaa");
		}

		var partId = _getPartId(col, row);
		if(partId) {
			_drawPart(partId, _parts[partId].threadSize, _parts[partId].type, "red");
		}
		return partId;
	}

	function _drawTray () {
		if (_trayCanvas && _trayCanvas.getContext) {
			var ctx = _trayCanvas.getContext("2d");
			if (ctx) {
				var size_x = ctx.canvas.width;
				var size_y = ctx.canvas.height;
				var canvasBoxSize = _getCanvasBoxSize();

				//initialize white tray
				ctx.strokeStyle = "black";
				ctx.fillStyle = "white";
				ctx.lineWidth = 1;
				ctx.fillRect(0,0,size_x,size_y);
				ctx.strokeRect (0,0,size_x,size_y);

				for(var x = 0; x < _rows; x++) {
					for(var y = 0; y < _cols; y++) {
						_drawTrayBox(y + 1, x + 1, canvasBoxSize);
					}
				}
			}
		}
	}

	//draw a part into a tray box
	function _drawPart(partID, threadSize, type, color) {
		part = _parts[partID];

		//clear old box
		var canvasBoxSize = _getCanvasBoxSize();
		_drawTrayBox(part.col, part.row, canvasBoxSize);

		if (_trayCanvas && _trayCanvas.getContext) {
			var ctx = _trayCanvas.getContext("2d");
			var scale = canvasBoxSize/_trayBoxSize;
			if (ctx) {
				var col_offset = part.col*canvasBoxSize-canvasBoxSize+4;
				var row_offset = _rows*canvasBoxSize-part.row*canvasBoxSize+4;

				//print part names
				ctx.font = "8px Verdana";
				ctx.fillStyle = "#000000";
				ctx.textBaseline = "top";
				ctx.fillText("partnr " + part.id, col_offset, row_offset + canvasBoxSize - 16);

				partOutlineSize = (partSize * 5 + 3) * (canvasBoxSize / 100)
				// let size = parseFloat(threadSize) * 5;
				let size = partOutlineSize;
				x = (part.col - 1) * canvasBoxSize + 4 / 2 + canvasBoxSize / 2;
				y = _rows * canvasBoxSize - (part.row - 1) * canvasBoxSize + 4 / 2 - canvasBoxSize / 2;

				ctx.fillStyle = color;
				ctx.beginPath();
				if (slotOrientation === "flat") {
					if (type === "hexnut") {
						for (let i = 0; i < 360; i += 60) {
							ctx.lineTo(x + Math.sin(i * Math.PI / 180) * size * 0.45, y + Math.cos(i * Math.PI / 180) * size * 0.45);
						}
					}
					else if (type === "squarenut") {
						ctx.lineTo(x - size / 2, y -  size / 2);
						ctx.lineTo(x +  size / 2,y - size / 2);
						ctx.lineTo(x + size / 2,y + size / 2);
						ctx.lineTo(x - size / 2, y + size / 2);
					}
					ctx.closePath();
					ctx.fill();

					ctx.beginPath();
					ctx.fillStyle = "white";
					ctx.arc(x, y, size / 7.0, 0, 2 * Math.PI);
					ctx.fill();
					ctx.closePath();
				} else if (slotOrientation === "upright") {
					if (type === "hexnut") {
						ctx.beginPath();
						ctx.lineTo(x + partOutlineSize / 6, y - partOutlineSize / 2);
						ctx.lineTo(x + partOutlineSize / 6, y + partOutlineSize / 2);
						ctx.lineTo(x - partOutlineSize / 6, y + partOutlineSize / 2);
						ctx.lineTo(x - partOutlineSize / 6, y - partOutlineSize / 2);
						ctx.closePath();
						ctx.fill();

						ctx.beginPath();
						ctx.moveTo(x - partOutlineSize / 6, y + partOutlineSize / 4);
						ctx.lineTo(x + partOutlineSize / 6, y + partOutlineSize / 4);
						ctx.moveTo(x - partOutlineSize / 6, y - partOutlineSize / 4);
						ctx.lineTo(x + partOutlineSize / 6, y - partOutlineSize / 4);
						ctx.stroke();
					} else if (type === "squarenut") {
						ctx.beginPath();
						ctx.lineTo(x + partOutlineSize / 6, y - partOutlineSize / 2);
						ctx.lineTo(x + partOutlineSize / 6, y + partOutlineSize / 2);
						ctx.lineTo(x - partOutlineSize / 6, y + partOutlineSize / 2);
						ctx.lineTo(x - partOutlineSize / 6, y - partOutlineSize / 2);
						ctx.fill();
					}
				}

			}
		}
	}

	// draw a single tray box
	function _drawTrayBox(col, row, size) {
		col -=1;
		row -=1;
		if (_trayCanvas && _trayCanvas.getContext) {
			var ctx = _trayCanvas.getContext("2d");
			if (ctx) {
				var canvasBoxSize = _getCanvasBoxSize();
				ctx.lineWidth = 1;
				ctx.strokeStyle = "black";
				ctx.fillStyle = "white";
				ctx.strokeRect (col*size+ctx.lineWidth/2,(_rows-1)*size-row*size+ctx.lineWidth/2,size-ctx.lineWidth/2,size-ctx.lineWidth/2);
				ctx.fillRect (col*size+ctx.lineWidth,(_rows-1)*size-row*size+ctx.lineWidth,size-ctx.lineWidth,size-ctx.lineWidth);
				x = col * size + ctx.lineWidth / 2 + size / 2 + 1.5;
				y = (_rows - 1) * size - row * size + ctx.lineWidth / 2 + size / 2 + 1.5;

				nutShape = _config[(parseInt(row)) * parseInt(_cols) + parseInt(col)].nut
				partSize = _config[(parseInt(row)) * parseInt(_cols) + parseInt(col)].thread_size
				slotOrientation = _config[(parseInt(row)) * parseInt(_cols) + parseInt(col)].slot_orientation
				partOutlineSize = (partSize * 5 + 3) * (canvasBoxSize / 100)

				ctx.beginPath();
				ctx.fillStyle = '#888';
				ctx.font = "8px Verdana";
				ctx.fillText("M" + partSize + " " + nutShape.replace("nut",""), x - canvasBoxSize / 2.0 + 4, y - canvasBoxSize / 2.0 + 10);
				ctx.fillText(slotOrientation, x - canvasBoxSize / 2.0 + 4, y - canvasBoxSize / 2.0 + 18);
				ctx.fillStyle = '#000';
				if (nutShape === "hexnut") {
					if (slotOrientation === "flat") {
						for (let i = 0; i < 360; i += 60) {
							ctx.lineTo(x + Math.sin(i * Math.PI / 180) * partOutlineSize * 0.45, y + Math.cos(i * Math.PI / 180) * partOutlineSize * 0.45);
						}
					} else if (slotOrientation === "upright") {
						ctx.moveTo(x - partOutlineSize / 6, y + partOutlineSize / 4);
						ctx.lineTo(x + partOutlineSize / 6, y + partOutlineSize / 4);
						ctx.moveTo(x - partOutlineSize / 6, y - partOutlineSize / 4);
						ctx.lineTo(x + partOutlineSize / 6, y - partOutlineSize / 4);

						ctx.moveTo(x - partOutlineSize / 6, y - partOutlineSize / 2);
						ctx.lineTo(x + partOutlineSize / 6, y - partOutlineSize / 2);
						ctx.lineTo(x + partOutlineSize / 6, y + partOutlineSize / 2);
						ctx.lineTo(x - partOutlineSize / 6, y + partOutlineSize / 2);
						ctx.lineTo(x - partOutlineSize / 6, y - partOutlineSize / 2);
					}
				} else if (nutShape === "squarenut") {
					if (slotOrientation === "flat") {
						ctx.lineTo(x - partOutlineSize / 2, y - partOutlineSize / 2);
						ctx.lineTo(x + partOutlineSize / 2, y - partOutlineSize / 2);
						ctx.lineTo(x + partOutlineSize / 2, y + partOutlineSize / 2);
						ctx.lineTo(x - partOutlineSize / 2, y + partOutlineSize / 2);
					} else if (slotOrientation === "upright") {
						ctx.lineTo(x + partOutlineSize / 6, y - partOutlineSize / 2);
						ctx.lineTo(x + partOutlineSize / 6, y + partOutlineSize / 2);
						ctx.lineTo(x - partOutlineSize / 6, y + partOutlineSize / 2);
						ctx.lineTo(x - partOutlineSize / 6, y - partOutlineSize / 2);
					}
				}
				ctx.closePath();
				ctx.lineWidth = 1;
				ctx.stroke();
			}
		}
	}

	// returns the box size to use the available canvas-space in an optimal way
	function _getCanvasBoxSize() {
		var boxSize = 0;
		if (_trayCanvas && _trayCanvas.getContext) {
			var ctx = _trayCanvas.getContext("2d");
			if (ctx) {
				var size_x = ctx.canvas.width;
				var size_y = ctx.canvas.height;
				boxSize = Math.min((size_x-4)/_cols, (size_y-4)/_rows);
			}
		}
		return Math.floor(boxSize);
	}

	// select partId from col/row
	function _getPartId(col, row) {
		var result = false;
		for (var id in _parts) {
			if((_parts[id].col == col) && (_parts[id].row == row)) {
				result = id;
				break;
			}
		}
		return result;
	}
}

<|endoftext|>