Vidya reddy prettier (#58)

* upgraded to Node16

* Enforce Prettier

* code fix

* jest version change and prettify code

Co-authored-by: Vidya Reddy <vidyareddy@microsoft.com>
This commit is contained in:
Vidya Reddy 2022-06-27 15:31:07 -07:00 committed by GitHub
parent b474dc39ef
commit 2eb2a370ff
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 11418 additions and 11311 deletions

View file

@ -4,7 +4,4 @@ about: Create a report to help us improve
title: '' title: ''
labels: need-to-triage labels: need-to-triage
assignees: '@aksatlanta' assignees: '@aksatlanta'
--- ---

View file

@ -2,7 +2,7 @@ name: setting-default-labels
on: on:
schedule: schedule:
- cron: "0 0/3 * * *" - cron: '0 0/3 * * *'
jobs: jobs:
label-issues: label-issues:

View file

@ -3,11 +3,11 @@ on: # rebuild any PRs and main branch changes
pull_request: pull_request:
branches: branches:
- main - main
- "releases/*" - 'releases/*'
push: push:
branches: branches:
- main - main
- "releases/*" - 'releases/*'
jobs: jobs:
run-integration-test: run-integration-test:
@ -32,18 +32,18 @@ jobs:
- uses: actions/setup-python@v2 - uses: actions/setup-python@v2
name: Install Python name: Install Python
with: with:
python-version: "3.x" python-version: '3.x'
- name: Install requests library - name: Install requests library
run: pip install requests run: pip install requests
- name: Validate kubectl setup - name: Validate kubectl setup
run: python test/validate-kubectl.py !v1.15.1 run: python test/validate-kubectl.py latest
- name: Setup kubectl - name: Setup kubectl
uses: ./ uses: ./
with: with:
version: "v1.15.1" version: 'v1.15.1'
- name: Validate kubectl setup - name: Validate kubectl setup
run: python test/validate-kubectl.py 'v1.15.1' run: python test/validate-kubectl.py 'v1.15.1'

18
.github/workflows/prettify-code.yml vendored Normal file
View file

@ -0,0 +1,18 @@
name: 'Run prettify'
on:
pull_request:
push:
branches: [main]
jobs:
prettier:
name: Prettier Check
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v2
- name: Enforce Prettier
uses: actionsx/prettier@v2
with:
args: --check .

View file

@ -4,7 +4,7 @@ on:
workflow_dispatch: workflow_dispatch:
inputs: inputs:
release: release:
description: "Define release version (ex: v1, v2, v3)" description: 'Define release version (ex: v1, v2, v3)'
required: true required: true
jobs: jobs:

View file

@ -1,4 +1,4 @@
name: "Run unit tests." name: 'Run unit tests.'
on: # rebuild any PRs and main branch changes on: # rebuild any PRs and main branch changes
pull_request: pull_request:
branches: branches:

4
.prettierignore Normal file
View file

@ -0,0 +1,4 @@
# dependencies
/node_modules
coverage
/lib

8
.prettierrc.json Normal file
View file

@ -0,0 +1,8 @@
{
"trailingComma": "none",
"bracketSpacing": false,
"semi": false,
"tabWidth": 3,
"singleQuote": true,
"printWidth": 80
}

View file

@ -1,4 +1,5 @@
# Setup Kubectl # Setup Kubectl
#### Sample workflow to install a specific version of kubectl binary on the runner. #### Sample workflow to install a specific version of kubectl binary on the runner.
Acceptable values are latest or any semantic version string like `v1.15.0`. Use this action in workflow to define which version of kubectl will be used. Acceptable values are latest or any semantic version string like `v1.15.0`. Use this action in workflow to define which version of kubectl will be used.
@ -9,6 +10,7 @@ Acceptable values are latest or any semantic version string like `v1.15.0`. Use
version: '<version>' # default is latest stable version: '<version>' # default is latest stable
id: install id: install
``` ```
Refer to the action metadata file for details about all the inputs https://github.com/Azure/setup-kubectl/blob/main/action.yml Refer to the action metadata file for details about all the inputs https://github.com/Azure/setup-kubectl/blob/main/action.yml
# Contributing # Contributing

View file

@ -4,7 +4,7 @@
Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [many more](https://opensource.microsoft.com/). Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [many more](https://opensource.microsoft.com/).
If you believe you have found a security vulnerability in any Microsoft-owned repository that meets Microsoft's [definition](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)) of a security vulnerability, please report it to us as described below. If you believe you have found a security vulnerability in any Microsoft-owned repository that meets Microsoft's [definition](<https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)>) of a security vulnerability, please report it to us as described below.
## Reporting Security Issues ## Reporting Security Issues
@ -14,13 +14,13 @@ You should receive a response within 24 hours. If for some reason you do not, pl
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) - Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
* Full paths of source file(s) related to the manifestation of the issue - Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL) - The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue - Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue - Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible) - Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue - Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly. This information will help us triage your report more quickly.

View file

@ -1,15 +1,15 @@
name: "Kubectl tool installer" name: 'Kubectl tool installer'
description: "Install a specific version of kubectl binary. Acceptable values are latest or any semantic version string like 1.15.0" description: 'Install a specific version of kubectl binary. Acceptable values are latest or any semantic version string like 1.15.0'
inputs: inputs:
version: version:
description: "Version of kubectl" description: 'Version of kubectl'
required: true required: true
default: "latest" default: 'latest'
outputs: outputs:
kubectl-path: kubectl-path:
description: "Path to the cached kubectl binary" description: 'Path to the cached kubectl binary'
branding: branding:
color: "blue" color: 'blue'
runs: runs:
using: "node16" using: 'node16'
main: "lib/index.js" main: 'lib/index.js'

View file

@ -8,11 +8,11 @@ module.exports = {
}, },
verbose: true, verbose: true,
coverageThreshold: { coverageThreshold: {
"global": { global: {
"branches": 0, branches: 0,
"functions": 14, functions: 14,
"lines": 27, lines: 27,
"statements": 27 statements: 27
} }
} }
} }

37
package-lock.json generated
View file

@ -18,6 +18,7 @@
"@types/node": "^12.0.4", "@types/node": "^12.0.4",
"@vercel/ncc": "^0.33.1", "@vercel/ncc": "^0.33.1",
"jest": "^26.0.1", "jest": "^26.0.1",
"prettier": "2.7.1",
"ts-jest": "^26.0.1", "ts-jest": "^26.0.1",
"typescript": "3.9.2" "typescript": "3.9.2"
} }
@ -10463,38 +10464,21 @@
} }
}, },
"ts-jest": { "ts-jest": {
"version": "26.5.6", "version": "25.5.1",
"resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-26.5.6.tgz", "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-25.5.1.tgz",
"integrity": "sha512-rua+rCP8DxpA8b4DQD/6X2HQS8Zy/xzViVYfEs2OQu68tkCuKLV0Md8pmX55+W24uRIyAsf/BajRfxOs+R2MKA==", "integrity": "sha512-kHEUlZMK8fn8vkxDjwbHlxXRB9dHYpyzqKIGDNxbzs+Rz+ssNDSDNusEK8Fk/sDd4xE6iKoQLfFkFVaskmTJyw==",
"dev": true, "dev": true,
"requires": { "requires": {
"bs-logger": "0.x", "bs-logger": "0.x",
"buffer-from": "1.x", "buffer-from": "1.x",
"fast-json-stable-stringify": "2.x", "fast-json-stable-stringify": "2.x",
"jest-util": "^26.1.0",
"json5": "2.x", "json5": "2.x",
"lodash": "4.x", "lodash.memoize": "4.x",
"make-error": "1.x", "make-error": "1.x",
"mkdirp": "1.x", "micromatch": "4.x",
"semver": "7.x", "mkdirp": "0.x",
"yargs-parser": "20.x" "semver": "6.x",
}, "yargs-parser": "18.x"
"dependencies": {
"semver": {
"version": "7.3.7",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz",
"integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==",
"dev": true,
"requires": {
"lru-cache": "^6.0.0"
}
},
"yargs-parser": {
"version": "20.2.9",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz",
"integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==",
"dev": true
}
} }
}, },
"tunnel": { "tunnel": {
@ -10823,7 +10807,8 @@
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"dev": true "dev": true,
"optional": true
}, },
"yargs": { "yargs": {
"version": "15.4.1", "version": "15.4.1",

View file

@ -6,7 +6,9 @@
"scripts": { "scripts": {
"build": "ncc build src/run.ts -o lib", "build": "ncc build src/run.ts -o lib",
"test": "jest", "test": "jest",
"test-coverage": "jest --coverage" "test-coverage": "jest --coverage",
"format": "prettier --write .",
"format-check": "prettier --check ."
}, },
"keywords": [ "keywords": [
"actions", "actions",
@ -21,11 +23,12 @@
"@actions/tool-cache": "^1.0.0" "@actions/tool-cache": "^1.0.0"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "^26.0.0",
"@types/node": "^12.0.4", "@types/node": "^12.0.4",
"@vercel/ncc": "^0.33.1", "@vercel/ncc": "^0.33.1",
"jest": "^26.0.1", "jest": "^26.0.1",
"@types/jest": "^26.0.1", "prettier": "2.7.1",
"ts-jest": "^26.0.1", "ts-jest": "^26.0.0",
"typescript": "3.9.2" "typescript": "3.9.2"
} }
} }

View file

@ -1,31 +1,43 @@
import * as os from 'os'; import * as os from 'os'
import * as util from 'util'; import * as util from 'util'
export function getKubectlArch(): string { export function getKubectlArch(): string {
const arch = os.arch(); const arch = os.arch()
if (arch === 'x64') { if (arch === 'x64') {
return 'amd64'; return 'amd64'
} }
return arch; return arch
} }
export function getkubectlDownloadURL(version: string, arch: string): string { export function getkubectlDownloadURL(version: string, arch: string): string {
switch (os.type()) { switch (os.type()) {
case 'Linux': case 'Linux':
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/kubectl', version, arch); return util.format(
'https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/kubectl',
version,
arch
)
case 'Darwin': case 'Darwin':
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/darwin/%s/kubectl', version, arch); return util.format(
'https://storage.googleapis.com/kubernetes-release/release/%s/bin/darwin/%s/kubectl',
version,
arch
)
case 'Windows_NT': case 'Windows_NT':
default: default:
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/windows/%s/kubectl.exe', version, arch); return util.format(
'https://storage.googleapis.com/kubernetes-release/release/%s/bin/windows/%s/kubectl.exe',
version,
arch
)
} }
} }
export function getExecutableExtension(): string { export function getExecutableExtension(): string {
if (os.type().match(/^Win/)) { if (os.type().match(/^Win/)) {
return '.exe'; return '.exe'
} }
return ''; return ''
} }

View file

@ -1,183 +1,235 @@
import * as run from './run' import * as run from './run'
import { getkubectlDownloadURL, getKubectlArch, getExecutableExtension } from './helpers'; import {
import * as os from 'os'; getkubectlDownloadURL,
import * as toolCache from '@actions/tool-cache'; getKubectlArch,
import * as fs from 'fs'; getExecutableExtension
import * as path from 'path'; } from './helpers'
import * as core from '@actions/core'; import * as os from 'os'
import * as util from 'util'; import * as toolCache from '@actions/tool-cache'
import * as fs from 'fs'
import * as path from 'path'
import * as core from '@actions/core'
import * as util from 'util'
describe('Testing all functions in run file.', () => { describe('Testing all functions in run file.', () => {
test('getExecutableExtension() - return .exe when os is Windows', () => { test('getExecutableExtension() - return .exe when os is Windows', () => {
jest.spyOn(os, 'type').mockReturnValue('Windows_NT'); jest.spyOn(os, 'type').mockReturnValue('Windows_NT')
expect(getExecutableExtension()).toBe('.exe'); expect(getExecutableExtension()).toBe('.exe')
expect(os.type).toBeCalled(); expect(os.type).toBeCalled()
}); })
test('getExecutableExtension() - return empty string for non-windows OS', () => { test('getExecutableExtension() - return empty string for non-windows OS', () => {
jest.spyOn(os, 'type').mockReturnValue('Darwin'); jest.spyOn(os, 'type').mockReturnValue('Darwin')
expect(getExecutableExtension()).toBe(''); expect(getExecutableExtension()).toBe('')
expect(os.type).toBeCalled(); expect(os.type).toBeCalled()
}); })
test.each([ test.each([
['arm', 'arm'], ['arm', 'arm'],
['arm64', 'arm64'], ['arm64', 'arm64'],
['x64', 'amd64'] ['x64', 'amd64']
])("getKubectlArch() - return on %s os arch %s kubectl arch", (osArch, kubectlArch) => { ])(
jest.spyOn(os, 'arch').mockReturnValue(osArch); 'getKubectlArch() - return on %s os arch %s kubectl arch',
(osArch, kubectlArch) => {
jest.spyOn(os, 'arch').mockReturnValue(osArch)
expect(getKubectlArch()).toBe(kubectlArch); expect(getKubectlArch()).toBe(kubectlArch)
expect(os.arch).toBeCalled(); expect(os.arch).toBeCalled()
}); }
)
test.each([ test.each([['arm'], ['arm64'], ['amd64']])(
['arm'], 'getkubectlDownloadURL() - return the URL to download %s kubectl for Linux',
['arm64'], (arch) => {
['amd64'] jest.spyOn(os, 'type').mockReturnValue('Linux')
])('getkubectlDownloadURL() - return the URL to download %s kubectl for Linux', (arch) => { const kubectlLinuxUrl = util.format(
jest.spyOn(os, 'type').mockReturnValue('Linux'); 'https://storage.googleapis.com/kubernetes-release/release/v1.15.0/bin/linux/%s/kubectl',
const kubectlLinuxUrl = util.format('https://storage.googleapis.com/kubernetes-release/release/v1.15.0/bin/linux/%s/kubectl', arch); arch
)
expect(getkubectlDownloadURL('v1.15.0', arch)).toBe(kubectlLinuxUrl); expect(getkubectlDownloadURL('v1.15.0', arch)).toBe(kubectlLinuxUrl)
expect(os.type).toBeCalled(); expect(os.type).toBeCalled()
}); }
)
test.each([ test.each([['arm'], ['arm64'], ['amd64']])(
['arm'], 'getkubectlDownloadURL() - return the URL to download %s kubectl for Darwin',
['arm64'], (arch) => {
['amd64'] jest.spyOn(os, 'type').mockReturnValue('Darwin')
])('getkubectlDownloadURL() - return the URL to download %s kubectl for Darwin', (arch) => { const kubectlDarwinUrl = util.format(
jest.spyOn(os, 'type').mockReturnValue('Darwin'); 'https://storage.googleapis.com/kubernetes-release/release/v1.15.0/bin/darwin/%s/kubectl',
const kubectlDarwinUrl = util.format('https://storage.googleapis.com/kubernetes-release/release/v1.15.0/bin/darwin/%s/kubectl', arch); arch
)
expect(getkubectlDownloadURL('v1.15.0', arch)).toBe(kubectlDarwinUrl); expect(getkubectlDownloadURL('v1.15.0', arch)).toBe(kubectlDarwinUrl)
expect(os.type).toBeCalled(); expect(os.type).toBeCalled()
}); }
)
test.each([ test.each([['arm'], ['arm64'], ['amd64']])(
['arm'], 'getkubectlDownloadURL() - return the URL to download %s kubectl for Windows',
['arm64'], (arch) => {
['amd64'] jest.spyOn(os, 'type').mockReturnValue('Windows_NT')
])('getkubectlDownloadURL() - return the URL to download %s kubectl for Windows', (arch) => {
jest.spyOn(os, 'type').mockReturnValue('Windows_NT');
const kubectlWindowsUrl = util.format('https://storage.googleapis.com/kubernetes-release/release/v1.15.0/bin/windows/%s/kubectl.exe', arch); const kubectlWindowsUrl = util.format(
expect(getkubectlDownloadURL('v1.15.0', arch)).toBe(kubectlWindowsUrl); 'https://storage.googleapis.com/kubernetes-release/release/v1.15.0/bin/windows/%s/kubectl.exe',
expect(os.type).toBeCalled(); arch
}); )
expect(getkubectlDownloadURL('v1.15.0', arch)).toBe(kubectlWindowsUrl)
expect(os.type).toBeCalled()
}
)
test('getStableKubectlVersion() - download stable version file, read version and return it', async () => { test('getStableKubectlVersion() - download stable version file, read version and return it', async () => {
jest.spyOn(toolCache, 'downloadTool').mockReturnValue(Promise.resolve('pathToTool')); jest
jest.spyOn(fs, 'readFileSync').mockReturnValue('v1.20.4'); .spyOn(toolCache, 'downloadTool')
.mockReturnValue(Promise.resolve('pathToTool'))
jest.spyOn(fs, 'readFileSync').mockReturnValue('v1.20.4')
expect(await run.getStableKubectlVersion()).toBe('v1.20.4'); expect(await run.getStableKubectlVersion()).toBe('v1.20.4')
expect(toolCache.downloadTool).toBeCalled(); expect(toolCache.downloadTool).toBeCalled()
expect(fs.readFileSync).toBeCalledWith('pathToTool', 'utf8'); expect(fs.readFileSync).toBeCalledWith('pathToTool', 'utf8')
}); })
test('getStableKubectlVersion() - return default v1.15.0 if version read is empty', async () => { test('getStableKubectlVersion() - return default v1.15.0 if version read is empty', async () => {
jest.spyOn(toolCache, 'downloadTool').mockReturnValue(Promise.resolve('pathToTool')); jest
jest.spyOn(fs, 'readFileSync').mockReturnValue(''); .spyOn(toolCache, 'downloadTool')
.mockReturnValue(Promise.resolve('pathToTool'))
jest.spyOn(fs, 'readFileSync').mockReturnValue('')
expect(await run.getStableKubectlVersion()).toBe('v1.15.0'); expect(await run.getStableKubectlVersion()).toBe('v1.15.0')
expect(toolCache.downloadTool).toBeCalled(); expect(toolCache.downloadTool).toBeCalled()
expect(fs.readFileSync).toBeCalledWith('pathToTool', 'utf8'); expect(fs.readFileSync).toBeCalledWith('pathToTool', 'utf8')
}); })
test('getStableKubectlVersion() - return default v1.15.0 if unable to download file', async () => { test('getStableKubectlVersion() - return default v1.15.0 if unable to download file', async () => {
jest.spyOn(toolCache, 'downloadTool').mockRejectedValue('Unable to download.'); jest
.spyOn(toolCache, 'downloadTool')
.mockRejectedValue('Unable to download.')
expect(await run.getStableKubectlVersion()).toBe('v1.15.0'); expect(await run.getStableKubectlVersion()).toBe('v1.15.0')
expect(toolCache.downloadTool).toBeCalled(); expect(toolCache.downloadTool).toBeCalled()
}); })
test('downloadKubectl() - download kubectl, add it to toolCache and return path to it', async () => { test('downloadKubectl() - download kubectl, add it to toolCache and return path to it', async () => {
jest.spyOn(toolCache, 'find').mockReturnValue(''); jest.spyOn(toolCache, 'find').mockReturnValue('')
jest.spyOn(toolCache, 'downloadTool').mockReturnValue(Promise.resolve('pathToTool')); jest
jest.spyOn(toolCache, 'cacheFile').mockReturnValue(Promise.resolve('pathToCachedTool')); .spyOn(toolCache, 'downloadTool')
jest.spyOn(os, 'type').mockReturnValue('Windows_NT'); .mockReturnValue(Promise.resolve('pathToTool'))
jest.spyOn(fs, 'chmodSync').mockImplementation(() => { }); jest
.spyOn(toolCache, 'cacheFile')
.mockReturnValue(Promise.resolve('pathToCachedTool'))
jest.spyOn(os, 'type').mockReturnValue('Windows_NT')
jest.spyOn(fs, 'chmodSync').mockImplementation(() => {})
expect(await run.downloadKubectl('v1.15.0')).toBe(path.join('pathToCachedTool', 'kubectl.exe')); expect(await run.downloadKubectl('v1.15.0')).toBe(
expect(toolCache.find).toBeCalledWith('kubectl', 'v1.15.0'); path.join('pathToCachedTool', 'kubectl.exe')
expect(toolCache.downloadTool).toBeCalled(); )
expect(toolCache.cacheFile).toBeCalled(); expect(toolCache.find).toBeCalledWith('kubectl', 'v1.15.0')
expect(os.type).toBeCalled(); expect(toolCache.downloadTool).toBeCalled()
expect(fs.chmodSync).toBeCalledWith(path.join('pathToCachedTool', 'kubectl.exe'), '775'); expect(toolCache.cacheFile).toBeCalled()
}); expect(os.type).toBeCalled()
expect(fs.chmodSync).toBeCalledWith(
path.join('pathToCachedTool', 'kubectl.exe'),
'775'
)
})
test('downloadKubectl() - throw DownloadKubectlFailed error when unable to download kubectl', async () => { test('downloadKubectl() - throw DownloadKubectlFailed error when unable to download kubectl', async () => {
jest.spyOn(toolCache, 'find').mockReturnValue(''); jest.spyOn(toolCache, 'find').mockReturnValue('')
jest.spyOn(toolCache, 'downloadTool').mockRejectedValue('Unable to download kubectl.'); jest
.spyOn(toolCache, 'downloadTool')
.mockRejectedValue('Unable to download kubectl.')
await expect(run.downloadKubectl('v1.15.0')).rejects.toThrow('DownloadKubectlFailed'); await expect(run.downloadKubectl('v1.15.0')).rejects.toThrow(
expect(toolCache.find).toBeCalledWith('kubectl', 'v1.15.0'); 'DownloadKubectlFailed'
expect(toolCache.downloadTool).toBeCalled(); )
}); expect(toolCache.find).toBeCalledWith('kubectl', 'v1.15.0')
expect(toolCache.downloadTool).toBeCalled()
})
test('downloadKubectl() - throw kubectl not found error when receive 404 response', async () => { test('downloadKubectl() - throw kubectl not found error when receive 404 response', async () => {
const kubectlVersion = 'v1.15.0' const kubectlVersion = 'v1.15.0'
const arch = 'arm128'; const arch = 'arm128'
jest.spyOn(os, 'arch').mockReturnValue(arch); jest.spyOn(os, 'arch').mockReturnValue(arch)
jest.spyOn(toolCache, 'find').mockReturnValue(''); jest.spyOn(toolCache, 'find').mockReturnValue('')
jest.spyOn(toolCache, 'downloadTool').mockImplementation(_ => { jest.spyOn(toolCache, 'downloadTool').mockImplementation((_) => {
throw new toolCache.HTTPError(404); throw new toolCache.HTTPError(404)
}); })
await expect(run.downloadKubectl(kubectlVersion)).rejects await expect(run.downloadKubectl(kubectlVersion)).rejects.toThrow(
.toThrow(util.format("Kubectl '%s' for '%s' arch not found.", kubectlVersion, arch)); util.format(
expect(os.arch).toBeCalled(); "Kubectl '%s' for '%s' arch not found.",
expect(toolCache.find).toBeCalledWith('kubectl', kubectlVersion); kubectlVersion,
expect(toolCache.downloadTool).toBeCalled(); arch
}); )
)
expect(os.arch).toBeCalled()
expect(toolCache.find).toBeCalledWith('kubectl', kubectlVersion)
expect(toolCache.downloadTool).toBeCalled()
})
test('downloadKubectl() - return path to existing cache of kubectl', async () => { test('downloadKubectl() - return path to existing cache of kubectl', async () => {
jest.spyOn(toolCache, 'find').mockReturnValue('pathToCachedTool'); jest.spyOn(toolCache, 'find').mockReturnValue('pathToCachedTool')
jest.spyOn(os, 'type').mockReturnValue('Windows_NT'); jest.spyOn(os, 'type').mockReturnValue('Windows_NT')
jest.spyOn(fs, 'chmodSync').mockImplementation(() => { }); jest.spyOn(fs, 'chmodSync').mockImplementation(() => {})
jest.spyOn(toolCache, 'downloadTool'); jest.spyOn(toolCache, 'downloadTool')
expect(await run.downloadKubectl('v1.15.0')).toBe(path.join('pathToCachedTool', 'kubectl.exe')); expect(await run.downloadKubectl('v1.15.0')).toBe(
expect(toolCache.find).toBeCalledWith('kubectl', 'v1.15.0'); path.join('pathToCachedTool', 'kubectl.exe')
expect(os.type).toBeCalled(); )
expect(fs.chmodSync).toBeCalledWith(path.join('pathToCachedTool', 'kubectl.exe'), '775'); expect(toolCache.find).toBeCalledWith('kubectl', 'v1.15.0')
expect(toolCache.downloadTool).not.toBeCalled(); expect(os.type).toBeCalled()
}); expect(fs.chmodSync).toBeCalledWith(
path.join('pathToCachedTool', 'kubectl.exe'),
'775'
)
expect(toolCache.downloadTool).not.toBeCalled()
})
test('run() - download specified version and set output', async () => { test('run() - download specified version and set output', async () => {
jest.spyOn(core, 'getInput').mockReturnValue('v1.15.5'); jest.spyOn(core, 'getInput').mockReturnValue('v1.15.5')
jest.spyOn(toolCache, 'find').mockReturnValue('pathToCachedTool'); jest.spyOn(toolCache, 'find').mockReturnValue('pathToCachedTool')
jest.spyOn(os, 'type').mockReturnValue('Windows_NT'); jest.spyOn(os, 'type').mockReturnValue('Windows_NT')
jest.spyOn(fs, 'chmodSync').mockImplementation(); jest.spyOn(fs, 'chmodSync').mockImplementation()
jest.spyOn(core, 'addPath').mockImplementation(); jest.spyOn(core, 'addPath').mockImplementation()
jest.spyOn(console, 'log').mockImplementation(); jest.spyOn(console, 'log').mockImplementation()
jest.spyOn(core, 'setOutput').mockImplementation(); jest.spyOn(core, 'setOutput').mockImplementation()
expect(await run.run()).toBeUndefined(); expect(await run.run()).toBeUndefined()
expect(core.getInput).toBeCalledWith('version', { 'required': true }); expect(core.getInput).toBeCalledWith('version', {required: true})
expect(core.addPath).toBeCalledWith('pathToCachedTool'); expect(core.addPath).toBeCalledWith('pathToCachedTool')
expect(core.setOutput).toBeCalledWith('kubectl-path', path.join('pathToCachedTool', 'kubectl.exe')); expect(core.setOutput).toBeCalledWith(
}); 'kubectl-path',
path.join('pathToCachedTool', 'kubectl.exe')
)
})
test('run() - get latest version, download it and set output', async () => { test('run() - get latest version, download it and set output', async () => {
jest.spyOn(core, 'getInput').mockReturnValue('latest'); jest.spyOn(core, 'getInput').mockReturnValue('latest')
jest.spyOn(toolCache, 'downloadTool').mockReturnValue(Promise.resolve('pathToTool')); jest
jest.spyOn(fs, 'readFileSync').mockReturnValue('v1.20.4'); .spyOn(toolCache, 'downloadTool')
jest.spyOn(toolCache, 'find').mockReturnValue('pathToCachedTool'); .mockReturnValue(Promise.resolve('pathToTool'))
jest.spyOn(os, 'type').mockReturnValue('Windows_NT'); jest.spyOn(fs, 'readFileSync').mockReturnValue('v1.20.4')
jest.spyOn(fs, 'chmodSync').mockImplementation(); jest.spyOn(toolCache, 'find').mockReturnValue('pathToCachedTool')
jest.spyOn(core, 'addPath').mockImplementation(); jest.spyOn(os, 'type').mockReturnValue('Windows_NT')
jest.spyOn(console, 'log').mockImplementation(); jest.spyOn(fs, 'chmodSync').mockImplementation()
jest.spyOn(core, 'setOutput').mockImplementation(); jest.spyOn(core, 'addPath').mockImplementation()
jest.spyOn(console, 'log').mockImplementation()
jest.spyOn(core, 'setOutput').mockImplementation()
expect(await run.run()).toBeUndefined(); expect(await run.run()).toBeUndefined()
expect(toolCache.downloadTool).toBeCalledWith('https://storage.googleapis.com/kubernetes-release/release/stable.txt'); expect(toolCache.downloadTool).toBeCalledWith(
expect(core.getInput).toBeCalledWith('version', { 'required': true }); 'https://storage.googleapis.com/kubernetes-release/release/stable.txt'
expect(core.addPath).toBeCalledWith('pathToCachedTool'); )
expect(core.setOutput).toBeCalledWith('kubectl-path', path.join('pathToCachedTool', 'kubectl.exe')); expect(core.getInput).toBeCalledWith('version', {required: true})
}); expect(core.addPath).toBeCalledWith('pathToCachedTool')
}); expect(core.setOutput).toBeCalledWith(
'kubectl-path',
path.join('pathToCachedTool', 'kubectl.exe')
)
})
})

View file

@ -1,64 +1,93 @@
import * as path from 'path'; import * as path from 'path'
import * as util from 'util'; import * as util from 'util'
import * as fs from 'fs'; import * as fs from 'fs'
import * as toolCache from '@actions/tool-cache'; import * as toolCache from '@actions/tool-cache'
import * as core from '@actions/core'; import * as core from '@actions/core'
import { getkubectlDownloadURL, getKubectlArch, getExecutableExtension } from './helpers'; import {
getkubectlDownloadURL,
getKubectlArch,
getExecutableExtension
} from './helpers'
const kubectlToolName = 'kubectl'; const kubectlToolName = 'kubectl'
const stableKubectlVersion = 'v1.15.0'; const stableKubectlVersion = 'v1.15.0'
const stableVersionUrl = 'https://storage.googleapis.com/kubernetes-release/release/stable.txt'; const stableVersionUrl =
'https://storage.googleapis.com/kubernetes-release/release/stable.txt'
export async function run() { export async function run() {
let version = core.getInput('version', { 'required': true }); let version = core.getInput('version', {required: true})
if (version.toLocaleLowerCase() === 'latest') { if (version.toLocaleLowerCase() === 'latest') {
version = await getStableKubectlVersion(); version = await getStableKubectlVersion()
} }
const cachedPath = await downloadKubectl(version); const cachedPath = await downloadKubectl(version)
core.addPath(path.dirname(cachedPath)); core.addPath(path.dirname(cachedPath))
core.debug(`Kubectl tool version: '${version}' has been cached at ${cachedPath}`); core.debug(
core.setOutput('kubectl-path', cachedPath); `Kubectl tool version: '${version}' has been cached at ${cachedPath}`
)
core.setOutput('kubectl-path', cachedPath)
} }
export async function getStableKubectlVersion(): Promise<string> { export async function getStableKubectlVersion(): Promise<string> {
return toolCache.downloadTool(stableVersionUrl).then((downloadPath) => { return toolCache.downloadTool(stableVersionUrl).then(
let version = fs.readFileSync(downloadPath, 'utf8').toString().trim(); (downloadPath) => {
let version = fs.readFileSync(downloadPath, 'utf8').toString().trim()
if (!version) { if (!version) {
version = stableKubectlVersion; version = stableKubectlVersion
} }
return version; return version
}, (error) => { },
core.debug(error); (error) => {
core.warning('GetStableVersionFailed'); core.debug(error)
return stableKubectlVersion; core.warning('GetStableVersionFailed')
}); return stableKubectlVersion
}
)
} }
export async function downloadKubectl(version: string): Promise<string> { export async function downloadKubectl(version: string): Promise<string> {
let cachedToolpath = toolCache.find(kubectlToolName, version); let cachedToolpath = toolCache.find(kubectlToolName, version)
let kubectlDownloadPath = ''; let kubectlDownloadPath = ''
const arch = getKubectlArch(); const arch = getKubectlArch()
if (!cachedToolpath) { if (!cachedToolpath) {
try { try {
kubectlDownloadPath = await toolCache.downloadTool(getkubectlDownloadURL(version, arch)); kubectlDownloadPath = await toolCache.downloadTool(
getkubectlDownloadURL(version, arch)
)
} catch (exception) { } catch (exception) {
if (exception instanceof toolCache.HTTPError && exception.httpStatusCode === 404) { if (
throw new Error(util.format("Kubectl '%s' for '%s' arch not found.", version, arch)); exception instanceof toolCache.HTTPError &&
exception.httpStatusCode === 404
) {
throw new Error(
util.format(
"Kubectl '%s' for '%s' arch not found.",
version,
arch
)
)
} else { } else {
throw new Error('DownloadKubectlFailed'); throw new Error('DownloadKubectlFailed')
} }
} }
cachedToolpath = await toolCache.cacheFile(kubectlDownloadPath, kubectlToolName + getExecutableExtension(), kubectlToolName, version); cachedToolpath = await toolCache.cacheFile(
kubectlDownloadPath,
kubectlToolName + getExecutableExtension(),
kubectlToolName,
version
)
} }
const kubectlPath = path.join(cachedToolpath, kubectlToolName + getExecutableExtension()); const kubectlPath = path.join(
fs.chmodSync(kubectlPath, '775'); cachedToolpath,
return kubectlPath; kubectlToolName + getExecutableExtension()
)
fs.chmodSync(kubectlPath, '775')
return kubectlPath
} }
run().catch(core.setFailed); run().catch(core.setFailed)

View file

@ -3,8 +3,5 @@
"target": "ES6", "target": "ES6",
"module": "commonjs" "module": "commonjs"
}, },
"exclude": [ "exclude": ["node_modules", "test"]
"node_modules",
"test"
]
} }