Skip to content

Commit

Permalink
feat: Upgrade octokit/core and actions (#1404)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason3S authored Oct 17, 2023
1 parent 326c081 commit 6bff88c
Show file tree
Hide file tree
Showing 16 changed files with 15,356 additions and 16,025 deletions.
6 changes: 6 additions & 0 deletions .github/workflows/test-action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,17 @@ jobs:
- uses: actions/checkout@v4
- uses: ./
id: cspell-action
env:
TEST: true

test-action-with-file: # run the action
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ./
id: cspell-action
env:
TEST: true
with:
files: |
**/*.ts
Expand All @@ -33,6 +37,8 @@ jobs:
- uses: actions/checkout@v4
- uses: ./
id: cspell-action
env:
TEST: true
with:
incremental_files_only: false
files: |
Expand Down
31 changes: 21 additions & 10 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,46 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: streetsidesoftware/actions/public/setup-node-pnpm@v1

- run: pnpm i
- run: git --no-pager diff --compact-summary --exit-code

unit-test: # make sure unit-tests run
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: streetsidesoftware/actions/public/setup-node-pnpm@v1
- run: pnpm i
# Build should not be necessary to run tests
- run: GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} GITHUB_OUTPUT="" pnpm test
# unit-test: # make sure unit-tests run
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v4
# - uses: streetsidesoftware/actions/public/setup-node-pnpm@v1

# - run: pnpm i

# # Build should not be necessary to run tests
# - env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# run: GITHUB_OUTPUT="" TEST="true" pnpm test

clean-build: # make sure nothing changes with a clean build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: streetsidesoftware/actions/public/setup-node-pnpm@v1

- run: pnpm i

# Ensure the repository is clean after build
- run: pnpm clean-build

- run: git --no-pager diff --compact-summary --exit-code

coverage: # run coverage
coverage: # run coverage and unit tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: streetsidesoftware/actions/public/setup-node-pnpm@v1
- run: pnpm i
- run: GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} GITHUB_OUTPUT="" pnpm coverage

- env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: GITHUB_OUTPUT="" TEST="true" pnpm coverage

- name: Upload coverage Coveralls
uses: coverallsapp/github-action@3dfc5567390f6fa9267c0ee9c251e4c8c3f18949 # 2.2.3
Expand Down
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ node_modules/
package-lock.json
dist/
action/
pnpm-lock.yaml
6 changes: 3 additions & 3 deletions RUN-BOOK.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
## Publishing Action

1. Run Workflow [Create Release Version Tag](https://github.com/streetsidesoftware/cspell-action/actions/workflows/release.yml)

<img width="1258" alt="image" src="https://user-images.githubusercontent.com/3740137/170319864-99c557be-4de0-47c2-821e-5e5446313855.png">

1. Edit the Draft [Release](https://github.com/streetsidesoftware/cspell-action/releases)

<img width="936" alt="image" src="https://user-images.githubusercontent.com/3740137/170321272-2a7560a8-ed96-42f9-9107-ae10365e8fb9.png">

1. Review the Release notes and Publish

<img width="447" alt="image" src="https://user-images.githubusercontent.com/3740137/170321640-a06e4b0b-118b-4efb-8ff6-d85ac42f7bac.png">

Note: `latest` and major version (`v2`) tags will be automatically created by the [Keep the versions up-to-date](https://github.com/streetsidesoftware/cspell-action/actions/workflows/latest.yml) action.
Expand Down
10 changes: 5 additions & 5 deletions action-src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"build": "node ./build.mjs",
"clean-build": "pnpm clean && pnpm build",
"clean": "shx rm -rf ../action/lib dist",
"eslint": "eslint 'action-source/**/*.ts'",
"lint": "eslint . --fix",
"prettier": "prettier -w \"**/*.{md,yaml,yml,json,ts}\"",
"prepublishOnly": "pnpm build",
"smoke-test-push": "env-cmd -f ./fixtures/push.json node ./action/lib/main_root.js",
Expand All @@ -25,11 +25,11 @@
},
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^5.1.1",
"@actions/github": "^6.0.0",
"@cspell/cspell-bundled-dicts": "^7.3.8",
"@octokit/core": "^4.2.4",
"@octokit/plugin-rest-endpoint-methods": "^7.2.3",
"@octokit/rest": "^19.0.13",
"@octokit/core": "^5.0.1",
"@octokit/plugin-rest-endpoint-methods": "^10.0.1",
"@octokit/rest": "^20.0.2",
"cspell": "^7.3.8",
"cspell-glob": "^7.3.8",
"vscode-uri": "^3.0.8"
Expand Down
18 changes: 10 additions & 8 deletions action-src/src/action.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as core from '@actions/core';
import { debug, info, error, warning, setFailed, setOutput } from '@actions/core';
import { Context as GitHubContext } from '@actions/github/lib/context';
import { Octokit } from '@octokit/core';
import { RunResult } from 'cspell';
Expand All @@ -10,6 +10,8 @@ import { fetchFilesForCommits, getPullRequestFiles } from './github';
import { CSpellReporterForGithubAction } from './reporter';
import { lint, LintOptions } from './spell';

const core = { debug, error, info, warning };

interface Context {
githubContext: GitHubContext;
github: Octokit;
Expand Down Expand Up @@ -176,7 +178,7 @@ export async function action(githubContext: GitHubContext, octokit: Octokit): Pr
const err = `${result.issues} spelling issue${fnS(result.issues)} found in ${filesWithIssues} of the ${
result.files
} file${fnS(result.files)} checked.`;
core.setFailed(err);
setFailed(err);
}

return !(result.issues + result.errors);
Expand All @@ -185,12 +187,12 @@ export async function action(githubContext: GitHubContext, octokit: Octokit): Pr
function outputResult(runResult: RunResult) {
const result = normalizeResult(runResult);

core.setOutput('success', result.success);
core.setOutput('number_of_files_checked', result.number_of_files_checked);
core.setOutput('number_of_issues', result.number_of_issues);
core.setOutput('number_of_files_with_issues', result.files_with_issues.length);
core.setOutput('files_with_issues', normalizeFiles(result.files_with_issues));
core.setOutput('result', result);
setOutput('success', result.success);
setOutput('number_of_files_checked', result.number_of_files_checked);
setOutput('number_of_issues', result.number_of_issues);
setOutput('number_of_files_with_issues', result.files_with_issues.length);
setOutput('files_with_issues', normalizeFiles(result.files_with_issues));
setOutput('result', result);
}

function normalizeResult(result: RunResult) {
Expand Down
20 changes: 10 additions & 10 deletions action-src/src/getActionParams.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import * as core from '@actions/core';
import { getInput } from '@actions/core';
import { ActionParamsInput, applyDefaults, TrueFalse } from './ActionParams';

export function getActionParams(): ActionParamsInput {
return applyDefaults({
github_token: core.getInput('github_token', { required: true }),
files: core.getInput('files'),
incremental_files_only: tf(core.getInput('incremental_files_only')),
config: core.getInput('config'),
root: core.getInput('root'),
inline: core.getInput('inline').toLowerCase(),
strict: tf(core.getInput('strict')),
verbose: tf(core.getInput('verbose')),
check_dot_files: tf(core.getInput('check_dot_files')),
github_token: getInput('github_token', { required: true }),
files: getInput('files'),
incremental_files_only: tf(getInput('incremental_files_only')),
config: getInput('config'),
root: getInput('root'),
inline: getInput('inline').toLowerCase(),
strict: tf(getInput('strict')),
verbose: tf(getInput('verbose')),
check_dot_files: tf(getInput('check_dot_files')),
});
}

Expand Down
15 changes: 14 additions & 1 deletion action-src/src/github.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Octokit } from '@octokit/core';
import type { Octokit } from '@octokit/core';
import { restEndpointMethods } from '@octokit/plugin-rest-endpoint-methods';

type RestEndpointMethods = ReturnType<typeof restEndpointMethods>['rest'];

export interface GitContext {
owner: string;
repo: string;
Expand All @@ -13,12 +15,16 @@ export interface PullRequestRef extends GitContext {
export async function getPullRequestFiles(git: Octokit, prRef: PullRequestRef): Promise<Set<string>> {
const { owner, repo, pull_number } = prRef;
const { rest } = restEndpointMethods(git);

await reportUsage(rest, 'getPullRequestFiles RateLimit start:');
const commits = await rest.pulls.listCommits({ owner, repo, pull_number });

console.time('Fetch file names in commits');
const files = await fetchFilesForCommits(git, prRef, commits.data.map((c) => c.sha).filter(isString));
console.timeEnd('Fetch file names in commits');
// console.log('files %o', files);

await reportUsage(rest, 'getPullRequestFiles RateLimit end:');
return files;
}

Expand Down Expand Up @@ -56,3 +62,10 @@ async function* fetchFilesForCommitsX(
}
}
}

async function reportUsage(rest: RestEndpointMethods, message: string) {
if (!process.env['DEBUG'] && !process.env['TEST'] && !process.env['GITHUB_USAGE']) return;
const rate = (await rest.rateLimit.get()).data.rate;
const now = Math.floor(Date.now() / 1000);
console.info('%s: %o, time until reset: %is', message, rate, rate.reset - now);
}
44 changes: 33 additions & 11 deletions action-src/src/main.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as process from 'process';
import * as helper from './test/helper';
import { run } from './main';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';

const timeout = 20000;

Expand All @@ -14,6 +14,10 @@ describe('Validate Main', () => {
spyStdout.mockClear();
});

afterEach(() => {
vi.resetAllMocks();
});

test('GITHUB_TOKEN', () => {
expect(process.env['GITHUB_TOKEN']).not.toBeUndefined();
});
Expand All @@ -38,16 +42,34 @@ describe('Validate Main', () => {
);
});

// function cleanResult(output: string): string {
// // Remove time
// output = output.replace(/\(\d+\.\d\dms\)$/gm, '(???.??ms)');
describe('Validate Main No Token', () => {
beforeEach(() => {
vi.spyOn(console, 'error').mockImplementation(() => undefined);
});

// const rootRegExp = new RegExp(escapeRegEx(root), 'g');
// output = output.replace(rootRegExp, '.');
afterEach(() => {
vi.resetAllMocks();
});

// return output;
// }
test.each`
test | file
${'event pull_request main.js'} | ${'pull_request.json'}
${'event pull_request_with_files main.js'} | ${'pull_request_with_files.json'}
${'event push main.js'} | ${'push.json'}
`(
'$test',
async ({ test: testName, file }) => {
await helper.pollyRun(__filename, testName, async () => {
const env = helper.fetchGithubActionFixture(file);
env.FIXTURE_FILE_NAME = file;
Object.assign(process.env, env);

process.env['INPUT_GITHUB_TOKEN'] = undefined;
process.env['GITHUB_TOKEN'] = undefined;

// function escapeRegEx(s: string) {
// return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
// }
await expect(run()).resolves.toEqual(expect.any(Error));
});
},
timeout,
);
});
26 changes: 14 additions & 12 deletions action-src/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
// Must include .pnp before anything else
// require('../.pnp.js').setup();

import * as core from '@actions/core';
import { info, getInput, setFailed } from '@actions/core';
import { getOctokit } from '@actions/github';
import { Context } from '@actions/github/lib/context';
import assert from 'assert';
import { isAppError, isError } from './error';
import { action } from './action';
import { format } from 'util';

function getGithubToken(): string {
const t0 = core.getInput('github_token', { required: true });
function getGithubToken(): string | undefined {
const t0 = getInput('github_token', { required: true });
if (t0[0] !== '$') {
return t0;
return t0 !== 'undefined' ? t0 : undefined;
}
return process.env[t0.slice(1)] || 'undefined';
return process.env[t0.slice(1)] || undefined;
}

export async function run(): Promise<void> {
export async function run(): Promise<undefined | Error> {
try {
core.info('cspell-action');
info('cspell-action');
const githubContext = new Context();
const githubToken = getGithubToken();
assert(githubToken, 'GITHUB_TOKEN is required.');

await action(githubContext, getOctokit(githubToken));
core.info('Done.');
info('Done.');
return undefined;
} catch (error) {
console.error(error);
core.setFailed(isAppError(error) ? error.message : isError(error) ? error : format(error));
setFailed(isAppError(error) ? error.message : isError(error) ? error : format(error));
return isError(error) ? error : Error(format(error));
}
}
4 changes: 3 additions & 1 deletion action-src/src/reporter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as core from '@actions/core';
import { debug, info, warning, error } from '@actions/core';
import { issueCommand } from '@actions/core/lib/command';
import type {
CSpellReporter,
Expand All @@ -11,6 +11,8 @@ import type {
import { URI } from 'vscode-uri';
import * as path from 'path';

const core = { debug, info, warning, error };

export interface LintResult {
issues: Issue[];
result: RunResult;
Expand Down
8 changes: 4 additions & 4 deletions action-src/src/spell.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as cspellApp from 'cspell';
import { CSpellReporter } from 'cspell';
import { type CSpellApplicationOptions, lint as cspellAppLint } from 'cspell';
import type { CSpellReporter } from 'cspell';

export interface LintOptions {
root: string;
Expand All @@ -21,11 +21,11 @@ export interface LintOptions {
*/
export async function lint(files: string[], lintOptions: LintOptions, reporter: CSpellReporter): Promise<void> {
const { root, config, checkDotFiles } = lintOptions;
const options: cspellApp.CSpellApplicationOptions = { root, config };
const options: CSpellApplicationOptions = { root, config };
if (checkDotFiles) {
options.dot = true;
} else if (checkDotFiles === false) {
options.dot = false;
}
await cspellApp.lint(files, options, reporter);
await cspellAppLint(files, options, reporter);
}
Loading

0 comments on commit 6bff88c

Please sign in to comment.