UNPKG

3.17 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const child_process_1 = require("child_process");
4const findUp = require("find-up");
5const fs = require("fs");
6const ini = require("ini");
7const os = require("os");
8const path = require("path");
9const rc = require("rc");
10const util_1 = require("util");
11const constants_1 = require("./constants");
12const writeFile = util_1.promisify(fs.writeFile);
13const readFile = util_1.promisify(fs.readFile);
14class Config {
15 constructor(runPath) {
16 this.runPath = runPath;
17 this.setIntegrationConfig = (config) => {
18 const { integrationTitle, integrationId } = config;
19 fs.writeFileSync(this.integrationRc, ini.stringify({ integrationTitle, integrationId }));
20 };
21 this.storeToken = async (token) => {
22 try {
23 const file = this.bearerConfig.config || path.join(os.homedir(), '.bearerrc');
24 let config = {};
25 if (fs.existsSync(file)) {
26 const configContent = await readFile(file, { encoding: 'utf8' });
27 config = ini.parse(configContent);
28 }
29 const tokenWithExpires = Object.assign({}, token, { expires_at: Date.now() + token.expires_in * 1000 });
30 await writeFile(file, ini.stringify(Object.assign({}, config, { token: tokenWithExpires })));
31 }
32 catch (e) {
33 console.error('Error while writing token', e);
34 }
35 };
36 this.integrationLocation = this.runPath.startsWith('~')
37 ? path.resolve(runPath.replace(/^~/, os.homedir()))
38 : path.resolve(runPath);
39 }
40 get command() {
41 return this.isYarnInstalled ? 'yarn' : 'npm';
42 }
43 get bearerConfig() {
44 return rc('bearer');
45 }
46 get integrationConfig() {
47 return rc('integration', { config: this.integrationRc });
48 }
49 get integrationRc() {
50 return path.join(this.integrationLocation, '.integrationrc');
51 }
52 get integrationTitle() {
53 return this.integrationConfig.integrationTitle;
54 }
55 get BUID() {
56 return process.env.BEARER_INTEGRATION_ID || this.integrationConfig.integrationId;
57 }
58 get bearerUid() {
59 if (this.hasIntegrationLinked) {
60 return this.BUID;
61 }
62 return 'unset';
63 }
64 get hasIntegrationLinked() {
65 return Boolean(this.BUID);
66 }
67 get rootPath() {
68 return findUp.sync('.bearer', { cwd: this.integrationLocation });
69 }
70 get isYarnInstalled() {
71 return !!child_process_1.spawnSync('yarn', ['bin']).output;
72 }
73 async getToken() {
74 const file = this.bearerConfig.config || path.join(os.homedir(), '.bearerrc');
75 if (fs.existsSync(file)) {
76 const configContent = await readFile(file, { encoding: 'utf8' });
77 return ini.parse(configContent).token;
78 }
79 return undefined;
80 }
81}
82exports.Config = Config;
83exports.default = (runPath = process.cwd()) => {
84 return {
85 config: new Config(runPath),
86 constants: constants_1.CONFIGS[constants_1.BEARER_ENV]
87 };
88};