Compare commits

..

1 Commits

Author SHA1 Message Date
github-actions[bot]
76757a8d01 Update configuration files 2026-07-12 04:15:25 +00:00
84 changed files with 103091 additions and 108887 deletions

6
.eslintignore Normal file
View File

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

51
.eslintrc.js Normal file
View File

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

View File

@@ -10,11 +10,7 @@ allowed:
- mit - mit
- cc0-1.0 - cc0-1.0
- unlicense - unlicense
- blueoak-1.0.0
reviewed: reviewed:
npm: npm:
- "@actions/http-client" - "@actions/http-client"
- balanced-match
- brace-expansion
- fast-content-type-parse

View File

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

View File

@@ -1,6 +1,6 @@
--- ---
name: "@actions/core" name: "@actions/core"
version: 3.0.1 version: 2.0.3
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,6 +1,6 @@
--- ---
name: "@actions/exec" name: "@actions/exec"
version: 3.0.0 version: 2.0.0
type: npm type: npm
summary: Actions exec lib summary: Actions exec lib
homepage: https://github.com/actions/toolkit/tree/main/packages/exec homepage: https://github.com/actions/toolkit/tree/main/packages/exec

View File

@@ -1,6 +1,6 @@
--- ---
name: "@actions/github" name: "@actions/github"
version: 9.1.1 version: 6.0.1
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

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

View File

@@ -1,10 +1,10 @@
--- ---
name: "@actions/http-client" name: "@actions/http-client"
version: 4.0.1 version: 2.2.3
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
license: other license: mit
licenses: licenses:
- sources: LICENSE - sources: LICENSE
text: | text: |

View File

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

View File

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

View File

@@ -1,19 +1,16 @@
--- ---
name: fast-content-type-parse name: "@azure/abort-controller"
version: 3.0.0 version: 1.1.0
type: npm type: npm
summary: Parse HTTP Content-Type header according to RFC 7231 summary: Microsoft Azure SDK for JavaScript - Aborter
homepage: https://github.com/fastify/fast-content-type-parse#readme homepage: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/abort-controller/README.md
license: other license: mit
licenses: licenses:
- sources: LICENSE - sources: LICENSE
text: |- text: |
MIT License The MIT License (MIT)
Copyright (c) 2023 The Fastify Team Copyright (c) 2020 Microsoft
The Fastify team members are listed at https://github.com/fastify/fastify#team
and in the README file.
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
@@ -32,6 +29,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: Licensed under [MIT](./LICENSE).
notices: [] notices: []

View File

@@ -1,6 +1,6 @@
--- ---
name: "@azure/core-http-compat" name: "@azure/core-http-compat"
version: 2.4.0 version: 2.3.1
type: npm type: npm
summary: Core HTTP Compatibility Library to bridge the gap between Core V1 & V2 packages. summary: Core HTTP Compatibility Library to bridge the gap between Core V1 & V2 packages.
homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-compat/ homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-compat/

View File

@@ -1,6 +1,6 @@
--- ---
name: "@azure/core-rest-pipeline" name: "@azure/core-rest-pipeline"
version: 1.23.0 version: 1.22.2
type: npm type: npm
summary: Isomorphic client library for making HTTP requests in node.js and browser. summary: Isomorphic client library for making HTTP requests in node.js and browser.
homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-rest-pipeline/ homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-rest-pipeline/

View File

@@ -1,6 +1,6 @@
--- ---
name: "@azure/core-xml" name: "@azure/core-xml"
version: 1.5.1 version: 1.5.0
type: npm type: npm
summary: Core library for interacting with XML payloads summary: Core library for interacting with XML payloads
homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-xml/ homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-xml/

View File

@@ -1,6 +1,6 @@
--- ---
name: "@azure/storage-blob" name: "@azure/storage-blob"
version: 12.31.0 version: 12.29.1
type: npm type: npm
summary: Microsoft Azure Storage SDK for JavaScript - Blob summary: Microsoft Azure Storage SDK for JavaScript - Blob
homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/storage/storage-blob/ homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/storage/storage-blob/

View File

@@ -1,6 +1,6 @@
--- ---
name: "@azure/storage-common" name: "@azure/storage-common"
version: 12.3.0 version: 12.1.1
type: npm type: npm
summary: Azure Storage Common Client Library for JavaScript summary: Azure Storage Common Client Library for JavaScript
homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/storage/storage-internal-avro/ homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/storage/storage-internal-avro/

View File

@@ -1,9 +1,9 @@
--- ---
name: "@nodable/entities" name: "@nodable/entities"
version: 2.1.0 version: 2.2.0
type: npm type: npm
summary: Entity parser for XML, HTML, External entites with security and NCR control summary: Entity parser for XML, HTML, External entites with security and NCR control
homepage: homepage:
license: mit license: mit
licenses: licenses:
- sources: README.md - sources: README.md

View File

@@ -1,6 +1,6 @@
--- ---
name: "@octokit/auth-token" name: "@octokit/auth-token"
version: 6.0.0 version: 4.0.0
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:

View File

@@ -1,6 +1,6 @@
--- ---
name: "@octokit/core" name: "@octokit/core"
version: 7.0.6 version: 5.2.2
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: 11.0.3 version: 9.0.6
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: 9.0.3 version: 7.1.1
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,14 +1,14 @@
--- ---
name: "@octokit/openapi-types" name: "@octokit/openapi-types"
version: 27.0.0 version: 20.0.0
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 for api.github.com
homepage: homepage:
license: mit license: mit
licenses: licenses:
- sources: LICENSE - sources: LICENSE
text: | text: |-
Copyright (c) GitHub 2025 - Licensed as MIT. 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: 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:

View File

@@ -1,20 +1,20 @@
--- ---
name: "@actions/glob" name: "@octokit/openapi-types"
version: 0.7.0 version: 24.2.0
type: npm type: npm
summary: Actions glob lib summary: Generated TypeScript definitions based on GitHub's OpenAPI spec for api.github.com
homepage: https://github.com/actions/toolkit/tree/main/packages/glob homepage:
license: mit license: mit
licenses: licenses:
- sources: LICENSE.md - sources: LICENSE
text: |- text: |-
The MIT License (MIT) Copyright 2020 Gregor Martynus
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: 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 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. 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: [] notices: []

View File

@@ -1,6 +1,6 @@
--- ---
name: "@octokit/plugin-paginate-rest" name: "@octokit/plugin-paginate-rest"
version: 14.0.0 version: 9.2.2
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: 17.0.0 version: 10.4.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: 7.1.0 version: 5.1.1
type: npm type: npm
summary: Error class for Octokit request errors summary: Error class for Octokit request errors
homepage: homepage:

View File

@@ -1,6 +1,6 @@
--- ---
name: "@octokit/request" name: "@octokit/request"
version: 10.0.8 version: 8.4.1
type: npm type: npm
summary: Send parameterized requests to GitHub's APIs with sensible defaults in browsers summary: Send parameterized requests to GitHub's APIs with sensible defaults in browsers
and Node and Node

View File

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

View File

@@ -0,0 +1,20 @@
---
name: "@octokit/types"
version: 13.10.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: "@typespec/ts-http-runtime" name: "@typespec/ts-http-runtime"
version: 0.3.5 version: 0.3.2
type: npm type: npm
summary: Isomorphic client library for making HTTP requests in node.js and browser. summary: Isomorphic client library for making HTTP requests in node.js and browser.
homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/ts-http-runtime/ homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/ts-http-runtime/

View File

@@ -1,17 +1,17 @@
--- ---
name: json-with-bigint name: anynum
version: 3.5.8 version: 1.0.1
type: npm type: npm
summary: JS library that allows you to easily serialize and deserialize data with summary: Normalize all Unicode decimal digits (Devanagari, Arabic, Thai, etc.) to
BigInt values ASCII numerals. Zero dependencies, performance-first.
homepage: homepage:
license: mit license: mit
licenses: licenses:
- sources: LICENSE - sources: LICENSE
text: | text: |
MIT License MIT License
Copyright (c) 2023 Ivan Korolenko Copyright (c) 2026 Natural Intelligence
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
@@ -30,4 +30,6 @@ 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
notices: [] notices: []

View File

@@ -1,34 +0,0 @@
---
name: balanced-match
version: 4.0.4
type: npm
summary: Match balanced character pairs, like "{" and "}"
homepage:
license: other
licenses:
- sources: LICENSE.md
text: |
(MIT)
Original code Copyright Julian Gruber <julian@juliangruber.com>
Port to TypeScript Copyright Isaac Z. Schlueter <i@izs.me>
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: before-after-hook name: before-after-hook
version: 4.0.0 version: 2.2.3
type: npm type: npm
summary: asynchronous before/error/after hooks for internal functionality summary: asynchronous before/error/after hooks for internal functionality
homepage: homepage:
license: apache-2.0 license: apache-2.0
licenses: licenses:
- sources: LICENSE - sources: LICENSE

28
.licenses/npm/deprecation.dep.yml generated Normal file
View File

@@ -0,0 +1,28 @@
---
name: deprecation
version: 2.3.1
type: npm
summary: Log a deprecation message with stack
homepage: https://github.com/gr2m/deprecation#readme
license: isc
licenses:
- sources: LICENSE
text: |
The ISC License
Copyright (c) Gregor Martynus and contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- sources: README.md
text: "[ISC](LICENSE)"
notices: []

View File

@@ -1,9 +1,9 @@
--- ---
name: fast-xml-parser name: fast-xml-parser
version: 5.7.2 version: 5.9.2
type: npm type: npm
summary: Validate XML, Parse XML, Build XML without C/C++ based libraries summary: Validate XML, Parse XML, Build XML without C/C++ based libraries
homepage: homepage:
license: mit license: mit
licenses: licenses:
- sources: LICENSE - sources: LICENSE

View File

@@ -1,18 +1,17 @@
--- ---
name: brace-expansion name: is-unsafe
version: 5.0.6 version: 1.0.1
type: npm type: npm
summary: Brace expansion as known from sh/bash summary: Zero-dependency, DOM-free, pure predicate for detecting unsafe strings across
homepage: HTML, XML, SVG, SQL, SHELL, and REGEX contexts
license: other homepage:
license: mit
licenses: licenses:
- sources: LICENSE - sources: LICENSE
text: | text: |
MIT License MIT License
Copyright Julian Gruber <julian@juliangruber.com> Copyright (c) 2026 Natural Intelligence
TypeScript port Copyright Isaac Z. Schlueter <i@izs.me>
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
@@ -31,4 +30,6 @@ 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
notices: [] notices: []

View File

@@ -1,66 +0,0 @@
---
name: minimatch
version: 10.2.5
type: npm
summary: a glob matcher in javascript
homepage:
license: blueoak-1.0.0
licenses:
- sources: LICENSE.md
text: |
# Blue Oak Model License
Version 1.0.0
## Purpose
This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.
## Acceptance
In order to receive this license, you must agree to its
rules. The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.
## Copyright
Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.
## Notices
You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
<https://blueoakcouncil.org/license/1.0.0>.
## Excuse
If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice. If you do not do so, your license
ends immediately.
## Patent
Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.
## Reliability
No contributor can revoke this license.
## No Liability
**_As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim._**
notices: []

26
.licenses/npm/once.dep.yml generated Normal file
View File

@@ -0,0 +1,26 @@
---
name: once
version: 1.4.0
type: npm
summary: Run a function exactly one time
homepage: https://github.com/isaacs/once#readme
license: isc
licenses:
- sources: LICENSE
text: |
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
notices: []

26
.licenses/npm/semver-6.3.1.dep.yml generated Normal file
View File

@@ -0,0 +1,26 @@
---
name: semver
version: 6.3.1
type: npm
summary: The semantic version parser used by npm.
homepage:
license: isc
licenses:
- sources: LICENSE
text: |
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
notices: []

View File

@@ -1,6 +1,6 @@
--- ---
name: semver name: semver
version: 7.8.5 version: 7.7.3
type: npm type: npm
summary: The semantic version parser used by npm. summary: The semantic version parser used by npm.
homepage: homepage:

View File

@@ -1,9 +1,9 @@
--- ---
name: strnum name: strnum
version: 2.2.3 version: 2.4.1
type: npm type: npm
summary: Parse String to Number based on configuration summary: Parse String to Number based on configuration
homepage: homepage:
license: mit license: mit
licenses: licenses:
- sources: LICENSE - sources: LICENSE

View File

@@ -1,8 +1,8 @@
--- ---
name: universal-user-agent name: universal-user-agent
version: 7.0.3 version: 6.0.1
type: npm type: npm
summary: Get a user agent string across all JavaScript Runtime Environments summary: Get a user agent string in both browser and node
homepage: homepage:
license: isc license: isc
licenses: licenses:
@@ -10,7 +10,7 @@ licenses:
text: | text: |
# [ISC License](https://spdx.org/licenses/ISC) # [ISC License](https://spdx.org/licenses/ISC)
Copyright (c) 2018-2021, Gregor Martynus (https://github.com/gr2m) Copyright (c) 2018, Gregor Martynus (https://github.com/gr2m)
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

26
.licenses/npm/wrappy.dep.yml generated Normal file
View File

@@ -0,0 +1,26 @@
---
name: wrappy
version: 1.0.2
type: npm
summary: Callback wrapping utility
homepage: https://github.com/npm/wrappy
license: isc
licenses:
- sources: LICENSE
text: |
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
notices: []

View File

@@ -4,7 +4,7 @@ version: 0.1.0
type: npm type: npm
summary: Validates XML name productions — Name, NCName, QName, NMToken, NMTokens — summary: Validates XML name productions — Name, NCName, QName, NMToken, NMTokens —
for XML 1.0 and 1.1 for XML 1.0 and 1.1
homepage: homepage:
license: mit license: mit
licenses: licenses:
- sources: README.md - sources: README.md

11
.prettierrc.js Normal file
View File

@@ -0,0 +1,11 @@
// 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'
};

View File

@@ -12,10 +12,6 @@ This action provides the following functionality for GitHub Actions users:
- Registering problem matchers for error output - Registering problem matchers for error output
- Configuring authentication for GPR or npm - Configuring authentication for GPR or npm
## Breaking changes in V7
- **Migrated to ESM** to enable support for the latest `@actions/*` package versions.
## Breaking changes in V6 ## Breaking changes in V6
- Caching is now automatically enabled for npm projects when either the `devEngines.packageManager` field or the top-level `packageManager` field in `package.json` is set to `npm`. For other package managers, such as Yarn and pnpm, caching is disabled by default and must be configured manually using the `cache` input. - Caching is now automatically enabled for npm projects when either the `devEngines.packageManager` field or the top-level `packageManager` field in `package.json` is set to `npm`. For other package managers, such as Yarn and pnpm, caching is disabled by default and must be configured manually using the `cache` input.

View File

@@ -1,57 +1,19 @@
import {
jest,
describe,
it,
expect,
beforeAll,
beforeEach,
afterAll
} from '@jest/globals';
import {fileURLToPath} from 'url';
import os from 'os'; import os from 'os';
import fs from 'fs'; import fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import * as core from '@actions/core';
import * as io from '@actions/io'; import * as io from '@actions/io';
import * as auth from '../src/authutil';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); import * as cacheUtils from '../src/cache-utils';
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn((name: string) => {
const val =
process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
return val.trim();
}),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn())
}));
// Dynamic imports AFTER mocking so authutil sees the mocked core.
const core = await import('@actions/core');
const auth = await import('../src/authutil.js');
let rcFile: string; let rcFile: string;
describe('authutil tests', () => { describe('authutil tests', () => {
const _runnerDir = path.join(__dirname, 'runner'); const _runnerDir = path.join(__dirname, 'runner');
let cnSpy: jest.SpiedFunction<typeof process.stdout.write>; let cnSpy: jest.SpyInstance;
let logSpy: jest.SpiedFunction<typeof console.log>; let logSpy: jest.SpyInstance;
let dbgSpy: jest.SpyInstance;
beforeAll(async () => { beforeAll(async () => {
const randPath = path.join(Math.random().toString(36).substring(7)); const randPath = path.join(Math.random().toString(36).substring(7));
@@ -75,8 +37,19 @@ describe('authutil tests', () => {
// writes // writes
cnSpy = jest.spyOn(process.stdout, 'write'); cnSpy = jest.spyOn(process.stdout, 'write');
logSpy = jest.spyOn(console, 'log'); logSpy = jest.spyOn(console, 'log');
cnSpy.mockImplementation(() => true); dbgSpy = jest.spyOn(core, 'debug');
logSpy.mockImplementation(() => {}); cnSpy.mockImplementation(line => {
// uncomment to debug
// process.stderr.write('write:' + line + '\n');
});
logSpy.mockImplementation(line => {
// uncomment to debug
// process.stderr.write('log:' + line + '\n');
});
dbgSpy.mockImplementation(msg => {
// uncomment to see debug output
// process.stderr.write(msg + '\n');
});
}, 100000); }, 100000);
function dbg(message: string) { function dbg(message: string) {
@@ -146,8 +119,7 @@ describe('authutil tests', () => {
}); });
it('should not export NODE_AUTH_TOKEN if not set in environment', async () => { it('should not export NODE_AUTH_TOKEN if not set in environment', async () => {
const exportSpy = core.exportVariable as jest.Mock; const exportSpy = jest.spyOn(core, 'exportVariable');
exportSpy.mockClear();
delete process.env.NODE_AUTH_TOKEN; delete process.env.NODE_AUTH_TOKEN;
await auth.configAuthentication('https://registry.npmjs.org/'); await auth.configAuthentication('https://registry.npmjs.org/');
expect(fs.statSync(rcFile)).toBeDefined(); expect(fs.statSync(rcFile)).toBeDefined();
@@ -160,8 +132,7 @@ describe('authutil tests', () => {
}); });
it('should export NODE_AUTH_TOKEN if set to empty string', async () => { it('should export NODE_AUTH_TOKEN if set to empty string', async () => {
const exportSpy = core.exportVariable as jest.Mock; const exportSpy = jest.spyOn(core, 'exportVariable');
exportSpy.mockClear();
process.env.NODE_AUTH_TOKEN = ''; process.env.NODE_AUTH_TOKEN = '';
await auth.configAuthentication('https://registry.npmjs.org/'); await auth.configAuthentication('https://registry.npmjs.org/');
expect(fs.statSync(rcFile)).toBeDefined(); expect(fs.statSync(rcFile)).toBeDefined();

View File

@@ -1,67 +1,11 @@
import {jest, describe, it, expect, beforeEach, afterEach} from '@jest/globals'; import * as core from '@actions/core';
import {fileURLToPath} from 'url'; import * as cache from '@actions/cache';
import * as path from 'path'; import * as path from 'path';
import * as glob from '@actions/glob';
import osm from 'os'; import osm from 'os';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); import * as utils from '../src/cache-utils';
import {restoreCache} from '../src/cache-restore';
// Mock @actions modules before importing anything that depends on them
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((p: string) => p),
toWin32Path: jest.fn((p: string) => p),
toPosixPath: jest.fn((p: string) => p)
}));
jest.unstable_mockModule('@actions/cache', () => ({
saveCache: jest.fn(),
restoreCache: jest.fn(),
isFeatureAvailable: jest.fn()
}));
jest.unstable_mockModule('@actions/glob', () => ({
hashFiles: jest.fn(),
create: jest.fn()
}));
jest.unstable_mockModule('@actions/exec', () => ({
exec: jest.fn(),
getExecOutput: jest.fn()
}));
jest.unstable_mockModule('@actions/io', () => ({
which: jest.fn(),
mkdirP: jest.fn(),
rmRF: jest.fn(),
mv: jest.fn(),
cp: jest.fn()
}));
// Dynamic imports after mocking
const core = await import('@actions/core');
const cache = await import('@actions/cache');
const glob = await import('@actions/glob');
const exec = await import('@actions/exec');
const utils = await import('../src/cache-utils.js');
const {restoreCache} = await import('../src/cache-restore.js');
describe('cache-restore', () => { describe('cache-restore', () => {
const packageManagers = ['yarn', 'npm', 'pnpm'] as const; const packageManagers = ['yarn', 'npm', 'pnpm'] as const;
@@ -109,66 +53,64 @@ describe('cache-restore', () => {
} }
} }
let saveStateSpy: jest.Mock; let saveStateSpy: jest.SpyInstance;
let infoSpy: jest.Mock; let infoSpy: jest.SpyInstance;
let debugSpy: jest.Mock; let debugSpy: jest.SpyInstance;
let setOutputSpy: jest.Mock; let setOutputSpy: jest.SpyInstance;
let getExecOutputSpy: jest.Mock; let getCommandOutputSpy: jest.SpyInstance;
let restoreCacheSpy: jest.Mock; let restoreCacheSpy: jest.SpyInstance;
let hashFilesSpy: jest.Mock; let hashFilesSpy: jest.SpyInstance;
let archSpy: jest.SpiedFunction<typeof osm.arch>; let archSpy: jest.SpyInstance;
beforeEach(() => { beforeEach(() => {
// core // core
infoSpy = core.info as jest.Mock; infoSpy = jest.spyOn(core, 'info');
infoSpy.mockImplementation(() => undefined); infoSpy.mockImplementation(() => undefined);
debugSpy = core.debug as jest.Mock; debugSpy = jest.spyOn(core, 'debug');
debugSpy.mockImplementation(() => undefined); debugSpy.mockImplementation(() => undefined);
setOutputSpy = core.setOutput as jest.Mock; setOutputSpy = jest.spyOn(core, 'setOutput');
setOutputSpy.mockImplementation(() => undefined); setOutputSpy.mockImplementation(() => undefined);
saveStateSpy = core.saveState as jest.Mock; saveStateSpy = jest.spyOn(core, 'saveState');
saveStateSpy.mockImplementation(() => undefined); saveStateSpy.mockImplementation(() => undefined);
// glob // glob
hashFilesSpy = glob.hashFiles as jest.Mock; hashFilesSpy = jest.spyOn(glob, 'hashFiles');
(hashFilesSpy as jest.Mock<typeof glob.hashFiles>).mockImplementation( hashFilesSpy.mockImplementation((pattern: string) => {
async (pattern: string) => { if (pattern.includes('package-lock.json')) {
if (pattern.includes('package-lock.json')) { return npmFileHash;
return npmFileHash; } else if (pattern.includes('pnpm-lock.yaml')) {
} else if (pattern.includes('pnpm-lock.yaml')) { return pnpmFileHash;
return pnpmFileHash; } else if (pattern.includes('yarn.lock')) {
} else if (pattern.includes('yarn.lock')) { return yarnFileHash;
return yarnFileHash; } else {
} else { return '';
return ''; }
});
// cache
restoreCacheSpy = jest.spyOn(cache, 'restoreCache');
restoreCacheSpy.mockImplementation(
(cachePaths: Array<string>, key: string) => {
if (!cachePaths || cachePaths.length === 0) {
return undefined;
} }
const cachPath = cachePaths[0];
const fileHash = cachesObject[cachPath];
if (key.includes(fileHash)) {
return key;
}
return undefined;
} }
); );
// cache // cache-utils
restoreCacheSpy = cache.restoreCache as jest.Mock; getCommandOutputSpy = jest.spyOn(utils, 'getCommandOutput');
(
restoreCacheSpy as jest.Mock<typeof cache.restoreCache>
).mockImplementation(async (cachePaths: string[], key: string) => {
if (!cachePaths || cachePaths.length === 0) {
return undefined;
}
const cachPath = cachePaths[0];
const fileHash = cachesObject[cachPath];
if (key.includes(fileHash)) {
return key;
}
return undefined;
});
// exec
getExecOutputSpy = exec.getExecOutput as jest.Mock;
// os // os
archSpy = jest.spyOn(osm, 'arch'); archSpy = jest.spyOn(osm, 'arch');
@@ -192,18 +134,19 @@ describe('cache-restore', () => {
['yarn', '1.2.3', yarnFileHash], ['yarn', '1.2.3', yarnFileHash],
['npm', '', npmFileHash], ['npm', '', npmFileHash],
['pnpm', '', pnpmFileHash] ['pnpm', '', pnpmFileHash]
])( ] as const)(
'restored dependencies for %s', 'restored dependencies for %s',
async (packageManager, toolVersion, fileHash) => { async (packageManager, toolVersion, fileHash) => {
const expectedCacheKey = `node-cache-${platform}-${arch}-${packageManager}-${fileHash}`; const expectedCacheKey = `node-cache-${platform}-${arch}-${packageManager}-${fileHash}`;
setWorkspaceFor(packageManager as PackageManager); // Set workspace to the appropriate fixture folder
getExecOutputSpy.mockImplementation(async (command: any) => ({ setWorkspaceFor(packageManager);
stdout: command.includes('version') getCommandOutputSpy.mockImplementation((command: string) => {
? toolVersion if (command.includes('version')) {
: findCacheFolder(command), return toolVersion;
stderr: '', } else {
exitCode: 0 return findCacheFolder(command);
})); }
});
await restoreCache(packageManager, ''); await restoreCache(packageManager, '');
expect(hashFilesSpy).toHaveBeenCalled(); expect(hashFilesSpy).toHaveBeenCalled();
@@ -232,18 +175,19 @@ describe('cache-restore', () => {
['yarn', '1.2.3', yarnFileHash], ['yarn', '1.2.3', yarnFileHash],
['npm', '', npmFileHash], ['npm', '', npmFileHash],
['pnpm', '', pnpmFileHash] ['pnpm', '', pnpmFileHash]
])( ] as const)(
'dependencies are changed %s', 'dependencies are changed %s',
async (packageManager, toolVersion, fileHash) => { async (packageManager, toolVersion, fileHash) => {
const expectedCacheKey = `node-cache-${platform}-${arch}-${packageManager}-${fileHash}`; const expectedCacheKey = `node-cache-${platform}-${arch}-${packageManager}-${fileHash}`;
setWorkspaceFor(packageManager as PackageManager); // Set workspace to the appropriate fixture folder
getExecOutputSpy.mockImplementation(async (command: any) => ({ setWorkspaceFor(packageManager);
stdout: command.includes('version') getCommandOutputSpy.mockImplementation((command: string) => {
? toolVersion if (command.includes('version')) {
: findCacheFolder(command), return toolVersion;
stderr: '', } else {
exitCode: 0 return findCacheFolder(command);
})); }
});
restoreCacheSpy.mockImplementationOnce(() => undefined); restoreCacheSpy.mockImplementationOnce(() => undefined);
await restoreCache(packageManager, ''); await restoreCache(packageManager, '');

View File

@@ -1,74 +1,12 @@
import {jest, describe, it, expect, beforeEach, afterEach} from '@jest/globals'; import * as core from '@actions/core';
import {fileURLToPath} from 'url'; import * as cache from '@actions/cache';
import path from 'path'; import * as glob from '@actions/glob';
import fs from 'fs'; import fs from 'fs';
import path from 'path';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); import * as utils from '../src/cache-utils';
import {run} from '../src/cache-save';
// Mock @actions modules before importing anything that depends on them import {State} from '../src/constants';
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((p: string) => p),
toWin32Path: jest.fn((p: string) => p),
toPosixPath: jest.fn((p: string) => p)
}));
jest.unstable_mockModule('@actions/cache', () => ({
saveCache: jest.fn(),
restoreCache: jest.fn(),
isFeatureAvailable: jest.fn(),
ValidationError: class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = 'ValidationError';
}
}
}));
jest.unstable_mockModule('@actions/glob', () => ({
hashFiles: jest.fn(),
create: jest.fn()
}));
jest.unstable_mockModule('@actions/exec', () => ({
exec: jest.fn(),
getExecOutput: jest.fn()
}));
jest.unstable_mockModule('@actions/io', () => ({
which: jest.fn(),
mkdirP: jest.fn(),
rmRF: jest.fn(),
mv: jest.fn(),
cp: jest.fn()
}));
// Dynamic imports after mocking
const core = await import('@actions/core');
const cache = await import('@actions/cache');
const glob = await import('@actions/glob');
const exec = await import('@actions/exec');
const utils = await import('../src/cache-utils.js');
const {run} = await import('../src/cache-save.js');
const {State} = await import('../src/constants.js');
describe('run', () => { describe('run', () => {
const yarnFileHash = const yarnFileHash =
@@ -82,42 +20,42 @@ describe('run', () => {
const inputs = {} as any; const inputs = {} as any;
let getInputSpy: jest.Mock; let getInputSpy: jest.SpyInstance;
let infoSpy: jest.Mock; let infoSpy: jest.SpyInstance;
let warningSpy: jest.Mock; let warningSpy: jest.SpyInstance;
let debugSpy: jest.Mock; let debugSpy: jest.SpyInstance;
let setFailedSpy: jest.Mock; let setFailedSpy: jest.SpyInstance;
let getStateSpy: jest.Mock; let getStateSpy: jest.SpyInstance;
let saveCacheSpy: jest.Mock; let saveCacheSpy: jest.SpyInstance;
let getExecOutputSpy: jest.Mock; let getCommandOutputSpy: jest.SpyInstance;
let hashFilesSpy: jest.Mock; let hashFilesSpy: jest.SpyInstance;
let existsSpy: jest.SpiedFunction<typeof fs.existsSync>; let existsSpy: jest.SpyInstance;
beforeEach(() => { beforeEach(() => {
getInputSpy = core.getInput as jest.Mock; getInputSpy = jest.spyOn(core, 'getInput');
getInputSpy.mockImplementation((name: any) => inputs[name]); getInputSpy.mockImplementation((name: string) => inputs[name]);
infoSpy = core.info as jest.Mock; infoSpy = jest.spyOn(core, 'info');
infoSpy.mockImplementation(() => undefined); infoSpy.mockImplementation(() => undefined);
warningSpy = core.warning as jest.Mock; warningSpy = jest.spyOn(core, 'warning');
warningSpy.mockImplementation(() => undefined); warningSpy.mockImplementation(() => undefined);
setFailedSpy = core.setFailed as jest.Mock; setFailedSpy = jest.spyOn(core, 'setFailed');
setFailedSpy.mockImplementation(() => undefined); setFailedSpy.mockImplementation(() => undefined);
debugSpy = core.debug as jest.Mock; debugSpy = jest.spyOn(core, 'debug');
debugSpy.mockImplementation(() => undefined); debugSpy.mockImplementation(() => undefined);
getStateSpy = core.getState as jest.Mock; getStateSpy = jest.spyOn(core, 'getState');
// cache // cache
saveCacheSpy = cache.saveCache as jest.Mock; saveCacheSpy = jest.spyOn(cache, 'saveCache');
saveCacheSpy.mockImplementation(() => undefined); saveCacheSpy.mockImplementation(() => undefined);
// glob // glob
hashFilesSpy = glob.hashFiles as jest.Mock; hashFilesSpy = jest.spyOn(glob, 'hashFiles');
hashFilesSpy.mockImplementation((pattern: any) => { hashFilesSpy.mockImplementation((pattern: string) => {
if (pattern.includes('package-lock.json')) { if (pattern.includes('package-lock.json')) {
return npmFileHash; return npmFileHash;
} else if (pattern.includes('yarn.lock')) { } else if (pattern.includes('yarn.lock')) {
@@ -130,20 +68,17 @@ describe('run', () => {
existsSpy = jest.spyOn(fs, 'existsSync'); existsSpy = jest.spyOn(fs, 'existsSync');
existsSpy.mockImplementation(() => true); existsSpy.mockImplementation(() => true);
// exec // utils
getExecOutputSpy = exec.getExecOutput as jest.Mock; getCommandOutputSpy = jest.spyOn(utils, 'getCommandOutput');
}); });
afterEach(() => { afterEach(() => {
existsSpy.mockRestore(); existsSpy.mockRestore();
jest.resetAllMocks();
jest.clearAllMocks();
}); });
describe('Package manager validation', () => { describe('Package manager validation', () => {
it('Package manager is not provided, skip caching', async () => { it('Package manager is not provided, skip caching', async () => {
inputs['cache'] = ''; inputs['cache'] = '';
getStateSpy.mockImplementation(() => '');
await run(); await run();
@@ -189,7 +124,7 @@ describe('run', () => {
expect(getInputSpy).not.toHaveBeenCalled(); expect(getInputSpy).not.toHaveBeenCalled();
expect(getStateSpy).toHaveBeenCalledTimes(4); expect(getStateSpy).toHaveBeenCalledTimes(4);
expect(getExecOutputSpy).toHaveBeenCalledTimes(0); expect(getCommandOutputSpy).toHaveBeenCalledTimes(0);
expect(debugSpy).toHaveBeenCalledTimes(0); expect(debugSpy).toHaveBeenCalledTimes(0);
expect(infoSpy).toHaveBeenCalledWith( expect(infoSpy).toHaveBeenCalledWith(
`Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.`
@@ -213,7 +148,7 @@ describe('run', () => {
expect(getInputSpy).not.toHaveBeenCalled(); expect(getInputSpy).not.toHaveBeenCalled();
expect(getStateSpy).toHaveBeenCalledTimes(4); expect(getStateSpy).toHaveBeenCalledTimes(4);
expect(getExecOutputSpy).toHaveBeenCalledTimes(0); expect(getCommandOutputSpy).toHaveBeenCalledTimes(0);
expect(debugSpy).toHaveBeenCalledTimes(0); expect(debugSpy).toHaveBeenCalledTimes(0);
expect(infoSpy).toHaveBeenCalledWith( expect(infoSpy).toHaveBeenCalledWith(
`Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.`
@@ -232,17 +167,13 @@ describe('run', () => {
? '["/foo/bar"]' ? '["/foo/bar"]'
: 'not expected' : 'not expected'
); );
getExecOutputSpy.mockImplementationOnce(() => ({ getCommandOutputSpy.mockImplementationOnce(() => `${commonPath}/npm`);
stdout: `${commonPath}/npm`,
stderr: '',
exitCode: 0
}));
await run(); await run();
expect(getInputSpy).not.toHaveBeenCalled(); expect(getInputSpy).not.toHaveBeenCalled();
expect(getStateSpy).toHaveBeenCalledTimes(4); expect(getStateSpy).toHaveBeenCalledTimes(4);
expect(getExecOutputSpy).toHaveBeenCalledTimes(0); expect(getCommandOutputSpy).toHaveBeenCalledTimes(0);
expect(debugSpy).toHaveBeenCalledTimes(0); expect(debugSpy).toHaveBeenCalledTimes(0);
expect(setFailedSpy).not.toHaveBeenCalled(); expect(setFailedSpy).not.toHaveBeenCalled();
}); });
@@ -263,7 +194,7 @@ describe('run', () => {
expect(getInputSpy).not.toHaveBeenCalled(); expect(getInputSpy).not.toHaveBeenCalled();
expect(getStateSpy).toHaveBeenCalledTimes(4); expect(getStateSpy).toHaveBeenCalledTimes(4);
expect(getExecOutputSpy).toHaveBeenCalledTimes(0); expect(getCommandOutputSpy).toHaveBeenCalledTimes(0);
expect(debugSpy).toHaveBeenCalledTimes(0); expect(debugSpy).toHaveBeenCalledTimes(0);
expect(setFailedSpy).not.toHaveBeenCalled(); expect(setFailedSpy).not.toHaveBeenCalled();
}); });
@@ -272,7 +203,7 @@ describe('run', () => {
describe('action saves the cache', () => { describe('action saves the cache', () => {
it('saves cache from yarn 1', async () => { it('saves cache from yarn 1', async () => {
inputs['cache'] = 'yarn'; inputs['cache'] = 'yarn';
getStateSpy.mockImplementation((key: any) => getStateSpy.mockImplementation((key: string) =>
key === State.CachePackageManager key === State.CachePackageManager
? inputs['cache'] ? inputs['cache']
: key === State.CacheMatchedKey : key === State.CacheMatchedKey
@@ -288,7 +219,7 @@ describe('run', () => {
expect(getInputSpy).not.toHaveBeenCalled(); expect(getInputSpy).not.toHaveBeenCalled();
expect(getStateSpy).toHaveBeenCalledTimes(4); expect(getStateSpy).toHaveBeenCalledTimes(4);
expect(getExecOutputSpy).toHaveBeenCalledTimes(0); expect(getCommandOutputSpy).toHaveBeenCalledTimes(0);
expect(debugSpy).toHaveBeenCalledTimes(0); expect(debugSpy).toHaveBeenCalledTimes(0);
expect(infoSpy).not.toHaveBeenCalledWith( expect(infoSpy).not.toHaveBeenCalledWith(
`Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.`
@@ -302,7 +233,7 @@ describe('run', () => {
it('saves cache from yarn 2', async () => { it('saves cache from yarn 2', async () => {
inputs['cache'] = 'yarn'; inputs['cache'] = 'yarn';
getStateSpy.mockImplementation((key: any) => getStateSpy.mockImplementation((key: string) =>
key === State.CachePackageManager key === State.CachePackageManager
? inputs['cache'] ? inputs['cache']
: key === State.CacheMatchedKey : key === State.CacheMatchedKey
@@ -318,7 +249,7 @@ describe('run', () => {
expect(getInputSpy).not.toHaveBeenCalled(); expect(getInputSpy).not.toHaveBeenCalled();
expect(getStateSpy).toHaveBeenCalledTimes(4); expect(getStateSpy).toHaveBeenCalledTimes(4);
expect(getExecOutputSpy).toHaveBeenCalledTimes(0); expect(getCommandOutputSpy).toHaveBeenCalledTimes(0);
expect(debugSpy).toHaveBeenCalledTimes(0); expect(debugSpy).toHaveBeenCalledTimes(0);
expect(infoSpy).not.toHaveBeenCalledWith( expect(infoSpy).not.toHaveBeenCalledWith(
`Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.` `Cache hit occurred on the primary key ${yarnFileHash}, not saving cache.`
@@ -332,7 +263,7 @@ describe('run', () => {
it('saves cache from npm', async () => { it('saves cache from npm', async () => {
inputs['cache'] = 'npm'; inputs['cache'] = 'npm';
getStateSpy.mockImplementation((key: any) => getStateSpy.mockImplementation((key: string) =>
key === State.CachePackageManager key === State.CachePackageManager
? inputs['cache'] ? inputs['cache']
: key === State.CacheMatchedKey : key === State.CacheMatchedKey
@@ -348,7 +279,7 @@ describe('run', () => {
expect(getInputSpy).not.toHaveBeenCalled(); expect(getInputSpy).not.toHaveBeenCalled();
expect(getStateSpy).toHaveBeenCalledTimes(4); expect(getStateSpy).toHaveBeenCalledTimes(4);
expect(getExecOutputSpy).toHaveBeenCalledTimes(0); expect(getCommandOutputSpy).toHaveBeenCalledTimes(0);
expect(debugSpy).toHaveBeenCalledTimes(0); expect(debugSpy).toHaveBeenCalledTimes(0);
expect(infoSpy).not.toHaveBeenCalledWith( expect(infoSpy).not.toHaveBeenCalledWith(
`Cache hit occurred on the primary key ${npmFileHash}, not saving cache.` `Cache hit occurred on the primary key ${npmFileHash}, not saving cache.`
@@ -362,7 +293,7 @@ describe('run', () => {
it('saves cache from pnpm', async () => { it('saves cache from pnpm', async () => {
inputs['cache'] = 'pnpm'; inputs['cache'] = 'pnpm';
getStateSpy.mockImplementation((key: any) => getStateSpy.mockImplementation((key: string) =>
key === State.CachePackageManager key === State.CachePackageManager
? inputs['cache'] ? inputs['cache']
: key === State.CacheMatchedKey : key === State.CacheMatchedKey
@@ -378,7 +309,7 @@ describe('run', () => {
expect(getInputSpy).not.toHaveBeenCalled(); expect(getInputSpy).not.toHaveBeenCalled();
expect(getStateSpy).toHaveBeenCalledTimes(4); expect(getStateSpy).toHaveBeenCalledTimes(4);
expect(getExecOutputSpy).toHaveBeenCalledTimes(0); expect(getCommandOutputSpy).toHaveBeenCalledTimes(0);
expect(debugSpy).toHaveBeenCalledTimes(0); expect(debugSpy).toHaveBeenCalledTimes(0);
expect(infoSpy).not.toHaveBeenCalledWith( expect(infoSpy).not.toHaveBeenCalledWith(
`Cache hit occurred on the primary key ${pnpmFileHash}, not saving cache.` `Cache hit occurred on the primary key ${pnpmFileHash}, not saving cache.`
@@ -392,7 +323,7 @@ describe('run', () => {
it('save with -1 cacheId , should not fail workflow', async () => { it('save with -1 cacheId , should not fail workflow', async () => {
inputs['cache'] = 'npm'; inputs['cache'] = 'npm';
getStateSpy.mockImplementation((key: any) => getStateSpy.mockImplementation((key: string) =>
key === State.CachePackageManager key === State.CachePackageManager
? inputs['cache'] ? inputs['cache']
: key === State.CacheMatchedKey : key === State.CacheMatchedKey
@@ -411,8 +342,8 @@ describe('run', () => {
expect(getInputSpy).not.toHaveBeenCalled(); expect(getInputSpy).not.toHaveBeenCalled();
expect(getStateSpy).toHaveBeenCalledTimes(4); expect(getStateSpy).toHaveBeenCalledTimes(4);
expect(getExecOutputSpy).toHaveBeenCalledTimes(0); expect(getCommandOutputSpy).toHaveBeenCalledTimes(0);
expect(debugSpy).toHaveBeenCalledWith( expect(debugSpy).toHaveBeenLastCalledWith(
`Cache was not saved for the key: ${yarnFileHash}` `Cache was not saved for the key: ${yarnFileHash}`
); );
expect(infoSpy).not.toHaveBeenCalledWith( expect(infoSpy).not.toHaveBeenCalledWith(
@@ -427,7 +358,7 @@ describe('run', () => {
it('saves with error from toolkit, should fail workflow', async () => { it('saves with error from toolkit, should fail workflow', async () => {
inputs['cache'] = 'npm'; inputs['cache'] = 'npm';
getStateSpy.mockImplementation((key: any) => getStateSpy.mockImplementation((key: string) =>
key === State.CachePackageManager key === State.CachePackageManager
? inputs['cache'] ? inputs['cache']
: key === State.CacheMatchedKey : key === State.CacheMatchedKey
@@ -446,7 +377,7 @@ describe('run', () => {
expect(getInputSpy).not.toHaveBeenCalled(); expect(getInputSpy).not.toHaveBeenCalled();
expect(getStateSpy).toHaveBeenCalledTimes(4); expect(getStateSpy).toHaveBeenCalledTimes(4);
expect(getExecOutputSpy).toHaveBeenCalledTimes(0); expect(getCommandOutputSpy).toHaveBeenCalledTimes(0);
expect(debugSpy).toHaveBeenCalledTimes(0); expect(debugSpy).toHaveBeenCalledTimes(0);
expect(infoSpy).not.toHaveBeenCalledWith( expect(infoSpy).not.toHaveBeenCalledWith(
`Cache hit occurred on the primary key ${npmFileHash}, not saving cache.` `Cache hit occurred on the primary key ${npmFileHash}, not saving cache.`
@@ -455,4 +386,9 @@ describe('run', () => {
expect(setFailedSpy).toHaveBeenCalled(); expect(setFailedSpy).toHaveBeenCalled();
}); });
}); });
afterEach(() => {
jest.resetAllMocks();
jest.clearAllMocks();
});
}); });

View File

@@ -1,133 +1,45 @@
import { import * as core from '@actions/core';
jest, import * as cache from '@actions/cache';
describe,
it,
expect,
beforeEach,
afterEach,
afterAll
} from '@jest/globals';
import {fileURLToPath} from 'url';
import path from 'path'; import path from 'path';
import fs from 'fs'; import * as utils from '../src/cache-utils';
import {
const __dirname = path.dirname(fileURLToPath(import.meta.url)); PackageManagerInfo,
// Mock @actions modules before importing anything that depends on them
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((p: string) => p),
toWin32Path: jest.fn((p: string) => p),
toPosixPath: jest.fn((p: string) => p)
}));
jest.unstable_mockModule('@actions/cache', () => ({
saveCache: jest.fn(),
restoreCache: jest.fn(),
isFeatureAvailable: jest.fn()
}));
jest.unstable_mockModule('@actions/glob', () => ({
hashFiles: jest.fn(),
create: jest.fn()
}));
jest.unstable_mockModule('@actions/exec', () => ({
exec: jest.fn(),
getExecOutput: jest.fn()
}));
jest.unstable_mockModule('@actions/io', () => ({
which: jest.fn(),
mkdirP: jest.fn(),
rmRF: jest.fn(),
mv: jest.fn(),
cp: jest.fn()
}));
// Dynamic imports after mocking
const core = await import('@actions/core');
const cache = await import('@actions/cache');
const glob = await import('@actions/glob');
const exec = await import('@actions/exec');
const utils = await import('../src/cache-utils.js');
const cacheUtils = await import('../src/cache-utils.js');
// @ts-ignore - test file outside rootDir
const {MockGlobber} = await import('./mock/glob-mock.js');
import type {PackageManagerInfo} from '../src/cache-utils.js';
const {
isCacheFeatureAvailable, isCacheFeatureAvailable,
supportedPackageManagers, supportedPackageManagers,
isGhes, isGhes,
resetProjectDirectoriesMemoized resetProjectDirectoriesMemoized
} = utils; } from '../src/cache-utils';
import fs from 'fs';
// Helper: mock exec.getExecOutput to simulate getCommandOutput behavior import * as cacheUtils from '../src/cache-utils';
function mockGetCommandOutput( import * as glob from '@actions/glob';
spy: jest.Mock, import {Globber} from '@actions/glob';
fn: (command: string, cwd?: string) => string import {MockGlobber} from './mock/glob-mock';
) {
spy.mockImplementation(async (command: any, _args: any, options: any) => ({
stdout: fn(command, options?.cwd),
stderr: '',
exitCode: 0
}));
}
function mockGetCommandOutputOnce(spy: jest.Mock, result: string) {
spy.mockImplementationOnce(async () => ({
stdout: result,
stderr: '',
exitCode: 0
}));
}
describe('cache-utils', () => { describe('cache-utils', () => {
const versionYarn1 = '1.2.3'; const versionYarn1 = '1.2.3';
let debugSpy: jest.Mock; let debugSpy: jest.SpyInstance;
let getExecOutputSpy: jest.Mock; let getCommandOutputSpy: jest.SpyInstance;
let isFeatureAvailable: jest.Mock; let isFeatureAvailable: jest.SpyInstance;
let info: jest.Mock; let info: jest.SpyInstance;
let warningSpy: jest.Mock; let warningSpy: jest.SpyInstance;
let fsRealPathSyncSpy: jest.SpiedFunction<typeof fs.realpathSync>; let fsRealPathSyncSpy: jest.SpyInstance;
beforeEach(() => { beforeEach(() => {
console.log('::stop-commands::stoptoken'); console.log('::stop-commands::stoptoken');
process.env['GITHUB_WORKSPACE'] = path.join(__dirname, 'data'); process.env['GITHUB_WORKSPACE'] = path.join(__dirname, 'data');
debugSpy = jest.spyOn(core, 'debug');
debugSpy.mockImplementation(msg => {});
debugSpy = core.debug as jest.Mock; info = jest.spyOn(core, 'info');
debugSpy.mockImplementation((_msg: any) => {}); warningSpy = jest.spyOn(core, 'warning');
info = core.info as jest.Mock; isFeatureAvailable = jest.spyOn(cache, 'isFeatureAvailable');
warningSpy = core.warning as jest.Mock;
isFeatureAvailable = cache.isFeatureAvailable as jest.Mock; getCommandOutputSpy = jest.spyOn(utils, 'getCommandOutput');
getExecOutputSpy = exec.getExecOutput as jest.Mock;
fsRealPathSyncSpy = jest.spyOn(fs, 'realpathSync'); fsRealPathSyncSpy = jest.spyOn(fs, 'realpathSync');
fsRealPathSyncSpy.mockImplementation((dirName: any) => { fsRealPathSyncSpy.mockImplementation(dirName => {
return dirName; return dirName;
}); });
}); });
@@ -135,6 +47,7 @@ describe('cache-utils', () => {
afterEach(() => { afterEach(() => {
jest.resetAllMocks(); jest.resetAllMocks();
jest.clearAllMocks(); jest.clearAllMocks();
//jest.restoreAllMocks();
}); });
afterAll(async () => { afterAll(async () => {
@@ -151,7 +64,7 @@ describe('cache-utils', () => {
['yarn2', null], ['yarn2', null],
['npm7', null] ['npm7', null]
])('getPackageManagerInfo for %s is %o', async (packageManager, result) => { ])('getPackageManagerInfo for %s is %o', async (packageManager, result) => {
mockGetCommandOutputOnce(getExecOutputSpy, versionYarn1); getCommandOutputSpy.mockImplementationOnce(() => versionYarn1);
await expect(utils.getPackageManagerInfo(packageManager)).resolves.toBe( await expect(utils.getPackageManagerInfo(packageManager)).resolves.toBe(
result result
); );
@@ -179,6 +92,7 @@ describe('cache-utils', () => {
it('isCacheFeatureAvailable for GHES is available', () => { it('isCacheFeatureAvailable for GHES is available', () => {
isFeatureAvailable.mockImplementation(() => true); isFeatureAvailable.mockImplementation(() => true);
expect(isCacheFeatureAvailable()).toStrictEqual(true); expect(isCacheFeatureAvailable()).toStrictEqual(true);
}); });
@@ -189,22 +103,24 @@ describe('cache-utils', () => {
}); });
describe('getCacheDirectoriesPaths', () => { describe('getCacheDirectoriesPaths', () => {
let existsSpy: jest.SpiedFunction<typeof fs.existsSync>; let existsSpy: jest.SpyInstance;
let lstatSpy: jest.SpiedFunction<typeof fs.lstatSync>; let lstatSpy: jest.SpyInstance;
let globCreateSpy: jest.Mock; let globCreateSpy: jest.SpyInstance;
beforeEach(() => { beforeEach(() => {
existsSpy = jest.spyOn(fs, 'existsSync'); existsSpy = jest.spyOn(fs, 'existsSync');
existsSpy.mockImplementation(() => true); existsSpy.mockImplementation(() => true);
lstatSpy = jest.spyOn(fs, 'lstatSync'); lstatSpy = jest.spyOn(fs, 'lstatSync');
lstatSpy.mockImplementation( lstatSpy.mockImplementation(arg => ({
(_arg: any) => ({isDirectory: () => true}) as any isDirectory: () => true
); }));
globCreateSpy = glob.create as jest.Mock; globCreateSpy = jest.spyOn(glob, 'create');
globCreateSpy.mockImplementation((_pattern: any) =>
MockGlobber.create(['/foo', '/bar']) globCreateSpy.mockImplementation(
(pattern: string): Promise<Globber> =>
MockGlobber.create(['/foo', '/bar'])
); );
resetProjectDirectoriesMemoized(); resetProjectDirectoriesMemoized();
@@ -213,6 +129,7 @@ describe('cache-utils', () => {
afterEach(() => { afterEach(() => {
existsSpy.mockRestore(); existsSpy.mockRestore();
lstatSpy.mockRestore(); lstatSpy.mockRestore();
globCreateSpy.mockRestore();
}); });
it.each([ it.each([
@@ -225,18 +142,22 @@ describe('cache-utils', () => {
])( ])(
'getCacheDirectoriesPaths should return one dir for non yarn', 'getCacheDirectoriesPaths should return one dir for non yarn',
async (packageManagerInfo, cacheDependency) => { async (packageManagerInfo, cacheDependency) => {
mockGetCommandOutput(getExecOutputSpy, () => 'foo'); getCommandOutputSpy.mockImplementation(() => 'foo');
const dirs = await cacheUtils.getCacheDirectories( const dirs = await cacheUtils.getCacheDirectories(
packageManagerInfo, packageManagerInfo,
cacheDependency cacheDependency
); );
expect(dirs).toEqual(['foo']); expect(dirs).toEqual(['foo']);
expect(getExecOutputSpy).toHaveBeenCalledTimes(1); // to do not call for a version
// call once for get cache folder
expect(getCommandOutputSpy).toHaveBeenCalledTimes(1);
} }
); );
it('getCacheDirectoriesPaths should return one dir for yarn without cacheDependency', async () => { it('getCacheDirectoriesPaths should return one dir for yarn without cacheDependency', async () => {
mockGetCommandOutput(getExecOutputSpy, () => 'foo'); getCommandOutputSpy.mockImplementation(() => 'foo');
const dirs = await cacheUtils.getCacheDirectories( const dirs = await cacheUtils.getCacheDirectories(
supportedPackageManagers.yarn, supportedPackageManagers.yarn,
'' ''
@@ -257,12 +178,15 @@ describe('cache-utils', () => {
])( ])(
'getCacheDirectoriesPaths should throw for getCommandOutput returning empty', 'getCacheDirectoriesPaths should throw for getCommandOutput returning empty',
async (packageManagerInfo, cacheDependency) => { async (packageManagerInfo, cacheDependency) => {
mockGetCommandOutput(getExecOutputSpy, (command: string) => getCommandOutputSpy.mockImplementation((command: string) =>
// return empty string to indicate getCacheFolderPath failed
// --version still works
command.includes('version') ? '1.' : '' command.includes('version') ? '1.' : ''
); );
await expect( await expect(
cacheUtils.getCacheDirectories(packageManagerInfo, cacheDependency) cacheUtils.getCacheDirectories(packageManagerInfo, cacheDependency)
).rejects.toThrow(); ).rejects.toThrow(); //'Could not get cache folder path for /dir');
} }
); );
@@ -272,9 +196,10 @@ describe('cache-utils', () => {
])( ])(
'getCacheDirectoriesPaths should nothrow in case of having not directories', 'getCacheDirectoriesPaths should nothrow in case of having not directories',
async (packageManagerInfo, cacheDependency) => { async (packageManagerInfo, cacheDependency) => {
lstatSpy.mockImplementation( lstatSpy.mockImplementation(arg => ({
(_arg: any) => ({isDirectory: () => false}) as any isDirectory: () => false
); }));
await cacheUtils.getCacheDirectories( await cacheUtils.getCacheDirectories(
packageManagerInfo, packageManagerInfo,
cacheDependency cacheDependency
@@ -289,8 +214,9 @@ describe('cache-utils', () => {
it.each(['1.1.1', '2.2.2'])( it.each(['1.1.1', '2.2.2'])(
'getCacheDirectoriesPaths yarn v%s should return one dir without cacheDependency', 'getCacheDirectoriesPaths yarn v%s should return one dir without cacheDependency',
async version => { async version => {
mockGetCommandOutputOnce(getExecOutputSpy, version); getCommandOutputSpy.mockImplementationOnce(() => version);
mockGetCommandOutputOnce(getExecOutputSpy, `foo${version}`); getCommandOutputSpy.mockImplementationOnce(() => `foo${version}`);
const dirs = await cacheUtils.getCacheDirectories( const dirs = await cacheUtils.getCacheDirectories(
supportedPackageManagers.yarn, supportedPackageManagers.yarn,
'' ''
@@ -303,12 +229,14 @@ describe('cache-utils', () => {
'getCacheDirectoriesPaths yarn v%s should return 2 dirs with globbed cacheDependency', 'getCacheDirectoriesPaths yarn v%s should return 2 dirs with globbed cacheDependency',
async version => { async version => {
let dirNo = 1; let dirNo = 1;
mockGetCommandOutput(getExecOutputSpy, (command: string) => getCommandOutputSpy.mockImplementation((command: string) =>
command.includes('version') ? version : `file_${version}_${dirNo++}` command.includes('version') ? version : `file_${version}_${dirNo++}`
); );
globCreateSpy.mockImplementation((_pattern: any) => globCreateSpy.mockImplementation(
MockGlobber.create(['/tmp/dir1/file', '/tmp/dir2/file']) (pattern: string): Promise<Globber> =>
MockGlobber.create(['/tmp/dir1/file', '/tmp/dir2/file'])
); );
const dirs = await cacheUtils.getCacheDirectories( const dirs = await cacheUtils.getCacheDirectories(
supportedPackageManagers.yarn, supportedPackageManagers.yarn,
'/tmp/**/file' '/tmp/**/file'
@@ -321,16 +249,18 @@ describe('cache-utils', () => {
'getCacheDirectoriesPaths yarn v%s should return 2 dirs with globbed cacheDependency expanding to duplicates', 'getCacheDirectoriesPaths yarn v%s should return 2 dirs with globbed cacheDependency expanding to duplicates',
async version => { async version => {
let dirNo = 1; let dirNo = 1;
mockGetCommandOutput(getExecOutputSpy, (command: string) => getCommandOutputSpy.mockImplementation((command: string) =>
command.includes('version') ? version : `file_${version}_${dirNo++}` command.includes('version') ? version : `file_${version}_${dirNo++}`
); );
globCreateSpy.mockImplementation((_pattern: any) => globCreateSpy.mockImplementation(
MockGlobber.create([ (pattern: string): Promise<Globber> =>
'/tmp/dir1/file', MockGlobber.create([
'/tmp/dir2/file', '/tmp/dir1/file',
'/tmp/dir1/file' '/tmp/dir2/file',
]) '/tmp/dir1/file'
])
); );
const dirs = await cacheUtils.getCacheDirectories( const dirs = await cacheUtils.getCacheDirectories(
supportedPackageManagers.yarn, supportedPackageManagers.yarn,
'/tmp/**/file' '/tmp/**/file'
@@ -343,59 +273,55 @@ describe('cache-utils', () => {
'getCacheDirectoriesPaths yarn v%s should return 2 uniq dirs despite duplicate cache directories', 'getCacheDirectoriesPaths yarn v%s should return 2 uniq dirs despite duplicate cache directories',
async version => { async version => {
let dirNo = 1; let dirNo = 1;
mockGetCommandOutput(getExecOutputSpy, (command: string) => getCommandOutputSpy.mockImplementation((command: string) =>
command.includes('version') command.includes('version')
? version ? version
: `file_${version}_${dirNo++ % 2}` : `file_${version}_${dirNo++ % 2}`
); );
globCreateSpy.mockImplementation((_pattern: any) => globCreateSpy.mockImplementation(
MockGlobber.create([ (pattern: string): Promise<Globber> =>
'/tmp/dir1/file', MockGlobber.create([
'/tmp/dir2/file', '/tmp/dir1/file',
'/tmp/dir3/file' '/tmp/dir2/file',
]) '/tmp/dir3/file'
])
); );
const dirs = await cacheUtils.getCacheDirectories( const dirs = await cacheUtils.getCacheDirectories(
supportedPackageManagers.yarn, supportedPackageManagers.yarn,
'/tmp/**/file' '/tmp/**/file'
); );
expect(dirs).toEqual([`file_${version}_1`, `file_${version}_0`]); expect(dirs).toEqual([`file_${version}_1`, `file_${version}_0`]);
expect(getExecOutputSpy).toHaveBeenCalledTimes(6); expect(getCommandOutputSpy).toHaveBeenCalledTimes(6);
expect(getExecOutputSpy).toHaveBeenCalledWith( expect(getCommandOutputSpy).toHaveBeenCalledWith(
'yarn --version', 'yarn --version',
undefined, '/tmp/dir1'
expect.objectContaining({cwd: '/tmp/dir1'})
); );
expect(getExecOutputSpy).toHaveBeenCalledWith( expect(getCommandOutputSpy).toHaveBeenCalledWith(
'yarn --version', 'yarn --version',
undefined, '/tmp/dir2'
expect.objectContaining({cwd: '/tmp/dir2'})
); );
expect(getExecOutputSpy).toHaveBeenCalledWith( expect(getCommandOutputSpy).toHaveBeenCalledWith(
'yarn --version', 'yarn --version',
undefined, '/tmp/dir3'
expect.objectContaining({cwd: '/tmp/dir3'})
); );
expect(getExecOutputSpy).toHaveBeenCalledWith( expect(getCommandOutputSpy).toHaveBeenCalledWith(
version.startsWith('1.') version.startsWith('1.')
? 'yarn cache dir' ? 'yarn cache dir'
: 'yarn config get cacheFolder', : 'yarn config get cacheFolder',
undefined, '/tmp/dir1'
expect.objectContaining({cwd: '/tmp/dir1'})
); );
expect(getExecOutputSpy).toHaveBeenCalledWith( expect(getCommandOutputSpy).toHaveBeenCalledWith(
version.startsWith('1.') version.startsWith('1.')
? 'yarn cache dir' ? 'yarn cache dir'
: 'yarn config get cacheFolder', : 'yarn config get cacheFolder',
undefined, '/tmp/dir2'
expect.objectContaining({cwd: '/tmp/dir2'})
); );
expect(getExecOutputSpy).toHaveBeenCalledWith( expect(getCommandOutputSpy).toHaveBeenCalledWith(
version.startsWith('1.') version.startsWith('1.')
? 'yarn cache dir' ? 'yarn cache dir'
: 'yarn config get cacheFolder', : 'yarn config get cacheFolder',
undefined, '/tmp/dir3'
expect.objectContaining({cwd: '/tmp/dir3'})
); );
} }
); );
@@ -403,20 +329,22 @@ describe('cache-utils', () => {
it.each(['1.1.1', '2.2.2'])( it.each(['1.1.1', '2.2.2'])(
'getCacheDirectoriesPaths yarn v%s should return 4 dirs with multiple globs', 'getCacheDirectoriesPaths yarn v%s should return 4 dirs with multiple globs',
async version => { async version => {
// simulate wrong indents
const cacheDependencyPath = `/tmp/dir1/file const cacheDependencyPath = `/tmp/dir1/file
/tmp/dir2/file /tmp/dir2/file
/tmp/**/file /tmp/**/file
`; `;
globCreateSpy.mockImplementation((_pattern: any) => globCreateSpy.mockImplementation(
MockGlobber.create([ (pattern: string): Promise<Globber> =>
'/tmp/dir1/file', MockGlobber.create([
'/tmp/dir2/file', '/tmp/dir1/file',
'/tmp/dir3/file', '/tmp/dir2/file',
'/tmp/dir4/file' '/tmp/dir3/file',
]) '/tmp/dir4/file'
])
); );
let dirNo = 1; let dirNo = 1;
mockGetCommandOutput(getExecOutputSpy, (command: string) => getCommandOutputSpy.mockImplementation((command: string) =>
command.includes('version') ? version : `file_${version}_${dirNo++}` command.includes('version') ? version : `file_${version}_${dirNo++}`
); );
const dirs = await cacheUtils.getCacheDirectories( const dirs = await cacheUtils.getCacheDirectories(

View File

@@ -1,162 +1,51 @@
import { import * as core from '@actions/core';
jest, import * as io from '@actions/io';
describe, import * as tc from '@actions/tool-cache';
it, import * as httpm from '@actions/http-client';
expect, import * as exec from '@actions/exec';
beforeEach, import * as cache from '@actions/cache';
afterEach,
afterAll
} from '@jest/globals';
import {fileURLToPath} from 'url';
import fs from 'fs'; import fs from 'fs';
import cp from 'child_process'; import cp from 'child_process';
import osm from 'os'; import osm from 'os';
import path from 'path'; import path from 'path';
import * as main from '../src/main';
import * as auth from '../src/authutil';
import {INodeVersion} from '../src/distributions/base-models';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); import nodeTestManifest from './data/versions-manifest.json';
import nodeTestDist from './data/node-dist-index.json';
// Mock @actions modules before importing anything that depends on them import nodeTestDistNightly from './data/node-nightly-index.json';
jest.unstable_mockModule('@actions/core', () => ({ import nodeTestDistRc from './data/node-rc-index.json';
info: jest.fn(), import nodeV8CanaryTestDist from './data/v8-canary-dist-index.json';
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((p: string) => p),
toWin32Path: jest.fn((p: string) => p),
toPosixPath: jest.fn((p: string) => p)
}));
jest.unstable_mockModule('@actions/io', () => ({
which: jest.fn(),
mkdirP: jest.fn(),
rmRF: jest.fn(),
mv: jest.fn(),
cp: jest.fn()
}));
jest.unstable_mockModule('@actions/tool-cache', () => ({
find: jest.fn(),
findAllVersions: jest.fn(),
downloadTool: jest.fn(),
extractTar: jest.fn(),
extractZip: jest.fn(),
extractXar: jest.fn(),
extract7z: jest.fn(),
cacheDir: jest.fn(),
cacheFile: jest.fn(),
getManifestFromRepo: jest.fn(),
findFromManifest: jest.fn(),
HTTPError: class HTTPError extends Error {
readonly httpStatusCode: number;
constructor(httpStatusCode?: number) {
super(`Unexpected HTTP response: ${httpStatusCode}`);
this.httpStatusCode = httpStatusCode ?? 0;
}
}
}));
const _mockGetJson = jest.fn();
jest.unstable_mockModule('@actions/http-client', () => ({
HttpClient: jest.fn().mockImplementation(() => ({
getJson: _mockGetJson
}))
}));
jest.unstable_mockModule('@actions/exec', () => ({
exec: jest.fn(),
getExecOutput: jest.fn()
}));
jest.unstable_mockModule('@actions/cache', () => ({
saveCache: jest.fn(),
restoreCache: jest.fn(),
isFeatureAvailable: jest.fn()
}));
// Pre-import real authutil before mocking
const realAuth = await import('../src/authutil.js');
jest.unstable_mockModule('../src/authutil.js', () => ({
...realAuth,
configAuthentication: jest.fn()
}));
// Dynamic imports after mocking
const core = await import('@actions/core');
const io = await import('@actions/io');
const tc = await import('@actions/tool-cache');
const httpm = await import('@actions/http-client');
const exec = await import('@actions/exec');
const cache = await import('@actions/cache');
const main = await import('../src/main.js');
const auth = await import('../src/authutil.js');
const {default: nodeTestManifest} = await import(
'./data/versions-manifest.json',
{with: {type: 'json'}}
);
const {default: nodeTestDist} = await import('./data/node-dist-index.json', {
with: {type: 'json'}
});
const {default: nodeTestDistNightly} = await import(
'./data/node-nightly-index.json',
{with: {type: 'json'}}
);
const {default: nodeTestDistRc} = await import('./data/node-rc-index.json', {
with: {type: 'json'}
});
const {default: nodeV8CanaryTestDist} = await import(
'./data/v8-canary-dist-index.json',
{with: {type: 'json'}}
);
import type {INodeVersion} from '../src/distributions/base-models.js';
import type {IToolRelease} from '@actions/tool-cache';
describe('setup-node', () => { describe('setup-node', () => {
let inputs = {} as any; let inputs = {} as any;
let os = {} as any; let os = {} as any;
let inSpy: jest.Mock; let inSpy: jest.SpyInstance;
let findSpy: jest.Mock; let findSpy: jest.SpyInstance;
let findAllVersionsSpy: jest.Mock; let findAllVersionsSpy: jest.SpyInstance;
let cnSpy: jest.SpiedFunction<typeof process.stdout.write>; let cnSpy: jest.SpyInstance;
let logSpy: jest.Mock; let logSpy: jest.SpyInstance;
let warningSpy: jest.Mock; let warningSpy: jest.SpyInstance;
let addPathSpy: jest.Mock; let getManifestSpy: jest.SpyInstance;
let setFailedSpy: jest.Mock; let getDistSpy: jest.SpyInstance;
let getManifestSpy: jest.Mock; let platSpy: jest.SpyInstance;
let getDistSpy: jest.Mock; let archSpy: jest.SpyInstance;
let platSpy: jest.SpiedFunction<typeof osm.platform>; let dlSpy: jest.SpyInstance;
let archSpy: jest.SpiedFunction<typeof osm.arch>; let exSpy: jest.SpyInstance;
let dlSpy: jest.Mock; let cacheSpy: jest.SpyInstance;
let exSpy: jest.Mock; let dbgSpy: jest.SpyInstance;
let cacheSpy: jest.Mock; let whichSpy: jest.SpyInstance;
let dbgSpy: jest.Mock; let existsSpy: jest.SpyInstance;
let whichSpy: jest.Mock; let readFileSyncSpy: jest.SpyInstance;
let existsSpy: jest.SpiedFunction<typeof fs.existsSync>; let mkdirpSpy: jest.SpyInstance;
let readFileSyncSpy: jest.Mock; let execSpy: jest.SpyInstance;
let mkdirpSpy: jest.Mock; let authSpy: jest.SpyInstance;
let execSpy: jest.SpiedFunction<typeof cp.execSync>; let parseNodeVersionSpy: jest.SpyInstance;
let authSpy: jest.Mock; let isCacheActionAvailable: jest.SpyInstance;
let parseNodeVersionSpy: jest.Mock; let getExecOutputSpy: jest.SpyInstance;
let isCacheActionAvailable: jest.Mock; let getJsonSpy: jest.SpyInstance;
let getExecOutputSpy: jest.Mock;
let getJsonSpy: jest.Mock;
beforeEach(() => { beforeEach(() => {
// @actions/core // @actions/core
@@ -164,8 +53,8 @@ describe('setup-node', () => {
process.env['GITHUB_PATH'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out process.env['GITHUB_PATH'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out
process.env['GITHUB_OUTPUT'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out process.env['GITHUB_OUTPUT'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out
inputs = {}; inputs = {};
inSpy = core.getInput as jest.Mock; inSpy = jest.spyOn(core, 'getInput');
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
// node // node
os = {}; os = {};
@@ -176,35 +65,34 @@ describe('setup-node', () => {
execSpy = jest.spyOn(cp, 'execSync'); execSpy = jest.spyOn(cp, 'execSync');
// @actions/tool-cache // @actions/tool-cache
findSpy = tc.find as jest.Mock; findSpy = jest.spyOn(tc, 'find');
findAllVersionsSpy = tc.findAllVersions as jest.Mock; findAllVersionsSpy = jest.spyOn(tc, 'findAllVersions');
dlSpy = tc.downloadTool as jest.Mock; dlSpy = jest.spyOn(tc, 'downloadTool');
exSpy = tc.extractTar as jest.Mock; exSpy = jest.spyOn(tc, 'extractTar');
cacheSpy = tc.cacheDir as jest.Mock; cacheSpy = jest.spyOn(tc, 'cacheDir');
getManifestSpy = tc.getManifestFromRepo as jest.Mock; getManifestSpy = jest.spyOn(tc, 'getManifestFromRepo');
// http-client // http-client
getJsonSpy = _mockGetJson; getJsonSpy = jest.spyOn(httpm.HttpClient.prototype, 'getJson');
(httpm.HttpClient as jest.Mock).mockImplementation(() => ({
getJson: _mockGetJson
}));
// io // io
whichSpy = io.which as jest.Mock; whichSpy = jest.spyOn(io, 'which');
existsSpy = jest.spyOn(fs, 'existsSync'); existsSpy = jest.spyOn(fs, 'existsSync');
mkdirpSpy = io.mkdirP as jest.Mock; mkdirpSpy = jest.spyOn(io, 'mkdirP');
// @actions/tool-cache // @actions/tool-cache
isCacheActionAvailable = cache.isFeatureAvailable as jest.Mock; isCacheActionAvailable = jest.spyOn(cache, 'isFeatureAvailable');
// disable authentication portion for installer tests // disable authentication portion for installer tests
authSpy = auth.configAuthentication as jest.Mock; authSpy = jest.spyOn(auth, 'configAuthentication');
authSpy.mockImplementation(() => {}); authSpy.mockImplementation(() => {});
// gets // gets
getManifestSpy.mockImplementation(() => <IToolRelease[]>nodeTestManifest); getManifestSpy.mockImplementation(
() => <tc.IToolRelease[]>nodeTestManifest
);
getJsonSpy.mockImplementation((url: any) => { getJsonSpy.mockImplementation(url => {
let res: any; let res: any;
if (url.includes('/rc')) { if (url.includes('/rc')) {
res = <INodeVersion[]>nodeTestDistRc; res = <INodeVersion[]>nodeTestDistRc;
@@ -221,18 +109,28 @@ describe('setup-node', () => {
// writes // writes
cnSpy = jest.spyOn(process.stdout, 'write'); cnSpy = jest.spyOn(process.stdout, 'write');
logSpy = core.info as jest.Mock; logSpy = jest.spyOn(core, 'info');
dbgSpy = core.debug as jest.Mock; dbgSpy = jest.spyOn(core, 'debug');
warningSpy = core.warning as jest.Mock; warningSpy = jest.spyOn(core, 'warning');
addPathSpy = core.addPath as jest.Mock; cnSpy.mockImplementation(line => {
setFailedSpy = core.setFailed as jest.Mock; // uncomment to debug
cnSpy.mockImplementation(() => true); // process.stderr.write('write:' + line + '\n');
logSpy.mockImplementation(() => {}); });
dbgSpy.mockImplementation(() => {}); logSpy.mockImplementation(line => {
warningSpy.mockImplementation(() => {}); // uncomment to debug
// process.stderr.write('log:' + line + '\n');
});
dbgSpy.mockImplementation(msg => {
// uncomment to see debug output
// process.stderr.write(msg + '\n');
});
warningSpy.mockImplementation(msg => {
// uncomment to debug
// process.stderr.write('log:' + msg + '\n');
});
// @actions/exec // @actions/exec
getExecOutputSpy = exec.getExecOutput as jest.Mock; getExecOutputSpy = jest.spyOn(exec, 'getExecOutput');
getExecOutputSpy.mockImplementation(() => 'v16.15.0'); getExecOutputSpy.mockImplementation(() => 'v16.15.0');
}); });
@@ -280,7 +178,7 @@ describe('setup-node', () => {
inputs['node-version'] = '20-v8-canary'; inputs['node-version'] = '20-v8-canary';
os['arch'] = 'x64'; os['arch'] = 'x64';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const toolPath = path.normalize( const toolPath = path.normalize(
'/cache/node/20.0.0-v8-canary20221103f7e2421e91/x64' '/cache/node/20.0.0-v8-canary20221103f7e2421e91/x64'
@@ -295,7 +193,7 @@ describe('setup-node', () => {
await main.run(); await main.run();
const expPath = path.join(toolPath, 'bin'); const expPath = path.join(toolPath, 'bin');
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('handles unhandled find error and reports error', async () => { it('handles unhandled find error and reports error', async () => {
@@ -315,7 +213,7 @@ describe('setup-node', () => {
await main.run(); await main.run();
expect(setFailedSpy).toHaveBeenCalledWith(errMsg); expect(cnSpy).toHaveBeenCalledWith('::error::' + errMsg + osm.EOL);
}); });
//-------------------------------------------------- //--------------------------------------------------
@@ -351,7 +249,7 @@ describe('setup-node', () => {
expect(logSpy).toHaveBeenCalledWith( expect(logSpy).toHaveBeenCalledWith(
`Attempting to download ${versionSpec}...` `Attempting to download ${versionSpec}...`
); );
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('does not find a version that does not exist', async () => { it('does not find a version that does not exist', async () => {
@@ -370,8 +268,8 @@ describe('setup-node', () => {
]); ]);
await main.run(); await main.run();
expect(setFailedSpy).toHaveBeenCalledWith( expect(cnSpy).toHaveBeenCalledWith(
`Unable to find Node version '${versionSpec}' for platform ${os.platform} and architecture ${os.arch}.` `::error::Unable to find Node version '${versionSpec}' for platform ${os.platform} and architecture ${os.arch}.${osm.EOL}`
); );
}); });
@@ -397,7 +295,7 @@ describe('setup-node', () => {
}); });
await main.run(); await main.run();
expect(setFailedSpy).toHaveBeenCalledWith(errMsg); expect(cnSpy).toHaveBeenCalledWith(`::error::${errMsg}${osm.EOL}`);
}); });
it('acquires specified architecture of node', async () => { it('acquires specified architecture of node', async () => {
@@ -421,6 +319,7 @@ describe('setup-node', () => {
darwin: 'darwin', darwin: 'darwin',
win32: 'win' win32: 'win'
}[os.platform]; }[os.platform];
inputs['node-version'] = version; inputs['node-version'] = version;
inputs['architecture'] = arch; inputs['architecture'] = arch;
inputs['token'] = 'faketoken'; inputs['token'] = 'faketoken';
@@ -494,7 +393,9 @@ describe('setup-node', () => {
); );
expect(logSpy).toHaveBeenCalledWith('Extracting ...'); expect(logSpy).toHaveBeenCalledWith('Extracting ...');
expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...'); expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...');
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin')); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
);
} }
); );
@@ -527,7 +428,9 @@ describe('setup-node', () => {
// assert // assert
expect(findAllVersionsSpy).toHaveBeenCalled(); expect(findAllVersionsSpy).toHaveBeenCalled();
expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`); expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`);
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin')); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
);
} }
); );
@@ -587,7 +490,9 @@ describe('setup-node', () => {
); );
expect(logSpy).toHaveBeenCalledWith('Extracting ...'); expect(logSpy).toHaveBeenCalledWith('Extracting ...');
expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...'); expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...');
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin')); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
);
} }
); );
@@ -649,7 +554,9 @@ describe('setup-node', () => {
); );
expect(logSpy).toHaveBeenCalledWith('Extracting ...'); expect(logSpy).toHaveBeenCalledWith('Extracting ...');
expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...'); expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...');
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin')); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
);
} }
); );
}); });
@@ -668,11 +575,13 @@ describe('setup-node', () => {
findAllVersionsSpy.mockImplementation(() => [versionExpected]); findAllVersionsSpy.mockImplementation(() => [versionExpected]);
const toolPath = path.normalize(`/cache/node/${versionExpected}/x64`); const toolPath = path.normalize(`/cache/node/${versionExpected}/x64`);
findSpy.mockImplementation((version: any) => toolPath); findSpy.mockImplementation(version => toolPath);
await main.run(); await main.run();
expect(addPathSpy).toHaveBeenCalledWith(`${toolPath}${path.sep}bin`); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${toolPath}${path.sep}bin${osm.EOL}`
);
expect(dlSpy).not.toHaveBeenCalled(); expect(dlSpy).not.toHaveBeenCalled();
expect(exSpy).not.toHaveBeenCalled(); expect(exSpy).not.toHaveBeenCalled();

View File

@@ -1,125 +1,43 @@
import { import * as core from '@actions/core';
jest, import * as exec from '@actions/exec';
describe, import * as tc from '@actions/tool-cache';
it, import * as cache from '@actions/cache';
expect, import * as io from '@actions/io';
beforeEach,
afterEach,
afterAll
} from '@jest/globals';
import {fileURLToPath} from 'url';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import osm from 'os'; import osm from 'os';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Mock @actions modules before importing anything that depends on them
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((p: string) => p),
toWin32Path: jest.fn((p: string) => p),
toPosixPath: jest.fn((p: string) => p)
}));
jest.unstable_mockModule('@actions/exec', () => ({
exec: jest.fn(),
getExecOutput: jest.fn()
}));
jest.unstable_mockModule('@actions/tool-cache', () => ({
find: jest.fn(),
findAllVersions: jest.fn(),
downloadTool: jest.fn(),
extractTar: jest.fn(),
extractZip: jest.fn(),
extractXar: jest.fn(),
extract7z: jest.fn(),
cacheDir: jest.fn(),
cacheFile: jest.fn(),
getManifestFromRepo: jest.fn(),
findFromManifest: jest.fn()
}));
jest.unstable_mockModule('@actions/cache', () => ({
saveCache: jest.fn(),
restoreCache: jest.fn(),
isFeatureAvailable: jest.fn()
}));
jest.unstable_mockModule('@actions/io', () => ({
which: jest.fn(),
mkdirP: jest.fn(),
rmRF: jest.fn(),
mv: jest.fn(),
cp: jest.fn()
}));
// Pre-import real util before mocking so we can spread it
const realUtil = await import('../src/util.js');
jest.unstable_mockModule('../src/util.js', () => ({
...realUtil,
getNodeVersionFromFile: jest.fn(realUtil.getNodeVersionFromFile)
}));
// Dynamic imports after mocking
const core = await import('@actions/core');
const exec = await import('@actions/exec');
const tc = await import('@actions/tool-cache');
const cache = await import('@actions/cache');
const io = await import('@actions/io');
const main = await import('../src/main.js');
const util = await import('../src/util.js');
const {default: OfficialBuilds} =
await import('../src/distributions/official_builds/official_builds.js');
import each from 'jest-each'; import each from 'jest-each';
import * as main from '../src/main';
import * as util from '../src/util';
import OfficialBuilds from '../src/distributions/official_builds/official_builds';
describe('main tests', () => { describe('main tests', () => {
let inputs = {} as any; let inputs = {} as any;
let os = {} as any; let os = {} as any;
let infoSpy: jest.Mock; let infoSpy: jest.SpyInstance;
let warningSpy: jest.Mock; let warningSpy: jest.SpyInstance;
let saveStateSpy: jest.Mock; let saveStateSpy: jest.SpyInstance;
let inSpy: jest.Mock; let inSpy: jest.SpyInstance;
let setOutputSpy: jest.Mock; let setOutputSpy: jest.SpyInstance;
let startGroupSpy: jest.Mock; let startGroupSpy: jest.SpyInstance;
let endGroupSpy: jest.Mock; let endGroupSpy: jest.SpyInstance;
let whichSpy: jest.Mock; let whichSpy: jest.SpyInstance;
let existsSpy: jest.Mock; let existsSpy: jest.SpyInstance;
let getExecOutputSpy: jest.Mock; let getExecOutputSpy: jest.SpyInstance;
let getNodeVersionFromFileSpy: jest.Mock; let getNodeVersionFromFileSpy: jest.SpyInstance;
let cnSpy: jest.SpiedFunction<typeof process.stdout.write>; let cnSpy: jest.SpyInstance;
let findSpy: jest.Mock; let findSpy: jest.SpyInstance;
let isCacheActionAvailable: jest.Mock; let isCacheActionAvailable: jest.SpyInstance;
let setupNodeJsSpy: jest.SpiedFunction< let setupNodeJsSpy: jest.SpyInstance;
typeof OfficialBuilds.prototype.setupNodeJs
>;
beforeEach(() => { beforeEach(() => {
inputs = {}; inputs = {};
@@ -130,34 +48,37 @@ describe('main tests', () => {
process.env['GITHUB_WORKSPACE'] = path.join(__dirname, 'data'); process.env['GITHUB_WORKSPACE'] = path.join(__dirname, 'data');
process.env['GITHUB_PATH'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out process.env['GITHUB_PATH'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out
process.env['GITHUB_OUTPUT'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out process.env['GITHUB_OUTPUT'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out
infoSpy = core.info as jest.Mock; infoSpy = jest.spyOn(core, 'info');
infoSpy.mockImplementation(() => {}); infoSpy.mockImplementation(() => {});
setOutputSpy = core.setOutput as jest.Mock; setOutputSpy = jest.spyOn(core, 'setOutput');
setOutputSpy.mockImplementation(() => {}); setOutputSpy.mockImplementation(() => {});
warningSpy = core.warning as jest.Mock; warningSpy = jest.spyOn(core, 'warning');
warningSpy.mockImplementation(() => {}); warningSpy.mockImplementation(() => {});
saveStateSpy = core.saveState as jest.Mock; saveStateSpy = jest.spyOn(core, 'saveState');
saveStateSpy.mockImplementation(() => {}); saveStateSpy.mockImplementation(() => {});
startGroupSpy = core.startGroup as jest.Mock; startGroupSpy = jest.spyOn(core, 'startGroup');
startGroupSpy.mockImplementation(() => {}); startGroupSpy.mockImplementation(() => {});
endGroupSpy = core.endGroup as jest.Mock; endGroupSpy = jest.spyOn(core, 'endGroup');
endGroupSpy.mockImplementation(() => {}); endGroupSpy.mockImplementation(() => {});
inSpy = core.getInput as jest.Mock; inSpy = jest.spyOn(core, 'getInput');
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
whichSpy = io.which as jest.Mock; whichSpy = jest.spyOn(io, 'which');
getExecOutputSpy = exec.getExecOutput as jest.Mock; getExecOutputSpy = jest.spyOn(exec, 'getExecOutput');
findSpy = tc.find as jest.Mock; findSpy = jest.spyOn(tc, 'find');
isCacheActionAvailable = cache.isFeatureAvailable as jest.Mock; isCacheActionAvailable = jest.spyOn(cache, 'isFeatureAvailable');
cnSpy = jest.spyOn(process.stdout, 'write'); cnSpy = jest.spyOn(process.stdout, 'write');
cnSpy.mockImplementation(() => true); cnSpy.mockImplementation(line => {
// uncomment to debug
process.stderr.write('write:' + line + '\n');
});
setupNodeJsSpy = jest.spyOn(OfficialBuilds.prototype, 'setupNodeJs'); setupNodeJsSpy = jest.spyOn(OfficialBuilds.prototype, 'setupNodeJs');
setupNodeJsSpy.mockImplementation(async () => {}); setupNodeJsSpy.mockImplementation(() => {});
}); });
afterEach(() => { afterEach(() => {
@@ -172,12 +93,6 @@ describe('main tests', () => {
}, 100000); }, 100000);
describe('getNodeVersionFromFile', () => { describe('getNodeVersionFromFile', () => {
beforeEach(() => {
(util.getNodeVersionFromFile as jest.Mock).mockImplementation(
realUtil.getNodeVersionFromFile as any
);
});
each` each`
contents | expected contents | expected
${'12'} | ${'12'} ${'12'} | ${'12'}
@@ -197,12 +112,12 @@ describe('main tests', () => {
${'{"engines": {"node": "17.0.0"}}'} | ${'17.0.0'} ${'{"engines": {"node": "17.0.0"}}'} | ${'17.0.0'}
${'{"devEngines": {"runtime": {"name": "node", "version": "22.0.0"}}}'} | ${'22.0.0'} ${'{"devEngines": {"runtime": {"name": "node", "version": "22.0.0"}}}'} | ${'22.0.0'}
${'{"devEngines": {"runtime": [{"name": "bun"}, {"name": "node", "version": "22.0.0"}]}}'} | ${'22.0.0'} ${'{"devEngines": {"runtime": [{"name": "bun"}, {"name": "node", "version": "22.0.0"}]}}'} | ${'22.0.0'}
`.it('parses "$contents"', ({contents, expected}: any) => { `.it('parses "$contents"', ({contents, expected}) => {
const existsSpy = jest.spyOn(fs, 'existsSync'); const existsSpy = jest.spyOn(fs, 'existsSync');
existsSpy.mockImplementation(() => true); existsSpy.mockImplementation(() => true);
const readFileSpy = jest.spyOn(fs, 'readFileSync'); const readFileSpy = jest.spyOn(fs, 'readFileSync');
readFileSpy.mockImplementation((filePath: any) => { readFileSpy.mockImplementation(filePath => {
if ( if (
typeof filePath === 'string' && typeof filePath === 'string' &&
path.basename(filePath) === 'package.json' path.basename(filePath) === 'package.json'
@@ -224,10 +139,8 @@ describe('main tests', () => {
[{node: '16.0.2', npm: '7.3.3', yarn: '2.22.11'}], [{node: '16.0.2', npm: '7.3.3', yarn: '2.22.11'}],
[{node: '14.0.1', npm: '8.1.0', yarn: '3.2.1'}], [{node: '14.0.1', npm: '8.1.0', yarn: '3.2.1'}],
[{node: '17.0.2', npm: '6.3.3', yarn: ''}] [{node: '17.0.2', npm: '6.3.3', yarn: ''}]
])('Tools versions %p', async (obj: any) => { ])('Tools versions %p', async obj => {
( getExecOutputSpy.mockImplementation(async command => {
getExecOutputSpy as jest.Mock<typeof exec.getExecOutput>
).mockImplementation(async (command: string) => {
if (Reflect.has(obj, command) && !obj[command]) { if (Reflect.has(obj, command) && !obj[command]) {
return { return {
stdout: '', stdout: '',
@@ -239,14 +152,14 @@ describe('main tests', () => {
return {stdout: obj[command], stderr: '', exitCode: 0}; return {stdout: obj[command], stderr: '', exitCode: 0};
}); });
whichSpy.mockImplementation((cmd: any) => { whichSpy.mockImplementation(cmd => {
return `some/${cmd}/path`; return `some/${cmd}/path`;
}); });
await util.printEnvDetailsAndSetOutput(); await util.printEnvDetailsAndSetOutput();
expect(setOutputSpy).toHaveBeenCalledWith('node-version', obj['node']); expect(setOutputSpy).toHaveBeenCalledWith('node-version', obj['node']);
Object.getOwnPropertyNames(obj).forEach((name: any) => { Object.getOwnPropertyNames(obj).forEach(name => {
if (!obj[name]) { if (!obj[name]) {
expect(infoSpy).toHaveBeenCalledWith( expect(infoSpy).toHaveBeenCalledWith(
`[warning]${name} does not exist` `[warning]${name} does not exist`
@@ -262,16 +175,11 @@ describe('main tests', () => {
delete inputs['node-version']; delete inputs['node-version'];
inputs['node-version-file'] = '.nvmrc'; inputs['node-version-file'] = '.nvmrc';
getNodeVersionFromFileSpy = util.getNodeVersionFromFile as jest.Mock; getNodeVersionFromFileSpy = jest.spyOn(util, 'getNodeVersionFromFile');
getNodeVersionFromFileSpy.mockImplementation(
realUtil.getNodeVersionFromFile as any
);
}); });
afterEach(() => { afterEach(() => {
getNodeVersionFromFileSpy.mockImplementation( getNodeVersionFromFileSpy.mockRestore();
realUtil.getNodeVersionFromFile as any
);
}); });
it('does not read node-version-file if node-version is provided', async () => { it('does not read node-version-file if node-version is provided', async () => {
@@ -330,8 +238,8 @@ describe('main tests', () => {
// Assert // Assert
expect(getNodeVersionFromFileSpy).toHaveBeenCalled(); expect(getNodeVersionFromFileSpy).toHaveBeenCalled();
expect(core.setFailed as jest.Mock).toHaveBeenCalledWith( expect(cnSpy).toHaveBeenCalledWith(
`The specified node version file at: ${versionFilePath} does not exist` `::error::The specified node version file at: ${versionFilePath} does not exist${osm.EOL}`
); );
}); });
}); });
@@ -341,7 +249,7 @@ describe('main tests', () => {
inputs['node-version'] = '12'; inputs['node-version'] = '12';
inputs['cache'] = 'npm'; inputs['cache'] = 'npm';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const toolPath = path.normalize('/cache/node/12.16.1/x64'); const toolPath = path.normalize('/cache/node/12.16.1/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
@@ -361,7 +269,7 @@ describe('main tests', () => {
inputs['node-version'] = '12'; inputs['node-version'] = '12';
inputs['cache'] = 'npm'; inputs['cache'] = 'npm';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const toolPath = path.normalize('/cache/node/12.16.1/x64'); const toolPath = path.normalize('/cache/node/12.16.1/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
@@ -384,7 +292,7 @@ describe('main tests', () => {
inputs['cache'] = ''; inputs['cache'] = '';
isCacheActionAvailable.mockImplementation(() => true); isCacheActionAvailable.mockImplementation(() => true);
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const readFileSpy = jest.spyOn(fs, 'readFileSync'); const readFileSpy = jest.spyOn(fs, 'readFileSync');
readFileSpy.mockImplementation(() => readFileSpy.mockImplementation(() =>
JSON.stringify({ JSON.stringify({
@@ -402,7 +310,7 @@ describe('main tests', () => {
inputs['cache'] = ''; inputs['cache'] = '';
isCacheActionAvailable.mockImplementation(() => true); isCacheActionAvailable.mockImplementation(() => true);
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const readFileSpy = jest.spyOn(fs, 'readFileSync'); const readFileSpy = jest.spyOn(fs, 'readFileSync');
readFileSpy.mockImplementation(() => readFileSpy.mockImplementation(() =>
JSON.stringify({ JSON.stringify({
@@ -422,7 +330,7 @@ describe('main tests', () => {
inputs['cache'] = ''; inputs['cache'] = '';
isCacheActionAvailable.mockImplementation(() => true); isCacheActionAvailable.mockImplementation(() => true);
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const readFileSpy = jest.spyOn(fs, 'readFileSync'); const readFileSpy = jest.spyOn(fs, 'readFileSync');
readFileSpy.mockImplementation(() => readFileSpy.mockImplementation(() =>
JSON.stringify({ JSON.stringify({
@@ -440,7 +348,7 @@ describe('main tests', () => {
it('Should not enable caching if packageManager is "pnpm@8.0.0" and cache input is not provided', async () => { it('Should not enable caching if packageManager is "pnpm@8.0.0" and cache input is not provided', async () => {
inputs['package-manager-cache'] = 'true'; inputs['package-manager-cache'] = 'true';
inputs['cache'] = ''; inputs['cache'] = '';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const readFileSpy = jest.spyOn(fs, 'readFileSync'); const readFileSpy = jest.spyOn(fs, 'readFileSync');
readFileSpy.mockImplementation(() => readFileSpy.mockImplementation(() =>
JSON.stringify({ JSON.stringify({
@@ -456,7 +364,7 @@ describe('main tests', () => {
it('Should not enable caching if devEngines.packageManager.name is "pnpm"', async () => { it('Should not enable caching if devEngines.packageManager.name is "pnpm"', async () => {
inputs['package-manager-cache'] = 'true'; inputs['package-manager-cache'] = 'true';
inputs['cache'] = ''; inputs['cache'] = '';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const readFileSpy = jest.spyOn(fs, 'readFileSync'); const readFileSpy = jest.spyOn(fs, 'readFileSync');
readFileSpy.mockImplementation(() => readFileSpy.mockImplementation(() =>
JSON.stringify({ JSON.stringify({
@@ -474,7 +382,7 @@ describe('main tests', () => {
it('Should not enable caching if devEngines.packageManager is array without "npm"', async () => { it('Should not enable caching if devEngines.packageManager is array without "npm"', async () => {
inputs['package-manager-cache'] = 'true'; inputs['package-manager-cache'] = 'true';
inputs['cache'] = ''; inputs['cache'] = '';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const readFileSpy = jest.spyOn(fs, 'readFileSync'); const readFileSpy = jest.spyOn(fs, 'readFileSync');
readFileSpy.mockImplementation(() => readFileSpy.mockImplementation(() =>
JSON.stringify({ JSON.stringify({
@@ -492,7 +400,7 @@ describe('main tests', () => {
it('Should not enable caching if packageManager field is missing in package.json and cache input is not provided', async () => { it('Should not enable caching if packageManager field is missing in package.json and cache input is not provided', async () => {
inputs['package-manager-cache'] = 'true'; inputs['package-manager-cache'] = 'true';
inputs['cache'] = ''; inputs['cache'] = '';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const readFileSpy = jest.spyOn(fs, 'readFileSync'); const readFileSpy = jest.spyOn(fs, 'readFileSync');
readFileSpy.mockImplementation(() => readFileSpy.mockImplementation(() =>
JSON.stringify({ JSON.stringify({
@@ -508,7 +416,7 @@ describe('main tests', () => {
it('Should skip caching when package-manager-cache is false', async () => { it('Should skip caching when package-manager-cache is false', async () => {
inputs['package-manager-cache'] = 'false'; inputs['package-manager-cache'] = 'false';
inputs['cache'] = ''; inputs['cache'] = '';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
await main.run(); await main.run();
expect(saveStateSpy).not.toHaveBeenCalled(); expect(saveStateSpy).not.toHaveBeenCalled();
}); });
@@ -516,7 +424,7 @@ describe('main tests', () => {
it('Should enable caching with cache input explicitly provided', async () => { it('Should enable caching with cache input explicitly provided', async () => {
inputs['package-manager-cache'] = 'true'; inputs['package-manager-cache'] = 'true';
inputs['cache'] = 'npm'; inputs['cache'] = 'npm';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
isCacheActionAvailable.mockImplementation(() => true); isCacheActionAvailable.mockImplementation(() => true);
await main.run(); await main.run();
expect(saveStateSpy).toHaveBeenCalledWith(expect.anything(), 'npm'); expect(saveStateSpy).toHaveBeenCalledWith(expect.anything(), 'npm');

View File

@@ -1,5 +1,4 @@
import {describe, it, expect} from '@jest/globals'; import {MockGlobber} from './glob-mock';
import {MockGlobber} from './glob-mock.js';
describe('mocked globber tests', () => { describe('mocked globber tests', () => {
it('globber should return generator', async () => { it('globber should return generator', async () => {

View File

@@ -1,160 +1,51 @@
import { import * as core from '@actions/core';
jest, import * as io from '@actions/io';
describe, import * as tc from '@actions/tool-cache';
it, import * as httpm from '@actions/http-client';
expect, import * as exec from '@actions/exec';
beforeEach, import * as cache from '@actions/cache';
afterEach,
afterAll
} from '@jest/globals';
import {fileURLToPath} from 'url';
import fs from 'fs'; import fs from 'fs';
import cp from 'child_process'; import cp from 'child_process';
import osm from 'os'; import osm from 'os';
import path from 'path'; import path from 'path';
import * as main from '../src/main';
import * as auth from '../src/authutil';
import {INodeVersion} from '../src/distributions/base-models';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); import nodeTestManifest from './data/versions-manifest.json';
import nodeTestDist from './data/node-dist-index.json';
// Mock @actions modules before importing anything that depends on them import nodeTestDistNightly from './data/node-nightly-index.json';
jest.unstable_mockModule('@actions/core', () => ({ import nodeTestDistRc from './data/node-rc-index.json';
info: jest.fn(), import nodeV8CanaryTestDist from './data/v8-canary-dist-index.json';
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((p: string) => p),
toWin32Path: jest.fn((p: string) => p),
toPosixPath: jest.fn((p: string) => p)
}));
jest.unstable_mockModule('@actions/io', () => ({
which: jest.fn(),
mkdirP: jest.fn(),
rmRF: jest.fn(),
mv: jest.fn(),
cp: jest.fn()
}));
jest.unstable_mockModule('@actions/tool-cache', () => ({
find: jest.fn(),
findAllVersions: jest.fn(),
downloadTool: jest.fn(),
extractTar: jest.fn(),
extractZip: jest.fn(),
extractXar: jest.fn(),
extract7z: jest.fn(),
cacheDir: jest.fn(),
cacheFile: jest.fn(),
getManifestFromRepo: jest.fn(),
findFromManifest: jest.fn(),
HTTPError: class HTTPError extends Error {
readonly httpStatusCode: number;
constructor(httpStatusCode?: number) {
super(`Unexpected HTTP response: ${httpStatusCode}`);
this.httpStatusCode = httpStatusCode ?? 0;
}
}
}));
const _mockGetJson = jest.fn();
jest.unstable_mockModule('@actions/http-client', () => ({
HttpClient: jest.fn().mockImplementation(() => ({
getJson: _mockGetJson
}))
}));
jest.unstable_mockModule('@actions/exec', () => ({
exec: jest.fn(),
getExecOutput: jest.fn()
}));
jest.unstable_mockModule('@actions/cache', () => ({
saveCache: jest.fn(),
restoreCache: jest.fn(),
isFeatureAvailable: jest.fn()
}));
const realAuth = await import('../src/authutil.js');
jest.unstable_mockModule('../src/authutil.js', () => ({
...realAuth,
configAuthentication: jest.fn()
}));
// Dynamic imports after mocking
const core = await import('@actions/core');
const io = await import('@actions/io');
const tc = await import('@actions/tool-cache');
const httpm = await import('@actions/http-client');
const exec = await import('@actions/exec');
const cache = await import('@actions/cache');
const main = await import('../src/main.js');
const auth = await import('../src/authutil.js');
const {default: nodeTestManifest} = await import(
'./data/versions-manifest.json',
{with: {type: 'json'}}
);
const {default: nodeTestDist} = await import('./data/node-dist-index.json', {
with: {type: 'json'}
});
const {default: nodeTestDistNightly} = await import(
'./data/node-nightly-index.json',
{with: {type: 'json'}}
);
const {default: nodeTestDistRc} = await import('./data/node-rc-index.json', {
with: {type: 'json'}
});
const {default: nodeV8CanaryTestDist} = await import(
'./data/v8-canary-dist-index.json',
{with: {type: 'json'}}
);
import type {INodeVersion} from '../src/distributions/base-models.js';
describe('setup-node', () => { describe('setup-node', () => {
let inputs = {} as any; let inputs = {} as any;
let os = {} as any; let os = {} as any;
let inSpy: jest.Mock; let inSpy: jest.SpyInstance;
let findSpy: jest.Mock; let findSpy: jest.SpyInstance;
let findAllVersionsSpy: jest.Mock; let findAllVersionsSpy: jest.SpyInstance;
let cnSpy: jest.SpiedFunction<typeof process.stdout.write>; let cnSpy: jest.SpyInstance;
let logSpy: jest.Mock; let logSpy: jest.SpyInstance;
let warningSpy: jest.Mock; let warningSpy: jest.SpyInstance;
let addPathSpy: jest.Mock; let getManifestSpy: jest.SpyInstance;
let setFailedSpy: jest.Mock; let getDistSpy: jest.SpyInstance;
let getManifestSpy: jest.Mock; let platSpy: jest.SpyInstance;
let getDistSpy: jest.Mock; let archSpy: jest.SpyInstance;
let platSpy: jest.SpiedFunction<typeof osm.platform>; let dlSpy: jest.SpyInstance;
let archSpy: jest.SpiedFunction<typeof osm.arch>; let exSpy: jest.SpyInstance;
let dlSpy: jest.Mock; let cacheSpy: jest.SpyInstance;
let exSpy: jest.Mock; let dbgSpy: jest.SpyInstance;
let cacheSpy: jest.Mock; let whichSpy: jest.SpyInstance;
let dbgSpy: jest.Mock; let existsSpy: jest.SpyInstance;
let whichSpy: jest.Mock; let mkdirpSpy: jest.SpyInstance;
let existsSpy: jest.SpiedFunction<typeof fs.existsSync>; let cpSpy: jest.SpyInstance;
let mkdirpSpy: jest.Mock; let execSpy: jest.SpyInstance;
let cpSpy: jest.Mock; let authSpy: jest.SpyInstance;
let execSpy: jest.SpiedFunction<typeof cp.execSync>; let parseNodeVersionSpy: jest.SpyInstance;
let authSpy: jest.Mock; let isCacheActionAvailable: jest.SpyInstance;
let parseNodeVersionSpy: jest.Mock; let getExecOutputSpy: jest.SpyInstance;
let isCacheActionAvailable: jest.Mock; let getJsonSpy: jest.SpyInstance;
let getExecOutputSpy: jest.Mock;
let getJsonSpy: jest.Mock;
beforeEach(() => { beforeEach(() => {
// @actions/core // @actions/core
@@ -163,8 +54,8 @@ describe('setup-node', () => {
process.env['GITHUB_OUTPUT'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out process.env['GITHUB_OUTPUT'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out
process.env['RUNNER_TEMP'] = '/runner_temp'; process.env['RUNNER_TEMP'] = '/runner_temp';
inputs = {}; inputs = {};
inSpy = core.getInput as jest.Mock; inSpy = jest.spyOn(core, 'getInput');
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
// node // node
os = {}; os = {};
@@ -175,33 +66,30 @@ describe('setup-node', () => {
execSpy = jest.spyOn(cp, 'execSync'); execSpy = jest.spyOn(cp, 'execSync');
// @actions/tool-cache // @actions/tool-cache
findSpy = tc.find as jest.Mock; findSpy = jest.spyOn(tc, 'find');
findAllVersionsSpy = tc.findAllVersions as jest.Mock; findAllVersionsSpy = jest.spyOn(tc, 'findAllVersions');
dlSpy = tc.downloadTool as jest.Mock; dlSpy = jest.spyOn(tc, 'downloadTool');
exSpy = tc.extractTar as jest.Mock; exSpy = jest.spyOn(tc, 'extractTar');
cacheSpy = tc.cacheDir as jest.Mock; cacheSpy = jest.spyOn(tc, 'cacheDir');
getManifestSpy = tc.getManifestFromRepo as jest.Mock; getManifestSpy = jest.spyOn(tc, 'getManifestFromRepo');
// http-client // http-client
getJsonSpy = _mockGetJson; getJsonSpy = jest.spyOn(httpm.HttpClient.prototype, 'getJson');
(httpm.HttpClient as jest.Mock).mockImplementation(() => ({
getJson: _mockGetJson
}));
// io // io
whichSpy = io.which as jest.Mock; whichSpy = jest.spyOn(io, 'which');
existsSpy = jest.spyOn(fs, 'existsSync'); existsSpy = jest.spyOn(fs, 'existsSync');
mkdirpSpy = io.mkdirP as jest.Mock; mkdirpSpy = jest.spyOn(io, 'mkdirP');
cpSpy = io.cp as jest.Mock; cpSpy = jest.spyOn(io, 'cp');
// @actions/tool-cache // @actions/tool-cache
isCacheActionAvailable = cache.isFeatureAvailable as jest.Mock; isCacheActionAvailable = jest.spyOn(cache, 'isFeatureAvailable');
// disable authentication portion for installer tests // disable authentication portion for installer tests
authSpy = auth.configAuthentication as jest.Mock; authSpy = jest.spyOn(auth, 'configAuthentication');
authSpy.mockImplementation(() => {}); authSpy.mockImplementation(() => {});
getJsonSpy.mockImplementation((url: any) => { getJsonSpy.mockImplementation(url => {
let res: any; let res: any;
if (url.includes('/rc')) { if (url.includes('/rc')) {
res = <INodeVersion[]>nodeTestDistRc; res = <INodeVersion[]>nodeTestDistRc;
@@ -218,18 +106,28 @@ describe('setup-node', () => {
// writes // writes
cnSpy = jest.spyOn(process.stdout, 'write'); cnSpy = jest.spyOn(process.stdout, 'write');
logSpy = core.info as jest.Mock; logSpy = jest.spyOn(core, 'info');
dbgSpy = core.debug as jest.Mock; dbgSpy = jest.spyOn(core, 'debug');
warningSpy = core.warning as jest.Mock; warningSpy = jest.spyOn(core, 'warning');
addPathSpy = core.addPath as jest.Mock; cnSpy.mockImplementation(line => {
setFailedSpy = core.setFailed as jest.Mock; // uncomment to debug
cnSpy.mockImplementation(() => true); // process.stderr.write('write:' + line + '\n');
logSpy.mockImplementation(() => {}); });
dbgSpy.mockImplementation(() => {}); logSpy.mockImplementation(line => {
warningSpy.mockImplementation(() => {}); // uncomment to debug
// process.stderr.write('log:' + line + '\n');
});
dbgSpy.mockImplementation(msg => {
// uncomment to see debug output
// process.stderr.write(msg + '\n');
});
warningSpy.mockImplementation(msg => {
// uncomment to debug
// process.stderr.write('log:' + msg + '\n');
});
// @actions/exec // @actions/exec
getExecOutputSpy = exec.getExecOutput as jest.Mock; getExecOutputSpy = jest.spyOn(exec, 'getExecOutput');
getExecOutputSpy.mockImplementation(() => 'v16.15.0'); getExecOutputSpy.mockImplementation(() => 'v16.15.0');
}); });
@@ -304,7 +202,7 @@ describe('setup-node', () => {
inputs['node-version'] = '16-nightly'; inputs['node-version'] = '16-nightly';
os['arch'] = 'x64'; os['arch'] = 'x64';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const toolPath = path.normalize( const toolPath = path.normalize(
'/cache/node/16.0.0-nightly20210417bc31dc0e0f/x64' '/cache/node/16.0.0-nightly20210417bc31dc0e0f/x64'
@@ -326,7 +224,7 @@ describe('setup-node', () => {
); );
const expPath = path.join(toolPath, 'bin'); const expPath = path.join(toolPath, 'bin');
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('handles unhandled find error and reports error', async () => { it('handles unhandled find error and reports error', async () => {
@@ -346,7 +244,7 @@ describe('setup-node', () => {
await main.run(); await main.run();
expect(setFailedSpy).toHaveBeenCalledWith(errMsg); expect(cnSpy).toHaveBeenCalledWith('::error::' + errMsg + osm.EOL);
}); });
it('falls back to a version from node dist', async () => { it('falls back to a version from node dist', async () => {
@@ -376,7 +274,7 @@ describe('setup-node', () => {
expect(dlSpy).toHaveBeenCalled(); expect(dlSpy).toHaveBeenCalled();
expect(exSpy).toHaveBeenCalled(); expect(exSpy).toHaveBeenCalled();
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('windows: falls back to exe version if not in manifest and not in node dist', async () => { it('windows: falls back to exe version if not in manifest and not in node dist', async () => {
@@ -398,8 +296,8 @@ describe('setup-node', () => {
findSpy.mockImplementation(() => ''); findSpy.mockImplementation(() => '');
findAllVersionsSpy.mockImplementation(() => []); findAllVersionsSpy.mockImplementation(() => []);
dlSpy.mockImplementation(async (url: any) => { dlSpy.mockImplementation(async url => {
if (workingUrls.includes(url as string)) { if (workingUrls.includes(url)) {
return '/some/temp/path'; return '/some/temp/path';
} }
@@ -414,10 +312,10 @@ describe('setup-node', () => {
await main.run(); await main.run();
workingUrls.forEach((url: any) => { workingUrls.forEach(url => {
expect(dlSpy).toHaveBeenCalledWith(url, undefined, undefined); expect(dlSpy).toHaveBeenCalledWith(url, undefined, undefined);
}); });
expect(addPathSpy).toHaveBeenCalledWith(toolPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${toolPath}${osm.EOL}`);
}); });
it('linux: does not fall back to exe version if not in manifest and not in node dist', async () => { it('linux: does not fall back to exe version if not in manifest and not in node dist', async () => {
@@ -439,8 +337,8 @@ describe('setup-node', () => {
findSpy.mockImplementation(() => ''); findSpy.mockImplementation(() => '');
findAllVersionsSpy.mockImplementation(() => []); findAllVersionsSpy.mockImplementation(() => []);
dlSpy.mockImplementation(async (url: any) => { dlSpy.mockImplementation(async url => {
if (workingUrls.includes(url as string)) { if (workingUrls.includes(url)) {
return '/some/temp/path'; return '/some/temp/path';
} }
@@ -455,10 +353,12 @@ describe('setup-node', () => {
await main.run(); await main.run();
workingUrls.forEach((url: any) => { workingUrls.forEach(url => {
expect(dlSpy).not.toHaveBeenCalledWith(url); expect(dlSpy).not.toHaveBeenCalledWith(url);
}); });
expect(setFailedSpy).toHaveBeenCalledWith('Unexpected HTTP response: 404'); expect(cnSpy).toHaveBeenCalledWith(
`::error::Unexpected HTTP response: 404${osm.EOL}`
);
}); });
it('does not find a version that does not exist', async () => { it('does not find a version that does not exist', async () => {
@@ -472,8 +372,8 @@ describe('setup-node', () => {
findAllVersionsSpy.mockImplementation(() => []); findAllVersionsSpy.mockImplementation(() => []);
await main.run(); await main.run();
expect(setFailedSpy).toHaveBeenCalledWith( expect(cnSpy).toHaveBeenCalledWith(
`Unable to find Node version '${versionSpec}' for platform ${os.platform} and architecture ${os.arch}.` `::error::Unable to find Node version '${versionSpec}' for platform ${os.platform} and architecture ${os.arch}.${osm.EOL}`
); );
}); });
@@ -496,7 +396,7 @@ describe('setup-node', () => {
}); });
await main.run(); await main.run();
expect(setFailedSpy).toHaveBeenCalledWith(errMsg); expect(cnSpy).toHaveBeenCalledWith(`::error::${errMsg}${osm.EOL}`);
}); });
it('acquires specified architecture of node', async () => { it('acquires specified architecture of node', async () => {
@@ -520,6 +420,7 @@ describe('setup-node', () => {
darwin: 'darwin', darwin: 'darwin',
win32: 'win' win32: 'win'
}[os.platform]; }[os.platform];
inputs['node-version'] = version; inputs['node-version'] = version;
inputs['architecture'] = arch; inputs['architecture'] = arch;
inputs['token'] = 'faketoken'; inputs['token'] = 'faketoken';
@@ -564,6 +465,7 @@ describe('setup-node', () => {
darwin: 'darwin', darwin: 'darwin',
win32: 'win' win32: 'win'
}[os.platform]; }[os.platform];
inputs['node-version'] = version; inputs['node-version'] = version;
inputs['architecture'] = arch; inputs['architecture'] = arch;
inputs['token'] = 'faketoken'; inputs['token'] = 'faketoken';
@@ -639,7 +541,9 @@ describe('setup-node', () => {
); );
expect(logSpy).toHaveBeenCalledWith('Extracting ...'); expect(logSpy).toHaveBeenCalledWith('Extracting ...');
expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...'); expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...');
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin')); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
);
} }
); );
@@ -669,7 +573,9 @@ describe('setup-node', () => {
// assert // assert
expect(findAllVersionsSpy).toHaveBeenCalled(); expect(findAllVersionsSpy).toHaveBeenCalled();
expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`); expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`);
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin')); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
);
} }
); );
@@ -735,7 +641,9 @@ describe('setup-node', () => {
); );
expect(logSpy).toHaveBeenCalledWith('Extracting ...'); expect(logSpy).toHaveBeenCalledWith('Extracting ...');
expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...'); expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...');
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin')); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
);
} }
); );
}); });

View File

@@ -1,163 +1,51 @@
import { import * as core from '@actions/core';
jest, import * as io from '@actions/io';
describe, import * as tc from '@actions/tool-cache';
it, import * as httpm from '@actions/http-client';
expect, import * as exec from '@actions/exec';
beforeEach, import * as cache from '@actions/cache';
afterEach,
afterAll
} from '@jest/globals';
import {fileURLToPath} from 'url';
import fs from 'fs'; import fs from 'fs';
import cp from 'child_process'; import cp from 'child_process';
import osm from 'os'; import osm from 'os';
import path from 'path'; import path from 'path';
import * as main from '../src/main';
import * as auth from '../src/authutil';
import OfficialBuilds from '../src/distributions/official_builds/official_builds';
import {INodeVersion} from '../src/distributions/base-models';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); import nodeTestManifest from './data/versions-manifest.json';
import nodeTestDist from './data/node-dist-index.json';
// Mock @actions modules before importing anything that depends on them import nodeTestDistNightly from './data/node-nightly-index.json';
jest.unstable_mockModule('@actions/core', () => ({ import nodeTestDistRc from './data/node-rc-index.json';
info: jest.fn(), import nodeV8CanaryTestDist from './data/v8-canary-dist-index.json';
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((p: string) => p),
toWin32Path: jest.fn((p: string) => p),
toPosixPath: jest.fn((p: string) => p)
}));
jest.unstable_mockModule('@actions/io', () => ({
which: jest.fn(),
mkdirP: jest.fn(),
rmRF: jest.fn(),
mv: jest.fn(),
cp: jest.fn()
}));
jest.unstable_mockModule('@actions/tool-cache', () => ({
find: jest.fn(),
findAllVersions: jest.fn(),
downloadTool: jest.fn(),
extractTar: jest.fn(),
extractZip: jest.fn(),
extractXar: jest.fn(),
extract7z: jest.fn(),
cacheDir: jest.fn(),
cacheFile: jest.fn(),
getManifestFromRepo: jest.fn(),
findFromManifest: jest.fn(),
HTTPError: class HTTPError extends Error {
readonly httpStatusCode: number;
constructor(httpStatusCode?: number) {
super(`Unexpected HTTP response: ${httpStatusCode}`);
this.httpStatusCode = httpStatusCode ?? 0;
}
}
}));
const _mockGetJson = jest.fn();
jest.unstable_mockModule('@actions/http-client', () => ({
HttpClient: jest.fn().mockImplementation(() => ({
getJson: _mockGetJson
}))
}));
jest.unstable_mockModule('@actions/exec', () => ({
exec: jest.fn(),
getExecOutput: jest.fn()
}));
jest.unstable_mockModule('@actions/cache', () => ({
saveCache: jest.fn(),
restoreCache: jest.fn(),
isFeatureAvailable: jest.fn()
}));
// Pre-import real authutil before mocking
const realAuth = await import('../src/authutil.js');
jest.unstable_mockModule('../src/authutil.js', () => ({
...realAuth,
configAuthentication: jest.fn()
}));
// Dynamic imports after mocking
const core = await import('@actions/core');
const io = await import('@actions/io');
const tc = await import('@actions/tool-cache');
const httpm = await import('@actions/http-client');
const exec = await import('@actions/exec');
const cache = await import('@actions/cache');
const main = await import('../src/main.js');
const auth = await import('../src/authutil.js');
const {default: OfficialBuilds} =
await import('../src/distributions/official_builds/official_builds.js');
const {default: nodeTestManifest} = await import(
'./data/versions-manifest.json',
{with: {type: 'json'}}
);
const {default: nodeTestDist} = await import('./data/node-dist-index.json', {
with: {type: 'json'}
});
const {default: nodeTestDistNightly} = await import(
'./data/node-nightly-index.json',
{with: {type: 'json'}}
);
const {default: nodeTestDistRc} = await import('./data/node-rc-index.json', {
with: {type: 'json'}
});
const {default: nodeV8CanaryTestDist} = await import(
'./data/v8-canary-dist-index.json',
{with: {type: 'json'}}
);
import type {INodeVersion} from '../src/distributions/base-models.js';
import type {IToolRelease} from '@actions/tool-cache';
describe('setup-node', () => { describe('setup-node', () => {
let build: InstanceType<typeof OfficialBuilds>; let build: OfficialBuilds;
let inputs = {} as any; let inputs = {} as any;
let os = {} as any; let os = {} as any;
let inSpy: jest.Mock; let inSpy: jest.SpyInstance;
let findSpy: jest.Mock; let findSpy: jest.SpyInstance;
let findAllVersionsSpy: jest.Mock; let findAllVersionsSpy: jest.SpyInstance;
let cnSpy: jest.SpiedFunction<typeof process.stdout.write>; let cnSpy: jest.SpyInstance;
let logSpy: jest.Mock; let logSpy: jest.SpyInstance;
let warningSpy: jest.Mock; let warningSpy: jest.SpyInstance;
let addPathSpy: jest.Mock; let getManifestSpy: jest.SpyInstance;
let setFailedSpy: jest.Mock; let platSpy: jest.SpyInstance;
let getManifestSpy: jest.Mock; let archSpy: jest.SpyInstance;
let platSpy: jest.SpiedFunction<typeof osm.platform>; let dlSpy: jest.SpyInstance;
let archSpy: jest.SpiedFunction<typeof osm.arch>; let exSpy: jest.SpyInstance;
let dlSpy: jest.Mock; let cacheSpy: jest.SpyInstance;
let exSpy: jest.Mock; let dbgSpy: jest.SpyInstance;
let cacheSpy: jest.Mock; let whichSpy: jest.SpyInstance;
let dbgSpy: jest.Mock; let existsSpy: jest.SpyInstance;
let whichSpy: jest.Mock; let readFileSyncSpy: jest.SpyInstance;
let existsSpy: jest.SpiedFunction<typeof fs.existsSync>; let mkdirpSpy: jest.SpyInstance;
let readFileSyncSpy: jest.Mock; let execSpy: jest.SpyInstance;
let mkdirpSpy: jest.Mock; let authSpy: jest.SpyInstance;
let execSpy: jest.SpiedFunction<typeof cp.execSync>; let isCacheActionAvailable: jest.SpyInstance;
let authSpy: jest.Mock; let getExecOutputSpy: jest.SpyInstance;
let isCacheActionAvailable: jest.Mock; let getJsonSpy: jest.SpyInstance;
let getExecOutputSpy: jest.Mock;
let getJsonSpy: jest.Mock;
beforeEach(() => { beforeEach(() => {
// @actions/core // @actions/core
@@ -165,8 +53,8 @@ describe('setup-node', () => {
process.env['GITHUB_PATH'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out process.env['GITHUB_PATH'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out
process.env['GITHUB_OUTPUT'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out process.env['GITHUB_OUTPUT'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out
inputs = {}; inputs = {};
inSpy = core.getInput as jest.Mock; inSpy = jest.spyOn(core, 'getInput');
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
// node // node
os = {}; os = {};
@@ -177,61 +65,34 @@ describe('setup-node', () => {
execSpy = jest.spyOn(cp, 'execSync'); execSpy = jest.spyOn(cp, 'execSync');
// @actions/tool-cache // @actions/tool-cache
findSpy = tc.find as jest.Mock; findSpy = jest.spyOn(tc, 'find');
findAllVersionsSpy = tc.findAllVersions as jest.Mock; findAllVersionsSpy = jest.spyOn(tc, 'findAllVersions');
dlSpy = tc.downloadTool as jest.Mock; dlSpy = jest.spyOn(tc, 'downloadTool');
exSpy = tc.extractTar as jest.Mock; exSpy = jest.spyOn(tc, 'extractTar');
cacheSpy = tc.cacheDir as jest.Mock; cacheSpy = jest.spyOn(tc, 'cacheDir');
getManifestSpy = tc.getManifestFromRepo as jest.Mock; getManifestSpy = jest.spyOn(tc, 'getManifestFromRepo');
// Restore findFromManifest after clearMocks.
// In ESM, the real tc.findFromManifest uses os.platform() from its own
// module namespace, which jest.spyOn on our os import cannot override.
// So we provide a minimal reimplementation that uses the test's os var.
(tc.findFromManifest as jest.Mock).mockImplementation(
async (versionSpec: any, stable: any, manifest: any, archFilter: any) => {
const arch = archFilter || os['arch'] || 'x64';
const plat = os['platform'] || process.platform;
const semverModule = await import('semver');
for (const rel of manifest || []) {
if (
semverModule.default.satisfies(rel.version, versionSpec, {
includePrerelease: true
}) &&
rel.stable === stable
) {
const file = rel.files.find(
(f: any) => f.arch === arch && f.platform === plat
);
if (file) return {...rel, files: [file]};
}
}
return undefined;
}
);
// http-client // http-client
getJsonSpy = _mockGetJson; getJsonSpy = jest.spyOn(httpm.HttpClient.prototype, 'getJson');
(httpm.HttpClient as jest.Mock).mockImplementation(() => ({
getJson: _mockGetJson
}));
// io // io
whichSpy = io.which as jest.Mock; whichSpy = jest.spyOn(io, 'which');
existsSpy = jest.spyOn(fs, 'existsSync'); existsSpy = jest.spyOn(fs, 'existsSync');
mkdirpSpy = io.mkdirP as jest.Mock; mkdirpSpy = jest.spyOn(io, 'mkdirP');
// @actions/tool-cache // @actions/tool-cache
isCacheActionAvailable = cache.isFeatureAvailable as jest.Mock; isCacheActionAvailable = jest.spyOn(cache, 'isFeatureAvailable');
// disable authentication portion for installer tests // disable authentication portion for installer tests
authSpy = auth.configAuthentication as jest.Mock; authSpy = jest.spyOn(auth, 'configAuthentication');
authSpy.mockImplementation(() => {}); authSpy.mockImplementation(() => {});
// gets // gets
getManifestSpy.mockImplementation(() => <IToolRelease[]>nodeTestManifest); getManifestSpy.mockImplementation(
() => <tc.IToolRelease[]>nodeTestManifest
);
getJsonSpy.mockImplementation((url: any) => { getJsonSpy.mockImplementation(url => {
let res: any; let res: any;
if (url.includes('/rc')) { if (url.includes('/rc')) {
res = <INodeVersion[]>nodeTestDistRc; res = <INodeVersion[]>nodeTestDistRc;
@@ -246,18 +107,28 @@ describe('setup-node', () => {
// writes // writes
cnSpy = jest.spyOn(process.stdout, 'write'); cnSpy = jest.spyOn(process.stdout, 'write');
logSpy = core.info as jest.Mock; logSpy = jest.spyOn(core, 'info');
dbgSpy = core.debug as jest.Mock; dbgSpy = jest.spyOn(core, 'debug');
warningSpy = core.warning as jest.Mock; warningSpy = jest.spyOn(core, 'warning');
addPathSpy = core.addPath as jest.Mock; cnSpy.mockImplementation(line => {
setFailedSpy = core.setFailed as jest.Mock; // uncomment to debug
cnSpy.mockImplementation(() => true); process.stderr.write('write:' + line + '\n');
logSpy.mockImplementation(() => {}); });
dbgSpy.mockImplementation(() => {}); logSpy.mockImplementation(line => {
warningSpy.mockImplementation(() => {}); // uncomment to debug
process.stderr.write('log:' + line + '\n');
});
dbgSpy.mockImplementation(msg => {
// uncomment to see debug output
// process.stderr.write(msg + '\n');
});
warningSpy.mockImplementation(msg => {
// uncomment to debug
// process.stderr.write('log:' + msg + '\n');
});
// @actions/exec // @actions/exec
getExecOutputSpy = exec.getExecOutput as jest.Mock; getExecOutputSpy = jest.spyOn(exec, 'getExecOutput');
getExecOutputSpy.mockImplementation(() => 'v16.15.0'); getExecOutputSpy.mockImplementation(() => 'v16.15.0');
}); });
@@ -285,7 +156,7 @@ describe('setup-node', () => {
async (versionSpec, platform, expectedVersion, expectedLts) => { async (versionSpec, platform, expectedVersion, expectedLts) => {
os.platform = platform; os.platform = platform;
os.arch = 'x64'; os.arch = 'x64';
const versions: IToolRelease[] | null = await tc.getManifestFromRepo( const versions: tc.IToolRelease[] | null = await tc.getManifestFromRepo(
'actions', 'actions',
'node-versions', 'node-versions',
'mocktoken' 'mocktoken'
@@ -316,7 +187,7 @@ describe('setup-node', () => {
it('finds version in cache with stable not supplied', async () => { it('finds version in cache with stable not supplied', async () => {
inputs['node-version'] = '12'; inputs['node-version'] = '12';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const toolPath = path.normalize('/cache/node/12.16.1/x64'); const toolPath = path.normalize('/cache/node/12.16.1/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
@@ -328,14 +199,14 @@ describe('setup-node', () => {
it('finds version in cache and adds it to the path', async () => { it('finds version in cache and adds it to the path', async () => {
inputs['node-version'] = '12'; inputs['node-version'] = '12';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const toolPath = path.normalize('/cache/node/12.16.1/x64'); const toolPath = path.normalize('/cache/node/12.16.1/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
await main.run(); await main.run();
const expPath = path.join(toolPath, 'bin'); const expPath = path.join(toolPath, 'bin');
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('handles unhandled find error and reports error', async () => { it('handles unhandled find error and reports error', async () => {
@@ -348,7 +219,7 @@ describe('setup-node', () => {
await main.run(); await main.run();
expect(setFailedSpy).toHaveBeenCalledWith(errMsg); expect(cnSpy).toHaveBeenCalledWith('::error::' + errMsg + osm.EOL);
}); });
//-------------------------------------------------- //--------------------------------------------------
@@ -376,7 +247,7 @@ describe('setup-node', () => {
const toolPath = path.normalize('/cache/node/12.16.2/x64'); const toolPath = path.normalize('/cache/node/12.16.2/x64');
exSpy.mockImplementation(async () => '/some/other/temp/path'); exSpy.mockImplementation(async () => '/some/other/temp/path');
cacheSpy.mockImplementation(async () => toolPath); cacheSpy.mockImplementation(async () => toolPath);
whichSpy.mockImplementation((cmd: any) => { whichSpy.mockImplementation(cmd => {
return `some/${cmd}/path`; return `some/${cmd}/path`;
}); });
@@ -407,7 +278,7 @@ describe('setup-node', () => {
expect(logSpy).toHaveBeenCalledWith( expect(logSpy).toHaveBeenCalledWith(
`Attempting to download ${versionSpec}...` `Attempting to download ${versionSpec}...`
); );
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('falls back to a version from node dist from mirror', async () => { it('falls back to a version from node dist from mirror', async () => {
@@ -443,7 +314,7 @@ describe('setup-node', () => {
); );
expect(dlSpy).toHaveBeenCalled(); expect(dlSpy).toHaveBeenCalled();
expect(exSpy).toHaveBeenCalled(); expect(exSpy).toHaveBeenCalled();
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('falls back to a version from node dist', async () => { it('falls back to a version from node dist', async () => {
@@ -477,7 +348,7 @@ describe('setup-node', () => {
); );
expect(dlSpy).toHaveBeenCalled(); expect(dlSpy).toHaveBeenCalled();
expect(exSpy).toHaveBeenCalled(); expect(exSpy).toHaveBeenCalled();
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('does not find a version that does not exist', async () => { it('does not find a version that does not exist', async () => {
@@ -496,8 +367,8 @@ describe('setup-node', () => {
expect(logSpy).toHaveBeenCalledWith( expect(logSpy).toHaveBeenCalledWith(
`Attempting to download ${versionSpec}...` `Attempting to download ${versionSpec}...`
); );
expect(setFailedSpy).toHaveBeenCalledWith( expect(cnSpy).toHaveBeenCalledWith(
`Unable to find Node version '${versionSpec}' for platform ${os.platform} and architecture ${os.arch}.` `::error::Unable to find Node version '${versionSpec}' for platform ${os.platform} and architecture ${os.arch}.${osm.EOL}`
); );
}); });
@@ -519,7 +390,7 @@ describe('setup-node', () => {
}); });
await main.run(); await main.run();
expect(setFailedSpy).toHaveBeenCalledWith(errMsg); expect(cnSpy).toHaveBeenCalledWith(`::error::${errMsg}${osm.EOL}`);
}); });
it('reports when download failed but version exists', async () => { it('reports when download failed but version exists', async () => {
@@ -712,7 +583,7 @@ describe('setup-node', () => {
expect(logSpy).toHaveBeenCalledWith( expect(logSpy).toHaveBeenCalledWith(
`Attempting to download ${versionSpec}...` `Attempting to download ${versionSpec}...`
); );
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('fallback to dist if manifest is not available', async () => { it('fallback to dist if manifest is not available', async () => {
@@ -755,7 +626,7 @@ describe('setup-node', () => {
expect(logSpy).toHaveBeenCalledWith( expect(logSpy).toHaveBeenCalledWith(
`Attempting to download ${versionSpec}...` `Attempting to download ${versionSpec}...`
); );
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
}); });
@@ -797,7 +668,9 @@ describe('setup-node', () => {
`Found LTS release '${expectedVersion}' for Node version 'lts/${lts}'` `Found LTS release '${expectedVersion}' for Node version 'lts/${lts}'`
); );
expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`); expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`);
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin')); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
);
} }
); );
@@ -855,7 +728,9 @@ describe('setup-node', () => {
); );
expect(logSpy).toHaveBeenCalledWith('Extracting ...'); expect(logSpy).toHaveBeenCalledWith('Extracting ...');
expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...'); expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...');
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin')); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
);
} }
); );
@@ -875,8 +750,8 @@ describe('setup-node', () => {
expect(dbgSpy).toHaveBeenCalledWith( expect(dbgSpy).toHaveBeenCalledWith(
'Getting manifest from actions/node-versions@main' 'Getting manifest from actions/node-versions@main'
); );
expect(setFailedSpy).toHaveBeenCalledWith( expect(cnSpy).toHaveBeenCalledWith(
`Unable to parse LTS alias for Node version 'lts/'` `::error::Unable to parse LTS alias for Node version 'lts/'${osm.EOL}`
); );
}); });
@@ -899,8 +774,8 @@ describe('setup-node', () => {
expect(dbgSpy).toHaveBeenCalledWith( expect(dbgSpy).toHaveBeenCalledWith(
`LTS alias 'unknown' for Node version 'lts/unknown'` `LTS alias 'unknown' for Node version 'lts/unknown'`
); );
expect(setFailedSpy).toHaveBeenCalledWith( expect(cnSpy).toHaveBeenCalledWith(
`Unable to find LTS release 'unknown' for Node version 'lts/unknown'.` `::error::Unable to find LTS release 'unknown' for Node version 'lts/unknown'.${osm.EOL}`
); );
}); });
@@ -924,7 +799,9 @@ describe('setup-node', () => {
expect(dbgSpy).toHaveBeenCalledWith( expect(dbgSpy).toHaveBeenCalledWith(
'Getting manifest from actions/node-versions@main' 'Getting manifest from actions/node-versions@main'
); );
expect(setFailedSpy).toHaveBeenCalledWith('Unable to download manifest'); expect(cnSpy).toHaveBeenCalledWith(
`::error::Unable to download manifest${osm.EOL}`
);
}); });
}); });
@@ -994,6 +871,7 @@ describe('setup-node', () => {
darwin: 'darwin', darwin: 'darwin',
win32: 'win' win32: 'win'
}[os.platform]; }[os.platform];
inputs['node-version'] = version; inputs['node-version'] = version;
inputs['architecture'] = arch; inputs['architecture'] = arch;
inputs['token'] = 'faketoken'; inputs['token'] = 'faketoken';

View File

@@ -1,5 +1,4 @@
import {describe, it, expect} from '@jest/globals'; import tscMatcher from '../.github/tsc.json';
import tscMatcher from '../.github/tsc.json' with {type: 'json'};
describe('problem matcher tests', () => { describe('problem matcher tests', () => {
it('tsc: matches TypeScript "pretty" error message', () => { it('tsc: matches TypeScript "pretty" error message', () => {

View File

@@ -1,152 +1,46 @@
import { import * as core from '@actions/core';
jest, import * as io from '@actions/io';
describe, import * as tc from '@actions/tool-cache';
it, import * as httpm from '@actions/http-client';
expect, import * as exec from '@actions/exec';
beforeEach, import * as cache from '@actions/cache';
afterEach,
afterAll
} from '@jest/globals';
import {fileURLToPath} from 'url';
import fs from 'fs'; import fs from 'fs';
import cp from 'child_process'; import cp from 'child_process';
import osm from 'os'; import osm from 'os';
import path from 'path'; import path from 'path';
import * as main from '../src/main';
import * as auth from '../src/authutil';
import {INodeVersion} from '../src/distributions/base-models';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); import nodeTestDist from './data/node-dist-index.json';
import nodeTestDistNightly from './data/node-nightly-index.json';
// Mock @actions modules before importing anything that depends on them import nodeTestDistRc from './data/node-rc-index.json';
jest.unstable_mockModule('@actions/core', () => ({ import nodeV8CanaryTestDist from './data/v8-canary-dist-index.json';
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((p: string) => p),
toWin32Path: jest.fn((p: string) => p),
toPosixPath: jest.fn((p: string) => p)
}));
jest.unstable_mockModule('@actions/io', () => ({
which: jest.fn(),
mkdirP: jest.fn(),
rmRF: jest.fn(),
mv: jest.fn(),
cp: jest.fn()
}));
jest.unstable_mockModule('@actions/tool-cache', () => ({
find: jest.fn(),
findAllVersions: jest.fn(),
downloadTool: jest.fn(),
extractTar: jest.fn(),
extractZip: jest.fn(),
extractXar: jest.fn(),
extract7z: jest.fn(),
cacheDir: jest.fn(),
cacheFile: jest.fn(),
getManifestFromRepo: jest.fn(),
findFromManifest: jest.fn(),
HTTPError: class HTTPError extends Error {
readonly httpStatusCode: number;
constructor(httpStatusCode?: number) {
super(`Unexpected HTTP response: ${httpStatusCode}`);
this.httpStatusCode = httpStatusCode ?? 0;
}
}
}));
const _mockGetJson = jest.fn();
jest.unstable_mockModule('@actions/http-client', () => ({
HttpClient: jest.fn().mockImplementation(() => ({
getJson: _mockGetJson
}))
}));
jest.unstable_mockModule('@actions/exec', () => ({
exec: jest.fn(),
getExecOutput: jest.fn()
}));
jest.unstable_mockModule('@actions/cache', () => ({
saveCache: jest.fn(),
restoreCache: jest.fn(),
isFeatureAvailable: jest.fn()
}));
const realAuth = await import('../src/authutil.js');
jest.unstable_mockModule('../src/authutil.js', () => ({
...realAuth,
configAuthentication: jest.fn()
}));
// Dynamic imports after mocking
const core = await import('@actions/core');
const io = await import('@actions/io');
const tc = await import('@actions/tool-cache');
const httpm = await import('@actions/http-client');
const exec = await import('@actions/exec');
const cache = await import('@actions/cache');
const main = await import('../src/main.js');
const auth = await import('../src/authutil.js');
const {default: nodeTestDist} = await import('./data/node-dist-index.json', {
with: {type: 'json'}
});
const {default: nodeTestDistNightly} = await import(
'./data/node-nightly-index.json',
{with: {type: 'json'}}
);
const {default: nodeTestDistRc} = await import('./data/node-rc-index.json', {
with: {type: 'json'}
});
const {default: nodeV8CanaryTestDist} = await import(
'./data/v8-canary-dist-index.json',
{with: {type: 'json'}}
);
import type {INodeVersion} from '../src/distributions/base-models.js';
describe('setup-node', () => { describe('setup-node', () => {
let inputs = {} as any; let inputs = {} as any;
let os = {} as any; let os = {} as any;
let inSpy: jest.Mock; let inSpy: jest.SpyInstance;
let findSpy: jest.Mock; let findSpy: jest.SpyInstance;
let findAllVersionsSpy: jest.Mock; let findAllVersionsSpy: jest.SpyInstance;
let cnSpy: jest.SpiedFunction<typeof process.stdout.write>; let cnSpy: jest.SpyInstance;
let logSpy: jest.Mock; let logSpy: jest.SpyInstance;
let warningSpy: jest.Mock; let warningSpy: jest.SpyInstance;
let addPathSpy: jest.Mock; let platSpy: jest.SpyInstance;
let setFailedSpy: jest.Mock; let archSpy: jest.SpyInstance;
let platSpy: jest.SpiedFunction<typeof osm.platform>; let dlSpy: jest.SpyInstance;
let archSpy: jest.SpiedFunction<typeof osm.arch>; let exSpy: jest.SpyInstance;
let dlSpy: jest.Mock; let cacheSpy: jest.SpyInstance;
let exSpy: jest.Mock; let dbgSpy: jest.SpyInstance;
let cacheSpy: jest.Mock; let whichSpy: jest.SpyInstance;
let dbgSpy: jest.Mock; let existsSpy: jest.SpyInstance;
let whichSpy: jest.Mock; let mkdirpSpy: jest.SpyInstance;
let existsSpy: jest.SpiedFunction<typeof fs.existsSync>; let execSpy: jest.SpyInstance;
let mkdirpSpy: jest.Mock; let authSpy: jest.SpyInstance;
let execSpy: jest.SpiedFunction<typeof cp.execSync>; let isCacheActionAvailable: jest.SpyInstance;
let authSpy: jest.Mock; let getExecOutputSpy: jest.SpyInstance;
let isCacheActionAvailable: jest.Mock; let getJsonSpy: jest.SpyInstance;
let getExecOutputSpy: jest.Mock;
let getJsonSpy: jest.Mock;
beforeEach(() => { beforeEach(() => {
// @actions/core // @actions/core
@@ -154,8 +48,8 @@ describe('setup-node', () => {
process.env['GITHUB_PATH'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out process.env['GITHUB_PATH'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out
process.env['GITHUB_OUTPUT'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out process.env['GITHUB_OUTPUT'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out
inputs = {}; inputs = {};
inSpy = core.getInput as jest.Mock; inSpy = jest.spyOn(core, 'getInput');
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
// node // node
os = {}; os = {};
@@ -166,33 +60,30 @@ describe('setup-node', () => {
execSpy = jest.spyOn(cp, 'execSync'); execSpy = jest.spyOn(cp, 'execSync');
// @actions/tool-cache // @actions/tool-cache
findSpy = tc.find as jest.Mock; findSpy = jest.spyOn(tc, 'find');
findAllVersionsSpy = tc.findAllVersions as jest.Mock; findAllVersionsSpy = jest.spyOn(tc, 'findAllVersions');
dlSpy = tc.downloadTool as jest.Mock; dlSpy = jest.spyOn(tc, 'downloadTool');
exSpy = tc.extractTar as jest.Mock; exSpy = jest.spyOn(tc, 'extractTar');
cacheSpy = tc.cacheDir as jest.Mock; cacheSpy = jest.spyOn(tc, 'cacheDir');
// getDistSpy = jest.spyOn(im, 'getVersionsFromDist') as jest.Mock; // getDistSpy = jest.spyOn(im, 'getVersionsFromDist');
// http-client // http-client
getJsonSpy = _mockGetJson; getJsonSpy = jest.spyOn(httpm.HttpClient.prototype, 'getJson');
(httpm.HttpClient as jest.Mock).mockImplementation(() => ({
getJson: _mockGetJson
}));
// io // io
whichSpy = io.which as jest.Mock; whichSpy = jest.spyOn(io, 'which');
existsSpy = jest.spyOn(fs, 'existsSync'); existsSpy = jest.spyOn(fs, 'existsSync');
mkdirpSpy = io.mkdirP as jest.Mock; mkdirpSpy = jest.spyOn(io, 'mkdirP');
// @actions/tool-cache // @actions/tool-cache
isCacheActionAvailable = cache.isFeatureAvailable as jest.Mock; isCacheActionAvailable = jest.spyOn(cache, 'isFeatureAvailable');
isCacheActionAvailable.mockImplementation(() => false); isCacheActionAvailable.mockImplementation(() => false);
// disable authentication portion for installer tests // disable authentication portion for installer tests
authSpy = auth.configAuthentication as jest.Mock; authSpy = jest.spyOn(auth, 'configAuthentication');
authSpy.mockImplementation(() => {}); authSpy.mockImplementation(() => {});
getJsonSpy.mockImplementation((url: any) => { getJsonSpy.mockImplementation(url => {
let res: any; let res: any;
if (url.includes('/rc')) { if (url.includes('/rc')) {
res = <INodeVersion[]>nodeTestDistRc; res = <INodeVersion[]>nodeTestDistRc;
@@ -207,18 +98,28 @@ describe('setup-node', () => {
// writes // writes
cnSpy = jest.spyOn(process.stdout, 'write'); cnSpy = jest.spyOn(process.stdout, 'write');
logSpy = core.info as jest.Mock; logSpy = jest.spyOn(core, 'info');
dbgSpy = core.debug as jest.Mock; dbgSpy = jest.spyOn(core, 'debug');
warningSpy = core.warning as jest.Mock; warningSpy = jest.spyOn(core, 'warning');
addPathSpy = core.addPath as jest.Mock; cnSpy.mockImplementation(line => {
setFailedSpy = core.setFailed as jest.Mock; // uncomment to debug
cnSpy.mockImplementation(() => true); // process.stderr.write('write:' + line + '\n');
logSpy.mockImplementation(() => {}); });
dbgSpy.mockImplementation(() => {}); logSpy.mockImplementation(line => {
warningSpy.mockImplementation(() => {}); // uncomment to debug
// process.stderr.write('log:' + line + '\n');
});
dbgSpy.mockImplementation(msg => {
// uncomment to see debug output
// process.stderr.write(msg + '\n');
});
warningSpy.mockImplementation(msg => {
// uncomment to debug
// process.stderr.write('log:' + msg + '\n');
});
// @actions/exec // @actions/exec
getExecOutputSpy = exec.getExecOutput as jest.Mock; getExecOutputSpy = jest.spyOn(exec, 'getExecOutput');
getExecOutputSpy.mockImplementation(() => 'v16.15.0-rc.1'); getExecOutputSpy.mockImplementation(() => 'v16.15.0-rc.1');
}); });
@@ -251,7 +152,7 @@ describe('setup-node', () => {
it('finds version in cache with stable not supplied', async () => { it('finds version in cache with stable not supplied', async () => {
inputs['node-version'] = '12.0.0-rc.1'; inputs['node-version'] = '12.0.0-rc.1';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64'); const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
@@ -263,14 +164,14 @@ describe('setup-node', () => {
it('finds version in cache and adds it to the path', async () => { it('finds version in cache and adds it to the path', async () => {
inputs['node-version'] = '12.0.0-rc.1'; inputs['node-version'] = '12.0.0-rc.1';
inSpy.mockImplementation((name: any) => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64'); const toolPath = path.normalize('/cache/node/12.0.0-rc.1/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
await main.run(); await main.run();
const expPath = path.join(toolPath, 'bin'); const expPath = path.join(toolPath, 'bin');
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('handles unhandled find error and reports error', async () => { it('handles unhandled find error and reports error', async () => {
@@ -283,7 +184,7 @@ describe('setup-node', () => {
await main.run(); await main.run();
expect(setFailedSpy).toHaveBeenCalledWith(errMsg); expect(cnSpy).toHaveBeenCalledWith('::error::' + errMsg + osm.EOL);
}); });
it('falls back to a version from node dist', async () => { it('falls back to a version from node dist', async () => {
@@ -311,7 +212,7 @@ describe('setup-node', () => {
expect(exSpy).toHaveBeenCalled(); expect(exSpy).toHaveBeenCalled();
expect(logSpy).toHaveBeenCalledWith('Extracting ...'); expect(logSpy).toHaveBeenCalledWith('Extracting ...');
expect(logSpy).toHaveBeenCalledWith('Done'); expect(logSpy).toHaveBeenCalledWith('Done');
expect(addPathSpy).toHaveBeenCalledWith(expPath); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('does not find a version that does not exist', async () => { it('does not find a version that does not exist', async () => {
@@ -324,8 +225,8 @@ describe('setup-node', () => {
findSpy.mockImplementation(() => ''); findSpy.mockImplementation(() => '');
await main.run(); await main.run();
expect(setFailedSpy).toHaveBeenCalledWith( expect(cnSpy).toHaveBeenCalledWith(
`Unable to find Node version '${versionSpec}' for platform ${os.platform} and architecture ${os.arch}.` `::error::Unable to find Node version '${versionSpec}' for platform ${os.platform} and architecture ${os.arch}.${osm.EOL}`
); );
}); });
@@ -346,7 +247,7 @@ describe('setup-node', () => {
}); });
await main.run(); await main.run();
expect(setFailedSpy).toHaveBeenCalledWith(errMsg); expect(cnSpy).toHaveBeenCalledWith(`::error::${errMsg}${osm.EOL}`);
}); });
it('acquires specified architecture of node', async () => { it('acquires specified architecture of node', async () => {
@@ -362,6 +263,7 @@ describe('setup-node', () => {
darwin: 'darwin', darwin: 'darwin',
win32: 'win' win32: 'win'
}[os.platform]; }[os.platform];
inputs['node-version'] = version; inputs['node-version'] = version;
inputs['architecture'] = arch; inputs['architecture'] = arch;
inputs['token'] = 'faketoken'; inputs['token'] = 'faketoken';
@@ -432,7 +334,9 @@ describe('setup-node', () => {
// assert // assert
expect(logSpy).toHaveBeenCalledWith('Extracting ...'); expect(logSpy).toHaveBeenCalledWith('Extracting ...');
expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...'); expect(logSpy).toHaveBeenCalledWith('Adding to the cache ...');
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin')); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
);
} }
); );
@@ -466,7 +370,9 @@ describe('setup-node', () => {
// assert // assert
expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`); expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`);
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin')); expect(cnSpy).toHaveBeenCalledWith(
`::add-path::${path.join(toolPath, 'bin')}${osm.EOL}`
);
} }
); );
@@ -485,8 +391,8 @@ describe('setup-node', () => {
await main.run(); await main.run();
// assert // assert
expect(setFailedSpy).toHaveBeenCalledWith( expect(cnSpy).toHaveBeenCalledWith(
`Unable to find Node version '${versionSpec}' for platform ${os.platform} and architecture ${os.arch}.` `::error::Unable to find Node version '${versionSpec}' for platform ${os.platform} and architecture ${os.arch}.${osm.EOL}`
); );
}); });
}); });

96483
dist/cache-save/index.js vendored

File diff suppressed because one or more lines are too long

View File

@@ -1,3 +0,0 @@
{
"type": "module"
}

107940
dist/setup/index.js vendored

File diff suppressed because one or more lines are too long

View File

@@ -1,3 +0,0 @@
{
"type": "module"
}

11
jest.config.js Normal file
View File

@@ -0,0 +1,11 @@
module.exports = {
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
testEnvironment: 'node',
testMatch: ['**/*.test.ts'],
testRunner: 'jest-circus/runner',
transform: {
'^.+\\.ts$': 'ts-jest'
},
verbose: true
}

View File

@@ -1,24 +0,0 @@
export default {
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
roots: ['<rootDir>'],
testEnvironment: 'node',
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.ts$': [
'ts-jest',
{
useESM: true,
diagnostics: {
ignoreCodes: [151002]
}
}
]
},
extensionsToTreatAsEsm: ['.ts'],
transformIgnorePatterns: ['node_modules/(?!(@actions)/)'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1'
},
verbose: true
}

4793
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,6 @@
{ {
"name": "setup-node", "name": "setup-node",
"version": "7.0.0", "version": "6.5.0",
"type": "module",
"private": true, "private": true,
"description": "setup node action", "description": "setup node action",
"main": "lib/setup-node.js", "main": "lib/setup-node.js",
@@ -10,11 +9,11 @@
}, },
"scripts": { "scripts": {
"build": "ncc build -o dist/setup src/setup-node.ts && ncc build -o dist/cache-save src/cache-save.ts", "build": "ncc build -o dist/setup src/setup-node.ts && ncc build -o dist/cache-save src/cache-save.ts",
"format": "prettier --no-error-on-unmatched-pattern --write \"**/*.{ts,yml,yaml}\"", "format": "prettier --no-error-on-unmatched-pattern --config ./.prettierrc.js --write \"**/*.{ts,yml,yaml}\"",
"format-check": "prettier --no-error-on-unmatched-pattern --check \"**/*.{ts,yml,yaml}\"", "format-check": "prettier --no-error-on-unmatched-pattern --config ./.prettierrc.js --check \"**/*.{ts,yml,yaml}\"",
"lint": "eslint \"**/*.ts\"", "lint": "eslint --config ./.eslintrc.js \"**/*.ts\"",
"lint:fix": "eslint \"**/*.ts\" --fix", "lint:fix": "eslint --config ./.eslintrc.js \"**/*.ts\" --fix",
"test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --runInBand --coverage", "test": "jest --coverage",
"pre-checkin": "npm run format && npm run lint:fix && npm run build && npm test" "pre-checkin": "npm run format && npm run lint:fix && npm run build && npm test"
}, },
"repository": { "repository": {
@@ -29,33 +28,36 @@
"author": "GitHub", "author": "GitHub",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/cache": "^6.1.0", "@actions/cache": "^5.1.0",
"@actions/core": "^3.0.1", "@actions/core": "^2.0.3",
"@actions/exec": "^3.0.0", "@actions/exec": "^2.0.0",
"@actions/github": "^9.1.1", "@actions/github": "^6.0.1",
"@actions/glob": "^0.7.0", "@actions/glob": "^0.5.1",
"@actions/http-client": "^4.0.1", "@actions/http-client": "^3.0.2",
"@actions/io": "^3.0.2", "@actions/io": "^2.0.0",
"@actions/tool-cache": "^4.0.0", "@actions/tool-cache": "^3.0.1",
"semver": "^7.8.5" "semver": "^7.6.3"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^10.0.1", "@types/jest": "^29.5.14",
"@jest/globals": "^30.4.1", "@types/node": "^24.1.0",
"@types/node": "^26.0.0", "@types/semver": "^7.5.8",
"@types/semver": "^7.7.0", "@typescript-eslint/eslint-plugin": "^5.54.0",
"@typescript-eslint/eslint-plugin": "^8.62.0", "@typescript-eslint/parser": "^5.54.0",
"@typescript-eslint/parser": "^8.62.0", "@vercel/ncc": "^0.38.3",
"@vercel/ncc": "^0.44.0", "eslint": "^8.57.0",
"eslint": "^10.5.0", "eslint-config-prettier": "^8.6.0",
"eslint-config-prettier": "^10.1.8", "eslint-plugin-jest": "^27.9.0",
"eslint-plugin-jest": "^29.15.2", "eslint-plugin-node": "^11.1.0",
"eslint-plugin-n": "^18.1.0", "jest": "^29.7.0",
"globals": "^17.7.0", "jest-circus": "^29.7.0",
"jest": "^30.4.2", "jest-each": "^29.7.0",
"jest-each": "^30.4.1", "prettier": "^3.6.2",
"prettier": "^3.8.4", "ts-jest": "^29.4.1",
"ts-jest": "^29.4.11", "typescript": "^5.4.2"
"typescript": "^6.0.3" },
"overrides": {
"undici": "^6.24.1",
"fast-xml-parser": "^5.9.2"
} }
} }

View File

@@ -5,13 +5,13 @@ import path from 'path';
import fs from 'fs'; import fs from 'fs';
import os from 'os'; import os from 'os';
import {State} from './constants.js'; import {State} from './constants';
import { import {
getCacheDirectories, getCacheDirectories,
getPackageManagerInfo, getPackageManagerInfo,
repoHasYarnBerryManagedDependencies, repoHasYarnBerryManagedDependencies,
PackageManagerInfo PackageManagerInfo
} from './cache-utils.js'; } from './cache-utils';
export const restoreCache = async ( export const restoreCache = async (
packageManager: string, packageManager: string,

View File

@@ -1,8 +1,8 @@
import * as core from '@actions/core'; import * as core from '@actions/core';
import * as cache from '@actions/cache'; import * as cache from '@actions/cache';
import {State} from './constants.js'; import {State} from './constants';
import {getPackageManagerInfo} from './cache-utils.js'; import {getPackageManagerInfo} from './cache-utils';
// Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in // Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in
// @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to // @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to

View File

@@ -4,7 +4,7 @@ import * as cache from '@actions/cache';
import * as glob from '@actions/glob'; import * as glob from '@actions/glob';
import path from 'path'; import path from 'path';
import fs from 'fs'; import fs from 'fs';
import {unique} from './util.js'; import {unique} from './util';
export interface PackageManagerInfo { export interface PackageManagerInfo {
name: string; name: string;
@@ -91,7 +91,7 @@ export const getCommandOutputNotEmpty = async (
error: string, error: string,
cwd?: string cwd?: string
): Promise<string> => { ): Promise<string> => {
const stdOut = await getCommandOutput(toolCommand, cwd); const stdOut = getCommandOutput(toolCommand, cwd);
if (!stdOut) { if (!stdOut) {
throw new Error(error); throw new Error(error);
} }

View File

@@ -2,8 +2,8 @@ import * as tc from '@actions/tool-cache';
import semver from 'semver'; import semver from 'semver';
import BaseDistribution from './base-distribution.js'; import BaseDistribution from './base-distribution';
import {NodeInputs} from './base-models.js'; import {NodeInputs} from './base-models';
export default abstract class BasePrereleaseNodejs extends BaseDistribution { export default abstract class BasePrereleaseNodejs extends BaseDistribution {
protected abstract distribution: string; protected abstract distribution: string;

View File

@@ -9,8 +9,8 @@ import * as assert from 'assert';
import * as path from 'path'; import * as path from 'path';
import os from 'os'; import os from 'os';
import fs from 'fs'; import fs from 'fs';
import {fileURLToPath} from 'url';
import {NodeInputs, INodeVersion, INodeVersionInfo} from './base-models.js'; import {NodeInputs, INodeVersion, INodeVersionInfo} from './base-models';
export default abstract class BaseDistribution { export default abstract class BaseDistribution {
protected httpClient: hc.HttpClient; protected httpClient: hc.HttpClient;
@@ -26,8 +26,9 @@ export default abstract class BaseDistribution {
protected abstract getDistributionUrl(mirror: string): string; protected abstract getDistributionUrl(mirror: string): string;
public async setupNodeJs() { public async setupNodeJs() {
let nodeJsVersions: INodeVersion[] | undefined;
if (this.nodeInfo.checkLatest) { if (this.nodeInfo.checkLatest) {
const evaluatedVersion = await this.findVersionInDist(undefined); const evaluatedVersion = await this.findVersionInDist(nodeJsVersions);
this.nodeInfo.versionSpec = evaluatedVersion; this.nodeInfo.versionSpec = evaluatedVersion;
} }
@@ -35,7 +36,7 @@ export default abstract class BaseDistribution {
if (toolPath) { if (toolPath) {
core.info(`Found in cache @ ${toolPath}`); core.info(`Found in cache @ ${toolPath}`);
} else { } else {
const evaluatedVersion = await this.findVersionInDist(undefined); const evaluatedVersion = await this.findVersionInDist(nodeJsVersions);
const toolName = this.getNodejsDistInfo(evaluatedVersion); const toolName = this.getNodejsDistInfo(evaluatedVersion);
toolPath = await this.downloadNodejs(toolName); toolPath = await this.downloadNodejs(toolName);
} }
@@ -167,14 +168,12 @@ export default abstract class BaseDistribution {
return toolPath; return toolPath;
} }
protected validRange(versionSpec: string): { protected validRange(versionSpec: string) {
range: string; let options: semver.RangeOptions | undefined;
options: semver.RangeOptions | undefined;
} {
const c = semver.clean(versionSpec) || ''; const c = semver.clean(versionSpec) || '';
const valid = semver.valid(c) ?? versionSpec; const valid = semver.valid(c) ?? versionSpec;
return {range: valid, options: undefined}; return {range: valid, options};
} }
protected async acquireWindowsNodeFromFallbackLocation( protected async acquireWindowsNodeFromFallbackLocation(
@@ -260,12 +259,7 @@ export default abstract class BaseDistribution {
fs.renameSync(downloadPath, renamedArchive); fs.renameSync(downloadPath, renamedArchive);
extPath = await tc.extractZip(renamedArchive); extPath = await tc.extractZip(renamedArchive);
} else { } else {
const _7zPath = path.join( const _7zPath = path.join(__dirname, '../..', 'externals', '7zr.exe');
path.dirname(fileURLToPath(import.meta.url)),
'../..',
'externals',
'7zr.exe'
);
extPath = await tc.extract7z(downloadPath, undefined, _7zPath); extPath = await tc.extract7z(downloadPath, undefined, _7zPath);
} }
// 7z extracts to folder matching file name // 7z extracts to folder matching file name

View File

@@ -1,9 +1,9 @@
import BaseDistribution from './base-distribution.js'; import BaseDistribution from './base-distribution';
import {NodeInputs} from './base-models.js'; import {NodeInputs} from './base-models';
import NightlyNodejs from './nightly/nightly_builds.js'; import NightlyNodejs from './nightly/nightly_builds';
import OfficialBuilds from './official_builds/official_builds.js'; import OfficialBuilds from './official_builds/official_builds';
import RcBuild from './rc/rc_builds.js'; import RcBuild from './rc/rc_builds';
import CanaryBuild from './v8-canary/canary_builds.js'; import CanaryBuild from './v8-canary/canary_builds';
enum Distributions { enum Distributions {
DEFAULT = '', DEFAULT = '',

View File

@@ -1,5 +1,5 @@
import BasePrereleaseNodejs from '../base-distribution-prerelease.js'; import BasePrereleaseNodejs from '../base-distribution-prerelease';
import {NodeInputs} from '../base-models.js'; import {NodeInputs} from '../base-models';
export default class NightlyNodejs extends BasePrereleaseNodejs { export default class NightlyNodejs extends BasePrereleaseNodejs {
protected distribution = 'nightly'; protected distribution = 'nightly';

View File

@@ -2,8 +2,8 @@ import * as core from '@actions/core';
import * as tc from '@actions/tool-cache'; import * as tc from '@actions/tool-cache';
import path from 'path'; import path from 'path';
import BaseDistribution from '../base-distribution.js'; import BaseDistribution from '../base-distribution';
import {NodeInputs, INodeVersion, INodeVersionInfo} from '../base-models.js'; import {NodeInputs, INodeVersion, INodeVersionInfo} from '../base-models';
interface INodeRelease extends tc.IToolRelease { interface INodeRelease extends tc.IToolRelease {
lts?: string; lts?: string;

View File

@@ -1,5 +1,5 @@
import BaseDistribution from '../base-distribution.js'; import BaseDistribution from '../base-distribution';
import {NodeInputs} from '../base-models.js'; import {NodeInputs} from '../base-models';
export default class RcBuild extends BaseDistribution { export default class RcBuild extends BaseDistribution {
constructor(nodeInfo: NodeInputs) { constructor(nodeInfo: NodeInputs) {

View File

@@ -1,5 +1,5 @@
import BasePrereleaseNodejs from '../base-distribution-prerelease.js'; import BasePrereleaseNodejs from '../base-distribution-prerelease';
import {NodeInputs} from '../base-models.js'; import {NodeInputs} from '../base-models';
export default class CanaryBuild extends BasePrereleaseNodejs { export default class CanaryBuild extends BasePrereleaseNodejs {
protected distribution = 'v8-canary'; protected distribution = 'v8-canary';

View File

@@ -2,15 +2,14 @@ import * as core from '@actions/core';
import os from 'os'; import os from 'os';
import fs from 'fs'; import fs from 'fs';
import {fileURLToPath} from 'url';
import * as auth from './authutil.js'; import * as auth from './authutil';
import * as path from 'path'; import * as path from 'path';
import {restoreCache} from './cache-restore.js'; import {restoreCache} from './cache-restore';
import {isCacheFeatureAvailable} from './cache-utils.js'; import {isCacheFeatureAvailable} from './cache-utils';
import {getNodejsDistribution} from './distributions/installer-factory.js'; import {getNodejsDistribution} from './distributions/installer-factory';
import {getNodeVersionFromFile, printEnvDetailsAndSetOutput} from './util.js'; import {getNodeVersionFromFile, printEnvDetailsAndSetOutput} from './util';
import {State} from './constants.js'; import {State} from './constants';
export async function run() { export async function run() {
try { try {
@@ -88,11 +87,7 @@ export async function run() {
} }
} }
const matchersPath = path.join( const matchersPath = path.join(__dirname, '../..', '.github');
path.dirname(fileURLToPath(import.meta.url)),
'../..',
'.github'
);
core.info(`##[add-matcher]${path.join(matchersPath, 'tsc.json')}`); core.info(`##[add-matcher]${path.join(matchersPath, 'tsc.json')}`);
core.info( core.info(
`##[add-matcher]${path.join(matchersPath, 'eslint-stylish.json')}` `##[add-matcher]${path.join(matchersPath, 'eslint-stylish.json')}`

View File

@@ -1,3 +1,3 @@
import {run} from './main.js'; import {run} from './main';
run(); run();

View File

@@ -105,7 +105,7 @@ async function getToolVersion(tool: string, options: string[]) {
} }
return stdout.trim(); return stdout.trim();
} catch { } catch (err) {
return ''; return '';
} }
} }

View File

@@ -1,7 +1,7 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2022", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "target": "ES2022", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "NodeNext", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"outDir": "./lib", /* Redirect output structure to the directory. */ "outDir": "./lib", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"sourceMap": true, "sourceMap": true,
@@ -10,5 +10,5 @@
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"resolveJsonModule": true, /* Allows importing modules with a '.json' extension, which is a common practice in node projects. */ "resolveJsonModule": true, /* Allows importing modules with a '.json' extension, which is a common practice in node projects. */
}, },
"exclude": ["__tests__", "lib", "node_modules", "jest.config.ts"] "exclude": ["__tests__", "lib", "node_modules"]
} }