From ebb1f4f1ce428a0059c593205e6841e61f479915 Mon Sep 17 00:00:00 2001 From: Kanad Gupta Date: Tue, 12 Sep 2023 18:32:19 -0500 Subject: [PATCH] refactor: remove node-config --- __tests__/cmds/logout.test.ts | 6 ++-- __tests__/cmds/open.test.ts | 6 ++-- __tests__/cmds/openapi/index.test.ts | 4 +-- __tests__/cmds/whoami.test.ts | 4 +-- __tests__/helpers/get-api-mock.ts | 6 ++-- .../single-threaded/openapi/index.test.ts | 22 ++++++------ config/custom-environment-variables.json | 1 - config/localhost.json | 4 --- config/rdme-test.json | 1 - package-lock.json | 36 ------------------- package.json | 1 - src/cmds/categories/create.ts | 4 +-- src/cmds/docs/edit.ts | 4 +-- src/cmds/docs/prune.ts | 4 +-- src/cmds/logout.ts | 5 ++- src/cmds/open.ts | 10 +++--- src/cmds/openapi/inspect.ts | 6 ++-- src/cmds/versions/create.ts | 4 +-- src/cmds/whoami.ts | 4 +-- src/index.ts | 32 +++++------------ config/default.js => src/lib/config.ts | 9 ++--- src/lib/help.ts | 12 +++---- src/lib/logger.ts | 4 +-- src/lib/readmeAPIFetch.ts | 4 +-- src/lib/syncDocsPath.ts | 4 +-- 25 files changed, 68 insertions(+), 129 deletions(-) delete mode 100644 config/custom-environment-variables.json delete mode 100644 config/localhost.json delete mode 100644 config/rdme-test.json rename config/default.js => src/lib/config.ts (52%) diff --git a/__tests__/cmds/logout.test.ts b/__tests__/cmds/logout.test.ts index ae3d2b415..82f682992 100644 --- a/__tests__/cmds/logout.test.ts +++ b/__tests__/cmds/logout.test.ts @@ -1,7 +1,7 @@ -import config from 'config'; import { describe, afterEach, it, expect } from 'vitest'; import Command from '../../src/cmds/logout'; +import config from '../../src/lib/config'; import configStore from '../../src/lib/configstore'; const cmd = new Command(); @@ -16,7 +16,7 @@ describe('rdme logout', () => { configStore.delete('project'); return expect(cmd.run({})).resolves.toBe( - `You have logged out of ReadMe. Please use \`${config.get('cli')} login\` to login again.`, + `You have logged out of ReadMe. Please use \`${config.cli} login\` to login again.`, ); }); @@ -25,7 +25,7 @@ describe('rdme logout', () => { configStore.set('project', 'subdomain'); await expect(cmd.run({})).resolves.toBe( - `You have logged out of ReadMe. Please use \`${config.get('cli')} login\` to login again.`, + `You have logged out of ReadMe. Please use \`${config.cli} login\` to login again.`, ); expect(configStore.get('email')).toBeUndefined(); diff --git a/__tests__/cmds/open.test.ts b/__tests__/cmds/open.test.ts index fee0ee488..202005b69 100644 --- a/__tests__/cmds/open.test.ts +++ b/__tests__/cmds/open.test.ts @@ -1,10 +1,10 @@ import type { Version } from '../../src/cmds/versions'; import chalk from 'chalk'; -import config from 'config'; import { describe, afterEach, it, expect } from 'vitest'; import Command from '../../src/cmds/open'; +import config from '../../src/lib/config'; import configStore from '../../src/lib/configstore'; import getAPIMock from '../helpers/get-api-mock'; @@ -18,7 +18,7 @@ describe('rdme open', () => { it('should error if no project provided', () => { configStore.delete('project'); - return expect(cmd.run({})).rejects.toStrictEqual(new Error(`Please login using \`${config.get('cli')} login\`.`)); + return expect(cmd.run({})).rejects.toStrictEqual(new Error(`Please login using \`${config.cli} login\`.`)); }); it('should open the project', () => { @@ -82,7 +82,7 @@ describe('rdme open', () => { } return expect(cmd.run({ mockOpen, dash: true, key: '12345' })).rejects.toStrictEqual( - new Error(`Please login using \`${config.get('cli')} login\`.`), + new Error(`Please login using \`${config.cli} login\`.`), ); }); }); diff --git a/__tests__/cmds/openapi/index.test.ts b/__tests__/cmds/openapi/index.test.ts index f755c151b..f481d5433 100644 --- a/__tests__/cmds/openapi/index.test.ts +++ b/__tests__/cmds/openapi/index.test.ts @@ -2,7 +2,6 @@ import fs from 'fs'; import chalk from 'chalk'; -import config from 'config'; import nock from 'nock'; import prompts from 'prompts'; import { describe, beforeAll, beforeEach, afterEach, it, expect, vi } from 'vitest'; @@ -10,6 +9,7 @@ import { describe, beforeAll, beforeEach, afterEach, it, expect, vi } from 'vite import OpenAPICommand from '../../../src/cmds/openapi'; import SwaggerCommand from '../../../src/cmds/swagger'; import APIError from '../../../src/lib/apiError'; +import config from '../../../src/lib/config'; import petstoreWeird from '../../__fixtures__/petstore-simple-weird-version.json'; import getAPIMock, { getAPIMockWithVersionHeader } from '../../helpers/get-api-mock'; import { after, before } from '../../helpers/get-gha-setup'; @@ -24,7 +24,7 @@ let consoleWarnSpy; const key = 'API_KEY'; const id = '5aa0409b7cf527a93bfb44df'; const version = '1.0.0'; -const exampleRefLocation = `${config.get('host')}/project/example-project/1.0.1/refs/ex`; +const exampleRefLocation = `${config.host}/project/example-project/1.0.1/refs/ex`; const successfulMessageBase = (specPath, specType) => [ '', `\t${chalk.green(exampleRefLocation)}`, diff --git a/__tests__/cmds/whoami.test.ts b/__tests__/cmds/whoami.test.ts index ab3007404..a7432681c 100644 --- a/__tests__/cmds/whoami.test.ts +++ b/__tests__/cmds/whoami.test.ts @@ -1,7 +1,7 @@ -import config from 'config'; import { describe, afterEach, it, expect } from 'vitest'; import Command from '../../src/cmds/whoami'; +import config from '../../src/lib/config'; import configStore from '../../src/lib/configstore'; const cmd = new Command(); @@ -15,7 +15,7 @@ describe('rdme whoami', () => { configStore.delete('email'); configStore.delete('project'); - return expect(cmd.run({})).rejects.toStrictEqual(new Error(`Please login using \`${config.get('cli')} login\`.`)); + return expect(cmd.run({})).rejects.toStrictEqual(new Error(`Please login using \`${config.cli} login\`.`)); }); it('should return the authenticated user', () => { diff --git a/__tests__/helpers/get-api-mock.ts b/__tests__/helpers/get-api-mock.ts index 263d63093..942d95c68 100644 --- a/__tests__/helpers/get-api-mock.ts +++ b/__tests__/helpers/get-api-mock.ts @@ -1,10 +1,10 @@ import type { Headers } from 'headers-polyfill'; import type { ResponseTransformer } from 'msw'; -import config from 'config'; import { rest } from 'msw'; import nock from 'nock'; +import config from '../../src/lib/config'; import { getUserAgent } from '../../src/lib/readmeAPIFetch'; /** @@ -20,7 +20,7 @@ type ReqHeaders = Record; * @param proxy Optional proxy URL. Must contain trailing slash. */ export default function getAPIMock(reqHeaders = {}, proxy = '') { - return nock(`${proxy}${config.get('host')}`, { + return nock(`${proxy}${config.host}`, { reqheaders: { 'User-Agent': getUserAgent(), ...reqHeaders, @@ -76,7 +76,7 @@ export function getAPIMockMSW( expectedReqHeaders: ReqHeaders = {}, proxy = '', ) { - return rest.get(`${proxy}${config.get('host')}${path}`, (req, res, ctx) => { + return rest.get(`${proxy}${config.host}${path}`, (req, res, ctx) => { try { validateHeaders(req.headers, basicAuthUser, expectedReqHeaders); let responseTransformer: ResponseTransformer; diff --git a/__tests__/single-threaded/openapi/index.test.ts b/__tests__/single-threaded/openapi/index.test.ts index ecf4888e5..1ac580c91 100644 --- a/__tests__/single-threaded/openapi/index.test.ts +++ b/__tests__/single-threaded/openapi/index.test.ts @@ -2,13 +2,13 @@ import fs from 'fs'; import chalk from 'chalk'; -import config from 'config'; import { rest } from 'msw'; import { setupServer } from 'msw/node'; import prompts from 'prompts'; import { describe, beforeAll, beforeEach, afterEach, it, expect, vi, afterAll } from 'vitest'; import OpenAPICommand from '../../../src/cmds/openapi'; +import config from '../../../src/lib/config'; import { getAPIMockMSW } from '../../helpers/get-api-mock'; import { after, before } from '../../helpers/get-gha-setup'; import { after as afterGHAEnv, before as beforeGHAEnv } from '../../helpers/setup-gha-env'; @@ -20,7 +20,7 @@ let consoleWarnSpy; const key = 'API_KEY'; const version = '1.0.0'; -const exampleRefLocation = `${config.get('host')}/project/example-project/1.0.1/refs/ex`; +const exampleRefLocation = `${config.host}/project/example-project/1.0.1/refs/ex`; const successfulMessageBase = (specPath, specType) => [ '', `\t${chalk.green(exampleRefLocation)}`, @@ -73,13 +73,13 @@ describe('rdme openapi (single-threaded)', () => { server.use( ...[ getAPIMockMSW(`/api/v1/version/${version}`, 200, { json: { version } }, key), - rest.post(`${config.get('host')}/api/v1/api-registry`, async (req, res, ctx) => { + rest.post(`${config.host}/api/v1/api-registry`, async (req, res, ctx) => { const body = await req.text(); expect(body).toMatch('form-data; name="spec"'); return res(ctx.status(201), ctx.json({ registryUUID, spec: { openapi: '3.0.0' } })); }), getAPIMockMSW('/api/v1/api-specification', 200, { json: [] }, key, { 'x-readme-version': version }), - rest.post(`${config.get('host')}/api/v1/api-specification`, async (req, res, ctx) => { + rest.post(`${config.host}/api/v1/api-specification`, async (req, res, ctx) => { const body = await req.json(); expect(body).toStrictEqual({ registryUUID }); expect(req.headers.get('authorization')).toBeBasicAuthApiKey(key); @@ -112,7 +112,7 @@ describe('rdme openapi (single-threaded)', () => { server.use( ...[ getAPIMockMSW(`/api/v1/version/${version}`, 200, { json: { version } }, key), - rest.post(`${config.get('host')}/api/v1/api-registry`, async (req, res, ctx) => { + rest.post(`${config.host}/api/v1/api-registry`, async (req, res, ctx) => { const body = await req.text(); requestBody = body.substring(body.indexOf('{'), body.lastIndexOf('}') + 1); requestBody = JSON.parse(requestBody); @@ -120,7 +120,7 @@ describe('rdme openapi (single-threaded)', () => { return res(ctx.status(201), ctx.json({ registryUUID, spec: { openapi: '3.0.0' } })); }), getAPIMockMSW('/api/v1/api-specification', 200, { json: [] }, key, { 'x-readme-version': version }), - rest.post(`${config.get('host')}/api/v1/api-specification`, async (req, res, ctx) => { + rest.post(`${config.host}/api/v1/api-specification`, async (req, res, ctx) => { const body = await req.json(); expect(body).toStrictEqual({ registryUUID }); expect(req.headers.get('authorization')).toBeBasicAuthApiKey(key); @@ -152,7 +152,7 @@ describe('rdme openapi (single-threaded)', () => { server.use( ...[ getAPIMockMSW(`/api/v1/version/${version}`, 200, { json: { version } }, key), - rest.post(`${config.get('host')}/api/v1/api-registry`, async (req, res, ctx) => { + rest.post(`${config.host}/api/v1/api-registry`, async (req, res, ctx) => { const body = await req.text(); expect(body).toMatch('form-data; name="spec"'); return res(ctx.status(201), ctx.json({ registryUUID, spec: { openapi: '3.0.0' } })); @@ -211,13 +211,13 @@ describe('rdme openapi (single-threaded)', () => { server.use( ...[ getAPIMockMSW(`/api/v1/version/${version}`, 200, { json: { version } }, key), - rest.post(`${config.get('host')}/api/v1/api-registry`, async (req, res, ctx) => { + rest.post(`${config.host}/api/v1/api-registry`, async (req, res, ctx) => { const body = await req.text(); expect(body).toMatch('form-data; name="spec"'); return res(ctx.status(201), ctx.json({ registryUUID, spec: { openapi: '3.0.0' } })); }), getAPIMockMSW('/api/v1/api-specification', 200, { json: [] }, key, { 'x-readme-version': version }), - rest.post(`${config.get('host')}/api/v1/api-specification`, async (req, res, ctx) => { + rest.post(`${config.host}/api/v1/api-specification`, async (req, res, ctx) => { expect(req.headers.get('authorization')).toBeBasicAuthApiKey(key); const body = await req.json(); expect(body).toStrictEqual({ registryUUID }); @@ -260,13 +260,13 @@ describe('rdme openapi (single-threaded)', () => { server.use( ...[ getAPIMockMSW(`/api/v1/version/${version}`, 200, { json: { version } }, key), - rest.post(`${config.get('host')}/api/v1/api-registry`, async (req, res, ctx) => { + rest.post(`${config.host}/api/v1/api-registry`, async (req, res, ctx) => { const body = await req.text(); expect(body).toMatch('form-data; name="spec"'); return res(ctx.status(201), ctx.json({ registryUUID, spec: { openapi: '3.0.0' } })); }), getAPIMockMSW('/api/v1/api-specification', 200, { json: [] }, key, { 'x-readme-version': version }), - rest.post(`${config.get('host')}/api/v1/api-specification`, async (req, res, ctx) => { + rest.post(`${config.host}/api/v1/api-specification`, async (req, res, ctx) => { expect(req.headers.get('authorization')).toBeBasicAuthApiKey(key); expect(req.headers.get('x-rdme-ci')).toBe('GitHub Actions (test)'); expect(req.headers.get('x-readme-source')).toBe('cli-gh'); diff --git a/config/custom-environment-variables.json b/config/custom-environment-variables.json deleted file mode 100644 index 1a403feca..000000000 --- a/config/custom-environment-variables.json +++ /dev/null @@ -1 +0,0 @@ -{ "host": "README_HOST", "hub": "README_HUB" } diff --git a/config/localhost.json b/config/localhost.json deleted file mode 100644 index beed57634..000000000 --- a/config/localhost.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "host": "http://dash.readme.local:3000", - "hub": "http://{project}.readme.local:3000" -} diff --git a/config/rdme-test.json b/config/rdme-test.json deleted file mode 100644 index 0967ef424..000000000 --- a/config/rdme-test.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/package-lock.json b/package-lock.json index 84cf66274..cc8428223 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,7 +14,6 @@ "ci-info": "^3.6.1", "command-line-args": "^5.2.0", "command-line-usage": "^7.0.1", - "config": "^3.1.0", "configstore": "^5.0.0", "debug": "^4.3.3", "editor": "^1.0.0", @@ -3681,17 +3680,6 @@ "typedarray": "^0.0.6" } }, - "node_modules/config": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/config/-/config-3.3.9.tgz", - "integrity": "sha512-G17nfe+cY7kR0wVpc49NCYvNtelm/pPy8czHoFkAgtV1lkmcp7DHtWCdDu+C9Z7gb2WVqa9Tm3uF9aKaPbCfhg==", - "dependencies": { - "json5": "^2.2.3" - }, - "engines": { - "node": ">= 10.0.0" - } - }, "node_modules/config-chain": { "version": "1.1.13", "resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.13.tgz", @@ -8179,17 +8167,6 @@ "node": ">= 4" } }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, "node_modules/jsonc-parser": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.0.tgz", @@ -17808,14 +17785,6 @@ "typedarray": "^0.0.6" } }, - "config": { - "version": "3.3.9", - "resolved": "https://registry.npmjs.org/config/-/config-3.3.9.tgz", - "integrity": "sha512-G17nfe+cY7kR0wVpc49NCYvNtelm/pPy8czHoFkAgtV1lkmcp7DHtWCdDu+C9Z7gb2WVqa9Tm3uF9aKaPbCfhg==", - "requires": { - "json5": "^2.2.3" - } - }, "config-chain": { "version": "1.1.13", "resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.13.tgz", @@ -21016,11 +20985,6 @@ "grapheme-splitter": "^1.0.4" } }, - "json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==" - }, "jsonc-parser": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.0.tgz", diff --git a/package.json b/package.json index 98d6e333f..0400111c1 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,6 @@ "ci-info": "^3.6.1", "command-line-args": "^5.2.0", "command-line-usage": "^7.0.1", - "config": "^3.1.0", "configstore": "^5.0.0", "debug": "^4.3.3", "editor": "^1.0.0", diff --git a/src/cmds/categories/create.ts b/src/cmds/categories/create.ts index 96df23e30..b7a900796 100644 --- a/src/cmds/categories/create.ts +++ b/src/cmds/categories/create.ts @@ -1,10 +1,10 @@ import type { CommandOptions } from '../../lib/baseCommand'; import chalk from 'chalk'; -import config from 'config'; import { Headers } from 'node-fetch'; import Command, { CommandCategories } from '../../lib/baseCommand'; +import config from '../../lib/config'; import getCategories from '../../lib/getCategories'; import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch'; import { getProjectVersion } from '../../lib/versionSelect'; @@ -58,7 +58,7 @@ export default class CategoriesCreateCommand extends Command { const { categoryType, title, key, version, preventDuplicates } = opts; if (!title) { - return Promise.reject(new Error(`No title provided. Usage \`${config.get('cli')} ${this.usage}\`.`)); + return Promise.reject(new Error(`No title provided. Usage \`${config.cli} ${this.usage}\`.`)); } if (categoryType !== 'guide' && categoryType !== 'reference') { diff --git a/src/cmds/docs/edit.ts b/src/cmds/docs/edit.ts index 131c949eb..9305dd57a 100644 --- a/src/cmds/docs/edit.ts +++ b/src/cmds/docs/edit.ts @@ -3,13 +3,13 @@ import type { CommandOptions } from '../../lib/baseCommand'; import fs from 'fs'; import { promisify } from 'util'; -import config from 'config'; import { Headers } from 'node-fetch'; import editor from 'editor'; import APIError from '../../lib/apiError'; import Command, { CommandCategories } from '../../lib/baseCommand'; +import config from '../../lib/config'; import isHidden from '../../lib/decorators/isHidden'; import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch'; import { getProjectVersion } from '../../lib/versionSelect'; @@ -52,7 +52,7 @@ export default class DocsEditCommand extends Command { const { slug, key, version } = opts; if (!slug) { - return Promise.reject(new Error(`No slug provided. Usage \`${config.get('cli')} ${this.usage}\`.`)); + return Promise.reject(new Error(`No slug provided. Usage \`${config.cli} ${this.usage}\`.`)); } const selectedVersion = await getProjectVersion(version, key); diff --git a/src/cmds/docs/prune.ts b/src/cmds/docs/prune.ts index cbc140f09..a8729d7b5 100644 --- a/src/cmds/docs/prune.ts +++ b/src/cmds/docs/prune.ts @@ -1,10 +1,10 @@ import type { CommandOptions } from '../../lib/baseCommand'; import chalk from 'chalk'; -import config from 'config'; import prompts from 'prompts'; import Command, { CommandCategories } from '../../lib/baseCommand'; +import config from '../../lib/config'; import createGHA from '../../lib/createGHA'; import deleteDoc from '../../lib/deleteDoc'; import getDocs from '../../lib/getDocs'; @@ -62,7 +62,7 @@ export default class DocsPruneCommand extends Command { const { dryRun, folder, key, version } = opts; if (!folder) { - return Promise.reject(new Error(`No folder provided. Usage \`${config.get('cli')} ${this.usage}\`.`)); + return Promise.reject(new Error(`No folder provided. Usage \`${config.cli} ${this.usage}\`.`)); } // TODO: should we allow version selection at all here? diff --git a/src/cmds/logout.ts b/src/cmds/logout.ts index ee0c68fb6..377bb79ab 100644 --- a/src/cmds/logout.ts +++ b/src/cmds/logout.ts @@ -1,8 +1,7 @@ import type { CommandOptions } from '../lib/baseCommand'; -import config from 'config'; - import Command, { CommandCategories } from '../lib/baseCommand'; +import config from '../lib/config'; import configStore from '../lib/configstore'; export default class LogoutCommand extends Command { @@ -24,6 +23,6 @@ export default class LogoutCommand extends Command { configStore.clear(); } - return Promise.resolve(`You have logged out of ReadMe. Please use \`${config.get('cli')} login\` to login again.`); + return Promise.resolve(`You have logged out of ReadMe. Please use \`${config.cli} login\` to login again.`); } } diff --git a/src/cmds/open.ts b/src/cmds/open.ts index 76b980dc7..17ecce073 100644 --- a/src/cmds/open.ts +++ b/src/cmds/open.ts @@ -1,10 +1,10 @@ import type { CommandOptions } from '../lib/baseCommand'; import chalk from 'chalk'; -import config from 'config'; import open from 'open'; import Command, { CommandCategories } from '../lib/baseCommand'; +import config from '../lib/config'; import getCurrentConfig from '../lib/getCurrentConfig'; import { getProjectVersion } from '../lib/versionSelect'; @@ -39,21 +39,21 @@ export default class OpenCommand extends Command { Command.debug(`project: ${project}`); if (!project) { - return Promise.reject(new Error(`Please login using \`${config.get('cli')} login\`.`)); + return Promise.reject(new Error(`Please login using \`${config.cli} login\`.`)); } let url: string; if (dash) { if (!apiKey) { - return Promise.reject(new Error(`Please login using \`${config.get('cli')} login\`.`)); + return Promise.reject(new Error(`Please login using \`${config.cli} login\`.`)); } const selectedVersion = await getProjectVersion(undefined, apiKey, true); - const dashURL: string = config.get('host'); + const dashURL: string = config.host; url = `${dashURL}/project/${project}/v${selectedVersion}/overview`; } else { - const hubURL: string = config.get('hub'); + const hubURL: string = config.hub; url = hubURL.replace('{project}', project); } diff --git a/src/cmds/openapi/inspect.ts b/src/cmds/openapi/inspect.ts index fa5981470..49265f1ae 100644 --- a/src/cmds/openapi/inspect.ts +++ b/src/cmds/openapi/inspect.ts @@ -3,13 +3,13 @@ import type { CommandOptions } from '../../lib/baseCommand'; import type { OASDocument } from 'oas/dist/rmoas.types'; import chalk from 'chalk'; -import config from 'config'; import ora from 'ora'; import pluralize from 'pluralize'; import { getBorderCharacters, table } from 'table'; import analyzeOas, { getSupportedFeatures } from '../../lib/analyzeOas'; import Command, { CommandCategories } from '../../lib/baseCommand'; +import config from '../../lib/config'; import { oraOptions } from '../../lib/logger'; import prepareOas from '../../lib/prepareOas'; import SoftError from '../../lib/softError'; @@ -226,9 +226,7 @@ export default class OpenAPIInspectCommand extends Command { if (invalidFeatures.length) { return Promise.reject( new Error( - `Unknown features: ${invalidFeatures.join(', ')}. See \`${config.get('cli')} help ${ - this.command - }\` for help.`, + `Unknown features: ${invalidFeatures.join(', ')}. See \`${config.cli} help ${this.command}\` for help.`, ), ); } diff --git a/src/cmds/versions/create.ts b/src/cmds/versions/create.ts index 5b79854e2..a16a67e07 100644 --- a/src/cmds/versions/create.ts +++ b/src/cmds/versions/create.ts @@ -1,13 +1,13 @@ import type { Version } from '.'; import type { CommandOptions } from '../../lib/baseCommand'; -import config from 'config'; import { Headers } from 'node-fetch'; import prompts from 'prompts'; import semver from 'semver'; import Command, { CommandCategories } from '../../lib/baseCommand'; import castStringOptToBool from '../../lib/castStringOptToBool'; +import config from '../../lib/config'; import * as promptHandler from '../../lib/prompts'; import promptTerminal from '../../lib/promptWrapper'; import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch'; @@ -53,7 +53,7 @@ export default class CreateVersionCommand extends Command { if (!version || !semver.valid(semver.coerce(version))) { return Promise.reject( - new Error(`Please specify a semantic version. See \`${config.get('cli')} help ${this.command}\` for help.`), + new Error(`Please specify a semantic version. See \`${config.cli} help ${this.command}\` for help.`), ); } diff --git a/src/cmds/whoami.ts b/src/cmds/whoami.ts index 3e906b96d..d43df443b 100644 --- a/src/cmds/whoami.ts +++ b/src/cmds/whoami.ts @@ -1,9 +1,9 @@ import type { CommandOptions } from '../lib/baseCommand'; import chalk from 'chalk'; -import config from 'config'; import Command, { CommandCategories } from '../lib/baseCommand'; +import config from '../lib/config'; import getCurrentConfig from '../lib/getCurrentConfig'; export default class WhoAmICommand extends Command { @@ -24,7 +24,7 @@ export default class WhoAmICommand extends Command { const { email, project } = getCurrentConfig(); if (!email || !project) { - return Promise.reject(new Error(`Please login using \`${config.get('cli')} login\`.`)); + return Promise.reject(new Error(`Please login using \`${config.cli} login\`.`)); } return Promise.resolve( diff --git a/src/index.ts b/src/index.ts index 8a3b0f42f..0ec4751de 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,33 +1,19 @@ -/* eslint-disable import/first, import/order, no-underscore-dangle */ -import path from 'path'; +/* eslint-disable no-underscore-dangle */ +import type Command from './lib/baseCommand'; +import type { CommandOptions } from './lib/baseCommand'; import chalk from 'chalk'; import cliArgs from 'command-line-args'; import parseArgsStringToArgv from 'string-argv'; -// We have to do this otherwise `require('config')` loads -// from the cwd where the user is running `rdme` which -// wont be what we want -// -// This is a little sketchy overwriting environment variables -// but since this is only supposed to be a cli and not -// requireable, i think this is okay -const configDir = process.env.NODE_CONFIG_DIR; -process.env.NODE_CONFIG_DIR = path.join(__dirname, '../config'); - -import config from 'config'; - -process.env.NODE_CONFIG_DIR = configDir; - import { version } from '../package.json'; import * as commands from './lib/commands'; -import * as help from './lib/help'; -import { debug } from './lib/logger'; +import config from './lib/config'; import createGHA from './lib/createGHA'; -import type Command from './lib/baseCommand'; -import type { CommandOptions } from './lib/baseCommand'; import getCurrentConfig from './lib/getCurrentConfig'; +import * as help from './lib/help'; +import { debug } from './lib/logger'; /** * @param {Array} processArgv - An array of arguments from the current process. Can be used to mock @@ -41,7 +27,7 @@ export default function rdme(rawProcessArgv: NodeJS.Process['argv']) { name: 'version', alias: 'v', type: Boolean, - description: `Show the current ${config.get('cli')} version (v${version})`, + description: `Show the current ${config.cli} version (v${version})`, }, { name: 'command', type: String, defaultOption: true }, ]; @@ -156,9 +142,7 @@ export default function rdme(rawProcessArgv: NodeJS.Process['argv']) { }); } catch (e) { if (e.message === 'Command not found.') { - e.message = `${e.message}\n\nType \`${chalk.yellow(`${config.get('cli')} help`)}\` ${chalk.red( - 'to see all commands', - )}`; + e.message = `${e.message}\n\nType \`${chalk.yellow(`${config.cli} help`)}\` ${chalk.red('to see all commands')}`; } return Promise.reject(e); diff --git a/config/default.js b/src/lib/config.ts similarity index 52% rename from config/default.js rename to src/lib/config.ts index c00432e7a..531513e2a 100644 --- a/config/default.js +++ b/src/lib/config.ts @@ -1,6 +1,7 @@ -module.exports = { - // eslint-disable-next-line global-require - cli: require('../package.json').name, +const config = { + cli: 'rdme', host: 'https://dash.readme.com', hub: 'https://{project}.readme.io', // this is only used for the `open` command -}; +} as const; + +export default config; diff --git a/src/lib/help.ts b/src/lib/help.ts index 75d7ffc36..743ce7464 100644 --- a/src/lib/help.ts +++ b/src/lib/help.ts @@ -3,9 +3,9 @@ import type { Section } from 'command-line-usage'; import chalk from 'chalk'; import usage from 'command-line-usage'; -import config from 'config'; import * as commands from './commands'; +import config from './config'; function formatCommands(cmds: { description: string; hidden: boolean; name: string }[]) { return cmds @@ -13,7 +13,7 @@ function formatCommands(cmds: { description: string; hidden: boolean; name: stri .filter(command => !command.hidden) .map(command => { return { - name: `${chalk.grey('$')} ${config.get('cli')} ${command.name}`, + name: `${chalk.grey('$')} ${config.cli} ${command.name}`, summary: command.description, }; }); @@ -21,7 +21,7 @@ function formatCommands(cmds: { description: string; hidden: boolean; name: stri const owlbert = () => { // http://asciiart.club - return ` 📖 ${chalk.blue.bold(config.get('cli'))} + return ` 📖 ${chalk.blue.bold(config.cli)} ${chalk.bold('a utility for interacting with ReadMe')} . @@ -63,7 +63,7 @@ function commandUsage(cmd: Command) { }, { header: 'Usage', - content: `${config.get('cli')} ${cmd.usage}`, + content: `${config.cli} ${cmd.usage}`, }, { header: 'Options', @@ -98,7 +98,7 @@ async function globalUsage(args: Command['args']) { }, { header: 'Usage', - content: `${config.get('cli')} [arguments]`, + content: `${config.cli} [arguments]`, }, { header: 'Options', @@ -120,7 +120,7 @@ async function globalUsage(args: Command['args']) { helpContent.push( { - content: `Run ${chalk.dim(`${config.get('cli')} help `)} for help with a specific command.`, + content: `Run ${chalk.dim(`${config.cli} help `)} for help with a specific command.`, raw: true, }, { diff --git a/src/lib/logger.ts b/src/lib/logger.ts index c6a64b421..648700c88 100644 --- a/src/lib/logger.ts +++ b/src/lib/logger.ts @@ -3,12 +3,12 @@ import type { Writable } from 'type-fest'; import * as core from '@actions/core'; import chalk from 'chalk'; -import config from 'config'; import debugModule from 'debug'; +import config from './config'; import { isGHA, isTest } from './isCI'; -const debugPackage = debugModule(config.get('cli')); +const debugPackage = debugModule(config.cli); /** * Wrapper for debug statements. diff --git a/src/lib/readmeAPIFetch.ts b/src/lib/readmeAPIFetch.ts index a788505b1..21833c2ed 100644 --- a/src/lib/readmeAPIFetch.ts +++ b/src/lib/readmeAPIFetch.ts @@ -3,13 +3,13 @@ import type { RequestInit, Response } from 'node-fetch'; import path from 'path'; -import config from 'config'; import mime from 'mime-types'; import nodeFetch, { Headers } from 'node-fetch'; // eslint-disable-line no-restricted-imports import pkg from '../../package.json'; import APIError from './apiError'; +import config from './config'; import { git } from './createGHA'; import isCI, { ciName, isGHA } from './isCI'; import { debug, warn } from './logger'; @@ -182,7 +182,7 @@ export default async function readmeAPIFetch( headers.set('x-readme-source-url', fileOpts.filePath); } - const fullUrl = `${getProxy()}${config.get('host')}${pathname}`; + const fullUrl = `${getProxy()}${config.host}${pathname}`; debug( `making ${(options.method || 'get').toUpperCase()} request to ${fullUrl} with headers: ${sanitizeHeaders(headers)}`, diff --git a/src/lib/syncDocsPath.ts b/src/lib/syncDocsPath.ts index 845c771df..3f0652645 100644 --- a/src/lib/syncDocsPath.ts +++ b/src/lib/syncDocsPath.ts @@ -2,11 +2,11 @@ import fs from 'fs/promises'; import path from 'path'; import chalk from 'chalk'; -import config from 'config'; import { Headers } from 'node-fetch'; import APIError from './apiError'; import Command, { CommandCategories } from './baseCommand'; +import config from './config'; import { debug } from './logger'; import readdirRecursive from './readdirRecursive'; import readDoc from './readDoc'; @@ -167,7 +167,7 @@ export default async function syncDocsPath( allowedFileExtensions = ['.markdown', '.md'], ) { if (!pathInput) { - return Promise.reject(new Error(`No path provided. Usage \`${config.get('cli')} ${usage}\`.`)); + return Promise.reject(new Error(`No path provided. Usage \`${config.cli} ${usage}\`.`)); } const stat = await fs.stat(pathInput).catch(err => {