forked from intelligo-mn/intelligo-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·286 lines (232 loc) · 5.83 KB
/
index.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/env node
const fs = require('fs')
const mkdirp = require('mkdirp')
const path = require('path')
const program = require('commander')
const readline = require('readline')
const util = require('util')
const MODE_0666 = parseInt('0666', 8)
const MODE_0755 = parseInt('0755', 8)
const TEMPLATE_DIR = path.join(__dirname, '.', 'templates')
const VERSION = require('./package').version
let _exit = process.exit
process.exit = exit
around(program, 'optionMissingArgument', function (fn, args) {
program.outputHelp()
fn.apply(this, args)
return { args: [], unknown: [] }
})
before(program, 'outputHelp', function () {
// track if help was shown for unknown option
this._helpShown = true
})
before(program, 'unknownOption', function () {
// allow unknown options if help was shown, to prevent trailing error
this._allowUnknownOption = this._helpShown
// show help if not yet shown
if (!this._helpShown) {
program.outputHelp()
}
})
program
.name('intelligo')
.version(VERSION, ' --version')
.usage('[dir]')
.parse(process.argv)
if (!exit.exited) {
main()
}
/**
* Install an around function; AOP.
*/
function around (obj, method, fn) {
let old = obj[method]
obj[method] = function () {
let args = new Array(arguments.length)
for (let i = 0; i < args.length; i++) args[i] = arguments[i]
return fn.call(this, old, args)
}
}
/**
* Install a before function; AOP.
*/
function before (obj, method, fn) {
let old = obj[method]
obj[method] = function () {
fn.call(this)
old.apply(this, arguments)
}
}
/**
* Prompt for confirmation on STDOUT/STDIN
*/
function confirm (msg, callback) {
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
rl.question(msg, function (input) {
rl.close()
callback(/^y|yes|ok|true$/i.test(input))
})
}
/**
* Copy file from template directory.
*/
function copyTemplate (from, to) {
write(to, fs.readFileSync(path.join(TEMPLATE_DIR, from), 'utf-8'))
}
/**
* Create bot at the given directory.
*
* @param {string} name
* @param {string} dir
*/
function createBotApp (name, dir) {
console.log()
// Package
const pkg = {
name: name,
version: '0.0.0',
private: true,
scripts: {
start: 'node index.js'
},
dependencies: {
'config': '~3.0.1',
'express': '~4.16.1',
'intelligo': '^0.8.7'
}
}
if (dir !== '.') {
mkdir(dir, '.')
}
mkdir(dir, 'config')
copyTemplate('config/default.json', path.join(dir, 'config/default.json'))
copyTemplate('gitignore_temp', path.join(dir, '.gitignore'))
copyTemplate('index.js', path.join(dir, 'index.js'))
write(path.join(dir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n')
const prompt = '$'
if (dir !== '.') {
console.log()
console.log(' change directory:')
console.log(' %s cd %s', prompt, dir)
}
console.log()
console.log(' install dependencies:')
console.log(' %s npm install', prompt)
console.log()
console.log(' run the app:')
console.log(' %s npm start', prompt)
console.log()
}
/**
* Create an app name from a directory path, fitting npm naming requirements.
*
* @param {String} pathName
*/
function createAppName (pathName) {
return path.basename(pathName)
.replace(/[^A-Za-z0-9.-]+/g, '-')
.replace(/^[-_.]+|-+$/g, '')
.toLowerCase()
}
/**
* Check if the given directory `dir` is empty.
*
* @param {String} dir
* @param {Function} fn
*/
function emptyDirectory (dir, fn) {
fs.readdir(dir, function (err, files) {
if (err && err.code !== 'ENOENT') throw err
fn(!files || !files.length)
})
}
/**
* Main program.
*/
function main () {
// Path
let destinationPath = program.args.shift() || '.'
// App name
let appName = createAppName(path.resolve(destinationPath)) || 'intelligo-bot'
// Generate application
emptyDirectory(destinationPath, function (empty) {
if (empty || program.force) {
createBotApp(appName, destinationPath)
} else {
confirm('destination is not empty, continue? [y/N] ', function (ok) {
if (ok) {
process.stdin.destroy()
createBotApp(appName, destinationPath)
} else {
console.error('aborting')
exit(1)
}
})
}
})
}
/**
* Make the given dir relative to base.
*
* @param {string} base
* @param {string} dir
*/
function mkdir (base, dir) {
let loc = path.join(base, dir)
console.log(' \x1b[36mcreate\x1b[0m : ' + loc + path.sep)
mkdirp.sync(loc, MODE_0755)
}
/**
* Generate a callback function for commander to warn about renamed option.
*
* @param {String} originalName
* @param {String} newName
*/
function renamedOption (originalName, newName) {
return function (val) {
warning(util.format("option `%s' has been renamed to `%s'", originalName, newName))
return val
}
}
function exit (code) {
// flush output for Node.js Windows pipe bug
// https://github.com/joyent/node/issues/6247 is just one bug example
// https://github.com/visionmedia/mocha/issues/333 has a good discussion
function done () {
if (!(draining--)) _exit(code)
}
let draining = 0
let streams = [process.stdout, process.stderr]
exit.exited = true
streams.forEach(function (stream) {
// submit empty write request and wait for completion
draining += 1
stream.write('', done)
})
done()
}
/**
* Display a warning similar to how errors are displayed by commander.
*
* @param {String} message
*/
function warning (message) {
console.error()
message.split('\n').forEach(function (line) {
console.error(' warning: %s', line)
})
console.error()
}
/**
* echo str > file.
*
* @param {String} file
* @param {String} str
*/
function write (file, str, mode) {
fs.writeFileSync(file, str, { mode: mode || MODE_0666 })
console.log(' \x1b[36mcreate\x1b[0m : ' + file)
}