Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: minor refactor of how we debug and log out data in commands #563

Merged
merged 25 commits into from
Aug 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
8a5619c
docs: add some JSDocs for getProjectVersion
kanadgupta Aug 5, 2022
a39abe7
fix(openapi): add trailing period to param description
kanadgupta Aug 5, 2022
36e74dd
refactor: consolidate version opt descriptions
kanadgupta Aug 5, 2022
4be032d
test: update snapshots
kanadgupta Aug 5, 2022
f937dc1
feat: initial pass at CI version handling
kanadgupta Aug 8, 2022
f2fb63d
feat: initial pass at `useSpecVersion` flag
kanadgupta Aug 8, 2022
313505c
test: fix snapshots
kanadgupta Aug 8, 2022
8ebaf2c
test: fix test
kanadgupta Aug 8, 2022
6f87f80
test: add coverage for various version edge cases
kanadgupta Aug 8, 2022
8b445fb
test: use different file
kanadgupta Aug 8, 2022
ea5dff1
chore(openapi): alphabetize opts
kanadgupta Aug 8, 2022
6925bd4
chore: use info statement instead of debug
kanadgupta Aug 8, 2022
bfba671
chore: use info emoji in logger
kanadgupta Aug 9, 2022
ab9c956
test: fix tests
kanadgupta Aug 9, 2022
2172213
chore: attempt to merge
kanadgupta Aug 9, 2022
ae493f1
fix: import paths for versionOpt
kanadgupta Aug 9, 2022
f979f5b
fix: some merge issues
kanadgupta Aug 9, 2022
07cddf9
fix: lint
kanadgupta Aug 9, 2022
26d9f9f
test: fix one more test jeez
kanadgupta Aug 9, 2022
2cd9847
Merge branch 'main' into kanad/rm-4984-if-run-in-ci-environment-just-…
kanadgupta Aug 9, 2022
695438b
fix: trailing period
kanadgupta Aug 9, 2022
ab3fad6
fix: version arg refactors
erunion Aug 9, 2022
54ddc0a
feat: minor refactor of how we debug and log out data in commands
erunion Aug 9, 2022
a66095f
chore(deps-dev): bumping eslint-config to v10
erunion Aug 10, 2022
2efc978
Merge branch 'main' into feat/minor-refactors
kanadgupta Aug 10, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 0 additions & 9 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,6 @@
*/
"class-methods-use-this": ["error", { "exceptMethods": ["run"] }],

"import/order": ["error", {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved into our core standards and tagged a major release of that pkg. readmeio/standards@edffdbe

"alphabetize": {
"order": "asc",
"caseInsensitive": true
},
"groups": ["type", "builtin", "external", "internal", "parent", "sibling", "index", "object"],
"newlines-between": "always"
}],

/**
* This is a small rule to prevent us from using console.log() statements in our commands.
*
Expand Down
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
"update-notifier": "^5.1.0"
},
"devDependencies": {
"@readme/eslint-config": "^9.0.0",
"@readme/eslint-config": "^10.0.0",
"@readme/oas-examples": "^5.3.0",
"@types/cli-table": "^0.3.0",
"@types/command-line-args": "^5.2.0",
Expand Down
3 changes: 1 addition & 2 deletions src/cmds/categories/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { Headers } from 'node-fetch';
import Command, { CommandCategories } from '../../lib/baseCommand';
import fetch, { cleanHeaders, handleRes } from '../../lib/fetch';
import getCategories from '../../lib/getCategories';
import { debug } from '../../lib/logger';
import { getProjectVersion } from '../../lib/versionSelect';

interface Category {
Expand Down Expand Up @@ -73,7 +72,7 @@ export default class CategoriesCreateCommand extends Command {

const selectedVersion = await getProjectVersion(version, key, false);

debug(`selectedVersion: ${selectedVersion}`);
Command.debug(`selectedVersion: ${selectedVersion}`);

async function matchCategory() {
const allCategories = await getCategories(key, selectedVersion);
Expand Down
3 changes: 1 addition & 2 deletions src/cmds/categories/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { CommandOptions } from '../../lib/baseCommand';

import Command, { CommandCategories } from '../../lib/baseCommand';
import getCategories from '../../lib/getCategories';
import { debug } from '../../lib/logger';
import { getProjectVersion } from '../../lib/versionSelect';

export default class CategoriesCommand extends Command {
Expand Down Expand Up @@ -32,7 +31,7 @@ export default class CategoriesCommand extends Command {

const selectedVersion = await getProjectVersion(version, key, true);

debug(`selectedVersion: ${selectedVersion}`);
Command.debug(`selectedVersion: ${selectedVersion}`);

const allCategories = await getCategories(key, selectedVersion);

Expand Down
3 changes: 1 addition & 2 deletions src/cmds/changelogs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import chalk from 'chalk';
import config from 'config';

import Command, { CommandCategories } from '../../lib/baseCommand';
import { debug } from '../../lib/logger';
import pushDoc, { readdirRecursive } from '../../lib/pushDoc';

export type Options = {
Expand Down Expand Up @@ -56,7 +55,7 @@ export default class ChangelogsCommand extends Command {
file => file.toLowerCase().endsWith('.md') || file.toLowerCase().endsWith('.markdown')
);

debug(`number of files: ${files.length}`);
Command.debug(`number of files: ${files.length}`);

if (!files.length) {
return Promise.reject(new Error(`We were unable to locate Markdown files in ${folder}.`));
Expand Down
3 changes: 1 addition & 2 deletions src/cmds/custompages/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import chalk from 'chalk';
import config from 'config';

import Command, { CommandCategories } from '../../lib/baseCommand';
import { debug } from '../../lib/logger';
import pushDoc, { readdirRecursive } from '../../lib/pushDoc';

export type Options = {
Expand Down Expand Up @@ -59,7 +58,7 @@ export default class CustomPagesCommand extends Command {
file.toLowerCase().endsWith('.markdown')
);

debug(`number of files: ${files.length}`);
Command.debug(`number of files: ${files.length}`);

if (!files.length) {
return Promise.reject(new Error(`We were unable to locate Markdown or HTML files in ${folder}.`));
Expand Down
18 changes: 10 additions & 8 deletions src/cmds/docs/edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import editor from 'editor';
import APIError from '../../lib/apiError';
import Command, { CommandCategories } from '../../lib/baseCommand';
import fetch, { cleanHeaders, handleRes } from '../../lib/fetch';
import { debug, info } from '../../lib/logger';
import { getProjectVersion } from '../../lib/versionSelect';

const writeFile = promisify(fs.writeFile);
Expand Down Expand Up @@ -60,7 +59,7 @@ export default class EditDocsCommand extends Command {

const selectedVersion = await getProjectVersion(version, key, true);

debug(`selectedVersion: ${selectedVersion}`);
Command.debug(`selectedVersion: ${selectedVersion}`);

const filename = `${slug}.md`;

Expand All @@ -77,15 +76,15 @@ export default class EditDocsCommand extends Command {

await writeFile(filename, existingDoc.body);

debug(`wrote to local file: ${filename}, opening editor`);
Command.debug(`wrote to local file: ${filename}, opening editor`);

return new Promise((resolve, reject) => {
(opts.mockEditor || editor)(filename, async (code: number) => {
debug(`editor closed with code ${code}`);
Command.debug(`editor closed with code ${code}`);
if (code !== 0) return reject(new Error('Non zero exit code from $EDITOR'));
const updatedDoc = await readFile(filename, 'utf8');

debug(`read edited contents of ${filename}, sending to ReadMe`);
Command.debug(`read edited contents of ${filename}, sending to ReadMe`);

return fetch(`${config.get('host')}/api/v1/docs/${slug}`, {
method: 'put',
Expand All @@ -104,16 +103,19 @@ export default class EditDocsCommand extends Command {
})
.then(res => res.json())
.then(async res => {
debug(`response from PUT request: ${res}`);
Command.debug(`response from PUT request: ${res}`);
// The reason we aren't using our handleRes() function here is
// because we need to use the `reject` function from
// the Promise that's wrapping this function.
if (res.error) {
return reject(new APIError(res));
}
info('Doc successfully updated. Cleaning up local file.');

Command.info('Doc successfully updated. Cleaning up local file.');

await unlink(filename);
debug('file unlinked');
Command.debug('file unlinked');

// Normally we should resolve with a value that is logged to the console,
// but since we need to wait for the temporary file to be removed,
// it's okay to resolve the promise with no value.
Expand Down
5 changes: 2 additions & 3 deletions src/cmds/docs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import chalk from 'chalk';
import config from 'config';

import Command, { CommandCategories } from '../../lib/baseCommand';
import { debug } from '../../lib/logger';
import pushDoc, { readdirRecursive } from '../../lib/pushDoc';
import { getProjectVersion } from '../../lib/versionSelect';

Expand Down Expand Up @@ -58,14 +57,14 @@ export default class DocsCommand extends Command {
// Ideally we should ignore this parameter entirely if the category is included.
const selectedVersion = await getProjectVersion(version, key, false);

debug(`selectedVersion: ${selectedVersion}`);
Command.debug(`selectedVersion: ${selectedVersion}`);

// Strip out non-markdown files
const files = readdirRecursive(folder).filter(
file => file.toLowerCase().endsWith('.md') || file.toLowerCase().endsWith('.markdown')
);

debug(`number of files: ${files.length}`);
Command.debug(`number of files: ${files.length}`);

if (!files.length) {
return Promise.reject(new Error(`We were unable to locate Markdown files in ${folder}.`));
Expand Down
3 changes: 1 addition & 2 deletions src/cmds/docs/single.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import chalk from 'chalk';
import config from 'config';

import Command, { CommandCategories } from '../../lib/baseCommand';
import { debug } from '../../lib/logger';
import pushDoc from '../../lib/pushDoc';
import { getProjectVersion } from '../../lib/versionSelect';

Expand Down Expand Up @@ -62,7 +61,7 @@ export default class SingleDocCommand extends Command {
// Ideally we should ignore this parameter entirely if the category is included.
const selectedVersion = await getProjectVersion(version, key, false);

debug(`selectedVersion: ${selectedVersion}`);
Command.debug(`selectedVersion: ${selectedVersion}`);

const createdDoc = await pushDoc(key, selectedVersion, dryRun, filePath, this.cmdCategory);

Expand Down
3 changes: 1 addition & 2 deletions src/cmds/open.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import open from 'open';

import Command, { CommandCategories } from '../lib/baseCommand';
import configStore from '../lib/configstore';
import { debug } from '../lib/logger';

export type Options = {
mockOpen?: (url: string) => Promise<void>;
Expand All @@ -29,7 +28,7 @@ export default class OpenCommand extends Command {
super.run(opts);

const project = configStore.get('project');
debug(`project: ${project}`);
Command.debug(`project: ${project}`);

if (!project) {
return Promise.reject(new Error(`Please login using \`${config.get('cli')} login\`.`));
Expand Down
26 changes: 15 additions & 11 deletions src/cmds/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import parse from 'parse-link-header';

import Command, { CommandCategories } from '../lib/baseCommand';
import fetch, { cleanHeaders, handleRes } from '../lib/fetch';
import { debug, info, warn, oraOptions } from '../lib/logger';
import { oraOptions } from '../lib/logger';
import prepareOas from '../lib/prepareOas';
import * as promptHandler from '../lib/prompts';
import streamSpecToRegistry from '../lib/streamSpecToRegistry';
Expand Down Expand Up @@ -81,32 +81,36 @@ export default class OpenAPICommand extends Command {
}

if (version && id) {
warn("We'll be using the version associated with the `--id` option, so the `--version` option will be ignored.");
Command.warn(
"We'll be using the version associated with the `--id` option, so the `--version` option will be ignored."
);
}

// Reason we're hardcoding in command here is because `swagger` command
// relies on this and we don't want to use `swagger` in this function
const { bundledSpec, specPath, specType, specVersion } = await prepareOas(spec, 'openapi');

if (useSpecVersion) {
info(`Using the version specified in your API definition for your ReadMe project version (${specVersion})`);
Command.info(
`Using the version specified in your API definition for your ReadMe project version (${specVersion})`
);
selectedVersion = specVersion;
}

if (!id) {
selectedVersion = await getProjectVersion(selectedVersion, key, true);
}

debug(`selectedVersion: ${selectedVersion}`);
Command.debug(`selectedVersion: ${selectedVersion}`);

async function success(data: Response) {
const message = !isUpdate
? `You've successfully uploaded a new ${specType} file to your ReadMe project!`
: `You've successfully updated an existing ${specType} file on your ReadMe project!`;

debug(`successful ${data.status} response`);
Command.debug(`successful ${data.status} response`);
const body = await data.json();
debug(`successful response payload: ${JSON.stringify(body)}`);
Command.debug(`successful response payload: ${JSON.stringify(body)}`);

return Promise.resolve(
[
Expand Down Expand Up @@ -211,23 +215,23 @@ export default class OpenAPICommand extends Command {
}

if (!id) {
debug('no id parameter, retrieving list of API specs');
Command.debug('no id parameter, retrieving list of API specs');
const apiSettings = await getSpecs('/api/v1/api-specification');

const totalPages = Math.ceil(parseInt(apiSettings.headers.get('x-total-count'), 10) / 10);
const parsedDocs = parse(apiSettings.headers.get('link'));
debug(`total pages: ${totalPages}`);
debug(`pagination result: ${JSON.stringify(parsedDocs)}`);
Command.debug(`total pages: ${totalPages}`);
Command.debug(`pagination result: ${JSON.stringify(parsedDocs)}`);

const apiSettingsBody = await apiSettings.json();
debug(`api settings list response payload: ${JSON.stringify(apiSettingsBody)}`);
Command.debug(`api settings list response payload: ${JSON.stringify(apiSettingsBody)}`);
if (!apiSettingsBody.length) return createSpec();

const { option }: { option: 'create' | 'update' } = await prompt(
promptHandler.createOasPrompt(apiSettingsBody, parsedDocs, totalPages, getSpecs)
);

debug(`selection result: ${option}`);
Command.debug(`selection result: ${option}`);
if (!option) return null;
return option === 'create' ? createSpec() : updateSpec(option);
}
Expand Down
4 changes: 2 additions & 2 deletions src/cmds/swagger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { CommandOptions } from '../lib/baseCommand';
import type { Options } from './openapi';

import { warn } from '../lib/logger';
import Command from '../lib/baseCommand';

import OpenAPICommand from './openapi';

Expand All @@ -16,7 +16,7 @@ export default class SwaggerCommand extends OpenAPICommand {
}

async run(opts: CommandOptions<Options>) {
warn('`rdme swagger` has been deprecated. Please use `rdme openapi` instead.');
Command.warn('`rdme swagger` has been deprecated. Please use `rdme openapi` instead.');
return super.run(opts);
}
}
3 changes: 1 addition & 2 deletions src/cmds/versions/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import config from 'config';

import Command, { CommandCategories } from '../../lib/baseCommand';
import fetch, { cleanHeaders, handleRes } from '../../lib/fetch';
import { debug } from '../../lib/logger';
import { getProjectVersion } from '../../lib/versionSelect';

export default class DeleteVersionCommand extends Command {
Expand Down Expand Up @@ -41,7 +40,7 @@ export default class DeleteVersionCommand extends Command {
return Promise.reject(e);
});

debug(`selectedVersion: ${selectedVersion}`);
Command.debug(`selectedVersion: ${selectedVersion}`);

return fetch(`${config.get('host')}/api/v1/version/${selectedVersion}`, {
method: 'delete',
Expand Down
3 changes: 1 addition & 2 deletions src/cmds/versions/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { Headers } from 'node-fetch';

import Command, { CommandCategories } from '../../lib/baseCommand';
import fetch, { cleanHeaders, handleRes } from '../../lib/fetch';
import { debug } from '../../lib/logger';
import * as promptHandler from '../../lib/prompts';
import { getProjectVersion } from '../../lib/versionSelect';

Expand Down Expand Up @@ -68,7 +67,7 @@ export default class UpdateVersionCommand extends Command {
return Promise.reject(e);
});

debug(`selectedVersion: ${selectedVersion}`);
Command.debug(`selectedVersion: ${selectedVersion}`);

const foundVersion = await fetch(`${config.get('host')}/api/v1/version/${selectedVersion}`, {
method: 'get',
Expand Down
Loading