Compare commits

..

4 Commits

Author SHA1 Message Date
Marko Zivic
0776a67936 Merge pull request #571 from akv-platform/remove-implicit-dependencies
Remove implicit dependencies
2023-05-24 08:35:34 +02:00
Nikolai Laevskii
08382d15cb Move eslint-plugin-node to dev dependencies 2023-05-23 11:57:56 +02:00
Nikolai Laevskii
d1dd326ccc Install eslint-plugin-node 2023-05-23 11:41:49 +02:00
github-actions[bot]
91076827ed Update configuration files 2023-05-23 08:39:00 +00:00
18 changed files with 407 additions and 1899 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: [
{ {

View File

@@ -2,83 +2,58 @@
[![Basic validation](https://github.com/actions/labeler/actions/workflows/basic-validation.yml/badge.svg?branch=main)](https://github.com/actions/labeler/actions/workflows/basic-validation.yml) [![Basic validation](https://github.com/actions/labeler/actions/workflows/basic-validation.yml/badge.svg?branch=main)](https://github.com/actions/labeler/actions/workflows/basic-validation.yml)
Automatically label new pull requests based on the paths of files being changed or the branch name. Automatically label new pull requests based on the paths of files being changed.
## Usage ## Usage
### Create `.github/labeler.yml` ### Create `.github/labeler.yml`
Create a `.github/labeler.yml` file with a list of labels and config options to match and apply the label. Create a `.github/labeler.yml` file with a list of labels and [minimatch](https://github.com/isaacs/minimatch) globs to match to apply the label.
The key is the name of the label in your repository that you want to add (eg: "merge conflict", "needs-updating") and the value is a match object. The key is the name of the label in your repository that you want to add (eg: "merge conflict", "needs-updating") and the value is the path (glob) of the changed files (eg: `src/**/*`, `tests/*.spec.js`) or a match object.
#### Match Object #### Match Object
The match object allows control over the matching options, you can specify the label to be applied based on the files that have changed or the name of either the base branch or the head branch. For the changed files options you provide a [path glob](https://github.com/isaacs/minimatch#minimatch), and for the branches you provide a regexp to match against the branch name. For more control over matching, you can provide a match object instead of a simple path glob. The match object is defined as:
The base match object is defined as:
```yml ```yml
- changed-files: ['list', 'of', 'globs'] - any: ['list', 'of', 'globs']
- base-branch: ['list', 'of', 'regexps'] all: ['list', 'of', 'globs']
- head-branch: ['list', 'of', 'regexps']
``` ```
There are two top level keys of `any` and `all`, which both accept the same config options: One or both fields can be provided for fine-grained matching. Unlike the top-level list, the list of path globs provided to `any` and `all` must ALL match against a path for the label to be applied.
```yml
- any:
- changed-files: ['list', 'of', 'globs']
- base-branch: ['list', 'of', 'regexps']
- head-branch: ['list', 'of', 'regexps']
- all:
- changed-files: ['list', 'of', 'globs']
- base-branch: ['list', 'of', 'regexps']
- head-branch: ['list', 'of', 'regexps']
```
One or all fields can be provided for fine-grained matching.
The fields are defined as follows: The fields are defined as follows:
* `all`: all of the provided options must match in order for the label to be applied * `any`: match ALL globs against ANY changed path
* `any`: if any of the provided options match then a label will be applied * `all`: match ALL globs against ALL changed paths
* `base-branch`: match regexps against the base branch name
* `changed-files`: match glob patterns against the changed paths
* `head-branch`: match regexps against the head branch name
If a base option is provided without a top-level key then it will default to `any`. More specifically, the following two configurations are equivalent: A simple path glob is the equivalent to `any: ['glob']`. More specifically, the following two configurations are equivalent:
```yml ```yml
label1: label1:
- changed-files: example1/* - example1/*
``` ```
and and
```yml ```yml
label1: label1:
- any: - any: ['example1/*']
- changed-files: ['example1/*']
``` ```
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 are `OR`-ed together and individual match rules within an object are `AND`-ed. Combined with `!` negation, you can write complex matching rules.
#### Basic Examples #### Basic Examples
```yml ```yml
# Add 'label1' to any changes within 'example' folder or any subfolders # Add 'label1' to any changes within 'example' folder or any subfolders
label1: label1:
- changed-files: example/**/* - example/**/*
# Add 'label2' to any file changes within 'example2' folder # Add 'label2' to any file changes within 'example2' folder
label2: label2: example2/*
- changed-files: example2/*
# Add label3 to any change to .txt files within the entire repository. Quotation marks are required for the leading asterisk # Add label3 to any change to .txt files within the entire repository. Quotation marks are required for the leading asterisk
label3: label3:
- changed-files: '**/*.txt' - '**/*.txt'
# Add 'label4' to any PR where the head branch name starts with 'example4'
label4:
- head-branch: '^example4'
# Add 'label5' to any PR where the base branch name starts with 'example5'
label5:
- base-branch: '^example5'
``` ```
#### Common Examples #### Common Examples
@@ -86,37 +61,25 @@ label5:
```yml ```yml
# Add 'repo' label to any root file changes # Add 'repo' label to any root file changes
repo: repo:
- changed-files: '*' - '*'
# Add '@domain/core' label to any change within the 'core' package # Add '@domain/core' label to any change within the 'core' package
'@domain/core': '@domain/core':
- changed-files: - package/core/*
- package/core/* - package/core/**/*
- package/core/**/*
# Add 'test' label to any change to *.spec.js files within the source dir # Add 'test' label to any change to *.spec.js files within the source dir
test: test:
- changed-files: src/**/*.spec.js - src/**/*.spec.js
# Add 'source' label to any change to src files within the source dir EXCEPT for the docs sub-folder # Add 'source' label to any change to src files within the source dir EXCEPT for the docs sub-folder
source: source:
- changed-files: - any: ['src/**/*', '!src/docs/*']
- any: ['src/**/*', '!src/docs/*']
# Add 'frontend` label to any change to *.js files as long as the `main.js` hasn't changed # Add 'frontend` label to any change to *.js files as long as the `main.js` hasn't changed
frontend: frontend:
- any: - any: ['src/**/*.js']
- changed-files: ['src/**/*.js'] all: ['!src/main.js']
- all:
- changed-files: ['!src/main.js']
# Add 'feature' label to any PR where the head branch name starts with `feature` or has a `feature` section in the name
feature:
- head-branch: ['^feature', 'feature']
# Add 'release' label to any PR that is opened against the `main` branch
release:
- base-branch: 'main'
``` ```
### Create Workflow ### Create Workflow
@@ -135,7 +98,7 @@ jobs:
pull-requests: write pull-requests: write
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/labeler@v5 - uses: actions/labeler@v4
``` ```
#### Inputs #### Inputs

View File

@@ -1,13 +1,7 @@
export const context = { export const context = {
payload: { payload: {
pull_request: { pull_request: {
number: 123, number: 123
head: {
ref: 'head-branch-name'
},
base: {
ref: 'base-branch-name'
}
} }
}, },
repo: { repo: {

View File

@@ -1,210 +0,0 @@
import {
getBranchName,
checkAnyBranch,
checkAllBranch,
toBranchMatchConfig,
BranchMatchConfig
} from '../src/branch';
import * as github from '@actions/github';
jest.mock('@actions/core');
jest.mock('@actions/github');
describe('getBranchName', () => {
describe('when the pull requests base branch is requested', () => {
it('returns the base branch name', () => {
const result = getBranchName('base');
expect(result).toEqual('base-branch-name');
});
});
describe('when the pull requests head branch is requested', () => {
it('returns the head branch name', () => {
const result = getBranchName('head');
expect(result).toEqual('head-branch-name');
});
});
});
describe('checkAllBranch', () => {
beforeEach(() => {
github.context.payload.pull_request!.head = {
ref: 'test/feature/123'
};
github.context.payload.pull_request!.base = {
ref: 'main'
};
});
describe('when a single pattern is provided', () => {
describe('and the pattern matches the head branch', () => {
it('returns true', () => {
const result = checkAllBranch(['^test'], 'head');
expect(result).toBe(true);
});
});
describe('and the pattern does not match the head branch', () => {
it('returns false', () => {
const result = checkAllBranch(['^feature/'], 'head');
expect(result).toBe(false);
});
});
});
describe('when multiple patterns are provided', () => {
describe('and not all patterns matched', () => {
it('returns false', () => {
const result = checkAllBranch(['^test/', '^feature/'], 'head');
expect(result).toBe(false);
});
});
describe('and all patterns match', () => {
it('returns true', () => {
const result = checkAllBranch(['^test/', '/feature/'], 'head');
expect(result).toBe(true);
});
});
describe('and no patterns match', () => {
it('returns false', () => {
const result = checkAllBranch(['^feature/', '/test$'], 'head');
expect(result).toBe(false);
});
});
});
describe('when the branch to check is specified as the base branch', () => {
describe('and the pattern matches the base branch', () => {
it('returns true', () => {
const result = checkAllBranch(['^main$'], 'base');
expect(result).toBe(true);
});
});
});
});
describe('checkAnyBranch', () => {
beforeEach(() => {
github.context.payload.pull_request!.head = {
ref: 'test/feature/123'
};
github.context.payload.pull_request!.base = {
ref: 'main'
};
});
describe('when a single pattern is provided', () => {
describe('and the pattern matches the head branch', () => {
it('returns true', () => {
const result = checkAnyBranch(['^test'], 'head');
expect(result).toBe(true);
});
});
describe('and the pattern does not match the head branch', () => {
it('returns false', () => {
const result = checkAnyBranch(['^feature/'], 'head');
expect(result).toBe(false);
});
});
});
describe('when multiple patterns are provided', () => {
describe('and at least one pattern matches', () => {
it('returns true', () => {
const result = checkAnyBranch(['^test/', '^feature/'], 'head');
expect(result).toBe(true);
});
});
describe('and all patterns match', () => {
it('returns true', () => {
const result = checkAnyBranch(['^test/', '/feature/'], 'head');
expect(result).toBe(true);
});
});
describe('and no patterns match', () => {
it('returns false', () => {
const result = checkAnyBranch(['^feature/', '/test$'], 'head');
expect(result).toBe(false);
});
});
});
describe('when the branch to check is specified as the base branch', () => {
describe('and the pattern matches the base branch', () => {
it('returns true', () => {
const result = checkAnyBranch(['^main$'], 'base');
expect(result).toBe(true);
});
});
});
});
describe('toBranchMatchConfig', () => {
describe('when there are no branch keys in the config', () => {
const config = {'changed-files': [{any: ['testing']}]};
it('returns an empty object', () => {
const result = toBranchMatchConfig(config);
expect(result).toEqual({});
});
});
describe('when the config contains a head-branch option', () => {
const config = {'head-branch': ['testing']};
it('sets headBranch in the matchConfig', () => {
const result = toBranchMatchConfig(config);
expect(result).toEqual<BranchMatchConfig>({
headBranch: ['testing']
});
});
describe('and the matching option is a string', () => {
const stringConfig = {'head-branch': 'testing'};
it('sets headBranch in the matchConfig', () => {
const result = toBranchMatchConfig(stringConfig);
expect(result).toEqual<BranchMatchConfig>({
headBranch: ['testing']
});
});
});
});
describe('when the config contains a base-branch option', () => {
const config = {'base-branch': ['testing']};
it('sets baseBranch in the matchConfig', () => {
const result = toBranchMatchConfig(config);
expect(result).toEqual<BranchMatchConfig>({
baseBranch: ['testing']
});
});
describe('and the matching option is a string', () => {
const stringConfig = {'base-branch': 'testing'};
it('sets baseBranch in the matchConfig', () => {
const result = toBranchMatchConfig(stringConfig);
expect(result).toEqual<BranchMatchConfig>({
baseBranch: ['testing']
});
});
});
});
describe('when the config contains both a base-branch and head-branch option', () => {
const config = {'base-branch': ['testing'], 'head-branch': ['testing']};
it('sets headBranch and baseBranch in the matchConfig', () => {
const result = toBranchMatchConfig(config);
expect(result).toEqual<BranchMatchConfig>({
baseBranch: ['testing'],
headBranch: ['testing']
});
});
});
});

View File

@@ -1,220 +0,0 @@
import {
ChangedFilesMatchConfig,
checkAllChangedFiles,
checkAnyChangedFiles,
toChangedFilesMatchConfig,
checkIfAnyGlobMatchesAnyFile,
checkIfAllGlobsMatchAnyFile,
checkIfAnyGlobMatchesAllFiles,
checkIfAllGlobsMatchAllFiles
} from '../src/changedFiles';
jest.mock('@actions/core');
jest.mock('@actions/github');
describe('checkAllChangedFiles', () => {
const changedFiles = ['foo.txt', 'bar.txt'];
describe('when all given glob pattern configs matched', () => {
const globPatternsConfigs = [
{AnyGlobToAnyFile: ['foo.txt']},
{AnyGlobToAllFiles: ['*.txt']},
{AllGlobsToAllFiles: ['**']}
];
it('returns true', () => {
const result = checkAllChangedFiles(changedFiles, globPatternsConfigs);
expect(result).toBe(true);
});
});
describe(`when some given glob pattern config did not match`, () => {
const globPatternsConfigs = [
{AnyGlobToAnyFile: ['*.md']},
{AnyGlobToAllFiles: ['*.txt']},
{AllGlobsToAllFiles: ['**']}
];
it('returns false', () => {
const result = checkAllChangedFiles(changedFiles, globPatternsConfigs);
expect(result).toBe(false);
});
});
});
describe('checkAnyChangedFiles', () => {
const changedFiles = ['foo.txt', 'bar.txt'];
describe('when any given glob pattern config matched', () => {
const globPatternsConfigs = [
{AnyGlobToAnyFile: ['*.md']},
{AnyGlobToAllFiles: ['*.txt']}
];
it('returns true', () => {
const result = checkAnyChangedFiles(changedFiles, globPatternsConfigs);
expect(result).toBe(true);
});
});
describe('when none of the given glob pattern configs matched', () => {
const globPatternsConfigs = [
{AnyGlobToAnyFile: ['*.md']},
{AnyGlobToAllFiles: ['!*.txt']}
];
it('returns false', () => {
const result = checkAnyChangedFiles(changedFiles, globPatternsConfigs);
expect(result).toBe(false);
});
});
});
describe('toChangedFilesMatchConfig', () => {
describe(`when there is no 'changed-files' key in the config`, () => {
const config = {'head-branch': 'test'};
it('returns an empty object', () => {
const result = toChangedFilesMatchConfig(config);
expect(result).toEqual<ChangedFilesMatchConfig>({});
});
});
describe(`when there is a 'changed-files' key in the config`, () => {
describe('but the glob pattern config key is not provided', () => {
const config = {'changed-files': ['bar']};
it('throws the error', () => {
expect(() => {
toChangedFilesMatchConfig(config);
}).toThrow(
`The "changed-files" section must have a valid config structure. Please read the action documentation for more information`
);
});
});
describe('but the glob pattern config key is not valid', () => {
const config = {'changed-files': [{NotValidConfigKey: ['bar']}]};
it('throws the error', () => {
expect(() => {
toChangedFilesMatchConfig(config);
}).toThrow(
`Unknown config options were under "changed-files": NotValidConfigKey`
);
});
});
describe('and the glob pattern config key is provided', () => {
describe('and the value is an array of strings', () => {
const config = {'changed-files': [{AnyGlobToAnyFile: ['testing']}]};
it('sets the value in the config object', () => {
const result = toChangedFilesMatchConfig(config);
expect(result).toEqual<ChangedFilesMatchConfig>({
changedFiles: [{AnyGlobToAnyFile: ['testing']}]
});
});
});
describe('and the value is a string', () => {
const config = {'changed-files': [{AnyGlobToAnyFile: 'testing'}]};
it(`sets the string as an array in the config object`, () => {
const result = toChangedFilesMatchConfig(config);
expect(result).toEqual<ChangedFilesMatchConfig>({
changedFiles: [{AnyGlobToAnyFile: ['testing']}]
});
});
});
});
});
});
describe('checkIfAnyGlobMatchesAnyFile', () => {
const changedFiles = ['foo.txt', 'bar.txt'];
describe('when any given glob pattern matched any file', () => {
const globPatterns = ['*.md', 'foo.txt'];
it('returns true', () => {
const result = checkIfAnyGlobMatchesAnyFile(changedFiles, globPatterns);
expect(result).toBe(true);
});
});
describe('when none of the given glob pattern matched any file', () => {
const globPatterns = ['*.md', '!*.txt'];
it('returns false', () => {
const result = checkIfAnyGlobMatchesAnyFile(changedFiles, globPatterns);
expect(result).toBe(false);
});
});
});
describe('checkIfAllGlobsMatchAnyFile', () => {
const changedFiles = ['foo.txt', 'bar.txt'];
describe('when all given glob patterns matched any file', () => {
const globPatterns = ['**/bar.txt', 'bar.txt'];
it('returns true', () => {
const result = checkIfAllGlobsMatchAnyFile(changedFiles, globPatterns);
expect(result).toBe(true);
});
});
describe('when some of the given glob patterns did not match any file', () => {
const globPatterns = ['*.txt', '*.md'];
it('returns false', () => {
const result = checkIfAllGlobsMatchAnyFile(changedFiles, globPatterns);
expect(result).toBe(false);
});
});
});
describe('checkIfAnyGlobMatchesAllFiles', () => {
const changedFiles = ['foo.txt', 'bar.txt'];
describe('when any given glob pattern matched all files', () => {
const globPatterns = ['*.md', '*.txt'];
it('returns true', () => {
const result = checkIfAnyGlobMatchesAllFiles(changedFiles, globPatterns);
expect(result).toBe(true);
});
});
describe('when none of the given glob patterns matched all files', () => {
const globPatterns = ['*.md', 'bar.txt', 'foo.txt'];
it('returns false', () => {
const result = checkIfAnyGlobMatchesAllFiles(changedFiles, globPatterns);
expect(result).toBe(false);
});
});
});
describe('checkIfAllGlobsMatchAllFiles', () => {
const changedFiles = ['foo.txt', 'bar.txt'];
describe('when all given glob patterns matched all files', () => {
const globPatterns = ['*.txt', '**'];
it('returns true', () => {
const result = checkIfAllGlobsMatchAllFiles(changedFiles, globPatterns);
expect(result).toBe(true);
});
});
describe('when some of the given glob patterns did not match all files', () => {
const globPatterns = ['**', 'foo.txt'];
it('returns false', () => {
const result = checkIfAllGlobsMatchAllFiles(changedFiles, globPatterns);
expect(result).toBe(false);
});
});
});

View File

@@ -1,17 +0,0 @@
label1:
- any:
- changed-files:
- AnyGlobToAnyFile: ['glob']
- head-branch: ['regexp']
- base-branch: ['regexp']
- all:
- changed-files:
- AllGlobsToAllFiles: ['glob']
- head-branch: ['regexp']
- base-branch: ['regexp']
label2:
- changed-files:
- AnyGlobToAnyFile: ['glob']
- head-branch: ['regexp']
- base-branch: ['regexp']

View File

@@ -1,8 +0,0 @@
tests:
- any:
- head-branch: ['^tests/', '^test/']
- changed-files:
- AnyGlobToAnyFile: ['tests/**/*']
- all:
- changed-files:
- AllGlobsToAllFiles: ['!tests/requirements.txt']

View File

@@ -1,11 +0,0 @@
test-branch:
- head-branch: '^test/'
feature-branch:
- head-branch: '/feature/'
bug-branch:
- head-branch: '^bug/|fix/'
array-branch:
- head-branch: ['^array/']

View File

@@ -1,3 +0,0 @@
label:
- all:
- unknown: 'this-is-not-supported'

View File

@@ -1,3 +1,2 @@
touched-a-pdf-file: touched-a-pdf-file:
- changed-files: - any: ['*.pdf']
- AnyGlobToAnyFile: ['*.pdf']

View File

@@ -1,13 +1,6 @@
import { import {checkGlobs} from '../src/labeler';
checkMatchConfigs,
MatchConfig,
toMatchConfig,
getLabelConfigMapFromObject,
BaseMatchConfig
} from '../src/labeler';
import * as yaml from 'js-yaml';
import * as core from '@actions/core'; import * as core from '@actions/core';
import * as fs from 'fs';
jest.mock('@actions/core'); jest.mock('@actions/core');
@@ -17,131 +10,20 @@ beforeAll(() => {
}); });
}); });
const loadYaml = (filepath: string) => { const matchConfig = [{any: ['*.txt']}];
const loadedFile = fs.readFileSync(filepath);
const content = Buffer.from(loadedFile).toString();
return yaml.load(content);
};
describe('getLabelConfigMapFromObject', () => { describe('checkGlobs', () => {
const yamlObject = loadYaml('__tests__/fixtures/all_options.yml'); it('returns true when our pattern does match changed files', () => {
const expected = new Map<string, MatchConfig[]>(); const changedFiles = ['foo.txt', 'bar.txt'];
expected.set('label1', [ const result = checkGlobs(changedFiles, matchConfig);
{
any: [
{changedFiles: [{AnyGlobToAnyFile: ['glob']}]},
{baseBranch: undefined, headBranch: ['regexp']},
{baseBranch: ['regexp'], headBranch: undefined}
]
},
{
all: [
{changedFiles: [{AllGlobsToAllFiles: ['glob']}]},
{baseBranch: undefined, headBranch: ['regexp']},
{baseBranch: ['regexp'], headBranch: undefined}
]
}
]);
expected.set('label2', [
{
any: [
{changedFiles: [{AnyGlobToAnyFile: ['glob']}]},
{baseBranch: undefined, headBranch: ['regexp']},
{baseBranch: ['regexp'], headBranch: undefined}
]
}
]);
it('returns a MatchConfig', () => { expect(result).toBeTruthy();
const result = getLabelConfigMapFromObject(yamlObject); });
expect(result).toEqual(expected);
}); it('returns false when our pattern does not match changed files', () => {
}); const changedFiles = ['foo.docx'];
const result = checkGlobs(changedFiles, matchConfig);
describe('toMatchConfig', () => {
describe('when all expected config options are present', () => { expect(result).toBeFalsy();
const config = {
'changed-files': [{AnyGlobToAnyFile: ['testing-files']}],
'head-branch': ['testing-head'],
'base-branch': ['testing-base']
};
const expected: BaseMatchConfig = {
changedFiles: [{AnyGlobToAnyFile: ['testing-files']}],
headBranch: ['testing-head'],
baseBranch: ['testing-base']
};
it('returns a MatchConfig object with all options', () => {
const result = toMatchConfig(config);
expect(result).toEqual(expected);
});
describe('and there are also unexpected options present', () => {
config['test-test'] = 'testing';
it('does not include the unexpected items in the returned MatchConfig object', () => {
const result = toMatchConfig(config);
expect(result).toEqual(expected);
});
});
});
});
describe('checkMatchConfigs', () => {
describe('when a single match config is provided', () => {
const matchConfig: MatchConfig[] = [
{any: [{changedFiles: [{AnyGlobToAnyFile: ['*.txt']}]}]}
];
it('returns true when our pattern does match changed files', () => {
const changedFiles = ['foo.txt', 'bar.txt'];
const result = checkMatchConfigs(changedFiles, matchConfig);
expect(result).toBeTruthy();
});
it('returns false when our pattern does not match changed files', () => {
const changedFiles = ['foo.docx'];
const result = checkMatchConfigs(changedFiles, matchConfig);
expect(result).toBeFalsy();
});
it('returns true when either the branch or changed files patter matches', () => {
const matchConfig: MatchConfig[] = [
{
any: [
{changedFiles: [{AnyGlobToAnyFile: ['*.txt']}]},
{headBranch: ['some-branch']}
]
}
];
const changedFiles = ['foo.txt', 'bar.txt'];
const result = checkMatchConfigs(changedFiles, matchConfig);
expect(result).toBe(true);
});
});
describe('when multiple MatchConfigs are supplied', () => {
const matchConfig: MatchConfig[] = [
{any: [{changedFiles: [{AnyGlobToAnyFile: ['*.txt']}]}]},
{any: [{headBranch: ['some-branch']}]}
];
const changedFiles = ['foo.txt', 'bar.md'];
it('returns false when only one config matches', () => {
const result = checkMatchConfigs(changedFiles, matchConfig);
expect(result).toBe(false);
});
it('returns true when only both config matches', () => {
const matchConfig: MatchConfig[] = [
{any: [{changedFiles: [{AnyGlobToAnyFile: ['*.txt']}]}]},
{any: [{headBranch: ['head-branch']}]}
];
const result = checkMatchConfigs(changedFiles, matchConfig);
expect(result).toBe(true);
});
}); });
}); });

View File

@@ -15,10 +15,7 @@ const paginateMock = jest.spyOn(gh, 'paginate');
const getPullMock = jest.spyOn(gh.rest.pulls, 'get'); const getPullMock = jest.spyOn(gh.rest.pulls, 'get');
const yamlFixtures = { const yamlFixtures = {
'branches.yml': fs.readFileSync('__tests__/fixtures/branches.yml'), 'only_pdfs.yml': fs.readFileSync('__tests__/fixtures/only_pdfs.yml')
'only_pdfs.yml': fs.readFileSync('__tests__/fixtures/only_pdfs.yml'),
'not_supported.yml': fs.readFileSync('__tests__/fixtures/not_supported.yml'),
'any_and_all.yml': fs.readFileSync('__tests__/fixtures/any_and_all.yml')
}; };
afterAll(() => jest.restoreAllMocks()); afterAll(() => jest.restoreAllMocks());
@@ -50,29 +47,16 @@ describe('run', () => {
expect(addLabelsMock).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 () => { it('(with sync-labels: true) it deletes preexisting PR labels that no longer match the glob pattern', async () => {
const mockInput = { const mockInput = {
'repo-token': 'foo', 'repo-token': 'foo',
'configuration-path': 'bar', 'configuration-path': 'bar',
'sync-labels': 'true' 'sync-labels': true
}; };
jest jest
.spyOn(core, 'getInput') .spyOn(core, 'getInput')
.mockImplementation((name: string, ...opts) => mockInput[name]); .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.txt');
@@ -98,17 +82,12 @@ describe('run', () => {
const mockInput = { const mockInput = {
'repo-token': 'foo', 'repo-token': 'foo',
'configuration-path': 'bar', 'configuration-path': 'bar',
'sync-labels': 'false' 'sync-labels': false
}; };
jest jest
.spyOn(core, 'getInput') .spyOn(core, 'getInput')
.mockImplementation((name: string, ...opts) => mockInput[name]); .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.txt');
@@ -123,87 +102,6 @@ describe('run', () => {
expect(addLabelsMock).toHaveBeenCalledTimes(0); expect(addLabelsMock).toHaveBeenCalledTimes(0);
expect(removeLabelMock).toHaveBeenCalledTimes(0); expect(removeLabelMock).toHaveBeenCalledTimes(0);
}); });
it('adds labels based on the branch names that match the regexp pattern', async () => {
github.context.payload.pull_request!.head = {ref: 'test/testing-time'};
usingLabelerConfigYaml('branches.yml');
await run();
expect(addLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 123,
labels: ['test-branch']
});
});
it('adds multiple labels based on branch names that match different regexp patterns', async () => {
github.context.payload.pull_request!.head = {
ref: 'test/feature/123'
};
usingLabelerConfigYaml('branches.yml');
await run();
expect(addLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 123,
labels: ['test-branch', 'feature-branch']
});
});
it('can support multiple branches by batching', async () => {
github.context.payload.pull_request!.head = {ref: 'fix/123'};
usingLabelerConfigYaml('branches.yml');
await run();
expect(addLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 123,
labels: ['bug-branch']
});
});
it('can support multiple branches by providing an array', async () => {
github.context.payload.pull_request!.head = {ref: 'array/123'};
usingLabelerConfigYaml('branches.yml');
await run();
expect(addLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 123,
labels: ['array-branch']
});
});
it('adds a label when matching any and all patterns are provided', async () => {
usingLabelerConfigYaml('any_and_all.yml');
mockGitHubResponseChangedFiles('tests/test.ts');
await run();
expect(addLabelsMock).toHaveBeenCalledTimes(1);
expect(addLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 123,
labels: ['tests']
});
});
it('does not add a label when not all any and all patterns are matched', async () => {
usingLabelerConfigYaml('any_and_all.yml');
mockGitHubResponseChangedFiles('tests/requirements.txt');
await run();
expect(addLabelsMock).toHaveBeenCalledTimes(0);
expect(removeLabelMock).toHaveBeenCalledTimes(0);
});
}); });
function usingLabelerConfigYaml(fixtureName: keyof typeof yamlFixtures): void { function usingLabelerConfigYaml(fixtureName: keyof typeof yamlFixtures): void {

579
dist/index.js vendored
View File

@@ -1,358 +1,6 @@
/******/ (() => { // webpackBootstrap /******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({ /******/ var __webpack_modules__ = ({
/***/ 8045:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkAllBranch = exports.checkAnyBranch = exports.getBranchName = exports.toBranchMatchConfig = void 0;
const core = __importStar(__nccwpck_require__(2186));
const github = __importStar(__nccwpck_require__(5438));
function toBranchMatchConfig(config) {
if (!config['head-branch'] && !config['base-branch']) {
return {};
}
const branchConfig = {
headBranch: config['head-branch'],
baseBranch: config['base-branch']
};
for (const branchName in branchConfig) {
if (typeof branchConfig[branchName] === 'string') {
branchConfig[branchName] = [branchConfig[branchName]];
}
}
return branchConfig;
}
exports.toBranchMatchConfig = toBranchMatchConfig;
function getBranchName(branchBase) {
var _a, _b;
const pullRequest = github.context.payload.pull_request;
if (!pullRequest) {
return undefined;
}
if (branchBase === 'base') {
return (_a = pullRequest.base) === null || _a === void 0 ? void 0 : _a.ref;
}
else {
return (_b = pullRequest.head) === null || _b === void 0 ? void 0 : _b.ref;
}
}
exports.getBranchName = getBranchName;
function checkAnyBranch(regexps, branchBase) {
const branchName = getBranchName(branchBase);
if (!branchName) {
core.debug(` no branch name`);
return false;
}
core.debug(` checking "branch" pattern against ${branchName}`);
const matchers = regexps.map(regexp => new RegExp(regexp));
for (const matcher of matchers) {
if (matchBranchPattern(matcher, branchName)) {
core.debug(` "branch" patterns matched against ${branchName}`);
return true;
}
}
core.debug(` "branch" patterns did not match against ${branchName}`);
return false;
}
exports.checkAnyBranch = checkAnyBranch;
function checkAllBranch(regexps, branchBase) {
const branchName = getBranchName(branchBase);
if (!branchName) {
core.debug(` cannot fetch branch name from the pull request`);
return false;
}
core.debug(` checking "branch" pattern against ${branchName}`);
const matchers = regexps.map(regexp => new RegExp(regexp));
for (const matcher of matchers) {
if (!matchBranchPattern(matcher, branchName)) {
core.debug(` "branch" patterns did not match against ${branchName}`);
return false;
}
}
core.debug(` "branch" patterns matched against ${branchName}`);
return true;
}
exports.checkAllBranch = checkAllBranch;
function matchBranchPattern(matcher, branchName) {
core.debug(` - ${matcher}`);
if (matcher.test(branchName)) {
core.debug(` "branch" pattern matched`);
return true;
}
core.debug(` ${matcher} did not match`);
return false;
}
/***/ }),
/***/ 7358:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkIfAllGlobsMatchAllFiles = exports.checkIfAnyGlobMatchesAllFiles = exports.checkIfAllGlobsMatchAnyFile = exports.checkIfAnyGlobMatchesAnyFile = exports.checkAllChangedFiles = exports.checkAnyChangedFiles = exports.toChangedFilesMatchConfig = exports.getChangedFiles = void 0;
const core = __importStar(__nccwpck_require__(2186));
const github = __importStar(__nccwpck_require__(5438));
const minimatch_1 = __nccwpck_require__(2002);
const ALLOWED_FILES_CONFIG_KEYS = [
'AnyGlobToAnyFile',
'AnyGlobToAllFiles',
'AllGlobsToAnyFile',
'AllGlobsToAllFiles'
];
function getChangedFiles(client, prNumber) {
return __awaiter(this, void 0, void 0, function* () {
const listFilesOptions = client.rest.pulls.listFiles.endpoint.merge({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: prNumber
});
const listFilesResponse = yield client.paginate(listFilesOptions);
const changedFiles = listFilesResponse.map((f) => f.filename);
core.debug('found changed files:');
for (const file of changedFiles) {
core.debug(' ' + file);
}
return changedFiles;
});
}
exports.getChangedFiles = getChangedFiles;
function toChangedFilesMatchConfig(config) {
if (!config['changed-files'] || !config['changed-files'].length) {
return {};
}
const changedFilesConfigs = Array.isArray(config['changed-files'])
? config['changed-files']
: [config['changed-files']];
const validChangedFilesConfigs = [];
changedFilesConfigs.forEach(changedFilesConfig => {
if (!isObject(changedFilesConfig)) {
throw new Error(`The "changed-files" section must have a valid config structure. Please read the action documentation for more information`);
}
const changedFilesConfigKeys = Object.keys(changedFilesConfig);
const invalidKeys = changedFilesConfigKeys.filter(key => !ALLOWED_FILES_CONFIG_KEYS.includes(key));
if (invalidKeys.length) {
throw new Error(`Unknown config options were under "changed-files": ${invalidKeys.join(', ')}`);
}
changedFilesConfigKeys.forEach(key => {
validChangedFilesConfigs.push({
[key]: Array.isArray(changedFilesConfig[key])
? changedFilesConfig[key]
: [changedFilesConfig[key]]
});
});
});
return {
changedFiles: validChangedFilesConfigs
};
}
exports.toChangedFilesMatchConfig = toChangedFilesMatchConfig;
function isObject(obj) {
return obj !== null && typeof obj === 'object' && !Array.isArray(obj);
}
function printPattern(matcher) {
return (matcher.negate ? '!' : '') + matcher.pattern;
}
function checkAnyChangedFiles(changedFiles, globPatternsConfigs) {
core.debug(` checking "changed-files" patterns`);
for (const globPatternsConfig of globPatternsConfigs) {
if (globPatternsConfig.AnyGlobToAnyFile) {
if (checkIfAnyGlobMatchesAnyFile(changedFiles, globPatternsConfig.AnyGlobToAnyFile)) {
core.debug(` "changed-files" matched`);
return true;
}
}
if (globPatternsConfig.AnyGlobToAllFiles) {
if (checkIfAnyGlobMatchesAllFiles(changedFiles, globPatternsConfig.AnyGlobToAllFiles)) {
core.debug(` "changed-files" matched`);
return true;
}
}
if (globPatternsConfig.AllGlobsToAnyFile) {
if (checkIfAllGlobsMatchAnyFile(changedFiles, globPatternsConfig.AllGlobsToAnyFile)) {
core.debug(` "changed-files" matched`);
return true;
}
}
if (globPatternsConfig.AllGlobsToAllFiles) {
if (checkIfAllGlobsMatchAllFiles(changedFiles, globPatternsConfig.AllGlobsToAllFiles)) {
core.debug(` "changed-files" matched`);
return true;
}
}
}
core.debug(` "changed-files" did not match`);
return false;
}
exports.checkAnyChangedFiles = checkAnyChangedFiles;
function checkAllChangedFiles(changedFiles, globPatternsConfigs) {
core.debug(` checking "changed-files" patterns`);
for (const globPatternsConfig of globPatternsConfigs) {
if (globPatternsConfig.AnyGlobToAnyFile) {
if (!checkIfAnyGlobMatchesAnyFile(changedFiles, globPatternsConfig.AnyGlobToAnyFile)) {
core.debug(` "changed-files" did not match`);
return false;
}
}
if (globPatternsConfig.AnyGlobToAllFiles) {
if (!checkIfAnyGlobMatchesAllFiles(changedFiles, globPatternsConfig.AnyGlobToAllFiles)) {
core.debug(` "changed-files" did not match`);
return false;
}
}
if (globPatternsConfig.AllGlobsToAnyFile) {
if (!checkIfAllGlobsMatchAnyFile(changedFiles, globPatternsConfig.AllGlobsToAnyFile)) {
core.debug(` "changed-files" did not match`);
return false;
}
}
if (globPatternsConfig.AllGlobsToAllFiles) {
if (!checkIfAllGlobsMatchAllFiles(changedFiles, globPatternsConfig.AllGlobsToAllFiles)) {
core.debug(` "changed-files" did not match`);
return false;
}
}
}
core.debug(` "changed-files" patterns matched`);
return true;
}
exports.checkAllChangedFiles = checkAllChangedFiles;
function checkIfAnyGlobMatchesAnyFile(changedFiles, globs) {
core.debug(` checking "AnyGlobToAnyFile" config patterns`);
const matchers = globs.map(g => new minimatch_1.Minimatch(g));
for (const matcher of matchers) {
const matchedFile = changedFiles.find(changedFile => {
core.debug(` checking "${printPattern(matcher)}" pattern against ${changedFile}`);
return matcher.match(changedFile);
});
if (matchedFile) {
core.debug(` "${printPattern(matcher)}" pattern matched ${matchedFile}`);
return true;
}
}
core.debug(` none of the patterns matched any of the files`);
return false;
}
exports.checkIfAnyGlobMatchesAnyFile = checkIfAnyGlobMatchesAnyFile;
function checkIfAllGlobsMatchAnyFile(changedFiles, globs) {
core.debug(` checking "AllGlobsToAnyFile" config patterns`);
const matchers = globs.map(g => new minimatch_1.Minimatch(g));
for (const changedFile of changedFiles) {
const mismatchedGlob = matchers.find(matcher => {
core.debug(` checking "${printPattern(matcher)}" pattern against ${changedFile}`);
return !matcher.match(changedFile);
});
if (mismatchedGlob) {
core.debug(` "${printPattern(mismatchedGlob)}" pattern did not match ${changedFile}`);
continue;
}
core.debug(` all patterns matched ${changedFile}`);
return true;
}
core.debug(` none of the files matched all patterns`);
return false;
}
exports.checkIfAllGlobsMatchAnyFile = checkIfAllGlobsMatchAnyFile;
function checkIfAnyGlobMatchesAllFiles(changedFiles, globs) {
core.debug(` checking "AnyGlobToAllFiles" config patterns`);
const matchers = globs.map(g => new minimatch_1.Minimatch(g));
for (const matcher of matchers) {
const mismatchedFile = changedFiles.find(changedFile => {
core.debug(` checking "${printPattern(matcher)}" pattern against ${changedFile}`);
return !matcher.match(changedFile);
});
if (mismatchedFile) {
core.debug(` "${printPattern(matcher)}" pattern did not match ${mismatchedFile}`);
continue;
}
core.debug(` "${printPattern(matcher)}" pattern matched all files`);
return true;
}
core.debug(` none of the patterns matched all files`);
return false;
}
exports.checkIfAnyGlobMatchesAllFiles = checkIfAnyGlobMatchesAllFiles;
function checkIfAllGlobsMatchAllFiles(changedFiles, globs) {
core.debug(` checking "AllGlobsToAllFiles" config patterns`);
const matchers = globs.map(g => new minimatch_1.Minimatch(g));
for (const changedFile of changedFiles) {
const mismatchedGlob = matchers.find(matcher => {
core.debug(` checking "${printPattern(matcher)}" pattern against ${changedFile}`);
return !matcher.match(changedFile);
});
if (mismatchedGlob) {
core.debug(` "${printPattern(mismatchedGlob)}" pattern did not match ${changedFile}`);
return false;
}
}
core.debug(` all patterns matched all files`);
return true;
}
exports.checkIfAllGlobsMatchAllFiles = checkIfAllGlobsMatchAllFiles;
/***/ }),
/***/ 5272: /***/ 5272:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
@@ -391,19 +39,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}); });
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkAll = exports.checkAny = exports.checkMatchConfigs = exports.toMatchConfig = exports.getLabelConfigMapFromObject = exports.run = void 0; exports.checkGlobs = exports.run = void 0;
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const github = __importStar(__nccwpck_require__(5438)); const github = __importStar(__nccwpck_require__(5438));
const yaml = __importStar(__nccwpck_require__(1917)); const yaml = __importStar(__nccwpck_require__(1917));
const changedFiles_1 = __nccwpck_require__(7358); const minimatch_1 = __nccwpck_require__(2002);
const branch_1 = __nccwpck_require__(8045);
const ALLOWED_CONFIG_KEYS = ['changed-files', 'head-branch', 'base-branch'];
function run() { function run() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try { try {
const token = core.getInput('repo-token'); const token = core.getInput('repo-token');
const configPath = core.getInput('configuration-path', { required: true }); const configPath = core.getInput('configuration-path', { required: true });
const syncLabels = core.getBooleanInput('sync-labels'); const syncLabels = !!core.getInput('sync-labels', { required: false });
const prNumber = getPrNumber(); const prNumber = getPrNumber();
if (!prNumber) { if (!prNumber) {
core.info('Could not get pull request number from context, exiting'); core.info('Could not get pull request number from context, exiting');
@@ -416,13 +62,13 @@ function run() {
pull_number: prNumber pull_number: prNumber
}); });
core.debug(`fetching changed files for pr #${prNumber}`); core.debug(`fetching changed files for pr #${prNumber}`);
const changedFiles = yield (0, changedFiles_1.getChangedFiles)(client, prNumber); const changedFiles = yield getChangedFiles(client, prNumber);
const labelConfigs = yield getMatchConfigs(client, configPath); const labelGlobs = yield getLabelGlobs(client, configPath);
const labels = []; const labels = [];
const labelsToRemove = []; const labelsToRemove = [];
for (const [label, configs] of labelConfigs.entries()) { for (const [label, globs] of labelGlobs.entries()) {
core.debug(`processing ${label}`); core.debug(`processing ${label}`);
if (checkMatchConfigs(changedFiles, configs)) { if (checkGlobs(changedFiles, globs)) {
labels.push(label); labels.push(label);
} }
else if (pullRequest.labels.find(l => l.name === label)) { else if (pullRequest.labels.find(l => l.name === label)) {
@@ -450,13 +96,29 @@ function getPrNumber() {
} }
return pullRequest.number; return pullRequest.number;
} }
function getMatchConfigs(client, configurationPath) { function getChangedFiles(client, prNumber) {
return __awaiter(this, void 0, void 0, function* () {
const listFilesOptions = client.rest.pulls.listFiles.endpoint.merge({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: prNumber
});
const listFilesResponse = yield client.paginate(listFilesOptions);
const changedFiles = listFilesResponse.map((f) => f.filename);
core.debug('found changed files:');
for (const file of changedFiles) {
core.debug(' ' + file);
}
return changedFiles;
});
}
function getLabelGlobs(client, configurationPath) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const configurationContent = yield fetchContent(client, configurationPath); const configurationContent = yield fetchContent(client, configurationPath);
// loads (hopefully) a `{[label:string]: MatchConfig[]}`, but is `any`: // loads (hopefully) a `{[label:string]: string | StringOrMatchConfig[]}`, but is `any`:
const configObject = yaml.load(configurationContent); const configObject = yaml.load(configurationContent);
// transform `any` => `Map<string,MatchConfig[]>` or throw if yaml is malformed: // transform `any` => `Map<string,StringOrMatchConfig[]>` or throw if yaml is malformed:
return getLabelConfigMapFromObject(configObject); return getLabelGlobMapFromObject(configObject);
}); });
} }
function fetchContent(client, repoPath) { function fetchContent(client, repoPath) {
@@ -470,155 +132,94 @@ function fetchContent(client, repoPath) {
return Buffer.from(response.data.content, response.data.encoding).toString(); return Buffer.from(response.data.content, response.data.encoding).toString();
}); });
} }
function getLabelConfigMapFromObject(configObject) { function getLabelGlobMapFromObject(configObject) {
const labelMap = new Map(); const labelGlobs = new Map();
for (const label in configObject) { for (const label in configObject) {
const configOptions = configObject[label]; if (typeof configObject[label] === 'string') {
if (!Array.isArray(configOptions) || labelGlobs.set(label, [configObject[label]]);
!configOptions.every(opts => typeof opts === 'object')) {
throw Error(`found unexpected type for label '${label}' (should be array of config options)`);
} }
const matchConfigs = configOptions.reduce((updatedConfig, configValue) => { else if (configObject[label] instanceof Array) {
if (!configValue) { labelGlobs.set(label, configObject[label]);
return updatedConfig; }
} else {
Object.entries(configValue).forEach(([key, value]) => { throw Error(`found unexpected type for label ${label} (should be string or array of globs)`);
var _a;
// 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) {
(_a = updatedConfig[indexOfAny].any) === null || _a === void 0 ? void 0 : _a.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; return labelGlobs;
} }
exports.getLabelConfigMapFromObject = getLabelConfigMapFromObject;
function toMatchConfig(config) { function toMatchConfig(config) {
const changedFilesConfig = (0, changedFiles_1.toChangedFilesMatchConfig)(config); if (typeof config === 'string') {
const branchConfig = (0, branch_1.toBranchMatchConfig)(config); return {
return Object.assign(Object.assign({}, changedFilesConfig), branchConfig); any: [config]
};
}
return config;
} }
exports.toMatchConfig = toMatchConfig; function printPattern(matcher) {
function checkMatchConfigs(changedFiles, matchConfigs) { return (matcher.negate ? '!' : '') + matcher.pattern;
for (const config of matchConfigs) {
core.debug(` checking config ${JSON.stringify(config)}`);
if (!checkMatch(changedFiles, config)) {
return false;
}
}
return true;
} }
exports.checkMatchConfigs = checkMatchConfigs; function checkGlobs(changedFiles, globs) {
function checkMatch(changedFiles, matchConfig) { for (const glob of globs) {
if (!Object.keys(matchConfig).length) { core.debug(` checking pattern ${JSON.stringify(glob)}`);
core.debug(` no "any" or "all" patterns to check`); const matchConfig = toMatchConfig(glob);
return false; if (checkMatch(changedFiles, matchConfig)) {
return true;
}
} }
if (matchConfig.all) { return false;
if (!checkAll(matchConfig.all, changedFiles)) { }
return false; exports.checkGlobs = checkGlobs;
} function isMatch(changedFile, matchers) {
} core.debug(` matching patterns against file ${changedFile}`);
if (matchConfig.any) { for (const matcher of matchers) {
if (!checkAny(matchConfig.any, changedFiles)) { core.debug(` - ${printPattern(matcher)}`);
if (!matcher.match(changedFile)) {
core.debug(` ${printPattern(matcher)} did not match`);
return false; return false;
} }
} }
core.debug(` all patterns matched`);
return true; return true;
} }
// equivalent to "Array.some()" but expanded for debugging and clarity // equivalent to "Array.some()" but expanded for debugging and clarity
function checkAny(matchConfigs, changedFiles) { function checkAny(changedFiles, globs) {
const matchers = globs.map(g => new minimatch_1.Minimatch(g));
core.debug(` checking "any" patterns`); core.debug(` checking "any" patterns`);
if (!matchConfigs.length || for (const changedFile of changedFiles) {
!matchConfigs.some(configOption => Object.keys(configOption).length)) { if (isMatch(changedFile, matchers)) {
core.debug(` no "any" patterns to check`); core.debug(` "any" patterns matched against ${changedFile}`);
return false; return true;
}
for (const matchConfig of matchConfigs) {
if (matchConfig.baseBranch) {
if ((0, branch_1.checkAnyBranch)(matchConfig.baseBranch, 'base')) {
core.debug(` "any" patterns matched`);
return true;
}
}
if (matchConfig.changedFiles) {
if ((0, changedFiles_1.checkAnyChangedFiles)(changedFiles, matchConfig.changedFiles)) {
core.debug(` "any" patterns matched`);
return true;
}
}
if (matchConfig.headBranch) {
if ((0, branch_1.checkAnyBranch)(matchConfig.headBranch, 'head')) {
core.debug(` "any" patterns matched`);
return true;
}
} }
} }
core.debug(` "any" patterns did not match any configs`); core.debug(` "any" patterns did not match any files`);
return false; return false;
} }
exports.checkAny = checkAny;
// equivalent to "Array.every()" but expanded for debugging and clarity // equivalent to "Array.every()" but expanded for debugging and clarity
function checkAll(matchConfigs, changedFiles) { function checkAll(changedFiles, globs) {
core.debug(` checking "all" patterns`); const matchers = globs.map(g => new minimatch_1.Minimatch(g));
if (!matchConfigs.length || core.debug(` checking "all" patterns`);
!matchConfigs.some(configOption => Object.keys(configOption).length)) { for (const changedFile of changedFiles) {
core.debug(` no "all" patterns to check`); if (!isMatch(changedFile, matchers)) {
return false; core.debug(` "all" patterns did not match against ${changedFile}`);
} return false;
for (const matchConfig of matchConfigs) { }
if (matchConfig.baseBranch) { }
if (!(0, branch_1.checkAllBranch)(matchConfig.baseBranch, 'base')) { core.debug(` "all" patterns matched all files`);
core.debug(` "all" patterns did not match`); return true;
return false; }
} function checkMatch(changedFiles, matchConfig) {
} if (matchConfig.all !== undefined) {
if (matchConfig.changedFiles) { if (!checkAll(changedFiles, matchConfig.all)) {
if (!changedFiles.length) { return false;
core.debug(` no files to check "changed-files" patterns against`); }
return false; }
} if (matchConfig.any !== undefined) {
if (!(0, changedFiles_1.checkAllChangedFiles)(changedFiles, matchConfig.changedFiles)) { if (!checkAny(changedFiles, matchConfig.any)) {
core.debug(` "all" patterns did not match`); return false;
return false;
}
}
if (matchConfig.headBranch) {
if (!(0, branch_1.checkAllBranch)(matchConfig.headBranch, 'head')) {
core.debug(` "all" patterns did not match`);
return false;
}
} }
} }
core.debug(` "all" patterns matched all configs`);
return true; return true;
} }
exports.checkAll = checkAll;
function addLabels(client, prNumber, labels) { function addLabels(client, prNumber, labels) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
yield client.rest.issues.addLabels({ yield client.rest.issues.addLabels({

166
package-lock.json generated
View File

@@ -25,6 +25,7 @@
"eslint": "^8.41.0", "eslint": "^8.41.0",
"eslint-config-prettier": "^8.8.0", "eslint-config-prettier": "^8.8.0",
"eslint-plugin-jest": "^27.2.1", "eslint-plugin-jest": "^27.2.1",
"eslint-plugin-node": "^11.1.0",
"jest": "^27.5.1", "jest": "^27.5.1",
"prettier": "^2.8.8", "prettier": "^2.8.8",
"ts-jest": "^27.1.3", "ts-jest": "^27.1.3",
@@ -2521,6 +2522,25 @@
"eslint": ">=7.0.0" "eslint": ">=7.0.0"
} }
}, },
"node_modules/eslint-plugin-es": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/eslint-plugin-es/-/eslint-plugin-es-3.0.1.tgz",
"integrity": "sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ==",
"dev": true,
"dependencies": {
"eslint-utils": "^2.0.0",
"regexpp": "^3.0.0"
},
"engines": {
"node": ">=8.10.0"
},
"funding": {
"url": "https://github.com/sponsors/mysticatea"
},
"peerDependencies": {
"eslint": ">=4.19.1"
}
},
"node_modules/eslint-plugin-jest": { "node_modules/eslint-plugin-jest": {
"version": "27.2.1", "version": "27.2.1",
"resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-27.2.1.tgz", "resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-27.2.1.tgz",
@@ -2545,6 +2565,48 @@
} }
} }
}, },
"node_modules/eslint-plugin-node": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz",
"integrity": "sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g==",
"dev": true,
"dependencies": {
"eslint-plugin-es": "^3.0.0",
"eslint-utils": "^2.0.0",
"ignore": "^5.1.1",
"minimatch": "^3.0.4",
"resolve": "^1.10.1",
"semver": "^6.1.0"
},
"engines": {
"node": ">=8.10.0"
},
"peerDependencies": {
"eslint": ">=5.16.0"
}
},
"node_modules/eslint-plugin-node/node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/eslint-plugin-node/node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"dev": true,
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/eslint-scope": { "node_modules/eslint-scope": {
"version": "5.1.1", "version": "5.1.1",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz",
@@ -2567,6 +2629,30 @@
"node": ">=4.0" "node": ">=4.0"
} }
}, },
"node_modules/eslint-utils": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz",
"integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==",
"dev": true,
"dependencies": {
"eslint-visitor-keys": "^1.1.0"
},
"engines": {
"node": ">=6"
},
"funding": {
"url": "https://github.com/sponsors/mysticatea"
}
},
"node_modules/eslint-utils/node_modules/eslint-visitor-keys": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz",
"integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==",
"dev": true,
"engines": {
"node": ">=4"
}
},
"node_modules/eslint-visitor-keys": { "node_modules/eslint-visitor-keys": {
"version": "3.4.1", "version": "3.4.1",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.1.tgz", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.1.tgz",
@@ -4858,6 +4944,18 @@
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true "dev": true
}, },
"node_modules/regexpp": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz",
"integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==",
"dev": true,
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/mysticatea"
}
},
"node_modules/require-directory": { "node_modules/require-directory": {
"version": "2.1.1", "version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
@@ -7810,6 +7908,16 @@
"dev": true, "dev": true,
"requires": {} "requires": {}
}, },
"eslint-plugin-es": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/eslint-plugin-es/-/eslint-plugin-es-3.0.1.tgz",
"integrity": "sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ==",
"dev": true,
"requires": {
"eslint-utils": "^2.0.0",
"regexpp": "^3.0.0"
}
},
"eslint-plugin-jest": { "eslint-plugin-jest": {
"version": "27.2.1", "version": "27.2.1",
"resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-27.2.1.tgz", "resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-27.2.1.tgz",
@@ -7819,6 +7927,41 @@
"@typescript-eslint/utils": "^5.10.0" "@typescript-eslint/utils": "^5.10.0"
} }
}, },
"eslint-plugin-node": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz",
"integrity": "sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g==",
"dev": true,
"requires": {
"eslint-plugin-es": "^3.0.0",
"eslint-utils": "^2.0.0",
"ignore": "^5.1.1",
"minimatch": "^3.0.4",
"resolve": "^1.10.1",
"semver": "^6.1.0"
},
"dependencies": {
"brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"dev": true,
"requires": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"dev": true,
"requires": {
"brace-expansion": "^1.1.7"
}
}
}
},
"eslint-scope": { "eslint-scope": {
"version": "5.1.1", "version": "5.1.1",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz",
@@ -7837,6 +7980,23 @@
} }
} }
}, },
"eslint-utils": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz",
"integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==",
"dev": true,
"requires": {
"eslint-visitor-keys": "^1.1.0"
},
"dependencies": {
"eslint-visitor-keys": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz",
"integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==",
"dev": true
}
}
},
"eslint-visitor-keys": { "eslint-visitor-keys": {
"version": "3.4.1", "version": "3.4.1",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.1.tgz", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.1.tgz",
@@ -9434,6 +9594,12 @@
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true "dev": true
}, },
"regexpp": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz",
"integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==",
"dev": true
},
"require-directory": { "require-directory": {
"version": "2.1.1", "version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",

View File

@@ -40,6 +40,7 @@
"eslint": "^8.41.0", "eslint": "^8.41.0",
"eslint-config-prettier": "^8.8.0", "eslint-config-prettier": "^8.8.0",
"eslint-plugin-jest": "^27.2.1", "eslint-plugin-jest": "^27.2.1",
"eslint-plugin-node": "^11.1.0",
"jest": "^27.5.1", "jest": "^27.5.1",
"prettier": "^2.8.8", "prettier": "^2.8.8",
"ts-jest": "^27.1.3", "ts-jest": "^27.1.3",

View File

@@ -1,98 +0,0 @@
import * as core from '@actions/core';
import * as github from '@actions/github';
export interface BranchMatchConfig {
headBranch?: string[];
baseBranch?: string[];
}
type BranchBase = 'base' | 'head';
export function toBranchMatchConfig(config: any): BranchMatchConfig {
if (!config['head-branch'] && !config['base-branch']) {
return {};
}
const branchConfig = {
headBranch: config['head-branch'],
baseBranch: config['base-branch']
};
for (const branchName in branchConfig) {
if (typeof branchConfig[branchName] === 'string') {
branchConfig[branchName] = [branchConfig[branchName]];
}
}
return branchConfig;
}
export function getBranchName(branchBase: BranchBase): string | undefined {
const pullRequest = github.context.payload.pull_request;
if (!pullRequest) {
return undefined;
}
if (branchBase === 'base') {
return pullRequest.base?.ref;
} else {
return pullRequest.head?.ref;
}
}
export function checkAnyBranch(
regexps: string[],
branchBase: BranchBase
): boolean {
const branchName = getBranchName(branchBase);
if (!branchName) {
core.debug(` no branch name`);
return false;
}
core.debug(` checking "branch" pattern against ${branchName}`);
const matchers = regexps.map(regexp => new RegExp(regexp));
for (const matcher of matchers) {
if (matchBranchPattern(matcher, branchName)) {
core.debug(` "branch" patterns matched against ${branchName}`);
return true;
}
}
core.debug(` "branch" patterns did not match against ${branchName}`);
return false;
}
export function checkAllBranch(
regexps: string[],
branchBase: BranchBase
): boolean {
const branchName = getBranchName(branchBase);
if (!branchName) {
core.debug(` cannot fetch branch name from the pull request`);
return false;
}
core.debug(` checking "branch" pattern against ${branchName}`);
const matchers = regexps.map(regexp => new RegExp(regexp));
for (const matcher of matchers) {
if (!matchBranchPattern(matcher, branchName)) {
core.debug(` "branch" patterns did not match against ${branchName}`);
return false;
}
}
core.debug(` "branch" patterns matched against ${branchName}`);
return true;
}
function matchBranchPattern(matcher: RegExp, branchName: string): boolean {
core.debug(` - ${matcher}`);
if (matcher.test(branchName)) {
core.debug(` "branch" pattern matched`);
return true;
}
core.debug(` ${matcher} did not match`);
return false;
}

View File

@@ -1,353 +0,0 @@
import * as core from '@actions/core';
import * as github from '@actions/github';
import {Minimatch} from 'minimatch';
export interface ChangedFilesMatchConfig {
changedFiles?: ChangedFilesGlobPatternsConfig[];
}
interface ChangedFilesGlobPatternsConfig {
AnyGlobToAnyFile?: string[];
AnyGlobToAllFiles?: string[];
AllGlobsToAnyFile?: string[];
AllGlobsToAllFiles?: string[];
}
type ClientType = ReturnType<typeof github.getOctokit>;
const ALLOWED_FILES_CONFIG_KEYS = [
'AnyGlobToAnyFile',
'AnyGlobToAllFiles',
'AllGlobsToAnyFile',
'AllGlobsToAllFiles'
];
export async function getChangedFiles(
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;
}
export function toChangedFilesMatchConfig(
config: any
): ChangedFilesMatchConfig {
if (!config['changed-files'] || !config['changed-files'].length) {
return {};
}
const changedFilesConfigs = Array.isArray(config['changed-files'])
? config['changed-files']
: [config['changed-files']];
const validChangedFilesConfigs: ChangedFilesGlobPatternsConfig[] = [];
changedFilesConfigs.forEach(changedFilesConfig => {
if (!isObject(changedFilesConfig)) {
throw new Error(
`The "changed-files" section must have a valid config structure. Please read the action documentation for more information`
);
}
const changedFilesConfigKeys = Object.keys(changedFilesConfig);
const invalidKeys = changedFilesConfigKeys.filter(
key => !ALLOWED_FILES_CONFIG_KEYS.includes(key)
);
if (invalidKeys.length) {
throw new Error(
`Unknown config options were under "changed-files": ${invalidKeys.join(
', '
)}`
);
}
changedFilesConfigKeys.forEach(key => {
validChangedFilesConfigs.push({
[key]: Array.isArray(changedFilesConfig[key])
? changedFilesConfig[key]
: [changedFilesConfig[key]]
});
});
});
return {
changedFiles: validChangedFilesConfigs
};
}
function isObject(obj: unknown): obj is object {
return obj !== null && typeof obj === 'object' && !Array.isArray(obj);
}
function printPattern(matcher: Minimatch): string {
return (matcher.negate ? '!' : '') + matcher.pattern;
}
export function checkAnyChangedFiles(
changedFiles: string[],
globPatternsConfigs: ChangedFilesGlobPatternsConfig[]
): boolean {
core.debug(` checking "changed-files" patterns`);
for (const globPatternsConfig of globPatternsConfigs) {
if (globPatternsConfig.AnyGlobToAnyFile) {
if (
checkIfAnyGlobMatchesAnyFile(
changedFiles,
globPatternsConfig.AnyGlobToAnyFile
)
) {
core.debug(` "changed-files" matched`);
return true;
}
}
if (globPatternsConfig.AnyGlobToAllFiles) {
if (
checkIfAnyGlobMatchesAllFiles(
changedFiles,
globPatternsConfig.AnyGlobToAllFiles
)
) {
core.debug(` "changed-files" matched`);
return true;
}
}
if (globPatternsConfig.AllGlobsToAnyFile) {
if (
checkIfAllGlobsMatchAnyFile(
changedFiles,
globPatternsConfig.AllGlobsToAnyFile
)
) {
core.debug(` "changed-files" matched`);
return true;
}
}
if (globPatternsConfig.AllGlobsToAllFiles) {
if (
checkIfAllGlobsMatchAllFiles(
changedFiles,
globPatternsConfig.AllGlobsToAllFiles
)
) {
core.debug(` "changed-files" matched`);
return true;
}
}
}
core.debug(` "changed-files" did not match`);
return false;
}
export function checkAllChangedFiles(
changedFiles: string[],
globPatternsConfigs: ChangedFilesGlobPatternsConfig[]
): boolean {
core.debug(` checking "changed-files" patterns`);
for (const globPatternsConfig of globPatternsConfigs) {
if (globPatternsConfig.AnyGlobToAnyFile) {
if (
!checkIfAnyGlobMatchesAnyFile(
changedFiles,
globPatternsConfig.AnyGlobToAnyFile
)
) {
core.debug(` "changed-files" did not match`);
return false;
}
}
if (globPatternsConfig.AnyGlobToAllFiles) {
if (
!checkIfAnyGlobMatchesAllFiles(
changedFiles,
globPatternsConfig.AnyGlobToAllFiles
)
) {
core.debug(` "changed-files" did not match`);
return false;
}
}
if (globPatternsConfig.AllGlobsToAnyFile) {
if (
!checkIfAllGlobsMatchAnyFile(
changedFiles,
globPatternsConfig.AllGlobsToAnyFile
)
) {
core.debug(` "changed-files" did not match`);
return false;
}
}
if (globPatternsConfig.AllGlobsToAllFiles) {
if (
!checkIfAllGlobsMatchAllFiles(
changedFiles,
globPatternsConfig.AllGlobsToAllFiles
)
) {
core.debug(` "changed-files" did not match`);
return false;
}
}
}
core.debug(` "changed-files" patterns matched`);
return true;
}
export function checkIfAnyGlobMatchesAnyFile(
changedFiles: string[],
globs: string[]
): boolean {
core.debug(` checking "AnyGlobToAnyFile" config patterns`);
const matchers = globs.map(g => new Minimatch(g));
for (const matcher of matchers) {
const matchedFile = changedFiles.find(changedFile => {
core.debug(
` checking "${printPattern(
matcher
)}" pattern against ${changedFile}`
);
return matcher.match(changedFile);
});
if (matchedFile) {
core.debug(
` "${printPattern(matcher)}" pattern matched ${matchedFile}`
);
return true;
}
}
core.debug(` none of the patterns matched any of the files`);
return false;
}
export function checkIfAllGlobsMatchAnyFile(
changedFiles: string[],
globs: string[]
): boolean {
core.debug(` checking "AllGlobsToAnyFile" config patterns`);
const matchers = globs.map(g => new Minimatch(g));
for (const changedFile of changedFiles) {
const mismatchedGlob = matchers.find(matcher => {
core.debug(
` checking "${printPattern(
matcher
)}" pattern against ${changedFile}`
);
return !matcher.match(changedFile);
});
if (mismatchedGlob) {
core.debug(
` "${printPattern(
mismatchedGlob
)}" pattern did not match ${changedFile}`
);
continue;
}
core.debug(` all patterns matched ${changedFile}`);
return true;
}
core.debug(` none of the files matched all patterns`);
return false;
}
export function checkIfAnyGlobMatchesAllFiles(
changedFiles: string[],
globs: string[]
): boolean {
core.debug(` checking "AnyGlobToAllFiles" config patterns`);
const matchers = globs.map(g => new Minimatch(g));
for (const matcher of matchers) {
const mismatchedFile = changedFiles.find(changedFile => {
core.debug(
` checking "${printPattern(
matcher
)}" pattern against ${changedFile}`
);
return !matcher.match(changedFile);
});
if (mismatchedFile) {
core.debug(
` "${printPattern(
matcher
)}" pattern did not match ${mismatchedFile}`
);
continue;
}
core.debug(` "${printPattern(matcher)}" pattern matched all files`);
return true;
}
core.debug(` none of the patterns matched all files`);
return false;
}
export function checkIfAllGlobsMatchAllFiles(
changedFiles: string[],
globs: string[]
): boolean {
core.debug(` checking "AllGlobsToAllFiles" config patterns`);
const matchers = globs.map(g => new Minimatch(g));
for (const changedFile of changedFiles) {
const mismatchedGlob = matchers.find(matcher => {
core.debug(
` checking "${printPattern(
matcher
)}" pattern against ${changedFile}`
);
return !matcher.match(changedFile);
});
if (mismatchedGlob) {
core.debug(
` "${printPattern(
mismatchedGlob
)}" pattern did not match ${changedFile}`
);
return false;
}
}
core.debug(` all patterns matched all files`);
return true;
}

View File

@@ -1,37 +1,21 @@
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 yaml from 'js-yaml';
import {Minimatch} from 'minimatch';
import { interface MatchConfig {
ChangedFilesMatchConfig, all?: string[];
getChangedFiles, any?: string[];
toChangedFilesMatchConfig, }
checkAllChangedFiles,
checkAnyChangedFiles
} from './changedFiles';
import {
checkAnyBranch,
checkAllBranch,
toBranchMatchConfig,
BranchMatchConfig
} from './branch';
export type BaseMatchConfig = BranchMatchConfig & ChangedFilesMatchConfig;
export type MatchConfig = {
any?: BaseMatchConfig[];
all?: BaseMatchConfig[];
};
type StringOrMatchConfig = string | MatchConfig;
type ClientType = ReturnType<typeof github.getOctokit>; type ClientType = ReturnType<typeof github.getOctokit>;
const ALLOWED_CONFIG_KEYS = ['changed-files', 'head-branch', 'base-branch'];
export async function run() { export async function run() {
try { try {
const token = core.getInput('repo-token'); const token = core.getInput('repo-token');
const configPath = core.getInput('configuration-path', {required: true}); const configPath = core.getInput('configuration-path', {required: true});
const syncLabels = core.getBooleanInput('sync-labels'); const syncLabels = !!core.getInput('sync-labels', {required: false});
const prNumber = getPrNumber(); const prNumber = getPrNumber();
if (!prNumber) { if (!prNumber) {
@@ -49,16 +33,16 @@ export async function run() {
core.debug(`fetching changed files for pr #${prNumber}`); core.debug(`fetching changed files for pr #${prNumber}`);
const changedFiles: string[] = await getChangedFiles(client, prNumber); const changedFiles: string[] = await getChangedFiles(client, prNumber);
const labelConfigs: Map<string, MatchConfig[]> = await getMatchConfigs( const labelGlobs: Map<string, StringOrMatchConfig[]> = await getLabelGlobs(
client, client,
configPath configPath
); );
const labels: string[] = []; const labels: string[] = [];
const labelsToRemove: string[] = []; const labelsToRemove: string[] = [];
for (const [label, configs] of labelConfigs.entries()) { for (const [label, globs] of labelGlobs.entries()) {
core.debug(`processing ${label}`); core.debug(`processing ${label}`);
if (checkMatchConfigs(changedFiles, configs)) { if (checkGlobs(changedFiles, globs)) {
labels.push(label); labels.push(label);
} else if (pullRequest.labels.find(l => l.name === label)) { } else if (pullRequest.labels.find(l => l.name === label)) {
labelsToRemove.push(label); labelsToRemove.push(label);
@@ -87,20 +71,41 @@ function getPrNumber(): number | undefined {
return pullRequest.number; return pullRequest.number;
} }
async function getMatchConfigs( async function getChangedFiles(
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;
}
async function getLabelGlobs(
client: ClientType, client: ClientType,
configurationPath: string configurationPath: string
): Promise<Map<string, MatchConfig[]>> { ): Promise<Map<string, StringOrMatchConfig[]>> {
const configurationContent: string = await fetchContent( const configurationContent: string = await fetchContent(
client, client,
configurationPath configurationPath
); );
// loads (hopefully) a `{[label:string]: MatchConfig[]}`, but is `any`: // loads (hopefully) a `{[label:string]: string | StringOrMatchConfig[]}`, but is `any`:
const configObject: any = yaml.load(configurationContent); const configObject: any = yaml.load(configurationContent);
// transform `any` => `Map<string,MatchConfig[]>` or throw if yaml is malformed: // transform `any` => `Map<string,StringOrMatchConfig[]>` or throw if yaml is malformed:
return getLabelConfigMapFromObject(configObject); return getLabelGlobMapFromObject(configObject);
} }
async function fetchContent( async function fetchContent(
@@ -117,192 +122,110 @@ async function fetchContent(
return Buffer.from(response.data.content, response.data.encoding).toString(); return Buffer.from(response.data.content, response.data.encoding).toString();
} }
export function getLabelConfigMapFromObject( function getLabelGlobMapFromObject(
configObject: any configObject: any
): Map<string, MatchConfig[]> { ): Map<string, StringOrMatchConfig[]> {
const labelMap: Map<string, MatchConfig[]> = new Map(); const labelGlobs: Map<string, StringOrMatchConfig[]> = new Map();
for (const label in configObject) { for (const label in configObject) {
const configOptions = configObject[label]; if (typeof configObject[label] === 'string') {
if ( labelGlobs.set(label, [configObject[label]]);
!Array.isArray(configOptions) || } else if (configObject[label] instanceof Array) {
!configOptions.every(opts => typeof opts === 'object') labelGlobs.set(label, configObject[label]);
) { } else {
throw Error( throw Error(
`found unexpected type for label '${label}' (should be array of config options)` `found unexpected type for label ${label} (should be string or array of globs)`
); );
} }
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; return labelGlobs;
} }
export function toMatchConfig(config: any): BaseMatchConfig { function toMatchConfig(config: StringOrMatchConfig): MatchConfig {
const changedFilesConfig = toChangedFilesMatchConfig(config); if (typeof config === 'string') {
const branchConfig = toBranchMatchConfig(config); return {
any: [config]
};
}
return { return config;
...changedFilesConfig,
...branchConfig
};
} }
export function checkMatchConfigs( function printPattern(matcher: Minimatch): string {
return (matcher.negate ? '!' : '') + matcher.pattern;
}
export function checkGlobs(
changedFiles: string[], changedFiles: string[],
matchConfigs: MatchConfig[] globs: StringOrMatchConfig[]
): boolean { ): boolean {
for (const config of matchConfigs) { for (const glob of globs) {
core.debug(` checking config ${JSON.stringify(config)}`); core.debug(` checking pattern ${JSON.stringify(glob)}`);
if (!checkMatch(changedFiles, config)) { const matchConfig = toMatchConfig(glob);
return false; if (checkMatch(changedFiles, matchConfig)) {
return true;
} }
} }
return false;
return true;
} }
function checkMatch(changedFiles: string[], matchConfig: MatchConfig): boolean { function isMatch(changedFile: string, matchers: Minimatch[]): boolean {
if (!Object.keys(matchConfig).length) { core.debug(` matching patterns against file ${changedFile}`);
core.debug(` no "any" or "all" patterns to check`); for (const matcher of matchers) {
return false; core.debug(` - ${printPattern(matcher)}`);
} if (!matcher.match(changedFile)) {
core.debug(` ${printPattern(matcher)} did not match`);
if (matchConfig.all) {
if (!checkAll(matchConfig.all, changedFiles)) {
return false;
}
}
if (matchConfig.any) {
if (!checkAny(matchConfig.any, changedFiles)) {
return false; return false;
} }
} }
core.debug(` all patterns matched`);
return true; return true;
} }
// equivalent to "Array.some()" but expanded for debugging and clarity // equivalent to "Array.some()" but expanded for debugging and clarity
export function checkAny( function checkAny(changedFiles: string[], globs: string[]): boolean {
matchConfigs: BaseMatchConfig[], const matchers = globs.map(g => new Minimatch(g));
changedFiles: string[]
): boolean {
core.debug(` checking "any" patterns`); core.debug(` checking "any" patterns`);
if ( for (const changedFile of changedFiles) {
!matchConfigs.length || if (isMatch(changedFile, matchers)) {
!matchConfigs.some(configOption => Object.keys(configOption).length) core.debug(` "any" patterns matched against ${changedFile}`);
) { return true;
core.debug(` no "any" patterns to check`);
return false;
}
for (const matchConfig of matchConfigs) {
if (matchConfig.baseBranch) {
if (checkAnyBranch(matchConfig.baseBranch, 'base')) {
core.debug(` "any" patterns matched`);
return true;
}
}
if (matchConfig.changedFiles) {
if (checkAnyChangedFiles(changedFiles, matchConfig.changedFiles)) {
core.debug(` "any" patterns matched`);
return true;
}
}
if (matchConfig.headBranch) {
if (checkAnyBranch(matchConfig.headBranch, 'head')) {
core.debug(` "any" patterns matched`);
return true;
}
} }
} }
core.debug(` "any" patterns did not match any configs`); core.debug(` "any" patterns did not match any files`);
return false; return false;
} }
// equivalent to "Array.every()" but expanded for debugging and clarity // equivalent to "Array.every()" but expanded for debugging and clarity
export function checkAll( function checkAll(changedFiles: string[], globs: string[]): boolean {
matchConfigs: BaseMatchConfig[], const matchers = globs.map(g => new Minimatch(g));
changedFiles: string[] core.debug(` checking "all" patterns`);
): boolean { for (const changedFile of changedFiles) {
core.debug(` checking "all" patterns`); if (!isMatch(changedFile, matchers)) {
if ( core.debug(` "all" patterns did not match against ${changedFile}`);
!matchConfigs.length || return false;
!matchConfigs.some(configOption => Object.keys(configOption).length) }
) { }
core.debug(` no "all" patterns to check`);
return false; core.debug(` "all" patterns matched all files`);
} return true;
}
for (const matchConfig of matchConfigs) {
if (matchConfig.baseBranch) { function checkMatch(changedFiles: string[], matchConfig: MatchConfig): boolean {
if (!checkAllBranch(matchConfig.baseBranch, 'base')) { if (matchConfig.all !== undefined) {
core.debug(` "all" patterns did not match`); if (!checkAll(changedFiles, matchConfig.all)) {
return false; return false;
} }
} }
if (matchConfig.changedFiles) { if (matchConfig.any !== undefined) {
if (!changedFiles.length) { if (!checkAny(changedFiles, matchConfig.any)) {
core.debug(` no files to check "changed-files" patterns against`); return false;
return false;
}
if (!checkAllChangedFiles(changedFiles, matchConfig.changedFiles)) {
core.debug(` "all" patterns did not match`);
return false;
}
}
if (matchConfig.headBranch) {
if (!checkAllBranch(matchConfig.headBranch, 'head')) {
core.debug(` "all" patterns did not match`);
return false;
}
} }
} }
core.debug(` "all" patterns matched all configs`);
return true; return true;
} }