UNPKG

1.43 kBJavaScriptView Raw
1const path = require('path')
2const ora = require('ora')
3const chalk = require('chalk')
4const rimraf = require('rimraf')
5const download = require('download')
6const util = require('./util')
7
8const options = {
9 extract: true,
10 strip: 1,
11 mode: '666',
12 headers: {
13 'accept': 'application/zip',
14 'user-agent': util.generator
15 }
16}
17
18const spinner = ora('Downloading template...')
19
20/**
21 * Fetch template from remote or cache
22 * @param {String} template Template name
23 * @param {Boolean} offline Offline mode
24 * @return {Promise} Fetch promise
25 */
26module.exports = (template, offline) => {
27 // TODO: template id
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}