UNPKG

1.82 kBJavaScriptView Raw
1const os = require('os')
2const fs = require('fs')
3const path = require('path')
4const crypto = require('crypto')
5const pkg = require('../package')
6
7const homedir = os.homedir()
8
9/**
10 * Generator name
11 * @type {String}
12 */
13exports.generator = `${pkg.name}/${pkg.version} (${pkg.homepage})`
14
15/**
16 * Current user home path
17 * @type {String}
18 */
19exports.homedir = homedir
20
21/**
22 * Check path exists.
23 */
24exports.exists = input => {
25 return new Promise(resolve => fs.access(input, e => resolve(!e)))
26}
27
28/**
29 * Check path exists sync.
30 */
31exports.existsSync = input => {
32 try {
33 fs.accessSync(input)
34 return true
35 } catch (e) {
36 return false
37 }
38}
39
40/**
41 * Check path locally
42 */
43exports.isLocalPath = input => {
44 return /^[./]|^[a-zA-Z]:/.test(input)
45}
46
47/**
48 * Get template url
49 */
50exports.getTemplateUrl = input => {
51 if (/^https?:/.test(input)) return input
52
53 input = input.includes('/') ? input : `zce-templates/${input}`
54 const temp = input.split('#')
55 let repo = temp[0]
56 let branch = temp[1]
57 branch = branch || 'master'
58
59 return `https://github.com/${repo}/archive/${branch}.zip`
60}
61
62/**
63 * Tildify input path
64 */
65exports.tildify = input => {
66 input = path.normalize(input)
67 return input.includes(homedir) ? input.replace(homedir, '~') : input
68}
69
70/**
71 * Untildify input path
72 */
73exports.untildify = input => {
74 input = path.normalize(input)
75 return input.includes('~') ? input.replace('~', homedir) : input
76}
77
78/**
79 * MD5
80 */
81exports.md5 = input => {
82 const temp = crypto.createHash('md5')
83 temp.update(input)
84 return temp.digest('hex')
85}
86
87/**
88 * Eval
89 */
90exports.eval = (exp, data) => {
91 /* eslint-disable no-new-func */
92 try {
93 return new Function('data', `with (data) { return ${exp} }`)(data)
94 } catch (e) {
95 throw new Error(`Error when evaluating filter condition: ${exp}`)
96 }
97}