Skip to content

Commit

Permalink
refactor: move away from @param syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
kanadgupta committed Jan 31, 2025
1 parent 0f28713 commit c5fbf86
Show file tree
Hide file tree
Showing 11 changed files with 95 additions and 52 deletions.
6 changes: 4 additions & 2 deletions __tests__/helpers/get-gha-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ import getGitRemoteMock from './get-git-mock.js';
/**
* A helper function for setting up tests for our GitHub Action onboarding.
*
* @param writeFileSyncCb the mock function that should be called in place of `fs.writeFileSync`.
* @see {@link __tests__/lib/createGHA.test.ts}
*/
export function before(writeFileSyncCb) {
export function before(
/** the mock function that should be called in place of `fs.writeFileSync` */
writeFileSyncCb: typeof fs.writeFileSync,
) {
fs.writeFileSync = vi.fn(writeFileSyncCb);

git.checkIsRepo = vi.fn(() => {
Expand Down
7 changes: 3 additions & 4 deletions __tests__/helpers/get-git-mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@ import { vi } from 'vitest';

/**
* Creates a mock function for testing `git.remote`.
*
* @param remote remote to return (usually `origin`)
* @param remoteUrl git URL for the given remote
* @param defaultBranch the HEAD branch
*/
export default function getGitRemoteMock(
/** remote to return (usually `origin`) */
remote = 'origin',
/** git URL for the given remote */
remoteUrl = 'https://github.com/readmeio/rdme.git',
/** the HEAD branch */
defaultBranch = 'main',
) {
return vi.fn(arr => {
Expand Down
12 changes: 8 additions & 4 deletions src/lib/createGHA/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ type ParsedOpts = Record<string, unknown>;

/**
* Generates the key for storing info in `configstore` object.
* @param repoRoot The root of the repo
*/
export const getConfigStoreKey = (repoRoot: string) => `createGHA.${repoRoot}`;
export const getConfigStoreKey = (
/** the root of the repository */
repoRoot: string,
) => `createGHA.${repoRoot}`;
/**
* The directory where GitHub Actions workflow files are stored.
*
Expand All @@ -40,9 +42,11 @@ export const git = simpleGit();
/**
* Removes any non-file-friendly characters and adds
* the full path + file extension for GitHub Workflow files.
* @param fileName raw file name to clean up
*/
export const getGHAFileName = (fileName: string) => {
export const getGHAFileName = (
/** raw file name to clean up */
fileName: string,
) => {
return path.join(GITHUB_WORKFLOW_DIR, `${cleanFileName(fileName).toLowerCase()}.yml`);
};

Expand Down
11 changes: 8 additions & 3 deletions src/lib/getPkg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,19 @@ export function getPkgVersion(this: Hook.Context | void): string {
/**
* The current `rdme` version
*
* @param npmDistTag the `npm` dist tag to retrieve. If this value is omitted,
* the version from the `package.json` is returned.
* @example "8.0.0"
* @see {@link https://docs.npmjs.com/adding-dist-tags-to-packages}
* @note we mock this function in our snapshots
* @see {@link https://stackoverflow.com/a/54245672}
*/
export async function getPkgVersionFromNPM(this: Hook.Context | void, npmDistTag?: npmDistTag): Promise<string> {
export async function getPkgVersionFromNPM(
this: Hook.Context | void,
/**
* The `npm` dist tag to retrieve. If this value is omitted,
* the version from the `package.json` is returned.
*/
npmDistTag?: npmDistTag,
): Promise<string> {
if (npmDistTag) {
return fetch(registryUrl)
.then(res => res.json() as Promise<{ 'dist-tags': Record<string, string> }>)
Expand Down
11 changes: 8 additions & 3 deletions src/lib/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,15 @@ function oraOptions() {

/**
* Wrapper for warn statements.
* @param prefix Text that precedes the warning.
* This is *not* used in the GitHub Actions-formatted warning.
*/
function warn(input: string, prefix = 'Warning!') {
function warn(
/**
* Text that precedes the warning.
* This is *not* used in the GitHub Actions-formatted warning.
*/
input: string,
prefix = 'Warning!',
) {
/* istanbul ignore next */
if (isGHA() && !isTest()) return core.warning(input);
// eslint-disable-next-line no-console
Expand Down
11 changes: 8 additions & 3 deletions src/lib/loginFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,16 @@ function loginFetch(body: LoginBody) {
* The prompt flow for logging a user in and writing the credentials to
* `configstore`. This is a separate lib function because we reuse it both
* in the `login` command as well as any time a user omits an API key.
* @param otp an optional one-time passcode, if the user passes one in
* via a flag to the the `login` command
*
* @returns A Promise-wrapped string with the logged-in user's credentials
*/
export default async function loginFlow(otp?: string) {
export default async function loginFlow(
/**
* An optional one-time passcode, if the user passes one in
* via a flag to the the `login` command
*/
otp?: string,
) {
const storedConfig = getCurrentConfig();
const { email, password, project } = await promptTerminal([
{
Expand Down
13 changes: 8 additions & 5 deletions src/lib/prepareOas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,17 @@ const capitalizeSpecType = (type: string) =>

/**
* Normalizes, validates, and (optionally) bundles an OpenAPI definition.
*
* @param path Path to a spec file. If this is missing, the current directory is searched for
* certain file names.
* @param command The command context in which this is being run within (uploading a spec,
* validation, or reducing one).
*/
export default async function prepareOas(
/**
* Path to a spec file. If this is missing, the current directory is searched for
* certain file names.
*/
path: string | undefined,
/**
* The command context in which this is being run within (uploading a spec,
* validation, or reducing one).
*/
command: `openapi ${OpenAPIAction}`,
opts: {
/**
Expand Down
12 changes: 8 additions & 4 deletions src/lib/readDoc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,15 @@ export interface PageMetadata<T = Record<string, unknown>> {

/**
* Returns the content, matter and slug of the specified Markdown or HTML file
*
* @param {String} filePath path to the HTML/Markdown file
* (file extension must end in `.html`, `.md`., or `.markdown`)
*/
export default function readPage(this: ChangelogsCommand, filePath: string): PageMetadata {
export default function readPage(
this: ChangelogsCommand,
/**
* path to the HTML/Markdown file
* (file extension must end in `.html`, `.md`., or `.markdown`)
*/
filePath: string,
): PageMetadata {
this.debug(`reading file ${filePath}`);
const rawFileContents = fs.readFileSync(filePath, 'utf8');
// by default, grayMatter maintains a buggy cache with the page data,
Expand Down
14 changes: 10 additions & 4 deletions src/lib/readdirRecursive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,18 @@ import { debug } from './logger.js';
/**
* Recursively grabs all files within a given directory
* (including subdirectories)
* @param folderToSearch path to directory
* @param ignoreGit boolean to indicate whether or not to ignore
* `.git` directory plus any files specified in `.gitignore`
*
* @returns array of file names
*/
export default function readdirRecursive(folderToSearch: string, ignoreGit = false): string[] {
export default function readdirRecursive(
/** path to directory */
folderToSearch: string,
/**
* Boolean to indicate whether or not to ignore `.git` directory
* as well as any files specified in `.gitignore`
*/
ignoreGit = false,
): string[] {
debug(`current readdirRecursive folder: ${folderToSearch}`);

let ignoreFilter: Ignore;
Expand Down
35 changes: 20 additions & 15 deletions src/lib/readmeAPIFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,15 @@ function stripQuotes(s: string) {

/**
* Parses Warning header into an array of warning header objects
* @param header raw `Warning` header
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Warning}
* @see {@link https://www.rfc-editor.org/rfc/rfc7234#section-5.5}
* @see {@link https://github.com/marcbachmann/warning-header-parser}
*/
function parseWarningHeader(header: string): WarningHeader[] {
function parseWarningHeader(
/** The raw `Warning` header string */
header: string,
): WarningHeader[] {
try {
const warnings = header.split(/([0-9]{3} [a-z0-9.@\-/]*) /g);

Expand Down Expand Up @@ -124,15 +127,14 @@ function sanitizeHeaders(headers: Headers) {
/**
* Wrapper for the `fetch` API so we can add rdme-specific headers to all ReadMe API v1 requests.
*
* @param pathname the pathname to make the request to. Must have a leading slash.
* @param fileOpts optional object containing information about the file being sent.
* We use this to construct a full source URL for the file.
*
* @deprecated This is for APIv1 only. Use {@link readmeAPIv2Fetch} instead, if possible.
*/
export async function readmeAPIv1Fetch(
/** The pathname to make the request to. Must have a leading slash. */
pathname: string,
options: RequestInit = { headers: new Headers() },
/** optional object containing information about the file being sent.
* We use this to construct a full source URL for the file. */
fileOpts: FilePathDetails = { filePath: '', fileType: false },
) {
let source = 'cli';
Expand Down Expand Up @@ -213,15 +215,14 @@ export async function readmeAPIv1Fetch(

/**
* Wrapper for the `fetch` API so we can add rdme-specific headers to all ReadMe API v2 requests.
*
* @param pathname the pathname to make the request to. Must have a leading slash.
* @param fileOpts optional object containing information about the file being sent.
* We use this to construct a full source URL for the file.
*/
export async function readmeAPIv2Fetch(
this: CommandClass['prototype'],
/** The pathname to make the request to. Must have a leading slash. */
pathname: string,
options: RequestInit = { headers: new Headers() },
/** optional object containing information about the file being sent.
* We use this to construct a full source URL for the file. */
fileOpts: FilePathDetails = { filePath: '', fileType: false },
) {
let source = 'cli';
Expand Down Expand Up @@ -314,13 +315,17 @@ export async function readmeAPIv2Fetch(
*
* If we receive non-JSON responses, we consider them errors and throw them.
*
* @param rejectOnJsonError if omitted (or set to true), the function will return
* an `APIv1Error` if the JSON body contains an `error` property. If set to false,
* the function will return a resolved promise containing the JSON object.
*
* @deprecated This is for APIv1 only. Use {@link handleAPIv2Res} instead, if possible.
*/
export async function handleAPIv1Res(res: Response, rejectOnJsonError = true) {
export async function handleAPIv1Res(
res: Response,
/**
* If omitted (or set to true), the function will return an `APIv1Error`
* if the JSON body contains an `error` property. If set to false,
* the function will return a resolved promise containing the JSON object.
*/
rejectOnJsonError = true,
) {
const contentType = res.headers.get('content-type') || '';
const extension = mime.extension(contentType);
if (extension === 'json') {
Expand Down
15 changes: 10 additions & 5 deletions src/lib/validatePromptInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@ export const cleanFileName = (input: string) => input.replace(/[^a-z0-9]/gi, '-'
* A validator function used in our prompts for when a user
* is prompted to specify a file path.
*
* @param value the file name
* @param getFullPath An optional function for adding a file path or any filename validations
* @returns true if path is valid (i.e. is non-empty and doesn't already exist),
* otherwise a string containing the error message
*/
export function validateFilePath(value: string, getFullPath: (file: string) => string = file => file) {
export function validateFilePath(
/** the file name */
value: string,
/** An optional function for adding a file path or any filename validations */
getFullPath: (file: string) => string = file => file,
) {
if (value.length) {
const fullPath = getFullPath(value);
if (!fs.existsSync(fullPath)) {
Expand All @@ -32,10 +35,12 @@ export function validateFilePath(value: string, getFullPath: (file: string) => s
/**
* Validates that a project subdomain value is valid.
*
* @param value the terminal input
* @returns true if the subdomain value is valid, else an error message
*/
export function validateSubdomain(value: string) {
export function validateSubdomain(
/** the raw project subdomain value */
value: string,
) {
return (
/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/.test(value) || 'Project subdomain must contain only letters, numbers and dashes.'
);
Expand Down

0 comments on commit c5fbf86

Please sign in to comment.