UNPKG

4.53 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 Octokit = require("@octokit/rest");
9const fs = require("fs");
10const inquirer = require("inquirer");
11const moment = require("moment");
12const path_1 = require("path");
13const userhome = require("userhome");
14const configs_1 = require("./configs");
15const logger = require("./logger");
16const url_1 = require("url");
17async function getGitHubInstance() {
18 const config = configs_1.getConfig();
19 const { github_token: token, github_user: user, api: { protocol, pathPrefix, host }, } = config;
20 const isEnterprise = host !== 'api.github.com';
21 const apiUrl = `${protocol}://${isEnterprise ? host : 'api.github.com'}`;
22 const { href } = new url_1.URL(`${apiUrl}${pathPrefix || ''}`);
23 // trim trailing slash for Octokit
24 const baseUrl = href.replace(/\/+$/, '');
25 const throttlePlugin = await Promise.resolve().then(() => require('@octokit/plugin-throttling'));
26 Octokit.plugin(throttlePlugin);
27 return new Octokit({
28 // log: console,
29 baseUrl,
30 auth: await getToken({ token, user }),
31 throttle: {
32 onRateLimit: (retryAfter, options) => {
33 console.warn(`Request quota exhausted for request ${options.method} ${options.url}`);
34 if (options.request.retryCount === 0) {
35 // only retries once
36 console.log(`Retrying after ${retryAfter} seconds!`);
37 return true;
38 }
39 },
40 onAbuseLimit: (_, options) => {
41 // does not retry, only logs a warning
42 console.warn(`Abuse detected for request ${options.method} ${options.url}`);
43 },
44 },
45 });
46}
47exports.getGitHubInstance = getGitHubInstance;
48async function getToken(tokenAndUser) {
49 let token;
50 if (!tokenExists(tokenAndUser)) {
51 token = await createNewOathToken();
52 }
53 else {
54 token = getSavedToken(tokenAndUser.token);
55 }
56 if (token) {
57 return token;
58 }
59 process.exit(1);
60}
61exports.getToken = getToken;
62function tokenExists({ token, user }) {
63 if (process.env.GENERATE_NEW_TOKEN) {
64 return false;
65 }
66 return (token && user) || (process.env.GH_TOKEN && process.env.GH_USER);
67}
68exports.tokenExists = tokenExists;
69function getSavedToken(token) {
70 if (process.env.CONTINUOUS_INTEGRATION) {
71 return process.env.GH_TOKEN;
72 }
73 if (process.env.NODE_ENV === 'testing') {
74 // Load your local token when generating test fixtures
75 return JSON.parse(fs.readFileSync(userhome('.gh.json')).toString()).github_token;
76 }
77 return token;
78}
79async function createNewOathToken() {
80 logger.log(`In order to use GitHub's API, you will need to login with your GitHub account.`);
81 const answers = await inquirer.prompt([
82 {
83 type: 'input',
84 message: 'Enter your GitHub user',
85 name: 'username',
86 },
87 {
88 type: 'password',
89 message: 'Enter your GitHub password',
90 name: 'password',
91 },
92 ]);
93 const octokit = new Octokit({
94 auth: {
95 username: answers.username,
96 password: answers.password,
97 async on2fa() {
98 const { code } = await inquirer.prompt([
99 {
100 type: 'input',
101 message: 'Enter your Two-factor GitHub authenticator code',
102 name: 'code',
103 },
104 ]);
105 return code;
106 },
107 },
108 });
109 const payload = {
110 note: `Node GH (${moment().format('MMMM Do YYYY, h:mm:ss a')})`,
111 note_url: 'https://github.com/node-gh/gh',
112 scopes: ['user', 'public_repo', 'repo', 'repo:status', 'delete_repo', 'gist'],
113 };
114 try {
115 var { data } = await octokit.oauthAuthorizations.createAuthorization(payload);
116 }
117 catch (err) {
118 throw new Error(`Error creating GitHub token\n${err.message}`);
119 }
120 if (data.token) {
121 configs_1.writeGlobalConfigCredentials(answers.username, data.token, process.env.GENERATE_NEW_TOKEN && path_1.join(__dirname, '../__tests__/auth.json'));
122 return data.token;
123 }
124 logger.log(`Was not able to retrieve token from GitHub's api`);
125}
126//# sourceMappingURL=github.js.map
\No newline at end of file