示例#1
0
                gitPull(tempRootDirectoryPath, gitUrl, sourceType, sourceBranch, logMethod, function (err) {

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

                    var tempRootDirectoryRelativePath = tempRootDirectoryPath;
                    if (relativePath && relativePath != "/")
                    {
                        tempRootDirectoryRelativePath = path.join(tempRootDirectoryRelativePath, relativePath);
                    }

                    // make sure the tempRootDirectoryRelativePath exists
                    var tempRootDirectoryRelativePathExists = fs.existsSync(tempRootDirectoryRelativePath);
                    if (!tempRootDirectoryRelativePathExists)
                    {
                        return callback({
                            "message": "The relative path: " + relativePath + " does not exist within the Git repository: " + gitUrl
                        });
                    }

                    if (moveToPublic)
                    {
                        // if there isn't a "public" and there isn't a "public_build" directory,
                        // then move files into public
                        var publicExists = fs.existsSync(path.join(tempRootDirectoryRelativePath, "public"));
                        var publicBuildExists = fs.existsSync(path.join(tempRootDirectoryRelativePath, "public_build"));
                        if (!publicExists && !publicBuildExists)
                        {
                            fs.mkdirSync(path.join(tempRootDirectoryRelativePath, "public"));

                            var filenames = fs.readdirSync(tempRootDirectoryRelativePath);
                            if (filenames && filenames.length > 0)
                            {
                                for (var i = 0; i < filenames.length; i++)
                                {
                                    if (!shouldIgnore(path.join(tempRootDirectoryRelativePath, filenames[i])))
                                    {
                                        if ("config" === filenames[i])
                                        {
                                            // skip this
                                        }
                                        else if ("gitana.json" === filenames[i])
                                        {
                                            // skip
                                        }
                                        else if ("descriptor.json" === filenames[i])
                                        {
                                            // skip
                                        }
                                        else if ("public" === filenames[i])
                                        {
                                            // skip
                                        }
                                        else if ("public_build" === filenames[i])
                                        {
                                            // skip
                                        }
                                        else
                                        {
                                            fs.renameSync(path.join(tempRootDirectoryRelativePath, filenames[i]), path.join(tempRootDirectoryRelativePath, "public", filenames[i]));
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // copy everything from temp dir into the store
                    logMethod("[gitCheckout] Copy from temp to store");
                    copyToStore(tempRootDirectoryRelativePath, rootStore, offsetPath, function(err) {

                        logMethod("[gitCheckout] Remove temp dir: " + tempRootDirectoryPath);

                        // now remove temp directory
                        rmdir(tempRootDirectoryPath);

                        logMethod("[gitCheckout] Done");

                        callback(err);
                    });
                });
示例#2
0
var path = require('path')
var viewerMock = require('../mock-viewer')

var fs = require('fs')
var readme = fs.readFileSync(__dirname + '/README.md', 'utf8')
var success = fs.readFileSync(__dirname + '/success.md', 'utf8')
var indexHTML = fs.readFileSync(__dirname + '/index.html', 'utf8')
var files = fs.readdirSync(__dirname + '/files')
var exName = path.basename(__dirname)

// extrasolar.pdf
var url = 'https://view-api.box.com/1/sessions/e2edd7aa94fe460d9d61f649bad94c45/assets/'
  , currentViewer

module.exports = {
    dirname: exName
  , description: readme
  , success: success
  , files: files
  , test: test
  , setup: setup
  , next: require('../next-exercise')(exName)
}

function requireSolution(name, ext) {
  // require solution files in this way so browserify doesnt try to bundle them
  return require(name + '.' + (ext || 'js'))
}

function test(done) {
  if (currentViewer) {
  fs.readFile(path.join(appPath,'plugins','ios.json'), function(err, data) {
    console.log('Reading plugins/ios.json');
    if(err) {
      console.log('Error reading plugins.json');
      callback(err);
      return;
    }
    //get plugins from fqcn directories at project root with a 'plugin.xml' inside
    console.log('Reading plugins from root path dirs...');
    var pluginsDirs = fs.readdirSync(appPath).filter(function getPluginsDirs(e){
      //check for fqcn-style dirs with a 'plugin.xml' inside them
      return e.split('.').length > 2 && fs.existsSync(path.join(appPath,e,'plugin.xml'));
    });
    console.log('Plugins found on project root path: ')
    console.log(pluginsDirs);

    console.log('Reading plugins from plugins path...');
    var pluginsInPluginsDir = fs.readdirSync(path.join(appPath,'plugins')).filter(function getPluginsInDir(e){
      //check for fqcn-style dirs with a 'plugin.xml' inside them
      // console.log(e);
      // console.log("Seems like reversed DNS path:",e.split(".").length > 2);
      // console.log("Has plugin.xml inside("+path.join(appPath,'plugins',e,'plugin.xml')+"):",fs.existsSync(path.join(appPath,e,'plugin.xml')));
      return e.split('.').length > 2 && fs.existsSync(path.join(appPath,'plugins',e,'plugin.xml'));
    });
    console.log('Plugins found on plugins dir: ');
    console.log(pluginsInPluginsDir);

    var pluginsJson = JSON.parse(data);
    console.log('Plugins found on plugins/json: ');
    console.log(Object.keys(pluginsJson.installed_plugins));

    //remove duplicates from concat (dirs and installed_plugins)
    var plugs = arrayUnique(
      Object.keys(pluginsJson.installed_plugins).concat(pluginsDirs).concat(pluginsInPluginsDir))
    //then filter which ever is a dependant plugin
    .filter(function(e){
      return Object.keys(pluginsJson.dependent_plugins).indexOf(e) === -1;
    });

    console.log('Will remove and reinstall these plugins:',plugs);
    // return false;

    //if no plugins are present, just move on
    if(plugs.length < 1) {
      console.log('No plugins to remove/install');
      return callback();
    }
    
    if(report) {
      console.log("Script called with --inspect, aborting");
      callback();
      return;
    }
    process.chdir(appPath);
    cordova.plugin('rm',plugs, function(e){
      if(e) {
        console.log('Error removing plugins from project');
        console.log(plugs);
        if(!force) {
          process.chdir(originalCWD);
          callback(e);
          return;
        }
        console.log('Error removing plugins, but --force implemented, continuing');
      }
      if(!e) console.log('Plugins removed succesfully');
      // return false;
      cordova.plugin('add', plugs, function(e) {
        process.chdir(originalCWD);
        if(e) {
          console.log('Error installing plugins');
          callback(e);
          return;
        }
        console.log('Plugins reinstalled succesfully');
        callback();
      });
    });
  });
示例#4
0
  clearDatabase(sequelize) {
    return sequelize
      .getQueryInterface()
      .dropAllTables()
      .then(() => {
        sequelize.modelManager.models = [];
        sequelize.models = {};

        return sequelize
          .getQueryInterface()
          .dropAllEnums();
      });
  },

  getSupportedDialects() {
    return fs.readdirSync(__dirname + '/../lib/dialects').filter(file => {
      return file.indexOf('.js') === -1 && file.indexOf('abstract') === -1;
    });
  },

  checkMatchForDialects(dialect, value, expectations) {
    if (expectations[dialect]) {
      expect(value).to.match(expectations[dialect]);
    } else {
      throw new Error('Undefined expectation for "' + dialect + '"!');
    }
  },

  getAbstractQueryGenerator(sequelize) {
    class ModdedQueryGenerator extends AbstractQueryGenerator {
      quoteIdentifier(x) {
'use strict';

var path = require('path');
var fs = require('fs');
var gulp = require('gulp');
var loadPlugins = require('gulp-load-plugins');
var plugins = loadPlugins({
	DEBUG: false,
	rename: {
		'gulp-ruby-sass': 'sass'
	}
});
plugins.mainBowerFiles = require('main-bower-files');
plugins.config = require(path.join(__dirname, '../config/global.development.json')).gulp;

var taskFiles = fs.readdirSync(path.join(__dirname, plugins.config.paths.tasks));
taskFiles.forEach(function (taskFile) {
	require(path.join(__dirname, plugins.config.paths.tasks + taskFile))(gulp, plugins);
});

gulp.task('development', ['serve:development']);
示例#6
0
var servers = function(api, next){

  api.servers = {};
  api.servers.servers = [];

  api.servers._start = function(api, next){
    var started = 0;
    if(api.utils.hashLength(api.configData.servers) == 0){ next(); }
    for(var server in api.configData.servers){
      started++;
      api.log("starting server: " + server, "notice");
      api.servers.servers[server]._start(function(){
        process.nextTick(function(){
          started--;
          if(started == 0){ next(); }
        });
      });
    };    
  }

  api.servers._teardown = function(api, next){
    var started = 0;
    if(api.utils.hashLength(api.servers.servers) == 0){ next(); }
    for(var server in api.servers.servers){
      started++;
      api.log("stopping server: " + server, "notice");
      api.servers.servers[server]._teardown(function(){        
        process.nextTick(function(){
          started--;
          if(started == 0){ next(); }
        });
      });
    };
  }

  // Load the servers

  var serverFolders = [ 
    __dirname + "/../servers",
    api.configData.general.paths.server,
  ];
    
  var inits = {}
  for(var i in serverFolders){
    var folder = serverFolders[i];
    if(fs.existsSync(folder)){
      fs.readdirSync(folder).sort().forEach(function(file){
        var fullFilePath = serverFolders[i] + "/" + file;
        var fileParts = file.split('.');
        var ext = fileParts[(fileParts.length - 1)];
        if (file[0] != "." && ext === 'js'){
          var server = file.split(".")[0];
          if(api.configData.servers[server] != null){
            inits[server] = require(fullFilePath)[server];
          }

          if(api.configData.general.developmentMode == true){
            api.watchedFiles.push(fullFilePath);
            (function() {
              fs.watchFile(fullFilePath, {interval:1000}, function(curr, prev){
                if(curr.mtime > prev.mtime){
                  api.log("\r\n\r\n*** rebooting due to server change ***\r\n\r\n", "info");
                  delete require.cache[require.resolve(fullFilePath)];
                  api._commands.restart.call(api._self);
                }
              });
            })();
          }
        }
      });
    }
  }

  var started = 0;
  for(var server in inits){
    started++;
    (function(server){
      var options = api.configData.servers[server];
      inits[server](api, options, function(serverObject){
        api.servers.servers[server] = serverObject;
        api.log("initialized server: " + server, "debug");
        process.nextTick(function(){
          started--;
          if(started == 0){ next(); }
        });
      });
    })(server)
  }
  if(started == 0){ next(); }
}
示例#7
0
var fs = require('fs'),
    path = require('path');

fs.readdirSync(__dirname).forEach(function(file) {
  require('./' + file);
});
示例#8
0
function readdirFullPath(rootDir) {
    return fs.readdirSync(rootDir).map(mapToFullPath.bind(null, rootDir))
}
示例#9
0
    exports.projectsFile      = path.join(exports.userDataDir, 'projects.json');
    exports.settingsFile      = path.join(exports.userDataDir, 'settings.json');

// Create it if the directory is not exists
if (!fs.existsSync(exports.userDataDir)) {
    fs.mkdirSync(exports.userDataDir);
}
if (!fs.existsSync(exports.userExtensionsDir)) {
    fs.mkdirSync(exports.userExtensionsDir);
}
if (!fs.existsSync(exports.userLocalesDir)) {
    fs.mkdirSync(exports.userLocalesDir);
}
// Migration
if (exports.oldUserDataDir !== exports.userDataDir && fs.existsSync(exports.oldUserDataDir)) {
    fs.readdirSync(exports.oldUserDataDir).forEach(function (fileName) {
        fs.renameSync(path.join(exports.oldUserDataDir, fileName), path.join(exports.userDataDir, fileName));
    });
    fs.rmdirSync(exports.oldUserDataDir);
}

/**
 * tmp dir of system
 * @return {String} tmp dir
 */
exports.tmpDir = function () {
    var systemTmpDir =
            process.env.TMPDIR ||
            process.env.TMP ||
            process.env.TEMP ||
            (process.platform === 'win32' ? 'c:\\windows\\temp' : '/tmp');
示例#10
0
var fs=require('fs');
var mongoose=require('mongoose');
var Promise=require('bluebird');

var data={
    connect:function(connectionString){
        mongoose.connect(connectionString);
        console.log('Connected to database');
    }
};

var files=fs.readdirSync(__dirname+'/types-data');

for (var i = 0; len = files.length, i < len; i += 1) {
    var typeData=require('./types-data/'+files[i]);
    data[typeData.name]=typeData.data;
}

module.exports=data;
exports.sqlRestMapper = function(root) {

    var map = {},
        maps = [],
        _processing = {},
        _cur = '';

    _.map(fs.readdirSync(root + '/.'), function(file) {
        if (file === 'map.js' || file === 'baseMap.js' || file === 'queryToRestMap.js') {
            console.log('Loading Base Map: ' + file);
            map = require(root + '/' + file);

        } else if (file != 'index.js' && file != 'map.js' && file.indexOf('.') !== 0) {
            var name = file;
            var ext = path.extname(file);
            if (ext)
                name = name.slice(0, -ext.length);

            maps[name] = require(root + '/' + name);

        } else {
            console.log('Ignoring: ' + file);
        }
    });

    _.map(_.keys(maps), function(_cur) {

        console.log('Loading Map: ' + _cur);
        _processing = maps[_cur];
        _.map(_.keys(_processing), function(key) {

            //grab the entry, BEFORE we munge the key
            var item = _processing[key];

            if (key === 'self' || key === _cur) {
                //Special case of 'self'
                key = _cur;

            } else if (key.indexOf(_cur + '/') === 0) {
                //Already handled

            } else {
                //prepend the root
                key = _cur + '/' + key;

            }

            //If there is ONLY an expanded querystring, use it for basic and vice versa...
            if (!item.queryStringBasic && item.queryStringExpanded)
                item.queryStringBasic = item.queryStringExpanded;

            if (!item.queryStringExpanded && item.queryStringBasic)
                item.queryStringExpanded = item.queryStringBasic;

            //if neither, don't load
            if (item.queryStringBasic)
                if (map[key])
                    console.log('Overriding: ' + key);

            map[key] = item;

        });
    });
    return map;

};
示例#12
0
    function testRun( testOption, jobs ) {
        var fs = require("fs");
        var path = require("path");
        var done = this.async();

        var totalTests = 0;
        var testsDone = 0;
        function testDone() {
            testsDone++;
            if( testsDone >= totalTests ) {
                done();
            }
        }
        var files;
        if( testOption === "aplus" ) {
            files = fs.readdirSync("test/mocha").filter(function(f){
                return /^\d+\.\d+\.\d+/.test(f);
            }).map(function( f ){
                return "mocha/" + f;
            });
        }
        else {
            files = testOption === "all"
                ? fs.readdirSync('test')
                    .concat(fs.readdirSync('test/mocha')
                        .map(function(fileName){
                            return "mocha/" + fileName
                        })
                    )
                : [testOption + ".js" ];


            if( testOption !== "all" &&
                !fs.existsSync( "./test/" + files[0] ) ) {
                files[0] = "mocha/" + files[0];
            }
        }
        files = files.filter(function(fileName){
            if( !node11 && fileName.indexOf("generator") > -1 ) {
                return false;
            }
            return /\.js$/.test(fileName);
        }).map(function(f){
            return f.replace( /(\d)(\d)(\d)/, "$1.$2.$3" );
        });


        var slowTests = files.filter(isSlowTest);
        files = files.filter(function(file){
            return !isSlowTest(file);
        });

        function runFile(file) {
            totalTests++;
            grunt.log.writeln("Running test " + file );
            var env = undefined;
            if (file.indexOf("bluebird-debug-env-flag") >= 0) {
                env = Object.create(process.env);
                env["BLUEBIRD_DEBUG"] = true;
            }
            runIndependentTest(file, function(err) {
                if( err ) throw new Error(err + " " + file + " failed");
                grunt.log.writeln("Test " + file + " succeeded");
                testDone();
                if( files.length > 0 ) {
                    runFile( files.shift() );
                }
            }, env);
        }

        slowTests.forEach(runFile);

        jobs = Math.min( files.length, jobs );
        if (jobs === 1) {
            grunt.option("verbose", true);
        }
        for( var i = 0; i < jobs; ++i ) {
            runFile( files.shift() );
        }
    }
示例#13
0
var rmdirRecursiveSync = function(directoryOrFilePath)
{
    if (!assertSafeToDelete(directoryOrFilePath))
    {
        return false;
    }

    if (!fs.existsSync(directoryOrFilePath))
    {
        return false;
    }

    // get stats about the things we're about to delete
    var isDirectory = false;
    var isFile = false;
    var isLink = false;
    try
    {
        var stat = fs.lstatSync(directoryOrFilePath);

        isDirectory = stat.isDirectory();
        isFile = stat.isFile();
        isLink = stat.isSymbolicLink();

    }
    catch (e)
    {
        console.log("Failed to get lstat for file: " + directoryOrFilePath);
        return false;
    }

    // check if the file is a symbolic link
    // if so, we just unlink it and save ourselves a lot of work
    if (isLink)
    {
        try
        {
            fs.unlinkSync(directoryOrFilePath);
        }
        catch (e)
        {
            console.log("Unable to unlink: " + directoryOrFilePath + ", err: " + JSON.stringify(e));
        }
    }
    else
    {
        // it is a physical directory or file...

        // if it is a directory, dive down into children first
        if (isDirectory)
        {
            var list = null;
            try
            {
                list = fs.readdirSync(directoryOrFilePath);
            }
            catch (e)
            {
                console.log("Failed to read dir for: " + directoryOrFilePath + ", err: " + JSON.stringify(e));
                list = null;
            }

            if (list)
            {
                for (var i = 0; i < list.length; i++)
                {
                    if (list[i] == "." || list[i] == "..")
                    {
                        // skip these files
                        continue;
                    }

                    var childPath = path.join(directoryOrFilePath, list[i]);

                    rmdirRecursiveSync(childPath);
                }
            }
        }

        // now delete the actual file or directory
        if (isFile)
        {
            try
            {
                fs.unlinkSync(directoryOrFilePath);
            }
            catch (e)
            {
                console.log("Unable to delete file: " + directoryOrFilePath + ", err: " + JSON.stringify(e));
            }
        }
        else if (isDirectory)
        {
            try
            {
                fs.rmdirSync(directoryOrFilePath);
            }
            catch (e)
            {
                console.log("Unable to remove directory: " + directoryOrFilePath + ", err: " + JSON.stringify(e));
            }
        }
    }
};
示例#14
0
var copyToStore = exports.copyToStore = function(sourceDirectory, targetStore, offsetPath, callback)
{
    var f = function(filepath, fns) {

        var sourceFilePath = path.join(sourceDirectory, filepath);
        if (!shouldIgnore(sourceFilePath))
        {
            var sourceStats = fs.lstatSync(sourceFilePath);
            if (sourceStats) {
                if (sourceStats.isDirectory()) {

                    // list files
                    var filenames = fs.readdirSync(sourceFilePath);
                    if (filenames && filenames.length > 0) {
                        for (var i = 0; i < filenames.length; i++) {
                            f(path.join(filepath, filenames[i]), fns);
                        }
                    }

                }
                else if (sourceStats.isFile()) {

                    // STORE: CREATE_FILE
                    fns.push(function (sourceFilePath, filepath, targetStore) {
                        return function (done) {
                            //console.log("source: " + sourceFilePath);
                            fs.readFile(sourceFilePath, function (err, data) {

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

                                var targetFilePath = filepath;
                                if (offsetPath)
                                {
                                    targetFilePath = path.join(offsetPath, targetFilePath);
                                }

                                //console.log("target: " + targetFilePath);

                                targetStore.writeFile(targetFilePath, data, function (err) {
                                    done(err);
                                });
                            });
                        };
                    }(sourceFilePath, filepath, targetStore));
                }
            }
        }
    };

    var copyFunctions = [];

    var filenames = fs.readdirSync(sourceDirectory);
    for (var i = 0; i < filenames.length; i++)
    {
        f(filenames[i], copyFunctions);
    }

    // run all the copy functions
    async.series(copyFunctions, function (errors) {
        callback();
    });

};
示例#15
0
文件: meteor.js 项目: Cahya/meteor
    func: function (argv) {
      // reparse args
      var opt = require('optimist')
            .describe('example', 'Example template to use.')
            .boolean('list')
            .describe('list', 'Show list of available examples.')
            .usage(
              "Usage: meteor create [--release <release>] <name>\n" +
                "       meteor create [--release <release>] --example <example_name> [<name>]\n" +
                "       meteor create --list\n" +
                "\n" +
                "Make a subdirectory named <name> and create a new Meteor project\n" +
                "there. You can also pass an absolute or relative path.\n" +
                "\n" +
                "The project will use the release of Meteor specified with the --release\n" +
                "option, or the latest available version if the option is not specified.\n" +
                "\n" +
                "You can pass --example to start off with a copy of one of the Meteor\n" +
                "sample applications. Use --list to see the available examples.");

      var new_argv = opt.argv;
      var appPath;

      var example_dir = path.join(__dirname, '..', 'examples');
      var examples = _.reject(fs.readdirSync(example_dir), function (e) {
        return (e === 'unfinished' || e === 'other'  || e[0] === '.');
      });

      if (argv._.length === 1) {
        appPath = argv._[0];
      } else if (argv._.length === 0 && new_argv.example) {
        appPath = new_argv.example;
      }

      if (new_argv['list']) {
        process.stdout.write("Available examples:\n");
        _.each(examples, function (e) {
          process.stdout.write("  " + e + "\n");
        });
        process.stdout.write("\n" +
                             "Create a project from an example with 'meteor create --example <name>'.\n");
        process.exit(1);
      };

      if (argv.help || !appPath) {
        process.stdout.write(opt.help());
        process.exit(1);
      }

      if (fs.existsSync(appPath)) {
        process.stderr.write(appPath + ": Already exists\n");
        process.exit(1);
      }

      if (files.findAppDir(appPath)) {
        process.stderr.write(
          "You can't create a Meteor project inside another Meteor project.\n");
        process.exit(1);
      }

      var transform = function (x) {
        return x.replace(/~name~/g, path.basename(appPath));
      };

      if (new_argv.example) {
        if (examples.indexOf(new_argv.example) === -1) {
          process.stderr.write(new_argv.example + ": no such example\n\n");
          process.stderr.write("List available applications with 'meteor create --list'.\n");
          process.exit(1);
        } else {
          files.cp_r(path.join(example_dir, new_argv.example), appPath, {
            ignore: [/^local$/]
          });
        }
      } else {
        files.cp_r(path.join(__dirname, 'skel'), appPath, {
          transform_filename: function (f) {
            return transform(f);
          },
          transform_contents: function (contents, f) {
            if ((/(\.html|\.js|\.css)/).test(f))
              return new Buffer(transform(contents.toString()));
            else
              return contents;
          },
          ignore: [/^local$/]
        });
      }

      // Use the global release version, so that it isn't influenced by the
      // release version of the app dir you happen to be inside now.
      project.writeMeteorReleaseVersion(appPath, context.globalReleaseVersion);

      process.stderr.write(appPath + ": created");
      if (new_argv.example &&
          new_argv.example !== appPath)
        process.stderr.write(" (from '" + new_argv.example + "' template)");
      process.stderr.write(".\n\n");

      process.stderr.write(
        "To run your new app:\n" +
          "   cd " + appPath + "\n" +
          "   meteor\n");
    }
示例#16
0
//be used to create a menu.html

var fs = require("fs");

var base = "./src/";
var files = fs.readdirSync(base);

var html = fs.readFileSync("./menu.html").toString();
var ul_html = '\n<div class="view">';
files.forEach(function(f){
    var npath = base + f;
    var array;

    if(fs.lstatSync(npath).isDirectory()){
        array = findHtml(npath);

        if(array.length > 0){
            ul_html += '\n<p>' + f + '</p>\n<ul class="main">\n';

            array.forEach(function(p){
                var title = /<title>(.*)<\/title>/.test(fs.readFileSync(p[0]).toString()) ? RegExp.$1 : "Document";
                ul_html += '<li><a href="' + p[0] + '" target="_blank">' + title + '(' + p[1] + ')</a></li>\n';
            });

            ul_html += '</ul>\n';
        }
    }
});
ul_html += "</div>\n";
html = html.replace(/(<body>)[\s\S]*?(<\/body>)/ , "$1"+ul_html+"$2");
fs.writeFileSync("./menu.html" , html);
示例#17
0
 *
 * @param {String} message
 */
function logWarn(message)
{
	if(options.log) console.warn("apidoc: " + message.yellow);
} // logWarn
var app = {
	debug: debug,
	log: log,
	logWarn: logWarn,
	filters: {},
	parsers: {},
	workers: {}
}; // app
fs.readdirSync(path.dirname(module.filename) + '/plugins').forEach(function(filename) {
	if (filename.lastIndexOf('.js') !== filename.length - 3)
		return;
	var basename = path.basename(filename, '.js');
	var name = basename.split('_');
	var type = name.shift() + 's';
	name = name.join('');
	app[type][name] = './plugins/' + filename;
});

/**
 * Read package.json Data and optianl descriptions.
 */
function getPackageData()
{
	var packageInfos = {};
var jsx = require('jsx-templates');
var fs = require('fs');
var path = require('path');

var JSX_SRC_PATH = __dirname + '/shared/jsx/';
var JSX_DIST_PATH = __dirname + '/shared/jsx_dist/jsx_dist.js';

var dir = fs.readdirSync(path.resolve(JSX_SRC_PATH));
var result = ["var jsx = require('jsx');"];

dir.forEach(function(file) {
  var filePath = path.resolve(JSX_SRC_PATH, file);
  var input = fs.readFileSync(filePath);
  var name = file.lastIndexOf('.');

  name = file.slice(0, name === -1 ? file.length : name);

  var output = jsx.generate(name, input);
  result.push(output);
});

fs.writeFileSync(path.resolve(JSX_DIST_PATH), result.join('\n\n'));
function getDirectories(srcpath) {
  return fs.readdirSync(srcpath).filter(function(file) {
    return fs.statSync(path.join(srcpath, file)).isDirectory();
  });
}
示例#20
0
    console.log(cmd);
  }
}


var JS_FILES = [
  'cartodb.js',
  'cartodb.uncompressed.js'
]

var CSS_FILES = [
  'cartodb.css',
  'cartodb.ie.css'
]

var CSS_IMAGE_FILES = fs.readdirSync('themes/css/images')

var IMG_FILES = fs.readdirSync('themes/img')

var only_invalidate = process.argv.length > 2 && process.argv[2] == '--invalidate';
var only_current_version = process.argv.length > 2 && process.argv[2] == '--current_version';

if(!only_invalidate) {
  if(!only_current_version) {
    put_files(JS_FILES, 'v2', 'cartodb.js/v2')
    put_files(CSS_FILES, 'v2/themes/css', 'cartodb.js/v2/themes/css')
    put_files(CSS_IMAGE_FILES, 'v2/themes/css/images', 'cartodb.js/v2/themes/css/images')
    put_files(IMG_FILES, 'v2/themes/img', 'cartodb.js/v2/themes/img')
  }

  put_files(JS_FILES, 'v2', 'cartodb.js/v2/' + package_.version)
示例#21
0
var printer = require('../');
var fs = require('fs');
var path = require('path');
var mapnik = require('mapnik');

// defaults
var zoom = 5,
    scale = 4,
    x = 4096,
    y = 4096,
    quality = 256,
    format = 'png';
    limit = 19008;

// fixtures
var tiles = fs.readdirSync(path.resolve(__dirname + '/fixtures')).reduce(function(memo, basename) {
        var key = basename.split('.').slice(0,3).join('.');
        memo[key] = fs.readFileSync(path.resolve(__dirname + '/fixtures/' + basename));
        return memo;
    }, {});

describe('Get center from bbox', function() {
    it('should fail if (x1, y1) and (x2,y2) are equal', function(done) {
        var bbox = [0, 0, 0, 0];

        assert.throws( function() {
            printer.coordsFromBbox(zoom, scale, bbox, limit);
        }, /Incorrect coordinates/);
        done();
    });
    it('should fail if the image is too large', function(done) {
    }
  },
  plugins: [],
  devtool: 'sourcemap',
  debug: !production
};

function getConfig(webpackConfig) {
  let config = extend({}, sharedConfig);
  return extend(config, webpackConfig);
}

//
// BACKEND CONFIG
//
fs.readdirSync('node_modules')
  .forEach(function(module) {
    node_modules[module] = 'commonjs ' + module;
  });

backendConfig = getConfig({
  entry: ['babel-polyfill', './server/init.js'],
  target: 'node',
  node: {
    __filename: true,
    __dirname: false
  },
  externals: node_modules,
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'backend.js'
示例#23
0
const getFolders = dir => {
    return fs.readdirSync(dir)
        .filter(function(file) {
            return fs.statSync(path.join(dir, file)).isDirectory();
        });
};
示例#24
0
 listFiles: function(path){
         var myArr = Array()
         myArr[0] = '/files/test.json';
         return fs.readdirSync(__dirname + path)
     }
示例#25
0
文件: taskmgr.js 项目: kmpm/hydra
TaskMgr.prototype.refresh = function(){
  var dirs = fs.readdirSync(TASKSPATH);
  for(var i in dirs){
    this.parseTask(dirs[i]);
  }
}
describe('Nuclide service parser test suite.', () => {
  beforeEach(function() {
    addMatchers(this);
  });

  for (const file of fs.readdirSync(nuclideUri.join(__dirname, 'fixtures'))) {
    if (file.endsWith('.def')) {
      it(`Successfully parses ${file}`, () => {
        const fixturePath = nuclideUri.join(__dirname, 'fixtures', file);
        const code = fs.readFileSync(fixturePath, 'utf8');
        const expected = JSON.parse(
          fs.readFileSync(nuclideUri.join(__dirname, 'fixtures', file) + '.json', 'utf8'));
        const definitions = parseServiceDefinition(file, code);
        expect(mapDefinitions(definitions)).diffJson(expected);
      });
    }
  }

  it('duplicate global definitions throw', () => {
    const code = `
      export function f(): void {}
      export class f {
        m(): void {}
        dispose(): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('duplicate member definitions throw', () => {
    const code = `
      export class f {
        m(): void {}
        m(): void {}
        dispose(): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Invalid dispose arguments throw', () => {
    const code = `
      export class f {
        dispose(x: int): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Invalid dispose return type throw', () => {
    const code = `
      export class f {
        dispose(): int {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Missing dispose throw', () => {
    const code = `
      export class f {
        m(): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Missing type definitions throw', () => {
    const code = `
      export class f {
        m(): Promise<MissingType> {}
        dispose(): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('More missing type definitions throw', () => {
    const code = `
      export class f {
        static m(): Observable<Map<string, {f: [string, ?Set<Array<MissingType>>]}>> {}
        dispose(): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Missing types in functions throw', () => {
    const code = `
      export type UsesMissingType = {
        f: MissingType;
      };
      export function f(p: UsesMissingType): void {}
      `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Missing types in ctor args throw', () => {
    const code = `
      export class C {
        constructor(p: MissingType) {}
        dispose(): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('User defined type conflicting with builtin', () => {
    const code = `
      export class Object {
        constructor() {}
        dispose(): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Promise may only be a return type', () => {
    const code = `
      export class C {
        constructor(p: Promise<string>) {}
        dispose(): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Observable may only be a return type', () => {
    const code = `
      export class C {
        m(p: Array<Observable<number>>): void {}
        dispose(): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('void may only be a return type', () => {
    const code = `
      export class C {
        m(p: void): void {}
        dispose(): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Constructors may not have return types', () => {
    const code = `
      export class C {
        constructor(): Promise<void> {}
        dispose(): void {}
      }`;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Aliases cannot be recursive', () => {
    const code = `
      export type R = R;
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Aliases cannot be recursive throw constructed types', () => {
    const code = `
      export type R = Promise<R>;
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Aliases cannot be mutually recursive', () => {
    const code = `
      export type A = B;
      export type B = A;
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Complex Aliases cannot be mutually recursive', () => {
    const code = `
      export type A = Promise<T>;
      export type T = [O];
      export type O = {f: A};
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Return types must be promise/observable/void', () => {
    const code = `
      export type A = number;
      export function f(): A {};
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Missing type in union throws', () => {
    const code = `
      export type A = B | 42;
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Recursion in union throws', () => {
    const code = `
      export type A = 42 | A;
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Promise in union throws', () => {
    const code = `
      export type A = 42 | Promise<42>;
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Non-literal in union throws', () => {
    const code = `
      export type A = 42 | number;
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Duplicate alternates in union throws', () => {
    const code = `
      export type A = 42 | 42;
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Mismatched alternates in object union throws', () => {
    const code = `
      export type A = {kind: 'foo'} | '42';
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('No valid alternates in object union throws', () => {
    const code = `
      export type A = {kind: 'foo'} | {kind: string};
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('No common discriminants in object union throws', () => {
    const code = `
      export type A = {kind1: 'foo'} | {kind2: 'bar'};
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('Duplicate values in discriminant in object union throws', () => {
    const code = `
      export type A = {kind: 'foo'} | {kind: 'foo'};
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('allows intersections', () => {
    const code = `
      export type A = {x: string} & {y: string};
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).not.toThrow();
  });

  it('disallows intersections of non-object types', () => {
    const code = `
      export type A = {x: string} & boolean;
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('disallows intersections with overlapping fields', () => {
    const code = `
      export type A = {x: string} & {x: string};
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });

  it('importing type aliases not supported', () => {
    const code = `
      import type {A as T} from 'foo';
      export f(p: T): void {};
    `;
    expect(() => {
      parseServiceDefinition('fileName', code);
    }).toThrow();
  });
});
示例#27
0
    fs = require('fs'),
    passport = require('passport'),
    mongoose = require('mongoose'),
    coffee = require('coffee-script')

var env = process.env.NODE_ENV || 'development',
    config = require('./config/environment')[env],
    auth = require('./config/middlewares/authorization')
    
// Bootstrap database
console.log('Connecting to database at ' + config.db)
mongoose.connect(config.db)

// Bootstrap models
var modelsPath = __dirname + '/app/models'
fs.readdirSync(modelsPath).forEach(function (file) {
  require(modelsPath+'/'+file)
});

// bootstrap passport config
require('./config/passport')(passport, config)

var app = express()
// express settings
require('./config/express')(app, config, passport)

// Bootstrap routes
require('./config/routes')(app, config, passport, auth)

// Helper funtions
require('./app/helpers/general')(app)
示例#28
0
const getDirectories = (source) => {
  const list = readdirSync(source).map(name => join(source, name)).filter(isDirectory);
  if (list.length === 0) return ['.'];
  return list;
};
示例#29
0
文件: bootstrap.js 项目: monaca/medic
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var shell = require('shelljs'),
    fs    = require('fs'),
    path  = require('path'),
    libs  = require('./libraries');

var libDir = path.join(__dirname, 'lib');
shell.mkdir('-p', libDir);
shell.rm('-rf', path.join(libDir, 'test'));

var contents = fs.readdirSync(libDir);

var command_queue = [];

for (var i=0; i<libs.platforms.length; i++){
    platform = libs.platforms[i];
    if (contents.indexOf(platform) == -1) {
        // Don't have the lib, get it.
        var cmd = 'git clone ' + libs[platform].git + ' ' + libs[platform].path;
        command_queue.push(cmd);

        cmd = 'cd ' + libs[platform].path + ' && git submodule init && git submodule update';
        command_queue.push(cmd);
    } else {
        // Have the lib, update it.
        var cmd = 'cd ' + path.join(libDir, platform) + ' && git checkout -- . && git checkout master && git pull && git fetch --tags';
示例#30
0
  locales: function() {
    locales = locales ||
      _.without(fs.readdirSync(__dirname + '/../locale'), 'templates');

    return locales;
  },