Merge branch 'main'

This commit is contained in:
MaksimZhukov
2023-10-24 12:11:31 +02:00
35 changed files with 7607 additions and 1338 deletions

View File

@@ -7,7 +7,7 @@ module.exports = {
'eslint-config-prettier' 'eslint-config-prettier'
], ],
parser: '@typescript-eslint/parser', parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'eslint-plugin-jest'], plugins: ['@typescript-eslint', 'eslint-plugin-node', 'eslint-plugin-jest'],
rules: { rules: {
'@typescript-eslint/no-require-imports': 'error', '@typescript-eslint/no-require-imports': 'error',
'@typescript-eslint/no-non-null-assertion': 'off', '@typescript-eslint/no-non-null-assertion': 'off',
@@ -28,7 +28,8 @@ module.exports = {
} }
], ],
'no-control-regex': 'off', 'no-control-regex': 'off',
'no-constant-condition': ['error', {checkLoops: false}] 'no-constant-condition': ['error', {checkLoops: false}],
'node/no-extraneous-import': 'error'
}, },
overrides: [ overrides: [
{ {

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
.DS_Store .DS_Store
node_modules/ node_modules/
lib/ lib/
.idea

View File

@@ -0,0 +1,20 @@
---
name: "@octokit/openapi-types"
version: 18.0.0
type: npm
summary: Generated TypeScript definitions based on GitHub's OpenAPI spec for api.github.com
homepage:
license: mit
licenses:
- sources: LICENSE
text: |-
Copyright 2020 Gregor Martynus
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- sources: README.md
text: "[MIT](LICENSE)"
notices: []

View File

@@ -0,0 +1,34 @@
---
name: "@octokit/plugin-retry"
version: 5.0.5
type: npm
summary: Automatic retry plugin for octokit
homepage:
license: mit
licenses:
- sources: LICENSE
text: |
MIT License
Copyright (c) 2018 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- sources: README.md
text: "[MIT](LICENSE)"
notices: []

View File

@@ -0,0 +1,34 @@
---
name: "@octokit/request-error"
version: 4.0.2
type: npm
summary: Error class for Octokit request errors
homepage:
license: mit
licenses:
- sources: LICENSE
text: |
The MIT License
Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
- sources: README.md
text: "[MIT](LICENSE)"
notices: []

View File

@@ -0,0 +1,20 @@
---
name: "@octokit/types"
version: 10.0.0
type: npm
summary: Shared TypeScript definitions for Octokit projects
homepage:
license: mit
licenses:
- sources: LICENSE
text: |
MIT License Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- sources: README.md
text: "[MIT](LICENSE)"
notices: []

31
.licenses/npm/bottleneck.dep.yml generated Normal file
View File

@@ -0,0 +1,31 @@
---
name: bottleneck
version: 2.19.5
type: npm
summary: Distributed task scheduler and rate limiter
homepage:
license: mit
licenses:
- sources: LICENSE
text: |
The MIT License (MIT)
Copyright (c) 2014 Simon Grondin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
notices: []

58
.licenses/npm/lodash.isequal.dep.yml generated Normal file
View File

@@ -0,0 +1,58 @@
---
name: lodash.isequal
version: 4.5.0
type: npm
summary: The Lodash method `_.isEqual` exported as a module.
homepage: https://lodash.com/
license: mit
licenses:
- sources: LICENSE
text: |
Copyright JS Foundation and other contributors <https://js.foundation/>
Based on Underscore.js, copyright Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/lodash/lodash
The following license applies to all parts of this software except as
documented below:
====
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
====
Copyright and related rights for sample code are waived via CC0. Sample
code is defined as all source code displayed within the prose of the
documentation.
CC0: http://creativecommons.org/publicdomain/zero/1.0/
====
Files located in the node_modules and vendor directories are externally
maintained libraries used by this software which have their own
licenses; we recommend you read them, as their terms may differ from the
terms above.
notices: []

View File

@@ -1,6 +1,6 @@
--- ---
name: minimatch name: minimatch
version: 7.4.3 version: 9.0.3
type: npm type: npm
summary: a glob matcher in javascript summary: a glob matcher in javascript
homepage: homepage:

119
README.md
View File

@@ -57,6 +57,11 @@ label1:
From a boolean logic perspective, top-level match objects, and options within `all` are `AND`-ed together and individual match rules within the `any` object are `OR`-ed. If path globs are combined with `!` negation, you can write complex matching rules. From a boolean logic perspective, top-level match objects, and options within `all` are `AND`-ed together and individual match rules within the `any` object are `OR`-ed. If path globs are combined with `!` negation, you can write complex matching rules.
> ⚠️ This action uses [minimatch](https://www.npmjs.com/package/minimatch) to apply glob patterns.
> For historical reasons, paths starting with dot (e.g. `.github`) are not matched by default.
> You need to set `dot: true` to change this behavior.
> See [Inputs](#inputs) table below for details.
#### Basic Examples #### Basic Examples
```yml ```yml
@@ -121,7 +126,7 @@ release:
### Create Workflow ### Create Workflow
Create a workflow (eg: `.github/workflows/labeler.yml` see [Creating a Workflow file](https://help.github.com/en/articles/configuring-a-workflow#creating-a-workflow-file)) to utilize the labeler action with content: Create a workflow (e.g. `.github/workflows/labeler.yml` see [Creating a Workflow file](https://help.github.com/en/articles/configuring-a-workflow#creating-a-workflow-file)) to utilize the labeler action with content:
```yml ```yml
name: "Pull Request Labeler" name: "Pull Request Labeler"
@@ -142,12 +147,112 @@ jobs:
Various inputs are defined in [`action.yml`](action.yml) to let you configure the labeler: Various inputs are defined in [`action.yml`](action.yml) to let you configure the labeler:
| Name | Description | Default | | Name | Description | Default |
| - | - | - | |----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------|
| `repo-token` | Token to use to authorize label changes. Typically the GITHUB_TOKEN secret, with `contents:read` and `pull-requests:write` access | `github.token` | | `repo-token` | Token to use to authorize label changes. Typically the GITHUB_TOKEN secret | `github.token` |
| `configuration-path` | The path to the label configuration file | `.github/labeler.yml` | | `configuration-path` | The path to the label configuration file. If the file doesn't exist at the specified path on the runner, action will read from the source repository via the Github API. | `.github/labeler.yml` |
| `sync-labels` | Whether or not to remove labels when matching files are reverted or no longer changed by the PR | `false`| | `sync-labels` | Whether or not to remove labels when matching files are reverted or no longer changed by the PR | `false` |
| `dot` | Whether or not to auto-include paths starting with dot (e.g. `.github`) | `false` |
| `pr-number` | The number(s) of pull request to update, rather than detecting from the workflow context | N/A |
# Contributions ##### Using `configuration-path` input together with the `@actions/checkout` action
You might want to use action called [@actions/checkout](https://github.com/actions/checkout) to upload label configuration file onto the runner from the current or any other repositories. See usage example below:
```yml
steps:
- uses: actions/checkout@v3 # Uploads repository content to the runner
with:
repository: "owner/repositoryName" # The one of the available inputs, visit https://github.com/actions/checkout#readme to find more
- uses: actions/labeler@v4
```
##### Peculiarities of using the `dot` input
When `dot` is disabled, and you want to include _all_ files in a folder:
```yml
label1:
- path/to/folder/**/*
- path/to/folder/**/.*
```
If `dot` is enabled:
```yml
label1:
- path/to/folder/**
```
##### Example workflow specifying Pull request numbers
```yml
name: "Label Previous Pull Requests"
on:
schedule:
- cron: "0 1 * * 1"
jobs:
triage:
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
steps:
# Label PRs 1, 2, and 3
- uses: actions/labeler@v4
with:
pr-number: |
1
2
3
```
**Note:** in normal usage the `pr-number` input is not required as the action will detect the PR number from the workflow context.
#### Outputs
Labeler provides the following outputs:
| Name | Description |
|--------------|-----------------------------------------------------------|
| `new-labels` | A comma-separated list of all new labels |
| `all-labels` | A comma-separated list of all labels that the PR contains |
The following example performs steps based on the output of labeler:
```yml
name: "My workflow"
on:
- pull_request_target
jobs:
triage:
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
steps:
- id: label-the-PR
uses: actions/labeler@v4
- id: run-frontend-tests
if: contains(steps.label-the-PR.outputs.all-labels, 'frontend')
run: |
echo "Running frontend tests..."
# Put your commands for running frontend tests here
- id: run-backend-tests
if: contains(steps.label-the-PR.outputs.all-labels, 'backend')
run: |
echo "Running backend tests..."
# Put your commands for running backend tests here
```
## Permissions
In order to add labels to pull requests, the GitHub labeler action requires write permissions on the pull-request. However, when the action runs on a pull request from a forked repository, GitHub only grants read access tokens for `pull_request` events, at most. If you encounter an `Error: HttpError: Resource not accessible by integration`, it's likely due to these permission constraints. To resolve this issue, you can modify the `on:` section of your workflow to use
[`pull_request_target`](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target) instead of `pull_request` (see example [above](#create-workflow)). This change allows the action to have write access, because `pull_request_target` alters the [context of the action](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target) and safely grants additional permissions. Refer to the [GitHub token permissions documentation](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token) for more details about access levels and event contexts.
## Contributions
Contributions are welcome! See the [Contributor's Guide](CONTRIBUTING.md). Contributions are welcome! See the [Contributor's Guide](CONTRIBUTING.md).

View File

@@ -19,11 +19,14 @@ export const context = {
const mockApi = { const mockApi = {
rest: { rest: {
issues: { issues: {
addLabels: jest.fn(), setLabels: jest.fn()
removeLabel: jest.fn()
}, },
pulls: { pulls: {
get: jest.fn().mockResolvedValue({}), get: jest.fn().mockResolvedValue({
data: {
labels: []
}
}),
listFiles: { listFiles: {
endpoint: { endpoint: {
merge: jest.fn().mockReturnValue({}) merge: jest.fn().mockReturnValue({})

View File

@@ -23,7 +23,11 @@ describe('checkAllChangedFiles', () => {
]; ];
it('returns true', () => { it('returns true', () => {
const result = checkAllChangedFiles(changedFiles, globPatternsConfigs); const result = checkAllChangedFiles(
changedFiles,
globPatternsConfigs,
false
);
expect(result).toBe(true); expect(result).toBe(true);
}); });
}); });
@@ -36,7 +40,11 @@ describe('checkAllChangedFiles', () => {
]; ];
it('returns false', () => { it('returns false', () => {
const result = checkAllChangedFiles(changedFiles, globPatternsConfigs); const result = checkAllChangedFiles(
changedFiles,
globPatternsConfigs,
false
);
expect(result).toBe(false); expect(result).toBe(false);
}); });
}); });
@@ -52,7 +60,11 @@ describe('checkAnyChangedFiles', () => {
]; ];
it('returns true', () => { it('returns true', () => {
const result = checkAnyChangedFiles(changedFiles, globPatternsConfigs); const result = checkAnyChangedFiles(
changedFiles,
globPatternsConfigs,
false
);
expect(result).toBe(true); expect(result).toBe(true);
}); });
}); });
@@ -64,7 +76,11 @@ describe('checkAnyChangedFiles', () => {
]; ];
it('returns false', () => { it('returns false', () => {
const result = checkAnyChangedFiles(changedFiles, globPatternsConfigs); const result = checkAnyChangedFiles(
changedFiles,
globPatternsConfigs,
false
);
expect(result).toBe(false); expect(result).toBe(false);
}); });
}); });
@@ -138,7 +154,11 @@ describe('checkIfAnyGlobMatchesAnyFile', () => {
const globPatterns = ['*.md', 'foo.txt']; const globPatterns = ['*.md', 'foo.txt'];
it('returns true', () => { it('returns true', () => {
const result = checkIfAnyGlobMatchesAnyFile(changedFiles, globPatterns); const result = checkIfAnyGlobMatchesAnyFile(
changedFiles,
globPatterns,
false
);
expect(result).toBe(true); expect(result).toBe(true);
}); });
}); });
@@ -147,7 +167,11 @@ describe('checkIfAnyGlobMatchesAnyFile', () => {
const globPatterns = ['*.md', '!*.txt']; const globPatterns = ['*.md', '!*.txt'];
it('returns false', () => { it('returns false', () => {
const result = checkIfAnyGlobMatchesAnyFile(changedFiles, globPatterns); const result = checkIfAnyGlobMatchesAnyFile(
changedFiles,
globPatterns,
false
);
expect(result).toBe(false); expect(result).toBe(false);
}); });
}); });
@@ -160,7 +184,11 @@ describe('checkIfAllGlobsMatchAnyFile', () => {
const globPatterns = ['**/bar.txt', 'bar.txt']; const globPatterns = ['**/bar.txt', 'bar.txt'];
it('returns true', () => { it('returns true', () => {
const result = checkIfAllGlobsMatchAnyFile(changedFiles, globPatterns); const result = checkIfAllGlobsMatchAnyFile(
changedFiles,
globPatterns,
false
);
expect(result).toBe(true); expect(result).toBe(true);
}); });
}); });
@@ -169,7 +197,11 @@ describe('checkIfAllGlobsMatchAnyFile', () => {
const globPatterns = ['*.txt', '*.md']; const globPatterns = ['*.txt', '*.md'];
it('returns false', () => { it('returns false', () => {
const result = checkIfAllGlobsMatchAnyFile(changedFiles, globPatterns); const result = checkIfAllGlobsMatchAnyFile(
changedFiles,
globPatterns,
false
);
expect(result).toBe(false); expect(result).toBe(false);
}); });
}); });
@@ -182,7 +214,11 @@ describe('checkIfAnyGlobMatchesAllFiles', () => {
const globPatterns = ['*.md', '*.txt']; const globPatterns = ['*.md', '*.txt'];
it('returns true', () => { it('returns true', () => {
const result = checkIfAnyGlobMatchesAllFiles(changedFiles, globPatterns); const result = checkIfAnyGlobMatchesAllFiles(
changedFiles,
globPatterns,
false
);
expect(result).toBe(true); expect(result).toBe(true);
}); });
}); });
@@ -191,7 +227,11 @@ describe('checkIfAnyGlobMatchesAllFiles', () => {
const globPatterns = ['*.md', 'bar.txt', 'foo.txt']; const globPatterns = ['*.md', 'bar.txt', 'foo.txt'];
it('returns false', () => { it('returns false', () => {
const result = checkIfAnyGlobMatchesAllFiles(changedFiles, globPatterns); const result = checkIfAnyGlobMatchesAllFiles(
changedFiles,
globPatterns,
false
);
expect(result).toBe(false); expect(result).toBe(false);
}); });
}); });
@@ -204,7 +244,11 @@ describe('checkIfAllGlobsMatchAllFiles', () => {
const globPatterns = ['*.txt', '**']; const globPatterns = ['*.txt', '**'];
it('returns true', () => { it('returns true', () => {
const result = checkIfAllGlobsMatchAllFiles(changedFiles, globPatterns); const result = checkIfAllGlobsMatchAllFiles(
changedFiles,
globPatterns,
false
);
expect(result).toBe(true); expect(result).toBe(true);
}); });
}); });
@@ -213,7 +257,11 @@ describe('checkIfAllGlobsMatchAllFiles', () => {
const globPatterns = ['**', 'foo.txt']; const globPatterns = ['**', 'foo.txt'];
it('returns false', () => { it('returns false', () => {
const result = checkIfAllGlobsMatchAllFiles(changedFiles, globPatterns); const result = checkIfAllGlobsMatchAllFiles(
changedFiles,
globPatterns,
false
);
expect(result).toBe(false); expect(result).toBe(false);
}); });
}); });

View File

@@ -1,13 +1,13 @@
import * as yaml from 'js-yaml';
import * as core from '@actions/core';
import * as fs from 'fs';
import {checkMatchConfigs} from '../src/labeler';
import { import {
checkMatchConfigs,
MatchConfig, MatchConfig,
toMatchConfig, toMatchConfig,
getLabelConfigMapFromObject, getLabelConfigMapFromObject,
BaseMatchConfig BaseMatchConfig
} from '../src/labeler'; } from '../src/api/get-label-configs';
import * as yaml from 'js-yaml';
import * as core from '@actions/core';
import * as fs from 'fs';
jest.mock('@actions/core'); jest.mock('@actions/core');
@@ -95,14 +95,14 @@ describe('checkMatchConfigs', () => {
it('returns true when our pattern does match changed files', () => { it('returns true when our pattern does match changed files', () => {
const changedFiles = ['foo.txt', 'bar.txt']; const changedFiles = ['foo.txt', 'bar.txt'];
const result = checkMatchConfigs(changedFiles, matchConfig); const result = checkMatchConfigs(changedFiles, matchConfig, false);
expect(result).toBeTruthy(); expect(result).toBeTruthy();
}); });
it('returns false when our pattern does not match changed files', () => { it('returns false when our pattern does not match changed files', () => {
const changedFiles = ['foo.docx']; const changedFiles = ['foo.docx'];
const result = checkMatchConfigs(changedFiles, matchConfig); const result = checkMatchConfigs(changedFiles, matchConfig, false);
expect(result).toBeFalsy(); expect(result).toBeFalsy();
}); });
@@ -118,9 +118,23 @@ describe('checkMatchConfigs', () => {
]; ];
const changedFiles = ['foo.txt', 'bar.txt']; const changedFiles = ['foo.txt', 'bar.txt'];
const result = checkMatchConfigs(changedFiles, matchConfig); const result = checkMatchConfigs(changedFiles, matchConfig, false);
expect(result).toBe(true); expect(result).toBe(true);
}); });
it('returns false for a file starting with dot if `dot` option is false', () => {
const changedFiles = ['.foo.txt'];
const result = checkMatchConfigs(changedFiles, matchConfig, false);
expect(result).toBeFalsy();
});
it('returns true for a file starting with dot if `dot` option is true', () => {
const changedFiles = ['.foo.txt'];
const result = checkMatchConfigs(changedFiles, matchConfig, true);
expect(result).toBeTruthy();
});
}); });
describe('when multiple MatchConfigs are supplied', () => { describe('when multiple MatchConfigs are supplied', () => {
@@ -131,7 +145,7 @@ describe('checkMatchConfigs', () => {
const changedFiles = ['foo.txt', 'bar.md']; const changedFiles = ['foo.txt', 'bar.md'];
it('returns false when only one config matches', () => { it('returns false when only one config matches', () => {
const result = checkMatchConfigs(changedFiles, matchConfig); const result = checkMatchConfigs(changedFiles, matchConfig, false);
expect(result).toBe(false); expect(result).toBe(false);
}); });
@@ -140,7 +154,7 @@ describe('checkMatchConfigs', () => {
{any: [{changedFiles: [{AnyGlobToAnyFile: ['*.txt']}]}]}, {any: [{changedFiles: [{AnyGlobToAnyFile: ['*.txt']}]}]},
{any: [{headBranch: ['head-branch']}]} {any: [{headBranch: ['head-branch']}]}
]; ];
const result = checkMatchConfigs(changedFiles, matchConfig); const result = checkMatchConfigs(changedFiles, matchConfig, false);
expect(result).toBe(true); expect(result).toBe(true);
}); });
}); });

View File

@@ -1,18 +1,37 @@
import {run} from '../src/labeler'; import {run} from '../src/labeler';
import * as github from '@actions/github'; import * as github from '@actions/github';
import * as core from '@actions/core'; import * as core from '@actions/core';
import path from 'path';
const fs = jest.requireActual('fs'); import fs from 'fs';
jest.mock('@actions/core'); jest.mock('@actions/core');
jest.mock('@actions/github'); jest.mock('@actions/github');
const gh = github.getOctokit('_'); const gh = github.getOctokit('_');
const addLabelsMock = jest.spyOn(gh.rest.issues, 'addLabels'); const setLabelsMock = jest.spyOn(gh.rest.issues, 'setLabels');
const removeLabelMock = jest.spyOn(gh.rest.issues, 'removeLabel');
const reposMock = jest.spyOn(gh.rest.repos, 'getContent'); const reposMock = jest.spyOn(gh.rest.repos, 'getContent');
const paginateMock = jest.spyOn(gh, 'paginate'); const paginateMock = jest.spyOn(gh, 'paginate');
const getPullMock = jest.spyOn(gh.rest.pulls, 'get'); const getPullMock = jest.spyOn(gh.rest.pulls, 'get');
const readFileSyncMock = jest.spyOn(fs, 'readFileSync');
const existsSyncMock = jest.spyOn(fs, 'existsSync');
const coreErrorMock = jest.spyOn(core, 'error');
const coreWarningMock = jest.spyOn(core, 'warning');
const coreSetFailedMock = jest.spyOn(core, 'setFailed');
const setOutputSpy = jest.spyOn(core, 'setOutput');
class HttpError extends Error {
constructor(message: string) {
super(message);
this.name = 'HttpError';
}
}
class NotFound extends Error {
constructor(message: string) {
super(message);
this.name = 'NotFound';
}
}
const yamlFixtures = { const yamlFixtures = {
'branches.yml': fs.readFileSync('__tests__/fixtures/branches.yml'), 'branches.yml': fs.readFileSync('__tests__/fixtures/branches.yml'),
@@ -21,189 +40,460 @@ const yamlFixtures = {
'any_and_all.yml': fs.readFileSync('__tests__/fixtures/any_and_all.yml') 'any_and_all.yml': fs.readFileSync('__tests__/fixtures/any_and_all.yml')
}; };
const configureInput = (
mockInput: Partial<{
'repo-token': string;
'configuration-path': string;
'sync-labels': boolean;
dot: boolean;
'pr-number': string[];
}>
) => {
jest
.spyOn(core, 'getInput')
.mockImplementation((name: string, ...opts) => mockInput[name]);
jest
.spyOn(core, 'getMultilineInput')
.mockImplementation((name: string, ...opts) => mockInput[name]);
jest
.spyOn(core, 'getBooleanInput')
.mockImplementation((name: string, ...opts) => mockInput[name]);
};
afterAll(() => jest.restoreAllMocks()); afterAll(() => jest.restoreAllMocks());
describe('run', () => { describe('run', () => {
it('adds labels to PRs that match our glob patterns', async () => { it('(with dot: false) adds labels to PRs that match our glob patterns', async () => {
configureInput({});
usingLabelerConfigYaml('only_pdfs.yml'); usingLabelerConfigYaml('only_pdfs.yml');
mockGitHubResponseChangedFiles('foo.pdf'); mockGitHubResponseChangedFiles('foo.pdf');
getPullMock.mockResolvedValue(<any>{
data: {
labels: []
}
});
await run(); await run();
expect(removeLabelMock).toHaveBeenCalledTimes(0); expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledWith({ expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa', owner: 'monalisa',
repo: 'helloworld', repo: 'helloworld',
issue_number: 123, issue_number: 123,
labels: ['touched-a-pdf-file'] labels: ['touched-a-pdf-file']
}); });
expect(setOutputSpy).toHaveBeenCalledWith(
'new-labels',
'touched-a-pdf-file'
);
expect(setOutputSpy).toHaveBeenCalledWith(
'all-labels',
'touched-a-pdf-file'
);
}); });
it('does not add labels to PRs that do not match our glob patterns', async () => { it('(with dot: true) adds labels to PRs that match our glob patterns', async () => {
configureInput({dot: true});
usingLabelerConfigYaml('only_pdfs.yml'); usingLabelerConfigYaml('only_pdfs.yml');
mockGitHubResponseChangedFiles('foo.txt'); mockGitHubResponseChangedFiles('.foo.pdf');
await run();
expect(removeLabelMock).toHaveBeenCalledTimes(0);
expect(addLabelsMock).toHaveBeenCalledTimes(0);
});
it('does not add a label when the match config options are not supported', async () => {
usingLabelerConfigYaml('not_supported.yml');
await run();
expect(addLabelsMock).toHaveBeenCalledTimes(0);
expect(removeLabelMock).toHaveBeenCalledTimes(0);
});
it('(with sync-labels: true) it deletes preexisting PR labels that no longer match the glob pattern', async () => {
const mockInput = {
'repo-token': 'foo',
'configuration-path': 'bar',
'sync-labels': 'true'
};
jest
.spyOn(core, 'getInput')
.mockImplementation((name: string, ...opts) => mockInput[name]);
jest
.spyOn(core, 'getBooleanInput')
.mockImplementation(
(name: string, ...opts) => mockInput[name] === 'true'
);
usingLabelerConfigYaml('only_pdfs.yml');
mockGitHubResponseChangedFiles('foo.txt');
getPullMock.mockResolvedValue(<any>{ getPullMock.mockResolvedValue(<any>{
data: { data: {
labels: [{name: 'touched-a-pdf-file'}] labels: []
} }
}); });
await run(); await run();
expect(addLabelsMock).toHaveBeenCalledTimes(0); expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(removeLabelMock).toHaveBeenCalledTimes(1); expect(setLabelsMock).toHaveBeenCalledWith({
expect(removeLabelMock).toHaveBeenCalledWith({
owner: 'monalisa', owner: 'monalisa',
repo: 'helloworld', repo: 'helloworld',
issue_number: 123, issue_number: 123,
name: 'touched-a-pdf-file' labels: ['touched-a-pdf-file']
}); });
expect(setOutputSpy).toHaveBeenCalledWith(
'new-labels',
'touched-a-pdf-file'
);
expect(setOutputSpy).toHaveBeenCalledWith(
'all-labels',
'touched-a-pdf-file'
);
}); });
it('(with sync-labels: false) it issues no delete calls even when there are preexisting PR labels that no longer match the glob pattern', async () => { it('(with dot: false) does not add labels to PRs that do not match our glob patterns', async () => {
const mockInput = { configureInput({});
'repo-token': 'foo',
'configuration-path': 'bar',
'sync-labels': 'false'
};
jest
.spyOn(core, 'getInput')
.mockImplementation((name: string, ...opts) => mockInput[name]);
jest
.spyOn(core, 'getBooleanInput')
.mockImplementation(
(name: string, ...opts) => mockInput[name] === 'true'
);
usingLabelerConfigYaml('only_pdfs.yml'); usingLabelerConfigYaml('only_pdfs.yml');
mockGitHubResponseChangedFiles('foo.txt'); mockGitHubResponseChangedFiles('.foo.pdf');
getPullMock.mockResolvedValue(<any>{ getPullMock.mockResolvedValue(<any>{
data: { data: {
labels: [{name: 'touched-a-pdf-file'}] labels: []
} }
}); });
await run(); await run();
expect(addLabelsMock).toHaveBeenCalledTimes(0); expect(setLabelsMock).toHaveBeenCalledTimes(0);
expect(removeLabelMock).toHaveBeenCalledTimes(0); expect(setOutputSpy).toHaveBeenCalledWith('new-labels', '');
expect(setOutputSpy).toHaveBeenCalledWith('all-labels', '');
});
it('(with dot: true) does not add labels to PRs that do not match our glob patterns', async () => {
configureInput({dot: true});
usingLabelerConfigYaml('only_pdfs.yml');
mockGitHubResponseChangedFiles('foo.txt');
await run();
expect(setLabelsMock).toHaveBeenCalledTimes(0);
});
it('does not add a label when the match config options are not supported', async () => {
configureInput({});
usingLabelerConfigYaml('not_supported.yml');
await run();
expect(setLabelsMock).toHaveBeenCalledTimes(0);
}); });
it('adds labels based on the branch names that match the regexp pattern', async () => { it('adds labels based on the branch names that match the regexp pattern', async () => {
configureInput({});
github.context.payload.pull_request!.head = {ref: 'test/testing-time'}; github.context.payload.pull_request!.head = {ref: 'test/testing-time'};
usingLabelerConfigYaml('branches.yml'); usingLabelerConfigYaml('branches.yml');
await run(); await run();
expect(addLabelsMock).toHaveBeenCalledTimes(1); expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledWith({ expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa', owner: 'monalisa',
repo: 'helloworld', repo: 'helloworld',
issue_number: 123, issue_number: 123,
labels: ['test-branch'] labels: ['test-branch']
}); });
expect(setOutputSpy).toHaveBeenCalledWith('new-labels', 'test-branch');
expect(setOutputSpy).toHaveBeenCalledWith('all-labels', 'test-branch');
}); });
it('adds multiple labels based on branch names that match different regexp patterns', async () => { it('adds multiple labels based on branch names that match different regexp patterns', async () => {
configureInput({});
github.context.payload.pull_request!.head = { github.context.payload.pull_request!.head = {
ref: 'test/feature/123' ref: 'test/feature/123'
}; };
usingLabelerConfigYaml('branches.yml'); usingLabelerConfigYaml('branches.yml');
await run(); await run();
expect(addLabelsMock).toHaveBeenCalledTimes(1); expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledWith({ expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa', owner: 'monalisa',
repo: 'helloworld', repo: 'helloworld',
issue_number: 123, issue_number: 123,
labels: ['test-branch', 'feature-branch'] labels: ['test-branch', 'feature-branch']
}); });
expect(setOutputSpy).toHaveBeenCalledWith(
'new-labels',
'test-branch,feature-branch'
);
expect(setOutputSpy).toHaveBeenCalledWith(
'all-labels',
'test-branch,feature-branch'
);
}); });
it('can support multiple branches by batching', async () => { it('can support multiple branches by batching', async () => {
configureInput({});
github.context.payload.pull_request!.head = {ref: 'fix/123'}; github.context.payload.pull_request!.head = {ref: 'fix/123'};
usingLabelerConfigYaml('branches.yml'); usingLabelerConfigYaml('branches.yml');
await run(); await run();
expect(addLabelsMock).toHaveBeenCalledTimes(1); expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledWith({ expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa', owner: 'monalisa',
repo: 'helloworld', repo: 'helloworld',
issue_number: 123, issue_number: 123,
labels: ['bug-branch'] labels: ['bug-branch']
}); });
expect(setOutputSpy).toHaveBeenCalledWith('new-labels', 'bug-branch');
expect(setOutputSpy).toHaveBeenCalledWith('all-labels', 'bug-branch');
}); });
it('can support multiple branches by providing an array', async () => { it('can support multiple branches by providing an array', async () => {
configureInput({});
github.context.payload.pull_request!.head = {ref: 'array/123'}; github.context.payload.pull_request!.head = {ref: 'array/123'};
usingLabelerConfigYaml('branches.yml'); usingLabelerConfigYaml('branches.yml');
await run(); await run();
expect(addLabelsMock).toHaveBeenCalledTimes(1); expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledWith({ expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa', owner: 'monalisa',
repo: 'helloworld', repo: 'helloworld',
issue_number: 123, issue_number: 123,
labels: ['array-branch'] labels: ['array-branch']
}); });
expect(setOutputSpy).toHaveBeenCalledWith('new-labels', 'array-branch');
expect(setOutputSpy).toHaveBeenCalledWith('all-labels', 'array-branch');
}); });
it('adds a label when matching any and all patterns are provided', async () => { it('adds a label when matching any and all patterns are provided', async () => {
configureInput({});
usingLabelerConfigYaml('any_and_all.yml'); usingLabelerConfigYaml('any_and_all.yml');
mockGitHubResponseChangedFiles('tests/test.ts'); mockGitHubResponseChangedFiles('tests/test.ts');
await run(); await run();
expect(addLabelsMock).toHaveBeenCalledTimes(1); expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledWith({ expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa', owner: 'monalisa',
repo: 'helloworld', repo: 'helloworld',
issue_number: 123, issue_number: 123,
labels: ['tests'] labels: ['tests']
}); });
expect(setOutputSpy).toHaveBeenCalledWith('new-labels', 'tests');
expect(setOutputSpy).toHaveBeenCalledWith('all-labels', 'tests');
}); });
it('does not add a label when not all any and all patterns are matched', async () => { it('does not add a label when not all any and all patterns are matched', async () => {
configureInput({});
usingLabelerConfigYaml('any_and_all.yml'); usingLabelerConfigYaml('any_and_all.yml');
mockGitHubResponseChangedFiles('tests/requirements.txt'); mockGitHubResponseChangedFiles('tests/requirements.txt');
await run(); await run();
expect(addLabelsMock).toHaveBeenCalledTimes(0); expect(setLabelsMock).toHaveBeenCalledTimes(0);
expect(removeLabelMock).toHaveBeenCalledTimes(0);
}); });
it('(with sync-labels: true) it deletes preexisting PR labels that no longer match the glob pattern', async () => {
configureInput({
'repo-token': 'foo',
'configuration-path': 'bar',
'sync-labels': true
});
usingLabelerConfigYaml('only_pdfs.yml');
mockGitHubResponseChangedFiles('foo.txt');
getPullMock.mockResolvedValue(<any>{
data: {
labels: [{name: 'touched-a-pdf-file'}, {name: 'manually-added'}]
}
});
await run();
expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 123,
labels: ['manually-added']
});
expect(setOutputSpy).toHaveBeenCalledWith('new-labels', '');
expect(setOutputSpy).toHaveBeenCalledWith('all-labels', 'manually-added');
});
it('(with sync-labels: false) it issues no delete calls even when there are preexisting PR labels that no longer match the glob pattern', async () => {
configureInput({
'repo-token': 'foo',
'configuration-path': 'bar',
'sync-labels': false
});
usingLabelerConfigYaml('only_pdfs.yml');
mockGitHubResponseChangedFiles('foo.txt');
getPullMock.mockResolvedValue(<any>{
data: {
labels: [{name: 'touched-a-pdf-file'}, {name: 'manually-added'}]
}
});
await run();
expect(setLabelsMock).toHaveBeenCalledTimes(0);
expect(setOutputSpy).toHaveBeenCalledWith('new-labels', '');
expect(setOutputSpy).toHaveBeenCalledWith(
'all-labels',
'touched-a-pdf-file,manually-added'
);
});
it('(with sync-labels: false) it only logs the excess labels', async () => {
configureInput({
'repo-token': 'foo',
'configuration-path': 'bar',
'sync-labels': false
});
usingLabelerConfigYaml('only_pdfs.yml');
mockGitHubResponseChangedFiles('foo.pdf');
const existingLabels = Array.from({length: 100}).map((_, idx) => ({
name: `existing-label-${idx}`
}));
getPullMock.mockResolvedValue(<any>{
data: {
labels: existingLabels
}
});
await run();
expect(setLabelsMock).toHaveBeenCalledTimes(0);
expect(coreWarningMock).toHaveBeenCalledTimes(1);
expect(coreWarningMock).toHaveBeenCalledWith(
'Maximum of 100 labels allowed. Excess labels: touched-a-pdf-file',
{title: 'Label limit for a PR exceeded'}
);
const allLabels: string = existingLabels.map(i => i.name).join(',');
expect(setOutputSpy).toHaveBeenCalledWith('new-labels', '');
expect(setOutputSpy).toHaveBeenCalledWith('all-labels', allLabels);
});
it('(with pr-number: array of one item, uses the PR number specified in the parameters', async () => {
configureInput({
'repo-token': 'foo',
'configuration-path': 'bar',
'pr-number': ['104']
});
usingLabelerConfigYaml('only_pdfs.yml');
mockGitHubResponseChangedFiles('foo.pdf');
getPullMock.mockResolvedValue(<any>{
data: {
labels: [{name: 'manually-added'}]
}
});
await run();
expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 104,
labels: ['manually-added', 'touched-a-pdf-file']
});
expect(setOutputSpy).toHaveBeenCalledWith(
'new-labels',
'touched-a-pdf-file'
);
expect(setOutputSpy).toHaveBeenCalledWith(
'all-labels',
'manually-added,touched-a-pdf-file'
);
});
it('(with pr-number: array of two items, uses the PR number specified in the parameters', async () => {
configureInput({
'repo-token': 'foo',
'configuration-path': 'bar',
'pr-number': ['104', '150']
});
usingLabelerConfigYaml('only_pdfs.yml');
mockGitHubResponseChangedFiles('foo.pdf');
getPullMock.mockResolvedValueOnce(<any>{
data: {
labels: [{name: 'manually-added'}]
}
});
getPullMock.mockResolvedValueOnce(<any>{
data: {
labels: []
}
});
await run();
expect(setLabelsMock).toHaveBeenCalledTimes(2);
expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 104,
labels: ['manually-added', 'touched-a-pdf-file']
});
expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 150,
labels: ['touched-a-pdf-file']
});
expect(setOutputSpy).toHaveBeenCalledWith(
'new-labels',
'touched-a-pdf-file'
);
expect(setOutputSpy).toHaveBeenCalledWith(
'all-labels',
'manually-added,touched-a-pdf-file'
);
});
it('does not add labels to PRs that have no changed files', async () => {
usingLabelerConfigYaml('only_pdfs.yml');
mockGitHubResponseChangedFiles();
await run();
expect(setLabelsMock).toHaveBeenCalledTimes(0);
});
it('should use local configuration file if it exists', async () => {
const configFile = 'only_pdfs.yml';
const configFilePath = path.join(__dirname, 'fixtures', configFile);
mockGitHubResponseChangedFiles('foo.pdf');
const readFileSyncOptions = {encoding: 'utf8'};
configureInput({
'configuration-path': configFilePath
});
await run();
expect(existsSyncMock).toHaveBeenCalledWith(configFilePath);
expect(readFileSyncMock).toHaveBeenCalledWith(
configFilePath,
readFileSyncOptions
);
expect(reposMock).not.toHaveBeenCalled();
});
it('should fetch configuration file from API if it does not exist locally', async () => {
const configFilePath = 'non_existed_path/labeler.yml';
mockGitHubResponseChangedFiles('foo.pdf');
configureInput({
'configuration-path': configFilePath
});
await run();
expect(existsSyncMock).toHaveBeenCalledWith(configFilePath);
expect(readFileSyncMock).not.toHaveBeenCalled();
expect(reposMock).toHaveBeenCalled();
});
test.each([
[new HttpError('Error message')],
[new NotFound('Error message')]
])(
'should warn if configuration file could not be fetched through the API, log error and fail the action',
async error => {
const configFilePath = 'non_existed_path/labeler.yml';
reposMock.mockImplementation(() => {
throw error;
});
const warningMessage = `The config file was not found at ${configFilePath}. Make sure it exists and that this action has the correct access rights.`;
mockGitHubResponseChangedFiles('foo.pdf');
configureInput({
'configuration-path': configFilePath
});
await run();
expect(coreWarningMock).toHaveBeenCalledWith(warningMessage);
expect(coreErrorMock).toHaveBeenCalledWith(error);
expect(coreSetFailedMock).toHaveBeenCalledWith(error.message);
}
);
}); });
function usingLabelerConfigYaml(fixtureName: keyof typeof yamlFixtures): void { function usingLabelerConfigYaml(fixtureName: keyof typeof yamlFixtures): void {

View File

@@ -14,7 +14,19 @@ inputs:
description: 'Whether or not to remove labels when matching files are reverted' description: 'Whether or not to remove labels when matching files are reverted'
default: false default: false
required: false required: false
dot:
description: 'Whether or not to auto-include paths starting with dot (e.g. `.github`)'
default: false
required: false
pr-number:
description: 'The pull request number(s)'
required: false
outputs:
new-labels:
description: 'A comma-separated list of all new labels'
all-labels:
description: 'A comma-separated list of all labels that the PR contains'
runs: runs:
using: 'node16' using: 'node16'
main: 'dist/index.js' main: 'dist/index.js'

5482
dist/index.js vendored

File diff suppressed because it is too large Load Diff

1932
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "labeler", "name": "labeler",
"version": "4.0.1", "version": "4.1.0",
"description": "Labels pull requests by files altered", "description": "Labels pull requests by files altered",
"main": "lib/main.js", "main": "lib/main.js",
"scripts": { "scripts": {
@@ -26,22 +26,26 @@
"dependencies": { "dependencies": {
"@actions/core": "^1.10.0", "@actions/core": "^1.10.0",
"@actions/github": "^5.1.1", "@actions/github": "^5.1.1",
"@octokit/plugin-retry": "^5.0.5",
"js-yaml": "^4.1.0", "js-yaml": "^4.1.0",
"minimatch": "^7.4.3" "lodash.isequal": "^4.5.0",
"minimatch": "^9.0.3"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "^27.4.1", "@types/jest": "^27.4.1",
"@types/js-yaml": "^4.0.5", "@types/js-yaml": "^4.0.6",
"@types/lodash.isequal": "^4.5.6",
"@types/minimatch": "^5.1.2", "@types/minimatch": "^5.1.2",
"@types/node": "^16.11.7", "@types/node": "^16.11.7",
"@typescript-eslint/eslint-plugin": "^5.59.7", "@typescript-eslint/eslint-plugin": "^6.7.4",
"@typescript-eslint/parser": "^5.59.7", "@typescript-eslint/parser": "^6.7.2",
"@vercel/ncc": "^0.36.1", "@vercel/ncc": "^0.36.1",
"eslint": "^8.41.0", "eslint": "^8.51.0",
"eslint-config-prettier": "^8.8.0", "eslint-config-prettier": "^8.10.0",
"eslint-plugin-jest": "^27.2.1", "eslint-plugin-jest": "^27.4.2",
"eslint-plugin-node": "^11.1.0",
"jest": "^27.5.1", "jest": "^27.5.1",
"prettier": "^2.8.8", "prettier": "^3.0.3",
"ts-jest": "^27.1.3", "ts-jest": "^27.1.3",
"typescript": "^4.9.5" "typescript": "^4.9.5"
} }

View File

@@ -0,0 +1,24 @@
import * as core from '@actions/core';
import * as github from '@actions/github';
import {ClientType} from './types';
export const getChangedFiles = async (
client: ClientType,
prNumber: number
): Promise<string[]> => {
const listFilesOptions = client.rest.pulls.listFiles.endpoint.merge({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: prNumber
});
const listFilesResponse = await client.paginate(listFilesOptions);
const changedFiles = listFilesResponse.map((f: any) => f.filename);
core.debug('found changed files:');
for (const file of changedFiles) {
core.debug(' ' + file);
}
return changedFiles;
};

View File

@@ -0,0 +1,38 @@
import * as core from '@actions/core';
import * as github from '@actions/github';
import {getChangedFiles} from './get-changed-files';
import {ClientType} from './types';
export async function* getPullRequests(
client: ClientType,
prNumbers: number[]
) {
for (const prNumber of prNumbers) {
core.debug(`looking for pr #${prNumber}`);
let prData: any;
try {
const result = await client.rest.pulls.get({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: prNumber
});
prData = result.data;
} catch (error: any) {
core.warning(`Could not find pull request #${prNumber}, skipping`);
continue;
}
core.debug(`fetching changed files for pr #${prNumber}`);
const changedFiles: string[] = await getChangedFiles(client, prNumber);
if (!changedFiles.length) {
core.warning(`Pull request #${prNumber} has no changed files, skipping`);
continue;
}
yield {
data: prData,
number: prNumber,
changedFiles
};
}
}

16
src/api/get-content.ts Normal file
View File

@@ -0,0 +1,16 @@
import * as github from '@actions/github';
import {ClientType} from './types';
export const getContent = async (
client: ClientType,
repoPath: string
): Promise<string> => {
const response: any = await client.rest.repos.getContent({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
path: repoPath,
ref: github.context.sha
});
return Buffer.from(response.data.content, response.data.encoding).toString();
};

View File

@@ -0,0 +1,126 @@
import * as core from '@actions/core';
import * as yaml from 'js-yaml';
import fs from 'fs';
import {ClientType} from './types';
import {getContent} from './get-content';
import {
ChangedFilesMatchConfig,
toChangedFilesMatchConfig
} from '../changedFiles';
import {toBranchMatchConfig, BranchMatchConfig} from '../branch';
export interface MatchConfig {
all?: BaseMatchConfig[];
any?: BaseMatchConfig[];
}
export type BaseMatchConfig = BranchMatchConfig & ChangedFilesMatchConfig;
const ALLOWED_CONFIG_KEYS = ['changed-files', 'head-branch', 'base-branch'];
export const getLabelConfigs = (
client: ClientType,
configurationPath: string
): Promise<Map<string, MatchConfig[]>> =>
Promise.resolve()
.then(() => {
if (!fs.existsSync(configurationPath)) {
core.info(
`The configuration file (path: ${configurationPath}) was not found locally, fetching via the api`
);
return getContent(client, configurationPath);
}
core.info(
`The configuration file (path: ${configurationPath}) was found locally, reading from the file`
);
return fs.readFileSync(configurationPath, {
encoding: 'utf8'
});
})
.catch(error => {
if (error.name == 'HttpError' || error.name == 'NotFound') {
core.warning(
`The config file was not found at ${configurationPath}. Make sure it exists and that this action has the correct access rights.`
);
}
return Promise.reject(error);
})
.then(configuration => {
// loads (hopefully) a `{[label:string]: MatchConfig[]}`, but is `any`:
const configObject: any = yaml.load(configuration);
// transform `any` => `Map<string,MatchConfig[]>` or throw if yaml is malformed:
return getLabelConfigMapFromObject(configObject);
});
export function getLabelConfigMapFromObject(
configObject: any
): Map<string, MatchConfig[]> {
const labelMap: Map<string, MatchConfig[]> = new Map();
for (const label in configObject) {
const configOptions = configObject[label];
if (
!Array.isArray(configOptions) ||
!configOptions.every(opts => typeof opts === 'object')
) {
throw Error(
`found unexpected type for label '${label}' (should be array of config options)`
);
}
const matchConfigs = configOptions.reduce<MatchConfig[]>(
(updatedConfig, configValue) => {
if (!configValue) {
return updatedConfig;
}
Object.entries(configValue).forEach(([key, value]) => {
// If the top level `any` or `all` keys are provided then set them, and convert their values to
// our config objects.
if (key === 'any' || key === 'all') {
if (Array.isArray(value)) {
const newConfigs = value.map(toMatchConfig);
updatedConfig.push({[key]: newConfigs});
}
} else if (ALLOWED_CONFIG_KEYS.includes(key)) {
const newMatchConfig = toMatchConfig({[key]: value});
// Find or set the `any` key so that we can add these properties to that rule,
// Or create a new `any` key and add that to our array of configs.
const indexOfAny = updatedConfig.findIndex(mc => !!mc['any']);
if (indexOfAny >= 0) {
updatedConfig[indexOfAny].any?.push(newMatchConfig);
} else {
updatedConfig.push({any: [newMatchConfig]});
}
} else {
// Log the key that we don't know what to do with.
core.info(`An unknown config option was under ${label}: ${key}`);
}
});
return updatedConfig;
},
[]
);
if (matchConfigs.length) {
labelMap.set(label, matchConfigs);
}
}
return labelMap;
}
export function toMatchConfig(config: any): BaseMatchConfig {
const changedFilesConfig = toChangedFilesMatchConfig(config);
const branchConfig = toBranchMatchConfig(config);
return {
...changedFilesConfig,
...branchConfig
};
}

6
src/api/index.ts Normal file
View File

@@ -0,0 +1,6 @@
export * from './get-changed-files';
export * from './get-changed-pull-requests';
export * from './get-content';
export * from './get-label-configs';
export * from './set-labels';
export * from './types';

15
src/api/set-labels.ts Normal file
View File

@@ -0,0 +1,15 @@
import * as github from '@actions/github';
import {ClientType} from './types';
export const setLabels = async (
client: ClientType,
prNumber: number,
labels: string[]
) => {
await client.rest.issues.setLabels({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: prNumber,
labels: labels
});
};

2
src/api/types.ts Normal file
View File

@@ -0,0 +1,2 @@
import * as github from '@actions/github';
export type ClientType = ReturnType<typeof github.getOctokit>;

View File

@@ -99,7 +99,8 @@ function printPattern(matcher: Minimatch): string {
export function checkAnyChangedFiles( export function checkAnyChangedFiles(
changedFiles: string[], changedFiles: string[],
globPatternsConfigs: ChangedFilesGlobPatternsConfig[] globPatternsConfigs: ChangedFilesGlobPatternsConfig[],
dot: boolean
): boolean { ): boolean {
core.debug(` checking "changed-files" patterns`); core.debug(` checking "changed-files" patterns`);
@@ -108,7 +109,8 @@ export function checkAnyChangedFiles(
if ( if (
checkIfAnyGlobMatchesAnyFile( checkIfAnyGlobMatchesAnyFile(
changedFiles, changedFiles,
globPatternsConfig.AnyGlobToAnyFile globPatternsConfig.AnyGlobToAnyFile,
dot
) )
) { ) {
core.debug(` "changed-files" matched`); core.debug(` "changed-files" matched`);
@@ -120,7 +122,8 @@ export function checkAnyChangedFiles(
if ( if (
checkIfAnyGlobMatchesAllFiles( checkIfAnyGlobMatchesAllFiles(
changedFiles, changedFiles,
globPatternsConfig.AnyGlobToAllFiles globPatternsConfig.AnyGlobToAllFiles,
dot
) )
) { ) {
core.debug(` "changed-files" matched`); core.debug(` "changed-files" matched`);
@@ -132,7 +135,8 @@ export function checkAnyChangedFiles(
if ( if (
checkIfAllGlobsMatchAnyFile( checkIfAllGlobsMatchAnyFile(
changedFiles, changedFiles,
globPatternsConfig.AllGlobsToAnyFile globPatternsConfig.AllGlobsToAnyFile,
dot
) )
) { ) {
core.debug(` "changed-files" matched`); core.debug(` "changed-files" matched`);
@@ -144,7 +148,8 @@ export function checkAnyChangedFiles(
if ( if (
checkIfAllGlobsMatchAllFiles( checkIfAllGlobsMatchAllFiles(
changedFiles, changedFiles,
globPatternsConfig.AllGlobsToAllFiles globPatternsConfig.AllGlobsToAllFiles,
dot
) )
) { ) {
core.debug(` "changed-files" matched`); core.debug(` "changed-files" matched`);
@@ -159,7 +164,8 @@ export function checkAnyChangedFiles(
export function checkAllChangedFiles( export function checkAllChangedFiles(
changedFiles: string[], changedFiles: string[],
globPatternsConfigs: ChangedFilesGlobPatternsConfig[] globPatternsConfigs: ChangedFilesGlobPatternsConfig[],
dot: boolean
): boolean { ): boolean {
core.debug(` checking "changed-files" patterns`); core.debug(` checking "changed-files" patterns`);
@@ -168,7 +174,8 @@ export function checkAllChangedFiles(
if ( if (
!checkIfAnyGlobMatchesAnyFile( !checkIfAnyGlobMatchesAnyFile(
changedFiles, changedFiles,
globPatternsConfig.AnyGlobToAnyFile globPatternsConfig.AnyGlobToAnyFile,
dot
) )
) { ) {
core.debug(` "changed-files" did not match`); core.debug(` "changed-files" did not match`);
@@ -180,7 +187,8 @@ export function checkAllChangedFiles(
if ( if (
!checkIfAnyGlobMatchesAllFiles( !checkIfAnyGlobMatchesAllFiles(
changedFiles, changedFiles,
globPatternsConfig.AnyGlobToAllFiles globPatternsConfig.AnyGlobToAllFiles,
dot
) )
) { ) {
core.debug(` "changed-files" did not match`); core.debug(` "changed-files" did not match`);
@@ -192,7 +200,8 @@ export function checkAllChangedFiles(
if ( if (
!checkIfAllGlobsMatchAnyFile( !checkIfAllGlobsMatchAnyFile(
changedFiles, changedFiles,
globPatternsConfig.AllGlobsToAnyFile globPatternsConfig.AllGlobsToAnyFile,
dot
) )
) { ) {
core.debug(` "changed-files" did not match`); core.debug(` "changed-files" did not match`);
@@ -204,7 +213,8 @@ export function checkAllChangedFiles(
if ( if (
!checkIfAllGlobsMatchAllFiles( !checkIfAllGlobsMatchAllFiles(
changedFiles, changedFiles,
globPatternsConfig.AllGlobsToAllFiles globPatternsConfig.AllGlobsToAllFiles,
dot
) )
) { ) {
core.debug(` "changed-files" did not match`); core.debug(` "changed-files" did not match`);
@@ -219,10 +229,11 @@ export function checkAllChangedFiles(
export function checkIfAnyGlobMatchesAnyFile( export function checkIfAnyGlobMatchesAnyFile(
changedFiles: string[], changedFiles: string[],
globs: string[] globs: string[],
dot: boolean
): boolean { ): boolean {
core.debug(` checking "AnyGlobToAnyFile" config patterns`); core.debug(` checking "AnyGlobToAnyFile" config patterns`);
const matchers = globs.map(g => new Minimatch(g)); const matchers = globs.map(g => new Minimatch(g, {dot}));
for (const matcher of matchers) { for (const matcher of matchers) {
const matchedFile = changedFiles.find(changedFile => { const matchedFile = changedFiles.find(changedFile => {
@@ -249,10 +260,11 @@ export function checkIfAnyGlobMatchesAnyFile(
export function checkIfAllGlobsMatchAnyFile( export function checkIfAllGlobsMatchAnyFile(
changedFiles: string[], changedFiles: string[],
globs: string[] globs: string[],
dot: boolean
): boolean { ): boolean {
core.debug(` checking "AllGlobsToAnyFile" config patterns`); core.debug(` checking "AllGlobsToAnyFile" config patterns`);
const matchers = globs.map(g => new Minimatch(g)); const matchers = globs.map(g => new Minimatch(g, {dot}));
for (const changedFile of changedFiles) { for (const changedFile of changedFiles) {
const mismatchedGlob = matchers.find(matcher => { const mismatchedGlob = matchers.find(matcher => {
@@ -285,10 +297,11 @@ export function checkIfAllGlobsMatchAnyFile(
export function checkIfAnyGlobMatchesAllFiles( export function checkIfAnyGlobMatchesAllFiles(
changedFiles: string[], changedFiles: string[],
globs: string[] globs: string[],
dot: boolean
): boolean { ): boolean {
core.debug(` checking "AnyGlobToAllFiles" config patterns`); core.debug(` checking "AnyGlobToAllFiles" config patterns`);
const matchers = globs.map(g => new Minimatch(g)); const matchers = globs.map(g => new Minimatch(g, {dot}));
for (const matcher of matchers) { for (const matcher of matchers) {
const mismatchedFile = changedFiles.find(changedFile => { const mismatchedFile = changedFiles.find(changedFile => {
@@ -321,10 +334,11 @@ export function checkIfAnyGlobMatchesAllFiles(
export function checkIfAllGlobsMatchAllFiles( export function checkIfAllGlobsMatchAllFiles(
changedFiles: string[], changedFiles: string[],
globs: string[] globs: string[],
dot: boolean
): boolean { ): boolean {
core.debug(` checking "AllGlobsToAllFiles" config patterns`); core.debug(` checking "AllGlobsToAllFiles" config patterns`);
const matchers = globs.map(g => new Minimatch(g)); const matchers = globs.map(g => new Minimatch(g, {dot}));
for (const changedFile of changedFiles) { for (const changedFile of changedFiles) {
const mismatchedGlob = matchers.find(matcher => { const mismatchedGlob = matchers.find(matcher => {

View File

@@ -0,0 +1,10 @@
import * as core from '@actions/core';
import {getPrNumbers} from './get-pr-numbers';
export const getInputs = () => ({
token: core.getInput('repo-token'),
configPath: core.getInput('configuration-path', {required: true}),
syncLabels: core.getBooleanInput('sync-labels'),
dot: core.getBooleanInput('dot'),
prNumbers: getPrNumbers()
});

View File

@@ -0,0 +1,28 @@
import * as core from '@actions/core';
import * as github from '@actions/github';
const getPrNumberFromContext = () =>
github.context.payload.pull_request?.number;
export const getPrNumbers = (): number[] => {
const prInput = core.getMultilineInput('pr-number');
if (!prInput?.length) {
return [getPrNumberFromContext()].filter(Boolean) as number[];
}
const result: number[] = [];
for (const line of prInput) {
const prNumber = parseInt(line, 10);
if (isNaN(prNumber) && prNumber <= 0) {
core.warning(`'${prNumber}' is not a valid pull request number`);
continue;
}
result.push(prNumber);
}
return result;
};

1
src/get-inputs/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from './get-inputs';

View File

@@ -1,196 +1,110 @@
import * as core from '@actions/core'; import * as core from '@actions/core';
import * as github from '@actions/github'; import * as github from '@actions/github';
import * as yaml from 'js-yaml'; import * as pluginRetry from '@octokit/plugin-retry';
import * as api from './api';
import isEqual from 'lodash.isequal';
import {getInputs} from './get-inputs';
import { import {BaseMatchConfig, MatchConfig} from './api/get-label-configs';
ChangedFilesMatchConfig,
getChangedFiles,
toChangedFilesMatchConfig,
checkAllChangedFiles,
checkAnyChangedFiles
} from './changedFiles';
import {
checkAnyBranch,
checkAllBranch,
toBranchMatchConfig,
BranchMatchConfig
} from './branch';
export type BaseMatchConfig = BranchMatchConfig & ChangedFilesMatchConfig; import {checkAllChangedFiles, checkAnyChangedFiles} from './changedFiles';
export type MatchConfig = { import {checkAnyBranch, checkAllBranch} from './branch';
any?: BaseMatchConfig[];
all?: BaseMatchConfig[];
};
type ClientType = ReturnType<typeof github.getOctokit>; type ClientType = ReturnType<typeof github.getOctokit>;
const ALLOWED_CONFIG_KEYS = ['changed-files', 'head-branch', 'base-branch']; // GitHub Issues cannot have more than 100 labels
const GITHUB_MAX_LABELS = 100;
export async function run() { export const run = () =>
try { labeler().catch(error => {
const token = core.getInput('repo-token'); core.error(error);
const configPath = core.getInput('configuration-path', {required: true}); core.setFailed(error.message);
const syncLabels = core.getBooleanInput('sync-labels'); });
const prNumber = getPrNumber(); async function labeler() {
if (!prNumber) { const {token, configPath, syncLabels, dot, prNumbers} = getInputs();
core.info('Could not get pull request number from context, exiting');
return;
}
const client: ClientType = github.getOctokit(token); if (!prNumbers.length) {
core.warning('Could not get pull request number(s), exiting');
return;
}
const {data: pullRequest} = await client.rest.pulls.get({ const client: ClientType = github.getOctokit(token, {}, pluginRetry.retry);
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: prNumber
});
core.debug(`fetching changed files for pr #${prNumber}`); const pullRequests = api.getPullRequests(client, prNumbers);
const changedFiles: string[] = await getChangedFiles(client, prNumber);
const labelConfigs: Map<string, MatchConfig[]> = await getMatchConfigs( for await (const pullRequest of pullRequests) {
const labelConfigs: Map<string, MatchConfig[]> = await api.getLabelConfigs(
client, client,
configPath configPath
); );
const preexistingLabels = pullRequest.data.labels.map(l => l.name);
const allLabels: Set<string> = new Set<string>(preexistingLabels);
const labels: string[] = [];
const labelsToRemove: string[] = [];
for (const [label, configs] of labelConfigs.entries()) { for (const [label, configs] of labelConfigs.entries()) {
core.debug(`processing ${label}`); core.debug(`processing ${label}`);
if (checkMatchConfigs(changedFiles, configs)) { if (checkMatchConfigs(pullRequest.changedFiles, configs, dot)) {
labels.push(label); allLabels.add(label);
} else if (pullRequest.labels.find(l => l.name === label)) { } else if (syncLabels) {
labelsToRemove.push(label); allLabels.delete(label);
} }
} }
if (labels.length > 0) { const labelsToAdd = [...allLabels].slice(0, GITHUB_MAX_LABELS);
await addLabels(client, prNumber, labels); const excessLabels = [...allLabels].slice(GITHUB_MAX_LABELS);
let newLabels: string[] = [];
try {
if (!isEqual(labelsToAdd, preexistingLabels)) {
await api.setLabels(client, pullRequest.number, labelsToAdd);
newLabels = labelsToAdd.filter(
label => !preexistingLabels.includes(label)
);
}
} catch (error: any) {
if (
error.name !== 'HttpError' ||
error.message !== 'Resource not accessible by integration'
) {
throw error;
}
core.warning(
`The action requires write permission to add labels to pull requests. For more information please refer to the action documentation: https://github.com/actions/labeler#permissions`,
{
title: `${process.env['GITHUB_ACTION_REPOSITORY']} running under '${github.context.eventName}' is misconfigured`
}
);
core.setFailed(error.message);
return;
} }
if (syncLabels && labelsToRemove.length) { core.setOutput('new-labels', newLabels.join(','));
await removeLabels(client, prNumber, labelsToRemove); core.setOutput('all-labels', labelsToAdd.join(','));
}
} catch (error: any) {
core.error(error);
core.setFailed(error.message);
}
}
function getPrNumber(): number | undefined { if (excessLabels.length) {
const pullRequest = github.context.payload.pull_request; core.warning(
if (!pullRequest) { `Maximum of ${GITHUB_MAX_LABELS} labels allowed. Excess labels: ${excessLabels.join(
return undefined; ', '
} )}`,
{title: 'Label limit for a PR exceeded'}
return pullRequest.number;
}
async function getMatchConfigs(
client: ClientType,
configurationPath: string
): Promise<Map<string, MatchConfig[]>> {
const configurationContent: string = await fetchContent(
client,
configurationPath
);
// loads (hopefully) a `{[label:string]: MatchConfig[]}`, but is `any`:
const configObject: any = yaml.load(configurationContent);
// transform `any` => `Map<string,MatchConfig[]>` or throw if yaml is malformed:
return getLabelConfigMapFromObject(configObject);
}
async function fetchContent(
client: ClientType,
repoPath: string
): Promise<string> {
const response: any = await client.rest.repos.getContent({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
path: repoPath,
ref: github.context.sha
});
return Buffer.from(response.data.content, response.data.encoding).toString();
}
export function getLabelConfigMapFromObject(
configObject: any
): Map<string, MatchConfig[]> {
const labelMap: Map<string, MatchConfig[]> = new Map();
for (const label in configObject) {
const configOptions = configObject[label];
if (
!Array.isArray(configOptions) ||
!configOptions.every(opts => typeof opts === 'object')
) {
throw Error(
`found unexpected type for label '${label}' (should be array of config options)`
); );
} }
const matchConfigs = configOptions.reduce<MatchConfig[]>(
(updatedConfig, configValue) => {
if (!configValue) {
return updatedConfig;
}
Object.entries(configValue).forEach(([key, value]) => {
// If the top level `any` or `all` keys are provided then set them, and convert their values to
// our config objects.
if (key === 'any' || key === 'all') {
if (Array.isArray(value)) {
const newConfigs = value.map(toMatchConfig);
updatedConfig.push({[key]: newConfigs});
}
} else if (ALLOWED_CONFIG_KEYS.includes(key)) {
const newMatchConfig = toMatchConfig({[key]: value});
// Find or set the `any` key so that we can add these properties to that rule,
// Or create a new `any` key and add that to our array of configs.
const indexOfAny = updatedConfig.findIndex(mc => !!mc['any']);
if (indexOfAny >= 0) {
updatedConfig[indexOfAny].any?.push(newMatchConfig);
} else {
updatedConfig.push({any: [newMatchConfig]});
}
} else {
// Log the key that we don't know what to do with.
core.info(`An unknown config option was under ${label}: ${key}`);
}
});
return updatedConfig;
},
[]
);
if (matchConfigs.length) {
labelMap.set(label, matchConfigs);
}
} }
return labelMap;
}
export function toMatchConfig(config: any): BaseMatchConfig {
const changedFilesConfig = toChangedFilesMatchConfig(config);
const branchConfig = toBranchMatchConfig(config);
return {
...changedFilesConfig,
...branchConfig
};
} }
export function checkMatchConfigs( export function checkMatchConfigs(
changedFiles: string[], changedFiles: string[],
matchConfigs: MatchConfig[] matchConfigs: MatchConfig[],
dot: boolean
): boolean { ): boolean {
for (const config of matchConfigs) { for (const config of matchConfigs) {
core.debug(` checking config ${JSON.stringify(config)}`); core.debug(` checking config ${JSON.stringify(config)}`);
if (!checkMatch(changedFiles, config)) { if (!checkMatch(changedFiles, config, dot)) {
return false; return false;
} }
} }
@@ -198,20 +112,24 @@ export function checkMatchConfigs(
return true; return true;
} }
function checkMatch(changedFiles: string[], matchConfig: MatchConfig): boolean { function checkMatch(
changedFiles: string[],
matchConfig: MatchConfig,
dot: boolean
): boolean {
if (!Object.keys(matchConfig).length) { if (!Object.keys(matchConfig).length) {
core.debug(` no "any" or "all" patterns to check`); core.debug(` no "any" or "all" patterns to check`);
return false; return false;
} }
if (matchConfig.all) { if (matchConfig.all) {
if (!checkAll(matchConfig.all, changedFiles)) { if (!checkAll(matchConfig.all, changedFiles, dot)) {
return false; return false;
} }
} }
if (matchConfig.any) { if (matchConfig.any) {
if (!checkAny(matchConfig.any, changedFiles)) { if (!checkAny(matchConfig.any, changedFiles, dot)) {
return false; return false;
} }
} }
@@ -222,7 +140,8 @@ function checkMatch(changedFiles: string[], matchConfig: MatchConfig): boolean {
// equivalent to "Array.some()" but expanded for debugging and clarity // equivalent to "Array.some()" but expanded for debugging and clarity
export function checkAny( export function checkAny(
matchConfigs: BaseMatchConfig[], matchConfigs: BaseMatchConfig[],
changedFiles: string[] changedFiles: string[],
dot: boolean
): boolean { ): boolean {
core.debug(` checking "any" patterns`); core.debug(` checking "any" patterns`);
if ( if (
@@ -242,7 +161,7 @@ export function checkAny(
} }
if (matchConfig.changedFiles) { if (matchConfig.changedFiles) {
if (checkAnyChangedFiles(changedFiles, matchConfig.changedFiles)) { if (checkAnyChangedFiles(changedFiles, matchConfig.changedFiles, dot)) {
core.debug(` "any" patterns matched`); core.debug(` "any" patterns matched`);
return true; return true;
} }
@@ -263,7 +182,8 @@ export function checkAny(
// equivalent to "Array.every()" but expanded for debugging and clarity // equivalent to "Array.every()" but expanded for debugging and clarity
export function checkAll( export function checkAll(
matchConfigs: BaseMatchConfig[], matchConfigs: BaseMatchConfig[],
changedFiles: string[] changedFiles: string[],
dot: boolean
): boolean { ): boolean {
core.debug(` checking "all" patterns`); core.debug(` checking "all" patterns`);
if ( if (
@@ -288,7 +208,7 @@ export function checkAll(
return false; return false;
} }
if (!checkAllChangedFiles(changedFiles, matchConfig.changedFiles)) { if (!checkAllChangedFiles(changedFiles, matchConfig.changedFiles, dot)) {
core.debug(` "all" patterns did not match`); core.debug(` "all" patterns did not match`);
return false; return false;
} }
@@ -305,33 +225,3 @@ export function checkAll(
core.debug(` "all" patterns matched all configs`); core.debug(` "all" patterns matched all configs`);
return true; return true;
} }
async function addLabels(
client: ClientType,
prNumber: number,
labels: string[]
) {
await client.rest.issues.addLabels({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: prNumber,
labels: labels
});
}
async function removeLabels(
client: ClientType,
prNumber: number,
labels: string[]
) {
await Promise.all(
labels.map(label =>
client.rest.issues.removeLabel({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: prNumber,
name: label
})
)
);
}

1
src/utils/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from './print-pattern';

View File

@@ -0,0 +1,5 @@
import {Minimatch} from 'minimatch';
export const printPattern = (matcher: Minimatch): string => {
return (matcher.negate ? '!' : '') + matcher.pattern;
};