Compare commits

..
Author SHA1 Message Date
Andy McKay 9df4cea915 Mark this repository as unmaintained
Prepare to mark this repository as unmaintained, let's see what other Actions we can find that also do this.
2021-03-29 15:45:24 -07:00
30 changed files with 27119 additions and 41567 deletions
+8 -27
View File
@@ -1,6 +1,6 @@
{ {
"plugins": ["jest", "@typescript-eslint"], "plugins": ["jest", "@typescript-eslint"],
"extends": ["plugin:github/recommended","plugin:@typescript-eslint/recommended"], "extends": ["plugin:github/es6"],
"parser": "@typescript-eslint/parser", "parser": "@typescript-eslint/parser",
"parserOptions": { "parserOptions": {
"ecmaVersion": 9, "ecmaVersion": 9,
@@ -17,29 +17,13 @@
"@typescript-eslint/no-require-imports": "error", "@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/array-type": "error", "@typescript-eslint/array-type": "error",
"@typescript-eslint/await-thenable": "error", "@typescript-eslint/await-thenable": "error",
"@typescript-eslint/ban-ts-comment": "error", "@typescript-eslint/ban-ts-ignore": "error",
"camelcase": "off", "camelcase": "off",
"@typescript-eslint/naming-convention": [ "@typescript-eslint/camelcase": "error",
"error", "@typescript-eslint/class-name-casing": "error",
{
"selector": "class",
"format": ["PascalCase"]
},
{
"selector": "interface",
"format": ["PascalCase"]
},
{
"selector": "typeProperty",
"format": [],
"custom": {
"regex": "^[A-Z][A-Za-z]*$",
"match": false
}
}
],
"@typescript-eslint/explicit-function-return-type": ["error", {"allowExpressions": true}], "@typescript-eslint/explicit-function-return-type": ["error", {"allowExpressions": true}],
"@typescript-eslint/func-call-spacing": ["error", "never"], "@typescript-eslint/func-call-spacing": ["error", "never"],
"@typescript-eslint/generic-type-naming": ["error", "^[A-Z][A-Za-z]*$"],
"@typescript-eslint/no-array-constructor": "error", "@typescript-eslint/no-array-constructor": "error",
"@typescript-eslint/no-empty-interface": "error", "@typescript-eslint/no-empty-interface": "error",
"@typescript-eslint/no-explicit-any": "error", "@typescript-eslint/no-explicit-any": "error",
@@ -49,7 +33,7 @@
"@typescript-eslint/no-misused-new": "error", "@typescript-eslint/no-misused-new": "error",
"@typescript-eslint/no-namespace": "error", "@typescript-eslint/no-namespace": "error",
"@typescript-eslint/no-non-null-assertion": "warn", "@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/consistent-type-assertions": "error", "@typescript-eslint/no-object-literal-type-assertion": "error",
"@typescript-eslint/no-unnecessary-qualifier": "error", "@typescript-eslint/no-unnecessary-qualifier": "error",
"@typescript-eslint/no-unnecessary-type-assertion": "error", "@typescript-eslint/no-unnecessary-type-assertion": "error",
"@typescript-eslint/no-useless-constructor": "error", "@typescript-eslint/no-useless-constructor": "error",
@@ -57,7 +41,7 @@
"@typescript-eslint/prefer-for-of": "warn", "@typescript-eslint/prefer-for-of": "warn",
"@typescript-eslint/prefer-function-type": "warn", "@typescript-eslint/prefer-function-type": "warn",
"@typescript-eslint/prefer-includes": "error", "@typescript-eslint/prefer-includes": "error",
"@typescript-eslint/consistent-type-definitions": "error", "@typescript-eslint/prefer-interface": "error",
"@typescript-eslint/prefer-string-starts-ends-with": "error", "@typescript-eslint/prefer-string-starts-ends-with": "error",
"@typescript-eslint/promise-function-async": "error", "@typescript-eslint/promise-function-async": "error",
"@typescript-eslint/require-array-sort-compare": "error", "@typescript-eslint/require-array-sort-compare": "error",
@@ -66,10 +50,7 @@
"@typescript-eslint/semi": ["error", "never"], "@typescript-eslint/semi": ["error", "never"],
"@typescript-eslint/type-annotation-spacing": "error", "@typescript-eslint/type-annotation-spacing": "error",
"@typescript-eslint/unbound-method": "error", "@typescript-eslint/unbound-method": "error",
"no-console": "off", "no-console": "off"
"import/no-unresolved": "off",
"sort-imports": "off",
"filenames/match-regex": "off"
}, },
"env": { "env": {
"node": true, "node": true,
-51
View File
@@ -1,51 +0,0 @@
# `dist/index.js` is a special file in Actions.
# When you reference an action with `uses:` in a workflow,
# `index.js` is the code that will run.
# For our project, we generate this file through a build process
# from other source files.
# We need to make sure the checked-in `index.js` actually matches what we expect it to be.
name: Check dist/
on:
push:
branches:
- main
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
workflow_dispatch:
jobs:
check-dist:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set Node.js 16.x
uses: actions/setup-node@v1
with:
node-version: 16.x
- name: Install dependencies
run: npm ci
- name: Rebuild the index.js file
run: npm run build
- name: Compare the expected and actual dist/ directories
run: |
if [ "$(git diff --ignore-space-at-eol dist/ | wc -l)" -gt "0" ]; then
echo "Detected uncommitted changes after build. See status below:"
git diff
exit 1
fi
# If dist/ was different than expected, upload the expected version as an artifact
- uses: actions/upload-artifact@v2
if: ${{ failure() && steps.diff.conclusion == 'failure' }}
with:
name: dist
path: dist/
+2 -6
View File
@@ -1,12 +1,8 @@
name: Licensed name: Licensed
on: on:
push: push: {branches: main}
branches: pull_request: {branches: main}
- main
pull_request:
branches:
- main
jobs: jobs:
test: test:
+1 -5
View File
@@ -7,9 +7,6 @@ on: # rebuild any PRs and main branch changes
- main - main
- 'releases/*' - 'releases/*'
permissions:
packages: write
jobs: jobs:
package: # make sure build/ci work properly package: # make sure build/ci work properly
@@ -32,6 +29,5 @@ jobs:
- uses: ./ - uses: ./
name: Smoke Test Delete Package Versions Action name: Smoke Test Delete Package Versions Action
with: with:
package-name: 'action-ci-test-package' package-name: 'com.github.actions.test-package'
package-type: 'npm'
num-old-versions-to-delete: 0 num-old-versions-to-delete: 0
+1 -1
View File
@@ -1,6 +1,6 @@
--- ---
name: "@actions/core" name: "@actions/core"
version: 1.9.1 version: 1.2.0
type: npm type: npm
summary: Actions core lib summary: Actions core lib
homepage: https://github.com/actions/toolkit/tree/master/packages/core homepage: https://github.com/actions/toolkit/tree/master/packages/core
-32
View File
@@ -1,32 +0,0 @@
---
name: "@actions/http-client-1.0.11"
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: []
@@ -1,5 +1,5 @@
--- ---
name: "@actions/http-client-1.0.8" name: "@actions/http-client"
version: 1.0.8 version: 1.0.8
type: npm type: npm
summary: Actions Http Client summary: Actions Http Client
+1 -1
View File
@@ -1,6 +1,6 @@
--- ---
name: "@octokit/rest" name: "@octokit/rest"
version: 19.0.5 version: 16.43.1
type: npm type: npm
summary: GitHub REST API client for Node.js summary: GitHub REST API client for Node.js
homepage: https://github.com/octokit/rest.js#readme homepage: https://github.com/octokit/rest.js#readme
+1 -1
View File
@@ -1,6 +1,6 @@
--- ---
name: node-fetch name: node-fetch
version: 2.6.5 version: 2.6.0
type: npm type: npm
summary: A light-weight module that brings window.fetch to node.js summary: A light-weight module that brings window.fetch to node.js
homepage: https://github.com/bitinn/node-fetch homepage: https://github.com/bitinn/node-fetch
+1 -1
View File
@@ -1,6 +1,6 @@
--- ---
name: rxjs name: rxjs
version: 6.6.7 version: 6.5.4
type: npm type: npm
summary: Reactive Extensions for modern JavaScript summary: Reactive Extensions for modern JavaScript
homepage: https://github.com/ReactiveX/RxJS homepage: https://github.com/ReactiveX/RxJS
-28
View File
@@ -1,28 +0,0 @@
---
name: "tr46"
version: 0.0.3
type: npm
summary: An JavaScript implementation of Unicode Technical Standard #46: Unicode IDNA Compatibility Processing.
homepage: https://github.com/jsdom/tr46#readme
license: mit
licenses:
- sources: LICENSE.md
text: |
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: []
-23
View File
@@ -1,23 +0,0 @@
---
name: "webidl-conversions"
version: 3.0.1
type: npm
summary: Implements the Web IDL algorithms for converting to and from JavaScript values
homepage: https://github.com/jsdom/webidl-conversions#readme
license: bsd-2-clause
licenses:
- sources: LICENSE.md
text: |
All rights reserved.
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:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
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.
-28
View File
@@ -1,28 +0,0 @@
---
name: "whatwg-url"
version: 5.0.0
type: npm
summary: An implementation of the WHATWG URL Standard in JavaScript
homepage: https://github.com/jsdom/whatwg-url#readme
license: mit
licenses:
- sources: LICENSE.md
text: |
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: []
-1
View File
@@ -1 +0,0 @@
* @actions/packages
+152 -315
View File
@@ -1,385 +1,222 @@
# Delete Package Versions # Delete Package Versions
This action deletes versions of a package from [GitHub Packages](https://github.com/features/packages). This action will only delete a maximum of 100 versions in one run. **Please note:** This repository is currently unmaintained by a team of developers at GitHub. The
repository is here and you can use it as an example, or in Actions. However please be aware that
we are not going to be updating issues or pull requests on this repository.
**Maintained Actions:**
* [SmartsquareGmbH/delete-old-packages](https://github.com/SmartsquareGmbH/delete-old-packages)
To reflect this state weve marked this repository as Archived.
If you are having an issue or question about GitHub Actions then please [contact customer support](https://help.github.com/en/articles/about-github-actions#contacting-support).
If you have found a security issue [please submit it here](https://hackerone.com/github).
---
This action deletes versions of a package from [GitHub Packages](https://github.com/features/packages).
### What It Can Do ### What It Can Do
* Create a retention policy (delete all except n most recent pre-release versions)
* Delete all package versions except n most recent versions
* Delete oldest version(s)
* Ignore version(s) from deletion through regex
* Delete version(s) of a package that is hosted from a repo having access to package
* Delete version(s) of a package that is hosted from a repo not having access to package
* Delete a single version * Delete a single version
* Delete multiple versions * Delete multiple versions
* Delete specific version(s) * Delete specific version(s)
* Delete oldest version(s)
* Delete version(s) of a package that is hosted in the same repo that is executing the workflow
* Delete version(s) of a package that is hosted in a different repo than the one executing the workflow
# Usage # Usage
```yaml ```yaml
- uses: actions/delete-package-versions@v4 - uses: actions/delete-package-versions@v1
with: with:
# Can be a single package version id, or a comma separated list of package version ids. # Can be a single package version id, or a comma separated list of package version ids.
# Defaults to an empty string. # Defaults to an empty string.
package-version-ids: package-version-ids:
# Owner of the package. # Owner of the repo hosting the package.
# Defaults to the owner of the repo executing the workflow. # Defaults to the owner of the repo executing the workflow.
# Required if deleting a version from a package hosted in a different org than the one executing the workflow. # Required if deleting a version from a package hosted in a different repo than the one executing the workflow.
owner: owner:
# Name of the package. # Repo hosting the package.
# Required # Defaults to the repo executing the workflow.
package-name: # Required if deleting a version from a package hosted in a different repo than the one executing the workflow.
repo:
# Type of the package. Can be one of container, maven, npm, nuget, or rubygems. # Name of the package.
# Required # Defaults to an empty string.
package-type: # Required if `package-version-ids` input is not given.
package-name:
# The number of old versions to delete starting from the oldest version. # The number of old versions to delete starting from the oldest version.
# Defaults to 1. # Defaults to 1.
num-old-versions-to-delete: num-old-versions-to-delete:
# The number of latest versions to keep.
# This cannot be specified with `num-old-versions-to-delete`. By default, `min-versions-to-keep` takes precedence over `num-old-versions-to-delete`.
# When set to 0, all deletable versions will be deleted.
# When set greater than 0, all deletable package versions except the specified number will be deleted.
min-versions-to-keep:
# The package versions to exclude from deletion.
# Takes regex for the version name as input.
# By default nothing is ignored. This is ignored when `delete-only-pre-release-versions` is true
ignore-versions:
# If true it will delete only the pre-release versions.
# The number of pre-release versions to keep can be set by using `min-versions-to-keep` value with this.
# When `min-versions-to-keep` is 0, all pre-release versions get deleted.
# Defaults to false.
# Cannot be used with `num-old-versions-to-delete` and `ignore-versions`.
delete-only-pre-release-versions:
# The token used to authenticate with GitHub Packages. # The token used to authenticate with GitHub Packages.
# Defaults to github.token. # Defaults to github.token.
# Required if the repo running the workflow does not have access to delete the package. # Required if deleting a version from a package hosted in a different repo than the one executing the workflow.
# For rubygems and maven package, repo has access if package is hosted in the same repo as the workflow.
# For container, npm and nuget package, repo has access if assigned **Admin** role under Package Settings > Manage Actions Access.
# If `package-version-ids` is given the token only needs the delete packages scope. # If `package-version-ids` is given the token only needs the delete packages scope.
# If `package-version-ids` is not given the token needs the delete packages scope and the read packages scope # If `package-version-ids` is not given the token needs the delete packages scope and the read packages scope
token: token:
``` ```
# Valid Input Combinations
`owner`, `package-name`, `package-type` and `token` can be used with the following combinations in a workflow -
- `num-old-versions-to-delete`
- `min-versions-to-keep`
- `delete-only-pre-release-versions`
- `ignore-versions`
- `num-old-versions-to-delete` + `ignore-versions`
- `min-versions-to-keep` + `ignore-versions`
- `min-versions-to-keep` + `delete-only-pre-release-versions`
# Scenarios # Scenarios
- [Delete Package Versions](#delete-package-versions) * [Delete a specific version of a package hosted in the same repo as the workflow](#delete-a-specific-version-of-a-package-hosted-in-the-same-repo-as-the-workflow)
- [What It Can Do](#what-it-can-do) * [Delete a specific version of a package hosted in a different repo than the workflow](#delete-a-specific-version-of-a-package-hosted-in-a-different-repo-than-the-workflow)
- [Usage](#usage) * [Delete multiple specific versions of a package hosted in the same repo as the workflow](#delete-multiple-specific-versions-of-a-package-hosted-in-the-same-repo-as-the-workflow)
- [Valid Input Combinations](#valid-input-combinations) * [Delete multiple specific versions of a package hosted in a different repo than the workflow](#delete-multiple-specific-versions-of-a-package-hosted-in-a-different-repo-than-the-workflow)
- [Scenarios](#scenarios) * [Delete oldest version of a package hosted in the same repo as the workflow](#delete-oldest-version-of-a-package-hosted-in-the-same-repo-as-the-workflow)
- [Delete all pre-release versions except y latest pre-release package versions](#delete-all-pre-release-versions-except-y-latest-pre-release-package-versions) * [Delete oldest x number of versions of a package hosted in the same repo as the workflow](#delete-oldest-x-number-of-versions-of-a-package-hosted-in-the-same-repo-as-the-workflow)
- [Delete all except y latest versions while ignoring particular package versions](#delete-all-except-y-latest-versions-while-ignoring-particular-package-versions) * [Delete oldest x number of versions of a package hosted in a different repo than the workflow](#delete-oldest-x-number-of-versions-of-a-package-hosted-in-a-different-repo-than-the-workflow)
- [Delete oldest x number of versions while ignoring particular package versions](#delete-oldest-x-number-of-versions-while-ignoring-particular-package-versions)
- [Delete all except y latest versions of a package](#delete-all-except-y-latest-versions-of-a-package)
- [Delete oldest x number of versions of a package](#delete-oldest-x-number-of-versions-of-a-package)
- [Delete oldest version of a package](#delete-oldest-version-of-a-package)
- [Delete a specific version of a package](#delete-a-specific-version-of-a-package)
- [Delete multiple specific versions of a package](#delete-multiple-specific-versions-of-a-package)
- [License](#license)
### Delete a specific version of a package hosted in the same repo as the workflow
### Delete all pre-release versions except y latest pre-release package versions To delete a specific version of a package that is hosted in the same repo as the one executing the workflow the __package-version-ids__ input is required.
To delete all pre release versions except y latest pre-release package versions, the __package-name__, __min-versions-to-keep__ and __delete-only-pre-release-versions__ inputs are required. Package version ids can be retrieved via the [GitHub GraphQL API][api]
__Example__ __Example__
Delete all pre-release package versions except latest 10 ```yaml
- uses: actions/delete-package-versions@v1
```yaml
- uses: actions/delete-package-versions@v4
with:
package-name: 'test-package'
package-type: 'npm'
min-versions-to-keep: 10
delete-only-pre-release-versions: "true"
```
To delete all pre release versions except y latest pre-release package versions from a repo not having access to package, the __owner__, __package-name__, __token__, __min-versions-to-keep__ and __delete-only-pre-release-versions__ inputs are required.
__Example__
Delete all pre-release package versions except latest 10 from a repo not having access to package
```yaml
- uses: actions/delete-package-versions@v4
with:
owner: 'github'
package-name: 'test-package'
package-type: 'npm'
token: ${{ secrets.GITHUB_PAT }}
min-versions-to-keep: 10
delete-only-pre-release-versions: "true"
```
<br>
### Delete all except y latest versions while ignoring particular package versions
To delete all except y latest versions while ignoring particular package versions, the __package-name__, __min-versions-to-keep__ and __ignore-versions__ inputs are required.
__Example__
Delete all except latest 3 package versions excluding major versions as per semver
```yaml
- uses: actions/delete-package-versions@v4
with:
package-name: 'test-package'
package-type: 'npm'
min-versions-to-keep: 3
ignore-versions: '^(0|[1-9]\\d*)\\.0\\.0$'
```
To delete all except y latest versions while ignoring particular package versions from a repo not having access to package, the __owner__, __package-name__, __token__, __min-versions-to-keep__ and __ignore-versions__ inputs are required.
The [token][token] needs the delete packages and read packages scope. It is recommended [to store the token as a secret][secret]. In this example the [token][token] was stored as a secret named __GITHUB_PAT__.
__Example__
Delete all except latest 3 package versions excluding major versions as per semver from a repo not having access to package
```yaml
- uses: actions/delete-package-versions@v4
with:
owner: 'github'
package-name: 'test-package'
package-type: 'npm'
token: ${{ secrets.GITHUB_PAT }}
min-versions-to-keep: 3
ignore-versions: '^(0|[1-9]\\d*)\\.0\\.0$'
```
<br>
### Delete oldest x number of versions while ignoring particular package versions
To delete oldest x number of versions while ignoring all the major package versions, the __package-name__, __num-oldest-versions-to-delete__ and __ignore-versions__ inputs are required.
There is a possibility if the oldest x number of versions contain ignored package versions, actual package versions to get deleted will be less than x.
__Example__
Delete 3 oldest versions excluding major versions as per semver
```yaml
- uses: actions/delete-package-versions@v4
with:
package-name: 'test-package'
package-type: 'npm'
num-old-versions-to-delete: 3
ignore-versions: '^(0|[1-9]\\d*)\\.0\\.0$'
```
To delete oldest x number of versions while ignoring all the major package versions from a repo not having access to package, the __owner__, __package-name__, __token__, __num-oldest-versions-to-delete__ and __ignore-versions__ inputs are required.
There is a possibility if the oldest x number of versions contain ignored package versions, actual package versions to get deleted will be less than x.
__Example__
Delete 3 oldest versions excluding major versions as per semver from a repo not having access to package
```yaml
- uses: actions/delete-package-versions@v4
with:
owner: 'github'
package-name: 'test-package'
package-type: 'npm'
token: ${{ secrets.PAT }}
num-old-versions-to-delete: 3
ignore-versions: '^(0|[1-9]\\d*)\\.0\\.0$'
```
<br>
### Delete all except y latest versions of a package
To delete all except y latest versions of a package hosted, the __package-name__ and __min-versions-to-keep__ inputs are required.
__Example__
Delete all except latest 2 versions of a package hosted
```yaml
- uses: actions/delete-package-versions@v4
with:
package-name: 'test-package'
package-type: 'npm'
min-versions-to-keep: 2
```
To delete all except y latest versions of a package hosted from a repo not having access to package, the __owner__, __package-name__, __token__ and __min-versions-to-keep__ inputs are required.
The [token][token] needs the delete packages and read packages scope. It is recommended [to store the token as a secret][secret]. In this example the [token][token] was stored as a secret named __GITHUB_PAT__.
__Example__
Delete all except latest 2 versions of a package hosted from a repo not having access to package
```yaml
- uses: actions/delete-package-versions@v4
with:
owner: 'github'
package-name: 'test-package'
package-type: 'npm'
token: ${{ secrets.PAT }}
min-versions-to-keep: 2
```
<br>
### Delete oldest x number of versions of a package
To delete the oldest x number of versions of a package hosted, the __package-name__, and __num-old-versions-to-delete__ inputs are required.
__Example__
Delete the oldest 3 version of a package hosted
```yaml
- uses: actions/delete-package-versions@v4
with:
package-name: 'test-package'
package-type: 'npm'
num-old-versions-to-delete: 3
```
To delete the oldest x number of versions of a package hosted from a repo not having access to package, the __owner__, __package-name__, __token__ and __num-old-versions-to-delete__ inputs are required.
The [token][token] needs the delete packages and read packages scope. It is recommended [to store the token as a secret][secret]. In this example the [token][token] was stored as a secret named __GITHUB_PAT__.
__Example__
Delete the oldest 3 version of a package hosted from a repo not having access to package
```yaml
- uses: actions/delete-package-versions@v4
with:
owner: 'github'
package-name: 'test-package'
package-type: 'npm'
num-old-versions-to-delete: 3
token: ${{ secrets.GITHUB_PAT }}
```
<br>
### Delete oldest version of a package
To delete the oldest version of a package that is hosted, the __package-name__ input is required.
__Example__
```yaml
- uses: actions/delete-package-versions@v4
with:
package-name: 'test-package'
package-type: 'npm'
```
To delete the oldest version of a package that is hosted from a repo not having access to package, the __owner__, __package-name__, __token__ inputs are required.
__Example__
```yaml
- uses: actions/delete-package-versions@v4
with:
owner: 'github'
package-name: 'test-package'
package-type: 'npm'
token: ${{ secrets.PAT }}
```
<br>
### Delete a specific version of a package
To delete a specific version of a package that is hosted, the __package-version-ids__ input is required.
Package version ids can be retrieved via the [GitHub REST API][api]
__Example__
```yaml
- uses: actions/delete-package-versions@v4
with: with:
package-version-ids: 'MDE0OlBhY2thZ2VWZXJzaW9uOTcyMDY3' package-version-ids: 'MDE0OlBhY2thZ2VWZXJzaW9uOTcyMDY3'
package-name: 'test-package' ```
package-type: 'npm'
```
To delete a specific version of a package that is hosted from a repo not having access to package, the __package-version-ids__ and __token__ inputs are required. <br>
Package version ids can be retrieved via the [GitHub REST API][api] ### Delete a specific version of a package hosted in a different repo than the workflow
__Example__ To delete a specific version of a package that is hosted in a different repo than the one executing the workflow the __package-version-ids__, and __token__ inputs are required.
```yaml Package version ids can be retrieved via the [GitHub GraphQL API][api].
- uses: actions/delete-package-versions@v4
The [token][token] only needs the delete packages scope. It is recommended [to store the token as a secret][secret]. In this example the [token][token] was stored as a secret named __GITHUB_PAT__.
__Example__
```yaml
- uses: actions/delete-package-versions@v1
with: with:
package-version-ids: 'MDE0OlBhY2thZ2VWZXJzaW9uOTcyMDY3' package-version-ids: 'MDE0OlBhY2thZ2VWZXJzaW9uOTcyMDY3'
package-name: 'test-package' token: ${{ secrets.GITHUB_PAT }}
package-type: 'npm' ```
token: ${{ secrets.PAT }}
```
<br> <br>
### Delete multiple specific versions of a package ### Delete multiple specific versions of a package hosted in the same repo as the workflow
To delete multiple specific versions of a package that is hosted, the __package-version-ids__ input is required. To delete multiple specifc versions of a package that is hosted in the same repo that is executing the workflow the __package-version-ids__ input is required.
The __package-version-ids__ input should be a comma separated string of package version ids. Package version ids can be retrieved via the [GitHub REST API][api]. The __package-version-ids__ input should be a comma separated string of package version ids. Package version ids can be retrieved via the [GitHub GraphQL API][api].
__Example__ __Example__
```yaml ```yaml
- uses: actions/delete-package-versions@v4 - uses: actions/delete-package-versions@v1
with: with:
package-version-ids: 'MDE0OlBhY2thZ2VWZXJzaW9uOTcyMDY3, MDE0OlBhY2thZ2VWZXJzaW9uOTcyMzQ5, MDE0OlBhY2thZ2VWZXJzaW9uOTcyMzUw' package-version-ids: 'MDE0OlBhY2thZ2VWZXJzaW9uOTcyMDY3, MDE0OlBhY2thZ2VWZXJzaW9uOTcyMzQ5, MDE0OlBhY2thZ2VWZXJzaW9uOTcyMzUw'
package-name: 'test-package' ```
package-type: 'npm'
```
To delete multiple specific versions of a package that is hosted from a repo not having access to package, the __package-version-ids__, __token__ inputs are required. <br>
The __package-version-ids__ input should be a comma separated string of package version ids. Package version ids can be retrieved via the [GitHub REST API][api]. ### Delete multiple specific versions of a package hosted in a different repo than the workflow
__Example__ To delete multiple specifc versions of a package that is hosted in a different repo than the one executing the workflow the __package-version-ids__, and __token__ inputs are required.
```yaml The __package-version-ids__ input should be a comma separated string of package version ids. Package version ids can be retrieved via the [GitHub GraphQL API][api].
- uses: actions/delete-package-versions@v4
The [token][token] only needs the delete packages scope. It is recommended [to store the token as a secret][secret]. In this example the [token][token] was stored as a secret named __GITHUB_PAT__.
__Example__
```yaml
- uses: actions/delete-package-versions@v1
with: with:
package-version-ids: 'MDE0OlBhY2thZ2VWZXJzaW9uOTcyMDY3, MDE0OlBhY2thZ2VWZXJzaW9uOTcyMzQ5, MDE0OlBhY2thZ2VWZXJzaW9uOTcyMzUw' package-version-ids: 'MDE0OlBhY2thZ2VWZXJzaW9uOTcyMDY3, MDE0OlBhY2thZ2VWZXJzaW9uOTcyMzQ5, MDE0OlBhY2thZ2VWZXJzaW9uOTcyMzUw'
token: ${{ secrets.GITHUB_PAT }}
```
<br>
### Delete oldest version of a package hosted in the same repo as the workflow
To delete the oldest version of a package that is hosted in the same repo that is executing the workflow the __package-name__ input is required.
__Example__
```yaml
- uses: actions/delete-package-versions@v1
with:
package-name: 'test-package' package-name: 'test-package'
package-type: 'npm' ```
token: ${{ secrets.PAT }}
``` <br>
### Delete oldest version of a package hosted in a different repo than the workflow
To delete the oldest version of a package that is hosted in a different repo than the one executing the workflow the __package-name__, __owner__, __repo__, and __token__ inputs are required.
The [token][token] needs the delete packages and read packages scope. It is recommended [to store the token as a secret][secret]. In this example the [token][token] was stored as a secret named __GITHUB_PAT__.
__Example__
```yaml
- uses: actions/delete-package-versions@v1
with:
owner: 'github'
repo: 'packages'
package-name: 'test-package'
token: ${{ secrets.GITHUB_PAT }}
```
<br>
### Delete oldest x number of versions of a package hosted in the same repo as the workflow
To delete the oldest x number of versions of a package hosted in the same repo that is executing the workflow the __package-name__, and __num-old-versions-to-delete__ inputs are required.
__Example__
Delete the oldest 3 version of a package hosted in the same repo as the workflow
```yaml
- uses: actions/delete-package-versions@v1
with:
package-name: 'test-package'
num-old-versions-to-delete: 3
```
<br>
### Delete oldest x number of versions of a package hosted in a different repo than the workflow
To delete the oldest x number of versions of a package hosted in a different repo than the one executing the workflow the __package-name__, __num-old-versions-to-delete__, __owner__, __repo__, and __token__ inputs are required.
The [token][token] needs the delete packages and read packages scope. It is recommended [to store the token as a secret][secret]. In this example the [token][token] was stored as a secret named __GITHUB_PAT__.
__Example__
Delete the oldest 3 version of a package hosted in a different repo than the one executing the workflow
```yaml
- uses: actions/delete-package-versions@v1
with:
owner: 'github'
repo: 'packages'
package-name: 'test-package'
num-old-versions-to-delete: 3
token: ${{ secrets.GITHUB_PAT }}
```
# License # License
The scripts and documentation in this project are released under the [MIT License](https://github.com/actions/delete-package-versions/blob/main/LICENSE) The scripts and documentation in this project are released under the [MIT License](https://github.com/actions/delete-package-versions/blob/main/LICENSE)
[api]: https://docs.github.com/en/rest/packages [api]: https://developer.github.com/v4/previews/#github-packages
[token]: https://help.github.com/en/packages/publishing-and-managing-packages/about-github-packages#about-tokens [token]: https://help.github.com/en/packages/publishing-and-managing-packages/about-github-packages#about-tokens
[secret]: https://help.github.com/en/actions/configuring-and-managing-workflows/creating-and-storing-encrypted-secrets [secret]: https://help.github.com/en/actions/configuring-and-managing-workflows/creating-and-storing-encrypted-secrets
+48 -319
View File
@@ -1,270 +1,43 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import {rest} from 'msw'
import {setupServer} from 'msw/node'
import {Input, InputParams} from '../src/input' import {Input, InputParams} from '../src/input'
import {deleteVersions, finalIds, RATE_LIMIT} from '../src/delete' import {deleteVersions, getVersionIds} from '../src/delete'
import {getMockedVersionsResponse} from './version/rest.mock'
import {RestEndpointMethodTypes} from '@octokit/plugin-rest-endpoint-methods/dist-types/generated/parameters-and-response-types'
type GetVersionsResponseData = describe.skip('index tests -- call graphql', () => {
RestEndpointMethodTypes['packages']['getAllPackageVersionsForPackageOwnedByUser']['response']['data'] it('getVersionIds test -- get oldest version', done => {
const numVersions = 1
describe('index tests -- call rest', () => { getVersionIds(getInput({numOldVersionsToDelete: numVersions})).subscribe(
let server = setupServer() ids => {
beforeEach(() => {
server = setupServer()
server.listen()
})
afterEach(() => {
server.close()
})
it('finalIds test - supplied package version id', done => {
const suppliedIds = ['123', '456', '789']
finalIds(getInput({packageVersionIds: suppliedIds})).subscribe(ids => {
expect(ids).toStrictEqual(suppliedIds)
done()
})
})
it('finalIDs test - success', done => {
const numVersions = 10
let apiCalled = 0
const versions = getMockedVersionsResponse(numVersions)
server.use(
rest.get(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions',
(req, res, ctx) => {
apiCalled++
return res(ctx.status(200), ctx.json(versions))
}
)
)
finalIds(getInput()).subscribe(ids => {
expect(apiCalled).toBe(1)
expect(ids.length).toBe(numVersions) expect(ids.length).toBe(numVersions)
for (let i = 0; i < numVersions; i++) {
expect(ids[i]).toBe(versions[i].id.toString())
}
done()
})
})
it('finalIDs test - success - pagination', done => {
const numVersions = RATE_LIMIT * 2
let apiCalled = 0
const versions = getMockedVersionsResponse(numVersions)
const firstPage = versions.slice(0, RATE_LIMIT)
const secondPage = versions.slice(RATE_LIMIT)
server.use(
rest.get(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions',
(req, res, ctx) => {
apiCalled++
const page = req.url.searchParams.get('page')
if (page === '1') {
return res(ctx.status(200), ctx.json(firstPage))
} else if (page === '2') {
return res(ctx.status(200), ctx.json(secondPage))
} else {
return res(ctx.status(200), ctx.json([]))
}
}
)
)
finalIds(getInput()).subscribe(ids => {
expect(apiCalled).toBe(3) // 2 full pages + 1 empty page
// never returns more than RATE_LIMIT versions
expect(ids.length).toBe(RATE_LIMIT)
for (let i = 0; i < RATE_LIMIT; i++) {
expect(ids[i]).toBe(versions[i].id.toString())
}
done()
})
})
it('finalIDs test - success - sorting accross pages', done => {
const numVersions = RATE_LIMIT * 2
let apiCalled = 0
// versions is in ascending order of created_at
const versions = getMockedVersionsResponse(numVersions)
// return newer versions on first page to test sorting
const firstPage = versions.slice(RATE_LIMIT).reverse()
const secondPage = versions.slice(0, RATE_LIMIT).reverse()
server.use(
rest.get(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions',
(req, res, ctx) => {
apiCalled++
const page = req.url.searchParams.get('page')
if (page === '1') {
return res(ctx.status(200), ctx.json(firstPage))
} else if (page === '2') {
return res(ctx.status(200), ctx.json(secondPage))
} else {
return res(ctx.status(200), ctx.json([]))
}
}
)
)
finalIds(getInput()).subscribe(ids => {
expect(apiCalled).toBe(3) // 2 full pages + 1 empty page
expect(ids.length).toBe(RATE_LIMIT)
for (let i = 0; i < RATE_LIMIT; i++) {
expect(ids[i]).toBe(versions[i].id.toString())
}
done()
})
})
it('finalIds test - do not delete more than numOldVersionsToDelete', done => {
const numVersions = 50
let apiCalled = 0
const versions = getMockedVersionsResponse(numVersions)
server.use(
rest.get(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions',
(req, res, ctx) => {
apiCalled++
return res(ctx.status(200), ctx.json(versions))
}
)
)
const numOldVersionsToDelete = 10
finalIds(getInput({numOldVersionsToDelete})).subscribe(ids => {
expect(apiCalled).toBe(1)
expect(ids.length).toBe(numOldVersionsToDelete)
for (let i = 0; i < numOldVersionsToDelete; i++) {
expect(ids[i]).toBe(versions[i].id.toString())
}
done()
})
})
it('finalIds test - keep minVersionsToKeep', done => {
const numVersions = 50
let apiCalled = 0
const versions = getMockedVersionsResponse(numVersions)
server.use(
rest.get(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions',
(req, res, ctx) => {
apiCalled++
return res(ctx.status(200), ctx.json(versions))
}
)
)
const minVersionsToKeep = 10
finalIds(getInput({minVersionsToKeep})).subscribe(ids => {
expect(apiCalled).toBe(1)
expect(ids.length).toBe(numVersions - minVersionsToKeep)
for (let i = 0; i < numVersions - minVersionsToKeep; i++) {
expect(ids[i]).toBe(versions[i].id.toString())
}
done()
})
})
it('finalIds test - delete only prerelease versions with minVersionsToKeep', done => {
const numVersions = 50
let apiCalled = 0
const versions = getMockedVersionsResponse(numVersions)
// make half versions prerelease
for (let i = 0; i < numVersions; i++) {
if (i % 2 === 0) {
versions[i].name += '-alpha'
}
}
server.use(
rest.get(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions',
(req, res, ctx) => {
apiCalled++
return res(ctx.status(200), ctx.json(versions))
}
)
)
const toDelete = numVersions / 2 - 10
finalIds(
getInput({
ignoreVersions: RegExp('^(0|[1-9]\\d*)((\\.(0|[1-9]\\d*))*)$'),
minVersionsToKeep: 10
})
).subscribe(ids => {
expect(apiCalled).toBe(1)
expect(ids.length).toBe(toDelete)
for (let i = 0; i < toDelete; i++) {
expect(ids[i]).toBe(versions[i * 2].id.toString())
}
done()
})
})
it('finalIds test - no versions deleted if API error even once', done => {
const numVersions = RATE_LIMIT * 2
let apiCalled = 0
const versions = getMockedVersionsResponse(numVersions)
const firstPage = versions.slice(0, RATE_LIMIT)
const secondPage = versions.slice(RATE_LIMIT)
server.use(
rest.get(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions',
(req, res, ctx) => {
apiCalled++
const page = req.url.searchParams.get('page')
if (page === '1') {
return res(ctx.status(200), ctx.json(firstPage))
} else if (page === '2') {
return res(ctx.status(500), ctx.json([]))
} else {
return res(ctx.status(200), ctx.json([]))
}
}
)
)
finalIds(getInput()).subscribe(
() => {
done.fail('should not complete')
},
err => {
expect(apiCalled).toBe(2) // 1 full page + 1 error page
expect(err).toBeTruthy()
expect(err).toContain('get versions API failed.')
done() done()
} }
) )
}) })
it('deleteVersions test - missing token', done => { it('getVersionIds test -- get oldest 3 versions', done => {
const numVersions = 3
getVersionIds(getInput({numOldVersionsToDelete: numVersions})).subscribe(
ids => {
expect(ids.length).toBe(numVersions)
done()
}
)
})
it('getVersionIds test -- supplied package version id', done => {
const suppliedIds = [
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB',
'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC'
]
getVersionIds(getInput({packageVersionIds: suppliedIds})).subscribe(ids => {
expect(ids).toBe(suppliedIds)
done()
})
})
it('deleteVersions test -- missing token', done => {
deleteVersions(getInput({token: ''})).subscribe({ deleteVersions(getInput({token: ''})).subscribe({
error: err => { error: err => {
expect(err).toBeTruthy() expect(err).toBeTruthy()
@@ -274,7 +47,7 @@ describe('index tests -- call rest', () => {
}) })
}) })
it('deleteVersions test - missing packageName', done => { it('deleteVersions test -- missing packageName', done => {
deleteVersions(getInput({packageName: ''})).subscribe({ deleteVersions(getInput({packageName: ''})).subscribe({
error: err => { error: err => {
expect(err).toBeTruthy() expect(err).toBeTruthy()
@@ -284,76 +57,32 @@ describe('index tests -- call rest', () => {
}) })
}) })
it('deleteVersions test - missing packageType', done => { it('deleteVersions test -- delete oldest version', done => {
deleteVersions(getInput({packageType: ''})).subscribe({ deleteVersions(getInput({numOldVersionsToDelete: 1})).subscribe(
error: err => { isSuccess => {
expect(err).toBeTruthy() expect(isSuccess).toBe(true)
done() done()
},
complete: async () => done.fail('no error thrown')
})
})
it('deleteVersions test - zero numOldVersionsToDelete', done => {
deleteVersions(getInput({numOldVersionsToDelete: 0})).subscribe(result => {
expect(result).toBe(true)
done()
})
})
it('deleteVersions test - success complete flow', done => {
const numVersions = 10
let getApiCalled = 0
let deleteApiCalled = 0
const versions = getMockedVersionsResponse(numVersions)
const versionsDeleted: string[] = []
server.use(
rest.get(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions',
(req, res, ctx) => {
getApiCalled++
return res(ctx.status(200), ctx.json(versions))
} }
) )
)
server.use(
rest.delete(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions/:versionId',
(req, res, ctx) => {
deleteApiCalled++
versionsDeleted.push(req.params.versionId as string)
return res(ctx.status(204))
}
)
)
deleteVersions(getInput())
.subscribe(result => {
expect(result).toBe(true)
}) })
.add(() => {
expect(getApiCalled).toBe(1) it('deleteVersions test -- delete 3 oldest versions', done => {
expect(deleteApiCalled).toBe(numVersions) deleteVersions(getInput({numOldVersionsToDelete: 3})).subscribe(
for (let i = 0; i < numVersions; i++) { isSuccess => {
expect(versionsDeleted[i]).toBe(versions[i].id.toString()) expect(isSuccess).toBe(true)
}
done() done()
}) }
)
}) })
}) })
const defaultInput: InputParams = { const defaultInput: InputParams = {
packageVersionIds: [], packageVersionIds: [],
owner: 'test-owner', owner: 'trent-j',
packageName: 'test-package', repo: 'actions-testing',
packageType: 'npm', packageName: 'com.github.trent-j.actions-test',
numOldVersionsToDelete: RATE_LIMIT, numOldVersionsToDelete: 1,
minVersionsToKeep: -1, token: process.env.GITHUB_TOKEN as string
ignoreVersions: RegExp('^$'),
token: 'test-token'
} }
function getInput(params?: InputParams): Input { function getInput(params?: InputParams): Input {
+18 -133
View File
@@ -1,140 +1,25 @@
import {rest} from 'msw'
import {setupServer} from 'msw/node'
import {deletePackageVersion, deletePackageVersions} from '../../src/version' import {deletePackageVersion, deletePackageVersions} from '../../src/version'
describe('delete tests - mock rest', () => { const githubToken = process.env.GITHUB_TOKEN as string
let server = setupServer()
beforeEach(() => { describe.skip('delete tests', () => {
server = setupServer() it('deletePackageVersion', async () => {
server.listen() const response = await deletePackageVersion(
'MDE0OlBhY2thZ2VWZXJzaW9uNjg5OTU1',
githubToken
).toPromise()
expect(response).toBe(true)
}) })
afterEach(() => { it('deletePackageVersions', async () => {
server.close() const response = await deletePackageVersions(
}) [
'MDE0OlBhY2thZ2VWZXJzaW9uNjk4Mjc0',
it('deletePackageVersion', done => { 'MDE0OlBhY2thZ2VWZXJzaW9uNjk4Mjcx',
server.use( 'MDE0OlBhY2thZ2VWZXJzaW9uNjk4MjY3'
rest.delete( ],
'https://api.github.com/users/test-owner/packages/npm/test-package/versions/123', githubToken
(req, res, ctx) => { ).toPromise()
return res(ctx.status(204)) expect(response).toBe(true)
}
)
)
deletePackageVersion(
'123',
'test-owner',
'test-package',
'npm',
'test-token'
).subscribe(result => {
expect(result).toBe(true)
done()
})
})
it('deletePackageVersions', done => {
let success = 0
server.use(
rest.delete(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions/*',
(req, res, ctx) => {
return res(ctx.status(204))
}
)
)
deletePackageVersions(
['123', '456', '789'],
'test-owner',
'test-package',
'npm',
'test-token'
)
.subscribe(
result => {
expect(result).toBe(true)
success++
},
err => {
// should not get here
done.fail(err)
}
)
.add(() => {
expect(success).toBe(3)
done()
})
})
it('deletePackageVersion - API error', done => {
server.use(
rest.delete(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions/123',
(req, res, ctx) => {
return res(ctx.status(500))
}
)
)
deletePackageVersion(
'123',
'test-owner',
'test-package',
'npm',
'test-token'
).subscribe(
() => {
done.fail('should not get here.')
},
err => {
expect(err).toContain('delete version API failed.')
done()
}
)
})
it('deletePackageVersions - API error for some versions', done => {
let success = 0
let failed = 0
server.use(
rest.delete(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions/:versionId',
(req, res, ctx) => {
if (req.params.versionId === '456') {
return res(ctx.status(500))
}
return res(ctx.status(204))
}
)
)
deletePackageVersions(
['123', '456', '789'],
'test-owner',
'test-package',
'npm',
'test-token'
)
.subscribe(
result => {
expect(result).toBe(true)
success++
},
err => {
expect(err).toContain('delete version API failed.')
failed++
}
)
.add(() => {
expect(success).toBe(2)
expect(failed).toBe(1)
done()
})
}) })
}) })
+34 -87
View File
@@ -1,121 +1,68 @@
import {rest} from 'msw' // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
import {setupServer} from 'msw/node' // @ts-ignore
import {mockOldestQueryResponse} from './graphql.mock'
import { import {
getOldestVersions as _getOldestVersions, getOldestVersions as _getOldestVersions,
RestQueryInfo VersionInfo
} from '../../src/version' } from '../../src/version'
import {Observable} from 'rxjs' import {Observable} from 'rxjs'
import {getMockedVersionsResponse} from './rest.mock'
import {RATE_LIMIT} from '../../src/delete'
describe('get versions tests -- mock rest', () => { describe.skip('get versions tests -- call graphql', () => {
let server = setupServer() it('getOldestVersions -- succeeds', done => {
const numVersions = 1
beforeEach(() => { getOldestVersions({numVersions}).subscribe(versions => {
server = setupServer() expect(versions.length).toBe(numVersions)
server.listen()
})
afterEach(() => {
server.close()
})
it('getOldestVersions -- success', done => {
const numVersions = RATE_LIMIT
const resp = getMockedVersionsResponse(numVersions)
server.use(
rest.get(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions',
(req, res, ctx) => {
return res(ctx.status(200), ctx.json(resp))
}
)
)
getOldestVersions({numVersions}).subscribe(result => {
expect(result.versions.length).toBe(numVersions)
for (let i = 0; i < numVersions; i++) {
expect(result.versions[i].id).toBe(resp[i].id)
expect(result.versions[i].version).toBe(resp[i].name)
expect(result.versions[i].created_at).toBe(resp[i].created_at)
}
expect(result.paginate).toBe(true)
expect(result.totalCount).toBe(numVersions)
done() done()
}) })
}) })
it('getOldestVersions -- paginate is false when fetched versions is less than page size', done => { it('getOldestVersions -- fails for invalid repo', done => {
const numVersions = 5 getOldestVersions({repo: 'actions-testin'}).subscribe({
error: err => {
server.use( expect(err).toBeTruthy()
rest.get(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions',
(req, res, ctx) => {
return res(
ctx.status(200),
ctx.json(getMockedVersionsResponse(numVersions))
)
}
)
)
// In the call numVersions is set to RATE_LIMIT, but the response has only 5 versions.
getOldestVersions().subscribe(result => {
expect(result.paginate).toBe(false)
done() done()
})
})
it('getOldestVersions -- API error', done => {
server.use(
rest.get(
'https://api.github.com/users/test-owner/packages/npm/test-package/versions',
(req, res, ctx) => {
return res(ctx.status(500))
}
)
)
getOldestVersions().subscribe(
() => {
done.fail('should not get here.')
}, },
err => { complete: async () => done.fail('no error thrown')
expect(err).toContain('get versions API failed.') })
})
})
describe('get versions tests -- mock graphql', () => {
it('getOldestVersions -- success', done => {
const numVersions = 5
mockOldestQueryResponse(numVersions)
getOldestVersions({numVersions}).subscribe(versions => {
expect(versions.length).toBe(numVersions)
done() done()
} })
)
}) })
}) })
interface Params { interface Params {
owner?: string owner?: string
repo?: string
packageName?: string packageName?: string
packageType?: string
numVersions?: number numVersions?: number
page?: number
token?: string token?: string
} }
const defaultParams = { const defaultParams = {
owner: 'test-owner', owner: 'trent-j',
packageName: 'test-package', repo: 'actions-testing',
packageType: 'npm', packageName: 'com.github.trent-j.actions-test',
numVersions: RATE_LIMIT, numVersions: 3,
page: 1, token: process.env.GITHUB_TOKEN as string
token: 'test-token'
} }
function getOldestVersions(params?: Params): Observable<RestQueryInfo> { function getOldestVersions(params?: Params): Observable<VersionInfo[]> {
const p: Required<Params> = {...defaultParams, ...params} const p: Required<Params> = {...defaultParams, ...params}
return _getOldestVersions( return _getOldestVersions(
p.owner, p.owner,
p.repo,
p.packageName, p.packageName,
p.packageType,
p.numVersions, p.numVersions,
p.page,
p.token p.token
) )
} }
+49
View File
@@ -0,0 +1,49 @@
import {
GraphQlQueryResponseData,
RequestParameters
} from '@octokit/graphql/dist-types/types'
import * as Graphql from '../../src/version/graphql'
import {GetVersionsQueryResponse} from '../../src/version'
export function getMockedOldestQueryResponse(
numVersions: number
): GetVersionsQueryResponse {
const versions = []
for (let i = 1; i <= numVersions; ++i) {
versions.push({
node: {
id: i.toString(),
version: `${i}.0.0`
}
})
}
return {
repository: {
packages: {
edges: [
{
node: {
name: 'test',
versions: {
edges: versions.reverse()
}
}
}
]
}
}
}
}
export function mockOldestQueryResponse(
numVersions: number
) {
const response = new Promise((resolve) => {
resolve(getMockedOldestQueryResponse(numVersions))
}) as Promise<GraphQlQueryResponseData>
jest.spyOn(Graphql, 'graphql').mockImplementation(
(token: string, query: string, parameters: RequestParameters) => response)
}
-24
View File
@@ -1,24 +0,0 @@
import {RestEndpointMethodTypes} from '@octokit/plugin-rest-endpoint-methods/dist-types/generated/parameters-and-response-types'
type GetVersionsResponseData =
RestEndpointMethodTypes['packages']['getAllPackageVersionsForPackageOwnedByUser']['response']['data']
export function getMockedVersionsResponse(
numVersions: number,
offset = 0
): GetVersionsResponseData {
const versions: GetVersionsResponseData = []
for (let i = 1 + offset; i <= numVersions + offset; ++i) {
const created_at = new Date()
created_at.setUTCFullYear(2000 + Number(i), 1, 1)
versions.push({
id: i,
name: `${i}.0.0`,
url: '',
created_at: created_at.toUTCString(),
package_html_url: '',
updated_at: ''
})
}
return versions
}
+9 -30
View File
@@ -15,15 +15,17 @@ inputs:
Defaults to the owner of the repo running the action. Defaults to the owner of the repo running the action.
required: false required: false
repo:
description: >
Repo containing the package version to delete.
Defaults to the repo running the action.
required: false
package-name: package-name:
description: > description: >
Name of the package containing the version to delete. Name of the package containing the version to delete.
required: true Required if dynamically deleting oldest versions.
required: false
package-type:
description: >
Type of package. Can be one of container, maven, npm, nuget, or rubygems.
required: true
num-old-versions-to-delete: num-old-versions-to-delete:
description: > description: >
@@ -32,29 +34,6 @@ inputs:
required: false required: false
default: "1" default: "1"
min-versions-to-keep:
description: >
Number of versions to keep starting with the latest version
By default keeps no version.
To delete all versions set this as 0.
required: false
default: "-1"
ignore-versions:
description: >
Regex pattern for package versions to ignore.
Defaults to delete all versions.
required: false
default: "^$"
delete-only-pre-release-versions:
description: >
Deletes only pre-release versions. The number of pre-release versions to keep can be specified by min-versions-to-keep.
When this is set num-old-versions-to-delete and ignore-versions will not be taken into account.
By default this is set to false
required: false
default: "false"
token: token:
description: > description: >
Token with the necessary scopes to delete package versions. Token with the necessary scopes to delete package versions.
@@ -65,7 +44,7 @@ inputs:
default: ${{ github.token }} default: ${{ github.token }}
runs: runs:
using: node16 using: node12
main: dist/index.js main: dist/index.js
branding: branding:
+21475 -28083
View File
File diff suppressed because one or more lines are too long
+5128 -12103
View File
File diff suppressed because it is too large Load Diff
+16 -18
View File
@@ -7,10 +7,9 @@
"scripts": { "scripts": {
"format": "prettier --write **/*.ts", "format": "prettier --write **/*.ts",
"format-check": "prettier --check **/*.ts", "format-check": "prettier --check **/*.ts",
"lint": "eslint src/**/*.ts --fix", "lint": "eslint src/**/*.ts",
"lint-check": "eslint src/**/*.ts",
"test": "jest", "test": "jest",
"build": "npm run format-check && npm run lint-check && npm run test && tsc", "build": "npm run format-check && npm run lint && npm run test && tsc",
"pack": "rm -rf ./lib ./dist && npm run build && ncc build" "pack": "rm -rf ./lib ./dist && npm run build && ncc build"
}, },
"repository": { "repository": {
@@ -25,24 +24,23 @@
"author": "YourNameOrOrganization", "author": "YourNameOrOrganization",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/core": "^1.9.1", "@actions/core": "^1.2.0",
"@actions/github": "^2.1.1", "@actions/github": "^2.1.1",
"@octokit/rest": "^19.0.5",
"rxjs": "^6.5.4" "rxjs": "^6.5.4"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "^27.5.2", "@types/jest": "^24.0.23",
"@types/node": "^18.11.18", "@types/node": "^12.7.12",
"@typescript-eslint/parser": "^5.47.1", "@typescript-eslint/parser": "^2.8.0",
"@vercel/ncc": "^0.36.0", "@zeit/ncc": "^0.20.5",
"eslint": "^8.30.0", "eslint": "^5.16.0",
"eslint-plugin-github": "^4.6.0", "eslint-plugin-github": "^2.0.0",
"eslint-plugin-jest": "^27.1.7", "eslint-plugin-jest": "^22.21.0",
"jest": "^29.3.1", "jest": "^24.9.0",
"jest-circus": "^29.3.1", "jest-circus": "^24.9.0",
"js-yaml": "^4.1.0", "js-yaml": "^3.13.1",
"msw": "^0.49.2", "prettier": "^1.19.1",
"prettier": "^2.8.1", "ts-jest": "^24.2.0",
"ts-jest": "^29.0.3" "typescript": "^3.6.4"
} }
} }
+15 -100
View File
@@ -1,96 +1,25 @@
/* eslint-disable i18n-text/no-en */
import {Input} from './input' import {Input} from './input'
import {EMPTY, Observable, of, throwError} from 'rxjs' import {Observable, of, throwError} from 'rxjs'
import {reduce, concatMap, map, expand, tap} from 'rxjs/operators' import {deletePackageVersions, getOldestVersions} from './version'
import { import {concatMap, map} from 'rxjs/operators'
deletePackageVersions,
getOldestVersions,
RestVersionInfo
} from './version'
export const RATE_LIMIT = 100 export function getVersionIds(input: Input): Observable<string[]> {
let totalCount = 0
export function getVersionIds(
owner: string,
packageName: string,
packageType: string,
numVersions: number,
page: number,
token: string
): Observable<RestVersionInfo[]> {
return getOldestVersions(
owner,
packageName,
packageType,
numVersions,
page,
token
).pipe(
expand(value =>
value.paginate
? getOldestVersions(
owner,
packageName,
packageType,
numVersions,
value.page + 1,
token
)
: EMPTY
),
tap(value => (totalCount = totalCount + value.totalCount)),
reduce((acc, value) => acc.concat(value.versions), [] as RestVersionInfo[])
)
}
export function finalIds(input: Input): Observable<string[]> {
if (input.packageVersionIds.length > 0) { if (input.packageVersionIds.length > 0) {
const toDelete = Math.min(input.packageVersionIds.length, RATE_LIMIT) return of(input.packageVersionIds)
return of(input.packageVersionIds.slice(0, toDelete))
} }
if (input.hasOldestVersionQueryInfo()) { if (input.hasOldestVersionQueryInfo()) {
return getVersionIds( return getOldestVersions(
input.owner, input.owner,
input.repo,
input.packageName, input.packageName,
input.packageType, input.numOldVersionsToDelete,
RATE_LIMIT,
1,
input.token input.token
).pipe( ).pipe(map(versionInfo => versionInfo.map(info => info.id)))
// This code block executes on all versions of a package starting from oldest
map(value => {
// we need to delete oldest versions first
value.sort((a, b) => {
return (
new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
)
})
/*
Here first filter out the versions that are to be ignored.
Then compute number of versions to delete (toDelete) based on the inputs.
*/
value = value.filter(info => !input.ignoreVersions.test(info.version))
let toDelete = 0
if (input.minVersionsToKeep < 0) {
toDelete = Math.min(
value.length,
Math.min(input.numOldVersionsToDelete, RATE_LIMIT)
)
} else {
toDelete = Math.min(
value.length - input.minVersionsToKeep,
RATE_LIMIT
)
}
if (toDelete < 0) return []
return value.map(info => info.id.toString()).slice(0, toDelete)
})
)
} }
return throwError( return throwError(
"Could not get packageVersionIds. Explicitly specify using the 'package-version-ids' input" "Could not get packageVersionIds. Explicitly specify using the 'package-version-ids' input or provide the 'package-name' and 'num-old-versions-to-delete' inputs to dynamically retrieve oldest versions"
) )
} }
@@ -99,28 +28,14 @@ export function deleteVersions(input: Input): Observable<boolean> {
return throwError('No token found') return throwError('No token found')
} }
if (!input.checkInput()) { if (input.numOldVersionsToDelete <= 0) {
return throwError('Invalid input combination')
}
if (input.numOldVersionsToDelete <= 0 && input.minVersionsToKeep < 0) {
console.log( console.log(
'Number of old versions to delete input is 0 or less, no versions will be deleted' 'Number of old versions to delete input is 0 or less, no versions will be deleted'
) )
return of(true) return of(true)
} }
const result = finalIds(input) return getVersionIds(input).pipe(
concatMap(ids => deletePackageVersions(ids, input.token))
return result.pipe(
concatMap(ids =>
deletePackageVersions(
ids,
input.owner,
input.packageName,
input.packageType,
input.token
)
)
) )
} }
+6 -44
View File
@@ -1,85 +1,47 @@
export interface InputParams { export interface InputParams {
packageVersionIds?: string[] packageVersionIds?: string[]
owner?: string owner?: string
repo?: string
packageName?: string packageName?: string
packageType?: string
numOldVersionsToDelete?: number numOldVersionsToDelete?: number
minVersionsToKeep?: number
ignoreVersions?: RegExp
token?: string token?: string
deletePreReleaseVersions?: string
} }
const defaultParams = { const defaultParams = {
packageVersionIds: [], packageVersionIds: [],
owner: '', owner: '',
repo: '',
packageName: '', packageName: '',
packageType: '',
numOldVersionsToDelete: 0, numOldVersionsToDelete: 0,
minVersionsToKeep: 0,
ignoreVersions: new RegExp(''),
deletePreReleaseVersions: '',
token: '' token: ''
} }
export class Input { export class Input {
packageVersionIds: string[] packageVersionIds: string[]
owner: string owner: string
repo: string
packageName: string packageName: string
packageType: string
numOldVersionsToDelete: number numOldVersionsToDelete: number
minVersionsToKeep: number
ignoreVersions: RegExp
deletePreReleaseVersions: string
token: string token: string
numDeleted: number
constructor(params?: InputParams) { constructor(params?: InputParams) {
const validatedParams: Required<InputParams> = {...defaultParams, ...params} const validatedParams: Required<InputParams> = {...defaultParams, ...params}
this.packageVersionIds = validatedParams.packageVersionIds this.packageVersionIds = validatedParams.packageVersionIds
this.owner = validatedParams.owner this.owner = validatedParams.owner
this.repo = validatedParams.repo
this.packageName = validatedParams.packageName this.packageName = validatedParams.packageName
this.packageType = validatedParams.packageType
this.numOldVersionsToDelete = validatedParams.numOldVersionsToDelete this.numOldVersionsToDelete = validatedParams.numOldVersionsToDelete
this.minVersionsToKeep = validatedParams.minVersionsToKeep
this.ignoreVersions = validatedParams.ignoreVersions
this.deletePreReleaseVersions = validatedParams.deletePreReleaseVersions
this.token = validatedParams.token this.token = validatedParams.token
this.numDeleted = 0
} }
hasOldestVersionQueryInfo(): boolean { hasOldestVersionQueryInfo(): boolean {
return !!( return !!(
this.owner && this.owner &&
this.repo &&
this.packageName && this.packageName &&
this.numOldVersionsToDelete >= 0 && this.numOldVersionsToDelete > 0 &&
this.token this.token
) )
} }
checkInput(): boolean {
if (
this.numOldVersionsToDelete > 1 &&
(this.minVersionsToKeep >= 0 || this.deletePreReleaseVersions === 'true')
) {
return false
}
if (this.packageType === '' || this.packageName === '') {
return false
}
if (this.deletePreReleaseVersions === 'true') {
this.minVersionsToKeep =
this.minVersionsToKeep > 0 ? this.minVersionsToKeep : 0
this.ignoreVersions = new RegExp('^(0|[1-9]\\d*)((\\.(0|[1-9]\\d*))*)$')
}
if (this.minVersionsToKeep >= 0) {
this.numOldVersionsToDelete = 0
}
return true
}
} }
+1 -10
View File
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import {getInput, setFailed} from '@actions/core' import {getInput, setFailed} from '@actions/core'
import {context} from '@actions/github' import {context} from '@actions/github'
import {Input} from './input' import {Input} from './input'
@@ -12,14 +11,9 @@ function getActionInput(): Input {
? getInput('package-version-ids').split(',') ? getInput('package-version-ids').split(',')
: [], : [],
owner: getInput('owner') ? getInput('owner') : context.repo.owner, owner: getInput('owner') ? getInput('owner') : context.repo.owner,
repo: getInput('repo') ? getInput('repo') : context.repo.repo,
packageName: getInput('package-name'), packageName: getInput('package-name'),
packageType: getInput('package-type'),
numOldVersionsToDelete: Number(getInput('num-old-versions-to-delete')), numOldVersionsToDelete: Number(getInput('num-old-versions-to-delete')),
minVersionsToKeep: Number(getInput('min-versions-to-keep')),
ignoreVersions: RegExp(getInput('ignore-versions')),
deletePreReleaseVersions: getInput(
'delete-only-pre-release-versions'
).toLowerCase(),
token: getInput('token') token: getInput('token')
}) })
} }
@@ -30,11 +24,8 @@ function run(): Observable<boolean> {
catchError(err => throwError(err)) catchError(err => throwError(err))
) )
} catch (error) { } catch (error) {
if (error instanceof Error) {
return throwError(error.message) return throwError(error.message)
} }
return throwError(error)
}
} }
run().subscribe({ run().subscribe({
+30 -31
View File
@@ -1,66 +1,65 @@
import {from, Observable, merge, throwError, of} from 'rxjs' import {from, Observable, merge, throwError, of} from 'rxjs'
import {catchError, map, tap} from 'rxjs/operators' import {catchError, map, tap} from 'rxjs/operators'
import {Octokit} from '@octokit/rest' import {GraphQlQueryResponse} from '@octokit/graphql/dist-types/types'
import {RestEndpointMethodTypes} from '@octokit/plugin-rest-endpoint-methods/dist-types/generated/parameters-and-response-types' import {graphql} from './graphql'
let deleted = 0 export interface DeletePackageVersionMutationResponse {
type PackageType = deletePackageVersion: {
RestEndpointMethodTypes['packages']['getAllPackageVersionsForPackageOwnedByUser']['parameters']['package_type'] success: boolean
}
}
const mutation = `
mutation deletePackageVersion($packageVersionId: String!) {
deletePackageVersion(input: {packageVersionId: $packageVersionId}) {
success
}
}`
export function deletePackageVersion( export function deletePackageVersion(
packageVersionId: string, packageVersionId: string,
owner: string,
packageName: string,
packageType: string,
token: string token: string
): Observable<boolean> { ): Observable<boolean> {
const octokit = new Octokit({
auth: token
})
const package_version_id = +packageVersionId
const package_type: PackageType = packageType as PackageType
deleted += 1
return from( return from(
octokit.rest.packages.deletePackageVersionForUser({ graphql(token, mutation, {
package_type, packageVersionId,
package_name: packageName, headers: {
username: owner, Accept: 'application/vnd.github.package-deletes-preview+json'
package_version_id }
}) }) as Promise<DeletePackageVersionMutationResponse>
).pipe( ).pipe(
catchError(err => { catchError((err: GraphQlQueryResponse) => {
const msg = 'delete version API failed.' const msg = 'delete version mutation failed.'
return throwError( return throwError(
err.errors && err.errors.length > 0 err.errors && err.errors.length > 0
? `${msg} ${err.errors[0].message}` ? `${msg} ${err.errors[0].message}`
: `${msg} ${err.message} \n${deleted - 1} versions deleted till now.` : `${msg} verify input parameters are correct`
) )
}), }),
map(response => response.status === 204) map(response => response.deletePackageVersion.success)
) )
} }
export function deletePackageVersions( export function deletePackageVersions(
packageVersionIds: string[], packageVersionIds: string[],
owner: string,
packageName: string,
packageType: string,
token: string token: string
): Observable<boolean> { ): Observable<boolean> {
if (packageVersionIds.length === 0) { if (packageVersionIds.length === 0) {
console.log('no package version ids found, no versions will be deleted')
return of(true) return of(true)
} }
const deletes = packageVersionIds.map(id => const deletes = packageVersionIds.map(id =>
deletePackageVersion(id, owner, packageName, packageType, token).pipe( deletePackageVersion(id, token).pipe(
tap(result => { tap(result => {
if (!result) { if (result) {
console.log(`version with id: ${id}, deleted`)
} else {
console.log(`version with id: ${id}, not deleted`) console.log(`version with id: ${id}, not deleted`)
} }
}) })
) )
) )
console.log(`Total versions deleted till now: ${deleted}`)
return merge(...deletes) return merge(...deletes)
} }
+87 -48
View File
@@ -1,71 +1,110 @@
/* eslint-disable @typescript-eslint/no-unused-vars */ import {GraphQlQueryResponse} from '@octokit/graphql/dist-types/types'
import {from, Observable, merge, throwError, of} from 'rxjs' import {Observable, from, throwError} from 'rxjs'
import {catchError, map} from 'rxjs/operators' import {catchError, map} from 'rxjs/operators'
import {Octokit} from '@octokit/rest' import {graphql} from './graphql'
import {RestEndpointMethodTypes} from '@octokit/plugin-rest-endpoint-methods/dist-types/generated/parameters-and-response-types'
export interface RestVersionInfo { export interface VersionInfo {
id: number id: string
version: string version: string
created_at: string
} }
export interface RestQueryInfo { export interface GetVersionsQueryResponse {
versions: RestVersionInfo[] repository: {
page: number packages: {
paginate: boolean edges: {
totalCount: number node: {
name: string
versions: {
edges: {node: VersionInfo}[]
}
}
}[]
}
}
} }
type PackageType = const query = `
RestEndpointMethodTypes['packages']['getAllPackageVersionsForPackageOwnedByUser']['parameters']['package_type'] query getVersions($owner: String!, $repo: String!, $package: String!, $last: Int!) {
type GetVersionsResponse = repository(owner: $owner, name: $repo) {
RestEndpointMethodTypes['packages']['getAllPackageVersionsForPackageOwnedByUser']['response']['data'] packages(first: 1, names: [$package]) {
edges {
node {
name
versions(last: $last) {
edges {
node {
id
version
}
}
}
}
}
}
}
}`
export function getOldestVersions( export function queryForOldestVersions(
owner: string, owner: string,
repo: string,
packageName: string, packageName: string,
packageType: string,
numVersions: number, numVersions: number,
page: number,
token: string token: string
): Observable<RestQueryInfo> { ): Observable<GetVersionsQueryResponse> {
const octokit = new Octokit({
auth: token
})
const package_type: PackageType = packageType as PackageType
return from( return from(
octokit.rest.packages.getAllPackageVersionsForPackageOwnedByUser({ graphql(token, query, {
package_type, owner,
package_name: packageName, repo,
username: owner, package: packageName,
per_page: numVersions, last: numVersions,
page headers: {
}) Accept: 'application/vnd.github.packages-preview+json'
}
}) as Promise<GetVersionsQueryResponse>
).pipe( ).pipe(
catchError(err => { catchError((err: GraphQlQueryResponse) => {
const msg = 'get versions API failed.' const msg = 'query for oldest version failed.'
return throwError( return throwError(
err.errors && err.errors.length > 0 err.errors && err.errors.length > 0
? `${msg} ${err.errors[0].message}` ? `${msg} ${err.errors[0].message}`
: `${msg} ${err.message}` : `${msg} verify input parameters are correct`
) )
}), })
map(response => { )
const resp = { }
versions: response.data.map((version: GetVersionsResponse[0]) => {
return { export function getOldestVersions(
id: version.id, owner: string,
version: version.name, repo: string,
created_at: version.created_at packageName: string,
numVersions: number,
token: string
): Observable<VersionInfo[]> {
return queryForOldestVersions(
owner,
repo,
packageName,
numVersions,
token
).pipe(
map(result => {
if (result.repository.packages.edges.length < 1) {
throwError(
`package: ${packageName} not found for owner: ${owner} in repo: ${repo}`
)
} }
}),
page, const versions = result.repository.packages.edges[0].node.versions.edges
paginate: response.data.length === numVersions,
totalCount: response.data.length if (versions.length !== numVersions) {
console.log(
`number of versions requested was: ${numVersions}, but found: ${versions.length}`
)
} }
return resp
return versions
.map(value => ({id: value.node.id, version: value.node.version}))
.reverse()
}) })
) )
} }
+19
View File
@@ -0,0 +1,19 @@
import {GitHub} from '@actions/github'
import {GraphQlQueryResponseData} from '@octokit/graphql/dist-types/types'
import {RequestParameters} from '@octokit/types/dist-types/RequestParameters'
/**
* Sends a GraphQL query request based on endpoint options
*
* @param {string} token Auth token
* @param {string} query GraphQL query. Example: `'query { viewer { login } }'`.
* @param {object} parameters URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
export async function graphql(
token: string,
query: string,
parameters: RequestParameters
): Promise<GraphQlQueryResponseData> {
const github = new GitHub(token)
return await github.graphql(query, parameters)
}