UNPKG

3.54 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const path = require("path");
4exports.default = (ctx) => {
5 ctx.registerCommand({
6 name: 'config',
7 optionsMap: {
8 '--json': '以 JSON 形式输出'
9 },
10 synopsisList: [
11 'taro config set <key> <value>',
12 'taro config get <key>',
13 'taro config delete <key>',
14 'taro config list [--json]'
15 ],
16 fn() {
17 const { cmd, key, value, json } = ctx.runOpts;
18 const { fs, getUserHomeDir, TARO_CONFIG_FLODER, TARO_BASE_CONFIG } = ctx.helper;
19 const homedir = getUserHomeDir();
20 const configPath = path.join(homedir, `${TARO_CONFIG_FLODER}/${TARO_BASE_CONFIG}`);
21 if (!homedir)
22 return console.log('找不到用户根目录');
23 function displayConfigPath(configPath) {
24 console.log('Config path:', configPath);
25 console.log();
26 }
27 switch (cmd) {
28 case 'get':
29 if (!key)
30 return console.log('Usage: taro config get foo');
31 if (fs.existsSync(configPath)) {
32 displayConfigPath(configPath);
33 const config = fs.readJSONSync(configPath);
34 console.log('Key:', key, ', value:', config[key]);
35 }
36 break;
37 case 'set':
38 if (!key || !value)
39 return console.log('Usage: taro config set foo bar');
40 if (fs.existsSync(configPath)) {
41 displayConfigPath(configPath);
42 const config = fs.readJSONSync(configPath);
43 config[key] = value;
44 fs.writeJSONSync(configPath, config);
45 }
46 else {
47 fs.ensureFileSync(configPath);
48 fs.writeJSONSync(configPath, {
49 [key]: value
50 });
51 }
52 console.log('Set key:', key, ', value:', value);
53 break;
54 case 'delete':
55 if (!key)
56 return console.log('Usage: taro config delete foo');
57 if (fs.existsSync(configPath)) {
58 displayConfigPath(configPath);
59 const config = fs.readJSONSync(configPath);
60 delete config[key];
61 fs.writeJSONSync(configPath, config);
62 }
63 console.log('Deleted:', key);
64 break;
65 case 'list':
66 case 'ls':
67 if (fs.existsSync(configPath)) {
68 displayConfigPath(configPath);
69 console.log('Config info:');
70 const config = fs.readJSONSync(configPath);
71 if (json) {
72 console.log(JSON.stringify(config, null, 2));
73 }
74 else {
75 for (const key in config) {
76 console.log(`${key}=${config[key]}`);
77 }
78 }
79 }
80 break;
81 default:
82 break;
83 }
84 }
85 });
86};