Skip to content

Commit

Permalink
fix: feature: make it possible to check all files (#216)
Browse files Browse the repository at this point in the history
* fix: make it possible to check all files
* fix: When filtering files to include, use include mode.
  • Loading branch information
Jason3S committed Jun 7, 2021
1 parent d6de91d commit a43683f
Show file tree
Hide file tree
Showing 27 changed files with 307 additions and 61 deletions.
2 changes: 2 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']

# cspell:ignore issuehunt
21 changes: 21 additions & 0 deletions .github/workflows/test-action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,24 @@ jobs:
steps:
- uses: actions/checkout@v2
- uses: ./

test-action-with-file: # run the action
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: ./
with:
files: |
**/*.ts
**/*.md
test-action-no-increment: # run the action
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: ./
with:
incremental_files_only: false
files: |
**
.*/**
3 changes: 0 additions & 3 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
"**/.yarn": true,
"**/.pnp.*": true
},
"eslint.nodePath": "action-src/.yarn/sdks",
"prettier.prettierPath": "action-src/.yarn/sdks/prettier/index.js",
"typescript.tsdk": "action-src/.yarn/sdks/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"git.ignoreLimitWarning": true
}
24 changes: 24 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Contributing

Contributions are welcome.

Layout

```
root
├── action.yaml
└── action-src
├── package.json
├── node_modules
└── src
└── *.ts
└── action
├── package.json
├── node_modules
└── lib
└── *.js
```

**action** is the compiled code used to run the action. The entire folder is in the source tree.
**action-src** is the source code for the action.
46 changes: 26 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,38 +58,44 @@ jobs:
# Allowed values are: true, false
# Default: true
strict: true
```

# Limit the files checked to the ones in the pull request or push.
incremental_files_only: true

# Path to `cspell.json`
config: '.'
```
## Yarn 2 - PlugNPlay
To use dictionaries stored within a Yarn 2 workspace, there are two choices:
1. Add `"usePnP": true` to the workspace `cspell.json` file. This tells `cspell` to search for the
nearest `.pnp.js` or `.pnp.cjs` file and load it.
nearest `.pnp.js` or `.pnp.cjs` file and load it.

Example for medical terms:
```js
{
"usePnP": true,
"import": ["@cspell/dict-medicalterms/cspell-ext.json"]
}
```
Example for medical terms:

```js
{
"usePnP": true,
"import": ["@cspell/dict-medicalterms/cspell-ext.json"]
}
```

2. Require the `.pnp.js` or `.pnp.cjs` in a `cspell.config.js` file.
This must be done before importing any packages.

```js
'use strict';
require('./.pnp.js').setup(); // or './.pnp.cjs'
/** @type { import("@cspell/cspell-types").CSpellUserSettings } */
const cspell = {
description: 'Yarn 2 Aware cspell config',
import: ["@cspell/dict-medicalterms/cspell-ext.json"]
};
module.exports = cspell;
```
```js
'use strict';
require('./.pnp.js').setup(); // or './.pnp.cjs'
/** @type { import("@cspell/cspell-types").CSpellUserSettings } */
const cspell = {
description: 'Yarn 2 Aware cspell config',
import: ['@cspell/dict-medicalterms/cspell-ext.json'],
};
module.exports = cspell;
```

<!---
cspell:ignore medicalterms
Expand Down
7 changes: 7 additions & 0 deletions action-src/cspell.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"ignorePaths": [
"node_modules",
"__recordings__",
"__snapshots__"
]
}
3 changes: 3 additions & 0 deletions action-src/fixtures/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Fixtures

Here is a bit of text.
7 changes: 6 additions & 1 deletion action-src/fixtures/cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@
"streetsidesoftware"
],
"ignorePaths": [
"node_modules",
"action/",
"cspell.json",
"fixtures/**/*.json"
"__recordings__",
"**/*.json"
],
"overrides": [
{
Expand All @@ -32,5 +34,8 @@
],
"enableFiletypes": [
"shellscript"
],
"import": [
"../cspell.json"
]
}
4 changes: 0 additions & 4 deletions action-src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,8 @@
"@types/pollyjs__adapter-node-http": "^2.0.1",
"@types/pollyjs__core": "^4.3.1",
"@types/pollyjs__persister-fs": "^2.0.1",
"@typescript-eslint/eslint-plugin": "^4.20.0",
"@typescript-eslint/parser": "^4.20.0",
"env-cmd": "^10.1.0",
"eslint": "^7.16.0",
"jest": "^27.0.4",
"prettier": "^2.2.1",
"rimraf": "^3.0.2",
"standard-version": "^9.1.1",
"ts-jest": "^27.0.3",
Expand Down
29 changes: 25 additions & 4 deletions action-src/src/action.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('Validate Action', () => {
`(
'$test',
async ({ file, expected }) => {
const context = createContext(file);
const context = createContextFromFile(file);
const octokit = createOctokit();
expect.assertions(1);
await expect(action(context, octokit)).rejects.toEqual(expected);
Expand All @@ -45,14 +45,31 @@ describe('Validate Action', () => {
'$testName',
async ({ testName, file, expected }) => {
return helper.pollyRun(__filename, testName, async () => {
const context = createContext(file);
const context = createContextFromFile(file);
const octokit = createOctokit();
expect.assertions(1);
await expect(action(context, octokit)).resolves.toBe(expected);
});
},
timeout
);
test.each`
files | expected
${'**'} | ${false}
${'**/*.md'} | ${true}
`(
'check all $files',
async ({ files, expected }) => {
const context = createContextFromFile('pull_request.json', {
INPUT_FILES: files,
INPUT_INCREMENTAL_FILES_ONLY: 'false',
});
const octokit = createOctokit();
expect.assertions(1);
await expect(action(context, octokit)).resolves.toBe(expected);
},
timeout
);
});

function cleanEnv() {
Expand Down Expand Up @@ -89,8 +106,12 @@ function getGithubToken(): string {
return process.env[t0.slice(1)] || 'undefined';
}

function createContext(filename: string): Context {
Object.assign(process.env, fetchGithubActionFixture(filename));
function createContextFromFile(filename: string, ...params: Record<string, string>[]): Context {
return createContext(fetchGithubActionFixture(filename), ...params);
}

function createContext(...params: Record<string, string>[]): Context {
Object.assign(process.env, ...params);
setEnvIfNotExist('INPUT_ROOT', root);
setEnvIfNotExist('INPUT_CONFIG', configFile);
process.env.INPUT_CONFIG = path.resolve(root, process.env.INPUT_CONFIG || configFile);
Expand Down
53 changes: 45 additions & 8 deletions action-src/src/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { fetchFilesForCommits, getPullRequestFiles } from './github';
import { Octokit } from '@octokit/core';
import { lint, LintOptions } from './spell';
import * as path from 'path';
import { format } from 'util';
import { AppError } from './error';
import * as glob from 'cspell-glob';
import { existsSync } from 'fs';
Expand All @@ -14,6 +15,7 @@ interface Context {
githubContext: GitHubContext;
github: Octokit;
files: string;
useEventFiles: boolean;
}

type EventNames = 'push' | 'pull_request';
Expand All @@ -30,6 +32,7 @@ type TrueFalse = 'true' | 'false';
interface ActionParams {
github_token: string;
files: string;
incremental_files_only: string;
config: string;
root: string;
inline: string;
Expand All @@ -39,6 +42,7 @@ interface ActionParams {
interface ValidActionParams {
github_token: string;
files: string;
incremental_files_only: TrueFalse;
config: string;
root: string;
inline: InlineWorkflowCommand;
Expand Down Expand Up @@ -106,14 +110,29 @@ function friendlyEventName(eventName: EventNames | string): string {
case 'pull_request':
return 'Pull Request';
default:
return `Unknown event: '${eventName}'`;
return `'${eventName}'`;
}
}

function isSupportedEvent(eventName: EventNames | string): eventName is EventNames {
return supportedEvents.has(eventName);
}

async function gatherFilesFromContext(context: Context): Promise<Set<string>> {
if (context.useEventFiles) {
const eventFiles = await gatherFiles(context);
return filterFiles(context.files, eventFiles);
}

const files = new Set<string>(
context.files
.split('\n')
.map((a) => a.trim())
.filter((a) => !!a)
);
return files;
}

/**
* Gather the set of files to be spell checked.
* @param context Context
Expand All @@ -135,7 +154,7 @@ function filterFiles(globPattern: string, files: Set<string>): Set<string> {

const matchingFiles = new Set<string>();

const g = new glob.GlobMatcher(globPattern);
const g = new glob.GlobMatcher(globPattern, { mode: 'include' });
for (const p of files) {
if (g.match(p)) {
matchingFiles.add(p);
Expand All @@ -149,6 +168,7 @@ function getActionParams(): ActionParams {
return {
github_token: core.getInput('github_token', { required: true }),
files: core.getInput('files'),
incremental_files_only: tf(core.getInput('incremental_files_only')) || 'true',
config: core.getInput('config'),
root: core.getInput('root'),
inline: (core.getInput('inline') || 'warning').toLowerCase(),
Expand All @@ -172,7 +192,14 @@ function tf(v: string | boolean | number): TrueFalse | string {
}

function validateActionParams(params: ActionParams | ValidActionParams): params is ValidActionParams {
const validations = [validateToken, validateConfig, validateRoot, validateInlineLevel, validateStrict];
const validations = [
validateToken,
validateConfig,
validateRoot,
validateInlineLevel,
validateStrict,
validateIncrementalFilesOnly,
];
const success = validations.map((fn) => fn(params)).reduce((a, b) => a && b, true);
if (!success) {
throw new AppError('Bad Configuration.');
Expand All @@ -185,6 +212,15 @@ function validateToken(params: ActionParams) {
return !!token;
}

function validateIncrementalFilesOnly(params: ActionParams) {
const isIncrementalOnly = params.incremental_files_only;
const success = isIncrementalOnly === 'true' || isIncrementalOnly === 'false';
if (!success) {
core.error('Invalid incremental_files_only setting, must be one of (true, false)');
}
return success;
}

function validateConfig(params: ActionParams) {
const config = params.config;
const success = !config || existsSync(config);
Expand Down Expand Up @@ -216,7 +252,7 @@ function validateStrict(params: ActionParams) {
const isStrict = params.strict;
const success = isStrict === 'true' || isStrict === 'false';
if (!success) {
core.error('Invalid strict setting, must be of of (true, false)');
core.error('Invalid strict setting, must be one of (true, false)');
}
return success;
}
Expand All @@ -237,19 +273,20 @@ export async function action(githubContext: GitHubContext, octokit: Octokit): Pr
return false;
}
const eventName = githubContext.eventName;
if (!isSupportedEvent(eventName)) {
if (params.incremental_files_only === 'true' && !isSupportedEvent(eventName)) {
const msg = `Unsupported event: '${eventName}'`;
throw new AppError(msg);
}
const context: Context = {
githubContext,
github: octokit,
files: core.getInput('files'),
files: params.files,
useEventFiles: params.incremental_files_only === 'true',
};

core.info(friendlyEventName(eventName));
const eventFiles = await gatherFiles(context);
const files = filterFiles(context.files, eventFiles);
core.debug(format('Options: %o', params));
const files = await gatherFilesFromContext(context);
const result = await checkSpelling(params, [...files]);
if (result === true) {
return true;
Expand Down
2 changes: 0 additions & 2 deletions action-src/src/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import * as process from 'process';
import * as helper from './test/helper';
import { run } from './main';

const root = helper.root;

const timeout = 20000;

describe('Validate Main', () => {
Expand Down
Loading

0 comments on commit a43683f

Please sign in to comment.