Ejemplo n.º 1
0
module.exports = (() => {
    const commandLineArgs = require('command-line-args');
    const commandLineUsage = require('command-line-usage');

    const commandLineDefs = [
        { name: 'help', alias: 'h', type: Boolean, description: 'Show this help' },
        { name: 'config', alias: 'c', type: String, description: 'Location of config.json' },
        { name: 'version', alias: 'v', type: Boolean, description: 'Show ffffng version' }
    ];

    let commandLineOptions;
    try {
        commandLineOptions = commandLineArgs(commandLineDefs);
    } catch (e) {
        console.error(e.message);
        console.error('Try \'--help\' for more information.');
        process.exit(1);
    }

    const fs = require('graceful-fs');

    const packageJsonFile = __dirname + '/../package.json';
    let version = 'unknown';
    if (fs.existsSync(packageJsonFile)) {
        version = JSON.parse(fs.readFileSync(packageJsonFile, 'utf8')).version;
    }

    function usage () {
        console.log(commandLineUsage([
            {
                header: 'ffffng - ' + version + ' - Freifunk node management form',
                optionList: commandLineDefs
            }
        ]));
    }

    if (commandLineOptions.help) {
        usage();
        process.exit(0);
    }

    if (commandLineOptions.version) {
        console.log('ffffng - ' + version);
        process.exit(0);
    }

    if (!commandLineOptions.config) {
        usage();
        process.exit(1);
    }

    const deepExtend = require('deep-extend');

    const defaultConfig = {
        server: {
            baseUrl: 'http://localhost:8080',
            port: 8080,

            databaseFile: '/tmp/ffffng.sqlite',
            peersPath: '/tmp/peers',

            logging: {
                directory: '/tmp/logs',
                debug: false,
                profile: false,
                logRequests: false
            },

            internal: {
                active: false,
                user: 'admin',
                password: 'secret'
            },

            email: {
                from: 'Freifunk Knotenformular <no-reply@musterstadt.freifunk.net>',

                // For details see: https://nodemailer.com/2-0-0-beta/setup-smtp/
                smtp: {
                    host: 'mail.example.com',
                    port: '465',
                    secure: true,
                    auth: {
                        user: 'user@example.com',
                        pass: 'pass'
                    }
                }
            },

            map: {
                nodesJsonUrl: ['http://map.musterstadt.freifunk.net/nodes.json']
            }
        },
        client: {
            community: {
                name: 'Freifunk Musterstadt',
                domain: 'musterstadt.freifunk.net',
                contactEmail: 'kontakt@musterstadt.freifunk.net',
                sites: [],
                domains: []
            },
            legal: {
                privacyUrl: null,
                imprintUrl: null
            },
            map: {
                mapUrl: 'http://map.musterstadt.freifunk.net'
            },
            monitoring: {
                enabled: false
            },
            coordsSelector: {
                showInfo: false,
                showBorderForDebugging: false,
                localCommunityPolygon: [],
                lat: 53.565278,
                lng: 10.001389,
                defaultZoom: 10,
                layers: {}
            }
        }
    };

    const configJSONFile = commandLineOptions.config;
    let configJSON = {};

    if (fs.existsSync(configJSONFile)) {
        configJSON = JSON.parse(fs.readFileSync(configJSONFile, 'utf8'));
    } else {
        console.error('config.json not found: ' + configJSONFile);
        process.exit(1);
    }

    const _ = require('lodash');

    function stripTrailingSlash (obj, field) {
        const url = obj[field];
        if (_.isString(url) && _.last(url) === '/') {
            obj[field] = url.substr(0, url.length - 1);
        }
    }

    const config = deepExtend({}, defaultConfig, configJSON);

    stripTrailingSlash(config.server, 'baseUrl');
    stripTrailingSlash(config.client.map, 'mapUrl');

    const url = require('url');
    config.server.rootPath = url.parse(config.server.baseUrl).pathname;
    config.client.rootPath = config.server.rootPath;

    return {
        config,
        version
    }
})()
Ejemplo n.º 2
0
Archivo: index.js Proyecto: taion/jest
  requireModule(
    from: Path,
    moduleName?: string,
    options: ?InternalModuleOptions,
  ) {
    const moduleID = this._resolver.getModuleID(
      this._virtualMocks,
      from,
      moduleName,
    );
    let modulePath;

    const moduleRegistry =
      !options || !options.isInternalModule
        ? this._moduleRegistry
        : this._internalModuleRegistry;

    // Some old tests rely on this mocking behavior. Ideally we'll change this
    // to be more explicit.
    const moduleResource = moduleName && this._resolver.getModule(moduleName);
    const manualMock =
      moduleName && this._resolver.getMockModule(from, moduleName);
    if (
      (!options || !options.isInternalModule) &&
      !moduleResource &&
      manualMock &&
      manualMock !== this._isCurrentlyExecutingManualMock &&
      this._explicitShouldMock[moduleID] !== false
    ) {
      modulePath = manualMock;
    }

    if (moduleName && this._resolver.isCoreModule(moduleName)) {
      // $FlowFixMe
      return require(moduleName);
    }

    if (!modulePath) {
      modulePath = this._resolveModule(from, moduleName);
    }

    if (!moduleRegistry[modulePath]) {
      // We must register the pre-allocated module object first so that any
      // circular dependencies that may arise while evaluating the module can
      // be satisfied.
      const localModule = {
        exports: {},
        filename: modulePath,
        id: modulePath,
      };
      moduleRegistry[modulePath] = localModule;
      if (path.extname(modulePath) === '.json') {
        localModule.exports = this._environment.global.JSON.parse(
          stripBOM(fs.readFileSync(modulePath, 'utf8')),
        );
      } else if (path.extname(modulePath) === '.node') {
        // $FlowFixMe
        localModule.exports = require(modulePath);
      } else {
        this._execModule(localModule, options);
      }
    }
    return moduleRegistry[modulePath].exports;
  }
var fs = require('graceful-fs'),
    path = require('path'),
    _ = require('lodash'),
    glob = require('glob'),
    Q = require('q');

var stagecraftStubDir = path.resolve(__dirname, '../dashboards'),
    stagecraftStubGlob = path.resolve(stagecraftStubDir, '**/*.json');

var departments = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../departments.json')));

var dashboards = [
  {
    slug: 'licensing',
    title: 'Licensing',
    'dashboard-type': 'transaction'
  }
];

function readModule(file) {
  var defer = Q.defer();
  fs.readFile(file, 'utf8', function (err, dashboardData) {
    var dashboard;
    if (err) {
      if (err.code === 'EISDIR') {
        defer.resolve();
        return;
      } else {
        defer.reject(err);
        throw err;
      }
Ejemplo n.º 4
0
	function GlobalRoom(roomid) {
		this.id = roomid;

		// init battle rooms
		this.battleCount = 0;
		this.searchers = [];

		// Never do any other file IO synchronously
		// but this is okay to prevent race conditions as we start up PS
		this.lastBattle = 0;
		try {
			this.lastBattle = parseInt(fs.readFileSync('logs/lastbattle.txt')) || 0;
		} catch (e) {} // file doesn't exist [yet]

		this.chatRoomData = [];
		try {
			this.chatRoomData = JSON.parse(fs.readFileSync('config/chatrooms.json'));
			if (!Array.isArray(this.chatRoomData)) this.chatRoomData = [];
		} catch (e) {} // file doesn't exist [yet]

		if (!this.chatRoomData.length) {
			this.chatRoomData = [{
				title: 'Lobby',
				isOfficial: true,
				autojoin: true
			}, {
				title: 'Staff',
				isPrivate: true,
				staffRoom: true,
				staffAutojoin: true
			}];
		}

		this.chatRooms = [];

		this.autojoin = []; // rooms that users autojoin upon connecting
		this.staffAutojoin = []; // rooms that staff autojoin upon connecting
		for (var i = 0; i < this.chatRoomData.length; i++) {
			if (!this.chatRoomData[i] || !this.chatRoomData[i].title) {
				console.log('ERROR: Room number ' + i + ' has no data.');
				continue;
			}
			var id = toId(this.chatRoomData[i].title);
			console.log("NEW CHATROOM: " + id);
			var room = Rooms.createChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]);
			if (room.aliases) {
				for (var a = 0; a < room.aliases.length; a++) {
					aliases[room.aliases[a]] = room;
				}
			}
			this.chatRooms.push(room);
			if (room.autojoin) this.autojoin.push(id);
			if (room.staffAutojoin) this.staffAutojoin.push(id);
		}

		// this function is complex in order to avoid several race conditions
		var self = this;
		this.writeNumRooms = (function () {
			var writing = false;
			var lastBattle;	// last lastBattle to be written to file
			var finishWriting = function () {
				writing = false;
				if (lastBattle < self.lastBattle) {
					self.writeNumRooms();
				}
			};
			return function () {
				if (writing) return;

				// batch writing lastbattle.txt for every 10 battles
				if (lastBattle >= self.lastBattle) return;
				lastBattle = self.lastBattle + 10;

				writing = true;
				fs.writeFile('logs/lastbattle.txt.0', '' + lastBattle, function () {
					// rename is atomic on POSIX, but will throw an error on Windows
					fs.rename('logs/lastbattle.txt.0', 'logs/lastbattle.txt', function (err) {
						if (err) {
							// This should only happen on Windows.
							fs.writeFile('logs/lastbattle.txt', '' + lastBattle, finishWriting);
							return;
						}
						finishWriting();
					});
				});
			};
		})();

		this.writeChatRoomData = (function () {
			var writing = false;
			var writePending = false; // whether or not a new write is pending
			var finishWriting = function () {
				writing = false;
				if (writePending) {
					writePending = false;
					self.writeChatRoomData();
				}
			};
			return function () {
				if (writing) {
					writePending = true;
					return;
				}
				writing = true;
				var data = JSON.stringify(self.chatRoomData).replace(/\{"title"\:/g, '\n{"title":').replace(/\]$/, '\n]');
				fs.writeFile('config/chatrooms.json.0', data, function () {
					// rename is atomic on POSIX, but will throw an error on Windows
					fs.rename('config/chatrooms.json.0', 'config/chatrooms.json', function (err) {
						if (err) {
							// This should only happen on Windows.
							fs.writeFile('config/chatrooms.json', data, finishWriting);
							return;
						}
						finishWriting();
					});
				});
			};
		})();

		// init users
		this.users = {};
		this.userCount = 0; // cache of `Object.size(this.users)`
		this.maxUsers = 0;
		this.maxUsersDate = 0;

		this.reportUserStatsInterval = setInterval(
			this.reportUserStats.bind(this),
			REPORT_USER_STATS_INTERVAL
		);
	}
Ejemplo n.º 5
0
exports.convert = function(flow, icon, done) {

    var icon_folder = util.normalize(path.join(icon.source, 'windows'));
    var icon_file = icon.dest+'.ico';
    var icon_source = util.normalize(path.join(icon_folder, icon_file));
	var cpp_path = path.join(flow.project.paths.build,'cpp');

    flow.log(3, 'icons / converting %s for use', icon.source );

    var icon_xml = path.join(__dirname,'windows','icon.xml');

    	//first copy the ico to the build folder
    util.copy_path(flow, icon_source, path.join(cpp_path, icon_file));
    	//and copy the xml file to include the icon in the exe
    util.copy_path(flow, icon_xml, path.join(cpp_path, '__icon.xml'));
    	//then copy the icon.rc file to the build folder, it needs to be templated to the icon dest name
    var context = { icon : icon.dest };
    var content = fs.readFileSync(path.join(__dirname,'windows/icon.rc'), 'utf8');
    var template = bars.compile(content);
    var rccontent = template(context);

    var rcfilepath = path.join(cpp_path,'icon.rc');

    fse.ensureFileSync(rcfilepath);
    fs.writeFileSync(rcfilepath, rccontent, 'utf8');

    	//:todo: configure/safety
        //note: uses 2013 first because that's the default
    var vsdir = process.env['VS120COMNTOOLS'] ||
                process.env['VS150COMNTOOLS'] ||
                process.env['VS140COMNTOOLS'] ||
                process.env['VS110COMNTOOLS'] ||
                process.env['VS100COMNTOOLS'];

    flow.log(3, 'icons - vsdir detected as `%s`', vsdir);
    flow.log(3, 'icons -       checked 120: `%s`', process.env['VS120COMNTOOLS']);
    flow.log(3, 'icons -       checked 140: `%s`', process.env['VS140COMNTOOLS']);
    flow.log(3, 'icons -       checked 110: `%s`', process.env['VS110COMNTOOLS']);
    flow.log(3, 'icons -       checked 100: `%s`', process.env['VS100COMNTOOLS']);

    if(!vsdir) {

        flow.log(1,'icons - failed - do you have visual C++ installed?');

        flow.project.failed = true;

        if(done) {
            done('cannot find vs directory');
        }

        return;

    } //vsdir

    var vsvars = path.resolve(vsdir, '../../vc/vcvarsall.bat');

    cmd.exec(flow,'cmd.exe', ['/c', vsvars, '&&', 'rc', '/r', 'icon.rc'], {cwd:cpp_path,quiet:true}, function(code,out,err) {

    	if(!code) {

                //finally, for windows icons, we append a hxcpp include
                //so that it can link against the icon.
            flow.project.prepared.hxcpp.includes['__icon'] = {
                name:'__icon', file:'__icon.xml', path:'__icon.xml',
                source:'flow internal', internal:true
            };

            flow.log(3,'icons - ok - will be embedded in exe at link time');
        } else {
            flow.log(1,'icons - failed - see log above');
        }

        if(done) {
            done();
        }

    });

} //convert
Ejemplo n.º 6
0
Archivo: npmrc.js Proyecto: jspm/npm
function safeRead(filepath) {
  if (fs.existsSync(filepath))
    return fs.readFileSync(filepath).toString();
}
Ejemplo n.º 7
0
exports.getParser = function (platformName) {

  if (!platformName) {
    return false;
  }

  var folderAddress = path.join(platformsFolder, platformName);
  var pfile = false;

  if (fs.existsSync(folderAddress) && fs.statSync(folderAddress).isDirectory()) {

    var parserAddress = path.join(folderAddress, '/parser');
    var parserJsAddress = path.join(folderAddress, '/parser.js');
    var parserMiscAddress;
    var firstLine;
    var match;
    var lang = '';

    if (fs.existsSync(parserAddress) && fs.statSync(parserAddress).isFile()) {

      firstLine = fs.readFileSync(parserAddress, 'utf8').split('\n')[0];
      match = /^\#\!\/usr\/bin\/env ([a-zA-Z]+)$/.exec(firstLine);

      if (match && match[1]) {

        lang = match[1];
      }
      pfile = {
          path: parserAddress,
          language: lang
        };
    } else if (fs.existsSync(parserJsAddress) && fs.statSync(parserJsAddress).isFile()) {

      firstLine = fs.readFileSync(parserJsAddress, 'utf8').split('\n')[0];
      match = /^\#\!\/usr\/bin\/env ([a-zA-Z]+)$/.exec(firstLine);

      if (match && match[1]) {

        lang = match[1];
      }
      pfile = {
          path: parserJsAddress,
          language: lang
        };
    } else {

      var fileNames = fs.readdirSync(folderAddress);

      for (var i = 0; i < fileNames.length; i++) {

        parserMiscAddress = path.join(folderAddress, fileNames[i]);

        if (/^parser\.[a-zA-Z0-9]+$/.test(fileNames[i])
          && fs.statSync(parserMiscAddress).isFile()) {

          firstLine = fs.readFileSync(parserMiscAddress, 'utf8').split('\n')[0];
          match = /^\#\!\/usr\/bin\/env ([a-zA-Z]+)$/.exec(firstLine);

          if (match && match[1]) {

            lang = match[1];
          }
          pfile = {
              path: parserMiscAddress,
              language: lang
            };
        }
      }
    }
  }

  return pfile;
};
Ejemplo n.º 8
0
    fs.mkdirSync(process.env.HOME + path.sep + '.jspm');
  }
  catch(e) {
    if (e.code != 'EEXIST')
      ui.log('err', 'Unable to create jspm system folder\n' + e.stack);
  }
  try {
    fs.writeFileSync(globalConfigFile, JSON.stringify(exports.globalConfig, null, 2));
  }
  catch(e) {
    ui.log('err', 'Unable to write global configuration file\n' + e.stack);
  }
}
if (fs.existsSync(globalConfigFile)) {
  try {
    exports.globalConfig = JSON.parse(fs.readFileSync(globalConfigFile) + '');
  }
  catch(e) {
    ui.log('err', 'Unable to read global configuration file');
    exports.globalConfig = {};
  }
}
else {
  exports.globalConfig = {};
  if (process.env.HOME)
    saveGlobalConfig();
}

exports.set = function(name, val) {
  var nameParts = name.split('.');
Ejemplo n.º 9
0
var client_bot = require('./client_bot.js');
var url_map = new HashMap();
var hoturl_map = new HashMap();
var keys;//record all key from url_map
var values;//record all values from url_map

var index=0;
var real_index=index+1;
//var list_num=10;
var list_num=parseInt(process.argv[2]);
var total_list_num=parseInt(process.argv[3]);

var date_start;
var date_end;

var list_config = JSON.parse(fs.readFileSync(`${__dirname}/getBoardname/config/setting`));
var list_name = list_config['list_filename'];
var hot_list_name = list_config['hot_list_filename'];

var board_flag="";

//var numWorkers = require('os').cpus().length;
//console.log("numWorkers:"+numWorkers);

readhotURL(hot_list_name,function(msg){
    init(list_num);
});

function init(lnum){
    var toDir = "test1";
    var i;
Ejemplo n.º 10
0
}

var projectConf = path.resolve(__dirname, '..', '..', '.npmrc')
try {
  fs.statSync(projectConf)
} catch (er) {
  // project conf not found, probably working with packed npm
  fs.writeFileSync(projectConf, function () { /*
save-prefix = ~
legacy-bundling = true
  */ }.toString().split('\n').slice(1, -1).join('\n'))
}

var projectRc = path.join(__dirname, '..', 'fixtures', 'config', '.npmrc')
try {
  fs.statSync(projectRc)
} catch (er) {
  // project conf not found, probably working with packed npm
  fs.writeFileSync(projectRc, 'just = testing')
}

if (module === require.main) {
  // set the globalconfig in the userconfig
  var uc = fs.readFileSync(userconfigSrc)
  var gcini = 'globalconfig = ' + exports.globalconfig + '\n'
  fs.writeFileSync(exports.userconfig, gcini + uc)

  console.log('1..1')
  console.log('ok 1 setup done')
}
Ejemplo n.º 11
0
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

var fs = require('graceful-fs');
var jasminePit = require('jasmine-pit');
var JasmineReporter = require('./JasmineReporter');
var path = require('path');
var utils = require('../lib/utils');

var JASMINE_PATH = require.resolve('../../vendor/jasmine/jasmine-1.3.0');
var jasmineFileContent =
  fs.readFileSync(require.resolve(JASMINE_PATH), 'utf8');

var JASMINE_ONLY_ROOT = path.dirname(require.resolve('jasmine-only'));
var POTENTIALLY_PRECOMPILED_FILE = path.join(
  JASMINE_ONLY_ROOT,
  'app',
  'js',
  'jasmine_only.js'
);
var COFFEE_SCRIPT_FILE = path.join(
  JASMINE_ONLY_ROOT,
  'app',
  'js',
  'jasmine_only.coffee'
);
Ejemplo n.º 12
0
  '.json',
  '/index.js',
]

module.exports = Scripts

Builder.extend(Scripts)

/**
 * require() implementation.
 * Not included by default.
 *
 * @api public
 */

Scripts.require = fs.readFileSync(require.resolve('component-require2'), 'utf8');

/**
 * Return the entry point of a tree.
 * i.e. the canonical name of the first component
 * with a JS entry point, allowing you to
 * `require(<canonical>.canonical)` to initiate all the
 * components.
 *
 * @param {Object} tree
 * @return {Object} tree
 * @api public
 */

Scripts.canonical = function (tree) {
  // main root has it's own scripts,
Ejemplo n.º 13
0
  /**
   * Send a mail using mail settings
   * Require sender, receiver(s), and a smtp server
   */
  function sendFeedback(req, res) {
    res.header('Content-Type', 'application/json; charset=utf-8');
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');

    var feedback = req.body;

    if (!feedback || !feedback.note) {
      res.send(400);
      return;
    }

    var username;
    if (feedback.username) {
      username = feedback.username;
    } else if (req.user) {
      username = req.user.username;
    }

    var subject = '[ezPAARSE] Feedback ';
    subject += username ? 'de ' + username : 'anonyme';
    var text = "Utilisateur : " + (username ? username : "non connecté");
    if (feedback.browser) {
      if (feedback.browser.userAgent) { text += '\nNavigateur : ' + feedback.browser.userAgent; }
      if (feedback.browser.platform)  { text += '\nPlateforme : ' + feedback.browser.platform; }
    }
    text += "\n===============================\n\n";
    text += feedback.note;


    var mailOptions = {
      from: config.EZPAARSE_ADMIN_MAIL,
      to: config.EZPAARSE_FEEDBACK_RECIPIENTS,
      subject: subject,
      text: text,
      attachments: []
    };

    if (feedback.img) {
      mailOptions.attachments.push({
        fileName: "screenshot.png",
        contents: new Buffer(feedback.img.replace(/^data:image\/png;base64,/, ""), "Base64")
      });
    }

    if (feedback.report) {
      mailOptions.attachments.push({
        fileName: "report.json",
        contents: feedback.report
      });
    } else if (req.cookies && req.cookies.lastJob) {
      var jobID      = req.cookies.lastJob;
      var reportFile = path.join(__dirname, '/../tmp/jobs/',
        jobID.charAt(0),
        jobID.charAt(1),
        jobID,
        'report.json');
      if (fs.existsSync(reportFile)) {
        mailOptions.attachments.push({
          fileName: "report.json",
          contents: fs.readFileSync(reportFile)
        });
      }
    }

    // send mail with defined transport object
    smtpTransport.sendMail(mailOptions, function (error, response) {
      if (error) {
        console.log(error);
        res.send(500);
      } else {
        console.log("Message sent: " + response.message);
        res.send(201, {});
      }
    });
  }
Ejemplo n.º 14
0
 readJSON: function ( filePath ) {
   return circularJson.parse( fs.readFileSync( filePath ).toString() );
 },
Ejemplo n.º 15
0
module.exports = (filePath, config) => {
  const mtime = fs.statSync(filePath).mtime;
  const mapCacheKey = filePath + '_' + mtime.getTime();

  if (cache.has(mapCacheKey)) {
    return cache.get(mapCacheKey);
  }

  let fileData = fs.readFileSync(filePath, 'utf8');
  // If the file data starts with a shebang remove it. Leaves the empty line
  // to keep stack trace line numbers correct.
  if (fileData.startsWith('#!')) {
    fileData = fileData.replace(/^#!.*/, '');
  }

  if (!preprocessorRegExpCache.has(config)) {
    preprocessorRegExpCache.set(
      config,
      new RegExp(config.preprocessorIgnorePatterns.join('|'))
    );
  }
  const regex = preprocessorRegExpCache.get(config);
  if (
    config.scriptPreprocessor &&
    (
      !config.preprocessorIgnorePatterns.length || !regex.test(filePath)
    )
  ) {
    const preprocessor = require(config.scriptPreprocessor);
    if (typeof preprocessor.process !== 'function') {
      throw new TypeError(
        'Jest: a preprocessor must export a `process` function.'
      );
    }

    if (config.cache === true) {
      const baseCacheDir = path.join(config.cacheDirectory, 'preprocess-cache');
      const cacheKey = getCacheKey(preprocessor, fileData, filePath, config);
      // Create sub folders based on the cacheKey to avoid creating one
      // directory with many files.
      const cacheDir = path.join(baseCacheDir, cacheKey[0] + cacheKey[1]);
      const cachePath = path.join(
        cacheDir,
        path.basename(filePath, path.extname(filePath)) + '_' + cacheKey
      );
      createDirectory(cacheDir);
      const cachedData = readCacheFile(filePath, cachePath);
      if (cachedData) {
        fileData = cachedData;
      } else {
        fileData = preprocessor.process(fileData, filePath, config);
        writeCacheFile(cachePath, fileData);
      }
    } else {
      fileData = preprocessor.process(fileData, filePath, config);
    }
  }

  cache.set(mapCacheKey, fileData);
  return fileData;
};
Ejemplo n.º 16
0
  requireModule(currPath, moduleName) {
    const moduleID = this._getNormalizedModuleID(currPath, moduleName);
    let modulePath;

    // I don't like this behavior as it makes the module system's mocking
    // rules harder to understand. Would much prefer that mock state were
    // either "on" or "off" -- rather than "automock on", "automock off",
    // "automock off -- but there's a manual mock, so you get that if you ask
    // for the module and one doesnt exist", or "automock off -- but theres a
    // useAutoMock: false entry in the package.json -- and theres a manual
    // mock -- and the module is listed in the unMockList in the test config
    // -- soooo...uhh...fuck I lost track".
    //
    // To simplify things I'd like to move to a system where tests must
    // explicitly call .mock() on a module to receive the mocked version if
    // automocking is off. If a manual mock exists, that is used. Otherwise
    // we fall back to the automocking system to generate one for you.
    //
    // The only reason we're supporting this in jest for now is because we
    // have some tests that depend on this behavior. I'd like to clean this
    // up at some point in the future.
    let manualMockResource = null;
    let moduleResource = null;
    moduleResource = this._getModule(moduleName);
    manualMockResource = this._getMockModule(moduleName);
    if (
      !moduleResource &&
      manualMockResource &&
      manualMockResource !== this._isCurrentlyExecutingManualMock &&
      this._explicitShouldMock[moduleID] !== false
    ) {
      modulePath = manualMockResource;
    }

    if (resolve.isCore(moduleName)) {
      return require(moduleName);
    }

    if (!modulePath) {
      modulePath = this._resolveModuleName(currPath, moduleName);
    }

    if (!modulePath) {
      throw new Error(`Cannot find module '${moduleName}' from '${currPath}'`);
    }

    let moduleObj;
    moduleObj = this._moduleRegistry[modulePath];
    if (!moduleObj) {
      // We must register the pre-allocated module object first so that any
      // circular dependencies that may arise while evaluating the module can
      // be satisfied.
      moduleObj = {
        __filename: modulePath,
        exports: {},
      };

      this._moduleRegistry[modulePath] = moduleObj;
      if (path.extname(modulePath) === '.json') {
        moduleObj.exports = this._environment.global.JSON.parse(
          fs.readFileSync(modulePath, 'utf8')
        );
      } else if (path.extname(modulePath) === '.node') {
        moduleObj.exports = require(modulePath);
      } else {
        this._execModule(moduleObj);
      }
    }

    return moduleObj.exports;
  }
import merge from 'lodash/object/merge';
import webpack from 'webpack';
import fs from 'graceful-fs';
import path from 'path';
import * as config from './config';
import writeStats from './utils/write-stats';
import notifyStats from './utils/notify-stats';

const babelrc = JSON.parse(fs.readFileSync(path.join(__dirname, '../.babelrc'), 'utf8'));

export const client = merge({}, config.client, {
  devtool: 'eval',
  entry: {
    main: [
      'webpack-hot-middleware/client'
    ].concat(config.client.entry.main)
  },
  module: {
    loaders: config.client.module.loaders.concat([
      {
        test: /\.jsx?$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: merge({}, babelrc, {
          plugins: [
            'react-transform'
          ],
          extra: {
            'react-transform': {
              transforms: [
                {
Ejemplo n.º 18
0
module.exports.sync = fp => parse(fs.readFileSync(fp, 'utf8'), fp);
Ejemplo n.º 19
0
 it('recognize asar archvies', function () {
   var p = path.join(fixtures, 'asar', 'a.asar', 'link1')
   assert.equal(gfs.readFileSync(p).toString().trim(), 'file1')
 })