forked from jlord/workshopper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workshopper.js
executable file
·440 lines (371 loc) · 12.9 KB
/
workshopper.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
const argv = require('optimist').argv
, fs = require('fs')
, path = require('path')
, mkdirp = require('mkdirp')
, map = require('map-async')
, msee = require('msee')
, http = require('http')
, ecstatic = require('ecstatic')
const showMenu = require('./menu')
, verify = require('./verify')
, printText = require('./print-text')
, repeat = require('./term-util').repeat
, bold = require('./term-util').bold
, red = require('./term-util').red
, green = require('./term-util').green
, yellow = require('./term-util').yellow
, center = require('./term-util').center
const defaultWidth = 65
function Workshopper (options) {
if (!(this instanceof Workshopper))
return new Workshopper(options)
if (typeof options != 'object')
throw new TypeError('need to provide an options object')
if (typeof options.name != 'string')
throw new TypeError('need to provide a `name` String option')
if (typeof options.title != 'string')
throw new TypeError('need to provide a `title` String option')
if (typeof options.appDir != 'string')
throw new TypeError('need to provide an `appDir` String option')
this.name = options.name
this.title = options.title
this.subtitle = options.subtitle
this.menuOptions = options.menu
this.helpFile = options.helpFile
this.creditsFile = options.creditsFile
this.prerequisitesFile = options.prerequisitesFile
this.width = typeof options.width == 'number' ? options.width : defaultWidth
this.appDir = options.appDir
this.dataDir = path.join(
process.env.HOME || process.env.USERPROFILE
, '.config'
, this.name
)
mkdirp.sync(this.dataDir)
}
Workshopper.prototype.init = function () {
if (argv.h || argv.help || argv._[0] == 'help')
return this._printHelp()
if (argv.s || argv.server || argv._[0] == 'server')
if (argv._[1]) {
return this._runServer(argv._[1])
} else {
return this._runServer()
}
if (argv._[0] == 'credits')
return this._printCredits()
if (argv._[0] == 'prerequisites')
return this._printPrerequisities()
if (argv.v || argv.version || argv._[0] == 'version')
return console.log(this.name + '@' + require(path.join(this.appDir, 'package.json')).version)
if (argv._[0] == 'list') {
return this.problems().forEach(function (name) {
console.log(name)
})
}
if (argv._[0] == 'current')
return console.log(this.getData('current'))
if (argv._[0] == 'select' || argv._[0] == 'print') {
return onselect.call(this, argv._.length > 1
? argv._.slice(1).join(' ')
: this.getData('current')
)
}
var run = argv._[0] == 'run'
if (argv._[0] == 'verify' || run)
return this.verify(run)
this.printMenu()
}
Workshopper.prototype.verify = function (run) {
var current = this.getData('current')
, setupFn
, dir
, setup
if (!current) {
console.error('ERROR: No active problem. Select a challenge from the menu.')
return process.exit(1)
}
dir = this.dirFromName(current)
setupFn = require(dir + '/setup.js')
if (!setupFn.async) {
setup = setupFn(run)
return setTimeout(this.runSolution.bind(this, setup, dir, current, run), setup.wait || 1)
}
setupFn(run, function (err, setup) {
if (err) {
console.error('An error occurred during setup:', err)
return console.error(err.stack)
}
setTimeout(this.runSolution.bind(this, setup, dir, current, run), setup.wait || 1)
}.bind(this))
}
Workshopper.prototype.printMenu = function () {
var menu = showMenu({
name : this.name
, title : this.title
, subtitle : this.subtitle
, width : this.width
, completed : this.getData('completed') || []
, problems : this.problems()
, menu : this.menuOptions
, credits : this.creditsFile && fs.existsSync(this.creditsFile)
, prerequisites : this.prerequisitesFile && fs.existsSync(this.prerequisitesFile)
})
menu.on('select', onselect.bind(this))
menu.on('exit', function () {
console.log()
process.exit(0)
})
menu.on('help', function () {
console.log()
return this._printHelp()
}.bind(this))
menu.on('credits', function () {
console.log()
return this._printCredits()
}.bind(this))
menu.on('prerequisites', function () {
console.log()
return this._printPrerequisites()
}.bind(this))
}
Workshopper.prototype.problems = function () {
if (!this._problems)
this._problems = require(path.join(this.appDir, 'menu.json'))
return this._problems
}
Workshopper.prototype.getData = function (name) {
var file = path.resolve(this.dataDir, name + '.json')
try {
return JSON.parse(fs.readFileSync(file, 'utf8'))
} catch (e) {}
return null
}
Workshopper.prototype.updateData = function (name, fn) {
var json = {}
, file
try {
json = this.getData(name)
} catch (e) {}
file = path.resolve(this.dataDir, name + '.json')
fs.writeFileSync(file, JSON.stringify(fn(json)))
}
Workshopper.prototype.dirFromName = function (name) {
return path.join(
this.appDir
, 'problems'
, name.toLowerCase()
.replace(/\s/g, '_')
.replace(/[^a-z_]/gi, '')
)
}
Workshopper.prototype.runSolution = function (setup, dir, current, run) {
console.log(
bold(yellow((run ? 'Running' : 'Verifying') + ' "' + current + '"...')) + '\n'
)
var a = submissionCmd(dir, setup)
, b = solutionCmd(dir, setup)
, v = verify(a, b, {
a : setup.a
, b : setup.b
, long : setup.long
, run : run
, custom : setup.verify
})
v.on('pass', onpass.bind(this, setup, dir, current))
v.on('fail', onfail.bind(this, setup, dir, current))
if (run && setup.close)
v.on('end', setup.close)
if (setup.stdin) {
setup.stdin.pipe(v)
setup.stdin.resume()
}
if (setup.a && (!setup.a._readableState || !setup.a._readableState.flowing))
setup.a.resume()
if (setup.b && (!setup.a._readableState || !setup.a._readableState.flowing))
setup.b.resume()
}
function solutionCmd (dir, setup) {
var args = setup.args || setup.solutionArgs || []
, exec
if (setup.solutionExecWrap) {
exec = [ require.resolve('./exec-wrapper') ]
exec = exec.concat(setup.solutionExecWrap)
exec = exec.concat(dir + '/solution.js')
} else {
exec = [ dir + '/solution.js' ]
}
return exec.concat(args)
}
function submissionCmd (dir, setup) {
var filename = argv._[1]
if (!filename) filename = dir + '/verify.js'
var args = setup.args || setup.submissionArgs || []
, exec
if (setup.modUseTrack) {
// deprecated
exec = [
require.resolve('./exec-wrapper')
, require.resolve('./module-use-tracker')
, setup.modUseTrack.trackFile
, setup.modUseTrack.modules.join(',')
, filename
]
} else if (setup.execWrap) {
exec = [ require.resolve('./exec-wrapper') ]
exec = exec.concat(setup.execWrap)
exec = exec.concat(filename)
} else {
exec = [ filename ]
}
return exec.concat(args)
}
Workshopper.prototype._printHelp = function () {
this._printUsage()
if (this.helpFile)
printText(this.name, this.appDir, this.helpFile)
}
Workshopper.prototype._runServer = function (lang) {
var server = http.createServer(
ecstatic({ root: this.appDir + '/guide' })
).listen(0)
server.on('listening', function () {
var addr = this.address()
var langLocation = addr.port + (lang ? '/index-' + lang + '.html' : '')
console.log('Open this in your browser: %s%s', 'http://localhost:' + langLocation , '\n'
+ 'Open a new terminal window and run `git-it` again.\n'
+ 'When you are done with server, press CTRL + C to end it.')
})
}
Workshopper.prototype._printCredits = function () {
if (this.creditsFile)
printText(this.name, this.appDir, this.creditsFile)
}
Workshopper.prototype._printPrerequisites = function () {
if (this.prerequisitesFile)
printText(this.name, this.appDir, this.prerequisitesFile)
}
Workshopper.prototype._printUsage = function () {
printText(this.name, this.appDir, path.join(__dirname, './usage.txt'))
}
function onpass (setup, dir, current) {
console.log(bold(green('# PASS')))
console.log(green(bold('\nYour solution to ' + current + ' passed!')))
if (setup.hideSolutions)
return
// console.log('\nHere\'s what the official solution is if you want to compare notes:\n')
var solutions = fs.readdirSync(dir).filter(function (file) {
return (/^solution.*\.js/).test(file)
}).map(function (file) {
return {
name: file
, content: fs.readFileSync(path.join(dir, file), 'utf8')
.toString()
.replace(/^/gm, ' ')
}
})
, completed
, remaining
map(
solutions
, function (file, i, callback) {
// code fencing is necessary for msee to render the solution as code
file.content = msee.parse('```js\n' + file.content + '\n```')
callback(null, file)
}
, function (err, solutions) {
if (err)
throw err
// solutions.forEach(function (file, i) {
// console.log(repeat('-', this.width) + '\n')
// if (solutions.length > 1)
// console.log(bold(file.name) + ':\n')
// console.log(file.content)
// if (i == solutions.length - 1)
// console.log(repeat('-', this.width) + '\n')
// }.bind(this))
this.updateData('completed', function (xs) {
if (!xs) xs = []
var ix = xs.indexOf(current)
return ix >= 0 ? xs : xs.concat(current)
})
completed = this.getData('completed') || []
remaining = this.problems().length - completed.length
if (remaining === 0) {
console.log('You\'ve finished all the challenges! Hooray!\n')
} else {
console.log(repeat('-', this.width) + '\n')
console.log(
'You have '
+ remaining
+ ' challenge'
+ (remaining != 1 ? 's' : '')
+ ' left.'
)
console.log('Type `' + this.name + '` to show the menu.\n')
console.log(repeat('-', this.width) + '\n')
}
if (setup.close)
setup.close()
}.bind(this)
)
}
function onfail (setup, dir, current) {
if (setup.close) setup.close()
console.log(bold(red('# FAIL')))
if (typeof setup.verify == 'function')
console.log('\nYour solution to ' + current + ' didn\'t pass. Try again!')
else
console.log('\nYour solution to ' + current + ' didn\'t match the expected output.\nTry again!')
console.log(repeat('-', this.width) + '\n')
}
function onselect (name) {
console.log('\n ' + repeat('#', 69))
console.log(center(this.width, '~~ ' + name + ' ~~'))
console.log(' ' + repeat('#', 69) + '\n')
var dir = this.dirFromName(name)
, txt = path.resolve(dir, 'problem.txt')
, md = path.resolve(dir, 'problem.md')
, file
this.updateData('current', function () {
return name
})
// Preferentially render Markdown, fall back to text if it's not present.
if (fs.existsSync(md))
file = md
else
file = txt
printText(this.name, this.appDir, file, path.extname(file), function () {
var pathtoguide = path.join(this.appDir,'guide', 'index')
// console.log(
// bold('\n » To print these instructions again, run: `' + this.name + ' print`.\n'))
// console.log(
// bold(' » To execute your program in a test environment, run:\n `' + this.name + ' run program.js`.'))
console.log(
bold(green(' » To verify your work for this problem, run: `' + this.name + ' verify`.\n » Run `git-it` again to launch menu & go onto next challenge\n')))
// console.log(
// bold(green(' » Run `git-it` again to launch menu & go onto next challenge\n')))
console.log(bold(green(' GUIDE\n')))
console.log(green(' » Refer to Compass for the instructions / guide\n'))
// console.log(
// bold(' » To launch the guide, run: `' + this.name + ' server`.\n'))
// console.log(
// ' » To view guide offline, copy this address to your browser:\n' + ' » ' + pathtoguide + '.html \n'
// + ' » ' + pathtoguide + '-zhtw.html\n')
// if (this.helpFile) {
// console.log(bold(" HELP\n"))
// console.log(
// bold(' » For help with this problem or with ' + this.name + ', run:\n `' + this.name + ' help`.'))
// }
// if (this.creditsFile) {
// console.log(
// bold(' » For a list of those who contributed to ' + this.name + ', run:\n `' + this.name + ' credits`.'))
// }
// if (this.prerequisitesFile) {
// console.log(
// bold(' » For any set up/installion prerequisites for ' + this.name + ', run:\n `' + this.name + ' prerequisites`.'))
// }
console.log()
}.bind(this))
}
module.exports = Workshopper