forked from fastify/fastify-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.js
More file actions
61 lines (47 loc) · 1.58 KB
/
Copy pathutil.js
File metadata and controls
61 lines (47 loc) · 1.58 KB
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
const fs = require('fs')
const path = require('path')
const resolveFrom = require('resolve-from')
function exit (message) {
if (message instanceof Error) {
console.log(message)
return process.exit(1)
} else if (message) {
console.log(`Warn: ${message}`)
return process.exit(1)
}
process.exit()
}
function requireFastifyForModule (modulePath) {
try {
const basedir = path.resolve(process.cwd(), modulePath)
const module = require(resolveFrom.silent(basedir, 'fastify') || 'fastify')
return { module }
} catch (e) {
exit('unable to load fastify module')
}
}
function isInvalidAsyncPlugin (plugin) {
return plugin.length !== 2 && plugin.constructor.name === 'AsyncFunction'
}
function requireServerPluginFromPath (modulePath) {
const resolvedModulePath = path.resolve(process.cwd(), modulePath)
if (!fs.existsSync(resolvedModulePath)) {
throw new Error(`${resolvedModulePath} doesn't exist within ${process.cwd()}`)
}
const serverPlugin = require(resolvedModulePath)
if (isInvalidAsyncPlugin(serverPlugin)) {
return new Error('Async/Await plugin function should contain 2 arguments.' +
'Refer to documentation for more information.')
}
return serverPlugin
}
function showHelpForCommand (commandName) {
const helpFilePath = path.join(__dirname, 'help', `${commandName}.txt`)
try {
console.log(fs.readFileSync(helpFilePath, 'utf8'))
exit()
} catch (e) {
exit(`unable to get help for command "${commandName}"`)
}
}
module.exports = { exit, requireFastifyForModule, showHelpForCommand, requireServerPluginFromPath }