Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: actions/labeler
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v4
Choose a base ref
...
head repository: actions/labeler
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: v5
Choose a head ref

Commits on Aug 7, 2021

  1. Copy the full SHA
    2bf42e4 View commit details
  2. Copy the full SHA
    ad73546 View commit details
  3. Copy the full SHA
    6c50d09 View commit details
  4. Copy the full SHA
    ee0e0eb View commit details
  5. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    a01b9ae View commit details
  6. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    bce88a9 View commit details
  7. Run build

    joshdales committed Aug 7, 2021

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    765934f View commit details

Commits on Sep 15, 2021

  1. Fix PR branch labeler

    amiel committed Sep 15, 2021

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    827e118 View commit details
  2. Run build

    amiel committed Sep 15, 2021

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    8aa7614 View commit details
  3. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    cb5f448 View commit details
  4. Run build

    amiel committed Sep 15, 2021

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    2ced1f3 View commit details
  5. Format

    amiel committed Sep 15, 2021

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    d9ed3e8 View commit details
  6. Include a test for branching

    amiel committed Sep 15, 2021

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    79c0cc7 View commit details

Commits on Sep 16, 2021

  1. Update src/labeler.ts

    Safer access of pull_request data.
    
    Co-authored-by: Josh Dales <30500472+joshdales@users.noreply.github.com>
    amiel and joshdales authored Sep 16, 2021

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    27a1d89 View commit details
  2. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    7624214 View commit details

Commits on Sep 29, 2021

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    2d63815 View commit details
  2. Copy the full SHA
    ab49f7a View commit details
  3. Run build

    joshdales committed Sep 29, 2021
    Copy the full SHA
    2246b66 View commit details

Commits on Oct 29, 2021

  1. minor adjustment for successful branch matching.

    To better follow the any convention as opposed to all
    joshdales committed Oct 29, 2021
    Copy the full SHA
    89f6b77 View commit details
  2. Copy the full SHA
    7aadc17 View commit details
  3. run the build script

    joshdales committed Oct 29, 2021
    Copy the full SHA
    71fc664 View commit details

Commits on Jun 11, 2022

  1. Copy the full SHA
    818399d View commit details
  2. Copy the full SHA
    6e27606 View commit details

Commits on Aug 30, 2022

  1. Copy the full SHA
    0ad789c View commit details
  2. Run the build command

    joshdales committed Aug 30, 2022
    Copy the full SHA
    0861fa5 View commit details

Commits on Sep 22, 2022

  1. Fix typo in the README

    joshdales committed Sep 22, 2022
    Copy the full SHA
    4c74e84 View commit details

Commits on Jan 11, 2023

  1. Copy the full SHA
    7f8d8e4 View commit details
  2. Run prettier

    joshdales committed Jan 11, 2023
    Copy the full SHA
    c54c5a2 View commit details
  3. Run the build command

    joshdales committed Jan 11, 2023
    Copy the full SHA
    7b1327b View commit details

Commits on Jan 28, 2023

  1. Copy the full SHA
    8c59ecc View commit details
  2. Copy the full SHA
    f2b2513 View commit details
  3. Copy the full SHA
    2343710 View commit details
  4. Copy the full SHA
    cd3a8df View commit details
  5. Copy the full SHA
    0b6e68d View commit details
  6. Copy the full SHA
    2daf35a View commit details

Commits on Jan 29, 2023

  1. Copy the full SHA
    231de6b View commit details
  2. Copy the full SHA
    922ffdf View commit details
  3. Copy the full SHA
    7a5c525 View commit details
  4. Copy the full SHA
    969899d View commit details
  5. Update the labeler tests

    joshdales committed Jan 29, 2023
    Copy the full SHA
    7d17531 View commit details
  6. Run the build command

    joshdales committed Jan 29, 2023
    Copy the full SHA
    b071d82 View commit details
  7. Copy the full SHA
    0eb9d49 View commit details

Commits on Feb 19, 2023

  1. Copy the full SHA
    09f0853 View commit details
  2. Copy the full SHA
    ed31b27 View commit details
  3. Copy the full SHA
    da83a18 View commit details

Commits on Feb 21, 2023

  1. Copy the full SHA
    56347d5 View commit details
  2. Copy the full SHA
    8943ca2 View commit details
  3. Copy the full SHA
    e5b1bdd View commit details

Commits on Mar 3, 2023

  1. Reference minimatch in docs

    Co-authored-by: MaksimZhukov <46996400+MaksimZhukov@users.noreply.github.com>
    joshdales and MaksimZhukov authored Mar 3, 2023
    Copy the full SHA
    2e10ffb View commit details
  2. Fix bad test descriptions

    Co-authored-by: MaksimZhukov <46996400+MaksimZhukov@users.noreply.github.com>
    joshdales and MaksimZhukov authored Mar 3, 2023
    Copy the full SHA
    2a5bc55 View commit details
Showing with 39,705 additions and 20,868 deletions.
  1. +2 −0 .github/workflows/basic-validation.yml
  2. +2 −0 .github/workflows/check-dist.yml
  3. +1 −1 .licenses/npm/@actions/core.dep.yml
  4. +1 −1 .licenses/npm/@actions/github.dep.yml
  5. +1 −1 .licenses/npm/@actions/http-client.dep.yml
  6. +12 −16 .licenses/npm/{@octokit/request-error-4.0.2.dep.yml → @fastify/busboy.dep.yml}
  7. +0 −32 .licenses/npm/@jest/schemas.dep.yml
  8. +0 −32 .licenses/npm/@jest/types.dep.yml
  9. +1 −1 .licenses/npm/@octokit/auth-token.dep.yml
  10. +1 −1 .licenses/npm/@octokit/core.dep.yml
  11. +1 −1 .licenses/npm/@octokit/endpoint.dep.yml
  12. +1 −1 .licenses/npm/@octokit/graphql.dep.yml
  13. +0 −20 .licenses/npm/@octokit/openapi-types-12.11.0.dep.yml
  14. +1 −1 .licenses/npm/@octokit/{openapi-types-18.0.0.dep.yml → openapi-types.dep.yml}
  15. +1 −1 .licenses/npm/@octokit/plugin-paginate-rest.dep.yml
  16. +1 −1 .licenses/npm/@octokit/plugin-rest-endpoint-methods.dep.yml
  17. +1 −1 .licenses/npm/@octokit/plugin-retry.dep.yml
  18. +1 −1 .licenses/npm/@octokit/{request-error-2.1.0.dep.yml → request-error.dep.yml}
  19. +1 −1 .licenses/npm/@octokit/request.dep.yml
  20. +0 −20 .licenses/npm/@octokit/types-6.41.0.dep.yml
  21. +1 −1 .licenses/npm/@octokit/{types-10.0.0.dep.yml → types.dep.yml}
  22. +0 −26 .licenses/npm/@sinclair/typebox.dep.yml
  23. +0 −32 .licenses/npm/@types/istanbul-lib-coverage.dep.yml
  24. +0 −32 .licenses/npm/@types/istanbul-lib-report.dep.yml
  25. +0 −32 .licenses/npm/@types/istanbul-reports.dep.yml
  26. +0 −32 .licenses/npm/@types/node.dep.yml
  27. +0 −32 .licenses/npm/@types/yargs-parser.dep.yml
  28. +0 −32 .licenses/npm/@types/yargs.dep.yml
  29. +0 −20 .licenses/npm/ansi-styles-4.3.0.dep.yml
  30. +0 −20 .licenses/npm/ansi-styles-5.2.0.dep.yml
  31. +0 −20 .licenses/npm/chalk.dep.yml
  32. +0 −34 .licenses/npm/ci-info.dep.yml
  33. +0 −19 .licenses/npm/color-name.dep.yml
  34. +0 −26 .licenses/npm/graceful-fs.dep.yml
  35. +0 −22 .licenses/npm/has-flag.dep.yml
  36. +0 −32 .licenses/npm/jest-get-type.dep.yml
  37. +0 −32 .licenses/npm/jest-util.dep.yml
  38. +32 −9 .licenses/npm/{color-convert.dep.yml → lodash.isequal.dep.yml}
  39. +1 −1 .licenses/npm/minimatch.dep.yml
  40. +0 −56 .licenses/npm/node-fetch.dep.yml
  41. +0 −38 .licenses/npm/picomatch.dep.yml
  42. +0 −32 .licenses/npm/pretty-format.dep.yml
  43. +0 −32 .licenses/npm/react-is.dep.yml
  44. +0 −20 .licenses/npm/supports-color.dep.yml
  45. +0 −30 .licenses/npm/tr46.dep.yml
  46. +5 −5 .licenses/npm/{jest-each.dep.yml → undici.dep.yml}
  47. +0 −23 .licenses/npm/webidl-conversions.dep.yml
  48. +0 −32 .licenses/npm/whatwg-url.dep.yml
  49. +112 −107 README.md
  50. +7 −1 __mocks__/@actions/github.ts
  51. +210 −0 __tests__/branch.test.ts
  52. +270 −0 __tests__/changedFiles.test.ts
  53. +17 −0 __tests__/fixtures/all_options.yml
  54. +8 −0 __tests__/fixtures/any_and_all.yml
  55. +11 −0 __tests__/fixtures/branches.yml
  56. +3 −0 __tests__/fixtures/not_supported.yml
  57. +2 −1 __tests__/fixtures/only_pdfs.yml
  58. +138 −20 __tests__/labeler.test.ts
  59. +122 −4 __tests__/main.test.ts
  60. +2 −2 action.yml
  61. +36,130 −12,827 dist/index.js
  62. +1,698 −6,761 package-lock.json
  63. +19 −18 package.json
  64. +24 −0 src/api/get-changed-files.ts
  65. +38 −0 src/api/get-changed-pull-requests.ts
  66. +16 −0 src/api/get-content.ts
  67. +126 −0 src/api/get-label-configs.ts
  68. +6 −0 src/api/index.ts
  69. +15 −0 src/api/set-labels.ts
  70. +2 −0 src/api/types.ts
  71. +98 −0 src/branch.ts
  72. +360 −0 src/changedFiles.ts
  73. +10 −0 src/get-inputs/get-inputs.ts
  74. +28 −0 src/get-inputs/get-pr-numbers.ts
  75. +1 −0 src/get-inputs/index.ts
  76. +151 −272 src/labeler.ts
  77. +13 −0 src/utils.ts
2 changes: 2 additions & 0 deletions .github/workflows/basic-validation.yml
Original file line number Diff line number Diff line change
@@ -15,3 +15,5 @@ jobs:
call-basic-validation:
name: Basic validation
uses: actions/reusable-workflows/.github/workflows/basic-validation.yml@main
with:
node-version: '20.x'
2 changes: 2 additions & 0 deletions .github/workflows/check-dist.yml
Original file line number Diff line number Diff line change
@@ -15,3 +15,5 @@ jobs:
call-check-dist:
name: Check dist/
uses: actions/reusable-workflows/.github/workflows/check-dist.yml@main
with:
node-version: '20.x'
2 changes: 1 addition & 1 deletion .licenses/npm/@actions/core.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .licenses/npm/@actions/github.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .licenses/npm/@actions/http-client.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 0 additions & 32 deletions .licenses/npm/@jest/schemas.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/@jest/types.dep.yml

This file was deleted.

2 changes: 1 addition & 1 deletion .licenses/npm/@octokit/auth-token.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .licenses/npm/@octokit/core.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .licenses/npm/@octokit/endpoint.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .licenses/npm/@octokit/graphql.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 0 additions & 20 deletions .licenses/npm/@octokit/openapi-types-12.11.0.dep.yml

This file was deleted.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .licenses/npm/@octokit/plugin-paginate-rest.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .licenses/npm/@octokit/plugin-retry.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .licenses/npm/@octokit/request.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 0 additions & 20 deletions .licenses/npm/@octokit/types-6.41.0.dep.yml

This file was deleted.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 0 additions & 26 deletions .licenses/npm/@sinclair/typebox.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/@types/istanbul-lib-coverage.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/@types/istanbul-lib-report.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/@types/istanbul-reports.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/@types/node.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/@types/yargs-parser.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/@types/yargs.dep.yml

This file was deleted.

20 changes: 0 additions & 20 deletions .licenses/npm/ansi-styles-4.3.0.dep.yml

This file was deleted.

20 changes: 0 additions & 20 deletions .licenses/npm/ansi-styles-5.2.0.dep.yml

This file was deleted.

20 changes: 0 additions & 20 deletions .licenses/npm/chalk.dep.yml

This file was deleted.

34 changes: 0 additions & 34 deletions .licenses/npm/ci-info.dep.yml

This file was deleted.

19 changes: 0 additions & 19 deletions .licenses/npm/color-name.dep.yml

This file was deleted.

26 changes: 0 additions & 26 deletions .licenses/npm/graceful-fs.dep.yml

This file was deleted.

22 changes: 0 additions & 22 deletions .licenses/npm/has-flag.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/jest-get-type.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/jest-util.dep.yml

This file was deleted.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .licenses/npm/minimatch.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

56 changes: 0 additions & 56 deletions .licenses/npm/node-fetch.dep.yml

This file was deleted.

38 changes: 0 additions & 38 deletions .licenses/npm/picomatch.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/pretty-format.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/react-is.dep.yml

This file was deleted.

20 changes: 0 additions & 20 deletions .licenses/npm/supports-color.dep.yml

This file was deleted.

30 changes: 0 additions & 30 deletions .licenses/npm/tr46.dep.yml

This file was deleted.

10 changes: 5 additions & 5 deletions .licenses/npm/jest-each.dep.yml → .licenses/npm/undici.dep.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 0 additions & 23 deletions .licenses/npm/webidl-conversions.dep.yml

This file was deleted.

32 changes: 0 additions & 32 deletions .licenses/npm/whatwg-url.dep.yml

This file was deleted.

219 changes: 112 additions & 107 deletions README.md

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion __mocks__/@actions/github.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
export const context = {
payload: {
pull_request: {
number: 123
number: 123,
head: {
ref: 'head-branch-name'
},
base: {
ref: 'base-branch-name'
}
}
},
repo: {
210 changes: 210 additions & 0 deletions __tests__/branch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
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']
});
});
});
});
270 changes: 270 additions & 0 deletions __tests__/changedFiles.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
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,
false
);
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,
false
);
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,
false
);
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,
false
);
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': [{'any-glob-to-any-file': ['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': [{'any-glob-to-any-file': '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,
false
);
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,
false
);
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,
false
);
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,
false
);
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,
false
);
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,
false
);
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,
false
);
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,
false
);
expect(result).toBe(false);
});
});
});
17 changes: 17 additions & 0 deletions __tests__/fixtures/all_options.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
label1:
- any:
- changed-files:
- any-glob-to-any-file: ['glob']
- head-branch: ['regexp']
- base-branch: ['regexp']
- all:
- changed-files:
- all-globs-to-all-files: ['glob']
- head-branch: ['regexp']
- base-branch: ['regexp']

label2:
- changed-files:
- any-glob-to-any-file: ['glob']
- head-branch: ['regexp']
- base-branch: ['regexp']
8 changes: 8 additions & 0 deletions __tests__/fixtures/any_and_all.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
tests:
- any:
- head-branch: ['^tests/', '^test/']
- changed-files:
- any-glob-to-any-file: ['tests/**/*']
- all:
- changed-files:
- all-globs-to-all-files: ['!tests/requirements.txt']
11 changes: 11 additions & 0 deletions __tests__/fixtures/branches.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
test-branch:
- head-branch: '^test/'

feature-branch:
- head-branch: '/feature/'

bug-branch:
- head-branch: '^bug/|fix/'

array-branch:
- head-branch: ['^array/']
3 changes: 3 additions & 0 deletions __tests__/fixtures/not_supported.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
label:
- all:
- unknown: 'this-is-not-supported'
3 changes: 2 additions & 1 deletion __tests__/fixtures/only_pdfs.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
touched-a-pdf-file:
- any: ['*.pdf']
- changed-files:
- any-glob-to-any-file: ['*.pdf']
158 changes: 138 additions & 20 deletions __tests__/labeler.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import {checkGlobs} from '../src/labeler';

import * as yaml from 'js-yaml';
import * as core from '@actions/core';
import * as fs from 'fs';
import {checkMatchConfigs} from '../src/labeler';
import {
MatchConfig,
toMatchConfig,
getLabelConfigMapFromObject,
BaseMatchConfig
} from '../src/api/get-label-configs';

jest.mock('@actions/core');

@@ -10,34 +17,145 @@ beforeAll(() => {
});
});

const matchConfig = [{any: ['*.txt']}];
const loadYaml = (filepath: string) => {
const loadedFile = fs.readFileSync(filepath);
const content = Buffer.from(loadedFile).toString();
return yaml.load(content);
};

describe('checkGlobs', () => {
it('returns true when our pattern does match changed files', () => {
const changedFiles = ['foo.txt', 'bar.txt'];
const result = checkGlobs(changedFiles, matchConfig, false);
describe('getLabelConfigMapFromObject', () => {
const yamlObject = loadYaml('__tests__/fixtures/all_options.yml');
const expected = new Map<string, MatchConfig[]>();
expected.set('label1', [
{
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}
]
}
]);

expect(result).toBeTruthy();
it('returns a MatchConfig', () => {
const result = getLabelConfigMapFromObject(yamlObject);
expect(result).toEqual(expected);
});
});

describe('toMatchConfig', () => {
describe('when all expected config options are present', () => {
const config = {
'changed-files': [{'any-glob-to-any-file': ['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);
});

it('returns false when our pattern does not match changed files', () => {
const changedFiles = ['foo.docx'];
const result = checkGlobs(changedFiles, matchConfig, false);
describe('and there are also unexpected options present', () => {
config['test-test'] = 'testing';

expect(result).toBeFalsy();
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, false);

expect(result).toBeTruthy();
});

it('returns false for a file starting with dot if `dot` option is false', () => {
const changedFiles = ['.foo.txt'];
const result = checkGlobs(changedFiles, matchConfig, false);
it('returns false when our pattern does not match changed files', () => {
const changedFiles = ['foo.docx'];
const result = checkMatchConfigs(changedFiles, matchConfig, false);

expect(result).toBeFalsy();
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, false);
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();
});
});

it('returns true for a file starting with dot if `dot` option is true', () => {
const changedFiles = ['.foo.txt'];
const result = checkGlobs(changedFiles, matchConfig, 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, false);
expect(result).toBe(false);
});

expect(result).toBeTruthy();
it('returns true when only both config matches', () => {
const matchConfig: MatchConfig[] = [
{any: [{changedFiles: [{anyGlobToAnyFile: ['*.txt']}]}]},
{any: [{headBranch: ['head-branch']}]}
];
const result = checkMatchConfigs(changedFiles, matchConfig, false);
expect(result).toBe(true);
});
});
});
126 changes: 122 additions & 4 deletions __tests__/main.test.ts
Original file line number Diff line number Diff line change
@@ -3,7 +3,6 @@ import * as github from '@actions/github';
import * as core from '@actions/core';
import path from 'path';
import fs from 'fs';
import each from 'jest-each';

jest.mock('@actions/core');
jest.mock('@actions/github');
@@ -35,7 +34,10 @@ class NotFound extends Error {
}

const yamlFixtures = {
'only_pdfs.yml': fs.readFileSync('__tests__/fixtures/only_pdfs.yml')
'branches.yml': fs.readFileSync('__tests__/fixtures/branches.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')
};

const configureInput = (
@@ -147,6 +149,121 @@ describe('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 () => {
configureInput({});
github.context.payload.pull_request!.head = {ref: 'test/testing-time'};
usingLabelerConfigYaml('branches.yml');
await run();

expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 123,
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 () => {
configureInput({});
github.context.payload.pull_request!.head = {
ref: 'test/feature/123'
};
usingLabelerConfigYaml('branches.yml');
await run();

expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 123,
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 () => {
configureInput({});
github.context.payload.pull_request!.head = {ref: 'fix/123'};
usingLabelerConfigYaml('branches.yml');
await run();

expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 123,
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 () => {
configureInput({});
github.context.payload.pull_request!.head = {ref: 'array/123'};
usingLabelerConfigYaml('branches.yml');
await run();

expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 123,
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 () => {
configureInput({});
usingLabelerConfigYaml('any_and_all.yml');
mockGitHubResponseChangedFiles('tests/test.ts');
await run();

expect(setLabelsMock).toHaveBeenCalledTimes(1);
expect(setLabelsMock).toHaveBeenCalledWith({
owner: 'monalisa',
repo: 'helloworld',
issue_number: 123,
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 () => {
configureInput({});
usingLabelerConfigYaml('any_and_all.yml');
mockGitHubResponseChangedFiles('tests/requirements.txt');
await run();

expect(setLabelsMock).toHaveBeenCalledTimes(0);
});

it('(with sync-labels: true) it deletes preexisting PR labels that no longer match the glob pattern', async () => {
configureInput({
'repo-token': 'foo',
@@ -171,6 +288,7 @@ describe('run', () => {
issue_number: 123,
labels: ['manually-added']
});

expect(setOutputSpy).toHaveBeenCalledWith('new-labels', '');
expect(setOutputSpy).toHaveBeenCalledWith('all-labels', 'manually-added');
});
@@ -353,10 +471,10 @@ describe('run', () => {
expect(reposMock).toHaveBeenCalled();
});

each([
test.each([
[new HttpError('Error message')],
[new NotFound('Error message')]
]).test(
])(
'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';
4 changes: 2 additions & 2 deletions action.yml
Original file line number Diff line number Diff line change
@@ -16,7 +16,7 @@ inputs:
required: false
dot:
description: 'Whether or not to auto-include paths starting with dot (e.g. `.github`)'
default: false
default: true
required: false
pr-number:
description: 'The pull request number(s)'
@@ -28,5 +28,5 @@ outputs:
all-labels:
description: 'A comma-separated list of all labels that the PR contains'
runs:
using: 'node16'
using: 'node20'
main: 'dist/index.js'
48,957 changes: 36,130 additions & 12,827 deletions dist/index.js

Large diffs are not rendered by default.

8,459 changes: 1,698 additions & 6,761 deletions package-lock.json

Large diffs are not rendered by default.

37 changes: 19 additions & 18 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "labeler",
"version": "4.1.0",
"version": "5.0.0",
"description": "Labels pull requests by files altered",
"main": "lib/main.js",
"scripts": {
@@ -25,27 +25,28 @@
"license": "MIT",
"dependencies": {
"@actions/core": "^1.10.0",
"@actions/github": "^5.1.1",
"@octokit/plugin-retry": "^5.0.5",
"jest-each": "^29.6.1",
"@actions/github": "^6.0.0",
"@octokit/plugin-retry": "^6.0.0",
"js-yaml": "^4.1.0",
"minimatch": "^7.4.3"
"lodash.isequal": "^4.5.0",
"minimatch": "^9.0.3"
},
"devDependencies": {
"@types/jest": "^27.4.1",
"@types/js-yaml": "^4.0.5",
"@types/jest": "^29.5.6",
"@types/js-yaml": "^4.0.6",
"@types/lodash.isequal": "^4.5.6",
"@types/minimatch": "^5.1.2",
"@types/node": "^16.11.7",
"@typescript-eslint/eslint-plugin": "^5.61.0",
"@typescript-eslint/parser": "^5.61.0",
"@vercel/ncc": "^0.36.1",
"eslint": "^8.44.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-jest": "^27.2.2",
"@types/node": "^20.8.8",
"@typescript-eslint/eslint-plugin": "^6.7.4",
"@typescript-eslint/parser": "^6.7.2",
"@vercel/ncc": "^0.38.1",
"eslint": "^8.51.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-jest": "^27.4.2",
"eslint-plugin-node": "^11.1.0",
"jest": "^27.5.1",
"prettier": "^2.8.8",
"ts-jest": "^27.1.3",
"typescript": "^4.9.5"
"jest": "^29.7.0",
"prettier": "^3.0.3",
"ts-jest": "^29.1.1",
"typescript": "^5.2.2"
}
}
24 changes: 24 additions & 0 deletions src/api/get-changed-files.ts
Original file line number Diff line number Diff line change
@@ -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;
};
38 changes: 38 additions & 0 deletions src/api/get-changed-pull-requests.ts
Original file line number Diff line number Diff line change
@@ -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 changes: 16 additions & 0 deletions src/api/get-content.ts
Original file line number Diff line number Diff line change
@@ -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();
};
126 changes: 126 additions & 0 deletions src/api/get-label-configs.ts
Original file line number Diff line number Diff line change
@@ -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 changes: 6 additions & 0 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -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 changes: 15 additions & 0 deletions src/api/set-labels.ts
Original file line number Diff line number Diff line change
@@ -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 changes: 2 additions & 0 deletions src/api/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import * as github from '@actions/github';
export type ClientType = ReturnType<typeof github.getOctokit>;
98 changes: 98 additions & 0 deletions src/branch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
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;
}
360 changes: 360 additions & 0 deletions src/changedFiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,360 @@
import * as core from '@actions/core';
import * as github from '@actions/github';
import {Minimatch} from 'minimatch';
import {printPattern, isObject, kebabToCamel} from './utils';

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 = [
'any-glob-to-any-file',
'any-glob-to-all-files',
'all-globs-to-any-file',
'all-globs-to-all-files'
];

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({
[kebabToCamel(key)]: Array.isArray(changedFilesConfig[key])
? changedFilesConfig[key]
: [changedFilesConfig[key]]
});
});
});

return {
changedFiles: validChangedFilesConfigs
};
}

export function checkAnyChangedFiles(
changedFiles: string[],
globPatternsConfigs: ChangedFilesGlobPatternsConfig[],
dot: boolean
): boolean {
core.debug(` checking "changed-files" patterns`);

for (const globPatternsConfig of globPatternsConfigs) {
if (globPatternsConfig.anyGlobToAnyFile) {
if (
checkIfAnyGlobMatchesAnyFile(
changedFiles,
globPatternsConfig.anyGlobToAnyFile,
dot
)
) {
core.debug(` "changed-files" matched`);
return true;
}
}

if (globPatternsConfig.anyGlobToAllFiles) {
if (
checkIfAnyGlobMatchesAllFiles(
changedFiles,
globPatternsConfig.anyGlobToAllFiles,
dot
)
) {
core.debug(` "changed-files" matched`);
return true;
}
}

if (globPatternsConfig.allGlobsToAnyFile) {
if (
checkIfAllGlobsMatchAnyFile(
changedFiles,
globPatternsConfig.allGlobsToAnyFile,
dot
)
) {
core.debug(` "changed-files" matched`);
return true;
}
}

if (globPatternsConfig.allGlobsToAllFiles) {
if (
checkIfAllGlobsMatchAllFiles(
changedFiles,
globPatternsConfig.allGlobsToAllFiles,
dot
)
) {
core.debug(` "changed-files" matched`);
return true;
}
}
}

core.debug(` "changed-files" did not match`);
return false;
}

export function checkAllChangedFiles(
changedFiles: string[],
globPatternsConfigs: ChangedFilesGlobPatternsConfig[],
dot: boolean
): boolean {
core.debug(` checking "changed-files" patterns`);

for (const globPatternsConfig of globPatternsConfigs) {
if (globPatternsConfig.anyGlobToAnyFile) {
if (
!checkIfAnyGlobMatchesAnyFile(
changedFiles,
globPatternsConfig.anyGlobToAnyFile,
dot
)
) {
core.debug(` "changed-files" did not match`);
return false;
}
}

if (globPatternsConfig.anyGlobToAllFiles) {
if (
!checkIfAnyGlobMatchesAllFiles(
changedFiles,
globPatternsConfig.anyGlobToAllFiles,
dot
)
) {
core.debug(` "changed-files" did not match`);
return false;
}
}

if (globPatternsConfig.allGlobsToAnyFile) {
if (
!checkIfAllGlobsMatchAnyFile(
changedFiles,
globPatternsConfig.allGlobsToAnyFile,
dot
)
) {
core.debug(` "changed-files" did not match`);
return false;
}
}

if (globPatternsConfig.allGlobsToAllFiles) {
if (
!checkIfAllGlobsMatchAllFiles(
changedFiles,
globPatternsConfig.allGlobsToAllFiles,
dot
)
) {
core.debug(` "changed-files" did not match`);
return false;
}
}
}

core.debug(` "changed-files" patterns matched`);
return true;
}

export function checkIfAnyGlobMatchesAnyFile(
changedFiles: string[],
globs: string[],
dot: boolean
): boolean {
core.debug(` checking "any-glob-to-any-file" config patterns`);
const matchers = globs.map(g => new Minimatch(g, {dot}));

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[],
dot: boolean
): boolean {
core.debug(` checking "all-globs-to-any-file" config patterns`);
const matchers = globs.map(g => new Minimatch(g, {dot}));

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[],
dot: boolean
): boolean {
core.debug(` checking "any-glob-to-all-files" config patterns`);
const matchers = globs.map(g => new Minimatch(g, {dot}));

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[],
dot: boolean
): boolean {
core.debug(` checking "all-globs-to-all-files" config patterns`);
const matchers = globs.map(g => new Minimatch(g, {dot}));

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;
}
10 changes: 10 additions & 0 deletions src/get-inputs/get-inputs.ts
Original file line number Diff line number Diff line change
@@ -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()
});
28 changes: 28 additions & 0 deletions src/get-inputs/get-pr-numbers.ts
Original file line number Diff line number Diff line change
@@ -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 change: 1 addition & 0 deletions src/get-inputs/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './get-inputs';
423 changes: 151 additions & 272 deletions src/labeler.ts

Large diffs are not rendered by default.

13 changes: 13 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {Minimatch} from 'minimatch';

export const printPattern = (matcher: Minimatch): string => {
return (matcher.negate ? '!' : '') + matcher.pattern;
};

export const kebabToCamel = (str: string): string => {
return str.replace(/-./g, m => m.toUpperCase()[1]);
};

export function isObject(obj: unknown): obj is object {
return obj !== null && typeof obj === 'object' && !Array.isArray(obj);
}