1 | const inquirer = require('inquirer');
|
2 | const path = require('path');
|
3 | const fs = require('fs');
|
4 | const chalk = require('chalk');
|
5 | const { promisify } = require('util');
|
6 | const getConfigPath = require('./config-path');
|
7 |
|
8 | const [readFile, writeFile] = [fs.readFile, fs.writeFile].map((fn) =>
|
9 | promisify(fn)
|
10 | );
|
11 | const TOKEN_PATH = path.join(getConfigPath(), '.token');
|
12 |
|
13 | async function tokenPrepare(isInnerNet) {
|
14 | const tokenExists = fs.existsSync(TOKEN_PATH);
|
15 | if (!tokenExists) {
|
16 | return writeToken(isInnerNet);
|
17 | }
|
18 | const tokenFile = await readFile(TOKEN_PATH, 'utf-8');
|
19 |
|
20 | let token;
|
21 | try {
|
22 | token = JSON.parse(tokenFile).token;
|
23 | } catch (error) {
|
24 | token = null;
|
25 | }
|
26 |
|
27 | if (!token) {
|
28 | return writeToken(isInnerNet);
|
29 | }
|
30 | return token;
|
31 | }
|
32 |
|
33 | async function clearToken() {
|
34 | await writeFile(TOKEN_PATH, '{"token": ""}', 'utf-8');
|
35 | }
|
36 |
|
37 | async function writeToken(isInnerNet) {
|
38 | TokenFirstLyMessage(isInnerNet);
|
39 | const answers = await inquirer.prompt([
|
40 | {
|
41 | name: 'token',
|
42 | message: 'Please input your fusion.design token: ',
|
43 | validate(input) {
|
44 |
|
45 | const done = this.async();
|
46 | if (typeof input === 'string' && input) {
|
47 | done(null, true);
|
48 | } else {
|
49 | done('token should be a no empty string');
|
50 | }
|
51 | },
|
52 | },
|
53 | ]);
|
54 | const { token } = answers;
|
55 | await writeFile(TOKEN_PATH, JSON.stringify({ token }, null, 2), 'utf-8');
|
56 | return token;
|
57 | }
|
58 |
|
59 | module.exports = {
|
60 | writeToken, clearToken, tokenPrepare,
|
61 | };
|
62 |
|
63 | function TokenFirstLyMessage(isInnerNet) {
|
64 | console.log();
|
65 | console.log();
|
66 | const address = `https://${isInnerNet ? 'fusion.alibaba-inc.com' : 'fusion.design'}/help.html#/dev-create-site`;
|
67 | console.log(`如果这是你第一次使用该功能,或者不知道如何获取Token。\n请查看文档: ${chalk.yellow(address)}`);
|
68 | console.log();
|
69 | console.log();
|
70 | }
|