UNPKG

npm-fetch-changelog

Version:

fetch the changelog for an npm package from GitHub

108 lines 3.26 kB
import * as fs from 'fs-extra'; import path from 'path'; import os from 'os'; import once from "./util/once.mjs"; import { spawn } from 'promisify-child-process'; import { debug } from "./util/debug.mjs"; const configFilePath = path.join(os.homedir(), '.config', 'npm-fetch-changelog.json'); const getConfig = once(async function getConfig() { const configSources = await Promise.all([(async () => { try { const { githubToken, npmToken } = await fs.readJson(configFilePath); return { file: '~/.config/npm-fetch-changelog.json', config: { githubToken: typeof githubToken === 'string' ? githubToken : undefined, npmToken: typeof npmToken === 'string' ? npmToken : undefined } }; } catch (error) { return { file: '~/.config/npm-fetch-changelog.json', error }; } })(), (async () => { try { var _exec; const npmrc = await fs.readFile(path.join(os.homedir(), '.npmrc'), 'utf8'); const npmToken = (_exec = /\/\/registry\.npmjs\.org\/?:_authToken=(\S+)/.exec(npmrc)) === null || _exec === void 0 ? void 0 : _exec[1]; return { file: '~/.npmrc', config: { npmToken } }; } catch (error) { return { file: '~/.npmrc', error }; } })(), (async () => { try { var _await$spawn$stdout; const githubToken = (_await$spawn$stdout = (await spawn('gh', ['auth', 'token'], { stdio: 'pipe', maxBuffer: 1024 })).stdout) === null || _await$spawn$stdout === void 0 ? void 0 : _await$spawn$stdout.toString().trim(); return { file: 'gh auth token', config: { githubToken } }; } catch (error) { return { file: 'gh auth token', error }; } })(), { file: 'process.env.GH_TOKEN', config: { githubToken: process.env.GH_TOKEN || undefined } }, { file: 'process.env.NPM_TOKEN', config: { npmToken: process.env.NPM_TOKEN || undefined } }]); const result = {}; for (const { file, config, error } of configSources) { if (error) { if ((error === null || error === void 0 ? void 0 : error.code) === 'ENOENT') { debug(`${file} not found`); } else { debug(`failed to read ${file}`, error instanceof Error ? error.stack : error); } continue; } if (config) { if ('githubToken' in config) { debug(`${file} ${config !== null && config !== void 0 && config.githubToken ? 'has' : 'does not have'} githubToken`); } if ('npmToken' in config) { debug(`${file} ${config !== null && config !== void 0 && config.npmToken ? 'has' : 'does not have'} npmToken`); } if (!(result !== null && result !== void 0 && result.githubToken) && config.githubToken) { debug(`using githubToken from ${file}`); result.githubToken = config.githubToken; } if (!(result !== null && result !== void 0 && result.npmToken) && config.npmToken) { debug(`using npmToken from ${file}`); result.npmToken = config.npmToken; } } } return result; }); export default getConfig;