Skip to content

Commit

Permalink
Fix linting issues
Browse files Browse the repository at this point in the history
  • Loading branch information
lo1tuma committed Sep 26, 2023
1 parent bfcde42 commit 7ad8910
Show file tree
Hide file tree
Showing 19 changed files with 222 additions and 141 deletions.
12 changes: 6 additions & 6 deletions source/bin/pr-log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { createCommand } from 'commander';
import { Octokit } from '@octokit/rest';
import prependFile from 'prepend-file';
import { execaCommand } from 'execa';
import { createCliRunner, RunOptions } from '../lib/cli.js';
import { createCliRunner, type RunOptions } from '../lib/cli.js';
import { ensureCleanLocalGitStateFactory } from '../lib/ensure-clean-local-git-state.js';
import { getMergedPullRequestsFactory } from '../lib/get-merged-pull-requests.js';
import { createChangelogFactory } from '../lib/create-changelog.js';
Expand All @@ -16,13 +16,12 @@ import { createGitCommandRunner } from '../lib/git-command-runner.js';

async function readJson(filePath: string): Promise<unknown> {
const fileContent = await fs.readFile(filePath, { encoding: 'utf8' });
return JSON.parse(fileContent);
return JSON.parse(fileContent) as unknown;
}

const prLogPackageJsonURL = new URL('../../../../package.json', import.meta.url);
const config = (await readJson(prLogPackageJsonURL.pathname)) as Record<string, string>;

// eslint-disable-next-line node/no-process-env
const { GH_TOKEN } = process.env;
const githubClient = new Octokit({ auth: GH_TOKEN });

Expand All @@ -36,7 +35,9 @@ const getMergedPullRequests = getMergedPullRequestsFactory({
gitCommandRunner,
getPullRequestLabel
});
const getCurrentDate = (): Date => new Date();
const getCurrentDate = (): Readonly<Date> => {
return new Date();
};

const program = createCommand(config.name ?? '');
program
Expand All @@ -49,7 +50,7 @@ program
.action(async (versionNumber: string, options: Record<string, unknown>) => {
const runOptions: RunOptions = { sloppy: options.sloppy === true, changelogPath };
isTracingEnabled = options.trace === true;
if (GH_TOKEN) {
if (GH_TOKEN !== undefined) {
await githubClient.auth();
}
const packageInfo = (await readJson(path.join(process.cwd(), 'package.json'))) as Record<string, unknown>;
Expand All @@ -73,7 +74,6 @@ function crash(error: Readonly<Error>): void {
message = error.stack;
}

// eslint-disable-next-line no-console
console.error(message);
process.exitCode = 1;
}
Expand Down
39 changes: 26 additions & 13 deletions source/lib/cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { stub } from 'sinon';
import test from 'ava';
import _prependFile from 'prepend-file';
import type { CliRunner, CliRunnerDependencies } from './cli.js';
import { createCliRunner } from './cli.js';
import type _prependFile from 'prepend-file';
import { createCliRunner, type CliRunner, type CliRunnerDependencies } from './cli.js';

function createCli(dependencies: Partial<CliRunnerDependencies> = {}): CliRunner {
const {
Expand Down Expand Up @@ -110,28 +109,42 @@ test('uses custom labels if they are provided in package.json', async (t) => {
t.deepEqual(createChangelog.firstCall.args, ['1.0.0', expectedLabels, undefined, 'foo/bar']);
});

test('reports the generated changelog', async (t) => {
const createChangelog = stub().returns('generated changelog');
const getMergedPullRequests = stub().resolves();
test('calls ensureCleanLocalGitState with correct parameters', async (t) => {
const ensureCleanLocalGitState = stub().resolves();
const prependFile = stub().resolves();

const cli = createCli({
createChangelog,
getMergedPullRequests,
ensureCleanLocalGitState,
prependFile: prependFile as unknown as typeof _prependFile
});
const cli = createCli({ ensureCleanLocalGitState });

const expectedGithubRepo = 'foo/bar';

await cli.run('1.0.0', options);

t.is(ensureCleanLocalGitState.callCount, 1);
t.deepEqual(ensureCleanLocalGitState.firstCall.args, [expectedGithubRepo]);
});

test('calls getMergedPullRequests with the correct repo', async (t) => {
const getMergedPullRequests = stub().resolves();

const cli = createCli({ getMergedPullRequests });

const expectedGithubRepo = 'foo/bar';

await cli.run('1.0.0', options);

t.is(getMergedPullRequests.callCount, 1);
t.is(getMergedPullRequests.firstCall.args[0], expectedGithubRepo);
});

test('reports the generated changelog', async (t) => {
const createChangelog = stub().returns('generated changelog');
const prependFile = stub().resolves();

const cli = createCli({
createChangelog,
prependFile: prependFile as unknown as typeof _prependFile
});

await cli.run('1.0.0', options);

t.is(createChangelog.callCount, 1);
t.is(createChangelog.firstCall.args[0], '1.0.0');
Expand Down
26 changes: 13 additions & 13 deletions source/lib/cli.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import semver from 'semver';
import _prependFile from 'prepend-file';
import { CreateChangelog } from './create-changelog.js';
import type _prependFile from 'prepend-file';
import type { CreateChangelog } from './create-changelog.js';
import { getGithubRepo } from './get-github-repo.js';
import { defaultValidLabels } from './valid-labels.js';
import { GetMergedPullRequests } from './get-merged-pull-requests.js';
import { EnsureCleanLocalGitState } from './ensure-clean-local-git-state.js';
import type { GetMergedPullRequests } from './get-merged-pull-requests.js';
import type { EnsureCleanLocalGitState } from './ensure-clean-local-git-state.js';

function stripTrailingEmptyLine(text: string): string {
if (text.endsWith('\n\n')) {
Expand All @@ -27,31 +27,31 @@ function getValidLabels(packageInfo: Record<string, unknown>): ReadonlyMap<strin
return defaultValidLabels;
}

function validateVersionNumber(versionNumber?: string): void {
if (!versionNumber) {
throw new Error('version-number not specified');
function validateVersionNumber(versionNumber: string): void {
if (versionNumber.length === 0) {
throw new TypeError('version-number not specified');
}
if (semver.valid(versionNumber) === null) {
throw new Error('version-number is invalid');
}
}

export interface RunOptions {
export type RunOptions = {
readonly changelogPath: string;
readonly sloppy: boolean;
}
};

export interface CliRunnerDependencies {
export type CliRunnerDependencies = {
readonly ensureCleanLocalGitState: EnsureCleanLocalGitState;
readonly getMergedPullRequests: GetMergedPullRequests;
readonly createChangelog: CreateChangelog;
readonly packageInfo: Record<string, unknown>;
readonly prependFile: typeof _prependFile;
}
};

export interface CliRunner {
export type CliRunner = {
run(newVersionNumber: string, options: RunOptions): Promise<void>;
}
};

export function createCliRunner(dependencies: CliRunnerDependencies): CliRunner {
const { ensureCleanLocalGitState, getMergedPullRequests, createChangelog, packageInfo, prependFile } = dependencies;
Expand Down
35 changes: 30 additions & 5 deletions source/lib/create-changelog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ import { createChangelogFactory } from './create-changelog.js';
import { defaultValidLabels } from './valid-labels.js';

test('contains a title with the version number and the formatted date', (t) => {
const createChangelog = createChangelogFactory({ getCurrentDate: () => new Date(0), packageInfo: {} });
const createChangelog = createChangelogFactory({
getCurrentDate: () => {
return new Date(0);
},
packageInfo: {}
});
const changelog = createChangelog('1.0.0', defaultValidLabels, [], '');
const expectedTitle = '## 1.0.0 (January 1, 1970)';

Expand All @@ -12,15 +17,25 @@ test('contains a title with the version number and the formatted date', (t) => {

test('format the date with a custom date format', (t) => {
const packageInfo = { 'pr-log': { dateFormat: 'dd.MM.yyyy' } };
const createChangelog = createChangelogFactory({ getCurrentDate: () => new Date(0), packageInfo });
const createChangelog = createChangelogFactory({
getCurrentDate: () => {
return new Date(0);
},
packageInfo
});
const changelog = createChangelog('1.0.0', defaultValidLabels, [], '');
const expectedTitle = '## 1.0.0 (01.01.1970)';

t.true(changelog.includes(expectedTitle));
});

test('creates a formatted changelog', (t) => {
const createChangelog = createChangelogFactory({ getCurrentDate: () => new Date(0), packageInfo: {} });
const createChangelog = createChangelogFactory({
getCurrentDate: () => {
return new Date(0);
},
packageInfo: {}
});
const mergedPullRequests = [
{
id: 1,
Expand Down Expand Up @@ -57,7 +72,12 @@ test('creates a formatted changelog', (t) => {
});

test('uses custom labels when provided', (t) => {
const createChangelog = createChangelogFactory({ getCurrentDate: () => new Date(0), packageInfo: {} });
const createChangelog = createChangelogFactory({
getCurrentDate: () => {
return new Date(0);
},
packageInfo: {}
});
const customValidLabels = new Map([
['core', 'Core Features'],
['addons', 'Addons']
Expand Down Expand Up @@ -98,7 +118,12 @@ test('uses custom labels when provided', (t) => {
});

test('uses the same order for the changelog sections as in validLabels', (t) => {
const createChangelog = createChangelogFactory({ getCurrentDate: () => new Date(0), packageInfo: {} });
const createChangelog = createChangelogFactory({
getCurrentDate: () => {
return new Date(0);
},
packageInfo: {}
});
const customValidLabels = new Map([
['first', 'First Section'],
['second', 'Second Section']
Expand Down
16 changes: 10 additions & 6 deletions source/lib/create-changelog.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { format as formatDate } from 'date-fns';
import enLocale from 'date-fns/locale/en-US/index.js';
import { PullRequest, PullRequestWithLabel } from './get-merged-pull-requests.js';
import type { PullRequest, PullRequestWithLabel } from './get-merged-pull-requests.js';

function formatLinkToPullRequest(pullRequestId: number, repo: string): string {
return `[#${pullRequestId}](https://github.com/${repo}/pull/${pullRequestId})`;
Expand All @@ -11,7 +11,11 @@ function formatPullRequest(pullRequest: PullRequest, repo: string): string {
}

function formatListOfPullRequests(pullRequests: readonly PullRequest[], repo: string): string {
return pullRequests.map((pr) => formatPullRequest(pr, repo)).join('');
return pullRequests
.map((pr) => {
return formatPullRequest(pr, repo);
})
.join('');
}

function formatSection(displayLabel: string, pullRequests: readonly PullRequest[], repo: string): string {
Expand Down Expand Up @@ -63,10 +67,10 @@ function groupByLabel(pullRequests: readonly PullRequestWithLabel[]): Record<str
}, {});
}

interface Dependencies {
type Dependencies = {
readonly packageInfo: PackageInfo;
getCurrentDate(): Date;
}
getCurrentDate(): Readonly<Date>;
};

const defaultDateFormat = 'MMMM d, yyyy';

Expand All @@ -84,7 +88,7 @@ export function createChangelogFactory(dependencies: Dependencies): CreateChange
for (const [label, displayLabel] of validLabels) {
const pullRequests = groupedPullRequests[label];

if (pullRequests) {
if (pullRequests !== undefined) {
changelog += formatSection(displayLabel, pullRequests, repo);
}
}
Expand Down
23 changes: 13 additions & 10 deletions source/lib/ensure-clean-local-git-state.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import test from 'ava';
import { fake, SinonSpy } from 'sinon';
import type { EnsureCleanLocalGitState, EnsureCleanLocalGitStateDependencies } from './ensure-clean-local-git-state.js';
import { ensureCleanLocalGitStateFactory } from './ensure-clean-local-git-state.js';
import { fake, type SinonSpy } from 'sinon';
import {
ensureCleanLocalGitStateFactory,
type EnsureCleanLocalGitState,
type EnsureCleanLocalGitStateDependencies
} from './ensure-clean-local-git-state.js';

const githubRepo = 'foo/bar';

interface Overrides {
getShortStatus?: SinonSpy;
getCurrentBranchName?: SinonSpy;
getSymmetricDifferencesBetweenBranches?: SinonSpy;
fetchRemote?: SinonSpy;
findRemoteAlias?: SinonSpy;
}
type Overrides = {
readonly getShortStatus?: SinonSpy;
readonly getCurrentBranchName?: SinonSpy;
readonly getSymmetricDifferencesBetweenBranches?: SinonSpy;
readonly fetchRemote?: SinonSpy;
readonly findRemoteAlias?: SinonSpy;
};

function factory(overrides: Overrides = {}): EnsureCleanLocalGitState {
const {
Expand Down
10 changes: 6 additions & 4 deletions source/lib/ensure-clean-local-git-state.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { oneLine } from 'common-tags';
import type { FindRemoteAlias } from './find-remote-alias.js';
import { GitCommandRunner } from './git-command-runner.js';
import type { GitCommandRunner } from './git-command-runner.js';

export interface EnsureCleanLocalGitStateDependencies {
export type EnsureCleanLocalGitStateDependencies = {
readonly gitCommandRunner: GitCommandRunner;
readonly findRemoteAlias: FindRemoteAlias;
}
};

export type EnsureCleanLocalGitState = (githubRepo: string) => Promise<void>;

Expand Down Expand Up @@ -43,7 +44,8 @@ export function ensureCleanLocalGitStateFactory(
});

if (commitsAhead > 0 || commitsBehind > 0) {
const errorMessage = `Local git master branch is ${commitsAhead} commits ahead and ${commitsBehind} commits behind of ${remoteBranch}`;
const errorMessage = oneLine`Local git master branch is ${commitsAhead} commits ahead
and ${commitsBehind} commits behind of ${remoteBranch}`;

throw new Error(errorMessage);
}
Expand Down
4 changes: 2 additions & 2 deletions source/lib/find-remote-alias.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import test from 'ava';
import { fake } from 'sinon';
import { findRemoteAliasFactory, FindRemoteAliasDependencies, FindRemoteAlias } from './find-remote-alias.js';
import { RemoteAlias } from './git-command-runner.js';
import { findRemoteAliasFactory, type FindRemoteAliasDependencies, type FindRemoteAlias } from './find-remote-alias.js';
import type { RemoteAlias } from './git-command-runner.js';

const githubRepo = 'foo/bar';

Expand Down
12 changes: 6 additions & 6 deletions source/lib/find-remote-alias.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import parseGitUrl from 'git-url-parse';
import { GitCommandRunner } from './git-command-runner.js';
import type { GitCommandRunner } from './git-command-runner.js';

function isSameGitUrl(gitUrlA: string, gitUrlB: string): boolean {
const parsedUrlA = parseGitUrl(gitUrlA);
Expand All @@ -14,9 +14,9 @@ function getGitUrl(githubRepo: string): string {
return `git://github.com/${githubRepo}.git`;
}

export interface FindRemoteAliasDependencies {
export type FindRemoteAliasDependencies = {
readonly gitCommandRunner: GitCommandRunner;
}
};

export type FindRemoteAlias = (githubRepo: string) => Promise<string>;

Expand All @@ -28,11 +28,11 @@ export function findRemoteAliasFactory(dependencies: FindRemoteAliasDependencies

const remotes = await gitCommandRunner.getRemoteAliases();
const matchedRemote = remotes.find((remote) => {
return remote.url && isSameGitUrl(gitRemote, remote.url);
return isSameGitUrl(gitRemote, remote.url);
});

if (!matchedRemote) {
throw new Error(`This local git repository doesn’t have a remote pointing to ${gitRemote}`);
if (matchedRemote === undefined) {
throw new TypeError(`This local git repository doesn’t have a remote pointing to ${gitRemote}`);
}

return matchedRemote.alias;
Expand Down
7 changes: 6 additions & 1 deletion source/lib/get-github-repo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,10 @@ test('extracts the repo path of a github URL', (t) => {
});

test('throws if the given URL is not a github URL', (t) => {
t.throws(() => getGithubRepo('git://foo.com/bar.git'), { message: 'Invalid GitHub URI git://foo.com/bar.git' });
t.throws(
() => {
return getGithubRepo('git://foo.com/bar.git');
},
{ message: 'Invalid GitHub URI git://foo.com/bar.git' }
);
});
Loading

0 comments on commit 7ad8910

Please sign in to comment.