Compare commits

..

1 Commits
main ... v3.6.0

Author SHA1 Message Date
Priya Gupta
b4b75a2513
v3 - upgrade @actions/cache (#579)
* Upgrade-actions/cache for v3

* Upgrade actions/upload-artifact from v3 to v4

* audit fix

* Replaced macos-latest with macos-13

* fix check failures
2025-04-13 22:13:57 -05:00
85 changed files with 64208 additions and 87224 deletions

View File

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

View File

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

2
.gitattributes vendored
View File

@ -1,2 +1,2 @@
* text=auto eol=lf * text=auto
.licenses/** -diff linguist-generated=true .licenses/** -diff linguist-generated=true

View File

@ -1 +1 @@
blank_issues_enabled: false blank_issues_enabled: false

View File

@ -1,22 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
# Enable version updates for npm
- package-ecosystem: 'npm'
# Look for `package.json` and `lock` files in the `root` directory
directory: '/'
# Check the npm registry for updates every day (weekdays)
schedule:
interval: 'weekly'
# Enable version updates for GitHub Actions
- package-ecosystem: 'github-actions'
# Workflow files stored in the default location of `.github/workflows`
# You don't need to specify `/.github/workflows` for `directory`. You can use `directory: "/"`.
directory: '/'
schedule:
interval: 'weekly'

View File

@ -1,18 +0,0 @@
name: Basic validation
on:
push:
branches:
- main
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
jobs:
call-basic-validation:
name: Basic validation
uses: actions/reusable-workflows/.github/workflows/basic-validation.yml@main
with:
node-version: '20'

View File

@ -1,3 +1,8 @@
# `dist/index.js` is a special file in Actions.
# When you reference an action with `uses:` in a workflow,
# `index.js` is the code that will run.
# For our project, we generate this file through a build process from other source files.
# We need to make sure the checked-in `index.js` actually matches what we expect it to be.
name: Check dist/ name: Check dist/
on: on:
@ -12,8 +17,36 @@ on:
workflow_dispatch: workflow_dispatch:
jobs: jobs:
call-check-dist: check-dist:
name: Check dist/ runs-on: ubuntu-latest
uses: actions/reusable-workflows/.github/workflows/check-dist.yml@main
with: steps:
node-version: '20' - uses: actions/checkout@v3
- name: Set Node.js 16.x
uses: actions/setup-node@v3
with:
node-version: 16.x
cache: npm
- name: Install dependencies
run: npm ci
- name: Rebuild the dist/ directory
run: npm run build
- name: Compare the expected and actual dist/ directories
run: |
if [ "$(git diff --ignore-space-at-eol dist/ | wc -l)" -gt "0" ]; then
echo "Detected uncommitted changes after build. See status below:"
git diff
exit 1
fi
id: diff
# If index.js was different than expected, upload the expected version as an artifact
- uses: actions/upload-artifact@v4
if: ${{ failure() && steps.diff.conclusion == 'failure' }}
with:
name: dist
path: dist/

View File

@ -1,14 +0,0 @@
name: CodeQL analysis
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: '0 3 * * 0'
jobs:
call-codeQL-analysis:
name: CodeQL analysis
uses: actions/reusable-workflows/.github/workflows/codeql-analysis.yml@main

View File

@ -9,6 +9,20 @@ on:
- main - main
jobs: jobs:
call-licensed: test:
name: Licensed runs-on: ubuntu-latest
uses: actions/reusable-workflows/.github/workflows/licensed.yml@main name: Check licenses
steps:
- uses: actions/checkout@v3
- name: Set Node.js 16.x
uses: actions/setup-node@v3
with:
node-version: 16.x
- run: npm ci
- name: Install licensed
run: |
cd $RUNNER_TEMP
curl -Lfs -o licensed.tar.gz https://github.com/github/licensed/releases/download/3.4.4/licensed-3.4.4-linux-x64.tar.gz
sudo tar -xzf licensed.tar.gz
sudo mv licensed /usr/local/bin/licensed
- run: licensed status

View File

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

View File

@ -1,5 +1,4 @@
name: Release new action version name: Release new action version
on: on:
release: release:
types: [released] types: [released]
@ -22,7 +21,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Update the ${{ env.TAG_NAME }} tag - name: Update the ${{ env.TAG_NAME }} tag
uses: actions/publish-action@v0.3.0 uses: actions/publish-action@v0.2.1
with: with:
source-tag: ${{ env.TAG_NAME }} source-tag: ${{ env.TAG_NAME }}
slack-webhook: ${{ secrets.SLACK_WEBHOOK }} slack-webhook: ${{ secrets.SLACK_WEBHOOK }}

View File

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

View File

@ -1,5 +1,4 @@
name: Validate 'setup-go' name: Validate 'setup-go'
on: on:
push: push:
branches: branches:
@ -18,9 +17,9 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [ubuntu-latest, windows-latest, macos-latest, macos-13] os: [ubuntu-latest, windows-latest, macos-latest]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- name: Setup Go Stable - name: Setup Go Stable
uses: ./ uses: ./
with: with:
@ -33,31 +32,29 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [ubuntu-latest, windows-latest, macos-latest, macos-13] os: [ubuntu-latest, windows-latest, macos-latest]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- name: Setup Go oldStable - name: Setup Go oldStable
uses: ./ uses: ./
with: with:
go-version: oldstable go-version: oldstable
- name: Verify Go - name: Verify Go
run: go version run: go version
aliases-arch: aliases-arch:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [ubuntu-latest, windows-latest, macos-latest, macos-13] os: [ubuntu-latest, windows-latest, macos-latest]
version: [stable, oldstable] version: [stable, oldstable]
architecture: [x64, x32] architecture: [x64, x32]
exclude: exclude:
- os: macos-latest - os: macos-latest
architecture: x32 architecture: x32
- os: macos-13
architecture: x32
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- name: Setup Go ${{ matrix.version }} ${{ matrix.architecture }} - name: Setup Go ${{ matrix.version }} ${{ matrix.architecture }}
uses: ./ uses: ./
with: with:
@ -72,17 +69,11 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [macos-latest, windows-latest, ubuntu-latest, macos-13] os: [macos-latest, windows-latest, ubuntu-latest]
go: [1.21.13, 1.22.8, 1.23.2] go: [1.17, 1.18, 1.19]
include:
- os: windows-latest
go: 1.20.14
exclude:
- os: windows-latest
go: 1.23.2
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: setup-go ${{ matrix.go }} - name: setup-go ${{ matrix.go }}
uses: ./ uses: ./
@ -98,10 +89,10 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [ubuntu-latest, windows-latest, macos-latest, macos-13] os: [ubuntu-latest, windows-latest, macos-latest]
go-version: ['1.20', '1.21', '1.22', '1.23'] go-version: [1.16, 1.17]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- name: Setup Go and check latest - name: Setup Go and check latest
uses: ./ uses: ./
with: with:
@ -115,15 +106,15 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [ubuntu-latest, windows-latest, macos-latest, macos-13] os: [ubuntu-latest, windows-latest, macos-13]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- name: Setup Go and check latest - name: Setup Go and check latest
uses: ./ uses: ./
with: with:
go-version-file: __tests__/data/go.mod go-version-file: __tests__/data/go.mod
- name: verify go - name: verify go
run: __tests__/verify-go.sh 1.20.14 run: __tests__/verify-go.sh 1.14
shell: bash shell: bash
go-version-file-with-gowork: go-version-file-with-gowork:
@ -131,27 +122,28 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [ubuntu-latest, windows-latest, macos-latest, macos-13] os: [ubuntu-latest, windows-latest, macos-latest]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- name: Setup Go and check latest - name: Setup Go and check latest
uses: ./ uses: ./
with: with:
go-version-file: __tests__/data/go.work go-version-file: __tests__/data/go.work
- name: verify go - name: verify go
run: __tests__/verify-go.sh 1.21 run: __tests__/verify-go.sh 1.19
shell: bash shell: bash
setup-versions-from-manifest: setup-versions-from-manifest:
name: Setup ${{ matrix.go }} ${{ matrix.os }}
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [macos-latest, windows-latest, ubuntu-latest, macos-13] os: [macos-13, windows-latest, ubuntu-latest]
go: [1.20.14, 1.21.10, 1.22.8, 1.23.2] go: [1.12.16, 1.13.11, 1.14.3]
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: setup-go ${{ matrix.go }} - name: setup-go ${{ matrix.go }}
uses: ./ uses: ./
@ -163,15 +155,19 @@ jobs:
shell: bash shell: bash
setup-versions-from-dist: setup-versions-from-dist:
name: Setup ${{ matrix.go }} ${{ matrix.os }}
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [windows-latest, ubuntu-latest, macos-13] os: [macos-13, windows-latest, ubuntu-latest]
go: [1.11.12] go: [1.11.12, 1.8.6]
exclude:
- os: macos-13
go: 1.8.6
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: setup-go ${{ matrix.go }} - name: setup-go ${{ matrix.go }}
uses: ./ uses: ./
@ -187,23 +183,14 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [ubuntu-latest, windows-latest, macos-latest, macos-13] os: [ubuntu-latest, windows-latest, macos-latest]
go-version: [1.20.14, 1.21, 1.22, 1.23] go-version: [1.16, 1.17]
include:
- os: macos-latest
architecture: arm64
- os: ubuntu-latest
architecture: x64
- os: windows-latest
architecture: x64
- os: macos-13
architecture: x64
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- name: Setup Go and check latest - name: Setup Go and check latest
uses: ./ uses: ./
with: with:
go-version: ${{ matrix.go-version }} go-version: ${{ matrix.go-version }}
architecture: ${{ matrix.architecture }} architecture: x64
- name: Verify Go - name: Verify Go
run: go version run: go version

View File

@ -1,136 +0,0 @@
name: Validate Windows installation
on:
push:
branches:
- main
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
jobs:
create-link-if-not-default:
runs-on: windows-latest
name: 'Validate if symlink is created'
strategy:
matrix:
cache: [false, true]
go: [1.20.1]
steps:
- uses: actions/checkout@v4
- name: 'Setup ${{ matrix.cache }}, cache: ${{ matrix.go }}'
uses: ./
with:
go-version: ${{ matrix.go }}
cache: ${{ matrix.cache }}
- name: 'Drive C: should have zero size link'
run: |
du -m -s 'C:\hostedtoolcache\windows\go\${{ matrix.go }}\x64'
# make sure drive c: contains only a link
size=$(du -m -s 'C:\hostedtoolcache\windows\go\${{ matrix.go }}\x64'|cut -f1 -d$'\t')
if [ $size -ne 0 ];then
echo 'Size of the link created on drive c: must be 0'
exit 1
fi
shell: bash
# Drive D: is small, take care the action does not eat up the space
- name: 'Drive D: space usage should be below 1G'
run: |
du -m -s 'D:\hostedtoolcache\windows\go\${{ matrix.go }}\x64'
size=$(du -m -s 'D:\hostedtoolcache\windows\go\${{ matrix.go }}\x64'|cut -f1 -d$'\t')
# make sure archive does not take lot of space
if [ $size -gt 999 ];then
echo 'Size of installed on drive d: go is too big';
exit 1
fi
shell: bash
# make sure the Go installation has not been changed to the end user
- name: Test paths and environments
run: |
echo $PATH
which go
go version
go env
if [ $(which go) != '/c/hostedtoolcache/windows/go/${{ matrix.go }}/x64/bin/go' ];then
echo 'which go should return "/c/hostedtoolcache/windows/go/${{ matrix.go }}/x64/bin/go"'
exit 1
fi
if [ $(go env GOROOT) != 'C:\hostedtoolcache\windows\go\${{ matrix.go }}\x64' ];then
echo 'go env GOROOT should return "C:\hostedtoolcache\windows\go\${{ matrix.go }}\x64"'
exit 1
fi
shell: bash
find-default-go:
name: 'Find default go version'
runs-on: windows-latest
outputs:
version: ${{ steps.goversion.outputs.version }}
steps:
- run: |
version=`go env GOVERSION|sed s/^go//`
echo "default go version: $version"
echo "version=$version" >> "$GITHUB_OUTPUT"
id: goversion
shell: bash
dont-create-link-if-default:
name: 'Validate if symlink is not created for default go'
runs-on: windows-latest
needs: find-default-go
strategy:
matrix:
cache: [false, true]
steps:
- uses: actions/checkout@v4
- name: 'Setup default go, cache: ${{ matrix.cache }}'
uses: ./
with:
go-version: ${{ needs.find-default-go.outputs.version }}
cache: ${{ matrix.cache }}
- name: 'Drive C: should have Go installation, cache: ${{ matrix.cache}}'
run: |
size=$(du -m -s 'C:\hostedtoolcache\windows\go\${{ needs.find-default-go.outputs.version }}\x64'|cut -f1 -d$'\t')
if [ $size -eq 0 ];then
echo 'Size of the hosted go installed on drive c: must be above zero'
exit 1
fi
shell: bash
- name: 'Drive D: should not have Go installation, cache: ${{ matrix.cache }}'
run: |
if [ -e 'D:\hostedtoolcache\windows\go\${{ needs.find-default-go.outputs.version }}\x64' ];then
echo 'D:\hostedtoolcache\windows\go\${{ needs.find-default-go.outputs.version }}\x64 should not exist for hosted version of go';
exit 1
fi
shell: bash
hostedtoolcache:
name: 'Validate if hostedtoolcache works as expected'
runs-on: windows-latest
strategy:
matrix:
cache: [false]
go: [1.20.1]
steps:
- uses: actions/checkout@v4
- name: 'Setup ${{ matrix.go }}, cache: ${{ matrix.cache }}'
uses: ./
with:
go-version: ${{ matrix.go }}
cache: ${{ matrix.cache }}
- name: 'Setup ${{ matrix.go }}, cache: ${{ matrix.cache }} (from hostedtoolcache)'
uses: ./
with:
go-version: ${{ matrix.go }}
cache: ${{ matrix.cache }}

39
.github/workflows/workflow.yml vendored Normal file
View File

@ -0,0 +1,39 @@
name: build-test
on:
push:
branches:
- main
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
jobs:
run:
name: Run
runs-on: ${{ matrix.operating-system }}
strategy:
matrix:
operating-system: [ubuntu-latest, windows-latest]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup node 16
uses: actions/setup-node@v3
with:
node-version: 16
cache: npm
- name: npm ci
run: npm ci
- name: Lint
run: npm run format-check
- name: npm test
run: npm test
- name: audit packages
run: npm audit --audit-level=high
if: matrix.operating-system == 'ubuntu-latest'

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
.licenses/npm/@azure/core-client.dep.yml generated Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
.licenses/npm/@azure/core-xml.dep.yml generated Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
.licenses/npm/agent-base.dep.yml generated Normal file

Binary file not shown.

BIN
.licenses/npm/debug.dep.yml generated Normal file

Binary file not shown.

BIN
.licenses/npm/fast-xml-parser.dep.yml generated Normal file

Binary file not shown.

Binary file not shown.

BIN
.licenses/npm/https-proxy-agent.dep.yml generated Normal file

Binary file not shown.

BIN
.licenses/npm/ms.dep.yml generated Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
.licenses/npm/tslib-2.8.1.dep.yml generated Normal file

Binary file not shown.

Binary file not shown.

View File

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

View File

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

11
.prettierrc.json Normal file
View File

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

View File

@ -1 +1 @@
* @actions/setup-actions-team * @actions/actions-service

175
README.md
View File

@ -1,6 +1,6 @@
# setup-go # setup-go
[![Basic validation](https://github.com/actions/setup-go/actions/workflows/basic-validation.yml/badge.svg)](https://github.com/actions/setup-go/actions/workflows/basic-validation.yml) [![build-test](https://github.com/actions/setup-go/actions/workflows/workflow.yml/badge.svg)](https://github.com/actions/setup-go/actions/workflows/workflow.yml)
[![Validate 'setup-go'](https://github.com/actions/setup-go/actions/workflows/versions.yml/badge.svg)](https://github.com/actions/setup-go/actions/workflows/versions.yml) [![Validate 'setup-go'](https://github.com/actions/setup-go/actions/workflows/versions.yml/badge.svg)](https://github.com/actions/setup-go/actions/workflows/versions.yml)
This action sets up a go environment for use in actions by: This action sets up a go environment for use in actions by:
@ -8,24 +8,6 @@ This action sets up a go environment for use in actions by:
- Optionally downloading and caching a version of Go by version and adding to `PATH`. - Optionally downloading and caching a version of Go by version and adding to `PATH`.
- Registering problem matchers for error output. - Registering problem matchers for error output.
# V5
The V5 edition of the action offers:
- Upgraded Node.js runtime from node16 to node20
See full release notes on the [releases page](https://github.com/actions/setup-go/releases).
# V4
The V4 edition of the action offers:
- Enabled caching by default
The action will try to enable caching unless the `cache` input is explicitly set to false.
Please see "[Caching dependency files and build outputs](https://github.com/actions/setup-go#caching-dependency-files-and-build-outputs)" for more information.
# V3 # V3
The V3 edition of the action offers: The V3 edition of the action offers:
@ -37,21 +19,16 @@ The V3 edition of the action offers:
- stable and oldstable aliases - stable and oldstable aliases
- Bug Fixes (including issues around version matching and semver) - Bug Fixes (including issues around version matching and semver)
The action will first check the local cache for a version match. If a version is not found locally, it will pull it from The action will first check the local cache for a version match. If a version is not found locally, it will pull it from the `main` branch of the [go-versions](https://github.com/actions/go-versions/blob/main/versions-manifest.json) repository. On miss or failure, it will fall back to downloading directly from [go dist](https://storage.googleapis.com/golang). To change the default behavior, please use the [check-latest input](#check-latest-version).
the `main` branch of the [go-versions](https://github.com/actions/go-versions/blob/main/versions-manifest.json)
repository. On miss or failure, it will fall back to downloading directly
from [go dist](https://storage.googleapis.com/golang). To change the default behavior, please use
the [check-latest input](#check-latest-version).
**Note:** The `setup-go` action uses executable binaries which are built by Golang side. The action does not build **Note:** The `setup-go` action uses executable binaries which are built by Golang side. The action does not build golang from source code.
golang from source code.
Matching by [semver spec](https://github.com/npm/node-semver): Matching by [semver spec](https://github.com/npm/node-semver):
```yaml ```yaml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v5 - uses: actions/setup-go@v3
with: with:
go-version: '^1.13.1' # The Go version to download (if necessary) and use. go-version: '^1.13.1' # The Go version to download (if necessary) and use.
- run: go version - run: go version
@ -59,27 +36,19 @@ steps:
```yaml ```yaml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v5 - uses: actions/setup-go@v3
with: with:
go-version: '>=1.17.0' go-version: '>=1.17.0'
- run: go version - run: go version
``` ```
> **Note**: Due to the peculiarities of YAML parsing, it is recommended to wrap the version in single quotation marks:
>
> ```yaml
> go-version: '1.20'
> ```
>
> The recommendation is based on the YAML parser's behavior, which interprets non-wrapped values as numbers and, in the case of version 1.20, trims it down to 1.2, which may not be very obvious.
Matching an unstable pre-release: Matching an unstable pre-release:
```yaml ```yaml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v5 - uses: actions/setup-go@v3
with: with:
go-version: '1.18.0-rc.1' # The Go version to download (if necessary) and use. go-version: '1.18.0-rc.1' # The Go version to download (if necessary) and use.
- run: go version - run: go version
@ -87,8 +56,8 @@ steps:
```yaml ```yaml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v5 - uses: actions/setup-go@v3
with: with:
go-version: '1.16.0-beta.1' # The Go version to download (if necessary) and use. go-version: '1.16.0-beta.1' # The Go version to download (if necessary) and use.
- run: go version - run: go version
@ -102,29 +71,26 @@ See [action.yml](action.yml)
```yaml ```yaml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v5 - uses: actions/setup-go@v3
with: with:
go-version: '1.16.1' # The Go version to download (if necessary) and use. go-version: '1.16.1' # The Go version to download (if necessary) and use.
- run: go run hello.go - run: go run hello.go
``` ```
## Check latest version ## Check latest version
The `check-latest` flag defaults to `false`. Use the default or set `check-latest` to `false` if you prefer stability The `check-latest` flag defaults to `false`. Use the default or set `check-latest` to `false` if you prefer stability and if you want to ensure a specific Go version is always used.
and if you want to ensure a specific Go version is always used.
If `check-latest` is set to `true`, the action first checks if the cached version is the latest one. If the locally If `check-latest` is set to `true`, the action first checks if the cached version is the latest one. If the locally cached version is not the most up-to-date, a Go version will then be downloaded. Set `check-latest` to `true` if you want the most up-to-date Go version to always be used.
cached version is not the most up-to-date, a Go version will then be downloaded. Set `check-latest` to `true` if you
want the most up-to-date Go version to always be used.
> Setting `check-latest` to `true` has performance implications as downloading Go versions is slower than using cached > Setting `check-latest` to `true` has performance implications as downloading Go versions is slower than using cached versions.
> versions.
```yaml ```yaml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v5 - uses: actions/setup-go@v3
with: with:
go-version: '1.14' go-version: '1.14'
check-latest: true check-latest: true
@ -133,19 +99,16 @@ steps:
## Using stable/oldstable aliases ## Using stable/oldstable aliases
If `stable` is provided, action will get the latest stable version from If `stable` is provided, action will get the latest stable version from the [`go-versions`](https://github.com/actions/go-versions/blob/main/versions-manifest.json) repository manifest.
the [`go-versions`](https://github.com/actions/go-versions/blob/main/versions-manifest.json) repository manifest.
If `oldstable` is provided, when current release is 1.19.x, action will resolve version as 1.18.x, where x is the latest If `oldstable` is provided, when current release is 1.19.x, action will resolve version as 1.18.x, where x is the latest patch release.
patch release.
**Note:** using these aliases will result in same version as using corresponding minor release with `check-latest` input **Note:** using these aliases will result in same version as using corresponding minor release with `check-latest` input set to `true`
set to `true`
```yaml ```yaml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v5 - uses: actions/setup-go@v3
with: with:
go-version: 'stable' go-version: 'stable'
- run: go run hello.go - run: go run hello.go
@ -153,8 +116,8 @@ steps:
```yaml ```yaml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v5 - uses: actions/setup-go@v3
with: with:
go-version: 'oldstable' go-version: 'oldstable'
- run: go run hello.go - run: go run hello.go
@ -162,53 +125,48 @@ steps:
## Caching dependency files and build outputs: ## Caching dependency files and build outputs:
The action has a built-in functionality for caching and restoring go modules and build outputs. It The action has a built-in functionality for caching and restoring go modules and build outputs. It uses [actions/cache](https://github.com/actions/cache) under the hood but requires less configuration settings. The `cache` input is optional, and caching is turned off by default.
uses [toolkit/cache](https://github.com/actions/toolkit/tree/main/packages/cache) under the hood but requires less configuration settings.
The `cache` input is optional, and caching is turned on by default.
The action defaults to search for the dependency file - go.sum in the repository root, and uses its hash as a part of The action defaults to search for the dependency file - go.sum in the repository root, and uses its hash as a part of the cache key. Use `cache-dependency-path` input for cases when multiple dependency files are used, or they are located in different subdirectories.
the cache key. Use `cache-dependency-path` input for cases when multiple dependency files are used, or they are located
in different subdirectories. The input supports glob patterns.
If some problem that prevents success caching happens then the action issues the warning in the log and continues the execution of the pipeline.
**Caching in monorepos**
**Caching without specifying dependency file path**
```yaml ```yaml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v5 - uses: actions/setup-go@v3
with: with:
go-version: '1.17' go-version: '1.17'
check-latest: true check-latest: true
cache-dependency-path: | cache: true
subdir/go.sum - run: go run hello.go
tools/go.sum ```
# cache-dependency-path: "**/*.sum"
**Caching in monorepos**
```yaml
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v3
with:
go-version: '1.17'
check-latest: true
cache: true
cache-dependency-path: subdir/go.sum
- run: go run hello.go - run: go run hello.go
``` ```
## Getting go version from the go.mod file ## Getting go version from the go.mod file
The `go-version-file` input accepts a path to a `go.mod` file or a `go.work` file that contains the version of Go to be used by a project. The `go-version-file` input accepts a path to a `go.mod` file or a `go.work` file that contains the version of Go to be used by a project. As the `go.mod` file contains only major and minor (e.g. 1.18) tags, the action will search for the latest available patch version sequentially in the runner's directory with the cached tools, in the [version-manifest.json](https://github.com/actions/go-versions/blob/main/versions-manifest.json) file or at the go servers.
The `go` directive in `go.mod` can specify a patch version or omit it altogether (e.g., `go 1.22.0` or `go 1.22`).
If a patch version is specified, that specific patch version will be used.
If no patch version is specified, it will search for the latest available patch version in the cache,
[versions-manifest.json](https://github.com/actions/go-versions/blob/main/versions-manifest.json), and the
[official Go language website](https://golang.org/dl/?mode=json&include=all), in that order.
If both the `go-version` and the `go-version-file` inputs are provided then the `go-version` input is used. If both the `go-version` and the `go-version-file` inputs are provided then the `go-version` input is used.
> The action will search for the `go.mod` file relative to the repository root > The action will search for the `go.mod` file relative to the repository root
```yaml ```yaml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v5 - uses: actions/setup-go@v3
with: with:
go-version-file: 'path/to/go.mod' go-version-file: 'path/to/go.mod'
- run: go version - run: go version
``` ```
## Matrix testing ## Matrix testing
@ -222,9 +180,9 @@ jobs:
go: [ '1.14', '1.13' ] go: [ '1.14', '1.13' ]
name: Go ${{ matrix.go }} sample name: Go ${{ matrix.go }} sample
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- name: Setup go - name: Setup go
uses: actions/setup-go@v5 uses: actions/setup-go@v3
with: with:
go-version: ${{ matrix.go }} go-version: ${{ matrix.go }}
- run: go run hello.go - run: go run hello.go
@ -237,39 +195,22 @@ The `go-version` input supports the following syntax:
- Specific versions: `1.15`, `1.16.1`, `1.17.0-rc.2`, `1.16.0-beta.1` - Specific versions: `1.15`, `1.16.1`, `1.17.0-rc.2`, `1.16.0-beta.1`
- SemVer's version range syntax: `^1.13.1`, `>=1.18.0-rc.1` - SemVer's version range syntax: `^1.13.1`, `>=1.18.0-rc.1`
For more information about semantic versioning, please refer to [semver](https://github.com/npm/node-semver) For more information about semantic versioning, please refer to [semver](https://github.com/npm/node-semver) documentation.
documentation.
## Using `setup-go` on GHES ## Using `setup-go` on GHES
`setup-go` comes pre-installed on the appliance with GHES if Actions is enabled. `setup-go` comes pre-installed on the appliance with GHES if Actions is enabled. When dynamically downloading Go distributions, `setup-go` downloads distributions from [`actions/go-versions`](https://github.com/actions/go-versions) on github.com (outside of the appliance). These calls to `actions/go-versions` are made via unauthenticated requests, which are limited to [60 requests per hour per IP](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting). If more requests are made within the time frame, then you will start to see rate-limit errors during downloading that looks like: `##[error]API rate limit exceeded for...`. After that error the action will try to download versions directly from https://storage.googleapis.com/golang, but it also can have rate limit so it's better to put token.
When dynamically downloading Go distributions, `setup-go` downloads distributions from [`actions/go-versions`](https://github.com/actions/go-versions) on github.com (outside of the appliance).
These calls to `actions/go-versions` are made via unauthenticated requests, which are limited to [60 requests per hour per IP](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting). To get a higher rate limit, you can [generate a personal access token on github.com](https://github.com/settings/tokens/new) and pass it as the `token` input for the action:
If more requests are made within the time frame, then the action leverages the `raw API` to retrieve the version-manifest. This approach does not impose a rate limit and hence facilitates unrestricted consumption. This is particularly beneficial for GHES runners, which often share the same IP, to avoid the quick exhaustion of the unauthenticated rate limit.
If that fails as well the action will try to download versions directly from https://storage.googleapis.com/golang.
If that fails as well you can get a higher rate limit with [generating a personal access token on github.com](https://github.com/settings/tokens/new) and passing it as the `token` input to the action:
```yaml ```yaml
uses: actions/setup-go@v5 uses: actions/setup-go@v3
with: with:
token: ${{ secrets.GH_DOTCOM_TOKEN }} token: ${{ secrets.GH_DOTCOM_TOKEN }}
go-version: '1.18' go-version: 1.18
``` ```
If the runner is not able to access github.com, any Go versions requested during a workflow run must come from the runner's tool cache. If the runner is not able to access github.com, any Go versions requested during a workflow run must come from the runner's tool cache. See "[Setting up the tool cache on self-hosted runners without internet access](https://docs.github.com/en/enterprise-server@3.2/admin/github-actions/managing-access-to-actions-from-githubcom/setting-up-the-tool-cache-on-self-hosted-runners-without-internet-access)" for more information.
See "[Setting up the tool cache on self-hosted runners without internet access](https://docs.github.com/en/enterprise-server@3.2/admin/github-actions/managing-access-to-actions-from-githubcom/setting-up-the-tool-cache-on-self-hosted-runners-without-internet-access)"
for more information.
## Recommended permissions
When using the `setup-go` action in your GitHub Actions workflow, it is recommended to set the following permissions to ensure proper functionality:
```yaml
permissions:
contents: read # access to check out code and install dependencies
```
# License # License

View File

@ -8,14 +8,14 @@ import {PackageManagerInfo} from '../src/package-managers';
describe('restoreCache', () => { describe('restoreCache', () => {
//Arrange //Arrange
const hashFilesSpy = jest.spyOn(glob, 'hashFiles'); let hashFilesSpy = jest.spyOn(glob, 'hashFiles');
const getCacheDirectoryPathSpy = jest.spyOn( let getCacheDirectoryPathSpy = jest.spyOn(
cacheUtils, cacheUtils,
'getCacheDirectoryPath' 'getCacheDirectoryPath'
); );
const restoreCacheSpy = jest.spyOn(cache, 'restoreCache'); let restoreCacheSpy = jest.spyOn(cache, 'restoreCache');
const infoSpy = jest.spyOn(core, 'info'); let infoSpy = jest.spyOn(core, 'info');
const setOutputSpy = jest.spyOn(core, 'setOutput'); let setOutputSpy = jest.spyOn(core, 'setOutput');
const versionSpec = '1.13.1'; const versionSpec = '1.13.1';
const packageManager = 'default'; const packageManager = 'default';
@ -40,13 +40,13 @@ describe('restoreCache', () => {
}); });
//Act + Assert //Act + Assert
await expect(async () => { expect(async () => {
await cacheRestore.restoreCache( await cacheRestore.restoreCache(
versionSpec, versionSpec,
packageManager, packageManager,
cacheDependencyPath cacheDependencyPath
); );
}).rejects.toThrow( }).rejects.toThrowError(
'Some specified paths were not resolved, unable to cache dependencies.' 'Some specified paths were not resolved, unable to cache dependencies.'
); );
}); });
@ -71,7 +71,7 @@ describe('restoreCache', () => {
packageManager, packageManager,
cacheDependencyPath cacheDependencyPath
); );
expect(infoSpy).toHaveBeenCalledWith(`Cache is not found`); expect(infoSpy).toBeCalledWith(`Cache is not found`);
}); });
it('should set output if cache hit is occured', async () => { it('should set output if cache hit is occured', async () => {
@ -94,6 +94,6 @@ describe('restoreCache', () => {
packageManager, packageManager,
cacheDependencyPath cacheDependencyPath
); );
expect(setOutputSpy).toHaveBeenCalledWith('cache-hit', true); expect(setOutputSpy).toBeCalledWith('cache-hit', true);
}); });
}); });

View File

@ -6,7 +6,7 @@ import {PackageManagerInfo} from '../src/package-managers';
describe('getCommandOutput', () => { describe('getCommandOutput', () => {
//Arrange //Arrange
const getExecOutputSpy = jest.spyOn(exec, 'getExecOutput'); let getExecOutputSpy = jest.spyOn(exec, 'getExecOutput');
it('should return trimmed stdout in case of successful exit code', async () => { it('should return trimmed stdout in case of successful exit code', async () => {
//Arrange //Arrange
@ -36,7 +36,7 @@ describe('getCommandOutput', () => {
}); });
//Act + Assert //Act + Assert
await expect(async () => { expect(async () => {
await cacheUtils.getCommandOutput('command'); await cacheUtils.getCommandOutput('command');
}).rejects.toThrow(); }).rejects.toThrow();
}); });
@ -62,7 +62,7 @@ describe('getPackageManagerInfo', () => {
const packageManagerName = 'invalidName'; const packageManagerName = 'invalidName';
//Act + Assert //Act + Assert
await expect(async () => { expect(async () => {
await cacheUtils.getPackageManagerInfo(packageManagerName); await cacheUtils.getPackageManagerInfo(packageManagerName);
}).rejects.toThrow(); }).rejects.toThrow();
}); });
@ -70,7 +70,7 @@ describe('getPackageManagerInfo', () => {
describe('getCacheDirectoryPath', () => { describe('getCacheDirectoryPath', () => {
//Arrange //Arrange
const getExecOutputSpy = jest.spyOn(exec, 'getExecOutput'); let getExecOutputSpy = jest.spyOn(exec, 'getExecOutput');
const validPackageManager: PackageManagerInfo = { const validPackageManager: PackageManagerInfo = {
dependencyFilePattern: 'go.sum', dependencyFilePattern: 'go.sum',
@ -93,41 +93,6 @@ describe('getCacheDirectoryPath', () => {
.then(data => expect(data).toEqual(expectedResult)); .then(data => expect(data).toEqual(expectedResult));
}); });
it('should return path to the cache folder if one command return empty str', async () => {
//Arrange
getExecOutputSpy.mockImplementationOnce((commandLine: string) => {
return new Promise<exec.ExecOutput>(resolve => {
resolve({exitCode: 0, stdout: 'path/to/cache/folder', stderr: ''});
});
});
getExecOutputSpy.mockImplementationOnce((commandLine: string) => {
return new Promise<exec.ExecOutput>(resolve => {
resolve({exitCode: 0, stdout: '', stderr: ''});
});
});
const expectedResult = ['path/to/cache/folder'];
//Act + Assert
return cacheUtils
.getCacheDirectoryPath(validPackageManager)
.then(data => expect(data).toEqual(expectedResult));
});
it('should throw if the both commands return empty str', async () => {
getExecOutputSpy.mockImplementation((commandLine: string) => {
return new Promise<exec.ExecOutput>(resolve => {
resolve({exitCode: 10, stdout: '', stderr: ''});
});
});
//Act + Assert
await expect(async () => {
await cacheUtils.getCacheDirectoryPath(validPackageManager);
}).rejects.toThrow();
});
it('should throw if the specified package name is invalid', async () => { it('should throw if the specified package name is invalid', async () => {
getExecOutputSpy.mockImplementation((commandLine: string) => { getExecOutputSpy.mockImplementation((commandLine: string) => {
return new Promise<exec.ExecOutput>(resolve => { return new Promise<exec.ExecOutput>(resolve => {
@ -136,7 +101,7 @@ describe('getCacheDirectoryPath', () => {
}); });
//Act + Assert //Act + Assert
await expect(async () => { expect(async () => {
await cacheUtils.getCacheDirectoryPath(validPackageManager); await cacheUtils.getCacheDirectoryPath(validPackageManager);
}).rejects.toThrow(); }).rejects.toThrow();
}); });
@ -144,8 +109,8 @@ describe('getCacheDirectoryPath', () => {
describe('isCacheFeatureAvailable', () => { describe('isCacheFeatureAvailable', () => {
//Arrange //Arrange
const isFeatureAvailableSpy = jest.spyOn(cache, 'isFeatureAvailable'); let isFeatureAvailableSpy = jest.spyOn(cache, 'isFeatureAvailable');
const warningSpy = jest.spyOn(core, 'warning'); let warningSpy = jest.spyOn(core, 'warning');
it('should return true when cache feature is available', () => { it('should return true when cache feature is available', () => {
//Arrange //Arrange
@ -153,14 +118,16 @@ describe('isCacheFeatureAvailable', () => {
return true; return true;
}); });
let functionResult;
//Act //Act
const functionResult = cacheUtils.isCacheFeatureAvailable(); functionResult = cacheUtils.isCacheFeatureAvailable();
//Assert //Assert
expect(functionResult).toBeTruthy(); expect(functionResult).toBeTruthy();
}); });
it('should warn when cache feature is unavailable and GHES is not used', () => { it('should warn when cache feature is unavailable and GHES is not used ', () => {
//Arrange //Arrange
isFeatureAvailableSpy.mockImplementation(() => { isFeatureAvailableSpy.mockImplementation(() => {
return false; return false;
@ -168,7 +135,7 @@ describe('isCacheFeatureAvailable', () => {
process.env['GITHUB_SERVER_URL'] = 'https://github.com'; process.env['GITHUB_SERVER_URL'] = 'https://github.com';
const warningMessage = let warningMessage =
'The runner was not able to contact the cache service. Caching will be skipped'; 'The runner was not able to contact the cache service. Caching will be skipped';
//Act //Act
@ -186,14 +153,16 @@ describe('isCacheFeatureAvailable', () => {
process.env['GITHUB_SERVER_URL'] = 'https://github.com'; process.env['GITHUB_SERVER_URL'] = 'https://github.com';
let functionResult;
//Act //Act
const functionResult = cacheUtils.isCacheFeatureAvailable(); functionResult = cacheUtils.isCacheFeatureAvailable();
//Assert //Assert
expect(functionResult).toBeFalsy(); expect(functionResult).toBeFalsy();
}); });
it('should warn when cache feature is unavailable and GHES is used', () => { it('should throw when cache feature is unavailable and GHES is used', () => {
//Arrange //Arrange
isFeatureAvailableSpy.mockImplementation(() => { isFeatureAvailableSpy.mockImplementation(() => {
return false; return false;
@ -201,49 +170,10 @@ describe('isCacheFeatureAvailable', () => {
process.env['GITHUB_SERVER_URL'] = 'https://nongithub.com'; process.env['GITHUB_SERVER_URL'] = 'https://nongithub.com';
const warningMessage = let errorMessage =
'Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'; 'Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.';
//Act + Assert //Act + Assert
expect(cacheUtils.isCacheFeatureAvailable()).toBeFalsy(); expect(() => cacheUtils.isCacheFeatureAvailable()).toThrow(errorMessage);
expect(warningSpy).toHaveBeenCalledWith(warningMessage);
});
});
describe('isGhes', () => {
const pristineEnv = process.env;
beforeEach(() => {
jest.resetModules();
process.env = {...pristineEnv};
});
afterAll(() => {
process.env = pristineEnv;
});
it('returns false when the GITHUB_SERVER_URL environment variable is not defined', async () => {
delete process.env['GITHUB_SERVER_URL'];
expect(cacheUtils.isGhes()).toBeFalsy();
});
it('returns false when the GITHUB_SERVER_URL environment variable is set to github.com', async () => {
process.env['GITHUB_SERVER_URL'] = 'https://github.com';
expect(cacheUtils.isGhes()).toBeFalsy();
});
it('returns false when the GITHUB_SERVER_URL environment variable is set to a GitHub Enterprise Cloud-style URL', async () => {
process.env['GITHUB_SERVER_URL'] = 'https://contoso.ghe.com';
expect(cacheUtils.isGhes()).toBeFalsy();
});
it('returns false when the GITHUB_SERVER_URL environment variable has a .localhost suffix', async () => {
process.env['GITHUB_SERVER_URL'] = 'https://mock-github.localhost';
expect(cacheUtils.isGhes()).toBeFalsy();
});
it('returns true when the GITHUB_SERVER_URL environment variable is set to some other URL', async () => {
process.env['GITHUB_SERVER_URL'] = 'https://src.onpremise.fabrikam.com';
expect(cacheUtils.isGhes()).toBeTruthy();
}); });
}); });

View File

@ -1,6 +1,6 @@
module example.com/mymodule module example.com/mymodule
go 1.20 go 1.14
require ( require (
example.com/othermodule v1.2.3 example.com/othermodule v1.2.3

View File

@ -1,3 +1,3 @@
go 1.21 go 1.19
use . use .

View File

@ -3,21 +3,18 @@ import * as io from '@actions/io';
import * as tc from '@actions/tool-cache'; import * as tc from '@actions/tool-cache';
import fs from 'fs'; import fs from 'fs';
import cp from 'child_process'; import cp from 'child_process';
import osm, {type} from 'os'; import osm from 'os';
import path from 'path'; import path from 'path';
import * as main from '../src/main'; import * as main from '../src/main';
import * as im from '../src/installer'; import * as im from '../src/installer';
import * as httpm from '@actions/http-client';
import goJsonData from './data/golang-dl.json'; let goJsonData = require('./data/golang-dl.json');
import matchers from '../matchers.json'; let matchers = require('../matchers.json');
import goTestManifest from './data/versions-manifest.json'; let goTestManifest = require('./data/versions-manifest.json');
const matcherPattern = matchers.problemMatcher[0].pattern[0]; let matcherPattern = matchers.problemMatcher[0].pattern[0];
const matcherRegExp = new RegExp(matcherPattern.regexp); let matcherRegExp = new RegExp(matcherPattern.regexp);
const win32Join = path.win32.join; let win32Join = path.win32.join;
const posixJoin = path.posix.join; let posixJoin = path.posix.join;
jest.setTimeout(10000);
describe('setup-go', () => { describe('setup-go', () => {
let inputs = {} as any; let inputs = {} as any;
@ -42,12 +39,9 @@ describe('setup-go', () => {
let existsSpy: jest.SpyInstance; let existsSpy: jest.SpyInstance;
let readFileSpy: jest.SpyInstance; let readFileSpy: jest.SpyInstance;
let mkdirpSpy: jest.SpyInstance; let mkdirpSpy: jest.SpyInstance;
let mkdirSpy: jest.SpyInstance;
let symlinkSpy: jest.SpyInstance;
let execSpy: jest.SpyInstance; let execSpy: jest.SpyInstance;
let getManifestSpy: jest.SpyInstance; let getManifestSpy: jest.SpyInstance;
let getAllVersionsSpy: jest.SpyInstance; let getAllVersionsSpy: jest.SpyInstance;
let httpmGetJsonSpy: jest.SpyInstance;
beforeAll(async () => { beforeAll(async () => {
process.env['GITHUB_ENV'] = ''; // Stub out Environment file functionality so we can verify it writes to standard out (toolkit is backwards compatible) process.env['GITHUB_ENV'] = ''; // Stub out Environment file functionality so we can verify it writes to standard out (toolkit is backwards compatible)
@ -92,20 +86,12 @@ describe('setup-go', () => {
getManifestSpy = jest.spyOn(tc, 'getManifestFromRepo'); getManifestSpy = jest.spyOn(tc, 'getManifestFromRepo');
getAllVersionsSpy = jest.spyOn(im, 'getManifest'); getAllVersionsSpy = jest.spyOn(im, 'getManifest');
// httm
httpmGetJsonSpy = jest.spyOn(httpm.HttpClient.prototype, 'getJson');
// io // io
whichSpy = jest.spyOn(io, 'which'); whichSpy = jest.spyOn(io, 'which');
existsSpy = jest.spyOn(fs, 'existsSync'); existsSpy = jest.spyOn(fs, 'existsSync');
readFileSpy = jest.spyOn(fs, 'readFileSync'); readFileSpy = jest.spyOn(fs, 'readFileSync');
mkdirpSpy = jest.spyOn(io, 'mkdirP'); mkdirpSpy = jest.spyOn(io, 'mkdirP');
// fs
mkdirSpy = jest.spyOn(fs, 'mkdir');
symlinkSpy = jest.spyOn(fs, 'symlinkSync');
symlinkSpy.mockImplementation(() => {});
// gets // gets
getManifestSpy.mockImplementation(() => <tc.IToolRelease[]>goTestManifest); getManifestSpy.mockImplementation(() => <tc.IToolRelease[]>goTestManifest);
@ -147,7 +133,7 @@ describe('setup-go', () => {
os.platform = 'darwin'; os.platform = 'darwin';
os.arch = 'x64'; os.arch = 'x64';
const match = await im.getInfoFromManifest('1.9.7', true, 'mocktoken'); let match = await im.getInfoFromManifest('1.9.7', true, 'mocktoken');
expect(match).toBeDefined(); expect(match).toBeDefined();
expect(match!.resolvedVersion).toBe('1.9.7'); expect(match!.resolvedVersion).toBe('1.9.7');
expect(match!.type).toBe('manifest'); expect(match!.type).toBe('manifest');
@ -156,26 +142,11 @@ describe('setup-go', () => {
); );
}); });
it('should return manifest from repo', async () => {
const manifest = await im.getManifest(undefined);
expect(manifest).toEqual(goTestManifest);
});
it('should return manifest from raw URL if repo fetch fails', async () => {
getManifestSpy.mockRejectedValue(new Error('Fetch failed'));
httpmGetJsonSpy.mockResolvedValue({
result: goTestManifest
});
const manifest = await im.getManifest(undefined);
expect(httpmGetJsonSpy).toHaveBeenCalled();
expect(manifest).toEqual(goTestManifest);
});
it('can find 1.9 from manifest on linux', async () => { it('can find 1.9 from manifest on linux', async () => {
os.platform = 'linux'; os.platform = 'linux';
os.arch = 'x64'; os.arch = 'x64';
const match = await im.getInfoFromManifest('1.9.7', true, 'mocktoken'); let match = await im.getInfoFromManifest('1.9.7', true, 'mocktoken');
expect(match).toBeDefined(); expect(match).toBeDefined();
expect(match!.resolvedVersion).toBe('1.9.7'); expect(match!.resolvedVersion).toBe('1.9.7');
expect(match!.type).toBe('manifest'); expect(match!.type).toBe('manifest');
@ -188,7 +159,7 @@ describe('setup-go', () => {
os.platform = 'win32'; os.platform = 'win32';
os.arch = 'x64'; os.arch = 'x64';
const match = await im.getInfoFromManifest('1.9.7', true, 'mocktoken'); let match = await im.getInfoFromManifest('1.9.7', true, 'mocktoken');
expect(match).toBeDefined(); expect(match).toBeDefined();
expect(match!.resolvedVersion).toBe('1.9.7'); expect(match!.resolvedVersion).toBe('1.9.7');
expect(match!.type).toBe('manifest'); expect(match!.type).toBe('manifest');
@ -202,11 +173,11 @@ describe('setup-go', () => {
os.arch = 'x64'; os.arch = 'x64';
// spec: 1.13.0 => 1.13 // spec: 1.13.0 => 1.13
const match: im.IGoVersion | undefined = await im.findMatch('1.13.0'); let match: im.IGoVersion | undefined = await im.findMatch('1.13.0');
expect(match).toBeDefined(); expect(match).toBeDefined();
const version: string = match ? match.version : ''; let version: string = match ? match.version : '';
expect(version).toBe('go1.13'); expect(version).toBe('go1.13');
const fileName = match ? match.files[0].filename : ''; let fileName = match ? match.files[0].filename : '';
expect(fileName).toBe('go1.13.darwin-amd64.tar.gz'); expect(fileName).toBe('go1.13.darwin-amd64.tar.gz');
}); });
@ -215,11 +186,11 @@ describe('setup-go', () => {
os.arch = 'x64'; os.arch = 'x64';
// spec: 1.13 => 1.13.7 (latest) // spec: 1.13 => 1.13.7 (latest)
const match: im.IGoVersion | undefined = await im.findMatch('1.13'); let match: im.IGoVersion | undefined = await im.findMatch('1.13');
expect(match).toBeDefined(); expect(match).toBeDefined();
const version: string = match ? match.version : ''; let version: string = match ? match.version : '';
expect(version).toBe('go1.13.7'); expect(version).toBe('go1.13.7');
const fileName = match ? match.files[0].filename : ''; let fileName = match ? match.files[0].filename : '';
expect(fileName).toBe('go1.13.7.linux-amd64.tar.gz'); expect(fileName).toBe('go1.13.7.linux-amd64.tar.gz');
}); });
@ -228,11 +199,11 @@ describe('setup-go', () => {
os.arch = 'x64'; os.arch = 'x64';
// spec: ^1.13.6 => 1.13.7 // spec: ^1.13.6 => 1.13.7
const match: im.IGoVersion | undefined = await im.findMatch('^1.13.6'); let match: im.IGoVersion | undefined = await im.findMatch('^1.13.6');
expect(match).toBeDefined(); expect(match).toBeDefined();
const version: string = match ? match.version : ''; let version: string = match ? match.version : '';
expect(version).toBe('go1.13.7'); expect(version).toBe('go1.13.7');
const fileName = match ? match.files[0].filename : ''; let fileName = match ? match.files[0].filename : '';
expect(fileName).toBe('go1.13.7.linux-amd64.tar.gz'); expect(fileName).toBe('go1.13.7.linux-amd64.tar.gz');
}); });
@ -241,11 +212,11 @@ describe('setup-go', () => {
os.arch = 'x32'; os.arch = 'x32';
// spec: 1 => 1.13.7 (latest) // spec: 1 => 1.13.7 (latest)
const match: im.IGoVersion | undefined = await im.findMatch('1'); let match: im.IGoVersion | undefined = await im.findMatch('1');
expect(match).toBeDefined(); expect(match).toBeDefined();
const version: string = match ? match.version : ''; let version: string = match ? match.version : '';
expect(version).toBe('go1.13.7'); expect(version).toBe('go1.13.7');
const fileName = match ? match.files[0].filename : ''; let fileName = match ? match.files[0].filename : '';
expect(fileName).toBe('go1.13.7.windows-386.zip'); expect(fileName).toBe('go1.13.7.windows-386.zip');
}); });
@ -254,11 +225,11 @@ describe('setup-go', () => {
os.arch = 'x64'; os.arch = 'x64';
// spec: 1.14, stable=false => go1.14rc1 // spec: 1.14, stable=false => go1.14rc1
const match: im.IGoVersion | undefined = await im.findMatch('1.14.0-rc.1'); let match: im.IGoVersion | undefined = await im.findMatch('1.14.0-rc.1');
expect(match).toBeDefined(); expect(match).toBeDefined();
const version: string = match ? match.version : ''; let version: string = match ? match.version : '';
expect(version).toBe('go1.14rc1'); expect(version).toBe('go1.14rc1');
const fileName = match ? match.files[0].filename : ''; let fileName = match ? match.files[0].filename : '';
expect(fileName).toBe('go1.14rc1.linux-amd64.tar.gz'); expect(fileName).toBe('go1.14rc1.linux-amd64.tar.gz');
}); });
@ -266,7 +237,7 @@ describe('setup-go', () => {
inputs['go-version'] = '1.13.0'; inputs['go-version'] = '1.13.0';
inputs.stable = 'true'; inputs.stable = 'true';
const toolPath = path.normalize('/cache/go/1.13.0/x64'); let toolPath = path.normalize('/cache/go/1.13.0/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
await main.run(); await main.run();
@ -278,7 +249,7 @@ describe('setup-go', () => {
inSpy.mockImplementation(name => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const toolPath = path.normalize('/cache/go/1.13.0/x64'); let toolPath = path.normalize('/cache/go/1.13.0/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
await main.run(); await main.run();
@ -289,10 +260,10 @@ describe('setup-go', () => {
inputs['go-version'] = '1.13.0'; inputs['go-version'] = '1.13.0';
inSpy.mockImplementation(name => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const toolPath = path.normalize('/cache/go/1.13.0/x64'); let toolPath = path.normalize('/cache/go/1.13.0/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
const vars: {[key: string]: string} = {}; let vars: {[key: string]: string} = {};
exportVarSpy.mockImplementation((name: string, val: string) => { exportVarSpy.mockImplementation((name: string, val: string) => {
vars[name] = val; vars[name] = val;
}); });
@ -305,10 +276,10 @@ describe('setup-go', () => {
inputs['go-version'] = '1.8'; inputs['go-version'] = '1.8';
inSpy.mockImplementation(name => inputs[name]); inSpy.mockImplementation(name => inputs[name]);
const toolPath = path.normalize('/cache/go/1.8.0/x64'); let toolPath = path.normalize('/cache/go/1.8.0/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
const vars: {[key: string]: string} = {}; let vars: {[key: string]: string} = {};
exportVarSpy.mockImplementation((name: string, val: string) => { exportVarSpy.mockImplementation((name: string, val: string) => {
vars[name] = val; vars[name] = val;
}); });
@ -322,7 +293,7 @@ describe('setup-go', () => {
it('finds a version of go already in the cache', async () => { it('finds a version of go already in the cache', async () => {
inputs['go-version'] = '1.13.0'; inputs['go-version'] = '1.13.0';
const toolPath = path.normalize('/cache/go/1.13.0/x64'); let toolPath = path.normalize('/cache/go/1.13.0/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
await main.run(); await main.run();
@ -331,16 +302,16 @@ describe('setup-go', () => {
it('finds a version in the cache and adds it to the path', async () => { it('finds a version in the cache and adds it to the path', async () => {
inputs['go-version'] = '1.13.0'; inputs['go-version'] = '1.13.0';
const toolPath = path.normalize('/cache/go/1.13.0/x64'); let toolPath = path.normalize('/cache/go/1.13.0/x64');
findSpy.mockImplementation(() => toolPath); findSpy.mockImplementation(() => toolPath);
await main.run(); await main.run();
const expPath = path.join(toolPath, 'bin'); let expPath = path.join(toolPath, 'bin');
expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
}); });
it('handles unhandled error and reports error', async () => { it('handles unhandled error and reports error', async () => {
const errMsg = 'unhandled error message'; let errMsg = 'unhandled error message';
inputs['go-version'] = '1.13.0'; inputs['go-version'] = '1.13.0';
findSpy.mockImplementation(() => { findSpy.mockImplementation(() => {
@ -358,12 +329,12 @@ describe('setup-go', () => {
findSpy.mockImplementation(() => ''); findSpy.mockImplementation(() => '');
dlSpy.mockImplementation(() => '/some/temp/path'); dlSpy.mockImplementation(() => '/some/temp/path');
const toolPath = path.normalize('/cache/go/1.13.0/x64'); let toolPath = path.normalize('/cache/go/1.13.0/x64');
extractTarSpy.mockImplementation(() => '/some/other/temp/path'); extractTarSpy.mockImplementation(() => '/some/other/temp/path');
cacheSpy.mockImplementation(() => toolPath); cacheSpy.mockImplementation(() => toolPath);
await main.run(); await main.run();
const expPath = path.join(toolPath, 'bin'); let expPath = path.join(toolPath, 'bin');
expect(dlSpy).toHaveBeenCalled(); expect(dlSpy).toHaveBeenCalled();
expect(extractTarSpy).toHaveBeenCalled(); expect(extractTarSpy).toHaveBeenCalled();
@ -381,12 +352,12 @@ describe('setup-go', () => {
dlSpy.mockImplementation(() => 'C:\\temp\\some\\path'); dlSpy.mockImplementation(() => 'C:\\temp\\some\\path');
extractZipSpy.mockImplementation(() => 'C:\\temp\\some\\other\\path'); extractZipSpy.mockImplementation(() => 'C:\\temp\\some\\other\\path');
const toolPath = path.normalize('C:\\cache\\go\\1.13.0\\x64'); let toolPath = path.normalize('C:\\cache\\go\\1.13.0\\x64');
cacheSpy.mockImplementation(() => toolPath); cacheSpy.mockImplementation(() => toolPath);
await main.run(); await main.run();
const expPath = path.win32.join(toolPath, 'bin'); let expPath = path.win32.join(toolPath, 'bin');
expect(dlSpy).toHaveBeenCalledWith( expect(dlSpy).toHaveBeenCalledWith(
'https://storage.googleapis.com/golang/go1.13.1.windows-amd64.zip', 'https://storage.googleapis.com/golang/go1.13.1.windows-amd64.zip',
'C:\\temp\\go1.13.1.windows-amd64.zip', 'C:\\temp\\go1.13.1.windows-amd64.zip',
@ -413,25 +384,25 @@ describe('setup-go', () => {
os.platform = 'linux'; os.platform = 'linux';
os.arch = 'x64'; os.arch = 'x64';
const versionSpec = '1.12.16'; let versionSpec = '1.12.16';
inputs['go-version'] = versionSpec; inputs['go-version'] = versionSpec;
inputs['token'] = 'faketoken'; inputs['token'] = 'faketoken';
const expectedUrl = let expectedUrl =
'https://github.com/actions/go-versions/releases/download/1.12.16-20200616.20/go-1.12.16-linux-x64.tar.gz'; 'https://github.com/actions/go-versions/releases/download/1.12.16-20200616.20/go-1.12.16-linux-x64.tar.gz';
// ... but not in the local cache // ... but not in the local cache
findSpy.mockImplementation(() => ''); findSpy.mockImplementation(() => '');
dlSpy.mockImplementation(async () => '/some/temp/path'); dlSpy.mockImplementation(async () => '/some/temp/path');
const toolPath = path.normalize('/cache/go/1.12.16/x64'); let toolPath = path.normalize('/cache/go/1.12.16/x64');
extractTarSpy.mockImplementation(async () => '/some/other/temp/path'); extractTarSpy.mockImplementation(async () => '/some/other/temp/path');
cacheSpy.mockImplementation(async () => toolPath); cacheSpy.mockImplementation(async () => toolPath);
await main.run(); await main.run();
const expPath = path.join(toolPath, 'bin'); let expPath = path.join(toolPath, 'bin');
expect(dlSpy).toHaveBeenCalled(); expect(dlSpy).toHaveBeenCalled();
expect(extractTarSpy).toHaveBeenCalled(); expect(extractTarSpy).toHaveBeenCalled();
@ -450,25 +421,25 @@ describe('setup-go', () => {
os.platform = 'linux'; os.platform = 'linux';
os.arch = 'x64'; os.arch = 'x64';
const versionSpec = '1.12'; let versionSpec = '1.12';
inputs['go-version'] = versionSpec; inputs['go-version'] = versionSpec;
inputs['token'] = 'faketoken'; inputs['token'] = 'faketoken';
const expectedUrl = let expectedUrl =
'https://github.com/actions/go-versions/releases/download/1.12.17-20200616.21/go-1.12.17-linux-x64.tar.gz'; 'https://github.com/actions/go-versions/releases/download/1.12.17-20200616.21/go-1.12.17-linux-x64.tar.gz';
// ... but not in the local cache // ... but not in the local cache
findSpy.mockImplementation(() => ''); findSpy.mockImplementation(() => '');
dlSpy.mockImplementation(async () => '/some/temp/path'); dlSpy.mockImplementation(async () => '/some/temp/path');
const toolPath = path.normalize('/cache/go/1.12.17/x64'); let toolPath = path.normalize('/cache/go/1.12.17/x64');
extractTarSpy.mockImplementation(async () => '/some/other/temp/path'); extractTarSpy.mockImplementation(async () => '/some/other/temp/path');
cacheSpy.mockImplementation(async () => toolPath); cacheSpy.mockImplementation(async () => toolPath);
await main.run(); await main.run();
const expPath = path.join(toolPath, 'bin'); let expPath = path.join(toolPath, 'bin');
expect(dlSpy).toHaveBeenCalled(); expect(dlSpy).toHaveBeenCalled();
expect(extractTarSpy).toHaveBeenCalled(); expect(extractTarSpy).toHaveBeenCalled();
@ -487,7 +458,7 @@ describe('setup-go', () => {
os.platform = 'linux'; os.platform = 'linux';
os.arch = 'x64'; os.arch = 'x64';
const versionSpec = '1.12.14'; let versionSpec = '1.12.14';
inputs['go-version'] = versionSpec; inputs['go-version'] = versionSpec;
inputs['token'] = 'faketoken'; inputs['token'] = 'faketoken';
@ -496,13 +467,13 @@ describe('setup-go', () => {
findSpy.mockImplementation(() => ''); findSpy.mockImplementation(() => '');
dlSpy.mockImplementation(async () => '/some/temp/path'); dlSpy.mockImplementation(async () => '/some/temp/path');
const toolPath = path.normalize('/cache/go/1.12.14/x64'); let toolPath = path.normalize('/cache/go/1.12.14/x64');
extractTarSpy.mockImplementation(async () => '/some/other/temp/path'); extractTarSpy.mockImplementation(async () => '/some/other/temp/path');
cacheSpy.mockImplementation(async () => toolPath); cacheSpy.mockImplementation(async () => toolPath);
await main.run(); await main.run();
const expPath = path.join(toolPath, 'bin'); let expPath = path.join(toolPath, 'bin');
expect(logSpy).toHaveBeenCalledWith('Setup go version spec 1.12.14'); expect(logSpy).toHaveBeenCalledWith('Setup go version spec 1.12.14');
expect(findSpy).toHaveBeenCalled(); expect(findSpy).toHaveBeenCalled();
expect(logSpy).toHaveBeenCalledWith('Attempting to download 1.12.14...'); expect(logSpy).toHaveBeenCalledWith('Attempting to download 1.12.14...');
@ -518,7 +489,7 @@ describe('setup-go', () => {
}); });
it('reports a failed download', async () => { it('reports a failed download', async () => {
const errMsg = 'unhandled download message'; let errMsg = 'unhandled download message';
os.platform = 'linux'; os.platform = 'linux';
os.arch = 'x64'; os.arch = 'x64';
@ -539,7 +510,7 @@ describe('setup-go', () => {
whichSpy.mockImplementation(async () => { whichSpy.mockImplementation(async () => {
return ''; return '';
}); });
const added = await main.addBinToPath(); let added = await main.addBinToPath();
expect(added).toBeFalsy(); expect(added).toBeFalsy();
}); });
@ -557,8 +528,8 @@ describe('setup-go', () => {
return false; return false;
}); });
const added = await main.addBinToPath(); let added = await main.addBinToPath();
expect(added).toBeTruthy(); expect(added).toBeTruthy;
}); });
interface Annotation { interface Annotation {
@ -572,9 +543,9 @@ describe('setup-go', () => {
// problem matcher regex pattern tests // problem matcher regex pattern tests
function testMatch(line: string): Annotation { function testMatch(line: string): Annotation {
const annotation = <Annotation>{}; let annotation = <Annotation>{};
const match = matcherRegExp.exec(line); let match = matcherRegExp.exec(line);
if (match) { if (match) {
annotation.line = parseInt(match[matcherPattern.line], 10); annotation.line = parseInt(match[matcherPattern.line], 10);
annotation.column = parseInt(match[matcherPattern.column], 10); annotation.column = parseInt(match[matcherPattern.column], 10);
@ -586,8 +557,8 @@ describe('setup-go', () => {
} }
it('matches on relative unix path', async () => { it('matches on relative unix path', async () => {
const line = './main.go:13:2: undefined: fmt.Printl'; let line = './main.go:13:2: undefined: fmt.Printl';
const annotation = testMatch(line); let annotation = testMatch(line);
expect(annotation).toBeDefined(); expect(annotation).toBeDefined();
expect(annotation.line).toBe(13); expect(annotation.line).toBe(13);
expect(annotation.column).toBe(2); expect(annotation.column).toBe(2);
@ -596,8 +567,8 @@ describe('setup-go', () => {
}); });
it('matches on unix path up the tree', async () => { it('matches on unix path up the tree', async () => {
const line = '../main.go:13:2: undefined: fmt.Printl'; let line = '../main.go:13:2: undefined: fmt.Printl';
const annotation = testMatch(line); let annotation = testMatch(line);
expect(annotation).toBeDefined(); expect(annotation).toBeDefined();
expect(annotation.line).toBe(13); expect(annotation.line).toBe(13);
expect(annotation.column).toBe(2); expect(annotation.column).toBe(2);
@ -606,8 +577,8 @@ describe('setup-go', () => {
}); });
it('matches on unix path down the tree', async () => { it('matches on unix path down the tree', async () => {
const line = 'foo/main.go:13:2: undefined: fmt.Printl'; let line = 'foo/main.go:13:2: undefined: fmt.Printl';
const annotation = testMatch(line); let annotation = testMatch(line);
expect(annotation).toBeDefined(); expect(annotation).toBeDefined();
expect(annotation.line).toBe(13); expect(annotation.line).toBe(13);
expect(annotation.column).toBe(2); expect(annotation.column).toBe(2);
@ -616,8 +587,8 @@ describe('setup-go', () => {
}); });
it('matches on rooted unix path', async () => { it('matches on rooted unix path', async () => {
const line = '/assert.go:4:1: missing return at end of function'; let line = '/assert.go:4:1: missing return at end of function';
const annotation = testMatch(line); let annotation = testMatch(line);
expect(annotation).toBeDefined(); expect(annotation).toBeDefined();
expect(annotation.line).toBe(4); expect(annotation.line).toBe(4);
expect(annotation.column).toBe(1); expect(annotation.column).toBe(1);
@ -626,8 +597,8 @@ describe('setup-go', () => {
}); });
it('matches on unix path with spaces', async () => { it('matches on unix path with spaces', async () => {
const line = ' ./assert.go:5:2: missing return at end of function '; let line = ' ./assert.go:5:2: missing return at end of function ';
const annotation = testMatch(line); let annotation = testMatch(line);
expect(annotation).toBeDefined(); expect(annotation).toBeDefined();
expect(annotation.line).toBe(5); expect(annotation.line).toBe(5);
expect(annotation.column).toBe(2); expect(annotation.column).toBe(2);
@ -636,8 +607,8 @@ describe('setup-go', () => {
}); });
it('matches on unix path with tabs', async () => { it('matches on unix path with tabs', async () => {
const line = '\t./assert.go:5:2: missing return at end of function '; let line = '\t./assert.go:5:2: missing return at end of function ';
const annotation = testMatch(line); let annotation = testMatch(line);
expect(annotation).toBeDefined(); expect(annotation).toBeDefined();
expect(annotation.line).toBe(5); expect(annotation.line).toBe(5);
expect(annotation.column).toBe(2); expect(annotation.column).toBe(2);
@ -646,8 +617,8 @@ describe('setup-go', () => {
}); });
it('matches on relative windows path', async () => { it('matches on relative windows path', async () => {
const line = '.\\main.go:13:2: undefined: fmt.Printl'; let line = '.\\main.go:13:2: undefined: fmt.Printl';
const annotation = testMatch(line); let annotation = testMatch(line);
expect(annotation).toBeDefined(); expect(annotation).toBeDefined();
expect(annotation.line).toBe(13); expect(annotation.line).toBe(13);
expect(annotation.column).toBe(2); expect(annotation.column).toBe(2);
@ -656,8 +627,8 @@ describe('setup-go', () => {
}); });
it('matches on windows path up the tree', async () => { it('matches on windows path up the tree', async () => {
const line = '..\\main.go:13:2: undefined: fmt.Printl'; let line = '..\\main.go:13:2: undefined: fmt.Printl';
const annotation = testMatch(line); let annotation = testMatch(line);
expect(annotation).toBeDefined(); expect(annotation).toBeDefined();
expect(annotation.line).toBe(13); expect(annotation.line).toBe(13);
expect(annotation.column).toBe(2); expect(annotation.column).toBe(2);
@ -759,7 +730,7 @@ describe('setup-go', () => {
os.platform = 'linux'; os.platform = 'linux';
os.arch = 'x64'; os.arch = 'x64';
const versionSpec = '1.13'; let versionSpec = '1.13';
inputs['go-version'] = versionSpec; inputs['go-version'] = versionSpec;
inputs['check-latest'] = true; inputs['check-latest'] = true;
@ -770,13 +741,13 @@ describe('setup-go', () => {
findSpy.mockImplementation(() => ''); findSpy.mockImplementation(() => '');
dlSpy.mockImplementation(async () => '/some/temp/path'); dlSpy.mockImplementation(async () => '/some/temp/path');
const toolPath = path.normalize('/cache/go/1.13.7/x64'); let toolPath = path.normalize('/cache/go/1.13.7/x64');
extractTarSpy.mockImplementation(async () => '/some/other/temp/path'); extractTarSpy.mockImplementation(async () => '/some/other/temp/path');
cacheSpy.mockImplementation(async () => toolPath); cacheSpy.mockImplementation(async () => toolPath);
await main.run(); await main.run();
const expPath = path.join(toolPath, 'bin'); let expPath = path.join(toolPath, 'bin');
expect(dlSpy).toHaveBeenCalled(); expect(dlSpy).toHaveBeenCalled();
expect(extractTarSpy).toHaveBeenCalled(); expect(extractTarSpy).toHaveBeenCalled();
@ -796,7 +767,7 @@ describe('setup-go', () => {
os.platform = 'linux'; os.platform = 'linux';
os.arch = 'x64'; os.arch = 'x64';
const versionSpec = '1.13'; let versionSpec = '1.13';
process.env['GITHUB_PATH'] = ''; process.env['GITHUB_PATH'] = '';
@ -810,19 +781,16 @@ describe('setup-go', () => {
getManifestSpy.mockImplementation(() => { getManifestSpy.mockImplementation(() => {
throw new Error('Unable to download manifest'); throw new Error('Unable to download manifest');
}); });
httpmGetJsonSpy.mockRejectedValue(
new Error('Unable to download manifest from raw URL')
);
getAllVersionsSpy.mockImplementationOnce(() => undefined); getAllVersionsSpy.mockImplementationOnce(() => undefined);
dlSpy.mockImplementation(async () => '/some/temp/path'); dlSpy.mockImplementation(async () => '/some/temp/path');
const toolPath = path.normalize('/cache/go/1.13.7/x64'); let toolPath = path.normalize('/cache/go/1.13.7/x64');
extractTarSpy.mockImplementation(async () => '/some/other/temp/path'); extractTarSpy.mockImplementation(async () => '/some/other/temp/path');
cacheSpy.mockImplementation(async () => toolPath); cacheSpy.mockImplementation(async () => toolPath);
await main.run(); await main.run();
const expPath = path.join(toolPath, 'bin'); let expPath = path.join(toolPath, 'bin');
expect(logSpy).toHaveBeenCalledWith( expect(logSpy).toHaveBeenCalledWith(
`Failed to resolve version ${versionSpec} from manifest` `Failed to resolve version ${versionSpec} from manifest`
@ -942,7 +910,7 @@ use .
inputs['go-version'] = version; inputs['go-version'] = version;
inputs['architecture'] = arch; inputs['architecture'] = arch;
const expectedUrl = let expectedUrl =
platform === 'win32' platform === 'win32'
? `https://github.com/actions/go-versions/releases/download/${version}/go-${version}-${platform}-${arch}.${fileExtension}` ? `https://github.com/actions/go-versions/releases/download/${version}/go-${version}-${platform}-${arch}.${fileExtension}`
: `https://storage.googleapis.com/golang/go${version}.${osSpec}-${arch}.${fileExtension}`; : `https://storage.googleapis.com/golang/go${version}.${osSpec}-${arch}.${fileExtension}`;
@ -951,7 +919,7 @@ use .
findSpy.mockImplementation(() => ''); findSpy.mockImplementation(() => '');
dlSpy.mockImplementation(async () => '/some/temp/path'); dlSpy.mockImplementation(async () => '/some/temp/path');
const toolPath = path.normalize(`/cache/go/${version}/${arch}`); let toolPath = path.normalize(`/cache/go/${version}/${arch}`);
cacheSpy.mockImplementation(async () => toolPath); cacheSpy.mockImplementation(async () => toolPath);
await main.run(); await main.run();
@ -976,7 +944,7 @@ use .
findSpy.mockImplementation(() => ''); findSpy.mockImplementation(() => '');
dlSpy.mockImplementation(async () => '/some/temp/path'); dlSpy.mockImplementation(async () => '/some/temp/path');
const toolPath = path.normalize(`/cache/go/${alias}/${arch}`); let toolPath = path.normalize(`/cache/go/${alias}/${arch}`);
cacheSpy.mockImplementation(async () => toolPath); cacheSpy.mockImplementation(async () => toolPath);
await main.run(); await main.run();

View File

@ -1,52 +0,0 @@
import {isSelfHosted} from '../src/utils';
describe('utils', () => {
describe('isSelfHosted', () => {
let AGENT_ISSELFHOSTED: string | undefined;
let RUNNER_ENVIRONMENT: string | undefined;
beforeEach(() => {
AGENT_ISSELFHOSTED = process.env['AGENT_ISSELFHOSTED'];
delete process.env['AGENT_ISSELFHOSTED'];
RUNNER_ENVIRONMENT = process.env['RUNNER_ENVIRONMENT'];
delete process.env['RUNNER_ENVIRONMENT'];
});
afterEach(() => {
if (AGENT_ISSELFHOSTED === undefined) {
delete process.env['AGENT_ISSELFHOSTED'];
} else {
process.env['AGENT_ISSELFHOSTED'] = AGENT_ISSELFHOSTED;
}
if (RUNNER_ENVIRONMENT === undefined) {
delete process.env['RUNNER_ENVIRONMENT'];
} else {
process.env['RUNNER_ENVIRONMENT'] = RUNNER_ENVIRONMENT;
}
});
it('isSelfHosted should be true if no environment variables set', () => {
expect(isSelfHosted()).toBeTruthy();
});
it('isSelfHosted should be true if environment variable is not set to denote GitHub hosted', () => {
process.env['RUNNER_ENVIRONMENT'] = 'some';
expect(isSelfHosted()).toBeTruthy();
});
it('isSelfHosted should be true if environment variable set to denote Azure Pipelines self hosted', () => {
process.env['AGENT_ISSELFHOSTED'] = '1';
expect(isSelfHosted()).toBeTruthy();
});
it('isSelfHosted should be false if environment variable set to denote GitHub hosted', () => {
process.env['RUNNER_ENVIRONMENT'] = 'github-hosted';
expect(isSelfHosted()).toBeFalsy();
});
it('isSelfHosted should be false if environment variable is not set to denote Azure Pipelines self hosted', () => {
process.env['AGENT_ISSELFHOSTED'] = 'some';
expect(isSelfHosted()).toBeFalsy();
});
});
});

View File

@ -1,62 +0,0 @@
import fs from 'fs';
import * as io from '@actions/io';
import * as tc from '@actions/tool-cache';
import path from 'path';
describe('Windows performance workaround', () => {
let mkdirSpy: jest.SpyInstance;
let symlinkSpy: jest.SpyInstance;
let statSpy: jest.SpyInstance;
let readdirSpy: jest.SpyInstance;
let writeFileSpy: jest.SpyInstance;
let rmRFSpy: jest.SpyInstance;
let mkdirPSpy: jest.SpyInstance;
let cpSpy: jest.SpyInstance;
let runnerToolCache: string | undefined;
beforeEach(() => {
mkdirSpy = jest.spyOn(fs, 'mkdir');
symlinkSpy = jest.spyOn(fs, 'symlinkSync');
statSpy = jest.spyOn(fs, 'statSync');
readdirSpy = jest.spyOn(fs, 'readdirSync');
writeFileSpy = jest.spyOn(fs, 'writeFileSync');
rmRFSpy = jest.spyOn(io, 'rmRF');
mkdirPSpy = jest.spyOn(io, 'mkdirP');
cpSpy = jest.spyOn(io, 'cp');
// default implementations
// @ts-ignore - not implement unused methods
statSpy.mockImplementation(() => ({
isDirectory: () => true
}));
readdirSpy.mockImplementation(() => []);
writeFileSpy.mockImplementation(() => {});
mkdirSpy.mockImplementation(() => {});
symlinkSpy.mockImplementation(() => {});
rmRFSpy.mockImplementation(() => Promise.resolve());
mkdirPSpy.mockImplementation(() => Promise.resolve());
cpSpy.mockImplementation(() => Promise.resolve());
runnerToolCache = process.env['RUNNER_TOOL_CACHE'];
});
afterEach(() => {
jest.clearAllMocks();
process.env['RUNNER_TOOL_CACHE'] = runnerToolCache;
});
// cacheWindowsToolkitDir depends on implementation of tc.cacheDir
// with the assumption that target dir is passed by RUNNER_TOOL_CACHE environment variable
// Make sure the implementation has not been changed
it('addExecutablesToCache should depend on env[RUNNER_TOOL_CACHE]', async () => {
process.env['RUNNER_TOOL_CACHE'] = '/faked-hostedtoolcache1';
const cacheDir1 = await tc.cacheDir('/qzx', 'go', '1.2.3', 'arch');
expect(cacheDir1).toBe(
path.join('/', 'faked-hostedtoolcache1', 'go', '1.2.3', 'arch')
);
process.env['RUNNER_TOOL_CACHE'] = '/faked-hostedtoolcache2';
const cacheDir2 = await tc.cacheDir('/qzx', 'go', '1.2.3', 'arch');
expect(cacheDir2).toBe(
path.join('/', 'faked-hostedtoolcache2', 'go', '1.2.3', 'arch')
);
});
});

View File

@ -3,18 +3,18 @@ description: 'Setup a Go environment and add it to the PATH'
author: 'GitHub' author: 'GitHub'
inputs: inputs:
go-version: go-version:
description: 'The Go version to download (if necessary) and use. Supports semver spec and ranges. Be sure to enclose this option in single quotation marks.' description: 'The Go version to download (if necessary) and use. Supports semver spec and ranges.'
go-version-file: go-version-file:
description: 'Path to the go.mod or go.work file.' description: 'Path to the go.mod or go.work file.'
check-latest: check-latest:
description: 'Set this option to true if you want the action to always check for the latest available version that satisfies the version spec' description: 'Set this option to true if you want the action to always check for the latest available version that satisfies the version spec'
default: false default: false
token: token:
description: Used to pull Go distributions from go-versions. Since there's a default, this is typically not supplied by the user. When running this action on github.com, the default value is sufficient. When running on GHES, you can pass a personal access token for github.com if you are experiencing rate limiting. description: Used to pull node distributions from go-versions. Since there's a default, this is typically not supplied by the user. When running this action on github.com, the default value is sufficient. When running on GHES, you can pass a personal access token for github.com if you are experiencing rate limiting.
default: ${{ github.server_url == 'https://github.com' && github.token || '' }} default: ${{ github.server_url == 'https://github.com' && github.token || '' }}
cache: cache:
description: Used to specify whether caching is needed. Set to true, if you'd like to enable caching. description: Used to specify whether caching is needed. Set to true, if you'd like to enable caching.
default: true default: false
cache-dependency-path: cache-dependency-path:
description: 'Used to specify the path to a dependency file - go.sum' description: 'Used to specify the path to a dependency file - go.sum'
architecture: architecture:
@ -25,7 +25,7 @@ outputs:
cache-hit: cache-hit:
description: 'A boolean value to indicate if a cache was hit' description: 'A boolean value to indicate if a cache was hit'
runs: runs:
using: 'node20' using: 'node16'
main: 'dist/setup/index.js' main: 'dist/setup/index.js'
post: 'dist/cache-save/index.js' post: 'dist/cache-save/index.js'
post-if: success() post-if: success()

68710
dist/cache-save/index.js vendored

File diff suppressed because one or more lines are too long

72933
dist/setup/index.js vendored

File diff suppressed because one or more lines are too long

View File

@ -4,7 +4,7 @@ Date: 2022-04-13
Status: Accepted Status: Accepted
# Context # Context
`actions/setup-go` is the one of the most popular action related to Golang in GitHub Actions. Many customers use it in conjunction with [actions/cache](https://github.com/actions/cache) to speed up dependency installation process. `actions/setup-go` is the one of the most popular action related to Golang in GitHub Actions. Many customers use it in conjunction with [actions/cache](https://github.com/actions/cache) to speed up dependency installation process.
See more examples on proper usage in [actions/cache documentation](https://github.com/actions/cache/blob/main/examples.md#go---modules). See more examples on proper usage in [actions/cache documentation](https://github.com/actions/cache/blob/main/examples.md#go---modules).
# Goals & Anti-Goals # Goals & Anti-Goals
@ -16,7 +16,7 @@ Integration of caching functionality into `actions/setup-go` action will bring t
We don't pursue the goal to provide wide customization of caching in scope of `actions/setup-go` action. The purpose of this integration is covering ~90% of basic use-cases. If user needs flexible customization, we should advice them to use `actions/cache` directly. We don't pursue the goal to provide wide customization of caching in scope of `actions/setup-go` action. The purpose of this integration is covering ~90% of basic use-cases. If user needs flexible customization, we should advice them to use `actions/cache` directly.
# Decision # Decision
- Add `cache` input parameter to `actions/setup-go`. For now, input will accept the following values: - Add `cache` input parameter to `actions/setup-go`. For now, input will accept the following values:
- `true` - enable caching for go dependencies - `true` - enable caching for go dependencies
- `false`- disable caching for go dependencies. This value will be set as default value - `false`- disable caching for go dependencies. This value will be set as default value
- Cache feature will be disabled by default to make sure that we don't break existing customers. We will consider enabling cache by default in next major releases - Cache feature will be disabled by default to make sure that we don't break existing customers. We will consider enabling cache by default in next major releases
@ -32,7 +32,7 @@ We don't pursue the goal to provide wide customization of caching in scope of `a
```yml ```yml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v3 - uses: actions/setup-go@v3
with: with:
go-version: '18' go-version: '18'
@ -43,7 +43,7 @@ steps:
```yml ```yml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v3 - uses: actions/setup-go@v3
with: with:
go-version: '18' go-version: '18'
@ -53,7 +53,7 @@ steps:
```yml ```yml
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- uses: actions/setup-go@v3 - uses: actions/setup-go@v3
with: with:
go-version: '18' go-version: '18'
@ -66,4 +66,4 @@ steps:
# Release process # Release process
As soon as functionality is implemented, we will release minor update of action. No need to bump major version since there are no breaking changes for existing users. As soon as functionality is implemented, we will release minor update of action. No need to bump major version since there are no breaking changes for existing users.
After that, we will update [starter-workflows](https://github.com/actions/starter-workflows/blob/main/ci/go.yml) After that, we will update [starter-workflows](https://github.com/actions/starter-workflows/blob/main/ci/go.yml)

View File

@ -6,13 +6,13 @@ We have prepared a short guide so that the process of making your contribution i
## How can I contribute... ## How can I contribute...
* [Contribute Documentation :green_book:](#contribute-documentation) * [Contribute Documentation:green_book:](#contribute-documentation)
* [Contribute Code :computer:](#contribute-code) * [Contribute Code :computer:](#contribute-code)
* [Provide Support on Issues :pencil:](#provide-support-on-issues) * [Provide Support on Issues:pencil:](#provide-support-on-issues)
* [Review Pull Requests :mag:](#review-pull-requests) * [Review Pull Requests:mag:](#review-pull-requests)
## Contribute documentation ## Contribute documentation
@ -52,7 +52,7 @@ Pull requests are the easiest way to contribute changes to git repos at GitHub.
- Please check that no one else has already created a pull request with these changes - Please check that no one else has already created a pull request with these changes
- Use a "feature branch" for your changes. That separates the changes in the pull request from your other changes and makes it easy to edit/amend commits in the pull request - Use a "feature branch" for your changes. That separates the changes in the pull request from your other changes and makes it easy to edit/amend commits in the pull request
- **Run `pre-checkin` script to format, lint, build and test changes** - **Run `pre-checkin` script to format, build and test changes**
- Make sure your changes are well formatted and that all tests are passing - Make sure your changes are well formatted and that all tests are passing
- If your pull request is connected to an open issue, please, leave a link to this issue in the `Related issue:` section - If your pull request is connected to an open issue, please, leave a link to this issue in the `Related issue:` section
- If you later need to add new commits to the pull request, you can simply commit the changes to the local branch and then push them. The pull request gets automatically updated - If you later need to add new commits to the pull request, you can simply commit the changes to the local branch and then push them. The pull request gets automatically updated
@ -61,7 +61,6 @@ Pull requests are the easiest way to contribute changes to git repos at GitHub.
- To implement new features or fix bugs, you need to make changes to the `.ts` files, which are located in the `src` folder - To implement new features or fix bugs, you need to make changes to the `.ts` files, which are located in the `src` folder
- To comply with the code style, **you need to run the `format` script** - To comply with the code style, **you need to run the `format` script**
- To lint the code, **you need to run the `lint:fix` script**
- To transpile source code to `javascript` we use [NCC](https://github.com/vercel/ncc). **It is very important to run the `build` script after making changes**, otherwise your changes will not get into the final `javascript` build - To transpile source code to `javascript` we use [NCC](https://github.com/vercel/ncc). **It is very important to run the `build` script after making changes**, otherwise your changes will not get into the final `javascript` build
- You can also start formatting, building code, and testing with a single `pre-checkin` command - You can also start formatting, building code, and testing with a single `pre-checkin` command
@ -113,4 +112,4 @@ Another great way to contribute is pull request reviews. Please, be extra kind:
- Make sure you're familiar with the code or documentation is updated, unless it's a minor change (spellchecking, minor formatting, etc.) - Make sure you're familiar with the code or documentation is updated, unless it's a minor change (spellchecking, minor formatting, etc.)
- Review changes using the GitHub functionality. You can ask a clarifying question, point out an error or suggest an alternative. - Review changes using the GitHub functionality. You can ask a clarifying question, point out an error or suggest an alternative.
> Note: You may ask for minor changes - "nitpicks", but consider whether they are real blockers to merging or not > Note: You may ask for minor changes - "nitpicks", but consider whether they are real blockers to merging or not
- Submit your review, which may include comments, an approval, or a changes request - Submit your review, which may include comments, an approval, or a changes request

8291
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +1,15 @@
{ {
"name": "setup-go", "name": "setup-go",
"version": "5.0.0", "version": "3.3.0",
"private": true, "private": true,
"description": "setup go action", "description": "setup go action",
"main": "lib/setup-go.js", "main": "lib/setup-go.js",
"scripts": { "scripts": {
"build": "tsc && ncc build -o dist/setup src/setup-go.ts && ncc build -o dist/cache-save src/cache-save.ts", "build": "tsc && ncc build -o dist/setup src/setup-go.ts && ncc build -o dist/cache-save src/cache-save.ts",
"format": "prettier --no-error-on-unmatched-pattern --config ./.prettierrc.js --write \"**/*.{ts,yml,yaml}\"", "format": "prettier --write **/*.ts",
"format-check": "prettier --no-error-on-unmatched-pattern --config ./.prettierrc.js --check \"**/*.{ts,yml,yaml}\"", "format-check": "prettier --check **/*.ts",
"lint": "eslint --config ./.eslintrc.js \"**/*.ts\"",
"lint:fix": "eslint --config ./.eslintrc.js \"**/*.ts\" --fix",
"test": "jest --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 build && npm test"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@ -26,30 +24,24 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/cache": "^4.0.3", "@actions/cache": "^4.0.3",
"@actions/core": "^1.11.1", "@actions/core": "^1.10.0",
"@actions/exec": "^1.1.1", "@actions/exec": "^1.1.0",
"@actions/glob": "^0.4.0", "@actions/glob": "^0.2.0",
"@actions/http-client": "^2.2.1", "@actions/http-client": "^2.0.1",
"@actions/io": "^1.0.2", "@actions/io": "^1.0.2",
"@actions/tool-cache": "^2.0.1", "@actions/tool-cache": "^1.5.5",
"semver": "^7.6.3" "semver": "^6.1.1"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "^29.5.12", "@types/jest": "^27.0.2",
"@types/node": "^20.11.28", "@types/node": "^16.11.25",
"@types/semver": "^7.5.8", "@types/semver": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^5.54.0", "@vercel/ncc": "^0.33.4",
"@typescript-eslint/parser": "^5.54.0", "jest": "^27.2.5",
"@vercel/ncc": "^0.38.1", "jest-circus": "^27.2.5",
"eslint": "^8.57.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-jest": "^27.9.0",
"eslint-plugin-node": "^11.1.0",
"jest": "^29.7.0",
"jest-circus": "^29.7.0",
"nock": "^10.0.6", "nock": "^10.0.6",
"prettier": "^2.8.4", "prettier": "^1.17.1",
"ts-jest": "^29.1.2", "ts-jest": "^27.0.5",
"typescript": "^5.4.2" "typescript": "^4.3.3"
} }
} }

View File

@ -15,7 +15,6 @@ export const restoreCache = async (
) => { ) => {
const packageManagerInfo = await getPackageManagerInfo(packageManager); const packageManagerInfo = await getPackageManagerInfo(packageManager);
const platform = process.env.RUNNER_OS; const platform = process.env.RUNNER_OS;
const arch = process.arch;
const cachePaths = await getCacheDirectoryPath(packageManagerInfo); const cachePaths = await getCacheDirectoryPath(packageManagerInfo);
@ -30,9 +29,7 @@ export const restoreCache = async (
); );
} }
const linuxVersion = const primaryKey = `setup-go-${platform}-go-${versionSpec}-${fileHash}`;
process.env.RUNNER_OS === 'Linux' ? `${process.env.ImageOS}-` : '';
const primaryKey = `setup-go-${platform}-${arch}-${linuxVersion}go-${versionSpec}-${fileHash}`;
core.debug(`primary key is ${primaryKey}`); core.debug(`primary key is ${primaryKey}`);
core.saveState(State.CachePrimaryKey, primaryKey); core.saveState(State.CachePrimaryKey, primaryKey);
@ -51,7 +48,7 @@ export const restoreCache = async (
}; };
const findDependencyFile = (packageManager: PackageManagerInfo) => { const findDependencyFile = (packageManager: PackageManagerInfo) => {
const dependencyFile = packageManager.dependencyFilePattern; let dependencyFile = packageManager.dependencyFilePattern;
const workspace = process.env.GITHUB_WORKSPACE!; const workspace = process.env.GITHUB_WORKSPACE!;
const rootContent = fs.readdirSync(workspace); const rootContent = fs.readdirSync(workspace);

View File

@ -12,19 +12,9 @@ process.on('uncaughtException', e => {
core.info(`${warningPrefix}${e.message}`); core.info(`${warningPrefix}${e.message}`);
}); });
// Added early exit to resolve issue with slow post action step: export async function run() {
// - https://github.com/actions/setup-node/issues/878
// https://github.com/actions/cache/pull/1217
export async function run(earlyExit?: boolean) {
try { try {
const cacheInput = core.getBooleanInput('cache'); await cachePackages();
if (cacheInput) {
await cachePackages();
if (earlyExit) {
process.exit(0);
}
}
} catch (error) { } catch (error) {
let message = 'Unknown error!'; let message = 'Unknown error!';
if (error instanceof Error) { if (error instanceof Error) {
@ -33,11 +23,16 @@ export async function run(earlyExit?: boolean) {
if (typeof error === 'string') { if (typeof error === 'string') {
message = error; message = error;
} }
core.warning(message); core.setFailed(message);
} }
} }
const cachePackages = async () => { const cachePackages = async () => {
const cacheInput = core.getBooleanInput('cache');
if (!cacheInput) {
return;
}
const packageManager = 'default'; const packageManager = 'default';
const state = core.getState(State.CacheMatchedKey); const state = core.getState(State.CacheMatchedKey);
@ -64,13 +59,6 @@ const cachePackages = async () => {
); );
} }
if (!primaryKey) {
core.info(
'Primary key was not generated. Please check the log messages above for more errors or information'
);
return;
}
if (primaryKey === state) { if (primaryKey === state) {
core.info( core.info(
`Cache hit occurred on the primary key ${primaryKey}, not saving cache.` `Cache hit occurred on the primary key ${primaryKey}, not saving cache.`
@ -90,4 +78,4 @@ function logWarning(message: string): void {
core.info(`${warningPrefix}${message}`); core.info(`${warningPrefix}${message}`);
} }
run(true); run();

View File

@ -34,58 +34,42 @@ export const getPackageManagerInfo = async (packageManager: string) => {
export const getCacheDirectoryPath = async ( export const getCacheDirectoryPath = async (
packageManagerInfo: PackageManagerInfo packageManagerInfo: PackageManagerInfo
) => { ) => {
const pathOutputs = await Promise.allSettled( let pathList = await Promise.all(
packageManagerInfo.cacheFolderCommandList.map(async command => packageManagerInfo.cacheFolderCommandList.map(command =>
getCommandOutput(command) getCommandOutput(command)
) )
); );
const results = pathOutputs.map(item => { const emptyPaths = pathList.filter(item => !item);
if (item.status === 'fulfilled') {
return item.value;
} else {
core.info(`[warning]getting cache directory path failed: ${item.reason}`);
}
return ''; if (emptyPaths.length) {
});
const cachePaths = results.filter(item => item);
if (!cachePaths.length) {
throw new Error(`Could not get cache folder paths.`); throw new Error(`Could not get cache folder paths.`);
} }
return cachePaths; return pathList;
}; };
export function isGhes(): boolean { export function isGhes(): boolean {
const ghUrl = new URL( const ghUrl = new URL(
process.env['GITHUB_SERVER_URL'] || 'https://github.com' process.env['GITHUB_SERVER_URL'] || 'https://github.com'
); );
return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM';
const hostname = ghUrl.hostname.trimEnd().toUpperCase();
const isGitHubHost = hostname === 'GITHUB.COM';
const isGitHubEnterpriseCloudHost = hostname.endsWith('.GHE.COM');
const isLocalHost = hostname.endsWith('.LOCALHOST');
return !isGitHubHost && !isGitHubEnterpriseCloudHost && !isLocalHost;
} }
export function isCacheFeatureAvailable(): boolean { export function isCacheFeatureAvailable(): boolean {
if (cache.isFeatureAvailable()) { if (!cache.isFeatureAvailable()) {
return true; if (isGhes()) {
} throw new Error(
'Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'
);
} else {
core.warning(
'The runner was not able to contact the cache service. Caching will be skipped'
);
}
if (isGhes()) {
core.warning(
'Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'
);
return false; return false;
} }
core.warning( return true;
'The runner was not able to contact the cache service. Caching will be skipped'
);
return false;
} }

View File

@ -6,12 +6,7 @@ import * as httpm from '@actions/http-client';
import * as sys from './system'; import * as sys from './system';
import fs from 'fs'; import fs from 'fs';
import os from 'os'; import os from 'os';
import {StableReleaseAlias, isSelfHosted} from './utils'; import {StableReleaseAlias} from './utils';
const MANIFEST_REPO_OWNER = 'actions';
const MANIFEST_REPO_NAME = 'go-versions';
const MANIFEST_REPO_BRANCH = 'main';
const MANIFEST_URL = `https://raw.githubusercontent.com/${MANIFEST_REPO_OWNER}/${MANIFEST_REPO_NAME}/${MANIFEST_REPO_BRANCH}/versions-manifest.json`;
type InstallationType = 'dist' | 'manifest'; type InstallationType = 'dist' | 'manifest';
@ -42,7 +37,7 @@ export async function getGo(
arch = os.arch() arch = os.arch()
) { ) {
let manifest: tc.IToolRelease[] | undefined; let manifest: tc.IToolRelease[] | undefined;
const osPlat: string = os.platform(); let osPlat: string = os.platform();
if ( if (
versionSpec === StableReleaseAlias.Stable || versionSpec === StableReleaseAlias.Stable ||
@ -88,7 +83,8 @@ export async function getGo(
} }
// check cache // check cache
const toolPath = tc.find('go', versionSpec, arch); let toolPath: string;
toolPath = tc.find('go', versionSpec, arch);
// If not found in cache, download // If not found in cache, download
if (toolPath) { if (toolPath) {
core.info(`Found in cache @ ${toolPath}`); core.info(`Found in cache @ ${toolPath}`);
@ -119,9 +115,9 @@ export async function getGo(
`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded` `Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`
); );
} else { } else {
core.info((err as Error).message); core.info(err.message);
} }
core.debug((err as Error).stack ?? ''); core.debug(err.stack);
core.info('Falling back to download directly from Go'); core.info('Falling back to download directly from Go');
} }
@ -165,75 +161,10 @@ async function resolveVersionFromManifest(
return info?.resolvedVersion; return info?.resolvedVersion;
} catch (err) { } catch (err) {
core.info('Unable to resolve a version from the manifest...'); core.info('Unable to resolve a version from the manifest...');
core.debug((err as Error).message); core.debug(err.message);
} }
} }
// for github hosted windows runner handle latency of OS drive
// by avoiding write operations to C:
async function cacheWindowsDir(
extPath: string,
tool: string,
version: string,
arch: string
): Promise<string | false> {
if (os.platform() !== 'win32') return false;
// make sure the action runs in the hosted environment
if (isSelfHosted()) return false;
const defaultToolCacheRoot = process.env['RUNNER_TOOL_CACHE'];
if (!defaultToolCacheRoot) return false;
if (!fs.existsSync('d:\\') || !fs.existsSync('c:\\')) return false;
const actualToolCacheRoot = defaultToolCacheRoot
.replace('C:', 'D:')
.replace('c:', 'd:');
// make toolcache root to be on drive d:
process.env['RUNNER_TOOL_CACHE'] = actualToolCacheRoot;
const actualToolCacheDir = await tc.cacheDir(extPath, tool, version, arch);
// create a link from c: to d:
const defaultToolCacheDir = actualToolCacheDir.replace(
actualToolCacheRoot,
defaultToolCacheRoot
);
fs.mkdirSync(path.dirname(defaultToolCacheDir), {recursive: true});
fs.symlinkSync(actualToolCacheDir, defaultToolCacheDir, 'junction');
core.info(`Created link ${defaultToolCacheDir} => ${actualToolCacheDir}`);
const actualToolCacheCompleteFile = `${actualToolCacheDir}.complete`;
const defaultToolCacheCompleteFile = `${defaultToolCacheDir}.complete`;
fs.symlinkSync(
actualToolCacheCompleteFile,
defaultToolCacheCompleteFile,
'file'
);
core.info(
`Created link ${defaultToolCacheCompleteFile} => ${actualToolCacheCompleteFile}`
);
// make outer code to continue using toolcache as if it were installed on c:
// restore toolcache root to default drive c:
process.env['RUNNER_TOOL_CACHE'] = defaultToolCacheRoot;
return defaultToolCacheDir;
}
async function addExecutablesToToolCache(
extPath: string,
info: IGoVersionInfo,
arch: string
): Promise<string> {
const tool = 'go';
const version = makeSemver(info.resolvedVersion);
return (
(await cacheWindowsDir(extPath, tool, version, arch)) ||
(await tc.cacheDir(extPath, tool, version, arch))
);
}
async function installGoVersion( async function installGoVersion(
info: IGoVersionInfo, info: IGoVersionInfo,
auth: string | undefined, auth: string | undefined,
@ -256,10 +187,14 @@ async function installGoVersion(
} }
core.info('Adding to the cache ...'); core.info('Adding to the cache ...');
const toolCacheDir = await addExecutablesToToolCache(extPath, info, arch); const cachedDir = await tc.cacheDir(
core.info(`Successfully cached go to ${toolCacheDir}`); extPath,
'go',
return toolCacheDir; makeSemver(info.resolvedVersion),
arch
);
core.info(`Successfully cached go to ${cachedDir}`);
return cachedDir;
} }
export async function extractGoArchive(archivePath: string): Promise<string> { export async function extractGoArchive(archivePath: string): Promise<string> {
@ -275,43 +210,8 @@ export async function extractGoArchive(archivePath: string): Promise<string> {
return extPath; return extPath;
} }
export async function getManifest( export async function getManifest(auth: string | undefined) {
auth: string | undefined return tc.getManifestFromRepo('actions', 'go-versions', auth, 'main');
): Promise<tc.IToolRelease[]> {
try {
return await getManifestFromRepo(auth);
} catch (err) {
core.debug('Fetching the manifest via the API failed.');
if (err instanceof Error) {
core.debug(err.message);
}
}
return await getManifestFromURL();
}
function getManifestFromRepo(
auth: string | undefined
): Promise<tc.IToolRelease[]> {
core.debug(
`Getting manifest from ${MANIFEST_REPO_OWNER}/${MANIFEST_REPO_NAME}@${MANIFEST_REPO_BRANCH}`
);
return tc.getManifestFromRepo(
MANIFEST_REPO_OWNER,
MANIFEST_REPO_NAME,
auth,
MANIFEST_REPO_BRANCH
);
}
async function getManifestFromURL(): Promise<tc.IToolRelease[]> {
core.debug('Falling back to fetching the manifest using raw URL.');
const http: httpm.HttpClient = new httpm.HttpClient('tool-cache');
const response = await http.getJson<tc.IToolRelease[]>(MANIFEST_URL);
if (!response.result) {
throw new Error(`Unable to get manifest from ${MANIFEST_URL}`);
}
return response.result;
} }
export async function getInfoFromManifest( export async function getInfoFromManifest(
@ -346,12 +246,13 @@ async function getInfoFromDist(
versionSpec: string, versionSpec: string,
arch: string arch: string
): Promise<IGoVersionInfo | null> { ): Promise<IGoVersionInfo | null> {
const version: IGoVersion | undefined = await findMatch(versionSpec, arch); let version: IGoVersion | undefined;
version = await findMatch(versionSpec, arch);
if (!version) { if (!version) {
return null; return null;
} }
const downloadUrl = `https://storage.googleapis.com/golang/${version.files[0].filename}`; let downloadUrl: string = `https://storage.googleapis.com/golang/${version.files[0].filename}`;
return <IGoVersionInfo>{ return <IGoVersionInfo>{
type: 'dist', type: 'dist',
@ -365,14 +266,14 @@ export async function findMatch(
versionSpec: string, versionSpec: string,
arch = os.arch() arch = os.arch()
): Promise<IGoVersion | undefined> { ): Promise<IGoVersion | undefined> {
const archFilter = sys.getArch(arch); let archFilter = sys.getArch(arch);
const platFilter = sys.getPlatform(); let platFilter = sys.getPlatform();
let result: IGoVersion | undefined; let result: IGoVersion | undefined;
let match: IGoVersion | undefined; let match: IGoVersion | undefined;
const dlUrl = 'https://golang.org/dl/?mode=json&include=all'; const dlUrl: string = 'https://golang.org/dl/?mode=json&include=all';
const candidates: IGoVersion[] | null = await module.exports.getVersionsDist( let candidates: IGoVersion[] | null = await module.exports.getVersionsDist(
dlUrl dlUrl
); );
if (!candidates) { if (!candidates) {
@ -381,8 +282,8 @@ export async function findMatch(
let goFile: IGoVersionFile | undefined; let goFile: IGoVersionFile | undefined;
for (let i = 0; i < candidates.length; i++) { for (let i = 0; i < candidates.length; i++) {
const candidate: IGoVersion = candidates[i]; let candidate: IGoVersion = candidates[i];
const version = makeSemver(candidate.version); let version = makeSemver(candidate.version);
core.debug(`check ${version} satisfies ${versionSpec}`); core.debug(`check ${version} satisfies ${versionSpec}`);
if (semver.satisfies(version, versionSpec)) { if (semver.satisfies(version, versionSpec)) {
@ -414,7 +315,7 @@ export async function getVersionsDist(
dlUrl: string dlUrl: string
): Promise<IGoVersion[] | null> { ): Promise<IGoVersion[] | null> {
// this returns versions descending so latest is first // this returns versions descending so latest is first
const http: httpm.HttpClient = new httpm.HttpClient('setup-go', [], { let http: httpm.HttpClient = new httpm.HttpClient('setup-go', [], {
allowRedirects: true, allowRedirects: true,
maxRedirects: 3 maxRedirects: 3
}); });
@ -430,9 +331,9 @@ export async function getVersionsDist(
export function makeSemver(version: string): string { export function makeSemver(version: string): string {
version = version.replace('go', ''); version = version.replace('go', '');
version = version.replace('beta', '-beta.').replace('rc', '-rc.'); version = version.replace('beta', '-beta.').replace('rc', '-rc.');
const parts = version.split('-'); let parts = version.split('-');
const semVersion = semver.coerce(parts[0])?.version; let semVersion = semver.coerce(parts[0])?.version;
if (!semVersion) { if (!semVersion) {
throw new Error( throw new Error(
`The version: ${version} can't be changed to SemVer notation` `The version: ${version} can't be changed to SemVer notation`
@ -468,10 +369,10 @@ export function parseGoVersionFile(versionFilePath: string): string {
} }
async function resolveStableVersionDist(versionSpec: string, arch: string) { async function resolveStableVersionDist(versionSpec: string, arch: string) {
const archFilter = sys.getArch(arch); let archFilter = sys.getArch(arch);
const platFilter = sys.getPlatform(); let platFilter = sys.getPlatform();
const dlUrl = 'https://golang.org/dl/?mode=json&include=all'; const dlUrl: string = 'https://golang.org/dl/?mode=json&include=all';
const candidates: IGoVersion[] | null = await module.exports.getVersionsDist( let candidates: IGoVersion[] | null = await module.exports.getVersionsDist(
dlUrl dlUrl
); );
if (!candidates) { if (!candidates) {

View File

@ -27,8 +27,8 @@ export async function run() {
} }
if (versionSpec) { if (versionSpec) {
const token = core.getInput('token'); let token = core.getInput('token');
const auth = !token ? undefined : `token ${token}`; let auth = !token ? undefined : `token ${token}`;
const checkLatest = core.getBooleanInput('check-latest'); const checkLatest = core.getBooleanInput('check-latest');
@ -51,31 +51,15 @@ export async function run() {
core.exportVariable('GOROOT', installDir); core.exportVariable('GOROOT', installDir);
} }
let added = await addBinToPath();
core.debug(`add bin ${added}`);
core.info(`Successfully set up Go version ${versionSpec}`); core.info(`Successfully set up Go version ${versionSpec}`);
} else {
core.info(
'[warning]go-version input was not specified. The action will try to use pre-installed version.'
);
} }
const added = await addBinToPath();
core.debug(`add bin ${added}`);
const goPath = await io.which('go');
const goVersion = (cp.execSync(`${goPath} version`) || '').toString();
if (cache && isCacheFeatureAvailable()) { if (cache && isCacheFeatureAvailable()) {
const packageManager = 'default'; const packageManager = 'default';
const cacheDependencyPath = core.getInput('cache-dependency-path'); const cacheDependencyPath = core.getInput('cache-dependency-path');
try { await restoreCache(versionSpec, packageManager, cacheDependencyPath);
await restoreCache(
parseGoVersion(goVersion),
packageManager,
cacheDependencyPath
);
} catch (error) {
core.warning(`Restore cache failed: ${(error as Error).message}`);
}
} }
// add problem matchers // add problem matchers
@ -83,31 +67,33 @@ export async function run() {
core.info(`##[add-matcher]${matchersPath}`); core.info(`##[add-matcher]${matchersPath}`);
// output the version actually being used // output the version actually being used
let goPath = await io.which('go');
let goVersion = (cp.execSync(`${goPath} version`) || '').toString();
core.info(goVersion); core.info(goVersion);
core.setOutput('go-version', parseGoVersion(goVersion)); core.setOutput('go-version', parseGoVersion(goVersion));
core.startGroup('go env'); core.startGroup('go env');
const goEnv = (cp.execSync(`${goPath} env`) || '').toString(); let goEnv = (cp.execSync(`${goPath} env`) || '').toString();
core.info(goEnv); core.info(goEnv);
core.endGroup(); core.endGroup();
} catch (error) { } catch (error) {
core.setFailed((error as Error).message); core.setFailed(error.message);
} }
} }
export async function addBinToPath(): Promise<boolean> { export async function addBinToPath(): Promise<boolean> {
let added = false; let added = false;
const g = await io.which('go'); let g = await io.which('go');
core.debug(`which go :${g}:`); core.debug(`which go :${g}:`);
if (!g) { if (!g) {
core.debug('go not in the path'); core.debug('go not in the path');
return added; return added;
} }
const buf = cp.execSync('go env GOPATH'); let buf = cp.execSync('go env GOPATH');
if (buf.length > 1) { if (buf.length > 1) {
const gp = buf.toString().trim(); let gp = buf.toString().trim();
core.debug(`go env GOPATH :${gp}:`); core.debug(`go env GOPATH :${gp}:`);
if (!fs.existsSync(gp)) { if (!fs.existsSync(gp)) {
// some of the hosted images have go install but not profile dir // some of the hosted images have go install but not profile dir
@ -115,7 +101,7 @@ export async function addBinToPath(): Promise<boolean> {
await io.mkdirP(gp); await io.mkdirP(gp);
} }
const bp = path.join(gp, 'bin'); let bp = path.join(gp, 'bin');
if (!fs.existsSync(bp)) { if (!fs.existsSync(bp)) {
core.debug(`creating ${bp}`); core.debug(`creating ${bp}`);
await io.mkdirP(bp); await io.mkdirP(bp);

View File

@ -1,4 +1,4 @@
import os from 'os'; const os = require('os');
export function getPlatform(): string { export function getPlatform(): string {
// darwin and linux match already // darwin and linux match already

View File

@ -2,13 +2,3 @@ export enum StableReleaseAlias {
Stable = 'stable', Stable = 'stable',
OldStable = 'oldstable' OldStable = 'oldstable'
} }
export const isSelfHosted = (): boolean =>
process.env['RUNNER_ENVIRONMENT'] !== 'github-hosted' &&
(process.env['AGENT_ISSELFHOSTED'] === '1' ||
process.env['AGENT_ISSELFHOSTED'] === undefined);
/* the above is simplified from:
process.env['RUNNER_ENVIRONMENT'] !== 'github-hosted' && process.env['AGENT_ISSELFHOSTED'] === '1'
||
process.env['RUNNER_ENVIRONMENT'] !== 'github-hosted' && process.env['AGENT_ISSELFHOSTED'] === undefined
*/

View File

@ -46,7 +46,6 @@
// "types": [], /* Type declaration files to be included in compilation. */ // "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"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. */
"sourceMap": true, "sourceMap": true,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */