UNPKG

2.71 kBJavaScriptView Raw
1"use strict";
2
3const _ = require("lodash");
4const colors = require("colors/safe");
5const fs = require("fs");
6const Helper = require("../helper");
7const path = require("path");
8
9let home;
10
11class Utils {
12 static extraHelp() {
13 [
14 "",
15 "",
16 " Environment variable:",
17 "",
18 ` THELOUNGE_HOME Path for all configuration files and folders. Defaults to ${colors.green(Helper.expandHome(Utils.defaultHome()))}.`,
19 "",
20 ].forEach((e) => log.raw(e));
21 }
22
23 static defaultHome() {
24 if (home) {
25 return home;
26 }
27
28 let distConfig;
29
30 // TODO: Remove this section when releasing The Lounge v3
31 const deprecatedDistConfig = path.resolve(path.join(
32 __dirname,
33 "..",
34 "..",
35 ".lounge_home"
36 ));
37 if (fs.existsSync(deprecatedDistConfig)) {
38 log.warn(`${colors.green(".lounge_home")} is ${colors.bold.red("deprecated")} and will be ignored as of The Lounge v3.`);
39 log.warn(`Use ${colors.green(".thelounge_home")} instead.`);
40
41 distConfig = deprecatedDistConfig;
42 } else {
43 distConfig = path.resolve(path.join(
44 __dirname,
45 "..",
46 "..",
47 ".thelounge_home"
48 ));
49 }
50
51 home = fs.readFileSync(distConfig, "utf-8").trim();
52
53 return home;
54 }
55
56 // Parses CLI options such as `-c public=true`, `-c debug.raw=true`, etc.
57 static parseConfigOptions(val, memo) {
58 // Invalid option that is not of format `key=value`, do nothing
59 if (!val.includes("=")) {
60 return memo;
61 }
62
63 const parseValue = (value) => {
64 if (value === "true") {
65 return true;
66 } else if (value === "false") {
67 return false;
68 } else if (value === "undefined") {
69 return undefined;
70 } else if (value === "null") {
71 return null;
72 } else if (/^\[.*\]$/.test(value)) { // Arrays
73 // Supporting arrays `[a,b]` and `[a, b]`
74 const array = value.slice(1, -1).split(/,\s*/);
75 // If [] is given, it will be parsed as `[ "" ]`, so treat this as empty
76 if (array.length === 1 && array[0] === "") {
77 return [];
78 }
79 return array.map(parseValue); // Re-parses all values of the array
80 }
81 return value;
82 };
83
84 // First time the option is parsed, memo is not set
85 if (memo === undefined) {
86 memo = {};
87 }
88
89 // Note: If passed `-c foo="bar=42"` (with single or double quotes), `val`
90 // will always be passed as `foo=bar=42`, never with quotes.
91 const position = val.indexOf("="); // Only split on the first = found
92 const key = val.slice(0, position);
93 const value = val.slice(position + 1);
94 const parsedValue = parseValue(value);
95
96 if (_.has(memo, key)) {
97 log.warn(`Configuration key ${colors.bold(key)} was already specified, ignoring...`);
98 } else {
99 memo = _.set(memo, key, parsedValue);
100 }
101
102 return memo;
103 }
104}
105
106module.exports = Utils;