This repository has been archived on 2021-07-14. You can view files and clone it, but cannot push or open issues or pull requests.
scriptcraft/src/main/js/lib/plugin.js

100 lines
2.3 KiB
JavaScript

'use strict';
var console = require('./console'),
File = java.io.File,
FileWriter = java.io.FileWriter,
PrintWriter = java.io.PrintWriter;
/*
plugin management
*/
var _plugins = {};
var _plugin = function(/* String */ moduleName, /* Object */ moduleObject, isPersistent ) {
//
// don't load plugin more than once
//
if ( typeof _plugins[moduleName] != 'undefined' ) {
return _plugins[moduleName].module;
}
var pluginData = { persistent: isPersistent, module: moduleObject };
if ( typeof moduleObject.store == 'undefined' ) {
moduleObject.store = {};
}
_plugins[moduleName] = pluginData;
if ( isPersistent ) {
moduleObject.store = persist( moduleName, moduleObject.store );
}
return moduleObject;
};
exports.plugin = _plugin;
var scriptCraftDir = null;
var pluginDir = null;
var dataDir = null;
exports.autoload = function( dir, logger ) {
scriptCraftDir = dir;
pluginDir = new File( dir, 'plugins' );
dataDir = new File( dir, 'data' );
var _canonize = function( file ) {
return '' + file.canonicalPath.replaceAll('\\\\','/');
};
/*
recursively walk the given directory and return a list of all .js files
*/
var _listSourceFiles = function( store, dir ) {
var files = dir.listFiles(),
file;
if ( !files ) {
return;
}
for ( var i = 0; i < files.length; i++ ) {
file = files[i];
if ( file.isDirectory( ) ) {
_listSourceFiles( store, file );
}else{
if ( file.canonicalPath.endsWith( '.js' ) ) {
store.push( file );
}
}
}
};
/*
Reload all of the .js files in the given directory
*/
(function( pluginDir ) {
var sourceFiles = [],
property,
module,
pluginPath;
_listSourceFiles( sourceFiles, pluginDir );
var len = sourceFiles.length;
if ( config.verbose ) {
console.info( len + ' scriptcraft plugins found.' );
}
for ( var i = 0; i < len; i++ ) {
pluginPath = _canonize( sourceFiles[i] );
module = {};
try {
module = require( pluginPath );
for ( property in module ) {
/*
all exports in plugins become global
*/
global[property] = module[property];
}
} catch ( e ) {
logger.severe( 'Plugin ' + pluginPath + ' ' + e );
}
}
}(pluginDir));
};