-
-
Notifications
You must be signed in to change notification settings - Fork 405
/
Copy pathrouter.js
87 lines (74 loc) · 2.31 KB
/
router.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
'use strict';
const path = require('path');
const titleize = require('titleize');
const humanizeString = require('humanize-string');
const readPkgUp = require('read-pkg-up');
const updateNotifier = require('update-notifier');
const Configstore = require('configstore');
const {namespaceToName} = require('./utils/namespace');
/**
* The router is in charge of handling `yo` different screens.
* @constructor
* @param {Environment} env A yeoman environment instance
* @param {Configstore} [conf] An optional config store instance
*/
class Router {
constructor(env, conf) {
const pkg = require('../package.json');
this.routes = {};
this.env = env;
this.conf = conf || new Configstore(pkg.name, {
generatorRunCount: {}
});
}
/**
* Navigate to a route
* @param {String} name Route name
* @param {*} arg A single argument to pass to the route handler
* @return {Promise} Promise this.
*/
navigate(name, arg) {
if (typeof this.routes[name] === 'function') {
return this.routes[name].call(null, this, arg).then(() => this);
}
throw new Error(`No routes called: ${name}`);
}
/**
* Register a route handler
* @param {String} name Name of the route
* @param {Function} handler Route handler
*/
registerRoute(name, handler) {
this.routes[name] = handler;
return this;
}
/**
* Update the available generators in the app
* TODO: Move this function elsewhere, try to make it stateless.
*/
updateAvailableGenerators() {
this.generators = {};
const resolveGenerators = generator => {
// Skip sub generators
if (!/:(app|all)$/.test(generator.namespace)) {
return;
}
const {packageJson: pkg} = readPkgUp.sync({cwd: path.dirname(generator.resolved)});
if (!pkg) {
return;
}
pkg.namespace = generator.namespace;
pkg.appGenerator = true;
pkg.prettyName = titleize(humanizeString(namespaceToName(generator.namespace)));
pkg.update = updateNotifier({pkg}).update;
if (pkg.update && pkg.version !== pkg.update.latest) {
pkg.updateAvailable = true;
}
this.generators[pkg.name] = pkg;
};
for (const generator of Object.values(this.env.getGeneratorsMeta())) {
resolveGenerators(generator);
}
}
}
module.exports = Router;