-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
76 lines (59 loc) · 1.92 KB
/
main.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
'use strict';
const egg = require('egg');
const path = require('path');
const Command = require('common-bin');
const fs = require('fs');
const detectPort = require('detect-port');
const assert = require('assert');
const cmd = process.cwd();
async function getMainCommand() {
class MainCommand extends Command {
constructor(rawArgv) {
super(rawArgv);
this.usage = 'Usage: egg-artisan <command> [options]';
// load sub command
this.load(path.join(cmd, 'app/artisan'));
}
load(fullPath) {
assert(fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory(),
`${fullPath} should exist and be a directory`);
// load entire directory
const files = fs.readdirSync(fullPath);
const names = [];
for (const file of files) {
if (path.extname(file) === '.js') {
const name = path.basename(file).replace(/\.js$/, '');
names.push(name);
const target = require(path.join(fullPath, file));
const artisanRun = target.prototype.run;
target.prototype.run = function* () {
const options = {};
options.clusterPort = yield detectPort();
// before: ready
const Agent = egg.Agent;
const agent = new Agent(options);
yield agent.ready();
const app = new egg.Application(options);
yield app.ready();
// run
this.ctx = app.createAnonymousContext();
try {
yield this.helper.callFn(artisanRun, arguments, this);
} catch (err) {
yield agent.close();
yield app.close();
throw err;
}
// after: close
yield agent.close();
yield app.close();
process.exit(0);
};
this.add(name, target);
}
}
}
}
return MainCommand;
}
module.exports = getMainCommand;