This repository has been archived by the owner on May 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ModuleSystem.iced
94 lines (75 loc) · 2.63 KB
/
ModuleSystem.iced
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
88
89
90
91
92
93
94
logger = require('log4js').getLogger 'ModuleSystem'
fs = require 'fs'
path = require 'path'
# TODO if some kind of semaphore in the start and stop logic
module.exports = ModuleSystem =
# all the running modules
running: {}
init: (dir, bot) ->
@dir = dir if dir
@dirName = path.basename dir
@bot = bot if bot
_toRequireName: (name) -> "./#{@dirName}/#{name}"
_scanDir: (cb) ->
await fs.readdir @dir, defer err, files
return cb err if err
available = files.map (name) -> name.replace '.iced', ''
cb null, available
# start 'name' if not already started
start: (name, cb) ->
# if exists in running, return
return cb 'module is already started' if @running[name]
# otherwise start it
# logger.debug "[fake] starting module #{name}"
# @running[name] = 'kaas'
# cb()
logger.info "starting module #{name}"
try
module = require @_toRequireName name
await @running[name] = module @bot, defer err
if err
logger.info "module #{name} started with err", err
else
logger.info "module #{name} started"
cb err
catch error
logger.warn "could not start module #{name}", error
cb error
# stop 'name' if not already stopped
stop: (name, cb) ->
# if not exists in running, return
return cb 'module does not exists' if not @running[name]
# otherwise stop it
logger.info "stopping module #{name}"
await @running[name] defer err
if err
logger.info "module #{name} stopped with err", err
else
logger.info "module #{name} stopped"
# delete it in our own cache
delete @running[name]
# delete it in global require cache
delete require.cache[require.resolve(@_toRequireName(name))]
cb err
startAll: (cb) ->
# calls start on everything in available
await @_scanDir defer err, available
return cb false if err
started = []
for name in available
await @start name, defer err
if err
logger.warn "Error while starting module #{name}"
else
started.push name
cb started
stopAll: (cb) ->
# calls stop on eveything in running
stopped = []
for name in Object.keys @running
await @stop name, defer err
if err
logger.warn "Error while stopping module #{name}"
else
stopped.push name
cb stopped