UNPKG

2.37 kBJavaScriptView Raw
1'use strict';
2
3const defaults = require('lodash.defaults');
4const fs = require('fs');
5const path = require('path');
6const osHomedir = require('os-homedir');
7
8let config = null;
9
10exports.reset = () => {
11 config = null;
12};
13
14exports.get = () => {
15 if (!config) {
16 config = load();
17 }
18 return config;
19};
20
21function load() {
22 const DEFAULT = path.join(__dirname, '..', 'config.json');
23 const CUSTOM = path.join(osHomedir(), '.tldrrc');
24
25 let defaultConfig = JSON.parse(fs.readFileSync(DEFAULT));
26 defaultConfig.cache = path.join(osHomedir(), '.tldr');
27 /*eslint-disable no-process-env */
28 defaultConfig.proxy = process.env.HTTP_PROXY || process.env.http_proxy;
29 /*eslint-enable no-process-env */
30
31 let customConfig = {};
32 try {
33 customConfig = JSON.parse(fs.readFileSync(CUSTOM));
34 } catch (ex) {
35 /*eslint-disable */
36 /*eslint-enable */
37 }
38
39 let merged = defaults(customConfig, defaultConfig);
40 // Validating the theme settings
41 let errors = Object.keys(!merged.themes ? {} : merged.themes).map(
42 (key) => {
43 return validateThemeItem(merged.themes[key], key);
44 }
45 );
46 errors.push(validatePlatform(merged.platform));
47 // Filtering out all the null entries
48 errors = errors.filter((item) => { return item !== null; });
49
50 if (errors.length > 0) {
51 throw new Error('Error in .tldrrc configuration:\n' + errors.join('\n'));
52 }
53 return merged;
54}
55
56function validatePlatform(os) {
57 let platform = require('./platform');
58 if (os && !platform.isSupported(os)) {
59 return 'Unsupported platform : ' + os;
60 }
61 return null;
62}
63
64function validateThemeItem(field, key) {
65 let validValues = ['',
66 'reset',
67 'bold',
68 'dim',
69 'italic',
70 'underline',
71 'inverse',
72 'hidden',
73 'black',
74 'red',
75 'green',
76 'yellow',
77 'blue',
78 'magenta',
79 'cyan',
80 'white',
81 'gray',
82 'bgBlack',
83 'bgRed',
84 'bgGreen',
85 'bgYellow',
86 'bgBlue',
87 'bgMagenta',
88 'bgCyan',
89 'bgWhite'
90 ];
91 // TODO: change this to return all errors in a field
92 for (let item in field) {
93 if (field.hasOwnProperty(item)) {
94 let tokens = field[item].replace(/\s+/g, '').split(',');
95 for (let i = 0; i < tokens.length; i++) {
96 if (validValues.indexOf(tokens[i]) < 0) {
97 return 'Invalid theme value : ' + tokens[i] + ' in ' + key + ' theme';
98 }
99 }
100 }
101 }
102 return null;
103}