Compare commits

..

1 Commits

Author SHA1 Message Date
Evgenii Korolevskii
4b5a5f236d Update CODEOWNERS 2022-12-23 00:00:24 +01:00
74 changed files with 13909 additions and 40258 deletions

View File

@@ -1,7 +0,0 @@
# Ignore list
/*
# Do not ignore these folders:
!__tests__/
!__mocks__/
!src/

View File

@@ -1,51 +0,0 @@
// This is a reusable configuration file copied from https://github.com/actions/reusable-workflows/tree/main/reusable-configurations. Please don't make changes to this file as it's the subject of an automatic update.
module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:eslint-plugin-jest/recommended',
'eslint-config-prettier'
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'eslint-plugin-node', 'eslint-plugin-jest'],
rules: {
'@typescript-eslint/no-require-imports': 'error',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/ban-ts-comment': [
'error',
{
'ts-ignore': 'allow-with-description'
}
],
'no-console': 'error',
'yoda': 'error',
'prefer-const': [
'error',
{
destructuring: 'all'
}
],
'no-control-regex': 'off',
'no-constant-condition': ['error', {checkLoops: false}],
'node/no-extraneous-import': 'error'
},
overrides: [
{
files: ['**/*{test,spec}.ts'],
rules: {
'@typescript-eslint/no-unused-vars': 'off',
'jest/no-standalone-expect': 'off',
'jest/no-conditional-expect': 'off',
'no-console': 'off',
}
}
],
env: {
node: true,
es6: true,
'jest/globals': true
}
};

2
.gitattributes vendored
View File

@@ -1,4 +1,4 @@
* text=auto eol=lf * text=auto
.licenses/** -diff linguist-generated=true .licenses/** -diff linguist-generated=true
# don't diff machine generated files # don't diff machine generated files

View File

@@ -15,5 +15,3 @@ jobs:
call-basic-validation: call-basic-validation:
name: Basic validation name: Basic validation
uses: actions/reusable-workflows/.github/workflows/basic-validation.yml@main uses: actions/reusable-workflows/.github/workflows/basic-validation.yml@main
with:
node-version: '24.x'

View File

@@ -15,5 +15,3 @@ jobs:
call-check-dist: call-check-dist:
name: Check dist/ name: Check dist/
uses: actions/reusable-workflows/.github/workflows/check-dist.yml@main uses: actions/reusable-workflows/.github/workflows/check-dist.yml@main
with:
node-version: '24.x'

View File

@@ -1,20 +0,0 @@
name: 'Publish Immutable Action Version'
on:
release:
types: [published]
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
packages: write
steps:
- name: Checking out
uses: actions/checkout@v5
- name: Publish
id: publish
uses: actions/publish-immutable-action@0.0.3

View File

@@ -22,7 +22,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Update the ${{ env.TAG_NAME }} tag - name: Update the ${{ env.TAG_NAME }} tag
uses: actions/publish-action@v0.4.0 uses: actions/publish-action@v0.2.1
with: with:
source-tag: ${{ env.TAG_NAME }} source-tag: ${{ env.TAG_NAME }}
slack-webhook: ${{ secrets.SLACK_WEBHOOK }} slack-webhook: ${{ secrets.SLACK_WEBHOOK }}

View File

@@ -1,11 +0,0 @@
name: Update configuration files
on:
schedule:
- cron: '0 3 * * 0'
workflow_dispatch:
jobs:
call-update-configuration-files:
name: Update configuration files
uses: actions/reusable-workflows/.github/workflows/update-config-files.yml@main

1
.gitignore vendored
View File

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

View File

@@ -1,6 +1,6 @@
--- ---
name: "@actions/core" name: "@actions/core"
version: 1.11.1 version: 1.10.0
type: npm type: npm
summary: Actions core lib summary: Actions core lib
homepage: https://github.com/actions/toolkit/tree/main/packages/core homepage: https://github.com/actions/toolkit/tree/main/packages/core

View File

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

View File

@@ -1,6 +1,6 @@
--- ---
name: "@actions/github" name: "@actions/github"
version: 6.0.0 version: 5.0.0
type: npm type: npm
summary: Actions github lib summary: Actions github lib
homepage: https://github.com/actions/toolkit/tree/main/packages/github homepage: https://github.com/actions/toolkit/tree/main/packages/github

View File

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

View File

@@ -1,6 +1,6 @@
--- ---
name: "@actions/http-client" name: "@actions/http-client"
version: 2.2.0 version: 2.0.1
type: npm type: npm
summary: Actions Http Client summary: Actions Http Client
homepage: https://github.com/actions/toolkit/tree/main/packages/http-client homepage: https://github.com/actions/toolkit/tree/main/packages/http-client

View File

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

View File

@@ -1,9 +1,9 @@
--- ---
name: "@octokit/auth-token" name: "@octokit/auth-token"
version: 4.0.0 version: 2.4.5
type: npm type: npm
summary: GitHub API token authentication for browsers and Node.js summary: GitHub API token authentication for browsers and Node.js
homepage: homepage: https://github.com/octokit/auth-token.js#readme
license: mit license: mit
licenses: licenses:
- sources: LICENSE - sources: LICENSE

View File

@@ -1,6 +1,6 @@
--- ---
name: "@octokit/core" name: "@octokit/core"
version: 5.0.1 version: 3.5.1
type: npm type: npm
summary: Extendable client for GitHub's REST & GraphQL APIs summary: Extendable client for GitHub's REST & GraphQL APIs
homepage: homepage:

View File

@@ -1,6 +1,6 @@
--- ---
name: "@octokit/endpoint" name: "@octokit/endpoint"
version: 9.0.1 version: 6.0.12
type: npm type: npm
summary: Turns REST API endpoints into generic request options summary: Turns REST API endpoints into generic request options
homepage: homepage:

View File

@@ -1,6 +1,6 @@
--- ---
name: "@octokit/graphql" name: "@octokit/graphql"
version: 7.0.2 version: 4.6.4
type: npm type: npm
summary: GitHub GraphQL API client for browsers and Node summary: GitHub GraphQL API client for browsers and Node
homepage: homepage:

View File

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

View File

@@ -1,8 +1,8 @@
--- ---
name: "@octokit/openapi-types" name: "@octokit/openapi-types"
version: 23.0.1 version: 7.3.2
type: npm type: npm
summary: Generated TypeScript definitions based on GitHub's OpenAPI spec for api.github.com summary: Generated TypeScript definitions based on GitHub's OpenAPI spec
homepage: homepage:
license: mit license: mit
licenses: licenses:

View File

@@ -1,6 +1,6 @@
--- ---
name: "@octokit/plugin-paginate-rest" name: "@octokit/plugin-paginate-rest"
version: 9.1.0 version: 2.13.5
type: npm type: npm
summary: Octokit plugin to paginate REST API endpoint responses summary: Octokit plugin to paginate REST API endpoint responses
homepage: homepage:

View File

@@ -1,6 +1,6 @@
--- ---
name: "@octokit/plugin-rest-endpoint-methods" name: "@octokit/plugin-rest-endpoint-methods"
version: 10.1.0 version: 5.3.1
type: npm type: npm
summary: Octokit plugin adding one method for all of api.github.com REST API endpoints summary: Octokit plugin adding one method for all of api.github.com REST API endpoints
homepage: homepage:

View File

@@ -1,6 +1,6 @@
--- ---
name: "@octokit/request-error" name: "@octokit/request-error"
version: 5.1.1 version: 2.1.0
type: npm type: npm
summary: Error class for Octokit request errors summary: Error class for Octokit request errors
homepage: homepage:

View File

@@ -1,9 +1,9 @@
--- ---
name: "@octokit/request" name: "@octokit/request"
version: 8.1.4 version: 5.6.0
type: npm type: npm
summary: Send parameterized requests to GitHub's APIs with sensible defaults in browsers summary: "Send parameterized requests to GitHubâ\x80\x99s APIs with sensible defaults
and Node in browsers and Node"
homepage: homepage:
license: mit license: mit
licenses: licenses:

View File

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

View File

@@ -1,6 +1,6 @@
--- ---
name: "@octokit/types" name: "@octokit/types"
version: 12.1.0 version: 6.16.4
type: npm type: npm
summary: Shared TypeScript definitions for Octokit projects summary: Shared TypeScript definitions for Octokit projects
homepage: homepage:

View File

@@ -1,6 +1,6 @@
--- ---
name: balanced-match name: balanced-match
version: 1.0.2 version: 1.0.0
type: npm type: npm
summary: Match balanced character pairs, like "{" and "}" summary: Match balanced character pairs, like "{" and "}"
homepage: https://github.com/juliangruber/balanced-match homepage: https://github.com/juliangruber/balanced-match

View File

@@ -1,6 +1,6 @@
--- ---
name: before-after-hook name: before-after-hook
version: 2.2.3 version: 2.2.2
type: npm type: npm
summary: asynchronous before/error/after hooks for internal functionality summary: asynchronous before/error/after hooks for internal functionality
homepage: homepage:

View File

@@ -1,6 +1,6 @@
--- ---
name: brace-expansion name: brace-expansion
version: 2.0.1 version: 1.1.11
type: npm type: npm
summary: Brace expansion as known from sh/bash summary: Brace expansion as known from sh/bash
homepage: https://github.com/juliangruber/brace-expansion homepage: https://github.com/juliangruber/brace-expansion

View File

@@ -1,16 +1,14 @@
--- ---
name: bottleneck name: concat-map
version: 2.19.5 version: 0.0.1
type: npm type: npm
summary: Distributed task scheduler and rate limiter summary: concatenative mapdashery
homepage: homepage:
license: mit license: other
licenses: licenses:
- sources: LICENSE - sources: LICENSE
text: | text: |
The MIT License (MIT) This software is released under the MIT license:
Copyright (c) 2014 Simon Grondin
Permission is hereby granted, free of charge, to any person obtaining a copy of Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in this software and associated documentation files (the "Software"), to deal in
@@ -28,4 +26,6 @@ licenses:
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- sources: README.markdown
text: MIT
notices: [] notices: []

View File

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

View File

@@ -1,6 +1,6 @@
--- ---
name: minimatch name: minimatch
version: 10.0.1 version: 3.1.2
type: npm type: npm
summary: a glob matcher in javascript summary: a glob matcher in javascript
homepage: homepage:
@@ -10,7 +10,7 @@ licenses:
text: | text: |
The ISC License The ISC License
Copyright (c) 2011-2022 Isaac Z. Schlueter and Contributors Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above purpose with or without fee is hereby granted, provided that the above

56
.licenses/npm/node-fetch.dep.yml generated Normal file
View File

@@ -0,0 +1,56 @@
---
name: node-fetch
version: 2.6.7
type: npm
summary: A light-weight module that brings window.fetch to node.js
homepage: https://github.com/bitinn/node-fetch
license: mit
licenses:
- sources: LICENSE.md
text: |+
The MIT License (MIT)
Copyright (c) 2016 David Frank
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- sources: README.md
text: |-
MIT
[npm-image]: https://flat.badgen.net/npm/v/node-fetch
[npm-url]: https://www.npmjs.com/package/node-fetch
[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch
[travis-url]: https://travis-ci.org/bitinn/node-fetch
[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master
[codecov-url]: https://codecov.io/gh/bitinn/node-fetch
[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch
[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch
[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square
[discord-url]: https://discord.gg/Zxbndcm
[opencollective-image]: https://opencollective.com/node-fetch/backers.svg
[opencollective-url]: https://opencollective.com/node-fetch
[whatwg-fetch]: https://fetch.spec.whatwg.org/
[response-init]: https://fetch.spec.whatwg.org/#responseinit
[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams
[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers
[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md
[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md
[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md
notices: []

View File

@@ -1,17 +1,15 @@
--- ---
name: "@octokit/plugin-retry" name: tr46
version: 6.0.1 version: 0.0.3
type: npm type: npm
summary: Automatic retry plugin for octokit summary: An implementation of the Unicode TR46 spec
homepage: homepage: https://github.com/Sebmaster/tr46.js#readme
license: mit license: mit
licenses: licenses:
- sources: LICENSE - sources: Auto-generated MIT license text
text: | text: |
MIT License MIT License
Copyright (c) 2018 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
@@ -29,6 +27,4 @@ licenses:
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
- sources: README.md
text: "[MIT](LICENSE)"
notices: [] notices: []

View File

@@ -1,16 +1,16 @@
--- ---
name: "@actions/io" name: uuid
version: 1.1.3 version: 8.3.2
type: npm type: npm
summary: Actions io lib summary: RFC4122 (v1, v4, and v5) UUIDs
homepage: https://github.com/actions/toolkit/tree/main/packages/io homepage:
license: mit license: mit
licenses: licenses:
- sources: LICENSE.md - sources: LICENSE.md
text: |- text: |
The MIT License (MIT) The MIT License (MIT)
Copyright 2019 GitHub Copyright (c) 2010-2020 Robert Kieffer and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

23
.licenses/npm/webidl-conversions.dep.yml generated Normal file
View File

@@ -0,0 +1,23 @@
---
name: webidl-conversions
version: 3.0.1
type: npm
summary: Implements the WebIDL algorithms for converting to and from JavaScript values
homepage:
license: bsd-2-clause
licenses:
- sources: LICENSE.md
text: |
# The BSD 2-Clause License
Copyright (c) 2014, Domenic Denicola
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
notices: []

View File

@@ -1,16 +1,16 @@
--- ---
name: undici name: whatwg-url
version: 5.29.0 version: 5.0.0
type: npm type: npm
summary: An HTTP/1.1 client, written from scratch for Node.js summary: An implementation of the WHATWG URL Standard's URL API and parsing machinery
homepage: https://undici.nodejs.org homepage:
license: mit license: mit
licenses: licenses:
- sources: LICENSE - sources: LICENSE.txt
text: | text: |
MIT License The MIT License (MIT)
Copyright (c) Matteo Collina and Undici contributors Copyright (c) 20152016 Sebastian Mayr
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
@@ -19,16 +19,14 @@ licenses:
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in
copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
SOFTWARE. THE SOFTWARE.
- sources: README.md
text: MIT
notices: [] notices: []

View File

@@ -1,8 +0,0 @@
# Ignore list
/*
# Do not ignore these folders:
!__tests__/
!__mocks__/
!.github/
!src/

View File

@@ -1,11 +0,0 @@
// This is a reusable configuration file copied from https://github.com/actions/reusable-workflows/tree/main/reusable-configurations. Please don't make changes to this file as it's the subject of an automatic update.
module.exports = {
printWidth: 80,
tabWidth: 2,
useTabs: false,
semi: true,
singleQuote: true,
trailingComma: 'none',
bracketSpacing: false,
arrowParens: 'avoid'
};

12
.prettierrc.json Normal file
View File

@@ -0,0 +1,12 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": false,
"arrowParens": "avoid",
"parser": "typescript",
"endOfLine": "auto"
}

View File

@@ -1 +1,3 @@
* @actions/setup-actions-team * @actions/actions-runtime
* @actions/runner-images-team

291
README.md
View File

@@ -1,154 +1,97 @@
# Pull Request Labeler # Pull Request Labeler
[![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) <p align="left">
<a href="https://github.com/actions/labeler/actions?query=workflow%3A%22Build+%26+Test%22++">
<img alt="build and test status" src="https://github.com/actions/labeler/actions/workflows/build_test.yml/badge.svg">
</a>
<a href="https://david-dm.org/actions/labeler">
<img alt="dependencies" src="https://status.david-dm.org/gh/actions/labeler.svg">
</a>
</p>
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.
## Breaking changes in V5
1) The ability to apply labels based on the names of base and/or head branches was added ([#186](https://github.com/actions/labeler/issues/186) and [#54](https://github.com/actions/labeler/issues/54)). The match object for changed files was expanded with new combinations in order to make it more intuitive and flexible ([#423](https://github.com/actions/labeler/issues/423) and [#101](https://github.com/actions/labeler/issues/101)). As a result, the configuration file structure was significantly redesigned and is not compatible with the structure of the previous version. Please read the documentation below to find out how to adapt your configuration files for use with the new action version.
2) The bug related to the `sync-labels` input was fixed ([#112](https://github.com/actions/labeler/issues/112)). Now the input value is read correctly.
3) By default, `dot` input is set to `true`. Now, paths starting with a dot (e.g. `.github`) are matched by default.
4) Version 5 of this action updated the [runtime to Node.js 20](https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#runs-for-javascript-actions). All scripts are now run with Node.js 20 instead of Node.js 16 and are affected by any breaking changes between Node.js 16 and 20.
> [!IMPORTANT]
> Before the update to the v5, please check out [this information](#notes-regarding-pull_request_target-event) about the `pull_request_target` event trigger.
## 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: - any: ['list', 'of', 'globs']
- any-glob-to-any-file: ['list', 'of', 'globs'] all: ['list', 'of', 'globs']
- any-glob-to-all-files: ['list', 'of', 'globs']
- all-globs-to-any-file: ['list', 'of', 'globs']
- all-globs-to-all-files: ['list', 'of', 'globs']
- base-branch: ['list', 'of', 'regexps']
- head-branch: ['list', 'of', 'regexps']
``` ```
There are two top-level keys, `any` and `all`, which both accept the same configuration 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:
- any-glob-to-any-file: ['list', 'of', 'globs']
- any-glob-to-all-files: ['list', 'of', 'globs']
- all-globs-to-any-file: ['list', 'of', 'globs']
- all-globs-to-all-files: ['list', 'of', 'globs']
- base-branch: ['list', 'of', 'regexps']
- head-branch: ['list', 'of', 'regexps']
- all:
- changed-files:
- any-glob-to-any-file: ['list', 'of', 'globs']
- any-glob-to-all-files: ['list', 'of', 'globs']
- all-globs-to-any-file: ['list', 'of', 'globs']
- all-globs-to-all-files: ['list', 'of', 'globs']
- base-branch: ['list', 'of', 'regexps']
- head-branch: ['list', 'of', 'regexps']
```
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.
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 for the label to be applied * `any`: match ALL globs against ANY changed path
- `any`: if ANY of the provided options match then the label will be applied * `all`: match ALL globs against ALL changed paths
- `base-branch`: match regexps against the base branch name
- `head-branch`: match regexps against the head branch name
- `changed-files`: match glob patterns against the changed paths
- `any-glob-to-any-file`: ANY glob must match against ANY changed file
- `any-glob-to-all-files`: ANY glob must match against ALL changed files
- `all-globs-to-any-file`: ALL globs must match against ANY changed file
- `all-globs-to-all-files`: ALL globs must match against ALL changed files
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
Documentation: label1:
- changed-files: - example1/*
- any-glob-to-any-file: 'docs/*'
``` ```
and and
```yml ```yml
Documentation: label1:
- any: - any: ['example1/*']
- changed-files:
- any-glob-to-any-file: 'docs/*'
``` ```
If path globs are combined with `!` negation, you can write complex matching rules. See the examples below for more information. 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 'root' label to any root file changes # Add 'label1' to any changes within 'example' folder or any subfolders
# Quotation marks are required for the leading asterisk label1:
root: - example/**/*
- changed-files:
- any-glob-to-any-file: '*'
# Add 'AnyChange' label to any changes within the entire repository # Add 'label2' to any file changes within 'example2' folder
AnyChange: label2: example2/*
- changed-files:
- any-glob-to-any-file: '**'
# Add 'Documentation' label to any changes within 'docs' folder or any subfolders # Add label3 to any change to .txt files within the entire repository. Quotation marks are required for the leading asterisk
Documentation: label3:
- changed-files: - '**/*.txt'
- any-glob-to-any-file: docs/**
# Add 'Documentation' label to any file changes within 'docs' folder ```
Documentation:
- changed-files:
- any-glob-to-any-file: docs/*
# Add 'Documentation' label to any file changes within 'docs' or 'guides' folders #### Common Examples
Documentation:
- changed-files:
- any-glob-to-any-file:
- docs/*
- guides/*
## Equivalent of the above mentioned configuration using another syntax ```yml
Documentation: # Add 'repo' label to any root file changes
- changed-files: repo:
- any-glob-to-any-file: ['docs/*', 'guides/*'] - '*'
# Add 'Documentation' label to any change to .md files within the entire repository # Add '@domain/core' label to any change within the 'core' package
Documentation: '@domain/core':
- changed-files: - package/core/*
- any-glob-to-any-file: '**/*.md' - package/core/**/*
# Add 'test' label to any change to *.spec.js files within the source dir
test:
- 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:
- all: - any: ['src/**/*', '!src/docs/*']
- changed-files:
- any-glob-to-any-file: 'src/**/*'
- all-globs-to-all-files: '!src/docs/*'
# Add 'feature' label to any PR where the head branch name starts with `feature` or has a `feature` section in the name # Add 'frontend` label to any change to *.js files as long as the `main.js` hasn't changed
feature: frontend:
- head-branch: ['^feature', 'feature'] - any: ['src/**/*.js']
all: ['!src/main.js']
# Add 'release' label to any PR that is opened against the `main` branch
release:
- base-branch: 'main'
``` ```
### Create Workflow ### Create Workflow
Create a workflow (e.g. `.github/workflows/labeler.yml` see [Creating a Workflow file](https://docs.github.com/en/actions/writing-workflows/quickstart#creating-your-first-workflow)) to utilize the labeler action with content: Create a workflow (eg: `.github/workflows/labeler.yml` see [Creating a Workflow file](https://help.github.com/en/articles/configuring-a-workflow#creating-a-workflow-file)) to utilize the labeler action with content:
```yml ```yml
name: "Pull Request Labeler" name: "Pull Request Labeler"
@@ -156,139 +99,29 @@ on:
- pull_request_target - pull_request_target
jobs: jobs:
labeler: triage:
permissions: permissions:
contents: read contents: read
pull-requests: write pull-requests: write
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/labeler@v6 - uses: actions/labeler@v4
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
``` ```
_Note: This grants access to the `GITHUB_TOKEN` so the action can make calls to GitHub's rest API_
#### Inputs #### Inputs
Various inputs are defined in [`action.yml`](action.yml) to let you configure the labeler: Various inputs are defined in [`action.yml`](action.yml) to let you configure the labeler:
| Name | Description | Default | | Name | Description | Default |
|----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------| | - | - | - |
| `repo-token` | Token to use to authorize label changes. Typically the GITHUB_TOKEN secret | `github.token` | | `repo-token` | Token to use to authorize label changes. Typically the GITHUB_TOKEN secret, with `contents:read` and `pull-requests:write` access | N/A |
| `configuration-path` | The path to the label configuration file. If the file doesn't exist at the specified path on the runner, action will read from the source repository via the Github API. | `.github/labeler.yml` | | `configuration-path` | The path to the label configuration file | `.github/labeler.yml` |
| `sync-labels` | Whether or not to remove labels when matching files are reverted or no longer changed by the PR | `false` | | `sync-labels` | Whether or not to remove labels when matching files are reverted or no longer changed by the PR | `false`
| `dot` | Whether or not to auto-include paths starting with dot (e.g. `.github`) | `true` |
| `pr-number` | The number(s) of pull request to update, rather than detecting from the workflow context | N/A |
##### Using `configuration-path` input together with the `@actions/checkout` action # Contributions
You might want to use action called [@actions/checkout](https://github.com/actions/checkout) to upload label configuration file onto the runner from the current or any other repositories. See usage example below:
```yml
steps:
- uses: actions/checkout@v5 # Uploads repository content to the runner
with:
repository: "owner/repositoryName" # The one of the available inputs, visit https://github.com/actions/checkout#readme to find more
- uses: actions/labeler@v6
with:
configuration-path: 'path/to/the/uploaded/configuration/file'
```
##### Example workflow specifying pull request numbers
```yml
name: "Label Previous Pull Requests"
on:
schedule:
- cron: "0 1 * * 1"
jobs:
labeler:
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
steps:
# Label PRs 1, 2, and 3
- uses: actions/labeler@v6
with:
pr-number: |
1
2
3
```
**Note:** in normal usage the `pr-number` input is not required as the action will detect the PR number from the workflow context.
#### Outputs
Labeler provides the following outputs:
| Name | Description |
|--------------|-----------------------------------------------------------|
| `new-labels` | A comma-separated list of all new labels |
| `all-labels` | A comma-separated list of all labels that the PR contains |
The following example performs steps based on the output of labeler:
```yml
name: "Pull Request Labeler"
on:
- pull_request_target
jobs:
labeler:
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
steps:
- id: label-the-PR
uses: actions/labeler@v6
- id: run-frontend-tests
if: contains(steps.label-the-PR.outputs.all-labels, 'frontend')
run: |
echo "Running frontend tests..."
# Put your commands for running frontend tests here
- id: run-backend-tests
if: contains(steps.label-the-PR.outputs.all-labels, 'backend')
run: |
echo "Running backend tests..."
# Put your commands for running backend tests here
```
## Recommended Permissions
In order to add labels to pull requests, the GitHub labeler action requires write permissions on the pull-request. However, when the action runs on a pull request from a forked repository, GitHub only grants read access tokens for `pull_request` events, at most. If you encounter an `Error: HttpError: Resource not accessible by integration`, it's likely due to these permission constraints. To resolve this issue, you can modify the `on:` section of your workflow to use
[`pull_request_target`](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target) instead of `pull_request` (see example [above](#create-workflow)). This change allows the action to have write access, because `pull_request_target` alters the [context of the action](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target) and safely grants additional permissions. There exists a potentially dangerous misuse of the pull_request_target workflow trigger that may lead to malicious PR authors (i.e. attackers) being able to obtain repository write permissions or stealing repository secrets, Hence it is advisible that pull_request_target should only be used in workflows that are carefully designed to avoid executing untrusted code and to also ensure that workflows using pull_request_target limit access to sensitive resources. Refer to the [GitHub token permissions documentation](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token) for more details about access levels and event contexts.
```yml
permissions:
contents: read
pull-requests: write
```
## Notes regarding `pull_request_target` event
Using the `pull_request_target` event trigger involves several peculiarities related to initial set up of the labeler or updating version of the labeler.
### Initial set up of the labeler action
When submitting an initial pull request to a repository using the `pull_request_target` event, the labeler workflow will not run on that pull request because the `pull_request_target` execution runs off the base branch instead of the pull request's branch. Unfortunately this means the introduction of the labeler can not be verified during that pull request and it needs to be committed blindly.
### Updating major version of the labeler
When submitting a pull request that includes updates of the labeler action version and associated configuration files, using the `pull_request_target` event may result in a failed workflow. This is due to the nature of `pull_request_target`, which uses the code from the base branch rather than the branch linked to the pull request — so, potentially outdated configuration files may not be compatible with the updated labeler action.
To prevent this issue, you can switch to using the `pull_request` event temporarily, before merging. This event execution draws from the code within the branch of your pull request, allowing you to verify the new configuration's compatibility with the updated labeler action.
```yml
name: "Pull Request Labeler"
on:
- pull_request
```
Once you confirm that the updated configuration files function as intended, you can then revert to using the `pull_request_target` event before merging the pull request. Following this step ensures that your workflow is robust and free from disruptions.
## Contributions
Contributions are welcome! See the [Contributor's Guide](CONTRIBUTING.md). Contributions are welcome! See the [Contributor's Guide](CONTRIBUTING.md).

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

View File

@@ -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,270 +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,
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);
});
});
});

View File

@@ -1,17 +0,0 @@
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']

View File

@@ -1,8 +0,0 @@
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']

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']
- any-glob-to-any-file: ['*.pdf']

View File

@@ -1,13 +1,6 @@
import * as yaml from 'js-yaml'; import {checkGlobs} from '../src/labeler';
import * as core from '@actions/core'; 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'); jest.mock('@actions/core');
@@ -17,145 +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', () => {
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}
]
}
]);
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);
});
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']}]}]}
];
describe('checkGlobs', () => {
it('returns true when our pattern does match changed files', () => { it('returns true when our pattern does match changed files', () => {
const changedFiles = ['foo.txt', 'bar.txt']; const changedFiles = ['foo.txt', 'bar.txt'];
const result = checkMatchConfigs(changedFiles, matchConfig, false); const result = checkGlobs(changedFiles, matchConfig);
expect(result).toBeTruthy(); expect(result).toBeTruthy();
}); });
it('returns false when our pattern does not match changed files', () => { it('returns false when our pattern does not match changed files', () => {
const changedFiles = ['foo.docx']; const changedFiles = ['foo.docx'];
const result = checkMatchConfigs(changedFiles, matchConfig, false); const result = checkGlobs(changedFiles, matchConfig);
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();
});
});
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);
});
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);
});
});
}); });

View File

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

View File

@@ -3,9 +3,7 @@ description: 'Automatically label new pull requests based on the paths of files
author: 'GitHub' author: 'GitHub'
inputs: inputs:
repo-token: repo-token:
description: 'The GitHub token used to manage labels' description: 'The GITHUB_TOKEN secret'
required: false
default: ${{ github.token }}
configuration-path: configuration-path:
description: 'The path for the label configurations' description: 'The path for the label configurations'
default: '.github/labeler.yml' default: '.github/labeler.yml'
@@ -14,19 +12,7 @@ inputs:
description: 'Whether or not to remove labels when matching files are reverted' description: 'Whether or not to remove labels when matching files are reverted'
default: false default: false
required: false required: false
dot:
description: 'Whether or not to auto-include paths starting with dot (e.g. `.github`)'
default: true
required: false
pr-number:
description: 'The pull request number(s)'
required: false
outputs:
new-labels:
description: 'A comma-separated list of all new labels'
all-labels:
description: 'A comma-separated list of all labels that the PR contains'
runs: runs:
using: 'node24' using: 'node16'
main: 'dist/index.js' main: 'dist/index.js'

42736
dist/index.js vendored

File diff suppressed because one or more lines are too long

8039
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,17 +1,13 @@
{ {
"name": "labeler", "name": "labeler",
"version": "6.0.0", "version": "4.0.1",
"description": "Labels pull requests by files altered", "description": "Labels pull requests by files altered",
"main": "lib/main.js", "main": "lib/main.js",
"engines": {
"node": ">=24"
},
"scripts": { "scripts": {
"build": "tsc && ncc build lib/main.js", "build": "tsc && ncc build lib/main.js",
"format": "prettier --no-error-on-unmatched-pattern --config ./.prettierrc.js --write \"**/*.{ts,yml,yaml}\"", "format": "prettier --write **/*.ts",
"format-check": "prettier --no-error-on-unmatched-pattern --config ./.prettierrc.js --check \"**/*.{ts,yml,yaml}\"", "format-check": "prettier --check **/*.ts",
"lint": "eslint --config ./.eslintrc.js \"**/*.ts\"", "lint": "echo \"Fake command that does nothing. It is used in reusable workflows\"",
"lint:fix": "eslint --config ./.eslintrc.js \"**/*.ts\" --fix",
"test": "jest" "test": "jest"
}, },
"repository": { "repository": {
@@ -27,30 +23,20 @@
"author": "GitHub", "author": "GitHub",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/core": "^1.11.1", "@actions/core": "^1.10.0",
"@actions/github": "^6.0.0", "@actions/github": "^5.0.0",
"@octokit/plugin-retry": "^6.0.0",
"js-yaml": "^4.1.0", "js-yaml": "^4.1.0",
"lodash.isequal": "^4.5.0", "minimatch": "^3.0.4"
"minimatch": "^10.0.1"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "^29.5.14", "@types/jest": "^27.4.1",
"@types/js-yaml": "^4.0.9", "@types/node": "^16.11.7",
"@types/lodash.isequal": "^4.5.8", "@types/minimatch": "^3.0.5",
"@types/minimatch": "^5.1.2", "@types/js-yaml": "^4.0.5",
"@types/node": "^24.1.0", "@vercel/ncc": "^0.34.0",
"@typescript-eslint/eslint-plugin": "^7.3.1", "jest": "^27.5.1",
"@typescript-eslint/parser": "^7.18.0", "prettier": "^2.7.1",
"@vercel/ncc": "^0.38.3", "ts-jest": "^27.1.3",
"eslint": "^8.57.0", "typescript": "^4.8.4"
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jest": "^28.11.0",
"eslint-plugin-node": "^11.1.0",
"jest": "^29.7.0",
"prettier": "^3.4.2",
"ts-jest": "^29.2.5",
"typescript": "^5.7.3"
} }
} }

View File

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

View File

@@ -1,38 +0,0 @@
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
};
}
}

View File

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

View File

@@ -1,126 +0,0 @@
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
};
}

View File

@@ -1,6 +0,0 @@
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';

View File

@@ -1,15 +0,0 @@
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
});
};

View File

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

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,360 +0,0 @@
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;
}

View File

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

View File

@@ -1,28 +0,0 @@
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;
};

View File

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

View File

@@ -1,227 +1,260 @@
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 pluginRetry from '@octokit/plugin-retry'; import * as yaml from 'js-yaml';
import * as api from './api'; import {Minimatch, IMinimatch} from 'minimatch';
import isEqual from 'lodash.isequal';
import {getInputs} from './get-inputs';
import {BaseMatchConfig, MatchConfig} from './api/get-label-configs'; interface MatchConfig {
all?: string[];
import {checkAllChangedFiles, checkAnyChangedFiles} from './changedFiles'; any?: string[];
}
import {checkAnyBranch, checkAllBranch} from './branch';
type StringOrMatchConfig = string | MatchConfig;
type ClientType = ReturnType<typeof github.getOctokit>; type ClientType = ReturnType<typeof github.getOctokit>;
// GitHub Issues cannot have more than 100 labels export async function run() {
const GITHUB_MAX_LABELS = 100; try {
const token = core.getInput('repo-token', {required: true});
const configPath = core.getInput('configuration-path', {required: true});
const syncLabels = !!core.getInput('sync-labels', {required: false});
export const run = () => const prNumber = getPrNumber();
labeler().catch(error => { if (!prNumber) {
core.error(error); console.log('Could not get pull request number from context, exiting');
core.setFailed(error.message);
});
async function labeler() {
const {token, configPath, syncLabels, dot, prNumbers} = getInputs();
if (!prNumbers.length) {
core.warning('Could not get pull request number(s), exiting');
return; return;
} }
const client: ClientType = github.getOctokit(token, {}, pluginRetry.retry); const client: ClientType = github.getOctokit(token);
const pullRequests = api.getPullRequests(client, prNumbers); const {data: pullRequest} = await client.rest.pulls.get({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: prNumber
});
for await (const pullRequest of pullRequests) { core.debug(`fetching changed files for pr #${prNumber}`);
const labelConfigs: Map<string, MatchConfig[]> = await api.getLabelConfigs( const changedFiles: string[] = await getChangedFiles(client, prNumber);
const labelGlobs: Map<string, StringOrMatchConfig[]> = await getLabelGlobs(
client, client,
configPath configPath
); );
const preexistingLabels = pullRequest.data.labels.map(l => l.name);
const allLabels: Set<string> = new Set<string>(preexistingLabels);
for (const [label, configs] of labelConfigs.entries()) { const labels: string[] = [];
const labelsToRemove: string[] = [];
for (const [label, globs] of labelGlobs.entries()) {
core.debug(`processing ${label}`); core.debug(`processing ${label}`);
if (checkMatchConfigs(pullRequest.changedFiles, configs, dot)) { if (checkGlobs(changedFiles, globs)) {
allLabels.add(label); labels.push(label);
} else if (syncLabels) { } else if (pullRequest.labels.find(l => l.name === label)) {
allLabels.delete(label); labelsToRemove.push(label);
} }
} }
const labelsToAdd = [...allLabels].slice(0, GITHUB_MAX_LABELS); if (labels.length > 0) {
const excessLabels = [...allLabels].slice(GITHUB_MAX_LABELS); await addLabels(client, prNumber, labels);
}
let newLabels: string[] = []; if (syncLabels && labelsToRemove.length) {
await removeLabels(client, prNumber, labelsToRemove);
try {
if (!isEqual(labelsToAdd, preexistingLabels)) {
await api.setLabels(client, pullRequest.number, labelsToAdd);
newLabels = labelsToAdd.filter(
label => !preexistingLabels.includes(label)
);
} }
} catch (error: any) { } catch (error: any) {
if ( core.error(error);
error.name !== 'HttpError' ||
error.message !== 'Resource not accessible by integration'
) {
throw error;
}
core.warning(
`The action requires write permission to add labels to pull requests. For more information please refer to the action documentation: https://github.com/actions/labeler#recommended-permissions`,
{
title: `${process.env['GITHUB_ACTION_REPOSITORY']} running under '${github.context.eventName}' is misconfigured`
}
);
core.setFailed(error.message); core.setFailed(error.message);
}
return;
} }
core.setOutput('new-labels', newLabels.join(',')); function getPrNumber(): number | undefined {
core.setOutput('all-labels', labelsToAdd.join(',')); const pullRequest = github.context.payload.pull_request;
if (!pullRequest) {
return undefined;
}
if (excessLabels.length) { return pullRequest.number;
core.warning( }
`Maximum of ${GITHUB_MAX_LABELS} labels allowed. Excess labels: ${excessLabels.join(
', ' async function getChangedFiles(
)}`, client: ClientType,
{title: 'Label limit for a PR exceeded'} 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,
configurationPath: string
): Promise<Map<string, StringOrMatchConfig[]>> {
const configurationContent: string = await fetchContent(
client,
configurationPath
);
// loads (hopefully) a `{[label:string]: string | StringOrMatchConfig[]}`, but is `any`:
const configObject: any = yaml.load(configurationContent);
// transform `any` => `Map<string,StringOrMatchConfig[]>` or throw if yaml is malformed:
return getLabelGlobMapFromObject(configObject);
}
async function fetchContent(
client: ClientType,
repoPath: string
): Promise<string> {
const response: any = await client.rest.repos.getContent({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
path: repoPath,
ref: github.context.sha
});
return Buffer.from(response.data.content, response.data.encoding).toString();
}
function getLabelGlobMapFromObject(
configObject: any
): Map<string, StringOrMatchConfig[]> {
const labelGlobs: Map<string, StringOrMatchConfig[]> = new Map();
for (const label in configObject) {
if (typeof configObject[label] === 'string') {
labelGlobs.set(label, [configObject[label]]);
} else if (configObject[label] instanceof Array) {
labelGlobs.set(label, configObject[label]);
} else {
throw Error(
`found unexpected type for label ${label} (should be string or array of globs)`
); );
} }
} }
return labelGlobs;
} }
export function checkMatchConfigs( function toMatchConfig(config: StringOrMatchConfig): MatchConfig {
if (typeof config === 'string') {
return {
any: [config]
};
}
return config;
}
function printPattern(matcher: IMinimatch): string {
return (matcher.negate ? '!' : '') + matcher.pattern;
}
export function checkGlobs(
changedFiles: string[], changedFiles: string[],
matchConfigs: MatchConfig[], globs: StringOrMatchConfig[]
dot: boolean
): 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, dot)) { const matchConfig = toMatchConfig(glob);
return false; if (checkMatch(changedFiles, matchConfig)) {
}
}
return true; return true;
} }
}
function checkMatch(
changedFiles: string[],
matchConfig: MatchConfig,
dot: boolean
): boolean {
if (!Object.keys(matchConfig).length) {
core.debug(` no "any" or "all" patterns to check`);
return false; return false;
} }
if (matchConfig.all) { function isMatch(changedFile: string, matchers: IMinimatch[]): boolean {
if (!checkAll(matchConfig.all, changedFiles, dot)) { core.debug(` matching patterns against file ${changedFile}`);
return false; for (const matcher of matchers) {
} core.debug(` - ${printPattern(matcher)}`);
} if (!matcher.match(changedFile)) {
core.debug(` ${printPattern(matcher)} did not match`);
if (matchConfig.any) {
if (!checkAny(matchConfig.any, changedFiles, dot)) {
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[],
dot: boolean
): 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}`);
) {
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; return true;
} }
} }
if (matchConfig.changedFiles) { core.debug(` "any" patterns did not match any files`);
if (checkAnyChangedFiles(changedFiles, matchConfig.changedFiles, dot)) {
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`);
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[],
dot: boolean
): boolean {
core.debug(` checking "all" patterns`); core.debug(` checking "all" patterns`);
if ( for (const changedFile of changedFiles) {
!matchConfigs.length || if (!isMatch(changedFile, matchers)) {
!matchConfigs.some(configOption => Object.keys(configOption).length) core.debug(` "all" patterns did not match against ${changedFile}`);
) {
core.debug(` no "all" patterns to check`);
return false;
}
for (const matchConfig of matchConfigs) {
if (matchConfig.baseBranch) {
if (!checkAllBranch(matchConfig.baseBranch, 'base')) {
core.debug(` "all" patterns did not match`);
return false; return false;
} }
} }
if (matchConfig.changedFiles) { core.debug(` "all" patterns matched all files`);
if (!changedFiles.length) {
core.debug(` no files to check "changed-files" patterns against`);
return false;
}
if (!checkAllChangedFiles(changedFiles, matchConfig.changedFiles, dot)) {
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;
} }
function checkMatch(changedFiles: string[], matchConfig: MatchConfig): boolean {
if (matchConfig.all !== undefined) {
if (!checkAll(changedFiles, matchConfig.all)) {
return false;
}
}
if (matchConfig.any !== undefined) {
if (!checkAny(changedFiles, matchConfig.any)) {
return false;
}
}
return true;
}
async function addLabels(
client: ClientType,
prNumber: number,
labels: string[]
) {
await client.rest.issues.addLabels({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: prNumber,
labels: labels
});
}
async function removeLabels(
client: ClientType,
prNumber: number,
labels: string[]
) {
await Promise.all(
labels.map(label =>
client.rest.issues.removeLabel({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: prNumber,
name: label
})
)
);
}

View File

@@ -1,13 +0,0 @@
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);
}