1 | const path = require('path')
|
2 | const ora = require('ora')
|
3 | const chalk = require('chalk')
|
4 | const rimraf = require('rimraf')
|
5 | const download = require('download')
|
6 | const util = require('./util')
|
7 |
|
8 | const options = {
|
9 | extract: true,
|
10 | strip: 1,
|
11 | mode: '666',
|
12 | headers: {
|
13 | 'accept': 'application/zip',
|
14 | 'user-agent': util.generator
|
15 | }
|
16 | }
|
17 |
|
18 | const spinner = ora('Downloading template...')
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | module.exports = (template, offline) => {
|
27 |
|
28 | const cachePath = path.join(util.homedir, '.zce-templates', util.md5(template))
|
29 | const cacheExists = util.existsSync(cachePath)
|
30 |
|
31 | if (offline && cacheExists) {
|
32 | console.log(`\nš Use cached template @ ${chalk.yellow(util.tildify(cachePath))}`)
|
33 | return Promise.resolve(cachePath)
|
34 | } else if (offline) {
|
35 | console.log(`\nš Template cache ${chalk.yellow(util.tildify(cachePath))} not found`)
|
36 | }
|
37 |
|
38 | console.log()
|
39 | spinner.start()
|
40 | cacheExists && rimraf.sync(cachePath)
|
41 |
|
42 | return download(util.getTemplateUrl(template), cachePath, options)
|
43 | .then(() => {
|
44 | spinner.succeed('Download complete.')
|
45 | return cachePath
|
46 | })
|
47 | .catch(err => {
|
48 | spinner.fail('Download failed.')
|
49 | throw new Error(`Failed to fetch template "${template}": ${err.message}`)
|
50 | })
|
51 | }
|