forked from n42k/brikkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpluginsystem.js
87 lines (74 loc) · 2.7 KB
/
pluginsystem.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const fs = require('fs');
const { execSync } = require('child_process');
const path = require('path');
const disrequire = require('disrequire');
const tmp = require('tmp');
tmp.setGracefulCleanup();
class PluginSystem {
constructor() {
this._plugins = {};
this._cleanup = [];
}
getAvailablePlugins() {
return fs.readdirSync('plugins');
}
loadPlugin(plugin) {
if(plugin.endsWith('zip'))
this._loadPluginZip(plugin);
else
this._loadPluginDirectory(plugin);
}
loadAllPlugins() {
const pluginPaths = this.getAvailablePlugins()
.map(plugin => path.parse(plugin));
// if 2 plugins have the same name (/example/ and /example.zip),
// let's give priority to the ones that are in a directory
// for this, we create a mapping of a bare plugin name (example)
// and the best [that we found so far] filename
const pluginNameMap = {};
pluginPaths.forEach(plugin => {
if(plugin.name in pluginNameMap) {
// if the plugin is already in the map, we gotta compare them
const otherPlugin = pluginNameMap[plugin.name];
// if the other plugin is a zip, the current plugin is
// a directory, thus we prefer it to the other
if(otherPlugin.ext === 'zip')
pluginNameMap[plugin.name] = plugin;
else // otherwise we prefer the other plugin
pluginNameMap[plugin.name] = otherPlugin;
} else // if the plugin isn't in the mapping, simply add it
pluginNameMap[plugin.name] = plugin;
});
this._cleanup.forEach(cleanup => {
if (typeof cleanup === 'function')
cleanup()
});
this._cleanup = [];
Object.values(pluginNameMap).forEach(pluginPath => this.loadPlugin(pluginPath.base));
}
_loadPluginZip(plugin) {
const path = tmp.dirSync().name;
execSync(`unzip ./plugins/${plugin} -d ${path}`);
try {
disrequire(`${path}/index.js`);
} catch(error) {
//lol idc
}
const cleanup = require(`${path}/index.js`);
if (cleanup) {
this._cleanup.push(cleanup);
}
}
_loadPluginDirectory(plugin) {
try {
disrequire(`${process.cwd()}/plugins/${plugin}/index.js`);
} catch(error) {
//lol idc
}
const cleanup = require(`${process.cwd()}/plugins/${plugin}/index.js`);
if (cleanup) {
this._cleanup.push(cleanup);
}
}
}
module.exports = PluginSystem;