UNPKG

7.95 kBJavaScriptView Raw
1"use strict";
2/**
3 * © 2013 Liferay, Inc. <https://liferay.com> and Node GH contributors
4 * (see file: README.md)
5 * SPDX-License-Identifier: BSD-3-Clause
6 */
7Object.defineProperty(exports, "__esModule", { value: true });
8const fs = require("fs");
9const lodash_1 = require("lodash");
10const path = require("path");
11const R = require("ramda");
12const S = require("sanctuary");
13const userhome = require("userhome");
14const which = require("which");
15const exec = require("./exec");
16const logger = require("./logger");
17const fp_1 = require("./fp");
18exports.PLUGINS_PATH_KEY = 'plugins_path';
19const testing = process.env.NODE_ENV === 'testing';
20/* Refactored FP Functions */
21const safeWhich = S.encase(which.sync);
22const safeRealpath = S.encase(fs.realpathSync);
23exports.getPluginPath = R.pipeK(safeWhich, safeRealpath);
24// TODO merge with getPlugin fn in cmd.ts
25exports.getPlugin = R.pipeK(S.prepend('gh-'), exports.getPluginPath, fp_1.safeImport);
26/* ----------------------- */
27// function concatError(leftMonad, errorMessage) {
28// const leftMonadContainsError = leftMonad && leftMonad.isLeft() && leftMonad.value
29// return leftMonadContainsError ? leftMonad.map(mapError) : Left(errorMessage)
30// function mapError(prevErrorMessage) {
31// return `${prevErrorMessage}\n${errorMessage}`
32// }
33// }
34// -- Config -------------------------------------------------------------------
35function getNodeModulesGlobalPath() {
36 try {
37 var { stdout } = exec.spawnSync('npm', ['root', '-g']);
38 }
39 catch (err) {
40 logger.warn(`Can't resolve plugins directory path.\n${err}`);
41 }
42 return stdout;
43}
44exports.getNodeModulesGlobalPath = getNodeModulesGlobalPath;
45function getGlobalPackageJson() {
46 const configFile = fs.readFileSync(path.join(__dirname, '../package.json'));
47 return JSON.parse(configFile.toString());
48}
49exports.getGlobalPackageJson = getGlobalPackageJson;
50function getDefaultConfigPath() {
51 return path.join(__dirname, '../default.gh.json');
52}
53exports.getDefaultConfigPath = getDefaultConfigPath;
54function getProjectConfigPath() {
55 return path.join(process.cwd(), '.gh.json');
56}
57exports.getProjectConfigPath = getProjectConfigPath;
58function getUserHomePath() {
59 return userhome('.gh.json');
60}
61exports.getUserHomePath = getUserHomePath;
62function resolveGHConfigs() {
63 const globalConfig = getGlobalConfig();
64 let projectConfig;
65 const result = {};
66 try {
67 projectConfig = JSON.parse(fs.readFileSync(getProjectConfigPath()).toString());
68 Object.keys(globalConfig).forEach(key => {
69 result[key] = globalConfig[key];
70 });
71 Object.keys(projectConfig).forEach(key => {
72 result[key] = projectConfig[key];
73 });
74 return result;
75 }
76 catch (e) {
77 logger.debug(e.message);
78 if (e.code !== 'MODULE_NOT_FOUND' && e.code !== 'ENOENT') {
79 throw e;
80 }
81 return globalConfig;
82 }
83}
84function getConfig() {
85 const config = resolveGHConfigs();
86 const protocol = `${config.api.protocol}://`;
87 const is_enterprise = config.api.host !== 'api.github.com';
88 if (config.github_host === undefined) {
89 config.github_host = `${protocol}${is_enterprise ? config.api.host : 'github.com'}`;
90 }
91 if (config.github_gist_host === undefined) {
92 config.github_gist_host = `${protocol}${is_enterprise ? `${config.api.host}/gist` : 'gist.github.com'}/`;
93 }
94 return config;
95}
96exports.getConfig = getConfig;
97function getGlobalConfig() {
98 const configPath = getUserHomePath();
99 const defaultPath = getDefaultConfigPath();
100 if (!fs.existsSync(configPath)) {
101 createGlobalConfig();
102 }
103 return JSON.parse(fs.readFileSync(testing ? defaultPath : configPath).toString());
104}
105exports.getGlobalConfig = getGlobalConfig;
106function removeGlobalConfig(key) {
107 var config = getGlobalConfig();
108 delete config[key];
109 saveJsonConfig(getUserHomePath(), config);
110}
111exports.removeGlobalConfig = removeGlobalConfig;
112function createGlobalConfig() {
113 saveJsonConfig(getUserHomePath(), JSON.parse(fs.readFileSync(getDefaultConfigPath()).toString()));
114}
115exports.createGlobalConfig = createGlobalConfig;
116function writeGlobalConfig(jsonPath, value) {
117 const config = getGlobalConfig();
118 let i;
119 let output;
120 let path;
121 let pathLen;
122 path = jsonPath.split('.');
123 output = config;
124 for (i = 0, pathLen = path.length; i < pathLen; i++) {
125 output[path[i]] = config[path[i]] || (i + 1 === pathLen ? value : {});
126 output = output[path[i]];
127 }
128 saveJsonConfig(getUserHomePath(), config);
129}
130exports.writeGlobalConfig = writeGlobalConfig;
131function saveJsonConfig(path, object) {
132 fs.writeFileSync(path, JSON.stringify(object, null, 4));
133}
134exports.saveJsonConfig = saveJsonConfig;
135function writeGlobalConfigCredentials(user, token, path) {
136 const configPath = path || getUserHomePath();
137 let config;
138 if (fs.existsSync(configPath)) {
139 config = JSON.parse(fs.readFileSync(configPath).toString());
140 }
141 else {
142 config = JSON.parse(fs.readFileSync(getDefaultConfigPath()).toString());
143 }
144 logger.log(`Writing GH config data: ${configPath}`);
145 try {
146 config.github_user = user;
147 config.github_token = token;
148 saveJsonConfig(configPath, config);
149 }
150 catch (err) {
151 throw new Error(`Error writing credentials to global config\n${err}`);
152 }
153 logger.log('Authentication succeed. Token written to global config.');
154}
155exports.writeGlobalConfigCredentials = writeGlobalConfigCredentials;
156// -- Plugins ------------------------------------------------------------------
157function addPluginConfig(plugin) {
158 try {
159 const pluginConfig = require(path.join(getNodeModulesGlobalPath(), `gh-${plugin}`, 'gh-plugin.json'));
160 const config = getGlobalConfig();
161 const configHooks = lodash_1.cloneDeep(config.hooks);
162 const pluginHooks = lodash_1.cloneDeep(pluginConfig.hooks);
163 if (config.plugins[plugin] && !config.plugins[plugin]['hooks_installed']) {
164 Object.keys(pluginHooks).forEach(cmd => {
165 Object.keys(pluginHooks[cmd]).forEach(hook => {
166 configHooks[cmd][hook].before = [
167 ...configHooks[cmd][hook].before,
168 ...pluginHooks[cmd][hook].before,
169 ];
170 configHooks[cmd][hook].after = [
171 ...configHooks[cmd][hook].after,
172 ...pluginHooks[cmd][hook].after,
173 ];
174 });
175 });
176 if (!testing) {
177 logger.log(logger.colors.yellow(`Copying over ${plugin} plugin hooks to your .gh.json hooks.`));
178 try {
179 config.hooks = configHooks;
180 config.plugins[plugin]['hooks_installed'] = true;
181 saveJsonConfig(getUserHomePath(), config);
182 }
183 catch (err) {
184 logger.error(`Error writing ${plugin} hooks to .gh.json config.\n${err}`);
185 }
186 logger.log(logger.colors.green('Copy successful.\n'));
187 }
188 }
189 }
190 catch (e) {
191 if (e.code !== 'MODULE_NOT_FOUND') {
192 throw e;
193 }
194 }
195}
196exports.addPluginConfig = addPluginConfig;
197function getPlugins() {
198 const pluginsPath = getNodeModulesGlobalPath();
199 if (pluginsPath === '') {
200 return [];
201 }
202 try {
203 var plugins = fs.readdirSync(pluginsPath).filter(plugin => {
204 return plugin.substring(0, 3) === 'gh-';
205 });
206 }
207 catch (err) {
208 logger.warn(`Can't read plugins directory.\n${err}`);
209 }
210 return plugins;
211}
212exports.getPlugins = getPlugins;
213function pluginHasConfig(pluginName) {
214 return Boolean(getConfig().plugins[pluginName]);
215}
216exports.pluginHasConfig = pluginHasConfig;
217//# sourceMappingURL=configs.js.map
\No newline at end of file