UNPKG

3.47 kBJavaScriptView Raw
1const fs = require('fs');
2const path = require('path');
3const ora = require('ora');
4const chalk = require('chalk');
5const tildify = require('tildify');
6const inquirer = require('inquirer');
7const home = require('user-home');
8const rm = require('rimraf').sync;
9const download = require('./cli/download');
10const localPath = require('./cli/local-path');
11const checkVersion = require('./cli/check-version');
12const generate = require('./cli/generate');
13const logger = require('./cli/logger');
14
15exports = module.exports = (template, rawName, program) => {
16 function gen (templatePath) {
17 generate(name, templatePath, to, err => {
18 if (err) logger.fatal(err);
19 console.log();
20 logger.success('Generated "%s".', name);
21 });
22 }
23
24 function run () {
25 if (localPath.isLocalPath(template)) {
26 // use local/cache template
27 // Example:
28 // wepy init E:\workspace\wepy_templates\standard my-wepy-project
29 // wepy init standard my-wepy-project --offline
30 const templatePath = localPath.getTemplatePath(template);
31 if (fs.existsSync(templatePath)) {
32 gen(templatePath);
33 } else {
34 logger.fatal('Local template "%s" not found.', template);
35 }
36 } else {
37 checkVersion(() => {
38 downloadAndGenerate(template);
39 });
40 }
41 }
42
43 function downloadAndGenerate (template) {
44 const spinner = ora('downloading template');
45 spinner.start();
46
47 if (fs.existsSync(tmp)) {
48 rm(tmp);
49 }
50
51 if (!hasSlash) {
52 // use official template
53 download.downloadOfficialZip(template, tmp, { extract: true }).then(() => {
54 spinner.stop()
55 gen(tmp);
56 }).catch(e => {
57 if (e.statusCode === 404) {
58 logger.fatal(`Unrecongnized template: "${template}". Try "wepy list" to show all available templates `);
59 } else if (e) {
60 logger.fatal('Failed to download repo ' + template + ': ' + e.message.trim());
61 }
62 });
63 } else {
64 // use third party template
65 download.downloadRepo(template, tmp, { clone }, err => {
66 spinner.stop();
67 if (err) logger.fatal('Failed to download repo ' + template + ': ' + err.message.trim());
68 gen(tmp);
69 });
70 }
71
72 }
73
74
75 const hasSlash = template.indexOf('/') > -1;
76 const inPlace = !rawName || rawName === '.';
77 const name = inPlace ? path.relative('../', process.cwd()) : rawName;
78 const to = path.resolve(rawName || '.');
79 const clone = program.clone || false;
80 const offline = program.offline || false;
81 let tmp = path.join(home, '.wepy_templates', template.replace(/\//g, '-'));
82
83 /**
84 * use offline cache
85 */
86 if (offline) {
87 console.log(`> Use cached template at ${chalk.yellow(tildify(tmp))}`);
88 template = tmp;
89 }
90
91 if (fs.existsSync(to)) {
92 inquirer.prompt([{
93 type: 'confirm',
94 message: inPlace
95 ? 'Generate project in current directory?'
96 : 'Target directory exists. Continue?',
97 name: 'ok'
98 }]).then(answers => {
99 if (answers.ok) {
100 run();
101 }
102 }).catch();
103 } else {
104 run();
105 }
106}