1 | const path = require('path')
|
2 |
|
3 | const ora = require('ora')
|
4 | const chalk = require('chalk')
|
5 | const rimraf = require('rimraf')
|
6 |
|
7 | const { logger, http, util } = require('../common')
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | const isLocalPath = template => {
|
14 | return /^[./]|^[a-zA-Z]:/.test(template)
|
15 | }
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | const getTemplateUrl = template => {
|
22 |
|
23 | if (/^https?:/.test(template)) return template
|
24 |
|
25 |
|
26 | template = template.includes('/') ? template : `zce-templates/${template}`
|
27 |
|
28 | const temp = template.split('#')
|
29 |
|
30 | return `https://github.com/${temp[0]}/archive/${temp[1] || 'master'}.zip`
|
31 | }
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | module.exports = async (template, offline) => {
|
40 | if (isLocalPath(template)) {
|
41 |
|
42 | return path.resolve(template)
|
43 | }
|
44 |
|
45 |
|
46 | const templateUrl = getTemplateUrl(template)
|
47 |
|
48 | const cachePath = util.getDataPath('generator/cache', templateUrl.replace(/[\W]+/g, '-'))
|
49 |
|
50 | const cacheExists = await util.exists(cachePath) && await util.isDirectory(cachePath)
|
51 |
|
52 | if (offline) {
|
53 |
|
54 | if (cacheExists) {
|
55 |
|
56 | logger.log(`🚆 Use cached template @ ${chalk.yellow(util.tildify(cachePath))}.`)
|
57 | return cachePath
|
58 | }
|
59 |
|
60 | logger.log(`😔 Template cache ${chalk.yellow(util.tildify(cachePath))} not found.`)
|
61 | }
|
62 |
|
63 |
|
64 | cacheExists && rimraf.sync(cachePath)
|
65 |
|
66 | const spinner = ora('Downloading template...')
|
67 |
|
68 | try {
|
69 | spinner.start()
|
70 | await http.download(templateUrl, cachePath, { extract: true, strip: 1, mode: 666 })
|
71 | spinner.succeed('Download complete.')
|
72 | return cachePath
|
73 | } catch (e) {
|
74 | spinner.fail('Download failed.')
|
75 | throw new Error(`Failed to fetch template "${template}": ${e.message}.`)
|
76 | }
|
77 | }
|
78 |
|
79 |
|
80 | module.exports.isLocalPath = isLocalPath
|
81 | module.exports.getTemplateUrl = getTemplateUrl
|